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
use crate::{
    AnimationCurve, Backdrop, ComponentMask, Context, CornerRadius, DebugStore, EntityId,
    ExternalVisual, ExternalVisualMetadata, InteractionState, LayoutPoint, LayoutRect, LayoutSize,
    MichiuError, MichiuSoA, MichiuTrace, PlaybackCount, PropertyList, RawWgpuRenderer,
    ResultTraceExt, StaticExternalTexture, VisualUpdateContext, WgpuRenderer,
    WindowsResultTraceExt, flush_trace, trace_error, trace_lifecycle,
};
use std::{
    cell::RefCell,
    rc::Rc,
    sync::{Arc, Mutex, OnceLock},
};
use windows::{
    Win32::{
        Foundation::{HMODULE, HWND, LPARAM, POINT, RECT, WPARAM},
        Graphics::{
            Direct3D::{D3D_DRIVER_TYPE_HARDWARE, ID3DInclude_Impl},
            Direct3D11::{
                D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_SDK_VERSION, D3D11CreateDevice,
                ID3D11Device,
            },
            DirectComposition::{
                DCompositionCreateDevice2, IDCompositionDesktopDevice,
                IDCompositionDesktopDevice_Impl, IDCompositionDevice, IDCompositionDevice_Impl,
                IDCompositionDevice2_Impl, IDCompositionRectangleClip_Impl, IDCompositionTarget,
                IDCompositionTarget_Impl, IDCompositionTranslateTransform_Impl,
                IDCompositionTranslateTransform3D_Impl, IDCompositionVisual,
                IDCompositionVisual_Impl, IDCompositionVisual2, IDCompositionVisual3_Impl,
            },
            Dxgi::*,
            Gdi::InvalidateRect,
            Imaging::{CLSID_WICImagingFactory, IWICImagingFactory},
        },
        System::{
            Com::{CLSCTX_INPROC_SERVER, CoCreateInstance},
            LibraryLoader::GetModuleHandleW,
        },
        UI::WindowsAndMessaging::{
            GWL_EXSTYLE, GetWindowLongW, SetWindowLongW, WM_MOUSEHWHEEL, WM_MOUSEWHEEL,
        },
    },
    core::{Interface, PCWSTR, PWSTR, w},
};
use windows_numerics::Matrix3x2;

pub struct MichiuRenderer {
    pub(crate) hwnd: HWND,
    pub(crate) layout_size: LayoutSize,
    pub(crate) scale_factor: f32,

    pub(crate) wic_factory: IWICImagingFactory,

    /// `DirectComposition` リソース
    pub(crate) d3d11_device: ID3D11Device,
    pub(crate) desktop_device: IDCompositionDesktopDevice,
    pub(crate) target: IDCompositionTarget,
    pub(crate) root_visual: IDCompositionVisual2,
    /// wgpu 用のビジュアル
    pub(crate) wgpu_visual: IDCompositionVisual2,

    /// wgpu レンダラー
    pub(crate) wgpu_renderer: WgpuRenderer,

    /// 動的に昇格されたレイヤーの一覧
    pub(crate) promoted_visuals: Vec<PromotedVisual>,

    /// `DComp` 側の Visual 削除を wgpu のピクセル定着から数フレーム遅延させるためのキュー
    pub(crate) pending_dcomp_releases: Vec<PendingDcompRelease>,

    /// 現在ウィンドウに適用中のバックドロップ状態
    pub(crate) current_backdrop: Backdrop,

    /// リサイズが完全に安定するまでキャプチャを保留するカウンター
    pub(crate) resize_cooldown_frames: u32,
}

#[derive(Debug, Clone)]
pub struct PendingDcompRelease {
    pub entity_id: EntityId,
    pub frames_left: u32,
}

#[derive(Debug, Clone)]
pub struct PromotedVisual {
    /// 昇格した要素の ID
    pub entity_id: EntityId,
    /// `DirectComposition` 側の Visual オブジェクト
    pub visual: IDCompositionVisual2,
    /// 適用しているトランスフォームオブジェクト (COM参照を維持するために保持)
    pub transform: Option<windows::core::IUnknown>,
    // DCompツリーにマウントされており、コントローラーが可視状態であるか
    pub is_visible: bool,
}

impl MichiuRenderer {
    /// Initialize the renderer.
    #[inline]
    pub async fn new(
        hwnd: HWND,
        layout_size: LayoutSize,
        scale_factor: f32,
    ) -> crate::Result<Self> {
        // DirectComposition の構築 (setup_direct_composition を内包)
        let (d3d11_device, desktop_device, target, root_visual, wgpu_visual) =
            MichiuRenderer::setup_direct_composition(hwnd)?;

        // HINSTANCE(h_instance)の解決
        let h_instance = unsafe { GetModuleHandleW(None)? };

        // wgpu レンダラーの初期化
        let raw_visual_ptr = wgpu_visual.as_raw();

        let wgpu_renderer = WgpuRenderer::new(raw_visual_ptr, layout_size, scale_factor).await?;

        unsafe {
            desktop_device.Commit()?;
        }

        let wic_factory: IWICImagingFactory =
            unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)? };

        Ok(Self {
            hwnd,
            layout_size,
            scale_factor,
            wic_factory,
            d3d11_device,
            desktop_device,
            target,
            root_visual,
            wgpu_visual,
            wgpu_renderer,
            promoted_visuals: Vec::new(),
            pending_dcomp_releases: Vec::new(),
            current_backdrop: Backdrop::None,
            resize_cooldown_frames: 0,
        })
    }

    /// Updates the overall settings and resizes wgpu when the window size changes.
    ///
    /// `new_physical_size`: (width, height)
    #[expect(clippy::cast_precision_loss)]
    #[inline]
    pub fn resize(&mut self, new_physical_size: (u32, u32), scale_factor: f32) {
        self.scale_factor = scale_factor;
        self.layout_size = LayoutSize::new(
            new_physical_size.0 as f32 / scale_factor,
            new_physical_size.1 as f32 / scale_factor,
        );
        self.wgpu_renderer.resize(new_physical_size, scale_factor);

        // リサイズが発生したため、キャプチャクールダウンを 15 フレームに設定
        // 拡大リサイズ中およびリサイズ直後の不安定なバッファへのキャプチャを遮断
        self.resize_cooldown_frames = 15;

        let _ = unsafe { self.desktop_device.Commit() };
    }

    /// Drawing Triggers
    #[track_caller]
    #[inline]
    pub fn draw(&mut self, cx: &mut Context) {
        self.wgpu_renderer.render(cx, self.scale_factor);

        unsafe {
            self.desktop_device
                .Commit()
                .unwrap_or_trace(None, &mut cx.debug);
        };

        #[cfg(feature = "trace-lifecycle")]
        trace_lifecycle!(None, &mut cx.debug, || MichiuTrace::Commit { add: None });

        #[cfg(feature = "trace-lifecycle")]
        {
            let total_entities = cx.topology.topo_entities.len();
            let active_entities = cx.topology.topo_active_entities.len();
            let dirty_layouts = cx.layouts.lay_dirty_entities.len();
            let dirty_renders = cx.renders.rnd_dirty_entities.len();

            #[cfg(feature = "trace-lifecycle")]
            trace_lifecycle!(None, &mut cx.debug, || MichiuTrace::ClearDirtyEntities {
                total_entities,
                active_entities,
                dirty_layouts,
                dirty_renders,
                add: Some(
                    "Immediately after this recording, the dirty flag is cleared and the log is sent."
                ),
            });
        }

        // ダーティフラグをクリア
        cx.clear_dirty();
        // ログを送信
        flush_trace!(cx, self);
    }

    #[track_caller]
    pub fn update_composition_tree(&mut self, cx: &mut Context) {
        unsafe {
            if self.resize_cooldown_frames > 0 {
                self.resize_cooldown_frames -= 1;
            }

            // ルート要素(root_node)のスタイルから DWM アクリル効果を自動検出して同期
            if let Some(&root_id) = cx.topology.topo_active_entities.first()
                && let Some(visual_prop) = cx.renders.rnd_visual.find(root_id)
            {
                let target_backdrop = visual_prop.backdrop;

                // スタイル変更があった場合のみ、拡張した apply_system_backdrop を即時更新
                if self.current_backdrop != target_backdrop {
                    apply_system_backdrop(self.hwnd, target_backdrop);
                    self.current_backdrop = target_backdrop;
                }
            }

            // 遅延キューの消化処理(1〜3フレーム目)
            let mut idx = 0;
            while idx < self.pending_dcomp_releases.len() {
                if self.pending_dcomp_releases[idx].frames_left > 0 {
                    self.pending_dcomp_releases[idx].frames_left -= 1;
                    idx += 1;
                } else {
                    // ディレイ猶予が切れたため、安全に DComp から破棄を実行
                    let release = self.pending_dcomp_releases.remove(idx);
                    let target_id = release.entity_id;

                    if let Some(pos) = self
                        .promoted_visuals
                        .iter()
                        .position(|v| v.entity_id == target_id)
                    {
                        let promoted = &mut self.promoted_visuals[pos];
                        // タイムアウトが切れたため(wgpuへのテクスチャ定着完了)、
                        // 実体は破棄せず、DCompツリーから取り外して不可視にするのみ
                        if promoted.is_visible {
                            let _ = self.root_visual.RemoveVisual(&promoted.visual);
                            promoted.is_visible = false;
                        }
                    }
                }
            }

            // 外部 Visual の一括更新 & アクティブ判定
            let mut current_promoted_ids = Vec::new();

            // ループの前にスナップショットを取得
            let visual_entries: Vec<(EntityId, Arc<dyn ExternalVisual>)> = cx
                .contents
                .cont_external_visual
                .iter()
                .map(|(id, v)| (id, Arc::clone(v)))
                .collect();

            for (id, visual_entry) in visual_entries {
                let rect = cx.outputs.out_rects.find_or_default(id, &mut cx.debug);
                let dcomp_visual = visual_entry.resolve_visual();
                let metadata = visual_entry.metadata();

                // 安定状態の判定
                let is_interactive = is_element_interactive(cx, id);
                let is_transitioning = is_element_transitioning(cx, id);
                let prev_rect = cx.outputs.out_prev_rects.find_or_default(id, &mut cx.debug);
                let is_size_changing = (rect.width - prev_rect.width).abs() > 0.01
                    || (rect.height - prev_rect.height).abs() > 0.01;
                let is_stable = !cx.window.win_is_resized
                    && self.resize_cooldown_frames == 0
                    && !is_transitioning
                    && !is_size_changing;

                // 各 Visual の状態更新フックを実行(WebView2 はここで Bounds 設定や自動キャプチャを行う)
                visual_entry.update(&VisualUpdateContext {
                    hwnd: self.hwnd,
                    rect,
                    scale_factor: self.scale_factor,
                    is_interactive,
                    is_stable,
                    device: &self.wgpu_renderer.device,
                    queue: &self.wgpu_renderer.queue,
                    wic_factory: &self.wic_factory,
                });

                // DComp Visual のレイアウト(位置・クリップ・トランスフォーム)を同期
                self.sync_visual_layout_and_clip(id, &dcomp_visual, metadata, cx);

                // 静止画テクスチャがあるかどうかで分岐
                if let Some(static_tex) = visual_entry.static_texture() {
                    // 静止画
                    cx.contents.cont_external_textures.insert(id, static_tex);
                    cx.topology
                        .topo_active_masks
                        .at_mut(id)
                        .set(ComponentMask::COMP_EXTERNAL_TEXTURE_CONTENT);
                    cx.renders.rnd_active_external_visual.remove(&id);

                    // wgpuの静止画描画と同時にDComp実体を外して二重描画を防止
                    if let Some(pos) = self.promoted_visuals.iter().position(|v| v.entity_id == id)
                    {
                        let promoted = &mut self.promoted_visuals[pos];
                        if promoted.is_visible {
                            let _ = self.root_visual.RemoveVisual(&promoted.visual);
                            promoted.is_visible = false;
                        }
                    }
                    self.pending_dcomp_releases.retain(|r| r.entity_id != id);
                } else {
                    // 実体表示
                    current_promoted_ids.push(id);
                    cx.topology
                        .topo_active_masks
                        .at_mut(id)
                        .unset(ComponentMask::COMP_EXTERNAL_TEXTURE_CONTENT);

                    // 遅延解放待ちにあれば解除
                    self.pending_dcomp_releases.retain(|r| r.entity_id != id);

                    // DComp ツリーへのマウント
                    if let Some(pos) = self.promoted_visuals.iter().position(|v| v.entity_id == id)
                    {
                        let promoted = &mut self.promoted_visuals[pos];
                        if !promoted.is_visible {
                            let _ = self.root_visual.AddVisual(
                                &promoted.visual,
                                false,
                                &self.wgpu_visual,
                            );
                            promoted.is_visible = true;
                        }
                    } else {
                        let _ = self
                            .root_visual
                            .AddVisual(&dcomp_visual, false, &self.wgpu_visual);
                        self.promoted_visuals.push(PromotedVisual {
                            entity_id: id,
                            visual: dcomp_visual.clone(),
                            transform: None,
                            is_visible: true,
                        });
                    }

                    // wgpu に穴あけ(Punchout)を指示
                    cx.renders.rnd_active_external_visual.insert(id);
                    cx.contents.cont_external_textures.remove(id);
                }
            }

            // アクティブから消えた(要素がデスポーンした)Visual をクリーンアップ
            let mut i = 0;
            while i < self.promoted_visuals.len() {
                let id = self.promoted_visuals[i].entity_id;

                // 生存していない(despawn済みの)要素はクリーンアップ
                if !cx.topology.topo_entities.contains_key(id) {
                    let promoted = &self.promoted_visuals[i];
                    if promoted.is_visible {
                        let _ = self.root_visual.RemoveVisual(&promoted.visual);
                    }
                    self.promoted_visuals.remove(i);
                    continue;
                }

                let is_pending_release = self
                    .pending_dcomp_releases
                    .iter()
                    .any(|r| r.entity_id == id);

                // 生きてはいるが、アクティブ維持対象外になった(静止画像へ移行した)もの
                if !current_promoted_ids.contains(&id) && !is_pending_release {
                    let promoted = &mut self.promoted_visuals[i];

                    // すでにキャッシュが存在し、表示維持が不要になったため、即座に非表示常駐化
                    if promoted.is_visible {
                        let _ = self.root_visual.RemoveVisual(&promoted.visual);
                        promoted.is_visible = false;
                    }
                }
                i += 1;
            }
        }
    }

    /// あらゆる `ExternalVisual` に共通の同期ヘルパー
    #[track_caller]
    fn sync_visual_layout_and_clip(
        &self,
        id: EntityId,
        visual: &IDCompositionVisual2,
        metadata: ExternalVisualMetadata,
        cx: &mut Context,
    ) {
        unsafe {
            let rect = cx.outputs.out_rects.find_or_default(id, &mut cx.debug);
            let clip_rect = cx.outputs.out_clip_rects.find_or_default(id, &mut cx.debug);
            let prev_rect = cx.outputs.out_prev_rects.find_or_default(id, &mut cx.debug);
            let prev_clip = cx
                .outputs
                .out_prev_clip_rects
                .find_or_default(id, &mut cx.debug);

            let has_active_transform_anim =
                cx.renders
                    .rnd_active_transitions
                    .find(id)
                    .is_some_and(|list| {
                        list.iter()
                            .any(|t| t.property_list == PropertyList::Transform)
                    });
            let is_resizing = cx.window.win_is_resized;

            // 変化がなければ早期リターン(点滅・CPU負荷防止)
            // sync_layout で prev_rects が既にスワップされているケースを考慮し、
            // 初回またはリサイズ時は確実に同期を通す
            if !is_resizing
                && rect == prev_rect
                && clip_rect == prev_clip
                && !has_active_transform_anim
            {
                return;
            }

            // 位置同期 (物理ピクセル)
            let phys_x = rect.x * self.scale_factor;
            let phys_y = rect.y * self.scale_factor;
            let _ = visual.SetOffsetX2(phys_x);
            let _ = visual.SetOffsetY2(phys_y);

            // 2D アフィン変換 (Transform2) の同期
            if metadata.auto_transform
                && let Some(visual_prop) = cx.renders.rnd_visual.find(id)
            {
                if let Some(m) = visual_prop.transform {
                    let m11 = m[0][0];
                    let m12 = m[0][1];
                    let m21 = m[1][0];
                    let m22 = m[1][1];
                    let tx = m[3][0] * self.scale_factor;
                    let ty = m[3][1] * self.scale_factor;

                    let origin = visual_prop
                        .transform_origin
                        .map_or([0.5, 0.5], |p| [p.x, p.y]);
                    let origin_x = origin[0] * rect.width * self.scale_factor;
                    let origin_y = origin[1] * rect.height * self.scale_factor;

                    let m31 = (1.0 - m11) * origin_x - m21 * origin_y + tx;
                    let m32 = -m12 * origin_x + (1.0 - m22) * origin_y + ty;

                    let dcomp_matrix = Matrix3x2 {
                        M11: m11,
                        M12: m12,
                        M21: m21,
                        M22: m22,
                        M31: m31,
                        M32: m32,
                    };
                    let _ = visual.SetTransform2(&raw const dcomp_matrix);
                } else {
                    let identity = Matrix3x2 {
                        M11: 1.0,
                        M12: 0.0,
                        M21: 0.0,
                        M22: 1.0,
                        M31: 0.0,
                        M32: 0.0,
                    };
                    let _ = visual.SetTransform2(&raw const identity);
                }
            }

            // 角丸・Scissor クリップ (RectangleClip) の同期
            if metadata.auto_clip
                && let Some(visual_prop) = cx.renders.rnd_visual.find(id)
            {
                let desktop_device = self.desktop_device.clone();
                if let Ok(rectangle_clip) = desktop_device.CreateRectangleClip() {
                    let clip_left = (clip_rect.x - rect.x).max(0.0) * self.scale_factor;
                    let clip_top = (clip_rect.y - rect.y).max(0.0) * self.scale_factor;
                    let clip_right = ((clip_rect.x + clip_rect.width) - rect.x).min(rect.width)
                        * self.scale_factor;
                    let clip_bottom = ((clip_rect.y + clip_rect.height) - rect.y).min(rect.height)
                        * self.scale_factor;

                    let _ = rectangle_clip.SetLeft2(clip_left);
                    let _ = rectangle_clip.SetTop2(clip_top);
                    let _ = rectangle_clip.SetRight2(clip_right);
                    let _ = rectangle_clip.SetBottom2(clip_bottom);

                    if let Some(radius) = visual_prop.corner_radius {
                        let r = radius.top_left * self.scale_factor;
                        let _ = rectangle_clip.SetTopLeftRadiusX2(r);
                        let _ = rectangle_clip.SetTopLeftRadiusY2(r);
                        let _ = rectangle_clip.SetTopRightRadiusX2(r);
                        let _ = rectangle_clip.SetTopRightRadiusY2(r);
                        let _ = rectangle_clip.SetBottomLeftRadiusX2(r);
                        let _ = rectangle_clip.SetBottomLeftRadiusY2(r);
                        let _ = rectangle_clip.SetBottomRightRadiusX2(r);
                        let _ = rectangle_clip.SetBottomRightRadiusY2(r);
                    } else {
                        let _ = rectangle_clip.SetTopLeftRadiusX2(0.0);
                        let _ = rectangle_clip.SetTopLeftRadiusY2(0.0);
                    }

                    let _ = visual.SetClip(&rectangle_clip);
                }
            }
        }
    }

    // ウィンドウハンドル (HWND) が手元にある状態からスタート
    pub(crate) fn setup_direct_composition(
        hwnd: HWND,
    ) -> crate::Result<(
        ID3D11Device,
        IDCompositionDesktopDevice,
        IDCompositionTarget,
        IDCompositionVisual2, // root_visual
        IDCompositionVisual2, // wgpu_visual
    )> {
        unsafe {
            // 1. D3D11 デバイスを作成
            // グローバルなマネージャーの解決を試みる(失敗時は呼び出し元にエラーを伝播できるよう、後々 Result にするか
            // ここではひとまず unwrap() などで処理する形
            let manager = DCompDeviceManager::global()?;
            let d3d11_device = manager.d3d11_device.clone();
            let desktop_device = manager.desktop_device.clone();

            let target = desktop_device.CreateTargetForHwnd(hwnd, true)?;
            let root_visual = desktop_device.CreateVisual()?;
            target.SetRoot(&root_visual)?;

            // wgpu 用のメインビジュアルを1つだけ作成して登録
            let wgpu_visual = desktop_device.CreateVisual()?;
            root_visual.AddVisual(&wgpu_visual, true, None)?;

            // 変更をコンポジターにコミットして反映
            desktop_device.Commit()?;

            Ok((
                d3d11_device,
                desktop_device,
                target,
                root_visual,
                wgpu_visual,
            ))
        }
    }

    /// Identifies the topmost `ExternalVisual` based on physical pixel coordinates
    /// and forwards the raw input.
    ///
    ///  Returns true if the event has been consumed.
    #[inline]
    pub fn dispatch_raw_input_to_external_visual(
        cx: &mut Context,
        msg: u32,
        wparam: WPARAM,
        lparam: LPARAM,
        window_phys_pos: LayoutPoint,
        scale_factor: f32,
    ) -> bool {
        crate::dispatch_raw_input_to_external_visual(
            cx,
            msg,
            wparam,
            lparam,
            window_phys_pos,
            scale_factor,
        )
    }

    #[inline]
    #[must_use]
    pub fn hwnd(&self) -> HWND {
        self.hwnd
    }

    #[inline]
    #[must_use]
    pub fn layout_size(&self) -> LayoutSize {
        self.layout_size
    }

    #[inline]
    #[must_use]
    pub fn scale_factor(&self) -> f32 {
        self.scale_factor
    }

    #[inline]
    #[must_use]
    pub fn wic_factory(&self) -> &IWICImagingFactory {
        &self.wic_factory
    }

    #[inline]
    #[must_use]
    pub fn d3d11_device(&self) -> &ID3D11Device {
        &self.d3d11_device
    }

    #[inline]
    #[must_use]
    pub fn desktop_device(&self) -> &IDCompositionDesktopDevice {
        &self.desktop_device
    }

    #[inline]
    pub fn composition_device(&self) -> windows_core::Result<IDCompositionDevice> {
        let result: IDCompositionDevice = self.desktop_device.clone().cast()?;
        Ok(result)
    }

    #[inline]
    #[must_use]
    pub fn target(&self) -> &IDCompositionTarget {
        &self.target
    }

    #[inline]
    #[must_use]
    pub fn root_visual(&self) -> &IDCompositionVisual2 {
        &self.root_visual
    }

    #[inline]
    #[must_use]
    pub fn wgpu_visual(&self) -> &IDCompositionVisual2 {
        &self.wgpu_visual
    }

    #[inline]
    #[must_use]
    pub fn promoted_visuals(&self) -> &[PromotedVisual] {
        &self.promoted_visuals
    }

    #[inline]
    #[must_use]
    pub fn pending_dcomp_releases(&self) -> &[PendingDcompRelease] {
        &self.pending_dcomp_releases
    }

    #[inline]
    #[must_use]
    pub fn current_backdrop(&self) -> &Backdrop {
        &self.current_backdrop
    }

    #[inline]
    #[must_use]
    pub fn resize_cooldown_frames(&self) -> u32 {
        self.resize_cooldown_frames
    }

    #[inline]
    #[must_use]
    pub fn wgpu_renderer(&self) -> &WgpuRenderer {
        &self.wgpu_renderer
    }

    #[inline]
    #[must_use]
    pub fn raw_wgpu_renderer_mut(&mut self) -> RawWgpuRenderer<'_> {
        self.wgpu_renderer.raw_wgpu_renderer_mut()
    }

    #[inline]
    #[must_use]
    pub fn raw_composed_renderer_mut(&mut self) -> RawComposedRenderer<'_> {
        RawComposedRenderer {
            hwnd: &mut self.hwnd,
            layout_size: &mut self.layout_size,
            scale_factor: &mut self.scale_factor,
            wic_factory: &mut self.wic_factory,
            d3d11_device: &mut self.d3d11_device,
            desktop_device: &mut self.desktop_device,
            target: &mut self.target,
            root_visual: &mut self.root_visual,
            wgpu_visual: &mut self.wgpu_visual,
            promoted_visuals: &mut self.promoted_visuals,
            pending_dcomp_releases: &mut self.pending_dcomp_releases,
            current_backdrop: &mut self.current_backdrop,
            resize_cooldown_frames: &mut self.resize_cooldown_frames,
        }
    }
}

pub struct RawComposedRenderer<'a> {
    pub hwnd: &'a mut HWND,
    pub layout_size: &'a mut LayoutSize,
    pub scale_factor: &'a mut f32,
    pub wic_factory: &'a mut IWICImagingFactory,
    pub d3d11_device: &'a mut ID3D11Device,
    pub desktop_device: &'a mut IDCompositionDesktopDevice,
    pub target: &'a mut IDCompositionTarget,
    pub root_visual: &'a mut IDCompositionVisual2,
    pub wgpu_visual: &'a mut IDCompositionVisual2,
    pub promoted_visuals: &'a mut Vec<PromotedVisual>,
    pub pending_dcomp_releases: &'a mut Vec<PendingDcompRelease>,
    pub current_backdrop: &'a mut Backdrop,
    pub resize_cooldown_frames: &'a mut u32,
}

#[track_caller]
fn is_element_interactive(cx: &Context, id: EntityId) -> bool {
    let is_focused = cx.interaction_id(InteractionState::Focused) == Some(id);
    let is_pressed = cx.interaction_id(InteractionState::Pressed) == Some(id);
    is_focused || is_pressed
}

fn is_element_transitioning(cx: &Context, id: EntityId) -> bool {
    cx.renders
        .rnd_active_transitions
        .find(id)
        .is_some_and(|list| {
            list.iter().any(|t| {
                t.property_list == PropertyList::Width
                    || t.property_list == PropertyList::Height
                    || t.property_list == PropertyList::Size
                    || t.property_list == PropertyList::Transform
            })
        })
        || cx
            .renders
            .rnd_active_animations
            .find(id)
            .is_some_and(|list| {
                list.iter().any(|a| {
                    a.property == PropertyList::Width
                        || a.property == PropertyList::Height
                        || a.property == PropertyList::Size
                        || a.property == PropertyList::Transform
                })
            })
}

pub(crate) struct DCompDeviceManager {
    pub(crate) d3d11_device: ID3D11Device,
    pub(crate) desktop_device: IDCompositionDesktopDevice,
}

unsafe impl Send for DCompDeviceManager {}
unsafe impl Sync for DCompDeviceManager {}

impl DCompDeviceManager {
    /// デバイスマネージャーのグローバル参照を取得。
    /// 未初期化、または過去の初期化でエラーが起きていた場合は再試行。
    pub(crate) fn global() -> crate::Result<&'static Self> {
        static INSTANCE: OnceLock<DCompDeviceManager> = OnceLock::new();

        if let Some(manager) = INSTANCE.get() {
            return Ok(manager);
        }

        let manager = Self::try_create_devices()?;

        // 完全に成功した場合にのみ OnceLock に実体をセットする。
        // 複数スレッドで同時に成功した場合、最初に完了した方がセットされ、
        // もう一方は set() で Err(manager) を返すが、
        // 最終的に get() 側で正しく1つのインスタンスに統合されるため安全。
        let _ = INSTANCE.set(manager);

        INSTANCE
            .get()
            .ok_or(MichiuError::UninitializedDeviceManager)
    }

    /// デバイスの生成・クエリを試みる、失敗を許容する内部ヘルパー
    fn try_create_devices() -> crate::Result<Self> {
        // D3D11 デバイスを作成
        let mut d3d11_device: Option<ID3D11Device> = None;
        unsafe {
            D3D11CreateDevice(
                None,
                D3D_DRIVER_TYPE_HARDWARE,
                HMODULE::default(),
                D3D11_CREATE_DEVICE_BGRA_SUPPORT,
                None,
                D3D11_SDK_VERSION,
                Some(&raw mut d3d11_device),
                None,
                None,
            )?;
        }
        let d3d11_device = d3d11_device.ok_or(MichiuError::D3d11DeviceCreationFailed)?;

        // DXGI デバイスをクエリ
        // let dxgi_device: IDXGIDevice = d3d11_device.cast()?;

        // windows-rs の型ミスマッチを防ぐため、一度 IUnknown にキャスト
        // let rendering_device: windows::core::IUnknown = dxgi_device.cast()?;

        // DCompositionCreateDevice ではなく DCompositionCreateDevice2 を使用。
        // これにより IDCompositionDesktopDevice の生成が正しくサポートされる。
        let desktop_device: IDCompositionDesktopDevice =
            unsafe { DCompositionCreateDevice2(None) }?;

        Ok(DCompDeviceManager {
            d3d11_device,
            desktop_device,
        })
    }
}

#[link(name = "dwmapi")]
unsafe extern "system" {
    fn DwmSetWindowAttribute(
        hwnd: HWND,
        dwattribute: u32,
        pvattribute: *const std::ffi::c_void,
        cbattribute: u32,
    ) -> windows::core::HRESULT;
}

// フレーム拡張用構造体
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct Margins {
    pub left: i32,
    pub right: i32,
    pub top: i32,
    pub bottom: i32,
}

#[link(name = "dwmapi")]
unsafe extern "system" {
    fn DwmExtendFrameIntoClientArea(
        hwnd: HWND,
        pMarInset: *const Margins,
    ) -> windows::core::HRESULT;
}

// apply_system_backdrop を拡張してダークモードとフレーム拡張を統合
#[expect(clippy::cast_possible_truncation)]
pub(crate) fn apply_system_backdrop(hwnd: HWND, backdrop: Backdrop) {
    unsafe {
        // DWMWA_USE_HOSTBACKDROPBRUSH (17) を TRUE に設定
        // DComp(NOREDIRECTIONBITMAP)ウィンドウでアクリル・Micaを透かすため
        let enable_host_backdrop: i32 = 1; // 1 = TRUE
        let _ = DwmSetWindowAttribute(
            hwnd,
            17, // DWMWA_USE_HOSTBACKDROPBRUSH
            (&raw const enable_host_backdrop).cast(),
            std::mem::size_of::<i32>() as u32,
        );
        // DWMWA_USE_IMMERSIVE_DARK_MODE (20) を true に設定(ダークアクリル下地を強制)
        let dark_mode: i32 = 1; // 1 = true
        let _ = DwmSetWindowAttribute(
            hwnd,
            20, // DWMWA_USE_IMMERSIVE_DARK_MODE
            (&raw const dark_mode).cast(),
            std::mem::size_of::<i32>() as u32,
        );

        // DWMWA_USE_HOSTBACKDROPBRUSH (36) を true に設定
        // WS_EX_NOREDIRECTIONBITMAP ウィンドウの背後に
        // DWM が自動でアクリル用のぼかし背景ブラシ(BackdropBrush)を合成
        let use_host_backdrop: i32 = 1; // 1 = TRUE
        let _ = DwmSetWindowAttribute(
            hwnd,
            36, // DWMWA_USE_HOSTBACKDROPBRUSH
            (&raw const use_host_backdrop).cast(),
            std::mem::size_of::<i32>() as u32,
        );

        // DWMWA_SYSTEMBACKDROP_TYPE (38) の設定(アクリル/Micaの適用)
        let backdrop_val = backdrop as i32;
        let _ = DwmSetWindowAttribute(
            hwnd,
            38, // DWMWA_SYSTEMBACKDROP_TYPE
            (&raw const backdrop_val).cast(),
            std::mem::size_of::<i32>() as u32,
        );

        // クライアント領域全体にアクリル・Micaを拡張 (DwmExtendFrameIntoClientArea)
        if backdrop == Backdrop::None {
            // 通常時はフレーム拡張をクリア (0)
            let margins = Margins {
                left: 0,
                right: 0,
                top: 0,
                bottom: 0,
            };
            let _ = DwmExtendFrameIntoClientArea(hwnd, &raw const margins);
        } else {
            // margins に -1 を指定することで、ウィンドウ全体にアクリルを浸透
            let margins = Margins {
                left: -1,
                right: -1,
                top: -1,
                bottom: -1,
            };
            let _ = DwmExtendFrameIntoClientArea(hwnd, &raw const margins);
        }
    }
}