stipple 0.0.4

Stipple: a cross-platform, self-drawn UI toolkit in Rust.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
//! A native Windows backend over raw Win32 FFI (`user32`/`gdi32`/`kernel32`).
//!
//! No `windows`/`winapi` crate — direct `extern "system"` declarations, so the
//! only "dependency" is the OS itself (the workspace policy in `ROADMAP.md`
//! §1). This module is the one place `unsafe` is permitted in the crate.
//!
//! Scope (v1): register a window class, create + show a top-level window, and
//! present the software [`Pixmap`] by blitting a top-down 32-bit DIB with
//! `StretchDIBits` on `WM_PAINT`. Input: mouse buttons, motion and the wheel
//! (`WM_MOUSEWHEEL`/`WM_MOUSEHWHEEL`), keys with their modifiers (`GetKeyState`)
//! and typed text from `WM_CHAR`.
//!
//! **Verification:** build-checked on the `windows-latest` CI runner via the
//! workspace build matrix; runtime-screenshotted by the Visual workflow's
//! Windows job.
#![allow(unsafe_code)]

use std::cell::RefCell;
use std::ffi::c_void;

use crate::geometry::{PhysicalSize, ScaleFactor, Size};
use crate::platform::ControlFlow;
use crate::platform::error::PlatformError;
use crate::platform::event::{ButtonState, Event, KeyCode, Modifiers, PointerButton, WindowId};
use crate::platform::input;
use crate::platform::menu::{MenuPopup, NativeMenu, NativeMenuBar, NativeMenuItem, NativeTray};
use crate::platform::window::{CursorIcon, Window, WindowAttributes, fit_icon};
use crate::render::{Pixmap, Surface};

/// Receiving drops (OLE `IDropTarget`, `WM_DROPFILES`).
mod dnd;
mod ime;
/// The notification-area icon and notification balloons.
mod tray;
/// Pacing animation frames by the compositor (`DwmFlush`).
mod vsync;

pub(crate) use tray::notify;

// ---- Win32 type aliases -----------------------------------------------------

type Handle = *mut c_void;
type Hwnd = Handle;
type Wparam = usize;
type Lparam = isize;
type Lresult = isize;
type WndProc = unsafe extern "system" fn(Hwnd, u32, Wparam, Lparam) -> Lresult;

const WS_OVERLAPPEDWINDOW: u32 = 0x00CF_0000;
const CW_USEDEFAULT: i32 = -2147483648; // 0x80000000
const SW_SHOW: i32 = 5;
const SW_MAXIMIZE: i32 = 3;
const SW_RESTORE: i32 = 9;
const WM_SETCURSOR: u32 = 0x0020;
const WM_GETMINMAXINFO: u32 = 0x0024;
const WM_SETICON: u32 = 0x0080;
/// `WM_SETCURSOR`'s hit-test code for the client area.
const HTCLIENT: u16 = 1;
const ICON_SMALL: usize = 0;
const ICON_BIG: usize = 1;
const GWL_STYLE: i32 = -16;
const SWP_NOMOVE: u32 = 0x0002;
const SWP_FRAMECHANGED: u32 = 0x0020;
const SWP_NOOWNERZORDER: u32 = 0x0200;
const MONITOR_DEFAULTTONEAREST: u32 = 2;
const WM_DESTROY: u32 = 0x0002;
const WM_SIZE: u32 = 0x0005;
const WM_PAINT: u32 = 0x000F;
const WM_CLOSE: u32 = 0x0010;
const WM_KEYDOWN: u32 = 0x0100;
const WM_KEYUP: u32 = 0x0101;
const WM_CHAR: u32 = 0x0102;
/// F10 and keys pressed with Alt arrive as "system" keys.
const WM_SYSKEYDOWN: u32 = 0x0104;
const WM_SYSKEYUP: u32 = 0x0105;
const WM_MOUSEWHEEL: u32 = 0x020A;
const WM_MOUSEHWHEEL: u32 = 0x020E;
const WM_MOUSEMOVE: u32 = 0x0200;
const WM_LBUTTONDOWN: u32 = 0x0201;
const WM_LBUTTONUP: u32 = 0x0202;
const WM_RBUTTONDOWN: u32 = 0x0204;
const WM_RBUTTONUP: u32 = 0x0205;
const WM_MBUTTONDOWN: u32 = 0x0207;
const WM_MBUTTONUP: u32 = 0x0208;
const WM_GETOBJECT: u32 = 0x003D;
const WM_SETTINGCHANGE: u32 = 0x001A;
const WM_THEMECHANGED: u32 = 0x031A;
const WM_DWMCOLORIZATIONCOLORCHANGED: u32 = 0x0320;
const WM_DPICHANGED: u32 = 0x02E0;
const WM_QUIT: u32 = 0x0012;
/// A menu item was picked (`HIWORD(wParam)` 0, `lParam` 0 for menus).
const WM_COMMAND: u32 = 0x0111;
const MF_STRING: u32 = 0x0000;
const MF_GRAYED: u32 = 0x0001;
const MF_CHECKED: u32 = 0x0008;
const MF_POPUP: u32 = 0x0010;
const MF_SEPARATOR: u32 = 0x0800;
/// `TrackPopupMenuEx`: return the picked id (0 for none) instead of posting
/// `WM_COMMAND`, and send no `WM_INITMENU*`/`WM_MENUSELECT` notifications.
const TPM_RETURNCMD: u32 = 0x0100;
const TPM_NONOTIFY: u32 = 0x0080;
const WM_NULL: u32 = 0x0000;
/// Posted by [`crate::platform::wake`] to end the message wait.
const WM_APP_WAKE: u32 = 0x8000 + 1;
const PM_REMOVE: u32 = 0x0001;
const QS_ALLINPUT: u32 = 0x04FF;
/// Also return for input already in the queue but not yet looked at.
const MWMO_INPUTAVAILABLE: u32 = 0x0004;
const INFINITE: u32 = u32::MAX;
const SWP_NOZORDER: u32 = 0x0004;
const SWP_NOACTIVATE: u32 = 0x0010;
const SWP_NOSIZE: u32 = 0x0001;
/// `DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2`.
const PER_MONITOR_AWARE_V2: isize = -4;
/// `lParam` value identifying UIA's request for our root fragment provider.
const UIA_ROOT_OBJECT_ID: i32 = -25;

const VK_SHIFT: i32 = 0x10;
const VK_CONTROL: i32 = 0x11;
const VK_MENU: i32 = 0x12;
const VK_LWIN: i32 = 0x5B;
const VK_RWIN: i32 = 0x5C;
const BI_RGB: u32 = 0;
const DIB_RGB_COLORS: u32 = 0;
const SRCCOPY: u32 = 0x00CC_0020;
const IDC_ARROW: usize = 32512;

/// The system cursor (`IDC_*` resource id) for each [`CursorIcon`]. Windows
/// has no grab cursors; the hand and the four-way arrow stand in.
fn cursor_id(icon: CursorIcon) -> usize {
    match icon {
        CursorIcon::Default => IDC_ARROW,
        CursorIcon::Text => 32513,                        // IDC_IBEAM
        CursorIcon::Crosshair => 32515,                   // IDC_CROSS
        CursorIcon::NwseResize => 32642,                  // IDC_SIZENWSE
        CursorIcon::NeswResize => 32643,                  // IDC_SIZENESW
        CursorIcon::EwResize => 32644,                    // IDC_SIZEWE
        CursorIcon::NsResize => 32645,                    // IDC_SIZENS
        CursorIcon::Move | CursorIcon::Grabbing => 32646, // IDC_SIZEALL
        CursorIcon::NotAllowed => 32648,                  // IDC_NO
        CursorIcon::Pointer | CursorIcon::Grab => 32649,  // IDC_HAND
    }
}

#[repr(C)]
struct WndClassW {
    style: u32,
    lpfn_wnd_proc: Option<WndProc>,
    cb_cls_extra: i32,
    cb_wnd_extra: i32,
    h_instance: Handle,
    h_icon: Handle,
    h_cursor: Handle,
    hbr_background: Handle,
    lpsz_menu_name: *const u16,
    lpsz_class_name: *const u16,
}

#[repr(C)]
struct Point {
    x: i32,
    y: i32,
}

#[repr(C)]
struct Msg {
    hwnd: Hwnd,
    message: u32,
    w_param: Wparam,
    l_param: Lparam,
    time: u32,
    pt: Point,
    private: u32,
}

#[repr(C)]
struct Rect {
    left: i32,
    top: i32,
    right: i32,
    bottom: i32,
}

/// `MINMAXINFO`, filled in on `WM_GETMINMAXINFO`.
#[repr(C)]
struct MinMaxInfo {
    reserved: Point,
    max_size: Point,
    max_position: Point,
    min_track_size: Point,
    max_track_size: Point,
}

/// `MONITORINFO`.
#[repr(C)]
struct MonitorInfo {
    cb_size: u32,
    rc_monitor: Rect,
    rc_work: Rect,
    flags: u32,
}

#[repr(C)]
struct PaintStruct {
    hdc: Handle,
    f_erase: i32,
    rc_paint: Rect,
    f_restore: i32,
    f_inc_update: i32,
    rgb_reserved: [u8; 32],
}

#[repr(C)]
struct BitmapInfoHeader {
    bi_size: u32,
    bi_width: i32,
    bi_height: i32,
    bi_planes: u16,
    bi_bit_count: u16,
    bi_compression: u32,
    bi_size_image: u32,
    bi_x_pels_per_meter: i32,
    bi_y_pels_per_meter: i32,
    bi_clr_used: u32,
    bi_clr_important: u32,
}

#[repr(C)]
struct BitmapInfo {
    header: BitmapInfoHeader,
    colors: [u32; 1],
}

#[link(name = "kernel32")]
unsafe extern "system" {
    fn GetModuleHandleW(name: *const u16) -> Handle;
}

#[link(name = "uiautomationcore")]
unsafe extern "system" {
    /// Package a UIA provider as the `WM_GETOBJECT` reply (handles the COM
    /// marshalling and `AddRef`), returning the `LRESULT` to pass back.
    fn UiaReturnRawElementProvider(hwnd: Hwnd, wp: Wparam, lp: Lparam, el: *mut c_void) -> Lresult;
}

const DWMWA_USE_IMMERSIVE_DARK_MODE: u32 = 20;

#[link(name = "dwmapi")]
unsafe extern "system" {
    fn DwmSetWindowAttribute(hwnd: Hwnd, attr: u32, value: *const c_void, size: u32) -> i32;
}

#[link(name = "user32")]
unsafe extern "system" {
    fn RegisterClassW(class: *const WndClassW) -> u16;
    fn LoadCursorW(instance: Handle, name: usize) -> Handle;
    #[allow(clippy::too_many_arguments)]
    fn CreateWindowExW(
        ex_style: u32,
        class_name: *const u16,
        window_name: *const u16,
        style: u32,
        x: i32,
        y: i32,
        w: i32,
        h: i32,
        parent: Hwnd,
        menu: Handle,
        instance: Handle,
        param: *mut c_void,
    ) -> Hwnd;
    fn SetProcessDpiAwarenessContext(context: isize) -> i32;
    fn GetDpiForSystem() -> u32;
    fn GetDpiForWindow(hwnd: Hwnd) -> u32;
    fn SetWindowPos(hwnd: Hwnd, after: Hwnd, x: i32, y: i32, w: i32, h: i32, flags: u32) -> i32;
    fn ShowWindow(hwnd: Hwnd, cmd: i32) -> i32;
    fn UpdateWindow(hwnd: Hwnd) -> i32;
    fn DefWindowProcW(hwnd: Hwnd, msg: u32, wp: Wparam, lp: Lparam) -> Lresult;
    fn PeekMessageW(msg: *mut Msg, hwnd: Hwnd, min: u32, max: u32, remove: u32) -> i32;
    fn PostMessageW(hwnd: Hwnd, msg: u32, wp: Wparam, lp: Lparam) -> i32;
    fn MsgWaitForMultipleObjectsEx(
        count: u32,
        handles: *const Handle,
        timeout_ms: u32,
        wake_mask: u32,
        flags: u32,
    ) -> u32;
    fn TranslateMessage(msg: *const Msg) -> i32;
    fn DispatchMessageW(msg: *const Msg) -> Lresult;
    fn PostQuitMessage(code: i32);
    fn DestroyWindow(hwnd: Hwnd) -> i32;
    fn GetClientRect(hwnd: Hwnd, rect: *mut Rect) -> i32;
    fn InvalidateRect(hwnd: Hwnd, rect: *const Rect, erase: i32) -> i32;
    fn BeginPaint(hwnd: Hwnd, ps: *mut PaintStruct) -> Handle;
    fn EndPaint(hwnd: Hwnd, ps: *const PaintStruct) -> i32;
    fn GetKeyState(vk: i32) -> i16;
    fn SetCapture(hwnd: Hwnd) -> Hwnd;
    fn ReleaseCapture() -> i32;
    fn SetCursor(cursor: Handle) -> Handle;
    fn SendMessageW(hwnd: Hwnd, msg: u32, wp: Wparam, lp: Lparam) -> Lresult;
    fn CreateIcon(
        instance: Handle,
        width: i32,
        height: i32,
        planes: u8,
        bits_per_pixel: u8,
        and_bits: *const u8,
        xor_bits: *const u8,
    ) -> Handle;
    fn DestroyIcon(icon: Handle) -> i32;
    fn GetWindowLongW(hwnd: Hwnd, index: i32) -> i32;
    fn SetWindowLongW(hwnd: Hwnd, index: i32, value: i32) -> i32;
    fn GetWindowRect(hwnd: Hwnd, rect: *mut Rect) -> i32;
    fn CreateMenu() -> Handle;
    fn CreatePopupMenu() -> Handle;
    fn AppendMenuW(menu: Handle, flags: u32, id: usize, text: *const u16) -> i32;
    fn SetMenu(hwnd: Hwnd, menu: Handle) -> i32;
    fn DestroyMenu(menu: Handle) -> i32;
    fn DrawMenuBar(hwnd: Hwnd) -> i32;
    fn TrackPopupMenuEx(
        menu: Handle,
        flags: u32,
        x: i32,
        y: i32,
        hwnd: Hwnd,
        params: *const c_void,
    ) -> i32;
    fn ClientToScreen(hwnd: Hwnd, point: *mut Point) -> i32;
    fn SetForegroundWindow(hwnd: Hwnd) -> i32;
    fn MonitorFromWindow(hwnd: Hwnd, flags: u32) -> Handle;
    fn GetMonitorInfoW(monitor: Handle, info: *mut MonitorInfo) -> i32;
    fn AdjustWindowRectExForDpi(
        rect: *mut Rect,
        style: u32,
        menu: i32,
        ex_style: u32,
        dpi: u32,
    ) -> i32;
}

#[link(name = "gdi32")]
unsafe extern "system" {
    #[allow(clippy::too_many_arguments)]
    fn StretchDIBits(
        hdc: Handle,
        x_dest: i32,
        y_dest: i32,
        w_dest: i32,
        h_dest: i32,
        x_src: i32,
        y_src: i32,
        w_src: i32,
        h_src: i32,
        bits: *const c_void,
        bmi: *const BitmapInfo,
        usage: u32,
        rop: u32,
    ) -> i32;
}

/// Per-thread window state shared between the message loop, the [`WndProc`]
/// (which blits on `WM_PAINT`), and the [`Surface`] (which updates the buffer).
#[derive(Default)]
struct WinCtx {
    /// Top-down BGRA framebuffer for the current frame.
    fb: Vec<u8>,
    fb_w: i32,
    fb_h: i32,
    /// Events pushed by the [`WndProc`], drained by the message loop.
    queue: Vec<Event>,
    /// The current UIA provider tree, vended from `WM_GETOBJECT`. Rebuilt each
    /// time the App pushes a new accessibility tree.
    uia: Option<crate::platform::uia::UiaTree>,
    /// The window's DPI. 0 until the window exists, which reads as 96 (1x).
    dpi: u32,
    /// The cursor shown over the client area (`WM_SETCURSOR`).
    cursor: CursorIcon,
    /// Inner size limits in logical pixels, applied on `WM_GETMINMAXINFO`.
    min_size: Option<Size>,
    max_size: Option<Size>,
    /// While fullscreen: the style and window rectangle to restore.
    restore: Option<(i32, [i32; 4])>,
    /// The `HICON` set with `WM_SETICON`, destroyed when replaced.
    icon: usize,
    /// While a text field has focus: its caret, in client physical pixels,
    /// where the IME's windows go. `None` while the IME is off.
    ime_area: Option<Rect>,
    /// Pairs up `WM_CHAR`'s surrogates.
    utf16: input::Utf16Joiner,
    /// The window's menu bar (`HMENU`), destroyed when replaced.
    menu: usize,
    /// The tray icon's menu and icon.
    tray: tray::TrayState,
    /// Whether the app takes the drag over the window (its last
    /// `set_drop_accepted`), and where the drag last was.
    drop_accepted: bool,
    drag_last: Option<crate::geometry::Point>,
    /// A drag out of the app the app started with `Window::start_drag`, for
    /// the message loop to run (see `dnd::drag_out`).
    drag_out: Option<crate::platform::DropData>,
}

/// Physical pixels per logical pixel for the window's current display.
fn current_scale() -> f64 {
    CTX.with(|c| match c.borrow().dpi {
        0 => 1.0,
        dpi => dpi as f64 / 96.0,
    })
}

fn push_event(ev: Event) {
    CTX.with(|c| c.borrow_mut().queue.push(ev));
}

/// Extract the signed `(x, y)` from a mouse-message `lParam` (LOWORD/HIWORD).
/// Returns a Stipple logical-pixel point (distinct from the local Win32 `Point`).
fn mouse_xy(lp: Lparam) -> crate::geometry::Point {
    let x = (lp & 0xffff) as u16 as i16 as f64;
    let y = ((lp >> 16) & 0xffff) as u16 as i16 as f64;
    // Windows reports physical pixels under per-monitor DPI awareness.
    let scale = current_scale();
    crate::geometry::Point::new(x / scale, y / scale)
}

/// The modifier keys held when the message being handled was posted
/// (`GetKeyState` follows the message queue, not the live keyboard).
fn modifiers() -> Modifiers {
    // The high bit (a negative SHORT) means the key is down.
    let down = |vk| unsafe { GetKeyState(vk) } < 0;
    Modifiers {
        shift: down(VK_SHIFT),
        ctrl: down(VK_CONTROL),
        alt: down(VK_MENU),
        meta: down(VK_LWIN) || down(VK_RWIN),
    }
}

/// The key event for a `WM_(SYS)KEYDOWN`/`UP`: a named key, or — with Ctrl,
/// Alt or the Windows key held — a letter/digit shortcut such as Ctrl+C, whose
/// `WM_CHAR` is only a control code (Alt+F arrives as `WM_SYSCHAR`). Ctrl+Alt
/// is AltGr, which types text.
fn key_event(vk: usize, state: ButtonState) -> Option<Event> {
    let modifiers = modifiers();
    let shortcut = modifiers.ctrl != modifiers.alt || modifiers.meta;
    let code = input::win32_vk(vk).or_else(|| {
        shortcut
            .then(|| input::win32_shortcut_char(vk, modifiers.shift))
            .flatten()
            .map(KeyCode::Char)
    })?;
    Some(Event::Key {
        code,
        state,
        modifiers,
    })
}

thread_local! {
    static CTX: RefCell<WinCtx> = RefCell::new(WinCtx::default());
}

fn wide(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}

/// Append `items` to the menu `menu`: `&` mnemonics pass through, and a
/// shortcut shows right-aligned after a tab.
fn fill_menu(menu: Handle, items: &[NativeMenuItem]) {
    for item in items {
        match item {
            NativeMenuItem::Action {
                id,
                label,
                shortcut,
                enabled,
                checked,
            } => {
                let mut text = label.clone();
                if let Some(s) = shortcut {
                    text.push('\t');
                    text.push_str(&s.label_for(false));
                }
                let mut flags = MF_STRING;
                if !enabled {
                    flags |= MF_GRAYED;
                }
                if *checked == Some(true) {
                    flags |= MF_CHECKED;
                }
                let text = wide(&text);
                unsafe { AppendMenuW(menu, flags, *id as usize, text.as_ptr()) };
            }
            NativeMenuItem::Separator => unsafe {
                AppendMenuW(menu, MF_SEPARATOR, 0, std::ptr::null());
            },
            NativeMenuItem::Submenu(sub) => {
                let popup = unsafe { CreatePopupMenu() };
                fill_menu(popup, &sub.items);
                let text = wide(&sub.label);
                unsafe { AppendMenuW(menu, MF_POPUP, popup as usize, text.as_ptr()) };
            }
        }
    }
}

/// Show `menu` as a context menu at `at` (logical client coordinates) and
/// wait for it to close. `TrackPopupMenuEx` runs its own modal loop; the
/// window keeps painting meanwhile, and input it gets is queued as usual.
fn popup_menu(hwnd: Hwnd, menu: &NativeMenu, at: crate::geometry::Point) -> MenuPopup {
    let popup = unsafe { CreatePopupMenu() };
    if popup.is_null() {
        return MenuPopup::Unsupported;
    }
    fill_menu(popup, &menu.items);
    let scale = current_scale();
    let mut p = Point {
        x: (at.x * scale).round() as i32,
        y: (at.y * scale).round() as i32,
    };
    let picked = unsafe {
        ClientToScreen(hwnd, &mut p);
        // The menu only closes on a click elsewhere if its owner is the
        // foreground window, and needs a message after it to settle (see
        // `TrackPopupMenu`'s remarks).
        SetForegroundWindow(hwnd);
        let id = TrackPopupMenuEx(
            popup,
            TPM_RETURNCMD | TPM_NONOTIFY,
            p.x,
            p.y,
            hwnd,
            std::ptr::null(),
        );
        PostMessageW(hwnd, WM_NULL, 0, 0);
        DestroyMenu(popup);
        id
    };
    if picked > 0 {
        MenuPopup::Picked(picked as u32)
    } else {
        MenuPopup::Dismissed
    }
}

/// Give `hwnd` a menu bar for `bar`, replacing the previous one. The first one
/// grows the window by the bar's height, so the client area keeps its size.
fn set_menu_bar(hwnd: Hwnd, bar: &NativeMenuBar) {
    let menu = unsafe { CreateMenu() };
    for m in &bar.menus {
        let popup = unsafe { CreatePopupMenu() };
        fill_menu(popup, &m.items);
        let text = wide(&m.label);
        unsafe { AppendMenuW(menu, MF_POPUP, popup as usize, text.as_ptr()) };
    }
    let client = |hwnd| {
        let mut r = Rect {
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
        };
        unsafe { GetClientRect(hwnd, &mut r) };
        r.bottom - r.top
    };
    let before = client(hwnd);
    unsafe { SetMenu(hwnd, menu) };
    let old = CTX.with(|c| std::mem::replace(&mut c.borrow_mut().menu, menu as usize));
    if old != 0 {
        // Destroys its submenus too.
        unsafe { DestroyMenu(old as Handle) };
    } else {
        let lost = before - client(hwnd);
        let mut w = Rect {
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
        };
        if lost > 0 && unsafe { GetWindowRect(hwnd, &mut w) } != 0 {
            unsafe {
                SetWindowPos(
                    hwnd,
                    std::ptr::null_mut(),
                    0,
                    0,
                    w.right - w.left,
                    w.bottom - w.top + lost,
                    SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,
                )
            };
        }
    }
    unsafe { DrawMenuBar(hwnd) };
}

/// Whether a `WM_SETTINGCHANGE` `lParam` (a NUL-terminated UTF-16 string, or
/// null) is `name`.
///
/// # Safety
/// `lp` must be null or point to a NUL-terminated UTF-16 string.
unsafe fn names_setting(lp: Lparam, name: &str) -> bool {
    let p = lp as *const u16;
    if p.is_null() {
        return false;
    }
    let mut want = name.encode_utf16();
    let mut i = 0;
    loop {
        let c = unsafe { *p.add(i) };
        match want.next() {
            Some(w) if w == c => i += 1,
            Some(_) => return false,
            None => return c == 0,
        }
    }
}

/// Ask the desktop window manager for a dark or light title bar.
fn set_dark_title(hwnd: Hwnd, dark: bool) {
    let value = dark as i32;
    unsafe {
        DwmSetWindowAttribute(
            hwnd,
            DWMWA_USE_IMMERSIVE_DARK_MODE,
            &value as *const i32 as *const c_void,
            4,
        );
    }
}

/// The window size (frame included) for an inner size in logical pixels, at
/// the window's DPI and with its current style.
fn outer_size(hwnd: Hwnd, size: Size) -> Point {
    let dpi = match unsafe { GetDpiForWindow(hwnd) } {
        0 => 96,
        dpi => dpi,
    };
    let inner = ScaleFactor::new(dpi as f64 / 96.0).to_physical(size);
    let mut r = Rect {
        left: 0,
        top: 0,
        right: inner.width as i32,
        bottom: inner.height as i32,
    };
    let style = unsafe { GetWindowLongW(hwnd, GWL_STYLE) } as u32;
    unsafe { AdjustWindowRectExForDpi(&mut r, style, 0, 0, dpi) };
    Point {
        x: r.right - r.left,
        y: r.bottom - r.top,
    }
}

/// Re-apply the size limits by "resizing" to the current size: Windows clamps
/// the new size through `WM_GETMINMAXINFO`.
fn reapply_limits(hwnd: Hwnd) {
    let mut r = Rect {
        left: 0,
        top: 0,
        right: 0,
        bottom: 0,
    };
    unsafe {
        GetWindowRect(hwnd, &mut r);
        SetWindowPos(
            hwnd,
            std::ptr::null_mut(),
            0,
            0,
            r.right - r.left,
            r.bottom - r.top,
            SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,
        );
    }
}

/// Make the window borderless and cover its monitor, or put back the style and
/// rectangle it had before.
fn set_fullscreen(hwnd: Hwnd, fullscreen: bool) {
    let saved = CTX.with(|c| c.borrow().restore);
    match (fullscreen, saved) {
        (true, None) => {
            let style = unsafe { GetWindowLongW(hwnd, GWL_STYLE) };
            let mut r = Rect {
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
            };
            let mut info = MonitorInfo {
                cb_size: core::mem::size_of::<MonitorInfo>() as u32,
                rc_monitor: Rect {
                    left: 0,
                    top: 0,
                    right: 0,
                    bottom: 0,
                },
                rc_work: Rect {
                    left: 0,
                    top: 0,
                    right: 0,
                    bottom: 0,
                },
                flags: 0,
            };
            let monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) };
            if unsafe { GetWindowRect(hwnd, &mut r) } == 0
                || unsafe { GetMonitorInfoW(monitor, &mut info) } == 0
            {
                return;
            }
            CTX.with(|c| {
                c.borrow_mut().restore = Some((style, [r.left, r.top, r.right, r.bottom]));
            });
            let m = info.rc_monitor;
            unsafe {
                SetWindowLongW(hwnd, GWL_STYLE, style & !(WS_OVERLAPPEDWINDOW as i32));
                SetWindowPos(
                    hwnd,
                    std::ptr::null_mut(), // HWND_TOP
                    m.left,
                    m.top,
                    m.right - m.left,
                    m.bottom - m.top,
                    SWP_NOOWNERZORDER | SWP_FRAMECHANGED,
                );
            }
        }
        (false, Some((style, [left, top, right, bottom]))) => {
            CTX.with(|c| c.borrow_mut().restore = None);
            unsafe {
                SetWindowLongW(hwnd, GWL_STYLE, style);
                SetWindowPos(
                    hwnd,
                    std::ptr::null_mut(),
                    left,
                    top,
                    right - left,
                    bottom - top,
                    SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED,
                );
            }
        }
        _ => {}
    }
}

/// An `HICON` from a straight-alpha RGBA image: 32-bit BGRA color bits, rows
/// top first, plus a 1-bit AND mask (set where fully transparent) with rows
/// padded to 16 bits.
fn create_icon(icon: &crate::render::Pixmap) -> Handle {
    let icon = fit_icon(icon, 256);
    let size = icon.size();
    let (w, h) = (size.width as usize, size.height as usize);
    let (bgra, mask) = icon_bits(icon.as_bytes(), w, h);
    unsafe {
        CreateIcon(
            GetModuleHandleW(std::ptr::null()),
            w as i32,
            h as i32,
            1,
            32,
            mask.as_ptr(),
            bgra.as_ptr(),
        )
    }
}

/// The color (BGRA) and AND-mask bytes for [`create_icon`].
fn icon_bits(rgba: &[u8], w: usize, h: usize) -> (Vec<u8>, Vec<u8>) {
    let stride = w.div_ceil(16) * 2;
    let mut mask = vec![0u8; stride * h];
    let mut bgra = Vec::with_capacity(rgba.len());
    for (i, p) in rgba.as_chunks::<4>().0.iter().enumerate() {
        bgra.extend_from_slice(&[p[2], p[1], p[0], p[3]]);
        if p[3] == 0 {
            let (x, y) = (i % w, i / w);
            mask[y * stride + x / 8] |= 0x80 >> (x % 8);
        }
    }
    (bgra, mask)
}

unsafe extern "system" fn wnd_proc(hwnd: Hwnd, msg: u32, wp: Wparam, lp: Lparam) -> Lresult {
    if tray::taskbar_created(hwnd, msg) {
        return 0;
    }
    match msg {
        WM_SETCURSOR if (lp & 0xffff) as u16 == HTCLIENT => {
            let id = CTX.with(|c| cursor_id(c.borrow().cursor));
            unsafe { SetCursor(LoadCursorW(std::ptr::null_mut(), id)) };
            1
        }
        WM_GETMINMAXINFO => {
            let (min, max, fullscreen) = CTX.with(|c| {
                let c = c.borrow();
                (c.min_size, c.max_size, c.restore.is_some())
            });
            let info = unsafe { &mut *(lp as *mut MinMaxInfo) };
            if let Some(min) = min {
                info.min_track_size = outer_size(hwnd, min);
            }
            // A fullscreen window covers the monitor whatever its maximum.
            if let Some(max) = max.filter(|_| !fullscreen) {
                info.max_track_size = outer_size(hwnd, max);
                info.max_size = outer_size(hwnd, max);
            }
            0
        }
        WM_PAINT => {
            let mut ps: PaintStruct = unsafe { std::mem::zeroed() };
            let hdc = unsafe { BeginPaint(hwnd, &mut ps) };
            CTX.with(|c| {
                let c = c.borrow();
                if !c.fb.is_empty() {
                    let bmi = BitmapInfo {
                        header: BitmapInfoHeader {
                            bi_size: core::mem::size_of::<BitmapInfoHeader>() as u32,
                            bi_width: c.fb_w,
                            // Negative height => top-down DIB (row 0 is the top).
                            bi_height: -c.fb_h,
                            bi_planes: 1,
                            bi_bit_count: 32,
                            bi_compression: BI_RGB,
                            bi_size_image: 0,
                            bi_x_pels_per_meter: 0,
                            bi_y_pels_per_meter: 0,
                            bi_clr_used: 0,
                            bi_clr_important: 0,
                        },
                        colors: [0],
                    };
                    unsafe {
                        StretchDIBits(
                            hdc,
                            0,
                            0,
                            c.fb_w,
                            c.fb_h,
                            0,
                            0,
                            c.fb_w,
                            c.fb_h,
                            c.fb.as_ptr() as *const c_void,
                            &bmi,
                            DIB_RGB_COLORS,
                            SRCCOPY,
                        );
                    }
                }
            });
            unsafe { EndPaint(hwnd, &ps) };
            0
        }
        WM_SIZE => {
            // lParam LOWORD/HIWORD = new client width/height.
            let w = (lp & 0xffff) as u32;
            let h = ((lp >> 16) & 0xffff) as u32;
            if w > 0 && h > 0 {
                push_event(Event::Resized(PhysicalSize::new(w, h)));
            }
            0
        }
        WM_DPICHANGED => {
            // wParam's low word is the new DPI; lParam is the suggested window
            // rectangle. Moving there sends the WM_SIZE that re-renders.
            let dpi = (wp & 0xffff) as u32;
            CTX.with(|c| c.borrow_mut().dpi = dpi);
            let r = unsafe { &*(lp as *const Rect) };
            unsafe {
                SetWindowPos(
                    hwnd,
                    std::ptr::null_mut(),
                    r.left,
                    r.top,
                    r.right - r.left,
                    r.bottom - r.top,
                    SWP_NOZORDER | SWP_NOACTIVATE,
                );
            }
            0
        }
        WM_MOUSEMOVE => {
            push_event(Event::PointerMoved {
                position: mouse_xy(lp),
            });
            0
        }
        WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN | WM_LBUTTONUP | WM_RBUTTONUP
        | WM_MBUTTONUP => {
            let button = match msg {
                WM_LBUTTONDOWN | WM_LBUTTONUP => PointerButton::Left,
                WM_RBUTTONDOWN | WM_RBUTTONUP => PointerButton::Right,
                _ => PointerButton::Middle,
            };
            let state = match msg {
                WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => ButtonState::Pressed,
                _ => ButtonState::Released,
            };
            crate::platform::set_pointer_modifiers(modifiers());
            // Keep the moves coming while the left button is down, even
            // outside the window: drags (and drags out of the app) need them.
            match msg {
                WM_LBUTTONDOWN => unsafe {
                    SetCapture(hwnd);
                },
                WM_LBUTTONUP => unsafe {
                    ReleaseCapture();
                },
                _ => {}
            }
            push_event(Event::PointerButton {
                button,
                state,
                position: mouse_xy(lp),
            });
            0
        }
        WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
            // The pointer position (in screen coordinates here) isn't needed:
            // the app scrolls whatever is under the last `WM_MOUSEMOVE`.
            push_event(Event::Scroll {
                delta: input::win32_wheel(wp, msg == WM_MOUSEHWHEEL),
            });
            0
        }
        WM_KEYDOWN | WM_KEYUP => {
            let state = if msg == WM_KEYDOWN {
                ButtonState::Pressed
            } else {
                ButtonState::Released
            };
            if let Some(ev) = key_event(wp, state) {
                push_event(ev);
            }
            0
        }
        WM_SYSKEYDOWN | WM_SYSKEYUP => {
            let state = if msg == WM_SYSKEYDOWN {
                ButtonState::Pressed
            } else {
                ButtonState::Released
            };
            if let Some(ev) = key_event(wp, state) {
                push_event(ev);
            }
            // Let Windows handle Alt+F4, Alt+Space and friends as well.
            unsafe { DefWindowProcW(hwnd, msg, wp, lp) }
        }
        WM_CHAR => {
            // wParam is a UTF-16 code unit (a character beyond the BMP comes
            // as two); emit printable characters as text, unless the key went
            // out as a shortcut from WM_KEYDOWN. A dead key followed by a
            // letter arrives here already composed, from TranslateMessage.
            let m = modifiers();
            let shortcut = (m.ctrl && !m.alt) || m.meta;
            let ch = CTX.with(|c| c.borrow_mut().utf16.push(wp as u16));
            if let Some(ch) = ch
                && !ch.is_control()
                && !shortcut
            {
                push_event(Event::Text(ch.to_string()));
            }
            0
        }
        // Input methods: we draw the composition inline, so the IME's own
        // composition window stays hidden (see `ime`).
        ime::WM_IME_SETCONTEXT => unsafe {
            DefWindowProcW(hwnd, msg, wp, lp & !ime::ISC_SHOWUICOMPOSITIONWINDOW)
        },
        ime::WM_IME_STARTCOMPOSITION => {
            ime::place_windows(hwnd);
            0
        }
        ime::WM_IME_COMPOSITION => {
            ime::composition(hwnd, lp);
            0
        }
        ime::WM_IME_ENDCOMPOSITION => {
            ime::end_composition();
            0
        }
        WM_GETOBJECT => {
            // UIA asks for our root provider with lParam == UiaRootObjectId. Hand
            // back the live provider tree; other object ids fall through to the
            // default (e.g. legacy MSAA, which we don't serve).
            if lp as i32 == UIA_ROOT_OBJECT_ID {
                let root = CTX.with(|c| {
                    c.borrow()
                        .uia
                        .as_ref()
                        .map(|t| t.root_provider())
                        .unwrap_or(std::ptr::null_mut())
                });
                if !root.is_null() {
                    return unsafe { UiaReturnRawElementProvider(hwnd, wp, lp, root) };
                }
            }
            unsafe { DefWindowProcW(hwnd, msg, wp, lp) }
        }
        // Dark mode and the accent color: `ImmersiveColorSet` names the setting
        // that changed; the colorization message follows accent changes. The
        // animation setting (reduced motion) comes with its SPI code.
        WM_SETTINGCHANGE | WM_THEMECHANGED | WM_DWMCOLORIZATIONCOLORCHANGED => {
            // SPI_SETCLIENTAREAANIMATION: the animation effects setting.
            if msg != WM_SETTINGCHANGE
                || wp == 0x1043
                || unsafe { names_setting(lp, "ImmersiveColorSet") }
            {
                crate::platform::native::note_changed();
            }
            unsafe { DefWindowProcW(hwnd, msg, wp, lp) }
        }
        // A pick from the menu bar. (Accelerator tables aren't used: the App
        // matches shortcuts from the key events, as on every platform.)
        WM_COMMAND if (wp >> 16) & 0xffff == 0 && lp == 0 => {
            push_event(Event::MenuCommand((wp & 0xffff) as u32));
            0
        }
        tray::WM_APP_TRAY => {
            tray::callback(hwnd, wp, lp);
            0
        }
        dnd::WM_DROPFILES => {
            dnd::drop_files(wp as *mut c_void);
            0
        }
        WM_CLOSE => {
            push_event(Event::CloseRequested);
            0
        }
        WM_DESTROY => {
            tray::remove_all(hwnd);
            unsafe { PostQuitMessage(0) };
            0
        }
        _ => unsafe { DefWindowProcW(hwnd, msg, wp, lp) },
    }
}

#[derive(Debug)]
struct WinWindow {
    hwnd: Hwnd,
    size: PhysicalSize,
}

impl Window for WinWindow {
    fn id(&self) -> WindowId {
        WindowId(self.hwnd as u64)
    }
    fn inner_size(&self) -> PhysicalSize {
        self.size
    }
    fn scale_factor(&self) -> ScaleFactor {
        ScaleFactor::new(current_scale())
    }
    fn request_redraw(&self) {
        unsafe { InvalidateRect(self.hwnd, std::ptr::null(), 0) };
    }
    fn set_title(&self, _title: &str) {}
    fn clipboard(&self) -> Option<String> {
        crate::platform::clipboard::text()
    }
    fn set_clipboard(&self, text: &str) {
        crate::platform::clipboard::set_text(text);
    }
    fn set_dark(&self, dark: bool) {
        set_dark_title(self.hwnd, dark);
        // Have the frame repaint now rather than at the next activation.
        unsafe {
            SetWindowPos(
                self.hwnd,
                std::ptr::null_mut(),
                0,
                0,
                0,
                0,
                SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
            )
        };
    }
    fn create_surface(&self) -> Box<dyn Surface> {
        Box::new(WinSurface {
            hwnd: self.hwnd,
            size: self.size,
        })
    }
    fn set_accessibility_tree(&self, root: &crate::platform::access::A11yNode) {
        // Rebuild the UIA provider tree; `WM_GETOBJECT` hands its root to UIA.
        let tree = crate::platform::uia::UiaTree::build(root);
        CTX.with(|c| c.borrow_mut().uia = Some(tree));
    }
    fn set_ime(&self, state: Option<&crate::platform::ImeState>) {
        ime::set_state(self.hwnd, state);
    }
    fn set_drop_accepted(&self, accepted: bool) {
        CTX.with(|c| c.borrow_mut().drop_accepted = accepted);
    }
    fn start_drag(&self, data: &crate::platform::DropData) -> bool {
        // `DoDragDrop` runs its own modal loop, so the message loop starts it
        // once the handler returns.
        if !data.can_leave_app() {
            return false;
        }
        CTX.with(|c| c.borrow_mut().drag_out = Some(data.clone()));
        true
    }
    fn set_cursor(&self, cursor: CursorIcon) {
        CTX.with(|c| c.borrow_mut().cursor = cursor);
        // The pointer is over the client area (we got here from a mouse move),
        // so show it now rather than on the next `WM_SETCURSOR`.
        unsafe { SetCursor(LoadCursorW(std::ptr::null_mut(), cursor_id(cursor))) };
    }
    fn set_min_size(&self, size: Option<Size>) {
        CTX.with(|c| c.borrow_mut().min_size = size);
        reapply_limits(self.hwnd);
    }
    fn set_max_size(&self, size: Option<Size>) {
        CTX.with(|c| c.borrow_mut().max_size = size);
        reapply_limits(self.hwnd);
    }
    fn set_maximized(&self, maximized: bool) {
        let cmd = if maximized { SW_MAXIMIZE } else { SW_RESTORE };
        unsafe { ShowWindow(self.hwnd, cmd) };
    }
    fn set_fullscreen(&self, fullscreen: bool) {
        set_fullscreen(self.hwnd, fullscreen);
    }
    fn set_menu_bar(&self, menu: &NativeMenuBar) -> bool {
        set_menu_bar(self.hwnd, menu);
        true
    }
    fn popup_menu(&self, menu: &NativeMenu, at: crate::geometry::Point) -> MenuPopup {
        popup_menu(self.hwnd, menu, at)
    }
    fn set_tray(&self, tray: Option<&NativeTray>) -> bool {
        tray::set_tray(self.hwnd, tray)
    }
    fn set_icon(&self, icon: Option<&crate::render::Pixmap>) {
        let new = icon.map_or(std::ptr::null_mut(), create_icon);
        unsafe {
            SendMessageW(self.hwnd, WM_SETICON, ICON_BIG, new as Lparam);
            SendMessageW(self.hwnd, WM_SETICON, ICON_SMALL, new as Lparam);
        }
        tray::set_app_icon(new);
        let old = CTX.with(|c| std::mem::replace(&mut c.borrow_mut().icon, new as usize));
        if old != 0 {
            unsafe { DestroyIcon(old as Handle) };
        }
    }
}

#[derive(Debug)]
struct WinSurface {
    hwnd: Hwnd,
    size: PhysicalSize,
}

impl Surface for WinSurface {
    fn resize(&mut self, size: PhysicalSize) {
        self.size = size;
    }
    fn size(&self) -> PhysicalSize {
        self.size
    }
    fn present(&mut self, pixmap: &Pixmap, _damage: &[crate::geometry::Rect]) {
        let size = pixmap.size();
        let src = pixmap.as_bytes();
        // RGBA -> BGRA (Win32 DIBs are BGRA, top-down via negative height).
        let mut fb = vec![0u8; src.len()];
        for (d, s) in fb
            .as_chunks_mut::<4>()
            .0
            .iter_mut()
            .zip(src.as_chunks::<4>().0)
        {
            d[0] = s[2];
            d[1] = s[1];
            d[2] = s[0];
            d[3] = s[3];
        }
        CTX.with(|c| {
            let mut c = c.borrow_mut();
            c.fb = fb;
            c.fb_w = size.width as i32;
            c.fb_h = size.height as i32;
        });
        unsafe { InvalidateRect(self.hwnd, std::ptr::null(), 0) };
    }
}

/// Create a window, render the initial frame, and pump the Win32 message loop
/// until `WM_QUIT`. `handler` is invoked for [`Event::RedrawRequested`] (to
/// produce the frame) and [`Event::CloseRequested`].
pub fn run<H>(attrs: WindowAttributes, mut handler: H) -> Result<(), PlatformError>
where
    H: FnMut(Event, &dyn Window) -> ControlFlow,
{
    let class_name = wide("StippleWindowClass");
    let title = wide(&attrs.title);
    // Without this, Windows renders us at 96 DPI and stretches the blurry result.
    // It fails harmlessly if the app's manifest already set an awareness.
    unsafe { SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2) };
    let system_dpi = unsafe { GetDpiForSystem() };
    let size = ScaleFactor::new(system_dpi as f64 / 96.0).to_physical(attrs.logical_size);

    let hinstance = unsafe { GetModuleHandleW(std::ptr::null()) };
    let cursor = unsafe { LoadCursorW(std::ptr::null_mut(), IDC_ARROW) };
    // Size limits, read on `WM_GETMINMAXINFO` (first sent while creating).
    CTX.with(|c| {
        let mut c = c.borrow_mut();
        c.min_size = attrs.min_size;
        c.max_size = attrs.max_size;
    });

    let class = WndClassW {
        style: 0,
        lpfn_wnd_proc: Some(wnd_proc),
        cb_cls_extra: 0,
        cb_wnd_extra: 0,
        h_instance: hinstance,
        h_icon: std::ptr::null_mut(),
        h_cursor: cursor,
        hbr_background: std::ptr::null_mut(),
        lpsz_menu_name: std::ptr::null(),
        lpsz_class_name: class_name.as_ptr(),
    };
    let atom = unsafe { RegisterClassW(&class) };
    if atom == 0 {
        return Err(PlatformError::Os("RegisterClassW failed".into()));
    }

    let hwnd = unsafe {
        CreateWindowExW(
            0,
            class_name.as_ptr(),
            title.as_ptr(),
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            size.width as i32,
            size.height as i32,
            std::ptr::null_mut(),
            std::ptr::null_mut(),
            hinstance,
            std::ptr::null_mut(),
        )
    };
    if hwnd.is_null() {
        return Err(PlatformError::Os("CreateWindowExW failed".into()));
    }
    tray::install(hwnd);
    // The window may have opened on a display with a different DPI to the system's.
    CTX.with(|c| c.borrow_mut().dpi = unsafe { GetDpiForWindow(hwnd) });
    if let Some(dark) = attrs.dark {
        // A title bar matching the content.
        set_dark_title(hwnd, dark);
    }

    // Use the actual client area for the framebuffer size.
    let mut rect = Rect {
        left: 0,
        top: 0,
        right: 0,
        bottom: 0,
    };
    unsafe { GetClientRect(hwnd, &mut rect) };
    let client = PhysicalSize::new(
        (rect.right - rect.left).max(1) as u32,
        (rect.bottom - rect.top).max(1) as u32,
    );
    let mut win = WinWindow { hwnd, size: client };
    // Take drops from other applications.
    if !dnd::register(hwnd) {
        eprintln!("stipple: RegisterDragDrop failed; only WM_DROPFILES drops work");
    }
    if let Some(icon) = attrs.icon.as_ref() {
        win.set_icon(Some(icon));
    }

    // Render the initial frame into the thread-local framebuffer.
    handler(Event::RedrawRequested, &win);

    let show = if attrs.maximized {
        SW_MAXIMIZE
    } else {
        SW_SHOW
    };
    unsafe {
        ShowWindow(hwnd, show);
        UpdateWindow(hwnd);
    }
    if attrs.fullscreen {
        set_fullscreen(hwnd, true);
    }

    // Message loop. The WndProc translates native messages into Stipple events
    // and queues them (it can't see the generic `handler`); we drain and
    // dispatch the queue after each message.
    //
    // Between messages, wait for input or a wakeup (timers, other threads). A
    // wake from another thread posts a message, which ends the wait.
    let target = hwnd as usize;
    crate::platform::wake::install(
        std::sync::Arc::new(move || unsafe {
            PostMessageW(target as Hwnd, WM_APP_WAKE, 0, 0);
        }),
        None,
    );
    // Animation frames are paced by DWM's composition, on a thread of their own.
    vsync::install();
    let mut msg: Msg = unsafe { std::mem::zeroed() };
    'outer: loop {
        let timeout = match crate::platform::wake::timeout(std::time::Instant::now()) {
            // Round up, so we don't wake a hair early and spin.
            Some(t) => t.as_micros().div_ceil(1000).min(INFINITE as u128 - 1) as u32,
            None => INFINITE,
        };
        unsafe {
            MsgWaitForMultipleObjectsEx(
                0,
                std::ptr::null(),
                timeout,
                QS_ALLINPUT,
                MWMO_INPUTAVAILABLE,
            )
        };
        while unsafe { PeekMessageW(&mut msg, std::ptr::null_mut(), 0, 0, PM_REMOVE) } != 0 {
            if msg.message == WM_QUIT {
                break 'outer;
            }
            unsafe {
                TranslateMessage(&msg);
                DispatchMessageW(&msg);
            }
            let events: Vec<Event> = CTX.with(|c| std::mem::take(&mut c.borrow_mut().queue));
            for event in events {
                if let Event::Resized(size) = event {
                    win.size = size;
                }
                if handler(event, &win) == ControlFlow::Exit {
                    unsafe { DestroyWindow(hwnd) };
                }
            }
            // A drag the app handed out runs here, outside the handler. What
            // it did to our own window waits in the queue; a message gets
            // the loop to deliver it.
            if let Some(data) = CTX.with(|c| c.borrow_mut().drag_out.take()) {
                unsafe { ReleaseCapture() };
                let _dropped = dnd::drag_out::run(&data);
                unsafe { PostMessageW(hwnd, WM_NULL, 0, 0) };
            }
        }
        if crate::platform::wake::take(std::time::Instant::now())
            && handler(Event::Wake, &win) == ControlFlow::Exit
        {
            unsafe { DestroyWindow(hwnd) };
        }
    }
    Ok(())
}