-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
360 lines (303 loc) · 13.3 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
360 lines (303 loc) · 13.3 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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Media;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
using ShutdownTimerPro.Models;
using ShutdownTimerPro.Utilities;
using ShutdownTimerPro.UI;
namespace ShutdownTimerPro
{
public partial class MainWindow : Window, IDisposable
{
private readonly DispatcherTimer _timer;
private System.Windows.Forms.NotifyIcon _notifyIcon;
private DateTime _targetTime;
private bool _reminderShowed;
private bool _isRealExit;
private bool _disposed;
public MainWindow()
{
InitializeComponent();
_timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
_timer.Tick += OnTimerTick;
InitializeApp();
}
public void Dispose()
{
if (_disposed) return;
_timer?.Stop();
_notifyIcon?.Dispose();
_disposed = true;
GC.SuppressFinalize(this);
}
// Initialization & Setup
private void InitializeApp()
{
ExactDatePicker.SelectedDate = DateTime.Today;
var theme = RegistryService.LoadTheme();
ThemeToggle.IsChecked = theme == AppTheme.Dark;
ThemeManager.ApplyTheme(this, theme);
SetupSystemTray();
var pendingTask = RegistryService.LoadTask();
if (pendingTask != null) RestoreState(pendingTask);
else ResetUIState();
}
private void SetupSystemTray()
{
_notifyIcon = new System.Windows.Forms.NotifyIcon
{
Icon = new System.Drawing.Icon(Application.GetResourceStream(new Uri("pack://application:,,,/assets/icon.ico")).Stream),
Text = "Shutdown Timer Pro",
Visible = true
};
var menu = new System.Windows.Forms.ContextMenuStrip();
menu.Items.Add("Show", null, (s, e) => ShowAndActivate());
menu.Items.Add(new System.Windows.Forms.ToolStripSeparator());
menu.Items.Add("Exit", null, (s, e) => ExitApplication());
_notifyIcon.ContextMenuStrip = menu;
_notifyIcon.DoubleClick += (s, e) => ShowAndActivate();
}
// Core Timer Logic
private async void OnTimerTick(object sender, EventArgs e)
{
UpdateStatusDisplay();
HandleReminder();
if ((_targetTime - DateTime.Now).TotalSeconds <= 0)
{
_timer.Stop();
RegistryService.ClearTask();
var action = GetSelectedAction();
bool force = ChkForce.IsChecked == true;
// Fire and forget asynchronous OS power command
await PowerManager.ExecuteAsync(action, force);
ExitApplication();
}
}
private void HandleReminder()
{
if (ChkReminder.IsChecked != true || _reminderShowed) return;
int reminderMins = ParseInput(TxtReminderMins.Text);
if ((_targetTime - DateTime.Now).TotalMinutes <= reminderMins)
{
_reminderShowed = true;
ShowAndActivate();
if (ChkSound.IsChecked == true) SystemSounds.Asterisk.Play();
ShowBalloonNotification("Task Reminder", $"System will {GetSelectedAction()} in {reminderMins} minute(s).", System.Windows.Forms.ToolTipIcon.Warning, 5000);
}
}
// Event Handlers: Execution
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
BtnStart.Focus();
try
{
_targetTime = CalculateTargetTime();
if (_targetTime <= DateTime.Now) throw new InvalidOperationException("Target time must be in the future.");
_reminderShowed = false;
LblInfo.Text = $"Device will be {GetSelectedAction()} at {_targetTime:dd/MM/yyyy HH:mm:ss}";
ToggleControls(false);
SaveCurrentState();
_timer.Start();
UpdateStatusDisplay();
Hide();
ShowBalloonNotification("Timer Started", "App is running in the background.", System.Windows.Forms.ToolTipIcon.Info, 3000);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Configuration Error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void BtnStop_Click(object sender, RoutedEventArgs e)
{
_timer.Stop();
RegistryService.ClearTask();
ResetUIState();
}
// Event Handlers: UI Interactions
private void ThemeToggle_Changed(object sender, RoutedEventArgs e)
{
if (ThemeToggle == null) return;
var theme = ThemeToggle.IsChecked == true ? AppTheme.Dark : AppTheme.Light;
ThemeManager.ApplyTheme(this, theme);
RegistryService.SaveTheme(theme);
UpdateStatusDisplay();
}
private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed) DragMove();
}
private void TimingMode_Changed(object sender, RoutedEventArgs e)
{
if (PanelTimer != null) ToggleControls(true);
}
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e) => e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
private void NumberTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (sender is TextBox txt && (e.Key == Key.Up || e.Key == Key.Down))
AdjustNumericInput(txt, e.Key == Key.Up ? 1 : -1);
}
private void NumberTextBox_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (sender is TextBox txt)
{
AdjustNumericInput(txt, e.Delta > 0 ? 1 : -1);
e.Handled = true;
}
}
private void TimeTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox txt)
{
int max = ParseInput(txt.Tag?.ToString() ?? "0");
txt.Text = string.IsNullOrWhiteSpace(txt.Text) ? "00" : Math.Min(ParseInput(txt.Text), max).ToString("D2");
}
}
// Helpers: Parsing & Numeric Input
private int ParseInput(string input) => int.TryParse(input, out int result) ? result : 0;
private void AdjustNumericInput(TextBox txt, int delta)
{
int max = ParseInput(txt.Tag?.ToString() ?? "0");
int val = ParseInput(txt.Text) + delta;
txt.Text = (val > max ? 0 : (val < 0 ? max : val)).ToString("D2");
txt.CaretIndex = txt.Text.Length;
}
// Helpers: Task Calculation
private DateTime CalculateTargetTime()
{
if (RbModeTimer.IsChecked == true)
{
var ts = new TimeSpan(ParseInput(TxtCdHours.Text), ParseInput(TxtCdMinutes.Text), ParseInput(TxtCdSeconds.Text));
if (ts.TotalSeconds == 0) throw new InvalidOperationException("Duration must be greater than zero.");
return DateTime.Now.Add(ts);
}
if (!ExactDatePicker.SelectedDate.HasValue) throw new InvalidOperationException("Invalid date selected.");
var date = ExactDatePicker.SelectedDate.Value;
return new DateTime(date.Year, date.Month, date.Day, ParseInput(TxtExHours.Text), ParseInput(TxtExMinutes.Text), ParseInput(TxtExSeconds.Text));
}
private PowerAction GetSelectedAction()
{
if (RbRestart.IsChecked == true) return PowerAction.Restart;
if (RbSleep.IsChecked == true) return PowerAction.Sleep;
if (RbLock.IsChecked == true) return PowerAction.Lock;
return PowerAction.Shutdown;
}
// Helpers: UI State Management
private void UpdateStatusDisplay()
{
if (LblStatusSpace == null) return;
var remaining = _targetTime - DateTime.Now;
if (remaining.TotalSeconds < 0) remaining = TimeSpan.Zero;
if (BtnStart.IsEnabled)
{
LblStatusSpace.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#555555"));
return;
}
LblStatusSpace.Text = remaining.Days > 0
? $"{remaining.Days} {(remaining.Days == 1 ? "day" : "days")}, {remaining:hh\\:mm\\:ss}"
: remaining.ToString(@"hh\:mm\:ss");
LblStatusSpace.Foreground = remaining.TotalSeconds <= 60 ? new SolidColorBrush(Colors.Red) :
remaining.TotalSeconds <= 180 ? new SolidColorBrush(Colors.Orange) :
(SolidColorBrush)Resources["TextPrimaryBrush"];
}
private void ToggleControls(bool isEnabled)
{
BtnStart.IsEnabled = isEnabled;
BtnStop.IsEnabled = !isEnabled;
RbShutdown.IsEnabled = RbRestart.IsEnabled = RbSleep.IsEnabled = RbLock.IsEnabled = isEnabled;
RbModeTimer.IsEnabled = RbModeExact.IsEnabled = isEnabled;
PanelTimer.IsEnabled = isEnabled && RbModeTimer.IsChecked == true;
PanelExact.IsEnabled = isEnabled && RbModeExact.IsChecked == true;
PanelOptions.IsEnabled = isEnabled;
}
private void ResetUIState()
{
LblInfo.Text = "Select a task and set the time to begin";
LblStatusSpace.Text = "-- : -- : --";
ToggleControls(true);
UpdateStatusDisplay();
}
// Helpers: State Persistence
private void SaveCurrentState()
{
RegistryService.SaveTask(new ScheduleSettings
{
TargetTime = _targetTime,
IsTimerMode = RbModeTimer.IsChecked == true,
Action = GetSelectedAction(),
Force = ChkForce.IsChecked == true,
ReminderMins = ChkReminder.IsChecked == true ? ParseInput(TxtReminderMins.Text) : -1,
Sound = ChkSound.IsChecked == true
});
}
private void RestoreState(ScheduleSettings settings)
{
_targetTime = settings.TargetTime;
// Detach handlers so restoring the radio state doesn't trigger a transient ToggleControls(true)
RbModeTimer.Checked -= TimingMode_Changed;
RbModeExact.Checked -= TimingMode_Changed;
RbModeTimer.IsChecked = settings.IsTimerMode;
RbModeExact.IsChecked = !settings.IsTimerMode;
RbModeTimer.Checked += TimingMode_Changed;
RbModeExact.Checked += TimingMode_Changed;
RbShutdown.IsChecked = settings.Action == PowerAction.Shutdown;
RbRestart.IsChecked = settings.Action == PowerAction.Restart;
RbSleep.IsChecked = settings.Action == PowerAction.Sleep;
RbLock.IsChecked = settings.Action == PowerAction.Lock;
ChkForce.IsChecked = settings.Force;
ChkReminder.IsChecked = settings.ReminderMins != -1;
TxtReminderMins.Text = settings.ReminderMins != -1 ? settings.ReminderMins.ToString() : "5";
ChkSound.IsChecked = settings.Sound;
ToggleControls(false);
LblInfo.Text = $"Resuming missed task. Device will be {settings.Action} at {_targetTime:dd/MM/yyyy HH:mm:ss}";
UpdateStatusDisplay();
_timer.Start();
}
// Window Lifecycle Management
private void ShowAndActivate()
{
Show();
WindowState = WindowState.Normal;
Activate();
}
private void ShowBalloonNotification(string title, string text, System.Windows.Forms.ToolTipIcon icon, int timeout)
{
_notifyIcon.BalloonTipTitle = title;
_notifyIcon.BalloonTipText = text;
_notifyIcon.BalloonTipIcon = icon;
_notifyIcon.ShowBalloonTip(timeout);
}
private void ExitApplication()
{
_isRealExit = true;
Dispose();
Application.Current.Shutdown();
}
private void BtnCloseApp_Click(object sender, RoutedEventArgs e) => ExitApplication();
protected override void OnClosing(CancelEventArgs e)
{
if (_isRealExit) return;
e.Cancel = true;
Hide();
ShowBalloonNotification("Shutdown Timer Pro", "App minimized to notification area.", System.Windows.Forms.ToolTipIcon.Info, 2000);
}
// Modals & Links
private void AboutApp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
AboutModal.Visibility = Visibility.Visible;
}
private void CloseAboutModal_Click(object sender, RoutedEventArgs e) => AboutModal.Visibility = Visibility.Collapsed;
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
e.Handled = true;
}
}
}