Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

74.0 KB
Raw Blame
//! Tauri desktop host integration for `ink-engine` on Windows 10/11.
//!
//! Responsibilities:
//! - Initializes [`DCompHost`] on the top-level `main` HWND (`topmost = false`) and configures
//!   WebView2's transparent background (`COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 }`).
//! - Spawns `ink-engine`'s dedicated DX12 render thread targeting `canvas_visual`.
//! - Attaches the lock-free `rtrb` SPSC tablet rings directly to `tablet_input.rs`.
//! - Installs a `main_hwnd` Win32 lifecycle subclass (`WM_SIZE`, `WM_DPICHANGED`,
//!   `WM_DISPLAYCHANGE`, `WM_DESTROY`) for minimize/restore and DPI invalidation.
//! - Runs a lightweight, high-priority `WH_MOUSE_LL` hook thread (`inkstudio-native-mouse`)
//!   that pushes mouse hover, wheel zoom/scroll, middle-click pan, Space+drag pan/rotate/zoom,
//!   and mouse PoC draw events directly into `ink-engine`'s lock-free `nav` SPSC ring
//!   (zero JS/IPC round-trips during camera navigation and hover cursor tracking).
//! - Bridges throttled `EngineEvent`s (`CameraChanged`, `Diagnostics`, `PointerStat`) back
//!   to React via Tauri app events.
//! - Guarantees strict ordered shutdown: detach input hooks -> join `ink-engine` (drops
//!   `wgpu::Surface` & DXGI swapchain) -> clear & drop `DCompHost`.

use ink_engine::collab::{RemoteStrokePoint, RemoteStrokeStartParams};
use ink_engine::tools::{
    LiquifyStepParams, RetouchSession, TransformCommitResult, TransformMode,
    TransformSessionSnapshot, TransformUpdatePayload,
};
use ink_engine::{
    BrushParams, BrushTextureKind, CameraState, CommittedStrokePoint, CompositorDisplayConfig,
    CursorConfig, EngineCommand, EngineDiagnostics, FlattenOptions, GlobalPressureCurve,
    GpuPoolStats, HistoryStateSnapshot, InteractionPolicy, NativeBrushConfig,
    PerspectiveRulerConfig, RectI32, ScratchpadStrokeInput, SelectionMetaSnapshot,
    StraightRulerConfig, ThumbnailUpdate, UiRect, ViewportRect,
};
use serde::Serialize;
use std::sync::{Arc, LazyLock, Mutex};

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeCameraEventPayload {
    pub pan_x: f32,
    pub pan_y: f32,
    pub zoom: f32,
    pub rotation: f32,
    pub flip_x: bool,
    pub flip_y: bool,
    pub commit: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativePointerStatPayload {
    pub doc_x: Option<i32>,
    pub doc_y: Option<i32>,
    pub pressure: f32,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeHistoryEventPayload {
    pub doc_id: String,
    pub history: HistoryStateSnapshot,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeThumbnailsEventPayload {
    pub doc_id: String,
    pub updates: Vec<ThumbnailUpdate>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeStrokeCommittedEventPayload {
    pub doc_id: String,
    pub layer_id: String,
    pub entry_id: String,
    pub dirty_rect: RectI32,
    pub history: HistoryStateSnapshot,
    pub points: Vec<CommittedStrokePoint>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeSelectionChangedPayload {
    pub doc_id: String,
    pub selection: SelectionMetaSnapshot,
}

pub const EVENT_CAMERA: &str = "native-engine://camera";
pub const EVENT_DIAGNOSTICS: &str = "native-engine://diagnostics";
pub const EVENT_POINTER_STAT: &str = "native-engine://pointer-stat";
pub const EVENT_HISTORY: &str = "native-engine://history";
pub const EVENT_THUMBNAILS: &str = "native-engine://thumbnails";
pub const EVENT_STROKE_COMMITTED: &str = "native-engine://stroke-committed";
pub const EVENT_SELECTION_CHANGED: &str = "native-engine://selection-changed";
pub const EVENT_VIEWPORT_INVALIDATED: &str = "native-engine://viewport-invalidated";

static FALLBACK_RETOUCH_SESSION: LazyLock<Arc<Mutex<RetouchSession>>> =
    LazyLock::new(|| Arc::new(Mutex::new(RetouchSession::default())));

#[cfg(target_os = "windows")]
mod win_host {
    use super::*;
    use crate::dcomp_host::DCompHost;
    use crate::tablet_input;
    use ink_engine::{
        EngineConfig, EngineEvent, EngineHandle, NativeNavEvent, NativeNavGesture, NavRingProducer,
        SharedHitTest, SurfaceTarget, WheelNavMode,
    };
    use std::cell::RefCell;
    use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, Ordering};
    use std::sync::{mpsc, Arc, LazyLock, Mutex};
    use std::thread::JoinHandle;
    use tauri::Emitter;
    use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
    use windows_sys::Win32::Graphics::Gdi::ScreenToClient;
    use windows_sys::Win32::System::Threading::{
        GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
    };
    use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
        GetAsyncKeyState, VK_CONTROL, VK_LBUTTON, VK_MBUTTON, VK_MENU, VK_RBUTTON, VK_SHIFT,
        VK_SPACE,
    };
    use windows_sys::Win32::UI::Shell::{
        DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass,
    };
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        CallNextHookEx, DispatchMessageW, GetAncestor, GetClientRect, GetForegroundWindow,
        GetMessageW, GetSystemMetrics, IsWindow, PostThreadMessageW, SetWindowsHookExW,
        TranslateMessage, UnhookWindowsHookEx, WindowFromPoint, GA_ROOT, HHOOK, MSG,
        MSLLHOOKSTRUCT, SIZE_MINIMIZED, SM_SWAPBUTTON, WA_INACTIVE, WH_MOUSE_LL, WM_ACTIVATE,
        WM_ACTIVATEAPP, WM_APP, WM_CANCELMODE, WM_CAPTURECHANGED, WM_DISPLAYCHANGE,
        WM_DPICHANGED, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP,
        WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_NCDESTROY, WM_QUIT, WM_SIZE,
    };

    const LIFECYCLE_SUBCLASS_ID: usize = 0x494E_4B45; // "INKE"
    const WM_APP_RESET_MOUSE_STATE: u32 = WM_APP + 1;
    const MI_WP_SIGNATURE: usize = 0xFF51_5700;
    const MI_WP_MASK: usize = 0xFFFF_FF00;
    const WHEEL_DELTA_NORM: f32 = 100.0 / 120.0;

    struct NativeEngineRuntime {
        dcomp: Arc<DCompHost>,
        engine: Arc<EngineHandle>,
        main_hwnd: isize,
        composition_mode: String,
        event_thread: Option<JoinHandle<()>>,
        mouse_hook_thread: Option<JoinHandle<()>>,
        last_viewport: ViewportRect,
        ui_visible: bool,
    }

    static RUNTIME: LazyLock<Mutex<Option<NativeEngineRuntime>>> =
        LazyLock::new(|| Mutex::new(None));
    static ENGINE_ACTIVE: AtomicBool = AtomicBool::new(false);
    static MAIN_HWND_RAW: AtomicIsize = AtomicIsize::new(0);
    static WINDOW_MINIMIZED: AtomicBool = AtomicBool::new(false);
    static MOUSE_HOOK_THREAD_ID: AtomicU32 = AtomicU32::new(0);
    static MOUSE_HOOK_RUNNING: AtomicBool = AtomicBool::new(false);
    static MOUSE_STATE_RESET_REQUESTED: AtomicBool = AtomicBool::new(false);

    // Non-blocking handles mirrored for the dedicated WH_MOUSE_LL hook thread & background tasks
    static HOOK_HIT_TEST: LazyLock<Mutex<Option<SharedHitTest>>> =
        LazyLock::new(|| Mutex::new(None));
    static STROKE_ACTIVE_FLAG: LazyLock<parking_lot::RwLock<Option<Arc<AtomicBool>>>> =
        LazyLock::new(|| parking_lot::RwLock::new(None));

    #[derive(Clone, Copy, PartialEq, Eq)]
    enum ActiveNavButton {
        None,
        Middle,
        LeftSpaceNav,
    }

    struct MouseHookLocal {
        nav_tx: Option<NavRingProducer>,
        hit_test: Option<SharedHitTest>,
        nav_button: ActiveNavButton,
        nav_down_ms: f64,
        mouse_drawing: bool,
        mouse_down_ms: f64,
        last_mouse_phys: (f32, f32),
        was_hovering_canvas: bool,
    }

    thread_local! {
        static MOUSE_HOOK_LOCAL: RefCell<MouseHookLocal> = const {
            RefCell::new(MouseHookLocal {
                nav_tx: None,
                hit_test: None,
                nav_button: ActiveNavButton::None,
                nav_down_ms: 0.0,
                mouse_drawing: false,
                mouse_down_ms: 0.0,
                last_mouse_phys: (0.0, 0.0),
                was_hovering_canvas: false,
            })
        };
    }

    #[inline]
    fn is_vk_pressed(vk: u16) -> bool {
        unsafe { (GetAsyncKeyState(vk as i32) as u16 & 0x8000) != 0 }
    }

    #[inline]
    fn is_primary_mouse_button_down() -> bool {
        unsafe {
            let vk = if GetSystemMetrics(SM_SWAPBUTTON) != 0 {
                VK_RBUTTON
            } else {
                VK_LBUTTON
            };
            (GetAsyncKeyState(vk as i32) as u16 & 0x8000) != 0
        }
    }

    fn request_mouse_hook_state_reset() {
        MOUSE_STATE_RESET_REQUESTED.store(true, Ordering::Release);
        let tid = MOUSE_HOOK_THREAD_ID.load(Ordering::Acquire);
        if tid != 0 {
            unsafe {
                let _ = PostThreadMessageW(tid, WM_APP_RESET_MOUSE_STATE, 0, 0);
            }
        }
    }

    fn flush_reset_mouse_hook_local() {
        MOUSE_HOOK_LOCAL.with(|cell| {
            let mut st = cell.borrow_mut();
            let now_ms = ink_engine::clock::now_ms();
            let (px, py) = st.last_mouse_phys;
            if st.mouse_drawing {
                st.mouse_drawing = false;
                if let Some(nav_tx) = st.nav_tx.as_mut() {
                    nav_tx.push(NativeNavEvent::MouseDraw {
                        phys_x: px,
                        phys_y: py,
                        phase: 3,
                        shift_held: false,
                        timestamp_ms: now_ms,
                    });
                }
            }
            if st.nav_button != ActiveNavButton::None {
                st.nav_button = ActiveNavButton::None;
                if let Some(nav_tx) = st.nav_tx.as_mut() {
                    nav_tx.push(NativeNavEvent::GestureEnd {
                        timestamp_ms: now_ms,
                    });
                }
            }
            if st.was_hovering_canvas {
                st.was_hovering_canvas = false;
                if let Some(nav_tx) = st.nav_tx.as_mut() {
                    nav_tx.push(NativeNavEvent::HoverLeave);
                }
            }
        });
    }

    #[inline]
    fn is_main_window_foreground(main_hwnd: HWND) -> bool {
        unsafe {
            let fg = GetForegroundWindow();
            if fg.is_null() {
                return false;
            }
            fg == main_hwnd || GetAncestor(fg, GA_ROOT) == main_hwnd
        }
    }

    #[inline]
    fn is_point_over_main_window(main_hwnd: HWND, screen_pt: POINT) -> bool {
        unsafe {
            let w = WindowFromPoint(screen_pt);
            if w.is_null() {
                return false;
            }
            w == main_hwnd || GetAncestor(w, GA_ROOT) == main_hwnd
        }
    }

    #[inline]
    fn screen_to_client_phys(main_hwnd: HWND, screen_pt: POINT) -> (f32, f32) {
        unsafe {
            let mut pt = screen_pt;
            ScreenToClient(main_hwnd, &mut pt);
            (pt.x as f32, pt.y as f32)
        }
    }

    #[inline]
    fn is_pen_or_touch_synthesized(extra_info: usize, now_ms: f64) -> bool {
        if (extra_info & MI_WP_MASK) == MI_WP_SIGNATURE {
            return true;
        }
        if tablet_input::is_stylus_in_contact() {
            return true;
        }
        // WinTab CXO_SYSTEM synthesizes Win32 mouse events without MI_WP_SIGNATURE while
        // the stylus is in proximity (or briefly between rapid strokes); gate against both
        // WinTab and Windows Ink stylus activity so synthesized clicks never collide with strokes.
        let last_wt = tablet_input::last_wintab_activity_ms();
        if last_wt > 0.0 && (now_ms - last_wt) < 150.0 {
            return true;
        }
        let last_stylus = tablet_input::last_stylus_activity_ms();
        last_stylus > 0.0 && (now_ms - last_stylus) < 150.0
    }

    /// Clamps a physical viewport rect strictly inside `main_hwnd`'s current client rect.
    /// Returns `(clamped_viewport, has_nonempty_client_area)`.
    fn clamp_viewport_to_client_rect(main_hwnd: HWND, vp: ViewportRect) -> (ViewportRect, bool) {
        if main_hwnd.is_null() {
            return (vp, vp.width_px > 0 && vp.height_px > 0);
        }
        let mut rc: RECT = unsafe { std::mem::zeroed() };
        let ok = unsafe { GetClientRect(main_hwnd, &mut rc) } != 0;
        if !ok {
            return (vp, vp.width_px > 0 && vp.height_px > 0);
        }
        let client_w = (rc.right - rc.left).max(0);
        let client_h = (rc.bottom - rc.top).max(0);
        if client_w == 0 || client_h == 0 || vp.width_px == 0 || vp.height_px == 0 {
            return (
                ViewportRect {
                    x_px: 0,
                    y_px: 0,
                    width_px: 0,
                    height_px: 0,
                    dpr: vp.dpr,
                },
                false,
            );
        }
        let x0 = vp.x_px.clamp(0, client_w);
        let y0 = vp.y_px.clamp(0, client_h);
        let x1 = vp.x_px.saturating_add(vp.width_px as i32).clamp(x0, client_w);
        let y1 = vp.y_px.saturating_add(vp.height_px as i32).clamp(y0, client_h);
        let w = (x1 - x0).max(0) as u32;
        let h = (y1 - y0).max(0) as u32;
        (
            ViewportRect {
                x_px: x0,
                y_px: y0,
                width_px: w,
                height_px: h,
                dpr: vp.dpr,
            },
            w > 0 && h > 0,
        )
    }

    /// Low-level mouse hook callback running on dedicated high-priority `inkstudio-native-mouse`
    /// thread. Strictly non-blocking (`try_read` + wait-free SPSC `rtrb` push) and returns in
    /// nanoseconds. NEVER swallows `WM_MOUSEMOVE` so the OS cursor stays smooth.
    unsafe extern "system" fn ll_mouse_proc(
        n_code: i32,
        w_param: WPARAM,
        l_param: LPARAM,
    ) -> LRESULT {
        if n_code < 0 || !ENGINE_ACTIVE.load(Ordering::Relaxed) {
            return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
        }

        let consume = std::panic::catch_unwind(|| -> bool {
            if MOUSE_STATE_RESET_REQUESTED.swap(false, Ordering::AcqRel) {
                flush_reset_mouse_hook_local();
            }

            let main_raw = MAIN_HWND_RAW.load(Ordering::Relaxed);
            if main_raw == 0 || l_param == 0 || WINDOW_MINIMIZED.load(Ordering::Relaxed) {
                return false;
            }
            let main_hwnd = main_raw as HWND;
            let ms = &*(l_param as *const MSLLHOOKSTRUCT);
            let msg = w_param as u32;

            MOUSE_HOOK_LOCAL.with(|cell| {
                let mut st_ref = cell.borrow_mut();
                let MouseHookLocal {
                    nav_tx,
                    hit_test,
                    nav_button,
                    nav_down_ms,
                    mouse_drawing,
                    mouse_down_ms,
                    last_mouse_phys,
                    was_hovering_canvas,
                } = &mut *st_ref;
                let (Some(nav_tx), Some(hit_test)) = (nav_tx.as_mut(), hit_test.as_ref()) else {
                    return false;
                };

                let has_active_capture = *nav_button != ActiveNavButton::None || *mouse_drawing;
                if !has_active_capture && !is_main_window_foreground(main_hwnd) {
                    if *was_hovering_canvas {
                        *was_hovering_canvas = false;
                        nav_tx.push(NativeNavEvent::HoverLeave);
                    }
                    return false;
                }

                let now_ms = ink_engine::clock::now_ms();
                let (px, py) = screen_to_client_phys(main_hwnd, ms.pt);
                *last_mouse_phys = (px, py);

                match msg {
                    WM_MOUSEMOVE => {
                        if *nav_button != ActiveNavButton::None {
                            let focus_lost = !is_main_window_foreground(main_hwnd);
                            let missed_release = (now_ms - *nav_down_ms) > 50.0
                                && match *nav_button {
                                    ActiveNavButton::Middle => !is_vk_pressed(VK_MBUTTON),
                                    ActiveNavButton::LeftSpaceNav => {
                                        !is_primary_mouse_button_down()
                                            && !tablet_input::is_stylus_in_contact()
                                    }
                                    ActiveNavButton::None => false,
                                };
                            if focus_lost || missed_release {
                                *nav_button = ActiveNavButton::None;
                                nav_tx.push(NativeNavEvent::GestureEnd {
                                    timestamp_ms: now_ms,
                                });
                                return false;
                            }
                            nav_tx.push(NativeNavEvent::GestureMove {
                                phys_x: px,
                                phys_y: py,
                                // Alt or Ctrl snaps rotation to 15° (matching useCanvasNavigation.ts);
                                // Shift is the Rotate trigger itself (Space+Shift+Drag / Middle+Shift+Drag).
                                snap_15_deg: is_vk_pressed(VK_MENU) || is_vk_pressed(VK_CONTROL),
                                timestamp_ms: now_ms,
                            });
                            return false;
                        }
                        if *mouse_drawing {
                            let focus_lost = !is_main_window_foreground(main_hwnd);
                            let stylus_took_over = tablet_input::is_stylus_in_contact();
                            let missed_release =
                                (now_ms - *mouse_down_ms) > 50.0 && !is_primary_mouse_button_down();
                            if focus_lost || missed_release || stylus_took_over {
                                *mouse_drawing = false;
                                nav_tx.push(NativeNavEvent::MouseDraw {
                                    phys_x: px,
                                    phys_y: py,
                                    phase: 3,
                                    shift_held: false,
                                    timestamp_ms: now_ms,
                                });
                                return false;
                            }
                            nav_tx.push(NativeNavEvent::MouseDraw {
                                phys_x: px,
                                phys_y: py,
                                phase: 2,
                                shift_held: is_vk_pressed(VK_SHIFT),
                                timestamp_ms: now_ms,
                            });
                            return false;
                        }

                        // Hover tracking for 120–240 Hz GPU brush cursor (skip pen-synthesized
                        // mouse moves while WinTab / Windows Ink is already feeding sub-pixel pen hover).
                        if is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms) {
                            return false;
                        }
                        // Foreground already verified above when !has_active_capture.
                        let over_unoccluded = is_point_over_main_window(main_hwnd, ms.pt)
                            && hit_test.try_is_unoccluded_canvas_point(px, py);
                        if over_unoccluded {
                            *was_hovering_canvas = true;
                            nav_tx.push(NativeNavEvent::Hover {
                                phys_x: px,
                                phys_y: py,
                                timestamp_ms: now_ms,
                            });
                        } else if *was_hovering_canvas {
                            *was_hovering_canvas = false;
                            nav_tx.push(NativeNavEvent::HoverLeave);
                        }
                        false
                    }
                    WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
                        if (has_active_capture && !is_main_window_foreground(main_hwnd))
                            || !is_point_over_main_window(main_hwnd, ms.pt)
                        {
                            return false;
                        }
                        if hit_test.try_wheel_mode() == WheelNavMode::BrushSize {
                            // Let React handle brush-size wheel stepping
                            return false;
                        }
                        if !hit_test.try_should_capture_native_nav(px, py) {
                            return false;
                        }
                        let raw_delta = ((ms.mouseData >> 16) as u16) as i16 as f32;
                        if raw_delta == 0.0 {
                            return false;
                        }
                        // Cleanly commit any active mouse stroke before wheel zoom/scroll so it
                        // never resumes spuriously after navigation.
                        if *mouse_drawing {
                            *mouse_drawing = false;
                            nav_tx.push(NativeNavEvent::MouseDraw {
                                phys_x: px,
                                phys_y: py,
                                phase: 3,
                                shift_held: false,
                                timestamp_ms: now_ms,
                            });
                        }
                        let (delta_x, delta_y) = if msg == WM_MOUSEWHEEL {
                            (0.0, -raw_delta * WHEEL_DELTA_NORM)
                        } else {
                            (raw_delta * WHEEL_DELTA_NORM, 0.0)
                        };
                        nav_tx.push(NativeNavEvent::Wheel {
                            phys_x: px,
                            phys_y: py,
                            delta_x,
                            delta_y,
                            ctrl_held: is_vk_pressed(VK_CONTROL),
                            shift_held: is_vk_pressed(VK_SHIFT),
                            timestamp_ms: now_ms,
                        });
                        true
                    }
                    WM_MBUTTONDOWN => {
                        if (has_active_capture && !is_main_window_foreground(main_hwnd))
                            || !is_point_over_main_window(main_hwnd, ms.pt)
                        {
                            return false;
                        }
                        if *nav_button != ActiveNavButton::None {
                            return true;
                        }
                        if !hit_test.try_should_capture_native_nav(px, py) {
                            return false;
                        }
                        if *mouse_drawing {
                            *mouse_drawing = false;
                            nav_tx.push(NativeNavEvent::MouseDraw {
                                phys_x: px,
                                phys_y: py,
                                phase: 3,
                                shift_held: false,
                                timestamp_ms: now_ms,
                            });
                        }
                        let gesture = if is_vk_pressed(VK_SHIFT) {
                            NativeNavGesture::Rotate
                        } else if is_vk_pressed(VK_CONTROL) {
                            NativeNavGesture::ZoomDrag
                        } else {
                            NativeNavGesture::Pan
                        };
                        *nav_button = ActiveNavButton::Middle;
                        *nav_down_ms = now_ms;
                        nav_tx.push(NativeNavEvent::GestureStart {
                            gesture,
                            phys_x: px,
                            phys_y: py,
                            timestamp_ms: now_ms,
                        });
                        true
                    }
                    WM_MBUTTONUP => {
                        if *nav_button == ActiveNavButton::Middle {
                            *nav_button = ActiveNavButton::None;
                            nav_tx.push(NativeNavEvent::GestureEnd {
                                timestamp_ms: now_ms,
                            });
                            return true;
                        }
                        false
                    }
                    WM_LBUTTONDOWN => {
                        if (has_active_capture && !is_main_window_foreground(main_hwnd))
                            || !is_point_over_main_window(main_hwnd, ms.pt)
                        {
                            return false;
                        }
                        if *nav_button != ActiveNavButton::None {
                            return true;
                        }
                        // Space + Left Drag -> native Pan / Shift+Rotate / Ctrl+ZoomDrag
                        // Skip pen-synthesized clicks: WinTab/Windows Ink stylus packets handle
                        // Space+Stylus navigation directly in `engine.rs` at full tablet Hz.
                        if !is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms)
                            && is_vk_pressed(VK_SPACE)
                            && !hit_test.try_text_input_focused()
                            && hit_test.try_should_capture_native_nav(px, py)
                        {
                            if *mouse_drawing {
                                *mouse_drawing = false;
                                nav_tx.push(NativeNavEvent::MouseDraw {
                                    phys_x: px,
                                    phys_y: py,
                                    phase: 3,
                                    shift_held: false,
                                    timestamp_ms: now_ms,
                                });
                            }
                            let gesture = if is_vk_pressed(VK_CONTROL) {
                                NativeNavGesture::ZoomDrag
                            } else if is_vk_pressed(VK_SHIFT) {
                                NativeNavGesture::Rotate
                            } else {
                                NativeNavGesture::Pan
                            };
                            *nav_button = ActiveNavButton::LeftSpaceNav;
                            *nav_down_ms = now_ms;
                            nav_tx.push(NativeNavEvent::GestureStart {
                                gesture,
                                phys_x: px,
                                phys_y: py,
                                timestamp_ms: now_ms,
                            });
                            return true;
                        }

                        // Mouse stroke on unoccluded canvas (skip pen-synthesized clicks so
                        // WinTab/Windows Ink remains sole owner of stylus strokes, and skip Alt
                        // modifier drags like Alt+Click eyedropper / Ctrl+Alt brush resize).
                        if !is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms)
                            && !is_vk_pressed(VK_MENU)
                            && hit_test.try_should_capture_native_stroke(px, py)
                        {
                            if *mouse_drawing {
                                *mouse_drawing = false;
                                nav_tx.push(NativeNavEvent::MouseDraw {
                                    phys_x: px,
                                    phys_y: py,
                                    phase: 3,
                                    shift_held: false,
                                    timestamp_ms: now_ms,
                                });
                            }
                            *mouse_drawing = true;
                            *mouse_down_ms = now_ms;
                            nav_tx.push(NativeNavEvent::MouseDraw {
                                phys_x: px,
                                phys_y: py,
                                phase: 1,
                                shift_held: is_vk_pressed(VK_SHIFT),
                                timestamp_ms: now_ms,
                            });
                            // Do NOT swallow WM_LBUTTONDOWN here so DOM focus/blur & non-modal
                            // menu dismissal keep working normally; React skips JS brush stroke
                            // dispatch when native canvas owns Brush/Eraser.
                        }
                        false
                    }
                    WM_LBUTTONUP => {
                        if *nav_button == ActiveNavButton::LeftSpaceNav {
                            *nav_button = ActiveNavButton::None;
                            nav_tx.push(NativeNavEvent::GestureEnd {
                                timestamp_ms: now_ms,
                            });
                            return true;
                        } else if *mouse_drawing {
                            *mouse_drawing = false;
                            nav_tx.push(NativeNavEvent::MouseDraw {
                                phys_x: px,
                                phys_y: py,
                                phase: 3,
                                shift_held: false,
                                timestamp_ms: now_ms,
                            });
                        }
                        false
                    }
                    _ => false,
                }
            })
        })
        .unwrap_or(false);

        if consume {
            1
        } else {
            CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param)
        }
    }

    fn spawn_mouse_hook_thread(
        nav_tx: NavRingProducer,
        hit_test: SharedHitTest,
    ) -> Result<JoinHandle<()>, String> {
        if let Ok(mut guard) = HOOK_HIT_TEST.lock() {
            *guard = Some(hit_test.clone());
        }
        let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();
        let handle = std::thread::Builder::new()
            .name("inkstudio-native-mouse".to_string())
            .spawn(move || unsafe {
                SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
                let tid = GetCurrentThreadId();
                MOUSE_HOOK_THREAD_ID.store(tid, Ordering::SeqCst);

                MOUSE_HOOK_LOCAL.with(|cell| {
                    let mut st = cell.borrow_mut();
                    st.nav_tx = Some(nav_tx);
                    st.hit_test = Some(hit_test);
                    st.nav_button = ActiveNavButton::None;
                    st.nav_down_ms = 0.0;
                    st.mouse_drawing = false;
                    st.mouse_down_ms = 0.0;
                    st.last_mouse_phys = (0.0, 0.0);
                    st.was_hovering_canvas = false;
                });

                let hook: HHOOK =
                    SetWindowsHookExW(WH_MOUSE_LL, Some(ll_mouse_proc), std::ptr::null_mut(), 0);
                if hook.is_null() {
                    MOUSE_HOOK_THREAD_ID.store(0, Ordering::SeqCst);
                    let _ = ready_tx.send(Err("Failed to install WH_MOUSE_LL hook".to_string()));
                    return;
                }

                MOUSE_HOOK_RUNNING.store(true, Ordering::SeqCst);
                let _ = ready_tx.send(Ok(()));

                let mut msg: MSG = std::mem::zeroed();
                while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 {
                    if msg.message == WM_APP_RESET_MOUSE_STATE {
                        MOUSE_STATE_RESET_REQUESTED.store(false, Ordering::Release);
                        flush_reset_mouse_hook_local();
                        continue;
                    }
                    TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                }

                UnhookWindowsHookEx(hook);
                MOUSE_HOOK_RUNNING.store(false, Ordering::SeqCst);
                MOUSE_HOOK_THREAD_ID.store(0, Ordering::SeqCst);
                MOUSE_STATE_RESET_REQUESTED.store(false, Ordering::SeqCst);
                MOUSE_HOOK_LOCAL.with(|cell| {
                    let mut st = cell.borrow_mut();
                    st.nav_tx = None;
                    st.hit_test = None;
                    st.nav_button = ActiveNavButton::None;
                    st.nav_down_ms = 0.0;
                    st.mouse_drawing = false;
                    st.mouse_down_ms = 0.0;
                    st.last_mouse_phys = (0.0, 0.0);
                    st.was_hovering_canvas = false;
                });
            })
            .map_err(|e| format!("Failed to spawn native mouse hook thread: {e}"))?;

        match ready_rx.recv_timeout(std::time::Duration::from_secs(2)) {
            Ok(Ok(())) => Ok(handle),
            Ok(Err(err)) => {
                let _ = handle.join();
                Err(err)
            }
            Err(_) => {
                let _ = handle.join();
                Err("Native mouse hook thread initialization timed out".to_string())
            }
        }
    }

    fn stop_mouse_hook_thread(handle: Option<JoinHandle<()>>) {
        let tid = MOUSE_HOOK_THREAD_ID.load(Ordering::SeqCst);
        if tid != 0 {
            unsafe {
                let _ = PostThreadMessageW(tid, WM_QUIT, 0, 0);
            }
        }
        if let Some(h) = handle {
            let _ = h.join();
        }
        if let Ok(mut guard) = HOOK_HIT_TEST.lock() {
            *guard = None;
        }
    }

    /// Top-level `main_hwnd` Win32 lifecycle subclass: handles minimize/restore (`WM_SIZE`),
    /// monitor DPI change (`WM_DPICHANGED`), display mode change (`WM_DISPLAYCHANGE`),
    /// and window teardown (`WM_NCDESTROY`).
    unsafe extern "system" fn lifecycle_subclass_proc(
        hwnd: HWND,
        msg: u32,
        wparam: WPARAM,
        lparam: LPARAM,
        uid_subclass: usize,
        _dw_ref_data: usize,
    ) -> LRESULT {
        let _ = std::panic::catch_unwind(|| match msg {
            WM_SIZE => {
                let client_w = (lparam & 0xFFFF) as u32;
                let client_h = ((lparam >> 16) & 0xFFFF) as u32;
                let minimized =
                    wparam == SIZE_MINIMIZED as usize || client_w == 0 || client_h == 0;
                let prev = WINDOW_MINIMIZED.swap(minimized, Ordering::SeqCst);
                if minimized && !prev {
                    request_mouse_hook_state_reset();
                    let handles = RUNTIME.try_lock().ok().and_then(|guard| {
                        guard.as_ref().map(|rt| {
                            (
                                Arc::clone(&rt.dcomp),
                                Arc::clone(&rt.engine),
                            )
                        })
                    });
                    if let Some((dcomp, engine)) = handles {
                        engine.send_command(EngineCommand::SetVisible(false));
                        let _ = dcomp.set_canvas_viewport(0, 0, 0, 0, false);
                    }
                } else if !minimized && prev {
                    let state = RUNTIME.try_lock().ok().and_then(|guard| {
                        guard.as_ref().map(|rt| {
                            (
                                Arc::clone(&rt.dcomp),
                                Arc::clone(&rt.engine),
                                rt.last_viewport,
                                rt.ui_visible,
                            )
                        })
                    });
                    if let Some((dcomp, engine, last_viewport, ui_visible)) = state {
                        let (clamped_vp, non_empty) =
                            clamp_viewport_to_client_rect(hwnd, last_viewport);
                        let vis = ui_visible && non_empty;
                        let _ = dcomp.stage_canvas_viewport(
                            clamped_vp.x_px,
                            clamped_vp.y_px,
                            clamped_vp.width_px,
                            clamped_vp.height_px,
                            vis,
                        );
                        engine.send_command(EngineCommand::SetViewport(clamped_vp));
                        engine.send_command(EngineCommand::SetVisible(vis));
                        engine.send_command(EngineCommand::NotifySurfaceInvalidated);
                    }
                }
                // Note: during normal non-minimized drag resizes, do NOT force-reconfigure
                // the swapchain with stale old dimensions on every WM_SIZE pixel; React's
                // ResizeObserver drives `set_viewport` with exact new physical bounds once/frame.
            }
            WM_CAPTURECHANGED | WM_CANCELMODE => {
                request_mouse_hook_state_reset();
            }
            WM_ACTIVATE => {
                if (wparam & 0xFFFF) == WA_INACTIVE as usize {
                    request_mouse_hook_state_reset();
                }
            }
            WM_ACTIVATEAPP => {
                if wparam == 0 {
                    request_mouse_hook_state_reset();
                }
            }
            WM_DPICHANGED | WM_DISPLAYCHANGE => {
                let engine = RUNTIME
                    .try_lock()
                    .ok()
                    .and_then(|guard| guard.as_ref().map(|rt| Arc::clone(&rt.engine)));
                if let Some(engine) = engine {
                    engine.send_command(EngineCommand::NotifySurfaceInvalidated);
                }
            }
            WM_NCDESTROY => {
                RemoveWindowSubclass(hwnd, Some(lifecycle_subclass_proc), uid_subclass);
                let _ = MAIN_HWND_RAW.compare_exchange(
                    hwnd as isize,
                    0,
                    Ordering::SeqCst,
                    Ordering::SeqCst,
                );
            }
            _ => {}
        });

        DefSubclassProc(hwnd, msg, wparam, lparam)
    }

    pub fn init_for_main_window(
        app_handle: tauri::AppHandle,
        main_window: &tauri::WebviewWindow,
    ) -> Result<(), String> {
        let hwnd = main_window
            .hwnd()
            .map_err(|e| format!("Failed to acquire main window HWND: {e}"))?;
        let main_hwnd_raw = hwnd.0 as isize;
        MAIN_HWND_RAW.store(main_hwnd_raw, Ordering::SeqCst);

        let dcomp = Arc::new(DCompHost::new(main_hwnd_raw)?);
        let dcomp_for_webview = Arc::clone(&dcomp);
        let composition_mode_cell = Arc::new(Mutex::new("DirectComposition (Underlay)".to_string()));
        let mode_clone = Arc::clone(&composition_mode_cell);

        // Configure WebView2 transparent background + disable browser accelerator keys on UI thread
        main_window
            .with_webview(move |webview| {
                use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Settings3;
                use windows_core::Interface;

                let controller = webview.controller();
                let mode = dcomp_for_webview.configure_webview2_controller(&controller);
                if let Ok(mut g) = mode_clone.lock() {
                    *g = mode;
                }

                unsafe {
                    if let Ok(core) = controller.CoreWebView2() {
                        if let Ok(settings) = core.Settings() {
                            if let Ok(settings3) = settings.cast::<ICoreWebView2Settings3>() {
                                let _ = settings3.SetAreBrowserAcceleratorKeysEnabled(false);
                            }
                        }
                    }
                }
            })
            .map_err(|e| format!("with_webview setup failed: {e}"))?;

        let composition_mode = composition_mode_cell
            .lock()
            .map(|g| g.clone())
            .unwrap_or_else(|_| "DirectComposition (Underlay)".to_string());

        let visual_raw = dcomp.canvas_visual_raw()?;
        let dcomp_commit = Arc::clone(&dcomp);
        let target = unsafe {
            SurfaceTarget::from_composition_visual(
                visual_raw,
                Arc::new(move || {
                    dcomp_commit.commit();
                }),
            )
        };

        let engine_cfg = EngineConfig {
            scratch_backend: Some(Arc::new(crate::native_docs::TauriScratchDiskBackend)),
            ..EngineConfig::default()
        };
        let (engine, producers) = EngineHandle::spawn(target, engine_cfg)?;
        *STROKE_ACTIVE_FLAG.write() = Some(engine.stroke_active_flag());
        crate::native_docs::attach_engine_documents(engine.documents());
        let hit_test = engine.hit_test();

        // Wire lock-free SPSC WinTab & Windows Ink rings directly into `tablet_input.rs`
        tablet_input::attach_engine_rings(producers.wintab, producers.winink, hit_test.clone());
        tablet_input::start_native_only_if_idle(main_hwnd_raw);

        // Spawn dedicated high-priority WH_MOUSE_LL zero-IPC nav & hover hook thread
        let mouse_hook_thread = match spawn_mouse_hook_thread(producers.nav, hit_test.clone()) {
            Ok(h) => Some(h),
            Err(err) => {
                eprintln!("[native_engine] WH_MOUSE_LL hook unavailable: {err}");
                None
            }
        };

        // Install main_hwnd Win32 lifecycle subclass on main UI thread
        let subclass_hwnd = main_hwnd_raw;
        let _ = main_window.run_on_main_thread(move || unsafe {
            let _ = SetWindowSubclass(
                subclass_hwnd as HWND,
                Some(lifecycle_subclass_proc),
                LIFECYCLE_SUBCLASS_ID,
                0,
            );
        });

        // Bridge throttled EngineEvents back to React
        let event_rx = engine.events().clone();
        let mode_for_events = composition_mode.clone();
        let event_thread = std::thread::Builder::new()
            .name("inkstudio-engine-events".to_string())
            .spawn(move || {
                while let Ok(evt) = event_rx.recv() {
                    match evt {
                        EngineEvent::CameraChanged { camera, commit } => {
                            let _ = app_handle.emit(
                                EVENT_CAMERA,
                                NativeCameraEventPayload {
                                    pan_x: camera.pan_x,
                                    pan_y: camera.pan_y,
                                    zoom: camera.zoom,
                                    rotation: camera.rotation,
                                    flip_x: camera.flip_x,
                                    flip_y: camera.flip_y,
                                    commit,
                                },
                            );
                        }
                        EngineEvent::Diagnostics(mut diag) => {
                            diag.composition_mode = mode_for_events.clone();
                            let _ = app_handle.emit(EVENT_DIAGNOSTICS, diag);
                        }
                        EngineEvent::PointerStat {
                            doc_x,
                            doc_y,
                            pressure,
                        } => {
                            let _ = app_handle.emit(
                                EVENT_POINTER_STAT,
                                NativePointerStatPayload {
                                    doc_x,
                                    doc_y,
                                    pressure,
                                },
                            );
                        }
                        EngineEvent::HistoryChanged { doc_id, history } => {
                            crate::raster_journal::notify_history_changed();
                            let _ = app_handle.emit(
                                EVENT_HISTORY,
                                NativeHistoryEventPayload { doc_id, history },
                            );
                        }
                        EngineEvent::ThumbnailsUpdated { doc_id, updates } => {
                            let _ = app_handle.emit(
                                EVENT_THUMBNAILS,
                                NativeThumbnailsEventPayload { doc_id, updates },
                            );
                        }
                        EngineEvent::StrokeCommitted {
                            doc_id,
                            layer_id,
                            entry_id,
                            dirty_rect,
                            history,
                            points,
                        } => {
                            crate::raster_journal::notify_history_changed();
                            let _ = app_handle.emit(
                                EVENT_STROKE_COMMITTED,
                                NativeStrokeCommittedEventPayload {
                                    doc_id,
                                    layer_id,
                                    entry_id,
                                    dirty_rect,
                                    history,
                                    points,
                                },
                            );
                        }
                        EngineEvent::SelectionChanged { doc_id, selection } => {
                            let _ = app_handle.emit(
                                EVENT_SELECTION_CHANGED,
                                NativeSelectionChangedPayload { doc_id, selection },
                            );
                        }
                        EngineEvent::ViewportInvalidated => {
                            let _ = app_handle.emit(EVENT_VIEWPORT_INVALIDATED, ());
                        }
                    }
                }
            })
            .ok();

        if let Ok(mut guard) = RUNTIME.lock() {
            *guard = Some(NativeEngineRuntime {
                dcomp,
                engine: Arc::new(engine),
                main_hwnd: main_hwnd_raw,
                composition_mode,
                event_thread,
                mouse_hook_thread,
                last_viewport: ViewportRect::default(),
                ui_visible: false,
            });
        }
        ENGINE_ACTIVE.store(true, Ordering::SeqCst);
        Ok(())
    }

    pub fn shutdown() {
        ENGINE_ACTIVE.store(false, Ordering::SeqCst);
        *STROKE_ACTIVE_FLAG.write() = None;
        crate::native_docs::detach_engine_documents();
        tablet_input::detach_engine_rings();

        let runtime = RUNTIME.lock().ok().and_then(|mut g| g.take());
        let Some(mut rt) = runtime else {
            return;
        };

        // 1. Stop WH_MOUSE_LL hook thread first so no more nav events are produced
        stop_mouse_hook_thread(rt.mouse_hook_thread.take());

        // 2. Remove main_hwnd lifecycle subclass
        if rt.main_hwnd != 0 {
            let hwnd = rt.main_hwnd as HWND;
            unsafe {
                if IsWindow(hwnd) != 0 {
                    let _ = RemoveWindowSubclass(
                        hwnd,
                        Some(lifecycle_subclass_proc),
                        LIFECYCLE_SUBCLASS_ID,
                    );
                }
            }
        }

        // 3. STRICT ORDER: Shut down and join ink-engine thread FIRST (drops wgpu::Surface &
        //    DXGI swapchain) BEFORE detaching and dropping DirectComposition visuals/device.
        rt.engine.shutdown();

        if let Some(ev_thread) = rt.event_thread.take() {
            let _ = ev_thread.join();
        }

        // 4. Detach visual content and drop DCompHost
        rt.dcomp.clear_content();
        drop(rt.dcomp);
        MAIN_HWND_RAW.store(0, Ordering::SeqCst);
    }

    pub fn is_active() -> bool {
        ENGINE_ACTIVE.load(Ordering::Acquire)
    }

    pub fn is_stroke_active() -> bool {
        STROKE_ACTIVE_FLAG
            .read()
            .as_ref()
            .is_some_and(|flag| flag.load(Ordering::Acquire))
    }

    pub fn set_viewport(viewport: ViewportRect, visible: bool) -> Result<(), String> {
        let (main_hwnd, dcomp, engine) = {
            let mut guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_mut() else {
                return Ok(());
            };
            rt.last_viewport = viewport;
            rt.ui_visible = visible;
            (
                rt.main_hwnd,
                Arc::clone(&rt.dcomp),
                Arc::clone(&rt.engine),
            )
        };

        // Release RUNTIME before invoking Win32 (`GetClientRect`) / DirectComposition (`Commit`)
        // to eliminate any main-thread re-entrant deadlock with `lifecycle_subclass_proc`.
        let (clamped_vp, has_client_area) =
            clamp_viewport_to_client_rect(main_hwnd as HWND, viewport);
        let effective_visible =
            visible && !WINDOW_MINIMIZED.load(Ordering::Acquire) && has_client_area;
        // Stage DComp offset/clip update so it commits atomically on the render thread right
        // after `surface.configure` / present (hiding commits immediately to avoid stale visual).
        dcomp.stage_canvas_viewport(
            clamped_vp.x_px,
            clamped_vp.y_px,
            clamped_vp.width_px,
            clamped_vp.height_px,
            effective_visible,
        )?;
        // `EngineHandle::send_command` updates `SharedHitTest` once synchronously.
        engine.send_command(EngineCommand::SetViewport(clamped_vp));
        engine.send_command(EngineCommand::SetVisible(effective_visible));
        Ok(())
    }

    pub fn set_occluded_rects(rects: Vec<UiRect>) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                // `EngineHandle::send_command` updates `SharedHitTest` once with zero Vec clone.
                rt.engine
                    .send_command(EngineCommand::SetOccludedRects(rects));
            }
        }
    }

    pub fn set_document(width: u32, height: u32, show_checkerboard: bool) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::SetDocumentSize {
                    width,
                    height,
                    show_checkerboard,
                });
            }
        }
    }

    pub fn set_appearance(matte_rgba: [f32; 4], show_checkerboard: bool) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetMatteColor(matte_rgba));
                rt.engine
                    .send_command(EngineCommand::SetShowCheckerboard(show_checkerboard));
            }
        }
    }

    pub fn set_display_config(config: CompositorDisplayConfig) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetDisplayConfig(config));
            }
        }
    }

    pub fn invalidate_compositor_cache() {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::InvalidateCompositorCache);
            }
        }
    }

    /// Executes headless document-space GPU flattening on the running DX12 render thread
    /// without holding the global `RUNTIME` mutex while waiting for GPU completion.
    pub fn render_document_flattened(
        doc_id: Option<String>,
        options: FlattenOptions,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine.send_command(EngineCommand::RenderDocumentFlattened {
                doc_id,
                options,
                reply: tx,
            });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(30))
            .map_err(|_| "Timed out waiting for GPU document flatten".to_string())?
    }

    /// Executes a GPU-accurate single-layer thumbnail render on the DX12 render thread.
    pub fn render_layer_thumbnail_gpu(
        doc_id: Option<String>,
        layer_id: String,
        max_dim: u32,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine.send_command(EngineCommand::RenderLayerThumbnail {
                doc_id,
                layer_id,
                max_dim,
                reply: tx,
            });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for GPU layer thumbnail".to_string())?
    }

    pub fn set_camera(camera: CameraState) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::SetCamera(camera));
            }
        }
    }

    pub fn set_cursor(config: CursorConfig) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetCursorConfig(config));
            }
        }
    }

    pub fn set_brush(params: BrushParams) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetBrushParams(params));
            }
        }
    }

    pub fn set_full_brush(config: NativeBrushConfig) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetFullBrushConfig(Box::new(config)));
            }
        }
    }

    pub fn clean_dirty_brush(preset_key: Option<String>) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::CleanDirtyBrush(preset_key));
            }
        }
    }

    pub fn set_mask_mode(enabled: bool) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::SetMaskMode(enabled));
            }
        }
    }

    pub fn render_brush_preview(
        brush: NativeBrushConfig,
        width: u32,
        height: u32,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine.send_command(EngineCommand::RenderBrushPreview {
                brush: Box::new(brush),
                width,
                height,
                reply: tx,
            });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(5))
            .map_err(|_| "Timed out waiting for GPU brush preview".to_string())?
    }

    pub fn render_scratchpad_preview(
        brush: NativeBrushConfig,
        strokes: Vec<ScratchpadStrokeInput>,
        width: u32,
        height: u32,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine.send_command(EngineCommand::RenderScratchpadPreview {
                brush: Box::new(brush),
                strokes,
                width,
                height,
                reply: tx,
            });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(5))
            .map_err(|_| "Timed out waiting for GPU scratchpad preview".to_string())?
    }

    pub fn set_pressure_curve(curve: GlobalPressureCurve) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetGlobalPressureCurve(curve));
            }
        }
    }

    pub fn set_rulers(
        straight: Option<StraightRulerConfig>,
        perspective: Option<PerspectiveRulerConfig>,
    ) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::SetRulers {
                    straight,
                    perspective,
                });
            }
        }
    }

    pub fn upload_brush_texture(
        hash: String,
        kind: BrushTextureKind,
        is_png: bool,
        width: u32,
        height: u32,
        data: Vec<u8>,
    ) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::UploadBrushTexture {
                    hash,
                    kind,
                    is_png,
                    width,
                    height,
                    data,
                });
            }
        }
    }

    pub fn set_policy(policy: InteractionPolicy) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                // `EngineHandle::send_command` updates `SharedHitTest` once synchronously.
                rt.engine
                    .send_command(EngineCommand::SetInteractionPolicy(policy));
            }
        }
    }

    pub fn set_collab_points_enabled(enabled: bool) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetCollabPointsEnabled(enabled));
            }
        }
    }

    pub fn clear_canvas() {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::ClearCanvas);
            }
        }
    }

    pub fn sync_active_document() {
        // Every native document mutation path funnels through here: journal its pixels.
        crate::raster_journal::notify_history_changed();
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::SyncActiveDocument);
            }
        }
    }

    pub fn set_vram_budget(budget_bytes: u64) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::SetVramBudget(budget_bytes));
            }
        }
    }

    pub fn flush_gpu_pool() {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::FlushGpuPool);
            }
        }
    }

    pub fn gpu_pool_stats() -> GpuPoolStats {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                return rt.engine.gpu_pool_stats();
            }
        }
        GpuPoolStats::default()
    }

    pub fn get_diagnostics() -> EngineDiagnostics {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                let mut diag = rt.engine.diagnostics();
                diag.composition_mode = rt.composition_mode.clone();
                return diag;
            }
        }
        EngineDiagnostics::default()
    }

    pub fn retouch_session() -> Arc<Mutex<RetouchSession>> {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                return rt.engine.retouch_session();
            }
        }
        Arc::clone(&FALLBACK_RETOUCH_SESSION)
    }

    pub fn liquify_begin(
        multi_layer: bool,
        layer_ids: Option<Vec<String>>,
    ) -> Result<Vec<String>, String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine.send_command(EngineCommand::LiquifyBegin {
                multi_layer,
                layer_ids,
                reply: tx,
            });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for LiquifyBegin".to_string())?
    }

    pub fn liquify_step(step: LiquifyStepParams) -> Result<RectI32, String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine
                .send_command(EngineCommand::LiquifyStep { step, reply: tx });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for LiquifyStep".to_string())?
    }

    pub fn liquify_commit() -> Result<(Vec<String>, RectI32), String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine
                .send_command(EngineCommand::LiquifyCommit { reply: tx });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(20))
            .map_err(|_| "Timed out waiting for LiquifyCommit".to_string())?
    }

    pub fn liquify_cancel() {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::LiquifyCancel);
            }
        }
    }

    pub fn transform_begin(
        mode: TransformMode,
        layer_ids: Option<Vec<String>>,
    ) -> Result<TransformSessionSnapshot, String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine.send_command(EngineCommand::TransformBegin {
                mode,
                layer_ids,
                reply: tx,
            });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(15))
            .map_err(|_| "Timed out waiting for TransformBegin".to_string())?
    }

    pub fn transform_update(
        payload: TransformUpdatePayload,
    ) -> Result<TransformSessionSnapshot, String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine
                .send_command(EngineCommand::TransformUpdate { payload, reply: tx });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(10))
            .map_err(|_| "Timed out waiting for TransformUpdate".to_string())?
    }

    pub fn transform_switch_mode(
        next_mode: TransformMode,
    ) -> Result<TransformSessionSnapshot, String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine.send_command(EngineCommand::TransformSwitchMode {
                next_mode,
                reply: tx,
            });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(15))
            .map_err(|_| "Timed out waiting for TransformSwitchMode".to_string())?
    }

    pub fn transform_commit() -> Result<TransformCommitResult, String> {
        let rx = {
            let guard = RUNTIME
                .lock()
                .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
            let Some(rt) = guard.as_ref() else {
                return Err("Native DX12 engine is not active".to_string());
            };
            let (tx, rx) = crossbeam_channel::bounded(1);
            rt.engine
                .send_command(EngineCommand::TransformCommit { reply: tx });
            rx
        };
        rx.recv_timeout(std::time::Duration::from_secs(20))
            .map_err(|_| "Timed out waiting for TransformCommit".to_string())?
    }

    pub fn transform_cancel() {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::TransformCancel);
            }
        }
    }

    pub fn set_tool_preview_rgba8(
        rect: RectI32,
        rgba: Vec<u8>,
        opacity: f32,
        replaced_layer_id: Option<String>,
    ) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::SetToolPreviewRgba8 {
                    rect,
                    rgba,
                    opacity,
                    replaced_layer_id,
                });
            }
        }
    }

    pub fn clear_tool_preview() {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::ClearToolPreview);
            }
        }
    }

    pub fn remote_stroke_start(params: RemoteStrokeStartParams) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::RemoteStrokeStart(params));
            }
        }
    }

    pub fn remote_stroke_chunk(
        peer_id: String,
        stroke_id: String,
        points: Vec<RemoteStrokePoint>,
    ) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::RemoteStrokeChunk {
                    peer_id,
                    stroke_id,
                    points,
                });
            }
        }
    }

    pub fn remote_stroke_finish(peer_id: String, stroke_id: String, expected_tiles: u32) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::RemoteStrokeFinish {
                    peer_id,
                    stroke_id,
                    expected_tiles,
                });
            }
        }
    }

    pub fn remote_stroke_dispose(peer_id: String, stroke_id: String) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine.send_command(EngineCommand::RemoteStrokeDispose {
                    peer_id,
                    stroke_id,
                });
            }
        }
    }

    pub fn remote_peer_dispose(peer_id: String) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::RemotePeerDispose { peer_id });
            }
        }
    }

    pub fn remote_notify_tile_delta(layer_id: String) {
        if let Ok(guard) = RUNTIME.lock() {
            if let Some(rt) = guard.as_ref() {
                rt.engine
                    .send_command(EngineCommand::RemoteNotifyTileDelta { layer_id });
            }
        }
    }
}

#[cfg(not(target_os = "windows"))]
mod win_host {
    use super::*;
    pub fn init_for_main_window(
        _app_handle: tauri::AppHandle,
        _main_window: &tauri::WebviewWindow,
    ) -> Result<(), String> {
        Ok(())
    }
    pub fn shutdown() {}
    pub fn is_active() -> bool {
        false
    }
    pub fn is_stroke_active() -> bool {
        false
    }
    pub fn set_viewport(_viewport: ViewportRect, _visible: bool) -> Result<(), String> {
        Ok(())
    }
    pub fn set_occluded_rects(_rects: Vec<UiRect>) {}
    pub fn set_document(_width: u32, _height: u32, _show_checkerboard: bool) {}
    pub fn set_appearance(_matte_rgba: [f32; 4], _show_checkerboard: bool) {}
    pub fn set_display_config(_config: CompositorDisplayConfig) {}
    pub fn invalidate_compositor_cache() {}
    pub fn render_document_flattened(
        _doc_id: Option<String>,
        _options: FlattenOptions,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn render_layer_thumbnail_gpu(
        _doc_id: Option<String>,
        _layer_id: String,
        _max_dim: u32,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn set_camera(_camera: CameraState) {}
    pub fn set_cursor(_config: CursorConfig) {}
    pub fn set_brush(_params: BrushParams) {}
    pub fn set_full_brush(_config: NativeBrushConfig) {}
    pub fn clean_dirty_brush(_preset_key: Option<String>) {}
    pub fn set_mask_mode(_enabled: bool) {}
    pub fn render_brush_preview(
        _brush: NativeBrushConfig,
        _width: u32,
        _height: u32,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn render_scratchpad_preview(
        _brush: NativeBrushConfig,
        _strokes: Vec<ScratchpadStrokeInput>,
        _width: u32,
        _height: u32,
    ) -> Result<(u32, u32, Vec<u8>), String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn set_pressure_curve(_curve: GlobalPressureCurve) {}
    pub fn set_rulers(
        _straight: Option<StraightRulerConfig>,
        _perspective: Option<PerspectiveRulerConfig>,
    ) {
    }
    pub fn upload_brush_texture(
        _hash: String,
        _kind: BrushTextureKind,
        _is_png: bool,
        _width: u32,
        _height: u32,
        _data: Vec<u8>,
    ) {
    }
    pub fn set_policy(_policy: InteractionPolicy) {}
    pub fn set_collab_points_enabled(_enabled: bool) {}
    pub fn clear_canvas() {}
    pub fn sync_active_document() {
        crate::raster_journal::notify_history_changed();
    }
    pub fn set_vram_budget(_budget_bytes: u64) {}
    pub fn flush_gpu_pool() {}
    pub fn gpu_pool_stats() -> GpuPoolStats {
        GpuPoolStats::default()
    }
    pub fn get_diagnostics() -> EngineDiagnostics {
        EngineDiagnostics::default()
    }
    pub fn retouch_session() -> Arc<Mutex<RetouchSession>> {
        Arc::clone(&FALLBACK_RETOUCH_SESSION)
    }
    pub fn liquify_begin(
        _multi_layer: bool,
        _layer_ids: Option<Vec<String>>,
    ) -> Result<Vec<String>, String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn liquify_step(_step: LiquifyStepParams) -> Result<RectI32, String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn liquify_commit() -> Result<(Vec<String>, RectI32), String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn liquify_cancel() {}
    pub fn transform_begin(
        _mode: TransformMode,
        _layer_ids: Option<Vec<String>>,
    ) -> Result<TransformSessionSnapshot, String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn transform_update(
        _payload: TransformUpdatePayload,
    ) -> Result<TransformSessionSnapshot, String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn transform_switch_mode(
        _next_mode: TransformMode,
    ) -> Result<TransformSessionSnapshot, String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn transform_commit() -> Result<TransformCommitResult, String> {
        Err("Native DX12 engine is not supported on this OS".to_string())
    }
    pub fn transform_cancel() {}
    pub fn set_tool_preview_rgba8(
        _rect: RectI32,
        _rgba: Vec<u8>,
        _opacity: f32,
        _replaced_layer_id: Option<String>,
    ) {
    }
    pub fn clear_tool_preview() {}
    pub fn remote_stroke_start(_params: RemoteStrokeStartParams) {}
    pub fn remote_stroke_chunk(
        _peer_id: String,
        _stroke_id: String,
        _points: Vec<RemoteStrokePoint>,
    ) {
    }
    pub fn remote_stroke_finish(_peer_id: String, _stroke_id: String, _expected_tiles: u32) {}
    pub fn remote_stroke_dispose(_peer_id: String, _stroke_id: String) {}
    pub fn remote_peer_dispose(_peer_id: String) {}
    pub fn remote_notify_tile_delta(_layer_id: String) {}
}

#[allow(unused_imports)]
pub use win_host::{
    clean_dirty_brush, clear_canvas, clear_tool_preview, flush_gpu_pool, get_diagnostics,
    gpu_pool_stats, init_for_main_window, invalidate_compositor_cache, is_active, is_stroke_active,
    liquify_begin, liquify_cancel, liquify_commit, liquify_step, remote_notify_tile_delta,
    remote_peer_dispose, remote_stroke_chunk, remote_stroke_dispose, remote_stroke_finish,
    remote_stroke_start, render_brush_preview, render_document_flattened,
    render_layer_thumbnail_gpu, render_scratchpad_preview, retouch_session, set_appearance, set_brush, set_camera,
    set_collab_points_enabled, set_cursor, set_display_config, set_document, set_full_brush,
    set_mask_mode, set_occluded_rects, set_policy, set_pressure_curve, set_rulers,
    set_tool_preview_rgba8, set_viewport, set_vram_budget, shutdown, sync_active_document,
    transform_begin, transform_cancel, transform_commit, transform_switch_mode, transform_update,
    upload_brush_texture,
};