-
Notifications
You must be signed in to change notification settings - Fork 675
Expand file tree
/
Copy pathDynamoViewModel.cs
More file actions
4801 lines (4223 loc) · 185 KB
/
Copy pathDynamoViewModel.cs
File metadata and controls
4801 lines (4223 loc) · 185 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.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Dynamo.Configuration;
using Dynamo.Controls;
using Dynamo.Core;
using Dynamo.Engine;
using Dynamo.Exceptions;
using Dynamo.Graph;
using Dynamo.Graph.Annotations;
using Dynamo.Graph.Connectors;
using Dynamo.Graph.Nodes;
using Dynamo.Graph.Nodes.CustomNodes;
using Dynamo.Graph.Notes;
using Dynamo.Graph.Workspaces;
using Dynamo.Interfaces;
using Dynamo.Logging;
using Dynamo.Models;
using Dynamo.PackageManager;
using Dynamo.PackageManager.UI;
using Dynamo.Scheduler;
using Dynamo.Search.SearchElements;
using Dynamo.Selection;
using Dynamo.Services;
using Dynamo.UI;
using Dynamo.UI.Prompts;
using Dynamo.Utilities;
using Dynamo.Visualization;
using Dynamo.Wpf.Interfaces;
using Dynamo.Wpf.Properties;
using Dynamo.Wpf.UI;
using Dynamo.Wpf.UI.GuidedTour;
using Dynamo.Wpf.Utilities;
using Dynamo.Wpf.ViewModels;
using Dynamo.Wpf.ViewModels.Core;
using Dynamo.Wpf.ViewModels.Core.Converters;
using Dynamo.Wpf.ViewModels.FileTrust;
using Dynamo.Wpf.ViewModels.Watch3D;
using DynamoMLDataPipeline;
using DynamoServices;
using DynamoUtilities;
using ICSharpCode.AvalonEdit;
using J2N.Text;
using Newtonsoft.Json;
using PythonNodeModels;
using ISelectable = Dynamo.Selection.ISelectable;
using WpfResources = Dynamo.Wpf.Properties.Resources;
namespace Dynamo.ViewModels
{
public interface IDynamoViewModel : INotifyPropertyChanged
{
ObservableCollection<WorkspaceViewModel> Workspaces { get; set; }
}
public partial class DynamoViewModel : ViewModelBase, IDynamoViewModel
{
#region properties
public Window Owner { get; set; }
private readonly DynamoModel model;
private Point transformOrigin;
private bool showStartPage = false;
private PreferencesViewModel preferencesViewModel;
private string dynamoMLDataPath = string.Empty;
private const string dynamoMLDataFileName = "DynamoMLDataPipeline.json";
private bool onlineAccess = true;
//2px tolerance range for node filtering during Home and End key press
private readonly int tolerance = 2;
// Can the user run the graph
private bool CanRunGraph => HomeSpace.RunSettings.RunEnabled && !HomeSpace.GraphRunInProgress;
private ObservableCollection<DefaultWatch3DViewModel> watch3DViewModels = new ObservableCollection<DefaultWatch3DViewModel>();
private ObservableCollection<TabItem> sideBarTabItems = new ObservableCollection<TabItem>();
/// <summary>
/// An observable collection of workspace view models which tracks the model.
/// </summary>
private ObservableCollection<WorkspaceViewModel> workspaces = new ObservableCollection<WorkspaceViewModel>();
/// <summary>
/// Set of node window id's that are currently docked in right side sidebar.
/// </summary>
internal HashSet<string> DockedNodeWindows { get; set; } = new HashSet<string>();
/// <summary>
/// Node window's state, either DockRight or FloatingWindow.
/// </summary>
internal Dictionary<string, ViewExtensionDisplayMode> NodeWindowsState { get; set; } = new Dictionary<string, ViewExtensionDisplayMode>();
internal DynamoMLDataPipelineExtension MLDataPipelineExtension { get; set; }
internal Dictionary<string, NodeSearchElementViewModel> DefaultAutocompleteCandidates;
/// <summary>
/// Collection of Right SideBar tab items: view extensions and docked windows.
/// </summary>
public ObservableCollection<TabItem> SideBarTabItems
{
get
{
return sideBarTabItems;
}
set
{
sideBarTabItems = value;
RaisePropertyChanged(nameof(SideBarTabItems));
}
}
public ObservableCollection<WorkspaceViewModel> Workspaces
{
get { return workspaces; }
set
{
workspaces = value;
RaisePropertyChanged("Workspaces");
}
}
public DynamoModel Model
{
get { return model; }
}
public PreferenceSettings PreferenceSettings
{
get { return Model.PreferenceSettings; }
}
internal PreferencesViewModel PreferencesViewModel
{
get
{
return preferencesViewModel;
}
}
/// <summary>
/// Denotes the last location used to open or close a workspace.
/// </summary>
internal string LastSavedLocation { get; set; }
/// <summary>
/// Toast messages manager used to create, update and clear toasts on Dynamo UI
/// </summary>
public ToastManager ToastManager { get; set; }
/// <summary>
/// Guided Tour Manager
/// </summary>
public GuidesManager MainGuideManager { get; set; }
public Point TransformOrigin
{
get { return transformOrigin; }
set
{
transformOrigin = value;
RaisePropertyChanged("TransformOrigin");
}
}
public bool ViewingHomespace
{
get { return model.CurrentWorkspace == HomeSpace; }
}
public int ScaleFactorLog
{
get
{
return (CurrentSpace == null) ? 0 :
Convert.ToInt32(Math.Log10(CurrentSpace.ScaleFactor));
}
set
{
CurrentSpace.ScaleFactor = Math.Pow(10, value);
CurrentSpace.ScaleFactorChanged = true;
}
}
public bool IsAbleToGoHome
{
get { return !(model.CurrentWorkspace is HomeWorkspaceModel); }
}
public HomeWorkspaceModel HomeSpace
{
get
{
return model.Workspaces.OfType<HomeWorkspaceModel>().FirstOrDefault();
}
}
public WorkspaceViewModel HomeSpaceViewModel
{
get { return Workspaces.FirstOrDefault(w => w.Model is HomeWorkspaceModel); }
}
public EngineController EngineController { get { return Model.EngineController; } }
public WorkspaceModel CurrentSpace
{
get { return model.CurrentWorkspace; }
}
/// <summary>
/// Controls if the the ML data ingestion pipeline is enabled or not.
/// </summary>
internal bool EnableDNADataIngestionPipeline
{
get
{
return DynamoModel.FeatureFlags?.CheckFeatureFlag("EnableDNADataIngestionPipeline", false) ?? false;
}
}
/// <summary>
/// Controls if the cluster node autocomplete placement feature is enabled from feature flag
/// </summary>
internal bool IsDNAClusterPlacementEnabled
{
get
{
return DynamoModel.FeatureFlags?.CheckFeatureFlag("IsDNAClusterPlacementEnabled", false) ?? false;
}
}
/// <summary>
/// Controls if the new DNA Flyout is enabled from preference settings.
/// </summary>
internal bool IsNewDNAUIEnabled
{
get
{
return model.PreferenceSettings.EnableNewNodeAutoCompleteUI;
}
}
/// <summary>
/// Count of unresolved issues on the linter manager.
/// This is used for binding in the NotificationsControl
/// </summary>
public int LinterIssuesCount
{
get => Model.LinterManager?.RuleEvaluationResults.Count ?? 0;
}
/// <summary>
/// Indicates whether Dynamo has online access.
/// </summary>
public bool OnlineAccess
{
get => onlineAccess;
private set
{
if (onlineAccess != value)
{
onlineAccess = value;
RaisePropertyChanged(nameof(OnlineAccess));
}
}
}
/// <summary>
/// Check for online access and update OnlineAccess property.
/// </summary>
internal void CheckOnlineAccess()
{
if (Model.NoNetworkMode)
{
OnlineAccess = false;
return;
}
Task.Run(async () =>
{
var result = await NetworkUtilities.CheckOnlineAccessAsync();
if (!result.Item2) //if check was canceled we just return - we are during shutdown sequence.
{
return;
}
try
{
await UIDispatcher?.BeginInvoke(DispatcherPriority.ApplicationIdle, () => OnlineAccess = result.Item1);
}
catch(Exception ex)
{
Trace.WriteLine($"Something went wrong mostlikely during the shutdown sequence: {ex.Message}");
}
});
}
public double WorkspaceActualHeight { get; set; }
public double WorkspaceActualWidth { get; set; }
public void WorkspaceActualSize(double width, double height)
{
WorkspaceActualWidth = width;
WorkspaceActualHeight = height;
RaisePropertyChanged("WorkspaceActualHeight");
RaisePropertyChanged("WorkspaceActualWidth");
}
/// <summary>
/// This property is the ViewModel that will be passed to the File Trust Warning popup when is created.
/// </summary>
internal FileTrustWarningViewModel FileTrustViewModel { get; set; }
private WorkspaceViewModel currentWorkspaceViewModel;
private string filePath;
private string fileContents;
/// <summary>
/// The index in the collection of workspaces of the current workspace.
/// This property is bound to the SelectedIndex property in the workspaces tab control
/// </summary>
public int CurrentWorkspaceIndex
{
get
{
// It is safe to assume that DynamoModel.CurrentWorkspace is
// update-to-date.
var viewModel = workspaces.FirstOrDefault(vm => vm.Model == model.CurrentWorkspace);
var index = workspaces.IndexOf(viewModel);
// As the getter could aslo be triggered by the change of model,
// we need to update currentWorkspaceViewModel here.
if (currentWorkspaceViewModel != viewModel)
currentWorkspaceViewModel = viewModel;
return index;
}
set
{
// It happens when current workspace is home workspace, and we
// open a new home workspace. At this moment, the old homework
// space is removed, before new home workspace is added, Dynamo
// has no idea about what is selected tab index.
if (value < 0)
return;
var viewModel = workspaces.ElementAt(value);
if (currentWorkspaceViewModel != viewModel)
{
currentWorkspaceViewModel = viewModel;
// Keep DynamoModel.CurrentWorkspace update-to-date
int modelIndex = model.Workspaces.IndexOf(currentWorkspaceViewModel.Model);
ExecuteCommand(new DynamoModel.SwitchTabCommand(modelIndex));
(HomeSpaceViewModel as HomeWorkspaceViewModel)?.UpdateRunStatusMsgBasedOnStates();
}
}
}
/// <summary>
/// Returns the workspace view model whose workspace model is the model's current workspace
/// </summary>
public WorkspaceViewModel CurrentSpaceViewModel
{
get
{
if (currentWorkspaceViewModel == null)
currentWorkspaceViewModel = workspaces.FirstOrDefault(vm => vm.Model == model.CurrentWorkspace);
return currentWorkspaceViewModel;
}
}
internal AutomationSettings Automation { get { return this.automationSettings; } }
internal string editName = "";
public string EditName
{
get { return editName; }
set
{
editName = value;
RaisePropertyChanged("EditName");
}
}
public bool ShowStartPage
{
get { return this.showStartPage; }
set
{
// If the caller attempts to show the start page, but we are
// currently in playback mode, then this will not be allowed
// (i.e. the start page will never be shown during a playback).
//
if ((value == true) && (null != automationSettings))
{
if (automationSettings.IsInPlaybackMode)
return;
}
showStartPage = value;
if (showStartPage) Logging.Analytics.TrackScreenView("StartPage");
RaisePropertyChanged("ShowStartPage");
if (DisplayStartPageCommand != null)
DisplayStartPageCommand.RaiseCanExecuteChanged();
if (DisplayInteractiveGuideCommand != null)
DisplayInteractiveGuideCommand.RaiseCanExecuteChanged();
if(ShowInsertDialogAndInsertResultCommand != null)
ShowInsertDialogAndInsertResultCommand.RaiseCanExecuteChanged();
}
}
public string LogText
{
get { return model.Logger.LogText; }
}
public int ConsoleHeight
{
get
{
return model.PreferenceSettings.ConsoleHeight;
}
set
{
model.PreferenceSettings.ConsoleHeight = value;
RaisePropertyChanged("ConsoleHeight");
}
}
private double minLeftMarignOffset;
/// <summary>
/// The
/// </summary>
public double MinLeftMarginOffset
{
get => minLeftMarignOffset;
set
{
if(minLeftMarignOffset != value)
{
minLeftMarignOffset = value;
RaisePropertyChanged(nameof(MinLeftMarginOffset));
}
}
}
/// <summary>
/// Indicates if preview bubbles should be displayed on nodes.
/// </summary>
[Obsolete("This was moved to PreferencesViewModel.cs")]
public bool ShowPreviewBubbles
{
get
{
return model.PreferenceSettings.ShowPreviewBubbles;
}
set
{
model.PreferenceSettings.ShowPreviewBubbles = value;
RaisePropertyChanged("ShowPreviewBubbles");
}
}
/// <summary>
/// Indicates if line numbers should be displayed on code block nodes.
/// </summary>
[Obsolete("This was moved to PreferencesViewModel.cs")]
public bool ShowCodeBlockLineNumber
{
get
{
return model.PreferenceSettings.ShowCodeBlockLineNumber;
}
set
{
model.PreferenceSettings.ShowCodeBlockLineNumber = value;
RaisePropertyChanged(nameof(ShowCodeBlockLineNumber));
}
}
/// <summary>
/// Indicates whether to make T-Spline nodes (under ProtoGeometry.dll) discoverable
/// in the node search library.
/// </summary>
[Obsolete("This was moved to PreferencesViewModel.cs")]
public bool EnableTSpline
{
get
{
return !PreferenceSettings.NamespacesToExcludeFromLibrary.Contains(
"ProtoGeometry.dll:Autodesk.DesignScript.Geometry.TSpline");
}
set
{
model.HideUnhideNamespace(!value,
"ProtoGeometry.dll", "Autodesk.DesignScript.Geometry.TSpline");
}
}
/// <summary>
/// Indicates whether to enabled node Auto Complete feature for port interaction.
/// </summary>
public bool EnableNodeAutoComplete
{
get
{
return PreferenceSettings.EnableNodeAutoComplete;
}
set
{
PreferenceSettings.EnableNodeAutoComplete = value;
}
}
public int LibraryWidth
{
get
{
return model.PreferenceSettings.LibraryWidth;
}
set
{
model.PreferenceSettings.LibraryWidth = value;
RaisePropertyChanged("LibraryWidth");
}
}
public bool IsShowingConnectors
{
get
{
return model.IsShowingConnectors;
}
set
{
model.IsShowingConnectors = value;
RaisePropertyChanged(nameof(IsShowingConnectors));
}
}
/// <summary>
/// Relaying the flag `IsShowingConnectorTooltip' coming from
/// the Dynamo model.
/// </summary>
public bool IsShowingConnectorTooltip
{
get
{
return model.IsShowingConnectorTooltip;
}
set
{
model.IsShowingConnectorTooltip = value;
RaisePropertyChanged(nameof(IsShowingConnectorTooltip));
}
}
public bool IsMouseDown { get; set; }
public ConnectorType ConnectorType
{
get
{
return model.ConnectorType;
}
set
{
model.ConnectorType = value;
RaisePropertyChanged("ConnectorType");
}
}
private ObservableCollection<string> recentFiles =
new ObservableCollection<string>();
public ObservableCollection<string> RecentFiles
{
get { return recentFiles; }
set
{
recentFiles = value;
RaisePropertyChanged("RecentFiles");
}
}
public bool WatchIsResizable { get; set; }
public string Version
{
get { return DynamoModel.Version; }
}
public string HostVersion
{
get { return model.HostVersion; }
}
public string HostName
{
get { return model.HostName; }
}
public string LicenseFile
{
get
{
string executingAssemblyPathName = Assembly.GetExecutingAssembly().Location;
string rootModuleDirectory = Path.GetDirectoryName(executingAssemblyPathName);
return Path.Combine(rootModuleDirectory, "License.rtf");
}
}
public bool VerboseLogging
{
get { return model.DebugSettings.VerboseLogging; }
set
{
model.DebugSettings.VerboseLogging = value;
RaisePropertyChanged("VerboseLogging");
}
}
public bool ShowDebugASTs
{
get { return IsDebugBuild && model.DebugSettings.ShowDebugASTs; }
set
{
model.DebugSettings.ShowDebugASTs = value;
RaisePropertyChanged("ShowDebugASTs");
}
}
internal Dispatcher UIDispatcher { get; set; }
public IWatchHandler WatchHandler { get; private set; }
[Obsolete("This Property will be obsoleted in a future version of Dynamo")]
internal SearchViewModel SearchViewModel { get; private set; }
public PackageManagerClientViewModel PackageManagerClientViewModel { get; private set; }
/// <summary>
/// Whether sign in should be shown in Dynamo. In instances where Dynamo obtains
/// authentication capabilities from a host, Dynamo's sign in should generally be
/// hidden to avoid inconsistencies in state.
/// </summary>
public bool ShowLogin { get; private set; }
private bool showRunPreview;
public bool ShowRunPreview
{
get { return showRunPreview; }
set
{
showRunPreview = value;
HomeSpace.GetExecutingNodes(showRunPreview);
RaisePropertyChanged("ShowRunPreview");
}
}
public RenderPackageFactoryViewModel RenderPackageFactoryViewModel { get; set; }
public bool EnablePresetOptions
{
get { return this.Model.CurrentWorkspace.Presets.Any(); }
}
/// <summary>
/// A collection of <see cref="DefaultWatch3DViewModel"/> objects.
///
/// Each DefaultWatch3DViewModel object is responsible for converting
/// data for visualization in a different context. For example, the
/// <see cref="HelixWatch3DViewModel"/> provides the geometry for the
/// background preview.
/// </summary>
public IEnumerable<DefaultWatch3DViewModel> Watch3DViewModels
{
get { return watch3DViewModels; }
}
/// <summary>
/// A <see cref="DefaultWatch3DViewModel"/> which provides the
/// geometry for the primary background 3d preview.
/// </summary>
public DefaultWatch3DViewModel BackgroundPreviewViewModel { get; private set; }
public bool BackgroundPreviewActive
{
get { return BackgroundPreviewViewModel.Active; }
}
public bool HideReportOptions { get; internal set; }
private DynamoPythonScriptEditorTextOptions editTextOptions = new DynamoPythonScriptEditorTextOptions();
/// <summary>
/// Gets/Sets the text editor options for python script editor.
/// </summary>
internal DynamoPythonScriptEditorTextOptions PythonScriptEditorTextOptions
{
get
{
return editTextOptions;
}
}
/// <summary>
/// Indicates if the whitespaces and tabs should be visible in the python script editor.
/// This property is for the global whitespace toggle option in settings menu.
/// </summary>
public bool ShowTabsAndSpacesInScriptEditor
{
get
{
return model.PreferenceSettings.ShowTabsAndSpacesInScriptEditor;
}
set
{
PythonScriptEditorTextOptions.ShowWhiteSpaceCharacters(value);
model.PreferenceSettings.ShowTabsAndSpacesInScriptEditor = value;
RaisePropertyChanged(nameof(ShowTabsAndSpacesInScriptEditor));
}
}
/// <summary>
/// Engine used by default for new Python script and string nodes. If not empty, this takes precedence over any system settings.
/// </summary>
[Obsolete ("This was moved to PreferencesViewModel.cs")]
public string DefaultPythonEngine
{
get { return model.PreferenceSettings.DefaultPythonEngine; }
set
{
if (value != model.PreferenceSettings.DefaultPythonEngine)
{
model.PreferenceSettings.DefaultPythonEngine = value;
RaisePropertyChanged(nameof(DefaultPythonEngine));
}
}
}
#endregion
public struct StartConfiguration
{
public string CommandFilePath { get; set; }
public IWatchHandler WatchHandler { get; set; }
public DynamoModel DynamoModel { get; set; }
public bool ShowLogin { get; set; }
public DefaultWatch3DViewModel Watch3DViewModel { get; set; }
/// <summary>
/// This property is initialized if there is an external host application
/// at startup in order to be used to pass in host specific resources to DynamoViewModel
/// </summary>
public IBrandingResourceProvider BrandingResourceProvider { get; set; }
/// <summary>
/// If true, Analytics and Usage options are hidden from UI
/// </summary>
public bool HideReportOptions { get; set; }
}
public static DynamoViewModel Start(StartConfiguration startConfiguration = new StartConfiguration())
{
if (startConfiguration.DynamoModel == null)
startConfiguration.DynamoModel = DynamoModel.Start();
if(startConfiguration.WatchHandler == null)
startConfiguration.WatchHandler = new DefaultWatchHandler(startConfiguration.DynamoModel.PreferenceSettings);
if (startConfiguration.Watch3DViewModel == null)
{
startConfiguration.Watch3DViewModel =
HelixWatch3DViewModel.TryCreateHelixWatch3DViewModel(
null,
new Watch3DViewModelStartupParams(startConfiguration.DynamoModel),
startConfiguration.DynamoModel.Logger);
}
return new DynamoViewModel(startConfiguration);
}
private void SearchDefaultNodeAutocompleteCandidates()
{
var tempSearchViewModel = new SearchViewModel(this)
{
Visible = true
};
DefaultAutocompleteCandidates = new Dictionary<string, NodeSearchElementViewModel>();
// TODO: These are basic input types in Dynamo
// This should be only served as a temporary default case.
var queries = new List<string>() { "String", "Number Slider", "Integer Slider", "Number", "Boolean", "Watch", "Watch 3D", "Python Script" };
var categories = new List<(string, SearchElementGroup)> { (".List", SearchElementGroup.Create), (".List", SearchElementGroup.Query) };
var addNodeIfValid = (NodeSearchElement nse) =>
{
var node = nse != null ? tempSearchViewModel.MakeNodeSearchElementVM(nse) : null;
if (node != null)
DefaultAutocompleteCandidates.Add(node.Name, node);
};
foreach (var query in queries)
{
addNodeIfValid(tempSearchViewModel.Model.Entries.FirstOrDefault(n => n.Name == query));
}
foreach(var query in categories)
{
var categoryNse = tempSearchViewModel.Model.Entries.Where(n => n.FullCategoryName.EndsWith(query.Item1) && n.Group == query.Item2);
foreach (var item in categoryNse)
{
addNodeIfValid(item);
}
}
tempSearchViewModel.Dispose();
}
protected DynamoViewModel(StartConfiguration startConfiguration)
{
// CurrentDomain_UnhandledException - catches unhandled exceptions that are fatal to the current process. These exceptions cannot be handled and process termination is guaranteed
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// Dispatcher.CurrentDispatcher.UnhandledException - catches unhandled exceptions from the UI thread. Can mark exceptions as handled (and close Dynamo) so that host apps can continue running normally even though Dynamo crashed
Dispatcher.CurrentDispatcher.UnhandledException += CurrentDispatcher_UnhandledException;
// TaskScheduler.UnobservedTaskException - catches unobserved Task exceptions from all threads. Does not crash Dynamo, we only log the exceptions and do not call CER or close Dynamo
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
this.ShowLogin = startConfiguration.ShowLogin;
// initialize core data structures
this.model = startConfiguration.DynamoModel;
this.model.CommandStarting += OnModelCommandStarting;
this.model.CommandCompleted += OnModelCommandCompleted;
this.model.RequestsCrashPrompt += CrashReportTool.ShowCrashWindow;
this.HideReportOptions = startConfiguration.HideReportOptions || model.NoNetworkMode;
UsageReportingManager.Instance.InitializeCore(this);
this.WatchHandler = startConfiguration.WatchHandler;
var pmExtension = model.GetPackageManagerExtension();
if (pmExtension != null)
{
this.PackageManagerClientViewModel = new PackageManagerClientViewModel(this, pmExtension.PackageManagerClient);
}
this.SearchViewModel = null;
// Start page should not show up during test mode.
this.ShowStartPage = !DynamoModel.IsTestMode;
this.BrandingResourceProvider = startConfiguration.BrandingResourceProvider ?? new DefaultBrandingResourceProvider();
// commands should be initialized before adding any WorkspaceViewModel
InitializeDelegateCommands();
//add the initial workspace and register for future
//updates to the workspaces collection
if(!Model.IsServiceMode)
{
SearchDefaultNodeAutocompleteCandidates();
}
var homespaceViewModel = new HomeWorkspaceViewModel(model.CurrentWorkspace as HomeWorkspaceModel, this);
workspaces.Add(homespaceViewModel);
currentWorkspaceViewModel = homespaceViewModel;
model.WorkspaceAdded += WorkspaceAdded;
model.WorkspaceRemoved += WorkspaceRemoved;
if (model.LinterManager != null)
{
model.LinterManager.RuleEvaluationResults.CollectionChanged += OnRuleEvaluationResultsCollectionChanged;
}
SubscribeModelCleaningUpEvent();
SubscribeModelUiEvents();
SubscribeModelChangedHandlers();
SubscribeModelBackupFileSaveEvent();
InitializeAutomationSettings(startConfiguration.CommandFilePath);
SubscribeLoggerHandlers();
DynamoSelection.Instance.Selection.CollectionChanged += SelectionOnCollectionChanged;
InitializeRecentFiles();
UsageReportingManager.Instance.PropertyChanged += CollectInfoManager_PropertyChanged;
WatchIsResizable = false;
SubscribeDispatcherHandlers();
RenderPackageFactoryViewModel = new RenderPackageFactoryViewModel(Model.PreferenceSettings);
RenderPackageFactoryViewModel.PropertyChanged += RenderPackageFactoryViewModel_PropertyChanged;
BackgroundPreviewViewModel = startConfiguration.Watch3DViewModel;
BackgroundPreviewViewModel.PropertyChanged += Watch3DViewModelPropertyChanged;
WatchHandler.RequestSelectGeometry += BackgroundPreviewViewModel.AddLabelForPath;
RegisterWatch3DViewModel(BackgroundPreviewViewModel, RenderPackageFactoryViewModel.Factory);
model.ComputeModelDeserialized += model_ComputeModelDeserialized;
model.RequestNotification += model_RequestNotification;
preferencesViewModel = new PreferencesViewModel(this);
dynamoMLDataPath = Path.Combine(Model.PathManager.UserDataDirectory, dynamoMLDataFileName);
if (!DynamoModel.IsTestMode && !DynamoModel.IsHeadless)
{
model.State = DynamoModel.DynamoModelState.StartedUI;
// deserialize workspace checksum hashes that is used for Dynamo ML data pipeline.
if (File.Exists(dynamoMLDataPath))
{
try
{
Model.GraphChecksumDictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(File.ReadAllText(dynamoMLDataPath));
}
catch (Exception ex)
{
Model.Logger.Log($"Failed to deserialize {dynamoMLDataFileName} : {ex.Message}", LogLevel.File);
}
}
}
FileTrustViewModel = new FileTrustWarningViewModel();
MLDataPipelineExtension = model.ExtensionManager.Extensions.OfType<DynamoMLDataPipelineExtension>().FirstOrDefault();
IsIDSDKInitialized();
NetworkUtilities.InitInternetCheck();
CheckOnlineAccess();
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
try
{
var crashData = new CrashErrorReportArgs(e.Exception);
Model?.Logger?.LogError($"Unobserved task exception: {crashData.Details}");
Analytics.TrackException(e.Exception, true);
}
catch
{ }
}
private void CurrentDispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (e.Handled || DynamoModel.IsCrashing)
{
return;
}
if (DynamoModel.IsTestMode)
{
// Do not handle the exception in test mode.
// Let the test host handle it.
}
else
{
// Try to handle the exception so that the host app can continue (in most cases).
// In some cases Dynamo code might still crash after this handler kicks in. In these edge cases
// we might see 2 CER windows (the extra one from the host app) - CER tool might handle this in the future.
e.Handled = true;
}
CrashGracefully(e.Exception);
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (!DynamoModel.IsCrashing)//Avoid duplicate CER reports
{
CrashGracefully(e.ExceptionObject as Exception, fatal: true);
}
}
// CrashGracefully should only be used in the DynamoViewModel class or within tests.
internal void CrashGracefully(Exception ex, bool fatal = false)
{
try
{
var exceptionAssembly = ex.TargetSite?.Module?.Assembly;
// TargetInvocationException is the exception that is thrown by methods invoked through reflection
// The inner exception contains the originating exception.
// https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/7.0/reflection-invoke-exceptions
if (ex is TargetInvocationException && ex.InnerException != null)