-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
946 lines (825 loc) · 37.9 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
946 lines (825 loc) · 37.9 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
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Win32;
using SonicBoard.Helpers;
using SonicBoard.Models;
using SonicBoard.Services;
namespace SonicBoard
{
public partial class MainWindow : Window
{
private readonly AudioEngine _audioEngine = new();
private readonly HotkeyManager _hotkeyManager = new();
private readonly ProfileManager _profileManager = new();
private readonly string[] _defaultCategories = { "General", "Music", "Game Calls", "Voice Lines", "Memes", "SFX" };
private AppSettings _settings = new();
private SoundProfile _currentProfile = new();
private ObservableCollection<SoundItem> _allSounds = new();
private bool _isListView = true;
private Key _capturedKey;
private ModifierKeys _capturedModifiers;
private string _selectedCategoryFilter = "All Categories";
private bool _isUpdatingCategoryUi;
public MainWindow()
{
InitializeComponent();
}
// ═══════════════════════════════════════════════════════
// WINDOW LIFECYCLE
// ═══════════════════════════════════════════════════════
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_hotkeyManager.Initialize(this);
_settings = _profileManager.LoadSettings();
// Check if running as Admin and update UI
bool isAdmin = IsRunningAsAdmin();
borderAdminWarning.Visibility = isAdmin ? Visibility.Collapsed : Visibility.Visible;
lblAdminStatus.Visibility = isAdmin ? Visibility.Visible : Visibility.Collapsed;
// Apply saved settings
sliderLocalVolume.Value = _settings.LocalVolume * 100;
sliderMicVolume.Value = _settings.VirtualMicVolume * 100;
chkOverlap.IsChecked = _settings.AllowOverlap;
chkAutoMuteMic.IsChecked = _settings.AutoMuteMic;
chkSuppressHotkeys.IsChecked = _settings.SuppressHotkeys;
_audioEngine.AutoMuteMic = _settings.AutoMuteMic;
_hotkeyManager.SuppressHotkeys = _settings.SuppressHotkeys;
Width = _settings.WindowWidth;
Height = _settings.WindowHeight;
// Load profiles
RefreshProfileList();
// Load devices
RefreshDeviceList();
// Load last profile
var profile = _profileManager.LoadProfile(_settings.LastProfileName);
if (profile != null)
LoadProfile(profile);
else
LoadProfile(new SoundProfile());
_audioEngine.OnSoundFinished += id =>
Dispatcher.Invoke(() => UpdateStatus($"Sound finished"));
// Real-time Audio Device Hotplugging listener
_audioEngine.OnDevicesChanged += () =>
{
Dispatcher.Invoke(() =>
{
RefreshDeviceList();
UpdateStatus("Audio devices updated (plug/unplug detected)");
});
};
UpdateStatus("Ready - Drag & drop audio files or click Add Sound");
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
SaveCurrentState();
_hotkeyManager.Dispose();
_audioEngine.Dispose();
}
private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
WindowState = WindowState == WindowState.Maximized
? WindowState.Normal : WindowState.Maximized;
}
else
DragMove();
}
// ═══════════════════════════════════════════════════════
// SOUND MANAGEMENT
// ═══════════════════════════════════════════════════════
private void AddSound_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog
{
Title = "Select Audio Files",
Filter = "Audio Files|*.mp3;*.wav;*.ogg;*.flac;*.wma;*.aac;*.m4a;*.aiff|All Files|*.*",
Multiselect = true
};
if (dlg.ShowDialog() == true)
{
foreach (string file in dlg.FileNames)
AddSoundFile(file);
}
}
private void AddSoundFile(string filePath)
{
if (!File.Exists(filePath)) return;
if (_allSounds.Any(s => s.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase)))
{
UpdateStatus($"Sound already exists: {Path.GetFileName(filePath)}");
return;
}
string initialCategory = (_selectedCategoryFilter != "All Categories" && !string.IsNullOrWhiteSpace(_selectedCategoryFilter))
? _selectedCategoryFilter
: "General";
var sound = new SoundItem
{
Name = Path.GetFileNameWithoutExtension(filePath),
FilePath = filePath,
Category = initialCategory
};
_audioEngine.PreloadSound(filePath);
_allSounds.Add(sound);
_currentProfile.Sounds.Add(sound);
RefreshCategoryList();
ApplyFilter();
UpdateSoundCount();
UpdateStatus($"Added: {sound.Name} [{sound.Category}]");
}
private void DeleteSound_Click(object sender, RoutedEventArgs e)
{
if (lvSounds.SelectedItems.Count == 0)
{
UpdateStatus("Select one or more sounds first to delete");
return;
}
var selectedSounds = lvSounds.SelectedItems.Cast<SoundItem>().ToList();
int deletedCount = selectedSounds.Count;
foreach (var sound in selectedSounds)
{
_audioEngine.StopSound(sound.Id);
_audioEngine.RemoveCachedSound(sound.FilePath);
_hotkeyManager.UnregisterHotkey(sound.Id);
_allSounds.Remove(sound);
_currentProfile.Sounds.Remove(sound);
}
RefreshCategoryList();
ApplyFilter();
UpdateSoundCount();
UpdateStatus(deletedCount == 1
? $"Deleted: {selectedSounds[0].Name}"
: $"Deleted {deletedCount} sounds");
}
private void SoundList_DoubleClick(object sender, MouseButtonEventArgs e)
{
if (lvSounds.SelectedItem is SoundItem sound)
PlayOrStopSound(sound);
}
private void PlayOrStopSound(SoundItem sound)
{
if (sound.IsFileMissing)
{
sound.RefreshFileStatus();
UpdateStatus($"⚠️ File not found on disk: {sound.Name} ({sound.FilePath})");
try { System.Media.SystemSounds.Exclamation.Play(); } catch { }
return;
}
if (sound.IsPlaying)
{
_audioEngine.StopSound(sound.Id);
UpdateStatus($"Stopped: {sound.Name}");
}
else
{
_audioEngine.PlaySound(sound, chkOverlap.IsChecked == true);
UpdateStatus($"Playing: {sound.Name}");
}
}
// ═══════════════════════════════════════════════════════
// PLAYBACK CONTROLS
// ═══════════════════════════════════════════════════════
private void StopAll_Click(object sender, RoutedEventArgs e)
{
_audioEngine.StopAll();
UpdateStatus("All sounds stopped");
}
private void PauseAll_Click(object sender, RoutedEventArgs e)
{
// Toggle pause label
if (btnPauseAll.Content.ToString()!.Contains("Pause"))
{
_audioEngine.StopAll();
btnPauseAll.Content = "▶ Resume";
UpdateStatus("All sounds paused");
}
else
{
btnPauseAll.Content = "⏸ Pause All";
UpdateStatus("Ready");
}
}
private void PlayRandom_Click(object sender, RoutedEventArgs e)
{
if (_allSounds.Count == 0) return;
var rng = new Random();
var sound = _allSounds[rng.Next(_allSounds.Count)];
_audioEngine.PlaySound(sound, chkOverlap.IsChecked == true);
UpdateStatus($"Random: {sound.Name}");
}
// ═══════════════════════════════════════════════════════
// HOTKEY MANAGEMENT
// ═══════════════════════════════════════════════════════
private void HotkeyCapture_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Handled = true;
var key = e.Key == Key.System ? e.SystemKey : e.Key;
// Ignore modifier-only presses
if (key == Key.LeftCtrl || key == Key.RightCtrl ||
key == Key.LeftAlt || key == Key.RightAlt ||
key == Key.LeftShift || key == Key.RightShift ||
key == Key.LWin || key == Key.RWin)
return;
_capturedKey = key;
_capturedModifiers = Keyboard.Modifiers;
txtHotkey.Text = HotkeyManager.GetHotkeyDisplayString(_capturedModifiers, _capturedKey);
}
private void HotkeyCapture_GotFocus(object sender, RoutedEventArgs e)
{
_hotkeyManager.IsSuspended = true;
txtHotkey.Text = "Press a key combo...";
txtHotkey.BorderBrush = new SolidColorBrush(Color.FromRgb(255, 136, 0));
}
private void HotkeyCapture_LostFocus(object sender, RoutedEventArgs e)
{
_hotkeyManager.IsSuspended = false;
txtHotkey.BorderBrush = (SolidColorBrush)FindResource("BorderBrush");
}
private void SetHotkey_Click(object sender, RoutedEventArgs e)
{
if (lvSounds.SelectedItem is not SoundItem sound)
{
UpdateStatus("Select a sound first to set hotkey");
return;
}
if (_capturedKey == Key.None)
{
UpdateStatus("Capture a hotkey first (click the hotkey box and press keys)");
return;
}
int mods = HotkeyManager.ModifierKeysToInt(_capturedModifiers);
int vk = HotkeyManager.KeyToVirtualKey(_capturedKey);
string display = HotkeyManager.GetHotkeyDisplayString(_capturedModifiers, _capturedKey);
// Check if any other sound already uses this hotkey
var conflictingSound = _allSounds.FirstOrDefault(s => s.Id != sound.Id && s.HotkeyKey == vk && s.HotkeyModifiers == mods);
if (conflictingSound != null)
{
var result = System.Windows.MessageBox.Show(
$"The hotkey '{display}' is already assigned to the sound '{conflictingSound.Name}'.\n\nDo you want to reassign this hotkey to '{sound.Name}' (it will be removed from '{conflictingSound.Name}')?",
"Duplicate Hotkey Warning",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result != MessageBoxResult.Yes)
{
UpdateStatus($"Hotkey assignment cancelled. '{conflictingSound.Name}' retained '{display}'");
return;
}
// Unregister and clear hotkey from conflicting sound
_hotkeyManager.UnregisterHotkey(conflictingSound.Id);
conflictingSound.HotkeyModifiers = 0;
conflictingSound.HotkeyKey = 0;
conflictingSound.HotkeyDisplay = "";
}
sound.HotkeyModifiers = mods;
sound.HotkeyKey = vk;
sound.HotkeyDisplay = display;
bool ok = _hotkeyManager.RegisterHotkey(sound.Id, mods, vk, () =>
{
Dispatcher.Invoke(() => PlayOrStopSound(sound));
});
if (conflictingSound != null)
{
UpdateStatus(ok ? $"Hotkey {display} reassigned to '{sound.Name}' (removed from '{conflictingSound.Name}')"
: $"Failed to register hotkey {display}");
}
else
{
UpdateStatus(ok ? $"Hotkey {display} set for: {sound.Name}"
: $"Failed to register hotkey {display} (may be in use)");
}
lvSounds.Items.Refresh();
RefreshGridView();
}
private void ClearHotkey_Click(object sender, RoutedEventArgs e)
{
if (lvSounds.SelectedItems.Count == 0)
{
UpdateStatus("Select one or more sounds first to clear hotkey");
return;
}
var selectedSounds = lvSounds.SelectedItems.Cast<SoundItem>().ToList();
int clearedCount = 0;
foreach (var sound in selectedSounds)
{
if (sound.HotkeyKey != 0)
{
_hotkeyManager.UnregisterHotkey(sound.Id);
sound.HotkeyDisplay = "";
sound.HotkeyModifiers = 0;
sound.HotkeyKey = 0;
clearedCount++;
}
}
if (clearedCount > 0)
{
lvSounds.Items.Refresh();
RefreshGridView();
UpdateStatus(clearedCount == 1
? "Hotkey cleared"
: $"Cleared hotkeys for {clearedCount} sounds");
}
else
{
UpdateStatus("Selected sounds do not have any hotkeys set");
}
txtHotkey.Text = "";
_capturedKey = Key.None;
_capturedModifiers = ModifierKeys.None;
}
private void SoundList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lvSounds.SelectedItem is SoundItem sound)
{
txtHotkey.Text = sound.HotkeyDisplay;
sliderSoundVolume.Value = sound.Volume * 100;
chkLoop.IsChecked = sound.Loop;
_isUpdatingCategoryUi = true;
try
{
cmbSoundCategory.Text = sound.Category;
cmbSoundCategory.SelectedItem = sound.Category;
}
finally
{
_isUpdatingCategoryUi = false;
}
}
else
{
txtHotkey.Text = "";
_isUpdatingCategoryUi = true;
try
{
cmbSoundCategory.Text = "";
cmbSoundCategory.SelectedItem = null;
}
finally
{
_isUpdatingCategoryUi = false;
}
}
}
private void SoundCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_isUpdatingCategoryUi) return;
if (cmbSoundCategory.SelectedItem is string newCategory && !string.IsNullOrWhiteSpace(newCategory))
{
ApplyCategoryToSelectedSounds(newCategory);
}
}
private void SoundCategory_LostFocus(object sender, RoutedEventArgs e)
{
if (_isUpdatingCategoryUi) return;
string text = cmbSoundCategory.Text?.Trim() ?? string.Empty;
if (!string.IsNullOrWhiteSpace(text))
{
ApplyCategoryToSelectedSounds(text);
}
}
private void ApplyCategoryToSelectedSounds(string category)
{
if (lvSounds.SelectedItems.Count == 0) return;
category = string.IsNullOrWhiteSpace(category) ? "General" : category.Trim();
var selectedSounds = lvSounds.SelectedItems.Cast<SoundItem>().ToList();
bool anyChanged = false;
foreach (var sound in selectedSounds)
{
if (!string.Equals(sound.Category, category, StringComparison.OrdinalIgnoreCase))
{
sound.Category = category;
anyChanged = true;
}
}
if (anyChanged)
{
RefreshCategoryList();
lvSounds.Items.Refresh();
ApplyFilter();
UpdateStatus(selectedSounds.Count == 1
? $"Category set to '{category}' for {selectedSounds[0].Name}"
: $"Category set to '{category}' for {selectedSounds.Count} sounds");
}
}
// ═══════════════════════════════════════════════════════
// VOLUME CONTROLS
// ═══════════════════════════════════════════════════════
private void LocalVolume_Changed(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (lblLocalVol == null) return;
_audioEngine.LocalVolume = (float)(e.NewValue / 100.0);
lblLocalVol.Text = $"{(int)e.NewValue}%";
}
private void MicVolume_Changed(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (lblMicVol == null) return;
_audioEngine.VirtualMicVolume = (float)(e.NewValue / 100.0);
lblMicVol.Text = $"{(int)e.NewValue}%";
}
private void SoundVolume_Changed(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (lblSoundVol == null) return;
lblSoundVol.Text = $"{(int)e.NewValue}%";
if (lvSounds.SelectedItem is SoundItem sound)
sound.Volume = (float)(e.NewValue / 100.0);
}
private void LoopToggle_Changed(object sender, RoutedEventArgs e)
{
if (lvSounds.SelectedItem is SoundItem sound)
sound.Loop = chkLoop.IsChecked == true;
}
private void OverlapToggle_Changed(object sender, RoutedEventArgs e) { }
private void AutoMuteMicToggle_Changed(object sender, RoutedEventArgs e)
{
if (_audioEngine != null && chkAutoMuteMic != null)
{
_audioEngine.AutoMuteMic = chkAutoMuteMic.IsChecked == true;
}
}
private void SuppressHotkeysToggle_Changed(object sender, RoutedEventArgs e)
{
if (_hotkeyManager != null && chkSuppressHotkeys != null)
{
_hotkeyManager.SuppressHotkeys = chkSuppressHotkeys.IsChecked == true;
}
}
// ═══════════════════════════════════════════════════════
// DEVICE MANAGEMENT
// ═══════════════════════════════════════════════════════
private void RefreshDevices_Click(object sender, RoutedEventArgs e) => RefreshDeviceList();
private void RefreshDeviceList()
{
spDevices.Children.Clear();
var devices = _audioEngine.GetOutputDevices();
foreach (var dev in devices)
{
var panel = new Grid { Margin = new Thickness(0, 2, 0, 2) };
panel.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(40) });
panel.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
bool isEnabled = _settings.EnabledDeviceIds.Contains(dev.Id) || (dev.IsDefault && _settings.EnabledDeviceIds.Count == 0);
var toggle = new ToggleButton
{
Style = (Style)FindResource("ToggleSwitch"),
IsChecked = isEnabled,
Tag = dev.Id
};
toggle.Checked += DeviceToggle_Changed;
toggle.Unchecked += DeviceToggle_Changed;
Grid.SetColumn(toggle, 0);
var label = new TextBlock
{
Text = TruncateDeviceName(dev.Name),
FontSize = 10,
Foreground = (SolidColorBrush)FindResource("TextSecondaryBrush"),
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(6, 0, 0, 0),
ToolTip = dev.Name,
TextTrimming = TextTrimming.CharacterEllipsis
};
Grid.SetColumn(label, 1);
panel.Children.Add(toggle);
panel.Children.Add(label);
spDevices.Children.Add(panel);
// Auto-enable device in engine and ensure it's in settings
if (isEnabled)
{
_audioEngine.EnableDevice(dev.Id, false);
if (!_settings.EnabledDeviceIds.Contains(dev.Id))
_settings.EnabledDeviceIds.Add(dev.Id);
}
}
}
private void DeviceToggle_Changed(object sender, RoutedEventArgs e)
{
if (sender is not ToggleButton toggle || toggle.Tag is not string devId) return;
if (toggle.IsChecked == true)
{
_audioEngine.EnableDevice(devId, false);
if (!_settings.EnabledDeviceIds.Contains(devId))
_settings.EnabledDeviceIds.Add(devId);
}
else
{
_audioEngine.DisableDevice(devId);
_settings.EnabledDeviceIds.Remove(devId);
}
_profileManager.SaveSettings(_settings);
}
private string TruncateDeviceName(string name)
{
return name.Length > 28 ? name[..28] + "..." : name;
}
// ═══════════════════════════════════════════════════════
// PROFILE MANAGEMENT
// ═══════════════════════════════════════════════════════
private void SaveProfile_Click(object sender, RoutedEventArgs e)
{
_profileManager.SaveProfile(_currentProfile);
SaveCurrentState();
UpdateStatus($"Profile saved: {_currentProfile.Name}");
}
private void NewProfile_Click(object sender, RoutedEventArgs e)
{
string name = $"Profile {DateTime.Now:MMdd_HHmm}";
var profile = new SoundProfile { Name = name };
_profileManager.SaveProfile(profile);
RefreshProfileList();
LoadProfile(profile);
UpdateStatus($"New profile created: {name}");
}
private void ProfileSelector_Changed(object sender, SelectionChangedEventArgs e)
{
if (cmbProfiles.SelectedItem is not string name) return;
if (name == _currentProfile.Name) return;
// Save current first
_profileManager.SaveProfile(_currentProfile);
var profile = _profileManager.LoadProfile(name);
if (profile != null) LoadProfile(profile);
}
private void RefreshProfileList()
{
var names = _profileManager.GetProfileNames();
cmbProfiles.ItemsSource = names;
cmbProfiles.SelectedItem = _currentProfile.Name;
}
private void LoadProfile(SoundProfile profile)
{
_hotkeyManager.UnregisterAll();
_audioEngine.ClearCache();
_currentProfile = profile;
_allSounds = new ObservableCollection<SoundItem>(profile.Sounds);
lvSounds.ItemsSource = _allSounds;
cmbProfiles.SelectedItem = profile.Name;
foreach (var sound in _allSounds)
{
sound.RefreshFileStatus();
if (sound.HotkeyKey != 0)
{
var s = sound; // capture for closure
_hotkeyManager.RegisterHotkey(s.Id, s.HotkeyModifiers, s.HotkeyKey, () =>
{
Dispatcher.Invoke(() => PlayOrStopSound(s));
});
}
}
AudioEngine.TrimMemory();
RefreshCategoryList();
ApplyFilter();
UpdateSoundCount();
UpdateStatus($"Loaded profile: {profile.Name}");
}
// ═══════════════════════════════════════════════════════
// VIEW TOGGLE
// ═══════════════════════════════════════════════════════
private void ToggleListView_Click(object sender, RoutedEventArgs e)
{
_isListView = true;
lvSounds.Visibility = Visibility.Visible;
gridViewPanel.Visibility = Visibility.Collapsed;
}
private void ToggleGridView_Click(object sender, RoutedEventArgs e)
{
_isListView = false;
lvSounds.Visibility = Visibility.Collapsed;
gridViewPanel.Visibility = Visibility.Visible;
RefreshGridView();
}
private void RefreshGridView()
{
if (_isListView) return;
wpButtons.Children.Clear();
string query = txtSearch.Text.Trim();
var filteredSounds = _allSounds.Where(sound =>
{
bool matchesCategory = string.IsNullOrEmpty(_selectedCategoryFilter) ||
_selectedCategoryFilter == "All Categories" ||
sound.Category.Equals(_selectedCategoryFilter, StringComparison.OrdinalIgnoreCase);
bool matchesQuery = string.IsNullOrEmpty(query) ||
sound.Name.Contains(query, StringComparison.OrdinalIgnoreCase) ||
sound.FileName.Contains(query, StringComparison.OrdinalIgnoreCase) ||
sound.Category.Contains(query, StringComparison.OrdinalIgnoreCase);
return matchesCategory && matchesQuery;
});
foreach (var sound in filteredSounds)
{
bool missing = sound.IsFileMissing;
string title = missing ? $"⚠️ {sound.Name}" : sound.Name;
var btn = new Button
{
Content = new TextBlock
{
Text = title,
TextWrapping = TextWrapping.Wrap,
TextAlignment = TextAlignment.Center,
FontSize = 11,
Foreground = missing ? (SolidColorBrush)FindResource("AccentOrangeBrush") : (SolidColorBrush)FindResource("TextPrimaryBrush")
},
Style = (Style)FindResource("SoundButton"),
Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(sound.ButtonColor)),
Width = _settings.ButtonSize,
Height = _settings.ButtonSize * 0.7,
Tag = sound,
ToolTip = missing
? $"⚠️ FILE NOT FOUND ON DISK:\n{sound.FilePath}\n\n📁 Category: {sound.Category}\n⌨️ {sound.HotkeyDisplay}"
: $"{sound.Name}\n📁 Category: {sound.Category}\n⌨️ {sound.HotkeyDisplay}\n🔊 Vol: {(int)(sound.Volume*100)}%"
};
btn.Click += (s, _) =>
{
if (s is Button b && b.Tag is SoundItem si)
PlayOrStopSound(si);
};
wpButtons.Children.Add(btn);
}
}
// ═══════════════════════════════════════════════════════
// DRAG & DROP
// ═══════════════════════════════════════════════════════
private void Window_DragOver(object sender, System.Windows.DragEventArgs e)
{
e.Effects = e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop)
? System.Windows.DragDropEffects.Copy : System.Windows.DragDropEffects.None;
e.Handled = true;
}
private void Window_Drop(object sender, System.Windows.DragEventArgs e)
{
if (!e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop)) return;
var files = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop);
string[] audioExts = { ".mp3", ".wav", ".ogg", ".flac", ".wma", ".aac", ".m4a", ".aiff" };
int added = 0;
foreach (string file in files)
{
if (audioExts.Contains(Path.GetExtension(file).ToLowerInvariant()))
{
AddSoundFile(file);
added++;
}
}
UpdateStatus(added > 0 ? $"Added {added} sound(s) via drag & drop" : "No supported audio files found");
}
// ═══════════════════════════════════════════════════════
// SEARCH & CATEGORY FILTER
// ═══════════════════════════════════════════════════════
private void CategoryFilter_Changed(object sender, SelectionChangedEventArgs e)
{
if (_isUpdatingCategoryUi) return;
if (cmbCategoryFilter.SelectedItem is string cat)
{
_selectedCategoryFilter = cat;
ApplyFilter();
}
}
private void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
{
ApplyFilter();
}
private void ApplyFilter()
{
string query = txtSearch.Text.Trim();
txtSearchPlaceholder.Visibility = string.IsNullOrEmpty(query)
? Visibility.Visible : Visibility.Collapsed;
var view = System.Windows.Data.CollectionViewSource.GetDefaultView(_allSounds);
if (view != null)
{
view.Filter = item =>
{
if (item is SoundItem sound)
{
bool matchesCategory = string.IsNullOrEmpty(_selectedCategoryFilter) ||
_selectedCategoryFilter == "All Categories" ||
sound.Category.Equals(_selectedCategoryFilter, StringComparison.OrdinalIgnoreCase);
bool matchesQuery = string.IsNullOrEmpty(query) ||
sound.Name.Contains(query, StringComparison.OrdinalIgnoreCase) ||
sound.FileName.Contains(query, StringComparison.OrdinalIgnoreCase) ||
sound.Category.Contains(query, StringComparison.OrdinalIgnoreCase);
return matchesCategory && matchesQuery;
}
return false;
};
}
RefreshGridView();
UpdateSoundCount();
}
private void RefreshCategoryList()
{
_isUpdatingCategoryUi = true;
try
{
var categories = _allSounds
.Select(s => s.Category)
.Where(c => !string.IsNullOrWhiteSpace(c))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
foreach (var defCat in _defaultCategories)
{
if (!categories.Any(c => c.Equals(defCat, StringComparison.OrdinalIgnoreCase)))
{
categories.Add(defCat);
}
}
categories.Sort(StringComparer.OrdinalIgnoreCase);
if (categories.Contains("General", StringComparer.OrdinalIgnoreCase))
{
categories.RemoveAll(c => c.Equals("General", StringComparison.OrdinalIgnoreCase));
categories.Insert(0, "General");
}
// Populate bottom bar category picker
string currentBottomCategory = cmbSoundCategory.Text;
cmbSoundCategory.ItemsSource = categories.ToList();
if (!string.IsNullOrEmpty(currentBottomCategory))
{
cmbSoundCategory.Text = currentBottomCategory;
}
// Populate top filter combo
var filterList = new List<string> { "All Categories" };
filterList.AddRange(categories);
string previousFilter = _selectedCategoryFilter;
cmbCategoryFilter.ItemsSource = filterList;
if (filterList.Contains(previousFilter, StringComparer.OrdinalIgnoreCase))
{
cmbCategoryFilter.SelectedItem = filterList.First(c => c.Equals(previousFilter, StringComparison.OrdinalIgnoreCase));
}
else
{
cmbCategoryFilter.SelectedIndex = 0;
_selectedCategoryFilter = "All Categories";
}
}
finally
{
_isUpdatingCategoryUi = false;
}
}
// ═══════════════════════════════════════════════════════
// HELPERS
// ═══════════════════════════════════════════════════════
private void SaveCurrentState()
{
_profileManager.SaveProfile(_currentProfile);
_settings.LocalVolume = (float)(sliderLocalVolume.Value / 100.0);
_settings.VirtualMicVolume = (float)(sliderMicVolume.Value / 100.0);
_settings.AllowOverlap = chkOverlap.IsChecked == true;
_settings.AutoMuteMic = chkAutoMuteMic.IsChecked == true;
_settings.SuppressHotkeys = chkSuppressHotkeys.IsChecked == true;
_settings.LastProfileName = _currentProfile.Name;
_settings.WindowWidth = Width;
_settings.WindowHeight = Height;
_profileManager.SaveSettings(_settings);
}
private void UpdateStatus(string msg)
{
lblStatus.Text = msg;
}
private void UpdateSoundCount()
{
if (lblSoundCount == null) return;
var view = System.Windows.Data.CollectionViewSource.GetDefaultView(_allSounds);
int visibleCount = view?.Cast<SoundItem>().Count() ?? _allSounds.Count;
if (visibleCount < _allSounds.Count)
{
lblSoundCount.Text = $"{visibleCount} of {_allSounds.Count} sound{(_allSounds.Count != 1 ? "s" : "")}";
}
else
{
lblSoundCount.Text = $"{_allSounds.Count} sound{(_allSounds.Count != 1 ? "s" : "")}";
}
}
private bool IsRunningAsAdmin()
{
try
{
using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent())
{
var principal = new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
}
catch
{
return false;
}
}
private void RunAsAdmin_Click(object sender, RoutedEventArgs e)
{
var processInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = Environment.ProcessPath,
UseShellExecute = true,
Verb = "runas"
};
try
{
System.Diagnostics.Process.Start(processInfo);
System.Windows.Application.Current.Shutdown();
}
catch (System.ComponentModel.Win32Exception)
{
UpdateStatus("Elevation failed. Admin rights are required to play sounds in games.");
}
}
}
}