Skip to main content

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        }
247    }
248
249    /// Returns the primary QuickApp canvas `WindowId`, if created.
250    ///
251    /// # Arguments
252    ///
253    /// - `&Self` - QuickApp platform reference.
254    ///
255    /// # Returns
256    ///
257    /// - `Option<WindowId>` - Primary window handle.
258    #[must_use]
259    pub fn primary_window_id(&self) -> Option<WindowId> {
260        let Self { primary_window, .. } = self;
261        *primary_window
262    }
263
264    /// Drains all queued outbound `@system.*` host commands for execution by the UX shell.
265    ///
266    /// # Arguments
267    ///
268    /// - `&Self` - Mutable QuickApp platform.
269    ///
270    /// # Returns
271    ///
272    /// - `Vec<QuickAppHostCommand>` - Ordered host commands.
273    pub fn drain_host_commands(&mut self) -> Vec<QuickAppHostCommand> {
274        take(self.get_mut_outbound_commands())
275    }
276
277    /// Translates QuickApp `<canvas>` touch coordinates (in `750px` design space) into EUV logical dp pointer events.
278    ///
279    /// # Arguments
280    ///
281    /// - `&Self` - Mutable QuickApp platform.
282    /// - `i32` - Normalized touch action (`ANDROID_ACTION_DOWN`..`ANDROID_ACTION_CANCEL`).
283    /// - `&[(i32, f32, f32)]` - Touch tuples `(pointer_id, design_x, design_y)`.
284    ///
285    /// # Returns
286    ///
287    /// - `Vec<WindowEvent>` - Normalized pointer events also enqueued for `poll_events()`.
288    pub fn handle_design_touch(
289        &mut self,
290        action: i32,
291        design_touches: &[(i32, f32, f32)],
292    ) -> Vec<WindowEvent> {
293        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
294        let metrics: QuickAppDeviceMetrics = self.get_device_metrics();
295        let mut logical: Vec<(i32, f32, f32)> = Vec::with_capacity(design_touches.len());
296        for &(pid, dx, dy) in design_touches.iter() {
297            logical.push((
298                pid,
299                quickapp_design_px_to_dp(dx, &metrics),
300                quickapp_design_px_to_dp(dy, &metrics),
301            ));
302        }
303        let events: Vec<WindowEvent> = self
304            .get_mut_touch_tracker()
305            .handle_android_motion(wid, action, 0, &logical);
306        self.get_mut_pending_events().extend(events.clone());
307        events
308    }
309
310    /// Dispatches UTF-8 text received from a QuickApp `<input>` bridge into EUV `TextInput` / `Ime` events.
311    ///
312    /// # Arguments
313    ///
314    /// - `&Self` - Mutable QuickApp platform.
315    /// - `String` - Committed UTF-8 text.
316    pub fn handle_ime_commit(&mut self, text: String) {
317        if text.is_empty() {
318            return;
319        }
320        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
321        self.get_mut_pending_events()
322            .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
323        self.get_mut_pending_events()
324            .push(WindowEvent::TextInput(wid, text));
325    }
326
327    /// Enqueues a 6-DOF `DeviceMotionSample` received from `@system.sensor`.
328    ///
329    /// # Arguments
330    ///
331    /// - `&Self` - Mutable QuickApp platform.
332    /// - `DeviceMotionSample` - Accelerometer/gyroscope motion sample.
333    pub fn handle_device_motion(&mut self, sample: DeviceMotionSample) {
334        self.get_mut_pending_events()
335            .push(WindowEvent::System(SystemEvent::DeviceMotion(sample)));
336    }
337
338    /// Updates physical screen dimensions and display density and emits `WindowEvent::Resized`.
339    ///
340    /// # Arguments
341    ///
342    /// - `&Self` - Mutable QuickApp platform.
343    /// - `u32` - Updated physical screen width in pixels.
344    /// - `u32` - Updated physical screen height in pixels.
345    /// - `f32` - Updated screen density scale factor.
346    pub fn handle_resize(&mut self, width_px: u32, height_px: u32, density: f32) {
347        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
348        let delta_val: f32 = if density.is_finite() {
349            density.clamp(0.75, 4.5)
350        } else {
351            1.0
352        };
353        self.get_mut_device_metrics()
354            .set_screen_width_px(width_px.max(1))
355            .set_screen_height_px(height_px.max(1))
356            .set_screen_density(delta_val);
357        let metrics: QuickAppDeviceMetrics = self.get_device_metrics();
358        let lw: u32 = metrics.logical_width();
359        let lh: u32 = metrics.logical_height();
360        for rec in self.get_mut_windows().values_mut() {
361            rec.get_mut_state()
362                .set_logical_width(lw as f32)
363                .set_logical_height(lh as f32)
364                .set_physical_width(width_px.max(1))
365                .set_physical_height(height_px.max(1))
366                .set_scale_factor(delta_val);
367        }
368        self.get_mut_pending_events()
369            .push(WindowEvent::Resized(wid, lw, lh, delta_val));
370        self.get_mut_pending_events()
371            .push(WindowEvent::System(SystemEvent::Resize {
372                width: lw as f32,
373                height: lh as f32,
374                scale_factor: delta_val,
375            }));
376    }
377
378    /// Translates a QuickApp `app.ux` / `page.ux` lifecycle callback into canonical EUV `SystemEvent`s.
379    ///
380    /// # Arguments
381    ///
382    /// - `&Self` - Mutable QuickApp platform.
383    /// - `QuickAppLifecycleHook` - QuickApp lifecycle hook payload.
384    ///
385    /// # Returns
386    ///
387    /// - `Vec<WindowEvent>` - Normalized events also enqueued for `poll_events()`.
388    pub fn handle_lifecycle_hook(&mut self, hook: QuickAppLifecycleHook) -> Vec<WindowEvent> {
389        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
390        let mut emitted: Vec<WindowEvent> = Vec::new();
391        match hook {
392            QuickAppLifecycleHook::OnCreate { deep_link } => {
393                self.set_pump_paused(false);
394                if let Some(uri) = deep_link
395                    && !uri.is_empty()
396                {
397                    emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
398                }
399            }
400            QuickAppLifecycleHook::OnShow => {
401                self.set_pump_paused(false);
402                emitted.push(WindowEvent::System(SystemEvent::Appear));
403                emitted.push(WindowEvent::System(SystemEvent::Foreground));
404            }
405            QuickAppLifecycleHook::OnHide => {
406                self.set_pump_paused(true);
407                let cancels: Vec<WindowEvent> =
408                    self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
409                emitted.extend(cancels);
410                emitted.push(WindowEvent::System(SystemEvent::Disappear));
411                emitted.push(WindowEvent::System(SystemEvent::Background));
412            }
413            QuickAppLifecycleHook::OnDestroy => {
414                self.set_pump_paused(true);
415                let cancels: Vec<WindowEvent> =
416                    self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
417                emitted.extend(cancels);
418                emitted.push(WindowEvent::System(SystemEvent::Terminate));
419            }
420            QuickAppLifecycleHook::OnBackPress => {
421                emitted.push(WindowEvent::KeyDown(
422                    wid,
423                    KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
424                ));
425                emitted.push(WindowEvent::System(SystemEvent::BackPressed));
426            }
427            QuickAppLifecycleHook::OnConfigurationChanged { theme, locale } => {
428                self.get_mut_device_metrics().set_theme(theme);
429                emitted.push(WindowEvent::ThemeChanged(wid, theme));
430                emitted.push(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
431                if !locale.trim().is_empty() {
432                    emitted.push(WindowEvent::System(SystemEvent::LocaleChanged(locale)));
433                }
434            }
435            QuickAppLifecycleHook::OnMemoryWarning(level) => {
436                let pressure: MemoryPressure = if level >= 2 {
437                    MemoryPressure::Critical
438                } else if level > 0 {
439                    MemoryPressure::Warning
440                } else {
441                    MemoryPressure::Normal
442                };
443                emitted.push(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
444            }
445            QuickAppLifecycleHook::OnKeyboardChanged { visible, height_px } => {
446                let density: f32 = self.get_device_metrics().get_screen_density().max(0.75);
447                let height_dp: f32 = if visible {
448                    (height_px as f32) / density
449                } else {
450                    0.0
451                };
452                emitted.push(WindowEvent::System(
453                    SystemEvent::KeyboardVisibilityChanged {
454                        visible,
455                        height: height_dp,
456                    },
457                ));
458            }
459            QuickAppLifecycleHook::OnNetworkChanged(status) => {
460                emitted.push(WindowEvent::System(SystemEvent::NetworkStatusChanged(
461                    status,
462                )));
463            }
464        }
465        self.get_mut_pending_events().extend(emitted.clone());
466        emitted
467    }
468}
469
470/// `WindowController` implementation for `QuickAppPlatform`.
471impl WindowController for QuickAppPlatform {
472    /// Applies a `WindowCommand` against the QuickApp `<canvas>` window record.
473    ///
474    /// # Arguments
475    ///
476    /// - `&Self` - Mutable QuickApp platform.
477    /// - `WindowCommand` - Command to apply.
478    ///
479    /// # Returns
480    ///
481    /// - `Result<(), PlatformError>` - Execution status.
482    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
483        match command {
484            WindowCommand::SetTitle(id, title) => {
485                let rec: &mut QuickAppWindowRecord = self
486                    .get_mut_windows()
487                    .get_mut(&id)
488                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
489                rec.get_mut_config().set_title(title.clone());
490                self.get_mut_outbound_commands()
491                    .push(QuickAppHostCommand::SetTitleBar(title));
492                Ok(())
493            }
494            WindowCommand::RequestRedraw(id) => {
495                if !self.get_windows().contains_key(&id) {
496                    return Err(PlatformError::WindowNotFound(id.get_value()));
497                }
498                self.get_mut_pending_events()
499                    .push(WindowEvent::RedrawRequested(id));
500                Ok(())
501            }
502            WindowCommand::Close(id) => {
503                if self.get_mut_windows().remove(&id).is_none() {
504                    return Err(PlatformError::WindowNotFound(id.get_value()));
505                }
506                Ok(())
507            }
508            WindowCommand::SetIme(id, enabled, rect) => {
509                if !self.get_windows().contains_key(&id) {
510                    return Err(PlatformError::WindowNotFound(id.get_value()));
511                }
512                self.get_mut_outbound_commands()
513                    .push(QuickAppHostCommand::ShowKeyboard { enabled, rect });
514                Ok(())
515            }
516            WindowCommand::SetSize(id, _, _)
517            | WindowCommand::SetPosition(id, _, _)
518            | WindowCommand::SetResizable(id, _)
519            | WindowCommand::SetDecorations(id, _)
520            | WindowCommand::SetAlwaysOnTop(id, _)
521            | WindowCommand::SetFullscreen(id, _)
522            | WindowCommand::SetVisible(id, _)
523            | WindowCommand::SetCursor(id, _)
524            | WindowCommand::SetStatusBarStyle(id, _)
525            | WindowCommand::SetRenderMode(id, _) => {
526                if !self.get_windows().contains_key(&id) {
527                    return Err(PlatformError::WindowNotFound(id.get_value()));
528                }
529                Ok(())
530            }
531        }
532    }
533}
534
535/// `PlatformBackend` implementation for `QuickAppPlatform`.
536impl PlatformBackend for QuickAppPlatform {
537    /// Returns `PlatformKind::QuickApp`.
538    ///
539    /// # Arguments
540    ///
541    /// - `&Self` - QuickApp platform reference.
542    ///
543    /// # Returns
544    ///
545    /// - `PlatformKind` - `PlatformKind::QuickApp`.
546    fn kind(&self) -> PlatformKind {
547        PlatformKind::QuickApp
548    }
549
550    /// Returns QuickApp capability flags.
551    ///
552    /// # Arguments
553    ///
554    /// - `&Self` - QuickApp platform reference.
555    ///
556    /// # Returns
557    ///
558    /// - `PlatformCapabilities` - QuickApp capability matrix.
559    fn capabilities(&self) -> PlatformCapabilities {
560        PlatformCapabilities::for_platform(PlatformKind::QuickApp)
561    }
562
563    /// Creates a QuickApp `<canvas>` window sized to the normalized logical screen dimensions.
564    ///
565    /// # Arguments
566    ///
567    /// - `&Self` - Mutable QuickApp platform.
568    /// - `&WindowConfig` - Declarative window config.
569    ///
570    /// # Returns
571    ///
572    /// - `Result<WindowState, PlatformError>` - Created QuickApp window state.
573    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
574        let id: WindowId = WindowId::new(self.get_next_id());
575        self.set_next_id(self.get_next_id().wrapping_add(1));
576        let metrics: QuickAppDeviceMetrics = self.get_device_metrics();
577        let mut qa_cfg: WindowConfig = config.clone();
578        qa_cfg.set_size(metrics.logical_width(), metrics.logical_height());
579        let mut state: WindowState =
580            WindowState::from_config(id, &qa_cfg, metrics.get_screen_density());
581        state.set_safe_area(self.get_safe_area());
582        state.set_system_theme(metrics.get_theme());
583        let record: QuickAppWindowRecord = QuickAppWindowRecord {
584            config: qa_cfg,
585            state,
586            canvas_id: id.get_value() as u32,
587            last_frame: Framebuffer::allocate(
588                state.get_physical_width(),
589                state.get_physical_height(),
590            ),
591            present_count: 0,
592        };
593        self.get_mut_windows().insert(id, record);
594        if self.primary_window_id().is_none() {
595            self.set_primary_window(Some(id));
596        }
597        Ok(state)
598    }
599
600    /// Queries live `WindowState` for `id`.
601    ///
602    /// # Arguments
603    ///
604    /// - `&Self` - QuickApp platform reference.
605    /// - `WindowId` - Window identifier.
606    ///
607    /// # Returns
608    ///
609    /// - `Option<WindowState>` - Window state if alive.
610    fn window_state(&self, id: WindowId) -> Option<WindowState> {
611        self.get_windows()
612            .get(&id)
613            .map(QuickAppWindowRecord::get_state)
614    }
615
616    /// Returns `RawWindowHandle::MiniAppCanvas` tagged with the active `QuickAppVendor`.
617    ///
618    /// # Arguments
619    ///
620    /// - `&Self` - QuickApp platform reference.
621    /// - `WindowId` - Window identifier.
622    ///
623    /// # Returns
624    ///
625    /// - `RawWindowHandle` - QuickApp canvas handle.
626    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
627        match self.get_windows().get(&id) {
628            Some(rec) => RawWindowHandle::MiniAppCanvas {
629                canvas_id: rec.get_canvas_id(),
630                vendor_tag: self.get_device_metrics().get_vendor().tag(),
631            },
632            None => RawWindowHandle::Headless,
633        }
634    }
635
636    /// Drains queued QuickApp touch, IME, back-press, and lifecycle events.
637    ///
638    /// # Arguments
639    ///
640    /// - `&Self` - Mutable QuickApp platform.
641    ///
642    /// # Returns
643    ///
644    /// - `Vec<WindowEvent>` - Pending events.
645    fn poll_events(&mut self) -> Vec<WindowEvent> {
646        take(self.get_mut_pending_events())
647    }
648
649    /// Pauses or resumes the QuickApp canvas frame pump flag.
650    ///
651    /// # Arguments
652    ///
653    /// - `&Self` - Mutable QuickApp platform.
654    /// - `bool` - `true` to pause for background freeze.
655    fn set_frame_pump_paused(&mut self, paused: bool) {
656        self.set_pump_paused(paused);
657    }
658
659    /// Returns whether the QuickApp frame pump is paused.
660    ///
661    /// # Arguments
662    ///
663    /// - `&Self` - QuickApp platform reference.
664    ///
665    /// # Returns
666    ///
667    /// - `bool` - Pause state.
668    fn is_frame_pump_paused(&self) -> bool {
669        self.get_pump_paused()
670    }
671
672    /// Stores `framebuffer` and queues `QuickAppHostCommand::PresentCanvas`.
673    ///
674    /// # Arguments
675    ///
676    /// - `&Self` - Mutable QuickApp platform.
677    /// - `WindowId` - Window identifier.
678    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
679    ///
680    /// # Returns
681    ///
682    /// - `Result<(), PlatformError>` - Presentation status.
683    fn present_framebuffer(
684        &mut self,
685        id: WindowId,
686        framebuffer: &Framebuffer,
687    ) -> Result<(), PlatformError> {
688        let rec: &mut QuickAppWindowRecord = self
689            .get_mut_windows()
690            .get_mut(&id)
691            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
692        rec.set_last_frame(framebuffer.clone());
693        rec.set_present_count(rec.get_present_count().wrapping_add(1));
694        self.get_mut_outbound_commands()
695            .push(QuickAppHostCommand::PresentCanvas {
696                width: framebuffer.get_width(),
697                height: framebuffer.get_height(),
698            });
699        Ok(())
700    }
701
702    /// Reads mirrored `@system.clipboard` text.
703    ///
704    /// # Arguments
705    ///
706    /// - `&Self` - QuickApp platform reference.
707    ///
708    /// # Returns
709    ///
710    /// - `Option<String>` - Cached clipboard string.
711    fn read_clipboard(&self) -> Option<String> {
712        let Self { clipboard, .. } = self;
713        clipboard.clone()
714    }
715
716    /// Writes `text` to clipboard cache and queues `QuickAppHostCommand::ClipboardSet`.
717    ///
718    /// # Arguments
719    ///
720    /// - `&Self` - Mutable QuickApp platform.
721    /// - `&str` - Clipboard text.
722    ///
723    /// # Returns
724    ///
725    /// - `Result<(), PlatformError>` - Write status.
726    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
727        self.set_clipboard(Some(text.to_string()));
728        self.get_mut_outbound_commands()
729            .push(QuickAppHostCommand::ClipboardSet(text.to_string()));
730        Ok(())
731    }
732
733    /// Returns active QuickApp appearance mode.
734    ///
735    /// # Arguments
736    ///
737    /// - `&Self` - QuickApp platform reference.
738    ///
739    /// # Returns
740    ///
741    /// - `ThemeMode` - Active appearance mode.
742    fn system_theme(&self) -> ThemeMode {
743        self.get_device_metrics().get_theme()
744    }
745}
746
747/// `PlatformStorage` implementation backed by `@system.storage` commands.
748impl PlatformStorage for QuickAppPlatform {
749    /// Reads `key` from mirrored `@system.storage`.
750    ///
751    /// # Arguments
752    ///
753    /// - `&Self` - QuickApp platform reference.
754    /// - `&str` - Storage key.
755    ///
756    /// # Returns
757    ///
758    /// - `Option<String>` - Stored value, if present.
759    fn storage_get(&self, key: &str) -> Option<String> {
760        self.get_storage().get(key).cloned()
761    }
762
763    /// Persists `(key, value)` and emits `QuickAppHostCommand::StorageSet`.
764    ///
765    /// # Arguments
766    ///
767    /// - `&Self` - Mutable QuickApp platform.
768    /// - `&str` - Storage key.
769    /// - `&str` - Value to store.
770    ///
771    /// # Returns
772    ///
773    /// - `Result<(), PlatformError>` - Storage status.
774    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
775        let _: Option<String> = self
776            .get_mut_storage()
777            .insert(key.to_string(), value.to_string());
778        self.get_mut_outbound_commands()
779            .push(QuickAppHostCommand::StorageSet {
780                key: key.to_string(),
781                value: value.to_string(),
782            });
783        Ok(())
784    }
785
786    /// Removes `key` and emits `QuickAppHostCommand::StorageDelete`.
787    ///
788    /// # Arguments
789    ///
790    /// - `&Self` - Mutable QuickApp platform.
791    /// - `&str` - Storage key.
792    ///
793    /// # Returns
794    ///
795    /// - `Result<(), PlatformError>` - Removal status.
796    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
797        let _: Option<String> = self.get_mut_storage().remove(key);
798        self.get_mut_outbound_commands()
799            .push(QuickAppHostCommand::StorageDelete(key.to_string()));
800        Ok(())
801    }
802
803    /// Clears storage and emits `QuickAppHostCommand::StorageClear`.
804    ///
805    /// # Arguments
806    ///
807    /// - `&Self` - Mutable QuickApp platform.
808    ///
809    /// # Returns
810    ///
811    /// - `Result<(), PlatformError>` - Clear status.
812    fn storage_clear(&mut self) -> Result<(), PlatformError> {
813        self.get_mut_storage().clear();
814        self.get_mut_outbound_commands()
815            .push(QuickAppHostCommand::StorageClear);
816        Ok(())
817    }
818}
819
820/// `PlatformNavigation` implementation backed by `@system.router` commands.
821impl PlatformNavigation for QuickAppPlatform {
822    /// Pushes `route` and emits `QuickAppHostCommand::RouterPush`.
823    ///
824    /// # Arguments
825    ///
826    /// - `&Self` - Mutable QuickApp platform.
827    /// - `&str` - Target page route URI.
828    ///
829    /// # Returns
830    ///
831    /// - `Result<(), PlatformError>` - Navigation status.
832    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
833        if !route.is_empty() {
834            self.get_mut_route_stack().push(route.to_string());
835            self.get_mut_outbound_commands()
836                .push(QuickAppHostCommand::RouterPush(route.to_string()));
837        }
838        Ok(())
839    }
840
841    /// Pops `delta` entries and emits `QuickAppHostCommand::RouterBack`.
842    ///
843    /// # Arguments
844    ///
845    /// - `&Self` - Mutable QuickApp platform.
846    /// - `u32` - Pages to navigate back.
847    ///
848    /// # Returns
849    ///
850    /// - `Result<(), PlatformError>` - Navigation status.
851    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
852        let steps: u32 = delta.max(1);
853        for _ in 0..steps {
854            if self.get_route_stack().len() > 1 {
855                let _: Option<String> = self.get_mut_route_stack().pop();
856            }
857        }
858        self.get_mut_outbound_commands()
859            .push(QuickAppHostCommand::RouterBack(steps));
860        Ok(())
861    }
862
863    /// Returns the currently active QuickApp page route URI.
864    ///
865    /// # Arguments
866    ///
867    /// - `&Self` - QuickApp platform reference.
868    ///
869    /// # Returns
870    ///
871    /// - `&str` - Active page route.
872    fn current_route(&self) -> &str {
873        self.get_route_stack()
874            .last()
875            .map(String::as_str)
876            .unwrap_or(QUICKAPP_DEFAULT_ROUTE)
877    }
878}
879
880/// `PlatformLifecycleBridge` implementation for `QuickAppPlatform`.
881impl PlatformLifecycleBridge for QuickAppPlatform {
882    /// Maps QuickApp `onHide` into unified freeze semantics.
883    ///
884    /// # Arguments
885    ///
886    /// - `&Self` - Mutable QuickApp platform.
887    ///
888    /// # Returns
889    ///
890    /// - `Vec<WindowEvent>` - Normalized freeze events.
891    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
892        self.handle_lifecycle_hook(QuickAppLifecycleHook::OnHide)
893    }
894
895    /// Maps QuickApp `onShow` into unified resume semantics.
896    ///
897    /// # Arguments
898    ///
899    /// - `&Self` - Mutable QuickApp platform.
900    ///
901    /// # Returns
902    ///
903    /// - `Vec<WindowEvent>` - Normalized resume events.
904    fn resume_surface(&mut self) -> Vec<WindowEvent> {
905        self.handle_lifecycle_hook(QuickAppLifecycleHook::OnShow)
906    }
907
908    /// Maps QuickApp `onDestroy` into unified destroy semantics.
909    ///
910    /// # Arguments
911    ///
912    /// - `&Self` - Mutable QuickApp platform.
913    ///
914    /// # Returns
915    ///
916    /// - `Vec<WindowEvent>` - Normalized destroy events.
917    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
918        self.handle_lifecycle_hook(QuickAppLifecycleHook::OnDestroy)
919    }
920}
921
922/// `PlatformHostAdapter` implementation for `QuickAppPlatform`.
923impl PlatformHostAdapter for QuickAppPlatform {
924    /// Returns `DeviceFormFactor::MiniProgram`.
925    ///
926    /// # Arguments
927    ///
928    /// - `&Self` - QuickApp platform reference.
929    ///
930    /// # Returns
931    ///
932    /// - `DeviceFormFactor` - `DeviceFormFactor::MiniProgram`.
933    fn device_form_factor(&self) -> DeviceFormFactor {
934        DeviceFormFactor::MiniProgram
935    }
936
937    /// Returns `"quickapp-alliance"` or `"quickapp-huawei"`.
938    ///
939    /// # Arguments
940    ///
941    /// - `&Self` - QuickApp platform reference.
942    ///
943    /// # Returns
944    ///
945    /// - `&'static str` - Canonical QuickApp vendor identifier.
946    fn host_vendor_name(&self) -> &'static str {
947        self.get_device_metrics().get_vendor().as_str()
948    }
949}
950
951/// Unified host-channel capability and visual-equivalence queries for `QuickAppPlatform`.
952impl QuickAppPlatform {
953    /// Returns the truthful `HostChannelCapabilities` declared by this QuickApp runtime.
954    ///
955    /// QuickApp hosts expose a single `<canvas>` 2D channel by default (`supported_channels.len() == 1`, zero probing),
956    /// and simulated/off-device profiles ALWAYS set `simulated_profile = true` and `direct_gpu_verified_on_device = false`.
957    ///
958    /// # Returns
959    ///
960    /// - `HostChannelCapabilities` - Declared QuickApp channels, visual gate, and honesty flags.
961    #[must_use]
962    pub fn host_channel_capabilities(&self) -> HostChannelCapabilities {
963        let simulated: bool = !cfg!(target_arch = "wasm32");
964        HostChannelCapabilities::from_host_declaration(
965            self.host_vendor_name(),
966            vec![HostRenderChannel::Canvas2d],
967            HostRenderChannel::Canvas2d,
968            HostVisualEquivalenceGate::default(),
969            simulated,
970            false,
971        )
972    }
973
974    /// Resolves the QuickApp rendering channel under unified visual-equivalence and single-channel non-probing rules.
975    ///
976    /// # Arguments
977    ///
978    /// - `Option<HostRenderChannel>` - Optional requested channel.
979    ///
980    /// # Returns
981    ///
982    /// - `HostChannelSelection` - Resolved channel decision.
983    #[must_use]
984    pub fn select_render_channel(
985        &self,
986        requested: Option<HostRenderChannel>,
987    ) -> HostChannelSelection {
988        self.host_channel_capabilities().select_channel(requested)
989    }
990}