forked from DynamoDS/Dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomNodeManager.cs
More file actions
1506 lines (1316 loc) · 59.8 KB
/
CustomNodeManager.cs
File metadata and controls
1506 lines (1316 loc) · 59.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Dynamo.Engine;
using Dynamo.Engine.NodeToCode;
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.Nodes.NodeLoaders;
using Dynamo.Graph.Nodes.ZeroTouch;
using Dynamo.Graph.Notes;
using Dynamo.Graph.Presets;
using Dynamo.Graph.Workspaces;
using Dynamo.Library;
using Dynamo.Logging;
using Dynamo.Migration;
using Dynamo.Models;
using Dynamo.Properties;
using Dynamo.Selection;
using Dynamo.Utilities;
using ProtoCore.AST.AssociativeAST;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Xml;
using Symbol = Dynamo.Graph.Nodes.CustomNodes.Symbol;
namespace Dynamo.Core
{
/// <summary>
/// Manages instantiation of custom nodes. All custom nodes known to Dynamo should be stored
/// with this type. This object implements late initialization of custom nodes by providing a
/// single interface to initialize custom nodes.
/// </summary>
public class CustomNodeManager : LogSourceBase, ICustomNodeSource, ICustomNodeManager, IDisposable
{
/// <summary>
/// This function creates CustomNodeManager
/// </summary>
/// <param name="nodeFactory">NodeFactory</param>
/// <param name="migrationManager">MigrationManager</param>
/// <param name="libraryServices">LibraryServices</param>
public CustomNodeManager(NodeFactory nodeFactory, MigrationManager migrationManager, LibraryServices libraryServices)
{
this.nodeFactory = nodeFactory;
this.migrationManager = migrationManager;
this.libraryServices = libraryServices;
//Todo decide were we want to store this
customNodeInfoCache = new JsonCache<CustomNodeInfo> ("C:\\Temp\\CustomNodeInforCache.temp");
}
#region Fields and properties
private LibraryServices libraryServices;
private JsonCache<CustomNodeInfo> customNodeInfoCache;
private readonly OrderedSet<Guid> loadOrder = new OrderedSet<Guid>();
private readonly Dictionary<Guid, CustomNodeDefinition> loadedCustomNodes =
new Dictionary<Guid, CustomNodeDefinition>();
private readonly Dictionary<Guid, CustomNodeWorkspaceModel> loadedWorkspaceModels =
new Dictionary<Guid, CustomNodeWorkspaceModel>();
private readonly NodeFactory nodeFactory;
private readonly MigrationManager migrationManager;
/// <summary>
/// CustomNodeDefinitions for all loaded custom nodes, in load order.
/// </summary>
public IEnumerable<CustomNodeDefinition> LoadedDefinitions
{
get { return loadOrder.Select(id => loadedCustomNodes[id]); }
}
/// <summary>
/// Registry of all NodeInfos corresponding to discovered custom nodes. These
/// custom nodes are not all necessarily initialized.
/// </summary>
public readonly Dictionary<Guid, CustomNodeInfo> NodeInfos = new Dictionary<Guid, CustomNodeInfo>();
/// <summary>
/// All loaded custom node workspaces.
/// </summary>
public IEnumerable<CustomNodeWorkspaceModel> LoadedWorkspaces
{
get { return loadedWorkspaceModels.Values; }
}
/// <summary>
/// Returns custom node workspace by a specified custom node ID
/// </summary>
/// <param name="customNodeId">Custom node ID of a requested workspace</param>
/// <returns>Custom node workspace by a specified ID</returns>
public CustomNodeWorkspaceModel GetWorkspaceById(Guid customNodeId)
{
return loadedWorkspaceModels.ContainsKey(customNodeId) ? loadedWorkspaceModels[customNodeId] : null;
}
#endregion
#region Events
/// <summary>
/// An event that is fired when a definition is updated
/// </summary>
public event Action<CustomNodeDefinition> DefinitionUpdated;
protected virtual void OnDefinitionUpdated(CustomNodeDefinition obj)
{
var handler = DefinitionUpdated;
if (handler != null) handler(obj);
}
/// <summary>
/// An event that is fired when new or updated info is available for
/// a custom node.
/// </summary>
public event Action<CustomNodeInfo> InfoUpdated;
protected virtual void OnInfoUpdated(CustomNodeInfo obj)
{
var handler = InfoUpdated;
if (handler != null) handler(obj);
}
/// <summary>
/// An event that is fired when a custom node is removed from Dynamo.
/// </summary>
public event Action<Guid> CustomNodeRemoved;
protected virtual void OnCustomNodeRemoved(Guid functionId)
{
var handler = CustomNodeRemoved;
if (handler != null) handler(functionId);
}
internal event Func<Guid, PackageInfo> RequestCustomNodeOwner;
private PackageInfo OnRequestCustomNodeOwner(Guid FunctionId)
{
return RequestCustomNodeOwner?.Invoke(FunctionId);
}
#endregion
/// <summary>
/// Creates a new Custom Node Instance.
/// </summary>
/// <param name="id">Identifier referring to a custom node definition.</param>
/// <param name="name">
/// Name for the custom node to be instantiated, used for error recovery if
/// the given id could not be found.
/// </param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <returns>Custom Node Instance</returns>
public Function CreateCustomNodeInstance(
Guid id,
string name = null,
bool isTestMode = false)
{
CustomNodeDefinition def = null;
CustomNodeInfo info = null;
TryGetCustomNodeData(id, name, isTestMode, out def, out info);
return CreateCustomNodeInstance(id, name, isTestMode, def, info);
}
/// <summary>
/// Attempts to get custom node info and definition data.
/// </summary>
/// <param name="id">Identifier referring to a custom node definition.</param>
/// <param name="name">
/// Name for the custom node to be instantiated, used for error recovery if
/// the given id could not be found.
/// </param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="def">
/// Custom node definition data
/// </param>
/// <param name="info">
/// Custom node information data
/// </param>
public bool TryGetCustomNodeData(
Guid id,
string name,
bool isTestMode,
out CustomNodeDefinition def,
out CustomNodeInfo info)
{
def = null;
info = null;
// Try to get the definition, initializing the custom node if necessary
if (TryGetFunctionDefinition(id, isTestMode, out def))
{
// Got the definition, proceed as planned.
info = NodeInfos[id];
return true;
}
// Couldn't get the workspace with the given ID, try a name lookup instead.
if (name != null && !TryGetNodeInfo(name, out info))
return false;
// Try to get the definition using the function ID, initializing the custom node if necessary
if (info != null && TryGetFunctionDefinition(info.FunctionId, isTestMode, out def))
return true;
return false;
}
/// <summary>
/// Creates a new Custom Node Instance.
/// </summary>
/// <param name="id">Identifier referring to a custom node definition.</param>
/// <param name="name">
/// Name for the custom node to be instantiated, used for error recovery if
/// the given id could not be found.
/// </param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="def">
/// Custom node definition data
/// </param>
/// <param name="info">
/// Custom node information data
/// </param>
/// <returns>Custom Node Instance</returns>
public Function CreateCustomNodeInstance(
Guid id,
string name,
bool isTestMode,
CustomNodeDefinition def,
CustomNodeInfo info)
{
if (info == null)
{
// Couldn't find the workspace at all, prepare for a late initialization.
Log(Properties.Resources.UnableToCreateCustomNodeID + id + "\"",
WarningLevel.Moderate);
info = new CustomNodeInfo(id, name ?? "", "", "", "");
}
if (def == null)
def = CustomNodeDefinition.MakeProxy(id, info.Name);
var node = new Function(def, info.Name, info.Description, info.Category);
CustomNodeWorkspaceModel workspace = null;
if (loadedWorkspaceModels.TryGetValue(id, out workspace))
RegisterCustomNodeInstanceForUpdates(node, workspace);
else
RegisterCustomNodeInstanceForLateInitialization(node, id, name, isTestMode);
return node;
}
private void RegisterCustomNodeInstanceForLateInitialization(
Function node,
Guid id,
string name,
bool isTestMode)
{
var disposed = false;
Action<CustomNodeInfo> infoUpdatedHandler = null;
infoUpdatedHandler = newInfo =>
{
if (newInfo.FunctionId == id || newInfo.Name == name)
{
CustomNodeWorkspaceModel foundWorkspace;
if (TryGetFunctionWorkspace(newInfo.FunctionId, isTestMode, out foundWorkspace))
{
node.ResyncWithDefinition(foundWorkspace.CustomNodeDefinition);
RegisterCustomNodeInstanceForUpdates(node, foundWorkspace);
InfoUpdated -= infoUpdatedHandler;
disposed = true;
}
}
};
InfoUpdated += infoUpdatedHandler;
node.Disposed += (args) =>
{
if (!disposed)
InfoUpdated -= infoUpdatedHandler;
};
}
private static void RegisterCustomNodeInstanceForUpdates(Function node, CustomNodeWorkspaceModel workspace)
{
Action defUpdatedHandler = () =>
{
node.ResyncWithDefinition(workspace.CustomNodeDefinition);
};
workspace.DefinitionUpdated += defUpdatedHandler;
Action infoChangedHandler = () =>
{
var info = workspace.CustomNodeInfo;
node.Name = info.Name;
node.Description = info.Description;
node.Category = info.Category;
};
workspace.InfoChanged += infoChangedHandler;
node.Disposed += (args) =>
{
workspace.DefinitionUpdated -= defUpdatedHandler;
workspace.InfoChanged -= infoChangedHandler;
};
}
/// <summary>
/// Returns a function id from a guid assuming that the file is already loaded.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public Guid GuidFromPath(string path)
{
var pair = NodeInfos.FirstOrDefault(x => x.Value.Path == path);
return pair.Key;
}
private void SetFunctionDefinition(CustomNodeDefinition def)
{
var id = def.FunctionId;
loadedCustomNodes[id] = def;
loadOrder.Add(id);
}
private void SetPreloadFunctionDefinition(Guid id)
{
loadedCustomNodes[id] = null;
}
/// <summary>
/// Import a dyf file for eventual initialization.
/// </summary>
/// <param name="file">Path to a custom node file on disk.</param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="info">
/// If the info was successfully processed, this parameter will be set to
/// it. Otherwise, it will be set to null.
/// </param>
/// <returns>True on success, false if the file could not be read properly.</returns>
public bool AddUninitializedCustomNode(string file, bool isTestMode, out CustomNodeInfo info)
{
if (TryGetInfoFromPath(file, isTestMode, out info))
{
SetNodeInfo(info);
return true;
}
return false;
}
/// <summary>
/// Attempts to remove all traces of a particular custom node from Dynamo, assuming the node is not in a loaded workspace.
/// </summary>
/// <param name="guid">Custom node identifier.</param>
public void Remove(Guid guid)
{
Uninitialize(guid);
NodeInfos.Remove(guid);
OnCustomNodeRemoved(guid);
}
/// <summary>
/// Uninitialized a custom node. The information for the node is still retained, but the next time
/// the node is queried for it's workspace / definition / an instace it will be re-initialized from
/// disk.
/// </summary>
/// <param name="guid">Custom node identifier.</param>
internal bool Uninitialize(Guid guid)
{
CustomNodeWorkspaceModel ws;
if (loadedWorkspaceModels.TryGetValue(guid, out ws))
{
ws.Dispose();
loadedWorkspaceModels.Remove(guid);
loadedCustomNodes.Remove(guid);
loadOrder.Remove(guid);
return true;
}
return false;
}
/// <summary>
/// Scans the given path for custom node files, retaining their information in the manager for later
/// potential initialization.
/// </summary>
/// <param name="path">Path on disk to scan for custom nodes.</param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="isPackageMember">
/// Indicates whether custom node comes from package or not.
/// </param>
/// <returns></returns>
public IEnumerable<CustomNodeInfo> AddUninitializedCustomNodesInPath(string path, bool isTestMode, bool isPackageMember = false)
{
var result = new List<CustomNodeInfo>();
foreach (var info in ScanNodeHeadersInDirectory(path, isTestMode))
{
info.IsPackageMember = isPackageMember;
SetNodeInfo(info);
result.Add(info);
}
return result;
}
/// <summary>
/// Scans the given path for custom node files, retaining their information in the manager for later
/// potential initialization. Should be used when packages load or reload customNodes.
/// </summary>
/// <param name="path">Path on disk to scan for custom nodes.</param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="packageInfo">
/// Info about the package that requested this customNode to be loaded or to which the customNode belongs.
/// Is PackageMember property will be true if this property is not null.
/// </param>
/// <returns></returns>
public IEnumerable<CustomNodeInfo> AddUninitializedCustomNodesInPath(string path, bool isTestMode, PackageInfo packageInfo)
{
var result = new List<CustomNodeInfo>();
foreach (var info in ScanNodeHeadersInDirectory(path, isTestMode))
{
info.IsPackageMember = true;
info.PackageInfo = packageInfo;
SetNodeInfo(info);
result.Add(info);
}
return result;
}
/// <summary>
/// Enumerates all of the files in the search path and get's their guids.
/// Does not instantiate the nodes.
/// </summary>
/// <returns>False if SearchPath is not a valid directory, otherwise true</returns>
private IEnumerable<CustomNodeInfo> ScanNodeHeadersInDirectory(string dir, bool isTestMode)
{
if (!Directory.Exists(dir))
{
Log(string.Format(Resources.InvalidCustomNodeFolderWarning, dir));
yield break;
}
// Will throw exception if we don't have write access
IEnumerable<string> dyfs;
try
{
dyfs = Directory.EnumerateFiles(dir, "*.dyf");
}
catch (Exception e)
{
Log(string.Format(Resources.CustomNodeFolderLoadFailure, dir));
Log(e);
yield break;
}
foreach (var file in dyfs)
{
CustomNodeInfo info;
if (TryGetInfoFromPath(file, isTestMode, out info))
yield return info;
}
}
/// <summary>
/// Stores the path and function definition without initializing a node.
/// Overwrites the existing NodeInfo if necessary!
/// </summary>
private void SetNodeInfo(CustomNodeInfo newInfo)
{
var guids = NodeInfos.Where(x =>
{
return !string.IsNullOrEmpty(x.Value.Path) &&
string.Compare(x.Value.Path, newInfo.Path, StringComparison.OrdinalIgnoreCase) == 0;
}).Select(x => x.Key).ToList();
foreach (var guid in guids)
{
NodeInfos.Remove(guid);
}
// we need to check with the packageManager that this node if this node is in a package or not -
// currently the package data is lost when the customNode workspace is loaded.
// we'll only do this check for customNode infos which don't have a package currently to verify if this
// is correct.
if(newInfo.IsPackageMember == false)
{
var owningPackage = this.OnRequestCustomNodeOwner(newInfo.FunctionId);
//we found a real package.
if(owningPackage != null)
{
newInfo.IsPackageMember = true;
newInfo.PackageInfo = owningPackage;
}
}
CustomNodeInfo info;
// if the custom node is part of a package make sure it does not overwrite another node
if (newInfo.IsPackageMember && NodeInfos.TryGetValue(newInfo.FunctionId, out info))
{
var newInfoPath = String.IsNullOrEmpty(newInfo.Path) ? string.Empty : Path.GetDirectoryName(newInfo.Path);
var infoPath = String.IsNullOrEmpty(info.Path) ? string.Empty : Path.GetDirectoryName(info.Path);
var message = string.Format(Resources.MessageCustomNodePackageFailedToLoad,
infoPath, newInfoPath);
//only try to compare package info if both customNodeInfos have package info.
if(info.IsPackageMember && info.PackageInfo != null)
{
// if these are different packages raise an error.
// TODO (for now we don't raise an error for different
//versions of the same package, don't want to effect publish new version workflows.
if (newInfo.PackageInfo.Name != info.PackageInfo.Name)
{
var ex = new CustomNodePackageLoadException(newInfoPath, infoPath, message);
Log(ex.Message, WarningLevel.Moderate);
// Log to notification view extension
Log(ex);
throw ex;
}
}
else //(newInfo has owning Package, oldInfo does not)
{
// This represents the case where a previous info was not from a package, but the current info
// has an owning package.
var looseCustomNodeToPackageMessage = String.Format(Properties.Resources.FunctionDefinitionOverwrittenMessage, newInfo.Name, newInfo.PackageInfo, info.Name);
var ex = new CustomNodePackageLoadException(newInfoPath, infoPath, looseCustomNodeToPackageMessage);
Log(ex.Message, WarningLevel.Mild);
Log(ex);
}
}
NodeInfos[newInfo.FunctionId] = newInfo;
OnInfoUpdated(newInfo);
}
/// <summary>
/// Returns the function workspace from a guid
/// </summary>
/// <param name="id">The unique id for the node.</param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="ws"></param>
/// <returns>The path to the node or null if it wasn't found.</returns>
public bool TryGetFunctionWorkspace(
Guid id,
bool isTestMode,
out CustomNodeWorkspaceModel ws)
{
if (Contains(id))
{
if (!loadedWorkspaceModels.TryGetValue(id, out ws))
{
if (InitializeCustomNode(id, isTestMode, out ws))
return true;
}
else
return true;
}
ws = null;
return false;
}
/// <summary>
/// Returns the function workspace.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="isTestMode">if set to <c>true</c> [is test mode].</param>
/// <param name="ws">The workspace.</param>
/// <returns>Boolean indicating if Custom Node Workspace defination is loaded.</returns>
public bool TryGetFunctionWorkspace(
Guid id,
bool isTestMode,
out ICustomNodeWorkspaceModel ws)
{
CustomNodeWorkspaceModel workSpace;
var result = TryGetFunctionWorkspace(id, isTestMode, out workSpace);
ws = workSpace;
return result;
}
/// <summary>
/// Returns the function definition from a guid.
/// </summary>
/// <param name="id">Custom node identifier.</param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="definition"></param>
/// <returns>Boolean indicating if Custom Node Workspace defination is loaded.</returns>
public bool TryGetFunctionDefinition(
Guid id,
bool isTestMode,
out CustomNodeDefinition definition)
{
if (Contains(id))
{
CustomNodeWorkspaceModel ws;
if (IsInitialized(id) || InitializeCustomNode(id, isTestMode, out ws))
{
definition = loadedCustomNodes[id];
return true;
}
}
definition = null;
return false;
}
/// <summary>
/// Returns true if the custom node's unique identifier is inside of the manager (initialized or not)
/// </summary>
/// <param name="guid">The FunctionId</param>
public bool Contains(Guid guid)
{
return IsInitialized(guid) || NodeInfos.ContainsKey(guid);
}
/// <summary>
/// Returns true if the custom node's name is inside the manager (initialized or not)
/// </summary>
/// <param name="name">The name of the custom node.</param>
public bool Contains(string name)
{
CustomNodeInfo info;
return TryGetNodeInfo(name, out info);
}
/// <summary>
/// Indicates whether the custom node is initialized in the manager
/// </summary>
/// <param name="name">The name of the node</param>
/// <returns>The name of the </returns>
internal bool IsInitialized(string name)
{
CustomNodeInfo info;
return TryGetNodeInfo(name, out info) && IsInitialized(info.FunctionId);
}
/// <summary>
/// Indicates whether the custom node is initialized in the manager
/// </summary>
/// <param name="guid">Whether the definition is stored with the manager.</param>
internal bool IsInitialized(Guid guid)
{
return loadedCustomNodes.ContainsKey(guid);
}
/// <summary>
/// Returns a boolean indicating if successfully get a CustomNodeInfo object from a workspace path
/// </summary>
/// <param name="path">The path from which to get the guid</param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="info"></param>
/// <returns>The custom node info object - null if we failed</returns>
internal bool TryGetInfoFromPath(string path, bool isTestMode, out CustomNodeInfo info)
{
WorkspaceInfo header = null;
XmlDocument xmlDoc;
string jsonDoc;
Exception ex;
try
{
var fileinfo = new FileInfo(path);
var lastWriteTime = fileinfo.LastWriteTimeUtc;
var length = fileinfo.Length;
//create a fast check for checking if the file has been loaded before. Could also do a file hash but we don't care too much about false negatives
var key = path + lastWriteTime.ToString() + length.ToString();
if (customNodeInfoCache.TryGet(key, out info))
{
return true;
}
if (DynamoUtilities.PathHelper.isValidJson(path, out jsonDoc, out ex))
{
if (!WorkspaceInfo.FromJsonDocument(jsonDoc, path, isTestMode, false, AsLogger(), out header))
{
Log(String.Format(Properties.Resources.FailedToLoadHeader, path));
info = null;
return false;
}
}
else if (DynamoUtilities.PathHelper.isValidXML(path, out xmlDoc, out ex))
{
if (!WorkspaceInfo.FromXmlDocument(xmlDoc, path, isTestMode, false, AsLogger(), out header))
{
Log(String.Format(Properties.Resources.FailedToLoadHeader, path));
info = null;
return false;
}
}
else throw ex;
info = new CustomNodeInfo(
Guid.Parse(header.ID),
header.Name,
header.Category,
header.Description,
path,
header.IsVisibleInDynamoLibrary);
customNodeInfoCache.Set(key, info);
return true;
}
catch (Exception e)
{
Log(String.Format(Properties.Resources.FailedToLoadHeader, path));
Log(e.ToString());
info = null;
return false;
}
}
/// <summary>
/// Opens a Custom Node workspace from an XmlDocument, given a pre-constructed WorkspaceInfo.
/// </summary>
/// <param name="workspaceInfo">Workspace header describing the custom node file.</param>
/// <param name="xmlDoc">Xml content of workspace</param>
/// <param name="isTestMode">
/// Flag specifying whether or not this should operate in "test mode".
/// </param>
/// <param name="workspace"></param>
/// <returns>Boolean indicating if Custom Node Workspace opened.</returns>
public bool OpenCustomNodeWorkspace(
XmlDocument xmlDoc,
WorkspaceInfo workspaceInfo,
bool isTestMode,
out WorkspaceModel workspace)
{
CustomNodeWorkspaceModel customNodeWorkspace;
if (InitializeCustomNode(
workspaceInfo,
xmlDoc,
out customNodeWorkspace))
{
workspace = customNodeWorkspace;
return true;
}
workspace = null;
return false;
}
private bool InitializeCustomNode(
WorkspaceInfo workspaceInfo,
XmlDocument xmlDoc,
out CustomNodeWorkspaceModel workspace)
{
// Add custom node definition firstly so that a recursive
// custom node won't recursively load itself.
SetPreloadFunctionDefinition(Guid.Parse(workspaceInfo.ID));
string jsonDoc;
CustomNodeWorkspaceModel newWorkspace = null;
if (xmlDoc is XmlDocument)
{
var nodeGraph = NodeGraph.LoadGraphFromXml(xmlDoc, nodeFactory);
newWorkspace = new CustomNodeWorkspaceModel(
nodeFactory,
nodeGraph.Nodes,
nodeGraph.Notes,
nodeGraph.Annotations,
nodeGraph.Presets,
nodeGraph.ElementResolver,
workspaceInfo);
}
else
{
Exception ex;
if (DynamoUtilities.PathHelper.isValidJson(workspaceInfo.FileName, out jsonDoc, out ex))
{
//we pass null for engine and scheduler as apparently the custom node constructor doesn't need them.
newWorkspace = (CustomNodeWorkspaceModel)WorkspaceModel.FromJson(jsonDoc, this.libraryServices, null, null, nodeFactory, false, true, this);
newWorkspace.FileName = workspaceInfo.FileName;
newWorkspace.Category = workspaceInfo.Category;
// Mark the custom node workspace as having no changes - when we set the category on the above line
// this marks the workspace as changed.
newWorkspace.HasUnsavedChanges = false;
}
}
RegisterCustomNodeWorkspace(newWorkspace);
workspace = newWorkspace;
return true;
}
private void RegisterCustomNodeWorkspace(CustomNodeWorkspaceModel newWorkspace)
{
RegisterCustomNodeWorkspace(
newWorkspace,
newWorkspace.CustomNodeInfo,
newWorkspace.CustomNodeDefinition);
}
private void RegisterCustomNodeWorkspace(
CustomNodeWorkspaceModel newWorkspace, CustomNodeInfo info, CustomNodeDefinition definition)
{
loadedWorkspaceModels[newWorkspace.CustomNodeId] = newWorkspace;
SetFunctionDefinition(definition);
OnDefinitionUpdated(definition);
newWorkspace.DefinitionUpdated += () =>
{
var newDef = newWorkspace.CustomNodeDefinition;
SetFunctionDefinition(newDef);
OnDefinitionUpdated(newDef);
};
SetNodeInfo(info);
newWorkspace.InfoChanged += () =>
{
var newInfo = newWorkspace.CustomNodeInfo;
SetNodeInfo(newInfo);
OnInfoUpdated(newInfo);
};
newWorkspace.FunctionIdChanged += oldGuid =>
{
loadedWorkspaceModels.Remove(oldGuid);
loadedCustomNodes.Remove(oldGuid);
loadOrder.Remove(oldGuid);
loadedWorkspaceModels[newWorkspace.CustomNodeId] = newWorkspace;
};
}
/// <summary>
/// Deserialize a function definition from a given path. A side effect of this function is that
/// the node is added to the dictionary of loadedNodes.
/// </summary>
/// <param name="functionId">The function guid we're currently loading</param>
/// <param name="isTestMode"></param>
/// <param name="workspace">The resultant function definition</param>
/// <returns>Boolean indicating if Custom Node initialized.</returns>
private bool InitializeCustomNode(
Guid functionId,
bool isTestMode,
out CustomNodeWorkspaceModel workspace)
{
try
{
var customNodeInfo = NodeInfos[functionId];
var path = customNodeInfo.Path;
Log(String.Format(Properties.Resources.LoadingNodeDefinition, customNodeInfo, path));
WorkspaceInfo info;
XmlDocument xmlDoc;
string strInput;
Exception ex;
if (DynamoUtilities.PathHelper.isValidJson(path, out strInput, out ex))
{
WorkspaceInfo.FromJsonDocument(strInput, path, isTestMode, false, AsLogger(), out info);
info.ID = functionId.ToString();
return InitializeCustomNode(info, null, out workspace);
}
else if (DynamoUtilities.PathHelper.isValidXML(path, out xmlDoc, out ex))
{
if (WorkspaceInfo.FromXmlDocument(xmlDoc, path, isTestMode, false, AsLogger(), out info))
{
info.ID = functionId.ToString();
if (migrationManager.ProcessWorkspace(info, xmlDoc, isTestMode, nodeFactory))
{
return InitializeCustomNode(info, xmlDoc, out workspace);
}
}
}
else throw ex;
Log(string.Format(Properties.Resources.CustomNodeCouldNotBeInitialized, customNodeInfo.Name));
workspace = null;
return false;
}
catch (Exception ex)
{
Log(Properties.Resources.OpenWorkspaceError);
Log(ex);
if (isTestMode)
throw; // Rethrow for NUnit.
workspace = null;
return false;
}
}
/// <summary>
/// Creates a new Custom Node in the manager.
/// </summary>
/// <param name="name">Name of the custom node.</param>
/// <param name="category">Category for the custom node.</param>
/// <param name="description">Description of the custom node.</param>
/// <param name="functionId">
/// Optional identifier to be used for the custom node. By default, will make a new unique one.
/// </param>
/// <returns>Newly created Custom Node Workspace.</returns>
internal WorkspaceModel CreateCustomNode(string name, string category, string description, Guid? functionId = null)
{
var newId = functionId ?? Guid.NewGuid();
var info = new WorkspaceInfo()
{
Name = name,
Category = category,
Description = description,
X = 0,
Y = 0,
ID = newId.ToString(),
FileName = string.Empty,
IsVisibleInDynamoLibrary = true
};
var workspace = new CustomNodeWorkspaceModel(info, nodeFactory);
RegisterCustomNodeWorkspace(workspace);
return workspace;
}
internal static string RemoveChars(string s, IEnumerable<string> chars)
{
return chars.Aggregate(s, (current, c) => current.Replace(c, ""));
}
/// <summary>
/// Attempts to retrieve information for the given custom node identifier.
/// </summary>
/// <param name="id">Custom node identifier.</param>
/// <param name="info"></param>
/// <returns>Success or failure.</returns>
internal bool TryGetNodeInfo(Guid id, out CustomNodeInfo info)
{
return NodeInfos.TryGetValue(id, out info);
}
/// <summary>
/// Attempts to retrieve information for the given custom node name. If there are multiple
/// custom nodes matching the given name, this method will return any one of them.
/// </summary>
/// <param name="name">Name of a custom node.</param>
/// <param name="info"></param>
/// <returns></returns>
internal bool TryGetNodeInfo(string name, out CustomNodeInfo info)
{
info = NodeInfos.Values.FirstOrDefault(x => x.Name == name);
return info != null;
}
/// <summary>
/// Collapse a set of nodes in a given workspace.
/// </summary>
/// <param name="selectedNodes"> The function definition for the user-defined node </param>
/// <param name="selectedNotes"> The note models in current selection </param>
/// <param name="currentWorkspace"> The workspace where</param>
/// <param name="isTestMode"></param>
/// <param name="args"></param>
internal CustomNodeWorkspaceModel Collapse(
IEnumerable<NodeModel> selectedNodes,
IEnumerable<NoteModel> selectedNotes,
WorkspaceModel currentWorkspace,
bool isTestMode,
FunctionNamePromptEventArgs args)
{
var selectedNodeSet = new HashSet<NodeModel>(selectedNodes);
// Note that undoable actions are only recorded for the "currentWorkspace",
// the nodes which get moved into "newNodeWorkspace" are not recorded for undo,
// even in the new workspace. Their creations will simply be treated as part of
// the opening of that new workspace (i.e. when a user opens a file, she will
// not expect the nodes that show up to be undoable).
//
// After local nodes are moved into "newNodeWorkspace" as the result of
// conversion, if user performs an undo, new set of nodes will be created in
// "currentWorkspace" (not moving those nodes in the "newNodeWorkspace" back
// into "currentWorkspace"). In another word, undo recording is on a per-
// workspace basis, it does not work across different workspaces.