-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.cs
More file actions
543 lines (467 loc) · 20.3 KB
/
Copy pathApp.cs
File metadata and controls
543 lines (467 loc) · 20.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
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
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using Microsoft.Win32;
using Application = System.Windows.Application;
using Button = System.Windows.Controls.Button;
using Clipboard = System.Windows.Clipboard;
using Color = System.Drawing.Color;
using FontFamily = System.Windows.Media.FontFamily;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using SystemFonts = System.Drawing.SystemFonts;
using TextBox = System.Windows.Controls.TextBox;
namespace ThinkPadBacklightTray;
public class App : Application
{
private const int DwmaUseImmersiveDarkMode = 20;
private EventMonitor? _eventMonitor;
private NotifyIcon? _notifyIcon;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ShutdownMode = ShutdownMode.OnExplicitShutdown;
SettingsManager.Initialize();
BacklightController.Initialize();
_eventMonitor = new EventMonitor();
_eventMonitor.OnRestoreBacklight += () => RestoreBacklight();
_eventMonitor.OnResumeRestoreBacklight += () => KickAndRestoreBacklight();
_eventMonitor.OnFnSpaceLevelChanged += level =>
{
Debug.WriteLine($"Fn+Space: persisting new level {level} to registry");
SettingsManager.SetBacklightLevel(level);
};
_eventMonitor.Start();
BuildTrayIcon();
// Restore backlight immediately on startup (e.g. after a reboot or log-on).
RestoreBacklight();
}
protected override void OnExit(ExitEventArgs e)
{
_eventMonitor?.Dispose();
_eventMonitor = null;
if (_notifyIcon != null)
{
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
_notifyIcon = null;
}
SettingsManager.Shutdown();
base.OnExit(e);
}
// ── tray icon ─────────────────────────────
private void BuildTrayIcon()
{
_notifyIcon = new NotifyIcon
{
Icon = LoadTrayIcon(),
Text = "ThinkPad Keyboard Backlight",
Visible = true,
ContextMenuStrip = BuildContextMenu()
};
_notifyIcon.MouseDoubleClick += (_, _) => _ = Task.Run(() => RestoreBacklight(true));
}
private ContextMenuStrip BuildContextMenu()
{
// Read from registry when building so menu always reflects persisted state.
var runAtStartupEnabled = SettingsManager.GetRunAtStartup();
var autoRestoreEnabled = SettingsManager.GetAutoRestore();
var restoreLevel = SettingsManager.GetRestoreLevel();
var restoreNow = new ToolStripMenuItem("Restore Now");
restoreNow.Click += (_, _) => _ = Task.Run(() => RestoreBacklight(true));
var autoRestoreItem = new ToolStripMenuItem("Auto Restore")
{
CheckOnClick = false,
Checked = autoRestoreEnabled
};
autoRestoreItem.Click += (_, _) =>
{
SettingsManager.SetAutoRestore(!autoRestoreEnabled);
RebuildTrayMenu();
};
// ── Restore To submenu (Last / Dim / Full) ──
var restoreToMenu = new ToolStripMenuItem("Restore To");
restoreToMenu.DropDownItems.Add(MakeRestoreToItem("Last", 0, restoreLevel));
restoreToMenu.DropDownItems.Add(MakeRestoreToItem("Dim", 1, restoreLevel));
restoreToMenu.DropDownItems.Add(MakeRestoreToItem("Full", 2, restoreLevel));
var runAtStartupItem = new ToolStripMenuItem("Run at Startup")
{
CheckOnClick = false,
Checked = runAtStartupEnabled
};
runAtStartupItem.Click += (_, _) =>
{
SettingsManager.SetRunAtStartup(!runAtStartupEnabled);
RebuildTrayMenu();
};
var info = new ToolStripMenuItem("Info...");
info.Click += (_, _) => ShowInfo();
var about = new ToolStripMenuItem("About...");
about.Click += (_, _) => ShowAbout();
var exit = new ToolStripMenuItem("Exit");
exit.Click += (_, _) => Shutdown();
var menu = new ContextMenuStrip
{
Font = SystemFonts.MenuFont,
ShowImageMargin = true,
ShowCheckMargin = true,
RenderMode = ToolStripRenderMode.Professional
};
menu.Items.Add(restoreNow);
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(autoRestoreItem);
menu.Items.Add(restoreToMenu);
menu.Items.Add(runAtStartupItem);
menu.Items.Add(info);
menu.Items.Add(about);
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(exit);
ApplyThemeToContextMenu(menu);
menu.Opening += (_, _) => ApplyThemeToContextMenu(menu);
return menu;
}
private ToolStripMenuItem MakeRestoreToItem(string text, int level, int currentLevel)
{
var item = new ToolStripMenuItem(text) { CheckOnClick = false, Checked = currentLevel == level };
item.Click += (_, _) => { SettingsManager.SetRestoreLevel(level); RebuildTrayMenu(); };
return item;
}
private void RebuildTrayMenu()
{
if (_notifyIcon == null) return;
var oldMenu = _notifyIcon.ContextMenuStrip;
_notifyIcon.ContextMenuStrip = BuildContextMenu();
oldMenu?.Dispose();
}
private static void ApplyThemeToContextMenu(ContextMenuStrip menu)
{
var darkMode = IsSystemDarkMode();
var renderer = new ToolStripProfessionalRenderer(new ThemedColorTable(darkMode));
var bg = darkMode ? Color.FromArgb(0x20, 0x20, 0x20) : Color.FromArgb(0xFA, 0xFA, 0xFA);
var fg = darkMode ? Color.FromArgb(0xF2, 0xF2, 0xF2) : Color.FromArgb(0x1C, 0x1C, 0x1C);
menu.Renderer = renderer;
menu.BackColor = bg;
menu.ForeColor = fg;
if (menu.IsHandleCreated)
_ = SetWindowTheme(menu.Handle, darkMode ? "DarkMode_Explorer" : "Explorer", null);
// Apply theming to any submenu dropdowns.
foreach (ToolStripItem item in menu.Items)
if (item is ToolStripMenuItem { HasDropDownItems: true } parent)
{
parent.DropDown.Renderer = renderer;
parent.DropDown.BackColor = bg;
parent.DropDown.ForeColor = fg;
}
}
private static Icon LoadTrayIcon()
{
try
{
var icoPath = Path.Combine(AppContext.BaseDirectory, "app.ico");
if (File.Exists(icoPath))
return new Icon(icoPath);
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to load tray icon: {ex.Message}");
}
return SystemIcons.Application;
}
// ── restore ───────────────────────────────
/// <summary>Returns true when the preconditions for a restore are met.</summary>
private static bool CanRestore(bool force, string callerName)
{
if (!force && !SettingsManager.GetAutoRestore())
{
Debug.WriteLine($"{callerName} skipped: auto restore is disabled");
return false;
}
if (!SessionHelper.IsConsoleSession())
{
Debug.WriteLine($"{callerName} skipped: not a physical console session");
return false;
}
if (!BacklightController.Initialize())
{
Debug.WriteLine($"{callerName} skipped: BacklightController not initialized");
return false;
}
return true;
}
private void RestoreBacklight(bool force = false)
{
if (!CanRestore(force, nameof(RestoreBacklight))) return;
var level = SettingsManager.GetEffectiveRestoreLevel();
BacklightController.SetBacklightLevel((BacklightController.BacklightLevel)level);
}
/// <summary>
/// Resume-only restore: sets a different level first to break the IBMPmDrv
/// post-sleep desync, waits briefly, then sets the real target.
/// </summary>
private void KickAndRestoreBacklight()
{
if (!CanRestore(false, nameof(KickAndRestoreBacklight))) return;
var target = SettingsManager.GetEffectiveRestoreLevel();
// Kick with Dim or Full (never Off) to break the post-sleep desync.
var kick = target == (int)BacklightController.BacklightLevel.Full
? BacklightController.BacklightLevel.Dim
: BacklightController.BacklightLevel.Full;
Debug.WriteLine($"KickAndRestoreBacklight: kick={kick} target={target}");
BacklightController.SetBacklightLevel(kick);
Thread.Sleep(500);
BacklightController.SetBacklightLevel((BacklightController.BacklightLevel)target);
}
// ── dialogs ───────────────────────────────
private static void ShowInfo()
{
var info = BuildInfoString();
var darkMode = IsSystemDarkMode();
var textBox = new TextBox
{
Text = info,
IsReadOnly = true,
FontFamily = new FontFamily("Consolas, Courier New, monospace"),
FontSize = 13,
AcceptsReturn = true,
TextWrapping = TextWrapping.Wrap,
BorderThickness = new Thickness(0),
Margin = new Thickness(12, 12, 12, 0),
VerticalScrollBarVisibility = ScrollBarVisibility.Auto
};
// Keep text selection-friendly while matching the current OS theme.
ApplyThemeToTextBox(textBox, darkMode);
var copyButton = new Button
{
Content = "Copy to Clipboard",
HorizontalAlignment = HorizontalAlignment.Right,
Margin = new Thickness(12),
Padding = new Thickness(16, 6, 16, 6)
};
ApplyThemeToButton(copyButton, darkMode);
var panel = new DockPanel();
DockPanel.SetDock(copyButton, Dock.Bottom);
panel.Children.Add(copyButton);
panel.Children.Add(textBox);
var window = new Window
{
Title = "ThinkPad Backlight Tray — Info",
Content = panel,
Width = 520,
Height = 420,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
ResizeMode = ResizeMode.CanResize
};
ApplyThemeToWindow(window, darkMode);
copyButton.Click += (_, _) =>
{
try
{
Clipboard.SetText(info);
copyButton.Content = "Copied ✓";
}
catch
{
copyButton.Content = "Copy failed";
}
};
window.Show();
}
private static void ShowAbout()
{
var darkMode = IsSystemDarkMode();
var version = Assembly.GetExecutingAssembly().GetName().Version;
var versionString = version != null ? $"v{version.Major}.{version.Minor}.{version.Build}" : "v1.0.0";
var titleText = new TextBlock
{
Text = "ThinkPad Backlight Tray",
FontSize = 18,
FontWeight = FontWeights.SemiBold,
Margin = new Thickness(0, 0, 0, 4)
};
var versionText = new TextBlock
{
Text = versionString,
FontSize = 12,
Opacity = 0.7,
Margin = new Thickness(0, 0, 0, 12)
};
var descText = new TextBlock
{
Text = "Automatically restores ThinkPad keyboard backlight\nafter lid-close, power, and display events.",
FontSize = 13,
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 0, 0, 12)
};
var licenseText = new TextBlock
{
Text = "Released under the MIT License.",
FontSize = 12,
Opacity = 0.7,
Margin = new Thickness(0, 0, 0, 8)
};
var closeButton = new Button
{
Content = "Close",
HorizontalAlignment = HorizontalAlignment.Right,
Margin = new Thickness(0, 16, 0, 0),
Padding = new Thickness(20, 6, 20, 6),
IsDefault = true,
IsCancel = true
};
ApplyThemeToButton(closeButton, darkMode);
var stack = new StackPanel { Margin = new Thickness(24, 24, 24, 20) };
stack.Children.Add(titleText);
stack.Children.Add(versionText);
stack.Children.Add(descText);
stack.Children.Add(licenseText);
stack.Children.Add(closeButton);
var window = new Window
{
Title = "About ThinkPad Backlight Tray",
Content = stack,
Width = 380,
SizeToContent = SizeToContent.Height,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
ResizeMode = ResizeMode.NoResize
};
ApplyThemeToWindow(window, darkMode);
// Propagate foreground to text blocks after theme sets window foreground.
var fg = window.Foreground;
titleText.Foreground = fg;
versionText.Foreground = fg;
descText.Foreground = fg;
licenseText.Foreground = fg;
closeButton.Click += (_, _) => window.Close();
window.Show();
}
// ── theming ───────────────────────────────
private static bool IsSystemDarkMode()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(
@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", false);
return Convert.ToInt32(key?.GetValue("AppsUseLightTheme", 1)) == 0;
}
catch
{
return false;
}
}
private static void ApplyThemeToWindow(Window window, bool darkMode)
{
var bg = darkMode
? System.Windows.Media.Color.FromRgb(0x20, 0x20, 0x20)
: System.Windows.Media.Color.FromRgb(0xF9, 0xF9, 0xF9);
var fg = darkMode
? System.Windows.Media.Color.FromRgb(0xF2, 0xF2, 0xF2)
: System.Windows.Media.Color.FromRgb(0x1C, 0x1C, 0x1C);
window.Background = new SolidColorBrush(bg);
window.Foreground = new SolidColorBrush(fg);
window.SourceInitialized += (_, _) =>
{
var hwnd = new WindowInteropHelper(window).Handle;
if (hwnd == IntPtr.Zero) return;
var useDark = darkMode ? 1 : 0;
_ = DwmSetWindowAttribute(hwnd, DwmaUseImmersiveDarkMode, ref useDark, sizeof(int));
_ = SetWindowTheme(hwnd, darkMode ? "DarkMode_Explorer" : "Explorer", null);
};
}
private static void ApplyThemeToTextBox(TextBox textBox, bool darkMode)
{
textBox.Background = new SolidColorBrush(darkMode
? System.Windows.Media.Color.FromRgb(0x2B, 0x2B, 0x2B)
: System.Windows.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
textBox.Foreground = new SolidColorBrush(darkMode
? System.Windows.Media.Color.FromRgb(0xF2, 0xF2, 0xF2)
: System.Windows.Media.Color.FromRgb(0x1C, 0x1C, 0x1C));
textBox.CaretBrush = textBox.Foreground;
}
private static void ApplyThemeToButton(Button button, bool darkMode)
{
button.Background = new SolidColorBrush(darkMode
? System.Windows.Media.Color.FromRgb(0x31, 0x31, 0x31)
: System.Windows.Media.Color.FromRgb(0xF3, 0xF3, 0xF3));
button.Foreground = new SolidColorBrush(darkMode
? System.Windows.Media.Color.FromRgb(0xF2, 0xF2, 0xF2)
: System.Windows.Media.Color.FromRgb(0x1C, 0x1C, 0x1C));
button.BorderBrush = new SolidColorBrush(darkMode
? System.Windows.Media.Color.FromRgb(0x4A, 0x4A, 0x4A)
: System.Windows.Media.Color.FromRgb(0xD0, 0xD0, 0xD0));
}
[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute);
[DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowTheme(IntPtr hwnd, string? pszSubAppName, string? pszSubIdList);
// ── info ──────────────────────────────────
internal static string BuildInfoString()
{
var savedLevel = SettingsManager.GetBacklightLevel();
var currentLevel = BacklightController.GetBacklightLevel();
var autoRestore = SettingsManager.GetAutoRestore();
var restoreLevel = SettingsManager.GetRestoreLevel();
var runAtStartup = SettingsManager.GetRunAtStartup();
var isConsoleSession = SessionHelper.IsConsoleSession();
var sb = new StringBuilder();
sb.AppendLine("ThinkPad Backlight Tray");
sb.AppendLine();
sb.AppendLine($"Machine: {Environment.MachineName}");
sb.AppendLine($"User: {Environment.UserName}");
sb.AppendLine($"OS: {Environment.OSVersion}");
sb.AppendLine($"Process: {(Environment.Is64BitProcess ? "x64" : "x86")}");
sb.AppendLine($"CLR: {Environment.Version}");
sb.AppendLine();
sb.AppendLine("Settings:");
sb.AppendLine($" Saved Backlight Level: {FormatLevel(savedLevel)} ({savedLevel})");
sb.AppendLine(
$" Current Backlight Level: {(currentLevel.HasValue ? $"{FormatLevel((int)currentLevel.Value)} ({(int)currentLevel.Value})" : "Unknown")}");
sb.AppendLine($" Auto Restore: {autoRestore}");
sb.AppendLine($" Restore To: {FormatRestoreMode(restoreLevel)}");
sb.AppendLine($" Run at Startup: {runAtStartup}");
sb.AppendLine($" Console Session: {isConsoleSession}");
sb.AppendLine();
sb.AppendLine(BacklightController.GetProviderStatusSummary());
return sb.ToString();
static string FormatLevel(int level) => level switch
{
0 => "Off",
1 => "Dim",
2 => "Full",
_ => "Unknown"
};
static string FormatRestoreMode(int mode) => mode switch
{
0 => "Last",
1 => "Dim",
2 => "Full",
_ => "Unknown"
};
}
private sealed class ThemedColorTable(bool darkMode) : ProfessionalColorTable
{
private readonly bool _dark = darkMode;
private Color Bg => _dark ? Color.FromArgb(0x20, 0x20, 0x20) : Color.FromArgb(0xFA, 0xFA, 0xFA);
private Color Border => _dark ? Color.FromArgb(0x44, 0x44, 0x44) : Color.FromArgb(0xD0, 0xD0, 0xD0);
private Color ItemHover => _dark ? Color.FromArgb(0x3A, 0x3A, 0x3A) : Color.FromArgb(0xE8, 0xE8, 0xE8);
private Color ItemPressed => _dark ? Color.FromArgb(0x45, 0x45, 0x45) : Color.FromArgb(0xDE, 0xDE, 0xDE);
private Color Sep => _dark ? Color.FromArgb(0x4A, 0x4A, 0x4A) : Color.FromArgb(0xDB, 0xDB, 0xDB);
public override Color ToolStripDropDownBackground => Bg;
public override Color MenuBorder => Border;
public override Color MenuItemBorder => Border;
public override Color MenuItemSelected => ItemHover;
public override Color MenuItemSelectedGradientBegin => ItemHover;
public override Color MenuItemSelectedGradientEnd => ItemHover;
public override Color MenuItemPressedGradientBegin => ItemPressed;
public override Color MenuItemPressedGradientMiddle => ItemPressed;
public override Color MenuItemPressedGradientEnd => ItemPressed;
public override Color SeparatorDark => Sep;
public override Color SeparatorLight => Sep;
public override Color ImageMarginGradientBegin => Bg;
public override Color ImageMarginGradientMiddle => Bg;
public override Color ImageMarginGradientEnd => Bg;
}
}