euv_core/platform/quickapp/impl.rs
1use super::*;
2
3/// Canonical identifier and ABI tag helpers for `QuickAppVendor`.
4impl QuickAppVendor {
5 /// Returns the canonical lowercase QuickApp vendor identifier string.
6 ///
7 /// # Arguments
8 ///
9 /// - `&Self` - QuickApp 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::Alliance => QUICKAPP_VENDOR_ALLIANCE,
18 Self::Huawei => QUICKAPP_VENDOR_HUAWEI,
19 }
20 }
21
22 /// Parses a QuickApp vendor identifier or OEM alliance alias into a `QuickAppVendor`.
23 ///
24 /// # Arguments
25 ///
26 /// - `&str` - Vendor identifier or alias (case-insensitive).
27 ///
28 /// # Returns
29 ///
30 /// - `Option<Self>` - Matching `QuickAppVendor`, if recognized.
31 #[must_use]
32 pub fn from_str_id(name: &str) -> Option<Self> {
33 let lower: String = name.trim().to_ascii_lowercase();
34 match lower.as_str() {
35 QUICKAPP_VENDOR_ALLIANCE
36 | QUICKAPP_ALIAS_ALLIANCE
37 | QUICKAPP_ALIAS_XIAOMI
38 | QUICKAPP_ALIAS_OPPO
39 | QUICKAPP_ALIAS_VIVO
40 | QUICKAPP_ALIAS_HONOR => Some(Self::Alliance),
41 QUICKAPP_VENDOR_HUAWEI | QUICKAPP_ALIAS_HUAWEI => Some(Self::Huawei),
42 _ => None,
43 }
44 }
45
46 /// Returns a compact ABI tag byte stored in `RawWindowHandle::MiniAppCanvas`.
47 ///
48 /// # Arguments
49 ///
50 /// - `&Self` - QuickApp vendor variant.
51 ///
52 /// # Returns
53 ///
54 /// - `u8` - Numeric vendor discriminant (`101` Alliance, `102` Huawei).
55 #[must_use]
56 pub const fn tag(&self) -> u8 {
57 match *self {
58 Self::Alliance => 101,
59 Self::Huawei => 102,
60 }
61 }
62
63 /// Returns both supported QuickApp runtime vendors.
64 ///
65 /// # Returns
66 ///
67 /// - `[Self; 2]` - `[Alliance, Huawei]`.
68 #[must_use]
69 pub const fn all_vendors() -> [Self; 2] {
70 [Self::Alliance, Self::Huawei]
71 }
72}
73
74/// Manifest feature name helpers for `QuickAppFeatureModule`.
75impl QuickAppFeatureModule {
76 /// Returns the canonical `manifest.json` `"features"` name string (e.g. `"system.router"`).
77 ///
78 /// # Arguments
79 ///
80 /// - `&Self` - QuickApp feature module variant.
81 ///
82 /// # Returns
83 ///
84 /// - `&'static str` - Manifest feature identifier.
85 #[must_use]
86 pub const fn manifest_name(&self) -> &'static str {
87 match *self {
88 Self::Router => QUICKAPP_FEATURE_ROUTER,
89 Self::Storage => QUICKAPP_FEATURE_STORAGE,
90 Self::Clipboard => QUICKAPP_FEATURE_CLIPBOARD,
91 Self::Device => QUICKAPP_FEATURE_DEVICE,
92 Self::Network => QUICKAPP_FEATURE_NETWORK,
93 Self::Vibrator => QUICKAPP_FEATURE_VIBRATOR,
94 Self::Prompt => QUICKAPP_FEATURE_PROMPT,
95 Self::Share => QUICKAPP_FEATURE_SHARE,
96 Self::Sensor => QUICKAPP_FEATURE_SENSOR,
97 }
98 }
99
100 /// Returns the complete baseline set of QuickApp manifest features required by EUV hosts.
101 ///
102 /// # Returns
103 ///
104 /// - `[Self; 9]` - All 9 core QuickApp system features.
105 #[must_use]
106 pub const fn core_features() -> [Self; 9] {
107 [
108 Self::Router,
109 Self::Storage,
110 Self::Clipboard,
111 Self::Device,
112 Self::Network,
113 Self::Vibrator,
114 Self::Prompt,
115 Self::Share,
116 Self::Sensor,
117 ]
118 }
119}
120
121/// Default `QuickAppDeviceMetrics` modeling a 1080x2400@3x QuickApp Alliance device.
122impl Default for QuickAppDeviceMetrics {
123 /// Creates default QuickApp Alliance display metrics.
124 ///
125 /// # Returns
126 ///
127 /// - `Self` - Default `QuickAppDeviceMetrics`.
128 fn default() -> Self {
129 Self::for_vendor(QuickAppVendor::Alliance)
130 }
131}
132
133/// Preset and logical-size helpers for `QuickAppDeviceMetrics`.
134impl QuickAppDeviceMetrics {
135 /// Creates canonical display metrics for `vendor`.
136 ///
137 /// # Arguments
138 ///
139 /// - `QuickAppVendor` - QuickApp runtime vendor.
140 ///
141 /// # Returns
142 ///
143 /// - `Self` - Preset device metrics.
144 #[must_use]
145 pub const fn for_vendor(vendor: QuickAppVendor) -> Self {
146 Self {
147 vendor,
148 screen_width_px: QUICKAPP_DEFAULT_SCREEN_W_PX,
149 screen_height_px: QUICKAPP_DEFAULT_SCREEN_H_PX,
150 screen_density: QUICKAPP_DEFAULT_DENSITY,
151 design_width: QUICKAPP_DESIGN_WIDTH_PX,
152 status_bar_height_px: QUICKAPP_DEFAULT_STATUS_BAR_PX,
153 nav_bar_height_px: QUICKAPP_DEFAULT_NAV_BAR_PX,
154 theme: ThemeMode::Light,
155 }
156 }
157
158 /// Computes logical viewport width in dp (`screen_width_px / screen_density`).
159 ///
160 /// # Arguments
161 ///
162 /// - `&Self` - Device metrics reference.
163 ///
164 /// # Returns
165 ///
166 /// - `u32` - Logical viewport width in dp (`>= 1`).
167 #[must_use]
168 pub fn logical_width(&self) -> u32 {
169 let delta_val: f32 = self.get_screen_density().max(0.75);
170 ((self.get_screen_width_px().max(1) as f32) / delta_val)
171 .round()
172 .max(1.0) as u32
173 }
174
175 /// Computes logical viewport height in dp (`screen_height_px / screen_density`).
176 ///
177 /// # Arguments
178 ///
179 /// - `&Self` - Device metrics reference.
180 ///
181 /// # Returns
182 ///
183 /// - `u32` - Logical viewport height in dp (`>= 1`).
184 #[must_use]
185 pub fn logical_height(&self) -> u32 {
186 let delta_val: f32 = self.get_screen_density().max(0.75);
187 ((self.get_screen_height_px().max(1) as f32) / delta_val)
188 .round()
189 .max(1.0) as u32
190 }
191}
192
193/// Default `QuickAppPlatform` configured for QuickApp Alliance (`QuickAppVendor::Alliance`).
194impl Default for QuickAppPlatform {
195 /// Creates a default QuickApp Alliance host adapter.
196 ///
197 /// # Returns
198 ///
199 /// - `Self` - Default `QuickAppPlatform`.
200 fn default() -> Self {
201 Self::for_vendor(QuickAppVendor::Alliance)
202 }
203}
204
205/// Vendor constructors, touch/IME/lifecycle handlers, and `@system.*` command queue helpers for `QuickAppPlatform`.
206impl QuickAppPlatform {
207 /// Creates a `QuickAppPlatform` configured for `vendor`.
208 ///
209 /// # Arguments
210 ///
211 /// - `QuickAppVendor` - QuickApp runtime vendor (`Alliance` or `Huawei`).
212 ///
213 /// # Returns
214 ///
215 /// - `Self` - Configured QuickApp backend.
216 #[must_use]
217 pub fn for_vendor(vendor: QuickAppVendor) -> Self {
218 Self::from_metrics(QuickAppDeviceMetrics::for_vendor(vendor))
219 }
220
221 /// Creates a `QuickAppPlatform` from explicit `@system.device` screen metrics.
222 ///
223 /// # Arguments
224 ///
225 /// - `QuickAppDeviceMetrics` - Reported device screen metrics.
226 ///
227 /// # Returns
228 ///
229 /// - `Self` - Configured QuickApp backend.
230 #[must_use]
231 pub fn from_metrics(device_metrics: QuickAppDeviceMetrics) -> Self {
232 let safe_area: SafeAreaInsets = resolve_quickapp_safe_area(&device_metrics);
233 Self {
234 device_metrics,
235 safe_area,
236 next_id: 1,
237 primary_window: None,
238 windows: HashMap::new(),
239 touch_tracker: TouchPointerTracker::default(),
240 pending_events: Vec::new(),
241 outbound_commands: Vec::new(),
242 storage: HashMap::new(),
243 route_stack: vec![QUICKAPP_DEFAULT_ROUTE.to_string()],
244 clipboard: None,
245 pump_paused: false,
246 capture_last_frame: false,
247 refresh_rate_hz: HIGH_REFRESH_DEFAULT_HZ,
248 }
249 }
250
251 /// Updates the QuickApp host display refresh rate without imposing any artificial upper ceiling.
252 ///
253 /// # Arguments
254 ///
255 /// - `&Self` - Mutable QuickApp platform.
256 /// - `f32` - Reported host hardware display refresh rate in Hertz.
257 pub fn update_refresh_rate_hz(&mut self, hz: f32) {
258 if !hz.is_finite() || hz < MIN_REFRESH_RATE_HZ {
259 return;
260 }
261 self.set_refresh_rate_hz(hz);
262 let rounded_hz: u32 = hz.round() as u32;
263 for rec in self.get_mut_windows().values_mut() {
264 rec.get_mut_state()
265 .get_mut_display()
266 .set_refresh_rate_hz(rounded_hz);
267 }
268 }
269
270 /// Enables or disables retaining a cloned snapshot of the last presented framebuffer.
271 ///
272 /// # Arguments
273 ///
274 /// - `Self` - QuickApp platform value.
275 /// - `bool` - `true` to capture snapshots on each present; `false` for zero-clone production mode.
276 ///
277 /// # Returns
278 ///
279 /// - `Self` - Updated QuickApp platform backend.
280 #[must_use]
281 pub fn with_capture_last_frame(mut self, enabled: bool) -> Self {
282 self.set_capture_last_frame(enabled);
283 self
284 }
285
286 /// Returns the last presented framebuffer snapshot for `id` when `capture_last_frame` is enabled.
287 ///
288 /// # Arguments
289 ///
290 /// - `&Self` - QuickApp platform reference.
291 /// - `WindowId` - Canvas window identifier.
292 ///
293 /// # Returns
294 ///
295 /// - `Option<&Framebuffer>` - Cloned framebuffer reference when capture is enabled and `id` exists.
296 #[must_use]
297 pub fn last_framebuffer(&self, id: WindowId) -> Option<&Framebuffer> {
298 if !self.get_capture_last_frame() {
299 return None;
300 }
301 self.get_windows()
302 .get(&id)
303 .map(QuickAppWindowRecord::get_last_frame)
304 }
305
306 /// Returns the primary QuickApp canvas `WindowId`, if created.
307 ///
308 /// # Arguments
309 ///
310 /// - `&Self` - QuickApp platform reference.
311 ///
312 /// # Returns
313 ///
314 /// - `Option<WindowId>` - Primary window handle.
315 #[must_use]
316 pub fn primary_window_id(&self) -> Option<WindowId> {
317 let Self { primary_window, .. } = self;
318 *primary_window
319 }
320
321 /// Drains all queued outbound `@system.*` host commands for execution by the UX shell.
322 ///
323 /// # Arguments
324 ///
325 /// - `&Self` - Mutable QuickApp platform.
326 ///
327 /// # Returns
328 ///
329 /// - `Vec<QuickAppHostCommand>` - Ordered host commands.
330 pub fn drain_host_commands(&mut self) -> Vec<QuickAppHostCommand> {
331 take(self.get_mut_outbound_commands())
332 }
333
334 /// Translates QuickApp `<canvas>` touch coordinates (in `750px` design space) into EUV logical dp pointer events.
335 ///
336 /// # Arguments
337 ///
338 /// - `&Self` - Mutable QuickApp platform.
339 /// - `i32` - Normalized touch action (`ANDROID_ACTION_DOWN`..`ANDROID_ACTION_CANCEL`).
340 /// - `&[(i32, f32, f32)]` - Touch tuples `(pointer_id, design_x, design_y)`.
341 ///
342 /// # Returns
343 ///
344 /// - `Vec<WindowEvent>` - Normalized pointer events also enqueued for `poll_events()`.
345 pub fn handle_design_touch(
346 &mut self,
347 action: i32,
348 design_touches: &[(i32, f32, f32)],
349 ) -> Vec<WindowEvent> {
350 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
351 let metrics: QuickAppDeviceMetrics = self.get_device_metrics();
352 let mut logical: Vec<(i32, f32, f32)> = Vec::with_capacity(design_touches.len());
353 for &(pid, dx, dy) in design_touches.iter() {
354 logical.push((
355 pid,
356 quickapp_design_px_to_dp(dx, &metrics),
357 quickapp_design_px_to_dp(dy, &metrics),
358 ));
359 }
360 let events: Vec<WindowEvent> = self
361 .get_mut_touch_tracker()
362 .handle_android_motion(wid, action, 0, &logical);
363 self.get_mut_pending_events().extend(events.clone());
364 events
365 }
366
367 /// Dispatches UTF-8 text received from a QuickApp `<input>` bridge into EUV `TextInput` / `Ime` events.
368 ///
369 /// # Arguments
370 ///
371 /// - `&Self` - Mutable QuickApp platform.
372 /// - `String` - Committed UTF-8 text.
373 pub fn handle_ime_commit(&mut self, text: String) {
374 if text.is_empty() {
375 return;
376 }
377 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
378 self.get_mut_pending_events()
379 .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
380 self.get_mut_pending_events()
381 .push(WindowEvent::TextInput(wid, text));
382 }
383
384 /// Enqueues a 6-DOF `DeviceMotionSample` received from `@system.sensor`.
385 ///
386 /// # Arguments
387 ///
388 /// - `&Self` - Mutable QuickApp platform.
389 /// - `DeviceMotionSample` - Accelerometer/gyroscope motion sample.
390 pub fn handle_device_motion(&mut self, sample: DeviceMotionSample) {
391 self.get_mut_pending_events()
392 .push(WindowEvent::System(SystemEvent::DeviceMotion(sample)));
393 }
394
395 /// Updates physical screen dimensions and display density and emits `WindowEvent::Resized`.
396 ///
397 /// # Arguments
398 ///
399 /// - `&Self` - Mutable QuickApp platform.
400 /// - `u32` - Updated physical screen width in pixels.
401 /// - `u32` - Updated physical screen height in pixels.
402 /// - `f32` - Updated screen density scale factor.
403 pub fn handle_resize(&mut self, width_px: u32, height_px: u32, density: f32) {
404 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
405 let delta_val: f32 = clamp_viewport_scale(density);
406 let pw: u32 = width_px.max(1);
407 let ph: u32 = height_px.max(1);
408 self.get_mut_device_metrics()
409 .set_screen_width_px(pw)
410 .set_screen_height_px(ph)
411 .set_screen_density(delta_val);
412 let exact_lw: f32 = ((pw as f32) / delta_val).max(1.0);
413 let exact_lh: f32 = ((ph as f32) / delta_val).max(1.0);
414 let lw: u32 = exact_lw.round().max(1.0) as u32;
415 let lh: u32 = exact_lh.round().max(1.0) as u32;
416 for rec in self.get_mut_windows().values_mut() {
417 rec.get_mut_state()
418 .set_logical_width(exact_lw)
419 .set_logical_height(exact_lh)
420 .set_physical_width(pw)
421 .set_physical_height(ph)
422 .set_scale_factor(delta_val);
423 }
424 self.get_mut_pending_events()
425 .push(WindowEvent::Resized(wid, lw, lh, delta_val));
426 self.get_mut_pending_events()
427 .push(WindowEvent::System(SystemEvent::Resize {
428 width: exact_lw,
429 height: exact_lh,
430 scale_factor: delta_val,
431 }));
432 }
433
434 /// Translates a QuickApp `app.ux` / `page.ux` lifecycle callback into canonical EUV `SystemEvent`s.
435 ///
436 /// # Arguments
437 ///
438 /// - `&Self` - Mutable QuickApp platform.
439 /// - `QuickAppLifecycleHook` - QuickApp lifecycle hook payload.
440 ///
441 /// # Returns
442 ///
443 /// - `Vec<WindowEvent>` - Normalized events also enqueued for `poll_events()`.
444 pub fn handle_lifecycle_hook(&mut self, hook: QuickAppLifecycleHook) -> Vec<WindowEvent> {
445 let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
446 let mut emitted: Vec<WindowEvent> = Vec::new();
447 match hook {
448 QuickAppLifecycleHook::OnCreate { deep_link } => {
449 self.set_pump_paused(false);
450 if let Some(uri) = deep_link
451 && !uri.is_empty()
452 {
453 emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
454 }
455 }
456 QuickAppLifecycleHook::OnShow => {
457 self.set_pump_paused(false);
458 emitted.push(WindowEvent::System(SystemEvent::Appear));
459 emitted.push(WindowEvent::System(SystemEvent::Foreground));
460 }
461 QuickAppLifecycleHook::OnHide => {
462 self.set_pump_paused(true);
463 let cancels: Vec<WindowEvent> =
464 self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
465 emitted.extend(cancels);
466 emitted.push(WindowEvent::System(SystemEvent::Disappear));
467 emitted.push(WindowEvent::System(SystemEvent::Background));
468 }
469 QuickAppLifecycleHook::OnDestroy => {
470 self.set_pump_paused(true);
471 let cancels: Vec<WindowEvent> =
472 self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
473 emitted.extend(cancels);
474 emitted.push(WindowEvent::System(SystemEvent::Terminate));
475 }
476 QuickAppLifecycleHook::OnBackPress => {
477 emitted.push(WindowEvent::KeyDown(
478 wid,
479 KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
480 ));
481 emitted.push(WindowEvent::System(SystemEvent::BackPressed));
482 }
483 QuickAppLifecycleHook::OnConfigurationChanged { theme, locale } => {
484 self.get_mut_device_metrics().set_theme(theme);
485 emitted.push(WindowEvent::ThemeChanged(wid, theme));
486 emitted.push(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
487 if !locale.trim().is_empty() {
488 emitted.push(WindowEvent::System(SystemEvent::LocaleChanged(locale)));
489 }
490 }
491 QuickAppLifecycleHook::OnMemoryWarning(level) => {
492 let pressure: MemoryPressure = if level >= 2 {
493 MemoryPressure::Critical
494 } else if level > 0 {
495 MemoryPressure::Warning
496 } else {
497 MemoryPressure::Normal
498 };
499 emitted.push(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
500 }
501 QuickAppLifecycleHook::OnKeyboardChanged { visible, height_px } => {
502 let density: f32 = self.get_device_metrics().get_screen_density().max(0.75);
503 let height_dp: f32 = if visible {
504 (height_px as f32) / density
505 } else {
506 0.0
507 };
508 emitted.push(WindowEvent::System(
509 SystemEvent::KeyboardVisibilityChanged {
510 visible,
511 height: height_dp,
512 },
513 ));
514 }
515 QuickAppLifecycleHook::OnNetworkChanged(status) => {
516 emitted.push(WindowEvent::System(SystemEvent::NetworkStatusChanged(
517 status,
518 )));
519 }
520 }
521 self.get_mut_pending_events().extend(emitted.clone());
522 emitted
523 }
524}
525
526/// `WindowController` implementation for `QuickAppPlatform`.
527impl WindowController for QuickAppPlatform {
528 /// Applies a `WindowCommand` against the QuickApp `<canvas>` window record.
529 ///
530 /// # Arguments
531 ///
532 /// - `&Self` - Mutable QuickApp platform.
533 /// - `WindowCommand` - Command to apply.
534 ///
535 /// # Returns
536 ///
537 /// - `Result<(), PlatformError>` - Execution status.
538 fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
539 match command {
540 WindowCommand::SetTitle(id, title) => {
541 let rec: &mut QuickAppWindowRecord = self
542 .get_mut_windows()
543 .get_mut(&id)
544 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
545 rec.get_mut_config().set_title(title.clone());
546 self.get_mut_outbound_commands()
547 .push(QuickAppHostCommand::SetTitleBar(title));
548 Ok(())
549 }
550 WindowCommand::RequestRedraw(id) => {
551 if !self.get_windows().contains_key(&id) {
552 return Err(PlatformError::WindowNotFound(id.get_value()));
553 }
554 self.get_mut_pending_events()
555 .push(WindowEvent::RedrawRequested(id));
556 Ok(())
557 }
558 WindowCommand::Close(id) => {
559 if self.get_mut_windows().remove(&id).is_none() {
560 return Err(PlatformError::WindowNotFound(id.get_value()));
561 }
562 Ok(())
563 }
564 WindowCommand::SetIme(id, enabled, rect) => {
565 if !self.get_windows().contains_key(&id) {
566 return Err(PlatformError::WindowNotFound(id.get_value()));
567 }
568 self.get_mut_outbound_commands()
569 .push(QuickAppHostCommand::ShowKeyboard { enabled, rect });
570 Ok(())
571 }
572 WindowCommand::SetSize(id, _, _)
573 | WindowCommand::SetPosition(id, _, _)
574 | WindowCommand::SetResizable(id, _)
575 | WindowCommand::SetDecorations(id, _)
576 | WindowCommand::SetAlwaysOnTop(id, _)
577 | WindowCommand::SetFullscreen(id, _)
578 | WindowCommand::SetVisible(id, _)
579 | WindowCommand::SetCursor(id, _)
580 | WindowCommand::SetStatusBarStyle(id, _)
581 | WindowCommand::SetRenderMode(id, _) => {
582 if !self.get_windows().contains_key(&id) {
583 return Err(PlatformError::WindowNotFound(id.get_value()));
584 }
585 Ok(())
586 }
587 }
588 }
589}
590
591/// `PlatformBackend` implementation for `QuickAppPlatform`.
592impl PlatformBackend for QuickAppPlatform {
593 /// Returns `PlatformKind::QuickApp`.
594 ///
595 /// # Arguments
596 ///
597 /// - `&Self` - QuickApp platform reference.
598 ///
599 /// # Returns
600 ///
601 /// - `PlatformKind` - `PlatformKind::QuickApp`.
602 fn kind(&self) -> PlatformKind {
603 PlatformKind::QuickApp
604 }
605
606 /// Returns QuickApp capability flags.
607 ///
608 /// # Arguments
609 ///
610 /// - `&Self` - QuickApp platform reference.
611 ///
612 /// # Returns
613 ///
614 /// - `PlatformCapabilities` - QuickApp capability matrix.
615 fn capabilities(&self) -> PlatformCapabilities {
616 PlatformCapabilities::for_platform(PlatformKind::QuickApp)
617 }
618
619 /// Creates a QuickApp `<canvas>` window sized to the normalized logical screen dimensions.
620 ///
621 /// # Arguments
622 ///
623 /// - `&Self` - Mutable QuickApp platform.
624 /// - `&WindowConfig` - Declarative window config.
625 ///
626 /// # Returns
627 ///
628 /// - `Result<WindowState, PlatformError>` - Created QuickApp window state.
629 fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
630 let id: WindowId = WindowId::new(self.get_next_id());
631 self.set_next_id(self.get_next_id().wrapping_add(1));
632 let metrics: QuickAppDeviceMetrics = self.get_device_metrics();
633 let mut qa_cfg: WindowConfig = config.clone();
634 qa_cfg.set_size(metrics.logical_width(), metrics.logical_height());
635 let mut state: WindowState =
636 WindowState::from_config(id, &qa_cfg, metrics.get_screen_density());
637 state.set_safe_area(self.get_safe_area());
638 state.set_system_theme(metrics.get_theme());
639 state
640 .get_mut_display()
641 .set_refresh_rate_hz(self.get_refresh_rate_hz().round() as u32);
642 let record: QuickAppWindowRecord = QuickAppWindowRecord {
643 config: qa_cfg,
644 state,
645 canvas_id: id.get_value() as u32,
646 last_frame: Framebuffer::allocate(1, 1),
647 present_count: 0,
648 };
649 self.get_mut_windows().insert(id, record);
650 if self.primary_window_id().is_none() {
651 self.set_primary_window(Some(id));
652 }
653 Ok(state)
654 }
655
656 /// Queries live `WindowState` for `id`.
657 ///
658 /// # Arguments
659 ///
660 /// - `&Self` - QuickApp platform reference.
661 /// - `WindowId` - Window identifier.
662 ///
663 /// # Returns
664 ///
665 /// - `Option<WindowState>` - Window state if alive.
666 fn window_state(&self, id: WindowId) -> Option<WindowState> {
667 self.get_windows()
668 .get(&id)
669 .map(QuickAppWindowRecord::get_state)
670 }
671
672 /// Returns `RawWindowHandle::MiniAppCanvas` tagged with the active `QuickAppVendor`.
673 ///
674 /// # Arguments
675 ///
676 /// - `&Self` - QuickApp platform reference.
677 /// - `WindowId` - Window identifier.
678 ///
679 /// # Returns
680 ///
681 /// - `RawWindowHandle` - QuickApp canvas handle.
682 fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
683 match self.get_windows().get(&id) {
684 Some(rec) => RawWindowHandle::MiniAppCanvas {
685 canvas_id: rec.get_canvas_id(),
686 vendor_tag: self.get_device_metrics().get_vendor().tag(),
687 },
688 None => RawWindowHandle::Headless,
689 }
690 }
691
692 /// Drains queued QuickApp touch, IME, back-press, and lifecycle events.
693 ///
694 /// # Arguments
695 ///
696 /// - `&Self` - Mutable QuickApp platform.
697 ///
698 /// # Returns
699 ///
700 /// - `Vec<WindowEvent>` - Pending events.
701 fn poll_events(&mut self) -> Vec<WindowEvent> {
702 take(self.get_mut_pending_events())
703 }
704
705 /// Pauses or resumes the QuickApp canvas frame pump flag.
706 ///
707 /// # Arguments
708 ///
709 /// - `&Self` - Mutable QuickApp platform.
710 /// - `bool` - `true` to pause for background freeze.
711 fn set_frame_pump_paused(&mut self, paused: bool) {
712 self.set_pump_paused(paused);
713 }
714
715 /// Returns whether the QuickApp frame pump is paused.
716 ///
717 /// # Arguments
718 ///
719 /// - `&Self` - QuickApp platform reference.
720 ///
721 /// # Returns
722 ///
723 /// - `bool` - Pause state.
724 fn is_frame_pump_paused(&self) -> bool {
725 self.get_pump_paused()
726 }
727
728 /// Stores `framebuffer` and queues `QuickAppHostCommand::PresentCanvas`.
729 ///
730 /// # Arguments
731 ///
732 /// - `&Self` - Mutable QuickApp platform.
733 /// - `WindowId` - Window identifier.
734 /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
735 ///
736 /// # Returns
737 ///
738 /// - `Result<(), PlatformError>` - Presentation status.
739 fn present_framebuffer(
740 &mut self,
741 id: WindowId,
742 framebuffer: &Framebuffer,
743 ) -> Result<(), PlatformError> {
744 let capture: bool = self.get_capture_last_frame();
745 let rec: &mut QuickAppWindowRecord = self
746 .get_mut_windows()
747 .get_mut(&id)
748 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
749 if capture {
750 rec.set_last_frame(framebuffer.clone());
751 }
752 rec.set_present_count(rec.get_present_count().wrapping_add(1));
753 self.get_mut_outbound_commands()
754 .push(QuickAppHostCommand::PresentCanvas {
755 width: framebuffer.get_width(),
756 height: framebuffer.get_height(),
757 });
758 Ok(())
759 }
760
761 /// Reads mirrored `@system.clipboard` text.
762 ///
763 /// # Arguments
764 ///
765 /// - `&Self` - QuickApp platform reference.
766 ///
767 /// # Returns
768 ///
769 /// - `Option<String>` - Cached clipboard string.
770 fn read_clipboard(&self) -> Option<String> {
771 let Self { clipboard, .. } = self;
772 clipboard.clone()
773 }
774
775 /// Writes `text` to clipboard cache and queues `QuickAppHostCommand::ClipboardSet`.
776 ///
777 /// # Arguments
778 ///
779 /// - `&Self` - Mutable QuickApp platform.
780 /// - `&str` - Clipboard text.
781 ///
782 /// # Returns
783 ///
784 /// - `Result<(), PlatformError>` - Write status.
785 fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
786 self.set_clipboard(Some(text.to_string()));
787 self.get_mut_outbound_commands()
788 .push(QuickAppHostCommand::ClipboardSet(text.to_string()));
789 Ok(())
790 }
791
792 /// Returns active QuickApp appearance mode.
793 ///
794 /// # Arguments
795 ///
796 /// - `&Self` - QuickApp platform reference.
797 ///
798 /// # Returns
799 ///
800 /// - `ThemeMode` - Active appearance mode.
801 fn system_theme(&self) -> ThemeMode {
802 self.get_device_metrics().get_theme()
803 }
804
805 /// Returns the uncapped QuickApp host display refresh rate in Hertz.
806 ///
807 /// # Arguments
808 ///
809 /// - `&Self` - QuickApp platform reference.
810 ///
811 /// # Returns
812 ///
813 /// - `f32` - Active host display refresh rate in Hertz.
814 fn display_refresh_rate_hz(&self) -> f32 {
815 self.get_refresh_rate_hz()
816 }
817}
818
819/// `PlatformStorage` implementation backed by `@system.storage` commands.
820impl PlatformStorage for QuickAppPlatform {
821 /// Reads `key` from mirrored `@system.storage`.
822 ///
823 /// # Arguments
824 ///
825 /// - `&Self` - QuickApp platform reference.
826 /// - `&str` - Storage key.
827 ///
828 /// # Returns
829 ///
830 /// - `Option<String>` - Stored value, if present.
831 fn storage_get(&self, key: &str) -> Option<String> {
832 self.get_storage().get(key).cloned()
833 }
834
835 /// Persists `(key, value)` and emits `QuickAppHostCommand::StorageSet`.
836 ///
837 /// # Arguments
838 ///
839 /// - `&Self` - Mutable QuickApp platform.
840 /// - `&str` - Storage key.
841 /// - `&str` - Value to store.
842 ///
843 /// # Returns
844 ///
845 /// - `Result<(), PlatformError>` - Storage status.
846 fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
847 let _: Option<String> = self
848 .get_mut_storage()
849 .insert(key.to_string(), value.to_string());
850 self.get_mut_outbound_commands()
851 .push(QuickAppHostCommand::StorageSet {
852 key: key.to_string(),
853 value: value.to_string(),
854 });
855 Ok(())
856 }
857
858 /// Removes `key` and emits `QuickAppHostCommand::StorageDelete`.
859 ///
860 /// # Arguments
861 ///
862 /// - `&Self` - Mutable QuickApp platform.
863 /// - `&str` - Storage key.
864 ///
865 /// # Returns
866 ///
867 /// - `Result<(), PlatformError>` - Removal status.
868 fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
869 let _: Option<String> = self.get_mut_storage().remove(key);
870 self.get_mut_outbound_commands()
871 .push(QuickAppHostCommand::StorageDelete(key.to_string()));
872 Ok(())
873 }
874
875 /// Clears storage and emits `QuickAppHostCommand::StorageClear`.
876 ///
877 /// # Arguments
878 ///
879 /// - `&Self` - Mutable QuickApp platform.
880 ///
881 /// # Returns
882 ///
883 /// - `Result<(), PlatformError>` - Clear status.
884 fn storage_clear(&mut self) -> Result<(), PlatformError> {
885 self.get_mut_storage().clear();
886 self.get_mut_outbound_commands()
887 .push(QuickAppHostCommand::StorageClear);
888 Ok(())
889 }
890}
891
892/// `PlatformNavigation` implementation backed by `@system.router` commands.
893impl PlatformNavigation for QuickAppPlatform {
894 /// Pushes `route` and emits `QuickAppHostCommand::RouterPush`.
895 ///
896 /// # Arguments
897 ///
898 /// - `&Self` - Mutable QuickApp platform.
899 /// - `&str` - Target page route URI.
900 ///
901 /// # Returns
902 ///
903 /// - `Result<(), PlatformError>` - Navigation status.
904 fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
905 if !route.is_empty() {
906 self.get_mut_route_stack().push(route.to_string());
907 self.get_mut_outbound_commands()
908 .push(QuickAppHostCommand::RouterPush(route.to_string()));
909 }
910 Ok(())
911 }
912
913 /// Pops `delta` entries and emits `QuickAppHostCommand::RouterBack`.
914 ///
915 /// # Arguments
916 ///
917 /// - `&Self` - Mutable QuickApp platform.
918 /// - `u32` - Pages to navigate back.
919 ///
920 /// # Returns
921 ///
922 /// - `Result<(), PlatformError>` - Navigation status.
923 fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
924 let steps: u32 = delta.max(1);
925 for _ in 0..steps {
926 if self.get_route_stack().len() > 1 {
927 let _: Option<String> = self.get_mut_route_stack().pop();
928 }
929 }
930 self.get_mut_outbound_commands()
931 .push(QuickAppHostCommand::RouterBack(steps));
932 Ok(())
933 }
934
935 /// Returns the currently active QuickApp page route URI.
936 ///
937 /// # Arguments
938 ///
939 /// - `&Self` - QuickApp platform reference.
940 ///
941 /// # Returns
942 ///
943 /// - `&str` - Active page route.
944 fn current_route(&self) -> &str {
945 self.get_route_stack()
946 .last()
947 .map(String::as_str)
948 .unwrap_or(QUICKAPP_DEFAULT_ROUTE)
949 }
950}
951
952/// `PlatformLifecycleBridge` implementation for `QuickAppPlatform`.
953impl PlatformLifecycleBridge for QuickAppPlatform {
954 /// Maps QuickApp `onHide` into unified freeze semantics.
955 ///
956 /// # Arguments
957 ///
958 /// - `&Self` - Mutable QuickApp platform.
959 ///
960 /// # Returns
961 ///
962 /// - `Vec<WindowEvent>` - Normalized freeze events.
963 fn freeze_surface(&mut self) -> Vec<WindowEvent> {
964 self.handle_lifecycle_hook(QuickAppLifecycleHook::OnHide)
965 }
966
967 /// Maps QuickApp `onShow` into unified resume semantics.
968 ///
969 /// # Arguments
970 ///
971 /// - `&Self` - Mutable QuickApp platform.
972 ///
973 /// # Returns
974 ///
975 /// - `Vec<WindowEvent>` - Normalized resume events.
976 fn resume_surface(&mut self) -> Vec<WindowEvent> {
977 self.handle_lifecycle_hook(QuickAppLifecycleHook::OnShow)
978 }
979
980 /// Maps QuickApp `onDestroy` into unified destroy semantics.
981 ///
982 /// # Arguments
983 ///
984 /// - `&Self` - Mutable QuickApp platform.
985 ///
986 /// # Returns
987 ///
988 /// - `Vec<WindowEvent>` - Normalized destroy events.
989 fn destroy_surface(&mut self) -> Vec<WindowEvent> {
990 self.handle_lifecycle_hook(QuickAppLifecycleHook::OnDestroy)
991 }
992}
993
994/// `PlatformHostAdapter` implementation for `QuickAppPlatform`.
995impl PlatformHostAdapter for QuickAppPlatform {
996 /// Returns `DeviceFormFactor::MiniProgram`.
997 ///
998 /// # Arguments
999 ///
1000 /// - `&Self` - QuickApp platform reference.
1001 ///
1002 /// # Returns
1003 ///
1004 /// - `DeviceFormFactor` - `DeviceFormFactor::MiniProgram`.
1005 fn device_form_factor(&self) -> DeviceFormFactor {
1006 DeviceFormFactor::MiniProgram
1007 }
1008
1009 /// Returns `"quickapp-alliance"` or `"quickapp-huawei"`.
1010 ///
1011 /// # Arguments
1012 ///
1013 /// - `&Self` - QuickApp platform reference.
1014 ///
1015 /// # Returns
1016 ///
1017 /// - `&'static str` - Canonical QuickApp vendor identifier.
1018 fn host_vendor_name(&self) -> &'static str {
1019 self.get_device_metrics().get_vendor().as_str()
1020 }
1021}
1022
1023/// Unified host-channel capability and visual-equivalence queries for `QuickAppPlatform`.
1024impl QuickAppPlatform {
1025 /// Returns the truthful `HostChannelCapabilities` declared by this QuickApp runtime.
1026 ///
1027 /// QuickApp hosts expose a single `<canvas>` 2D channel by default (`supported_channels.len() == 1`, zero probing),
1028 /// and simulated/off-device profiles ALWAYS set `simulated_profile = true` and `direct_gpu_verified_on_device = false`.
1029 ///
1030 /// # Returns
1031 ///
1032 /// - `HostChannelCapabilities` - Declared QuickApp channels, visual gate, and honesty flags.
1033 #[must_use]
1034 pub fn host_channel_capabilities(&self) -> HostChannelCapabilities {
1035 let simulated: bool = !cfg!(target_arch = "wasm32");
1036 HostChannelCapabilities::from_host_declaration(
1037 self.host_vendor_name(),
1038 vec![HostRenderChannel::Canvas2d],
1039 HostRenderChannel::Canvas2d,
1040 HostVisualEquivalenceGate::default(),
1041 simulated,
1042 false,
1043 )
1044 }
1045
1046 /// Resolves the QuickApp rendering channel under unified visual-equivalence and single-channel non-probing rules.
1047 ///
1048 /// # Arguments
1049 ///
1050 /// - `Option<HostRenderChannel>` - Optional requested channel.
1051 ///
1052 /// # Returns
1053 ///
1054 /// - `HostChannelSelection` - Resolved channel decision.
1055 #[must_use]
1056 pub fn select_render_channel(
1057 &self,
1058 requested: Option<HostRenderChannel>,
1059 ) -> HostChannelSelection {
1060 self.host_channel_capabilities().select_channel(requested)
1061 }
1062}