-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatchWorkspaceView.xaml.cs
More file actions
3450 lines (3109 loc) · 132 KB
/
Copy pathPatchWorkspaceView.xaml.cs
File metadata and controls
3450 lines (3109 loc) · 132 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.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using DanteConfigEditor.Models;
using DanteConfigEditor.Services;
namespace DanteConfigEditor;
public sealed class InlineChannelNavigationRequestEventArgs(
DanteChannelKind kind,
int danteId,
bool matrix) : EventArgs
{
public DanteChannelKind Kind { get; } = kind;
public int DanteId { get; } = danteId;
public bool Matrix { get; } = matrix;
}
public sealed class DirectPatchRequestEventArgs(
IReadOnlyList<PatchEditRequest> edits) : EventArgs
{
public IReadOnlyList<PatchEditRequest> Edits { get; } =
edits ?? throw new ArgumentNullException(nameof(edits));
}
public sealed class PatchDeviceFocusChangedEventArgs(
string deviceName,
DanteChannelKind kind) : EventArgs
{
public string DeviceName { get; } = deviceName;
public DanteChannelKind Kind { get; } = kind;
}
public sealed class PatchDetachRequestedEventArgs(
string? txDeviceName,
string? rxDeviceName,
bool warnOnExistingPatch) : EventArgs
{
public string? TxDeviceName { get; } = txDeviceName;
public string? RxDeviceName { get; } = rxDeviceName;
public bool WarnOnExistingPatch { get; } = warnOnExistingPatch;
}
public sealed record PatchMatrixOneToOneState(
string CountText,
string? TxDeviceName,
int? TxDanteId,
string? RxDeviceName,
int? RxDanteId);
public partial class PatchWorkspaceView : UserControl
{
private const double MinimumMatrixZoom = 0.5;
private const double MaximumMatrixZoom = 2.0;
private const double MatrixZoomStep = 0.1;
private readonly UiLanguage _language;
private readonly DanteProject _project;
private IPatchWorkspaceSession _session;
private PatchNavigationService _navigation;
private readonly bool _returnEditsOnly;
private readonly bool _lockRxDeviceSelection;
private readonly bool _embedded;
private readonly bool _allowDetach;
private readonly Func<string, DanteChannelKind, int, string, bool>? _renameChannelAction;
private readonly Func<string, DanteChannelKind, IReadOnlyList<int>, int, bool>? _extendChannelSeriesAction;
private readonly HashSet<string> _ambiguousSourceNames = new(StringComparer.OrdinalIgnoreCase);
private readonly List<ToggleButton> _matrixGestureHighlights = [];
private readonly ObservableCollection<PatchRxListItem> _rxRows = [];
private readonly ObservableCollection<PatchMatrixRow> _matrixRows = [];
private IReadOnlyList<PatchSourceDescriptor> _visibleSources = [];
private IReadOnlyList<PatchTargetDescriptor> _visibleTargets = [];
private PatchMatrixCell? _matrixGestureStart;
private PatchMatrixCell? _matrixGestureCurrent;
private PatchMatrixCell? _matrixOneToOneStart;
private bool _matrixGestureActive;
private string? _channelSeriesDeviceName;
private DanteChannelKind? _channelSeriesKind;
private int[] _channelSeriesSeeds = [];
private string? _matrixSeriesDeviceName;
private DanteChannelKind? _matrixSeriesKind;
private int[] _matrixSeriesSeeds = [];
private double _matrixZoom = 1.0;
private bool _initializing = true;
private ToggleButton? _navigationHighlightButton;
private int _navigationHighlightGeneration;
public PatchWorkspaceView(
UiLanguage language,
DanteProject project,
bool useLightTheme,
string? initialTxDeviceName = null,
string? initialRxDeviceName = null,
IEnumerable<PatchEditRequest>? initialEdits = null,
bool returnEditsOnly = false,
bool lockRxDeviceSelection = false,
bool embedded = false,
Func<string, DanteChannelKind, int, string, bool>? renameChannelAction = null,
Func<string, DanteChannelKind, IReadOnlyList<int>, int, bool>? extendChannelSeriesAction = null,
bool startInAssignmentMode = false,
bool warnOnExistingPatch = true,
IPatchWorkspaceSession? sharedSession = null,
bool allowDetach = true)
{
InitializeComponent();
// La grille est le mode principal d'Easy patch. La sélection par plage
// reste immédiatement accessible dans le second onglet.
PatchModeTabControl.Items.Remove(MatrixTab);
PatchModeTabControl.Items.Insert(0, MatrixTab);
if (startInAssignmentMode)
{
AssignmentTab.IsSelected = true;
}
else
{
MatrixTab.IsSelected = true;
}
_language = language;
_project = project ?? throw new ArgumentNullException(nameof(project));
_session = sharedSession
?? new PatchWorkspaceSession(project.PatchMatrix.Subscriptions, initialEdits);
_navigation = new PatchNavigationService(project, _session);
_returnEditsOnly = returnEditsOnly;
_lockRxDeviceSelection = lockRxDeviceSelection;
_embedded = embedded;
_allowDetach = allowDetach;
_renameChannelAction = renameChannelAction;
_extendChannelSeriesAction = extendChannelSeriesAction;
WarnOnExistingPatchCheckBox.IsChecked = warnOnExistingPatch;
RxChannelListBox.ItemsSource = _rxRows;
MatrixGrid.ItemsSource = _matrixRows;
ConfigureWorkflowPresentation();
ApplyTheme(useLightTheme);
ApplyLanguage();
PopulateDeviceSelectors(initialTxDeviceName, initialRxDeviceName);
_initializing = false;
RefreshSourceChannelsAndMatrixColumns();
RefreshTargetRows();
}
public IReadOnlyList<PatchEditRequest> Edits => _session.Edits;
public bool HasChanges => _session.HasChanges;
public bool CanRenameChannels => _renameChannelAction is not null;
public bool IsAssignmentModeSelected => AssignmentTab.IsSelected;
public bool IsMatrixModeSelected => MatrixTab.IsSelected;
public void ShowMatrixMode()
{
MatrixTab.IsSelected = true;
UpdateVisibleModePresentation();
}
public void ShowAssignmentMode()
{
AssignmentTab.IsSelected = true;
UpdateVisibleModePresentation();
}
public bool WarnOnExistingPatch =>
WarnOnExistingPatchCheckBox.IsChecked != false;
public string? SelectedTxDeviceName => TxDeviceComboBox.SelectedItem as string;
public string? SelectedRxDeviceName => RxDeviceComboBox.SelectedItem as string;
public bool FocusDevice(string deviceName)
{
DanteDevice? device = _project.FindDevice(deviceName);
if (device is null)
{
return false;
}
string? txDeviceName = device.TxCount > 0
? FindDeviceName(TxDeviceComboBox.Items.OfType<string>(), device.Name)
: null;
string? rxDeviceName = device.RxCount > 0
? FindDeviceName(RxDeviceComboBox.Items.OfType<string>(), device.Name)
: null;
if (txDeviceName is null && rxDeviceName is null)
{
return false;
}
bool wasInitializing = _initializing;
_initializing = true;
try
{
if (txDeviceName is not null)
{
TxDeviceComboBox.SelectedItem = txDeviceName;
}
if (rxDeviceName is not null && !_lockRxDeviceSelection)
{
RxDeviceComboBox.SelectedItem = rxDeviceName;
}
}
finally
{
_initializing = wasInitializing;
}
RefreshSourceChannelsAndMatrixColumns();
RefreshTargetRows();
UpdateDeviceNavigationState();
return true;
}
public event EventHandler? ApplyRequested;
public event EventHandler<DirectPatchRequestEventArgs>? DirectApplyRequested;
public event EventHandler<PatchDeviceFocusChangedEventArgs>? DeviceFocusChanged;
public event EventHandler<PatchDetachRequestedEventArgs>? DetachRequested;
public event EventHandler? CancelRequested;
public event EventHandler<InlineChannelNavigationRequestEventArgs>? InlineChannelNavigationRequested;
private void PatchWorkspaceView_SizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateResponsiveLayout();
}
private void UpdateResponsiveLayout()
{
// À 1366 x 768, une hauteur fixe de 132 px masque les premières
// lignes RX. Les grands écrans gardent les labels TX complets, tandis
// que les fenêtres compactes conservent au moins une ligne exploitable.
if (MatrixGrid is null)
{
return;
}
bool compact = ActualHeight < 600;
bool compactMatrix = _embedded && MatrixTab.IsSelected;
IntroTextBlock.Visibility = compact || compactMatrix
? Visibility.Collapsed
: Visibility.Visible;
RxDeviceLabel.Visibility = Visibility.Visible;
TxDeviceLabel.Visibility = Visibility.Visible;
RxDeviceLabel.Content = compactMatrix
? "RX"
: L("Machine réceptrice RX", "Receiving device (Rx)");
TxDeviceLabel.Content = compactMatrix
? "TX"
: L("Machine émettrice TX", "Transmitting device (Tx)");
RxDeviceLabel.Padding = compactMatrix
? new Thickness(0, 0, 0, 2)
: new Thickness(0, 8, 0, 4);
TxDeviceLabel.Padding = RxDeviceLabel.Padding;
RxDeviceLabel.FontWeight = compactMatrix ? FontWeights.SemiBold : FontWeights.Normal;
TxDeviceLabel.FontWeight = RxDeviceLabel.FontWeight;
MatrixOneToOneHintTextBlock.Visibility = ActualWidth < 1080
? Visibility.Collapsed
: Visibility.Visible;
TitleTextBlock.FontSize = compact || compactMatrix ? 16 : 20;
WorkspaceHeaderBorder.Padding = compact || compactMatrix
? new Thickness(16, 6, 16, 6)
: new Thickness(16, 12, 16, 12);
DeviceSelectorGrid.Margin = compactMatrix
? new Thickness(16, 5, 16, 5)
: new Thickness(16, 10, 16, 8);
SwapDeviceSelectionButton.Margin = compactMatrix
? new Thickness(8, 0, 8, 0)
: new Thickness(8, 22, 8, 0);
SwapDeviceSelectionButton.Height = compactMatrix ? 34 : 42;
WorkspaceFooterBorder.Padding = compact
? new Thickness(16, 5, 16, 5)
: new Thickness(16, 10, 16, 10);
MatrixGrid.ColumnHeaderHeight = ActualHeight switch
{
< 560 => 86,
< 680 => 106,
_ => 132
};
MatrixGrid.MinHeight = ActualHeight < 620 ? 156 : 230;
}
private void PatchModeTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!ReferenceEquals(e.OriginalSource, PatchModeTabControl))
{
return;
}
UpdateVisibleModePresentation();
}
public void FocusChannelEditor(DanteChannelKind kind, int danteId, bool matrix)
{
Dispatcher.BeginInvoke(new Action(() =>
FocusInlineChannelEditor(new InlineChannelNavigationTarget(kind, danteId, matrix))));
}
public PatchMatrixOneToOneState CaptureMatrixOneToOneState()
{
return new PatchMatrixOneToOneState(
MatrixOneToOneCountTextBox.Text,
_matrixOneToOneStart?.Source.DeviceName,
_matrixOneToOneStart?.Source.DanteId,
_matrixOneToOneStart?.Target.DeviceName,
_matrixOneToOneStart?.Target.DanteId);
}
public void RestoreMatrixOneToOneState(PatchMatrixOneToOneState? state)
{
if (state is null)
{
return;
}
// Un patch immédiat reconstruit Easy Patch : les identifiants stables
// permettent de retrouver le départ sans dépendre du nom des canaux.
bool wasInitializing = _initializing;
_initializing = true;
try
{
MatrixOneToOneCountTextBox.Text = state.CountText;
_matrixOneToOneStart = state.TxDanteId is int txDanteId
&& state.RxDanteId is int rxDanteId
&& !string.IsNullOrWhiteSpace(state.TxDeviceName)
&& !string.IsNullOrWhiteSpace(state.RxDeviceName)
? _matrixRows
.Where(row =>
row.Target.DanteId == rxDanteId
&& string.Equals(
row.Target.DeviceName,
state.RxDeviceName,
StringComparison.OrdinalIgnoreCase))
.SelectMany(row => row.Cells)
.FirstOrDefault(cell =>
cell.Source.DanteId == txDanteId
&& string.Equals(
cell.Source.DeviceName,
state.TxDeviceName,
StringComparison.OrdinalIgnoreCase))
: null;
}
finally
{
_initializing = wasInitializing;
}
UpdateCommandState();
}
public void ResetPendingChanges()
{
_session.Reset();
RefreshAllTargetStates();
SetInfo(L("Tous les changements Easy patch ont été appliqués.", "All Easy patch changes were applied."));
}
private void ConfigureWorkflowPresentation()
{
DetachMatrixButton.Visibility = _allowDetach
? Visibility.Visible
: Visibility.Collapsed;
if (!_embedded)
{
return;
}
// Dans l'onglet Easy Patch, chaque commande est appliquée directement.
// Les contrôles de lot restent réservés à la fenêtre autonome qui doit
// renvoyer ses modifications à la fiche machine lors de sa fermeture.
PreviewSelectionButton.Visibility = Visibility.Collapsed;
PreviewRangeButton.Visibility = Visibility.Collapsed;
PreviewGroupBox.Visibility = Visibility.Collapsed;
PendingHeaderTextBlock.Visibility = Visibility.Collapsed;
PendingFooterTextBlock.Visibility = Visibility.Collapsed;
ResetPendingButton.Visibility = Visibility.Collapsed;
CancelButton.Visibility = Visibility.Collapsed;
ApplyButton.Visibility = Visibility.Collapsed;
PatchModeTabControl.Template = (ControlTemplate)FindResource(
"EmbeddedPatchModeTabControlTemplate");
Grid.SetColumn(ApplySelectionDirectButton, 0);
Grid.SetColumnSpan(ApplySelectionDirectButton, 2);
ApplySelectionDirectButton.Margin = new Thickness(0, 0, 0, 6);
Grid.SetColumn(ApplyRangeDirectButton, 0);
Grid.SetColumnSpan(ApplyRangeDirectButton, 2);
ApplyRangeDirectButton.Margin = new Thickness(0);
}
private void PopulateDeviceSelectors(string? initialTxDeviceName, string? initialRxDeviceName)
{
string[] txDevices = _project.Devices
.Where(device => device.TxCount > 0)
.Select(device => device.Name)
.ToArray();
string[] rxDevices = _project.Devices
.Where(device => device.RxCount > 0)
.Select(device => device.Name)
.ToArray();
TxDeviceComboBox.ItemsSource = txDevices;
RxDeviceComboBox.ItemsSource = rxDevices;
PatchDeviceSelectionPair initialPair = PatchDeviceSelectionSwapper.ResolveInitialPair(
initialTxDeviceName,
initialRxDeviceName,
txDevices,
rxDevices);
TxDeviceComboBox.SelectedItem = initialPair.TxDeviceName;
RxDeviceComboBox.SelectedItem = initialPair.RxDeviceName;
RxDeviceComboBox.IsEnabled = !_lockRxDeviceSelection;
UpdateDeviceNavigationState();
}
private void PreviousRxDeviceButton_Click(object sender, RoutedEventArgs e)
{
MoveDeviceSelection(RxDeviceComboBox, -1);
}
private void NextRxDeviceButton_Click(object sender, RoutedEventArgs e)
{
MoveDeviceSelection(RxDeviceComboBox, 1);
}
private void PreviousTxDeviceButton_Click(object sender, RoutedEventArgs e)
{
MoveDeviceSelection(TxDeviceComboBox, -1);
}
private void NextTxDeviceButton_Click(object sender, RoutedEventArgs e)
{
MoveDeviceSelection(TxDeviceComboBox, 1);
}
private static void MoveDeviceSelection(ComboBox selector, int offset)
{
if (!selector.IsEnabled || selector.Items.Count <= 1)
{
return;
}
int currentIndex = selector.SelectedIndex >= 0 ? selector.SelectedIndex : 0;
selector.SelectedIndex = (currentIndex + offset + selector.Items.Count) % selector.Items.Count;
}
private void UpdateDeviceNavigationState()
{
bool canMoveRx = !_lockRxDeviceSelection && RxDeviceComboBox.Items.Count > 1;
PreviousRxDeviceButton.IsEnabled = canMoveRx;
NextRxDeviceButton.IsEnabled = canMoveRx;
bool canMoveTx = TxDeviceComboBox.Items.Count > 1;
PreviousTxDeviceButton.IsEnabled = canMoveTx;
NextTxDeviceButton.IsEnabled = canMoveTx;
SwapDeviceSelectionButton.IsEnabled = !_lockRxDeviceSelection
&& TxDeviceComboBox.SelectedItem is string
&& RxDeviceComboBox.SelectedItem is string;
}
private void SwapDeviceSelectionButton_Click(object sender, RoutedEventArgs e)
{
PatchDeviceSelectionSwapResult result = PatchDeviceSelectionSwapper.TrySwap(
TxDeviceComboBox.SelectedItem as string,
RxDeviceComboBox.SelectedItem as string,
TxDeviceComboBox.Items.OfType<string>(),
RxDeviceComboBox.Items.OfType<string>(),
_lockRxDeviceSelection);
if (!result.Success)
{
SetInfo(
_language == UiLanguage.English
? TranslateSwapError(result.ErrorMessage)
: result.ErrorMessage ?? "Inversion impossible.",
warning: true);
return;
}
_initializing = true;
TxDeviceComboBox.SelectedItem = result.TxDeviceName;
RxDeviceComboBox.SelectedItem = result.RxDeviceName;
_initializing = false;
RefreshSourceChannelsAndMatrixColumns();
RefreshTargetRows();
UpdateDeviceNavigationState();
NotifyDeviceFocus(result.RxDeviceName, DanteChannelKind.Rx);
SetInfo(_embedded
? L("Machines TX et RX inversées.", "Tx and Rx devices swapped.")
: L(
"Machines TX et RX inversées. Le lot en attente est conservé.",
"Tx and Rx devices swapped. The pending batch was preserved."));
}
private void TxDeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_initializing)
{
return;
}
RefreshSourceChannelsAndMatrixColumns();
RefreshTargetRows();
UpdateDeviceNavigationState();
NotifyDeviceFocus(TxDeviceComboBox.SelectedItem as string, DanteChannelKind.Tx);
}
private void RxDeviceComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!_initializing)
{
RefreshTargetRows();
UpdateDeviceNavigationState();
NotifyDeviceFocus(RxDeviceComboBox.SelectedItem as string, DanteChannelKind.Rx);
}
}
private void NotifyDeviceFocus(string? deviceName, DanteChannelKind kind)
{
if (!string.IsNullOrWhiteSpace(deviceName))
{
DeviceFocusChanged?.Invoke(
this,
new PatchDeviceFocusChangedEventArgs(deviceName, kind));
}
}
private void TxChannelListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateCommandState();
}
private void RxChannelListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateCommandState();
}
private void RefreshSourceChannelsAndMatrixColumns()
{
_matrixOneToOneStart = null;
int? selectedRangeDanteId = (RangeStartTxComboBox.SelectedItem as PatchSourceDescriptor)?.DanteId;
DanteDevice? device = _project.FindDevice(TxDeviceComboBox.SelectedItem as string);
_visibleSources = device?.TxChannels
.Select(channel => new PatchSourceDescriptor(
device.Name,
channel.DanteId,
channel.PositionIndex,
channel.DisplayName))
.OrderBy(channel => channel.PositionIndex)
.ToArray() ?? [];
TxChannelListBox.ItemsSource = _visibleSources.Select(source => new PatchTxListItem(source)).ToArray();
RangeStartTxComboBox.ItemsSource = _visibleSources;
RangeStartTxComboBox.SelectedItem = _visibleSources.FirstOrDefault(source => source.DanteId == selectedRangeDanteId)
?? _visibleSources.FirstOrDefault();
_ambiguousSourceNames.Clear();
foreach (IGrouping<string, PatchSourceDescriptor> duplicate in _visibleSources
.GroupBy(source => source.ChannelName, StringComparer.OrdinalIgnoreCase)
.Where(group => group.Count() > 1))
{
_ambiguousSourceNames.Add(duplicate.Key);
}
BuildMatrixColumns();
if (_ambiguousSourceNames.Count > 0)
{
SetInfo(
L(
"Cette machine contient des noms TX en double. Renommez-les avant de les utiliser dans la grille.",
"This device contains duplicate Tx names. Rename them before using them in the matrix."),
warning: true);
}
else
{
SetInfo(_embedded
? L(
"Sélectionnez les TX et les RX, puis appliquez la sélection ou une plage.",
"Select Tx and Rx channels, then apply the selection or a range.")
: L(
"Sélectionnez les TX et les RX, puis prévisualisez la sélection ou une plage.",
"Select the Tx and Rx channels, then preview the selection or a range."));
}
}
private void RefreshTargetRows()
{
_matrixOneToOneStart = null;
string? requestedDeviceName = RxDeviceComboBox.SelectedItem as string;
HashSet<int> selectedDanteIds = RxChannelListBox.SelectedItems
.OfType<PatchRxListItem>()
.Where(row => string.Equals(row.Target.DeviceName, requestedDeviceName, StringComparison.OrdinalIgnoreCase))
.Select(row => row.Target.DanteId)
.ToHashSet();
int? selectedRangeDanteId = (RangeStartRxComboBox.SelectedItem as PatchTargetDescriptor)?.DanteId;
DanteDevice? device = _project.FindDevice(RxDeviceComboBox.SelectedItem as string);
_visibleTargets = device?.RxChannels
.Select(channel => new PatchTargetDescriptor(
device.Name,
channel.DanteId,
channel.PositionIndex,
channel.DisplayName))
.OrderBy(channel => channel.PositionIndex)
.ToArray() ?? [];
_rxRows.Clear();
foreach (PatchTargetDescriptor target in _visibleTargets)
{
_rxRows.Add(BuildRxListItem(target));
}
foreach (PatchRxListItem row in _rxRows.Where(row => selectedDanteIds.Contains(row.Target.DanteId)))
{
RxChannelListBox.SelectedItems.Add(row);
}
if (RxChannelListBox.SelectedItems.Count == 0 && _rxRows.Count > 0)
{
RxChannelListBox.SelectedItem = _rxRows[0];
}
RangeStartRxComboBox.ItemsSource = _visibleTargets;
RangeStartRxComboBox.SelectedItem = _visibleTargets.FirstOrDefault(target => target.DanteId == selectedRangeDanteId)
?? _visibleTargets.FirstOrDefault();
_matrixRows.Clear();
for (int targetIndex = 0; targetIndex < _visibleTargets.Count; targetIndex++)
{
_matrixRows.Add(BuildMatrixRow(_visibleTargets[targetIndex], targetIndex));
}
RefreshPendingPreview();
UpdateCommandState();
}
private PatchRxListItem BuildRxListItem(PatchTargetDescriptor target)
{
EffectivePatchAssignment assignment = _session.GetEffectiveAssignment(target);
string source = assignment.IsActive
? $"{assignment.TxDeviceName} / {assignment.TxChannelName}"
: L("Libre", "Free");
string marker = assignment.IsPending ? L(" [modifié]", " [changed]") : string.Empty;
return new PatchRxListItem(target, target.ChannelName, source + marker);
}
private PatchMatrixRow BuildMatrixRow(PatchTargetDescriptor target, int targetIndex)
{
EffectivePatchAssignment assignment = _session.GetEffectiveAssignment(target);
PatchSourceNavigationResult navigation = _navigation.FindSource(target);
int assignedSourceIndex = FindAssignedSourceIndex(assignment);
PatchMatrixCell[] cells = _visibleSources
.Select((source, index) => new PatchMatrixCell(
source,
target,
index,
targetIndex,
index == assignedSourceIndex,
assignment.IsPending,
index == assignedSourceIndex ? "●" : string.Empty,
BuildCellToolTip(source, target, index == assignedSourceIndex, assignment.IsPending),
BuildCellAutomationName(source, target, index == assignedSourceIndex)))
.ToArray();
return new PatchMatrixRow(
target,
assignment.IsPending,
navigation.CanNavigate,
BuildSourceNavigationToolTip(target, navigation),
BuildSourceNavigationAutomationName(target, navigation),
cells);
}
private void RefreshTargetStates(IEnumerable<PatchTargetDescriptor> targets)
{
string? visibleDeviceName = RxDeviceComboBox.SelectedItem as string;
HashSet<int> danteIds = targets
.Where(target => string.Equals(
target.DeviceName,
visibleDeviceName,
StringComparison.OrdinalIgnoreCase))
.Select(target => target.DanteId)
.ToHashSet();
for (int targetIndex = 0; targetIndex < _visibleTargets.Count; targetIndex++)
{
if (danteIds.Contains(_visibleTargets[targetIndex].DanteId))
{
RefreshTargetState(targetIndex);
}
}
RefreshPendingPreview();
UpdateCommandState();
}
private void RefreshAllTargetStates()
{
for (int targetIndex = 0; targetIndex < _visibleTargets.Count; targetIndex++)
{
RefreshTargetState(targetIndex);
}
RefreshPendingPreview();
UpdateCommandState();
}
private void RefreshTargetState(int targetIndex)
{
if (targetIndex < 0
|| targetIndex >= _visibleTargets.Count
|| targetIndex >= _matrixRows.Count
|| targetIndex >= _rxRows.Count)
{
return;
}
PatchTargetDescriptor target = _visibleTargets[targetIndex];
EffectivePatchAssignment assignment = _session.GetEffectiveAssignment(target);
string source = assignment.IsActive
? $"{assignment.TxDeviceName} / {assignment.TxChannelName}"
: L("Libre", "Free");
string marker = assignment.IsPending ? L(" [modifié]", " [changed]") : string.Empty;
_rxRows[targetIndex].SourceDisplay = source + marker;
PatchMatrixRow row = _matrixRows[targetIndex];
row.IsPending = assignment.IsPending;
PatchSourceNavigationResult navigation = _navigation.FindSource(target);
row.UpdateNavigation(
navigation.CanNavigate,
BuildSourceNavigationToolTip(target, navigation),
BuildSourceNavigationAutomationName(target, navigation));
int assignedSourceIndex = FindAssignedSourceIndex(assignment);
for (int sourceIndex = 0; sourceIndex < row.Cells.Count; sourceIndex++)
{
PatchMatrixCell cell = row.Cells[sourceIndex];
bool isAssigned = sourceIndex == assignedSourceIndex;
cell.Update(
isAssigned,
assignment.IsPending,
isAssigned ? "●" : string.Empty,
BuildCellToolTip(cell.Source, cell.Target, isAssigned, assignment.IsPending),
BuildCellAutomationName(cell.Source, cell.Target, isAssigned));
}
}
private int FindAssignedSourceIndex(EffectivePatchAssignment assignment)
{
if (!assignment.IsActive)
{
return -1;
}
for (int index = 0; index < _visibleSources.Count; index++)
{
PatchSourceDescriptor source = _visibleSources[index];
if (string.Equals(source.DeviceName, assignment.TxDeviceName, StringComparison.OrdinalIgnoreCase)
&& string.Equals(source.ChannelName, assignment.TxChannelName, StringComparison.Ordinal))
{
// Le XML référence le nom du TX et non son numéro. En cas de
// doublon, une seule cellule est montrée et toute nouvelle
// affectation ambiguë reste bloquée.
return index;
}
}
return -1;
}
private void BuildMatrixColumns()
{
MatrixGrid.Columns.Clear();
FrameworkElementFactory rxPanel = new(typeof(Grid));
FrameworkElementFactory rxId = new(typeof(TextBlock));
rxId.SetBinding(TextBlock.TextProperty, new Binding("Target.DanteId") { StringFormat = "{0:000} - " });
rxId.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
rxPanel.AppendChild(rxId);
FrameworkElementFactory rxName = new(typeof(TextBox));
rxName.SetBinding(TextBox.TextProperty, new Binding("Target.ChannelName") { Mode = BindingMode.OneWay });
rxName.SetBinding(FrameworkElement.TagProperty, new Binding("Target"));
rxName.SetValue(FrameworkElement.MarginProperty, new Thickness(44, 0, 48, 0));
rxName.SetValue(Control.PaddingProperty, new Thickness(2, 0, 2, 0));
rxName.SetValue(Control.BorderThicknessProperty, new Thickness(0));
rxName.SetValue(Control.BackgroundProperty, Brushes.Transparent);
rxName.SetValue(Control.ForegroundProperty, (Brush)FindResource("TextBrush"));
rxName.SetValue(TextBox.IsReadOnlyProperty, _renameChannelAction is null);
rxName.SetValue(FrameworkElement.CursorProperty, Cursors.IBeam);
rxName.AddHandler(UIElement.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(InlineChannelNameTextBox_PreviewMouseLeftButtonDown));
rxName.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(InlineChannelNameTextBox_KeyDown));
rxName.AddHandler(UIElement.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(MatrixInlineTextBox_GotKeyboardFocus));
rxName.AddHandler(UIElement.LostKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(InlineChannelNameTextBox_LostKeyboardFocus));
rxPanel.AppendChild(rxName);
// La poignée reste au contact du nom. La flèche de navigation occupe
// seule le bord droit, immédiatement contre la grille de patch.
FrameworkElementFactory rxSeries = BuildMatrixSeriesThumbFactory("Target", Cursors.SizeNS);
rxSeries.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Right);
rxSeries.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
rxSeries.SetValue(FrameworkElement.MarginProperty, new Thickness(0, 0, 26, 0));
rxSeries.SetValue(Panel.ZIndexProperty, 2);
rxSeries.SetBinding(
UIElement.VisibilityProperty,
new Binding("Target.CanExtendNameSeries")
{
Converter = new BooleanToVisibilityConverter()
});
rxPanel.AppendChild(rxSeries);
FrameworkElementFactory locateSource = new(typeof(Button));
locateSource.SetValue(ContentControl.ContentProperty, "→");
locateSource.SetBinding(FrameworkElement.TagProperty, new Binding("Target"));
locateSource.SetBinding(
UIElement.IsEnabledProperty,
new Binding("CanNavigateToSource"));
locateSource.SetBinding(
ToolTipService.ToolTipProperty,
new Binding("SourceNavigationToolTip"));
locateSource.SetBinding(
AutomationProperties.NameProperty,
new Binding("SourceNavigationAutomationName"));
locateSource.SetValue(FrameworkElement.WidthProperty, 22d);
locateSource.SetValue(FrameworkElement.HeightProperty, 20d);
locateSource.SetValue(FrameworkElement.MarginProperty, new Thickness(0));
locateSource.SetValue(FrameworkElement.HorizontalAlignmentProperty, HorizontalAlignment.Right);
locateSource.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
locateSource.SetValue(Control.PaddingProperty, new Thickness(0));
locateSource.SetValue(Control.BackgroundProperty, (Brush)FindResource("SurfaceAltBrush"));
locateSource.SetValue(Control.ForegroundProperty, (Brush)FindResource("TextBrush"));
locateSource.SetValue(Control.BorderBrushProperty, (Brush)FindResource("BorderLineBrush"));
locateSource.SetValue(Panel.ZIndexProperty, 3);
locateSource.SetValue(ToolTipService.ShowOnDisabledProperty, true);
locateSource.AddHandler(
ButtonBase.ClickEvent,
new RoutedEventHandler(MatrixRxSourceButton_Click));
rxPanel.AppendChild(locateSource);
MatrixGrid.Columns.Add(new DataGridTemplateColumn
{
Header = L("Canal RX", "Rx channel"),
CellTemplate = new DataTemplate { VisualTree = rxPanel },
Width = new DataGridLength(210 * _matrixZoom),
IsReadOnly = true
});
Style cellStyle = (Style)FindResource("MatrixCellToggleStyle");
for (int index = 0; index < _visibleSources.Count; index++)
{
PatchSourceDescriptor source = _visibleSources[index];
FrameworkElementFactory toggle = new(typeof(ToggleButton));
toggle.SetValue(FrameworkElement.StyleProperty, cellStyle);
toggle.SetBinding(FrameworkElement.TagProperty, new Binding($"Cells[{index}]"));
toggle.SetBinding(ToggleButton.IsCheckedProperty, new Binding($"Cells[{index}].IsAssigned") { Mode = BindingMode.OneWay });
toggle.SetBinding(ContentControl.ContentProperty, new Binding($"Cells[{index}].Marker"));
toggle.SetBinding(ToolTipService.ToolTipProperty, new Binding($"Cells[{index}].ToolTip"));
toggle.SetBinding(AutomationProperties.NameProperty, new Binding($"Cells[{index}].AutomationName"));
toggle.SetValue(FrameworkElement.WidthProperty, 28 * _matrixZoom);
toggle.SetValue(FrameworkElement.HeightProperty, 22 * _matrixZoom);
toggle.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(MatrixCellButton_Click));
MatrixGrid.Columns.Add(new DataGridTemplateColumn
{
Header = BuildMatrixHeader(source),
CellTemplate = new DataTemplate { VisualTree = toggle },
Width = new DataGridLength(32 * _matrixZoom),
IsReadOnly = true
});
}
MatrixGrid.RowHeight = 26 * _matrixZoom;
MatrixGrid.ColumnHeaderHeight = 132 * _matrixZoom;
}
private FrameworkElement BuildMatrixHeader(PatchSourceDescriptor source)
{
PatchDestinationNavigationResult navigation =
_navigation.FindDestinations(source);
Grid panel = new()
{
Width = 28 * _matrixZoom,
Height = 106 * _matrixZoom,
VerticalAlignment = VerticalAlignment.Top,
Tag = source
};
panel.RowDefinitions.Add(new RowDefinition
{
Height = new GridLength(Math.Max(4, 6 * _matrixZoom))
});
panel.RowDefinitions.Add(new RowDefinition
{
Height = new GridLength(1, GridUnitType.Star)
});
panel.RowDefinitions.Add(new RowDefinition
{
Height = new GridLength(Math.Max(17, 20 * _matrixZoom))
});
Button label = new()
{
Content = source.Display,
Tag = source,
Width = 88 * _matrixZoom,
FontSize = Math.Max(8, 10 * _matrixZoom),
FontWeight = FontWeights.SemiBold,
Cursor = _renameChannelAction is null ? Cursors.Arrow : Cursors.IBeam,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0),
Padding = new Thickness(0),
Background = Brushes.Transparent,
BorderBrush = Brushes.Transparent,
BorderThickness = new Thickness(0),
Foreground = (Brush)FindResource("TextBrush"),
LayoutTransform = new RotateTransform(-90),
IsEnabled = _renameChannelAction is not null
};
label.Click += MatrixTxHeader_Click;
Grid.SetRow(label, 1);
panel.Children.Add(label);
Button destinationsButton = new()
{
Content = "↓",
Tag = source,
Width = Math.Max(18, 22 * _matrixZoom),
Height = Math.Max(17, 20 * _matrixZoom),
Padding = new Thickness(0),
Margin = new Thickness(0),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Bottom,
Background = (Brush)FindResource("SurfaceAltBrush"),
Foreground = (Brush)FindResource("TextBrush"),
BorderBrush = (Brush)FindResource("BorderLineBrush"),
BorderThickness = new Thickness(1),
RenderTransform = new TranslateTransform(0, -10 * _matrixZoom),
Cursor = navigation.CanNavigate ? Cursors.Hand : Cursors.Arrow,
IsEnabled = navigation.CanNavigate,
ToolTip = BuildDestinationNavigationToolTip(source, navigation)
};
destinationsButton.Click += MatrixTxDestinationsButton_Click;
ToolTipService.SetShowOnDisabled(destinationsButton, true);
AutomationProperties.SetName(
destinationsButton,
BuildDestinationNavigationAutomationName(source, navigation));
Panel.SetZIndex(destinationsButton, 3);
Grid.SetRow(destinationsButton, 2);
panel.Children.Add(destinationsButton);
Thumb series = BuildMatrixSeriesThumb(source, Cursors.SizeWE);
series.Visibility = source.CanExtendNameSeries ? Visibility.Visible : Visibility.Collapsed;
series.HorizontalAlignment = HorizontalAlignment.Stretch;
// En colonne TX, la poignée reste près du libellé et la flèche de
// navigation borde la matrice, sous le nom du canal.
series.VerticalAlignment = VerticalAlignment.Top;
Grid.SetRow(series, 0);
panel.Children.Add(series);
ToolTipService.SetToolTip(panel, L(
$"{source.FullDisplay}. Cliquez pour renommer ; tirez la poignée si le nom se termine par un numéro.",
$"{source.FullDisplay}. Click to rename; drag the handle when the name ends with a number."));
AutomationProperties.SetName(panel, source.FullDisplay);
return panel;
}
private void MatrixRxSourceButton_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
if (sender is not Button { Tag: PatchTargetDescriptor target })
{
return;
}
PatchSourceNavigationResult result = _navigation.FindSource(target);
if (!result.CanNavigate)
{
SetInfo(BuildSourceNavigationToolTip(target, result), warning: true);
return;
}
NavigateToMatrixConnection(result.Source!, target);
}
private void MatrixTxDestinationsButton_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
if (sender is not Button
{
Tag: PatchSourceDescriptor source
} button)
{