michiu_ui 0.0.3

The michiu library handles layout and rendering.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
use crate::{
    Color, ExternalTexture, ExternalTextureAlphaMode, ExternalTextureCompositingMode,
    ExternalTextureMetadata, ExternalVisual, ExternalVisualMetadata, LayoutRect, LayoutSize,
    MichiuError, StaticExternalTexture, MichiuTaskSender, VisualUpdateContext,
};
use std::{
    borrow::Cow,
    cell::{Cell, RefCell},
    rc::Rc,
    sync::Arc,
};
use webview2_com::{
    CapturePreviewCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler,
    Microsoft::Web::WebView2::Win32::{
        COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG, COREWEBVIEW2_COLOR,
        COREWEBVIEW2_MOUSE_EVENT_KIND, COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS,
        COREWEBVIEW2_MOVE_FOCUS_REASON, COREWEBVIEW2_MOVE_FOCUS_REASON_PREVIOUS,
        CreateCoreWebView2EnvironmentWithOptions, ICoreWebView2,
        ICoreWebView2CompositionController, ICoreWebView2Controller, ICoreWebView2Controller2,
        ICoreWebView2Environment, ICoreWebView2Environment3,
    },
};
use windows::{
    Win32::{
        Foundation::{HGLOBAL, HWND, LPARAM, POINT, RECT, WPARAM},
        Graphics::{
            DirectComposition::{IDCompositionDevice, IDCompositionVisual2},
            Gdi::InvalidateRect,
            Imaging::{
                GUID_WICPixelFormat32bppBGRA, IWICImagingFactory, WICBitmapDitherTypeNone,
                WICBitmapInterpolationModeLinear, WICBitmapPaletteTypeCustom,
                WICDecodeMetadataCacheOnDemand,
            },
        },
        System::{
            Com::{
                IStream,
                StructuredStorage::{CreateStreamOnHGlobal, GetHGlobalFromStream},
            },
            Memory::{GlobalLock, GlobalSize, GlobalUnlock},
        },
        UI::WindowsAndMessaging::{
            WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEHWHEEL,
            WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_RBUTTONDOWN, WM_RBUTTONUP,
        },
    },
    core::{Interface, PCWSTR},
};
use windows_core::{HRESULT, HSTRING};

#[derive(Debug, Clone, PartialEq)]
pub enum WebView2Source {
    /// External websites and local servers
    Url(Cow<'static, str>),
    /// Raw HTML code
    Html(Cow<'static, str>),
}

impl Default for WebView2Source {
    fn default() -> Self {
        Self::new()
    }
}

impl WebView2Source {
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self::Url("about:blank".into())
    }
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq)]
pub struct WebView2Contents {
    pub source: WebView2Source,
    /// Event Forward (Whether to accept mouse/keyboard input)
    pub allow_interaction: bool,
    /// Whether to display the system's default right-click menu
    pub enable_context_menu: bool,
    /// Can I open the developer tools by pressing `F12` ?
    pub enable_dev_tools: bool,
    /// Should I enable JavaScript?
    pub enable_scripts: bool,
    /// JavaScript to Run Automatically on Startup
    pub user_scripts: Vec<Cow<'static, str>>,
    /// Should it continue playing on the composition thread at all times,
    /// even when the user isn't interacting with it?
    pub always_active: bool,
    pub default_bg_color: Option<Color>,
}

impl Default for WebView2Contents {
    fn default() -> Self {
        Self {
            source: WebView2Source::new(),
            allow_interaction: true,
            enable_context_menu: false,
            enable_dev_tools: false,
            enable_scripts: true,
            user_scripts: Vec::new(),
            always_active: false,
            default_bg_color: None,
        }
    }
}

impl WebView2Contents {
    #[inline]
    #[must_use]
    pub fn new(source: WebView2Source) -> Self {
        Self {
            source,
            ..Default::default()
        }
    }

    #[inline]
    pub fn from_url(url: impl Into<Cow<'static, str>>) -> Self {
        Self::new(WebView2Source::Url(url.into()))
    }

    #[inline]
    pub fn from_html(html: impl Into<Cow<'static, str>>) -> Self {
        Self::new(WebView2Source::Html(html.into()))
    }

    #[inline]
    #[must_use]
    pub fn url(mut self, url: impl Into<Cow<'static, str>>) -> Self {
        self.source = WebView2Source::Url(url.into());
        self
    }

    #[inline]
    #[must_use]
    pub fn html(mut self, html: impl Into<Cow<'static, str>>) -> Self {
        self.source = WebView2Source::Html(html.into());
        self
    }

    #[inline]
    #[must_use]
    pub fn allow_interaction(mut self, allow: bool) -> Self {
        self.allow_interaction = allow;
        self
    }

    #[inline]
    #[must_use]
    pub fn enable_context_menu(mut self, enable: bool) -> Self {
        self.enable_context_menu = enable;
        self
    }

    #[inline]
    #[must_use]
    pub fn enable_dev_tools(mut self, enable: bool) -> Self {
        self.enable_dev_tools = enable;
        self
    }

    #[inline]
    #[must_use]
    pub fn enable_scripts(mut self, enable: bool) -> Self {
        self.enable_scripts = enable;
        self
    }

    /// `add_user_script(include_str!("example.js"))`
    #[inline]
    #[must_use]
    pub fn add_user_script(mut self, script: impl Into<Cow<'static, str>>) -> Self {
        self.user_scripts.push(script.into());
        self
    }

    /// Enable Always Render
    #[inline]
    #[must_use]
    pub fn always_active(mut self, always: bool) -> Self {
        self.always_active = always;
        self
    }

    #[inline]
    #[must_use]
    pub fn default_bg_color(mut self, color: Color) -> Self {
        self.default_bg_color = Some(color);
        self
    }
}

thread_local! {
    /// UI スレッドごとに 1 つだけ環境をキャッシュする
    static WEBVIEW2_THREAD_ENV: RefCell<Option<ICoreWebView2Environment3>> = const { RefCell::new(None) };
}

/// キャッシュ済みの環境があればクローンして即座に借用を解放して返す
pub(crate) fn get_cached_env() -> Option<ICoreWebView2Environment3> {
    WEBVIEW2_THREAD_ENV.with(|slot| slot.borrow().clone())
}

/// スレッドローカルに環境をキャッシュする
pub(crate) fn set_cached_env(env: ICoreWebView2Environment3) {
    WEBVIEW2_THREAD_ENV.with(|slot| {
        *slot.borrow_mut() = Some(env);
    });
}

#[derive(Debug, Clone)]
pub struct WebView2Visual {
    pub visual: IDCompositionVisual2,
    /// コントローラー(非同期生成完了時に格納)
    pub controller: Rc<RefCell<Option<ICoreWebView2Controller>>>,
    /// 静止画キャッシュ(アクティブ時は None、キャプチャ完了時に Some)
    pub cached_texture: Rc<RefCell<Option<Arc<StaticExternalTexture>>>>,
    /// キャプチャ実行中フラグ
    pub is_capturing: Rc<RefCell<bool>>,
    /// 設定情報
    pub contents: WebView2Contents,
    /// メタデータ
    pub metadata: ExternalVisualMetadata,
    current_rect: Cell<LayoutRect>,
    scale_factor: Cell<f32>,
}

// COM ポインタを抱えるため、UI スレッド/STA で安全に扱える前提で Send + Sync を付与
unsafe impl Send for WebView2Visual {}
unsafe impl Sync for WebView2Visual {}

impl ExternalVisual for WebView2Visual {
    fn resolve_visual(&self) -> IDCompositionVisual2 {
        self.visual.clone()
    }

    fn static_texture(&self) -> Option<Arc<dyn ExternalTexture>> {
        self.cached_texture
            .borrow()
            .clone()
            .map(|t| t as Arc<dyn ExternalTexture>)
    }

    fn update(&self, cx: &VisualUpdateContext) {
        self.current_rect.set(cx.rect);
        self.scale_factor.set(cx.scale_factor);

        let phys_w = (cx.rect.width * cx.scale_factor).round() as i32;
        let phys_h = (cx.rect.height * cx.scale_factor).round() as i32;

        let Some(ref controller) = *self.controller.borrow() else {
            return;
        };

        // WebView2 自身の Bounds を同期 (0,0 原点)
        let bounds = RECT {
            left: 0,
            top: 0,
            right: phys_w,
            bottom: phys_h,
        };
        let _ = unsafe { controller.SetBounds(bounds) };

        // 操作中・常時アクティブ・トランジション中は実体を維持
        let should_stay_active = cx.is_interactive || self.contents.always_active || !cx.is_stable;
        if should_stay_active {
            *self.cached_texture.borrow_mut() = None;
            return;
        }

        // 安定しており、かつまだキャッシュもキャプチャ中もない場合、自動キャプチャを発火
        if self.cached_texture.borrow().is_none()
            && !*self.is_capturing.borrow()
            && phys_w > 0
            && phys_h > 0
            && let Ok(webview) = unsafe { controller.CoreWebView2() }
        {
            *self.is_capturing.borrow_mut() = true;

            let device = cx.device.clone();
            let queue = cx.queue.clone();
            let wic_factory = cx.wic_factory.clone();
            let size = LayoutSize::new(cx.rect.width, cx.rect.height);

            let cached_texture_clone = self.cached_texture.clone();
            let is_capturing_clone = self.is_capturing.clone();

            // 非同期キャプチャの実行
            let _ = unsafe {
                Self::trigger_capture_async(
                    &webview,
                    phys_w as u32,
                    phys_h as u32,
                    device,
                    queue,
                    wic_factory,
                    move |result| {
                        if let Ok(wgpu_tex) = result {
                            let view =
                                wgpu_tex.create_view(&wgpu::TextureViewDescriptor::default());

                            let static_tex = Arc::new(StaticExternalTexture {
                                view,
                                metadata: ExternalTextureMetadata {
                                    size,
                                    alpha_mode: ExternalTextureAlphaMode::Straight,
                                    y_flip: false,
                                    is_srgb: true,
                                    compositing_mode: ExternalTextureCompositingMode::NonLinear(
                                        1.5,
                                    ),
                                },
                            });
                            // キャッシュをセットして強制再描画をキック
                            *cached_texture_clone.borrow_mut() = Some(static_tex);
                        }
                        *is_capturing_clone.borrow_mut() = false;
                    },
                )
            };
        }
    }

    fn handle_raw_input(
        &self,
        msg: u32,
        wparam: WPARAM,
        _lparam: LPARAM,
        local_phys_pos: POINT,
    ) -> bool {
        if !self.contents.allow_interaction {
            return false;
        }

        // 静止画表示中の単なるカーソル通過では実体化させない
        let is_static = self.cached_texture.borrow().is_some();
        if is_static && msg == WM_MOUSEMOVE {
            return false;
        }

        match msg {
            WM_MOUSEMOVE | WM_LBUTTONDOWN | WM_LBUTTONUP | WM_RBUTTONDOWN | WM_RBUTTONUP
            | WM_MBUTTONDOWN | WM_MBUTTONUP | WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
                // クリック等の明示的な操作時のみキャッシュを破棄して実体化
                if msg != WM_MOUSEMOVE {
                    *self.cached_texture.borrow_mut() = None;
                }

                if let Some(ref controller) = *self.controller.borrow()
                    && let Ok(comp) = controller.cast::<ICoreWebView2CompositionController>()
                {
                    let event_kind = COREWEBVIEW2_MOUSE_EVENT_KIND(msg as i32);
                    let virtual_keys = COREWEBVIEW2_MOUSE_EVENT_VIRTUAL_KEYS(wparam.0 as i32);
                    let mouse_data = if msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL {
                        ((wparam.0 >> 16) as i16) as i32 as u32
                    } else {
                        0
                    };
                    unsafe {
                        let _ = comp.SendMouseInput(
                            event_kind,
                            virtual_keys,
                            mouse_data,
                            local_phys_pos,
                        );
                    }
                }
                true
            }
            _ => false,
        }
    }

    fn metadata(&self) -> ExternalVisualMetadata {
        self.metadata
    }
}

impl WebView2Visual {
    pub fn new(
        dcomp_device: &IDCompositionDevice,
        hwnd: HWND,
        contents: WebView2Contents,
        scale_factor: f32,
        task_sender: &MichiuTaskSender,
    ) -> crate::Result<Self> {
        let visual: IDCompositionVisual2 = unsafe { dcomp_device.CreateVisual()?.cast()? };
        let controller = Rc::new(RefCell::new(None));

        let cached_env = get_cached_env();

        unsafe {
            Self::init_webview2_composition(
                hwnd,
                &visual,
                &controller,
                &contents,
                cached_env,
                task_sender,
            )?;
        }

        let metadata = ExternalVisualMetadata {
            size: LayoutSize::ZERO,
            auto_clip: true,
            auto_transform: true,
        };

        Ok(Self {
            visual,
            controller,
            cached_texture: Rc::new(RefCell::new(None)),
            is_capturing: Rc::new(RefCell::new(false)),
            contents,
            metadata,
            current_rect: Cell::default(),
            scale_factor: Cell::new(scale_factor),
        })
    }

    pub fn prewarm_webview2() {
        if get_cached_env().is_some() {
            return;
        }
        unsafe {
            let _ = CreateCoreWebView2EnvironmentCompletedHandler::wait_for_async_operation(
                Box::new(|handler| {
                    CreateCoreWebView2EnvironmentWithOptions(None, None, None, &handler)
                        .map_err(webview2_com::Error::WindowsError)
                }),
                Box::new(|res, env| {
                    if let Ok(()) = res
                        && let Some(e_ptr) = env
                        && let Ok(env3) = e_ptr.cast::<ICoreWebView2Environment3>()
                    {
                        set_cached_env(env3);
                    }
                    Ok(())
                }),
            );
        }
    }

    #[expect(clippy::too_many_arguments)]
    pub(crate) unsafe fn init_webview2_composition(
        hwnd: HWND,
        webview_visual: &IDCompositionVisual2,
        controller_slot: &Rc<RefCell<Option<ICoreWebView2Controller>>>,
        settings: &WebView2Contents,
        env_slot: Option<ICoreWebView2Environment3>,
        sys_task_sender: &MichiuTaskSender,
    ) -> crate::Result<()> {
        let webview_visual_clone = webview_visual.clone();
        let controller_slot_clone = controller_slot.clone();
        let settings_clone = settings.clone();
        let task_sender_clone = sys_task_sender.clone();
        let default_bg = if let Some(c) = settings.default_bg_color {
            COREWEBVIEW2_COLOR {
                A: c.a as u8,
                R: c.r as u8,
                G: c.g as u8,
                B: c.b as u8,
            }
        } else {
            COREWEBVIEW2_COLOR {
                A: 0,
                R: 0,
                G: 0,
                B: 0,
            }
        };

        // プリウォーム済み環境(Environment)の利用
        if let Some(env3) = env_slot {
            let handler =
                webview2_com::CreateCoreWebView2CompositionControllerCompletedHandler::create(
                    Box::new(
                        move |res, controller: Option<ICoreWebView2CompositionController>| {
                            // このクロージャは後から非同期にブラウザの初期化が終わった瞬間に実行。
                            let _ = res.map_err(webview2_com::Error::WindowsError);

                            let comp_controller =
                                controller.ok_or_else(windows_core::Error::from_thread)?;
                            unsafe { comp_controller.SetRootVisualTarget(&webview_visual_clone) }?;

                            let base_controller: ICoreWebView2Controller =
                                comp_controller.cast()?;

                            unsafe {
                                let _ = base_controller
                                    .cast::<ICoreWebView2Controller2>()?
                                    .SetDefaultBackgroundColor(default_bg);
                            };

                            // 位置(left, top)は DComp 側に一任するため 0 に設定
                            let bounds = RECT {
                                left: 0,
                                top: 0,
                                right: 0,
                                bottom: 0,
                            };
                            unsafe {
                                base_controller.SetBounds(bounds)?;
                                base_controller.SetIsVisible(true)?;
                            }

                            // キーボードフォーカス奪還ハンドラをバインド
                            let task_sender_inner = task_sender_clone.clone();
                            let focus_handler =
                                webview2_com::MoveFocusRequestedEventHandler::create(Box::new(
                                    move |_sender, args| {
                                        if let Some(args) = args {
                                            let mut reason = COREWEBVIEW2_MOVE_FOCUS_REASON(0);
                                            let _ = unsafe { args.Reason(&raw mut reason) };

                                            // Tab なら 順順移動(false), Shift+Tab なら 逆順移動(true)
                                            let is_reverse =
                                                reason == COREWEBVIEW2_MOVE_FOCUS_REASON_PREVIOUS;

                                            // メインスレッドの Context にフォーカス循環要求をディスパッチ
                                            let _ = task_sender_inner.send(move |cx| {
                                                cx.cycle_keyboard_focus(is_reverse);
                                            });

                                            // WebView2側にホストアプリがフォーカスを奪還したことを通知
                                            let _ = unsafe { args.SetHandled(true) };
                                        }
                                        Ok(())
                                    },
                                ));
                            unsafe {
                                base_controller.add_MoveFocusRequested(&focus_handler, &mut 0)?;
                            }

                            let webview = unsafe { base_controller.CoreWebView2()? };
                            let web_settings = unsafe { webview.Settings()? };

                            unsafe {
                                let _ =
                                    web_settings.SetIsScriptEnabled(settings_clone.enable_scripts);
                                let _ = web_settings
                                    .SetAreDevToolsEnabled(settings_clone.enable_dev_tools);
                                let _ = web_settings.SetAreDefaultContextMenusEnabled(
                                    settings_clone.enable_context_menu,
                                );
                            }

                            // ユーザースクリプト登録も非同期で安全に登録
                            for script in &settings_clone.user_scripts {
                                let script_u16: Vec<u16> =
                                    script.encode_utf16().chain(Some(0)).collect();
                                let pcw_script = PCWSTR(script_u16.as_ptr());
                                let webview_clone = webview.clone();

                                let script_handler = webview2_com::AddScriptToExecuteOnDocumentCreatedCompletedHandler::create(
                                Box::new(|res, _id| {
                                    let _ = res.map_err(webview2_com::Error::WindowsError);
                                    Ok(())
                                })
                            );
                                unsafe {
                                    webview_clone.AddScriptToExecuteOnDocumentCreated(
                                        pcw_script,
                                        &script_handler,
                                    )?;
                                }
                            }

                            // NavigationCompleted を購読して、描画ピクセルが準備できた段階でスロットに代入する
                            let controller_slot_inner = controller_slot_clone.clone();
                            let base_controller_inner = base_controller.clone();
                            let nav_handler = webview2_com::NavigationCompletedEventHandler::create(
                                Box::new(move |_sender, _args| {
                                    // ページが完全に初期描画フェーズに移行した
                                    *controller_slot_inner.borrow_mut() =
                                        Some(base_controller_inner.clone());

                                    // 強制的に再描画を走らせて穴あけと描画をトリガー
                                    let _ = unsafe { InvalidateRect(Some(hwnd), None, false) };

                                    Ok(())
                                }),
                            );

                            unsafe {
                                webview.add_NavigationCompleted(&nav_handler, &mut 0)?;
                            }

                            let source_string = match &settings_clone.source {
                                WebView2Source::Url(url) => HSTRING::from(url.as_ref()),
                                WebView2Source::Html(html) => HSTRING::from(html.as_ref()),
                            };

                            unsafe {
                                match &settings_clone.source {
                                    WebView2Source::Url(_) => webview.Navigate(&source_string)?,
                                    WebView2Source::Html(_) => {
                                        webview.NavigateToString(&source_string)?;
                                    }
                                }
                            }

                            Ok(())
                        },
                    ),
                );

            // 非同期処理をキックして即時リターン(ノンブロッキング)
            unsafe {
                env3.CreateCoreWebView2CompositionController(hwnd, &handler)?;
            }

            return Ok(());
        }

        // 初期起動時(env_slot がまだロード途中)の場合のフォールバック
        let handler = webview2_com::CreateCoreWebView2EnvironmentCompletedHandler::create(
            Box::new(move |res, environment: Option<ICoreWebView2Environment>| {
                let _ = res.map_err(webview2_com::Error::WindowsError);
                let env = environment.ok_or_else(windows_core::Error::from_thread)?;
                let env3: ICoreWebView2Environment3 = env.cast()?;

                // 環境スロットにキャッシュを保存
                set_cached_env(env3.clone());

                let webview_visual_clone2 = webview_visual_clone.clone();

                let controller_handler =
                    webview2_com::CreateCoreWebView2CompositionControllerCompletedHandler::create(
                        Box::new(
                            move |res, controller: Option<ICoreWebView2CompositionController>| {
                                let _ = res.map_err(webview2_com::Error::WindowsError);
                                let comp_controller =
                                    controller.ok_or_else(windows_core::Error::from_thread)?;
                                unsafe {
                                    comp_controller.SetRootVisualTarget(&webview_visual_clone2)
                                }?;

                                let base_controller: ICoreWebView2Controller =
                                    comp_controller.cast()?;

                                unsafe {
                                    let _ = base_controller
                                        .cast::<ICoreWebView2Controller2>()?
                                        .SetDefaultBackgroundColor(default_bg);
                                };

                                let bounds = RECT {
                                    left: 0,
                                    top: 0,
                                    right: 0,
                                    bottom: 0,
                                };
                                unsafe {
                                    base_controller.SetBounds(bounds)?;
                                    base_controller.SetIsVisible(true)?;
                                }

                                // キーボードフォーカス奪還ハンドラをバインド
                                let task_sender_inner = task_sender_clone.clone();
                                let focus_handler =
                                    webview2_com::MoveFocusRequestedEventHandler::create(Box::new(
                                        move |_sender, args| {
                                            if let Some(args) = args {
                                                let mut reason = COREWEBVIEW2_MOVE_FOCUS_REASON(0);
                                                let _ = unsafe { args.Reason(&raw mut reason) };

                                                // Tab なら 順順移動(false), Shift+Tab なら 逆順移動(true)
                                                let is_reverse = reason
                                                    == COREWEBVIEW2_MOVE_FOCUS_REASON_PREVIOUS;

                                                // メインスレッドの Context にフォーカス循環要求をディスパッチ
                                                let _ = task_sender_inner.send(move |cx| {
                                                    cx.cycle_keyboard_focus(is_reverse);
                                                });

                                                // WebView2側に「ホストアプリがフォーカスを奪還した」ことを通知
                                                let _ = unsafe { args.SetHandled(true) };
                                            }
                                            Ok(())
                                        },
                                    ));
                                unsafe {
                                    base_controller
                                        .add_MoveFocusRequested(&focus_handler, &mut 0)?;
                                }

                                let webview = unsafe { base_controller.CoreWebView2()? };

                                let controller_slot_inner = controller_slot_clone.clone();
                                let base_controller_inner = base_controller.clone();
                                let nav_handler =
                                    webview2_com::NavigationCompletedEventHandler::create(
                                        Box::new(move |_sender, _args| {
                                            *controller_slot_inner.borrow_mut() =
                                                Some(base_controller_inner.clone());

                                            let _ =
                                                unsafe { InvalidateRect(Some(hwnd), None, false) };

                                            Ok(())
                                        }),
                                    );

                                unsafe {
                                    webview.add_NavigationCompleted(&nav_handler, &mut 0)?;
                                }

                                let source_string = match &settings_clone.source {
                                    WebView2Source::Url(url) => HSTRING::from(url.as_ref()),
                                    WebView2Source::Html(html) => HSTRING::from(html.as_ref()),
                                };

                                unsafe {
                                    match &settings_clone.source {
                                        WebView2Source::Url(_) => {
                                            webview.Navigate(&source_string)?;
                                        }
                                        WebView2Source::Html(_) => {
                                            webview.NavigateToString(&source_string)?;
                                        }
                                    }
                                }

                                Ok(())
                            },
                        ),
                    );

                unsafe {
                    env3.CreateCoreWebView2CompositionController(hwnd, &controller_handler)?;
                }

                Ok(())
            }),
        );

        unsafe {
            CreateCoreWebView2EnvironmentWithOptions(None, None, None, &handler)?;
        }

        Ok(())
    }

    /// `WebView2` から非アクティブ時の静止画(1フレーム)をキャプチャし、
    /// wgpu 側の `wgpu::Texture` へとピクセルデータを転送します。
    pub(crate) unsafe fn trigger_capture_async<F>(
        webview: &ICoreWebView2,
        width: u32,
        height: u32,
        wgpu_device: wgpu::Device,
        wgpu_queue: wgpu::Queue,
        wic_factory: IWICImagingFactory,
        on_complete: F,
    ) -> crate::Result<()>
    where
        F: FnOnce(crate::Result<wgpu::Texture>) + 'static,
    {
        unsafe {
            // メモリ上に COM の IStream を作成
            let stream = CreateStreamOnHGlobal(HGLOBAL::default(), true)?;
            let stream_clone = stream.clone();

            // 完了コールバックの所有権をハンドラー内に安全に移すため、Option に包む
            let mut on_complete_opt = Some(on_complete);

            // ICoreWebView2::CapturePreview を呼び出し、PNG 形式でストリームに書き込ませる
            // ICoreWebView2CapturePreviewCompletedHandler を用いて非同期完了を同期的に待機
            webview.CapturePreview(
                COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_PNG,
                &stream,
                // 完了ハンドラー
                &CapturePreviewCompletedHandler::create(Box::new(move |result| {
                    // このクロージャは、WebView2 側の処理完了時にメインスレッド(STA)上で呼び出される
                    let on_complete = on_complete_opt.take().ok_or_else(|| {
                        // とりあえず E_FAIL を返しておく
                        windows_core::Error::from_hresult(HRESULT(0x8000_4005_u32.cast_signed()))
                    })?;

                    if let Err(e) = result {
                        on_complete(Err(e.into()));
                        return Ok(());
                    }

                    // ストリームから HGLOBAL をクエリして WIC で PMA (BGRA8) にデコード
                    let texture_res = Self::process_captured_stream(
                        &wgpu_device,
                        &wgpu_queue,
                        &wic_factory,
                        &stream_clone,
                        width,
                        height,
                    );

                    // 完了コールバックを呼び出してテクスチャを通知
                    on_complete(texture_res);
                    Ok(())
                })),
            )?;

            Ok(())
        }
    }

    /// 内部ヘルパー: ストリームに書き込まれた PNG バイト列を WIC で高速に BGRA8 ピクセル配列にデコードし、
    /// `wgpu::Texture` を作成してアップロード
    unsafe fn process_captured_stream(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        wic_factory: &IWICImagingFactory,
        stream: &IStream,
        width: u32,
        height: u32,
    ) -> crate::Result<wgpu::Texture> {
        unsafe {
            let hglobal = GetHGlobalFromStream(stream)?;
            let data_ptr = GlobalLock(hglobal);

            // ポインタが null の場合は早期リターン
            if data_ptr.is_null() {
                return Err(MichiuError::GlobalLockFailed);
            }

            let size = GlobalSize(hglobal);

            // 正常な PNG ファイルとして不十分なサイズの場合は即座にエラーとする
            if size < 128 {
                let _ = GlobalUnlock(hglobal);
                return Err(MichiuError::InvalidImageData);
            }

            let png_bytes = std::slice::from_raw_parts(data_ptr as *const u8, size);

            // wgpu 内にすでに定義されている WIC ファクトリ(IWICImagingFactory)を利用
            let wic_stream = wic_factory.CreateStream()?;
            wic_stream.InitializeFromMemory(png_bytes)?;

            // デコーダーとフレームの構築
            let decoder = wic_factory.CreateDecoderFromStream(
                &wic_stream,
                std::ptr::null(),
                WICDecodeMetadataCacheOnDemand,
            )?;

            let frame = decoder.GetFrame(0)?;

            // ストレート BGRA 形式に変換(PBGRA ではなくストレート BGRA)
            let converter = wic_factory.CreateFormatConverter()?;
            converter.Initialize(
                &frame,
                &GUID_WICPixelFormat32bppBGRA,
                WICBitmapDitherTypeNone,
                None,
                0.0,
                WICBitmapPaletteTypeCustom,
            )?;

            // WebView2 から提出された元画像サイズがどうであれ、
            // 目標の wgpu テクスチャサイズ (width x height) へ正確にリサイズ。
            let scaler = wic_factory.CreateBitmapScaler()?;
            scaler.Initialize(&converter, width, height, WICBitmapInterpolationModeLinear)?;

            let mut pixels = vec![0u8; (width * height * 4) as usize];
            scaler.CopyPixels(std::ptr::null(), width * 4, &mut pixels)?;

            // 静止画キャッシュの完全不透明化と、R/B チャンネル反転の修正
            // WIC の仕様上、scaler は入力されたフォーマットをそのまま維持しようとするが
            // GUID_WICPixelFormat32bppRGBA を直接リサイズする際に
            // 内部でWindows標準のBGRAに戻してしまうケースがあるらしい。
            for chunk in pixels.as_chunks_mut::<4>().0 {
                // どうやら現在 [B, G, R, A] で入っているっぽい
                let b = chunk[0];
                let r = chunk[2];
                chunk[0] = r; // B の位置に R を上書き
                chunk[2] = b; // R の位置に B を上書き
            }

            // メモリロック解除
            // windows-rs の自動 Result 変換のバグ(S_OK/NO_ERROR なのに 0 返却のため Err になる)を
            // 回避するため、? によるエラー早期返却をやめ、単に返り値を破棄する。
            let _ = GlobalUnlock(hglobal);

            // 新規 wgpu::Texture の生成
            let wgpu_texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("WebView2 Static Cache Texture"),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8UnormSrgb,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            });

            // VRAM へのアップロード
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &wgpu_texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                &pixels,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(width * 4),
                    rows_per_image: Some(height),
                },
                wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
            );

            Ok(wgpu_texture)
        }
    }
}