euv-core 0.47.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
use super::*;

/// Canonical identifier, global JS namespace, template extension, and tag helpers for `MiniAppVendor`.
impl MiniAppVendor {
    /// Returns the canonical lowercase vendor string identifier.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program vendor variant.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Canonical vendor identifier.
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match *self {
            Self::WeChat => MINIAPP_VENDOR_WECHAT,
            Self::Alipay => MINIAPP_VENDOR_ALIPAY,
            Self::Douyin => MINIAPP_VENDOR_DOUYIN,
            Self::Baidu => MINIAPP_VENDOR_BAIDU,
            Self::Qq => MINIAPP_VENDOR_QQ,
            Self::Kuaishou => MINIAPP_VENDOR_KUAISHOU,
            Self::HarmonyAtomic => MINIAPP_VENDOR_HARMONY_ATOMIC,
        }
    }

    /// Returns the vendor's global runtime API object name (`wx`, `my`, `tt`, `swan`, `qq`, `ks`, `atomic`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program vendor variant.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Global JS/ArkTS host namespace identifier.
    #[must_use]
    pub const fn global_namespace(&self) -> &'static str {
        match *self {
            Self::WeChat => MINIAPP_GLOBAL_WECHAT,
            Self::Alipay => MINIAPP_GLOBAL_ALIPAY,
            Self::Douyin => MINIAPP_GLOBAL_DOUYIN,
            Self::Baidu => MINIAPP_GLOBAL_BAIDU,
            Self::Qq => MINIAPP_GLOBAL_QQ,
            Self::Kuaishou => MINIAPP_GLOBAL_KUAISHOU,
            Self::HarmonyAtomic => MINIAPP_GLOBAL_HARMONY_ATOMIC,
        }
    }

    /// Returns the host page markup file extension used by the vendor shell generator.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program vendor variant.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Template extension without leading dot (`wxml`, `axml`, `ttml`, `swan`, `qml`, `ksml`, `ets`).
    #[must_use]
    pub const fn template_extension(&self) -> &'static str {
        match *self {
            Self::WeChat => MINIAPP_EXT_WXML,
            Self::Alipay => MINIAPP_EXT_AXML,
            Self::Douyin => MINIAPP_EXT_TTML,
            Self::Baidu => MINIAPP_EXT_SWAN,
            Self::Qq => MINIAPP_EXT_QML,
            Self::Kuaishou => MINIAPP_EXT_KSML,
            Self::HarmonyAtomic => MINIAPP_EXT_ETS,
        }
    }

    /// Returns a compact ABI tag byte stored in `RawWindowHandle::MiniAppCanvas`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program vendor variant.
    ///
    /// # Returns
    ///
    /// - `u8` - Numeric vendor discriminant (`1..=7`).
    #[must_use]
    pub const fn tag(&self) -> u8 {
        match *self {
            Self::WeChat => 1,
            Self::Alipay => 2,
            Self::Douyin => 3,
            Self::Baidu => 4,
            Self::Qq => 5,
            Self::Kuaishou => 6,
            Self::HarmonyAtomic => 7,
        }
    }

    /// Returns all 7 supported Mini-Program and Atomic Service vendors.
    ///
    /// # Returns
    ///
    /// - `[Self; 7]` - Complete array of Mini-Program vendors.
    #[must_use]
    pub const fn all_vendors() -> [Self; 7] {
        [
            Self::WeChat,
            Self::Alipay,
            Self::Douyin,
            Self::Baidu,
            Self::Qq,
            Self::Kuaishou,
            Self::HarmonyAtomic,
        ]
    }
}

/// Default `MiniAppSystemInfo` modeling a modern 390x844@3x smartphone Mini-Program container with floating capsule.
impl Default for MiniAppSystemInfo {
    /// Creates default WeChat Mini-Program system info metrics.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `MiniAppSystemInfo`.
    fn default() -> Self {
        Self::for_vendor(MiniAppVendor::WeChat)
    }
}

/// Preset builders for `MiniAppSystemInfo`.
impl MiniAppSystemInfo {
    /// Creates realistic default system metrics including floating capsule button geometry for `vendor`.
    ///
    /// # Arguments
    ///
    /// - `MiniAppVendor` - Target Mini-Program vendor.
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized `MiniAppSystemInfo` preset.
    #[must_use]
    pub fn for_vendor(vendor: MiniAppVendor) -> Self {
        let top: f32 = MINIAPP_DEFAULT_STATUS_BAR_DP + 4.0;
        let right: f32 = (MINIAPP_DEFAULT_WIDTH as f32) - MINIAPP_DEFAULT_CAPSULE_RIGHT_MARGIN;
        let left: f32 = right - MINIAPP_DEFAULT_CAPSULE_W;
        let bottom: f32 = top + MINIAPP_DEFAULT_CAPSULE_H;
        let capsule: MiniAppCapsuleRect = MiniAppCapsuleRect::new(
            top,
            right,
            bottom,
            left,
            MINIAPP_DEFAULT_CAPSULE_W,
            MINIAPP_DEFAULT_CAPSULE_H,
        );
        let canvas_mode: MiniAppCanvasMode = match vendor {
            MiniAppVendor::HarmonyAtomic => MiniAppCanvasMode::WebGl2,
            _ => MiniAppCanvasMode::Canvas2d,
        };
        Self {
            vendor,
            window_width: MINIAPP_DEFAULT_WIDTH,
            window_height: MINIAPP_DEFAULT_HEIGHT,
            pixel_ratio: MINIAPP_DEFAULT_DPR,
            status_bar_height: MINIAPP_DEFAULT_STATUS_BAR_DP,
            safe_area: SafeAreaInsets::new(
                MINIAPP_DEFAULT_STATUS_BAR_DP,
                0.0,
                MINIAPP_DEFAULT_SAFE_BOTTOM_DP,
                0.0,
            ),
            capsule,
            theme: ThemeMode::Light,
            language: MINIAPP_DEFAULT_LANGUAGE.to_string(),
            canvas_mode,
        }
    }
}

/// Default `MiniAppPlatform` targeting WeChat (`MiniAppVendor::WeChat`).
impl Default for MiniAppPlatform {
    /// Creates a default WeChat Mini-Program host adapter.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `MiniAppPlatform`.
    fn default() -> Self {
        Self::for_vendor(MiniAppVendor::WeChat)
    }
}

/// Vendor constructors, touch/IME/lifecycle translation, and outbound bridge queue helpers for `MiniAppPlatform`.
impl MiniAppPlatform {
    /// Creates a `MiniAppPlatform` configured for `vendor` with capsule-cleared safe-area insets.
    ///
    /// # Arguments
    ///
    /// - `MiniAppVendor` - Target Mini-Program host vendor.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured Mini-Program backend.
    #[must_use]
    pub fn for_vendor(vendor: MiniAppVendor) -> Self {
        Self::from_system_info(MiniAppSystemInfo::for_vendor(vendor))
    }

    /// Creates a `MiniAppPlatform` from concrete host `MiniAppSystemInfo`.
    ///
    /// # Arguments
    ///
    /// - `MiniAppSystemInfo` - Runtime system info reported by the host shell.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured Mini-Program backend.
    #[must_use]
    pub fn from_system_info(system_info: MiniAppSystemInfo) -> Self {
        let safe_area: SafeAreaInsets = resolve_miniapp_safe_area(&system_info, true);
        Self {
            system_info,
            resolved_safe_area: safe_area,
            next_id: 1,
            primary_window: None,
            windows: HashMap::new(),
            touch_tracker: TouchPointerTracker::default(),
            pending_events: Vec::new(),
            outbound_commands: Vec::new(),
            storage: HashMap::new(),
            route_stack: vec![MINIAPP_DEFAULT_ROUTE.to_string()],
            clipboard: None,
            pump_paused: false,
        }
    }

    /// Returns the primary Mini-Program canvas window identifier, if created.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `Option<WindowId>` - Primary canvas window handle.
    #[must_use]
    pub fn primary_window_id(&self) -> Option<WindowId> {
        let Self { primary_window, .. } = self;
        *primary_window
    }

    /// Drains all queued outbound host bridge commands for execution by the thin JS/ArkTS shell.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    ///
    /// # Returns
    ///
    /// - `Vec<MiniAppHostCommand>` - Ordered host commands.
    pub fn drain_host_commands(&mut self) -> Vec<MiniAppHostCommand> {
        take(self.get_mut_outbound_commands())
    }

    /// Updates host `MiniAppSystemInfo` (e.g. after orientation change or capsule query) and emits `SafeAreaChanged`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `MiniAppSystemInfo` - Updated host system info.
    pub fn update_system_info(&mut self, info: MiniAppSystemInfo) {
        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
        let safe: SafeAreaInsets = resolve_miniapp_safe_area(&info, true);
        let w: u32 = info.get_window_width().max(1);
        let h: u32 = info.get_window_height().max(1);
        let dpr: f32 = info.get_pixel_ratio().clamp(0.5, 4.5);
        self.set_system_info(info);
        self.set_resolved_safe_area(safe);
        for rec in self.get_mut_windows().values_mut() {
            rec.get_mut_state()
                .set_logical_width(w as f32)
                .set_logical_height(h as f32)
                .set_physical_width(((w as f32) * dpr).round() as u32)
                .set_physical_height(((h as f32) * dpr).round() as u32)
                .set_scale_factor(dpr)
                .set_safe_area(safe);
        }
        self.get_mut_pending_events()
            .push(WindowEvent::SafeAreaChanged(wid, safe));
        self.get_mut_pending_events()
            .push(WindowEvent::System(SystemEvent::SafeAreaChanged(safe)));
    }

    /// Translates Mini-Program `<canvas>` touch callbacks (`touchstart`/`touchmove`/`touchend`/`touchcancel`) into EUV pointer events.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `i32` - Normalized action (`ANDROID_ACTION_DOWN` / `MOVE` / `UP` / `CANCEL`).
    /// - `&[(i32, f32, f32)]` - Active touch contact tuples `(identifier, logical_x, logical_y)`.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Normalized pointer events also enqueued for `poll_events()`.
    pub fn handle_touch(&mut self, action: i32, touches: &[(i32, f32, f32)]) -> Vec<WindowEvent> {
        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
        let events: Vec<WindowEvent> = self
            .get_mut_touch_tracker()
            .handle_android_motion(wid, action, 0, touches);
        self.get_mut_pending_events().extend(events.clone());
        events
    }

    /// Dispatches UTF-8 text input received from a hidden Mini-Program `<input>` or `onKeyboardInput` bridge.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `String` - Committed UTF-8 text.
    /// - `bool` - When `true`, also emits `KeyCode::Enter` confirmation.
    pub fn handle_ime_input(&mut self, text: String, confirmed: bool) {
        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
        if !text.is_empty() {
            self.get_mut_pending_events()
                .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
            self.get_mut_pending_events()
                .push(WindowEvent::TextInput(wid, text));
        }
        if confirmed {
            self.get_mut_pending_events().push(WindowEvent::KeyDown(
                wid,
                KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
            ));
        }
    }

    /// Translates Mini-Program `onLaunch` / `onShow` / `onHide` / `onUnload` and system hooks into canonical EUV `SystemEvent`s.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `MiniAppLifecycleHook` - Vendor-neutral lifecycle hook payload.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Normalized events also enqueued for `poll_events()`.
    pub fn handle_lifecycle_hook(&mut self, hook: MiniAppLifecycleHook) -> Vec<WindowEvent> {
        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
        let mut emitted: Vec<WindowEvent> = Vec::new();
        match hook {
            MiniAppLifecycleHook::OnLaunch { query_uri } => {
                self.set_pump_paused(false);
                if let Some(uri) = query_uri
                    && !uri.is_empty()
                {
                    emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
                }
            }
            MiniAppLifecycleHook::OnShow { query_uri } => {
                self.set_pump_paused(false);
                emitted.push(WindowEvent::System(SystemEvent::Appear));
                emitted.push(WindowEvent::System(SystemEvent::Foreground));
                if let Some(uri) = query_uri
                    && !uri.is_empty()
                {
                    emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
                }
            }
            MiniAppLifecycleHook::OnHide => {
                self.set_pump_paused(true);
                let cancels: Vec<WindowEvent> =
                    self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
                emitted.extend(cancels);
                emitted.push(WindowEvent::System(SystemEvent::Disappear));
                emitted.push(WindowEvent::System(SystemEvent::Background));
            }
            MiniAppLifecycleHook::OnUnload => {
                self.set_pump_paused(true);
                let cancels: Vec<WindowEvent> =
                    self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
                emitted.extend(cancels);
                emitted.push(WindowEvent::System(SystemEvent::Terminate));
            }
            MiniAppLifecycleHook::OnResize {
                width,
                height,
                pixel_ratio,
            } => {
                let w: u32 = width.max(1);
                let h: u32 = height.max(1);
                let dpr: f32 = if pixel_ratio.is_finite() {
                    pixel_ratio.clamp(0.5, 4.5)
                } else {
                    1.0
                };
                self.get_mut_system_info()
                    .set_window_width(w)
                    .set_window_height(h)
                    .set_pixel_ratio(dpr);
                for rec in self.get_mut_windows().values_mut() {
                    rec.get_mut_state()
                        .set_logical_width(w as f32)
                        .set_logical_height(h as f32)
                        .set_physical_width(((w as f32) * dpr).round() as u32)
                        .set_physical_height(((h as f32) * dpr).round() as u32)
                        .set_scale_factor(dpr);
                }
                emitted.push(WindowEvent::Resized(wid, w, h, dpr));
                emitted.push(WindowEvent::System(SystemEvent::Resize {
                    width: w as f32,
                    height: h as f32,
                    scale_factor: dpr,
                }));
            }
            MiniAppLifecycleHook::OnThemeChange(theme) => {
                self.get_mut_system_info().set_theme(theme);
                emitted.push(WindowEvent::ThemeChanged(wid, theme));
                emitted.push(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
            }
            MiniAppLifecycleHook::OnMemoryWarning(level) => {
                let pressure: MemoryPressure = miniapp_memory_level_to_pressure(level);
                emitted.push(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
            }
            MiniAppLifecycleHook::OnKeyboardHeightChange(height) => {
                let h: f32 = if height.is_finite() {
                    height.max(0.0)
                } else {
                    0.0
                };
                emitted.push(WindowEvent::System(
                    SystemEvent::KeyboardVisibilityChanged {
                        visible: h > 0.0,
                        height: h,
                    },
                ));
            }
            MiniAppLifecycleHook::OnNetworkStatusChange(status) => {
                emitted.push(WindowEvent::System(SystemEvent::NetworkStatusChanged(
                    status,
                )));
            }
        }
        self.get_mut_pending_events().extend(emitted.clone());
        emitted
    }
}

/// `WindowController` implementation for `MiniAppPlatform`.
impl WindowController for MiniAppPlatform {
    /// Applies a `WindowCommand` and emits corresponding `MiniAppHostCommand`s when relevant.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `WindowCommand` - Command to apply.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Execution status.
    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
        match command {
            WindowCommand::SetTitle(id, title) => {
                let rec: &mut MiniAppWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().set_title(title.clone());
                self.get_mut_outbound_commands()
                    .push(MiniAppHostCommand::SetNavigationBarTitle(title));
                Ok(())
            }
            WindowCommand::SetIme(id, enabled, rect) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                self.get_mut_outbound_commands()
                    .push(MiniAppHostCommand::ShowKeyboard { enabled, rect });
                Ok(())
            }
            WindowCommand::SetRenderMode(id, mode) => {
                let rec: &mut MiniAppWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().get_mut_render().set_mode(mode);
                let next_canvas: MiniAppCanvasMode = match mode {
                    RenderMode::Software => MiniAppCanvasMode::Canvas2d,
                    RenderMode::Hardware | RenderMode::Hybrid | RenderMode::Auto => {
                        MiniAppCanvasMode::WebGl2
                    }
                };
                rec.set_canvas_mode(next_canvas);
                Ok(())
            }
            WindowCommand::RequestRedraw(id) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                self.get_mut_pending_events()
                    .push(WindowEvent::RedrawRequested(id));
                Ok(())
            }
            WindowCommand::Close(id) => {
                if self.get_mut_windows().remove(&id).is_none() {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                Ok(())
            }
            WindowCommand::SetSize(id, _, _)
            | WindowCommand::SetPosition(id, _, _)
            | WindowCommand::SetResizable(id, _)
            | WindowCommand::SetDecorations(id, _)
            | WindowCommand::SetAlwaysOnTop(id, _)
            | WindowCommand::SetFullscreen(id, _)
            | WindowCommand::SetVisible(id, _)
            | WindowCommand::SetCursor(id, _)
            | WindowCommand::SetStatusBarStyle(id, _) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                Ok(())
            }
        }
    }
}

/// `PlatformBackend` implementation for `MiniAppPlatform`.
impl PlatformBackend for MiniAppPlatform {
    /// Returns `PlatformKind::MiniApp`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `PlatformKind` - `PlatformKind::MiniApp`.
    fn kind(&self) -> PlatformKind {
        PlatformKind::MiniApp
    }

    /// Returns Mini-Program container capability flags (`capsule_chrome = true`, `local_storage = true`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `PlatformCapabilities` - Mini-Program capabilities.
    fn capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities::for_platform(PlatformKind::MiniApp)
    }

    /// Creates a canvas window sized to the host Mini-Program viewport with capsule-cleared safe-area insets.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `&WindowConfig` - Declarative window config.
    ///
    /// # Returns
    ///
    /// - `Result<WindowState, PlatformError>` - Created canvas window state.
    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
        let id: WindowId = WindowId::new(self.get_next_id());
        self.set_next_id(self.get_next_id().wrapping_add(1));
        let mut mini_cfg: WindowConfig = config.clone();
        mini_cfg.set_size(
            self.get_system_info().get_window_width(),
            self.get_system_info().get_window_height(),
        );
        let dpr: f32 = self.get_system_info().get_pixel_ratio();
        let mut state: WindowState = WindowState::from_config(id, &mini_cfg, dpr);
        state.set_safe_area(self.get_resolved_safe_area());
        state.set_system_theme(self.get_system_info().get_theme());
        let record: MiniAppWindowRecord = MiniAppWindowRecord {
            config: mini_cfg,
            state,
            canvas_id: id.get_value() as u32,
            canvas_mode: self.get_system_info().get_canvas_mode(),
            last_frame: Framebuffer::allocate(
                state.get_physical_width(),
                state.get_physical_height(),
            ),
            present_count: 0,
        };
        self.get_mut_windows().insert(id, record);
        if self.primary_window_id().is_none() {
            self.set_primary_window(Some(id));
        }
        Ok(state)
    }

    /// Queries live `WindowState` for `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    /// - `WindowId` - Window identifier.
    ///
    /// # Returns
    ///
    /// - `Option<WindowState>` - Live window state if open.
    fn window_state(&self, id: WindowId) -> Option<WindowState> {
        self.get_windows()
            .get(&id)
            .map(MiniAppWindowRecord::get_state)
    }

    /// Returns `RawWindowHandle::MiniAppCanvas` tagged with the active `MiniAppVendor`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    /// - `WindowId` - Window identifier.
    ///
    /// # Returns
    ///
    /// - `RawWindowHandle` - Mini-Program canvas handle.
    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
        match self.get_windows().get(&id) {
            Some(rec) => RawWindowHandle::MiniAppCanvas {
                canvas_id: rec.get_canvas_id(),
                vendor_tag: self.get_system_info().get_vendor().tag(),
            },
            None => RawWindowHandle::Headless,
        }
    }

    /// Drains queued Mini-Program touch, IME, resize, and lifecycle events.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Pending events.
    fn poll_events(&mut self) -> Vec<WindowEvent> {
        take(self.get_mut_pending_events())
    }

    /// Pauses or resumes the Mini-Program canvas frame pump flag.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `bool` - `true` when hidden.
    fn set_frame_pump_paused(&mut self, paused: bool) {
        self.set_pump_paused(paused);
    }

    /// Returns whether the Mini-Program frame pump is paused.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Pause state.
    fn is_frame_pump_paused(&self) -> bool {
        self.get_pump_paused()
    }

    /// Stores `framebuffer` and queues a `MiniAppHostCommand::PresentCanvas` command for the host canvas context.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `WindowId` - Window identifier.
    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Presentation status.
    fn present_framebuffer(
        &mut self,
        id: WindowId,
        framebuffer: &Framebuffer,
    ) -> Result<(), PlatformError> {
        let mode: MiniAppCanvasMode = {
            let rec: &mut MiniAppWindowRecord = self
                .get_mut_windows()
                .get_mut(&id)
                .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
            rec.set_last_frame(framebuffer.clone());
            rec.set_present_count(rec.get_present_count().wrapping_add(1));
            rec.get_canvas_mode()
        };
        self.get_mut_outbound_commands()
            .push(MiniAppHostCommand::PresentCanvas {
                mode,
                width: framebuffer.get_width(),
                height: framebuffer.get_height(),
            });
        Ok(())
    }

    /// Reads cached clipboard text.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Cached clipboard string.
    fn read_clipboard(&self) -> Option<String> {
        let Self { clipboard, .. } = self;
        clipboard.clone()
    }

    /// Writes `text` to the clipboard cache and queues `MiniAppHostCommand::SetClipboardData`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `&str` - Clipboard text.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Write status.
    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
        self.set_clipboard(Some(text.to_string()));
        self.get_mut_outbound_commands()
            .push(MiniAppHostCommand::SetClipboardData(text.to_string()));
        Ok(())
    }

    /// Returns the active Mini-Program host theme mode.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `ThemeMode` - Active theme mode.
    fn system_theme(&self) -> ThemeMode {
        self.get_system_info().get_theme()
    }
}

/// `PlatformStorage` implementation for `MiniAppPlatform`.
impl PlatformStorage for MiniAppPlatform {
    /// Reads `key` from mirrored Mini-Program sandbox storage.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    /// - `&str` - Storage key.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Stored value, if present.
    fn storage_get(&self, key: &str) -> Option<String> {
        self.get_storage().get(key).cloned()
    }

    /// Writes `(key, value)` to mirrored storage and emits `MiniAppHostCommand::SetStorageSync`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `&str` - Storage key.
    /// - `&str` - Value to store.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Storage status.
    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
        let _: Option<String> = self
            .get_mut_storage()
            .insert(key.to_string(), value.to_string());
        self.get_mut_outbound_commands()
            .push(MiniAppHostCommand::SetStorageSync {
                key: key.to_string(),
                value: value.to_string(),
            });
        Ok(())
    }

    /// Removes `key` from mirrored storage and emits `MiniAppHostCommand::RemoveStorageSync`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `&str` - Storage key.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Removal status.
    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
        let _: Option<String> = self.get_mut_storage().remove(key);
        self.get_mut_outbound_commands()
            .push(MiniAppHostCommand::RemoveStorageSync(key.to_string()));
        Ok(())
    }

    /// Clears mirrored storage and emits `MiniAppHostCommand::ClearStorageSync`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Clear status.
    fn storage_clear(&mut self) -> Result<(), PlatformError> {
        self.get_mut_storage().clear();
        self.get_mut_outbound_commands()
            .push(MiniAppHostCommand::ClearStorageSync);
        Ok(())
    }
}

/// `PlatformNavigation` implementation for `MiniAppPlatform`.
impl PlatformNavigation for MiniAppPlatform {
    /// Pushes `route` onto the Mini-Program navigation stack and emits `MiniAppHostCommand::NavigateTo`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `&str` - Target page route.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Navigation status.
    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
        if !route.is_empty() {
            self.get_mut_route_stack().push(route.to_string());
            self.get_mut_outbound_commands()
                .push(MiniAppHostCommand::NavigateTo(route.to_string()));
        }
        Ok(())
    }

    /// Pops `delta` entries from the navigation stack and emits `MiniAppHostCommand::NavigateBack`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    /// - `u32` - Pages to pop.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Navigation status.
    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
        let steps: u32 = delta.max(1);
        for _ in 0..steps {
            if self.get_route_stack().len() > 1 {
                let _: Option<String> = self.get_mut_route_stack().pop();
            }
        }
        self.get_mut_outbound_commands()
            .push(MiniAppHostCommand::NavigateBack(steps));
        Ok(())
    }

    /// Returns the currently active Mini-Program route path.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `&str` - Active route path.
    fn current_route(&self) -> &str {
        self.get_route_stack()
            .last()
            .map(String::as_str)
            .unwrap_or(MINIAPP_DEFAULT_ROUTE)
    }
}

/// `PlatformLifecycleBridge` implementation for `MiniAppPlatform`.
impl PlatformLifecycleBridge for MiniAppPlatform {
    /// Maps Mini-Program `onHide` into unified freeze semantics.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Normalized freeze events.
    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
        self.handle_lifecycle_hook(MiniAppLifecycleHook::OnHide)
    }

    /// Maps Mini-Program `onShow` into unified resume semantics.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Normalized resume events.
    fn resume_surface(&mut self) -> Vec<WindowEvent> {
        self.handle_lifecycle_hook(MiniAppLifecycleHook::OnShow { query_uri: None })
    }

    /// Maps Mini-Program `onUnload` into unified destroy semantics.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Mini-program platform.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Normalized destroy events.
    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
        self.handle_lifecycle_hook(MiniAppLifecycleHook::OnUnload)
    }
}

/// `PlatformHostAdapter` implementation for `MiniAppPlatform`.
impl PlatformHostAdapter for MiniAppPlatform {
    /// Returns `DeviceFormFactor::MiniProgram`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `DeviceFormFactor` - `DeviceFormFactor::MiniProgram`.
    fn device_form_factor(&self) -> DeviceFormFactor {
        DeviceFormFactor::MiniProgram
    }

    /// Returns the active Mini-Program vendor identifier (`"wechat"`, `"alipay"`, `"douyin"`, etc.).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mini-program platform reference.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Canonical vendor identifier.
    fn host_vendor_name(&self) -> &'static str {
        self.get_system_info().get_vendor().as_str()
    }
}