-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathDynamoModel.cs
More file actions
3917 lines (3360 loc) · 156 KB
/
DynamoModel.cs
File metadata and controls
3917 lines (3360 loc) · 156 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.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Dynamo.Configuration;
using Dynamo.Core;
using Dynamo.Engine;
using Dynamo.Events;
using Dynamo.Extensions;
using Dynamo.Graph;
using Dynamo.Graph.Annotations;
using Dynamo.Graph.Connectors;
using Dynamo.Graph.Nodes;
using Dynamo.Graph.Nodes.CustomNodes;
using Dynamo.Graph.Nodes.NodeLoaders;
using Dynamo.Graph.Nodes.ZeroTouch;
using Dynamo.Graph.Notes;
using Dynamo.Graph.Workspaces;
using Dynamo.Interfaces;
using Dynamo.Linting;
using Dynamo.Logging;
using Dynamo.Migration;
using Dynamo.Properties;
using Dynamo.Scheduler;
using Dynamo.Search;
using Dynamo.Search.SearchElements;
using Dynamo.Selection;
using Dynamo.Utilities;
using DynamoServices;
using DynamoUtilities;
using Greg;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ProtoCore;
using ProtoCore.Runtime;
using static Dynamo.Core.PathManager;
using Compiler = ProtoAssociative.Compiler;
// Dynamo package manager
using FunctionGroup = Dynamo.Engine.FunctionGroup;
using Symbol = Dynamo.Graph.Nodes.CustomNodes.Symbol;
using Utils = Dynamo.Graph.Nodes.Utilities;
namespace Dynamo.Models
{
/// <summary>
/// This class contains the extra Dynamo-specific preferences data
/// </summary>
public class DynamoPreferencesData
{
public double ScaleFactor { get; internal set; }
public bool HasRunWithoutCrash { get; internal set; }
public bool IsVisibleInDynamoLibrary { get; internal set; }
public string Version { get; internal set; }
public string RunType { get; internal set; }
public string RunPeriod { get; internal set; }
public DynamoPreferencesData(
double scaleFactor,
bool hasRunWithoutCrash,
bool isVisibleInDynamoLibrary,
string version,
string runType,
string runPeriod)
{
ScaleFactor = scaleFactor;
HasRunWithoutCrash = hasRunWithoutCrash;
IsVisibleInDynamoLibrary = isVisibleInDynamoLibrary;
Version = version;
RunType = runType;
RunPeriod = runPeriod;
}
public static DynamoPreferencesData Default()
{
return new DynamoPreferencesData(
1.0,
true,
true,
AssemblyHelper.GetDynamoVersion().ToString(),
Models.RunType.Automatic.ToString(),
RunSettings.DefaultRunPeriod.ToString());
}
}
/// <summary>
/// Host analytics related info
/// </summary>
public struct HostAnalyticsInfo
{
// Dynamo variation identified by host, e.g. Dynamo Revit
public string HostName;
// Dynamo variation version specific to host
public Version HostVersion;
// Dynamo host application name, e.g. Revit
public string HostProductName;
// Dynamo host application version, e.g. 2025.2.0
public Version HostProductVersion;
// Dynamo host parent id for analytics purpose.
public string ParentId;
// Dynamo host session id for analytics purpose.
public string SessionId;
}
/// <summary>
/// This class creates an interface for Engine controller.
/// </summary>
public interface IEngineControllerManager
{
/// <summary>
/// A controller to coordinate the interactions between some DesignScript
/// sub components like library management, live runner and so on.
/// </summary>
EngineController EngineController { get; }
}
/// <summary>
/// The core model of Dynamo.
/// </summary>
public partial class DynamoModel : IDynamoModel, IDisposable, IEngineControllerManager, ITraceReconciliationProcessor
{
#region private members
private readonly string geometryFactoryPath;
private readonly PathManager pathManager;
private WorkspaceModel currentWorkspace;
private Timer backupFilesTimer;
private Dictionary<Guid, string> backupFilesDict = new();
internal readonly Stopwatch stopwatch = Stopwatch.StartNew();
/// <summary>
/// Indicating if ASM is loaded correctly, defaulting to true because integrators most likely have code for ASM preloading
/// During sandbox initializing, Dynamo checks specifically if ASM loading was correct
/// </summary>
internal bool IsASMLoaded = true;
// Lucene search utility to perform indexing operations on nodes.
internal LuceneSearchUtility LuceneUtility
{
get
{
return LuceneSearch.LuceneUtilityNodeSearch;
}
}
/// <summary>
/// Return a dictionary of GraphChecksumItems.
/// Key will be the workspace guid and its value will be a list of saved checksums(sha256 hash) for that workspace.
/// </summary>
internal Dictionary<string, List<string>> GraphChecksumDictionary { get; set; }
// Get ProgramData folder path (usually C:\ProgramData)
static readonly string programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
#endregion
#region static properties
/// <summary>
/// Testing flag is used to defer calls to run in the idle thread
/// with the assumption that the entire test will be wrapped in an
/// idle thread call.
/// </summary>
public static bool IsTestMode { get; set; }
/// <summary>
/// Flag to indicate that there is no UI on this process, and things
/// like the node index process, update manager and the analytics collection
/// should be disabled.
/// </summary>
public static bool IsHeadless { get; set; }
/// <summary>
/// Specifies whether or not Dynamo is in a crash-state.
/// </summary>
public static bool IsCrashing { get; set; }
/// <summary>
/// Setting this flag enables creation of an XML in following format that records
/// node mapping information - which old node has been converted to which to new node(s)
/// </summary>
public static bool EnableMigrationLogging { get; set; }
#endregion
#region public properties
/// <summary>
/// DesignScript VM EngineController, used for this instance of Dynamo.
/// </summary>
public EngineController EngineController { get; set; }
/// <summary>
/// Manages all loaded ZeroTouch libraries.
/// </summary>
public readonly LibraryServices LibraryServices;
/// <summary>
/// Flag specifying whether a shutdown of Dynamo was requested.
/// </summary>
public bool ShutdownRequested { get; internal set; }
/// <summary>
/// This version of Dynamo.
/// </summary>
public static string Version
{
get { return Core.PathManager.Instance.GetProductVersion().ToString(); }
}
/// <summary>
/// Current Version of the Host (i.e. DynamoRevit/DynamoStudio)
/// </summary>
public string HostVersion { get; set; }
/// <summary>
/// Name of the Host (i.e. DynamoRevit/DynamoStudio)
/// </summary>
[Obsolete("This property will be removed in a future version of Dynamo - please use HostAnalyticsInfo")]
internal string HostName { get; set; }
/// <summary>
/// Host analytics info
/// </summary>
public static HostAnalyticsInfo HostAnalyticsInfo { get; set; }
/// <summary>
/// Boolean indication of launching Dynamo in service mode, this mode is optimized for minimal launch time, mostly leveraged by CLI or WPF CLI.
/// </summary>
internal bool IsServiceMode { get; set; }
/// <summary>
/// True if Dynamo is used in offline mode.
/// </summary>
internal bool NoNetworkMode { get; }
/// <summary>
/// Locale forced by cli arguments
/// </summary>
internal string CLILocale { get; set; }
/// <summary>
/// The path manager that configures path information required for
/// Dynamo to function properly. See IPathManager interface for more
/// details.
/// </summary>
public IPathManager PathManager { get { return pathManager; } }
/// <summary>
/// The context that Dynamo is running under.
/// </summary>
public readonly string Context;
/// <summary>
/// Manages all extensions for Dynamo
/// </summary>
public IExtensionManager ExtensionManager { get { return extensionManager; } }
/// <summary>
/// Manages the active linter
/// </summary>
public LinterManager LinterManager { get; }
private readonly ExtensionManager extensionManager;
/// <summary>
/// Manages all loaded NodeModel libraries.
/// </summary>
public readonly NodeModelAssemblyLoader Loader;
/// <summary>
/// Custom Node Manager instance, manages all loaded custom nodes.
/// </summary>
public readonly CustomNodeManager CustomNodeManager;
//TODO consider making this an interface.
/// <summary>
/// The Dynamo Logger, receives and manages all log messages.
/// </summary>
public readonly DynamoLogger Logger;
/// <summary>
/// The Dynamo Scheduler, handles scheduling of asynchronous tasks on different
/// threads.
/// </summary>
public DynamoScheduler Scheduler { get; private set; }
/// <summary>
/// The Dynamo Node Library, complete with Search.
/// </summary>
public readonly NodeSearchModel SearchModel;
/// <summary>
/// Debugging settings for this instance of Dynamo.
/// </summary>
public readonly DebugSettings DebugSettings;
/// <summary>
/// Preference settings for this instance of Dynamo.
/// </summary>
public PreferenceSettings PreferenceSettings { get; private set; }
/// <summary>
/// Node Factory, used for creating and intantiating loaded Dynamo nodes.
/// </summary>
public readonly NodeFactory NodeFactory;
/// <summary>
/// Migration Manager, upgrades old Dynamo file formats to the current version.
/// </summary>
public readonly MigrationManager MigrationManager;
/// <summary>
/// The active workspace in Dynamo.
/// </summary>
public WorkspaceModel CurrentWorkspace
{
get { return currentWorkspace; }
set
{
if (Equals(value, currentWorkspace)) return;
var old = currentWorkspace;
currentWorkspace = value;
OnWorkspaceHidden(old);
OnPropertyChanged(nameof(CurrentWorkspace));
}
}
/// <summary>
/// The copy/paste clipboard.
/// </summary>
public ObservableCollection<ModelBase> ClipBoard { get; set; }
/// <summary>
/// Specifies whether connectors are displayed in Dynamo.
/// </summary>
public bool IsShowingConnectors
{
get { return PreferenceSettings.ShowConnector; }
set
{
PreferenceSettings.ShowConnector = value;
}
}
/// <summary>
/// Flag specifying the current state of whether or not to show
/// tooltips in the graph. In addition to this toggle, tooltip is only
/// available when connectors are set to 'bezier' mode.
/// </summary>
public bool IsShowingConnectorTooltip
{
get
{
return PreferenceSettings.ShowConnectorToolTip;
}
set
{
PreferenceSettings.ShowConnectorToolTip = value;
}
}
private ConnectorType connectorType = ConnectorType.BEZIER;
/// <summary>
/// Specifies how connectors are displayed in Dynamo.
/// </summary>
public ConnectorType ConnectorType
{
get { return connectorType; }
set
{
connectorType = value;
}
}
/// <summary>
/// The private collection of visible workspaces in Dynamo
/// </summary>
private readonly List<WorkspaceModel> _workspaces = new();
/// <summary>
/// Returns collection of visible workspaces in Dynamo
/// </summary>
public IEnumerable<WorkspaceModel> Workspaces
{
get { return _workspaces; }
}
/// <summary>
/// An object which implements the ITraceReconciliationProcessor interface,
/// and is used for handlling the results of a trace reconciliation.
/// </summary>
public ITraceReconciliationProcessor TraceReconciliationProcessor { get; set; }
/// <summary>
/// Returns authentication manager object for oxygen authentication.
/// </summary>
public AuthenticationManager AuthenticationManager { get; set; }
internal static string DefaultPythonEngine { get; private set; }
internal static DynamoUtilities.DynamoFeatureFlagsManager FeatureFlags { get; private set; }
#endregion
#region constants
private const int INSERT_VERTICAL_OFFSET_VALUE = 750;
#endregion
#region initialization and disposal
/// <summary>
/// External components call this method to shutdown DynamoModel. This
/// method marks 'ShutdownRequested' property to 'true'. This method is
/// used rather than a public virtual method to ensure that the value of
/// ShutdownRequested is set to true.
/// </summary>
/// <param name="shutdownHost">Set this parameter to true to shutdown
/// the host application.</param>
public void ShutDown(bool shutdownHost)
{
if (ShutdownRequested)
{
const string message = "'DynamoModel.ShutDown' called twice";
throw new InvalidOperationException(message);
}
ShutdownRequested = true;
OnShutdownStarted(); // Notify possible event handlers.
foreach (var ext in ExtensionManager.Extensions)
{
try
{
ext.Shutdown();
}
catch (Exception exc)
{
Logger.Log($"{ext.Name} : {exc.Message} during shutdown");
}
}
PreShutdownCore(shutdownHost);
ShutDownCore(shutdownHost);
PostShutdownCore(shutdownHost);
AnalyticsService.ShutDown();
LuceneSearch.LuceneUtilityNodeSearch = null;
LuceneSearch.LuceneUtilityNodeAutocomplete = null;
LuceneSearch.LuceneUtilityPackageManager = null;
State = DynamoModelState.NotStarted;
OnShutdownCompleted(); // Notify possible event handlers.
}
/// <summary>
/// Based on the DynamoModelState a dependent component can take certain
/// decisions regarding its UI and functionality.
/// In order to be able to run a specified graph , DynamoModel needs to be
/// at least in StartedUIless state.
/// </summary>
public enum DynamoModelState { NotStarted, StartedUIless, StartedUI };
/// <summary>
/// The modelState tels us if the RevitDynamoModel was started and if has the
/// the Dynamo UI attached to it or not
/// </summary>
public DynamoModelState State { get; internal set; } = DynamoModelState.NotStarted;
/// <summary>
/// CLIMode indicates if we are running in DynamoCLI or DynamoWPFCLI mode.
/// Note that in CLI mode Scheduler is synchronous.
/// </summary>
public bool CLIMode { get; internal set; }
/// <summary>
/// The Autodesk CrashReport tool location on disk (directory that contains the "cer.dll")
/// </summary>
public string CERLocation { get; internal set; }
protected virtual void PreShutdownCore(bool shutdownHost)
{
}
protected virtual void ShutDownCore(bool shutdownHost)
{
Dispose();
PreferenceSettings.SaveInternal(pathManager.PreferenceFilePath);
OnCleanup();
DynamoSelection.DestroyInstance();
if (Scheduler != null)
{
Scheduler.Shutdown();
Scheduler.TaskStateChanged -= OnAsyncTaskStateChanged;
Scheduler = null;
}
}
protected virtual void PostShutdownCore(bool shutdownHost)
{
}
// TODO_Dynamo3.0: Replace the IStartConfiguration with a class or struct instance in order to avoid future breaking changes for every new option added.
public interface IStartConfiguration
{
string Context { get; set; }
string DynamoCorePath { get; set; }
string DynamoHostPath { get; set; }
IPreferences Preferences { get; set; }
IPathResolver PathResolver { get; set; }
bool StartInTestMode { get; set; }
ISchedulerThread SchedulerThread { get; set; }
string GeometryFactoryPath { get; set; }
IAuthProvider AuthProvider { get; set; }
IEnumerable<IExtension> Extensions { get; set; }
TaskProcessMode ProcessMode { get; set; }
/// <summary>
/// If true, the program does not have a UI.
/// No update checks or analytics collection should be done.
/// </summary>
bool IsHeadless { get; set; }
/// <summary>
/// Configuration option to start Dynamo in offline mode.
/// </summary>
bool NoNetworkMode => false;
/// <summary>
/// Configuration object that contains host information like Host name, parent id and session id.
/// </summary>
HostAnalyticsInfo HostAnalyticsInfo { get; set; }
}
/// <summary>
/// Options used to customize the CER (crash error reporting) experience.
/// </summary>
public struct CrashReporterStartupOptions
{
/// <summary>
/// The Autodesk CrashReport tool location on disk (directory that contains the "senddmp.exe")
/// </summary>
public string CERLocation { get; set; }
}
// Remove this interface in Dynamo4.0 and merge it back into IStartConfiguration.
/// <summary>
/// Use this interface to set the CER (crash error reporting) tool path.
/// </summary>
public interface IStartConfigCrashReporter
{
/// <summary>
/// CERLocation
/// </summary>
CrashReporterStartupOptions CRStartConfig { get; set; }
}
//TODO remove in dynamo 4.0
/// <summary>
/// Provides a mechanism to configure logging for DynamoModel.
/// Implement this interface to supply a logger instance for capturing logs during initialization and runtime.
/// </summary>
public interface IStartConfigurationLogger
{
/// <summary>
/// Specify the logger instance.
/// </summary>
DynamoLogger Logger { get; set; }
}
/// <summary>
/// Initialization settings for DynamoModel.
/// </summary>
public struct DefaultStartConfiguration : IStartConfiguration, IStartConfigurationLogger
{
public string Context { get; set; }
public string DynamoCorePath { get; set; }
public string DynamoHostPath { get; set; }
public IPreferences Preferences { get; set; }
public IPathResolver PathResolver { get; set; }
public bool StartInTestMode { get; set; }
public ISchedulerThread SchedulerThread { get; set; }
public string GeometryFactoryPath { get; set; }
public IAuthProvider AuthProvider { get; set; }
public IEnumerable<IExtension> Extensions { get; set; }
public TaskProcessMode ProcessMode { get; set; }
public bool IsHeadless { get; set; }
public bool NoNetworkMode { get; set; }
public bool IsServiceMode { get; set; }
public string PythonTemplatePath { get; set; }
/// <summary>
/// Default Python script engine
/// </summary>
public string DefaultPythonEngine { get; set; }
public HostAnalyticsInfo HostAnalyticsInfo { get; set; }
/// <summary>
/// CLIMode indicates if we are running in DynamoCLI or DynamoWPFCLI mode.
/// </summary>
public bool CLIMode { get; set; }
public string CLILocale { get; set; }
/// <summary>
/// Gets or sets the logger instance used for logging messages and events.
/// This property should be set to a valid <see cref="DynamoLogger"/> instance
/// to enable logging during the initialization and runtime of Dynamo.
/// </summary>
public DynamoLogger Logger { get; set; }
}
/// <summary>
/// Start DynamoModel with all default configuration options
/// </summary>
/// <returns>The instance of <see cref="DynamoModel"/></returns>
public static DynamoModel Start()
{
return Start(new DefaultStartConfiguration() { ProcessMode = TaskProcessMode.Asynchronous, Preferences = PreferenceSettings.Instance });
}
/// <summary>
/// Start DynamoModel with custom configuration. Defaults will be assigned not provided.
/// </summary>
/// <param name="configuration">Start configuration</param>
/// <returns>The instance of <see cref="DynamoModel"/></returns>
public static DynamoModel Start(IStartConfiguration configuration)
{
// where necessary, assign defaults
if (string.IsNullOrEmpty(configuration.Context))
configuration.Context = Configuration.Context.NONE;
return new DynamoModel(configuration);
}
// Token representing the Built-InPackages directory
internal static readonly string BuiltInPackagesToken = @"%BuiltInPackages%";
[Obsolete("Only used for migration to the new for this directory - BuiltInPackages - do not use for other purposes")]
// Token representing the standard library directory
internal static readonly string StandardLibraryToken = @"%StandardLibrary%";
/// <summary>
/// Default constructor for DynamoModel
/// </summary>
/// <param name="config">Start configuration</param>
protected DynamoModel(IStartConfiguration config)
{
DynamoModel.IsCrashing = false;
if (config is DefaultStartConfiguration defaultStartConfig)
{
// This is not exposed in IStartConfiguration to avoid a breaking change.
// TODO: This fact should probably be revisited in 3.0.
DefaultPythonEngine = defaultStartConfig.DefaultPythonEngine;
CLIMode = defaultStartConfig.CLIMode;
IsServiceMode = defaultStartConfig.IsServiceMode;
CLILocale = defaultStartConfig.CLILocale;
}
if (config is IStartConfigCrashReporter cerConfig)
{
CERLocation = cerConfig.CRStartConfig.CERLocation;
}
//if provided, override logger.
if (config is IStartConfigurationLogger loggerConfig && loggerConfig.Logger != null)
{
Logger = loggerConfig.Logger;
}
ClipBoard = new ObservableCollection<ModelBase>();
pathManager = CreatePathManager(config);
// Ensure we have all directories in place.
List<Exception> exceptions = [];
pathManager.EnsureDirectoryExistence(exceptions);
Context = config.Context;
IsTestMode = config.StartInTestMode;
IsHeadless = config.IsHeadless;
NoNetworkMode = config.NoNetworkMode;
HostAnalyticsInfo = config.HostAnalyticsInfo;
DebugSettings = new DebugSettings();
if (Logger == null)
{
// If logger is not provided, create a new one.
Logger = new DynamoLogger(DebugSettings, pathManager.LogDirectory, IsTestMode, CLIMode, IsServiceMode);
}
if (!IsServiceMode)
{
// Log all exceptions as part of directories check.
foreach (var exception in exceptions)
{
Logger.Log(exception);
}
}
MigrationManager = new MigrationManager(DisplayFutureFileMessage, DisplayObsoleteFileMessage);
MigrationManager.MessageLogged += LogMessage;
MigrationManager.MigrationTargets.Add(typeof(WorkspaceMigrations));
var thread = config.SchedulerThread ?? new DynamoSchedulerThread();
Scheduler = new DynamoScheduler(thread, config.ProcessMode);
Scheduler.TaskStateChanged += OnAsyncTaskStateChanged;
geometryFactoryPath = config.GeometryFactoryPath;
OnRequestUpdateLoadBarStatus(new SplashScreenLoadEventArgs(Resources.SplashScreenInitPreferencesSettings, 30));
PreferenceSettings = (PreferenceSettings)CreateOrLoadPreferences(config.Preferences);
PreferenceSettings.Instance = PreferenceSettings;
if (PreferenceSettings != null)
{
SetUICulture(CLILocale ?? PreferenceSettings.Locale);
PreferenceSettings.PropertyChanged += PreferenceSettings_PropertyChanged;
PreferenceSettings.MessageLogged += LogMessage;
}
HostName = HostAnalyticsInfo.HostName;
HostVersion = HostAnalyticsInfo.HostVersion?.ToString();
bool areAnalyticsDisabledFromConfig = false;
if (!IsServiceMode)
{ // Skip getting the value for areAnalyticsDisabledFromConfig because analytics is disabled for searvice mode anyway
try
{
// Dynamo, behind a proxy server, has been known to have issues loading the Analytics binaries.
// Using the "DisableAnalytics" configuration setting, a user can skip loading analytics binaries altogether.
var assemblyConfig = ConfigurationManager.OpenExeConfiguration(GetType().Assembly.Location);
if (assemblyConfig != null)
{
var disableAnalyticsValue = assemblyConfig.AppSettings.Settings["DisableAnalytics"];
if (disableAnalyticsValue != null)
bool.TryParse(disableAnalyticsValue.Value, out areAnalyticsDisabledFromConfig);
}
}
catch (Exception)
{
// Do nothing for now
}
}
//If network traffic is disabled, analytics should also be disabled - this is already done in
//our other entry points(CLI,Sandbox etc) - but
//not all integrators will use those entry points, some may just create a DynamoModel directly.
Analytics.DisableAnalytics = NoNetworkMode || Analytics.DisableAnalytics || IsServiceMode;
// If user skipped analytics from assembly config, do not try to launch the analytics client
// or the feature flags client for web traffic reason.
if (!IsServiceMode && !areAnalyticsDisabledFromConfig && !Analytics.DisableAnalytics && !NoNetworkMode)
{
HandleAnalytics();
//run process startup/reading on another thread so we don't block dynamo startup.
//if we end up needing to control aspects of dynamo model or view startup that we can't make
//event based/async then just run this on main thread - ie get rid of the Task.Run()
var mainThreadSyncContext = SynchronizationContext.Current ?? new SynchronizationContext();
Task.Run(() =>
{
try
{
//this will kill the CLI process after cacheing the flags in Dynamo process.
using (FeatureFlags =
new DynamoFeatureFlagsManager(
AnalyticsService.GetUserIDForSession(),
mainThreadSyncContext,
IsTestMode))
{
FeatureFlags.MessageLogged += LogMessageWrapper;
//this will block task thread as it waits for data from feature flags process.
FeatureFlags.CacheAllFlags();
}
}
catch (Exception e) { Logger.LogError($"could not start feature flags manager {e}"); };
});
DynamoFeatureFlagsManager.FlagsRetrieved += HandleFeatureFlags;
}
// TBD: Do we need settings migrator for service mode? If we config the docker correctly, this could be skipped I think
if (!IsServiceMode && !IsTestMode && PreferenceSettings.IsFirstRun)
{
DynamoMigratorBase migrator = null;
try
{
migrator = DynamoMigratorBase.MigrateBetweenDynamoVersions(pathManager);
}
catch (Exception e)
{
Logger.Log(e.Message);
}
if (migrator != null)
{
var isFirstRun = PreferenceSettings.IsFirstRun;
PreferenceSettings = migrator.PreferenceSettings;
PreferenceSettings.Instance = PreferenceSettings;
// Preserve the preference settings for IsFirstRun as this needs to be set
// only by UsageReportingManager
PreferenceSettings.IsFirstRun = isFirstRun;
}
}
if (!IsServiceMode && PreferenceSettings.IsFirstRun && !IsTestMode)
{
PreferenceSettings.AddDefaultTrustedLocations();
}
InitializePreferences();
// At this point, pathManager.PackageDirectories only has 1 element which is the directory
// in AppData. If list of PackageFolders is empty, add the folder in AppData to the list since there
// is no additional location specified. Otherwise, update pathManager.PackageDirectories to include
// PackageFolders
if (PreferenceSettings.CustomPackageFolders.Count == 0)
PreferenceSettings.CustomPackageFolders = [BuiltInPackagesToken, pathManager.UserDataDirectory];
if (!PreferenceSettings.CustomPackageFolders.Contains(BuiltInPackagesToken))
{
PreferenceSettings.CustomPackageFolders.Insert(0, BuiltInPackagesToken);
}
// Make sure that the default package folder is added in the list if custom packages folder.
var userDataFolder = pathManager.GetUserDataFolder(); // Get the default user data path
AddPackagePath(userDataFolder);
// Load Python Template
// The loading pattern is conducted in the following order
// 1) Set from DynamoSettings.XML
// 2) Set from API via the configuration file
// 3) Set from PythonTemplate.py located in 'C:\Users\USERNAME\AppData\Roaming\Dynamo\Dynamo Core\2.X'
// 4) Set from OOTB hard-coded default template
// If a custom python template path doesn't already exists in the DynamoSettings.xml
if (string.IsNullOrEmpty(PreferenceSettings.PythonTemplateFilePath) ||
!File.Exists(PreferenceSettings.PythonTemplateFilePath) && !IsServiceMode)
{
// To supply a custom python template host integrators should supply a 'DefaultStartConfiguration' config file
// or create a new struct that inherits from 'DefaultStartConfiguration' making sure to set the 'PythonTemplatePath'
// while passing the config to the 'DynamoModel' constructor.
if (config is DefaultStartConfiguration)
{
var configurationSettings = (DefaultStartConfiguration)config;
var templatePath = configurationSettings.PythonTemplatePath;
// If a custom python template path was set in the config apply that template
if (!string.IsNullOrEmpty(templatePath) && File.Exists(templatePath))
{
PreferenceSettings.PythonTemplateFilePath = templatePath;
Logger.Log($"{Resources.PythonTemplateDefinedByHost} : {PreferenceSettings.PythonTemplateFilePath}");
}
// Otherwise fallback to the default
else
{
SetDefaultPythonTemplate();
}
}
else
{
// Fallback to the default
SetDefaultPythonTemplate();
}
}
else
{
// A custom python template path already exists in the DynamoSettings.xml
Logger.Log($"{Resources.PythonTemplateUserFile} : {PreferenceSettings.PythonTemplateFilePath}");
}
pathManager.Preferences = PreferenceSettings;
PreferenceSettings.RequestUserDataFolder += pathManager.GetUserDataFolder;
if (!IsServiceMode)
{
SearchModel = new NodeSearchModel(Logger);
SearchModel.ItemProduced += SearchModel_ItemProduced;
}
NodeFactory = new NodeFactory();
NodeFactory.MessageLogged += LogMessage;
//Initialize the ExtensionManager with the CommonDataDirectory so that extensions found here are checked first for dll's with signed certificates
extensionManager = new ExtensionManager();
extensionManager.MessageLogged += LogMessage;
var extensions = config.Extensions ?? LoadExtensions();
//don't load linter manager in service mode.
if (!IsServiceMode)
{
LinterManager = new LinterManager(this.ExtensionManager);
}
// when dynamo is ready, alert the loaded extensions
DynamoReady += (readyParams) =>
{
this.dynamoReady = true;
DynamoReadyExtensionHandler(readyParams, ExtensionManager.Extensions);
};
// when an extension is added if dynamo is ready, alert that extension (this alerts late
// loaded extensions)
ExtensionManager.ExtensionAdded += (extension) =>
{
if (this.dynamoReady)
{
DynamoReadyExtensionHandler(new ReadyParams(this),
[extension]);
};
};
Loader = new NodeModelAssemblyLoader();
Loader.MessageLogged += LogMessage;
// Create a core which is used for parsing code and loading libraries
var libraryCore = new ProtoCore.Core(new Options())
{
ParsingMode = ParseMode.AllowNonAssignment
};
libraryCore.Compilers.Add(Language.Associative, new Compiler(libraryCore));
libraryCore.Compilers.Add(Language.Imperative, new ProtoImperative.Compiler(libraryCore));
LibraryServices = new LibraryServices(libraryCore, pathManager, PreferenceSettings);
LibraryServices.MessageLogged += LogMessage;
LibraryServices.LibraryLoaded += LibraryLoaded;
CustomNodeManager = new CustomNodeManager(NodeFactory, MigrationManager, LibraryServices, !IsServiceMode);
LuceneSearch.LuceneUtilityNodeSearch = new LuceneSearchUtility(this, LuceneSearchUtility.DefaultNodeIndexStartConfig);
InitializeCustomNodeManager();
ResetEngineInternal();
EngineController.VMLibrariesReset += ReloadDummyNodes;
AddHomeWorkspace();
AuthenticationManager = new AuthenticationManager(config.AuthProvider);
Logger.Log($"Dynamo -- Build {Assembly.GetExecutingAssembly().GetName().Version}");
DynamoModel.OnRequestUpdateLoadBarStatus(new SplashScreenLoadEventArgs(Resources.SplashScreenLoadNodeLibrary, 50));
InitializeNodeLibrary();
if (extensions.Any())
{
Logger.Log("\nLoading Dynamo extensions:");
var startupParams = new StartupParams(this);
foreach (var ext in extensions)
{
try
{
SetupExtensions(ext);
ext.Startup(startupParams);
// if we are starting extension (A) which is a source of other extensions (like packageManager)
// then we can start the extension(s) (B) that it requested be loaded.
if (ext is IExtensionSource)
{
foreach (var loadedExtension in (ext as IExtensionSource).RequestedExtensions)
{
if (loadedExtension is IExtension)
{
SetupExtensions(loadedExtension);
(loadedExtension as IExtension).Startup(startupParams);
}
}
}
}
catch (Exception ex)
{
Logger.Log(ex.Message);
}
ExtensionManager.Add(ext);
}
}