-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.Behaviors.partial.cs
More file actions
1771 lines (1558 loc) Β· 70.8 KB
/
MainWindow.Behaviors.partial.cs
File metadata and controls
1771 lines (1558 loc) Β· 70.8 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
/*
* ThreadPilot - Advanced Windows Process and Power Plan Manager
* Copyright (C) 2025 Prime Build
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace ThreadPilot
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using Microsoft.Extensions.DependencyInjection;
using ThreadPilot.Helpers;
using ThreadPilot.Services;
using ThreadPilot.ViewModels;
using ThreadPilot.Views;
public partial class MainWindow : Wpf.Ui.Controls.FluentWindow
{
private void SetDataContexts()
{
// Set DataContext for the main window
this.DataContext = this.mainWindowViewModel;
// Set DataContext for the power plans view
this.PowerPlanViewControl.DataContext = this.powerPlanViewModel;
// Set DataContext for the association view
this.AssociationView.DataContext = this.associationViewModel;
// Set DataContext for the performance view
this.PerformanceViewControl.DataContext = this.performanceViewModel;
// Set DataContext for the log viewer view
this.LogViewerViewControl.DataContext = this.logViewerViewModel;
// Set DataContext for the system tweaks view
this.SystemTweaksView.DataContext = this.systemTweaksViewModel;
// Set DataContext for the settings view
this.SettingsView.DataContext = this.settingsViewModel;
}
private void InitializeLoadingOverlay()
{
try
{
var loadingOverlay = this.FindName("LoadingOverlay") as Grid;
// Ensure overlay is visible while initialization runs
if (loadingOverlay != null)
{
loadingOverlay.Visibility = Visibility.Visible;
loadingOverlay.Opacity = 1;
}
// Enable blur on main app content during startup loading.
this.ApplyUIContentBlur(15);
// Start spinner animation if available
var spinnerAnimation = this.FindResource("SpinnerAnimation") as Storyboard;
spinnerAnimation?.Begin();
// Set a timeout guard for initialization
this.initializationTimeoutTimer = new System.Timers.Timer(15000)
{
AutoReset = false,
};
this.initializationTimeoutTimer.Elapsed += this.OnInitializationTimeout;
this.initializationTimeoutTimer.Start();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to initialize loading overlay: {ex.Message}");
}
}
private async Task InitializeApplicationAsync()
{
try
{
this.LogDebug("=== Starting InitializeApplicationAsync ===");
await this.Dispatcher.InvokeAsync(() => this.UpdateLoadingStatus("Loading view models...", "Loading process, power plan and rules data."));
this.LogDebug("About to call LoadViewModelsAsync...");
await this.LoadViewModelsAsync();
this.LogDebug("LoadViewModelsAsync completed successfully");
this.CompleteInitializationTask("ViewModels");
this.LogDebug("About to initialize MainWindowViewModel...");
await this.mainWindowViewModel.InitializeAsync();
this.LogDebug("MainWindowViewModel initialized successfully");
this.CompleteInitializationTask("MainWindowViewModel");
await this.Dispatcher.InvokeAsync(() => this.UpdateLoadingStatus("Initializing services...", "Starting monitoring, tray and notification services."));
this.LogDebug("About to call InitializeServicesAsync...");
await this.InitializeServicesAsync();
this.LogDebug("InitializeServicesAsync completed successfully");
this.CompleteInitializationTask("Services");
await this.Dispatcher.InvokeAsync(() => this.UpdateLoadingStatus("Finalizing startup...", "Applying final UI state and startup checks."));
this.LogDebug("Finalizing startup...");
await Task.Delay(500); // Brief delay to show final status
this.CompleteInitializationTask("Finalization");
// All initialization complete
this.LogDebug("All initialization complete, hiding overlay...");
await this.Dispatcher.InvokeAsync(() => this.HideLoadingOverlay());
this.LogDebug("=== InitializeApplicationAsync completed successfully ===");
}
catch (Exception ex)
{
this.LogDebug($"=== ERROR in InitializeApplicationAsync: {ex} ===");
await this.Dispatcher.InvokeAsync(() => this.ShowInitializationError(ex));
}
}
private void UpdateLoadingStatus(string stage, string details = "")
{
if (this.mainWindowViewModel != null)
{
this.mainWindowViewModel.InitializationStage = stage;
this.mainWindowViewModel.InitializationDetails = details;
}
}
private void CompleteInitializationTask(string taskName)
{
lock (this.initializationLock)
{
this.initializationTasks.Add(taskName);
System.Diagnostics.Debug.WriteLine($"Initialization task completed: {taskName}");
}
}
private void HideLoadingOverlay()
{
try
{
System.Diagnostics.Debug.WriteLine("=== Starting HideLoadingOverlay ===");
this.isInitializationComplete = true;
this.initializationTimeoutTimer?.Stop();
this.initializationTimeoutTimer?.Dispose();
// Stop spinner animation
var spinnerAnimation = this.FindResource("SpinnerAnimation") as Storyboard;
spinnerAnimation?.Stop();
System.Diagnostics.Debug.WriteLine("Spinner animation stopped");
// Start fade-out animation
var fadeOutAnimation = this.FindResource("FadeOutAnimation") as Storyboard;
if (fadeOutAnimation != null)
{
System.Diagnostics.Debug.WriteLine("Starting fade-out animation");
fadeOutAnimation.Completed += (s, e) =>
{
System.Diagnostics.Debug.WriteLine("Fade-out animation completed, hiding overlay");
var loadingOverlay = this.FindName("LoadingOverlay") as Grid;
if (loadingOverlay != null)
{
loadingOverlay.Visibility = Visibility.Collapsed;
System.Diagnostics.Debug.WriteLine("Loading overlay visibility set to Collapsed");
}
// Disable app content blur and restore style-driven behavior.
this.ClearUIContentBlur();
System.Diagnostics.Debug.WriteLine("=== Loading overlay hidden successfully ===");
// Show elevation warning if needed
this.TryShowElevationWarning();
};
fadeOutAnimation.Begin();
}
else
{
System.Diagnostics.Debug.WriteLine("WARNING: FadeOutAnimation not found, hiding overlay immediately");
// Fallback: hide overlay immediately if animation fails
var loadingOverlay = this.FindName("LoadingOverlay") as Grid;
if (loadingOverlay != null)
{
loadingOverlay.Visibility = Visibility.Collapsed;
}
this.ClearUIContentBlur();
System.Diagnostics.Debug.WriteLine("=== Loading overlay hidden immediately (fallback) ===");
// Show elevation warning if needed
this.TryShowElevationWarning();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"=== ERROR hiding loading overlay: {ex} ===");
// Emergency fallback: hide overlay without animation
try
{
var loadingOverlay = this.FindName("LoadingOverlay") as Grid;
if (loadingOverlay != null)
{
loadingOverlay.Visibility = Visibility.Collapsed;
}
this.ClearUIContentBlur();
System.Diagnostics.Debug.WriteLine("Emergency fallback: overlay hidden without animation");
// Show elevation warning if needed
this.TryShowElevationWarning();
}
catch (Exception fallbackEx)
{
System.Diagnostics.Debug.WriteLine($"Emergency fallback also failed: {fallbackEx}");
}
}
}
private void ApplyUIContentBlur(double radius)
{
if (this.UIContent.Effect is not BlurEffect blur)
{
blur = new BlurEffect();
this.UIContent.Effect = blur;
}
blur.KernelType = KernelType.Gaussian;
blur.Radius = radius;
}
private void ClearUIContentBlur()
{
this.UIContent.Effect = null;
}
private void OnInitializationTimeout(object? sender, ElapsedEventArgs e)
{
this.Dispatcher.InvokeAsync(() =>
{
if (!this.isInitializationComplete)
{
this.ShowInitializationError(new TimeoutException("Application initialization timed out after 15 seconds"));
}
});
}
private void ShowInitializationError(Exception ex)
{
try
{
this.UpdateLoadingStatus("Initialization failed", ex.Message);
var result = System.Windows.MessageBox.Show(
$"ThreadPilot failed to initialize properly:\n\n{ex.Message}\n\nDebug log: {this.debugLogPath}\n\nWould you like to retry initialization or close the application?",
"Initialization Error",
MessageBoxButton.YesNo,
MessageBoxImage.Error);
if (result == MessageBoxResult.Yes)
{
// Retry initialization - marshal to UI thread to prevent cross-thread access exceptions
this.isInitializationComplete = false;
this.initializationTasks.Clear();
this.UpdateLoadingStatus("Retrying initialization...", "Restarting startup sequence.");
this.LogDebug("=== RETRYING INITIALIZATION ===");
_ = this.Dispatcher.InvokeAsync(async () => await this.InitializeApplicationAsync());
}
else
{
// Close application
this.LogDebug("User chose to close application");
System.Windows.Application.Current.Shutdown();
}
}
catch (Exception overlayEx)
{
this.LogDebug($"Error showing initialization error: {overlayEx.Message}");
System.Windows.Application.Current.Shutdown();
}
}
private async Task LoadViewModelsAsync()
{
try
{
this.LogDebug("=== Starting LoadViewModelsAsync ===");
this.LogDebug("About to initialize ProcessViewModel (including CPU topology)...");
try
{
// Use the full initialization method instead of just LoadProcesses
var processTask = this.processViewModel.InitializeAsync();
var processResult = await Task.WhenAny(processTask, Task.Delay(15000)); // 15 second timeout for full initialization
if (processResult != processTask)
{
this.LogDebug("ProcessViewModel.InitializeAsync() timed out, trying fallback...");
// Fallback: just load processes without full initialization
await this.processViewModel.LoadProcesses();
this.LogDebug($"ProcessViewModel fallback (LoadProcesses only) completed, process count: {this.processViewModel.Processes?.Count ?? 0}, filtered count: {this.processViewModel.FilteredProcesses?.Count ?? 0}");
}
else
{
await processTask; // Ensure we get any exceptions
this.LogDebug($"ProcessViewModel initialized successfully (including CPU topology), process count: {this.processViewModel.Processes?.Count ?? 0}, filtered count: {this.processViewModel.FilteredProcesses?.Count ?? 0}");
}
}
catch (Exception processEx)
{
this.LogDebug($"ProcessViewModel initialization failed: {processEx.Message}, trying fallback...");
// Fallback: just load processes without full initialization
await this.processViewModel.LoadProcesses();
this.LogDebug($"ProcessViewModel fallback (LoadProcesses only) completed after exception, process count: {this.processViewModel.Processes?.Count ?? 0}, filtered count: {this.processViewModel.FilteredProcesses?.Count ?? 0}");
}
this.LogDebug("About to load PowerPlanViewModel...");
var powerPlanTask = this.powerPlanViewModel.LoadPowerPlans();
var powerPlanResult = await Task.WhenAny(powerPlanTask, Task.Delay(5000)); // 5 second timeout
if (powerPlanResult != powerPlanTask)
{
throw new TimeoutException("PowerPlanViewModel.LoadPowerPlans() timed out after 5 seconds");
}
await powerPlanTask; // Ensure we get any exceptions
this.LogDebug("PowerPlanViewModel loaded successfully");
this.LogDebug("About to initialize PerformanceViewModel...");
var performanceTask = this.performanceViewModel.InitializeAsync();
var performanceResult = await Task.WhenAny(performanceTask, Task.Delay(5000));
if (performanceResult != performanceTask)
{
throw new TimeoutException("PerformanceViewModel.InitializeAsync() timed out after 5 seconds");
}
await performanceTask; // Ensure we get any exceptions
this.LogDebug("PerformanceViewModel initialized successfully");
this.LogDebug("About to load SystemTweaksViewModel...");
var systemTweaksTask = this.systemTweaksViewModel.LoadCommand.ExecuteAsync(null);
var systemTweaksResult = await Task.WhenAny(systemTweaksTask, Task.Delay(5000)); // 5 second timeout
if (systemTweaksResult != systemTweaksTask)
{
throw new TimeoutException("SystemTweaksViewModel.LoadCommand.ExecuteAsync() timed out after 5 seconds");
}
await systemTweaksTask; // Ensure we get any exceptions
this.LogDebug("SystemTweaksViewModel loaded successfully");
// Initialize keyboard shortcuts after window is loaded
this.Loaded += this.OnWindowLoaded;
this.LogDebug("Keyboard shortcuts event handler attached");
// The association view model loads its data automatically in its constructor
this.LogDebug("=== LoadViewModelsAsync completed successfully ===");
}
catch (Exception ex)
{
this.LogDebug($"=== ERROR in LoadViewModelsAsync: {ex} ===");
throw; // Re-throw to be handled by initialization error handler
}
}
private async Task InitializeServicesAsync()
{
this.LogDebug("=== Starting InitializeServicesAsync ===");
this.LogDebug("About to initialize settings...");
await this.InitializeSettingsAsync();
this.LogDebug("Settings initialized successfully");
this.LogDebug("About to initialize system tray...");
try
{
var systemTrayTask = this.InitializeSystemTrayAsync();
var systemTrayResult = await Task.WhenAny(systemTrayTask, Task.Delay(5000)); // 5 second timeout
if (systemTrayResult != systemTrayTask)
{
this.LogDebug("System tray initialization timed out, continuing with basic tray setup...");
// Initialize basic system tray without context menu updates (Initialize() is idempotent)
await this.InitializeBasicSystemTrayAsync();
this.LogDebug("Basic system tray initialized (without context menu)");
}
else
{
await systemTrayTask; // Ensure we get any exceptions
this.LogDebug("System tray initialized successfully");
}
}
catch (Exception systemTrayEx)
{
this.LogDebug($"System tray initialization failed: {systemTrayEx.Message}, using basic tray...");
// Fallback: basic system tray initialization
try
{
await this.InitializeBasicSystemTrayAsync();
this.LogDebug("Fallback system tray initialized");
}
catch (Exception fallbackEx)
{
this.LogDebug($"Even fallback system tray failed: {fallbackEx.Message}");
}
}
this.LogDebug("About to initialize notifications...");
this.InitializeNotifications();
this.LogDebug("Notifications initialized successfully");
this.LogDebug("About to initialize monitoring...");
await this.InitializeMonitoringAsync();
this.LogDebug("Monitoring initialized successfully");
if (this.skipProcessMonitoringDuringStartup)
{
this.LogDebug("Skipping process monitoring manager startup (temporary bypass enabled)");
}
else
{
this.LogDebug("About to start process monitoring manager...");
try
{
var monitoringTask = this.StartProcessMonitoringManagerAsync();
var timeoutTask = Task.Delay(8000); // 8 second timeout
var completedTask = await Task.WhenAny(monitoringTask, timeoutTask);
if (completedTask == timeoutTask)
{
this.LogDebug("Process monitoring manager startup timed out after 8 seconds, continuing without monitoring...");
}
else
{
try
{
await monitoringTask; // Ensure we get any exceptions
this.LogDebug("Process monitoring manager started successfully");
}
catch (Exception taskEx)
{
this.LogDebug($"Process monitoring manager task failed: {taskEx.Message}");
}
}
}
catch (Exception monitoringEx)
{
this.LogDebug($"Process monitoring manager startup failed: {monitoringEx.Message}, continuing without monitoring...");
}
}
this.LogDebug("=== InitializeServicesAsync completed successfully ===");
}
private async Task InitializeSettingsAsync()
{
try
{
await this.settingsService.LoadSettingsAsync();
// Apply initial settings
var settings = this.settingsService.Settings;
var useDarkTheme = settings.HasUserThemePreference
? settings.UseDarkTheme
: this.themeService.GetSystemUsesDarkTheme();
if (!settings.HasUserThemePreference && settings.UseDarkTheme != useDarkTheme)
{
settings.UseDarkTheme = useDarkTheme;
await this.settingsService.UpdateSettingsAsync(settings);
}
this.themeService.ApplyTheme(useDarkTheme);
this.mainWindowViewModel.IsDarkTheme = useDarkTheme;
DwmHelper.ApplyWindowCaptionTheme(this, useDarkTheme);
if (settings.StartMinimized)
{
this.WindowState = WindowState.Minimized;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to load settings: {ex.Message}");
}
}
private async Task InitializeSystemTrayAsync()
{
try
{
this.systemTrayService.Initialize();
this.systemTrayService.Show();
// Subscribe to tray events
this.UnsubscribeSystemTrayEvents();
this.systemTrayService.ShowMainWindowRequested += this.OnShowMainWindowRequested;
this.systemTrayService.DashboardRequested += this.OnDashboardRequested;
this.systemTrayService.ExitRequested += this.OnExitRequested;
this.systemTrayService.MonitoringToggleRequested += this.OnMonitoringToggleRequested;
this.systemTrayService.SettingsRequested += this.OnSettingsRequested;
this.systemTrayService.PowerPlanChangeRequested += this.OnPowerPlanChangeRequested;
this.systemTrayService.ProfileApplicationRequested += this.OnProfileApplicationRequested;
this.systemTrayService.PerformanceDashboardRequested += this.OnPerformanceDashboardRequested;
// Update settings and tooltip
this.systemTrayService.UpdateSettings(this.settingsService.Settings);
this.systemTrayService.ApplyTheme(this.themeService.IsDarkTheme);
this.systemTrayService.UpdateTooltip("ThreadPilot - Process & Power Plan Manager");
// Initialize system tray context menu with current data
await this.UpdateSystemTrayContextMenuAsync();
// Start periodic system tray updates
this.StartSystemTrayUpdateTimer();
}
catch (Exception ex)
{
// Log error but don't fail startup
System.Diagnostics.Debug.WriteLine($"Failed to initialize system tray: {ex.Message}");
}
}
private async Task InitializeBasicSystemTrayAsync()
{
try
{
this.LogDebug("Initializing basic system tray (without full context menu)...");
// Initialize basic tray icon (this is idempotent)
this.systemTrayService.Initialize();
this.systemTrayService.Show();
// Subscribe to essential tray events only
this.UnsubscribeSystemTrayEvents();
this.systemTrayService.ShowMainWindowRequested += this.OnShowMainWindowRequested;
this.systemTrayService.DashboardRequested += this.OnDashboardRequested;
this.systemTrayService.ExitRequested += this.OnExitRequested;
// Update basic settings and tooltip
this.systemTrayService.UpdateSettings(this.settingsService.Settings);
this.systemTrayService.ApplyTheme(this.themeService.IsDarkTheme);
this.systemTrayService.UpdateTooltip("ThreadPilot - Process & Power Plan Manager (Basic Mode)");
this.LogDebug("Basic system tray initialization completed");
}
catch (Exception ex)
{
this.LogDebug($"Failed to initialize basic system tray: {ex.Message}");
throw;
}
}
private void OnShowMainWindowRequested(object? sender, EventArgs e)
{
this.ShowWindowFromTray();
}
private void OnExitRequested(object? sender, EventArgs e)
{
TaskSafety.FireAndForget(this.OnExitRequestedAsync(), ex =>
{
this.LogDebug($"OnExitRequested failed: {ex.Message}");
});
}
private async Task OnExitRequestedAsync()
{
await this.PerformGracefulShutdownAsync();
}
private void OnDashboardRequested(object? sender, EventArgs e)
{
this.ShowWindowFromTray("Process");
}
/// <summary>
/// Performs graceful shutdown with cleanup of all applied optimizations
/// Similar to CPU Set Setter's ExitAppGracefully.
/// </summary>
private async Task PerformGracefulShutdownAsync(bool validateUnsavedChanges = true)
{
if (this.isPerformingShutdown)
{
return;
}
if (validateUnsavedChanges && !await this.HandleUnsavedSettingsBeforeExitAsync())
{
return;
}
this.isPerformingShutdown = true;
try
{
this.LogDebug("Starting graceful shutdown...");
// 1. Stop monitoring services
try
{
this.LogDebug("Stopping process monitoring manager...");
await this.processMonitorManagerService.StopAsync();
this.LogDebug("Process monitoring manager stopped");
}
catch (Exception ex)
{
this.LogDebug($"Error stopping process monitoring: {ex.Message}");
}
// 2. Cleanup applied CPU masks (like CPU Set Setter's ClearAllProcessMasksNoSave)
if (this.settingsService.Settings.ClearMasksOnClose)
{
try
{
this.LogDebug("Clearing all applied CPU masks...");
var processService = this.serviceProvider.GetRequiredService<IProcessService>();
await processService.ClearAllAppliedMasksAsync();
this.LogDebug("CPU masks cleared");
}
catch (Exception ex)
{
this.LogDebug($"Error clearing CPU masks: {ex.Message}");
}
// Also reset priorities
try
{
this.LogDebug("Resetting all process priorities...");
var processService = this.serviceProvider.GetRequiredService<IProcessService>();
await processService.ResetAllProcessPrioritiesAsync();
this.LogDebug("Process priorities reset");
}
catch (Exception ex)
{
this.LogDebug($"Error resetting priorities: {ex.Message}");
}
}
// 3. Restore default power plan if configured
if (this.settingsService.Settings.RestoreDefaultPowerPlanOnExit)
{
try
{
var targetDefaultPowerPlanGuid = this.settingsService.Settings.DefaultPowerPlanId;
try
{
await this.processPowerPlanAssociationService.LoadConfigurationAsync();
var (associationDefaultPowerPlanGuid, _) = await this.processPowerPlanAssociationService.GetDefaultPowerPlanAsync();
if (!string.IsNullOrWhiteSpace(associationDefaultPowerPlanGuid))
{
targetDefaultPowerPlanGuid = associationDefaultPowerPlanGuid;
}
}
catch (Exception associationEx)
{
this.LogDebug($"Could not read default power plan from association config: {associationEx.Message}");
}
if (string.IsNullOrWhiteSpace(targetDefaultPowerPlanGuid))
{
this.LogDebug("No default power plan configured for restore on exit");
}
else
{
this.LogDebug("Restoring default power plan...");
var powerPlanService = this.serviceProvider.GetRequiredService<IPowerPlanService>();
await powerPlanService.SetActivePowerPlanByGuidAsync(targetDefaultPowerPlanGuid);
this.LogDebug("Default power plan restored");
}
}
catch (Exception ex)
{
this.LogDebug($"Error restoring power plan: {ex.Message}");
}
}
// 4. Save settings
try
{
this.LogDebug("Saving settings...");
await this.settingsService.SaveSettingsAsync();
this.LogDebug("Settings saved");
}
catch (Exception ex)
{
this.LogDebug($"Error saving settings: {ex.Message}");
}
// 5. Dispose tray service
try
{
this.LogDebug("Disposing system tray...");
this.systemTrayService.Dispose();
this.LogDebug("System tray disposed");
}
catch (Exception ex)
{
this.LogDebug($"Error disposing tray: {ex.Message}");
}
this.LogDebug("Graceful shutdown completed");
}
catch (Exception ex)
{
this.LogDebug($"Error during graceful shutdown: {ex.Message}");
}
finally
{
// Ensure application exits
System.Windows.Application.Current.Shutdown();
}
}
private async Task<bool> HandleUnsavedSettingsBeforeExitAsync()
{
if (!this.settingsViewModel.HasPendingChanges)
{
return true;
}
var result = System.Windows.MessageBox.Show(
"You have unsaved changes in Settings.\n\nChoose an action:\n- Yes: Save and exit\n- No: Discard and exit\n- Cancel: Return to app",
"Unsaved Settings",
MessageBoxButton.YesNoCancel,
MessageBoxImage.Warning);
if (result == MessageBoxResult.Cancel)
{
return false;
}
if (result == MessageBoxResult.Yes)
{
var saved = await this.settingsViewModel.SaveIfDirtyAsync();
return saved;
}
await this.settingsViewModel.DiscardPendingChangesAsync();
return true;
}
private async Task HandleWindowCloseAsync()
{
if (!await this.HandleUnsavedSettingsBeforeExitAsync())
{
return;
}
if (this.settingsService.Settings.CloseToTray)
{
this.WindowState = WindowState.Minimized;
return;
}
await this.PerformGracefulShutdownAsync(validateUnsavedChanges: false);
}
private void OnMonitoringToggleRequested(object? sender, MonitoringToggleEventArgs e)
{
TaskSafety.FireAndForget(this.OnMonitoringToggleRequestedAsync(e), ex =>
{
this.LogDebug($"OnMonitoringToggleRequested failed: {ex.Message}");
});
}
private async Task OnMonitoringToggleRequestedAsync(MonitoringToggleEventArgs e)
{
try
{
if (e.EnableMonitoring)
{
await this.processMonitorManagerService.StartAsync();
await this.notificationService.ShowSuccessNotificationAsync(
"Monitoring Enabled",
"Process monitoring and power plan management has been enabled");
}
else
{
await this.processMonitorManagerService.StopAsync();
await this.notificationService.ShowNotificationAsync(
"Monitoring Disabled",
"Process monitoring and power plan management has been disabled",
Models.NotificationType.Warning);
}
}
catch (Exception ex)
{
await this.notificationService.ShowErrorNotificationAsync(
"Monitoring Error",
"Failed to toggle process monitoring",
ex);
}
}
private void OnSettingsRequested(object? sender, EventArgs e)
{
try
{
this.ShowWindowFromTray("Settings");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to open settings: {ex.Message}");
}
}
private void OnPowerPlanChangeRequested(object? sender, PowerPlanChangeRequestedEventArgs e)
{
TaskSafety.FireAndForget(this.OnPowerPlanChangeRequestedAsync(e), ex =>
{
this.LogDebug($"OnPowerPlanChangeRequested failed: {ex.Message}");
});
}
private async Task OnPowerPlanChangeRequestedAsync(PowerPlanChangeRequestedEventArgs e)
{
try
{
var powerPlanService = this.serviceProvider.GetRequiredService<IPowerPlanService>();
var success = await powerPlanService.SetActivePowerPlanByGuidAsync(e.PowerPlanGuid);
if (success)
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot",
$"Power plan changed to {e.PowerPlanName}", 2000);
}
else
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot Error",
$"Failed to change power plan to {e.PowerPlanName}", 3000);
}
}
catch (Exception ex)
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot Error",
$"Error changing power plan: {ex.Message}", 3000);
}
}
private void OnProfileApplicationRequested(object? sender, ProfileApplicationRequestedEventArgs e)
{
TaskSafety.FireAndForget(this.OnProfileApplicationRequestedAsync(e), ex =>
{
this.LogDebug($"OnProfileApplicationRequested failed: {ex.Message}");
});
}
private async Task OnProfileApplicationRequestedAsync(ProfileApplicationRequestedEventArgs e)
{
try
{
var processService = this.serviceProvider.GetRequiredService<IProcessService>();
var selectedProcess = this.processViewModel.SelectedProcess;
if (selectedProcess != null)
{
var success = await processService.LoadProcessProfile(e.ProfileName, selectedProcess);
if (success)
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot",
$"Profile '{e.ProfileName}' applied to {selectedProcess.Name}", 2000);
}
else
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot Error",
$"Failed to apply profile '{e.ProfileName}'", 3000);
}
}
else
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot",
"No process selected for profile application", 2000);
}
}
catch (Exception ex)
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot Error",
$"Error applying profile: {ex.Message}", 3000);
}
}
private void OnPerformanceDashboardRequested(object? sender, EventArgs e)
{
try
{
this.ShowWindowFromTray("Performance");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to open performance dashboard: {ex.Message}");
}
}
private async Task InitializeKeyboardShortcutsAsync()
{
try
{
// Set window handle for global hotkey registration
var windowInteropHelper = new System.Windows.Interop.WindowInteropHelper(this);
var handle = windowInteropHelper.EnsureHandle();
if (this.keyboardShortcutService is KeyboardShortcutService service)
{
service.SetWindowHandle(handle);
}
// Subscribe to shortcut activation events
this.keyboardShortcutService.ShortcutActivated -= this.OnShortcutActivated;
this.keyboardShortcutService.ShortcutActivated += this.OnShortcutActivated;
// Load shortcuts from settings - with error handling
try
{
await this.keyboardShortcutService.LoadShortcutsFromSettingsAsync();
}
catch (Exception settingsEx)
{
System.Diagnostics.Debug.WriteLine($"Failed to load shortcuts from settings, using defaults: {settingsEx.Message}");
// Continue with default shortcuts if settings loading fails
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to initialize keyboard shortcuts: {ex.Message}");
// Don't let keyboard shortcut initialization failure prevent the app from starting
}
}
private void OnShortcutActivated(object? sender, ShortcutActivatedEventArgs e)
{
try
{
System.Windows.Application.Current.Dispatcher.InvokeAsync(async () =>
{
await this.HandleShortcutActionAsync(e.ActionName);
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error handling shortcut {e.ActionName}: {ex.Message}");
}
}
private async Task HandleShortcutActionAsync(string actionName)
{
switch (actionName)
{
case ShortcutActions.ShowMainWindow:
if (this.IsVisible && this.WindowState != WindowState.Minimized)
{
this.ShowInTaskbar = false;
this.Hide();
}
else
{
this.ShowWindowFromTray();
}
break;
case ShortcutActions.ToggleMonitoring:
// Toggle monitoring - implementation can be added later
await this.notificationService.ShowNotificationAsync("Keyboard Shortcut", "Toggle monitoring shortcut activated");
break;
case ShortcutActions.PowerPlanHighPerformance:
// Switch to high performance power plan - implementation can be added later
await this.notificationService.ShowNotificationAsync("Keyboard Shortcut", "High Performance power plan shortcut activated");
break;
case ShortcutActions.OpenTweaks:
this.ShowWindowFromTray("Tweaks");
break;
case ShortcutActions.OpenSettings:
this.ShowWindowFromTray("Settings");
break;
case ShortcutActions.RefreshProcessList:
// Refresh process list - implementation can be added later
await this.notificationService.ShowNotificationAsync("Keyboard Shortcut", "Refresh process list shortcut activated");
break;