forked from DynamoDS/Dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNodeAutoCompleteBarViewModel.cs
More file actions
1408 lines (1251 loc) · 59 KB
/
Copy pathNodeAutoCompleteBarViewModel.cs
File metadata and controls
1408 lines (1251 loc) · 59 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Dynamo.Configuration;
using Dynamo.Engine;
using Dynamo.Graph.Connectors;
using Dynamo.Graph.Nodes;
using Dynamo.Graph.Nodes.CustomNodes;
using Dynamo.Graph.Nodes.ZeroTouch;
using Dynamo.Logging;
using Dynamo.Models;
using Dynamo.PackageManager;
using Dynamo.Properties;
using Dynamo.Search;
using Dynamo.Search.SearchElements;
using Dynamo.Utilities;
using Dynamo.Wpf.ViewModels;
using Greg;
using Newtonsoft.Json;
using ProtoCore.AST.AssociativeAST;
using ProtoCore.Mirror;
using ProtoCore.Utils;
using RestSharp;
using Dynamo.Wpf.Utilities;
using Dynamo.ViewModels;
using System.Reflection;
using Dynamo.Graph.Workspaces;
using Dynamo.Graph;
using System.Windows.Media;
using System.ComponentModel;
using System.Windows.Data;
namespace Dynamo.NodeAutoComplete.ViewModels
{
/// <summary>
/// Search View Model for Node AutoComplete Search Bar
/// </summary>
public class NodeAutoCompleteBarViewModel : SearchViewModel
{
internal PortViewModel PortViewModel { get; set; }
private string autocompleteMLMessage;
private string autocompleteMLTitle;
private bool displayAutocompleteMLStaticPage;
private bool displayLowConfidence;
private const string nodeAutocompleteMLEndpoint = "MLNodeAutocomplete";
private const string nodeClusterAutocompleteMLEndpoint = "MLNodeClusterAutocomplete";
private const double minClusterConfidenceScore = 0.1;
private static Assembly dynamoCoreWpfAssembly;
private bool _isSingleAutocomplete;
public bool IsInput => PortViewModel.PortType == PortType.Input;
public bool SwitchIsEnabled => ResultsLoaded && !IsInput;
public bool IsSingleAutocomplete
{
get => _isSingleAutocomplete || IsInput;
set
{
if (PortViewModel.PortType == PortType.Output && _isSingleAutocomplete != value)
{
_isSingleAutocomplete = value;
RaisePropertyChanged(nameof(IsSingleAutocomplete));
PopulateAutoComplete();
}
}
}
// Lucene search utility to perform indexing operations just for NodeAutocomplete.
internal LuceneSearchUtility LuceneUtility
{
get
{
return LuceneSearch.LuceneUtilityNodeAutocomplete;
}
}
/// <summary>
/// The Node AutoComplete ML service version, this could be empty if user has not used ML way
/// </summary>
internal string ServiceVersion { get; set; }
/// <summary>
/// Cache of default node suggestions, use it in case where
/// a. our algorithm does not return sufficient results
/// b. the results returned by our algorithm will not be useful for user
/// </summary>
internal IEnumerable<NodeSearchElementViewModel> DefaultResults { get; set; }
/// <summary>
/// For checking if the ML method is selected
/// </summary>
public bool IsDisplayingMLRecommendation
{
get
{
return dynamoViewModel.PreferenceSettings.DefaultNodeAutocompleteSuggestion == Models.NodeAutocompleteSuggestion.MLRecommendation;
}
}
/// <summary>
/// If MLAutocompleteTOU is approved
/// </summary>
public bool IsMLAutocompleteTOUApproved
{
get
{
return dynamoViewModel.PreferenceSettings.IsMLAutocompleteTOUApproved;
}
}
/// <summary>
/// If true, autocomplete method options are hidden from UI
/// </summary>
public bool HideAutocompleteMethodOptions
{
get
{
return dynamoViewModel.PreferenceSettings.HideAutocompleteMethodOptions;
}
}
private IEnumerable<DNADropdownViewModel> dropdownResults;
/// <summary>
/// Cluster autocomplete search results.
/// </summary>
internal IEnumerable<DNADropdownViewModel> DropdownResults
{
get
{
return dropdownResults;
}
set
{
dropdownResults = value;
FilteredView = CollectionViewSource.GetDefaultView(dropdownResults);
if (FilteredView != null)
{
FilteredView.Filter = FilterLogic;
}
RaisePropertyChanged(nameof(NthofTotal));
RaisePropertyChanged(nameof(ResultsLoaded));
RaisePropertyChanged(nameof(SwitchIsEnabled));
RaisePropertyChanged(nameof(ConfirmSource));
RaisePropertyChanged(nameof(PreviousSource));
RaisePropertyChanged(nameof(NextSource));
RaisePropertyChanged(nameof(FilteredView));
}
}
/// <summary>
/// Return the filter associated currently with dropdown results.
/// </summary>
public ICollectionView FilteredView { get; set; }
/// <summary>
/// Return the qualified results from the ML service above preferred confidence threshold
/// </summary>
internal IEnumerable<ClusterResultItem> QualifiedResults
{
get
{
if (FullResults == null)
{
return null;
}
return FullResults.Results.Where(x => double.Parse(x.Probability) * 100 > minClusterConfidenceScore);
}
}
public bool ResultsLoaded => DropdownResults != null;
private bool isOpen;
public bool IsOpen
{
get
{
return isOpen;
}
set
{
if (isOpen == value) return;
isOpen = value;
if (isOpen) SubscribeWindowEvents();
else UnsubscribeWindowEvents();
}
}
private int ClusterResultsCount => DropdownResults == null ? 0 : DropdownResults.Count();
private int selectedIndex = 0;
private string _searchInput = string.Empty;
private bool FilterLogic(object item)
{
var dnaModel = item as DNADropdownViewModel;
if (dnaModel != null)
{
if (dnaModel.Description.IndexOf(SearchInput.Trim(), StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
return false;
}
return true;
}
public string SearchInput
{
get
{
return _searchInput;
}
set
{
if (_searchInput == value)
{
return;
}
_searchInput = value;
if (FilteredView != null)
{
FilteredView.Refresh();
}
}
}
/// <summary>
/// Selected index of the current cluster autocomplete option
/// </summary>
public int SelectedIndex
{
get
{
return selectedIndex;
}
set
{
/*don't try to add a node if the index is out of range or a selection is not made yet (-1)
an index of -1 occurs when using the switch to change between modes.*/
if (selectedIndex != value && value >= 0 && selectedIndex != -1)
{
ReAddNode(value);
}
selectedIndex = value;
RaisePropertyChanged(nameof(SelectedIndex));
RaisePropertyChanged(nameof(NthofTotal));
RaisePropertyChanged(nameof(PreviousSource));
RaisePropertyChanged(nameof(NextSource));
}
}
private void ReAddNode(int index)
{
if(FullResults == null)
{
return;
}
var results = QualifiedResults.ToList();
if(index >= 0 && index < results.Count)
{
AddCluster(results[index]);
}
}
internal void ConsolidateTransientNodes()
{
var node = PortViewModel.NodeViewModel;
var transientNodes = node.WorkspaceViewModel.Nodes.Where(x => x.IsTransient).ToList();
foreach (var transientNode in transientNodes)
{
transientNode.IsTransient = false;
}
//set the last connector to be connected
var transientConnectors = node.WorkspaceViewModel.Connectors.Where(c => c.IsConnecting).ToList();
foreach (var connector in transientConnectors)
{
connector.IsConnecting = false;
}
NodeAutoCompleteUtilities.PostAutoLayoutNodes(node.WorkspaceViewModel.Model, node.NodeModel, transientNodes.Select(x => x.NodeModel), true, true, false, null);
(node.WorkspaceViewModel.Model as HomeWorkspaceModel)?.MarkNodesAsModifiedAndRequestRun(transientNodes.Select(x => x.NodeModel));
ToggleUndoRedoLocked(false);
}
internal void ToggleUndoRedoLocked(bool toggle = true)
{
var node = PortViewModel.NodeViewModel;
//unlock undo/redo
node.WorkspaceViewModel.Model.IsUndoRedoLocked = toggle;
//allow for undo/redo again
node.DynamoViewModel.RaiseCanExecuteUndoRedo();
}
/// <summary>
/// Bitmap Source for left caret
/// </summary>
public string PreviousSource
{
get
{
return selectedIndex == 0 ? "/DynamoCoreWpf;component/UI/Images/caret-left-disabled.png" : "/DynamoCoreWpf;component/UI/Images/caret-left-default.png";
}
}
/// <summary>
/// Bitmap Source for right caret
/// </summary>
public string NextSource
{
get
{
return selectedIndex >= ClusterResultsCount - 1 ? "/DynamoCoreWpf;component/UI/Images/caret-right-disabled.png" : "/DynamoCoreWpf;component/UI/Images/caret-right-default.png";
}
}
/// <summary>
/// Bitmap Source for confirmation checkmark
/// </summary>
public string ConfirmSource
{
get
{
return ResultsLoaded ? "/DynamoCoreWpf;component/UI/Images/check.png" : "/DynamoCoreWpf;component/UI/Images/check-disabled.png";
}
}
/// <summary>
/// Language agnostic way of showing current result ordinal
/// </summary>
public string NthofTotal
{
get
{
return $"{selectedIndex + 1} / {ClusterResultsCount}";
}
}
/// <summary>
/// The No Recommendations or Low Confidence Title
/// </summary>
public string AutocompleteMLTitle
{
get { return autocompleteMLTitle; }
set
{
autocompleteMLTitle = value;
RaisePropertyChanged(nameof(AutocompleteMLTitle));
}
}
/// <summary>
/// The No Recommendations or Low Confidence message
/// </summary>
public string AutocompleteMLMessage
{
get { return autocompleteMLMessage; }
set
{
autocompleteMLMessage = value;
RaisePropertyChanged(nameof(AutocompleteMLMessage));
}
}
/// <summary>
/// Indicates the No recommendations / Low confidence message should be displayed (image and texts)
/// </summary>
public bool DisplayAutocompleteMLStaticPage
{
get { return displayAutocompleteMLStaticPage; }
set
{
displayAutocompleteMLStaticPage = value;
RaisePropertyChanged(nameof(DisplayAutocompleteMLStaticPage));
}
}
/// <summary>
/// Indicates if display the Low confidence option and Tooltip
/// </summary>
public bool DisplayLowConfidence
{
get { return displayLowConfidence; }
set
{
displayLowConfidence = value;
RaisePropertyChanged(nameof(DisplayLowConfidence));
}
}
internal event Action<NodeModel> ParentNodeRemoved;
internal MLNodeClusterAutoCompletionResponse FullResults { private set; get; }
internal List<SingleResultItem> FullSingleResults { set; get; }
private Guid LastRequestGuid;
/// <summary>
/// Constructor
/// </summary>
/// <param name="dynamoViewModel">Dynamo ViewModel</param>
internal NodeAutoCompleteBarViewModel(DynamoViewModel dynamoViewModel) : base(dynamoViewModel)
{
// Off load some time consuming operation here
DefaultResults = dynamoViewModel.DefaultAutocompleteCandidates.Values;
ServiceVersion = string.Empty;
}
/// <summary>
/// Reset Node AutoComplete search view state
/// </summary>
internal void ResetAutoCompleteSearchViewState()
{
DisplayAutocompleteMLStaticPage = false;
DisplayLowConfidence = dynamoViewModel.PreferenceSettings.HideNodesBelowSpecificConfidenceLevel && dynamoViewModel.PreferenceSettings.DefaultNodeAutocompleteSuggestion == NodeAutocompleteSuggestion.MLRecommendation;
AutocompleteMLMessage = string.Empty;
AutocompleteMLTitle = string.Empty;
FilteredResults = new List<NodeSearchElementViewModel>();
FilteredHighConfidenceResults = new List<NodeSearchElementViewModel>();
FilteredLowConfidenceResults = new List<NodeSearchElementViewModel>();
}
internal MLNodeAutoCompletionRequest GenerateRequestForMLAutocomplete()
{
// Initialize request for the the ML API
MLNodeAutoCompletionRequest request = new MLNodeAutoCompletionRequest(AssemblyHelper.GetDynamoVersion().ToString(), dynamoViewModel.PreferenceSettings.MLRecommendationNumberOfResults);
var nodeInfo = PortViewModel.PortModel.Owner;
var portInfo = PortViewModel.PortModel;
// Set node info
request.Node.Id = nodeInfo.GUID.ToString();
request.Node.Lacing = nodeInfo.ArgumentLacing.ToString();
if (nodeInfo is DSFunctionBase functionNode)
{
request.Node.Type.Id = functionNode.CreationName;
}
else if (nodeInfo is NodeModel nodeModel)
{
var typeID = new NodeModelTypeId(nodeModel.GetType().FullName, nodeModel.GetType().Assembly.GetName().Name);
request.Node.Type.Id = typeID.ToString();
}
// Set port info
// If the node is a Variable-input nodemodel or zero-touch node, then parse the port name to remove the digits at the end.
request.Port.Name = (nodeInfo is VariableInputNode || nodeInfo is DSVarArgFunction) ? ParseVariableInputPortName(portInfo.Name) : portInfo.Name;
request.Port.Index = portInfo.Index;
request.Port.Direction = portInfo.PortType == PortType.Input ? PortType.Input.ToString().ToLower() : PortType.Output.ToString().ToLower();
request.Port.KeepListStructure = portInfo.KeepListStructure.ToString();
request.Port.ListAtLevel = portInfo.Level;
// Set host info
var hostName = string.IsNullOrEmpty(DynamoModel.HostAnalyticsInfo.HostName) ? dynamoViewModel.Model.HostName : DynamoModel.HostAnalyticsInfo.HostName;
var hostNameEnum = GetHostNameEnum(hostName);
if (hostNameEnum != HostNames.None)
{
request.Host = new HostItem(hostNameEnum.ToString(), dynamoViewModel.Model.HostVersion);
}
// Set packages info
var packageManager = dynamoViewModel.Model.ExtensionManager.Extensions.OfType<PackageManagerExtension>().FirstOrDefault();
if (packageManager != null)
{
foreach (var pkg in packageManager.PackageLoader.LocalPackages)
{
request.Packages = request.Packages.Append(new PackageItem(pkg.Name, pkg.VersionName));
}
}
// Set context info which will contain all reachable nodes from the current node.
var upstreamNodes = nodeInfo.AllUpstreamNodes(new List<NodeModel>());
var downstreamNodes = nodeInfo.AllDownstreamNodes(new List<NodeModel>());
var upstreamAndDownstreamNodes = new List<NodeModel>();
upstreamAndDownstreamNodes.AddRange(upstreamNodes);
upstreamAndDownstreamNodes.AddRange(downstreamNodes);
foreach (NodeModel nodeModel in upstreamAndDownstreamNodes)
{
var nodeRequest = new NodeItem(nodeModel.GUID.ToString());
if (nodeModel is DSFunctionBase DSfunctionNode)
{
nodeRequest.Type.Id = DSfunctionNode.CreationName;
}
else if (nodeModel is NodeModel node)
{
var typeID = new NodeModelTypeId(node.GetType().FullName, nodeModel.GetType().Assembly.GetName().Name);
nodeRequest.Type.Id = typeID.ToString();
}
request.Context.Nodes = request.Context.Nodes.Append(nodeRequest);
}
// Set info regarding all the connectors in the reachable component.
var connectors = dynamoViewModel.CurrentSpaceViewModel.Model.Connectors;
foreach (ConnectorModel connector in connectors)
{
var startNode = connector.Start.Owner;
var endNode = connector.End.Owner;
if (startNode.Equals(nodeInfo) || endNode.Equals(nodeInfo) || upstreamAndDownstreamNodes.Contains(startNode) || upstreamAndDownstreamNodes.Contains(endNode))
{
var startPortName = (startNode is VariableInputNode || startNode is DSVarArgFunction) ? ParseVariableInputPortName(connector.Start.Name): connector.Start.Name;
var endPortName = (endNode is VariableInputNode || endNode is DSVarArgFunction) ? ParseVariableInputPortName(connector.End.Name) : connector.End.Name;
var connectorRequest = new ConnectionItem
{
StartNode = new ConnectorNodeItem(startNode.GUID.ToString(), startPortName),
EndNode = new ConnectorNodeItem(endNode.GUID.ToString(), endPortName)
};
request.Context.Connections = request.Context.Connections.Append(connectorRequest);
}
}
return request;
}
private IEnumerable<SingleResultItem> GetNodeAutocompleMLResults()
{
MLNodeAutoCompletionResponse MLresults = null;
// Get results from the ML API.
try
{
MLresults = GetGenericAutocompleteResult<MLNodeAutoCompletionResponse>(nodeAutocompleteMLEndpoint);
}
catch (Exception ex)
{
dynamoViewModel.Model.Logger.Log("Unable to fetch ML Node autocomplete results: " + ex.Message);
DisplayAutocompleteMLStaticPage = true;
AutocompleteMLTitle = Resources.LoginNeededTitle;
AutocompleteMLMessage = Resources.LoginNeededMessage;
Analytics.TrackEvent(Actions.View, Categories.NodeAutoCompleteOperations, "UnabletoFetch");
return new List<SingleResultItem>();
}
// no results
if (MLresults == null || MLresults.Results.Count() == 0)
{
DisplayAutocompleteMLStaticPage = true;
AutocompleteMLTitle = Resources.AutocompleteNoRecommendationsTitle;
AutocompleteMLMessage = Resources.AutocompleteNoRecommendationsMessage;
Analytics.TrackEvent(Actions.View, Categories.NodeAutoCompleteOperations, "NoRecommendation");
return new List<SingleResultItem>();
}
ServiceVersion = MLresults.Version;
var results = new List<SingleResultItem>();
var zeroTouchSearchElements = Model.Entries.OfType<ZeroTouchSearchElement>().Where(x => x.IsVisibleInSearch);
var nodeModelSearchElements = Model.Entries.OfType<NodeModelSearchElement>().Where(x => x.IsVisibleInSearch);
// ML Results are categorized based on the threshold confidence score before displaying.
foreach (var result in MLresults.Results)
{
var portName = result.Port != null ? result.Port.Name : string.Empty;
var portIndex = result.Port != null ? result.Port.Index : 0;
// DS Function node
if (result.Node.Type.NodeType.Equals(Function.FunctionNode))
{
NodeSearchElement nodeSearchElement = null;
var element = zeroTouchSearchElements.FirstOrDefault(n => n.Descriptor.MangledName.Equals(result.Node.Type.Id));
if (element != null)
{
nodeSearchElement = (NodeSearchElement)element.Clone();
// Set PortToConnect for each element based on port-index and port-name
nodeSearchElement.AutoCompletionNodeElementInfo = new AutoCompletionNodeElementInfo
{
PortToConnect = portIndex
};
foreach (var inputParameter in element.Descriptor.Parameters.Select((value, index) => (value, index)))
{
if (inputParameter.value.Name.Equals(portName))
{
nodeSearchElement.AutoCompletionNodeElementInfo.PortToConnect = element.Descriptor.Type == FunctionType.InstanceMethod ? inputParameter.index + 1 : inputParameter.index;
break;
}
}
var viewModelElement = new SingleResultItem(nodeSearchElement, result.Score);
results.Add(viewModelElement);
}
}
// Matching known node types of node-model nodes.
else if (Enum.IsDefined(typeof(NodeModelNodeTypes), result.Node.Type.NodeType))
{
// Retreive assembly name and full name from type id.
var typeInfo = GetInfoFromTypeId(result.Node.Type.Id);
string fullName = typeInfo.FullName;
string assemblyName = typeInfo.AssemblyName;
NodeSearchElement nodeSearchElement = null;
var nodesFromAssembly = nodeModelSearchElements.Where(n => Path.GetFileNameWithoutExtension(n.Assembly).Equals(assemblyName));
var element = nodesFromAssembly.FirstOrDefault(n => n.CreationName.Equals(fullName));
if (element != null)
{
nodeSearchElement = (NodeSearchElement)element.Clone();
nodeSearchElement.AutoCompletionNodeElementInfo = new AutoCompletionNodeElementInfo
{
PortToConnect = portIndex
};
var viewModelElement = new SingleResultItem(nodeSearchElement, result.Score);
results.Add(viewModelElement);
}
}
}
return results;
}
private T GetGenericAutocompleteResult<T>(string endpoint)
{
var requestDTO = GenerateRequestForMLAutocomplete();
var jsonRequest = JsonConvert.SerializeObject(requestDTO);
#if DEBUG
dynamoViewModel?.Model?.Logger?.Log(LogMessage.Info($"DNA Request: \n {jsonRequest}"));
#endif
T results = default;
try
{
var authProvider = dynamoViewModel?.Model?.AuthenticationManager?.AuthProvider;
if (!dynamoViewModel.IsIDSDKInitialized())
{
throw new Exception("IDSDK missing or failed initialization.");
}
if (authProvider is IOAuth2AuthProvider oauth2AuthProvider && authProvider is IOAuth2AccessTokenProvider tokenprovider)
{
try
{
if (dynamoCoreWpfAssembly is null)
{
dynamoCoreWpfAssembly = AppDomain.CurrentDomain
.GetAssemblies()
.FirstOrDefault(a => a.GetName().Name.Equals("DynamoCoreWPF", StringComparison.OrdinalIgnoreCase));
}
var uri = DynamoUtilities.PathHelper.GetServiceBackendAddress(dynamoCoreWpfAssembly, endpoint);
var client = new RestClient(uri);
var request = new RestRequest(string.Empty, Method.Post);
var tkn = tokenprovider?.GetAccessToken();
if (string.IsNullOrEmpty(tkn))
{
throw new Exception("Authentication required.");
}
request.AddHeader("Authorization", $"Bearer {tkn}");
request = request.AddJsonBody(jsonRequest);
request.RequestFormat = DataFormat.Json;
RestResponse response = client.Execute(request);
results = JsonConvert.DeserializeObject<T>(response.Content);
}
catch (Exception ex)
{
dynamoViewModel.Model.Logger.Log(ex.Message);
throw new Exception("Authentication failed.");
}
}
}
catch (Exception ex)
{
dynamoViewModel.Model.Logger.Log(ex.Message);
throw new Exception("Authentication failed.");
}
return results;
}
/// <summary>
/// Show the low confidence ML results.
/// </summary>
internal void ShowLowConfidenceResults()
{
DisplayLowConfidence = false;
DisplayAutocompleteMLStaticPage = false;
IEnumerable<NodeSearchElementViewModel> allResults = FilteredHighConfidenceResults.Concat(FilteredLowConfidenceResults);
FilteredResults = allResults;
}
// Full name and assembly name
internal NodeModelTypeId GetInfoFromTypeId(string typeId)
{
if (typeId.Contains(','))
{
var type = typeId.Split(',');
return new NodeModelTypeId(type[0].Trim(), type[1].Trim());
}
return new NodeModelTypeId(typeId);
}
// Remove the digits at the end of the portname for variable input node
private string ParseVariableInputPortName(string portName)
{
string pattern = @"\d+$";
Regex rgx = new Regex(pattern);
return rgx.Replace(portName, string.Empty);
}
// Get the host name from the enum list.
internal HostNames GetHostNameEnum(string HostName)
{
switch (HostName)
{
case string name when name.IndexOf("Revit", StringComparison.OrdinalIgnoreCase) >= 0:
return HostNames.Revit;
case string name when name.IndexOf("Civil", StringComparison.OrdinalIgnoreCase) >= 0:
return HostNames.Civil3d;
case string name when name.IndexOf("Alias", StringComparison.OrdinalIgnoreCase) >= 0:
return HostNames.Alias;
case string name when name.IndexOf("FormIt", StringComparison.OrdinalIgnoreCase) >= 0:
return HostNames.FormIt;
case string name when name.IndexOf("Steel", StringComparison.OrdinalIgnoreCase) >= 0:
return HostNames.AdvanceSteel;
case string name when name.IndexOf("RSA", StringComparison.OrdinalIgnoreCase) >= 0:
return HostNames.RSA;
default:
return HostNames.None;
}
}
/// <summary>
/// Key function to populate node autocomplete results to display
/// </summary>
internal IEnumerable<SingleResultItem> GetSingleAutocompleteResults()
{
if (PortViewModel == null) return null;
if (IsDisplayingMLRecommendation)
{
//Tracking Analytics when raising Node Autocomplete with the Recommended Nodes option selected (Machine Learning)
Analytics.TrackEvent(
Actions.Show,
Categories.NodeAutoCompleteOperations,
nameof(NodeAutocompleteSuggestion.MLRecommendation));
return GetNodeAutocompleMLResults();
}
else
{
//Tracking Analytics when raising Node Autocomplete with the Object Types option selected.
Analytics.TrackEvent(
Actions.Show,
Categories.NodeAutoCompleteOperations,
nameof(NodeAutocompleteSuggestion.ObjectType));
// Only call GetMatchingSearchElements() for object type match comparison
var objectTypeMatchingElements = GetMatchingSearchElements().ToList();
// If node match searchElements found, use default suggestions.
// These default suggestions will be populated based on the port type.
if (!objectTypeMatchingElements.Any())
{
return DefaultAutoCompleteCandidates().Select(x => new SingleResultItem(x.Model, 1.0));
}
else
{
return objectTypeMatchingElements.Select(x => new SingleResultItem(x, 1.0));
}
}
}
// Delete all transient nodes in the workspace
internal void DeleteTransientNodes()
{
var node = PortViewModel.NodeViewModel;
var wsViewModel = node.WorkspaceViewModel;
var transientNodes = wsViewModel.Nodes.Where(x => x.IsTransient).ToList();
if (transientNodes.Any())
{
dynamoViewModel.Model.ExecuteCommand(new DynamoModel.DeleteModelCommand(transientNodes.Select(x => x.Id), true));
//remove the deletion of the elements from the undo stack
wsViewModel.Model.UndoRecorder.PopFromUndoGroup();
//remove the layout of the elements from the undo stack
wsViewModel.Model.UndoRecorder.PopFromUndoGroup();
}
}
// Add Cluster from server result into the workspace
internal void AddCluster(ClusterResultItem clusterResultItem)
{
if (clusterResultItem == null || clusterResultItem.Topology == null)
return;
List<ModelBase> createdClusterItems = new List<ModelBase>();
var workspaceViewModel = PortViewModel.NodeViewModel.WorkspaceViewModel;
var workspaceModel = workspaceViewModel.Model;
var dynamoModel = PortViewModel.NodeViewModel.DynamoViewModel.Model;
var entryNodeId = clusterResultItem.Topology.Nodes.ElementAtOrDefault(clusterResultItem.EntryNodeIndex)?.Id;
// Lock undo/redo
ToggleUndoRedoLocked(true);
// Delete any existing transient nodes
DeleteTransientNodes();
// Map to store created nodes for connection lookup
var createdNodes = new Dictionary<string, NodeModel>();
// Create nodes from the cluster topology
var offset = PortViewModel.NodeViewModel.X + PortViewModel.NodeViewModel.NodeModel.Width;
List<List<NodeItem>> nodeStacks = NodeAutoCompleteUtilities.ComputeNodePlacementHeuristics(clusterResultItem.Topology.Connections.ToList(), clusterResultItem.Topology.Nodes.ToList());
foreach (var nodeStack in nodeStacks)
{
offset += PortViewModel.NodeViewModel.NodeModel.Width;
foreach (var nodeItem in nodeStack)
{
var typeInfo = new NodeModelTypeId(nodeItem.Type.Id);
var newNode = dynamoModel.CreateNodeFromNameOrType(Guid.NewGuid(), typeInfo.FullName, true);
if (newNode != null)
{
newNode.X = offset; // Adjust X position
newNode.Y = PortViewModel.NodeViewModel.NodeModel.Y; // Adjust Y position
workspaceModel.AddAndRegisterNode(newNode);
createdNodes[nodeItem.Id] = newNode;
createdClusterItems.Add(newNode);
var newNodeViewModel = workspaceViewModel.Nodes.Last();
newNodeViewModel.IsHidden = true; // Hide the node initially
}
}
}
// Connect the cluster to the original node and port
if (entryNodeId != null && createdNodes.TryGetValue(entryNodeId, out var entryNode))
{
ConnectorModel entryConnector = null;
if (PortViewModel.PortType == PortType.Output)
{
var portIndex = clusterResultItem.EntryNodeInPort;
if (entryNode.InPorts.Count > portIndex &&!entryNode.InPorts[portIndex].Connectors.Any())
{
entryConnector = ConnectorModel.Make(PortViewModel.NodeViewModel.NodeModel, entryNode, PortViewModel.PortModel.Index, portIndex);
}
}
else
{
var portIndex = clusterResultItem.EntryNodeOutPort;
if (entryNode.OutPorts.Count > portIndex && !entryNode.OutPorts[portIndex].Connectors.Any())
{
entryConnector = ConnectorModel.Make(entryNode, PortViewModel.NodeViewModel.NodeModel, portIndex, PortViewModel.PortModel.Index);
}
}
if (entryConnector != null)
{
entryConnector.IsHidden = true;
var entryConnectorViewModel = workspaceViewModel.Connectors.First(c => c.ConnectorModel.Equals(entryConnector));
entryConnectorViewModel.IsConnecting = true;
createdClusterItems.Add(entryConnector);
}
}
// Create connections between nodes
foreach (var connection in clusterResultItem.Topology.Connections)
{
if (createdNodes.TryGetValue(connection.StartNode.NodeId, out var sourceNode) &&
createdNodes.TryGetValue(connection.EndNode.NodeId, out var targetNode))
{
var sourcePortIndex = connection.StartNode.PortIndex - 1;
var targetPortIndex = connection.EndNode.PortIndex - 1;
if (sourceNode.OutPorts.Count > sourcePortIndex && targetNode.InPorts.Count > targetPortIndex)
{
if (!targetNode.InPorts[targetPortIndex].Connectors.Any())
{
var newConnector = ConnectorModel.Make(sourceNode, targetNode, sourcePortIndex, targetPortIndex);
if (newConnector != null)
{
newConnector.IsHidden = true; // Hide the connector initially
createdClusterItems.Add(newConnector);
}
}
}
}
}
//add the new items to the undo recorder (this ensures the elements are valid at this point in time before any other manipulation occurs)
DynamoModel.RecordUndoModels(workspaceModel, createdClusterItems);
// Perform auto-layout for the newly added nodes
NodeAutoCompleteUtilities.PostAutoLayoutNodes(
workspaceViewModel.DynamoViewModel.CurrentSpace,
PortViewModel.NodeViewModel.NodeModel,
createdNodes.Values,
false,
false,
false,
() =>
{
// Finalize visibility of nodes and connectors
foreach (var node in createdNodes.Values)
{
var matchingNode = workspaceViewModel.Nodes.FirstOrDefault(n => n.NodeModel.GUID.Equals(node.GUID));
if (matchingNode != null)
{
matchingNode.IsHidden = false;
}
foreach (var connector in node.AllConnectors)
{
connector.IsHidden = !PreferenceSettings.Instance.ShowConnector;
}
}
});
}
/// <summary>
/// Key function to populate node autocomplete results to display
/// </summary>
internal void PopulateAutoComplete()
{
if (PortViewModel == null) return;
ResetAutoCompleteSearchViewState();
FullResults = null;
if(DropdownResults != null)
{
DropdownResults = null;
}
//this should run on the UI thread, so thread safety is not a concern
LastRequestGuid = Guid.NewGuid();
var myRequest = LastRequestGuid;
//start a background thread to make the http request
Task.Run(() =>
{
List<SingleResultItem> fullSingleResults = null;
MLNodeClusterAutoCompletionResponse fullResults = null;
if (IsSingleAutocomplete || !IsDisplayingMLRecommendation)
{
fullSingleResults = GetSingleAutocompleteResults().ToList();
fullResults = new MLNodeClusterAutoCompletionResponse
{
Version = "0.0",
NumberOfResults = fullSingleResults.Count,
Results = fullSingleResults.Select(x => new ClusterResultItem
{
Description = x.Description,
Title = x.Description,
Probability = x.Score.ToString(),
EntryNodeIndex = 0,
EntryNodeInPort = PortViewModel.PortType == PortType.Output ? x.PortToConnect : -1,
EntryNodeOutPort = PortViewModel.PortType == PortType.Input ? x.PortToConnect : -1,
Topology = new TopologyItem
{
Nodes = new List<NodeItem> { new NodeItem {
Id = new Guid().ToString(),
Type = new NodeType { Id = x.CreationName } } },
Connections = new List<ConnectionItem>()
}
})
};
}
else
{
fullResults = GetGenericAutocompleteResult<MLNodeClusterAutoCompletionResponse>(nodeClusterAutocompleteMLEndpoint);
}
dynamoViewModel.UIDispatcher.BeginInvoke(() =>
{
if(LastRequestGuid != myRequest)
{
//a newer request came, we're no longer interested in the results of this one
//only latest request has the right to be committed to the UI and internal data structures
return;
}
if (!IsOpen)
{
// view disappeared while the background thread was waiting for the server response.
// Ignore the results are we're no longer interested.
return;
}