forked from DynamoDS/Dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkspaceModel.cs
More file actions
2750 lines (2401 loc) · 102 KB
/
Copy pathWorkspaceModel.cs
File metadata and controls
2750 lines (2401 loc) · 102 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.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Xml;
using Dynamo.Core;
using Dynamo.Engine;
using Dynamo.Engine.CodeGeneration;
using Dynamo.Events;
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.Presets;
using Dynamo.Linting;
using Dynamo.Logging;
using Dynamo.Models;
using Dynamo.Properties;
using Dynamo.PythonServices;
using Dynamo.Scheduler;
using Dynamo.Selection;
using Dynamo.Utilities;
using DynamoUtilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ProtoCore.Namespace;
namespace Dynamo.Graph.Workspaces
{
/// <summary>
/// Non view-specific container for additional view information required to
/// fully construct a WorkspaceModel from JSON
/// </summary>
public class ExtraWorkspaceViewInfo
{
public object Camera;
public IEnumerable<ExtraNodeViewInfo> NodeViews;
public IEnumerable<ExtraNoteViewInfo> Notes;
public IEnumerable<ExtraAnnotationViewInfo> Annotations;
public IEnumerable<ExtraConnectorPinInfo> ConnectorPins;
public double X;
public double Y;
public double Zoom;
/// <summary>
/// Load the extra view information required to fully construct a WorkspaceModel object
/// </summary>
/// <param name="json"></param>
static internal ExtraWorkspaceViewInfo ExtraWorkspaceViewInfoFromJson(string json)
{
JsonReader reader = new JsonTextReader(new StringReader(json));
var obj = JObject.Load(reader);
var viewBlock = obj["View"];
if (viewBlock == null)
return null;
var settings = new JsonSerializerSettings
{
Error = (sender, args) =>
{
args.ErrorContext.Handled = true;
Console.WriteLine(args.ErrorContext.Error);
},
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.None,
Formatting = Newtonsoft.Json.Formatting.Indented,
Culture = CultureInfo.InvariantCulture
};
return JsonConvert.DeserializeObject<ExtraWorkspaceViewInfo>(viewBlock.ToString(), settings);
}
}
/// <summary>
/// Non view-specific container for additional node view information
/// required to fully construct a WorkspaceModel from JSON
/// </summary>
public class ExtraNodeViewInfo
{
public string Id;
public string Name;
public double X;
public double Y;
public bool ShowGeometry;
public bool Excluded;
public bool IsSetAsInput;
public bool IsSetAsOutput;
public string UserDescription;
}
/// <summary>
/// Non view-specific container for additional note view information
/// required to fully construct a WorkspaceModel from JSON
/// </summary>
public class ExtraNoteViewInfo
{
public string Id;
public double X;
public double Y;
public string Text;
// TODO, QNTM-1099: Figure out if this is necessary
// public int ZIndex;
}
/// <summary>
/// Container for connector pin view information
/// required to fully construct a WorkspaceViewModel from JSON
/// </summary>
public class ExtraConnectorPinInfo
{
public string ConnectorGuid;
public double Left;
public double Top;
}
/// <summary>
/// Non view-specific container for additional annotation view information
/// required to fully construct a WorkspaceModel from JSON
/// </summary>
public class ExtraAnnotationViewInfo
{
public string Title;
public string DescriptionText;
[DefaultValue(true)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public bool IsExpanded;
public IEnumerable<string> Nodes;
public bool HasNestedGroups;
public double FontSize;
public Guid GroupStyleId;
public string Background;
public string Id;
public string PinnedNode;
public double WidthAdjustment;
public double HeightAdjustment;
public double WidthAdjustmentCollapsed;
public double HeightAdjustmentCollapsed;
public double WidthAdjustmentExpanded;
public double HeightAdjustmentExpanded;
public bool IsResizedWhileCollapsed;
// TODO, Determine if these are required
public double Left;
public double Top;
public double Width;
public double Height;
public double InitialTop;
public double InitialHeight;
public double TextBlockHeight;
private bool tolerantDoubleCompare(double a, double b)
{
return Math.Abs(a - b) < .0001;
}
public override bool Equals(object obj)
{
var other = obj as ExtraAnnotationViewInfo;
return other != null &&
this.Id == other.Id &&
this.Title == other.Title &&
this.DescriptionText == other.DescriptionText &&
this.Nodes.SequenceEqual(other.Nodes) &&
this.HasNestedGroups == other.HasNestedGroups &&
this.FontSize == other.FontSize &&
this.GroupStyleId == other.GroupStyleId &&
this.Background == other.Background &&
this.WidthAdjustment == other.WidthAdjustment &&
this.HeightAdjustment == other.HeightAdjustment;
//TODO try to get rid of these if possible
//needs investigation if we are okay letting them get
//calculated at runtime. currently checking them will fail as we do
//not deserialize them.
//tolerantDoubleCompare(this.Left, other.Left) &&
//tolerantDoubleCompare(this.Top, other.Top) &&
//tolerantDoubleCompare(this.InitialTop, other.InitialTop);
//this.Width == other.Width &&
//this.Height == other.Height &&
//this.TextBlockHeight == other.TextBlockHeight;
}
}
/// <summary>
/// Represents base class for all kind of workspaces which contains general data
/// such as Name, collections of nodes, notes, annotations, etc.
/// </summary>
public abstract partial class WorkspaceModel : NotificationObject, ILocatable, IUndoRedoRecorderClient, ILogSource, IDisposable, IWorkspaceModel
{
#region nested classes
/// <summary>
/// This class enables the delay of graph execution.
/// Use instances of this class to specify a code scope in which you want graph execution to be delayed.
/// Class is thread safe, although behavior is not well defined.
/// Nested instance of this class do not have a well defined behavior.
/// </summary>
internal class DelayedGraphExecution : IDisposable
{
private readonly WorkspaceModel workspace;
public DelayedGraphExecution(WorkspaceModel wModel)
{
workspace = wModel;
Interlocked.Increment(ref workspace.delayGraphExecutionCounter);
}
public virtual void Dispose()
{
Interlocked.Decrement(ref workspace.delayGraphExecutionCounter);
workspace.RequestRun();
}
}
#endregion
#region private/internal members
/// <summary>
/// The offset of the elements in the current paste operation
/// </summary>
private int currentPasteOffset = 0;
internal int CurrentPasteOffset
{
get
{
return currentPasteOffset + PasteOffsetStep;
}
}
/// <summary>
/// This is true only if the workspace contains legacy SOAP formatted binding data.
/// </summary>
internal bool ContainsLegacyTraceData { get; set; }
/// <summary>
/// Denotes if the current workspace was created from a template.
/// </summary>
internal bool IsTemplate { get; set; }
internal bool ScaleFactorChanged = false;
/// <summary>
/// The step to offset elements between subsequent paste operations
/// </summary>
internal static readonly int PasteOffsetStep = 10;
/// <summary>
/// The maximum paste offset before reset
/// </summary>
internal static readonly int PasteOffsetMax = 60;
internal readonly LinterManager linterManager;
private string fileName;
private string fromJsonGraphId;
private string name;
private double height = 100;
private double width = 100;
private double x;
private double y;
private double zoom = 1.0;
private DateTime lastSaved;
private string author = "None provided";
private string description;
private bool hasUnsavedChanges;
private bool isReadOnly;
private readonly List<NodeModel> nodes;
private readonly List<NoteModel> notes;
private readonly List<AnnotationModel> annotations;
internal readonly List<PresetModel> presets;
private readonly UndoRedoRecorder undoRecorder;
private static List<ModelBase> savedModels = null;
private double scaleFactor = 1.0;
private bool hasNodeInSyncWithDefinition;
protected Guid guid;
private HashSet<Guid> dependencies = new HashSet<Guid>();
private int delayGraphExecutionCounter = 0;
// For workspace references view extension.
private bool forceComputeWorkspaceReferences;
private List<INodeLibraryDependencyInfo> nodeLibraryDependencies;
private List<INodeLibraryDependencyInfo> nodeLocalDefinitions;
private List<INodeLibraryDependencyInfo> externalFileReferences;
private Dictionary<Guid, PackageInfo> nodePackageDictionary = new Dictionary<Guid, PackageInfo>();
private Dictionary<Guid, DependencyInfo> localDefinitionsDictionary = new Dictionary<Guid, DependencyInfo>();
private Dictionary<Guid, DependencyInfo> externalFilesDictionary = new Dictionary<Guid, DependencyInfo>();
private readonly string customNodeExtension = ".dyf";
/// <summary>
/// Whether or not to delay graph execution.
/// 64-bit read operations are already atomic so no need to lock here
/// </summary>
internal protected bool DelayGraphExecution => delayGraphExecutionCounter > 0;
/// <summary>
/// This is set to true after a workspace is added.
/// This is set to false, if the workspace is cleared or disposed.
/// </summary>
private bool workspaceLoaded;
/// <summary>
/// This event is raised after the workspace tries to resolve existing dummyNodes - for example after a new package or library is loaded.
/// </summary>
public static event Action DummyNodesReloaded;
/// <summary>
/// This method invokes the DummyNodesReloaded event on the workspace model.
/// </summary>
public void OnDummyNodesReloaded()
{
DummyNodesReloaded?.Invoke();
}
internal static string ComputeGraphIdFromJson(string fileContents)
{
return Hash.ToBase32String(Hash.GetHashFromString(fileContents));
}
/// <summary>
/// sets the name property of the model based on filename,backup state and model type.
/// </summary>
/// <param name="filePath">Full filepath to file to save.</param>
/// <param name="isBackup">Indicates if this save represents a backup save.</param>
internal void setNameBasedOnFileName(string filePath, bool isBackup)
{
string fileName = string.Empty;
try
{
fileName = Path.GetFileName(filePath);
string extension = Path.GetExtension(filePath);
if (extension == ".dyn" || extension == ".dyf")
{
fileName = Path.GetFileNameWithoutExtension(filePath);
}
}
catch (ArgumentException)
{
}
// Don't change name property if backup save or this is a customnode
if (fileName != string.Empty && isBackup == false && this is HomeWorkspaceModel)
{
this.Name = fileName;
}
}
#endregion
#region events
/// <summary>
/// Function that can be used to respond on a saved workspace.
/// </summary>
/// <param name="model">The <see cref="WorkspaceModel"/> object which has been saved.</param>
public delegate void WorkspaceSavedEvent(WorkspaceModel model);
/// <summary>
/// Event that is fired when a workspace requests that a Node or Note model is
/// centered.
/// </summary>
public event NodeEventHandler RequestNodeCentered;
/// <summary>
/// Requests that a Node or Note model should be centered.
/// </summary>
/// <param name="sender">The workspace object where the event handler is attached.</param>
/// <param name="e">The event data containing sufficient information about node.</param>
internal virtual void OnRequestNodeCentered(object sender, ModelEventArgs e)
{
if (RequestNodeCentered != null)
RequestNodeCentered(this, e);
}
/// <summary>
/// Function that can be used to respond to a "point event"
/// </summary>
/// <param name="sender">The object where the event handler is attached.</param>
/// <param name="e">The event data.</param>
public delegate void PointEventHandler(object sender, EventArgs e);
/// <summary>
/// Event that is fired every time the position offset of a workspace changes.
/// </summary>
public event PointEventHandler CurrentOffsetChanged;
/// <summary>
/// Used during open and workspace changes to set the location of the workspace
/// </summary>
/// <param name="sender">The object which triggers the event</param>
/// <param name="e">The offset event data.</param>
internal virtual void OnCurrentOffsetChanged(object sender, PointEventArgs e)
{
if (CurrentOffsetChanged != null)
{
Debug.WriteLine("Setting current offset to {0}", e.Point);
CurrentOffsetChanged(this, e);
}
}
/// <summary>
/// Event that is fired when the workspace is saved.
/// </summary>
public event Action Saved;
internal virtual void OnSaved()
{
LastSaved = DateTime.Now;
HasUnsavedChanges = false;
if (Saved != null)
Saved();
}
/// <summary>
/// Event that is fired when the workspace is starting the save process.
/// </summary>
public event Action<SaveContext> WorkspaceSaving;
internal virtual void OnSaving(SaveContext saveContext)
{
WorkspaceSaving?.Invoke(saveContext);
}
/// <summary>
/// Event that is fired when a node is added to the workspace.
/// </summary>
public event Action<NodeModel> NodeAdded;
protected virtual void OnNodeAdded(NodeModel node)
{
var handler = NodeAdded;
if (handler != null) handler(node);
}
/// <summary>
/// Event that is fired when a node is removed from the workspace.
/// </summary>
public event Action<NodeModel> NodeRemoved;
protected virtual void OnNodeRemoved(NodeModel node)
{
var handler = NodeRemoved;
if (handler != null) handler(node);
}
/// <summary>
/// Event that is fired when nodes are cleared from the workspace.
/// </summary>
public event Action NodesCleared;
protected virtual void OnNodesCleared()
{
var handler = NodesCleared;
if (handler != null) handler();
}
/// <summary>
/// Event that is fired when a note is added to the workspace.
/// </summary>
public event Action<NoteModel> NoteAdded;
protected virtual void OnNoteAdded(NoteModel note)
{
var handler = NoteAdded;
if (handler != null) handler(note);
}
/// <summary>
/// Event that is fired when a note is removed from the workspace.
/// </summary>
public event Action<NoteModel> NoteRemoved;
protected virtual void OnNoteRemoved(NoteModel note)
{
var handler = NoteRemoved;
if (handler != null) handler(note);
}
/// <summary>
/// Event that is fired when notes are cleared from the workspace.
/// </summary>
public event Action NotesCleared;
protected virtual void OnNotesCleared()
{
var handler = NotesCleared;
if (handler != null) handler();
}
/// <summary>
/// Event that is fired when an annotation is added to the workspace.
/// </summary>
public event Action<AnnotationModel> AnnotationAdded;
protected virtual void OnAnnotationAdded(AnnotationModel annotation)
{
var handler = AnnotationAdded;
if (handler != null) handler(annotation);
}
/// <summary>
/// Event that is fired when an annotation is removed from the workspace.
/// </summary>
public event Action<AnnotationModel> AnnotationRemoved;
protected virtual void OnAnnotationRemoved(AnnotationModel annotation)
{
var handler = AnnotationRemoved;
if (handler != null) handler(annotation);
}
/// <summary>
/// Event that is fired when annotations are cleared from the workspace.
/// </summary>
public event Action AnnotationsCleared;
protected virtual void OnAnnotationsCleared()
{
var handler = AnnotationsCleared;
if (handler != null) handler();
}
/// <summary>
/// Event that is fired when a connector is added to the workspace.
/// </summary>
public event Action<ConnectorModel> ConnectorAdded;
protected virtual void OnConnectorAdded(ConnectorModel obj)
{
RegisterConnector(obj);
var handler = ConnectorAdded;
if (handler != null) handler(obj);
//Check if the workspace is loaded, i.e all the nodes are
//added to the workspace. In that case, compute the Upstream cache for the
//given node.
if (workspaceLoaded)
{
obj.End.Owner.ComputeUpstreamOnDownstreamNodes();
}
}
private void RegisterConnector(ConnectorModel connector)
{
connector.Deleted += () => OnConnectorDeleted(connector);
}
/// <summary>
/// Event that is fired when a connector is deleted from a workspace.
/// </summary>
public event Action<ConnectorModel> ConnectorDeleted;
protected virtual void OnConnectorDeleted(ConnectorModel obj)
{
var handler = ConnectorDeleted;
if (handler != null) handler(obj);
//Check if the workspace is loaded, i.e all the nodes are
//added to the workspace. In that case, compute the Upstream cache for the
//given node.
if (workspaceLoaded)
{
obj.End.Owner.ComputeUpstreamOnDownstreamNodes();
}
}
/// <summary>
/// Implement recording node modification for undo/redo.
/// </summary>
/// <param name="models">Collection of <see cref="ModelBase"/> objects to record.</param>
public void RecordModelsForModification(IEnumerable<ModelBase> models)
{
RecordModelsForModification(models.ToList(), undoRecorder);
}
/// <summary>
/// Event that is fired when this workspace is disposed of.
/// </summary>
public event Action Disposed;
/// <summary>
/// Event that is fired during the saving of the workspace.
///
/// Add additional XmlNode objects to the XmlDocument provided,
/// in order to save data to the file.
/// </summary>
public event Action<XmlDocument> Saving;
protected virtual void OnSaving(XmlDocument obj)
{
var handler = Saving;
if (handler != null) handler(obj);
}
/// <summary>
/// Event that is fired when the workspace is collecting custom node package dependencies.
/// This event should only be subscribed to by the package manager.
/// </summary>
internal event Func<Guid, PackageInfo> CollectingCustomNodePackageDependencies;
/// <summary>
/// Event that is fired when the workspace is collecting node package dependencies.
/// This event should only be subscribed to by the package manager.
/// </summary>
internal event Func<AssemblyName, PackageInfo> CollectingNodePackageDependencies;
/// <summary>
/// This handler handles the workspaceModel's request to populate a JSON with view data.
/// This is used to construct a full workspace for instrumentation.
/// </summary>
internal delegate string PopulateJSONWorkspaceHandler(JObject modelData);
internal event PopulateJSONWorkspaceHandler PopulateJSONWorkspace;
protected virtual void OnPopulateJSONWorkspace(JObject modelData)
{
var handler = PopulateJSONWorkspace;
if (handler != null) handler(modelData);
}
private void OnSyncWithDefinitionStart(NodeModel nodeModel)
{
hasNodeInSyncWithDefinition = true;
}
private void OnSyncWithDefinitionEnd(NodeModel nodeModel)
{
hasNodeInSyncWithDefinition = false;
}
#endregion
#region public properties
/// <summary>
/// A NodeFactory used by this workspace to create Nodes.
/// </summary>
//TODO(Steve): This should only live on DynamoModel, not here. It's currently used to instantiate NodeModels during UndoRedo. -- MAGN-5713
public readonly NodeFactory NodeFactory;
/// <summary>
/// A set of input parameter states, this can be used to set the graph to a serialized state.
/// </summary>
public IEnumerable<PresetModel> Presets { get { return presets; } }
/// <summary>
/// The date of the last save.
/// </summary>
public DateTime LastSaved
{
get { return lastSaved; }
set
{
lastSaved = value;
RaisePropertyChanged("LastSaved");
}
}
/// <summary>
/// gathers the direct customNode workspace dependencies of this workspace.
/// </summary>
/// <returns> a list of workspace IDs in GUID form</returns>
public HashSet<Guid> Dependencies
{
get
{
dependencies.Clear();
//if the workspace is a main workspace then find all functions and their dependencies
if (this is HomeWorkspaceModel)
{
foreach (var node in this.Nodes.OfType<Function>())
{
dependencies.Add(node.FunctionSignature);
}
}
//else the workspace is a customnode - and we can add the dependencies directly
else
{
var customNodeDirectDependencies = new HashSet<Guid>((this as CustomNodeWorkspaceModel).
CustomNodeDefinition.DirectDependencies.Select(x => x.FunctionId));
dependencies = customNodeDirectDependencies;
}
return dependencies;
}
}
/// <summary>
/// Event requesting subscribers to return Python engine mapping for the current workspace nodes.
/// </summary>
internal event Func<Dictionary<Guid, String>> RequestPythonEngineMapping;
/// <summary>
/// Raised when the workspace needs to request for Python engine mapping
/// that can be returned from other subscribers such as view extensions.
/// E.g. The PythonMigrationViewExtension computes additional package dependencies required for Python nodes.
/// </summary>
/// <returns></returns>
internal Dictionary<Guid, String> OnRequestPythonEngineMapping()
{
return RequestPythonEngineMapping?.Invoke();
}
/// <summary>
/// NodeLibraries that the nodes in this graph depend on
/// </summary>
internal List<INodeLibraryDependencyInfo> NodeLibraryDependencies
{
get
{
if (HasUnsavedChanges || ForceComputeWorkspaceReferences)
{
nodeLibraryDependencies = ComputeNodeLibraryDependencies();
return nodeLibraryDependencies;
}
else
{
return nodeLibraryDependencies;
}
}
set
{
foreach (var dependency in value)
{
//handle package dependencies
if (dependency.ReferenceType == ReferenceType.Package
&& dependency is PackageDependencyInfo)
{
foreach (var node in dependency.Nodes)
{
nodePackageDictionary[node] = (dependency as PackageDependencyInfo).PackageInfo;
}
}
}
RaisePropertyChanged(nameof(NodeLibraryDependencies));
}
}
/// <summary>
/// Local Node Definitions that the nodes in this graph depend on
/// </summary>
internal List<INodeLibraryDependencyInfo> NodeLocalDefinitions
{
get
{
if (HasUnsavedChanges || ForceComputeWorkspaceReferences)
{
nodeLocalDefinitions = ComputeNodeLocalDefinitions();
return nodeLocalDefinitions;
}
else
{
return nodeLocalDefinitions;
}
}
set
{
foreach (var dependency in value)
{
if (dependency.ReferenceType == ReferenceType.DYFFile || dependency.ReferenceType == ReferenceType.ZeroTouch)
{
foreach (var node in dependency.Nodes)
{
localDefinitionsDictionary[node] = dependency as DependencyInfo;
}
}
}
RaisePropertyChanged(nameof(NodeLocalDefinitions));
}
}
/// <summary>
/// External File references that the nodes in this graph depend on
/// </summary>
internal List<INodeLibraryDependencyInfo> ExternalFiles
{
get
{
if (HasUnsavedChanges || ForceComputeWorkspaceReferences)
{
externalFileReferences = ComputeExternalFileReferences();
return externalFileReferences;
}
else
{
return externalFileReferences;
}
}
set
{
foreach (var dependency in value)
{
if (dependency.ReferenceType == ReferenceType.External)
{
foreach (var node in dependency.Nodes)
{
externalFilesDictionary[node] = dependency as DependencyInfo;
}
}
}
RaisePropertyChanged(nameof(ExternalFiles));
}
}
/// <summary>
/// Computes the node library dependencies in the current workspace.
/// </summary>
/// <returns></returns>
private List<INodeLibraryDependencyInfo> ComputeNodeLibraryDependencies()
{
var packageDependencies = new Dictionary<PackageInfo, PackageDependencyInfo>();
bool computePythonNodeMapping = true;
var pythonNodeMapping = new Dictionary<Guid, String>();
foreach (var node in Nodes)
{
var collected = GetNodePackage(node);
// Handle python nodes explicitly and use the collected node package for those node types.
if (node.ToString().Equals(PythonEngineManager.PythonNodeNamespace))
{
// Compute the node - python engine mapping for all python workspace nodes at once, when a python node is detected.
if (computePythonNodeMapping)
{
pythonNodeMapping = OnRequestPythonEngineMapping();
computePythonNodeMapping = false;
}
var pythonEnginePackage = (pythonNodeMapping != null && pythonNodeMapping.ContainsKey(node.GUID)) ? pythonNodeMapping[node.GUID] : string.Empty;
// For inbuilt python engine,package dependency is not set.
if (pythonEnginePackage.Equals("InBuilt"))
{
continue;
}
else if (collected != null)
{
if (!packageDependencies.ContainsKey(collected))
{
packageDependencies[collected] = new PackageDependencyInfo(collected);
}
packageDependencies[collected].AddDependent(node.GUID);
packageDependencies[collected].State = PackageDependencyState.Loaded;
nodePackageDictionary[node.GUID] = collected;
continue;
}
}
if (nodePackageDictionary.ContainsKey(node.GUID))
{
var saved = nodePackageDictionary[node.GUID];
if (!packageDependencies.ContainsKey(saved))
{
packageDependencies[saved] = new PackageDependencyInfo(saved);
}
packageDependencies[saved].AddDependent(node.GUID);
// if the package is not installed.
if (collected == null)
{
packageDependencies[saved].State = PackageDependencyState.Missing;
}
// If the state is Missing for at least one of the nodes,
// we set the state of the whole package dependency to Missing.
// Set other states accordingly, only if the PackageDependencyState(for that package)
// is not set to Missing by any of the other nodes.
else if (packageDependencies[saved].State != PackageDependencyState.Missing)
{
if (saved.Name == collected.Name)
{
// if the correct version of package is installed.
if (saved.Version == collected.Version)
{
packageDependencies[saved].State = PackageDependencyState.Loaded;
}
// If incorrect version of package is installed and not marked for uninstall,
// set the state. Otherwise, keep the RequiresRestart state away from overwritten.
else if (packageDependencies[saved].State != PackageDependencyState.RequiresRestart)
{
packageDependencies[saved].State = PackageDependencyState.IncorrectVersion;
}
}
// if the package is not installed, but the nodes are resolved by a different package.
else
{
packageDependencies[saved].State = PackageDependencyState.Warning;
}
}
}
else
{
if (collected != null)
{
if (!packageDependencies.ContainsKey(collected))
{
packageDependencies[collected] = new PackageDependencyInfo(collected);
}
packageDependencies[collected].AddDependent(node.GUID);
packageDependencies[collected].State = PackageDependencyState.Loaded;
}
}
}
return packageDependencies.Values.ToList<INodeLibraryDependencyInfo>();
}
/// <summary>
/// Computes the node local definitions in the current workspace.
/// </summary>
/// <returns></returns>
private List<INodeLibraryDependencyInfo> ComputeNodeLocalDefinitions()
{
var nodeLocalDefinitions = new Dictionary<object, DependencyInfo>();
foreach (var node in Nodes)
{
var collected = GetNodePackage(node);
if (!nodePackageDictionary.ContainsKey(node.GUID) && collected == null)
{
string localDefinitionName;
if (node.IsCustomFunction)
{
localDefinitionName = node.Name + customNodeExtension;
if (!nodeLocalDefinitions.ContainsKey(localDefinitionName))
{
nodeLocalDefinitions[localDefinitionName] = new DependencyInfo(localDefinitionName);
}
nodeLocalDefinitions[localDefinitionName].AddDependent(node.GUID);
nodeLocalDefinitions[localDefinitionName].ReferenceType = ReferenceType.DYFFile;
}
else if (node is DSFunctionBase functionNode)
{
string assemblyPath = functionNode.Controller.Definition.Assembly;
var directoryName = Path.GetDirectoryName(assemblyPath);
// For the local definition reference, the assembly directory exists on disc.
if (!string.IsNullOrEmpty(directoryName) && Directory.Exists(directoryName))
{
localDefinitionName = Path.GetFileName(assemblyPath);
if (!nodeLocalDefinitions.ContainsKey(localDefinitionName))
{
nodeLocalDefinitions[localDefinitionName] = new DependencyInfo(localDefinitionName, assemblyPath);
}
nodeLocalDefinitions[localDefinitionName].AddDependent(node.GUID);
nodeLocalDefinitions[localDefinitionName].ReferenceType = ReferenceType.ZeroTouch;
}
}
else if (node is DummyNode)
{
// Read the serialized value if the node is not resolved.
if (localDefinitionsDictionary.TryGetValue(node.GUID, out var localDefinitionInfo))
{
nodeLocalDefinitions[localDefinitionInfo.Name] = localDefinitionInfo;
}
}
}
}
return nodeLocalDefinitions.Values.ToList<INodeLibraryDependencyInfo>();
}
/// <summary>
/// Computes the external file references if the Workspace Model is a HomeWorkspaceModel and graph is not running.
/// </summary>
/// <returns></returns>
private List<INodeLibraryDependencyInfo> ComputeExternalFileReferences()
{
var externalFiles = new Dictionary<object, DependencyInfo>();
// If an execution is in progress we'll have to wait for it to be done before we can gather the
// external file references as this implementation relies on the output values of each node.
//instead just bail to avoid blocking the UI.
if (this is HomeWorkspaceModel homeWorkspaceModel && homeWorkspaceModel.RunSettings.RunEnabled && !RunSettings.ForceBlockRun)
{
foreach (var node in nodes)
{
externalFilesDictionary.TryGetValue(node.GUID, out var serializedDependencyInfo);
// Check for the file path string value at each of the output ports of all nodes in the workspace.
foreach (var port in node.OutPorts)
{
var id = node.GetAstIdentifierForOutputIndex(port.Index)?.Name;
var mirror = homeWorkspaceModel.EngineController.GetMirror(id);
var data = mirror?.GetData().Data;
if (data is string dataString && dataString.Contains(@"\"))
{
// Check if the value exists on disk
PathHelper.FileInfoAtPath(dataString, out bool fileExists, out string fileSize);
if (fileExists)
{
var externalFilePath = Path.GetFullPath(dataString);
var externalFileName = Path.GetFileName(dataString);
if (!externalFiles.ContainsKey(externalFilePath))
{
externalFiles[externalFilePath] = new DependencyInfo(externalFileName, dataString, ReferenceType.External);