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
1430 lines (1256 loc) · 62.1 KB
/
NodeAutoCompleteBarViewModel.cs
File metadata and controls
1430 lines (1256 loc) · 62.1 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 J2N.Text;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers.Classic;
using Lucene.Net.Search;
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.Core;
using Dynamo.Graph.Workspaces;
using Dynamo.Graph;
namespace Dynamo.NodeAutoComplete.ViewModels
{
/// <summary>
/// Search View Model for Node AutoComplete Search Bar
/// </summary>
public class NodeAutoCompleteBarViewModel : SearchViewModel
{
internal PortViewModel PortViewModel { get; set; }
private List<NodeSearchElementViewModel> searchElementsCache;
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;
// 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<NodeAutoCompleteClusterResult> clusterResults;
/// <summary>
/// Cluster autocomplete search results.
/// </summary>
public IEnumerable<NodeAutoCompleteClusterResult> ClusterResults
{
get
{
return clusterResults;
}
set
{
clusterResults = value;
RaisePropertyChanged(nameof(ClusterResults));
RaisePropertyChanged(nameof(NthofTotal));
RaisePropertyChanged(nameof(ResultsLoaded));
RaisePropertyChanged(nameof(ConfirmSource));
RaisePropertyChanged(nameof(PreviousSource));
RaisePropertyChanged(nameof(NextSource));
}
}
/// <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 => ClusterResults != null;
public bool IsOpen { get; set; }
private int ClusterResultsCount => ClusterResults == null ? 0 : ClusterResults.Count();
private int selectedIndex = 0;
/// <summary>
/// Selected index of the current cluster autocomplete option
/// </summary>
public int SelectedIndex
{
get
{
return selectedIndex;
}
set
{
if(selectedIndex != value && value >= 0)
{
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;
}
NodeAutoCompleteUtilities.PostAutoLayoutNodes(node.WorkspaceViewModel.Model, node.NodeModel, transientNodes.Select(x => x.NodeModel), true, true, false, null);
}
/// <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;
private MLNodeClusterAutoCompletionResponse fullResults;
/// <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>();
searchElementsCache = 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;
}
internal void ShowNodeAutocompleMLResults()
{
MLNodeAutoCompletionResponse MLresults = null;
var request = GenerateRequestForMLAutocomplete();
string jsonRequest = JsonConvert.SerializeObject(request);
// Get results from the ML API.
try
{
MLresults = GetMLNodeAutocompleteResults(jsonRequest);
}
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;
}
// 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;
}
ServiceVersion = MLresults.Version;
var results = new List<NodeSearchElementViewModel>();
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.
if (MLresults.Results.Count() > 0)
{
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
if (nodeSearchElement != null)
{
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 = GetViewModelForNodeSearchElement(nodeSearchElement);
if (viewModelElement != null)
{
viewModelElement.AutoCompletionNodeMachineLearningInfo = new AutoCompletionNodeMachineLearningInfo(true, true, Math.Round(result.Score * 100));
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();
}
if (nodeSearchElement != null)
{
nodeSearchElement.AutoCompletionNodeElementInfo = new AutoCompletionNodeElementInfo
{
PortToConnect = portIndex
};
}
var viewModelElement = GetViewModelForNodeSearchElement(nodeSearchElement);
if (viewModelElement != null)
{
viewModelElement.AutoCompletionNodeMachineLearningInfo = new AutoCompletionNodeMachineLearningInfo(true, true, Math.Round(result.Score * 100));
results.Add(viewModelElement);
}
}
}
OrganizeConfidenceSection(results);
}
}
/// <summary>
/// Compare to low confidence threadhold defined by user can origanize the results into high and low confidence sections.
/// </summary>
/// <param name="results"></param>
internal void OrganizeConfidenceSection(List<NodeSearchElementViewModel> results)
{
foreach (var result in results)
{
if (result.AutoCompletionNodeMachineLearningInfo.ConfidenceScore >= dynamoViewModel.PreferenceSettings.MLRecommendationConfidenceLevel)
{
FilteredHighConfidenceResults = FilteredHighConfidenceResults.Append(result);
}
else
{
FilteredLowConfidenceResults = FilteredLowConfidenceResults.Append(result);
}
}
// Show low confidence section if there are some results under threshold and feature enabled
DisplayLowConfidence = FilteredLowConfidenceResults.Any() && dynamoViewModel.PreferenceSettings.HideNodesBelowSpecificConfidenceLevel;
if (!FilteredHighConfidenceResults.Any())
{
DisplayAutocompleteMLStaticPage = true;
AutocompleteMLTitle = Resources.AutocompleteLowConfidenceTitle;
AutocompleteMLMessage = Resources.AutocompleteLowConfidenceMessage;
return;
}
// By default, show only the results which are above the threshold
FilteredResults = dynamoViewModel.PreferenceSettings.HideNodesBelowSpecificConfidenceLevel ? FilteredHighConfidenceResults : results;
}
private MLNodeAutoCompletionResponse GetMLNodeAutocompleteResults(string requestJSON)
{
MLNodeAutoCompletionResponse results = null;
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)
{
var uri = DynamoUtilities.PathHelper.GetServiceBackendAddress(this, nodeAutocompleteMLEndpoint);
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(requestJSON);
request.RequestFormat = DataFormat.Json;
RestResponse response = client.Execute(request);
//TODO maybe worth moving to system.text json in phases?
results = JsonConvert.DeserializeObject<MLNodeAutoCompletionResponse>(response.Content);
}
}
catch (Exception ex)
{
dynamoViewModel.Model.Logger.Log(ex.Message);
throw new Exception("Authentication failed.");
}
return results;
}
// Rest API call to get the Node cluster Autocomlete results from the service.
internal MLNodeClusterAutoCompletionResponse GetMLNodeClusterAutocompleteResults()
{
MLNodeClusterAutoCompletionResponse results = null;
try
{
var MLRequest = GenerateRequestForMLAutocomplete();
string jsonRequest = JsonConvert.SerializeObject(MLRequest);
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, nodeClusterAutocompleteMLEndpoint);
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<MLNodeClusterAutoCompletionResponse>(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;
// Save the filtered results for search.
searchElementsCache = FilteredResults.ToList();
}
// 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 void PopulateAutoCompleteCandidates()
{
if (PortViewModel == null) return;
dynamoViewModel.CurrentSpaceViewModel.Model.NodeRemoved += NodeViewModel_Removed;
ResetAutoCompleteSearchViewState();
if (IsDisplayingMLRecommendation)
{
ShowNodeAutocompleMLResults();
//Tracking Analytics when raising Node Autocomplete with the Recommended Nodes option selected (Machine Learning)
Analytics.TrackEvent(
Actions.Show,
Categories.NodeAutoCompleteOperations,
nameof(NodeAutocompleteSuggestion.MLRecommendation));
}
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())
{
PopulateDefaultAutoCompleteCandidates();
}
else
{
FilteredResults = GetViewModelForNodeSearchElements(objectTypeMatchingElements);
}
}
// Save the filtered results for search.
searchElementsCache = FilteredResults.ToList();
}
// 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)));
//remove the initial layout of the transient nodes from the undo stack
wsViewModel.Model.UndoRecorder.PopFromUndoGroup();
//remove the deletion of the transient nodes from the undo stack
wsViewModel.Model.UndoRecorder.PopFromUndoGroup();
}
}
// Add Cluster from server result into the workspace
internal void AddCluster(ClusterResultItem ClusterResultItem)
{
NodeViewModel targetNodeFromCluster = null;
var node = PortViewModel.NodeViewModel;
var wsViewModel = node.WorkspaceViewModel;
DeleteTransientNodes();
var index = 0;
// A map of the cluster result v.s. actual nodes created for node connection look up
var clusterMapping = new Dictionary<string, NodeViewModel>();
// Convert topology to actual cluster
var clusterNodes = ClusterResultItem.Topology.Nodes.ToList();
var clusterConnections = ClusterResultItem.Topology.Connections.ToList();
List<List<NodeItem>> nodeStacks = NodeAutoCompleteUtilities.ComputeNodePlacementHeuristics(clusterConnections, clusterNodes);
//store our nodes and wires to allow for one undo
List<ModelBase> newNodesAndWires = new List<ModelBase>();
double xoffset = node.X + node.NodeModel.Width;
foreach (var nodeStack in nodeStacks)
{
xoffset += node.NodeModel.Width;
foreach(var newNode in nodeStack)
{
// Retrieve assembly name and node full name from type.id.
var typeInfo = wsViewModel.NodeAutoCompleteSearchViewModel.GetInfoFromTypeId(newNode.Type.Id);
dynamoViewModel.Model.ExecuteCommand(new DynamoModel.CreateNodeCommand(Guid.NewGuid().ToString(), typeInfo.FullName, xoffset, node.NodeModel.Y, false, false));
//disallow the node creation command from the undo group, we group node creation and wires below
wsViewModel.Model.UndoRecorder.PopFromUndoGroup();
var nodeFromCluster = wsViewModel.Nodes.LastOrDefault();
newNodesAndWires.Add(nodeFromCluster.NodeModel);
nodeFromCluster.IsTransient = true;
nodeFromCluster.IsHidden = true;
clusterMapping.Add(newNode.Id, nodeFromCluster);
// Add the node to the selection to prepare for autolayout later
if (index == ClusterResultItem.EntryNodeIndex)
{
// This is the target node from cluster that should connect to the query node
targetNodeFromCluster = nodeFromCluster;
}
index++;
}
}
clusterConnections.ForEach(connection =>
{
// Connect the nodes
var sourceNode = clusterMapping[connection.StartNode.NodeId].NodeModel;
var targetNode = clusterMapping[connection.EndNode.NodeId].NodeModel;
// The port index is 1- based (currently a hack and not expected from service)
var sourcePort = sourceNode.OutPorts.FirstOrDefault(p => p.Index == connection.StartNode.PortIndex - 1);
var targetPort = targetNode.InPorts.FirstOrDefault(p => p.Index == connection.EndNode.PortIndex - 1);
if (targetPort != null && targetPort.Connectors.Count == 0)
{
var connector = ConnectorModel.Make(sourceNode, targetNode, connection.StartNode.PortIndex - 1, connection.EndNode.PortIndex - 1);
newNodesAndWires.Add(connector);
}
});
// Connect the cluster to the original node and port
var connector = ConnectorModel.Make(node.NodeModel, targetNodeFromCluster.NodeModel, 0, ClusterResultItem.EntryNodeInPort);
newNodesAndWires.Add(connector);
// Make connectors invisible ( just like the cluster nodes ) before they get a chance to be drawn.
var clusterNodesModel = clusterMapping.Values.ToList();
clusterNodesModel.ForEach(nodeInCluster => nodeInCluster?.NodeModel?.AllConnectors?.ToList().ForEach(connector =>
{
if (connector != null) connector.IsHidden = true;
}));
//Finalizer will make cluster nodes and their connections visible after autolayout has determined their final positions.
Action finalizer = () =>
{
clusterNodesModel.ForEach(nodeInCluster =>
{
nodeInCluster.IsHidden = false;
nodeInCluster.NodeModel?.AllConnectors?.ToList().ForEach(connector =>
{
if (connector != null) connector.IsHidden = !PreferenceSettings.Instance.ShowConnector;
});
});
};
// AutoLayout should be called after all nodes are connected.
NodeAutoCompleteUtilities.PostAutoLayoutNodes(wsViewModel.DynamoViewModel.CurrentSpace, node.NodeModel, clusterNodesModel.Select(x => x.NodeModel), false, false, false, finalizer);
//record all node and wire creation as one undo
RecordUndoModels(wsViewModel.Model, newNodesAndWires);
}
private void RecordUndoModels(WorkspaceModel workspace, List<ModelBase> undoItems)
{
var userActionDictionary = new Dictionary<ModelBase, UndoRedoRecorder.UserAction>();
//Add models that were newly created
foreach (var undoItem in undoItems)
{
if(undoItem is null) continue;
userActionDictionary.Add(undoItem, UndoRedoRecorder.UserAction.Creation);
}
WorkspaceModel.RecordModelsForUndo(userActionDictionary, workspace.UndoRecorder);
}
/// <summary>
/// Key function to populate node autocomplete results to display
/// </summary>
internal void PopulateClusterAutoComplete()
{
if (PortViewModel == null) return;
dynamoViewModel.CurrentSpaceViewModel.Model.NodeRemoved += NodeViewModel_Removed;
ResetAutoCompleteSearchViewState();
fullResults = null;
SelectedIndex = 0;
Task.Run(() =>
{
fullResults = GetMLNodeClusterAutocompleteResults();
var comboboxResults = QualifiedResults.Select(x => new NodeAutoCompleteClusterResult { Description = x.Description });
dynamoViewModel.UIDispatcher.BeginInvoke(() =>
{
if (!IsOpen)
{
// view dissapeared while the background thread was waiting for the server response.
// Ignore the results are we're no longer interested.
return;
}
// this runs synchronously on the UI thread, so the UI can't dissapear during execution
ClusterResults = comboboxResults;
if (QualifiedResults.Any())
{
var ClusterResultItem = QualifiedResults.First();
AddCluster(ClusterResultItem);
}
});
});
//Tracking Analytics when raising Node Autocomplete with the Recommended Nodes option selected (Machine Learning)
Analytics.TrackEvent(
Actions.Show,
Categories.NodeAutoCompleteOperations,
nameof(NodeAutocompleteSuggestion.MLRecommendation));
// Save the filtered results for search.
searchElementsCache = FilteredResults.ToList();
}
internal void PopulateDefaultAutoCompleteCandidates()
{
if (PortViewModel.PortModel.PortType == PortType.Input)
{
switch (PortViewModel.PortModel.GetInputPortType())
{
case "int":
FilteredResults = DefaultResults.Where(e => e.Name == "Number Slider" || e.Name == "Integer Slider").ToList();
break;
case "double":
FilteredResults = DefaultResults.Where(e => e.Name == "Number Slider" || e.Name == "Integer Slider").ToList();
break;
case "string":
FilteredResults = DefaultResults.Where(e => e.Name == "String").ToList();
break;
case "bool":
FilteredResults = DefaultResults.Where(e => e.Name == "Boolean").ToList();
break;
default:
FilteredResults = DefaultResults.Where(e => e.Name == "String" || e.Name == "Number Slider" || e.Name == "Integer Slider" || e.Name == "Number" || e.Name == "Boolean");
break;
}
}
else
{
FilteredResults = DefaultResults.Where(e => e.Name == "Watch" || e.Name == "Watch 3D" || e.Name == "Python Script").ToList();
}
}
internal void OnNodeAutoCompleteWindowClosed()
{
dynamoViewModel.CurrentSpaceViewModel.Model.NodeRemoved -= NodeViewModel_Removed;
}
internal void NodeViewModel_Removed(NodeModel node)
{
ParentNodeRemoved?.Invoke(node);
}
/// <summary>
/// Returns a IEnumberable of NodeSearchElementViewModel for respective NodeSearchElements.
/// </summary>
private IEnumerable<NodeSearchElementViewModel> GetViewModelForNodeSearchElements(List<NodeSearchElement> searchElementsCache)
{
return searchElementsCache.Select(e =>
{
var vm = new NodeSearchElementViewModel(e, this);
vm.RequestBitmapSource += SearchViewModelRequestBitmapSource;