-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
6390 lines (5723 loc) · 245 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
6390 lines (5723 loc) · 245 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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using DanteConfigEditor.Application;
using DanteConfigEditor.Application.Navigation;
using DanteConfigEditor.Application.Patch;
using DanteConfigEditor.Domain.Projects;
using DanteConfigEditor.Domain.Validation;
using DanteConfigEditor.Infrastructure.Migration;
using DanteConfigEditor.Models;
using DanteConfigEditor.Services;
using Microsoft.Win32;
namespace DanteConfigEditor;
public partial class MainWindow : Window
{
private enum AtomicPanelStage
{
Safe,
CoverOpen,
Armed,
Locked,
Fired
}
private string AllSendersItem => T("Filter.AllSenders");
private string AllReceiversItem => T("Filter.AllReceivers");
// Collections liées directement aux listes WPF. Quand on les modifie,
// l'interface se met à jour sans recréer toute la fenêtre.
private readonly ObservableCollection<DeviceRow> _deviceRows = [];
private readonly ObservableCollection<DanteSubscription> _patchRows = [];
private readonly ObservableCollection<string> _logs = [];
private readonly ObservableCollection<GlobalSearchResult> _searchResults = [];
private readonly ObservableCollection<ValidationCenterRow> _healthIssues = [];
private readonly ObservableCollection<PendingPatchRow> _pendingPatchRows = [];
private readonly HashSet<string> _lockedDeviceNames = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _warningDeviceNames = new(StringComparer.OrdinalIgnoreCase);
private readonly DispatcherTimer _recoveryTimer;
private readonly SupportReminderSettingsService _supportReminderSettings = new();
private readonly WorkspaceNavigationService _workspaceNavigation = new();
private readonly ProjectSession _projectSession = new();
private CancellationTokenSource? _recoveryWriteCancellation;
private string? _selectedWarningKey;
private DateTime? _lastSuccessfulSaveAt;
private bool _navigationExpanded = true;
private bool _inspectorExpanded = true;
private bool _deviceListExpanded;
private bool _synchronizingDeviceContext;
private string? _selectedDeviceContextStableIdentity;
private readonly LatencyChoice[] _latencies =
[
new("250", "0,25 ms"),
new("1000", "1 ms"),
new("2000", "2 ms"),
new("5000", "5 ms")
];
private readonly SampleRateChoice[] _sampleRates =
[
new("44100", "44,1 kHz"),
new("48000", "48 kHz"),
new("88200", "88,2 kHz"),
new("96000", "96 kHz"),
new("176400", "176,4 kHz"),
new("192000", "192 kHz")
];
private readonly EncodingChoice[] _encodings =
[
new("16", "16 bit"),
new("24", "24 bit"),
new("32", "32 bit")
];
private readonly string[] _patchViewModeKeys = [PatchViewMode.SimpleKey, PatchViewMode.ExpertKey];
private readonly string[] _patchStateFilterKeys =
[
"Filter.AllRx",
"Filter.ActivePatches",
"Filter.FreeRx",
"Filter.LocalPatches",
"Filter.MissingTxDevices",
"Filter.MissingTxChannels",
"Filter.Warnings",
"Filter.Conflicts",
"Filter.Modified"
];
private readonly string[] _healthFilterKeys =
[
"Filter.All",
"Filter.Info",
"Filter.HealthWarnings",
"Filter.Errors",
"Filter.Patches",
"Filter.Devices",
"Filter.Clock",
"Filter.Network",
"Filter.XmlCompatibility"
];
private readonly string[] _patchbookScopeKeys = ["Filter.AllRx", "Filter.ActivePatches", "Filter.WarningsConflicts"];
private readonly string[] _deviceFilterKeys =
[
"DeviceFilter.All",
"DeviceFilter.Locked",
"DeviceFilter.StaticIp",
"DeviceFilter.PreferredMaster",
"DeviceFilter.Redundant",
"DeviceFilter.Daisychain",
"DeviceFilter.NoTx",
"DeviceFilter.NoRx",
"DeviceFilter.Modified",
"DeviceFilter.WarningSelection",
"DeviceFilter.SampleRateDifferent",
"DeviceFilter.EncodingDifferent"
];
private readonly string[] _targetScopeKeys =
[
"Target.AllUnlocked",
"Target.SelectedUnlocked",
"Target.FilteredUnlocked"
];
private DanteProject? _project;
private DanteProject? _easyPatchProject;
private PatchWorkspaceView? _easyPatchWorkspace;
private DanteProject? _detachedPatchProject;
private PatchWorkspaceWindow? _detachedPatchWindow;
private UnifiedPatchSession? _unifiedPatchSession;
private PatchWorkspaceDisplayMode _patchWorkspaceDisplayMode = PatchWorkspaceDisplayMode.Matrix;
private AtomicPanelStage _atomicPanelStage = AtomicPanelStage.Safe;
private UiLanguage _language = UiLanguage.French;
private bool _editModeEnabled;
// Évite que les changements de sélection déclenchés par RefreshAll relancent
// eux-mêmes des actions utilisateur.
private bool _refreshingUi;
private bool _loadingThemePreference;
private bool _committingPatchInlineRename;
private string? _patchSeriesDeviceName;
private DanteChannelKind? _patchSeriesKind;
private int[] _patchSeriesSeeds = [];
private sealed record ChannelChoice(DanteChannelKind Kind, int Index, string Name)
{
public override string ToString()
{
return $"{Index} - {Name}";
}
}
private sealed record TxChannelChoice(string DeviceName, int DanteId, string ChannelName)
{
public override string ToString()
{
return $"{DanteId:000} - {ChannelName}";
}
}
private sealed record LatencyChoice(string XmlValue, string Display)
{
public override string ToString()
{
return Display;
}
}
private sealed record SampleRateChoice(string XmlValue, string Display)
{
public override string ToString()
{
return Display;
}
}
private sealed record EncodingChoice(string XmlValue, string Display)
{
public override string ToString()
{
return Display;
}
}
private sealed record LocalizedOption(string Key, string Display)
{
public override string ToString()
{
return Display;
}
}
private sealed record ProfileChoice(DeviceProfile Profile, string Display)
{
public override string ToString()
{
return Display;
}
}
private enum PatchWorkspaceDisplayMode
{
Matrix,
Easy,
List,
Device,
Pending
}
private sealed record PendingPatchRow(
string RxDeviceName,
int RxDanteId,
string OriginalSource,
string DesiredSource,
string ActionLabel);
private sealed record GlobalSearchResult(
string Kind,
string Label,
string? DeviceName = null,
DanteChannelKind? ChannelKind = null,
int? ChannelIndex = null,
string? RxDevice = null,
int? RxIndex = null)
{
public override string ToString()
{
return $"{Kind} - {Label}";
}
}
private sealed class DeviceRow
{
public DeviceRow(DanteDevice device, bool isLocked, bool isModified, bool english)
{
Device = device;
IsLocked = isLocked;
IsModified = isModified;
PreferredMasterToolTip = device.SupportsPreferredMaster
? english
? "Enable or disable Preferred Master for this device."
: "Active ou désactive Preferred Master pour cette machine."
: english
? "Unavailable: this Dante role does not expose the preferred_master setting."
: "Indisponible : ce rôle Dante n'expose pas le paramètre preferred_master.";
}
public DanteDevice Device { get; }
public bool IsLocked { get; set; }
public bool IsModified { get; }
public string Name => Device.Name;
public string FriendlyName => Device.FriendlyName;
public string NetworkMode => Device.NetworkMode;
public string LatencyDisplay => Device.LatencyDisplay;
public string SampleRateDisplay => Device.SampleRateDisplay;
public string EncodingDisplay => Device.EncodingDisplay;
public string IpModeDisplay => Device.IpModeDisplay;
public bool PreferredMaster => Device.PreferredMaster;
public bool SupportsPreferredMaster => Device.SupportsPreferredMaster;
public string PreferredMasterToolTip { get; }
public int TxCount => Device.TxCount;
public int RxCount => Device.RxCount;
}
private sealed record TargetDeviceSet(DanteDevice[] Devices, int LockedSkippedCount, string ScopeLabel);
public MainWindow()
{
InitializeComponent();
_workspaceNavigation.Changed += WorkspaceNavigation_Changed;
_recoveryTimer = new DispatcherTimer(DispatcherPriority.Background)
{
Interval = TimeSpan.FromMilliseconds(750)
};
_recoveryTimer.Tick += RecoveryTimer_Tick;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Initialisation des sources de données utilisées par les contrôles.
MigrateV36Settings();
_language = LanguageSettingsService.Load();
// Les trois zones principales repartent ouvertes à chaque lancement.
// Un repli reste volontaire et limité à la session courante.
ConfigurationEditorsGrid.Visibility = Visibility.Visible;
SessionRecoveryService.CleanupOld(TimeSpan.FromDays(30));
SetupLanguageComboBox();
LatencyComboBox.ItemsSource = _latencies;
GlobalLatencyComboBox.ItemsSource = _latencies;
GlobalSampleRateComboBox.ItemsSource = _sampleRates;
GlobalEncodingComboBox.ItemsSource = _encodings;
ChannelKindComboBox.ItemsSource = new[] { "TX", "RX" };
ChannelKindComboBox.SelectedItem = "TX";
RefreshLocalizedOptionSources();
RefreshQuickProfileOptions();
PatchGrid.ItemsSource = _patchRows;
DeviceGrid.ItemsSource = _deviceRows;
LogListBox.ItemsSource = _logs;
GlobalSearchListBox.ItemsSource = _searchResults;
HealthIssuesGrid.ItemsSource = _healthIssues;
SynopticDeviceGrid.ItemsSource = _synopticRows;
PendingPatchGrid.ItemsSource = _pendingPatchRows;
GlobalDaisychainRadioButton.IsChecked = true;
DaisychainRadioButton.IsChecked = true;
bool useLightTheme = ThemeSettingsService.LoadUseLightTheme();
_loadingThemePreference = true;
ThemeToggleButton.IsChecked = useLightTheme;
_loadingThemePreference = false;
SetTheme(useLightTheme);
DarkThemeMenuItem.IsChecked = !useLightTheme;
ApplyLanguageToInterface();
ResetAtomicControlPanel();
SetNavigationExpanded(true);
SetInspectorExpanded(true);
SetDeviceListExpanded(false);
RefreshRecentFiles();
RefreshAll();
HomeNavigationButton.IsChecked = true;
ApplyWorkspaceSection(WorkspaceSection.Home);
UpdateResponsiveConfigurationLayout(ActualWidth, ActualHeight);
InitializeSupportReminder();
_ = CheckForApplicationUpdateAsync(silentWhenCurrent: true);
}
private static void MigrateV36Settings()
{
try
{
_ = V36SettingsMigrationService.CreateDefault().Migrate();
}
catch (Exception ex) when (ex is IOException
or UnauthorizedAccessException
or InvalidDataException)
{
DiagnosticLogService.Default.Write(
"Migration",
"La copie des réglages V3.6 vers 2026.1 a échoué.",
ex);
}
}
private void OpenButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new()
{
Filter = T("Dialog.XmlFilter"),
Title = T("Dialog.OpenXmlTitle")
};
if (dialog.ShowDialog(this) != true)
{
return;
}
LoadProjectFromPath(dialog.FileName);
}
private void NewProjectButton_Click(object sender, RoutedEventArgs e)
{
if (_project?.IsModified == true)
{
MessageBoxResult abandon = MessageBox.Show(
this,
_language == UiLanguage.English
? "The current project has unsaved changes. Create another project without saving them?"
: "Le projet courant contient des changements non enregistrés. Créer un autre projet sans les sauvegarder ?",
T("Dialog.ConfirmTitle"),
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (abandon != MessageBoxResult.Yes)
{
return;
}
}
NewProjectWindow window = new(
_language,
ThemeToggleButton.IsChecked == true)
{
Owner = this
};
if (window.ShowDialog() != true || window.Result is null)
{
return;
}
try
{
NewProjectFormResult form = window.Result;
DanteProject created;
if (form.TemplateId.HasValue)
{
MachineTemplatePackage template = new MachineBankRepository(
form.BankPath).Load(form.TemplateId.Value);
created = DanteProject.CreateNewFromTemplate(
form.DestinationPath,
form.ProjectName,
form.Description,
template,
form.TemplateOptions
?? throw new InvalidOperationException(
"Les options d'instance du modèle sont absentes."));
}
else
{
created = DanteProject.CreateNew(
form.DestinationPath,
new NewProjectOptions
{
ProjectName = form.ProjectName,
Description = form.Description,
Machines =
[
new NewCustomMachineDefinition
{
Name = form.DeviceName,
TxCount = form.TxCount,
RxCount = form.RxCount,
SampleRate = form.SampleRate,
Encoding = form.Encoding,
UnicastLatency = form.UnicastLatency
}
]
});
}
created.SaveAs(form.DestinationPath);
_project = created;
_editModeEnabled = true;
_logs.Clear();
RecentFilesService.Add(form.DestinationPath);
RefreshRecentFiles();
AddLog(_language == UiLanguage.English
? $"Experimental project created: {form.DestinationPath}"
: $"Projet expérimental créé : {form.DestinationPath}");
RefreshAll();
SetStatus(_language == UiLanguage.English
? "Experimental project created. Validate it in Dante Controller."
: "Projet expérimental créé. Validez-le dans Dante Controller.");
MessageBox.Show(
this,
_language == UiLanguage.English
? "The XML was created and reloaded by DCE. This validates its internal structure only. "
+ "Import it in Dante Controller before production use."
: "Le XML a été créé puis rechargé par DCE. Cela valide seulement sa structure interne. "
+ "Importez-le dans Dante Controller avant tout usage en production.",
_language == UiLanguage.English
? "Manual validation required"
: "Validation manuelle obligatoire",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
catch (Exception ex)
{
ShowError(
_language == UiLanguage.English
? "Unable to create project"
: "Création du projet impossible",
ex);
}
}
private void MergeXmlButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded())
{
return;
}
OpenFileDialog dialog = new()
{
Filter = T("Dialog.XmlFilter"),
Title = T("Dialog.MergeXmlTitle")
};
if (dialog.ShowDialog(this) != true)
{
return;
}
IReadOnlyDictionary<string, string> renameMap = new Dictionary<string, string>();
IReadOnlyList<string> duplicateNames;
try
{
duplicateNames = _project!.FindDuplicateDeviceNamesInXml(dialog.FileName);
}
catch (Exception ex)
{
ShowError(T("Dialog.OpenFailedTitle"), ex);
return;
}
if (duplicateNames.Count > 0)
{
DuplicateDeviceRenameWindow duplicateWindow = new(
_language,
duplicateNames,
suffix => _project!.BuildAutomaticDuplicateRenameMap(dialog.FileName, suffix))
{
Owner = this
};
if (duplicateWindow.ShowDialog() != true || duplicateWindow.Choice == DuplicateDeviceImportChoice.Cancel)
{
return;
}
renameMap = duplicateWindow.RenameMap;
}
else
{
MessageBoxResult confirm = MessageBox.Show(this, T("Dialog.MergeXmlWarning"), T("Dialog.ConfirmTitle"), MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (confirm != MessageBoxResult.Yes)
{
return;
}
}
DanteMergeResult? mergeResult = null;
RunProjectAction(
T("Action.XmlMerged"),
() => mergeResult = _project!.MergeDevicesFromXml(dialog.FileName, renameMap));
if (mergeResult is not null)
{
AddLog(BuildMergeResultLog(dialog.FileName, mergeResult));
SetStatus(BuildMergeResultStatus(mergeResult));
}
}
private void OpenRecentButton_Click(object sender, RoutedEventArgs e)
{
if (RecentFilesComboBox.SelectedItem is not string path || string.IsNullOrWhiteSpace(path))
{
ShowError(T("Dialog.NoRecentFileTitle"), T("Dialog.NoRecentFileMessage"));
return;
}
if (!File.Exists(path))
{
ShowError(T("Dialog.FileMissingTitle"), T("Dialog.FileMissingMessage"));
RefreshRecentFiles();
return;
}
LoadProjectFromPath(path);
}
public void LoadProjectFromPath(string path)
{
try
{
// DanteProject contient toute la logique XML. La fenêtre ne garde que
// l'état d'affichage et les actions utilisateur.
RecoveryCandidate? recovery = SessionRecoveryService.Find(path);
bool recovered = false;
DanteProject? loadedProject = null;
if (recovery is not null)
{
string sourceWarning = recovery.SourceMatches
? string.Empty
: Environment.NewLine + Environment.NewLine + T("Dialog.RecoverySourceChanged");
MessageBoxResult restore = MessageBox.Show(
this,
Tf("Dialog.RecoveryFound", recovery.SavedAtUtc.ToLocalTime()) + sourceWarning,
T("Dialog.RecoveryTitle"),
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (restore == MessageBoxResult.Yes)
{
loadedProject = DanteProject.LoadRecovered(path, recovery.RecoveryXmlPath);
recovered = true;
}
else
{
SessionRecoveryService.Delete(path);
}
}
_project = loadedProject ?? DanteProject.Load(path);
_editModeEnabled = true;
_logs.Clear();
RecentFilesService.Add(path);
RefreshRecentFiles();
AddLog(Tf("Log.FileLoaded", path));
if (recovered)
{
AddLog(T("Log.RecoveryRestored"));
}
RefreshAll();
SetStatus(T(recovered ? "Status.RecoveryRestored" : "Status.FileLoaded"));
}
catch (Exception ex)
{
ShowError(T("Dialog.OpenFailedTitle"), ex);
}
}
private void ActivateEditButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded())
{
return;
}
MessageBoxResult confirm = MessageBox.Show(
this,
"Vous allez activer l'édition du fichier XML hors ligne. Travaillez toujours sur une copie et vérifiez le fichier final dans Dante Controller avant production.",
T("Status.ActivateEditButton"),
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (confirm != MessageBoxResult.Yes)
{
return;
}
_editModeEnabled = true;
AddLog(T("Log.EditEnabled"));
RefreshAll();
SetStatus(T("Status.EditEnabled"));
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
// Un XML Dante ouvert reste protégé : le premier enregistrement passe
// par Enregistrer sous afin de ne jamais écraser silencieusement la source.
SaveAsButton_Click(sender, e);
}
private void SaveAsButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded())
{
return;
}
if (!EnsureEditMode())
{
return;
}
// La validation est relancée juste avant la sauvegarde pour éviter de
// créer un fichier final manifestement invalide.
DanteValidationResult validation = _project!.Validate();
if (validation.HasErrors)
{
ShowError(T("Dialog.SaveImpossibleTitle"), validation.ToDisplayText(_language));
return;
}
SaveFileDialog dialog = new()
{
Filter = T("Dialog.XmlFilter"),
Title = T("Dialog.SaveXmlTitle"),
FileName = Path.GetFileName(SafeFileService.BuildDefaultSavePath(_project.OriginalFilePath)),
InitialDirectory = Path.GetDirectoryName(_project.OriginalFilePath)
};
if (dialog.ShowDialog(this) != true)
{
return;
}
if (IsOriginalProjectPath(dialog.FileName))
{
ShowError(
T("Dialog.ChooseAnotherNameTitle"),
T("Dialog.ChooseAnotherNameMessage"));
return;
}
if (File.Exists(dialog.FileName))
{
MessageBoxResult overwrite = MessageBox.Show(
this,
T("Dialog.OverwriteMessage"),
T("Dialog.ConfirmTitle"),
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (overwrite != MessageBoxResult.Yes)
{
return;
}
}
string summary = BuildLocalizedSaveSummary();
MessageBoxResult confirm = MessageBox.Show(
this,
summary + Environment.NewLine + Environment.NewLine + T("Dialog.OriginalBackupMessage"),
T("Dialog.SaveSummaryTitle"),
MessageBoxButton.YesNo,
validation.HasWarnings ? MessageBoxImage.Warning : MessageBoxImage.Information);
if (confirm != MessageBoxResult.Yes)
{
return;
}
try
{
CancelPendingRecoveryWrite();
string previousFilePath = _project.OriginalFilePath;
string backupPath = _project.SaveAs(dialog.FileName);
SessionRecoveryService.Delete(previousFilePath);
SessionRecoveryService.Delete(_project.OriginalFilePath);
RecentFilesService.Add(_project.OriginalFilePath);
AddLog(Tf("Log.OriginalBackupCreated", backupPath));
AddLog(Tf("Log.FileSaved", dialog.FileName));
_lastSuccessfulSaveAt = DateTime.Now;
_projectSession.MarkSaved();
RefreshAll();
SetStatus(T("Status.FileSaved"));
}
catch (Exception ex)
{
ShowError(T("Dialog.SaveErrorTitle"), ex);
}
}
private void RevertButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded())
{
return;
}
if (_project!.IsModified)
{
MessageBoxResult confirm = MessageBox.Show(
this,
T("Dialog.RevertMessage"),
T("Dialog.RevertTitle"),
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (confirm != MessageBoxResult.Yes)
{
return;
}
}
try
{
string path = _project.OriginalFilePath;
SessionRecoveryService.Delete(path);
_project = DanteProject.Load(path);
AddLog(T("Log.ReloadOriginal"));
RefreshAll();
SetStatus(T("Log.ReloadOriginal"));
}
catch (Exception ex)
{
ShowError(T("Dialog.ReloadErrorTitle"), ex);
}
}
private void UndoLastButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded())
{
return;
}
try
{
string label = _projectSession.CommandDispatcher.CanUndo
? _projectSession.CommandDispatcher.Undo()
: _project!.UndoLastChange();
AddLog(Tf("Log.ActionUndone", label));
RefreshAll();
ScheduleRecoverySnapshot();
SetStatus(T("Status.LastActionUndone"));
}
catch (Exception ex)
{
ShowError(T("Dialog.UndoErrorTitle"), ex);
}
}
private void DeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_refreshingUi || _synchronizingDeviceContext || _project is null)
{
return;
}
DanteDevice? device = _project.FindDevice(DeviceComboBox.SelectedItem as string);
if (device is null)
{
return;
}
SynchronizeSelectedDeviceContext(device.Name, synchronizeGrid: true);
}
private void ApplyDeviceSettingsButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded())
{
return;
}
string originalName = SelectedDeviceName();
DanteDevice device = _project!.FindDevice(originalName) ?? throw new InvalidOperationException("Device introuvable.");
string newName = NewNameTextBox.Text.Trim();
bool isRedundant = RedundantRadioButton.IsChecked == true;
string latency = SelectedLatencyXmlValue(LatencyComboBox);
bool preferredMaster = PreferredMasterCheckBox.IsChecked == true;
bool latencyChanged = device.SupportsLatency
&& !string.Equals(device.Latency, latency, StringComparison.OrdinalIgnoreCase);
bool hasChanges = !string.Equals(device.Name, newName, StringComparison.Ordinal)
|| device.SupportsNetworkMode && device.IsRedundant != isRedundant
|| latencyChanged
|| device.SupportsPreferredMaster && device.PreferredMaster != preferredMaster;
if (!hasChanges)
{
SetStatus(T("Status.NoDeviceSettingsChanged"));
return;
}
RunProjectAction(
T("Action.DeviceSettingsUpdated"),
() => _project!.ApplyBatch(_ => ApplySelectedDeviceSettings(originalName, newName, isRedundant, latency, preferredMaster)),
latencyChanged ? T("Dialog.LatencyWarning") : null);
}
private void ResetDevicePatchesButton_Click(object sender, RoutedEventArgs e)
{
string deviceName = SelectedDeviceName();
RunProjectAction(
T("Action.DevicePatchesReset"),
() => _project!.ResetDevicePatches(deviceName),
Tf("Dialog.ResetDevicePatchesWarning", deviceName));
}
private void ResetDeviceRxPatchesButton_Click(object sender, RoutedEventArgs e)
{
string deviceName = SelectedDeviceName();
RunProjectAction(
T("Action.DeviceRxPatchesReset"),
() => _project!.ResetDeviceRxPatches(deviceName),
$"Les entrées RX de la machine '{deviceName}' seront déconnectées. Continuer ?");
}
private void ResetDeviceTxPatchesButton_Click(object sender, RoutedEventArgs e)
{
string deviceName = SelectedDeviceName();
RunProjectAction(
T("Action.DeviceTxPatchesReset"),
() => _project!.ResetDeviceTxPatches(deviceName),
$"Tous les patchs qui utilisent les TX de la machine '{deviceName}' seront supprimés. Continuer ?");
}
private void ApplySelectedDeviceSettings(
string originalName,
string newName,
bool isRedundant,
string latency,
bool preferredMaster)
{
DanteDevice originalDevice = _project!.FindDevice(originalName) ?? throw new InvalidOperationException("Device introuvable.");
string currentName = originalDevice.Name;
// Une seule validation utilisateur applique tous les champs visibles de la machine.
if (!string.Equals(originalDevice.Name, newName, StringComparison.Ordinal))
{
_project.RenameDevice(currentName, newName);
currentName = newName;
}
if (originalDevice.SupportsNetworkMode
&& originalDevice.IsRedundant != isRedundant)
{
_project.SetNetworkMode(currentName, isRedundant);
}
if (originalDevice.SupportsLatency
&& !string.Equals(originalDevice.Latency, latency, StringComparison.OrdinalIgnoreCase))
{
_project.SetLatency(currentName, latency);
}
if (originalDevice.SupportsPreferredMaster
&& originalDevice.PreferredMaster != preferredMaster)
{
_project.SetPreferredMaster(currentName, preferredMaster);
}
}
private void DeleteDeviceButton_Click(object sender, RoutedEventArgs e)
{
string deviceName = SelectedDeviceName();
RunProjectAction(
T("Action.DeviceDeleted"),
() => _project!.DeleteDevice(deviceName),
Tf("Dialog.DeleteDeviceWarning", deviceName));
}
private void OpenMachineBankButton_Click(object sender, RoutedEventArgs e)
{
OpenMachineBankWindow(null);
}
private void ManageMachineBankButton_Click(object sender, RoutedEventArgs e)
{
OpenMachineBankWindow(null);
}
private void AddDeviceFromBankButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded() || !EnsureEditMode())
{
return;
}
OpenMachineBankWindow(null);
}
private void OpenMachineBankWindow(string? bankPath)
{
MachineBankWindow window = new(
_language,
ThemeToggleButton.IsChecked == true,
_project?.Devices.Select(device => device.Name) ?? [],
_project is not null && _editModeEnabled,
bankPath,
AddDevicesFromBank)
{
Owner = this
};
window.ShowDialog();
}
private IReadOnlyList<string>? AddDevicesFromBank(
MachineTemplatePackage package,
MachineInstanceBatchRequest request)
{
if (_project is null)
{
return null;
}
IReadOnlyList<MachineCloneResult>? results = null;
string actionLabel = request.Quantity == 1
? (_language == UiLanguage.English
? $"Device added from bank: {request.Options.NewName}"
: $"Machine ajoutée depuis la banque : {request.Options.NewName}")
: (_language == UiLanguage.English
? $"{request.Quantity} devices added from bank"
: $"{request.Quantity} machines ajoutées depuis la banque");
bool completed = RunProjectAction(
actionLabel,
() => results = _project.AddDevicesFromTemplate(package, request));
if (!completed || results is null)
{
return null;
}
string[] names = results.Select(result => result.NewName).ToArray();
DeviceComboBox.SelectedItem = names[^1];
return names;
}
private void RedoButton_Click(object sender, RoutedEventArgs e)
{
if (!EnsureProjectLoaded() || !_projectSession.CommandDispatcher.CanRedo)
{
return;
}
try
{
string commandId = _projectSession.CommandDispatcher.Redo();
AddLog(_language == UiLanguage.English
? $"Action redone: {commandId}"