-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.dart
More file actions
579 lines (530 loc) · 27.3 KB
/
Copy paththeme.dart
File metadata and controls
579 lines (530 loc) · 27.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
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
// Applies a palette to the Windows system accent.
//
// Windows keeps an eight-shade accent ramp in
// HKCU\...\Explorer\Accent -> AccentPalette (REG_BINARY, 8 x BGRA, dark -> light)
// and single colours in
// HKCU\Software\Microsoft\Windows\DWM -> AccentColor / ColorizationColor (ABGR)
// HKCU\...\Explorer\Accent -> AccentColorMenu / StartColorMenu (ABGR)
//
// The built-in "accent from wallpaper" feature writes these too, but gives no
// control over the result. Writing the whole ramp ourselves is what makes a derived
// theme look deliberate rather than like one colour smeared everywhere.
//
// Everything here is per-user registry only - no injection, and fully reversible
// from Settings > Personalisation > Colours.
import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'palette.dart';
class ThemeResult {
final bool applied;
final String message;
/// The ramp actually written to AccentPalette - which is NOT simply the ramp that
/// was passed in: the chosen accent is substituted into it. Callers that need a
/// related shade (the taskbar tint, say) must use this one, or they end up tinting
/// with a colour that is no longer in the palette.
final List<Swatch> ramp;
const ThemeResult(this.applied, this.message, {this.ramp = const []});
}
/// What Windows currently holds for the accent, and whether it hangs together.
class ThemeState {
final List<String> lines;
final bool consistent;
final String? accent;
const ThemeState({required this.lines, required this.consistent, this.accent});
}
/// The 48 accent colours Windows offers in Settings > Personalisation > Colours.
///
/// Offered as an option (`--snap`), NOT the default. Windows accepts any colour as an
/// accent - verified with tool/probe_nosnap.dart, which applies non-preset colours and
/// reads back the accent Windows derives for each: all exact.
///
/// Snapping existed to work around accents that seemed not to reach Start and the
/// notification centre. The real cause was the byte order in _abgr(); with that fixed,
/// snapping only takes colours away. It is actively wrong for anything outside the
/// preset gamut - the presets are nearly all mid-tone and saturated, so a dark or muted
/// pick has no near neighbour and lands on a grey: #2E1513, a deep maroon, snapped to
/// #4C4A48 and turned the whole desktop grey.
const windowsAccentColours = <String>[
'FFB900', 'E74856', '0078D7', '0099BC', '7A7574', '767676',
'FF8C00', 'E81123', '0063B1', '2D7D9A', '5D5A58', '4C4A48',
'F7630C', 'EA005E', '8E8CD8', '00B7C3', '68768A', '69797E',
'CA5010', 'C30052', '6B69D6', '038387', '515C6B', '4A5459',
'DA3B01', 'E3008C', '8764B8', '00B294', '567C73', '647C64',
'EF6950', 'BF0077', '744DA9', '018574', '486860', '525E54',
'D13438', 'C239B3', 'B146C2', '00CC6A', '498205', '847545',
'FF4343', '9A0089', '881798', '10893E', '107C10', '7E735F',
];
class SystemTheme {
static bool get supported => Platform.isWindows;
/// The Windows preset accent closest to [s].
///
/// Distance is "redmean" rather than plain RGB: it weights the channels roughly the
/// way the eye does, so the match looks right instead of merely being arithmetically
/// near.
static Swatch snapToWindowsAccent(Swatch s) {
Swatch? best;
var bestDistance = double.infinity;
for (final hex in windowsAccentColours) {
final v = int.parse(hex, radix: 16);
final r = (v >> 16) & 0xFF, g = (v >> 8) & 0xFF, b = v & 0xFF;
final rMean = (s.r + r) / 2;
final dr = (s.r - r).toDouble();
final dg = (s.g - g).toDouble();
final db = (s.b - b).toDouble();
final d = (2 + rMean / 256) * dr * dr +
4 * dg * dg +
(2 + (255 - rMean) / 256) * db * db;
if (d < bestDistance) {
bestDistance = d;
best = Swatch(r, g, b, s.population, chromatic: s.chromatic);
}
}
return best ?? s;
}
static const _accentKey = r'HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Accent';
static const _dwmKey = r'HKCU\Software\Microsoft\Windows\DWM';
/// Every accent value Windows stores is **RGBA in memory** - red byte first, alpha
/// last - which as a DWORD reads 0xAABBGGRR. One rule, no exceptions:
///
/// DWM\AccentColor / ColorizationColor / ColorizationAfterglow -> _abgr()
/// Explorer\Accent StartColorMenu / AccentColorMenu -> _abgr()
/// AccentPalette entries -> r,g,b,a bytes
///
/// Getting it backwards swaps red and blue, so a blue accent renders orange-brown -
/// the "buggy theme" colour that kept coming back no matter what was picked.
///
/// HOW TO CHECK IT, because this cost days: query the colour Windows itself derives,
///
/// $ui = [Windows.UI.ViewManagement.UISettings, Windows.UI.ViewManagement,
/// ContentType=WindowsRuntime]::new()
/// $ui.GetColorValue([Windows.UI.ViewManagement.UIColorType]::Accent)
///
/// and compare it with the accent that was applied. This is the immersive colour
/// set - what Firefox, UWP apps, Start and the notification centre actually read -
/// and it is derived from these registry values rather than copied, so it cannot
/// agree with a wrong write the way a read-back does.
///
/// Two earlier methods both gave false confirmation and should not be trusted alone:
///
/// * Reading our own writes back. Write and read the same wrong order and it
/// agrees perfectly - every self-check passed while the screen was wrong.
/// * Sampling a title bar (tool/probe_rendered_accent.dart). DWM is separately fed
/// the correct colour by pushToDwm, so title bars look right regardless of what
/// the registry holds. It measures DWM, not this.
///
/// And a grey accent is symmetric under a red/blue swap, so it hides the bug
/// entirely - always test with something saturated. The old claim that AccentPalette
/// was BGRA came from exactly that trap: it was "confirmed" against Windows' own
/// #DCDEDF entry, a grey, which reads the same either way.
static int _abgr(Swatch s, {int a = 0xFF}) =>
(a << 24) | (s.b << 16) | (s.g << 8) | s.r;
/// `reg add /t REG_DWORD /d` wants decimal or an explicit 0x prefix; bare hex is
/// rejected silently enough to look like the value simply did not apply.
static String _dword(int v) => '0x${(v & 0xFFFFFFFF).toRadixString(16).toUpperCase()}';
static ProcessResult _reg(List<String> args) => Process.runSync('reg', args);
/// Windows chooses black or white text on an accent-coloured surface (taskbar,
/// Start, title bars, menus) from the surface colour's brightness, using this
/// rule: white text when `2R + 5G + B <= 1024` (~50% of the 2040 max), else black.
/// Verified against the stock accents: #0078D4 -> 812 (white text), #FFF100 ->
/// 1715 (black text).
static bool winUsesWhiteText(Swatch s) => (2 * s.r + 5 * s.g + s.b) <= 1024;
/// Writing the accent registry keys does NOT repaint anything - the change only
/// shows on next login unless the shell is told to re-read its colours. This
/// broadcast is the difference between "theme applied but invisible" and it
/// actually taking effect live. Verified: without it, title bars stay dark despite
/// a valid AccentColor + ColorPrevalence; with it, they recolour immediately.
static void _broadcastColourChange() {
if (!Platform.isWindows) return;
final user32 = DynamicLibrary.open('user32.dll');
// SendMessageTimeoutW(hwnd, msg, wParam, lParam, flags, timeout, out result)
final sendW = user32.lookupFunction<
IntPtr Function(IntPtr, Uint32, IntPtr, Pointer<Utf16>, Uint32, Uint32, Pointer<IntPtr>),
int Function(int, int, int, Pointer<Utf16>, int, int, Pointer<IntPtr>)>('SendMessageTimeoutW');
const hwndBroadcast = 0xFFFF;
const smtoAbortIfHung = 0x0002;
final result = calloc<IntPtr>();
final immersive = 'ImmersiveColorSet'.toNativeUtf16();
final empty = ''.toNativeUtf16();
try {
// WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320 (DWM/title bars)
sendW(hwndBroadcast, 0x0320, 0, empty, smtoAbortIfHung, 1000, result);
// WM_THEMECHANGED = 0x031A
sendW(hwndBroadcast, 0x031A, 0, empty, smtoAbortIfHung, 1000, result);
// WM_SETTINGCHANGE = 0x001A with "ImmersiveColorSet" (Start/Settings/UWP)
sendW(hwndBroadcast, 0x001A, 0, immersive, smtoAbortIfHung, 1000, result);
} finally {
calloc.free(result);
calloc.free(immersive);
calloc.free(empty);
}
}
static const _personalizeKey =
r'HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize';
/// Hands the colour to DWM itself, which is the step that actually repaints title
/// bars and the accent surfaces.
///
/// Writing AccentColor to the registry does NOT reach DWM: it loads colorization
/// once and keeps it. Measured - three different registry layouts in a row all left
/// the title bar on the same stale colour, while changing the accent in Settings
/// worked instantly, because Settings does not merely write the registry either.
/// Everything that looked like a byte-order bug, a "stuck palette" or a theme that
/// "kept coming back" traces to this: the registry was right and DWM never re-read
/// it, so whatever colour DWM last loaded is what stayed on screen.
///
/// The call is DwmSetColorizationParameters, undocumented and exported by ordinal
/// only, so it lives in LucentAgent.exe - Dart FFI cannot look symbols up by
/// ordinal.
static bool pushToDwm(Swatch s) {
if (!Platform.isWindows) return false;
final agent = _agentPath();
if (agent == null) return false;
final argb = 'FF${s.hex}';
try {
return Process.runSync(agent, ['accent', argb]).exitCode == 0;
} catch (_) {
return false;
}
}
/// LucentAgent.exe, beside the CLI or in the install folder.
static String? _agentPath() {
final beside = File(Platform.resolvedExecutable).parent.path;
for (final c in [
'$beside\\LucentAgent.exe',
'${Platform.environment['LOCALAPPDATA']}\\Programs\\Lucent\\LucentAgent.exe',
]) {
if (File(c).existsSync()) return c;
}
return null;
}
/// Start and the notification centre are drawn by their OWN processes -
/// StartMenuExperienceHost.exe and ShellExperienceHost.exe - not by Explorer. They
/// read the accent once at launch and ignore the colour-change broadcast, so a new
/// theme leaves them on the previous colour until they next start.
///
/// Restarting them is what makes the change show without signing out; Windows
/// brings both back automatically the moment they are needed. An open Start menu
/// closes, which is the only visible cost.
static void refreshShellHosts() {
if (!Platform.isWindows) return;
for (final exe in const [
'StartMenuExperienceHost.exe',
'ShellExperienceHost.exe',
]) {
try {
Process.runSync('taskkill', ['/f', '/im', exe]);
} catch (_) {
// Not running, or Windows would not let it go - nothing to do either way.
}
}
}
/// Switch Windows between light and dark mode. [apps] controls app windows;
/// [system] controls the taskbar/Start/shell. Applies live via the same broadcast
/// the accent uses. Returns null on success or a reason.
static String? setMode({required bool light, bool apps = true, bool system = true}) {
if (!Platform.isWindows) return 'light/dark switching is Windows-only';
final v = light ? '1' : '0';
if (apps) {
_reg(['add', _personalizeKey, '/v', 'AppsUseLightTheme', '/t', 'REG_DWORD', '/d', v, '/f']);
}
if (system) {
_reg(['add', _personalizeKey, '/v', 'SystemUsesLightTheme', '/t', 'REG_DWORD', '/d', v, '/f']);
}
_broadcastColourChange();
return null;
}
/// True if Windows is currently in light mode (apps).
static bool isLightMode() {
if (!Platform.isWindows) return false;
final r = _reg(['query', _personalizeKey, '/v', 'AppsUseLightTheme']);
final m = RegExp(r'AppsUseLightTheme\s+REG_DWORD\s+0x([0-9a-fA-F]+)')
.firstMatch(r.stdout as String);
return m != null && int.parse(m.group(1)!, radix: 16) == 1;
}
/// The current system accent as hex RRGGBB, or null. Windows stores it as ABGR
/// (0xAABBGGRR) in DWM\AccentColor - the byte order is the usual gotcha.
static String? currentAccentHex() {
if (!Platform.isWindows) return null;
final r = _reg(['query', _dwmKey, '/v', 'AccentColor']);
final m = RegExp(r'AccentColor\s+REG_DWORD\s+0x([0-9a-fA-F]+)').firstMatch(r.stdout as String);
if (m == null) return null;
final v = int.parse(m.group(1)!, radix: 16);
// ABGR, matching _abgr().
final rr = v & 0xFF, gg = (v >> 8) & 0xFF, bb = (v >> 16) & 0xFF;
String h(int x) => x.toRadixString(16).padLeft(2, '0').toUpperCase();
return '${h(rr)}${h(gg)}${h(bb)}';
}
/// The live 8-shade accent ramp (dark -> light) as Windows currently holds it in
/// AccentPalette, so the app and the notification popup can tint themselves from
/// exactly the same source the shell is using. Falls back to a ramp derived from
/// AccentColor, then to null if there is no accent at all.
static List<Swatch>? currentRamp() {
if (!Platform.isWindows) return null;
final r = _reg(['query', _accentKey, '/v', 'AccentPalette']);
final m = RegExp(r'AccentPalette\s+REG_BINARY\s+([0-9A-Fa-f]+)').firstMatch(r.stdout as String);
final hex = m?.group(1);
if (hex != null && hex.length >= 64) {
final out = <Swatch>[];
for (var i = 0; i < 8; i++) {
final o = i * 8; // 4 bytes = 8 hex chars per entry, stored RGBA
final rr = int.parse(hex.substring(o, o + 2), radix: 16);
final g = int.parse(hex.substring(o + 2, o + 4), radix: 16);
final b = int.parse(hex.substring(o + 4, o + 6), radix: 16);
out.add(Swatch(rr, g, b, 1.0));
}
return out;
}
final accent = currentAccentHex();
if (accent == null) return null;
final v = int.parse(accent, radix: 16);
return PaletteExtractor.rampFrom(
Swatch((v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF, 1.0));
}
/// A snapshot of every accent surface, and whether they agree.
///
/// Worth having because a half-applied theme is invisible from the outside: title
/// bars read DWM\AccentColor while Start and the menus read their own values, so
/// one failed write leaves the desktop in two colours with nothing to say so.
static ThemeState describe() {
final accent = currentAccentHex();
final start = _readDwordColour(_accentKey, 'StartColorMenu');
final menu = _readDwordColour(_accentKey, 'AccentColorMenu');
final ramp = currentRamp();
final inPalette = accent != null && (ramp?.any((s) => s.hex == accent) ?? false);
// Windows' convention, which apply() follows: StartColorMenu is palette entry 4
// and AccentColorMenu entry 3 - darker shades, NOT the accent itself. Checking
// them against the accent (as this used to) reports a mismatch on a theme that is
// in fact correct.
final startWant = (ramp != null && ramp.length == 8) ? ramp[4].hex : null;
final menuWant = (ramp != null && ramp.length == 8) ? ramp[3].hex : null;
final lines = <String>[
'accent (title bars) #${accent ?? '??????'}',
'Start menu #${start ?? '??????'}'
'${startWant == null || start == startWant ? '' : ' (expected #$startWant)'}',
'menus #${menu ?? '??????'}'
'${menuWant == null || menu == menuWant ? '' : ' (expected #$menuWant)'}',
'palette ${ramp == null ? '??' : ramp.map((s) => '#${s.hex}').join(' ')}',
'accent in palette ${inPalette ? 'yes' : 'NO'}',
'title bars coloured ${_readDword(_dwmKey, 'ColorPrevalence') == 1}',
'Start + taskbar ${_readDword(_personalizeKey, 'ColorPrevalence') == 1}',
'shell mode ${_readDword(_personalizeKey, 'SystemUsesLightTheme') == 1 ? 'light' : 'dark'}',
];
final consistent = accent != null &&
inPalette &&
(startWant == null || start == startWant) &&
(menuWant == null || menu == menuWant);
return ThemeState(lines: lines, consistent: consistent, accent: accent);
}
static int? _readDword(String key, String value) {
final r = _reg(['query', key, '/v', value]);
if (r.exitCode != 0) return null;
final m = RegExp('$value\\s+REG_DWORD\\s+0x([0-9a-fA-F]+)')
.firstMatch(r.stdout as String);
return m == null ? null : int.parse(m.group(1)!, radix: 16);
}
/// Reads an ABGR colour DWORD back as RRGGBB.
static String? _readDwordColour(String key, String value) {
final v = _readDword(key, value);
if (v == null) return null;
String h(int x) => x.toRadixString(16).padLeft(2, '0').toUpperCase();
return '${h(v & 0xFF)}${h((v >> 8) & 0xFF)}${h((v >> 16) & 0xFF)}';
}
/// Reads the current values so they can be restored later.
static Map<String, String> snapshot() {
final out = <String, String>{};
for (final entry in [
(_accentKey, 'AccentPalette'),
(_accentKey, 'AccentColorMenu'),
(_accentKey, 'StartColorMenu'),
(_dwmKey, 'AccentColor'),
(_dwmKey, 'ColorizationColor'),
]) {
final r = _reg(['query', entry.$1, '/v', entry.$2]);
final m = RegExp(r'\s+REG_\w+\s+(\S+)').firstMatch(r.stdout as String);
if (m != null) out['${entry.$1}|${entry.$2}'] = m.group(1)!;
}
return out;
}
/// Applies [palette] as the system accent. Returns what happened.
///
/// [alsoTitleBars] colours window title bars with the accent (DWM ColorPrevalence)
/// - on by default, because without a coloured surface the theme change is nearly
/// invisible, which reads as "it didn't apply".
/// [matchShellToAccent] keeps the taskbar/Start text legible by putting the shell
/// into the light or dark mode that suits the accent being applied. Turn it off to
/// leave the shell mode strictly alone.
/// [refreshShell] restarts Start and the notification centre so they pick the new
/// accent up immediately instead of at next sign-in. See [refreshShellHosts].
/// [snapToWindows] rounds the chosen accent to the nearest colour Windows itself
/// offers in Settings. OFF by default - Windows takes any colour, and rounding
/// silently replaces the one that was picked. See [windowsAccentColours].
static ThemeResult apply(Palette palette,
{bool alsoTitleBars = true,
bool matchShellToAccent = true,
bool refreshShell = true,
bool snapToWindows = false}) {
if (!supported) {
return ThemeResult(false, 'system accent theming is Windows-only');
}
// APPLY THE COLOUR THAT WAS ACTUALLY CHOSEN.
//
// A previous version ran the choice through accentSurface() first, to guarantee
// Windows would pair it with legible text. The effect was that clicking a swatch
// applied some *other* shade of the ramp - pick #86DAFA, get #6195A8 - so the
// picker simply did not do what it said. Legibility is handled further down
// instead, by matching the shell's light/dark to this colour: adapt the TEXT to
// the colour, never the colour to the text.
final picked = palette.accent;
final main = snapToWindows ? snapToWindowsAccent(picked) : picked;
final snapNote = (main.hex == picked.hex)
? ''
: ' (snapped from #${picked.hex} to the nearest Windows accent)';
// Windows draws different surfaces from different AccentPalette entries, so the
// applied colour has to appear in the palette too - otherwise Start and the
// taskbar drift to a shade that was never chosen.
//
// It has to sit in the RIGHT slot, and Windows' choice is fixed: counting the
// light -> dark array written below, entry 3 is the accent, and the entries around
// it are the shades UISettings hands out. Measured directly:
//
// entry 1 -> AccentLight2 entry 3 -> Accent entry 5 -> AccentDark2
// entry 2 -> AccentLight1 entry 4 -> AccentDark1
//
// Placing it by brightness instead (which is what this did) left it at entry 2 for
// a mid-tone accent, so every app reading UISettings::Accent - Firefox, UWP, Start,
// the notification centre - got the shade one step DARKER than the one chosen.
final ramp = List<Swatch>.from(
main.hex == picked.hex ? palette.ramp : PaletteExtractor.rampFrom(main));
const windowsAccentSlot = 3; // in the light -> dark array, so 8-1-3 here
ramp[ramp.length - 1 - windowsAccentSlot] = main;
// AccentPalette in the layout WINDOWS ITSELF USES. Established by diffing the
// registry before and after picking an accent in Settings:
//
// * ordered LIGHT -> DARK. We had been writing dark -> light, i.e. backwards,
// so every shade Windows looked up came out at the opposite lightness.
// * the alpha byte is 0x00, not 0xFF.
// * StartColorMenu is entry 4 - one step DARKER than the accent - while
// AccentColorMenu is entry 3, the accent itself.
//
// Getting this wrong is why Start and the notification centre ignored the theme
// while the taskbar (which Lucent paints directly) looked fine.
final light = ramp.reversed.toList(); // ramp is dark -> light; Windows wants the reverse
final bytes = Uint8List(32);
for (var i = 0; i < 8; i++) {
final s = light[i];
// R,G,B,A. The old B,G,R,A was "confirmed" against Windows' own #DCDEDF entry
// (stored DF DE DC 00) - but that is a grey, and a grey reads the same in both
// directions, so the test could not have failed. See _abgr().
bytes[i * 4 + 0] = s.r;
bytes[i * 4 + 1] = s.g;
bytes[i * 4 + 2] = s.b;
bytes[i * 4 + 3] = 0x00;
}
final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
// The menu shades Windows derives, taken from the same light->dark ordering.
final startShade = light[4];
final menuShade = light[3];
final steps = <ProcessResult>[
_reg(['add', _accentKey, '/v', 'AccentPalette', '/t', 'REG_BINARY', '/d', hex, '/f']),
_reg(['add', _accentKey, '/v', 'AccentColorMenu', '/t', 'REG_DWORD', '/d', _dword(_abgr(menuShade)), '/f']),
_reg(['add', _accentKey, '/v', 'StartColorMenu', '/t', 'REG_DWORD', '/d', _dword(_abgr(startShade)), '/f']),
_reg(['add', _dwmKey, '/v', 'AccentColor', '/t', 'REG_DWORD', '/d', _dword(_abgr(main)), '/f']),
_reg(['add', _dwmKey, '/v', 'ColorizationColor', '/t', 'REG_DWORD', '/d', _dword(_abgr(main, a: 0xC4)), '/f']),
// Turn off "automatically pick an accent colour from my background" or
// Windows will overwrite everything above on the next wallpaper change.
_reg(['add', _dwmKey, '/v', 'ColorizationAfterglow', '/t', 'REG_DWORD', '/d', _dword(_abgr(main, a: 0xC4)), '/f']),
_reg([
'add', r'HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize',
'/v', 'AutoColorization', '/t', 'REG_DWORD', '/d', '0', '/f'
]),
];
final failed = steps.where((r) => r.exitCode != 0).length;
if (failed > 0) {
return ThemeResult(false, '$failed of ${steps.length} registry writes failed',
ramp: ramp);
}
// THERE ARE TWO ColorPrevalence VALUES and they control different surfaces:
// DWM\ColorPrevalence -> title bars and window borders
// Personalize\ColorPrevalence -> "Show accent colour on Start and taskbar"
// Writing only the DWM one (as an earlier version did) tinted title bars while
// Start and the taskbar stayed default, which reads as "the theme didn't apply".
final prevalence = alsoTitleBars ? '1' : '0';
_reg(['add', _dwmKey, '/v', 'ColorPrevalence', '/t', 'REG_DWORD', '/d', prevalence, '/f']);
_reg(['add', _personalizeKey, '/v', 'ColorPrevalence', '/t', 'REG_DWORD',
'/d', prevalence, '/f']);
// The shell paints its own text (the clock, the date, Start's labels) from
// SystemUsesLightTheme - NOT from the accent. So once the taskbar is filled with
// the accent, the two have to agree or the text is unreadable: a dark accent with
// the shell in light mode gives dark-on-dark, which is exactly what "the date is
// still dark" was. Match the shell to the accent we just applied.
//
// Only the shell is touched; app windows (AppsUseLightTheme) are left alone, and
// an explicit light/dark choice applied afterwards still wins.
var shellNote = '';
if (alsoTitleBars && matchShellToAccent) {
final wantsLightShell = !winUsesWhiteText(main);
_reg(['add', _personalizeKey, '/v', 'SystemUsesLightTheme', '/t', 'REG_DWORD',
'/d', wantsLightShell ? '1' : '0', '/f']);
shellNote = ', ${wantsLightShell ? 'light' : 'dark'} shell for legible text';
}
// Read the accent back and, if it did not stick, write it again.
//
// Every value here goes through reg.exe, and a dozen of those are spawned in
// quick succession. In practice one can fail to land - it was caught happening to
// DWM\AccentColor while the Explorer\Accent values all wrote fine, which left
// title bars on the previous colour while Start and the taskbar showed the new
// one. Verifying beats hoping, and turns a silent mismatch into either a fixed
// result or an honest error.
var verified = currentAccentHex() == main.hex;
if (!verified) {
_reg(['add', _dwmKey, '/v', 'AccentColor', '/t', 'REG_DWORD',
'/d', _dword(_abgr(main)), '/f']);
_reg(['add', _dwmKey, '/v', 'ColorizationColor', '/t', 'REG_DWORD',
'/d', _dword(_abgr(main, a: 0xC4)), '/f']);
verified = currentAccentHex() == main.hex;
}
// THE step that actually repaints: hand the colour to DWM. The registry alone
// only takes effect at next sign-in.
final pushed = pushToDwm(main);
// Still broadcast: this is what tells already-running apps to re-read.
_broadcastColourChange();
// Start and the notification centre cache the accent at launch and ignore the
// broadcast, so without this they keep showing the previous colour.
if (alsoTitleBars && refreshShell) refreshShellHosts();
if (!verified) {
return ThemeResult(
false,
'Windows did not keep accent #${main.hex} - it still reports '
'#${currentAccentHex() ?? 'unknown'}. Try applying again.',
ramp: ramp,
);
}
return ThemeResult(
true,
'accent #${main.hex} applied$snapNote (ramp #${ramp.first.hex} -> #${ramp.last.hex})'
'$shellNote'
'${pushed ? '' : ' - NOTE: could not reach DWM (LucentAgent.exe missing), so '
'title bars will only change at next sign-in'}'
'${_needsSignOutNote()}',
ramp: ramp,
);
}
/// Title bars and accent highlights update live via the broadcast; a few apps
/// cache their colours until restarted.
static String _needsSignOutNote() =>
'. Title bars update immediately; a few apps re-read on restart.';
/// Restores a snapshot taken earlier.
static ThemeResult restore(Map<String, String> snap) {
if (!supported) return const ThemeResult(false, 'Windows-only');
var ok = 0;
snap.forEach((k, v) {
final parts = k.split('|');
final type = parts[1] == 'AccentPalette' ? 'REG_BINARY' : 'REG_DWORD';
final val = type == 'REG_BINARY' ? v : _dword(int.parse(v.replaceFirst('0x', ''), radix: 16));
if (_reg(['add', parts[0], '/v', parts[1], '/t', type, '/d', val, '/f']).exitCode == 0) ok++;
});
_broadcastColourChange(); // apply the restore live too
return ThemeResult(ok > 0, 'restored $ok value(s)');
}
}