-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathModelSystemEditorViewModel.cs
More file actions
4232 lines (3694 loc) · 184 KB
/
Copy pathModelSystemEditorViewModel.cs
File metadata and controls
4232 lines (3694 loc) · 184 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
/*
Copyright 2026 University of Toronto
This file is part of XTMF2.
XTMF2 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
XTMF2 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with XTMF2. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using XTMF2;
using XTMF2.Editing;
using XTMF2.GUI.Controls;
using XTMF2.GUI.Resources;
using XTMF2.GUI.Views;
using XTMF2.ModelSystemConstruct;
using XTMF2.RuntimeModules;
namespace XTMF2.GUI.ViewModels;
/// <summary>
/// Holds the data captured for a single node (and its inlined parameter children)
/// at the moment it is copied, ready to be replicated by a paste operation.
/// </summary>
/// <param name="Name">The node's name at copy time.</param>
/// <param name="Type">The CLR type of the node's module.</param>
/// <param name="OriginalLocation">The canvas rectangle of the node at copy time.</param>
/// <param name="ParameterValue">
/// The string representation of the parameter value, or <c>null</c> when the node
/// is not a parameter node.
/// </param>
/// <param name="IsScriptedParam">
/// <c>true</c> when the parameter is a <c>ScriptedParameter</c>; <c>false</c>
/// for a <c>BasicParameter</c>. Ignored when <paramref name="ParameterValue"/> is <c>null</c>.
/// </param>
/// <param name="InlinedChildren">
/// One entry per hidden (inlined) child node that was connected to this node's hook
/// at copy time. The tuple stores the hook name and the child's own copy data.
/// </param>
internal sealed record NodePasteEntry(
string Name,
Type Type,
Rectangle OriginalLocation,
string? ParameterValue,
bool IsScriptedParam,
IReadOnlyList<(string HookName, NodePasteEntry Child)> InlinedChildren);
/// <summary>
/// View model for editing a single model system. Owns the <see cref="ModelSystemSession"/>
/// and disposes it when the tab is closed.
/// </summary>
public sealed partial class ModelSystemEditorViewModel : ObservableObject, IDisposable
{
private bool _disposed;
// ── Session / model ────────────────────────────────────────────────────
/// <summary>The active editing session for the model system.</summary>
public ModelSystemSession Session { get; }
// ── Run support ───────────────────────────────────────────────────────
/// <summary>
/// Optional run controller used to submit model system runs.
/// When null the Run button is disabled.
/// </summary>
private readonly RunController? _runController;
/// <summary>True when a <see cref="RunController"/> is available.</summary>
public bool CanRun => _runController is not null;
/// <summary>True when at least one estimation group has at least one parameter configured.</summary>
public bool HasEstimationTargets =>
EstimationGroups.Any(g => g.Parameters.Count > 0);
/// <summary>True when at least one calibration group has at least one parameter configured.</summary>
public bool HasCalibrationTargets =>
CalibrationGroups.Any(g => g.Parameters.Count > 0);
/// <summary>
/// Optional callback invoked on the UI thread after a run is successfully submitted.
/// Set by <see cref="MainWindow"/> to switch the active document to the Runs view.
/// </summary>
public Action? RunStarted { get; set; }
/// <summary>The user who owns this editing session.</summary>
public User User { get; }
/// <summary>The header of the model system being edited.</summary>
public ModelSystemHeader ModelSystemHeader => Session.ModelSystemHeader;
/// <summary>The global boundary of the model system; the root canvas scope.</summary>
public Boundary GlobalBoundary => Session.ModelSystem.GlobalBoundary;
// ── Active boundary ───────────────────────────────────────────────────
// Backing field; initialised in the constructor.
private Boundary _currentBoundary = null!;
/// <summary>The boundary currently rendered on the canvas.</summary>
public Boundary CurrentBoundary => _currentBoundary;
/// <summary>
/// Breadcrumb path from the root to the current boundary, e.g. "Root › Sub".
/// Shown as the placeholder text of the boundary navigation dropdown.
/// </summary>
public string CurrentBoundaryLabel
{
get
{
var parts = new System.Collections.Generic.List<string>();
var b = _currentBoundary;
while (b is not null) { parts.Insert(0, b.Name); b = b.Parent; }
// When inside a function template's InternalModules, append the template indicator.
if (_currentFunctionTemplate is { } ft)
parts[^1] = $"[{ft.Name}]";
return string.Join(" › ", parts);
}
}
/// <summary><c>true</c> when the current boundary is the global (root) boundary.</summary>
public bool IsAtRootBoundary => ReferenceEquals(_currentBoundary, GlobalBoundary);
// ── Function-template navigation ──────────────────────────────────────
/// <summary>
/// The function template whose <see cref="FunctionTemplate.InternalModules"/> is currently
/// being shown on the canvas, or <c>null</c> when viewing a regular boundary.
/// </summary>
private FunctionTemplateViewModel? _currentFunctionTemplate;
/// <summary><c>true</c> when the canvas is showing the inside of a function template.</summary>
public bool IsInsideFunctionTemplate => _currentFunctionTemplate is not null;
/// <summary>The function template currently being edited inside, or <c>null</c> when on a regular boundary.</summary>
public FunctionTemplateViewModel? CurrentFunctionTemplate => _currentFunctionTemplate;
/// <summary>Items shown in the boundary navigation dropdown.</summary>
public ObservableCollection<BoundaryNavigationItem> BoundaryNavigationItems { get; } = new();
// ── Dock integration ──────────────────────────────────────────────────
/// <summary>Tab title shown in the dock.</summary>
public string Title => $"✎ {ModelSystemHeader.Name ?? "Model System"}";
/// <summary>Allow the user to close this tab.</summary>
public bool CanClose => true;
// ── Canvas collections ────────────────────────────────────────────────
/// <summary>Observable wrappers around <see cref="Boundary.Modules"/>.</summary>
public ObservableCollection<NodeViewModel> Nodes { get; } = new();
/// <summary>Observable wrappers around <see cref="Boundary.Starts"/>.</summary>
public ObservableCollection<StartViewModel> Starts { get; } = new();
/// <summary>Observable wrappers around <see cref="Boundary.Links"/>.</summary>
public ObservableCollection<LinkViewModel> Links { get; } = new();
/// <summary>
/// Tracks the <see cref="INotifyPropertyChanged.PropertyChanged"/> handlers registered
/// on <see cref="SingleLink"/> objects so they can be properly unsubscribed when the
/// link is removed from the boundary or the boundary switches.
/// </summary>
private readonly Dictionary<SingleLink, System.ComponentModel.PropertyChangedEventHandler> _singleLinkDestHandlers = new();
/// <summary>Observable wrappers around <see cref="Boundary.CommentBlocks"/>.</summary>
public ObservableCollection<CommentBlockViewModel> CommentBlocks { get; } = new();
/// <summary>Observable wrappers around <see cref="Boundary.GhostNodes"/>.</summary>
public ObservableCollection<GhostNodeViewModel> GhostNodes { get; } = new();
/// <summary>Observable wrappers around <see cref="Boundary.FunctionTemplates"/>.</summary>
public ObservableCollection<FunctionTemplateViewModel> FunctionTemplates { get; } = new();
/// <summary>Observable wrappers around <see cref="Boundary.FunctionInstances"/>.</summary>
public ObservableCollection<FunctionInstanceViewModel> FunctionInstances { get; } = new();
/// <summary>
/// Observable wrappers around <see cref="FunctionTemplate.FunctionParameters"/> of the
/// currently active function template. Only populated while
/// <see cref="IsInsideFunctionTemplate"/> is <c>true</c>.
/// </summary>
public ObservableCollection<FunctionParameterViewModel> FunctionParameterVMs { get; } = new();
/// <summary>
/// Flat, searchable list of all visible canvas elements in the current boundary view:
/// non-inlined <see cref="NodeViewModel"/>s, <see cref="StartViewModel"/>s,
/// <see cref="FunctionTemplateViewModel"/>s, <see cref="FunctionInstanceViewModel"/>s,
/// and <see cref="FunctionParameterViewModel"/>s.
/// Rebuilt automatically whenever any constituent collection or a node's inline state changes.
/// </summary>
public ObservableCollection<ICanvasElement> SearchItems { get; } = new();
/// <summary>Observable view-models for the model system's variable list.</summary>
public ObservableCollection<ModelSystemVariableViewModel> ModelSystemVariables { get; } = new();
/// <summary>Observable view-models for the current FunctionTemplate's local variable list.
/// Empty when not inside a FunctionTemplate.</summary>
public ObservableCollection<ModelSystemVariableViewModel> LocalVariables { get; } = new();
/// <summary>Observable view-models for estimation groups (each containing nominated parameters).</summary>
public ObservableCollection<EstimationGroupViewModel> EstimationGroups { get; } = new();
/// <summary>Observable view-models for calibration groups.</summary>
public ObservableCollection<CalibrationGroupViewModel> CalibrationGroups { get; } = new();
/// <summary>Text typed into the variables filter box; filters <see cref="FilteredModelSystemVariables"/> and <see cref="FilteredLocalVariables"/>.</summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FilteredModelSystemVariables))]
[NotifyPropertyChangedFor(nameof(FilteredLocalVariables))]
private string _variableFilter = string.Empty;
/// <summary>
/// Sorted (by name) and filtered (by <see cref="VariableFilter"/>) view of
/// <see cref="ModelSystemVariables"/>. Matches on name or boundary path.
/// </summary>
public IEnumerable<ModelSystemVariableViewModel> FilteredModelSystemVariables
{
get
{
var q = ModelSystemVariables.AsEnumerable();
if (!string.IsNullOrWhiteSpace(VariableFilter))
{
var f = VariableFilter.Trim();
q = q.Where(v =>
v.Name.Contains(f, StringComparison.OrdinalIgnoreCase) ||
v.BoundaryPath.Contains(f, StringComparison.OrdinalIgnoreCase));
}
return q.OrderBy(v => v.Name, StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// Sorted (by name) and filtered (by <see cref="VariableFilter"/>) view of
/// <see cref="LocalVariables"/> for the current FunctionTemplate.
/// </summary>
public IEnumerable<ModelSystemVariableViewModel> FilteredLocalVariables
{
get
{
var q = LocalVariables.AsEnumerable();
if (!string.IsNullOrWhiteSpace(VariableFilter))
{
var f = VariableFilter.Trim();
q = q.Where(v => v.Name.Contains(f, StringComparison.OrdinalIgnoreCase));
}
return q.OrderBy(v => v.Name, StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>True when local FunctionTemplate variables are available (drives section visibility).</summary>
public bool HasLocalVariables => LocalVariables.Count > 0;
/// <summary>True when neither global nor local variables are defined (drives the empty-state label).</summary>
public bool HasNoVariablesAtAll => ModelSystemVariables.Count == 0 && LocalVariables.Count == 0;
/// <summary>The currently selected link, if any. Mutually exclusive with <see cref="SelectedElement"/>.</summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NothingSelected))]
private LinkViewModel? _selectedLink;
/// <summary>In-order list of destination entries for the currently selected Multi-Link.</summary>
public ObservableCollection<LinkDestinationViewModel> SelectedLinkDestinationEntries { get; } = new();
/// <summary>The destination entry currently selected in the destinations list.</summary>
[ObservableProperty]
private LinkDestinationViewModel? _selectedLinkDestinationEntry;
/// <summary>True when the selected link is a MultiLink (drives the destinations panel visibility).</summary>
public bool SelectedLinkIsMulti => SelectedLink?.UnderlyingLink is MultiLink;
/// <summary>True when neither an element nor a link is selected.</summary>
public bool NothingSelected => SelectedElement is null && SelectedLink is null;
// ── Canvas element search ─────────────────────────────────────────────
/// <summary>Fires when the user picks an element from the search box; the view should scroll to it.</summary>
public event Action<ICanvasElement>? ScrollToElementRequested;
/// <summary>
/// Holds an element that <see cref="NavigateToElementById"/> wanted to scroll to but could
/// not because no view was subscribed yet (e.g. the tab was just opened).
/// The view drains this after it attaches and completes its layout pass.
/// </summary>
private ICanvasElement? _pendingScrollTarget;
/// <summary>
/// The last scroll offset the user was at in the canvas. Persists across tab switches so
/// the view can restore the position when the tab is re-activated (the view may be recreated
/// by Dock.Avalonia on each activation).
/// </summary>
public Vector SavedScrollOffset { get; set; }
/// <summary>
/// Invokes <see cref="ScrollToElementRequested"/> for any element that was stored while
/// the view was not yet attached. Called by <see cref="Views.ModelSystemEditorView"/> after
/// it subscribes and layout has completed.
/// </summary>
public void FlushPendingScrollTarget()
{
var target = System.Threading.Interlocked.Exchange(ref _pendingScrollTarget, null);
if (target is not null)
ScrollToElementRequested?.Invoke(target);
}
/// <summary>Bound to the AutoCompleteBox SelectedItem; triggers navigation when set.</summary>
[ObservableProperty]
private ICanvasElement? _canvasSearchSelection;
partial void OnCanvasSearchSelectionChanged(ICanvasElement? value)
{
if (value is null) return;
SelectElement(value);
ScrollToElementRequested?.Invoke(value);
CanvasSearchSelection = null; // reset so the box is ready for the next search
}
// ── SearchItems tracking ──────────────────────────────────────────────
private readonly HashSet<NodeViewModel> _searchTrackedNodes = new();
/// <summary>
/// Rebuilds <see cref="SearchItems"/> from the current boundary's VM collections.
/// Non-inlined nodes and all Starts, FunctionTemplates, FunctionInstances,
/// and FunctionParameters are included.
/// </summary>
private void RebuildSearchItems()
{
SearchItems.Clear();
foreach (var nvm in Nodes)
if (!nvm.IsInlined)
SearchItems.Add(nvm);
foreach (var svm in Starts)
SearchItems.Add(svm);
foreach (var ftvm in FunctionTemplates)
SearchItems.Add(ftvm);
foreach (var fivm in FunctionInstances)
SearchItems.Add(fivm);
foreach (var fpvm in FunctionParameterVMs)
SearchItems.Add(fpvm);
}
private void OnNodesCollectionChangedForSearch(object? sender, NotifyCollectionChangedEventArgs e)
{
// Manage per-node IsInlined subscriptions so SearchItems stays in sync.
if (e.Action == NotifyCollectionChangedAction.Reset)
{
foreach (var nvm in _searchTrackedNodes)
nvm.PropertyChanged -= OnTrackedNodePropertyChanged;
_searchTrackedNodes.Clear();
}
else
{
if (e.NewItems is not null)
foreach (NodeViewModel nvm in e.NewItems)
if (_searchTrackedNodes.Add(nvm))
nvm.PropertyChanged += OnTrackedNodePropertyChanged;
if (e.OldItems is not null)
foreach (NodeViewModel nvm in e.OldItems)
if (_searchTrackedNodes.Remove(nvm))
nvm.PropertyChanged -= OnTrackedNodePropertyChanged;
}
RebuildSearchItems();
}
private void OnTrackedNodePropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(NodeViewModel.IsInlined))
RebuildSearchItems();
}
// Subscription to the live MultiLink.Destinations collection.
private NotifyCollectionChangedEventHandler? _destChangedHandler;
private MultiLink? _subscribedMultiLink;
// ── Selection ─────────────────────────────────────────────────────────
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(NothingSelected))]
private ICanvasElement? _selectedElement;
/// <summary>
/// A mutable copy of <see cref="SelectedElement"/>'s name/text for the properties panel text box.
/// For nodes/starts this is the name; for comment blocks this is the comment text.
/// Committed via <see cref="CommitRenameCommand"/>.
/// </summary>
[ObservableProperty]
private string _selectedElementEditName = string.Empty;
/// <summary>
/// Label for the edit field in the property panel.
/// "Name" for nodes and starts; "Comment" for comment blocks.
/// </summary>
public string SelectedElementFieldLabel =>
SelectedElement is CommentBlockViewModel ? "Comment" : "Name";
/// <summary>
/// True when the selected element is a <see cref="NodeViewModel"/>,
/// used to gate the Change Type button in the property panel.
/// </summary>
public bool SelectedElementIsNode => SelectedElement is NodeViewModel;
/// <summary>True when the selected element is a <see cref="CommentBlockViewModel"/>.</summary>
public bool SelectedElementIsComment => SelectedElement is CommentBlockViewModel;
/// <summary>True when the selected element is NOT a <see cref="CommentBlockViewModel"/>, used to hide the rename box for comments.</summary>
public bool SelectedElementIsNotComment => SelectedElement is not CommentBlockViewModel;
/// <summary>
/// True when the selected node is a BasicParameter or ScriptedParameter,
/// used to gate the parameter value editor in the property panel.
/// </summary>
public bool SelectedElementIsParameter
=> SelectedElement is NodeViewModel pnvm && pnvm.IsParameterNode;
/// <summary>
/// Mutable copy of the selected parameter node's current value string,
/// bound two-way to the parameter value text box.
/// </summary>
[ObservableProperty]
private string _selectedElementParameterValue = string.Empty;
/// <summary>
/// Human-readable type string shown in the property panel's "Type:" row.
/// Automatically updates when the node's type changes.
/// </summary>
public string SelectedElementTypeName => SelectedElement switch
{
StartViewModel => "Start (entry point)",
NodeViewModel nvm => $"Module\n{nvm.TypeName}",
CommentBlockViewModel => "Comment Block",
FunctionTemplateViewModel => "Function Template",
FunctionInstanceViewModel => "Function Instance",
FunctionParameterViewModel => "Function Parameter",
_ => string.Empty
};
/// <summary>True when the floating side panel should be shown.</summary>
public bool SelectedSidePanelIsVisible => true;
/// <summary>Module display name shown in the floating side panel.</summary>
public string SelectedSidePanelModuleName
=> TryGetSelectedSidePanelMetadata(out var metadata) ? metadata.moduleName : string.Empty;
/// <summary>Module or template type name shown beneath the title in the floating side panel.</summary>
public string SelectedSidePanelTypeName
=> TryGetSelectedSidePanelMetadata(out var metadata) ? metadata.typeName : string.Empty;
/// <summary>Module description shown inside the floating side panel.</summary>
public string SelectedSidePanelDescription
=> TryGetSelectedSidePanelMetadata(out var metadata) ? metadata.description : string.Empty;
/// <summary>Documentation URL shown as a link in the floating side panel.</summary>
public string SelectedSidePanelDocumentationLink
=> TryGetSelectedSidePanelMetadata(out var metadata) ? metadata.documentationLink : string.Empty;
/// <summary>True when the selected item exposes a documentation link.</summary>
public bool SelectedSidePanelHasDocumentationLink
=> !string.IsNullOrWhiteSpace(SelectedSidePanelDocumentationLink);
/// <summary>True when the selected element is a <see cref="FunctionInstanceViewModel"/>.</summary>
public bool SelectedSidePanelHasTemplateLink => SelectedElement is FunctionInstanceViewModel;
/// <summary>The button text used to open the selected function instance's template.</summary>
public string SelectedFunctionInstanceTemplateActionText
=> string.IsNullOrWhiteSpace(SelectedFunctionInstanceTemplateName)
? "Open Template"
: $"Open Template: {SelectedFunctionInstanceTemplateName}";
/// <summary>The name of the selected function parameter's template, shown as a quick context link.</summary>
public string SelectedFunctionParameterTemplateName
=> (SelectedElement as FunctionParameterViewModel)?.UnderlyingParameter.Template.Name ?? string.Empty;
/// <summary>True when the selected element is a <see cref="FunctionParameterViewModel"/>.</summary>
public bool SelectedSidePanelHasFunctionParameterContext => SelectedElement is FunctionParameterViewModel;
/// <summary>True when the selected element is a <see cref="FunctionTemplateViewModel"/>.</summary>
public bool SelectedElementIsFunctionTemplate => SelectedElement is FunctionTemplateViewModel;
/// <summary>True when the selected element is a <see cref="FunctionInstanceViewModel"/>.</summary>
public bool SelectedElementIsFunctionInstance => SelectedElement is FunctionInstanceViewModel;
/// <summary>
/// The name of the template referenced by the currently selected function instance,
/// or an empty string when nothing (or a non-instance element) is selected.
/// </summary>
public string SelectedFunctionInstanceTemplateName
=> (SelectedElement as FunctionInstanceViewModel)?.TemplateName ?? string.Empty;
/// <summary>
/// The <see cref="FunctionParameter"/> list of the template referenced by the currently
/// selected function instance, or an empty collection.
/// </summary>
public System.Collections.Generic.IEnumerable<ModelSystemConstruct.FunctionParameter> SelectedFunctionInstanceFunctionParameters
=> (SelectedElement as FunctionInstanceViewModel)?.FunctionParameters
?? System.Linq.Enumerable.Empty<ModelSystemConstruct.FunctionParameter>();
/// <summary>
/// <c>true</c> when the selected function instance's template has no function parameters —
/// drives the "(none)" hint text in the properties panel.
/// </summary>
public bool SelectedFunctionInstanceHasNoFunctionParameters
=> SelectedElement is not FunctionInstanceViewModel fi || fi.FunctionParameters.Count == 0;
/// <summary>
/// The <see cref="FunctionParameter"/> list of the currently selected function template,
/// or an empty list when nothing (or a non-template element) is selected.
/// </summary>
public IEnumerable<FunctionParameter> SelectedFunctionTemplateFunctionParameters
=> (SelectedElement as FunctionTemplateViewModel)?.FunctionParameters
?? System.Linq.Enumerable.Empty<FunctionParameter>();
/// <summary>
/// <c>true</c> when the selected function template has no function parameters —
/// drives the "(none)" hint text in the properties panel.
/// </summary>
public bool SelectedFunctionTemplateHasNoFunctionParameters
=> SelectedElement is not FunctionTemplateViewModel ft || ft.FunctionParameters.Count == 0;
/// <summary>All module types currently registered in the runtime.</summary>
public System.Collections.ObjectModel.ReadOnlyObservableCollection<Type> AvailableModuleTypes
=> Session.LoadedModuleTypes;
/// <summary>
/// When <c>true</c> the canvas renders every hook on every node.
/// When <c>false</c> only hooks that have an active link are shown.
/// </summary>
[ObservableProperty]
private bool _showAllHooks;
// ── Undo / Redo state ─────────────────────────────────────────────────
/// <summary>True when there is at least one undoable command.</summary>
[ObservableProperty]
private bool _canUndo;
/// <summary>True when there is at least one redoable command.</summary>
[ObservableProperty]
private bool _canRedo;
// Unsubscribe from the outgoing element before the field changes.
partial void OnSelectedElementChanging(ICanvasElement? value)
{
if (SelectedElement is System.ComponentModel.INotifyPropertyChanged oldNpc)
oldNpc.PropertyChanged -= OnSelectedElementPropertyChanged;
}
partial void OnSelectedElementChanged(ICanvasElement? value)
{
// Subscribe to the new element so TypeName changes propagate.
if (value is System.ComponentModel.INotifyPropertyChanged newNpc)
newNpc.PropertyChanged += OnSelectedElementPropertyChanged;
SelectedElementEditName = value?.Name ?? string.Empty;
OnPropertyChanged(nameof(SelectedElementFieldLabel));
OnPropertyChanged(nameof(SelectedElementTypeName));
OnPropertyChanged(nameof(SelectedElementIsNode));
OnPropertyChanged(nameof(SelectedElementIsComment));
OnPropertyChanged(nameof(SelectedElementIsNotComment));
OnPropertyChanged(nameof(SelectedElementIsParameter));
OnPropertyChanged(nameof(SelectedElementIsFunctionTemplate));
OnPropertyChanged(nameof(SelectedFunctionTemplateFunctionParameters));
OnPropertyChanged(nameof(SelectedFunctionTemplateHasNoFunctionParameters));
OnPropertyChanged(nameof(SelectedElementIsFunctionInstance));
OnPropertyChanged(nameof(SelectedFunctionInstanceTemplateName));
OnPropertyChanged(nameof(SelectedFunctionInstanceTemplateActionText));
OnPropertyChanged(nameof(SelectedFunctionInstanceFunctionParameters));
OnPropertyChanged(nameof(SelectedFunctionInstanceHasNoFunctionParameters));
OnPropertyChanged(nameof(SelectedFunctionParameterTemplateName));
OnPropertyChanged(nameof(SelectedSidePanelIsVisible));
OnPropertyChanged(nameof(SelectedSidePanelModuleName));
OnPropertyChanged(nameof(SelectedSidePanelTypeName));
OnPropertyChanged(nameof(SelectedSidePanelDescription));
OnPropertyChanged(nameof(SelectedSidePanelDocumentationLink));
OnPropertyChanged(nameof(SelectedSidePanelHasDocumentationLink));
OnPropertyChanged(nameof(SelectedSidePanelHasTemplateLink));
OnPropertyChanged(nameof(SelectedSidePanelHasFunctionParameterContext));
SelectedElementParameterValue =
value is NodeViewModel pnvm && pnvm.IsParameterNode
? pnvm.ParameterValueRepresentation
: string.Empty;
}
private void OnSelectedElementPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(NodeViewModel.TypeName)
or nameof(FunctionParameterViewModel.TypeName)
or nameof(FunctionInstanceViewModel.TemplateName)
or nameof(ICanvasElement.Name))
{
OnPropertyChanged(nameof(SelectedElementTypeName));
OnPropertyChanged(nameof(SelectedSidePanelIsVisible));
OnPropertyChanged(nameof(SelectedSidePanelModuleName));
OnPropertyChanged(nameof(SelectedSidePanelTypeName));
OnPropertyChanged(nameof(SelectedSidePanelDescription));
OnPropertyChanged(nameof(SelectedSidePanelDocumentationLink));
OnPropertyChanged(nameof(SelectedSidePanelHasDocumentationLink));
OnPropertyChanged(nameof(SelectedSidePanelHasTemplateLink));
OnPropertyChanged(nameof(SelectedSidePanelHasFunctionParameterContext));
OnPropertyChanged(nameof(SelectedFunctionInstanceTemplateName));
OnPropertyChanged(nameof(SelectedFunctionInstanceTemplateActionText));
OnPropertyChanged(nameof(SelectedFunctionParameterTemplateName));
}
if (e.PropertyName == nameof(NodeViewModel.ParameterValueRepresentation))
{
if (SelectedElement is NodeViewModel nvm && nvm.IsParameterNode)
SelectedElementParameterValue = nvm.ParameterValueRepresentation;
}
}
[RelayCommand]
private void OpenSelectedDocumentation()
{
var documentationLink = SelectedSidePanelDocumentationLink;
if (string.IsNullOrWhiteSpace(documentationLink))
return;
try
{
Process.Start(new ProcessStartInfo
{
FileName = documentationLink,
UseShellExecute = true
});
}
catch
{
// Ignore link launch failures.
}
}
[RelayCommand]
private void OpenSelectedFunctionTemplate()
{
if (SelectedElement is FunctionInstanceViewModel fivm)
OpenFunctionTemplateOfInstance(fivm);
}
private bool TryGetSelectedSidePanelMetadata(out (string moduleName, string typeName, string description, string documentationLink) metadata)
{
metadata = SelectedElement switch
{
null => ("No module selected", string.Empty, string.Empty, string.Empty),
CommentBlockViewModel comment => ("Comment Block", "Comment", comment.Name, string.Empty),
NodeViewModel node => BuildModuleMetadata(node.Name, node.UnderlyingNode.Type),
FunctionTemplateViewModel template => BuildModuleMetadata(template.Name, template.UnderlyingTemplate.Type),
FunctionInstanceViewModel instance => BuildModuleMetadata(instance.Name, instance.UnderlyingInstance.Template.Type),
FunctionParameterViewModel parameter => (
parameter.Name,
FormatTypeNameWithGenerics(parameter.UnderlyingParameter.Type),
string.Empty,
string.Empty),
_ => (string.Empty, string.Empty, string.Empty, string.Empty)
};
return true;
}
private static (string moduleName, string typeName, string description, string documentationLink) BuildModuleMetadata(string moduleName, Type? moduleType)
{
if (moduleType is null)
return (moduleName, string.Empty, string.Empty, string.Empty);
ModuleAttribute? moduleAttribute;
try
{
moduleAttribute = moduleType.GetCustomAttribute<ModuleAttribute>();
}
catch
{
moduleAttribute = null;
}
return (
moduleName,
FormatTypeNameWithGenerics(moduleType),
moduleAttribute?.Description ?? string.Empty,
moduleAttribute?.DocumentationLink ?? string.Empty);
}
/// <summary>
/// Formats a type name with full namespace, expanding generic parameters.
/// For example: "BasicParameter`1" becomes "XTMF2.ModelSystemConstruct.BasicParameter<System.Single>".
/// </summary>
private static string FormatTypeNameWithGenerics(Type type)
{
string typeName = type.FullName ?? type.Name;
if (!type.IsGenericType)
return typeName;
var backtickIndex = typeName.IndexOf('`');
var baseName = backtickIndex >= 0 ? typeName.Substring(0, backtickIndex) : typeName;
var genericArgs = type.GetGenericArguments();
var argNames = string.Join(", ", genericArgs.Select(arg => FormatTypeNameWithGenerics(arg)));
return $"{baseName}<{argNames}>";
}
// ── Parent window reference (set by the view) ─────────────────────────
/// <summary>
/// The top-level window, used to show dialogs.
/// Set by <see cref="Views.ModelSystemEditorView"/> once it is attached to the visual tree.
/// </summary>
public Window? ParentWindow { get; set; }
// ── Toast notification ────────────────────────────────────────────────
/// <summary>Current toast message, or <c>null</c> when the toast is hidden.</summary>
[ObservableProperty]
private string? _toastMessage;
/// <summary>
/// When <c>true</c> the toast is styled as an error; when <c>false</c> it is informational.
/// </summary>
[ObservableProperty]
private bool _toastIsError;
private CancellationTokenSource? _toastCts;
// ── Counters for default names ────────────────────────────────────────
private int _startCounter;
private int _commentCounter;
// ── Default placement step ────────────────────────────────────────────
private const float PlacementStep = 80f;
// =====================================================================
public ModelSystemEditorViewModel(ModelSystemSession session, User user, RunController? runController = null)
{
ArgumentNullException.ThrowIfNull(session);
ArgumentNullException.ThrowIfNull(user);
Session = session;
User = user;
_runController = runController;
// Build initial VM collections from the active boundary.
_currentBoundary = GlobalBoundary;
BuildFromBoundary(_currentBoundary);
SubscribeToBoundary(_currentBoundary);
RebuildBoundaryNavItems();
// Build the variables collection and keep it in sync.
SyncModelSystemVariables();
((System.Collections.Specialized.INotifyCollectionChanged)Session.ModelSystem.Variables)
.CollectionChanged += OnModelSystemVariablesChanged;
// Build estimation/calibration group collections and keep them in sync.
SyncEstimationGroups();
SyncCalibrationGroups();
((System.Collections.Specialized.INotifyCollectionChanged)Session.ModelSystem.EstimationGroups)
.CollectionChanged += OnEstimationGroupsChanged;
((System.Collections.Specialized.INotifyCollectionChanged)Session.ModelSystem.CalibrationGroups)
.CollectionChanged += OnCalibrationGroupsChanged;
// Mirror CanUndo/CanRedo from the session reactively.
_canUndo = Session.CanUndo;
_canRedo = Session.CanRedo;
((System.ComponentModel.INotifyPropertyChanged)Session).PropertyChanged += OnSessionPropertyChanged;
// Keep SearchItems in sync with the canvas collections.
// Nodes: also handles per-node IsInlined tracking.
Nodes.CollectionChanged += OnNodesCollectionChangedForSearch;
Starts.CollectionChanged += (_, _) => RebuildSearchItems();
FunctionTemplates.CollectionChanged += (_, _) => RebuildSearchItems();
FunctionInstances.CollectionChanged += (_, _) => RebuildSearchItems();
FunctionParameterVMs.CollectionChanged += (_, _) => RebuildSearchItems();
// Subscribe to nodes already populated by BuildFromBoundary.
foreach (var nvm in Nodes)
if (_searchTrackedNodes.Add(nvm))
nvm.PropertyChanged += OnTrackedNodePropertyChanged;
RebuildSearchItems();
}
private void OnSessionPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Session.CanUndo)) CanUndo = Session.CanUndo;
else if (e.PropertyName == nameof(Session.CanRedo)) CanRedo = Session.CanRedo;
}
// ── Collection sync ───────────────────────────────────────────────────
private void BuildFromBoundary(Boundary boundary)
{
foreach (var node in boundary.Modules) Nodes.Add(new NodeViewModel(node, Session, User));
foreach (var start in boundary.Starts) Starts.Add(new StartViewModel(start, Session, User));
// Ghost nodes and FunctionInstances must be populated before links so that
// ResolveElement can find their view-models when wiring up link destinations.
foreach (var ghost in boundary.GhostNodes) GhostNodes.Add(new GhostNodeViewModel(ghost, Session, User));
foreach (var ft in boundary.FunctionTemplates) FunctionTemplates.Add(new FunctionTemplateViewModel(ft, Session, User));
foreach (var fi in boundary.FunctionInstances) FunctionInstances.Add(new FunctionInstanceViewModel(fi, Session, User));
// Populate FunctionParameterVMs when inside a function template's InternalModules.
if (_currentFunctionTemplate is not null)
foreach (var fp in _currentFunctionTemplate.UnderlyingTemplate.FunctionParameters)
FunctionParameterVMs.Add(new FunctionParameterViewModel(fp, Session, User));
foreach (var link in boundary.Links) TryAddLinkViewModel(link);
foreach (var cb in boundary.CommentBlocks) CommentBlocks.Add(new CommentBlockViewModel(cb, Session, User));
}
// Cached reference to the current boundary's Boundaries collection so we can
// reliably unsubscribe (Boundary.Boundaries returns a new wrapper on every call).
private INotifyCollectionChanged? _subscribedChildBoundaries;
private void SubscribeToBoundary(Boundary boundary)
{
((INotifyCollectionChanged)boundary.Modules).CollectionChanged += OnModulesChanged;
((INotifyCollectionChanged)boundary.Starts).CollectionChanged += OnStartsChanged;
((INotifyCollectionChanged)boundary.Links).CollectionChanged += OnLinksChanged;
((INotifyCollectionChanged)boundary.CommentBlocks).CollectionChanged += OnCommentBlocksChanged;
((INotifyCollectionChanged)boundary.GhostNodes).CollectionChanged += OnGhostNodesChanged;
((INotifyCollectionChanged)boundary.FunctionTemplates).CollectionChanged += OnFunctionTemplatesChanged;
((INotifyCollectionChanged)boundary.FunctionInstances).CollectionChanged += OnFunctionInstancesChanged;
// Keep the same wrapper instance so we can correctly remove the handler later.
_subscribedChildBoundaries = boundary.Boundaries;
_subscribedChildBoundaries.CollectionChanged += OnChildBoundariesChanged;
}
private void UnsubscribeFromBoundary(Boundary boundary)
{
((INotifyCollectionChanged)boundary.Modules).CollectionChanged -= OnModulesChanged;
((INotifyCollectionChanged)boundary.Starts).CollectionChanged -= OnStartsChanged;
((INotifyCollectionChanged)boundary.Links).CollectionChanged -= OnLinksChanged;
((INotifyCollectionChanged)boundary.CommentBlocks).CollectionChanged -= OnCommentBlocksChanged;
((INotifyCollectionChanged)boundary.GhostNodes).CollectionChanged -= OnGhostNodesChanged;
((INotifyCollectionChanged)boundary.FunctionTemplates).CollectionChanged -= OnFunctionTemplatesChanged;
((INotifyCollectionChanged)boundary.FunctionInstances).CollectionChanged -= OnFunctionInstancesChanged;
if (_subscribedChildBoundaries is not null)
{
_subscribedChildBoundaries.CollectionChanged -= OnChildBoundariesChanged;
_subscribedChildBoundaries = null;
}
}
private void OnChildBoundariesChanged(object? sender, NotifyCollectionChangedEventArgs e)
=> RebuildBoundaryNavItems();
/// <summary>
/// Switches the canvas to <paramref name="boundary"/>, rebuilding all VM
/// collections and re-wiring change-event subscriptions.
/// </summary>
public void SwitchToBoundary(Boundary boundary)
{
if (ReferenceEquals(_currentBoundary, boundary)) return;
// Clear selection to avoid dangling VM references.
SelectElement(null);
SelectLink(null);
UnsubscribeFromBoundary(_currentBoundary);
foreach (var lvm in Links) lvm.Detach();
// Unsubscribe all SingleLink destination-change handlers tracked for the old boundary.
foreach (var (sl, h) in _singleLinkDestHandlers)
sl.PropertyChanged -= h;
_singleLinkDestHandlers.Clear();
Nodes.Clear();
Starts.Clear();
Links.Clear();
CommentBlocks.Clear();
GhostNodes.Clear();
foreach (var ft in FunctionTemplates) ft.Detach();
FunctionTemplates.Clear();
foreach (var fi in FunctionInstances) fi.Detach();
FunctionInstances.Clear();
foreach (var fp in FunctionParameterVMs) fp.Detach();
FunctionParameterVMs.Clear();
_currentBoundary = boundary;
OnPropertyChanged(nameof(CurrentBoundary));
OnPropertyChanged(nameof(CurrentBoundaryLabel));
OnPropertyChanged(nameof(IsAtRootBoundary));
// If the new boundary is not the InternalModules of the tracked template, leave FT mode.
if (_currentFunctionTemplate is not null
&& !ReferenceEquals(boundary, _currentFunctionTemplate.UnderlyingTemplate.InternalModules))
{
((INotifyCollectionChanged)_currentFunctionTemplate.UnderlyingTemplate.FunctionParameters).CollectionChanged
-= OnFunctionParametersChanged;
((INotifyCollectionChanged)_currentFunctionTemplate.UnderlyingTemplate.LocalVariables).CollectionChanged
-= OnLocalVariablesChanged;
_currentFunctionTemplate = null;
SyncLocalVariables(null);
OnPropertyChanged(nameof(IsInsideFunctionTemplate));
ExitFunctionTemplateCommand.NotifyCanExecuteChanged();
}
NavigateUpCommand.NotifyCanExecuteChanged();
OnPropertyChanged(nameof(CanNavigateUp));
SubscribeToBoundary(_currentBoundary);
BuildFromBoundary(_currentBoundary);
RebuildBoundaryNavItems();
}
/// <summary>Rebuilds the dropdown items for the boundary navigation ComboBox.</summary>
private void RebuildBoundaryNavItems()
{
BoundaryNavigationItems.Clear();
if (_currentBoundary.Parent is { } parent)
BoundaryNavigationItems.Add(BoundaryNavigationItem.ForBoundary($"↑ {parent.Name}", parent));
foreach (var child in _currentBoundary.Boundaries)
BoundaryNavigationItems.Add(BoundaryNavigationItem.ForBoundary(child.Name, child));
BoundaryNavigationItems.Add(BoundaryNavigationItem.Browse);
}
/// <summary>Returns all boundaries in the model system as a depth-first flat list with depth info.</summary>
private static IReadOnlyList<(Boundary Boundary, int Depth)> GetAllBoundaries(Boundary root)
{
var result = new List<(Boundary, int)>();
var stack = new Stack<(Boundary, int)>();
stack.Push((root, 0));
while (stack.Count > 0)
{
var (b, depth) = stack.Pop();
result.Add((b, depth));
foreach (var child in b.Boundaries.Reverse())
stack.Push((child, depth + 1));
}
return result;
}
private void OnModulesChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems is not null)
foreach (Node n in e.NewItems)
{
var nvm = new NodeViewModel(n, Session, User);
nvm.ShowHooks = true; // expand hooks by default so the user can immediately see all connections
Nodes.Add(nvm);
SelectElement(nvm);
}
if (e.OldItems is not null)
foreach (Node n in e.OldItems)
{
var vm = Nodes.FirstOrDefault(v => v.UnderlyingNode == n);
if (vm is not null) Nodes.Remove(vm);
}
}
private void OnStartsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems is not null)
foreach (Start s in e.NewItems)
{
var svm = new StartViewModel(s, Session, User);
Starts.Add(svm);
SelectElement(svm);
}
if (e.OldItems is not null)
foreach (Start s in e.OldItems)
{
var vm = Starts.FirstOrDefault(v => v.UnderlyingStart == s);
if (vm is not null) Starts.Remove(vm);
}
}
private void OnLinksChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems is not null)
foreach (Link link in e.NewItems)
TryAddLinkViewModel(link);
if (e.OldItems is not null)
foreach (Link link in e.OldItems)
{
// A MultiLink may have produced multiple LinkViewModels (one per destination).
var toRemove = Links.Where(v => v.UnderlyingLink == link).ToList();
foreach (var vm in toRemove)
{
vm.Detach();
Links.Remove(vm);
}
// Unsubscribe the destination-change handler registered in TryAddLinkViewModel.
if (link is SingleLink removedSl
&& _singleLinkDestHandlers.TryGetValue(removedSl, out var h))
{
removedSl.PropertyChanged -= h;
_singleLinkDestHandlers.Remove(removedSl);
}
}
}