forked from DynamoDS/Dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkspaceViewModel.cs
More file actions
1973 lines (1689 loc) · 71.8 KB
/
Copy pathWorkspaceViewModel.cs
File metadata and controls
1973 lines (1689 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Dynamo.Configuration;
using Dynamo.Engine;
using Dynamo.Graph;
using Dynamo.Graph.Annotations;
using Dynamo.Graph.Connectors;
using Dynamo.Graph.Nodes;
using Dynamo.Graph.Notes;
using Dynamo.Graph.Workspaces;
using Dynamo.Models;
using Dynamo.Search.SearchElements;
using Dynamo.Selection;
using Dynamo.UI.Prompts;
using Dynamo.Utilities;
using Dynamo.Wpf.ViewModels;
using Dynamo.Wpf.ViewModels.Core;
using Dynamo.Wpf.ViewModels.Watch3D;
using DynamoUtilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ViewModels.Core;
using Function = Dynamo.Graph.Nodes.CustomNodes.Function;
namespace Dynamo.ViewModels
{
public delegate void NoteEventHandler(object sender, EventArgs e);
public delegate void ViewEventHandler(object sender, EventArgs e);
public delegate void SelectionEventHandler(object sender, SelectionBoxUpdateArgs e);
public delegate void ViewModelAdditionEventHandler(object sender, ViewModelEventArgs e);
public delegate void WorkspacePropertyEditHandler(WorkspaceModel workspace);
public enum ShowHideFlags { Hide, Show };
public partial class WorkspaceViewModel : ViewModelBase
{
#region constants
/// <summary>
/// Represents maximum value of workspace zoom
/// </summary>
[JsonIgnore]
public const double ZOOM_MAXIMUM = 4.0;
/// <summary>
/// Represents minimum value of workspace zoom
/// </summary>
[JsonIgnore]
public const double ZOOM_MINIMUM = 0.01;
#endregion
#region events
/// <summary>
/// Function that can be used to respond to a changed workspace Zoom amount.
/// </summary>
/// <param name="sender">The object where the event handler is attached.</param>
/// <param name="e">The event data.</param>
public delegate void ZoomEventHandler(object sender, EventArgs e);
/// <summary>
/// Event that is fired every time the zoom factor of a workspace changes.
/// </summary>
public event ZoomEventHandler ZoomChanged;
/// <summary>
/// Used during open and workspace changes to set the zoom of the workspace
/// </summary>
/// <param name="sender">The object which triggers the event</param>
/// <param name="e">The zoom event data.</param>
internal virtual void OnZoomChanged(object sender, ZoomEventArgs e)
{
if (ZoomChanged != null)
{
//Debug.WriteLine(string.Format("Setting zoom to {0}", e.Zoom));
ZoomChanged(this, e);
}
}
public event ZoomEventHandler RequestZoomToViewportCenter;
/// <summary>
/// For requesting registered workspace to zoom in center
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnRequestZoomToViewportCenter(object sender, ZoomEventArgs e)
{
if (RequestZoomToViewportCenter != null)
{
RequestZoomToViewportCenter(this, e);
}
}
public event ZoomEventHandler RequestZoomToViewportPoint;
/// <summary>
/// For requesting registered workspace to zoom in out from a point
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void OnRequestZoomToViewportPoint(object sender, ZoomEventArgs e)
{
if (RequestZoomToViewportPoint != null)
{
RequestZoomToViewportPoint(this, e);
}
}
public event ZoomEventHandler RequestZoomToFitView;
/// <summary>
/// For requesting registered workspace to zoom in or out to fitview
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnRequestZoomToFitView(object sender, ZoomEventArgs e)
{
if (RequestZoomToFitView != null)
{
RequestZoomToFitView(this, e);
}
}
public event NodeEventHandler RequestCenterViewOnElement;
internal virtual void OnRequestCenterViewOnElement(object sender, ModelEventArgs e)
{
if (RequestCenterViewOnElement != null)
RequestCenterViewOnElement(this, e);
}
public event ViewEventHandler RequestAddViewToOuterCanvas;
public virtual void OnRequestAddViewToOuterCanvas(object sender, ViewEventArgs e)
{
if (RequestAddViewToOuterCanvas != null)
RequestAddViewToOuterCanvas(this, e);
}
public event SelectionEventHandler RequestSelectionBoxUpdate;
public virtual void OnRequestSelectionBoxUpdate(object sender, SelectionBoxUpdateArgs e)
{
if (RequestSelectionBoxUpdate != null)
RequestSelectionBoxUpdate(this, e);
}
public event WorkspacePropertyEditHandler WorkspacePropertyEditRequested;
public virtual void OnWorkspacePropertyEditRequested()
{
// extend this for all workspaces
if (WorkspacePropertyEditRequested != null)
WorkspacePropertyEditRequested(Model);
}
internal event Action<ShowHideFlags> RequestShowInCanvasSearch;
private void OnRequestShowInCanvasSearch(object param)
{
var flag = (ShowHideFlags)param;
RequestShowInCanvasSearch?.Invoke(flag);
}
internal event Action<object> RequestHideAllPopup;
private void OnRequestHideAllPopup(object param)
{
RequestHideAllPopup?.Invoke(param);
}
internal event Action RequestNodeAutoCompleteSearch;
internal event Action<PortViewModel> RequestNodeAutoCompleteBar;
internal event Action<ShowHideFlags, PortViewModel> RequestPortContextMenu;
internal static event Action<MLNodeClusterAutoCompletionResponse> RequestNodeAutoCompleteViewExtension;
internal void OnRequestNodeAutoCompleteSearch()
{
RequestNodeAutoCompleteSearch?.Invoke();
}
internal void OnRequestNodeAutocompleteBar(PortViewModel viewModel)
{
RequestNodeAutoCompleteBar?.Invoke(viewModel);
}
internal void OnRequestPortContextMenu(ShowHideFlags flag, PortViewModel viewModel)
{
RequestPortContextMenu?.Invoke(flag, viewModel);
}
internal void OnRequestNodeAutoCompleteViewExtension(MLNodeClusterAutoCompletionResponse clusterNodeAutoComplete)
{
RequestNodeAutoCompleteViewExtension?.Invoke(clusterNodeAutoComplete);
}
#endregion
#region Properties and Fields
[JsonIgnore]
public DynamoViewModel DynamoViewModel { get; private set; }
[JsonIgnore]
public readonly WorkspaceModel Model;
private bool _canFindNodesFromElements = false;
[JsonIgnore]
public PortViewModel portViewModel { get; set; }
[JsonIgnore]
public bool IsSnapping { get; set; }
/// <summary>
/// Gets the collection of Dynamo-specific preferences.
/// This is used when serializing Dynamo preferences in the View block of Graph.Json.
/// </summary>
[JsonProperty("Dynamo")]
public DynamoPreferencesData DynamoPreferences
{
get
{
bool hasRunWithoutCrash = false;
string runType = RunType.Manual.ToString();
string runPeriod = RunSettings.DefaultRunPeriod.ToString();
HomeWorkspaceModel homeWorkspace = Model as HomeWorkspaceModel;
if (homeWorkspace != null)
{
hasRunWithoutCrash = homeWorkspace.HasRunWithoutCrash;
runType = homeWorkspace.RunSettings.RunType.ToString();
runPeriod = homeWorkspace.RunSettings.RunPeriod.ToString();
}
bool isVisibleInDynamoLibrary = true;
CustomNodeWorkspaceModel customNodeWorkspace = Model as CustomNodeWorkspaceModel;
if (customNodeWorkspace != null)
isVisibleInDynamoLibrary = customNodeWorkspace.IsVisibleInDynamoLibrary;
return new DynamoPreferencesData(
Model.ScaleFactor,
hasRunWithoutCrash,
isVisibleInDynamoLibrary,
AssemblyHelper.GetDynamoVersion().ToString(),
runType,
runPeriod);
}
}
/// <summary>
/// Gets the Camera Data. This is used when serializing Camera Data in the View block
/// of Graph.Json.
/// </summary>
[JsonProperty("Camera")]
public CameraData Camera => DynamoViewModel.BackgroundPreviewViewModel?.GetCameraInformation() ?? new CameraData();
/// <summary>
/// ViewModel that is used in InCanvasSearch in context menu and called by Shift+DoubleClick.
/// </summary>
[JsonIgnore]
public SearchViewModel InCanvasSearchViewModel { get; private set; }
/// <summary>
/// ViewModel that is used in NodeAutoComplete feature in context menu and called by Shift+DoubleClick.
/// </summary>
[JsonIgnore]
public NodeAutoCompleteSearchViewModel NodeAutoCompleteSearchViewModel { get; private set; }
/// <summary>
/// Cursor Property Binding for WorkspaceView
/// </summary>
private Cursor currentCursor = null;
[JsonIgnore]
public Cursor CurrentCursor
{
get { return currentCursor; }
set { currentCursor = value; RaisePropertyChanged("CurrentCursor"); }
}
/// <summary>
/// Force Cursor Property Binding for WorkspaceView
/// </summary>
private bool isCursorForced = false;
[JsonIgnore]
public bool IsCursorForced
{
get { return isCursorForced; }
set { isCursorForced = value; RaisePropertyChanged("IsCursorForced"); }
}
[JsonIgnore]
public CompositeCollection WorkspaceElements { get; } = new CompositeCollection();
[JsonIgnore]
public ObservableCollection<ConnectorViewModel> Connectors { get; } = new ObservableCollection<ConnectorViewModel>();
[JsonProperty("NodeViews")]
public ObservableCollection<NodeViewModel> Nodes { get; } = new ObservableCollection<NodeViewModel>();
// Do not serialize notes, they will be converted to annotations during serialization
[JsonIgnore]
public ObservableCollection<NoteViewModel> Notes { get; } = new ObservableCollection<NoteViewModel>();
[JsonIgnore]
public ObservableCollection<ConnectorPinViewModel> Pins { get; } = new ObservableCollection<ConnectorPinViewModel>();
[JsonIgnore]
public ObservableCollection<InfoBubbleViewModel> Errors { get; } = new ObservableCollection<InfoBubbleViewModel>();
public ObservableCollection<AnnotationViewModel> Annotations { get; } = new ObservableCollection<AnnotationViewModel>();
[JsonIgnore]
public string Name
{
get
{
if (Model == DynamoViewModel.HomeSpace)
return "Home";
return Model.Name;
}
}
/// <summary>
/// Returns or set the X position of the workspace.
/// </summary>
public double X
{
get { return Model.X; }
set
{
Model.X = value;
}
}
/// <summary>
/// Returns or set the Y position of the workspace
/// </summary>
public double Y
{
get { return Model.Y; }
set
{
Model.Y = value;
}
}
[JsonIgnore]
public string FileName
{
get { return Model.FileName; }
}
[JsonIgnore]
public bool CanEditName
{
get { return Model != DynamoViewModel.HomeSpace; }
}
[JsonIgnore]
public bool IsCurrentSpace
{
get { return Model == DynamoViewModel.CurrentSpace; }
}
/// <summary>
/// Boolean indicating if the target workspace is home workspace (true), or custom node workspace (false)
/// </summary>
[JsonIgnore]
public bool IsHomeSpace
{
get { return Model == DynamoViewModel.HomeSpace; }
}
/// <summary>
/// Returns the Json representation of the current graph
/// </summary>
[JsonIgnore]
internal JObject JsonRepresentation { get; set; }
[JsonIgnore]
internal string CurrentCheckSum { get; set; }
/// <summary>
/// Returns the stringified representation of the node connections in the workspace.
/// </summary>
[JsonIgnore]
public string Checksum
{
get
{
List<string> nodeInfoConnections = new List<string>();
foreach (var connector in Connectors)
{
var connectorModel = connector.ConnectorModel;
var startingPort= connectorModel.Start;
var endingPort = connectorModel.End;
// node info connections has a unique id in the format: startnodeid[outputindex]endnodeid[outputindex].
nodeInfoConnections.Add(startingPort.Owner.AstIdentifierGuid + "[" + startingPort.Index.ToString() + "]" + endingPort.Owner.AstIdentifierGuid + "[" + endingPort.Index.ToString() + "]");
}
if (nodeInfoConnections.Count > 0)
{
var checksumhash = Hash.ToSha256String(String.Join(",", nodeInfoConnections));
CurrentCheckSum = checksumhash;
return checksumhash;
}
else
{
CurrentCheckSum = string.Empty;
return string.Empty;
}
}
}
Tuple<string,int> GetNodeByInputId(string inputId, JObject jsonWorkspace)
{
var nodes = jsonWorkspace["Nodes"];
string nodeId = string.Empty;
int connectedInputIndex = 1;
bool foundNode = false;
foreach (var node in nodes)
{
if (!foundNode)
{
nodeId = string.Empty;
connectedInputIndex = 1;
var nodeProperties = node.Children<JProperty>();
JProperty nodeProperty = nodeProperties.FirstOrDefault(x => x.Name == "Id");
nodeId = (String)nodeProperty.Value;
JProperty nodeInputs = nodeProperties.FirstOrDefault(x => x.Name == "Inputs");
var inputs = (JArray)nodeInputs.Value;
foreach (JObject input in inputs)
{
var inputProperties = input.Children<JProperty>();
JProperty connectedNodeInputId = inputProperties.FirstOrDefault(x => x.Name == "Id");
if ((String)connectedNodeInputId.Value == inputId)
{
foundNode = true;
break;
}
connectedInputIndex++;
}
}
}
return new Tuple<string, int>(nodeId, connectedInputIndex);
}
[JsonIgnore]
public bool HasUnsavedChanges
{
get { return Model.HasUnsavedChanges; }
set { Model.HasUnsavedChanges = value; }
}
private ObservableCollection<Watch3DFullscreenViewModel> _watches = new ObservableCollection<Watch3DFullscreenViewModel>();
[JsonIgnore]
public ObservableCollection<Watch3DFullscreenViewModel> Watch3DViewModels
{
get { return _watches; }
set
{
_watches = value;
RaisePropertyChanged("Watch3DViewModels");
}
}
/// <summary>
/// Get or set the zoom value of the workspace.
/// </summary>
public double Zoom
{
get { return this.Model.Zoom; }
set
{
this.Model.Zoom = value;
RaisePropertyChanged("Zoom");
}
}
/// <summary>
/// When enabled, some child WPF framework elements will not animate opacity changes,
/// and will enable bitmap cache on zoomed out state.
/// Depends on the node count threshold set via feature flag.
/// Useful for improving performance during zoom.
/// TODO DYN-8193 a future optimization if found to be necessary is to modify the styles this flag controls
/// to set visibility instead of opacity, this will likely lead to many fewer elements in the visual tree to
/// layout and render.
/// </summary>
[JsonIgnore]
public bool NodeCountOptimizationEnabled
{
get => nodeCountOptimizationEnabled;
set
{
if (nodeCountOptimizationEnabled != value)
{
nodeCountOptimizationEnabled = value;
RaisePropertyChanged(nameof(NodeCountOptimizationEnabled));
}
}
}
private bool nodeCountOptimizationEnabled = false;
private int zoomAnimationThresholdFeatureFlagVal = 0;
[JsonIgnore]
internal double MaxZoomScaleForBitmapCache
{
get => maxZoomScaleForBitmapCache;
set
{
if (maxZoomScaleForBitmapCache != value)
{
maxZoomScaleForBitmapCache = value;
RaisePropertyChanged(nameof(MaxZoomScaleForBitmapCache));
}
}
}
private double maxZoomScaleForBitmapCache = 0;
[JsonIgnore]
public bool CanZoomIn
{
get { return CanZoom(Configurations.ZoomIncrement); }
}
[JsonIgnore]
public bool CanZoomOut
{
get { return CanZoom(-Configurations.ZoomIncrement); }
}
[JsonIgnore]
public bool CanFindNodesFromElements
{
get { return _canFindNodesFromElements; }
set
{
_canFindNodesFromElements = value;
RaisePropertyChanged("CanFindNodesFromElements");
}
}
[JsonIgnore]
public bool CanShowInfoBubble
{
get { return stateMachine.IsInIdleState; }
}
[JsonIgnore]
public bool CanRunNodeToCode
{
get
{
return true;
}
}
[JsonIgnore]
public Action FindNodesFromElements { get; set; }
[JsonIgnore]
public RunSettingsViewModel RunSettingsViewModel { get; protected set; }
private GeometryScalingViewModel geoScalingViewModel;
internal GeometryScalingViewModel GeoScalingViewModel
{
get
{
return geoScalingViewModel;
}
}
/// <summary>
/// Ensures that a preview control is initialized only when it is
/// absolutely needed. It lives here so that it can be shared by
/// all node views for reduced overhead and better management.
/// </summary>
internal Wpf.Utilities.ActionDebouncer DelayNodePreviewControl
= new Wpf.Utilities.ActionDebouncer(null);
#endregion
public WorkspaceViewModel(WorkspaceModel model, DynamoViewModel dynamoViewModel)
{
this.DynamoViewModel = dynamoViewModel;
Model = model;
stateMachine = new StateMachine(this);
var nodesColl = new CollectionContainer { Collection = Nodes };
WorkspaceElements.Add(nodesColl);
var connColl = new CollectionContainer { Collection = Connectors };
WorkspaceElements.Add(connColl);
var notesColl = new CollectionContainer { Collection = Notes };
WorkspaceElements.Add(notesColl);
var pinsColl = new CollectionContainer { Collection = Pins };
WorkspaceElements.Add(pinsColl);
var errorsColl = new CollectionContainer { Collection = Errors };
WorkspaceElements.Add(errorsColl);
var annotationsColl = new CollectionContainer {Collection = Annotations};
WorkspaceElements.Add(annotationsColl);
//respond to collection changes on the model by creating new view models
//currently, view models are added for notes and nodes
//connector view models are added during connection
Model.NodeAdded += Model_NodeAdded;
Model.NodeRemoved += Model_NodeRemoved;
Model.NodesCleared += Model_NodesCleared;
Model.NoteAdded += Model_NoteAdded;
Model.NoteRemoved += Model_NoteRemoved;
Model.NotesCleared += Model_NotesCleared;
Model.AnnotationAdded += Model_AnnotationAdded;
Model.AnnotationRemoved += Model_AnnotationRemoved;
Model.AnnotationsCleared += Model_AnnotationsCleared;
Model.ConnectorAdded += Connectors_ConnectorAdded;
Model.ConnectorDeleted += Connectors_ConnectorDeleted;
Model.PropertyChanged += ModelPropertyChanged;
Model.PopulateJSONWorkspace += Model_PopulateJSONWorkspace;
DynamoSelection.Instance.Selection.CollectionChanged += RefreshViewOnSelectionChange;
DynamoViewModel.CopyCommand.CanExecuteChanged += CopyPasteChanged;
DynamoViewModel.PasteCommand.CanExecuteChanged += CopyPasteChanged;
// InCanvasSearchViewModel needs to happen before the nodes are created
// as we rely upon it to retrieve node icon images
if (!dynamoViewModel.Model.IsServiceMode)
{
InCanvasSearchViewModel = new SearchViewModel(DynamoViewModel)
{
Visible = true
};
NodeAutoCompleteSearchViewModel = new NodeAutoCompleteSearchViewModel(DynamoViewModel)
{
Visible = true
};
}
// sync collections
foreach (NodeModel node in Model.Nodes) Model_NodeAdded(node);
foreach (NoteModel note in Model.Notes) Model_NoteAdded(note);
foreach (AnnotationModel annotation in Model.Annotations) Model_AnnotationAdded(annotation);
foreach (ConnectorModel connector in Model.Connectors) Connectors_ConnectorAdded(connector);
geoScalingViewModel = new GeometryScalingViewModel(this.DynamoViewModel);
geoScalingViewModel.ScaleValue = Convert.ToInt32(Math.Log10(Model.ScaleFactor));
DynamoFeatureFlagsManager.FlagsRetrieved += OnFlagsRetrieved;
//if we've already retrieved flags, grab the value,
zoomAnimationThresholdFeatureFlagVal = (int)(DynamoModel.FeatureFlags?.CheckFeatureFlag<long>("zoom_opacity_animation_nodenum_threshold", 0) ?? 0);
SetNodeCountOptimizationEnabled(zoomAnimationThresholdFeatureFlagVal);
maxZoomScaleForBitmapCache = (double)(DynamoModel.FeatureFlags?.CheckFeatureFlag<double>("zoom_bitmap_cache_threshold", 0) ?? 0);
}
private void OnFlagsRetrieved()
{
zoomAnimationThresholdFeatureFlagVal = (int)(DynamoModel.FeatureFlags?.CheckFeatureFlag<long>("zoom_opacity_animation_nodenum_threshold", 0) ?? 0);
SetNodeCountOptimizationEnabled(zoomAnimationThresholdFeatureFlagVal);
DynamoFeatureFlagsManager.FlagsRetrieved -= OnFlagsRetrieved;
}
private void SetNodeCountOptimizationEnabled(int featureFlagValue)
{
//threshold mode so we can tune the cutoff.
if (featureFlagValue>0)
{
NodeCountOptimizationEnabled = Nodes.Count > featureFlagValue;
}
//always enable animations (ie, disable the feature flag)
else if (featureFlagValue == 0)
{
NodeCountOptimizationEnabled = false;
}
//always disable animations
else if (featureFlagValue<0)
{
NodeCountOptimizationEnabled = true;
}
}
/// <summary>
/// This event is triggered from Workspace Model. Used in instrumentation
/// </summary>
/// <param name="modelData"> Workspace model data as JSON </param>
/// <returns>workspace model with view block in string format</returns>
private string Model_PopulateJSONWorkspace(JObject modelData)
{
var jsonData = AddViewBlockToJSON(modelData);
return jsonData.ToString();
}
public override void Dispose()
{
Model.NodeAdded -= Model_NodeAdded;
Model.NodeRemoved -= Model_NodeRemoved;
Model.NodesCleared -= Model_NodesCleared;
Model.NoteAdded -= Model_NoteAdded;
Model.NoteRemoved -= Model_NoteRemoved;
Model.NotesCleared -= Model_NotesCleared;
Model.AnnotationAdded -= Model_AnnotationAdded;
Model.AnnotationRemoved -= Model_AnnotationRemoved;
Model.AnnotationsCleared -= Model_AnnotationsCleared;
Model.ConnectorAdded -= Connectors_ConnectorAdded;
Model.ConnectorDeleted -= Connectors_ConnectorDeleted;
Model.PropertyChanged -= ModelPropertyChanged;
Model.PopulateJSONWorkspace -= Model_PopulateJSONWorkspace;
DynamoSelection.Instance.Selection.CollectionChanged -= RefreshViewOnSelectionChange;
DynamoViewModel.CopyCommand.CanExecuteChanged -= CopyPasteChanged;
DynamoViewModel.PasteCommand.CanExecuteChanged -= CopyPasteChanged;
DynamoFeatureFlagsManager.FlagsRetrieved -= OnFlagsRetrieved;
var nodeViewModels = Nodes.ToList();
nodeViewModels.ForEach(nodeViewModel => nodeViewModel.Dispose());
nodeViewModels.ForEach(nodeViewModel => this.unsubscribeNodeEvents(nodeViewModel));
Notes.ToList().ForEach(noteViewModel => noteViewModel.Dispose());
Connectors.ToList().ForEach(connectorViewmModel => connectorViewmModel.Dispose());
Annotations.ToList().ForEach(AnnotationViewModel => AnnotationViewModel.Dispose());
Nodes.Clear();
Notes.Clear();
Pins.Clear();
Connectors.Clear();
Errors.Clear();
Annotations.Clear();
InCanvasSearchViewModel?.Dispose();
NodeAutoCompleteSearchViewModel.LuceneUtility?.DisposeAll();
NodeAutoCompleteSearchViewModel?.Dispose();
DelayNodePreviewControl?.Dispose();
DelayNodePreviewControl = null;
}
internal void ZoomInInternal()
{
var args = new ZoomEventArgs(Configurations.ZoomIncrement);
OnRequestZoomToViewportCenter(this, args);
ResetFitViewToggle(null);
}
internal void ZoomOutInternal()
{
var args = new ZoomEventArgs(-Configurations.ZoomIncrement);
OnRequestZoomToViewportCenter(this, args);
ResetFitViewToggle(null);
}
internal JObject GetJsonRepresentation(EngineController engine = null)
{
// Step 1: Serialize the workspace.
var json = Model.ToJson(engine);
var json_parsed = JObject.Parse(json);
// Step 2: Add the View.
return AddViewBlockToJSON(json_parsed);
}
/// <summary>
/// WorkspaceViewModel's Save method does a two-part serialization. First, it serializes the Workspace,
/// then adds a View property to serialized Workspace, and sets its value to the serialized ViewModel.
/// </summary>
/// <param name="filePath"></param>
/// <param name="isBackup"></param>
/// <param name="engine"></param>
/// <param name="saveContext"></param>
/// <exception cref="ArgumentNullException">Thrown when the file path is null.</exception>
internal bool Save(string filePath, bool isBackup = false, EngineController engine = null, SaveContext saveContext = SaveContext.None)
{
if (String.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException("filePath");
}
try
{
if (!isBackup)
{
Model.OnSaving(saveContext);
}
//set the name before serializing model.
this.Model.setNameBasedOnFileName(filePath, isBackup);
// Stage 1: Serialize the workspace and the View
var jo = GetJsonRepresentation(engine);
// Stage 2: Save
string saveContent;
if(saveContext == SaveContext.SaveAs && !isBackup)
{
// For intentional SaveAs either through UI or API calls, replace workspace elements' Guids and workspace Id
jo["Uuid"] = Guid.NewGuid().ToString();
if (jo["Bindings"] != null && jo["Bindings"].Any())
{
jo["Bindings"] = JToken.Parse("[]");
if (!DynamoModel.IsTestMode)
{
var result = DynamoMessageBox.Show(Wpf.Properties.Resources.ElementBindingWarningMessage,
Wpf.Properties.Resources.ElementBindingWarningTitle, MessageBoxButton.OKCancel,
MessageBoxImage.Warning, Wpf.Properties.Resources.ElementBindingDesc);
if (result == MessageBoxResult.Cancel)
{
return false;
}
}
}
saveContent = GuidUtility.UpdateWorkspaceGUIDs(jo.ToString());
}
else
{
saveContent = jo.ToString();
}
File.WriteAllText(filePath, saveContent);
// Handle Workspace or CustomNodeWorkspace related non-serialization internal logic
// Only for actual save, update file path and recent file list
// The assignation of the JsonRepresentation and Guid is only for the checksum flow, it will grab info only from .dyn files
if (!isBackup)
{
if (Path.GetExtension(filePath).Equals(".dyn"))
{
JsonRepresentation = JObject.Parse(saveContent);
DynamoViewModel.Workspaces[0].Model.Guid = new Guid(JsonRepresentation.Properties().First(p => p.Name == "Uuid").Value.ToString());
}
Model.FileName = filePath;
Model.OnSaved();
}
// If a new CustomNodeWorkspaceModel is created, store that info in CustomNodeManager without creating an instance of the custom node.
if (this.Model is CustomNodeWorkspaceModel customNodeWorkspaceModel)
{
//If the custom node Name is already set and the FileName is already set then we don't need to change the Name with "backup"
if(string.IsNullOrEmpty(customNodeWorkspaceModel.Name) && string.IsNullOrEmpty(customNodeWorkspaceModel.FileName))
customNodeWorkspaceModel.SetInfo(Path.GetFileNameWithoutExtension(filePath));
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + " : " + ex.StackTrace);
#pragma warning disable CA2200 // Rethrow to preserve stack details
throw ex;
#pragma warning restore CA2200 // Rethrow to preserve stack details
}
return true;
}
/// <summary>
/// This function appends view block to the model json
/// </summary>
/// <param name="modelData">Workspace Model data in JSON format</param>
private JObject AddViewBlockToJSON(JObject modelData)
{
var token = JToken.Parse(this.ToJson());
modelData.Add("View", token);
return modelData;
}
void CopyPasteChanged(object sender, EventArgs e)
{
RaisePropertyChanged("CanPaste", "CanCopy", "CanCopyOrPaste");
PasteCommand.RaiseCanExecuteChanged();
}
void Connectors_ConnectorAdded(ConnectorModel c)
{
var viewModel = new ConnectorViewModel(this, c);
if (Connectors.All(x => x.ConnectorModel != c))
Connectors.Add(viewModel);
}
void Connectors_ConnectorDeleted(ConnectorModel c)
{
var connector = Connectors.FirstOrDefault(x => x.ConnectorModel == c);
if (connector != null)
{
Connectors.Remove(connector);
connector.Dispose();
}
}
private void Model_NoteAdded(NoteModel note)
{
var viewModel = new NoteViewModel(this, note);
Notes.Add(viewModel);
}
private void Model_NoteRemoved(NoteModel note)
{
var matchingNoteViewModel = Notes.First(x => x.Model == note);
Notes.Remove(matchingNoteViewModel);
matchingNoteViewModel.Dispose();
}
private void Model_NotesCleared()
{
foreach (var noteViewModel in Notes)
{
noteViewModel.Dispose();
}
Notes.Clear();
}
private void Model_AnnotationAdded(AnnotationModel annotation)
{
var viewModel = new AnnotationViewModel(this, annotation);
Annotations.Add(viewModel);
}
private void Model_AnnotationRemoved(AnnotationModel annotation)
{
var matchingAnnotation = Annotations.First(x => x.AnnotationModel == annotation);
Annotations.Remove(matchingAnnotation);
matchingAnnotation.Dispose();
}
private void Model_AnnotationsCleared()
{
foreach (var annotationViewModel in Annotations)
{
annotationViewModel.Dispose();
}
Annotations.Clear();
}
void Model_NodesCleared()
{
lock (Nodes)
{
foreach (var nodeViewModel in Nodes)
{
this.unsubscribeNodeEvents(nodeViewModel);
nodeViewModel.Dispose();
}
Nodes.Clear();
}
Errors.Clear();
PostNodeChangeActions();
}
private void unsubscribeNodeEvents(NodeViewModel nodeViewModel)
{
nodeViewModel.SnapInputEvent -= nodeViewModel_SnapInputEvent;
nodeViewModel.NodeLogic.Modified -= OnNodeModified;
}
void Model_NodeRemoved(NodeModel node)
{
NodeViewModel nodeViewModel;
lock (Nodes)
{
nodeViewModel = Nodes.First(x => x.NodeLogic == node);
if (nodeViewModel.ErrorBubble != null)
Errors.Remove(nodeViewModel.ErrorBubble);
Nodes.Remove(nodeViewModel);
}
//unsub the events we attached below in NodeAdded.
this.unsubscribeNodeEvents(nodeViewModel);
nodeViewModel.Dispose();
PostNodeChangeActions();
SetNodeCountOptimizationEnabled(zoomAnimationThresholdFeatureFlagVal);
}
void Model_NodeAdded(NodeModel node)