Skip to content

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

22.6 KB
Raw Blame
//! Windows DirectComposition visual host for InkStudio's hybrid DX12 + WebView2 layering.
//!
//! # Visual Tree Architecture (`wry 0.57.3` / `tauri 2.12.7` on Windows 10/11)
//!
//! `wry` creates a child container HWND (`WRY_WEBVIEW`) inside the top-level `main_hwnd`
//! and hosts WebView2 via `ICoreWebView2Controller`. When `"transparent": true` is enabled
//! on `main`, `tao` activates DWM alpha composition on `main_hwnd` and `wry` sets
//! `COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 }` on the WebView2 controller.
//!
//! We bind an `IDCompositionTarget` directly to `main_hwnd` with `topmost = false`:
//! - **Bottom visual (`canvas_visual`):** Receives `wgpu` DX12 flip-model composition
//!   swapchain (`CreateSwapChainForComposition`, `DXGI_SWAP_EFFECT_FLIP_DISCARD`,
//!   `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT`, `SetMaximumFrameLatency(1)`),
//!   offset and clipped in physical client pixels to the transparent `<main>` viewport cutout.
//! - **Top layer (WebView2 UI):** Because `CreateTargetForHwnd(main_hwnd, false)` places
//!   our visual tree strictly beneath child HWNDs (`WRY_WEBVIEW`) in DWM, the transparent
//!   WebView2 UI renders cleanly on top with ZERO opaque canvas child HWND and ZERO clipping
//!   of dropdowns, tooltips, floating dock panels, modals, or `FloatingBrushPill`.
//! - If a future `wry` switches to `ICoreWebView2CompositionController`, `configure_webview2_controller`
//!   also opportunistically attaches a top `webview_visual` above `canvas_visual` via
//!   `SetRootVisualTarget`.
//!
//! # Lifecycle & Drop Order Invariant
//! `EngineHandle::shutdown()` MUST join the render thread (dropping `wgpu::Surface` and the
//! DXGI swapchain) strictly BEFORE `DCompHost::clear_content()` and dropping `DCompHost`.

#[cfg(target_os = "windows")]
mod imp {
    use std::ffi::c_void;
    use std::sync::Mutex;
    use webview2_com::Microsoft::Web::WebView2::Win32::{
        ICoreWebView2CompositionController, ICoreWebView2Controller, ICoreWebView2Controller2,
        COREWEBVIEW2_COLOR,
    };
    use windows::Win32::Foundation::HWND;
    use windows::Win32::Graphics::Direct2D::Common::D2D_RECT_F;
    use windows::Win32::Graphics::DirectComposition::{
        DCompositionCreateDevice2, IDCompositionDevice, IDCompositionTarget, IDCompositionVisual,
        DCOMPOSITION_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, DCOMPOSITION_BORDER_MODE_HARD,
    };
    use windows_core::{IUnknown, Interface};

    struct DCompInner {
        device: IDCompositionDevice,
        _target: IDCompositionTarget,
        root_visual: IDCompositionVisual,
        canvas_visual: IDCompositionVisual,
        webview_visual: Option<IDCompositionVisual>,
        last_rect: (i32, i32, u32, u32, bool),
        staged_rect: Option<(i32, i32, u32, u32, bool)>,
    }

    pub struct DCompHost {
        inner: Mutex<DCompInner>,
    }

    // SAFETY: DirectComposition COM interfaces are agile/MTA-safe when access is serialized.
    // Every method acquires `self.inner: Mutex<DCompInner>` before touching any COM pointer.
    unsafe impl Send for DCompHost {}
    unsafe impl Sync for DCompHost {}

    impl DCompHost {
        /// Creates a DirectComposition device, non-topmost target bound to `main_hwnd`,
        /// and bottom `canvas_visual` ready to receive `wgpu`'s DX12 composition swapchain.
        pub fn new(main_hwnd_raw: isize) -> Result<Self, String> {
            if main_hwnd_raw == 0 {
                return Err("Cannot initialize DirectComposition with null HWND".to_string());
            }
            let hwnd = HWND(main_hwnd_raw as *mut c_void);

            unsafe {
                let device: IDCompositionDevice =
                    DCompositionCreateDevice2(None::<&IUnknown>).map_err(|e| {
                        format!("DCompositionCreateDevice2 failed: {e}")
                    })?;

                // `topmost = false` layers the DirectComposition tree strictly BENEATH
                // child HWNDs (`WRY_WEBVIEW` / WebView2) so transparent UI chrome, modals,
                // tooltips, and floating panels composite cleanly on top without clipping.
                let target = device
                    .CreateTargetForHwnd(hwnd, false)
                    .map_err(|e| format!("IDCompositionDevice::CreateTargetForHwnd failed: {e}"))?;

                let root_visual = device
                    .CreateVisual()
                    .map_err(|e| format!("CreateVisual(root) failed: {e}"))?;
                let canvas_visual = device
                    .CreateVisual()
                    .map_err(|e| format!("CreateVisual(canvas) failed: {e}"))?;

                target
                    .SetRoot(&root_visual)
                    .map_err(|e| format!("IDCompositionTarget::SetRoot failed: {e}"))?;
                root_visual
                    .AddVisual(&canvas_visual, false, None)
                    .map_err(|e| format!("AddVisual(canvas) failed: {e}"))?;

                // Enforce hard clip edges and 1:1 physical-pixel presentation with zero
                // soft-border antialiasing seams or bilinear resampling blur.
                let _ = canvas_visual.SetBorderMode(DCOMPOSITION_BORDER_MODE_HARD);
                let _ = canvas_visual.SetBitmapInterpolationMode(
                    DCOMPOSITION_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
                );

                // Start hidden/clipped to 0x0 until React reports an active document viewport.
                let empty_clip = D2D_RECT_F {
                    left: 0.0,
                    top: 0.0,
                    right: 0.0,
                    bottom: 0.0,
                };
                let _ = canvas_visual.SetOffsetX2(0.0);
                let _ = canvas_visual.SetOffsetY2(0.0);
                let _ = canvas_visual.SetClip2(&empty_clip);
                device
                    .Commit()
                    .map_err(|e| format!("Initial IDCompositionDevice::Commit failed: {e}"))?;

                Ok(Self {
                    inner: Mutex::new(DCompInner {
                        device,
                        _target: target,
                        root_visual,
                        canvas_visual,
                        webview_visual: None,
                        last_rect: (0, 0, 0, 0, false),
                        staged_rect: None,
                    }),
                })
            }
        }

        /// Enforces transparent WebView2 default background (`ARGB = 0,0,0,0`) and, if the
        /// WebView2 controller exposes `ICoreWebView2CompositionController`, attaches a top
        /// visual strictly above `canvas_visual`.
        pub fn configure_webview2_controller(
            &self,
            controller: &ICoreWebView2Controller,
        ) -> String {
            unsafe {
                if let Ok(controller2) = controller.cast::<ICoreWebView2Controller2>() {
                    let _ = controller2.SetDefaultBackgroundColor(COREWEBVIEW2_COLOR {
                        A: 0,
                        R: 0,
                        G: 0,
                        B: 0,
                    });
                }

                // Future-proof: if wry ever uses ICoreWebView2CompositionController, place
                // WebView2's visual directly above canvas_visual in our single visual tree.
                if let Ok(comp_controller) = controller.cast::<ICoreWebView2CompositionController>()
                {
                    if let Ok(mut guard) = self.inner.lock() {
                        if guard.webview_visual.is_none() {
                            if let Ok(wv_visual) = guard.device.CreateVisual() {
                                let canvas_ref = guard.canvas_visual.clone();
                                if guard
                                    .root_visual
                                    .AddVisual(&wv_visual, true, Some(&canvas_ref))
                                    .is_ok()
                                    && comp_controller.SetRootVisualTarget(&wv_visual).is_ok()
                                {
                                    let _ = guard.device.Commit();
                                    guard.webview_visual = Some(wv_visual);
                                    return "DirectComposition (Dual Visual)".to_string();
                                }
                            }
                        }
                    }
                }
            }

            "DirectComposition (Underlay)".to_string()
        }

        /// Returns the raw `IDCompositionVisual` COM pointer for `wgpu`'s
        /// `SurfaceTargetUnsafe::CompositionVisual`.
        ///
        /// `wgpu-hal` calls `IDCompositionVisual::from_raw_borrowed` + `.to_owned()` (AddRef)
        /// immediately during `create_surface_unsafe`.
        pub fn canvas_visual_raw(&self) -> Result<*mut c_void, String> {
            let guard = self
                .inner
                .lock()
                .map_err(|_| "DirectComposition host mutex poisoned".to_string())?;
            Ok(guard.canvas_visual.as_raw())
        }

        /// Stages a canvas viewport offset/clip update to be applied and committed atomically
        /// on the render thread when `commit()` runs after `wgpu::Surface::configure()` / frame
        /// presentation, so the DirectComposition clip rect never updates ahead of DXGI swapchain
        /// buffers. Hiding (`visible == false` or empty rect) is committed immediately.
        pub fn stage_canvas_viewport(
            &self,
            x_px: i32,
            y_px: i32,
            width_px: u32,
            height_px: u32,
            visible: bool,
        ) -> Result<(), String> {
            if !visible || width_px == 0 || height_px == 0 {
                return self.set_canvas_viewport(0, 0, 0, 0, false);
            }
            let mut guard = self
                .inner
                .lock()
                .map_err(|_| "DirectComposition host mutex poisoned".to_string())?;
            let next = (x_px, y_px, width_px, height_px, visible);
            if guard.last_rect == next {
                guard.staged_rect = None;
                return Ok(());
            }
            guard.staged_rect = Some(next);
            Ok(())
        }

        /// Positions and clips `canvas_visual` to the physical client-pixel viewport cutout
        /// and commits the DirectComposition batch immediately.
        pub fn set_canvas_viewport(
            &self,
            x_px: i32,
            y_px: i32,
            width_px: u32,
            height_px: u32,
            visible: bool,
        ) -> Result<(), String> {
            let mut guard = self
                .inner
                .lock()
                .map_err(|_| "DirectComposition host mutex poisoned".to_string())?;
            guard.staged_rect = None;

            let next = (x_px, y_px, width_px, height_px, visible);
            if guard.last_rect == next {
                return Ok(());
            }

            Self::apply_rect_locked(&mut guard, next)?;
            unsafe {
                guard
                    .device
                    .Commit()
                    .map_err(|e| format!("IDCompositionDevice::Commit failed: {e}"))?;
            }
            Ok(())
        }

        fn apply_rect_locked(
            guard: &mut DCompInner,
            next: (i32, i32, u32, u32, bool),
        ) -> Result<(), String> {
            let (x_px, y_px, width_px, height_px, visible) = next;
            let clip = if visible && width_px > 0 && height_px > 0 {
                D2D_RECT_F {
                    left: 0.0,
                    top: 0.0,
                    right: width_px as f32,
                    bottom: height_px as f32,
                }
            } else {
                D2D_RECT_F {
                    left: 0.0,
                    top: 0.0,
                    right: 0.0,
                    bottom: 0.0,
                }
            };

            unsafe {
                guard
                    .canvas_visual
                    .SetOffsetX2(x_px as f32)
                    .map_err(|e| format!("SetOffsetX2 failed: {e}"))?;
                guard
                    .canvas_visual
                    .SetOffsetY2(y_px as f32)
                    .map_err(|e| format!("SetOffsetY2 failed: {e}"))?;
                guard
                    .canvas_visual
                    .SetClip2(&clip)
                    .map_err(|e| format!("SetClip2 failed: {e}"))?;
            }
            guard.last_rect = next;
            Ok(())
        }

        /// Applies any staged viewport offset/clip and commits pending DirectComposition updates
        /// (REQUIRED immediately after `wgpu::Surface::configure`, because `wgpu-hal` calls
        /// `IDCompositionVisual::SetContent` without committing the caller's `IDCompositionDevice`).
        pub fn commit(&self) {
            if let Ok(mut guard) = self.inner.lock() {
                if let Some(staged) = guard.staged_rect.take() {
                    if guard.last_rect != staged {
                        let _ = Self::apply_rect_locked(&mut guard, staged);
                    }
                }
                unsafe {
                    let _ = guard.device.Commit();
                }
            }
        }

        /// Detaches swapchain content from `canvas_visual` and commits.
        /// Call strictly AFTER `EngineHandle::shutdown()` joins the GPU thread.
        pub fn clear_content(&self) {
            if let Ok(mut guard) = self.inner.lock() {
                unsafe {
                    let _ = guard.canvas_visual.SetContent(None::<&IUnknown>);
                    let empty_clip = D2D_RECT_F {
                        left: 0.0,
                        top: 0.0,
                        right: 0.0,
                        bottom: 0.0,
                    };
                    let _ = guard.canvas_visual.SetClip2(&empty_clip);
                    let _ = guard.device.Commit();
                }
                guard.last_rect = (0, 0, 0, 0, false);
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use ink_engine::{
            CameraState, EngineCommand, EngineConfig, EngineHandle, NativeInputSample,
            SurfaceTarget, ViewportRect,
        };
        use std::sync::Arc;
        use std::time::{Duration, Instant};
        use windows_sys::Win32::UI::WindowsAndMessaging::{
            CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, WNDCLASSW, WS_POPUP,
        };

        #[test]
        fn test_direct_composition_wgpu_dx12_swapchain_configure_and_present() {
            unsafe {
                let class_name: Vec<u16> =
                    "InkStudioDCompTestWindow\0".encode_utf16().collect();
                let wc = WNDCLASSW {
                    style: 0,
                    lpfnWndProc: Some(DefWindowProcW),
                    cbClsExtra: 0,
                    cbWndExtra: 0,
                    hInstance: std::ptr::null_mut(),
                    hIcon: std::ptr::null_mut(),
                    hCursor: std::ptr::null_mut(),
                    hbrBackground: std::ptr::null_mut(),
                    lpszMenuName: std::ptr::null(),
                    lpszClassName: class_name.as_ptr(),
                };
                RegisterClassW(&wc);

                // Create a hidden top-level WS_POPUP window (never shown on screen) to exercise
                // real IDCompositionTarget + DXGI CreateSwapChainForComposition + latency=1.
                let hwnd = CreateWindowExW(
                    0,
                    class_name.as_ptr(),
                    class_name.as_ptr(),
                    WS_POPUP,
                    0,
                    0,
                    320,
                    240,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    std::ptr::null(),
                );
                assert!(!hwnd.is_null(), "CreateWindowExW for test window failed");

                let dcomp = Arc::new(
                    DCompHost::new(hwnd as isize).expect("DCompHost::new failed on test HWND"),
                );
                let visual_raw = dcomp.canvas_visual_raw().expect("canvas_visual_raw");
                let dcomp_commit = Arc::clone(&dcomp);
                let target = SurfaceTarget::from_composition_visual(
                    visual_raw,
                    Arc::new(move || {
                        dcomp_commit.commit();
                    }),
                );

                let spawned = EngineHandle::spawn(
                    target,
                    EngineConfig {
                        doc_width: 512,
                        doc_height: 512,
                        show_checkerboard: true,
                        matte_color: [0.086, 0.086, 0.086, 1.0],
                        ..Default::default()
                    },
                );

                let (handle, mut producers) = match spawned {
                    Ok(pair) => pair,
                    Err(err) => {
                        eprintln!(
                            "Skipping live DirectComposition DX12 test (no DX12 adapter): {err}"
                        );
                        dcomp.clear_content();
                        drop(dcomp);
                        DestroyWindow(hwnd);
                        return;
                    }
                };

                dcomp
                    .set_canvas_viewport(16, 16, 288, 208, true)
                    .expect("set_canvas_viewport");
                handle.send_command(EngineCommand::SetVisible(true));
                handle.send_command(EngineCommand::SetViewport(ViewportRect {
                    x_px: 16,
                    y_px: 16,
                    width_px: 288,
                    height_px: 208,
                    dpr: 1.0,
                }));
                handle.send_command(EngineCommand::SetCamera(CameraState {
                    pan_x: 144.0,
                    pan_y: 104.0,
                    zoom: 0.4,
                    rotation: 0.0,
                    flip_x: false,
                    flip_y: false,
                }));

                let now = ink_engine::clock::now_ms();
                producers.wintab.push_batch(&[
                    NativeInputSample {
                        phys_x: 100.0,
                        phys_y: 100.0,
                        pressure: 0.5,
                        tilt_x: 0.0,
                        tilt_y: 0.0,
                        twist: 0.0,
                        timestamp_ms: now,
                        buttons: 1,
                        phase: 1,
                        backend: 1,
                    },
                    NativeInputSample {
                        phys_x: 200.0,
                        phys_y: 140.0,
                        pressure: 0.85,
                        tilt_x: 0.0,
                        tilt_y: 0.0,
                        twist: 0.0,
                        timestamp_ms: now + 4.0,
                        buttons: 1,
                        phase: 2,
                        backend: 1,
                    },
                    NativeInputSample {
                        phys_x: 200.0,
                        phys_y: 140.0,
                        pressure: 0.0,
                        tilt_x: 0.0,
                        tilt_y: 0.0,
                        twist: 0.0,
                        timestamp_ms: now + 8.0,
                        buttons: 0,
                        phase: 3,
                        backend: 1,
                    },
                ]);

                let deadline = Instant::now() + Duration::from_secs(4);
                while Instant::now() < deadline {
                    if handle.diagnostics().total_frames_rendered >= 1 {
                        break;
                    }
                    std::thread::sleep(Duration::from_millis(10));
                }

                let diag = handle.diagnostics();
                assert!(diag.ready, "DX12 DirectComposition engine should be ready");
                assert_eq!(diag.backend, "DX12");
                assert_eq!(diag.max_frame_latency, 1);
                assert!(
                    diag.total_frames_rendered >= 1,
                    "Expected at least 1 presented DirectComposition frame, got {}",
                    diag.total_frames_rendered
                );

                // Exercise DPI changes (1.0, 1.25, 1.5, 2.0), resize, 0x0 minimize guard,
                // restore, and hide/show transitions without panic or device loss.
                let transitions: &[(i32, i32, u32, u32, f32, bool)] = &[
                    (16, 16, 288, 208, 1.25, true),
                    (24, 18, 260, 190, 1.5, true),
                    (0, 0, 0, 0, 1.5, false),       // Minimize / 0x0 guard
                    (20, 12, 300, 220, 2.0, true),  // Restore at 2.0x DPR
                    (20, 12, 300, 220, 1.0, false), // WelcomeScreen / Home hide
                    (12, 12, 296, 216, 1.0, true),  // Return to workspace
                ];
                let frames_before = handle.diagnostics().total_frames_rendered;
                for &(x, y, w, h, dpr, vis) in transitions {
                    dcomp
                        .set_canvas_viewport(x, y, w, h, vis)
                        .expect("set_canvas_viewport transition");
                    handle.send_command(EngineCommand::SetViewport(ViewportRect {
                        x_px: x,
                        y_px: y,
                        width_px: w,
                        height_px: h,
                        dpr,
                    }));
                    handle.send_command(EngineCommand::SetVisible(vis));
                    std::thread::sleep(Duration::from_millis(25));
                }
                let settle_deadline = Instant::now() + Duration::from_secs(3);
                while Instant::now() < settle_deadline {
                    let d = handle.diagnostics();
                    if d.total_frames_rendered > frames_before
                        && d.swapchain_width == 296
                        && d.swapchain_height == 216
                    {
                        break;
                    }
                    std::thread::sleep(Duration::from_millis(10));
                }
                let after = handle.diagnostics();
                assert_eq!(after.device_lost_recoveries, 0);
                assert_eq!(after.swapchain_width, 296);
                assert_eq!(after.swapchain_height, 216);

                // Verify strict ordered shutdown: engine stops & drops Surface BEFORE DCompHost drops.
                handle.shutdown();
                assert!(!handle.is_running());
                dcomp.clear_content();
                drop(dcomp);
                DestroyWindow(hwnd);
            }
        }
    }
}

#[cfg(target_os = "windows")]
pub use imp::DCompHost;