-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMainViewModel.cs
More file actions
1162 lines (999 loc) · 46.2 KB
/
MainViewModel.cs
File metadata and controls
1162 lines (999 loc) · 46.2 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.ComponentModel;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Timers;
using Highbyte.DotNet6502.App.Avalonia.Core.SystemSetup;
using Highbyte.DotNet6502.DebugAdapter;
using Highbyte.DotNet6502.Impl.Avalonia.Monitor;
using Highbyte.DotNet6502.Systems;
using Highbyte.DotNet6502.Systems.Commodore64;
using Highbyte.DotNet6502.Systems.Logging.InMem;
using Microsoft.Extensions.Logging;
using ReactiveUI;
namespace Highbyte.DotNet6502.App.Avalonia.Core.ViewModels;
public class MainViewModel : ViewModelBase, IDisposable
{
private readonly AvaloniaHostApp _hostApp;
private readonly EmulatorConfig _emulatorConfig;
private readonly ILogger _logger;
// Expose HostApp for EmulatorView that currently needs it (TODO: Consider removing this dependency via MainViewModel. Better that EmulatorViewModel provides it.)
public AvaloniaHostApp HostApp => _hostApp;
// Child ViewModels exposed as properties for XAML binding
public C64MenuViewModel C64MenuViewModel { get; }
public C64InfoViewModel C64InfoViewModel { get; }
public StatisticsViewModel StatisticsViewModel { get; }
public EmulatorViewModel EmulatorViewModel { get; }
public EmulatorPlaceholderViewModel EmulatorPlaceholderViewModel { get; }
// --- Start Binding Properties ---
// Read-only properties derived from HostApp
private readonly ObservableAsPropertyHelper<string> _selectedSystemName;
public string SelectedSystemName => _selectedSystemName.Value;
private readonly ObservableAsPropertyHelper<string> _selectedSystemConfigurationVariant;
public string SelectedSystemVariant => _selectedSystemConfigurationVariant.Value;
private readonly ObservableAsPropertyHelper<ObservableCollection<string>> _availableSystems;
public ObservableCollection<string> AvailableSystems => _availableSystems.Value;
private readonly ObservableAsPropertyHelper<ObservableCollection<string>> _availableSystemVariants;
public ObservableCollection<string> AvailableSystemVariants => _availableSystemVariants.Value;
private readonly ObservableAsPropertyHelper<EmulatorState> _emulatorState;
public EmulatorState EmulatorState => _emulatorState.Value;
private readonly ObservableAsPropertyHelper<bool> _isExternalDebuggerAttached;
public bool IsExternalDebuggerAttached => _isExternalDebuggerAttached.Value;
private readonly ObservableAsPropertyHelper<double> _scale;
public double Scale
{
get => _scale.Value;
set
{
_hostApp.Scale = (float)value;
}
}
public bool IsC64SystemSelected => string.Equals(SelectedSystemName, C64.SystemName, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Currently-active system menu contributor (supplies macOS native menu + keyboard shortcuts).
/// Swaps when <see cref="SelectedSystemName"/> changes; null when no system is selected.
/// </summary>
private ISystemMenuContributor? _activeMenuContributor;
public ISystemMenuContributor? ActiveMenuContributor
{
get => _activeMenuContributor;
private set => this.RaiseAndSetIfChanged(ref _activeMenuContributor, value);
}
// Computed properties for control enabled states based on EmulatorState
public bool IsEmulatorRunning => EmulatorState == EmulatorState.Running;
public bool IsEmulatorUninitialized => EmulatorState == EmulatorState.Uninitialized;
// Debug tab visibility from config
public bool IsDebugTabVisible => _emulatorConfig.ShowDebugTab;
// Private field to cache validation errors
private readonly ObservableAsPropertyHelper<ObservableCollection<string>> _validationErrors;
public ObservableCollection<string> ValidationErrors => _validationErrors.Value;
// Computed property that updates when ValidationErrors changes
private readonly ObservableAsPropertyHelper<bool> _hasValidationErrors;
public bool HasValidationErrors => _hasValidationErrors.Value;
// Private field for log messages collection
private readonly ObservableCollection<LogDisplayEntry> _logMessages = new();
public ObservableCollection<LogDisplayEntry> LogMessages => _logMessages;
// Log tab header properties
private string _logTabHeader = "Log";
public string LogTabHeader
{
get => _logTabHeader;
private set => this.RaiseAndSetIfChanged(ref _logTabHeader, value);
}
private bool _hasLogErrors = false;
public bool HasLogErrors
{
get => _hasLogErrors;
private set => this.RaiseAndSetIfChanged(ref _hasLogErrors, value);
}
// Scripts tab properties
private string _scriptsTabHeader = "Scripts";
public string ScriptsTabHeader
{
get => _scriptsTabHeader;
private set => this.RaiseAndSetIfChanged(ref _scriptsTabHeader, value);
}
private bool _hasDisabledScripts = false;
public bool HasDisabledScripts
{
get => _hasDisabledScripts;
private set => this.RaiseAndSetIfChanged(ref _hasDisabledScripts, value);
}
private bool _isScriptingEnabled;
public bool IsScriptingEnabled
{
get => _isScriptingEnabled;
private set => this.RaiseAndSetIfChanged(ref _isScriptingEnabled, value);
}
private readonly ObservableCollection<ScriptDisplayEntry> _scriptEntries = new();
public ObservableCollection<ScriptDisplayEntry> ScriptEntries => _scriptEntries;
private ScriptSortColumn _scriptSortColumn = ScriptSortColumn.FileName;
private bool _scriptSortAscending = true;
public string FileNameSortIndicator => SortIndicator(ScriptSortColumn.FileName);
public string StatusSortIndicator => SortIndicator(ScriptSortColumn.Status);
public string YieldSortIndicator => SortIndicator(ScriptSortColumn.YieldType);
public string HooksSortIndicator => SortIndicator(ScriptSortColumn.Hooks);
private string SortIndicator(ScriptSortColumn col) =>
_scriptSortColumn == col ? (_scriptSortAscending ? " ▲" : " ▼") : "";
public bool CanManageScripts { get; }
public bool CanLoadExamples { get; }
// Show the script directory info banner on Desktop (not browser) when scripting is enabled
public bool ShowScriptDirectoryInfo => IsScriptingEnabled && !CanManageScripts;
public string ScriptDirectory => _hostApp.ScriptDirectory;
// Tab tracking for performance optimization
private string _selectedTabName = "";
public string SelectedTabName
{
get => _selectedTabName;
set
{
this.RaiseAndSetIfChanged(ref _selectedTabName, value);
// Notify that log tab visibility may have changed
this.RaisePropertyChanged(nameof(IsLogTabVisible));
// If log tab just became visible and there are pending updates, trigger immediate update
if (IsLogTabVisible)
{
lock (_logUpdateLock)
{
if (_hasPendingLogUpdates)
{
// Copy new messages from backing store to UI collection
var newMessages = _logMessagesBackingStore.Skip(_logMessages.Count).ToList();
_hasPendingLogUpdates = false;
global::Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
try
{
// Add new messages to UI collection
foreach (var message in newMessages)
{
_logMessages.Add(message);
}
UpdateLogTabHeader();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating log UI on tab switch");
}
});
}
}
}
}
}
// Check if log tab is currently visible by name
public bool IsLogTabVisible => string.Equals(_selectedTabName, "LogTabItem", StringComparison.OrdinalIgnoreCase);
// Timer for batched UI updates
private Timer? _logUpdateTimer;
private readonly object _logUpdateLock = new object();
private bool _hasPendingLogUpdates = false;
// Thread-safe backing collection for log messages
private readonly List<LogDisplayEntry> _logMessagesBackingStore = new();
// Statistics panel visibility
private readonly ObservableAsPropertyHelper<bool> _isStatisticsPanelVisible;
public bool IsStatisticsPanelVisible => _isStatisticsPanelVisible.Value;
// Statistics panel column width - bind this to the grid column width
public string StatisticsPanelColumnWidth => "250";
// Monitor visibility - watches Monitor.IsVisible directly
private bool _isMonitorVisible;
private AvaloniaMonitor? _currentMonitor; // Track current monitor for proper event unsubscription
public bool IsMonitorVisible
{
get => _isMonitorVisible;
private set => this.RaiseAndSetIfChanged(ref _isMonitorVisible, value);
}
// Monitor ViewModel - created when monitor is enabled
private MonitorViewModel? _monitorViewModel;
public MonitorViewModel? MonitorViewModel
{
get
{
// Lazy creation: if monitor is visible but ViewModel is null, create it
if (_monitorViewModel == null && IsMonitorVisible)
{
_monitorViewModel = CreateMonitorViewModel();
}
return _monitorViewModel;
}
private set => this.RaiseAndSetIfChanged(ref _monitorViewModel, value);
}
// Audio properties - track AudioSupported and AudioEnabled from HostApp
private readonly ObservableAsPropertyHelper<bool> _audioSupported;
public bool AudioSupported => _audioSupported.Value;
public bool AudioSettingsEnabled => AudioSupported && EmulatorState == EmulatorState.Uninitialized;
// AudioEnabled - two-way binding property
private bool _audioEnabled;
public bool AudioEnabled
{
get => _audioEnabled;
set
{
if (_audioEnabled != value)
{
this.RaiseAndSetIfChanged(ref _audioEnabled, value);
// Update the host app when the value changes from UI
_hostApp.SetAudioEnabled(value).Wait();
}
}
}
private readonly ObservableAsPropertyHelper<string?> _audioTooltip;
public string? AudioTooltip => _audioTooltip.Value;
// Audio volume property - two-way binding
private double _audioVolumePercent = 20.0;
public double AudioVolumePercent
{
get => _audioVolumePercent;
set
{
this.RaiseAndSetIfChanged(ref _audioVolumePercent, value);
_hostApp.SetVolumePercent((float)value);
}
}
// External debug server properties (Desktop only; null controller → all false/zero)
private readonly IExternalDebugController? _externalDebugController;
public bool IsExternalDebugServerAvailable => _externalDebugController != null;
private bool _isExternalDebugListening;
public bool IsExternalDebugListening
{
get => _isExternalDebugListening;
private set => this.RaiseAndSetIfChanged(ref _isExternalDebugListening, value);
}
private bool _isExternalDebugClientConnected;
public bool IsExternalDebugClientConnected
{
get => _isExternalDebugClientConnected;
private set => this.RaiseAndSetIfChanged(ref _isExternalDebugClientConnected, value);
}
private int _externalDebugPort = 6502;
public int ExternalDebugPort
{
get => _externalDebugPort;
set => this.RaiseAndSetIfChanged(ref _externalDebugPort, value);
}
public string ExternalDebugStatusText => _externalDebugController switch
{
null => "",
{ IsClientConnected: true } => "Connected",
{ IsListening: true } => $"Listening on :{_externalDebugController.Port}",
_ => "Off"
};
public string ExternalDebugToggleButtonText => _isExternalDebugListening ? "Stop" : "Start";
public ReactiveCommand<Unit, Unit> ToggleExternalDebugCommand { get; }
public void ClearMonitorViewModel()
{
MonitorViewModel = null;
}
/// <summary>
/// Refreshes config-dependent properties after configuration changes.
/// Call this after saving emulator configuration.
/// </summary>
public void RefreshConfigProperties()
{
this.RaisePropertyChanged(nameof(IsDebugTabVisible));
}
// --- End Binding Properties ---
// --- ReactiveUI Commands ---
public ReactiveCommand<Unit, Unit> StartCommand { get; }
public ReactiveCommand<Unit, Unit> PauseCommand { get; }
public ReactiveCommand<Unit, Unit> StopCommand { get; }
public ReactiveCommand<Unit, Unit> ResetCommand { get; }
public ReactiveCommand<Unit, Unit> MonitorCommand { get; }
public ReactiveCommand<Unit, Unit> StatsCommand { get; }
public ReactiveCommand<Unit, Unit> ClearLogCommand { get; }
public ReactiveCommand<string, Unit> SelectSystemCommand { get; }
public ReactiveCommand<string, Unit> SelectSystemVariantCommand { get; }
public ReactiveCommand<string, Unit> ToggleScriptEnabledCommand { get; }
public ReactiveCommand<string, Unit> ReloadScriptCommand { get; }
public ReactiveCommand<Unit, Unit> AddScriptCommand { get; }
public ReactiveCommand<string, Unit> EditScriptCommand { get; }
public ReactiveCommand<string, Unit> DeleteScriptCommand { get; }
public ReactiveCommand<Unit, Unit> LoadExamplesCommand { get; }
public ReactiveCommand<Unit, Unit> RefreshScriptsCommand { get; }
public ReactiveCommand<Unit, Unit> OpenScriptFolderCommand { get; }
public ReactiveCommand<ScriptSortColumn, Unit> SortByColumnCommand { get; }
// Events for script editor dialog (UI operation handled in View code-behind)
public event EventHandler? RequestAddScript;
public event EventHandler<string>? RequestEditScript;
public event EventHandler<DeleteScriptConfirmationEventArgs>? RequestDeleteScript;
public event EventHandler? RequestOpenScriptFolder;
// Event for requesting the emulator options overlay (UI operation handled in View)
public event EventHandler? EmulatorOptionsRequested;
public ReactiveCommand<Unit, Unit> EmulatorOptionsCommand { get; }
// --- End ReactiveUI Commands ---
//public string Version => System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown";
public string Version => Assembly.GetEntryAssembly()!.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion;
// New properties to display runtime versions
public string DotNetVersion => RuntimeInformation.FrameworkDescription;
public string AvaloniaVersion
{
get
{
try
{
var asm = typeof(global::Avalonia.Controls.Control).Assembly;
var infoAttr = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
return infoAttr?.InformationalVersion ?? asm.GetName().Version?.ToString() ?? "Unknown";
}
catch
{
return "Unknown";
}
}
}
public string OSVersion => RuntimeInformation.OSDescription;
// Constructor with dependency injection - child ViewModels injected!
public MainViewModel(
AvaloniaHostApp hostApp,
EmulatorConfig emulatorConfig,
C64MenuViewModel c64MenuViewModel,
C64InfoViewModel c64InfoViewModel,
StatisticsViewModel statisticsViewModel,
EmulatorViewModel emulatorViewModel,
EmulatorPlaceholderViewModel emulatorPlaceholderViewModel,
ILoggerFactory loggerFactory)
{
_hostApp = hostApp ?? throw new ArgumentNullException(nameof(hostApp));
_emulatorConfig = emulatorConfig;
_logger = loggerFactory?.CreateLogger(nameof(MainViewModel)) ?? throw new ArgumentNullException(nameof(loggerFactory));
// Store injected child ViewModels
C64MenuViewModel = c64MenuViewModel ?? throw new ArgumentNullException(nameof(c64MenuViewModel));
C64InfoViewModel = c64InfoViewModel ?? throw new ArgumentNullException(nameof(c64InfoViewModel));
StatisticsViewModel = statisticsViewModel ?? throw new ArgumentNullException(nameof(statisticsViewModel));
EmulatorViewModel = emulatorViewModel ?? throw new ArgumentNullException(nameof(emulatorViewModel));
EmulatorPlaceholderViewModel = emulatorPlaceholderViewModel ?? throw new ArgumentNullException(nameof(emulatorPlaceholderViewModel));
// Set up reactive properties - all derived from HostApp (read-only)
_selectedSystemName = _hostApp
.WhenAnyValue(x => x.SelectedSystemName)
.ToProperty(this, x => x.SelectedSystemName);
_selectedSystemConfigurationVariant = _hostApp
.WhenAnyValue(x => x.SelectedSystemConfigurationVariant)
.ToProperty(this, x => x.SelectedSystemVariant);
_availableSystems = _hostApp
.WhenAnyValue(x => x.AvailableSystemNames)
.Select(systems => new ObservableCollection<string>(systems))
.ToProperty(this, x => x.AvailableSystems);
_availableSystemVariants = _hostApp
.WhenAnyValue(x => x.AllSelectedSystemConfigurationVariants)
.Select(variants => new ObservableCollection<string>(variants))
.ToProperty(this, x => x.AvailableSystemVariants);
_emulatorState = _hostApp
.WhenAnyValue(x => x.EmulatorState)
.ToProperty(this, x => x.EmulatorState);
_isExternalDebuggerAttached = _hostApp
.WhenAnyValue(x => x.IsExternalDebuggerAttached)
.ToProperty(this, x => x.IsExternalDebuggerAttached);
// Subscribe to EmulatorState changes AFTER ToProperty to ensure the value is updated first
this.WhenAnyValue(x => x.EmulatorState)
.Subscribe(_ =>
{
// Notify all computed properties that depend on EmulatorState
this.RaisePropertyChanged(nameof(IsEmulatorRunning));
this.RaisePropertyChanged(nameof(IsEmulatorUninitialized));
this.RaisePropertyChanged(nameof(AudioSettingsEnabled));
});
_scale = _hostApp
.WhenAnyValue(x => x.Scale)
.Select(s => (double)s)
.ToProperty(this, x => x.Scale);
_validationErrors = _hostApp
.WhenAnyValue(x => x.ValidationErrors)
.Select(errors => new ObservableCollection<string>(errors))
.ToProperty(this, x => x.ValidationErrors);
_hasValidationErrors = _hostApp
.WhenAnyValue(x => x.ValidationErrors)
.Select(errors => errors != null && errors.Count > 0)
.ToProperty(this, x => x.HasValidationErrors);
_isStatisticsPanelVisible = _hostApp
.WhenAnyValue(x => x.IsStatsPanelVisible)
.ToProperty(this, x => x.IsStatisticsPanelVisible);
// Subscribe to Monitor.IsVisible changes via HostApp.Monitor
// When Monitor changes (new system started), resubscribe to the new Monitor's PropertyChanged
_hostApp
.WhenAnyValue(x => x.Monitor)
.Subscribe(monitor =>
{
// Unsubscribe from previous monitor if exists
if (_currentMonitor != null)
{
_currentMonitor.PropertyChanged -= OnMonitorPropertyChanged;
}
_currentMonitor = monitor;
// Update visibility when monitor changes (e.g., on Stop, Monitor becomes null)
IsMonitorVisible = monitor?.IsVisible ?? false;
// Subscribe to new monitor's PropertyChanged
if (monitor != null)
{
monitor.PropertyChanged += OnMonitorPropertyChanged;
}
});
// Initialize Audio properties - track changes to CurrentHostSystemConfig
_audioSupported = _hostApp
.WhenAnyValue(x => x.CurrentHostSystemConfig)
.Select(config => config?.AudioSupported ?? false)
.ToProperty(this, x => x.AudioSupported);
// Subscribe to AudioSupported changes AFTER ToProperty to ensure the value is updated first
this.WhenAnyValue(x => x.AudioSupported)
.Subscribe(_ =>
{
// Notify AudioSettingsEnabled that depends on AudioSupported
this.RaisePropertyChanged(nameof(AudioSettingsEnabled));
});
// Subscribe to AudioEnabled changes from HostApp to update the UI property
_hostApp
.WhenAnyValue(x => x.CurrentHostSystemConfig)
.Select(config => config?.SystemConfig?.AudioEnabled ?? false)
.Subscribe(async enabled =>
{
if (_audioEnabled != enabled)
{
_audioEnabled = enabled;
this.RaisePropertyChanged(nameof(AudioEnabled));
}
});
_audioTooltip = _hostApp
.WhenAnyValue(x => x.CurrentHostSystemConfig)
.Select(config => GetAudioToolTip(config))
.ToProperty(this, x => x.AudioTooltip);
// External debug server (Desktop only — null on Browser)
_externalDebugController = App.Current?.ExternalDebugController;
if (_externalDebugController != null)
{
_isExternalDebugListening = _externalDebugController.IsListening;
_isExternalDebugClientConnected = _externalDebugController.IsClientConnected;
_externalDebugPort = _externalDebugController.Port;
_externalDebugController.StateChanged += OnExternalDebugControllerStateChanged;
}
ToggleExternalDebugCommand = ReactiveCommandHelper.CreateSafeCommand(
async () =>
{
if (_externalDebugController!.IsListening)
await _externalDebugController.StopAsync();
else
await _externalDebugController.StartAsync(Math.Max(1, _externalDebugPort));
},
this.WhenAnyValue(
x => x.IsExternalDebugClientConnected,
connected => !connected),
RxSchedulers.MainThreadScheduler);
// Initialize ReactiveCommands for ComboBox selections
SelectSystemCommand = ReactiveCommandHelper.CreateSafeCommand<string>(
async (selectedSystem) =>
{
if (!string.IsNullOrEmpty(selectedSystem) && _hostApp.SelectedSystemName != selectedSystem)
{
await _hostApp.SelectSystem(selectedSystem);
}
},
this.WhenAnyValue(
x => x.EmulatorState,
state => state == EmulatorState.Uninitialized),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
SelectSystemVariantCommand = ReactiveCommandHelper.CreateSafeCommand<string>(
async (selectedVariant) =>
{
if (!string.IsNullOrEmpty(selectedVariant) && _hostApp.SelectedSystemConfigurationVariant != selectedVariant)
{
await _hostApp.SelectSystemConfigurationVariant(selectedVariant);
}
},
this.WhenAnyValue(
x => x.EmulatorState,
state => state == EmulatorState.Uninitialized),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
// Initialize ReactiveCommands for buttons
StartCommand = ReactiveCommandHelper.CreateSafeCommand(
async () => await _hostApp.Start(),
this.WhenAnyValue(
x => x.EmulatorState,
x => x.HasValidationErrors,
(state, hasErrors) => !hasErrors && state != EmulatorState.Running),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
PauseCommand = ReactiveCommandHelper.CreateSafeCommand(
async () => _hostApp.Pause(),
this.WhenAnyValue(
x => x.EmulatorState,
state => state == EmulatorState.Running),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
StopCommand = ReactiveCommandHelper.CreateSafeCommand(
async () => _hostApp.Stop(),
this.WhenAnyValue(
x => x.EmulatorState,
state => state != EmulatorState.Uninitialized),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
ResetCommand = ReactiveCommandHelper.CreateSafeCommand(
async () => await _hostApp.Reset(),
this.WhenAnyValue(
x => x.EmulatorState,
state => state != EmulatorState.Uninitialized),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
MonitorCommand = ReactiveCommandHelper.CreateSafeCommand(
async () => _hostApp.Monitor?.Toggle(),
this.WhenAnyValue(
x => x.EmulatorState,
x => x.IsExternalDebuggerAttached,
(state, isExternalDebuggerAttached) => state == EmulatorState.Running && !isExternalDebuggerAttached),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
StatsCommand = ReactiveCommandHelper.CreateSafeCommand(
async () => _hostApp.ToggleStatisticsPanel(),
this.WhenAnyValue(
x => x.EmulatorState,
state => state != EmulatorState.Uninitialized),
RxSchedulers.MainThreadScheduler); // RxSchedulers.MainThreadScheduler required for it working in Browser app
ClearLogCommand = ReactiveCommandHelper.CreateSafeCommand(
() =>
{
_logger.LogInformation("Clearing log messages via ClearLogCommand");
lock (_logUpdateLock)
{
_logMessagesBackingStore.Clear();
_logMessages.Clear();
_hasPendingLogUpdates = false;
}
UpdateLogTabHeader();
if (_hostApp.LogStore is DotNet6502InMemLogStore logStore)
{
logStore.Clear();
}
},
this.WhenAnyValue(
x => x.LogMessages.Count,
count => count > 0),
RxSchedulers.MainThreadScheduler);
ToggleScriptEnabledCommand = ReactiveCommandHelper.CreateSafeCommand<string>(
(fileName) =>
{
var entry = _scriptEntries.FirstOrDefault(e => e.FileName == fileName);
if (entry == null) return;
bool newEnabled = entry.IsUserDisabled;
_hostApp.ScriptingEngine.SetScriptEnabled(fileName, newEnabled);
},
null,
RxSchedulers.MainThreadScheduler);
ReloadScriptCommand = ReactiveCommandHelper.CreateSafeCommand<string>(
(fileName) =>
{
_hostApp.ScriptingEngine.ReloadScript(fileName);
},
null,
RxSchedulers.MainThreadScheduler);
AddScriptCommand = ReactiveCommandHelper.CreateSafeCommand(
() =>
{
RequestAddScript?.Invoke(this, EventArgs.Empty);
},
null,
RxSchedulers.MainThreadScheduler);
EditScriptCommand = ReactiveCommandHelper.CreateSafeCommand<string>(
(fileName) =>
{
RequestEditScript?.Invoke(this, fileName);
},
null,
RxSchedulers.MainThreadScheduler);
DeleteScriptCommand = ReactiveCommandHelper.CreateSafeCommand<string>(
async (fileName) =>
{
var tcs = new TaskCompletionSource<bool>();
var args = new DeleteScriptConfirmationEventArgs(fileName, tcs);
RequestDeleteScript?.Invoke(this, args);
if (await tcs.Task)
_hostApp.DeleteScript(fileName);
},
null,
RxSchedulers.MainThreadScheduler);
RefreshScriptsCommand = ReactiveCommandHelper.CreateSafeCommand(
() => _hostApp.RefreshScripts(),
null,
RxSchedulers.MainThreadScheduler);
OpenScriptFolderCommand = ReactiveCommandHelper.CreateSafeCommand(
() => RequestOpenScriptFolder?.Invoke(this, EventArgs.Empty),
null,
RxSchedulers.MainThreadScheduler);
SortByColumnCommand = ReactiveCommandHelper.CreateSafeCommand<ScriptSortColumn>(
col =>
{
if (_scriptSortColumn == col)
_scriptSortAscending = !_scriptSortAscending;
else
{
_scriptSortColumn = col;
_scriptSortAscending = true;
}
ApplyScriptSort();
this.RaisePropertyChanged(nameof(FileNameSortIndicator));
this.RaisePropertyChanged(nameof(StatusSortIndicator));
this.RaisePropertyChanged(nameof(YieldSortIndicator));
this.RaisePropertyChanged(nameof(HooksSortIndicator));
},
null,
RxSchedulers.MainThreadScheduler);
// Emulator Options command - only enabled when emulator is uninitialized
EmulatorOptionsCommand = ReactiveCommandHelper.CreateSafeCommand(
() =>
{
EmulatorOptionsRequested?.Invoke(this, EventArgs.Empty);
},
this.WhenAnyValue(
x => x.EmulatorState,
state => state == EmulatorState.Uninitialized),
RxSchedulers.MainThreadScheduler);
// Initialize timer for batched log UI updates
InitializeLogUpdateTimer();
// Populate log messages initially
RefreshLogMessages();
// Subscribe to new log messages
_hostApp.LogStore?.LogMessageAdded += (sender, logEntry) =>
{
// Add message to backing store on current thread (no UI dispatch!)
lock (_logUpdateLock)
{
_logMessagesBackingStore.Add(new LogDisplayEntry(logEntry));
_hasPendingLogUpdates = true;
}
};
// System-specific ViewModel initializations
this.WhenAnyValue(x => x.SelectedSystemName)
.Subscribe(_ =>
{
this.RaisePropertyChanged(nameof(IsC64SystemSelected));
ActiveMenuContributor = ResolveMenuContributor();
});
// Initialize scripts tab data and subscribe to status changes
CanManageScripts = _hostApp.CanManageScripts;
CanLoadExamples = _hostApp.CanLoadExamples;
LoadExamplesCommand = ReactiveCommandHelper.CreateSafeCommand(
async () => await _hostApp.LoadExamplesAsync(),
null,
RxSchedulers.MainThreadScheduler);
RefreshScriptStatuses();
_hostApp.ScriptingEngine.ScriptStatusChanged += OnScriptStatusChanged;
}
private string GetAudioToolTip(IHostSystemConfig config)
{
if (config == null)
return string.Empty;
if (!config.AudioSupported)
return "Audio is not supported on current platform.";
if (PlatformDetection.IsRunningOnDesktop())
return "Audio is experimental. Fast assembly routines may not play audio correctly.";
if (PlatformDetection.IsRunningInWebAssembly())
return "Audio is experimental. Fast assembly routines may not play audio correctly. In browser there is a bigger performance cost that may affect entire emulation FPS. See config settings menu for different audio profiles to balance accuracy against latency.";
return string.Empty;
}
public async Task InitializeAsync()
{
await SetDefaultSystemSelection();
}
private ISystemMenuContributor? ResolveMenuContributor()
{
// Each system's menu ViewModel implements ISystemMenuContributor when it contributes
// shortcuts. Add more `else if` branches here as new systems gain shortcuts.
if (IsC64SystemSelected && C64MenuViewModel is ISystemMenuContributor c64Contributor)
return c64Contributor;
return null;
}
private async Task SetDefaultSystemSelection()
{
if (HostApp == null)
return;
// Skip default system selection if automated startup is handling it
if (HostApp.SkipDefaultSystemSelection)
{
_logger.LogInformation("Skipping default system selection - automated startup is active");
return;
}
_logger.LogInformation($"Setting default system '{_emulatorConfig.DefaultEmulator}' during MainViewModel initialization");
await HostApp.SelectSystem(_emulatorConfig.DefaultEmulator);
}
/// <summary>
/// Initialize the timer for batched log UI updates
/// </summary>
private void InitializeLogUpdateTimer()
{
_logUpdateTimer = new Timer(500); // Interval in ms
_logUpdateTimer.Elapsed += OnLogUpdateTimerElapsed;
_logUpdateTimer.AutoReset = true;
_logUpdateTimer.Start();
}
/// <summary>
/// Timer callback for batched log UI updates - only updates UI when log tab is visible
/// </summary>
private void OnLogUpdateTimerElapsed(object? sender, ElapsedEventArgs e)
{
lock (_logUpdateLock)
{
// Only update UI notifications if there are pending updates and log tab is visible
if (_hasPendingLogUpdates && IsLogTabVisible)
{
// Copy new messages from backing store to UI collection
var newMessages = _logMessagesBackingStore.Skip(_logMessages.Count).ToList();
_hasPendingLogUpdates = false;
// Dispatch UI update to UI thread
global::Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
try
{
// Add new messages to UI collection
foreach (var message in newMessages)
{
_logMessages.Add(message);
}
UpdateLogTabHeader();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating log UI");
}
});
}
// If log tab is not visible, keep pending updates flag to update later when tab becomes visible
else if (_hasPendingLogUpdates && !IsLogTabVisible)
{
// Keep the flag, will update when tab becomes visible
}
else
{
// Reset flag if no pending updates
_hasPendingLogUpdates = false;
}
}
}
/// <summary>
/// Refresh the log messages from the HostApp's log store
/// </summary>
public void RefreshLogMessages()
{
if (_hostApp?.LogStore == null)
return;
var logs = _hostApp.LogStore.GetFullLogMessages();
lock (_logUpdateLock)
{
// Update both backing store and UI collection with initial data
_logMessagesBackingStore.Clear();
foreach (var log in logs)
{
_logMessagesBackingStore.Add(new LogDisplayEntry(log));
}
// Only update UI collection if the logs have changed
if (logs.Count != _logMessages.Count || !logs.Select(l => l.Message).SequenceEqual(_logMessages.Select(l => l.Message)))
{
_logMessages.Clear();
foreach (var entry in _logMessagesBackingStore)
{
_logMessages.Add(entry);
}
}
}
UpdateLogTabHeader();
}
/// <summary>
/// Updates the log tab header and error state based on error/critical message count
/// </summary>
private void UpdateLogTabHeader()
{
var errorCount = _logMessages.Count(m => m.LogLevel == LogLevel.Error || m.LogLevel == LogLevel.Critical);
LogTabHeader = errorCount > 0 ? $"Log ({errorCount})" : "Log";
HasLogErrors = errorCount > 0;
}
private void RefreshScriptStatuses()
{
var engine = _hostApp.ScriptingEngine;
IsScriptingEnabled = engine.IsEnabled;
var statuses = engine.GetScriptStatuses();
_scriptEntries.Clear();
foreach (var status in statuses)
_scriptEntries.Add(new ScriptDisplayEntry(status));
ApplyScriptSort();
UpdateScriptsTabHeader();
}
private void ApplyScriptSort()
{
var sorted = (_scriptSortColumn switch
{
ScriptSortColumn.Status => _scriptSortAscending ? _scriptEntries.OrderBy(e => e.Status) : _scriptEntries.OrderByDescending(e => e.Status),
ScriptSortColumn.YieldType => _scriptSortAscending ? _scriptEntries.OrderBy(e => e.YieldType) : _scriptEntries.OrderByDescending(e => e.YieldType),
ScriptSortColumn.Hooks => _scriptSortAscending ? _scriptEntries.OrderBy(e => e.Hooks) : _scriptEntries.OrderByDescending(e => e.Hooks),
_ => _scriptSortAscending ? _scriptEntries.OrderBy(e => e.FileName) : _scriptEntries.OrderByDescending(e => e.FileName),
}).ToList();
for (int i = 0; i < sorted.Count; i++)
{
int current = _scriptEntries.IndexOf(sorted[i]);
if (current != i)
_scriptEntries.Move(current, i);
}
}
private void UpdateScriptsTabHeader()
{
var systemDisabledCount = _scriptEntries.Count(s => s.IsDisabled);
var activeCount = _scriptEntries.Count(s => s.IsScriptEnabled);
if (_scriptEntries.Count == 0)
ScriptsTabHeader = "Scripts";
else if (systemDisabledCount > 0 && activeCount > 0)
ScriptsTabHeader = $"Scripts ({activeCount}, {systemDisabledCount} disabled)";
else if (systemDisabledCount > 0)
ScriptsTabHeader = $"Scripts ({systemDisabledCount} disabled)";
else if (activeCount > 0)
ScriptsTabHeader = $"Scripts ({activeCount})";
else
ScriptsTabHeader = "Scripts";
// Only flag red styling for system-disabled scripts (errors), not user-disabled
HasDisabledScripts = systemDisabledCount > 0;
}
private void OnScriptStatusChanged(object? sender, EventArgs e)
{
global::Avalonia.Threading.Dispatcher.UIThread.Post(() => RefreshScriptStatuses());
}
/// <summary>
/// Creates a MonitorViewModel for the current monitor instance.
/// This method should be called by views that need to display the monitor.
/// </summary>
/// <returns>MonitorViewModel if monitor is available, null otherwise</returns>
private MonitorViewModel? CreateMonitorViewModel()
{
if (_hostApp.Monitor == null)
return null;
return new MonitorViewModel(_hostApp.Monitor, _hostApp);
}
/// <summary>
/// Handles StateChanged events from the external debug controller.
/// Fired from a background thread; dispatches property notifications to the UI thread.
/// </summary>
private void OnExternalDebugControllerStateChanged(object? sender, EventArgs e)
{
global::Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
IsExternalDebugListening = _externalDebugController?.IsListening ?? false;
IsExternalDebugClientConnected = _externalDebugController?.IsClientConnected ?? false;
if (_externalDebugController != null)
ExternalDebugPort = _externalDebugController.Port;
this.RaisePropertyChanged(nameof(ExternalDebugStatusText));
this.RaisePropertyChanged(nameof(ExternalDebugToggleButtonText));
});
}