-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
3068 lines (2593 loc) · 120 KB
/
Copy pathMainWindowViewModel.cs
File metadata and controls
3068 lines (2593 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SDRIQStreamer.CWSkimmer;
using SDRIQStreamer.Digital;
using SDRIQStreamer.FlexRadio;
namespace SDRIQStreamer.App;
public partial class MainWindowViewModel : ObservableObject, IDaxStationConfirmer
{
private static readonly object s_streamerLogSync = new();
private static readonly object s_spotPayloadLogSync = new();
private readonly IRadioDiscovery _discovery;
private readonly IRadioConnection _connection;
private readonly ICwSkimmerLauncher _launcher;
private readonly IDigitalAppLauncher _digitalLauncher;
private readonly AppSettingsSession _settingsSession;
private readonly AppSettings _settings;
private readonly FooterStatusBuffer _footerStatusBuffer;
private readonly CwSkimmerWorkflowService _cwSkimmerWorkflow;
private readonly IReleaseUpdateService _releaseUpdateService;
private readonly IAudioDeviceFinder _deviceFinder;
private static readonly (string ReleaseTag, string CommitHash, string Display, string BuildDate) s_appBuildInfo =
ResolveAppBuildInfo();
// ── Discovered radios ─────────────────────────────────────────────────────
public ObservableCollection<DiscoveredRadio> Radios { get; } = new();
public ObservableCollection<RadioConnectTarget> ConnectTargets { get; } = new();
[ObservableProperty]
[NotifyCanExecuteChangedFor("ConnectCommand")]
private RadioConnectTarget? _selectedConnectTarget;
[ObservableProperty]
private string _statusText = "Discovering…";
// ── Connection state ──────────────────────────────────────────────────────
[ObservableProperty]
[NotifyCanExecuteChangedFor("ConnectCommand")]
[NotifyCanExecuteChangedFor("DisconnectCommand")]
[NotifyCanExecuteChangedFor(nameof(ResetNetworkStatusCommand))]
private bool _isConnected;
[ObservableProperty]
private string _networkStatusLabel = "--";
[ObservableProperty]
private string _networkLatencyRttText = "--";
[ObservableProperty]
private string _networkMaxLatencyRttText = "--";
// ── Operating mode (issue #28) ────────────────────────────────────────────
// Mode gates which working tabs are visible. CW Mode = existing CW Skimmer
// tabs (unchanged); Digital Mode = WSJT-X / JTDX screens. The Launch tab is
// always visible and is selected on startup.
// Null until the operator chooses a mode on the Launch tab. While null, only
// the Launch and Help tabs are shown (the CW/Config/Logs and Digital tabs are
// mode-specific and stay hidden until a mode is picked).
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsCwMode))]
[NotifyPropertyChangedFor(nameof(IsDigitalMode))]
[NotifyPropertyChangedFor(nameof(IsModeActive))]
[NotifyPropertyChangedFor(nameof(ModeActionButtonLabel))]
[NotifyPropertyChangedFor(nameof(ModeHeaderText))]
[NotifyPropertyChangedFor(nameof(SelectedLaunchModeName))]
private AppMode? _activeMode;
public bool IsCwMode => ActiveMode == AppMode.Cw;
public bool IsDigitalMode => ActiveMode == AppMode.Digital;
/// <summary>True once a mode (CW or Digital) is active. Drives the Launch-tab
/// mode control: swaps the mode list for the running status and flips the
/// Start/Stop button (issue #28).</summary>
public bool IsModeActive => ActiveMode is not null;
// Launch-tab mode selector, consistent with the radio-station ListBox used to
// connect: pick CW or Digital from a single-select list, then one Start/Stop
// button enters/exits that mode. The list is disabled while a mode is active,
// so (like choosing a station only while disconnected) you Stop to switch.
private const string CwModeName = "CW";
private const string DigitalModeName = "Digital";
public IReadOnlyList<string> LaunchModes { get; } = [CwModeName, DigitalModeName];
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(SelectedLaunchModeName))]
private AppMode _selectedLaunchMode = AppMode.Cw;
/// <summary>
/// The mode-list selection. While a mode is running it reflects the active
/// mode (so the disabled list still shows what you are in); otherwise it is
/// the pending choice the Start button will launch.
/// </summary>
public string SelectedLaunchModeName
{
get => (ActiveMode ?? SelectedLaunchMode) == AppMode.Digital ? DigitalModeName : CwModeName;
set => SelectedLaunchMode = value == DigitalModeName ? AppMode.Digital : AppMode.Cw;
}
public string ModeActionButtonLabel => IsModeActive ? "Stop" : "Start";
/// <summary>
/// Header above the mode list: just "Mode" when idle (list shown), or the
/// running-mode status when active (list hidden, only Stop remains).
/// </summary>
public string ModeHeaderText => ActiveMode switch
{
AppMode.Cw => "Mode: CW Mode Running",
AppMode.Digital => "Mode: Digital Mode Running",
_ => "Mode",
};
/// <summary>
/// The single Launch-tab mode button: when no mode is active it starts the
/// selected mode; when a mode is active it stops/exits it. One button, like
/// Connect/Disconnect.
/// </summary>
[RelayCommand]
private async Task ModeAction()
{
if (IsModeActive)
{
await CloseModeCommand.ExecuteAsync(null);
return;
}
if (SelectedLaunchMode == AppMode.Cw)
await LaunchCwModeCommand.ExecuteAsync(null);
else
await LaunchDigitalModeCommand.ExecuteAsync(null);
}
/// <summary>Drives TabControl.SelectedIndex. 0 = Launch tab (startup).</summary>
[ObservableProperty]
private int _selectedTabIndex;
/// <summary>
/// Raised when an action (switch / close mode) would stop running apps. The
/// View shows a confirm dialog with the given message; returns true to proceed.
/// </summary>
public event Func<string, Task<bool>>? StopRunningAppsConfirmRequested;
// ── Digital Mode config (issue #28) ───────────────────────────────────────
// Operator identity + engine paths + recommended defaults written into each
// per-slice config at launch. Identity is prepopulated from an existing
// FlexRadio WSJT-X / JTDX profile when present (see ImportDigitalProfile).
[ObservableProperty]
private string _digitalMyCall = string.Empty;
[ObservableProperty]
private string _digitalMyGrid = string.Empty;
[ObservableProperty]
private string _digitalRig = "FlexRadio 6xxx";
// 0 = WSJT-X, 1 = JTDX-Improved, 2 = WSJT-Z. The single active engine;
// switching is a config change. Drives ActiveDigitalEngine and the active
// exe-path proxy below.
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ActiveDigitalEngine))]
[NotifyPropertyChangedFor(nameof(ActiveEngineLabel))]
[NotifyPropertyChangedFor(nameof(ActiveEngineExePath))]
[NotifyPropertyChangedFor(nameof(ActiveEngineExeFileName))]
[NotifyPropertyChangedFor(nameof(IsWsjtXSelected))]
[NotifyPropertyChangedFor(nameof(IsJtdxSelected))]
[NotifyPropertyChangedFor(nameof(IsWsjtZSelected))]
private int _digitalEngineIndex;
/// <summary>
/// The active engine can only be changed when no digital instance is running
/// (one engine at a time; switching is a config change). Bound to the engine
/// radio buttons' IsEnabled so the operator cannot mix WSJT-X and JTDX
/// against the same slice / CAT port (review #2).
/// </summary>
public bool CanChangeDigitalEngine => !_digitalLauncher.IsRunning;
// Radio-button bindings for the engine selector (mutually exclusive).
public bool IsWsjtXSelected
{
get => DigitalEngineIndex == 0;
set { if (value) DigitalEngineIndex = 0; }
}
public bool IsJtdxSelected
{
get => DigitalEngineIndex == 1;
set { if (value) DigitalEngineIndex = 1; }
}
public bool IsWsjtZSelected
{
get => DigitalEngineIndex == 2;
set { if (value) DigitalEngineIndex = 2; }
}
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ActiveEngineExePath))]
private string _wsjtXExePath = string.Empty;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ActiveEngineExePath))]
private string _jtdxExePath = string.Empty;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ActiveEngineExePath))]
private string _wsjtZExePath = string.Empty;
public DigitalEngine ActiveDigitalEngine => DigitalEngineIndex switch
{
1 => DigitalEngine.Jtdx,
2 => DigitalEngine.WsjtZ,
_ => DigitalEngine.WsjtX,
};
public string ActiveEngineLabel => ActiveDigitalEngine switch
{
DigitalEngine.Jtdx => "JTDX-Improved",
DigitalEngine.WsjtZ => "WSJT-Z",
_ => "WSJT-X",
};
// WSJT-Z's own executable is named wsjtx.exe, so only JTDX differs here.
public string ActiveEngineExeFileName => ActiveDigitalEngine == DigitalEngine.Jtdx ? "jtdx.exe" : "wsjtx.exe";
/// <summary>
/// Exe path of the active engine. Reads / writes the matching backing
/// property so the Config tab shows a single path for the chosen engine
/// while every engine's path stays remembered.
/// </summary>
public string ActiveEngineExePath
{
get => ActiveDigitalEngine switch
{
DigitalEngine.Jtdx => JtdxExePath,
DigitalEngine.WsjtZ => WsjtZExePath,
_ => WsjtXExePath,
};
set
{
switch (ActiveDigitalEngine)
{
case DigitalEngine.Jtdx: JtdxExePath = value; break;
case DigitalEngine.WsjtZ: WsjtZExePath = value; break;
default: WsjtXExePath = value; break;
}
}
}
/// <summary>
/// Per-slice DAX RX channel + CAT / UDP ports, pre-set to recommended
/// defaults but editable per slice. Edits persist to settings. TX audio is
/// the shared DAX TX (not per slice). Consumed by the Operating screen's
/// per-slice launch.
/// </summary>
public ObservableCollection<DigitalSliceConfigViewModel> DigitalSliceConfigs { get; } = new();
/// <summary>
/// Digital Operating screen rows: one per live slice, each paired with its
/// per-slice binding and Start/Stop for the active engine (issue #28).
/// </summary>
public ObservableCollection<DigitalOperatingRowViewModel> DigitalSlices { get; } = new();
// ── Post-connect details ──────────────────────────────────────────────────
/// <summary>Hierarchical view: client → panadapter(s) → slice(s).</summary>
public ObservableCollection<ClientGroup> ClientGroups { get; } = new();
public IEnumerable<ClientGroup> VisibleClientGroups =>
string.IsNullOrWhiteSpace(SelectedControlStation)
? ClientGroups
: ClientGroups.Where(g => string.Equals(g.Station, SelectedControlStation, StringComparison.OrdinalIgnoreCase));
public ObservableCollection<DaxIQStreamInfo> DaxIQStreams { get; } = new();
/// <summary>Station name of our own connected client.</summary>
public string OwnClientStation { get; private set; } = string.Empty;
public string SelectedControlStation { get; private set; } = string.Empty;
// Issue #45: tracks whether SelectedControlStation has been observed present
// in a GUI-client snapshot this session. Disconnect detection only fires
// after the station has been seen, so a partial/initial snapshot during
// connect cannot raise a false "station disconnected". Reset whenever the
// selected station changes (see SetSelectedControlStation).
private bool _controlStationSeen;
// ── CW Skimmer ────────────────────────────────────────────────────────────
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(LaunchCwSkimmerForChannelCommand))]
[NotifyCanExecuteChangedFor(nameof(LaunchCwSkimmerForSliceCommand))]
[NotifyCanExecuteChangedFor(nameof(StopCwSkimmerForSliceCommand))]
private string _cwSkimmerExePath = string.Empty;
[ObservableProperty]
private string _cwSkimmerIniPath = string.Empty;
[ObservableProperty]
private bool _isCwSkimmerRunning;
[ObservableProperty]
private string _telnetCallsign = string.Empty;
[ObservableProperty]
private int _connectDelaySeconds = 5;
[ObservableProperty]
private int _launchDelaySeconds = 3;
[ObservableProperty]
private int _telnetPortBase = 7300;
[ObservableProperty]
private bool _telnetClusterEnabled = true;
[ObservableProperty]
private string _streamerIniCh1PathText = "(not generated yet)";
[ObservableProperty]
private string _streamerIniCh1Path = string.Empty;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenStreamerIniCh1FileCommand))]
private bool _hasStreamerIniCh1File;
[ObservableProperty]
private string _streamerIniCh2PathText = "(not generated yet)";
[ObservableProperty]
private string _streamerIniCh2Path = string.Empty;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenStreamerIniCh2FileCommand))]
private bool _hasStreamerIniCh2File;
[ObservableProperty]
private string _streamerIniFolderPath = string.Empty;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenStreamerIniFolderCommand))]
private bool _hasStreamerIniFolder;
[ObservableProperty]
private string _logsFolderPathText = "(not available)";
[ObservableProperty]
private string _logsFolderPath = string.Empty;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenLogsFolderCommand))]
private bool _hasLogsFolder;
[ObservableProperty]
private bool _spotForwardingEnabled = true;
[ObservableProperty]
private int _spotLifetimeSeconds = 300;
[ObservableProperty]
private string _spotColor = "#FF00FFFF";
[ObservableProperty]
private string _spotBackgroundColor = "#00000000";
[ObservableProperty]
private SpotColorOption? _spotSelectedColorOption;
public IReadOnlyList<SpotColorOption> SpotColorOptions { get; } =
[
new SpotColorOption("Red", "#FFFF0000"),
new SpotColorOption("Green", "#FF008000"),
new SpotColorOption("Blue", "#FF0000FF"),
new SpotColorOption("Yellow", "#FFFFFF00"),
new SpotColorOption("Orange", "#FFFFA500"),
new SpotColorOption("Purple", "#FF800080"),
new SpotColorOption("Cyan", "#FF00FFFF"),
new SpotColorOption("White", "#FFFFFFFF"),
];
[ObservableProperty]
private SpotColorOption? _spotSelectedBackgroundColorOption;
public IReadOnlyList<SpotColorOption> SpotBackgroundColorOptions { get; } =
[
new SpotColorOption("Transparent", "#00000000"),
new SpotColorOption("Red", "#66FF0000"),
new SpotColorOption("Green", "#6600FF00"),
new SpotColorOption("Blue", "#660000FF"),
new SpotColorOption("Yellow", "#66FFFF00"),
new SpotColorOption("Orange", "#66FFA500"),
new SpotColorOption("Purple", "#66800080"),
new SpotColorOption("Cyan", "#6600FFFF"),
];
public ObservableCollection<string> FooterStatusLines { get; } = new();
private readonly Dictionary<int, string> _lastCwDevicePreviewByChannel = new();
private readonly Dictionary<int, CancellationTokenSource> _streamRemovedDebounceCtsByChannel = new();
private readonly CancellationTokenSource _updateCheckLoopCts = new();
private readonly SemaphoreSlim _updateCheckLock = new(1, 1);
private Task? _updateCheckLoopTask;
private string _lastAnnouncedUpdateTag = string.Empty;
private readonly object _syncDampenGate = new();
private readonly ThrottledStatusEmitter _ritStatusEmitter;
private readonly Dictionary<string, (bool RitEnabled, double RitOffsetHz)> _lastRitStateBySlice = new();
private readonly Dictionary<int, (double FreqMHz, DateTime Utc)> _lastOutboundQsyByChannel = new();
private readonly Dictionary<int, (double FreqMHz, DateTime Utc)> _lastInboundClickByChannel = new();
private readonly Dictionary<int, (long LoHz, double? RxMHz)> _lastLoggedPanSyncByChannel = new();
private bool _isApplyingStartupSettings;
private const double EchoSuppressToleranceMHz = 0.000010; // 10 Hz
private static readonly TimeSpan EchoSuppressWindow = TimeSpan.FromMilliseconds(700);
private const double DuplicateClickToleranceMHz = 0.000005; // 5 Hz
private static readonly TimeSpan DuplicateClickWindow = TimeSpan.FromMilliseconds(250);
private const int FallbackClickSnapStepHz = 50;
private static readonly TimeSpan RitStatusMinInterval = TimeSpan.FromMilliseconds(500);
private static readonly TimeSpan DaxStreamRemovedGracePeriod = TimeSpan.FromMilliseconds(1500);
[ObservableProperty]
private string _footerStatusText = string.Empty;
[ObservableProperty]
private string _latestFooterEvent = string.Empty;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenLatestReleaseCommand))]
private bool _isUpdateAvailable;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(OpenLatestReleaseCommand))]
private string _latestReleaseUrl = string.Empty;
[ObservableProperty]
private string _latestAvailableTag = string.Empty;
[ObservableProperty]
private string _updateStatusText = "Not checked yet.";
public string AppReleaseTag => s_appBuildInfo.ReleaseTag;
public string AppReleaseDisplay => FormatReleaseForHelp(AppReleaseTag);
public string AppCommitHash => s_appBuildInfo.CommitHash;
public string AppBuildDisplay => s_appBuildInfo.Display;
public string AppBuildDate => s_appBuildInfo.BuildDate;
private string AppReleaseTagForUpdateChecks => ResolveReleaseTagForUpdateChecks();
public string WindowTitle => $"SmartStreamer4 {AppBuildDisplay}";
public string ConnectTargetHeaderColor => IsConnected ? "Green" : "Gray";
public string ConnectTargetHeaderText
{
get
{
if (!IsConnected)
return "Available Radios";
var radioName = ResolveConnectedRadioDisplayName();
var stationName = !string.IsNullOrWhiteSpace(SelectedControlStation)
? SelectedControlStation
: OwnClientStation;
if (string.IsNullOrWhiteSpace(stationName))
stationName = "Unknown Station";
return $"Connected: {radioName} - {stationName}";
}
}
public string AboutDevelopedBy => "Developed by Chris L White, WX7V and Cursor.AI Premium Agent v31.14";
public string AboutLicenseReference => "Licensed under the MIT License. See LICENSE for full terms.";
// ── Constructor ───────────────────────────────────────────────────────────
public MainWindowViewModel(IRadioDiscovery discovery, IRadioConnection connection,
ICwSkimmerLauncher launcher, IDigitalAppLauncher digitalLauncher,
AppSettingsSession settingsSession,
IReleaseUpdateService releaseUpdateService,
IAudioDeviceFinder deviceFinder)
{
_discovery = discovery;
_connection = connection;
_launcher = launcher;
_digitalLauncher = digitalLauncher;
_settingsSession = settingsSession;
_settings = _settingsSession.Settings;
// No mode is active until the operator chooses one on the Launch tab, so
// only Launch + Help show initially. LastMode is still persisted on
// selection (reserved for a future "default mode" preference) but is not
// auto-activated here.
_activeMode = null;
_releaseUpdateService = releaseUpdateService;
_deviceFinder = deviceFinder;
_footerStatusBuffer = new FooterStatusBuffer(FooterStatusLines);
_ritStatusEmitter = new ThrottledStatusEmitter(RitStatusMinInterval, UIPost, AddTelnetStatus);
_cwSkimmerWorkflow = new CwSkimmerWorkflowService(_connection, _launcher, _settings, this);
_discovery.RadioAdded += OnRadioAdded;
_discovery.RadioRemoved += OnRadioRemoved;
_connection.ConnectionStateChanged += OnConnectionStateChanged;
_connection.PanadapterAdded += p => UIPost(() => AddPan(p));
_connection.PanadapterRemoved += p => UIPost(() => RemovePan(p));
_connection.PanadapterUpdated += p => UIPost(() => UpdatePan(p));
_connection.SliceAdded += s => UIPost(() => AddSlice(s));
_connection.SliceRemoved += s => UIPost(() => RemoveSlice(s));
_connection.SliceUpdated += s => UIPost(() => UpdateSlice(s));
_connection.DaxIQStreamAdded += d => UIPost(() => OnDaxIQStreamAdded(d));
_connection.DaxIQStreamRemoved += d => UIPost(() => OnDaxIQStreamRemoved(d));
_connection.DaxIQStreamUpdated += d => UIPost(() => OnDaxIQStreamUpdated(d));
_connection.NetworkStatusChanged += status => UIPost(() => ApplyNetworkStatus(status));
_connection.GuiClientsChanged += clients => UIPost(() => OnGuiClientsChanged(clients));
_connection.DiagnosticEvent += line => UIPost(() => AddDiagnosticStatus(line));
// Re-evaluate Launch command whenever the stream list changes
DaxIQStreams.CollectionChanged += (_, _) =>
UIPost(() =>
{
LaunchCwSkimmerForChannelCommand.NotifyCanExecuteChanged();
StopCwSkimmerForChannelCommand.NotifyCanExecuteChanged();
LaunchCwSkimmerForSliceCommand.NotifyCanExecuteChanged();
StopCwSkimmerForSliceCommand.NotifyCanExecuteChanged();
RefreshSliceSkimmerStates();
});
// Track CW Skimmer process state
_launcher.RunningStateChanged += running =>
UIPost(() =>
{
IsCwSkimmerRunning = running;
LaunchCwSkimmerForChannelCommand.NotifyCanExecuteChanged();
StopCwSkimmerForChannelCommand.NotifyCanExecuteChanged();
LaunchCwSkimmerForSliceCommand.NotifyCanExecuteChanged();
StopCwSkimmerForSliceCommand.NotifyCanExecuteChanged();
RefreshDaxStreamPanBindings();
RefreshSliceSkimmerStates();
RefreshAllPanStreamSummaries();
if (!running)
AddSkimmerStatus("CW Skimmer stopped.");
});
// Click→tune: when user clicks a signal in CW Skimmer, tune the associated slice
_launcher.FrequencyClicked += (daxIqChannel, freqKhz) =>
{
var slice = GetPreferredSliceForTune(daxIqChannel);
if (slice is null) return;
var rawFreqMHz = freqKhz / 1000.0;
var clickSnapStepHz = ResolveClickSnapStepHz(slice);
var snappedFreqMHz = FrequencyMath.SnapMHzToStepHz(rawFreqMHz, clickSnapStepHz);
if (ShouldSuppressInboundClick(daxIqChannel, snappedFreqMHz, clickSnapStepHz))
return;
_ = _connection.SetSliceFrequencyAsync(slice, snappedFreqMHz);
UIPost(() =>
{
if (Math.Abs(snappedFreqMHz - rawFreqMHz) >= 0.0000005)
{
AddTelnetStatus(
$"ch {daxIqChannel}: Click snap (Skimmer): {rawFreqMHz:F6} MHz -> {snappedFreqMHz:F6} MHz (step {clickSnapStepHz} Hz)");
}
AddTelnetStatus(
$"ch {daxIqChannel}: Click tune (Skimmer): {snappedFreqMHz:F6} MHz -> Slice {slice.Letter} ({slice.ClientStation})");
});
};
// Digital engine instances: on every launch/exit, refresh per-slice
// running state and the engine selector's enabled state. InstancesChanged
// (per-instance) fires even when one of several instances exits, unlike
// the aggregate RunningStateChanged (issue #28).
_digitalLauncher.InstancesChanged += () => UIPost(() =>
{
RefreshDigitalRunningStates();
OnPropertyChanged(nameof(CanChangeDigitalEngine));
});
_launcher.TelnetStatusChanged += message =>
UIPost(() => AddTelnetStatus(message));
_launcher.SpotReceived += (daxIqChannel, spot) =>
{
_ = PublishSkimmerSpotAsync(spot);
};
// Mirror sync-tracker outbound QSYs into echo-suppression state so
// CW Skimmer's click feedback for our own commands is recognized and
// doesn't loop back as a tune request.
_launcher.OutboundQsyEmitted += (daxIqChannel, freqMHz, _) =>
RecordOutboundQsy(daxIqChannel, freqMHz);
// Load persisted settings without emitting user-facing change notices.
_isApplyingStartupSettings = true;
try
{
CwSkimmerExePath = _settings.CwSkimmerExePath;
CwSkimmerIniPath = _settings.CwSkimmerIniPath;
TelnetCallsign = _settings.Callsign;
ConnectDelaySeconds = _settings.ConnectDelaySeconds;
LaunchDelaySeconds = _settings.LaunchDelaySeconds;
TelnetPortBase = _settings.TelnetPortBase;
TelnetClusterEnabled = _settings.TelnetClusterEnabled;
UpdateTelnetIniSummary();
SpotForwardingEnabled = _settings.SpotForwardingEnabled;
SpotLifetimeSeconds = _settings.SpotLifetimeSeconds;
SpotColor = _settings.SpotColor;
SpotBackgroundColor = _settings.SpotBackgroundColor;
UpdateSpotColorSelection(SpotColor);
UpdateSpotBackgroundColorSelection(SpotBackgroundColor);
DigitalMyCall = _settings.DigitalMyCall;
DigitalMyGrid = _settings.DigitalMyGrid;
DigitalRig = _settings.DigitalRig;
WsjtXExePath = _settings.WsjtXExePath;
JtdxExePath = _settings.JtdxExePath;
WsjtZExePath = _settings.WsjtZExePath;
DigitalEngineIndex = _settings.DigitalActiveEngine switch
{
var s when string.Equals(s, "Jtdx", StringComparison.OrdinalIgnoreCase) => 1,
var s when string.Equals(s, "WsjtZ", StringComparison.OrdinalIgnoreCase) => 2,
_ => 0,
};
}
finally
{
_isApplyingStartupSettings = false;
}
LoadDigitalSliceConfigs();
// Prepopulate call/grid from an existing FlexRadio profile for operators
// who already run WSJT-X / JTDX (issue #28). Only fills blanks, so it
// never clobbers values the operator has already entered.
TryPrepopulateDigitalIdentity();
UpdateLogsFolderSummary();
AddStreamerStatus($"Release: {AppReleaseTag} | Commit: {AppCommitHash}");
foreach (var line in AppDataPaths.DrainMigrationMessages())
AddStreamerStatus(line);
StartUpdateChecks();
_discovery.Start();
}
// ── Discovery ─────────────────────────────────────────────────────────────
private void OnRadioAdded(DiscoveredRadio radio) => UIPost(() =>
{
var existing = Radios.FirstOrDefault(r => r.Serial == radio.Serial);
if (existing is null)
Radios.Add(radio);
else
Radios[Radios.IndexOf(existing)] = radio;
RebuildConnectTargets();
StatusText = Radios.Count == 0 ? "No radios found" : string.Empty;
});
private void OnRadioRemoved(DiscoveredRadio radio) => UIPost(() =>
{
var m = Radios.FirstOrDefault(r => r.Serial == radio.Serial);
if (m is not null) Radios.Remove(m);
RebuildConnectTargets();
StatusText = Radios.Count == 0 ? "No radios found" : string.Empty;
});
// ── Connection ────────────────────────────────────────────────────────────
[RelayCommand(CanExecute = nameof(CanConnect))]
private async Task ConnectAsync()
{
if (SelectedConnectTarget is null) return;
SetSelectedControlStation(SelectedConnectTarget.Station);
bool ok = await _connection.ConnectAsync(SelectedConnectTarget.Radio);
if (!ok) AddStreamerStatus("Connection failed.");
}
private bool CanConnect() => SelectedConnectTarget is not null && !IsConnected;
[RelayCommand(CanExecute = nameof(CanDisconnect))]
private void Disconnect() => _connection.Disconnect();
private bool CanDisconnect() => IsConnected;
// ── Mode switching (issue #28) ────────────────────────────────────────────
// Tab order in MainWindow.axaml (visibility, not position, is gated by mode):
// 0 Launch | 1 CW | 2 CW Config | 3 Digital | 4 Digital Config | 5 Logs | 6 Help
// Launch / Logs / Help are always shown; activating a mode reveals that mode's
// operating + config tabs. Entering a mode navigates to its operating tab.
private const int CwHomeTabIndex = 1; // CW operating tab
private const int DigitalHomeTabIndex = 3; // Digital operating tab
[RelayCommand]
private Task LaunchCwMode() => SwitchModeAsync(AppMode.Cw);
[RelayCommand]
private Task LaunchDigitalMode() => SwitchModeAsync(AppMode.Digital);
/// <summary>
/// Close the active mode back to mode selection (only Launch + Help show).
/// The radio stays connected. `LastMode` is left unchanged so a future
/// "Auto Start Last Mode" can restore it.
/// </summary>
[RelayCommand]
private async Task CloseMode()
{
if (ActiveMode is not { } current)
return;
if (HasRunningAppForCurrentMode() && !await ConfirmStopRunningAsync(
$"Closing {ModeName(current)} Mode will stop its running application(s).\n\nContinue?"))
{
return;
}
StopCurrentModeApps();
ActiveMode = null; // back to "no mode"; LastMode intentionally preserved
SelectedTabIndex = 0; // Launch tab
}
private async Task SwitchModeAsync(AppMode target)
{
if (ActiveMode == target)
{
NavigateToModeHome(target);
return;
}
// Hard modes: leaving a mode with a running app stops it. Confirm first.
if (ActiveMode is { } current && HasRunningAppForCurrentMode() && !await ConfirmStopRunningAsync(
$"Switching to {ModeName(target)} Mode will stop {ModeName(current)} Mode's running application(s).\n\nContinue?"))
{
return;
}
StopCurrentModeApps();
ActiveMode = target; // flips tab visibility first
_settings.LastMode = target.ToString();
_settingsSession.Save();
NavigateToModeHome(target); // then select the now-visible tab
}
private async Task<bool> ConfirmStopRunningAsync(string message)
{
var handler = StopRunningAppsConfirmRequested;
return handler is null || await handler(message);
}
private static string ModeName(AppMode mode) => mode == AppMode.Cw ? "CW" : "Digital";
private bool HasRunningAppForCurrentMode() => ActiveMode switch
{
AppMode.Cw => _launcher.IsRunning,
AppMode.Digital => _digitalLauncher.IsRunning,
_ => false,
};
private void StopCurrentModeApps()
{
switch (ActiveMode)
{
case AppMode.Cw:
StopAllCwSkimmerInstances();
break;
case AppMode.Digital:
_digitalLauncher.Stop();
break;
}
}
private void NavigateToModeHome(AppMode mode) =>
SelectedTabIndex = mode == AppMode.Cw ? CwHomeTabIndex : DigitalHomeTabIndex;
// ── Digital Operating (issue #28) ─────────────────────────────────────────
/// <summary>
/// Adds or updates the Digital Operating row for <paramref name="slice"/>.
/// Scoped to the controlled station (like the CW VisibleClientGroups): a row
/// is keyed by slice letter, which is unique only WITHIN a station, so a
/// foreign station's slice must not feed in. Refreshes live mode/freq and
/// re-reads the per-slice binding so Config edits are reflected.
/// </summary>
private void SyncDigitalSliceRow(SliceInfo slice)
{
// Bug (reported 2026-06-11): with two stations (SUPERWIN + MaestroC) each
// has its own Slice A. Rows were keyed by letter only with no station
// filter, so the non-controlled station's Slice A (MaestroC, CW) appeared
// on the Digital Operating page when controlling SUPERWIN (DIGU). Fix:
// only sync slices owned by SelectedControlStation. Chosen over keying by
// station+letter because Digital Mode operates one station at a time, so
// the rows should mirror exactly the controlled station's slices.
if (!IsOwnStationSlice(slice))
return;
var (daxRx, catPort, udpPort) = GetBindingForLetter(slice.Letter);
var row = DigitalSlices.FirstOrDefault(r =>
string.Equals(r.SliceLetter, slice.Letter, StringComparison.OrdinalIgnoreCase));
if (row is null)
{
row = new DigitalOperatingRowViewModel(slice.Letter, slice.ClientStation);
InsertDigitalSliceRowSorted(row);
}
row.Mode = slice.Mode;
row.FreqMHz = slice.FreqMHz;
row.SliceDaxRxChannel = slice.DaxAudioChannel; // actual DAX RX assignment (issue #28)
row.DaxRxChannel = daxRx;
row.CatPort = catPort;
row.UdpPort = udpPort;
row.IsRunning = IsDigitalRowRunning(row);
}
private void InsertDigitalSliceRowSorted(DigitalOperatingRowViewModel row)
{
// Keep rows ordered by slice letter for a stable display.
var index = 0;
while (index < DigitalSlices.Count &&
string.CompareOrdinal(DigitalSlices[index].SliceLetter, row.SliceLetter) < 0)
index++;
DigitalSlices.Insert(index, row);
}
private void RemoveDigitalSliceRow(SliceInfo slice)
{
// Match station + letter so removing another station's Slice A cannot drop
// the controlled station's row (see SyncDigitalSliceRow, 2026-06-11).
var row = DigitalSlices.FirstOrDefault(r =>
string.Equals(r.SliceLetter, slice.Letter, StringComparison.OrdinalIgnoreCase) &&
string.Equals(r.Station, slice.ClientStation, StringComparison.OrdinalIgnoreCase));
if (row is not null)
DigitalSlices.Remove(row);
}
/// <summary>
/// Rebuilds the Digital Operating rows for the current
/// <see cref="SelectedControlStation"/> (issue #28). Called when the
/// controlled station changes (initial connect, or an issue #45 re-pin) so
/// the rows always reflect the controlled station's slices and never a
/// previously-shown station's.
/// </summary>
private void RebuildDigitalSlices()
{
DigitalSlices.Clear();
foreach (var slice in _connection.Slices)
SyncDigitalSliceRow(slice); // guard keeps only the controlled station
}
/// <summary>
/// The DAX RX / CAT / UDP for a slice letter: the operator's Config binding
/// when present, else recommended defaults derived from the letter ordinal
/// (e.g. slices beyond A-D on a FLEX-6700).
/// </summary>
private (int DaxRx, int CatPort, int UdpPort) GetBindingForLetter(string letter)
{
var binding = DigitalSliceConfigs.FirstOrDefault(c =>
string.Equals(c.SliceLetter, letter, StringComparison.OrdinalIgnoreCase));
if (binding is not null)
return (binding.DaxRxChannel, binding.CatPort, binding.UdpPort);
var ordinal = letter.Length == 1 ? Math.Max(0, char.ToUpperInvariant(letter[0]) - 'A') : 0;
return (ordinal + 1, 60_000 + ordinal, 2_237 + ordinal);
}
// Codex review 2026-06-11: rig names are per-slice-letter, so a digital
// instance launched for one station's Slice A would otherwise read as
// "running" on another controlled station's Slice A after a re-pin. Track
// which station launched each running rig so the row's state matches.
private readonly Dictionary<string, string> _digitalRigStations =
new(StringComparer.OrdinalIgnoreCase);
private bool IsDigitalRowRunning(DigitalOperatingRowViewModel row) =>
_digitalLauncher.IsInstanceRunning(row.RigName) &&
_digitalRigStations.TryGetValue(row.RigName, out var station) &&
string.Equals(station, row.Station, StringComparison.OrdinalIgnoreCase);
private void RefreshDigitalRunningStates()
{
// Forget rigs that have exited so a future same-letter row on another
// station can't inherit a stale "running" state.
foreach (var rig in _digitalRigStations.Keys
.Where(r => !_digitalLauncher.IsInstanceRunning(r)).ToList())
_digitalRigStations.Remove(rig);
foreach (var row in DigitalSlices)
row.IsRunning = IsDigitalRowRunning(row);
}
[RelayCommand]
private async Task StartDigitalForSlice(DigitalOperatingRowViewModel? row)
{
if (row is null)
return;
// Guard (issue #28): WSJT-X / JTDX get their RX audio from the slice's DAX
// audio channel, so refuse to start until the slice has one assigned in
// SmartSDR. Mirrors CW Mode requiring a DAX-IQ channel before launch.
if (!row.HasDaxRx)
{
row.StatusText = "Assign a DAX RX audio channel to this slice in SmartSDR before starting.";
return;
}
var engine = GetEngineDefinition(ActiveDigitalEngine);
var values = new DigitalProvisionValues(
DigitalMyCall, DigitalMyGrid, DigitalRig, row.DaxRxChannel, row.CatPort, row.UdpPort);
var provision = DigitalConfigProvisioner.Provision(engine, row.RigName, values);
if (provision.Outcome != DigitalProvisionOutcome.Success)
{
row.StatusText = "Could not write the engine config file.";
return;
}
var result = await _digitalLauncher.LaunchAsync(engine, row.RigName);
if (result == DigitalLaunchResult.Success)
_digitalRigStations[row.RigName] = row.Station; // remember which station launched this rig
row.StatusText = result switch
{
DigitalLaunchResult.Success => string.Empty,
DigitalLaunchResult.AlreadyRunning => "Already running.",
DigitalLaunchResult.ExeNotFound => $"{ActiveEngineLabel} not found. Set the Path on the Config tab.",
DigitalLaunchResult.InvalidRigName => "Invalid rig name.",
_ => "Failed to start the engine.",
};
RefreshDigitalRunningStates();
}
[RelayCommand]
private void StopDigitalForSlice(DigitalOperatingRowViewModel? row)
{
if (row is null)
return;
_digitalLauncher.Stop(row.RigName);
row.StatusText = string.Empty;
RefreshDigitalRunningStates();
}
private void OnConnectionStateChanged(bool connected)
{
UIPost(() =>
{
IsConnected = connected;
OnPropertyChanged(nameof(ConnectTargetHeaderColor));
OnPropertyChanged(nameof(ConnectTargetHeaderText));
if (connected)
{
OwnClientStation = _connection.OwnClientStation;
OnPropertyChanged(nameof(OwnClientStation));
EnsureSelectedControlStation();
foreach (var p in _connection.Panadapters)
AddPan(p);
foreach (var s in _connection.Slices)
AddSlice(s);
foreach (var d in _connection.DaxIQStreams)
OnDaxIQStreamAdded(d);
ApplyNetworkStatus(_connection.NetworkStatus);
AddStreamerStatus($"Connected to {_connection.ConnectedModel}.");
AddStreamerStatus($"Control station: {SelectedControlStation}");
LogGuiClientsSnapshot(_connection.GuiClients);
}
else
{
// Stop every external app on disconnect: CW Skimmer and the
// digital engines (WSJT-X / JTDX). Stop() is a no-op when the
// family isn't running, so calling both is safe (issue #28).
_launcher.Stop();
_digitalLauncher.Stop();
OwnClientStation = string.Empty;
OnPropertyChanged(nameof(OwnClientStation));
SetSelectedControlStation(string.Empty);
ClientGroups.Clear();
DigitalSlices.Clear();
DaxIQStreams.Clear();
ResetDisplayedNetworkStatus();
_lastCwDevicePreviewByChannel.Clear();
_lastRitStateBySlice.Clear();
_lastLoggedPanSyncByChannel.Clear();
lock (_syncDampenGate)
{
_lastOutboundQsyByChannel.Clear();
_lastInboundClickByChannel.Clear();
foreach (var cts in _streamRemovedDebounceCtsByChannel.Values)
{
try { cts.Cancel(); } catch { }
cts.Dispose();
}
_streamRemovedDebounceCtsByChannel.Clear();
}
_ritStatusEmitter.Clear();