rust_widgets 2.3.1

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Native surface for **self-drawn** widgets on Windows.
//!
//! Registers a dedicated child window class (`RustWidgetsCanvasClass`) whose
//! window procedure paints the mounted widget and forwards input to it. A
//! distinct class is used rather than extending `RustWidgetsWindowClass`, so the
//! canvas message path stays independent of menu/control command routing.
//!
//! See `docs/plans/custom-paint_mounting.md`.
//!
//! # Feature gate
//!
//! This module renders through `crate::widget::runtime`, which `mini`/`embedded`
//! do not compile (see `src/widget/mod.rs`). The gate is applied here as well as
//! on the `target_os` so those profiles build without a widget registry, and
//! `supports_surfaces()` reports `false` instead of promising a surface that
//! cannot be painted.

#![cfg(all(target_os = "windows", widgets_unstripped))]

use crate::core::{ObjectId, Point, Rect};
use crate::event::Event;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use winapi::shared::minwindef::{LPARAM, LRESULT, UINT, WPARAM};
use winapi::shared::windef::{HDC, HWND, RECT};
use winapi::um::wingdi::{
    StretchDIBits, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, SRCCOPY,
};
use winapi::um::winuser::{
    BeginPaint, CloseTouchInputHandle, CreateWindowExW, DefWindowProcW, EndPaint, GetClientRect,
    GetTouchInputInfo, InvalidateRect, LoadCursorW, RegisterClassW, RegisterTouchWindow, SetFocus,
    SetWindowPos, TrackMouseEvent, UpdateWindow, CS_HREDRAW, CS_OWNDC, CS_VREDRAW, IDC_ARROW,
    PAINTSTRUCT, SWP_NOACTIVATE, SWP_NOZORDER, TME_LEAVE, TOUCHEVENTF_DOWN, TOUCHEVENTF_MOVE,
    TOUCHEVENTF_UP, TOUCHINPUT, TRACKMOUSEEVENT, TWF_WANTPALM, WM_ERASEBKGND, WM_KEYDOWN,
    WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSELEAVE, WM_MOUSEMOVE, WM_PAINT, WM_SIZE, WM_TOUCH,
    WNDCLASSW, WS_CHILD, WS_TABSTOP, WS_VISIBLE,
};

/// Child-window class name used for every self-drawn canvas.
const CANVAS_CLASS: &str = "RustWidgetsCanvasClass";

/// Maps a canvas `HWND` to the widget registry id it paints.
///
/// Only the id is stored: geometry lives in `widget::runtime` (the widget owns
/// it) and the `HWND` itself is also kept on the window as `GWLP_USERDATA`, so a
/// message handler can recover the id without a map lookup if needed.
fn canvases() -> &'static Mutex<HashMap<usize, ObjectId>> {
    static CANVASES: OnceLock<Mutex<HashMap<usize, ObjectId>>> = OnceLock::new();
    CANVASES.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Maps a canvas `HWND` to its origin in the parent window's client area.
///
/// Win32 reports mouse positions in the *child window's own* client coordinates, but
/// widget geometry in this library is absolute, so an event has to be offset by this
/// origin before it can be hit-tested. The value is recorded at mount time and kept
/// current by [`resize_canvas`], which is the only thing that moves a canvas.
fn canvas_origins() -> &'static Mutex<HashMap<usize, (i32, i32)>> {
    static ORIGINS: OnceLock<Mutex<HashMap<usize, (i32, i32)>>> = OnceLock::new();
    ORIGINS.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Returns the recorded origin of a canvas, defaulting to `(0, 0)`.
///
/// A missing entry means the canvas was created before this map existed or its
/// origin was never recorded; treating that as `(0, 0)` keeps behaviour identical to
/// the pre-hit-test code path rather than dropping input.
fn canvas_origin(hwnd: HWND) -> (i32, i32) {
    canvas_origins()
        .lock()
        .ok()
        .and_then(|map| map.get(&(hwnd as usize)).copied())
        .unwrap_or((0, 0))
}

/// Encodes a Rust string as a NUL-terminated UTF-16 buffer for Win32 APIs.
fn to_wide(value: &str) -> Vec<u16> {
    value.encode_utf16().chain(std::iter::once(0)).collect()
}

extern "system" {
    /// Returns the module handle of the calling process when passed null.
    fn GetModuleHandleW(lp_module_name: *const u16) -> *mut std::ffi::c_void;
}

/// Registers `RustWidgetsCanvasClass`. Safe to call repeatedly.
pub(crate) fn ensure_canvas_class_registered() {
    static REGISTERED: OnceLock<()> = OnceLock::new();
    REGISTERED.get_or_init(|| {
        // SAFETY: RegisterClassW runs on the UI thread with a fully initialised
        // WNDCLASSW whose pointers outlive the call.
        unsafe {
            let class_name = to_wide(CANVAS_CLASS);
            let hinstance = GetModuleHandleW(std::ptr::null());
            let mut wnd_class: WNDCLASSW = std::mem::zeroed();
            // CS_OWNDC: the canvas owns its device context, so painting does not
            // contend with sibling controls for a shared DC.
            wnd_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
            wnd_class.lpfnWndProc = Some(canvas_wnd_proc);
            wnd_class.hInstance = hinstance as _;
            wnd_class.hCursor = LoadCursorW(std::ptr::null_mut(), IDC_ARROW);
            wnd_class.lpszClassName = class_name.as_ptr();
            if RegisterClassW(&wnd_class) == 0 {
                log::error!("[windows] RegisterClassW failed for {CANVAS_CLASS}");
            }
        }
    });
}

/// Window procedure for canvas child windows.
unsafe extern "system" fn canvas_wnd_proc(
    hwnd: HWND,
    msg: UINT,
    wparam: WPARAM,
    lparam: LPARAM,
) -> LRESULT {
    match msg {
        WM_PAINT => {
            paint_canvas(hwnd);
            0
        }
        // Painting covers the whole client area, so let it erase too. Returning
        // non-zero skips the background fill and avoids a one-frame white flash.
        WM_ERASEBKGND => 1,
        WM_SIZE => {
            invalidate_canvas(hwnd);
            0
        }
        WM_LBUTTONDOWN => {
            forward_mouse(hwnd, lparam, MousePhase::Press);
            0
        }
        WM_LBUTTONUP => {
            forward_mouse(hwnd, lparam, MousePhase::Release);
            0
        }
        WM_MOUSEMOVE => {
            forward_mouse(hwnd, lparam, MousePhase::Drag);
            0
        }
        WM_MOUSELEAVE => {
            // Win32 only sends this after the window asks for it, so the request is
            // (re)issued on every move (see `forward_mouse`). This is the one case the
            // coordinate-based hover transition cannot observe: the pointer is outside, so
            // the previously hovered control would otherwise stay highlighted.
            crate::widget::runtime::clear_hover(Point::new(0, 0));
            invalidate_canvas(hwnd);
            0
        }
        WM_TOUCH => {
            forward_touch(hwnd, wparam, lparam);
            0
        }
        WM_KEYDOWN => {
            forward_key(hwnd, wparam);
            0
        }
        _ => DefWindowProcW(hwnd, msg, wparam, lparam),
    }
}

/// Which mouse event to synthesise.
#[derive(Clone, Copy)]
enum MousePhase {
    Press,
    Release,
    Drag,
}

/// Returns the widget id painted by `hwnd`.
fn widget_id_of(hwnd: HWND) -> Option<ObjectId> {
    canvases().lock().ok()?.get(&(hwnd as usize)).copied()
}

/// Renders the mounted widget into the window's client area.
unsafe fn paint_canvas(hwnd: HWND) {
    let mut paint: PAINTSTRUCT = std::mem::zeroed();
    let hdc: HDC = BeginPaint(hwnd, &mut paint);

    let mut rect: RECT = std::mem::zeroed();
    if GetClientRect(hwnd, &mut rect) == 0 {
        log::error!("[windows] canvas: GetClientRect failed");
        EndPaint(hwnd, &paint);
        return;
    }
    let width = (rect.right - rect.left).max(1) as u32;
    let height = (rect.bottom - rect.top).max(1) as u32;

    let Some(widget_id) = widget_id_of(hwnd) else {
        log::error!("[windows] canvas: WM_PAINT for an hwnd with no widget id");
        EndPaint(hwnd, &paint);
        return;
    };
    // `render_frame_cached` rather than `render_frame`: it carries the previous frame
    // forward and repaints only the damage, so a widget in `RepaintMode::Dirty` does
    // not re-rasterise every pixel on each `WM_PAINT`. The returned frame is complete
    // — the swap below still walks it — because `StretchDIBits` presents a whole
    // bitmap; the saving is in what was drawn, not in what is converted.
    let Some(frame) = crate::widget::runtime::render_frame_cached(
        widget_id,
        crate::core::Size::new(width, height),
        crate::core::Color::WHITE,
    ) else {
        log::error!(
            "[windows] canvas: widget id={widget_id} produced no frame \
             (unmounted, or it does not implement Draw)"
        );
        EndPaint(hwnd, &paint);
        return;
    };

    // 32-bit top-down BGRA. The frame is RGBA, so red and blue are swapped while
    // copying; alpha is forced opaque because StretchDIBits with BI_RGB ignores it.
    let mut buffer = vec![0u8; width as usize * height as usize * 4];
    for (index, pixel) in frame.chunks_exact(4).enumerate() {
        let offset = index * 4;
        buffer[offset] = pixel[2];
        buffer[offset + 1] = pixel[1];
        buffer[offset + 2] = pixel[0];
        buffer[offset + 3] = 255;
    }

    let mut info: BITMAPINFOHEADER = std::mem::zeroed();
    info.biSize = std::mem::size_of::<BITMAPINFOHEADER>() as u32;
    info.biWidth = width as i32;
    // A negative height selects a top-down DIB, matching the frame's row order.
    info.biHeight = -(height as i32);
    info.biPlanes = 1;
    info.biBitCount = 32;
    info.biCompression = BI_RGB;

    let scanned = StretchDIBits(
        hdc,
        0,
        0,
        width as i32,
        height as i32,
        0,
        0,
        width as i32,
        height as i32,
        buffer.as_ptr() as *const _,
        &info as *const _ as *const BITMAPINFO,
        DIB_RGB_COLORS,
        SRCCOPY,
    );
    if scanned == 0 {
        log::error!("[windows] canvas: StretchDIBits failed for {width}x{height}");
    }

    EndPaint(hwnd, &paint);
}

/// Marks the whole canvas as needing a repaint.
pub(crate) fn invalidate_canvas(hwnd: HWND) {
    // SAFETY: a null RECT invalidates the entire client area, which is intended.
    unsafe {
        InvalidateRect(hwnd, std::ptr::null(), 0);
    }
}

/// Invalidates one rectangle of a canvas's client area.
///
/// # Why this rejects a rectangle outside the client area
///
/// `InvalidateRect` accepts any coordinates and simply unions them into the update
/// region; a rectangle wholly outside the window contributes nothing but is still
/// reported as accepted. Returning `true` for it would tell the caller its damage had
/// been delivered when the region is unchanged — so this checks first and reports
/// `false`, driving the caller's fallback to a whole-client invalidation.
///
/// Returns `false` when the rectangle is empty or lies wholly outside the client area,
/// or when the client rect cannot be queried.
pub(crate) fn invalidate_canvas_rect(hwnd: HWND, rect: Rect) -> bool {
    if rect.width == 0 || rect.height == 0 {
        return false;
    }

    let mut client: RECT = unsafe { core::mem::zeroed() };
    // SAFETY: `client` is a valid, writable RECT for the duration of the call.
    let have_client = unsafe { GetClientRect(hwnd, &mut client) != 0 };
    if !have_client {
        return false;
    }

    let x = rect.x;
    let y = rect.y;
    let right = rect.x.saturating_add(rect.width as i32);
    let bottom = rect.y.saturating_add(rect.height as i32);
    if x >= client.right || y >= client.bottom || right <= client.left || bottom <= client.top {
        return false;
    }

    let clip = RECT { left: x, top: y, right, bottom };
    // SAFETY: `clip` outlives the call and is a valid RECT; the HWND came from the
    // caller's canvas table, so it addresses a live child window.
    unsafe {
        InvalidateRect(hwnd, &clip, 0);
    }
    true
}

/// Translates a Win32 mouse message into a widget event and delivers it.
///
/// The coordinates Win32 reports are relative to this child window, so they are
/// offset by the canvas origin to reach the absolute space the widget tree uses.
/// Routing then goes through the platform's hit test, so a click on a widget nested
/// inside the mounted one reaches that widget rather than the surface owner.
unsafe fn forward_mouse(hwnd: HWND, lparam: LPARAM, phase: MousePhase) {
    let Some(widget_id) = widget_id_of(hwnd) else {
        return;
    };
    // The low/high words of lparam hold signed client-area coordinates.
    let x = (lparam & 0xFFFF) as u16 as i16 as i32;
    let y = ((lparam >> 16) & 0xFFFF) as u16 as i16 as i32;
    let (origin_x, origin_y) = canvas_origin(hwnd);
    let position = Point::new(origin_x + x, origin_y + y);
    let event = match phase {
        MousePhase::Press => Event::MousePress { pos: position, button: 1 },
        MousePhase::Release => Event::MouseRelease { pos: position, button: 1 },
        MousePhase::Drag => Event::MouseMove { pos: position },
    };
    let delivered =
        crate::platform::platform_facts().route_pointer_event(widget_id, &event, position);
    if matches!(phase, MousePhase::Drag) {
        // Ask Win32 for a `WM_MOUSELEAVE` on the next exit. The request is consumed
        // by the event it produces, so it must be re-issued on every move — without
        // it the leave message never arrives and hover would stick.
        let mut track: TRACKMOUSEEVENT = std::mem::zeroed();
        track.cbSize = std::mem::size_of::<TRACKMOUSEEVENT>() as u32;
        track.dwFlags = TME_LEAVE;
        track.hwndTrack = hwnd;
        TrackMouseEvent(&mut track);
    }
    if delivered {
        if matches!(phase, MousePhase::Press) {
            // A click can move focus to a nested control; give the canvas the
            // keyboard so subsequent keys are delivered here.
            SetFocus(hwnd);
        }
        invalidate_canvas(hwnd);
    }
}

/// Translates a `WM_TOUCH` message into widget touch events and delivers them.
///
/// # Why this exists
///
/// Without it the gesture engine never sees a `TouchBegin`: `is_touch()` accepts only
/// `Touch*` and gesture variants, so `GestureEngine::process` was never called with real
/// input and all eleven recognizers were reachable only from unit tests. Win32 reports
/// finger contacts as `WM_TOUCH` carrying *screen* coordinates and its own per-contact
/// ids; both are translated here.
///
/// # One message, several contacts
///
/// A single `WM_TOUCH` can describe multiple simultaneous fingers — that is how the
/// backend feeds the two independent contacts `Pinch`/`Rotate` need. Each contact is
/// dispatched separately so the recognizers see one event per finger, which is the
/// shape their state machines expect.
///
/// # Coordinate space
///
/// `TOUCHINPUT` carries coordinates in *hundredths of a pixel* in *screen* space. They
/// are converted to whole pixels relative to this window, then offset by the canvas
/// origin to reach the absolute space the widget tree uses — the same space
/// `forward_mouse` produces, so a touch and a click at the same place agree.
unsafe fn forward_touch(hwnd: HWND, wparam: WPARAM, lparam: LPARAM) {
    let input_count = (wparam & 0xFFFF) as u32;
    if input_count == 0 {
        return;
    }
    let mut inputs: Vec<TOUCHINPUT> = vec![std::mem::zeroed(); input_count as usize];
    let size = std::mem::size_of::<TOUCHINPUT>() as i32;
    if GetTouchInputInfo(lparam as *mut _, input_count, inputs.as_mut_ptr(), size) == 0 {
        // The handle must still be closed, or Win32 leaks it — but only on the path
        // where we are not going to inspect the contacts.
        CloseTouchInputHandle(lparam as *mut _);
        return;
    }

    let Some(widget_id) = widget_id_of(hwnd) else {
        CloseTouchInputHandle(lparam as *mut _);
        return;
    };
    let (origin_x, origin_y) = canvas_origin(hwnd);
    let mut delivered = false;

    for input in inputs.iter().take(input_count as usize) {
        // Hundredths of a pixel, screen-relative. `round()` rather than truncation so
        // a contact 1.6 px into a control is reported inside it, matching the pixel a
        // mouse click at the same place would hit.
        let local_x = (input.x as f32 / 100.0).round() as i32;
        let local_y = (input.y as f32 / 100.0).round() as i32;
        // `TOUCHINPUT` is in screen coordinates, so the canvas origin has to be added
        // before the window-relative conversion. `ScreenToClient` needs the point in
        // screen space, which is what we already have.
        let mut screen_point = winapi::shared::windef::POINT { x: local_x, y: local_y };
        if winapi::um::winuser::ScreenToClient(hwnd, &mut screen_point) == 0 {
            continue;
        }
        let position = Point::new(origin_x + screen_point.x, origin_y + screen_point.y);

        // `dwID` is Win32's per-contact identifier; it is stable for the whole
        // contact, which is exactly what `TouchId` must be for the recognizers to
        // track fingers across move/end.
        let touch_id = input.dwID as u64;
        let flags = input.dwFlags;
        let event = if flags & TOUCHEVENTF_DOWN != 0 {
            Event::TouchBegin { pos: position, touch_id }
        } else if flags & TOUCHEVENTF_UP != 0 {
            Event::TouchEnd { pos: position, touch_id }
        } else if flags & TOUCHEVENTF_MOVE != 0 {
            Event::TouchMove { pos: position, touch_id }
        } else {
            // Neither down, up nor move — nothing this layer can express.
            continue;
        };
        if crate::platform::platform_facts().route_pointer_event(widget_id, &event, position) {
            delivered = true;
        }
    }

    // The touch handle is owned by the caller of the window procedure, so it is
    // released exactly once, after every contact has been read from it.
    CloseTouchInputHandle(lparam as *mut _);

    if delivered {
        invalidate_canvas(hwnd);
    }
}

/// Translates a Win32 key message into a widget event and delivers it.
///
/// Tab is consumed here to move focus, matching the other backends: it is not a
/// printable character, so forwarding it to the widget would be a no-op and the user
/// could never leave the first control.
unsafe fn forward_key(hwnd: HWND, wparam: WPARAM) {
    let Some(widget_id) = widget_id_of(hwnd) else {
        return;
    };
    let key = wparam as u32;
    const VK_TAB: u32 = 0x09;
    const WIDGET_SHIFT: u32 = 1;
    if key == VK_TAB {
        let forward = current_modifiers() & WIDGET_SHIFT == 0;
        crate::widget::runtime::focus_next(forward);
        invalidate_canvas(hwnd);
        return;
    }
    let modifiers = current_modifiers();
    let event = Event::KeyPress { key, modifiers };
    // Keys follow focus: with nothing focused, the surface owner keeps them.
    let target = crate::widget::runtime::focused_widget().unwrap_or(widget_id);
    if crate::widget::runtime::dispatch_event(target, &event) {
        invalidate_canvas(hwnd);
    }
}

/// Reads the keyboard modifier state into the widget-layer bitfield.
/// Returns the modifier bitfield for the key currently being processed.
///
/// The widget-layer convention is shift = 1, control = 2, alt = 4,
/// meta/command = 8 (see `Modifiers::from_event_bits`). Windows has no Command
/// key, so bit 3 stays clear; Control is reported as physical Control, and any
/// `Shortcut::primary` binding is resolved against CTRL by the shortcut layer on
/// this platform.
pub(crate) unsafe fn current_modifiers() -> u32 {
    use winapi::um::winuser::{GetKeyState, VK_CONTROL, VK_MENU, VK_SHIFT};
    // Widget-layer bits (see `Modifiers::from_event_bits`).
    const WIDGET_SHIFT: u32 = 1;
    const WIDGET_CONTROL: u32 = 2;
    const WIDGET_ALT: u32 = 4;
    let mut modifiers = 0u32;
    // A negative result means the key is currently down.
    if GetKeyState(VK_SHIFT) < 0 {
        modifiers |= WIDGET_SHIFT;
    }
    if GetKeyState(VK_CONTROL) < 0 {
        modifiers |= WIDGET_CONTROL;
    }
    if GetKeyState(VK_MENU) < 0 {
        modifiers |= WIDGET_ALT;
    }
    modifiers
}

/// Creates and shows a canvas child window for `id`.
pub(crate) fn mount_canvas(parent: HWND, id: ObjectId, rect: Rect) -> Option<HWND> {
    ensure_canvas_class_registered();
    if !crate::widget::runtime::is_mounted(id) {
        log::error!(
            "[windows] mount_surface: id={id} is not in widget::runtime; \
             call runtime::register before mounting"
        );
        return None;
    }
    // SAFETY: all Win32 calls run on the UI thread; the class was registered just
    // above and `parent` is a live window handle supplied by the caller.
    unsafe {
        let class_name = to_wide(CANVAS_CLASS);
        let hinstance = GetModuleHandleW(std::ptr::null());
        let hwnd = CreateWindowExW(
            0,
            class_name.as_ptr(),
            to_wide("").as_ptr(),
            WS_CHILD | WS_VISIBLE | WS_TABSTOP,
            rect.x,
            rect.y,
            rect.width as i32,
            rect.height as i32,
            parent,
            std::ptr::null_mut(),
            hinstance as _,
            std::ptr::null_mut(),
        );
        if hwnd.is_null() {
            log::error!(
                "[windows] mount_surface: CreateWindowExW failed (GetLastError={})",
                winapi::um::errhandlingapi::GetLastError()
            );
            return None;
        }
        canvases().lock().expect("windows canvas lock poisoned").insert(hwnd as usize, id);
        // Record where this canvas sits so pointer coordinates can be made absolute
        // before hit-testing (see `canvas_origin`).
        canvas_origins()
            .lock()
            .expect("windows canvas origin lock poisoned")
            .insert(hwnd as usize, (rect.x, rect.y));
        // Opt in to `WM_TOUCH`. Win32 delivers finger contacts only to windows that
        // asked, and the call is what makes the touch path above reachable. A failure
        // is not fatal: a machine with no digitiser simply keeps using mouse input, so
        // it is logged rather than treated as a mount error.
        // `TWF_WANTPALM` suppresses the default press-and-hold "palm check" delay,
        // which would otherwise make a tap take ~1s to be delivered.
        if RegisterTouchWindow(hwnd, TWF_WANTPALM) == 0 {
            log::debug!(
                "[windows] mount_surface: RegisterTouchWindow declined for hwnd {hwnd:p}; \
                 touch input will not be delivered to this canvas"
            );
        }
        invalidate_canvas(hwnd);
        UpdateWindow(hwnd);
        Some(hwnd)
    }
}

/// Moves and resizes a canvas child window.
pub(crate) fn resize_canvas(hwnd: HWND, rect: Rect) -> bool {
    // SAFETY: `hwnd` comes from `mount_canvas` and is a live child window.
    unsafe {
        let moved = SetWindowPos(
            hwnd,
            std::ptr::null_mut(),
            rect.x,
            rect.y,
            rect.width as i32,
            rect.height as i32,
            SWP_NOZORDER | SWP_NOACTIVATE,
        );
        if moved == 0 {
            log::error!("[windows] resize_surface: SetWindowPos failed");
            return false;
        }
        // The canvas moved, so its origin — and therefore the offset applied to
        // pointer coordinates — must move with it, or hit-testing drifts by the
        // resize delta.
        canvas_origins()
            .lock()
            .expect("windows canvas origin lock poisoned")
            .insert(hwnd as usize, (rect.x, rect.y));
        invalidate_canvas(hwnd);
        true
    }
}

/// Destroys a canvas child window and forgets its state.
pub(crate) fn unmount_canvas(hwnd: HWND) -> bool {
    // SAFETY: `hwnd` came from `mount_canvas`; DestroyWindow is valid on a child
    // window and synchronously delivers WM_DESTROY.
    unsafe {
        use winapi::um::winuser::DestroyWindow;
        if DestroyWindow(hwnd) == 0 {
            log::error!("[windows] unmount_surface: DestroyWindow failed");
            return false;
        }
    }
    let _ = canvas_origins()
        .lock()
        .expect("windows canvas origin lock poisoned")
        .remove(&(hwnd as usize));
    canvases().lock().expect("windows canvas lock poisoned").remove(&(hwnd as usize)).is_some()
}

/// Looks up the canvas window for a mounted widget id.
pub(crate) fn hwnd_for_widget(id: ObjectId) -> Option<HWND> {
    let map = canvases().lock().ok()?;
    map.iter().find(|(_, widget)| **widget == id).map(|(hwnd, _)| *hwnd as HWND)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn class_name_is_stable() {
        // The name is part of the registered Win32 class; changing it would
        // orphan windows created by an older build in the same process.
        assert_eq!(CANVAS_CLASS, "RustWidgetsCanvasClass");
    }

    #[test]
    fn to_wide_is_nul_terminated() {
        assert_eq!(to_wide("ab"), vec![0x61, 0x62, 0x00]);
        assert_eq!(to_wide(""), vec![0x00]);
    }

    #[test]
    fn unknown_hwnd_has_no_widget() {
        assert!(widget_id_of(0 as HWND).is_none());
    }

    #[test]
    fn hwnd_for_unknown_widget_is_none() {
        assert!(hwnd_for_widget(0xDEAD_BEEF).is_none());
    }
}