-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1619 lines (1437 loc) · 61.2 KB
/
MainWindow.xaml.cs
File metadata and controls
1619 lines (1437 loc) · 61.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.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Material.Icons;
using MiIcon = Material.Icons.WPF.MaterialIcon;
using Wpf.Ui.Controls;
using AmpUp.Views;
using AmpUp.Core.Services;
namespace AmpUp;
public partial class MainWindow : FluentWindow
{
private readonly MixerView _mixerView = new();
private readonly ButtonsView _buttonsView = new();
private readonly LightsView _lightsView = new();
private readonly SettingsView _settingsView = new();
private readonly RoomView _ambienceView = new();
private readonly BindingsView _bindingsView = new();
private readonly OsdView _osdView = new();
private readonly GroupsView _groupsView = new();
private System.Windows.Controls.Button? _activeNavButton;
private System.Windows.Controls.Border? _activeNavBar;
private Window? _profileFlyout;
private bool _profileFlyoutOpen = false;
private bool _turnUpConnected;
private bool _streamControllerConnected;
private AppConfig _config;
private AudioMixer? _mixer;
private Action<AppConfig>? _onConfigChanged;
private System.Windows.Threading.DispatcherTimer? _hwPreviewTimer;
private volatile bool _windowActive = true; // safe to read from any thread
private long _lastHwPreviewLedFrameTick;
public MainWindow()
{
InitializeComponent();
Icon = new BitmapImage(new Uri("pack://application:,,,/Assets/icon/ampup-48.png", UriKind.Absolute));
_config = ConfigManager.Load();
VersionLabel.Text = $"v{UpdateChecker.CurrentVersion}";
UpdateProfileButton();
UpdateAccentDependentUI();
_bindingsView.SetNavigationCallbacks(
profileName =>
{
if (_config.ActiveProfile != profileName)
{
_onConfigChanged?.Invoke(_config);
(Application.Current as App)?.SwitchToProfile(profileName);
}
NavigateTo(_mixerView, NavMixer);
},
profileName =>
{
if (_config.ActiveProfile != profileName)
{
_onConfigChanged?.Invoke(_config);
(Application.Current as App)?.SwitchToProfile(profileName);
}
NavigateTo(_buttonsView, NavButtons);
},
profileName =>
{
_onConfigChanged?.Invoke(_config);
(Application.Current as App)?.SwitchToProfile(profileName);
// Stay on Overview — don't navigate away
NavigateTo(_bindingsView, NavBindings);
},
profileName =>
{
// Preview OSD for this profile without switching
var app = Application.Current as App;
if (app == null) return;
var profileConfig = ConfigManager.LoadProfile(profileName) ?? _config;
var iconCfg = _config.ProfileIcons.GetValueOrDefault(profileName) ?? new ProfileIconConfig();
app.PreviewProfileOsd(profileName, iconCfg, profileConfig);
});
_bindingsView.OnDuplicateProfile = profileName =>
{
DuplicateProfile(profileName);
};
_bindingsView.OnMoveProfile = (profileName, direction) =>
{
MoveProfile(profileName, direction);
};
NavigateTo(_mixerView, NavMixer);
SetupTrafficLightHovers();
ThemeManager.OnAccentChanged += () => Dispatcher.Invoke(UpdateAccentDependentUI);
// Remove Win11 DWM border (the white/gray 1px border around the window)
SourceInitialized += (_, _) =>
{
var hwnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;
NativeMethods.RemoveDwmBorder(hwnd);
};
// Silent startup update check
Loaded += async (_, _) => await CheckForUpdateOnStartup();
}
/// <summary>
/// Update UI elements that depend on the accent color but can't use DynamicResource
/// (DropShadowEffect Color, GradientStop, etc.).
/// </summary>
private void UpdateAccentDependentUI()
{
// Profile button border gradient
ProfileButton.BorderBrush = new LinearGradientBrush(
ThemeManager.WithAlpha(ThemeManager.Accent, 0x88),
ThemeManager.WithAlpha(ThemeManager.Accent, 0x44),
new Point(0, 0), new Point(1, 1));
// Profile button drop shadow
ProfileButton.Effect = new System.Windows.Media.Effects.DropShadowEffect
{
Color = ThemeManager.Accent,
BlurRadius = 12,
Opacity = 0.25,
ShadowDepth = 0
};
// Connection dot glow
ConnectionDotGlow.Color = ThemeManager.Accent;
}
/// <summary>
/// Wire up backend references and load config into all views.
/// </summary>
public void Initialize(AppConfig config, AudioMixer mixer, Action<AppConfig> onConfigChanged)
{
_config = config;
_mixer = mixer;
_onConfigChanged = onConfigChanged;
ApplyHardwareSurfaceFromState(persist: false);
RefreshViews();
StartHwPreviewTimer();
}
private void StartHwPreviewTimer()
{
// Subscribe to LED frame data from RgbController
if (App.Rgb != null)
App.Rgb.OnFrameReady += OnRgbFrameReady;
// Wire click to navigate to Mixer tab
HwPreview.OnKnobClicked = _ => NavigateTo(_mixerView, NavMixer);
// 100ms timer for preview VU smoothing + position updates.
// The preview is small and always visible while the window is open,
// so avoiding 20 FPS WASAPI peak reads trims idle CPU without
// affecting actual knob/volume handling.
_hwPreviewTimer = new System.Windows.Threading.DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(100)
};
_hwPreviewTimer.Tick += HwPreviewTimer_Tick;
_hwPreviewTimer.Start();
// Stop the timer when minimized or hidden to tray — WPF DispatcherTimers
// keep firing even when the window is minimized, causing unnecessary WASAPI
// peak calls + rendering at 20 FPS with nothing visible.
StateChanged += (_, _) =>
{
if (WindowState == WindowState.Minimized)
{
_windowActive = false;
_hwPreviewTimer.Stop();
}
else
{
_windowActive = true;
_hwPreviewTimer.Start();
}
};
IsVisibleChanged += (_, _) =>
{
if (!IsVisible)
{
_windowActive = false;
_hwPreviewTimer.Stop();
}
else if (WindowState != WindowState.Minimized)
{
_windowActive = true;
_hwPreviewTimer.Start();
}
};
}
private void OnRgbFrameReady(byte[] frame)
{
// Called from RgbController thread — _windowActive is volatile, safe to read here.
// Don't touch any WPF dependency properties (e.g. WindowState, IsVisible) from this thread.
if (!_windowActive) return;
long now = Environment.TickCount64;
long last = Interlocked.Read(ref _lastHwPreviewLedFrameTick);
if (now - last < 100) return;
Interlocked.Exchange(ref _lastHwPreviewLedFrameTick, now);
Dispatcher.BeginInvoke(() => HwPreview.SetLedFrame(frame));
}
private void HwPreviewTimer_Tick(object? sender, EventArgs e)
{
// Push current knob positions
HwPreview.SetPositions(App.KnobPositions);
// Push VU levels from mixer
if (_mixer != null)
{
for (int i = 0; i < 5; i++)
{
var knob = _config.Knobs.FirstOrDefault(k => k.Idx == i);
if (knob != null)
{
float peak = Math.Min(_mixer.GetPeakLevel(knob) * 2.3f, 1f);
HwPreview.SetVuLevel(i, peak);
}
}
}
HwPreview.Tick();
}
public void RefreshViews(AppConfig? newConfig = null)
{
if (newConfig != null) _config = newConfig;
ApplyHardwareSurfaceFromState(persist: false);
UpdateProfileButton();
Action<AppConfig> saveHandler = cfg =>
{
_config = cfg;
_onConfigChanged?.Invoke(cfg);
ApplyHardwareSurfaceFromState(persist: false);
// Update Ambience tab visibility when integrations are toggled
bool showAmbience = cfg.Ambience.GoveeEnabled || cfg.Ambience.GoveeCloudEnabled || cfg.Corsair.Enabled;
NavAmbience.Visibility = showAmbience ? Visibility.Visible : Visibility.Collapsed;
};
_settingsView.OnNavigateToOverview = () => NavigateTo(_bindingsView, NavBindings);
_settingsView.OnEditProfile = profileName => ShowProfileEditor(profileName);
_settingsView.OnActiveSurfaceChangedExternal = surface => ApplyDeviceSurface(surface, persist: true);
_settingsView.OnHardwareModeChangedExternal = () => RefreshViews();
_settingsView.LoadConfig(_config, saveHandler);
_lightsView.LoadConfig(_config, saveHandler, _mixer);
_buttonsView.LoadConfig(_config, _mixer!, saveHandler);
_mixerView.LoadConfig(_config, _mixer!, saveHandler);
_ambienceView.LoadConfig(_config, saveHandler);
_bindingsView.LoadConfig(_config);
_osdView.OnRequestRefresh = () => RefreshViews();
_osdView.LoadConfig(_config, saveHandler);
_groupsView.LoadConfig(_config, saveHandler);
// Show/hide Ambience nav based on Govee or Corsair enabled state
bool ambienceEnabled = _config.Ambience.GoveeEnabled || _config.Ambience.GoveeCloudEnabled || _config.Corsair.Enabled;
NavAmbience.Visibility = ambienceEnabled ? Visibility.Visible : Visibility.Collapsed;
// Sync knob labels into the hardware preview strip
for (int i = 0; i < 5; i++)
{
var knob = _config.Knobs.FirstOrDefault(k => k.Idx == i);
string label = knob != null && !string.IsNullOrWhiteSpace(knob.Label)
? knob.Label
: (knob?.Target ?? (i + 1).ToString());
HwPreview.SetLabel(i, label);
}
}
private void NavMixer_Click(object sender, RoutedEventArgs e) => NavigateTo(_mixerView, NavMixer);
private void NavButtons_Click(object sender, RoutedEventArgs e) => NavigateTo(_buttonsView, NavButtons);
private void NavLights_Click(object sender, RoutedEventArgs e)
{
// Refresh lights view to pick up label/color changes from mixer tab
_lightsView.LoadConfig(_config, cfg =>
{
_config = cfg;
_onConfigChanged?.Invoke(cfg);
}, _mixer);
NavigateTo(_lightsView, NavLights);
}
private void NavAmbience_Click(object sender, RoutedEventArgs e)
{
_ambienceView.LoadConfig(_config, cfg =>
{
_config = cfg;
_onConfigChanged?.Invoke(cfg);
});
NavigateTo(_ambienceView, NavAmbience);
}
private void NavSettings_Click(object sender, RoutedEventArgs e) => NavigateTo(_settingsView, NavSettings);
private void NavBindings_Click(object sender, RoutedEventArgs e) => NavigateTo(_bindingsView, NavBindings);
private void NavOsd_Click(object sender, RoutedEventArgs e) => NavigateTo(_osdView, NavOsd);
private void NavGroups_Click(object sender, RoutedEventArgs e)
{
_groupsView.LoadConfig(_config, cfg =>
{
_config = cfg;
_onConfigChanged?.Invoke(cfg);
});
NavigateTo(_groupsView, NavGroups);
}
public void NavigateToSettings() => NavigateTo(_settingsView, NavSettings);
public void LaunchImportWizard()
{
var wizard = new ImportWizardWindow { Owner = this };
wizard.ShowDialog();
if (wizard.ImportedProfileName != null)
{
var profileName = wizard.ImportedProfileName;
if (!_config.Profiles.Contains(profileName))
_config.Profiles.Add(profileName);
var loaded = ConfigManager.LoadProfile(profileName);
if (loaded != null)
{
loaded.ActiveProfile = profileName;
PreserveGlobalSettings(loaded);
_config = loaded;
_onConfigChanged?.Invoke(_config);
RefreshViews();
RefreshProfilePicker();
}
}
}
// Map nav buttons to their indicator bars
private Dictionary<System.Windows.Controls.Button, System.Windows.Controls.Border> GetNavBars() => new()
{
{ NavMixer, NavMixerBar },
{ NavButtons, NavButtonsBar },
{ NavLights, NavLightsBar },
{ NavAmbience, NavAmbienceBar },
{ NavOsd, NavOsdBar },
{ NavGroups, NavGroupsBar },
{ NavSettings, NavSettingsBar },
{ NavBindings, NavBindingsBar },
};
private void NavigateTo(System.Windows.Controls.UserControl view, System.Windows.Controls.Button navButton)
{
ContentArea.Content = view;
// Update sidebar highlight (icon + label)
var accent = (SolidColorBrush)FindResource("AccentBrush");
var dimIcon = (SolidColorBrush)FindResource("TextSecBrush");
var dimLabel = (SolidColorBrush)FindResource("TextSecBrush");
if (_activeNavButton != null)
{
var (oldPhIcon, oldLabel) = FindNavChildren(_activeNavButton);
if (oldPhIcon != null) oldPhIcon.IconColor = ((SolidColorBrush)dimIcon).Color;
if (oldLabel != null) oldLabel.Foreground = dimLabel;
if (_activeNavBar != null)
_activeNavBar.Visibility = Visibility.Collapsed;
}
var (newPhIcon, newLabel) = FindNavChildren(navButton);
if (newPhIcon != null) newPhIcon.IconColor = ((SolidColorBrush)accent).Color;
if (newLabel != null) newLabel.Foreground = accent;
// Show new indicator bar
var bars = GetNavBars();
if (bars.TryGetValue(navButton, out var bar))
{
bar.Visibility = Visibility.Visible;
_activeNavBar = bar;
}
_activeNavButton = navButton;
}
private static (Controls.PhosphorIcon? Icon, System.Windows.Controls.TextBlock? Label) FindNavChildren(System.Windows.Controls.Button button)
{
var grid = button.Content as System.Windows.Controls.Grid;
var sp = grid != null
? grid.Children.OfType<System.Windows.Controls.StackPanel>().FirstOrDefault()
: button.Content as System.Windows.Controls.StackPanel;
if (sp != null)
{
var phIcon = sp.Children.OfType<Controls.PhosphorIcon>().FirstOrDefault();
var label = sp.Children.OfType<System.Windows.Controls.TextBlock>().FirstOrDefault();
return (phIcon, label);
}
return (null, null);
}
// ── Window drag ─────────────────────────────────────────────────
private void HeaderBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
// Double-click to toggle maximize
WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
}
else if (e.ButtonState == MouseButtonState.Pressed)
{
try { DragMove(); } catch (InvalidOperationException) { }
}
}
// ── Traffic-light window buttons ──────────────────────────────
private void SetupTrafficLightHovers()
{
// Show icons on hover over any of the 3 buttons
var buttons = new[] { BtnMinimize, BtnMaximize, BtnClose };
var icons = new[] { MinIcon, MaxIcon, CloseIcon };
foreach (var btn in buttons)
{
btn.MouseEnter += (_, _) => { foreach (var ic in icons) ic.Opacity = 1; };
btn.MouseLeave += (_, _) => { foreach (var ic in icons) ic.Opacity = 0; };
}
}
private void BtnMinimize_Click(object sender, MouseButtonEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void BtnMaximize_Click(object sender, MouseButtonEventArgs e)
{
WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
}
private void BtnClose_Click(object sender, MouseButtonEventArgs e)
{
Close(); // triggers MainWindow_Closing → hides to tray
}
private bool _checkingUpdate;
private (string Tag, string Url)? _pendingUpdate;
private async Task CheckForUpdateOnStartup()
{
if (_config.AutoCheckUpdates != true) return;
try
{
var update = await UpdateChecker.CheckForUpdateAsync();
if (update != null)
{
_pendingUpdate = update;
VersionLabel.Text = $"Update available: {update.Value.Tag}";
VersionLabel.Foreground = (SolidColorBrush)FindResource("AccentBrush");
// Notify tray popup
if (Application.Current is App app)
app.NotifyUpdateAvailable();
}
}
catch (Exception ex)
{
Logger.Log($"Startup update check failed: {ex.Message}");
}
}
private async void VersionLabel_Click(object sender, MouseButtonEventArgs e)
{
if (_checkingUpdate) return;
_checkingUpdate = true;
VersionLabel.Text = "Checking...";
VersionLabel.Foreground = (SolidColorBrush)FindResource("AccentBrush");
try
{
var update = _pendingUpdate ?? await UpdateChecker.CheckForUpdateAsync();
_pendingUpdate = null;
if (update == null)
{
VersionLabel.Text = "Up to date!";
VersionLabel.Foreground = (SolidColorBrush)FindResource("SuccessGrnBrush");
await Task.Delay(2000);
VersionLabel.Text = $"v{UpdateChecker.CurrentVersion}";
VersionLabel.Foreground = (SolidColorBrush)FindResource("TextDimBrush");
}
else
{
var (tag, url) = update.Value;
if (GlassDialog.Confirm($"A new version ({tag}) is available. Download and install?", "UPDATE", owner: this))
{
VersionLabel.Text = "Downloading...";
await UpdateChecker.DownloadAndInstallAsync(url, progress =>
{
Dispatcher.Invoke(() => VersionLabel.Text = $"Downloading {progress}%");
});
}
else
{
VersionLabel.Text = $"v{UpdateChecker.CurrentVersion}";
VersionLabel.Foreground = (SolidColorBrush)FindResource("TextDimBrush");
}
}
}
catch (Exception ex)
{
Logger.Log($"Update check error: {ex.Message}");
VersionLabel.Text = "Update failed";
VersionLabel.Foreground = (SolidColorBrush)FindResource("DangerRedBrush");
await Task.Delay(2000);
VersionLabel.Text = $"v{UpdateChecker.CurrentVersion}";
VersionLabel.Foreground = (SolidColorBrush)FindResource("TextDimBrush");
}
finally
{
_checkingUpdate = false;
}
}
// ── Profile flyout ────────────────────────────────────────────
// Icon options for profile picker — MaterialIconKind names
private static readonly (string Category, string[] Symbols)[] ProfileIconCategories =
{
("Audio & Music", new[] {
"VolumeHigh", "VolumeOff", "VolumeMute", "Headphones",
"MusicNote", "MusicNoteEighth", "Microphone", "MicrophoneOff"
}),
("Gaming & Fun", new[] {
"GamepadVariant", "Trophy", "Rocket", "Star",
"Heart", "EmoticonHappy", "Robot", "AccountCircleOutline"
}),
("Lights & Effects", new[] {
"LightbulbOnOutline", "Flash", "Shimmer", "WeatherCloudy",
"WeatherNight", "WeatherSunny", "WaterOutline", "Fire"
}),
("Work & Streaming", new[] {
"Monitor", "Laptop", "Keyboard", "Video",
"RecordCircle", "Earth", "Bullhorn", "PresentationPlay"
}),
("Home & System", new[] {
"Home", "CogOutline", "Shield", "Lock",
"Eye", "Power", "Bluetooth", "Wifi"
}),
};
// Color presets for profile icons
private static readonly (string Name, string Hex)[] ProfileIconColors =
{
("Green", "#00E676"),
("Cyan", "#00B4D8"),
("Blue", "#4FC3F7"),
("Purple", "#BB86FC"),
("Pink", "#FF4081"),
("Red", "#FF6B6B"),
("Orange", "#FF7043"),
("Amber", "#FFB800"),
("Mint", "#69F0AE"),
("White", "#E8E8E8"),
};
private void UpdateProfileButton()
{
var icon = _config.ProfileIcons.GetValueOrDefault(_config.ActiveProfile) ?? new ProfileIconConfig();
if (Enum.TryParse<MaterialIconKind>(icon.Symbol, out var kind))
ProfileIcon.Kind = kind;
try { ProfileIcon.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(icon.Color)); } catch { }
ProfileLabel.Text = _config.ActiveProfile;
}
private DeviceSurface GetPreferredSurface()
{
// Read from the dedicated PreferredSurface field — this is the user's
// choice that survives device-connect events at startup. Buttons /
// Mixer / Lights on TabSelection reflect the currently-applied
// effective surface and get rewritten by the auto-detect pathway.
return _config.TabSelection.PreferredSurface;
}
private DeviceSurface GetEffectiveDeviceSurface()
{
return _config.HardwareMode switch
{
HardwareMode.TurnUpOnly => DeviceSurface.TurnUp,
HardwareMode.StreamControllerOnly => DeviceSurface.StreamController,
HardwareMode.DualMode => GetPreferredSurface(),
HardwareMode.Auto when _turnUpConnected && !_streamControllerConnected => DeviceSurface.TurnUp,
HardwareMode.Auto when !_turnUpConnected && _streamControllerConnected => DeviceSurface.StreamController,
HardwareMode.Auto when _turnUpConnected && _streamControllerConnected => DeviceSurface.TurnUp,
_ => GetPreferredSurface(),
};
}
public void ApplyDeviceSurface(DeviceSurface surface, bool persist)
{
_config.TabSelection.Mixer = surface;
_config.TabSelection.Buttons = surface;
_config.TabSelection.Lights = surface;
UpdateNavLightsVisibility(surface);
if (persist)
{
_onConfigChanged?.Invoke(_config);
RefreshViews();
}
}
private void ApplyHardwareSurfaceFromState(bool persist)
{
var surface = GetEffectiveDeviceSurface();
_config.TabSelection.Mixer = surface;
_config.TabSelection.Buttons = surface;
_config.TabSelection.Lights = surface;
UpdateNavLightsVisibility(surface);
if (persist)
_onConfigChanged?.Invoke(_config);
}
private void UpdateNavLightsVisibility(DeviceSurface surface)
{
bool showLights = surface is not DeviceSurface.StreamController;
NavLights.Visibility = showLights ? Visibility.Visible : Visibility.Collapsed;
// If Lights tab is active and now hidden, navigate away
if (!showLights && ContentArea.Content == _lightsView)
NavigateTo(_mixerView, NavMixer);
}
private void ProfileButton_Click(object sender, MouseButtonEventArgs e)
{
if (_profileFlyoutOpen)
CloseProfileFlyout();
else
OpenProfileFlyout();
e.Handled = true;
}
private void OpenProfileFlyout()
{
BuildProfileFlyout();
// Detach panel from any previous parent (Border, Grid, Window, etc.)
if (ProfilePopupPanel.Parent is System.Windows.Controls.Decorator oldDecorator)
oldDecorator.Child = null;
else if (ProfilePopupPanel.Parent is System.Windows.Controls.Panel oldPanel)
oldPanel.Children.Remove(ProfilePopupPanel);
else if (ProfilePopupPanel.Parent is System.Windows.Controls.ContentControl oldContent)
oldContent.Content = null;
var popupBorder = new System.Windows.Controls.Border
{
Background = (System.Windows.Media.Brush)FindResource("BgDarkBrush"),
BorderBrush = (System.Windows.Media.SolidColorBrush)FindResource("CardBorderBrush"),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(8),
Padding = new Thickness(6),
MinWidth = 200,
Child = ProfilePopupPanel
};
ProfilePopupPanel.Visibility = System.Windows.Visibility.Visible;
var screenPos = ProfileButton.PointToScreen(new Point(ProfileButton.ActualWidth + 4, 0));
var dpiSource = PresentationSource.FromVisual(ProfileButton);
if (dpiSource?.CompositionTarget != null)
{
var dpiX = dpiSource.CompositionTarget.TransformToDevice.M11;
var dpiY = dpiSource.CompositionTarget.TransformToDevice.M22;
screenPos = new Point(screenPos.X / dpiX, screenPos.Y / dpiY);
}
_profileFlyout = new Window
{
WindowStyle = WindowStyle.None,
ResizeMode = ResizeMode.NoResize,
SizeToContent = SizeToContent.WidthAndHeight,
ShowInTaskbar = false,
Topmost = true,
AllowsTransparency = false,
Background = (System.Windows.Media.Brush)FindResource("BgDarkBrush"),
Content = popupBorder,
Left = screenPos.X,
Top = screenPos.Y
};
_profileFlyout.Deactivated += (_, _) => CloseProfileFlyout();
_profileFlyout.KeyDown += (_, e2) => { if (e2.Key == Key.Escape) CloseProfileFlyout(); };
_profileFlyout.Show();
_profileFlyoutOpen = true;
}
public DeviceSurface GetCurrentDeviceSurface() => GetEffectiveDeviceSurface();
public (bool turnUp, bool streamController) GetHardwareConnectionState() =>
(_turnUpConnected, _streamControllerConnected);
private void CloseProfileFlyout()
{
if (!_profileFlyoutOpen) return;
_profileFlyoutOpen = false;
// Detach panel child before closing so it can be re-hosted next open
if (_profileFlyout?.Content is System.Windows.Controls.Border b)
b.Child = null;
_profileFlyout?.Close();
_profileFlyout = null;
}
private void BuildProfileFlyout()
{
ProfilePopupPanel.Children.Clear();
// Header
var header = new System.Windows.Controls.TextBlock
{
Text = "PROFILES",
FontSize = 9,
FontWeight = FontWeights.SemiBold,
Foreground = (SolidColorBrush)FindResource("TextDimBrush"),
Margin = new Thickness(6, 4, 0, 8)
};
ProfilePopupPanel.Children.Add(header);
// Profile items
foreach (var profile in _config.Profiles)
{
var profileCapture = profile;
bool isActive = profile == _config.ActiveProfile;
var iconCfg = _config.ProfileIcons.GetValueOrDefault(profile) ?? new ProfileIconConfig();
var row = new System.Windows.Controls.Grid();
row.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition { Width = System.Windows.GridLength.Auto });
row.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition { Width = new System.Windows.GridLength(1, System.Windows.GridUnitType.Star) });
row.ColumnDefinitions.Add(new System.Windows.Controls.ColumnDefinition { Width = System.Windows.GridLength.Auto });
// Icon button (clickable to change icon)
var iconElement = new MiIcon
{
Width = 18, Height = 18,
Margin = new Thickness(0, 0, 8, 0),
VerticalAlignment = VerticalAlignment.Center,
Cursor = Cursors.Hand,
ToolTip = "Change icon"
};
if (Enum.TryParse<MaterialIconKind>(iconCfg.Symbol, out var iconKind))
iconElement.Kind = iconKind;
try { iconElement.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(iconCfg.Color)); } catch { }
iconElement.MouseLeftButtonDown += (_, ev) =>
{
ev.Handled = true;
ShowIconPicker(profileCapture);
};
System.Windows.Controls.Grid.SetColumn(iconElement, 0);
row.Children.Add(iconElement);
// Profile name
var nameBlock = new System.Windows.Controls.TextBlock
{
Text = profile,
FontSize = 12,
FontWeight = isActive ? FontWeights.SemiBold : FontWeights.Normal,
Foreground = isActive
? (SolidColorBrush)FindResource("AccentBrush")
: (SolidColorBrush)FindResource("TextPrimaryBrush"),
VerticalAlignment = VerticalAlignment.Center
};
System.Windows.Controls.Grid.SetColumn(nameBlock, 1);
row.Children.Add(nameBlock);
// Edit + Delete buttons
var actionPanel = new System.Windows.Controls.StackPanel
{
Orientation = System.Windows.Controls.Orientation.Horizontal,
VerticalAlignment = VerticalAlignment.Center
};
// Edit button (pencil)
var editBtn = new System.Windows.Controls.TextBlock
{
Text = "\u270E", // ✎ pencil
FontSize = 11,
Foreground = (SolidColorBrush)FindResource("TextSecBrush"),
VerticalAlignment = VerticalAlignment.Center,
Cursor = Cursors.Hand,
Margin = new Thickness(8, 0, 0, 0),
ToolTip = "Edit profile"
};
editBtn.MouseEnter += (_, _) => editBtn.Foreground = (SolidColorBrush)FindResource("AccentBrush");
editBtn.MouseLeave += (_, _) => editBtn.Foreground = (SolidColorBrush)FindResource("TextSecBrush");
editBtn.MouseLeftButtonDown += (_, ev) =>
{
ev.Handled = true;
CloseProfileFlyout();
ShowProfileEditor(profileCapture);
};
actionPanel.Children.Add(editBtn);
// Delete button (not for Default)
if (profile != "Default")
{
var deleteBtn = new System.Windows.Controls.TextBlock
{
Text = "✕",
FontSize = 9,
Foreground = (SolidColorBrush)FindResource("DangerRedBrush"),
VerticalAlignment = VerticalAlignment.Center,
Cursor = Cursors.Hand,
Margin = new Thickness(6, 0, 0, 0),
ToolTip = "Delete profile"
};
deleteBtn.MouseEnter += (_, _) => deleteBtn.Foreground = new SolidColorBrush(Color.FromRgb(0xFF, 0x77, 0x77));
deleteBtn.MouseLeave += (_, _) => deleteBtn.Foreground = (SolidColorBrush)FindResource("DangerRedBrush");
deleteBtn.MouseLeftButtonDown += (_, ev) =>
{
ev.Handled = true;
DeleteProfile(profileCapture);
};
actionPanel.Children.Add(deleteBtn);
}
System.Windows.Controls.Grid.SetColumn(actionPanel, 2);
row.Children.Add(actionPanel);
var rowBorder = new System.Windows.Controls.Border
{
Padding = new Thickness(6, 6, 6, 6),
CornerRadius = new CornerRadius(6),
Cursor = Cursors.Hand,
Background = isActive
? new SolidColorBrush(Color.FromArgb(0x20, 0x00, 0xB4, 0xD8))
: System.Windows.Media.Brushes.Transparent,
Child = row
};
// Hover
rowBorder.MouseEnter += (_, _) =>
{
if (profileCapture != _config.ActiveProfile)
rowBorder.Background = (SolidColorBrush)FindResource("InputBgBrush");
};
rowBorder.MouseLeave += (_, _) =>
{
rowBorder.Background = profileCapture == _config.ActiveProfile
? new SolidColorBrush(Color.FromArgb(0x20, 0x00, 0xB4, 0xD8))
: System.Windows.Media.Brushes.Transparent;
};
// Click to switch
rowBorder.MouseLeftButtonDown += (_, ev) =>
{
if (profileCapture == _config.ActiveProfile) return;
SwitchToProfile(profileCapture);
CloseProfileFlyout();
};
ProfilePopupPanel.Children.Add(rowBorder);
}
// Divider
var divider = new System.Windows.Controls.Border
{
Height = 1,
Background = (SolidColorBrush)FindResource("CardBorderBrush"),
Margin = new Thickness(4, 6, 4, 6)
};
ProfilePopupPanel.Children.Add(divider);
// Add new profile button
var addRow = new System.Windows.Controls.StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal };
addRow.Children.Add(new System.Windows.Controls.TextBlock
{
Text = "+",
FontSize = 14,
FontWeight = FontWeights.Bold,
Foreground = (SolidColorBrush)FindResource("TextSecBrush"),
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(2, 0, 8, 0)
});
addRow.Children.Add(new System.Windows.Controls.TextBlock
{
Text = "New Profile",
FontSize = 12,
Foreground = (SolidColorBrush)FindResource("TextSecBrush"),
VerticalAlignment = VerticalAlignment.Center
});
var addBorder = new System.Windows.Controls.Border
{
Padding = new Thickness(6, 6, 6, 6),
CornerRadius = new CornerRadius(6),
Cursor = Cursors.Hand,
Child = addRow
};
addBorder.MouseEnter += (_, _) =>
{
addBorder.Background = (SolidColorBrush)FindResource("InputBgBrush");
};
addBorder.MouseLeave += (_, _) =>
{
addBorder.Background = System.Windows.Media.Brushes.Transparent;
};
addBorder.MouseLeftButtonDown += (_, _) =>
{
CloseProfileFlyout();
AddNewProfile();
};
ProfilePopupPanel.Children.Add(addBorder);
}
private void ShowProfileEditor(string profileName)
{
var currentIcon = _config.ProfileIcons.GetValueOrDefault(profileName) ?? new ProfileIconConfig();
Window? editorWindow = null;
bool closing = false;
string currentProfileName = profileName; // tracks renames
// Helper: save current icon/color state immediately
Action saveIconColor = () =>
{
_config.ProfileIcons[currentProfileName] = new ProfileIconConfig
{
Symbol = currentIcon.Symbol,
Color = currentIcon.Color
};
_onConfigChanged?.Invoke(_config);
UpdateProfileButton();
};
// Helper: apply rename if name changed
Action<string> tryRename = (newName) =>
{
if (string.IsNullOrWhiteSpace(newName) || newName == currentProfileName) return;
newName = newName.Trim();
if (_config.Profiles.Contains(newName)) return;
RenameProfile(currentProfileName, newName);
currentProfileName = newName;
_onConfigChanged?.Invoke(_config);
UpdateProfileButton();
RefreshViews();
};
Action closeEditor = () =>
{
if (closing) return;
closing = true;
// Apply any pending rename on close
var finalName = (editorWindow?.Content as System.Windows.Controls.Border)?
.FindName("_nameBox") as System.Windows.Controls.TextBox;
editorWindow?.Close();
editorWindow = null;
};
var outerPanel = new System.Windows.Controls.StackPanel { Margin = new Thickness(10) };
// ── Rename section ──
var renameLabel = new System.Windows.Controls.TextBlock
{
Text = "NAME",
FontSize = 9,
FontWeight = FontWeights.SemiBold,
Foreground = (SolidColorBrush)FindResource("TextDimBrush"),
Margin = new Thickness(2, 0, 0, 4)
};
outerPanel.Children.Add(renameLabel);
var nameBox = new System.Windows.Controls.TextBox
{
Text = profileName,
FontSize = 12,
Width = 280,
Foreground = (SolidColorBrush)FindResource("TextPrimaryBrush"),
Background = (SolidColorBrush)FindResource("InputBgBrush"),
BorderBrush = (SolidColorBrush)FindResource("InputBorderBrush"),
CaretBrush = (SolidColorBrush)FindResource("AccentBrush"),
Padding = new Thickness(8, 6, 8, 6),
HorizontalAlignment = HorizontalAlignment.Left
};
nameBox.GotFocus += (_, _) => nameBox.SelectAll();
// Save name on Enter or lost focus
nameBox.KeyDown += (_, e) =>
{
if (e.Key == Key.Enter)
{
tryRename(nameBox.Text);
Keyboard.ClearFocus();
}
};
nameBox.LostFocus += (_, _) => tryRename(nameBox.Text);
outerPanel.Children.Add(nameBox);
// ── Color swatches ──
var colorLabel = new System.Windows.Controls.TextBlock
{