lingxia-webview 0.17.0

WebView abstraction layer for LingXia framework (Android, iOS, HarmonyOS, Windows)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! WebView2 composition hosting.
//!
//! Each webview owns a `LingXiaWebViewSurface` child HWND created on its
//! dedicated UI thread, with a DirectComposition device/target/visual tree
//! bound to it; WebView2 renders into the tree through `RootVisualTarget`.
//! Reparenting moves the child HWND with Win32 `SetParent` — the DComp target
//! travels with the window, so surfaces keep their frames across host
//! switches — and the root visual's rectangle clip rounds whichever workspace
//! corners the shell assigns. Creation falls back to the windowed controller
//! when the runtime or the DComp setup cannot deliver composition.

use super::*;

mod dcomp;
mod dragdrop;
mod pointer;
mod surface_window;

use dcomp::DcompTree;
pub use dcomp::{CompositionSurfacePixels, IslandVideoFrame, IslandVisualSpec};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

type IslandPointerFilter = Arc<dyn Fn(&str, IslandPointerPhase, f32, f32) -> bool + Send + Sync>;

static ISLAND_VISUALS: OnceLock<Mutex<HashMap<String, Vec<IslandVisualSpec>>>> = OnceLock::new();
static SURFACE_WEBTAGS: OnceLock<Mutex<HashMap<isize, String>>> = OnceLock::new();
static ISLAND_POINTER_FILTER: OnceLock<Mutex<Option<IslandPointerFilter>>> = OnceLock::new();

/// High-word marker used by LingXia's deterministic `PostMessage` input.
/// Synthetic moves must not arm `TrackMouseEvent`, whose hover state follows
/// the unrelated physical cursor and would immediately emit `WM_MOUSELEAVE`.
pub const SYNTHETIC_MOUSE_WPARAM_MARKER: usize = 0x4c58_0000;

fn island_visuals() -> &'static Mutex<HashMap<String, Vec<IslandVisualSpec>>> {
    ISLAND_VISUALS.get_or_init(|| Mutex::new(HashMap::new()))
}

fn surface_webtags() -> &'static Mutex<HashMap<isize, String>> {
    SURFACE_WEBTAGS.get_or_init(|| Mutex::new(HashMap::new()))
}

fn island_pointer_filter() -> &'static Mutex<Option<IslandPointerFilter>> {
    ISLAND_POINTER_FILTER.get_or_init(|| Mutex::new(None))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IslandPointerPhase {
    Down,
    Move,
    Up,
    Cancel,
}

pub fn register_surface_webtag(hwnd: isize, webtag: &str) {
    if webtag.is_empty() {
        return;
    }
    if let Ok(mut tags) = surface_webtags().lock() {
        tags.insert(hwnd, webtag.to_string());
    }
}

pub fn unregister_surface_webtag(hwnd: isize) {
    if let Ok(mut tags) = surface_webtags().lock() {
        tags.remove(&hwnd);
    }
}

pub fn set_island_pointer_filter(
    filter: impl Fn(&str, IslandPointerPhase, f32, f32) -> bool + Send + Sync + 'static,
) {
    if let Ok(mut slot) = island_pointer_filter().lock() {
        *slot = Some(Arc::new(filter));
    }
}

pub fn consume_island_pointer(
    hwnd: windows::Win32::Foundation::HWND,
    phase: IslandPointerPhase,
    x: f32,
    y: f32,
) -> bool {
    let tag = surface_webtags()
        .lock()
        .ok()
        .and_then(|tags| tags.get(&(hwnd.0 as isize)).cloned());
    let Some(tag) = tag else {
        return false;
    };
    let filter = island_pointer_filter()
        .lock()
        .ok()
        .and_then(|slot| slot.clone());
    filter.is_some_and(|filter| filter(&tag, phase, x, y))
}

/// Stores island visuals for the next [`CompositionSurface::set_geometry`]
/// commit. No DComp calls — apply happens on WebView2's own composition pass.
pub fn queue_island_visuals(webtag_key: &str, visuals: Vec<IslandVisualSpec>) {
    if let Ok(mut queued) = island_visuals().lock() {
        queued.insert(webtag_key.to_string(), visuals);
    }
}

pub fn queued_island_visuals(webtag_key: &str) -> Vec<IslandVisualSpec> {
    island_visuals()
        .lock()
        .ok()
        .and_then(|queued| queued.get(webtag_key).cloned())
        .unwrap_or_default()
}

/// How a webview's controller is attached to the host window tree.
pub(crate) enum HostingMode {
    /// Classic windowed `ICoreWebView2Controller`: WebView2 owns a
    /// rectangular child HWND positioned in host client coordinates.
    Windowed,
    /// Composition-hosted controller rendering into [`CompositionSurface`].
    Composition(Box<CompositionSurface>),
}

pub(crate) struct CompositionSurface {
    /// The `LingXiaWebViewSurface` child window. Created on this webview's
    /// UI thread, but parented into foreign host windows — if such a host is
    /// destroyed, the surface dies with it and is recreated on the next
    /// reparent (see [`CompositionSurface::ensure_alive`]). Holds the
    /// input-forwarding state in its window user data.
    pub(crate) hwnd: HWND,
    env3: ICoreWebView2Environment3,
    controller: ICoreWebView2CompositionController,
    dcomp: DcompTree,
    /// Controller-level event subscriptions owned by the current surface
    /// window; removed before a recreation re-subscribes.
    input_tokens: surface_window::InputSubscriptions,
    /// The host the surface currently lives under, so a recreation from the
    /// geometry/visibility paths knows where to rebuild.
    parent: HWND,
    /// Last applied per-corner clip radii `[tl, tr, br, bl]`, physical px.
    radii: [i32; 4],
    /// Last applied wedge backdrop color (`0xAARGB`; alpha 0 = no wedges).
    corner_color: u32,
    /// Last applied bounds/visibility, replayed after a recreation.
    pub(crate) bounds: RECT,
    visible: bool,
    /// WebTag key used to look up queued island visuals on each geometry commit.
    webtag_key: String,
}

static COMPOSITION_HOSTING: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(true);

/// Programmatic default for WebView2 composition hosting (on unless changed).
/// The `LINGXIA_WEBVIEW_COMPOSITION` env var (`0|false|off` / `1|true|on`)
/// overrides the default per process.
pub fn set_webview_composition_hosting(enabled: bool) {
    COMPOSITION_HOSTING.store(enabled, std::sync::atomic::Ordering::Relaxed);
}

/// True when new webviews will attempt composition hosting. Host chrome
/// keys workarounds off this — e.g. the device frame drops its corner-mask
/// overlay and region clip when the composition corner wedges replace them.
pub fn webview_composition_hosting_enabled() -> bool {
    composition_hosting_enabled()
}

fn composition_hosting_enabled() -> bool {
    let configured = || COMPOSITION_HOSTING.load(std::sync::atomic::Ordering::Relaxed);
    match std::env::var("LINGXIA_WEBVIEW_COMPOSITION") {
        Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
            "0" | "false" | "off" => false,
            "1" | "true" | "on" => true,
            _ => configured(),
        },
        Err(_) => configured(),
    }
}

/// Creates the controller for the configured hosting mode. A composition
/// failure (old WebView2 runtime, DComp setup error) downgrades to the
/// windowed controller so webview creation itself never regresses.
pub(crate) fn create_hosting_controller(
    env: &ICoreWebView2Environment,
    parent: HWND,
) -> StdResult<(ICoreWebView2Controller, HostingMode)> {
    if composition_hosting_enabled() {
        match create_composition_surface(env, parent) {
            Ok((controller, surface)) => {
                return Ok((controller, HostingMode::Composition(surface)));
            }
            Err(err) => {
                log::warn!("composition hosting unavailable; using windowed WebView2: {err}");
            }
        }
    }
    Ok((create_controller(env, parent)?, HostingMode::Windowed))
}

fn create_composition_surface(
    env: &ICoreWebView2Environment,
    parent: HWND,
) -> StdResult<(ICoreWebView2Controller, Box<CompositionSurface>)> {
    let env3: ICoreWebView2Environment3 = env.cast().map_err(|err| {
        WebViewError::WebView(format!("WebView2 runtime lacks composition hosting: {err}"))
    })?;
    let mut bounds = RECT::default();
    unsafe {
        WindowsAndMessaging::GetClientRect(parent, &mut bounds)
            .map_err(|err| WebViewError::WebView(format!("GetClientRect failed: {err}")))?;
    }
    let hwnd = surface_window::create_surface_window(parent, bounds)?;
    let assembled = (|| {
        let dcomp = DcompTree::new(hwnd)?;
        let controller = create_composition_controller(&env3, hwnd)?;
        let input_tokens = attach_surface(hwnd, &dcomp, &env3, &controller)?;
        let base: ICoreWebView2Controller = controller.cast().map_err(|err| {
            WebViewError::WebView(format!("composition controller cast failed: {err}"))
        })?;
        Ok((
            base,
            Box::new(CompositionSurface {
                hwnd,
                env3,
                controller,
                dcomp,
                input_tokens,
                parent,
                radii: [0; 4],
                corner_color: 0,
                bounds,
                visible: false,
                webtag_key: String::new(),
            }),
        ))
    })();
    if assembled.is_err() {
        unsafe {
            let _ = WindowsAndMessaging::DestroyWindow(hwnd);
        }
    }
    assembled
}

/// Binds a surface window to the controller: visual target, input
/// forwarding, drag-and-drop. Shared by creation and post-teardown
/// recreation.
fn attach_surface(
    hwnd: HWND,
    dcomp: &DcompTree,
    env3: &ICoreWebView2Environment3,
    controller: &ICoreWebView2CompositionController,
) -> StdResult<surface_window::InputSubscriptions> {
    unsafe {
        controller
            .SetRootVisualTarget(dcomp.webview_visual())
            .map_err(|err| WebViewError::WebView(format!("SetRootVisualTarget failed: {err}")))?;
    }
    let base: ICoreWebView2Controller = controller.cast().map_err(|err| {
        WebViewError::WebView(format!("composition controller cast failed: {err}"))
    })?;
    let tokens = surface_window::attach_input(hwnd, env3, controller, &base);
    dragdrop::register_drop_target(hwnd, controller);
    Ok(tokens)
}

fn create_composition_controller(
    env3: &ICoreWebView2Environment3,
    hwnd: HWND,
) -> StdResult<ICoreWebView2CompositionController> {
    let env3 = env3.clone();
    let (tx, rx) = mpsc::channel();

    CreateCoreWebView2CompositionControllerCompletedHandler::wait_for_async_operation(
        Box::new(move |handler| unsafe {
            env3.CreateCoreWebView2CompositionController(hwnd, &handler)
                .map_err(webview2_com::Error::WindowsError)
        }),
        Box::new(move |result, controller| {
            result?;
            tx.send(controller.ok_or_else(|| windows::core::Error::from(E_POINTER)))
                .map_err(|_| windows::core::Error::from(E_POINTER))?;
            Ok(())
        }),
    )
    .map_err(map_webview2_error)?;

    rx.recv()
        .map_err(|_| {
            WebViewError::WebView("Composition controller callback channel failed".to_string())
        })?
        .map_err(|err| {
            WebViewError::WebView(format!("Composition controller creation failed: {err}"))
        })
}

impl CompositionSurface {
    /// Recreates the surface window under `parent` when the previous one was
    /// destroyed (its former host window was torn down — DestroyWindow kills
    /// reparented children), replaying the last applied geometry and
    /// visibility. Returns `true` when a recreation happened.
    fn ensure_alive(&mut self, parent: HWND, base: &ICoreWebView2Controller) -> StdResult<bool> {
        if unsafe { WindowsAndMessaging::IsWindow(Some(self.hwnd)).as_bool() } {
            return Ok(false);
        }
        log::info!("composition surface window died with its former host; recreating");
        // The dead window's controller-level subscriptions outlive it; drop
        // them before attach_surface re-subscribes, or handler chains grow
        // with every recovery.
        surface_window::detach_input(&self.controller, base, self.input_tokens);
        self.input_tokens = surface_window::InputSubscriptions::default();
        // The composition controller still references the visual target owned
        // by the dead child window. WebView2 rejects a replacement target until
        // that stale tree is explicitly disconnected.
        unsafe {
            self.controller
                .SetRootVisualTarget(None::<&windows::core::IUnknown>)
                .map_err(|err| {
                    WebViewError::WebView(format!(
                        "disconnecting stale RootVisualTarget failed: {err}"
                    ))
                })?;
        }
        let hwnd = surface_window::create_surface_window(parent, self.bounds)?;
        let rebuilt = (|| {
            let dcomp = DcompTree::new(hwnd)?;
            let tokens = attach_surface(hwnd, &dcomp, &self.env3, &self.controller)?;
            Ok((dcomp, tokens))
        })();
        let (dcomp, tokens) = match rebuilt {
            Ok(parts) => parts,
            Err(err) => {
                unsafe {
                    let _ = WindowsAndMessaging::DestroyWindow(hwnd);
                }
                return Err(err);
            }
        };
        self.hwnd = hwnd;
        self.dcomp = dcomp;
        self.input_tokens = tokens;
        self.parent = parent;
        let bounds = self.bounds;
        self.set_geometry(base, bounds, None, &self.webtag_key.clone())?;
        if self.visible {
            self.set_visible(base, true)?;
        }
        Ok(true)
    }

    /// Positions the surface window at `bounds` (host client coordinates),
    /// sizes the controller to match, and re-applies the corner clip and
    /// wedges — one commit, so bounds and corners never present out of sync.
    /// `corners` of `None` keeps the last applied style.
    pub(crate) fn set_geometry(
        &mut self,
        base: &ICoreWebView2Controller,
        bounds: RECT,
        corners: Option<([i32; 4], u32)>,
        webtag_key: &str,
    ) -> StdResult<()> {
        // Self-heal here too: the main surface's own parent window never gets
        // a reparent command, so a surface killed elsewhere would otherwise
        // stay dead when re-shown standalone.
        if !unsafe { WindowsAndMessaging::IsWindow(Some(self.hwnd)).as_bool() } {
            self.bounds = bounds;
            if let Some((radii, corner_color)) = corners {
                self.radii = radii;
                self.corner_color = corner_color;
            }
            let parent = self.parent;
            if !webtag_key.is_empty() {
                self.webtag_key = webtag_key.to_string();
            }
            return self.ensure_alive(parent, base).map(|_| ());
        }
        if !webtag_key.is_empty() {
            self.webtag_key = webtag_key.to_string();
        }
        register_surface_webtag(self.hwnd.0 as isize, &self.webtag_key);
        let (radii, corner_color) = corners.unwrap_or((self.radii, self.corner_color));
        let width = (bounds.right - bounds.left).max(0);
        let height = (bounds.bottom - bounds.top).max(0);
        unsafe {
            WindowsAndMessaging::SetWindowPos(
                self.hwnd,
                None,
                bounds.left,
                bounds.top,
                width,
                height,
                WindowsAndMessaging::SWP_NOZORDER | WindowsAndMessaging::SWP_NOACTIVATE,
            )
            .map_err(|err| WebViewError::WebView(format!("SetWindowPos failed: {err}")))?;
            base.SetBounds(RECT {
                left: 0,
                top: 0,
                right: width,
                bottom: height,
            })
            .map_err(|err| WebViewError::WebView(format!("SetBounds failed: {err}")))?;
        }
        self.bounds = bounds;
        self.radii = radii;
        self.corner_color = corner_color;
        let island = queued_island_visuals(webtag_key);
        self.dcomp
            .apply_geometry(width, height, radii, corner_color, &island)
    }

    /// Blits a decoded frame onto the island video visual. No DComp Commit.
    pub(crate) fn present_island_video_frame(
        &mut self,
        frame: &dcomp::IslandVideoFrame,
    ) -> StdResult<()> {
        self.dcomp.present_island_video_frame(frame)
    }

    /// Visibility is window-level first: hiding only hides the surface
    /// window and leaves the controller rendering through a grace timer, so
    /// a quick hide→show cycle (tab switches) re-reveals a live frame
    /// instead of flashing the card while WebView2 restarts presentation.
    /// The timer suspends long-hidden controllers to stop background
    /// rasterization.
    pub(crate) fn set_visible(
        &mut self,
        base: &ICoreWebView2Controller,
        visible: bool,
    ) -> StdResult<()> {
        self.visible = visible;
        unsafe {
            if visible {
                surface_window::cancel_hide_suspend(self.hwnd);
                let result = base
                    .SetIsVisible(true)
                    .map_err(|err| WebViewError::WebView(format!("SetIsVisible failed: {err}")));
                let _ = WindowsAndMessaging::ShowWindow(self.hwnd, WindowsAndMessaging::SW_SHOWNA);
                result
            } else {
                let _ = WindowsAndMessaging::ShowWindow(self.hwnd, WindowsAndMessaging::SW_HIDE);
                surface_window::schedule_hide_suspend(self.hwnd);
                Ok(())
            }
        }
    }

    pub(crate) fn bring_to_front(&mut self, base: &ICoreWebView2Controller) -> StdResult<()> {
        let parent = self.parent;
        self.ensure_alive(parent, base)?;
        unsafe {
            WindowsAndMessaging::SetWindowPos(
                self.hwnd,
                Some(WindowsAndMessaging::HWND_TOP),
                0,
                0,
                0,
                0,
                WindowsAndMessaging::SWP_NOMOVE
                    | WindowsAndMessaging::SWP_NOSIZE
                    | WindowsAndMessaging::SWP_NOACTIVATE
                    | WindowsAndMessaging::SWP_SHOWWINDOW,
            )
            .map_err(|err| WebViewError::WebView(format!("SetWindowPos failed: {err}")))
        }
    }

    /// Moves the surface window under a new host. WebView2's own parent stays
    /// the surface window, so its composition target survives the move — no
    /// blank frame, unlike the windowed controller's `SetParentWindow`. A
    /// surface killed by its former host's teardown is recreated here.
    pub(crate) fn set_parent(
        &mut self,
        base: &ICoreWebView2Controller,
        parent: HWND,
    ) -> StdResult<()> {
        unsafe {
            let rebuilt = self.ensure_alive(parent, base)?;
            if !rebuilt && self.parent != parent {
                WindowsAndMessaging::SetParent(self.hwnd, Some(parent))
                    .map_err(|err| WebViewError::WebView(format!("SetParent failed: {err}")))?;
            }
            self.parent = parent;
            // Sit beneath native-component siblings, matching the windowed
            // controller's placement; the shell paints chrome on the host
            // window itself, below all children.
            let _ = WindowsAndMessaging::SetWindowPos(
                self.hwnd,
                Some(WindowsAndMessaging::HWND_BOTTOM),
                0,
                0,
                0,
                0,
                WindowsAndMessaging::SWP_NOMOVE
                    | WindowsAndMessaging::SWP_NOSIZE
                    | WindowsAndMessaging::SWP_NOACTIVATE,
            );
        }
        Ok(())
    }

    /// Destroys the surface window. Must run on the webview's UI thread (the
    /// window's owner); called from `cleanup_state` after `Controller.Close`.
    /// The wndproc's WM_DESTROY arm revokes the OLE drop target.
    pub(crate) fn destroy(&self) {
        unregister_surface_webtag(self.hwnd.0 as isize);
        unsafe {
            let _ = WindowsAndMessaging::DestroyWindow(self.hwnd);
        }
    }
}

/// Finds the `LingXiaWebViewSurface` child of `parent` (host client HWND).
pub fn find_composition_surface_hwnd(parent: isize) -> Option<isize> {
    unsafe {
        let found = WindowsAndMessaging::FindWindowExW(
            Some(HWND(parent as *mut _)),
            None,
            windows::core::w!("LingXiaWebViewSurface"),
            None,
        )
        .ok()?;
        if found.0.is_null() {
            None
        } else {
            Some(found.0 as isize)
        }
    }
}

/// `PrintWindow(PW_RENDERFULLCONTENT)` of the DComp target HWND so island
/// visuals above `webview_visual` are in the buffer. Plain BitBlt misses
/// `WS_EX_NOREDIRECTIONBITMAP` surfaces.
pub fn capture_composition_surface_bgra(hwnd: isize) -> StdResult<CompositionSurfacePixels> {
    use windows::Win32::Graphics::Gdi::{
        BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleBitmap, CreateCompatibleDC,
        DIB_RGB_COLORS, DeleteDC, DeleteObject, GetDC, GetDIBits, ReleaseDC, SelectObject,
    };
    use windows::Win32::Storage::Xps::{PRINT_WINDOW_FLAGS, PrintWindow};
    use windows::Win32::UI::WindowsAndMessaging::PW_RENDERFULLCONTENT;

    unsafe {
        let hwnd = HWND(hwnd as *mut _);
        let mut rect = RECT::default();
        WindowsAndMessaging::GetClientRect(hwnd, &mut rect).map_err(|err| {
            WebViewError::WebView(format!("GetClientRect composition surface failed: {err}"))
        })?;
        let width = (rect.right - rect.left).max(0);
        let height = (rect.bottom - rect.top).max(0);
        if width == 0 || height == 0 {
            return Err(WebViewError::WebView(
                "composition surface has zero size".to_string(),
            ));
        }
        let screen = GetDC(None);
        let memdc = CreateCompatibleDC(Some(screen));
        let bmp = CreateCompatibleBitmap(screen, width, height);
        let old = SelectObject(memdc, bmp.into());
        let printed = PrintWindow(hwnd, memdc, PRINT_WINDOW_FLAGS(PW_RENDERFULLCONTENT)).as_bool();
        let mut info = BITMAPINFO {
            bmiHeader: BITMAPINFOHEADER {
                biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
                biWidth: width,
                biHeight: -height,
                biPlanes: 1,
                biBitCount: 32,
                biCompression: BI_RGB.0,
                ..Default::default()
            },
            ..Default::default()
        };
        let mut bgra = vec![0u8; (width * height * 4) as usize];
        let copied = if printed {
            GetDIBits(
                memdc,
                bmp,
                0,
                height as u32,
                Some(bgra.as_mut_ptr() as *mut _),
                &mut info,
                DIB_RGB_COLORS,
            )
        } else {
            0
        };
        SelectObject(memdc, old);
        let _ = DeleteObject(bmp.into());
        let _ = DeleteDC(memdc);
        ReleaseDC(None, screen);
        if copied == 0 {
            return Err(WebViewError::WebView(
                "PrintWindow/GetDIBits of LingXiaWebViewSurface failed".to_string(),
            ));
        }
        Ok(CompositionSurfacePixels {
            width: width as u32,
            height: height as u32,
            bgra,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{IslandVisualSpec, queue_island_visuals, queued_island_visuals};

    #[test]
    fn queued_island_visuals_are_visible_to_the_geometry_commit() {
        queue_island_visuals(
            "test-island-queue",
            vec![IslandVisualSpec {
                clip: None,
                id: "lx-video-1".into(),
                kind: "video".into(),
                offset_x: 8.0,
                offset_y: 40.0,
                width: 8,
                height: 8,
                dest_width: 8.0,
                dest_height: 8.0,
                color: 0xff10_1010,
                text: None,
                hwnd: None,
                pixels: None,
            }],
        );
        let queued = queued_island_visuals("test-island-queue");
        assert_eq!(queued.len(), 1);
        assert_eq!(queued[0].id, "lx-video-1");
        assert_eq!(queued[0].kind, "video");
        assert!(queued[0].hwnd.is_none());
    }
}