euv_core/platform/miniapp/impl.rs
1use super::*;
2
3/// Canonical identifier, global JS namespace, template extension, and tag helpers for `MiniAppVendor`.
4impl MiniAppVendor {
5 /// Returns the canonical lowercase vendor string identifier.
6 ///
7 /// # Arguments
8 ///
9 /// - `&Self` - Mini-program vendor variant.
10 ///
11 /// # Returns
12 ///
13 /// - `&'static str` - Canonical vendor identifier.
14 #[must_use]
15 pub const fn as_str(&self) -> &'static str {
16 match *self {
17 Self::WeChat => MINIAPP_VENDOR_WECHAT,
18 Self::Alipay => MINIAPP_VENDOR_ALIPAY,
19 Self::Douyin => MINIAPP_VENDOR_DOUYIN,
20 Self::Baidu => MINIAPP_VENDOR_BAIDU,
21 Self::Qq => MINIAPP_VENDOR_QQ,
22 Self::Kuaishou => MINIAPP_VENDOR_KUAISHOU,
23 Self::Jd => MINIAPP_VENDOR_JD,
24 Self::Xiaohongshu => MINIAPP_VENDOR_XHS,
25 Self::DingTalk => MINIAPP_VENDOR_DINGTALK,
26 Self::Feishu => MINIAPP_VENDOR_FEISHU,
27 Self::Taobao => MINIAPP_VENDOR_TAOBAO,
28 Self::Meituan => MINIAPP_VENDOR_MEITUAN,
29 Self::HarmonyAtomic => MINIAPP_VENDOR_HARMONY_ATOMIC,
30 }
31 }
32
33 /// Parses a canonical Mini-Program vendor identifier or alias into a `MiniAppVendor`.
34 ///
35 /// # Arguments
36 ///
37 /// - `&str` - Vendor identifier or alias (case-insensitive).
38 ///
39 /// # Returns
40 ///
41 /// - `Option<Self>` - Matching `MiniAppVendor`, if recognized.
42 #[must_use]
43 pub fn from_str_id(name: &str) -> Option<Self> {
44 let lower: String = name.trim().to_ascii_lowercase();
45 match lower.as_str() {
46 MINIAPP_VENDOR_WECHAT | MINIAPP_GLOBAL_WECHAT => Some(Self::WeChat),
47 MINIAPP_VENDOR_ALIPAY | MINIAPP_GLOBAL_ALIPAY => Some(Self::Alipay),
48 MINIAPP_VENDOR_DOUYIN | MINIAPP_GLOBAL_DOUYIN | MINIAPP_ALIAS_BYTEDANCE => {
49 Some(Self::Douyin)
50 }
51 MINIAPP_VENDOR_BAIDU | MINIAPP_GLOBAL_BAIDU => Some(Self::Baidu),
52 MINIAPP_VENDOR_QQ => Some(Self::Qq),
53 MINIAPP_VENDOR_KUAISHOU | MINIAPP_GLOBAL_KUAISHOU => Some(Self::Kuaishou),
54 MINIAPP_VENDOR_JD | MINIAPP_ALIAS_JINGDONG => Some(Self::Jd),
55 MINIAPP_VENDOR_XHS | MINIAPP_ALIAS_XIAOHONGSHU | MINIAPP_ALIAS_RED => {
56 Some(Self::Xiaohongshu)
57 }
58 MINIAPP_VENDOR_DINGTALK | MINIAPP_GLOBAL_DINGTALK => Some(Self::DingTalk),
59 MINIAPP_VENDOR_FEISHU | MINIAPP_ALIAS_LARK => Some(Self::Feishu),
60 MINIAPP_VENDOR_TAOBAO | MINIAPP_ALIAS_TB => Some(Self::Taobao),
61 MINIAPP_VENDOR_MEITUAN | MINIAPP_GLOBAL_MEITUAN => Some(Self::Meituan),
62 MINIAPP_VENDOR_HARMONY_ATOMIC | MINIAPP_ALIAS_ATOMIC => Some(Self::HarmonyAtomic),
63 _ => None,
64 }
65 }
66
67 /// Returns the vendor's global runtime API object name (`wx`, `my`, `tt`, `swan`, `qq`, `ks`, `jd`, `xhs`, `dd`, `mt`, `atomic`).
68 ///
69 /// # Arguments
70 ///
71 /// - `&Self` - Mini-program vendor variant.
72 ///
73 /// # Returns
74 ///
75 /// - `&'static str` - Global JS/ArkTS host namespace identifier.
76 #[must_use]
77 pub const fn global_namespace(&self) -> &'static str {
78 match *self {
79 Self::WeChat => MINIAPP_GLOBAL_WECHAT,
80 Self::Alipay => MINIAPP_GLOBAL_ALIPAY,
81 Self::Douyin => MINIAPP_GLOBAL_DOUYIN,
82 Self::Baidu => MINIAPP_GLOBAL_BAIDU,
83 Self::Qq => MINIAPP_GLOBAL_QQ,
84 Self::Kuaishou => MINIAPP_GLOBAL_KUAISHOU,
85 Self::Jd => MINIAPP_GLOBAL_JD,
86 Self::Xiaohongshu => MINIAPP_GLOBAL_XHS,
87 Self::DingTalk => MINIAPP_GLOBAL_DINGTALK,
88 Self::Feishu => MINIAPP_GLOBAL_FEISHU,
89 Self::Taobao => MINIAPP_GLOBAL_TAOBAO,
90 Self::Meituan => MINIAPP_GLOBAL_MEITUAN,
91 Self::HarmonyAtomic => MINIAPP_GLOBAL_HARMONY_ATOMIC,
92 }
93 }
94
95 /// Returns the host page markup file extension used by the vendor shell generator.
96 ///
97 /// # Arguments
98 ///
99 /// - `&Self` - Mini-program vendor variant.
100 ///
101 /// # Returns
102 ///
103 /// - `&'static str` - Template extension without leading dot.
104 #[must_use]
105 pub const fn template_extension(&self) -> &'static str {
106 match *self {
107 Self::WeChat => MINIAPP_EXT_WXML,
108 Self::Alipay | Self::DingTalk | Self::Taobao => MINIAPP_EXT_AXML,
109 Self::Douyin | Self::Feishu => MINIAPP_EXT_TTML,
110 Self::Baidu => MINIAPP_EXT_SWAN,
111 Self::Qq => MINIAPP_EXT_QML,
112 Self::Kuaishou => MINIAPP_EXT_KSML,
113 Self::Jd => MINIAPP_EXT_JXML,
114 Self::Xiaohongshu => MINIAPP_EXT_XHSML,
115 Self::Meituan => MINIAPP_EXT_MXML,
116 Self::HarmonyAtomic => MINIAPP_EXT_ETS,
117 }
118 }
119
120 /// Returns the host stylesheet file extension used by the vendor shell generator.
121 ///
122 /// # Arguments
123 ///
124 /// - `&Self` - Mini-program vendor variant.
125 ///
126 /// # Returns
127 ///
128 /// - `&'static str` - Stylesheet extension without leading dot.
129 #[must_use]
130 pub const fn style_extension(&self) -> &'static str {
131 match *self {
132 Self::WeChat => MINIAPP_STYLE_WXSS,
133 Self::Alipay | Self::DingTalk | Self::Taobao => MINIAPP_STYLE_ACSS,
134 Self::Douyin | Self::Feishu => MINIAPP_STYLE_TTSS,
135 Self::Baidu | Self::Kuaishou | Self::Xiaohongshu => MINIAPP_STYLE_CSS,
136 Self::Qq => MINIAPP_STYLE_QSS,
137 Self::Jd => MINIAPP_STYLE_JXSS,
138 Self::Meituan => MINIAPP_STYLE_MXSS,
139 Self::HarmonyAtomic => MINIAPP_STYLE_ETS,
140 }
141 }
142
143 /// Returns the vendor IDE project configuration filename.
144 ///
145 /// # Arguments
146 ///
147 /// - `&Self` - Mini-program vendor variant.
148 ///
149 /// # Returns
150 ///
151 /// - `&'static str` - Project config filename.
152 #[must_use]
153 pub const fn config_file_name(&self) -> &'static str {
154 match *self {
155 Self::Alipay | Self::DingTalk | Self::Taobao => MINIAPP_CFG_MINI_PROJECT,
156 Self::Baidu => MINIAPP_CFG_PROJECT_SWAN,
157 Self::HarmonyAtomic => MINIAPP_CFG_MODULE_JSON5,
158 _ => MINIAPP_CFG_PROJECT_CONFIG,
159 }
160 }
161
162 /// Returns `true` when the vendor template language uses Alipay-style `onTouchStart` attributes rather than `bindtouchstart`.
163 ///
164 /// # Arguments
165 ///
166 /// - `&Self` - Mini-program vendor variant.
167 ///
168 /// # Returns
169 ///
170 /// - `bool` - `true` for Alipay, DingTalk, and Taobao Mini-Programs.
171 #[must_use]
172 pub const fn uses_alipay_event_syntax(&self) -> bool {
173 matches!(*self, Self::Alipay | Self::DingTalk | Self::Taobao)
174 }
175
176 /// Returns the host WebAssembly global namespace identifier used to instantiate `.wasm` modules.
177 ///
178 /// # Arguments
179 ///
180 /// - `&Self` - Mini-program vendor variant.
181 ///
182 /// # Returns
183 ///
184 /// - `&'static str` - Host WebAssembly global identifier.
185 #[must_use]
186 pub const fn wasm_global_name(&self) -> &'static str {
187 match *self {
188 Self::WeChat => MINIAPP_WASM_WX,
189 Self::Alipay | Self::DingTalk | Self::Taobao => MINIAPP_WASM_MY,
190 Self::Douyin | Self::Feishu => MINIAPP_WASM_TT,
191 Self::Qq => MINIAPP_WASM_QQ,
192 _ => MINIAPP_WASM_STD,
193 }
194 }
195
196 /// Returns a compact ABI tag byte stored in `RawWindowHandle::MiniAppCanvas`.
197 ///
198 /// # Arguments
199 ///
200 /// - `&Self` - Mini-program vendor variant.
201 ///
202 /// # Returns
203 ///
204 /// - `u8` - Numeric vendor discriminant (`1..=13`).
205 #[must_use]
206 pub const fn tag(&self) -> u8 {
207 match *self {
208 Self::WeChat => 1,
209 Self::Alipay => 2,
210 Self::Douyin => 3,
211 Self::Baidu => 4,
212 Self::Qq => 5,
213 Self::Kuaishou => 6,
214 Self::HarmonyAtomic => 7,
215 Self::Jd => 8,
216 Self::Xiaohongshu => 9,
217 Self::DingTalk => 10,
218 Self::Feishu => 11,
219 Self::Taobao => 12,
220 Self::Meituan => 13,
221 }
222 }
223
224 /// Returns all 13 supported mainstream Mini-Program and Atomic Service vendors.
225 ///
226 /// # Returns
227 ///
228 /// - `[Self; 13]` - Complete array of Mini-Program vendors.
229 #[must_use]
230 pub const fn all_vendors() -> [Self; 13] {
231 [
232 Self::WeChat,
233 Self::Alipay,
234 Self::Douyin,
235 Self::Baidu,
236 Self::Qq,
237 Self::Kuaishou,
238 Self::Jd,
239 Self::Xiaohongshu,
240 Self::DingTalk,
241 Self::Feishu,
242 Self::Taobao,
243 Self::Meituan,
244 Self::HarmonyAtomic,
245 ]
246 }
247}
248
249/// Default `MiniAppSystemInfo` modeling a modern 390x844@3x smartphone Mini-Program container with floating capsule.
250impl Default for MiniAppSystemInfo {
251 /// Creates default WeChat Mini-Program system info metrics.
252 ///
253 /// # Returns
254 ///
255 /// - `Self` - Default `MiniAppSystemInfo`.
256 fn default() -> Self {
257 Self::for_vendor(MiniAppVendor::WeChat)
258 }
259}
260
261/// Preset builders for `MiniAppSystemInfo`.
262impl MiniAppSystemInfo {
263 /// Creates realistic default system metrics including floating capsule button geometry for `vendor`.
264 ///
265 /// # Arguments
266 ///
267 /// - `MiniAppVendor` - Target Mini-Program vendor.
268 ///
269 /// # Returns
270 ///
271 /// - `Self` - Normalized `MiniAppSystemInfo` preset.
272 #[must_use]
273 pub fn for_vendor(vendor: MiniAppVendor) -> Self {
274 let top: f32 = MINIAPP_DEFAULT_STATUS_BAR_DP + 4.0;
275 let right: f32 = (MINIAPP_DEFAULT_WIDTH as f32) - MINIAPP_DEFAULT_CAPSULE_RIGHT_MARGIN;
276 let left: f32 = right - MINIAPP_DEFAULT_CAPSULE_W;
277 let bottom: f32 = top + MINIAPP_DEFAULT_CAPSULE_H;
278 let capsule: MiniAppCapsuleRect = MiniAppCapsuleRect::new(
279 top,
280 right,
281 bottom,
282 left,
283 MINIAPP_DEFAULT_CAPSULE_W,
284 MINIAPP_DEFAULT_CAPSULE_H,
285 );
286 let canvas_mode: MiniAppCanvasMode = match vendor {
287 MiniAppVendor::HarmonyAtomic => MiniAppCanvasMode::WebGl2,
288 _ => MiniAppCanvasMode::Canvas2d,
289 };
290 Self {
291 vendor,
292 window_width: MINIAPP_DEFAULT_WIDTH,
293 window_height: MINIAPP_DEFAULT_HEIGHT,
294 pixel_ratio: MINIAPP_DEFAULT_DPR,
295 status_bar_height: MINIAPP_DEFAULT_STATUS_BAR_DP,
296 safe_area: SafeAreaInsets::new(
297 MINIAPP_DEFAULT_STATUS_BAR_DP,
298 0.0,
299 MINIAPP_DEFAULT_SAFE_BOTTOM_DP,
300 0.0,
301 ),
302 capsule,
303 theme: ThemeMode::Light,
304 language: MINIAPP_DEFAULT_LANGUAGE.to_string(),
305 canvas_mode,
306 }
307 }
308}
309
310/// Default `MiniAppPlatform` targeting WeChat (`MiniAppVendor::WeChat`).
311impl Default for MiniAppPlatform {
312 /// Creates a default WeChat Mini-Program host adapter.
313 ///
314 /// # Returns
315 ///
316 /// - `Self` - Default `MiniAppPlatform`.
317 fn default() -> Self {
318 Self::for_vendor(MiniAppVendor::WeChat)
319 }
320}
321
322/// Vendor constructors, touch/IME/lifecycle translation, and outbound bridge queue helpers for `MiniAppPlatform`.
323impl MiniAppPlatform {
324 /// Creates a `MiniAppPlatform` configured for `vendor` with capsule-cleared safe-area insets.
325 ///
326 /// # Arguments
327 ///
328 /// - `MiniAppVendor` - Target Mini-Program host vendor.
329 ///
330 /// # Returns
331 ///
332 /// - `Self` - Configured Mini-Program backend.
333 #[must_use]
334 pub fn for_vendor(vendor: MiniAppVendor) -> Self {
335 Self::from_system_info(MiniAppSystemInfo::for_vendor(vendor))
336 }
337
338 /// Creates a `MiniAppPlatform` from concrete host `MiniAppSystemInfo`.
339 ///
340 /// # Arguments
341 ///
342 /// - `MiniAppSystemInfo` - Runtime system info reported by the host shell.
343 ///
344 /// # Returns
345 ///
346 /// - `Self` - Configured Mini-Program backend.
347 #[must_use]
348 pub fn from_system_info(system_info: MiniAppSystemInfo) -> Self {
349 let safe_area: SafeAreaInsets = resolve_miniapp_safe_area(&system_info, true);
350 Self {
351 system_info,
352 resolved_safe_area: safe_area,
353 next_id: 1,
354 primary_window: None,
355 windows: HashMap::new(),
356 touch_tracker: TouchPointerTracker::default(),
357 pending_events: Vec::new(),
358 outbound_commands: Vec::new(),
359 storage: HashMap::new(),
360 route_stack: vec![MINIAPP_DEFAULT_ROUTE.to_string()],
361 clipboard: None,
362 pump_paused: false,
363 }
364 }
365
366 /// Returns the primary Mini-Program canvas window identifier, if created.
367 ///
368 /// # Arguments
369 ///
370 /// - `&Self` - Mini-program platform reference.
371 ///
372 /// # Returns
373 ///
374 /// - `Option<WindowId>` - Primary canvas window handle.
375 #[must_use]
376 pub fn primary_window_id(&self) -> Option<WindowId> {
377 let Self { primary_window, .. } = self;
378 *primary_window
379 }
380
381 /// Drains all queued outbound host bridge commands for execution by the thin JS/ArkTS shell.
382 ///
383 /// # Arguments
384 ///
385 /// - `&Self` - Mutable Mini-program platform.
386 ///
387 /// # Returns
388 ///
389 /// - `Vec<MiniAppHostCommand>` - Ordered host commands.
390 pub fn drain_host_commands(&mut self) -> Vec<MiniAppHostCommand> {
391 take(self.get_mut_outbound_commands())
392 }
393
394 /// Updates host `MiniAppSystemInfo` (e.g. after orientation change or capsule query) and emits `SafeAreaChanged`.
395 ///
396 /// # Arguments
397 ///
398 /// - `&Self` - Mutable Mini-program platform.
399 /// - `MiniAppSystemInfo` - Updated host system info.
400 pub fn update_system_info(&mut self, info: MiniAppSystemInfo) {
401 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
402 let safe: SafeAreaInsets = resolve_miniapp_safe_area(&info, true);
403 let w: u32 = info.get_window_width().max(1);
404 let h: u32 = info.get_window_height().max(1);
405 let dpr: f32 = info.get_pixel_ratio().clamp(0.5, 4.5);
406 self.set_system_info(info);
407 self.set_resolved_safe_area(safe);
408 for rec in self.get_mut_windows().values_mut() {
409 rec.get_mut_state()
410 .set_logical_width(w as f32)
411 .set_logical_height(h as f32)
412 .set_physical_width(((w as f32) * dpr).round() as u32)
413 .set_physical_height(((h as f32) * dpr).round() as u32)
414 .set_scale_factor(dpr)
415 .set_safe_area(safe);
416 }
417 self.get_mut_pending_events()
418 .push(WindowEvent::SafeAreaChanged(wid, safe));
419 self.get_mut_pending_events()
420 .push(WindowEvent::System(SystemEvent::SafeAreaChanged(safe)));
421 }
422
423 /// Translates Mini-Program `<canvas>` touch callbacks (`touchstart`/`touchmove`/`touchend`/`touchcancel`) into EUV pointer events.
424 ///
425 /// # Arguments
426 ///
427 /// - `&Self` - Mutable Mini-program platform.
428 /// - `i32` - Normalized action (`ANDROID_ACTION_DOWN` / `MOVE` / `UP` / `CANCEL`).
429 /// - `&[(i32, f32, f32)]` - Active touch contact tuples `(identifier, logical_x, logical_y)`.
430 ///
431 /// # Returns
432 ///
433 /// - `Vec<WindowEvent>` - Normalized pointer events also enqueued for `poll_events()`.
434 pub fn handle_touch(&mut self, action: i32, touches: &[(i32, f32, f32)]) -> Vec<WindowEvent> {
435 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
436 let events: Vec<WindowEvent> = self
437 .get_mut_touch_tracker()
438 .handle_android_motion(wid, action, 0, touches);
439 self.get_mut_pending_events().extend(events.clone());
440 events
441 }
442
443 /// Dispatches UTF-8 text input received from a hidden Mini-Program `<input>` or `onKeyboardInput` bridge.
444 ///
445 /// # Arguments
446 ///
447 /// - `&Self` - Mutable Mini-program platform.
448 /// - `String` - Committed UTF-8 text.
449 /// - `bool` - When `true`, also emits `KeyCode::Enter` confirmation.
450 pub fn handle_ime_input(&mut self, text: String, confirmed: bool) {
451 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
452 if !text.is_empty() {
453 self.get_mut_pending_events()
454 .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
455 self.get_mut_pending_events()
456 .push(WindowEvent::TextInput(wid, text));
457 }
458 if confirmed {
459 self.get_mut_pending_events().push(WindowEvent::KeyDown(
460 wid,
461 KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
462 ));
463 }
464 }
465
466 /// Enqueues a host accelerometer/gyroscope `DeviceMotionSample` received from a Mini-Program sensor listener.
467 ///
468 /// # Arguments
469 ///
470 /// - `&Self` - Mutable Mini-program platform.
471 /// - `DeviceMotionSample` - 6-DOF device motion sample.
472 pub fn handle_device_motion(&mut self, sample: DeviceMotionSample) {
473 self.get_mut_pending_events()
474 .push(WindowEvent::System(SystemEvent::DeviceMotion(sample)));
475 }
476
477 /// Queues a host toast notification command (`showToast`).
478 ///
479 /// # Arguments
480 ///
481 /// - `&Self` - Mutable Mini-program platform.
482 /// - `&str` - Short message text.
483 pub fn show_toast(&mut self, message: &str) {
484 self.get_mut_outbound_commands()
485 .push(MiniAppHostCommand::ShowToast(message.to_string()));
486 }
487
488 /// Queues an external URL open request for the host Mini-Program bridge.
489 ///
490 /// # Arguments
491 ///
492 /// - `&Self` - Mutable Mini-program platform.
493 /// - `&str` - Target URL string.
494 pub fn open_url(&mut self, url: &str) {
495 self.get_mut_outbound_commands()
496 .push(MiniAppHostCommand::OpenUrl(url.to_string()));
497 }
498
499 /// Translates Mini-Program `onLaunch` / `onShow` / `onHide` / `onUnload` and system hooks into canonical EUV `SystemEvent`s.
500 ///
501 /// # Arguments
502 ///
503 /// - `&Self` - Mutable Mini-program platform.
504 /// - `MiniAppLifecycleHook` - Vendor-neutral lifecycle hook payload.
505 ///
506 /// # Returns
507 ///
508 /// - `Vec<WindowEvent>` - Normalized events also enqueued for `poll_events()`.
509 pub fn handle_lifecycle_hook(&mut self, hook: MiniAppLifecycleHook) -> Vec<WindowEvent> {
510 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
511 let mut emitted: Vec<WindowEvent> = Vec::new();
512 match hook {
513 MiniAppLifecycleHook::OnLaunch { query_uri } => {
514 self.set_pump_paused(false);
515 if let Some(uri) = query_uri
516 && !uri.is_empty()
517 {
518 emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
519 }
520 }
521 MiniAppLifecycleHook::OnShow { query_uri } => {
522 self.set_pump_paused(false);
523 emitted.push(WindowEvent::System(SystemEvent::Appear));
524 emitted.push(WindowEvent::System(SystemEvent::Foreground));
525 if let Some(uri) = query_uri
526 && !uri.is_empty()
527 {
528 emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
529 }
530 }
531 MiniAppLifecycleHook::OnHide => {
532 self.set_pump_paused(true);
533 let cancels: Vec<WindowEvent> =
534 self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
535 emitted.extend(cancels);
536 emitted.push(WindowEvent::System(SystemEvent::Disappear));
537 emitted.push(WindowEvent::System(SystemEvent::Background));
538 }
539 MiniAppLifecycleHook::OnUnload => {
540 self.set_pump_paused(true);
541 let cancels: Vec<WindowEvent> =
542 self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
543 emitted.extend(cancels);
544 emitted.push(WindowEvent::System(SystemEvent::Terminate));
545 }
546 MiniAppLifecycleHook::OnResize {
547 width,
548 height,
549 pixel_ratio,
550 } => {
551 let w: u32 = width.max(1);
552 let h: u32 = height.max(1);
553 let dpr: f32 = if pixel_ratio.is_finite() {
554 pixel_ratio.clamp(0.5, 4.5)
555 } else {
556 1.0
557 };
558 self.get_mut_system_info()
559 .set_window_width(w)
560 .set_window_height(h)
561 .set_pixel_ratio(dpr);
562 for rec in self.get_mut_windows().values_mut() {
563 rec.get_mut_state()
564 .set_logical_width(w as f32)
565 .set_logical_height(h as f32)
566 .set_physical_width(((w as f32) * dpr).round() as u32)
567 .set_physical_height(((h as f32) * dpr).round() as u32)
568 .set_scale_factor(dpr);
569 }
570 emitted.push(WindowEvent::Resized(wid, w, h, dpr));
571 emitted.push(WindowEvent::System(SystemEvent::Resize {
572 width: w as f32,
573 height: h as f32,
574 scale_factor: dpr,
575 }));
576 }
577 MiniAppLifecycleHook::OnThemeChange(theme) => {
578 self.get_mut_system_info().set_theme(theme);
579 emitted.push(WindowEvent::ThemeChanged(wid, theme));
580 emitted.push(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
581 }
582 MiniAppLifecycleHook::OnMemoryWarning(level) => {
583 let pressure: MemoryPressure = miniapp_memory_level_to_pressure(level);
584 emitted.push(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
585 }
586 MiniAppLifecycleHook::OnKeyboardHeightChange(height) => {
587 let h: f32 = if height.is_finite() {
588 height.max(0.0)
589 } else {
590 0.0
591 };
592 emitted.push(WindowEvent::System(
593 SystemEvent::KeyboardVisibilityChanged {
594 visible: h > 0.0,
595 height: h,
596 },
597 ));
598 }
599 MiniAppLifecycleHook::OnNetworkStatusChange(status) => {
600 emitted.push(WindowEvent::System(SystemEvent::NetworkStatusChanged(
601 status,
602 )));
603 }
604 }
605 self.get_mut_pending_events().extend(emitted.clone());
606 emitted
607 }
608}
609
610/// `WindowController` implementation for `MiniAppPlatform`.
611impl WindowController for MiniAppPlatform {
612 /// Applies a `WindowCommand` and emits corresponding `MiniAppHostCommand`s when relevant.
613 ///
614 /// # Arguments
615 ///
616 /// - `&Self` - Mutable Mini-program platform.
617 /// - `WindowCommand` - Command to apply.
618 ///
619 /// # Returns
620 ///
621 /// - `Result<(), PlatformError>` - Execution status.
622 fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
623 match command {
624 WindowCommand::SetTitle(id, title) => {
625 let rec: &mut MiniAppWindowRecord = self
626 .get_mut_windows()
627 .get_mut(&id)
628 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
629 rec.get_mut_config().set_title(title.clone());
630 self.get_mut_outbound_commands()
631 .push(MiniAppHostCommand::SetNavigationBarTitle(title));
632 Ok(())
633 }
634 WindowCommand::SetIme(id, enabled, rect) => {
635 if !self.get_windows().contains_key(&id) {
636 return Err(PlatformError::WindowNotFound(id.get_value()));
637 }
638 self.get_mut_outbound_commands()
639 .push(MiniAppHostCommand::ShowKeyboard { enabled, rect });
640 Ok(())
641 }
642 WindowCommand::SetRenderMode(id, mode) => {
643 let rec: &mut MiniAppWindowRecord = self
644 .get_mut_windows()
645 .get_mut(&id)
646 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
647 rec.get_mut_config().get_mut_render().set_mode(mode);
648 let next_canvas: MiniAppCanvasMode = match mode {
649 RenderMode::Software => MiniAppCanvasMode::Canvas2d,
650 RenderMode::Hardware | RenderMode::Hybrid | RenderMode::Auto => {
651 MiniAppCanvasMode::WebGl2
652 }
653 };
654 rec.set_canvas_mode(next_canvas);
655 Ok(())
656 }
657 WindowCommand::RequestRedraw(id) => {
658 if !self.get_windows().contains_key(&id) {
659 return Err(PlatformError::WindowNotFound(id.get_value()));
660 }
661 self.get_mut_pending_events()
662 .push(WindowEvent::RedrawRequested(id));
663 Ok(())
664 }
665 WindowCommand::Close(id) => {
666 if self.get_mut_windows().remove(&id).is_none() {
667 return Err(PlatformError::WindowNotFound(id.get_value()));
668 }
669 Ok(())
670 }
671 WindowCommand::SetSize(id, _, _)
672 | WindowCommand::SetPosition(id, _, _)
673 | WindowCommand::SetResizable(id, _)
674 | WindowCommand::SetDecorations(id, _)
675 | WindowCommand::SetAlwaysOnTop(id, _)
676 | WindowCommand::SetFullscreen(id, _)
677 | WindowCommand::SetVisible(id, _)
678 | WindowCommand::SetCursor(id, _)
679 | WindowCommand::SetStatusBarStyle(id, _) => {
680 if !self.get_windows().contains_key(&id) {
681 return Err(PlatformError::WindowNotFound(id.get_value()));
682 }
683 Ok(())
684 }
685 }
686 }
687}
688
689/// `PlatformBackend` implementation for `MiniAppPlatform`.
690impl PlatformBackend for MiniAppPlatform {
691 /// Returns `PlatformKind::MiniApp`.
692 ///
693 /// # Arguments
694 ///
695 /// - `&Self` - Mini-program platform reference.
696 ///
697 /// # Returns
698 ///
699 /// - `PlatformKind` - `PlatformKind::MiniApp`.
700 fn kind(&self) -> PlatformKind {
701 PlatformKind::MiniApp
702 }
703
704 /// Returns Mini-Program container capability flags (`capsule_chrome = true`, `local_storage = true`).
705 ///
706 /// # Arguments
707 ///
708 /// - `&Self` - Mini-program platform reference.
709 ///
710 /// # Returns
711 ///
712 /// - `PlatformCapabilities` - Mini-Program capabilities.
713 fn capabilities(&self) -> PlatformCapabilities {
714 PlatformCapabilities::for_platform(PlatformKind::MiniApp)
715 }
716
717 /// Creates a canvas window sized to the host Mini-Program viewport with capsule-cleared safe-area insets.
718 ///
719 /// # Arguments
720 ///
721 /// - `&Self` - Mutable Mini-program platform.
722 /// - `&WindowConfig` - Declarative window config.
723 ///
724 /// # Returns
725 ///
726 /// - `Result<WindowState, PlatformError>` - Created canvas window state.
727 fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
728 let id: WindowId = WindowId::new(self.get_next_id());
729 self.set_next_id(self.get_next_id().wrapping_add(1));
730 let mut mini_cfg: WindowConfig = config.clone();
731 mini_cfg.set_size(
732 self.get_system_info().get_window_width(),
733 self.get_system_info().get_window_height(),
734 );
735 let dpr: f32 = self.get_system_info().get_pixel_ratio();
736 let mut state: WindowState = WindowState::from_config(id, &mini_cfg, dpr);
737 state.set_safe_area(self.get_resolved_safe_area());
738 state.set_system_theme(self.get_system_info().get_theme());
739 let record: MiniAppWindowRecord = MiniAppWindowRecord {
740 config: mini_cfg,
741 state,
742 canvas_id: id.get_value() as u32,
743 canvas_mode: self.get_system_info().get_canvas_mode(),
744 last_frame: Framebuffer::allocate(
745 state.get_physical_width(),
746 state.get_physical_height(),
747 ),
748 present_count: 0,
749 };
750 self.get_mut_windows().insert(id, record);
751 if self.primary_window_id().is_none() {
752 self.set_primary_window(Some(id));
753 }
754 Ok(state)
755 }
756
757 /// Queries live `WindowState` for `id`.
758 ///
759 /// # Arguments
760 ///
761 /// - `&Self` - Mini-program platform reference.
762 /// - `WindowId` - Window identifier.
763 ///
764 /// # Returns
765 ///
766 /// - `Option<WindowState>` - Live window state if open.
767 fn window_state(&self, id: WindowId) -> Option<WindowState> {
768 self.get_windows()
769 .get(&id)
770 .map(MiniAppWindowRecord::get_state)
771 }
772
773 /// Returns `RawWindowHandle::MiniAppCanvas` tagged with the active `MiniAppVendor`.
774 ///
775 /// # Arguments
776 ///
777 /// - `&Self` - Mini-program platform reference.
778 /// - `WindowId` - Window identifier.
779 ///
780 /// # Returns
781 ///
782 /// - `RawWindowHandle` - Mini-Program canvas handle.
783 fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
784 match self.get_windows().get(&id) {
785 Some(rec) => RawWindowHandle::MiniAppCanvas {
786 canvas_id: rec.get_canvas_id(),
787 vendor_tag: self.get_system_info().get_vendor().tag(),
788 },
789 None => RawWindowHandle::Headless,
790 }
791 }
792
793 /// Drains queued Mini-Program touch, IME, resize, and lifecycle events.
794 ///
795 /// # Arguments
796 ///
797 /// - `&Self` - Mutable Mini-program platform.
798 ///
799 /// # Returns
800 ///
801 /// - `Vec<WindowEvent>` - Pending events.
802 fn poll_events(&mut self) -> Vec<WindowEvent> {
803 take(self.get_mut_pending_events())
804 }
805
806 /// Pauses or resumes the Mini-Program canvas frame pump flag.
807 ///
808 /// # Arguments
809 ///
810 /// - `&Self` - Mutable Mini-program platform.
811 /// - `bool` - `true` when hidden.
812 fn set_frame_pump_paused(&mut self, paused: bool) {
813 self.set_pump_paused(paused);
814 }
815
816 /// Returns whether the Mini-Program frame pump is paused.
817 ///
818 /// # Arguments
819 ///
820 /// - `&Self` - Mini-program platform reference.
821 ///
822 /// # Returns
823 ///
824 /// - `bool` - Pause state.
825 fn is_frame_pump_paused(&self) -> bool {
826 self.get_pump_paused()
827 }
828
829 /// Stores `framebuffer` and queues a `MiniAppHostCommand::PresentCanvas` command for the host canvas context.
830 ///
831 /// # Arguments
832 ///
833 /// - `&Self` - Mutable Mini-program platform.
834 /// - `WindowId` - Window identifier.
835 /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
836 ///
837 /// # Returns
838 ///
839 /// - `Result<(), PlatformError>` - Presentation status.
840 fn present_framebuffer(
841 &mut self,
842 id: WindowId,
843 framebuffer: &Framebuffer,
844 ) -> Result<(), PlatformError> {
845 let mode: MiniAppCanvasMode = {
846 let rec: &mut MiniAppWindowRecord = self
847 .get_mut_windows()
848 .get_mut(&id)
849 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
850 rec.set_last_frame(framebuffer.clone());
851 rec.set_present_count(rec.get_present_count().wrapping_add(1));
852 rec.get_canvas_mode()
853 };
854 self.get_mut_outbound_commands()
855 .push(MiniAppHostCommand::PresentCanvas {
856 mode,
857 width: framebuffer.get_width(),
858 height: framebuffer.get_height(),
859 });
860 Ok(())
861 }
862
863 /// Reads cached clipboard text.
864 ///
865 /// # Arguments
866 ///
867 /// - `&Self` - Mini-program platform reference.
868 ///
869 /// # Returns
870 ///
871 /// - `Option<String>` - Cached clipboard string.
872 fn read_clipboard(&self) -> Option<String> {
873 let Self { clipboard, .. } = self;
874 clipboard.clone()
875 }
876
877 /// Writes `text` to the clipboard cache and queues `MiniAppHostCommand::SetClipboardData`.
878 ///
879 /// # Arguments
880 ///
881 /// - `&Self` - Mutable Mini-program platform.
882 /// - `&str` - Clipboard text.
883 ///
884 /// # Returns
885 ///
886 /// - `Result<(), PlatformError>` - Write status.
887 fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
888 self.set_clipboard(Some(text.to_string()));
889 self.get_mut_outbound_commands()
890 .push(MiniAppHostCommand::SetClipboardData(text.to_string()));
891 Ok(())
892 }
893
894 /// Returns the active Mini-Program host theme mode.
895 ///
896 /// # Arguments
897 ///
898 /// - `&Self` - Mini-program platform reference.
899 ///
900 /// # Returns
901 ///
902 /// - `ThemeMode` - Active theme mode.
903 fn system_theme(&self) -> ThemeMode {
904 self.get_system_info().get_theme()
905 }
906}
907
908/// `PlatformStorage` implementation for `MiniAppPlatform`.
909impl PlatformStorage for MiniAppPlatform {
910 /// Reads `key` from mirrored Mini-Program sandbox storage.
911 ///
912 /// # Arguments
913 ///
914 /// - `&Self` - Mini-program platform reference.
915 /// - `&str` - Storage key.
916 ///
917 /// # Returns
918 ///
919 /// - `Option<String>` - Stored value, if present.
920 fn storage_get(&self, key: &str) -> Option<String> {
921 self.get_storage().get(key).cloned()
922 }
923
924 /// Writes `(key, value)` to mirrored storage and emits `MiniAppHostCommand::SetStorageSync`.
925 ///
926 /// # Arguments
927 ///
928 /// - `&Self` - Mutable Mini-program platform.
929 /// - `&str` - Storage key.
930 /// - `&str` - Value to store.
931 ///
932 /// # Returns
933 ///
934 /// - `Result<(), PlatformError>` - Storage status.
935 fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
936 let _: Option<String> = self
937 .get_mut_storage()
938 .insert(key.to_string(), value.to_string());
939 self.get_mut_outbound_commands()
940 .push(MiniAppHostCommand::SetStorageSync {
941 key: key.to_string(),
942 value: value.to_string(),
943 });
944 Ok(())
945 }
946
947 /// Removes `key` from mirrored storage and emits `MiniAppHostCommand::RemoveStorageSync`.
948 ///
949 /// # Arguments
950 ///
951 /// - `&Self` - Mutable Mini-program platform.
952 /// - `&str` - Storage key.
953 ///
954 /// # Returns
955 ///
956 /// - `Result<(), PlatformError>` - Removal status.
957 fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
958 let _: Option<String> = self.get_mut_storage().remove(key);
959 self.get_mut_outbound_commands()
960 .push(MiniAppHostCommand::RemoveStorageSync(key.to_string()));
961 Ok(())
962 }
963
964 /// Clears mirrored storage and emits `MiniAppHostCommand::ClearStorageSync`.
965 ///
966 /// # Arguments
967 ///
968 /// - `&Self` - Mutable Mini-program platform.
969 ///
970 /// # Returns
971 ///
972 /// - `Result<(), PlatformError>` - Clear status.
973 fn storage_clear(&mut self) -> Result<(), PlatformError> {
974 self.get_mut_storage().clear();
975 self.get_mut_outbound_commands()
976 .push(MiniAppHostCommand::ClearStorageSync);
977 Ok(())
978 }
979}
980
981/// `PlatformNavigation` implementation for `MiniAppPlatform`.
982impl PlatformNavigation for MiniAppPlatform {
983 /// Pushes `route` onto the Mini-Program navigation stack and emits `MiniAppHostCommand::NavigateTo`.
984 ///
985 /// # Arguments
986 ///
987 /// - `&Self` - Mutable Mini-program platform.
988 /// - `&str` - Target page route.
989 ///
990 /// # Returns
991 ///
992 /// - `Result<(), PlatformError>` - Navigation status.
993 fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
994 if !route.is_empty() {
995 self.get_mut_route_stack().push(route.to_string());
996 self.get_mut_outbound_commands()
997 .push(MiniAppHostCommand::NavigateTo(route.to_string()));
998 }
999 Ok(())
1000 }
1001
1002 /// Pops `delta` entries from the navigation stack and emits `MiniAppHostCommand::NavigateBack`.
1003 ///
1004 /// # Arguments
1005 ///
1006 /// - `&Self` - Mutable Mini-program platform.
1007 /// - `u32` - Pages to pop.
1008 ///
1009 /// # Returns
1010 ///
1011 /// - `Result<(), PlatformError>` - Navigation status.
1012 fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1013 let steps: u32 = delta.max(1);
1014 for _ in 0..steps {
1015 if self.get_route_stack().len() > 1 {
1016 let _: Option<String> = self.get_mut_route_stack().pop();
1017 }
1018 }
1019 self.get_mut_outbound_commands()
1020 .push(MiniAppHostCommand::NavigateBack(steps));
1021 Ok(())
1022 }
1023
1024 /// Returns the currently active Mini-Program route path.
1025 ///
1026 /// # Arguments
1027 ///
1028 /// - `&Self` - Mini-program platform reference.
1029 ///
1030 /// # Returns
1031 ///
1032 /// - `&str` - Active route path.
1033 fn current_route(&self) -> &str {
1034 self.get_route_stack()
1035 .last()
1036 .map(String::as_str)
1037 .unwrap_or(MINIAPP_DEFAULT_ROUTE)
1038 }
1039}
1040
1041/// `PlatformLifecycleBridge` implementation for `MiniAppPlatform`.
1042impl PlatformLifecycleBridge for MiniAppPlatform {
1043 /// Maps Mini-Program `onHide` into unified freeze semantics.
1044 ///
1045 /// # Arguments
1046 ///
1047 /// - `&Self` - Mutable Mini-program platform.
1048 ///
1049 /// # Returns
1050 ///
1051 /// - `Vec<WindowEvent>` - Normalized freeze events.
1052 fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1053 self.handle_lifecycle_hook(MiniAppLifecycleHook::OnHide)
1054 }
1055
1056 /// Maps Mini-Program `onShow` into unified resume semantics.
1057 ///
1058 /// # Arguments
1059 ///
1060 /// - `&Self` - Mutable Mini-program platform.
1061 ///
1062 /// # Returns
1063 ///
1064 /// - `Vec<WindowEvent>` - Normalized resume events.
1065 fn resume_surface(&mut self) -> Vec<WindowEvent> {
1066 self.handle_lifecycle_hook(MiniAppLifecycleHook::OnShow { query_uri: None })
1067 }
1068
1069 /// Maps Mini-Program `onUnload` into unified destroy semantics.
1070 ///
1071 /// # Arguments
1072 ///
1073 /// - `&Self` - Mutable Mini-program platform.
1074 ///
1075 /// # Returns
1076 ///
1077 /// - `Vec<WindowEvent>` - Normalized destroy events.
1078 fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1079 self.handle_lifecycle_hook(MiniAppLifecycleHook::OnUnload)
1080 }
1081}
1082
1083/// `PlatformHostAdapter` implementation for `MiniAppPlatform`.
1084impl PlatformHostAdapter for MiniAppPlatform {
1085 /// Returns `DeviceFormFactor::MiniProgram`.
1086 ///
1087 /// # Arguments
1088 ///
1089 /// - `&Self` - Mini-program platform reference.
1090 ///
1091 /// # Returns
1092 ///
1093 /// - `DeviceFormFactor` - `DeviceFormFactor::MiniProgram`.
1094 fn device_form_factor(&self) -> DeviceFormFactor {
1095 DeviceFormFactor::MiniProgram
1096 }
1097
1098 /// Returns the active Mini-Program vendor identifier (`"wechat"`, `"alipay"`, `"douyin"`, etc.).
1099 ///
1100 /// # Arguments
1101 ///
1102 /// - `&Self` - Mini-program platform reference.
1103 ///
1104 /// # Returns
1105 ///
1106 /// - `&'static str` - Canonical vendor identifier.
1107 fn host_vendor_name(&self) -> &'static str {
1108 self.get_system_info().get_vendor().as_str()
1109 }
1110}
1111
1112/// Unified host-channel capability and visual-equivalence queries for `MiniAppPlatform`.
1113impl MiniAppPlatform {
1114 /// Returns the truthful `HostChannelCapabilities` declared by this Mini-Program host.
1115 ///
1116 /// A `Canvas2d`-only host locks single-channel mode (`supported_channels.len() == 1`) and NEVER probes WebGL;
1117 /// off-device/simulated profiles ALWAYS set `simulated_profile = true` and `direct_gpu_verified_on_device = false`.
1118 ///
1119 /// # Returns
1120 ///
1121 /// - `HostChannelCapabilities` - Declared MiniApp channels, visual gate, and honesty flags.
1122 #[must_use]
1123 pub fn host_channel_capabilities(&self) -> HostChannelCapabilities {
1124 let simulated: bool = !cfg!(target_arch = "wasm32");
1125 let (channels, preferred): (Vec<HostRenderChannel>, HostRenderChannel) =
1126 match self.get_system_info().get_canvas_mode() {
1127 MiniAppCanvasMode::Canvas2d => (
1128 vec![HostRenderChannel::Canvas2d],
1129 HostRenderChannel::Canvas2d,
1130 ),
1131 MiniAppCanvasMode::WebGl => (
1132 vec![HostRenderChannel::WebGl, HostRenderChannel::Canvas2d],
1133 HostRenderChannel::WebGl,
1134 ),
1135 MiniAppCanvasMode::WebGl2 => (
1136 vec![HostRenderChannel::WebGl2, HostRenderChannel::Canvas2d],
1137 HostRenderChannel::WebGl2,
1138 ),
1139 };
1140 HostChannelCapabilities::from_host_declaration(
1141 self.host_vendor_name(),
1142 channels,
1143 preferred,
1144 HostVisualEquivalenceGate::default(),
1145 simulated,
1146 false,
1147 )
1148 }
1149
1150 /// Resolves the MiniApp rendering channel under unified visual-equivalence and single-channel non-probing rules.
1151 ///
1152 /// # Arguments
1153 ///
1154 /// - `Option<HostRenderChannel>` - Optional requested channel.
1155 ///
1156 /// # Returns
1157 ///
1158 /// - `HostChannelSelection` - Resolved channel decision.
1159 #[must_use]
1160 pub fn select_render_channel(
1161 &self,
1162 requested: Option<HostRenderChannel>,
1163 ) -> HostChannelSelection {
1164 self.host_channel_capabilities().select_channel(requested)
1165 }
1166}