-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMainViewModel.cs
More file actions
1373 lines (1166 loc) · 41.6 KB
/
Copy pathMainViewModel.cs
File metadata and controls
1373 lines (1166 loc) · 41.6 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 CSharpCodeAnalyst.CodeGraph.Contracts;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using CSharpCodeAnalyst.AnalyzerSdk.Contracts;
using CSharpCodeAnalyst.AnalyzerSdk.DynamicDataGrid.Contracts.TabularData;
using CSharpCodeAnalyst.AnalyzerSdk.Messages;
using CSharpCodeAnalyst.AnalyzerSdk.Notifications;
using CSharpCodeAnalyst.AnalyzerSdk.Wpf;
using CSharpCodeAnalyst.CodeGraph.Algorithms.Cycles;
using CSharpCodeAnalyst.CodeGraph.Algorithms.Partitioning;
using CSharpCodeAnalyst.CodeGraph.Graph;
using CSharpCodeAnalyst.CodeGraph.Declarations;
using CSharpCodeAnalyst.CodeGraph.Metrics;
using CSharpCodeAnalyst.CodeParser.Parser;
using CSharpCodeAnalyst.CodeParser.Parser.Config;
using CSharpCodeAnalyst.Configuration;
using CSharpCodeAnalyst.Features.AdvancedSearch;
using CSharpCodeAnalyst.Features.Ai;
using CSharpCodeAnalyst.Features.Analyzers;
using CSharpCodeAnalyst.Features.CycleGroups;
using CSharpCodeAnalyst.Features.DsmMatrix;
using CSharpCodeAnalyst.Features.Export;
using CSharpCodeAnalyst.Features.Gallery;
using CSharpCodeAnalyst.Features.Graph;
using CSharpCodeAnalyst.Features.Help;
using CSharpCodeAnalyst.Features.History;
using CSharpCodeAnalyst.Features.Import;
using CSharpCodeAnalyst.Features.Info;
using CSharpCodeAnalyst.Features.Mcp;
using CSharpCodeAnalyst.Features.Partitions;
using CSharpCodeAnalyst.Features.Refactoring;
using CSharpCodeAnalyst.Features.Statistics;
using CSharpCodeAnalyst.Features.Tree;
using CSharpCodeAnalyst.Persistence.Contracts;
using CSharpCodeAnalyst.Persistence.Dto;
using CSharpCodeAnalyst.Resources;
using CSharpCodeAnalyst.Shared;
using CSharpCodeAnalyst.Shared.Contracts;
using CSharpCodeAnalyst.Shared.Filter;
using CSharpCodeAnalyst.Shared.Messages;
using CSharpCodeAnalyst.Shared.Notifications;
using CSharpCodeAnalyst.Shared.Services;
using CSharpCodeAnalyst.Shared.Tabs;
using CSharpCodeAnalyst.Shared.UI;
using CSharpCodeAnalyst.Shared.Wpf;
using CSharpCodeAnalyst.TreeMap;
// Both this application and DsmSuite have a MainViewModel.
using DsmMainViewModel = DsmSuite.DsmViewer.ViewModel.Main.MainViewModel;
namespace CSharpCodeAnalyst;
internal sealed class MainViewModel : INotifyPropertyChanged
{
private readonly AiAdvisorService _aiAdvisorService = new();
private readonly AnalyzerManager _analyzerManager;
/// <summary>Busy/status-bar sink shared by Importer, HistoryViewModel and IProjectService.</summary>
private readonly IProgress<BusyState> _busy;
private readonly Exporter _exporter;
private readonly Importer _importer;
private readonly ImporterManager _importerManager = new();
private readonly MessageBus _messaging;
private readonly ExternalContractStore _externalContractStore;
private readonly MetricStore _metricStore;
private readonly ProjectExclusionRegExCollection _projectExclusionFilters;
private readonly IProjectService _projectService;
private readonly RefactoringService _refactoringService;
private readonly IUserNotification _ui;
private AppSettings _applicationSettings;
private CodeGraph.Graph.CodeGraph? _codeGraph;
private Table? _cycles;
private Gallery? _gallery;
private GraphViewModel? _graphViewModel;
private InfoPanelViewModel? _infoPanelViewModel;
private string _loadMessage;
/// <summary>
/// Told when the graph is replaced or refactored, so the MCP server can hand out a fresh copy.
/// Always present, even with the server switched off - it does nothing until someone asks it
/// for a snapshot, which keeps the notifications below free of null checks.
/// </summary>
private readonly CodeGraphSnapshotProvider _mcpSnapshotProvider;
private readonly McpServerService _mcpServerService;
private LegendDialog? _openedLegendDialog;
private AdvancedSearchViewModel? _searchViewModel;
private TreeViewModel? _treeViewModel;
private UserPreferences _userSettings;
internal MainViewModel(MessageBus messaging, AppSettings settings, UserPreferences userSettings,
AnalyzerManager analyzerManager, RefactoringService refactoringService, IProjectService projectService,
MetricStore metricStore, ExternalContractStore externalContractStore,
CodeGraphSnapshotProvider mcpSnapshotProvider, McpServerService mcpServerService)
{
// Initialize settings
_applicationSettings = settings;
_userSettings = userSettings;
_analyzerManager = analyzerManager;
_refactoringService = refactoringService;
_metricStore = metricStore;
_externalContractStore = externalContractStore;
_mcpSnapshotProvider = mcpSnapshotProvider;
_mcpServerService = mcpServerService;
_mcpServerService.StateChanged += OnMcpServerStateChanged;
analyzerManager.AnalyzerDataChanged += OnAnalyzerDataChanged;
_ui = new WindowsUserNotification();
_busy = new Progress<BusyState>(OnBusyStateChanged);
_importer = new Importer(_ui, _busy);
_exporter = new Exporter(_ui);
_projectService = projectService;
_projectService.Progress = _busy;
_projectService.ProjectLoaded += OnProjectLoaded;
_projectService.ProjectSaved += OnProjectSaved;
_projectService.DirtyStateChanged += OnDirtyStateChanged;
History = new HistoryViewModel(messaging, _ui, _busy);
// Table data
_cycles = null;
// Apply settings
_projectExclusionFilters = new ProjectExclusionRegExCollection();
try
{
_projectExclusionFilters.Initialize(_applicationSettings.DefaultProjectExcludeFilter);
}
catch
{
_projectExclusionFilters.Initialize("");
}
_messaging = messaging;
_messaging.Subscribe<ClearQuickInfoRequest>(_ => ClearQuickInfo());
_gallery = new Gallery();
SearchCommand = new WpfCommand(Search);
LoadSolutionCommand = new WpfCommand(OnImportSolution);
ExecuteImporterCommand = new WpfCommand<string>(OnExecuteImporter);
LoadProjectCommand = new WpfCommand(OnLoadProject);
SaveProjectCommand = new WpfCommand(OnSaveProject);
GraphClearCommand = new WpfCommand(OnGraphClear);
GraphLayoutCommand = new WpfCommand(OnGraphLayout);
GraphRefitCommand = new WpfCommand(OnGraphRefit);
StopRenderingCommand = new WpfCommand(OnStopRendering);
FindCyclesCommand = new WpfCommand(OnFindCycles);
ShowDsmCommand = new WpfCommand(OnShowDsm);
AiAdviseCommand = new WpfCommand(OnAiAdvise);
ExecuteAnalyzerCommand = new WpfCommand<string>(OnExecuteAnalyzer);
ShowGalleryCommand = new WpfCommand(OnShowGallery);
OpenFilterDialogCommand = new WpfCommand(OnOpenFilterDialog);
OpenSettingsDialogCommand = new WpfCommand(OnOpenSettingsDialog);
ExportToDgmlCommand = new WpfCommand(OnExportToDgml);
ExportToPlantUmlCommand = new WpfCommand(OnExportToPlantUml);
ExportToSvgCommand = new WpfCommand(OnExportToSvg);
ExportToPngCommand = new WpfCommand(OnExportToPng);
ExportToDsiCommand = new WpfCommand(OnExportToDsi);
ExportPlainTextCommand = new WpfCommand(OnExportPlainText);
CopyBitmapToClipboardCommand = new WpfCommand(OnCopyCanvasToClipboard);
OpenRecentFileCommand = new WpfCommand<string>(OnOpenRecentFile);
SnapshotCommand = new WpfCommand(OnSnapshot);
RestoreCommand = new WpfCommand(OnRestore);
ToggleMcpServerCommand = new WpfCommand(OnToggleMcpServer);
CopyMcpSetupCommand = new WpfCommand(_mcpServerService.CopyClientSetupCommand,
() => _mcpServerService.IsRunning);
_loadMessage = string.Empty;
RefreshMru();
}
public HistoryViewModel History { get; private set; }
public WpfCommand ExportPlainTextCommand { get; set; }
public ObservableCollection<Mru> RecentFiles { get; } = [];
private ICommand OpenRecentFileCommand { get; }
/// <summary>
/// Dynamic result tabs (Method Complexity, Type Cohesion, Partitions, tree-map hotspots, ...),
/// created on demand and keyed by id. MainWindow's code-behind projects this onto the
/// working-area TabControl; see <see cref="DynamicTabActivated" /> for bringing one to the front.
/// </summary>
public ObservableCollection<ITabViewModel> DynamicTabs { get; } = [];
public Table? Cycles
{
get => _cycles;
set
{
_cycles = value;
OnPropertyChanged();
}
}
public InfoPanelViewModel? InfoPanelViewModel
{
get => _infoPanelViewModel;
set
{
if (Equals(value, _infoPanelViewModel))
{
return;
}
_infoPanelViewModel = value;
OnPropertyChanged();
}
}
public ICommand ShowGalleryCommand { get; }
public GraphViewModel? GraphViewModel
{
get => _graphViewModel;
set
{
_graphViewModel = value;
OnPropertyChanged();
}
}
public bool IsLeftPanelExpanded
{
get;
set
{
if (field == value)
{
return;
}
field = value;
OnPropertyChanged();
}
} = true;
public bool IsLoading
{
get;
set
{
field = value;
OnPropertyChanged();
}
}
public string LoadMessage
{
get => _loadMessage;
private set
{
_loadMessage = value;
OnPropertyChanged();
}
}
public ICommand LoadProjectCommand { get; }
public ICommand LoadSolutionCommand { get; }
public ICommand ExecuteImporterCommand { get; }
public ICommand SaveProjectCommand { get; }
public ICommand GraphClearCommand { get; }
public ICommand GraphLayoutCommand { get; }
public ICommand GraphRefitCommand { get; }
public ICommand StopRenderingCommand { get; }
public ICommand ExportToDgmlCommand { get; }
public ICommand ExportToPlantUmlCommand { get; }
public ICommand ExportToSvgCommand { get; set; }
public ICommand FindCyclesCommand { get; }
public ICommand ShowDsmCommand { get; }
public ICommand AiAdviseCommand { get; }
public ICommand ExportToDsiCommand { get; }
public ICommand SearchCommand { get; }
public ICommand ExportToPngCommand { get; }
public bool IsLegendOpen
{
get;
set
{
if (field == value)
{
return;
}
field = value;
OnPropertyChanged();
if (value)
{
OpenLegendDialog();
}
else
{
_openedLegendDialog?.Close();
}
}
}
public ICommand ExecuteAnalyzerCommand { get; set; }
public ICommand SnapshotCommand { get; }
public ICommand ToggleMcpServerCommand { get; }
public ICommand CopyMcpSetupCommand { get; }
public bool IsMcpServerRunning => _mcpServerService.IsRunning;
/// <summary>
/// The button says what pressing it does, not what the state is - a label that reads "Running"
/// leaves the user guessing whether clicking starts or stops it.
/// </summary>
public string McpServerLabel =>
IsMcpServerRunning ? Strings.Mcp_Stop_Label : Strings.Mcp_Start_Label;
/// <summary>
/// Carries the endpoint while running. A user who wants to register the server needs the exact
/// URL, and reconstructing it from a settings file is where the first attempt usually goes
/// wrong.
/// </summary>
public string McpServerTooltip =>
IsMcpServerRunning
? string.Format(Strings.Mcp_Tooltip_Running, _mcpServerService.Endpoint)
: Strings.Mcp_Tooltip_Stopped;
public ICommand RestoreCommand { get; }
public TreeViewModel? TreeViewModel
{
get => _treeViewModel;
set
{
_treeViewModel = value;
OnPropertyChanged();
}
}
public AdvancedSearchViewModel? SearchViewModel
{
get => _searchViewModel;
set
{
_searchViewModel = value;
OnPropertyChanged();
}
}
/// <summary>The in-graph search (its box lives in the web tab tool bar).</summary>
public GraphSearchViewModel? GraphSearchViewModel
{
get;
set
{
field = value;
OnPropertyChanged();
}
}
public int SelectedRightTabIndex
{
get;
set
{
if (value == field)
{
return;
}
field = value;
OnPropertyChanged();
}
} = TabIndices.Right.WebView; // Web View is the start-up tab (so its WebView2 inits eagerly)
public bool IsCanvasHintsVisible
{
get;
set
{
if (field == value)
{
return;
}
field = value;
OnPropertyChanged();
}
} = true;
public ICommand OpenFilterDialogCommand { get; }
public ICommand OpenSettingsDialogCommand { get; }
public ObservableCollection<IStatistic> Statistics
{
set
{
field = value;
OnPropertyChanged();
}
get;
} = [];
public int SelectedLeftTabIndex
{
get;
set
{
if (value == field)
{
return;
}
field = value;
InfoPanelViewModel?.Hide(value != TabIndices.Left.InfoPanel);
OnPropertyChanged();
}
}
public List<IAnalyzer> Analyzers
{
get => _analyzerManager.All.ToList();
}
/// <summary>
/// Bound by the import menu, so a new importer needs no XAML change - exactly like Analyzers.
/// The C# solution import leads because it is the primary one and the split button's default.
/// </summary>
public List<ImportMenuEntry> ImportMenuEntries
{
get =>
[
new(Strings.ImportSolution_Label, Strings.Import_DialogTitle, LoadSolutionCommand, null),
.. _importerManager.All.Select(i => new ImportMenuEntry(i.Name, i.Description, ExecuteImporterCommand, i.Id))
];
}
public ICommand CopyBitmapToClipboardCommand { get; set; }
public bool IsGraphToolPanelVisible
{
get;
set
{
if (value == field)
{
return;
}
field = value;
OnPropertyChanged();
}
} = true;
public string Title
{
get
{
var title = Strings.AppTitle;
if (_projectService.RequiresNewFilePath)
{
// Don't show filename when no longer valid
title = title + " - " + "Refactored (model changed)";
}
else if (!string.IsNullOrEmpty(_projectService.CurrentFilePath))
{
title = title + " - " + _projectService.CurrentFilePath;
}
if (_projectService.IsDirty)
{
title += " *";
}
return title;
}
}
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>Raised when a dynamic tab should become the active one (new or updated result).</summary>
public event Action<ITabViewModel>? DynamicTabActivated;
private void OnBusyStateChanged(BusyState state)
{
IsLoading = state.IsLoading;
LoadMessage = state.Message;
}
private void OnAnalyzerDataChanged(object? sender, EventArgs e)
{
if (_analyzerManager.IsDirty())
{
_projectService.MarkDirty();
}
}
private void OnProjectLoaded(object? sender, ProjectLoadedEventArgs e)
{
RestoreProjectData(e.Data);
RefreshMru();
LoadMessage = string.Empty;
IsCanvasHintsVisible = false;
IsLoading = false;
}
private void OnProjectSaved(object? sender, string filePath)
{
RefreshMru();
}
private void OnDirtyStateChanged(object? sender, EventArgs e)
{
OnPropertyChanged(nameof(Title));
}
private void RefreshMru()
{
RecentFiles.Clear();
// Always a first browse command to avoid empty menu
RecentFiles.Add(new Mru(Strings.Browse, LoadProjectCommand) { ImageSource = "/Resources/load_project.png" });
foreach (var path in _userSettings.RecentFiles.Where(File.Exists).Select(f => new Mru(f, OpenRecentFileCommand)))
{
RecentFiles.Add(path);
}
}
private void OnCopyCanvasToClipboard()
{
// The graph lives in the web view; it produces a PNG (cy.png) and copies it.
_messaging.Publish(new ExportWebGraphRequest(WebGraphExportFormat.ClipboardPng));
}
private void OnExecuteAnalyzer(string id)
{
if (_codeGraph is null)
{
return;
}
_analyzerManager.GetAnalyzer(id).Analyze(_codeGraph);
}
private void OnShowGallery()
{
if (_graphViewModel is null || _gallery is null || _codeGraph is null)
{
return;
}
var editor = new GalleryEditor
{
Owner = Application.Current.MainWindow
};
var viewModel = new GalleryEditorViewModel(_gallery,
PreviewSession,
AddSession,
RemoveSession,
LoadSession);
var backup = _graphViewModel.GetSession();
var hasPreviewedSession = false;
editor.DataContext = viewModel;
editor.WindowStartupLocation = WindowStartupLocation.CenterScreen;
var result = editor.ShowDialog();
if (result is false && hasPreviewedSession)
{
// Restore original state if previews were shown
_graphViewModel.LoadSession(backup, false);
}
return;
void RemoveSession(GraphSession session)
{
_gallery.Sessions.Remove(session);
_projectService.MarkDirty();
}
void PreviewSession(GraphSession session)
{
_graphViewModel.LoadSession(session, false);
hasPreviewedSession = true;
}
void LoadSession(GraphSession session)
{
_graphViewModel.LoadSession(session, true);
editor.DialogResult = true;
}
GraphSession AddSession(string name)
{
var session = _graphViewModel.GetSession();
session.Name = name;
_gallery.AddSession(session);
_projectService.MarkDirty();
return session;
}
}
private void OpenLegendDialog()
{
if (_openedLegendDialog != null)
{
_openedLegendDialog.Activate();
return;
}
_openedLegendDialog = new LegendDialog
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
_openedLegendDialog.Closed += OnLegendDialogClosed;
_openedLegendDialog.Show();
}
private void OnLegendDialogClosed(object? sender, EventArgs e)
{
_openedLegendDialog!.Closed -= OnLegendDialogClosed;
_openedLegendDialog = null;
IsLegendOpen = false;
}
private void OnOpenFilterDialog()
{
var filterDialog = new FilterDialog(_projectExclusionFilters);
filterDialog.ShowDialog();
}
private void OnOpenSettingsDialog()
{
var settingsDialog = new SettingsDialog(_applicationSettings, _userSettings)
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
if (settingsDialog.ShowDialog() == true)
{
_applicationSettings = settingsDialog.AppSettings;
_userSettings = settingsDialog.UserPreferences;
SourceLocationNavigator.PreferredEditor = _userSettings.PreferredEditor;
SaveSettings();
}
}
private void SaveSettings()
{
try
{
var appSettingsPath = Path.Join(Directory.GetCurrentDirectory(), "appsettings.json");
_applicationSettings.Save(appSettingsPath);
_userSettings.Save();
}
catch (Exception ex)
{
_ui.ShowError($"{Strings.Settings_Save_Error} {ex.Message}");
}
}
private void Search()
{
try
{
IsLoading = true;
// The search is quite fast but updating the tree view requires some time
// So running this in a background task has no effect at all.
TreeViewModel?.ExecuteSearch();
}
catch (Exception ex)
{
_ui.ShowError(string.Format(Strings.OperationFailed_Message, ex.Message));
}
finally
{
IsLoading = false;
}
}
/// <summary>
/// Exports the whole project to dsi.
/// </summary>
private void OnExportToDsi()
{
_exporter.ToDsi(_codeGraph);
}
public void HandleShowTabularData(ShowTabularDataRequest tabularDataRequest)
{
ShowTabularDataTab(tabularDataRequest.Id, tabularDataRequest.Title, tabularDataRequest.Table);
}
public void HandleShowHierarchicalData(ShowHierarchicalDataRequest hierarchicalDataRequest)
{
ShowHierarchicalDataTab(hierarchicalDataRequest.Id, hierarchicalDataRequest.Title, hierarchicalDataRequest.Data, hierarchicalDataRequest.OpenMode);
}
/// <summary>
/// Creates a new dynamic tab for <paramref name="id" />, or - if one already exists - updates
/// it in place, so re-running the same analyzer replaces its own tab instead of piling up
/// duplicates. Either way the tab is brought to the front.
/// </summary>
private void ShowTabularDataTab(string id, string title, Table table)
{
var tab = DynamicTabs.OfType<DynamicTabViewModel>().FirstOrDefault(t => t.Id == id);
if (tab is null)
{
tab = new DynamicTabViewModel(id, title, table);
tab.CloseCommand = new WpfCommand(() => DynamicTabs.Remove(tab));
DynamicTabs.Add(tab);
}
else
{
tab.Title = title;
tab.Table = table;
}
DynamicTabActivated?.Invoke(tab);
}
/// <summary>
/// Same as <see cref="ShowTabularDataTab" />, but for tree-map style hierarchical results.
/// </summary>
private void ShowHierarchicalDataTab(string id, string title, HierarchicalDataContext data, RequestOpenMode openMode = RequestOpenMode.Normal)
{
var tab = DynamicTabs.OfType<HierarchicalTabViewModel>().FirstOrDefault(t => t.Id == id);
if (tab is null)
{
if (openMode == RequestOpenMode.UpdateOnly)
{
return;
}
tab = new HierarchicalTabViewModel(id, title, data);
tab.CloseCommand = new WpfCommand(() => DynamicTabs.Remove(tab));
DynamicTabs.Add(tab);
}
else
{
tab.Title = title;
tab.Data = data;
}
DynamicTabActivated?.Invoke(tab);
}
/// <summary>
/// Same as <see cref="ShowTabularDataTab" />, but for the dependency structure matrix. There is only ever
/// one of it — it always shows the whole graph — so the id is fixed.
/// </summary>
private void ShowDsmTab(string id, string title, DsmMainViewModel matrix)
{
var tab = DynamicTabs.OfType<DsmTabViewModel>().FirstOrDefault(t => t.Id == id);
if (tab is null)
{
tab = new DsmTabViewModel(id, title, matrix);
var dsmTab = tab;
tab.CloseCommand = new WpfCommand(() => DynamicTabs.Remove(dsmTab));
tab.OpenFileCommand = new WpfCommand(() => OnOpenDsmFile(dsmTab));
DynamicTabs.Add(tab);
}
else
{
tab.Title = title;
tab.Matrix = matrix;
}
DynamicTabActivated?.Invoke(tab);
}
/// <summary>
/// Builds the dependency structure matrix over the whole type graph and shows it in its own tab.
/// </summary>
private async void OnShowDsm()
{
if (_codeGraph is null)
{
return;
}
DsmMainViewModel? matrix = null;
var codeGraph = _codeGraph;
try
{
IsLoading = true;
LoadMessage = Strings.BuildingDsm_Message;
await Task.Run(() => { matrix = DsmMatrixFactory.Create(codeGraph); });
}
catch (Exception ex)
{
_ui.ShowError(string.Format(Strings.OperationFailed_Message, ex.Message));
}
finally
{
LoadMessage = string.Empty;
IsLoading = false;
}
if (matrix is not null)
{
ShowDsmTab("dsm_id", Strings.Dsm_TabHeader, matrix);
}
}
/// <summary>
/// Opens a DsmSuite model file (.dsm) or analyzer intermediate (.dsi) into the given DSM tab,
/// replacing its matrix. The file dialog and the loading indicator live here, which is why the tab
/// delegates back to this via its <see cref="DsmTabViewModel.OpenFileCommand" />.
/// </summary>
private async void OnOpenDsmFile(DsmTabViewModel tab)
{
var path = _ui.ShowOpenFileDialog(
"DSM/DSI files (*.dsm;*.dsi)|*.dsm;*.dsi|All files (*.*)|*.*",
"Open DSM or DSI file");
if (string.IsNullOrEmpty(path))
{
return;
}
DsmMainViewModel? matrix = null;
try
{
IsLoading = true;
LoadMessage = Strings.BuildingDsm_Message;
await Task.Run(() => { matrix = DsmMatrixFactory.CreateFromFile(path); });
}
catch (Exception ex)
{
_ui.ShowError(string.Format(Strings.OperationFailed_Message, ex.Message));
}
finally
{
LoadMessage = string.Empty;
IsLoading = false;
}
if (matrix is not null)
{
tab.Matrix = matrix;
tab.Title = System.IO.Path.GetFileName(path);
}
}
private async void OnFindCycles()
{
if (_codeGraph is null)
{
return;
}
List<CycleGroup>? cycleGroups = null;
try
{
IsLoading = true;
LoadMessage = Strings.SearchingCycles_Message;
// The groups come back named after their most central element (see CycleFinder).
await Task.Run(() => { cycleGroups = CycleFinder.FindCycleGroups(_codeGraph); });
}
catch (Exception ex)
{
_ui.ShowError(string.Format(Strings.OperationFailed_Message, ex.Message));
}
finally
{
LoadMessage = string.Empty;
IsLoading = false;
}
if (cycleGroups != null)
{
_messaging.Publish(new CycleCalculationComplete(cycleGroups));
SelectedRightTabIndex = TabIndices.Right.Cycles;
}
}
private async void OnAiAdvise()
{
if (_graphViewModel is null)
{
return;
}
var endpoint = _userSettings.AiEndpoint;
if (string.IsNullOrWhiteSpace(endpoint) || !AiCredentialStorage.HasApiKey())
{
ToastManager.ShowWarning(Strings.AiAdvisor_NoEndpoint);
return;
}
var currentGraph = _graphViewModel.GetGraph();
if (currentGraph.Nodes.Count == 0)
{
return;
}
List<CycleGroup>? cycleGroups = null;
try
{
IsLoading = true;
LoadMessage = Strings.AiAdvisor_Analyzing;
await Task.Run(() => { cycleGroups = CycleFinder.FindCycleGroups(currentGraph); });
}
catch (Exception ex)
{
_ui.ShowError(string.Format(Strings.OperationFailed_Message, ex.Message));
return;
}
finally
{
LoadMessage = string.Empty;
IsLoading = false;
}
if (cycleGroups is not { Count: > 0 })
{
ToastManager.ShowWarning(Strings.AiAdvisor_NoCycles);
return;
}
string? response;
try
{
IsLoading = true;
LoadMessage = Strings.AiAdvisor_Querying;
var apiKey = AiCredentialStorage.LoadApiKey();
response = await _aiAdvisorService.GetCycleAdviceAsync(
cycleGroups[0], endpoint, apiKey, _userSettings.AiModel);
}
catch (AiClientException ex)
{
_ui.ShowError(ex.Message);
return;
}
catch (Exception ex)
{
_ui.ShowError(string.Format(Strings.OperationFailed_Message, ex.Message));
return;
}
finally
{
LoadMessage = string.Empty;
IsLoading = false;
}
if (!string.IsNullOrWhiteSpace(response))
{
AiAdvisorWindow.ShowAdvice(response, _ui);
}
}
private void OnGraphLayout()
{
// Full relayout: the web adapter re-runs its layout through the bus.
_messaging.Publish(new RelayoutGraphRequest());
}
private void OnGraphRefit()
{
// Recompute size and fit the view without re-running the layout. Web-only for now
_messaging.Publish(new RefitGraphRequest());
}
private void OnStopRendering()
{
// Abort a runaway render: the web adapter terminates its render process and reloads.
_messaging.Publish(new CancelWebRenderRequest());
}