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::HarmonyAtomic => MINIAPP_VENDOR_HARMONY_ATOMIC,
24 }
25 }
26
27 /// Returns the vendor's global runtime API object name (`wx`, `my`, `tt`, `swan`, `qq`, `ks`, `atomic`).
28 ///
29 /// # Arguments
30 ///
31 /// - `&Self` - Mini-program vendor variant.
32 ///
33 /// # Returns
34 ///
35 /// - `&'static str` - Global JS/ArkTS host namespace identifier.
36 #[must_use]
37 pub const fn global_namespace(&self) -> &'static str {
38 match *self {
39 Self::WeChat => MINIAPP_GLOBAL_WECHAT,
40 Self::Alipay => MINIAPP_GLOBAL_ALIPAY,
41 Self::Douyin => MINIAPP_GLOBAL_DOUYIN,
42 Self::Baidu => MINIAPP_GLOBAL_BAIDU,
43 Self::Qq => MINIAPP_GLOBAL_QQ,
44 Self::Kuaishou => MINIAPP_GLOBAL_KUAISHOU,
45 Self::HarmonyAtomic => MINIAPP_GLOBAL_HARMONY_ATOMIC,
46 }
47 }
48
49 /// Returns the host page markup file extension used by the vendor shell generator.
50 ///
51 /// # Arguments
52 ///
53 /// - `&Self` - Mini-program vendor variant.
54 ///
55 /// # Returns
56 ///
57 /// - `&'static str` - Template extension without leading dot (`wxml`, `axml`, `ttml`, `swan`, `qml`, `ksml`, `ets`).
58 #[must_use]
59 pub const fn template_extension(&self) -> &'static str {
60 match *self {
61 Self::WeChat => MINIAPP_EXT_WXML,
62 Self::Alipay => MINIAPP_EXT_AXML,
63 Self::Douyin => MINIAPP_EXT_TTML,
64 Self::Baidu => MINIAPP_EXT_SWAN,
65 Self::Qq => MINIAPP_EXT_QML,
66 Self::Kuaishou => MINIAPP_EXT_KSML,
67 Self::HarmonyAtomic => MINIAPP_EXT_ETS,
68 }
69 }
70
71 /// Returns a compact ABI tag byte stored in `RawWindowHandle::MiniAppCanvas`.
72 ///
73 /// # Arguments
74 ///
75 /// - `&Self` - Mini-program vendor variant.
76 ///
77 /// # Returns
78 ///
79 /// - `u8` - Numeric vendor discriminant (`1..=7`).
80 #[must_use]
81 pub const fn tag(&self) -> u8 {
82 match *self {
83 Self::WeChat => 1,
84 Self::Alipay => 2,
85 Self::Douyin => 3,
86 Self::Baidu => 4,
87 Self::Qq => 5,
88 Self::Kuaishou => 6,
89 Self::HarmonyAtomic => 7,
90 }
91 }
92
93 /// Returns all 7 supported Mini-Program and Atomic Service vendors.
94 ///
95 /// # Returns
96 ///
97 /// - `[Self; 7]` - Complete array of Mini-Program vendors.
98 #[must_use]
99 pub const fn all_vendors() -> [Self; 7] {
100 [
101 Self::WeChat,
102 Self::Alipay,
103 Self::Douyin,
104 Self::Baidu,
105 Self::Qq,
106 Self::Kuaishou,
107 Self::HarmonyAtomic,
108 ]
109 }
110}
111
112/// Default `MiniAppSystemInfo` modeling a modern 390x844@3x smartphone Mini-Program container with floating capsule.
113impl Default for MiniAppSystemInfo {
114 /// Creates default WeChat Mini-Program system info metrics.
115 ///
116 /// # Returns
117 ///
118 /// - `Self` - Default `MiniAppSystemInfo`.
119 fn default() -> Self {
120 Self::for_vendor(MiniAppVendor::WeChat)
121 }
122}
123
124/// Preset builders for `MiniAppSystemInfo`.
125impl MiniAppSystemInfo {
126 /// Creates realistic default system metrics including floating capsule button geometry for `vendor`.
127 ///
128 /// # Arguments
129 ///
130 /// - `MiniAppVendor` - Target Mini-Program vendor.
131 ///
132 /// # Returns
133 ///
134 /// - `Self` - Normalized `MiniAppSystemInfo` preset.
135 #[must_use]
136 pub fn for_vendor(vendor: MiniAppVendor) -> Self {
137 let top: f32 = MINIAPP_DEFAULT_STATUS_BAR_DP + 4.0;
138 let right: f32 = (MINIAPP_DEFAULT_WIDTH as f32) - MINIAPP_DEFAULT_CAPSULE_RIGHT_MARGIN;
139 let left: f32 = right - MINIAPP_DEFAULT_CAPSULE_W;
140 let bottom: f32 = top + MINIAPP_DEFAULT_CAPSULE_H;
141 let capsule: MiniAppCapsuleRect = MiniAppCapsuleRect::new(
142 top,
143 right,
144 bottom,
145 left,
146 MINIAPP_DEFAULT_CAPSULE_W,
147 MINIAPP_DEFAULT_CAPSULE_H,
148 );
149 let canvas_mode: MiniAppCanvasMode = match vendor {
150 MiniAppVendor::HarmonyAtomic => MiniAppCanvasMode::WebGl2,
151 _ => MiniAppCanvasMode::Canvas2d,
152 };
153 Self {
154 vendor,
155 window_width: MINIAPP_DEFAULT_WIDTH,
156 window_height: MINIAPP_DEFAULT_HEIGHT,
157 pixel_ratio: MINIAPP_DEFAULT_DPR,
158 status_bar_height: MINIAPP_DEFAULT_STATUS_BAR_DP,
159 safe_area: SafeAreaInsets::new(
160 MINIAPP_DEFAULT_STATUS_BAR_DP,
161 0.0,
162 MINIAPP_DEFAULT_SAFE_BOTTOM_DP,
163 0.0,
164 ),
165 capsule,
166 theme: ThemeMode::Light,
167 language: MINIAPP_DEFAULT_LANGUAGE.to_string(),
168 canvas_mode,
169 }
170 }
171}
172
173/// Default `MiniAppPlatform` targeting WeChat (`MiniAppVendor::WeChat`).
174impl Default for MiniAppPlatform {
175 /// Creates a default WeChat Mini-Program host adapter.
176 ///
177 /// # Returns
178 ///
179 /// - `Self` - Default `MiniAppPlatform`.
180 fn default() -> Self {
181 Self::for_vendor(MiniAppVendor::WeChat)
182 }
183}
184
185/// Vendor constructors, touch/IME/lifecycle translation, and outbound bridge queue helpers for `MiniAppPlatform`.
186impl MiniAppPlatform {
187 /// Creates a `MiniAppPlatform` configured for `vendor` with capsule-cleared safe-area insets.
188 ///
189 /// # Arguments
190 ///
191 /// - `MiniAppVendor` - Target Mini-Program host vendor.
192 ///
193 /// # Returns
194 ///
195 /// - `Self` - Configured Mini-Program backend.
196 #[must_use]
197 pub fn for_vendor(vendor: MiniAppVendor) -> Self {
198 Self::from_system_info(MiniAppSystemInfo::for_vendor(vendor))
199 }
200
201 /// Creates a `MiniAppPlatform` from concrete host `MiniAppSystemInfo`.
202 ///
203 /// # Arguments
204 ///
205 /// - `MiniAppSystemInfo` - Runtime system info reported by the host shell.
206 ///
207 /// # Returns
208 ///
209 /// - `Self` - Configured Mini-Program backend.
210 #[must_use]
211 pub fn from_system_info(system_info: MiniAppSystemInfo) -> Self {
212 let safe_area: SafeAreaInsets = resolve_miniapp_safe_area(&system_info, true);
213 Self {
214 system_info,
215 resolved_safe_area: safe_area,
216 next_id: 1,
217 primary_window: None,
218 windows: HashMap::new(),
219 touch_tracker: TouchPointerTracker::default(),
220 pending_events: Vec::new(),
221 outbound_commands: Vec::new(),
222 storage: HashMap::new(),
223 route_stack: vec![MINIAPP_DEFAULT_ROUTE.to_string()],
224 clipboard: None,
225 pump_paused: false,
226 }
227 }
228
229 /// Returns the primary Mini-Program canvas window identifier, if created.
230 ///
231 /// # Arguments
232 ///
233 /// - `&Self` - Mini-program platform reference.
234 ///
235 /// # Returns
236 ///
237 /// - `Option<WindowId>` - Primary canvas window handle.
238 #[must_use]
239 pub fn primary_window_id(&self) -> Option<WindowId> {
240 let Self { primary_window, .. } = self;
241 *primary_window
242 }
243
244 /// Drains all queued outbound host bridge commands for execution by the thin JS/ArkTS shell.
245 ///
246 /// # Arguments
247 ///
248 /// - `&Self` - Mutable Mini-program platform.
249 ///
250 /// # Returns
251 ///
252 /// - `Vec<MiniAppHostCommand>` - Ordered host commands.
253 pub fn drain_host_commands(&mut self) -> Vec<MiniAppHostCommand> {
254 take(self.get_mut_outbound_commands())
255 }
256
257 /// Updates host `MiniAppSystemInfo` (e.g. after orientation change or capsule query) and emits `SafeAreaChanged`.
258 ///
259 /// # Arguments
260 ///
261 /// - `&Self` - Mutable Mini-program platform.
262 /// - `MiniAppSystemInfo` - Updated host system info.
263 pub fn update_system_info(&mut self, info: MiniAppSystemInfo) {
264 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
265 let safe: SafeAreaInsets = resolve_miniapp_safe_area(&info, true);
266 let w: u32 = info.get_window_width().max(1);
267 let h: u32 = info.get_window_height().max(1);
268 let dpr: f32 = info.get_pixel_ratio().clamp(0.5, 4.5);
269 self.set_system_info(info);
270 self.set_resolved_safe_area(safe);
271 for rec in self.get_mut_windows().values_mut() {
272 rec.get_mut_state()
273 .set_logical_width(w as f32)
274 .set_logical_height(h as f32)
275 .set_physical_width(((w as f32) * dpr).round() as u32)
276 .set_physical_height(((h as f32) * dpr).round() as u32)
277 .set_scale_factor(dpr)
278 .set_safe_area(safe);
279 }
280 self.get_mut_pending_events()
281 .push(WindowEvent::SafeAreaChanged(wid, safe));
282 self.get_mut_pending_events()
283 .push(WindowEvent::System(SystemEvent::SafeAreaChanged(safe)));
284 }
285
286 /// Translates Mini-Program `<canvas>` touch callbacks (`touchstart`/`touchmove`/`touchend`/`touchcancel`) into EUV pointer events.
287 ///
288 /// # Arguments
289 ///
290 /// - `&Self` - Mutable Mini-program platform.
291 /// - `i32` - Normalized action (`ANDROID_ACTION_DOWN` / `MOVE` / `UP` / `CANCEL`).
292 /// - `&[(i32, f32, f32)]` - Active touch contact tuples `(identifier, logical_x, logical_y)`.
293 ///
294 /// # Returns
295 ///
296 /// - `Vec<WindowEvent>` - Normalized pointer events also enqueued for `poll_events()`.
297 pub fn handle_touch(&mut self, action: i32, touches: &[(i32, f32, f32)]) -> Vec<WindowEvent> {
298 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
299 let events: Vec<WindowEvent> = self
300 .get_mut_touch_tracker()
301 .handle_android_motion(wid, action, 0, touches);
302 self.get_mut_pending_events().extend(events.clone());
303 events
304 }
305
306 /// Dispatches UTF-8 text input received from a hidden Mini-Program `<input>` or `onKeyboardInput` bridge.
307 ///
308 /// # Arguments
309 ///
310 /// - `&Self` - Mutable Mini-program platform.
311 /// - `String` - Committed UTF-8 text.
312 /// - `bool` - When `true`, also emits `KeyCode::Enter` confirmation.
313 pub fn handle_ime_input(&mut self, text: String, confirmed: bool) {
314 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
315 if !text.is_empty() {
316 self.get_mut_pending_events()
317 .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
318 self.get_mut_pending_events()
319 .push(WindowEvent::TextInput(wid, text));
320 }
321 if confirmed {
322 self.get_mut_pending_events().push(WindowEvent::KeyDown(
323 wid,
324 KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
325 ));
326 }
327 }
328
329 /// Translates Mini-Program `onLaunch` / `onShow` / `onHide` / `onUnload` and system hooks into canonical EUV `SystemEvent`s.
330 ///
331 /// # Arguments
332 ///
333 /// - `&Self` - Mutable Mini-program platform.
334 /// - `MiniAppLifecycleHook` - Vendor-neutral lifecycle hook payload.
335 ///
336 /// # Returns
337 ///
338 /// - `Vec<WindowEvent>` - Normalized events also enqueued for `poll_events()`.
339 pub fn handle_lifecycle_hook(&mut self, hook: MiniAppLifecycleHook) -> Vec<WindowEvent> {
340 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
341 let mut emitted: Vec<WindowEvent> = Vec::new();
342 match hook {
343 MiniAppLifecycleHook::OnLaunch { query_uri } => {
344 self.set_pump_paused(false);
345 if let Some(uri) = query_uri
346 && !uri.is_empty()
347 {
348 emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
349 }
350 }
351 MiniAppLifecycleHook::OnShow { query_uri } => {
352 self.set_pump_paused(false);
353 emitted.push(WindowEvent::System(SystemEvent::Appear));
354 emitted.push(WindowEvent::System(SystemEvent::Foreground));
355 if let Some(uri) = query_uri
356 && !uri.is_empty()
357 {
358 emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
359 }
360 }
361 MiniAppLifecycleHook::OnHide => {
362 self.set_pump_paused(true);
363 let cancels: Vec<WindowEvent> =
364 self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
365 emitted.extend(cancels);
366 emitted.push(WindowEvent::System(SystemEvent::Disappear));
367 emitted.push(WindowEvent::System(SystemEvent::Background));
368 }
369 MiniAppLifecycleHook::OnUnload => {
370 self.set_pump_paused(true);
371 let cancels: Vec<WindowEvent> =
372 self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
373 emitted.extend(cancels);
374 emitted.push(WindowEvent::System(SystemEvent::Terminate));
375 }
376 MiniAppLifecycleHook::OnResize {
377 width,
378 height,
379 pixel_ratio,
380 } => {
381 let w: u32 = width.max(1);
382 let h: u32 = height.max(1);
383 let dpr: f32 = if pixel_ratio.is_finite() {
384 pixel_ratio.clamp(0.5, 4.5)
385 } else {
386 1.0
387 };
388 self.get_mut_system_info()
389 .set_window_width(w)
390 .set_window_height(h)
391 .set_pixel_ratio(dpr);
392 for rec in self.get_mut_windows().values_mut() {
393 rec.get_mut_state()
394 .set_logical_width(w as f32)
395 .set_logical_height(h as f32)
396 .set_physical_width(((w as f32) * dpr).round() as u32)
397 .set_physical_height(((h as f32) * dpr).round() as u32)
398 .set_scale_factor(dpr);
399 }
400 emitted.push(WindowEvent::Resized(wid, w, h, dpr));
401 emitted.push(WindowEvent::System(SystemEvent::Resize {
402 width: w as f32,
403 height: h as f32,
404 scale_factor: dpr,
405 }));
406 }
407 MiniAppLifecycleHook::OnThemeChange(theme) => {
408 self.get_mut_system_info().set_theme(theme);
409 emitted.push(WindowEvent::ThemeChanged(wid, theme));
410 emitted.push(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
411 }
412 MiniAppLifecycleHook::OnMemoryWarning(level) => {
413 let pressure: MemoryPressure = miniapp_memory_level_to_pressure(level);
414 emitted.push(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
415 }
416 MiniAppLifecycleHook::OnKeyboardHeightChange(height) => {
417 let h: f32 = if height.is_finite() {
418 height.max(0.0)
419 } else {
420 0.0
421 };
422 emitted.push(WindowEvent::System(
423 SystemEvent::KeyboardVisibilityChanged {
424 visible: h > 0.0,
425 height: h,
426 },
427 ));
428 }
429 MiniAppLifecycleHook::OnNetworkStatusChange(status) => {
430 emitted.push(WindowEvent::System(SystemEvent::NetworkStatusChanged(
431 status,
432 )));
433 }
434 }
435 self.get_mut_pending_events().extend(emitted.clone());
436 emitted
437 }
438}
439
440/// `WindowController` implementation for `MiniAppPlatform`.
441impl WindowController for MiniAppPlatform {
442 /// Applies a `WindowCommand` and emits corresponding `MiniAppHostCommand`s when relevant.
443 ///
444 /// # Arguments
445 ///
446 /// - `&Self` - Mutable Mini-program platform.
447 /// - `WindowCommand` - Command to apply.
448 ///
449 /// # Returns
450 ///
451 /// - `Result<(), PlatformError>` - Execution status.
452 fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
453 match command {
454 WindowCommand::SetTitle(id, title) => {
455 let rec: &mut MiniAppWindowRecord = self
456 .get_mut_windows()
457 .get_mut(&id)
458 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
459 rec.get_mut_config().set_title(title.clone());
460 self.get_mut_outbound_commands()
461 .push(MiniAppHostCommand::SetNavigationBarTitle(title));
462 Ok(())
463 }
464 WindowCommand::SetIme(id, enabled, rect) => {
465 if !self.get_windows().contains_key(&id) {
466 return Err(PlatformError::WindowNotFound(id.get_value()));
467 }
468 self.get_mut_outbound_commands()
469 .push(MiniAppHostCommand::ShowKeyboard { enabled, rect });
470 Ok(())
471 }
472 WindowCommand::SetRenderMode(id, mode) => {
473 let rec: &mut MiniAppWindowRecord = self
474 .get_mut_windows()
475 .get_mut(&id)
476 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
477 rec.get_mut_config().get_mut_render().set_mode(mode);
478 let next_canvas: MiniAppCanvasMode = match mode {
479 RenderMode::Software => MiniAppCanvasMode::Canvas2d,
480 RenderMode::Hardware | RenderMode::Hybrid | RenderMode::Auto => {
481 MiniAppCanvasMode::WebGl2
482 }
483 };
484 rec.set_canvas_mode(next_canvas);
485 Ok(())
486 }
487 WindowCommand::RequestRedraw(id) => {
488 if !self.get_windows().contains_key(&id) {
489 return Err(PlatformError::WindowNotFound(id.get_value()));
490 }
491 self.get_mut_pending_events()
492 .push(WindowEvent::RedrawRequested(id));
493 Ok(())
494 }
495 WindowCommand::Close(id) => {
496 if self.get_mut_windows().remove(&id).is_none() {
497 return Err(PlatformError::WindowNotFound(id.get_value()));
498 }
499 Ok(())
500 }
501 WindowCommand::SetSize(id, _, _)
502 | WindowCommand::SetPosition(id, _, _)
503 | WindowCommand::SetResizable(id, _)
504 | WindowCommand::SetDecorations(id, _)
505 | WindowCommand::SetAlwaysOnTop(id, _)
506 | WindowCommand::SetFullscreen(id, _)
507 | WindowCommand::SetVisible(id, _)
508 | WindowCommand::SetCursor(id, _)
509 | WindowCommand::SetStatusBarStyle(id, _) => {
510 if !self.get_windows().contains_key(&id) {
511 return Err(PlatformError::WindowNotFound(id.get_value()));
512 }
513 Ok(())
514 }
515 }
516 }
517}
518
519/// `PlatformBackend` implementation for `MiniAppPlatform`.
520impl PlatformBackend for MiniAppPlatform {
521 /// Returns `PlatformKind::MiniApp`.
522 ///
523 /// # Arguments
524 ///
525 /// - `&Self` - Mini-program platform reference.
526 ///
527 /// # Returns
528 ///
529 /// - `PlatformKind` - `PlatformKind::MiniApp`.
530 fn kind(&self) -> PlatformKind {
531 PlatformKind::MiniApp
532 }
533
534 /// Returns Mini-Program container capability flags (`capsule_chrome = true`, `local_storage = true`).
535 ///
536 /// # Arguments
537 ///
538 /// - `&Self` - Mini-program platform reference.
539 ///
540 /// # Returns
541 ///
542 /// - `PlatformCapabilities` - Mini-Program capabilities.
543 fn capabilities(&self) -> PlatformCapabilities {
544 PlatformCapabilities::for_platform(PlatformKind::MiniApp)
545 }
546
547 /// Creates a canvas window sized to the host Mini-Program viewport with capsule-cleared safe-area insets.
548 ///
549 /// # Arguments
550 ///
551 /// - `&Self` - Mutable Mini-program platform.
552 /// - `&WindowConfig` - Declarative window config.
553 ///
554 /// # Returns
555 ///
556 /// - `Result<WindowState, PlatformError>` - Created canvas window state.
557 fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
558 let id: WindowId = WindowId::new(self.get_next_id());
559 self.set_next_id(self.get_next_id().wrapping_add(1));
560 let mut mini_cfg: WindowConfig = config.clone();
561 mini_cfg.set_size(
562 self.get_system_info().get_window_width(),
563 self.get_system_info().get_window_height(),
564 );
565 let dpr: f32 = self.get_system_info().get_pixel_ratio();
566 let mut state: WindowState = WindowState::from_config(id, &mini_cfg, dpr);
567 state.set_safe_area(self.get_resolved_safe_area());
568 state.set_system_theme(self.get_system_info().get_theme());
569 let record: MiniAppWindowRecord = MiniAppWindowRecord {
570 config: mini_cfg,
571 state,
572 canvas_id: id.get_value() as u32,
573 canvas_mode: self.get_system_info().get_canvas_mode(),
574 last_frame: Framebuffer::allocate(
575 state.get_physical_width(),
576 state.get_physical_height(),
577 ),
578 present_count: 0,
579 };
580 self.get_mut_windows().insert(id, record);
581 if self.primary_window_id().is_none() {
582 self.set_primary_window(Some(id));
583 }
584 Ok(state)
585 }
586
587 /// Queries live `WindowState` for `id`.
588 ///
589 /// # Arguments
590 ///
591 /// - `&Self` - Mini-program platform reference.
592 /// - `WindowId` - Window identifier.
593 ///
594 /// # Returns
595 ///
596 /// - `Option<WindowState>` - Live window state if open.
597 fn window_state(&self, id: WindowId) -> Option<WindowState> {
598 self.get_windows()
599 .get(&id)
600 .map(MiniAppWindowRecord::get_state)
601 }
602
603 /// Returns `RawWindowHandle::MiniAppCanvas` tagged with the active `MiniAppVendor`.
604 ///
605 /// # Arguments
606 ///
607 /// - `&Self` - Mini-program platform reference.
608 /// - `WindowId` - Window identifier.
609 ///
610 /// # Returns
611 ///
612 /// - `RawWindowHandle` - Mini-Program canvas handle.
613 fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
614 match self.get_windows().get(&id) {
615 Some(rec) => RawWindowHandle::MiniAppCanvas {
616 canvas_id: rec.get_canvas_id(),
617 vendor_tag: self.get_system_info().get_vendor().tag(),
618 },
619 None => RawWindowHandle::Headless,
620 }
621 }
622
623 /// Drains queued Mini-Program touch, IME, resize, and lifecycle events.
624 ///
625 /// # Arguments
626 ///
627 /// - `&Self` - Mutable Mini-program platform.
628 ///
629 /// # Returns
630 ///
631 /// - `Vec<WindowEvent>` - Pending events.
632 fn poll_events(&mut self) -> Vec<WindowEvent> {
633 take(self.get_mut_pending_events())
634 }
635
636 /// Pauses or resumes the Mini-Program canvas frame pump flag.
637 ///
638 /// # Arguments
639 ///
640 /// - `&Self` - Mutable Mini-program platform.
641 /// - `bool` - `true` when hidden.
642 fn set_frame_pump_paused(&mut self, paused: bool) {
643 self.set_pump_paused(paused);
644 }
645
646 /// Returns whether the Mini-Program frame pump is paused.
647 ///
648 /// # Arguments
649 ///
650 /// - `&Self` - Mini-program platform reference.
651 ///
652 /// # Returns
653 ///
654 /// - `bool` - Pause state.
655 fn is_frame_pump_paused(&self) -> bool {
656 self.get_pump_paused()
657 }
658
659 /// Stores `framebuffer` and queues a `MiniAppHostCommand::PresentCanvas` command for the host canvas context.
660 ///
661 /// # Arguments
662 ///
663 /// - `&Self` - Mutable Mini-program platform.
664 /// - `WindowId` - Window identifier.
665 /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
666 ///
667 /// # Returns
668 ///
669 /// - `Result<(), PlatformError>` - Presentation status.
670 fn present_framebuffer(
671 &mut self,
672 id: WindowId,
673 framebuffer: &Framebuffer,
674 ) -> Result<(), PlatformError> {
675 let mode: MiniAppCanvasMode = {
676 let rec: &mut MiniAppWindowRecord = self
677 .get_mut_windows()
678 .get_mut(&id)
679 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
680 rec.set_last_frame(framebuffer.clone());
681 rec.set_present_count(rec.get_present_count().wrapping_add(1));
682 rec.get_canvas_mode()
683 };
684 self.get_mut_outbound_commands()
685 .push(MiniAppHostCommand::PresentCanvas {
686 mode,
687 width: framebuffer.get_width(),
688 height: framebuffer.get_height(),
689 });
690 Ok(())
691 }
692
693 /// Reads cached clipboard text.
694 ///
695 /// # Arguments
696 ///
697 /// - `&Self` - Mini-program platform reference.
698 ///
699 /// # Returns
700 ///
701 /// - `Option<String>` - Cached clipboard string.
702 fn read_clipboard(&self) -> Option<String> {
703 let Self { clipboard, .. } = self;
704 clipboard.clone()
705 }
706
707 /// Writes `text` to the clipboard cache and queues `MiniAppHostCommand::SetClipboardData`.
708 ///
709 /// # Arguments
710 ///
711 /// - `&Self` - Mutable Mini-program platform.
712 /// - `&str` - Clipboard text.
713 ///
714 /// # Returns
715 ///
716 /// - `Result<(), PlatformError>` - Write status.
717 fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
718 self.set_clipboard(Some(text.to_string()));
719 self.get_mut_outbound_commands()
720 .push(MiniAppHostCommand::SetClipboardData(text.to_string()));
721 Ok(())
722 }
723
724 /// Returns the active Mini-Program host theme mode.
725 ///
726 /// # Arguments
727 ///
728 /// - `&Self` - Mini-program platform reference.
729 ///
730 /// # Returns
731 ///
732 /// - `ThemeMode` - Active theme mode.
733 fn system_theme(&self) -> ThemeMode {
734 self.get_system_info().get_theme()
735 }
736}
737
738/// `PlatformStorage` implementation for `MiniAppPlatform`.
739impl PlatformStorage for MiniAppPlatform {
740 /// Reads `key` from mirrored Mini-Program sandbox storage.
741 ///
742 /// # Arguments
743 ///
744 /// - `&Self` - Mini-program platform reference.
745 /// - `&str` - Storage key.
746 ///
747 /// # Returns
748 ///
749 /// - `Option<String>` - Stored value, if present.
750 fn storage_get(&self, key: &str) -> Option<String> {
751 self.get_storage().get(key).cloned()
752 }
753
754 /// Writes `(key, value)` to mirrored storage and emits `MiniAppHostCommand::SetStorageSync`.
755 ///
756 /// # Arguments
757 ///
758 /// - `&Self` - Mutable Mini-program platform.
759 /// - `&str` - Storage key.
760 /// - `&str` - Value to store.
761 ///
762 /// # Returns
763 ///
764 /// - `Result<(), PlatformError>` - Storage status.
765 fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
766 let _: Option<String> = self
767 .get_mut_storage()
768 .insert(key.to_string(), value.to_string());
769 self.get_mut_outbound_commands()
770 .push(MiniAppHostCommand::SetStorageSync {
771 key: key.to_string(),
772 value: value.to_string(),
773 });
774 Ok(())
775 }
776
777 /// Removes `key` from mirrored storage and emits `MiniAppHostCommand::RemoveStorageSync`.
778 ///
779 /// # Arguments
780 ///
781 /// - `&Self` - Mutable Mini-program platform.
782 /// - `&str` - Storage key.
783 ///
784 /// # Returns
785 ///
786 /// - `Result<(), PlatformError>` - Removal status.
787 fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
788 let _: Option<String> = self.get_mut_storage().remove(key);
789 self.get_mut_outbound_commands()
790 .push(MiniAppHostCommand::RemoveStorageSync(key.to_string()));
791 Ok(())
792 }
793
794 /// Clears mirrored storage and emits `MiniAppHostCommand::ClearStorageSync`.
795 ///
796 /// # Arguments
797 ///
798 /// - `&Self` - Mutable Mini-program platform.
799 ///
800 /// # Returns
801 ///
802 /// - `Result<(), PlatformError>` - Clear status.
803 fn storage_clear(&mut self) -> Result<(), PlatformError> {
804 self.get_mut_storage().clear();
805 self.get_mut_outbound_commands()
806 .push(MiniAppHostCommand::ClearStorageSync);
807 Ok(())
808 }
809}
810
811/// `PlatformNavigation` implementation for `MiniAppPlatform`.
812impl PlatformNavigation for MiniAppPlatform {
813 /// Pushes `route` onto the Mini-Program navigation stack and emits `MiniAppHostCommand::NavigateTo`.
814 ///
815 /// # Arguments
816 ///
817 /// - `&Self` - Mutable Mini-program platform.
818 /// - `&str` - Target page route.
819 ///
820 /// # Returns
821 ///
822 /// - `Result<(), PlatformError>` - Navigation status.
823 fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
824 if !route.is_empty() {
825 self.get_mut_route_stack().push(route.to_string());
826 self.get_mut_outbound_commands()
827 .push(MiniAppHostCommand::NavigateTo(route.to_string()));
828 }
829 Ok(())
830 }
831
832 /// Pops `delta` entries from the navigation stack and emits `MiniAppHostCommand::NavigateBack`.
833 ///
834 /// # Arguments
835 ///
836 /// - `&Self` - Mutable Mini-program platform.
837 /// - `u32` - Pages to pop.
838 ///
839 /// # Returns
840 ///
841 /// - `Result<(), PlatformError>` - Navigation status.
842 fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
843 let steps: u32 = delta.max(1);
844 for _ in 0..steps {
845 if self.get_route_stack().len() > 1 {
846 let _: Option<String> = self.get_mut_route_stack().pop();
847 }
848 }
849 self.get_mut_outbound_commands()
850 .push(MiniAppHostCommand::NavigateBack(steps));
851 Ok(())
852 }
853
854 /// Returns the currently active Mini-Program route path.
855 ///
856 /// # Arguments
857 ///
858 /// - `&Self` - Mini-program platform reference.
859 ///
860 /// # Returns
861 ///
862 /// - `&str` - Active route path.
863 fn current_route(&self) -> &str {
864 self.get_route_stack()
865 .last()
866 .map(String::as_str)
867 .unwrap_or(MINIAPP_DEFAULT_ROUTE)
868 }
869}
870
871/// `PlatformLifecycleBridge` implementation for `MiniAppPlatform`.
872impl PlatformLifecycleBridge for MiniAppPlatform {
873 /// Maps Mini-Program `onHide` into unified freeze semantics.
874 ///
875 /// # Arguments
876 ///
877 /// - `&Self` - Mutable Mini-program platform.
878 ///
879 /// # Returns
880 ///
881 /// - `Vec<WindowEvent>` - Normalized freeze events.
882 fn freeze_surface(&mut self) -> Vec<WindowEvent> {
883 self.handle_lifecycle_hook(MiniAppLifecycleHook::OnHide)
884 }
885
886 /// Maps Mini-Program `onShow` into unified resume semantics.
887 ///
888 /// # Arguments
889 ///
890 /// - `&Self` - Mutable Mini-program platform.
891 ///
892 /// # Returns
893 ///
894 /// - `Vec<WindowEvent>` - Normalized resume events.
895 fn resume_surface(&mut self) -> Vec<WindowEvent> {
896 self.handle_lifecycle_hook(MiniAppLifecycleHook::OnShow { query_uri: None })
897 }
898
899 /// Maps Mini-Program `onUnload` into unified destroy semantics.
900 ///
901 /// # Arguments
902 ///
903 /// - `&Self` - Mutable Mini-program platform.
904 ///
905 /// # Returns
906 ///
907 /// - `Vec<WindowEvent>` - Normalized destroy events.
908 fn destroy_surface(&mut self) -> Vec<WindowEvent> {
909 self.handle_lifecycle_hook(MiniAppLifecycleHook::OnUnload)
910 }
911}
912
913/// `PlatformHostAdapter` implementation for `MiniAppPlatform`.
914impl PlatformHostAdapter for MiniAppPlatform {
915 /// Returns `DeviceFormFactor::MiniProgram`.
916 ///
917 /// # Arguments
918 ///
919 /// - `&Self` - Mini-program platform reference.
920 ///
921 /// # Returns
922 ///
923 /// - `DeviceFormFactor` - `DeviceFormFactor::MiniProgram`.
924 fn device_form_factor(&self) -> DeviceFormFactor {
925 DeviceFormFactor::MiniProgram
926 }
927
928 /// Returns the active Mini-Program vendor identifier (`"wechat"`, `"alipay"`, `"douyin"`, etc.).
929 ///
930 /// # Arguments
931 ///
932 /// - `&Self` - Mini-program platform reference.
933 ///
934 /// # Returns
935 ///
936 /// - `&'static str` - Canonical vendor identifier.
937 fn host_vendor_name(&self) -> &'static str {
938 self.get_system_info().get_vendor().as_str()
939 }
940}