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