-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
590 lines (502 loc) · 16.2 KB
/
MainWindow.xaml.cs
File metadata and controls
590 lines (502 loc) · 16.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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using TidyWindow.App.Services;
using TidyWindow.App.ViewModels;
using TidyWindow.App.Views;
namespace TidyWindow.App;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly NavigationService _navigationService;
private readonly MainViewModel _viewModel;
private readonly ITrayService _trayService;
private readonly UserPreferencesService _preferences;
private readonly PulseGuardService _pulseGuard;
private readonly IAutomationWorkTracker _workTracker;
private System.Windows.Navigation.NavigationService? _frameNavigationService;
private bool _contentDetached;
private CancellationTokenSource? _idleTrimCts;
private bool _initialNavigationCompleted;
private bool _autoCloseArmed;
private DispatcherTimer? _traySweepTimer;
private HwndSource? _hwndSource;
private static uint _taskbarCreatedMessage;
private static readonly TimeSpan TraySweepIntervalMinimum = TimeSpan.FromSeconds(30);
private static readonly TimeSpan TraySweepIntervalMaximum = TimeSpan.FromMinutes(10);
public MainWindow(MainViewModel viewModel, NavigationService navigationService, ITrayService trayService, UserPreferencesService preferences, PulseGuardService pulseGuard, IAutomationWorkTracker workTracker)
{
InitializeComponent();
_navigationService = navigationService;
_viewModel = viewModel;
_trayService = trayService ?? throw new ArgumentNullException(nameof(trayService));
_preferences = preferences ?? throw new ArgumentNullException(nameof(preferences));
_pulseGuard = pulseGuard ?? throw new ArgumentNullException(nameof(pulseGuard));
_workTracker = workTracker ?? throw new ArgumentNullException(nameof(workTracker));
DataContext = _viewModel;
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
ToggleLoadingOverlay(_viewModel.IsShellLoading);
Loaded += OnLoaded;
StateChanged += OnStateChanged;
_trayService.Attach(this);
UpdateMaximizeVisualState();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Loaded -= OnLoaded;
_viewModel.BeginShellLoad();
_navigationService.Initialize(ContentFrame);
_frameNavigationService = ContentFrame.NavigationService;
if (_frameNavigationService is not null)
{
_frameNavigationService.LoadCompleted += OnInitialNavigationCompleted;
}
_viewModel.Activate();
// Hook into window messages for shell restart notification (explorer.exe crashes)
RegisterForShellRestart();
}
/// <summary>
/// Registers for TaskbarCreated message to detect when explorer.exe restarts.
/// This allows us to recreate the tray icon if it was lost.
/// </summary>
private void RegisterForShellRestart()
{
if (!OperatingSystem.IsWindows())
{
return;
}
try
{
_taskbarCreatedMessage = RegisterWindowMessage("TaskbarCreated");
var helper = new WindowInteropHelper(this);
_hwndSource = HwndSource.FromHwnd(helper.Handle);
_hwndSource?.AddHook(WndProc);
}
catch
{
// Non-critical; tray service has backup health checks
}
}
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern uint RegisterWindowMessage(string lpString);
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Check if this is the TaskbarCreated message (explorer.exe restarted)
if (_taskbarCreatedMessage != 0 && msg == _taskbarCreatedMessage)
{
// Notify the tray service to recreate its icon
if (_trayService is TrayService trayService)
{
trayService.OnShellRestarted();
}
}
return IntPtr.Zero;
}
private async void OnInitialNavigationCompleted(object? sender, System.Windows.Navigation.NavigationEventArgs e)
{
if (_initialNavigationCompleted)
{
return;
}
_initialNavigationCompleted = true;
if (_frameNavigationService is not null)
{
_frameNavigationService.LoadCompleted -= OnInitialNavigationCompleted;
}
await Task.Delay(250);
_viewModel.CompleteShellLoad();
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(MainViewModel.IsShellLoading))
{
ToggleLoadingOverlay(_viewModel.IsShellLoading);
}
}
private void OnStateChanged(object? sender, EventArgs e)
{
UpdateMaximizeVisualState();
if (_contentDetached && WindowState != WindowState.Minimized)
{
CancelIdleTrim();
RestoreContentAfterBackground();
}
if (WindowState == WindowState.Minimized && _preferences.Current.RunInBackground)
{
StartTraySweepTimerIfNeeded();
}
else
{
StopTraySweepTimer();
}
}
private void ToggleLoadingOverlay(bool show)
{
if (LoadingOverlay is null)
{
return;
}
LoadingOverlay.BeginAnimation(OpacityProperty, null);
var duration = TimeSpan.FromMilliseconds(260);
var animation = new DoubleAnimation
{
To = show ? 1d : 0d,
Duration = new Duration(duration),
EasingFunction = new QuarticEase { EasingMode = EasingMode.EaseInOut }
};
if (show)
{
LoadingOverlay.Opacity = 0d;
LoadingOverlay.Visibility = Visibility.Visible;
LoadingOverlay.IsHitTestVisible = true;
animation.From = 0d;
LoadingOverlay.BeginAnimation(OpacityProperty, animation);
}
else
{
animation.Completed += (_, _) =>
{
LoadingOverlay.Visibility = Visibility.Collapsed;
LoadingOverlay.IsHitTestVisible = false;
};
LoadingOverlay.BeginAnimation(OpacityProperty, animation);
}
}
protected override void OnClosed(EventArgs e)
{
CancelAutoCloseSubscription();
base.OnClosed(e);
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
if (_frameNavigationService is not null)
{
_frameNavigationService.LoadCompleted -= OnInitialNavigationCompleted;
_frameNavigationService = null;
}
// Clean up shell restart hook
if (_hwndSource is not null)
{
_hwndSource.RemoveHook(WndProc);
_hwndSource = null;
}
StateChanged -= OnStateChanged;
}
protected override void OnClosing(CancelEventArgs e)
{
if (!_trayService.IsExitRequested && _preferences.Current.RunInBackground)
{
e.Cancel = true;
_trayService.HideToTray(showHint: true);
ScheduleIdleTrimIfSafe();
StartTraySweepTimerIfNeeded();
return;
}
if (!_preferences.Current.RunInBackground)
{
var activeWork = _workTracker.GetActiveWork();
if (activeWork.Count > 0)
{
var decision = _pulseGuard.PromptPendingAutomation(activeWork);
switch (decision)
{
case PendingAutomationDecision.WaitAndCloseAfterCompletion:
e.Cancel = true;
ArmAutoClose();
return;
case PendingAutomationDecision.WaitWithoutClosing:
e.Cancel = true;
CancelAutoCloseSubscription();
_viewModel.SetStatusMessage("Waiting for automation to finish; TidyWindow will stay open.");
return;
default:
CancelAutoCloseSubscription();
break;
}
}
}
_trayService.PrepareForExit();
base.OnClosing(e);
}
private void ArmAutoClose()
{
if (_autoCloseArmed)
{
return;
}
_autoCloseArmed = true;
_workTracker.ActiveWorkChanged += OnActiveWorkChanged;
_viewModel.SetStatusMessage("Waiting for automation to finish before closing...");
}
private void CancelAutoCloseSubscription()
{
if (!_autoCloseArmed)
{
return;
}
_workTracker.ActiveWorkChanged -= OnActiveWorkChanged;
_autoCloseArmed = false;
}
private async void OnActiveWorkChanged(object? sender, EventArgs e)
{
if (!_autoCloseArmed)
{
return;
}
if (_workTracker.HasActiveWork)
{
return;
}
await Task.Delay(400).ConfigureAwait(false);
if (_workTracker.HasActiveWork)
{
return;
}
CancelAutoCloseSubscription();
Dispatcher.Invoke(() =>
{
_trayService.PrepareForExit();
Close();
});
}
private void TitleBar_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
e.Handled = true;
ToggleWindowState();
return;
}
if (e.LeftButton == MouseButtonState.Pressed)
{
try
{
DragMove();
}
catch (InvalidOperationException)
{
// Swallow drag exceptions that can happen during state transitions.
}
}
}
private void MinimizeButton_OnClick(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void DetachContentForBackground()
{
if (_contentDetached)
{
return;
}
if (_workTracker.HasActiveWork)
{
return; // Do not clear UI while automation is active.
}
if (ContentFrame is null)
{
return;
}
if (_navigationService.IsInitialized)
{
_viewModel.NavigateTo(typeof(BootstrapPage));
}
var nav = ContentFrame.NavigationService;
if (nav is not null)
{
while (nav.RemoveBackEntry() is not null) { }
nav.Content = null;
}
ContentFrame.Content = null; // Release the visual tree so memory can drop while in the tray.
_navigationService.ClearCache();
_contentDetached = true;
// GC on a background thread so the UI thread stays responsive.
_ = Task.Run(() =>
{
GC.Collect(2, GCCollectionMode.Optimized, blocking: false);
GC.WaitForPendingFinalizers();
GC.Collect(0, GCCollectionMode.Optimized, blocking: false);
TrimWorkingSet();
});
}
private void RestoreContentAfterBackground()
{
if (!_contentDetached)
{
return;
}
CancelIdleTrim();
_contentDetached = false;
_viewModel.Activate(); // Re-navigate to the selected item (or default) to rebuild the UI.
}
private void ScheduleIdleTrimIfSafe()
{
CancelIdleTrim();
if (!_preferences.Current.RunInBackground)
{
return;
}
if (WindowState != WindowState.Minimized)
{
return;
}
if (_workTracker.HasActiveWork)
{
return;
}
_idleTrimCts = new CancellationTokenSource();
_ = RunIdleTrimAsync(_idleTrimCts.Token);
}
private async Task RunIdleTrimAsync(CancellationToken token)
{
try
{
await Task.Delay(TimeSpan.FromMinutes(5), token);
if (token.IsCancellationRequested)
{
return;
}
if (WindowState != WindowState.Minimized || !_preferences.Current.RunInBackground)
{
return;
}
if (_workTracker.HasActiveWork)
{
return; // Skip if any automation is running.
}
_navigationService.SweepCache();
_viewModel.LogActivityInformation("PulseGuard", "Idle tray cache sweep executed.");
TrimWorkingSet();
}
catch (OperationCanceledException)
{
// Ignore cancellation.
}
}
private void StartTraySweepTimerIfNeeded()
{
if (!_preferences.Current.RunInBackground || WindowState != WindowState.Minimized)
{
StopTraySweepTimer();
return;
}
if (_traySweepTimer is null)
{
_traySweepTimer = new DispatcherTimer();
_traySweepTimer.Tick += OnTraySweepTick;
}
ScheduleNextTraySweep();
}
private void StopTraySweepTimer()
{
if (_traySweepTimer is null)
{
return;
}
_traySweepTimer.Stop();
_traySweepTimer.Tick -= OnTraySweepTick;
_traySweepTimer = null;
}
private void OnTraySweepTick(object? sender, EventArgs e)
{
if (!_preferences.Current.RunInBackground || WindowState != WindowState.Minimized)
{
StopTraySweepTimer();
return;
}
if (_workTracker.HasActiveWork)
{
ScheduleNextTraySweep();
return;
}
_navigationService.SweepCache();
ScheduleNextTraySweep();
}
private void ScheduleNextTraySweep()
{
if (_traySweepTimer is null)
{
return;
}
_navigationService.SweepCache();
var nextExpiry = _navigationService.GetNextCacheExpiryUtc();
if (nextExpiry is null)
{
StopTraySweepTimer();
return;
}
var now = DateTimeOffset.UtcNow;
var delay = nextExpiry.Value - now;
if (delay < TraySweepIntervalMinimum)
{
delay = TraySweepIntervalMinimum;
}
else if (delay > TraySweepIntervalMaximum)
{
delay = TraySweepIntervalMaximum;
}
_traySweepTimer.Interval = delay;
if (!_traySweepTimer.IsEnabled)
{
_traySweepTimer.Start();
}
}
private void CancelIdleTrim()
{
_idleTrimCts?.Cancel();
_idleTrimCts?.Dispose();
_idleTrimCts = null;
}
private static void TrimWorkingSet()
{
if (!OperatingSystem.IsWindows())
{
return;
}
try
{
using var process = Process.GetCurrentProcess();
_ = EmptyWorkingSet(process.Handle);
_ = SetProcessWorkingSetSize(process.Handle, new IntPtr(-1), new IntPtr(-1));
}
catch
{
// Best-effort trim; ignore failures.
}
}
[DllImport("psapi.dll")]
private static extern bool EmptyWorkingSet(IntPtr hProcess);
[DllImport("kernel32.dll")]
private static extern bool SetProcessWorkingSetSize(IntPtr hProcess, IntPtr dwMinimumWorkingSetSize, IntPtr dwMaximumWorkingSetSize);
private void MaximizeButton_OnClick(object sender, RoutedEventArgs e)
{
ToggleWindowState();
}
private void CloseButton_OnClick(object sender, RoutedEventArgs e)
{
Close();
}
private void ToggleWindowState()
{
WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
UpdateMaximizeVisualState();
}
private void UpdateMaximizeVisualState()
{
if (MaximizeGlyph is null)
{
return;
}
MaximizeGlyph.Text = WindowState == WindowState.Maximized ? "\uE923" : "\uE922";
MaximizeGlyph.ToolTip = WindowState == WindowState.Maximized ? "Restore Down" : "Maximize";
}
}