Skip to main content

nsh_core/element/
ambient.rs

1//! What components that run once read of the surface and ask of the
2//! platform, as free functions (TS: `nsh`'s accessors and modules).
3//!
4//! The environment, the design tokens, globals and screens' insets are signals the
5//! core writes: reading one in a binding subscribes it, so a change reaches
6//! only what read it. Services (dialogs, the clipboard) are actions
7//! for the core; tasks and timers belong to the current owner and end with
8//! it.
9
10use std::{
11    any::{Any, TypeId},
12    cell::Cell,
13    future::Future,
14    path::PathBuf,
15    rc::Rc,
16    sync::Arc,
17    time::Duration,
18};
19
20use rustc_hash::FxHashMap;
21
22use super::{
23    AdaptiveColor, Environment, Memo, Owner, Signal, SignalEquals, Tokens, cleanup, computed,
24    reactive::with_data,
25    signal_with,
26    task::{
27        self, Action, Answer, ClipboardImage, ClipboardItem, ClipboardWrite, DialogAnswer,
28        Executor, FileAnswer, ImageSize,
29    },
30};
31use crate::{
32    AlertDialogRequest, Command, EdgeInsets, LayoutAnimation, NodeId, Points, Size,
33    canvas::CanvasFont,
34    color::Hsla,
35    platform::{Appearance, Idiom, Lifecycle, Locale, LocaleSettings, Network, Os},
36    time::Instant,
37};
38
39/// How text is measured on one line, in a canvas font.
40pub(crate) type MeasureFn = Rc<dyn Fn(&CanvasFont, &str) -> crate::canvas::TextMetrics>;
41
42/// What the core gives components that run once.
43#[derive(Default)]
44pub(crate) struct Ambient {
45    executor: Option<Rc<Executor>>,
46    env: Option<EnvSignals>,
47    tokens: Option<Signal<Arc<Tokens>>>,
48    globals: FxHashMap<TypeId, Box<dyn Any>>,
49    /// The insets of the screens or modals components are on, by host.
50    insets: FxHashMap<NodeId, Signal<EdgeInsets>>,
51    measure: Option<MeasureFn>,
52    /// The app's key-value storage (`nsh/storage`).
53    storage: Option<crate::storage::Store>,
54    /// The app's own data directory ([`data_dir`]).
55    data_dir: Option<std::path::PathBuf>,
56    /// The app as it was built ([`app_info`]).
57    app_info: Option<crate::platform::AppInfo>,
58    /// What the app may do ([`access`]).
59    access: Option<Arc<crate::access::Access>>,
60    /// Which engine this is ([`engine_id`]).
61    pub(super) engine_id: Option<EngineId>,
62    /// What `nsh/updater` checks with for Rust code
63    /// ([`crate::runtime::prompt_for_update`]).
64    updater: Option<std::sync::Arc<dyn crate::runtime::UpdaterHost>>,
65    /// The displays (desktops), as the platform reports them.
66    displays: Option<Signal<Arc<[crate::desktop::Display]>>>,
67    /// Whether the performance monitor measures, as the platform reports
68    /// it.
69    perf_monitor: Option<Signal<bool>>,
70    /// What the performance monitor measured last, as the engine reports
71    /// it ([`perf_stats`]).
72    perf_stats: Option<Signal<Option<crate::platform::PerfStats>>>,
73    /// The main window's close presses: how many, and the last one's
74    /// reason ([`crate::element::desktop::WindowRef::on_close_press`]).
75    main_close_press: Option<Signal<(u64, crate::desktop::CloseReason)>>,
76    /// The app's address (`set_app_url` resolves against its page base).
77    app_url: Option<crate::url_scheme::AppUrlCell>,
78}
79
80impl Ambient {
81    /// The hosts whose insets components read.
82    pub(crate) fn inset_hosts(&self) -> Vec<NodeId> {
83        self.insets.keys().copied().collect()
84    }
85}
86
87/// The environment as a signal, and a memo per part (a change notifies only
88/// the readers of the parts that changed).
89struct EnvSignals {
90    env: Signal<Environment>,
91    window: Memo<Size<Points>>,
92    horizontal_size_class: Memo<crate::platform::SizeClass>,
93    vertical_size_class: Memo<crate::platform::SizeClass>,
94    safe_area: Memo<EdgeInsets>,
95    reserved_regions: Memo<crate::platform::ReservedRegions>,
96    title_bar: Memo<crate::geometry::Edges<crate::geometry::Points>>,
97    window_state: Memo<Option<crate::desktop::WindowState>>,
98    keyboard_height: Memo<Points>,
99    keyboard_duration: Memo<f32>,
100    dark: Memo<bool>,
101    font_scale: Memo<f32>,
102    reduce_motion: Memo<bool>,
103    screen_reader: Memo<bool>,
104    rtl: Memo<bool>,
105    pixel_ratio: Memo<f32>,
106    locale: Memo<Locale>,
107    locale_settings: Memo<LocaleSettings>,
108    lifecycle: Memo<Lifecycle>,
109    wake_count: Memo<u32>,
110    network: Memo<Network>,
111    screen_color: Memo<bool>,
112    shaders: Memo<bool>,
113}
114
115impl EnvSignals {
116    fn new(env: Environment) -> Self {
117        Owner::detached().run(|| {
118            let signal = super::signal(env);
119            macro_rules! part {
120                ($field:ident) => {
121                    computed(move || signal.with(|e| e.$field))
122                };
123            }
124            Self {
125                env: signal,
126                window: part!(window),
127                horizontal_size_class: computed(move || {
128                    signal.with(|e| {
129                        e.horizontal_size_class.unwrap_or_else(|| {
130                            crate::platform::SizeClass::from_length(e.window.width)
131                        })
132                    })
133                }),
134                vertical_size_class: computed(move || {
135                    signal.with(|e| {
136                        e.vertical_size_class.unwrap_or_else(|| {
137                            crate::platform::SizeClass::from_length(e.window.height)
138                        })
139                    })
140                }),
141                safe_area: part!(safe_area),
142                reserved_regions: part!(reserved_regions),
143                title_bar: part!(title_bar),
144                window_state: part!(window_state),
145                keyboard_height: part!(keyboard_height),
146                keyboard_duration: part!(keyboard_duration),
147                dark: part!(dark),
148                font_scale: part!(font_scale),
149                reduce_motion: part!(reduce_motion),
150                screen_reader: part!(screen_reader),
151                rtl: part!(rtl),
152                pixel_ratio: part!(pixel_ratio),
153                locale: part!(locale),
154                locale_settings: part!(locale_settings),
155                lifecycle: part!(lifecycle),
156                wake_count: part!(wake_count),
157                network: part!(network),
158                screen_color: part!(screen_color),
159                shaders: part!(shaders),
160            }
161        })
162    }
163}
164
165// --- What the core sets ------------------------------------------------------
166
167impl super::Runtime {
168    /// The executor of tasks and actions.
169    pub(crate) fn set_services(&self, executor: Rc<Executor>) {
170        let _entered = self.enter();
171        with_data(|d| d.ambient.executor = Some(executor));
172    }
173
174    /// The app's address, the core's (`set_app_url`).
175    pub(crate) fn set_app_url(&self, app_url: crate::url_scheme::AppUrlCell) {
176        let _entered = self.enter();
177        with_data(|d| d.ambient.app_url = Some(app_url));
178    }
179
180    /// Where the app's storage is kept.
181    pub(crate) fn set_storage(&self, storage: crate::storage::Store) {
182        let _entered = self.enter();
183        with_data(|d| d.ambient.storage = Some(storage));
184    }
185
186    /// The app's own data directory ([`data_dir`]).
187    pub(crate) fn set_data_dir(&self, dir: Option<std::path::PathBuf>) {
188        let _entered = self.enter();
189        with_data(|d| d.ambient.data_dir = dir);
190    }
191
192    /// The app as it was built ([`app_info`]).
193    pub(crate) fn set_app_info(&self, info: Option<crate::platform::AppInfo>) {
194        let _entered = self.enter();
195        with_data(|d| d.ambient.app_info = info);
196    }
197
198    /// What the app may do ([`access`]).
199    pub(crate) fn set_access(&self, access: Arc<crate::access::Access>) {
200        let _entered = self.enter();
201        with_data(|d| d.ambient.access = Some(access));
202    }
203
204    /// What Rust code checks for updates with ([`updater_host`]).
205    pub(crate) fn set_updater(
206        &self,
207        updater: Option<std::sync::Arc<dyn crate::runtime::UpdaterHost>>,
208    ) {
209        let _entered = self.enter();
210        with_data(|d| d.ambient.updater = updater);
211    }
212
213    /// How text is measured (the core's text engine).
214    pub(crate) fn set_measure(&self, measure: MeasureFn) {
215        let _entered = self.enter();
216        with_data(|d| d.ambient.measure = Some(measure));
217    }
218
219    /// The environment now: what read a part that changed runs again.
220    pub(crate) fn set_environment(&self, env: Environment) {
221        let _entered = self.enter();
222        let signal = with_data(|d| d.ambient.env.as_ref().map(|e| e.env));
223        match signal {
224            Some(signal) => signal.set(env),
225            None => {
226                let signals = EnvSignals::new(env);
227                with_data(|d| d.ambient.env = Some(signals));
228            }
229        }
230    }
231
232    /// The displays now: what read them runs again.
233    pub(crate) fn set_displays(&self, displays: Arc<[crate::desktop::Display]>) {
234        let _entered = self.enter();
235        let signal = displays_signal();
236        if signal.with_untracked(|d| **d != *displays) {
237            signal.set(displays);
238        }
239    }
240
241    /// Whether the performance monitor measures now: what read it runs
242    /// again.
243    pub(crate) fn set_perf_monitor(&self, enabled: bool) {
244        let _entered = self.enter();
245        let signal = perf_monitor_signal();
246        if signal.get_untracked() != enabled {
247            signal.set(enabled);
248        }
249    }
250
251    /// What the performance monitor measured last (`None`: it does not
252    /// measure): what read it runs again.
253    pub(crate) fn set_perf_stats(&self, stats: Option<crate::platform::PerfStats>) {
254        let _entered = self.enter();
255        let signal = perf_stats_signal();
256        if signal.get_untracked() != stats {
257            signal.set(stats);
258        }
259    }
260
261    /// The user asked to close the main window: what listens hears it.
262    pub(crate) fn main_close_pressed(&self, reason: crate::desktop::CloseReason) {
263        let _entered = self.enter();
264        main_close_press_signal().update(|(count, last)| {
265            *count += 1;
266            *last = reason;
267        });
268    }
269
270    /// `placement` fitted on the displays now (`setPlacement`, a restored
271    /// window's), without subscribing to them.
272    pub(crate) fn fit_window_placement(
273        &self,
274        placement: crate::desktop::WindowPlacement,
275    ) -> crate::desktop::WindowPlacement {
276        let _entered = self.enter();
277        displays_signal().with_untracked(|d| placement.fit_on_displays(d))
278    }
279
280    /// The design tokens now: what read them runs again.
281    pub(crate) fn set_tokens(&self, tokens: Arc<Tokens>) {
282        let _entered = self.enter();
283        let signal = with_data(|d| d.ambient.tokens);
284        match signal {
285            Some(signal) => signal.set(tokens),
286            None => {
287                let signal = Owner::detached().run(|| signal_with(tokens, SignalEquals::Never));
288                with_data(|d| d.ambient.tokens = Some(signal));
289            }
290        }
291    }
292
293    /// The hosts whose insets components read.
294    pub(crate) fn inset_hosts(&self) -> Vec<NodeId> {
295        let _entered = self.enter();
296        with_data(|d| d.ambient.inset_hosts())
297    }
298
299    /// The insets of the screen or modal `host` is on.
300    pub(crate) fn set_insets(&self, host: NodeId, insets: EdgeInsets) {
301        let _entered = self.enter();
302        if let Some(signal) = with_data(|d| d.ambient.insets.get(&host).copied()) {
303            signal.set(insets);
304        }
305    }
306
307    /// `host` goes: its insets are no longer read.
308    pub(crate) fn forget_host(&self, host: NodeId) {
309        let _entered = self.enter();
310        with_data(|d| d.ambient.insets.remove(&host));
311    }
312}
313
314fn env<T: Clone + 'static>(part: impl FnOnce(&EnvSignals) -> Memo<T>) -> T {
315    let memo = with_data(|d| d.ambient.env.as_ref().map(part));
316    memo.expect("the core sets the environment before components run")
317        .get()
318}
319
320pub(super) fn executor() -> Rc<Executor> {
321    with_data(|d| d.ambient.executor.clone()).expect("the core sets the executor")
322}
323
324pub(crate) fn act(action: Action) {
325    executor().act(action);
326}
327
328/// [`act`] while the engine runs Rust code, else nothing: for cleanups and
329/// handles that may outlive it.
330pub(super) fn act_if_running(action: Action) {
331    if let Some(executor) = super::reactive::try_with_data(|d| d.ambient.executor.clone()).flatten()
332    {
333        executor.act(action);
334    }
335}
336
337// --- The environment ---------------------------------------------------------
338
339/// The surface's size in points (TS: `windowSize()`).
340pub fn window() -> Size<Points> {
341    env(|e| e.window)
342}
343
344/// The horizontal size class (reactive; TS: `horizontalSizeClass()`).
345/// iOS uses UIKit traits; elsewhere widths below 600pt are compact.
346pub fn horizontal_size_class() -> crate::platform::SizeClass {
347    env(|e| e.horizontal_size_class)
348}
349
350/// The vertical size class (reactive; TS: `verticalSizeClass()`).
351/// iOS uses UIKit traits; elsewhere heights below 600pt are compact.
352pub fn vertical_size_class() -> crate::platform::SizeClass {
353    env(|e| e.vertical_size_class)
354}
355
356/// The edges system UI covers: notch, home indicator (TS: `safeArea()`).
357pub fn safe_area() -> EdgeInsets {
358    env(|e| e.safe_area)
359}
360
361/// The parts of the surface the device reserves inside the safe area, in
362/// the surface's points (reactive; TS: `reservedRegions()`): the fold of a
363/// partly folded display ([`crate::platform::ReservedRegionKind::Division`]),
364/// a camera that shows through it. Keep what matters clear of them, with
365/// small adjustments rather than a new layout. Empty where the platform
366/// reports none.
367pub fn reserved_regions() -> crate::platform::ReservedRegions {
368    env(|e| e.reserved_regions)
369}
370
371/// The software keyboard's height over the surface, 0 when hidden (TS:
372/// `keyboardFrame().height`).
373pub fn keyboard_height() -> Points {
374    env(|e| e.keyboard_height)
375}
376
377/// How long the keyboard's show / hide animation takes, in milliseconds.
378pub fn keyboard_duration() -> f32 {
379    env(|e| e.keyboard_duration)
380}
381
382/// Dark appearance (TS: `colorScheme() === "dark"`). Theme colors follow
383/// it without this; read it for anything else.
384pub fn dark() -> bool {
385    env(|e| e.dark)
386}
387
388/// `color` for the appearance now (props that take one color, such as an
389/// input's placeholder color; styles take theme colors as they are).
390pub fn color(color: impl Into<AdaptiveColor>) -> Hsla {
391    let color = color.into();
392    if dark() { color.dark } else { color.light }
393}
394
395/// The user's text size relative to the default (TS: `fontScale()`).
396pub fn font_scale() -> f32 {
397    env(|e| e.font_scale)
398}
399
400/// The user asked for less motion (TS: `reduceMotion()`).
401pub fn reduce_motion() -> bool {
402    env(|e| e.reduce_motion)
403}
404
405/// A screen reader runs (TS: `screenReaderEnabled()`).
406pub fn screen_reader() -> bool {
407    env(|e| e.screen_reader)
408}
409
410/// The platform's screen readers follow the active descendant a focused
411/// element names ([`super::Interactive::accessibility_active_descendant`],
412/// [`crate::platform::Environment::reads_active_descendants`]); it does
413/// not change.
414pub fn reads_active_descendants() -> bool {
415    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
416        .expect("the core sets the environment")
417        .with_untracked(|e| e.reads_active_descendants)
418}
419
420/// Whether the platform draws shader views ([`super::shader`] and the
421/// other shader elements; TS: `shadersAvailable()`), reading subscribes.
422/// `false` where the platform was built without a renderer, on a grid
423/// surface, or once the platform found no GPU; it starts `true` elsewhere
424/// and turns `false` (never back) when the first shader mounts on a
425/// machine without one, so an app shows a shader while this holds and
426/// its own drawing (a canvas, an image) otherwise. Whether a source
427/// compiles is [`crate::shader::Shader::compile`]'s answer.
428pub fn shaders_available() -> bool {
429    env(|e| e.shaders)
430}
431
432/// Whether the surface lays out right to left: the root's direction,
433/// which follows the user's language unless the app sets the root's
434/// `direction` (reading subscribes).
435///
436/// The core's part of `nsh-base`'s controls, which swap Left and Right by
437/// it (WAI-ARIA's arrow keys in a right-to-left layout). Apps set a view's
438/// `direction` and style with logical properties or `rtl:` classes
439/// instead: Rust's `rtl()` is dropped (`docs/dev/api-naming.md`).
440#[doc(hidden)]
441pub fn layout_rtl() -> bool {
442    env(|e| e.rtl)
443}
444
445/// Device pixels per point (TS: `pixelRatio()`).
446pub fn pixel_ratio() -> f32 {
447    env(|e| e.pixel_ratio)
448}
449
450/// `points` rounded to whole device pixels (TS:
451/// `Math.round(x * pixelRatio()) / pixelRatio()`).
452pub fn round_to_nearest_pixel(points: Points) -> Points {
453    let ratio = pixel_ratio().max(f32::MIN_POSITIVE);
454    Points((points.0 * ratio).round() / ratio)
455}
456
457/// The user's locale (TS: what `Intl` formats for by default).
458pub fn locale() -> Locale {
459    env(|e| e.locale)
460}
461
462/// The user's locale settings (TS: `localeSettings()`): the preferred
463/// languages, most preferred first (the app shows its text in the first it
464/// has, the others are its fallbacks; an embedding app's own language comes
465/// first), the device's time zone as the system names it
466/// (`Europe/Berlin`), and the regional preferences: 12- or 24-hour time,
467/// the first day of the week, the measurement system and the temperature
468/// unit, each the system's setting, else the region's. Reading it
469/// subscribes, so what shows them follows the user's settings and travels;
470/// a `computed` of one of them changes only with it. `nsh_base`'s
471/// `TimeField` and `DatePicker` take their `HourCycle::H12` where
472/// [`HourCycle::twelve_hour`](crate::platform::HourCycle::twelve_hour),
473/// else `H23`; its `Calendar` and `DatePicker` count their
474/// `first_day_of_week` from 0 for Sunday: pass `number() % 7`.
475pub fn locale_settings() -> LocaleSettings {
476    env(|e| e.locale_settings)
477}
478
479/// Whether the app is in use: in the foreground, visible without the
480/// focus, or in the background (TS: `lifecycle()`). Reading it subscribes,
481/// so an effect pauses work in the background and resumes it after.
482pub fn lifecycle() -> Lifecycle {
483    env(|e| e.lifecycle)
484}
485
486/// How many times the system woke from sleep while the app ran (TS:
487/// `wakeCount()`), 0 until the first wake. Reading it subscribes, so an
488/// effect that reads it runs again after each wake: a sleep may leave
489/// [`lifecycle`] as it was (a laptop's lid closed and opened with the app
490/// in front), while network connections and timers did not live through
491/// it, so the app checks or opens them again there. macOS, Windows and
492/// Linux count wakes; on iOS and Android a sleeping device takes the app
493/// to the background, which [`lifecycle`] reports.
494pub fn wake_count() -> u32 {
495    env(|e| e.wake_count)
496}
497
498/// How the device reaches the network now (TS: `network()`): the kind of
499/// link its default route takes
500/// ([`NetworkKind::None`](crate::platform::NetworkKind::None) offline),
501/// whether that link costs the user or the user asked to save data on it,
502/// and on iOS whether the user lets the app use cellular data. Reading it
503/// subscribes, so an effect that reads it runs again when the route
504/// changes: a request that failed offline can wait for
505/// [`Network::online`] and try again at once, and one refused while
506/// [`CellularData::Restricted`](crate::platform::CellularData::Restricted)
507/// points the user to the system's settings instead of retrying. iOS and
508/// macOS follow the system's path monitor, Android its default network,
509/// the web `navigator.onLine` and `navigator.connection`; elsewhere it
510/// stays [`NetworkKind::Unknown`](crate::platform::NetworkKind::Unknown),
511/// which counts as online.
512pub fn network() -> Network {
513    env(|e| e.network)
514}
515
516/// The operating system (TS: `platform.os`); it does not change.
517pub fn os() -> Os {
518    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
519        .expect("the core sets the environment")
520        .with_untracked(|e| e.os)
521}
522
523/// The platform's name (TS: `platform.name`): the OS's on NSH's own
524/// platforms (`"ios"`, `"web"`, ...), a platform built outside NSH's own
525/// (`"miniprogram"`), whose OS is [`os`]; it does not change.
526pub fn platform_name() -> &'static str {
527    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
528        .expect("the core sets the environment")
529        .with_untracked(|e| e.platform_name())
530}
531
532/// The platform shows the system's tab bar: iOS and Android, unless a
533/// platform built outside NSH has none
534/// ([`crate::platform::Environment::tab_bar`]); it does not change.
535pub(crate) fn has_tab_bar() -> bool {
536    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
537        .expect("the core sets the environment")
538        .with_untracked(|e| matches!(e.os, Os::Ios | Os::Android) && e.tab_bar)
539}
540
541/// [`os`] where an engine runs (its thread, while it runs Rust code),
542/// else `None`: for code that also runs outside an engine (a unit test of
543/// a component's model).
544pub fn try_os() -> Option<Os> {
545    super::reactive::try_with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
546        .flatten()
547        .map(|env| env.with_untracked(|e| e.os))
548}
549
550/// The OS version: major and minor on iOS, the API level and 0 on Android
551/// (TS: `platform.version`).
552pub fn os_version() -> (u16, u16) {
553    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
554        .expect("the core sets the environment")
555        .with_untracked(|e| e.os_version)
556}
557
558/// The kind of device (TS: `platform.idiom`): [`Idiom::Terminal`] in a
559/// terminal, else [`Idiom::Desktop`] exactly where [`is_desktop`] holds
560/// ([`Idiom::reported_on`]).
561pub fn idiom() -> Idiom {
562    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
563        .expect("the core sets the environment")
564        .with_untracked(|e| e.idiom.reported_on(e.os))
565}
566
567/// The size of one Cell of a grid surface (a terminal), in points, as
568/// the core lays out on it ([`Environment::cell`]); `None` on every other
569/// surface. Components that size themselves in whole Cells read it.
570pub fn cell_size() -> Option<Size<Points>> {
571    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
572        .expect("the core sets the environment")
573        .with_untracked(|e| e.cell)
574}
575
576/// Whether the app runs under Mac Catalyst, in every idiom (TS:
577/// `platform.catalyst`, [`Os::is_catalyst`]); Catalyst is mobile, not
578/// desktop.
579pub fn is_catalyst() -> bool {
580    os().is_catalyst()
581}
582
583/// Whether desktop behavior applies, NSH's one definition of desktop: a
584/// desktop OS (macOS, Windows, Linux), a browser in the desktop idiom or
585/// a terminal (TS: `platform.desktop`, [`Idiom::desktop_on`]); it does not
586/// change.
587pub fn is_desktop() -> bool {
588    with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
589        .expect("the core sets the environment")
590        .with_untracked(|e| e.idiom.desktop_on(e.os))
591}
592
593/// The design tokens the app is drawn with (reading them subscribes: new
594/// tokens reach what read them).
595pub fn tokens() -> Arc<Tokens> {
596    with_data(|d| d.ambient.tokens)
597        .expect("the core sets the tokens")
598        .get()
599}
600
601/// Draws the app with the design tokens `tokens` (the app's own, which an
602/// embedding app's still win over), in place of the UI set's defaults or
603/// the theme file's: Tailwind's token classes, [`tokens`] and the
604/// platform's own controls (Linux's menus, Android's alerts) follow. An app that picks its
605/// theme while it runs sets it here (`set_tokens(theme.into())` of an
606/// `nsh_base::Theme`).
607pub fn set_tokens(tokens: impl Into<Tokens>) {
608    act(Action::Tokens(tokens.into()));
609}
610
611/// The width of `text` on one line in `font` (the CSS `font` shorthand; an
612/// invalid one measures in `10px sans-serif`), by the platform's text engine
613/// (TS: a canvas's `measureText(text).width`).
614pub fn measure_text(font: &str, text: &str) -> Points {
615    text_metrics(font, text).width
616}
617
618/// Captures the platform text measurer while a component's runtime is entered.
619/// The returned function can also be called by synchronous JS session queries,
620/// where the Rust reactive runtime is not entered.
621pub fn text_measurer() -> impl Fn(&str, &str) -> Points + Clone {
622    let measure = with_data(|d| d.ambient.measure.clone()).expect("the core sets the text engine");
623    move |font, text| {
624        let font = CanvasFont::parse(font).unwrap_or_default();
625        measure(&font, text).width
626    }
627}
628
629/// How `text` sits on one line in `font` (the CSS `font` shorthand; an
630/// invalid one measures in `10px sans-serif`), by the platform's text
631/// engine: its width and the font's ascent, descent and line height, to
632/// place text a canvas draws (a cell's baseline, a caret over it).
633pub fn text_metrics(font: &str, text: &str) -> crate::canvas::TextMetrics {
634    let font = CanvasFont::parse(font).unwrap_or_default();
635    let measure = with_data(|d| d.ambient.measure.clone()).expect("the core sets the text engine");
636    measure(&font, text)
637}
638
639/// The surface's `G`: one signal per type, made with `Default` the first
640/// time (TS: a signal at module level). Every write notifies.
641pub fn global<G: Default + 'static>() -> Signal<G> {
642    let id = TypeId::of::<G>();
643    if let Some(signal) = with_data(|d| {
644        d.ambient
645            .globals
646            .get(&id)
647            .and_then(|g| g.downcast_ref::<Signal<G>>().copied())
648    }) {
649        return signal;
650    }
651    let signal = Owner::detached().run(|| signal_with(G::default(), SignalEquals::Never));
652    with_data(|d| d.ambient.globals.insert(id, Box::new(signal)));
653    signal
654}
655
656/// [`global`] where a reactive runtime is entered (the engine's thread,
657/// while it runs Rust code), else `None`: for code that also runs outside
658/// an engine (a unit test of a component's model).
659pub fn try_global<G: Default + 'static>() -> Option<Signal<G>> {
660    super::reactive::try_with_data(|_| ())?;
661    Some(global::<G>())
662}
663
664/// The insets of the screen or modal the component on `host` is on, below
665/// its header, else the safe area (TS: `safeAreaInsets()`).
666pub(crate) fn insets_of(host: NodeId) -> EdgeInsets {
667    let existing = with_data(|d| d.ambient.insets.get(&host).copied());
668    let signal = existing.unwrap_or_else(|| {
669        // The core fills it in before the commit ends.
670        let signal = Owner::detached().run(|| super::signal(safe_area()));
671        with_data(|d| d.ambient.insets.insert(host, signal));
672        signal
673    });
674    signal.get()
675}
676
677// --- Services ----------------------------------------------------------------
678
679/// Shows `dialog` (an alert, or with `sheet` an action sheet); await the
680/// answer in a task.
681///
682/// The core's part of `nsh_base::alert_dialog`, which apps use.
683#[doc(hidden)]
684pub fn dialog(dialog: AlertDialogRequest) -> DialogAnswer {
685    let (answer, slot) = DialogAnswer::new();
686    act(Action::Dialog(dialog, slot));
687    answer
688}
689
690/// Unfocuses the focused input, hiding the software keyboard.
691pub fn dismiss_keyboard() {
692    act(Action::Command(crate::ROOT_ID, Command::Blur));
693}
694
695/// Animates the layout changes of the next commit (React Native's
696/// `LayoutAnimation.configureNext`).
697pub fn animate_layout(animation: LayoutAnimation) {
698    act(Action::Command(
699        crate::ROOT_ID,
700        Command::LayoutAnimation(animation),
701    ));
702}
703
704/// The screen reader reads `message` (TS:
705/// `announce`).
706pub fn announce_for_accessibility(message: impl Into<String>) {
707    act(super::services::announce(message.into()));
708}
709
710/// The device plays `haptic` (TS: `Haptics` of `nsh/mobile`): iOS and
711/// Android; elsewhere nothing happens.
712pub fn haptic(haptic: crate::Haptic) {
713    act(super::services::haptic(haptic));
714}
715
716/// Runs `f` with the app's storage (`nsh/storage`, [`crate::storage::Storage`]):
717/// the one the engine was given, or one in memory when it was given none.
718pub(crate) fn with_storage<R>(f: impl FnOnce(&crate::storage::Store) -> R) -> R {
719    let storage = with_data(|d| {
720        d.ambient
721            .storage
722            .get_or_insert_with(|| crate::storage::Store::new(None))
723            .clone()
724    });
725    f(&storage)
726}
727
728/// The app's own data directory (TS: `process.dataDir`): where its files
729/// are kept, `<data_dir>/<app id>` of the engine, beside its
730/// `storage.json`, on every platform. `None` when the host keeps no files
731/// for the app (the web). The directory may not exist yet: create it
732/// before writing.
733///
734/// ```ignore
735/// let db = data_dir().map(|dir| dir.join("app.sqlite"));
736/// ```
737pub fn data_dir() -> Option<std::path::PathBuf> {
738    with_data(|d| d.ambient.data_dir.clone())
739}
740
741/// The app as it was built (TS: `appInfo()`): its id, name, version and
742/// build number, and whether it is a development build
743/// ([`crate::platform::AppInfo`]). `None` in a TSX app, whose JS
744/// `appInfo()` reports it, and where the runner gave none.
745///
746/// ```ignore
747/// if let Some(version) = app_info().and_then(|info| info.version) {
748///     log::info!("version {version}");
749/// }
750/// ```
751pub fn app_info() -> Option<crate::platform::AppInfo> {
752    with_data(|d| d.ambient.app_info.clone())
753}
754
755/// What the app the calling code runs in may do: its capabilities (its
756/// `nsh.json` declaration and what the embedding app grants), as the
757/// engine checks them. A native module that guards a capability of its own
758/// checks it here for Rust callers, as its JS face does with the calling
759/// VM's [`System::access`](super::System) (`nsh-extra`'s `Speech` checks
760/// `speech`). `None` when the calling code does not run on an engine's
761/// thread (a thread of the module's own or of a library, a platform
762/// callback, a test without an engine): no app's grant applies there,
763/// though the code may well act for one. Rust code is trusted, so such a
764/// caller is not limited here; a module that must tie it to an app reads
765/// the access on the engine's thread first and carries it along.
766///
767/// ```ignore
768/// if access().is_some_and(|access| !access.allows_speech()) {
769///     return Err(not_allowed());
770/// }
771/// ```
772pub fn access() -> Option<Arc<crate::access::Access>> {
773    super::reactive::try_with_data(|d| d.ambient.access.clone()).flatten()
774}
775
776/// An engine of the process ([`engine_id`]): opaque, and never the same
777/// for two engines of one process, even after one goes.
778#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
779pub struct EngineId(std::num::NonZeroU64);
780
781impl EngineId {
782    /// One no engine had before.
783    pub(crate) fn next() -> Self {
784        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
785        let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
786        Self(std::num::NonZeroU64::new(id).expect("engine ids do not run out"))
787    }
788}
789
790/// The engine the calling code runs in: what a native module whose state
791/// is the process's (one microphone, one device) tells its engines'
792/// requests apart with. `None` outside an engine's Rust code (a thread of
793/// the module's own, a test without an engine).
794///
795/// ```ignore
796/// let displaced_by_another_app = running.owner != engine_id();
797/// ```
798pub fn engine_id() -> Option<EngineId> {
799    super::reactive::try_with_data(|d| d.ambient.engine_id).flatten()
800}
801
802/// What Rust code checks for updates with: the engine's, `None` where the
803/// app does not update.
804pub(crate) fn updater_host() -> Option<std::sync::Arc<dyn crate::runtime::UpdaterHost>> {
805    with_data(|d| d.ambient.updater.clone())
806}
807
808/// The file the app's log lines are written to (TS: `process.logFile`): a
809/// packaged desktop app's rolling log, `logs/app.log` in the app's data
810/// directory, for a diagnostics report or an "Open logs folder" command
811/// (older files beside it are `app.1.log`, `app.2.log`, ...). `None` where
812/// the lines go to the platform's log only: development hosts, embedding
813/// apps, mobile, the web.
814///
815/// ```ignore
816/// let folder = log_file().and_then(|file| file.parent().map(Path::to_path_buf));
817/// ```
818pub fn log_file() -> Option<std::path::PathBuf> {
819    crate::log_file::path().map(std::path::Path::to_path_buf)
820}
821
822/// Opens `url` outside the app (TS: `openUrl` of `nsh/device`): a web page
823/// in the browser, a `mailto:` or `tel:` link in its app, any scheme
824/// another app registered. The embedding app may take it first (its host
825/// channel's URL handler, which routes it through the host's router).
826/// Resolves to whether it opened: `false` for a URL
827/// [`crate::open_url::check_url`] refuses, when the app's `openUrl`
828/// capability is not granted, or when no app handles it. Await it in a
829/// task, or drop it when the answer does not matter.
830pub fn open_url(url: impl Into<String>) -> Answer<bool> {
831    let (answer, action) = super::services::open_url(url.into());
832    act(action);
833    answer
834}
835
836/// Puts `text` on the system clipboard (TS: `Clipboard.writeText`). The
837/// answer says whether the system clipboard took it
838/// ([`ClipboardWrite`]); drop it when that does not matter, the write
839/// happens either way.
840pub fn set_clipboard(text: impl Into<String>) -> Answer<ClipboardWrite> {
841    let (answer, action) = super::services::set_clipboard(text.into());
842    act(action);
843    answer
844}
845
846/// Puts `item` on the system clipboard (TS: `Clipboard.write`): its
847/// text, and its HTML as the platform's HTML type, which apps that read
848/// formatting paste. Where the platform has no HTML on the clipboard (a
849/// terminal) the text only.
850///
851/// The answer says whether the system clipboard took it
852/// ([`ClipboardWrite`]); drop it when that does not matter.
853pub fn set_clipboard_item(item: ClipboardItem) -> Answer<ClipboardWrite> {
854    let (answer, action) = super::services::set_clipboard_item(item);
855    act(action);
856    answer
857}
858
859/// The text on the system clipboard, `""` when it holds none (TS:
860/// `Clipboard.readText`), to await in a task.
861pub fn clipboard_string() -> Answer<String> {
862    let (answer, action) = super::services::clipboard_string();
863    act(action);
864    answer
865}
866
867/// The text on the system clipboard for `Clipboard.readText`: `""` when
868/// it holds none, `None` when the person refused the read (iOS's paste
869/// prompt).
870pub(crate) fn clipboard_checked_string() -> Answer<Option<String>> {
871    let (answer, action) = super::services::clipboard_checked_string();
872    act(action);
873    answer
874}
875
876/// Whether the system clipboard holds text (TS: `Clipboard.hasText`).
877pub fn clipboard_has_string() -> Answer<bool> {
878    let (answer, action) = super::services::clipboard_has_string();
879    act(action);
880    answer
881}
882
883/// Puts the image of a base64 `data:` URI, or of the URL
884/// [`clipboard_image`] gave, on the system clipboard (TS:
885/// `Clipboard.writeImage`). Where the platform puts no images on the
886/// clipboard (Android) nothing happens.
887pub fn set_clipboard_image(uri: impl Into<String>) {
888    act(super::services::set_clipboard_image(uri.into()));
889}
890
891/// The image on the system clipboard, `None` when it holds none, when it
892/// is over [`crate::platform::clipboard::MAX_IMAGE_BYTES`] encoded or the
893/// platform reads no images (Android) (TS: `Clipboard.readImage`), to
894/// await in a task.
895pub fn clipboard_image() -> Answer<Option<ClipboardImage>> {
896    let (answer, action) = super::services::clipboard_image();
897    act(action);
898    answer
899}
900
901/// [`clipboard_image`] for `Clipboard.readImage`: `Err` with the size in
902/// encoded bytes of an image over the limit.
903pub(crate) fn clipboard_checked_image() -> Answer<Result<Option<ClipboardImage>, usize>> {
904    let (answer, action) = super::services::clipboard_checked_image();
905    act(action);
906    answer
907}
908
909/// Whether the system clipboard holds an image, without reading it (TS:
910/// `Clipboard.hasImage`).
911pub fn clipboard_has_image() -> Answer<bool> {
912    let (answer, action) = super::services::clipboard_has_image();
913    act(action);
914    answer
915}
916
917/// Renders `request`'s drawing offscreen into an image
918/// ([`super::Painter::render`]).
919pub(crate) fn render_canvas(
920    request: crate::canvas::render::RenderRequest,
921) -> Answer<Result<Vec<u8>, super::JsError>> {
922    let (answer, action) = super::services::render_canvas(request);
923    act(action);
924    answer
925}
926
927/// Whether the platform lets the user pick a color on the screen
928/// ([`pick_screen_color`]): macOS and browsers with an `EyeDropper`.
929pub fn can_pick_screen_color() -> bool {
930    env(|e| e.screen_color)
931}
932
933/// The color the user picks anywhere on the screen (the system's color
934/// sampler, a browser's `EyeDropper`), to await in a task: `None` when the
935/// user cancelled or the platform has no sampler
936/// ([`can_pick_screen_color`]).
937pub fn pick_screen_color() -> Answer<Option<crate::Hsla>> {
938    let (answer, action) = super::services::pick_screen_color();
939    act(action);
940    answer
941}
942
943/// The `file:` URLs of the local files on the system clipboard (files
944/// copied in a file manager; TS: `Clipboard.readFiles`), to await in a task.
945pub fn clipboard_files() -> Answer<Vec<String>> {
946    let (answer, action) = super::services::clipboard_files();
947    act(action);
948    answer
949}
950
951/// Registers a font while the app runs (TS: `registerFont`): one it
952/// downloaded or made, as TrueType, OpenType, WOFF or WOFF2 data. Resolves
953/// to its family name, for `font_family`, or why `data` is no font; to
954/// await in a task. Text that names the family is laid out with it from
955/// then on.
956pub fn register_font(data: impl Into<Vec<u8>>) -> Answer<Result<String, String>> {
957    let (answer, action) = super::services::register_font(data.into());
958    act(action);
959    answer
960}
961
962/// Shows the system's open dialog and gives the files (or folders,
963/// [`OpenDialog::folders`](crate::file_dialog::OpenDialog::folders)) the
964/// user picked, to await in a task: `None` when cancelled, the error when
965/// the dialog could not show (on Linux without a file chooser portal, or
966/// on a platform without file dialogs, such as the web;
967/// [`crate::platform::Environment::file_requests`]). GPUI's
968/// `prompt_for_paths`. On iOS and Android, returns app-owned copies without
969/// loading the files into memory or imposing a size limit. Android copies
970/// into the app cache; move files you need to keep to persistent storage.
971/// Android's folder picker selects one folder at a time. Mobile pickers use
972/// the system's title, button label and initial location.
973pub fn pick_paths(
974    dialog: crate::file_dialog::OpenDialog,
975) -> Answer<Result<Option<Vec<PathBuf>>, String>> {
976    file_request(
977        crate::file_dialog::FileRequest::OpenDialog(dialog),
978        FileAnswer::OpenDialog,
979    )
980}
981
982/// Shows the system's save dialog and gives the path the user chose to
983/// save to, to await in a task: `None` when cancelled, the error when the
984/// dialog could not show ([`pick_paths`]). The file is not created. GPUI's
985/// `prompt_for_new_path`.
986pub fn pick_save_path(
987    dialog: crate::file_dialog::SaveDialog,
988) -> Answer<Result<Option<PathBuf>, String>> {
989    file_request(
990        crate::file_dialog::FileRequest::SaveDialog(dialog),
991        FileAnswer::SaveDialog,
992    )
993}
994
995/// Opens the local file or folder at `path` (absolute) in its default app
996/// (GPUI's `open_with_system`), to await in a task or drop: `Ok` once it
997/// opened, the error when it did not (no app for it, a relative path, a
998/// platform that opens no local paths). [`open_url`] opens no `file:`
999/// URLs; this is their way.
1000pub fn open_path(path: impl Into<PathBuf>) -> Answer<Result<(), String>> {
1001    file_request(
1002        crate::file_dialog::FileRequest::OpenPath(path.into()),
1003        FileAnswer::Done,
1004    )
1005}
1006
1007/// Shows the item at `path` (absolute) selected in the file manager
1008/// (Finder, File Explorer, the desktop's file manager; GPUI's
1009/// `reveal_path`), to await in a task or drop: `Ok` once it showed, the
1010/// error when it did not (it does not exist, a relative path, a platform
1011/// without a file manager).
1012pub fn reveal_path(path: impl Into<PathBuf>) -> Answer<Result<(), String>> {
1013    file_request(
1014        crate::file_dialog::FileRequest::RevealPath(path.into()),
1015        FileAnswer::Done,
1016    )
1017}
1018
1019/// Moves the item at `path` (absolute) to the trash (the Recycle Bin on
1020/// Windows), to await in a task: where it went when the platform says
1021/// (macOS), else `None`, which is no failure; the error when it could not
1022/// (it does not exist, the volume has no trash, the platform has none).
1023pub fn move_to_trash(path: impl Into<PathBuf>) -> Answer<Result<Option<PathBuf>, String>> {
1024    file_request(
1025        crate::file_dialog::FileRequest::MoveToTrash(path.into()),
1026        FileAnswer::Trash,
1027    )
1028}
1029
1030/// Sends file request `request`, answered through `answer`.
1031fn file_request<T>(
1032    request: crate::file_dialog::FileRequest,
1033    answer: impl FnOnce(super::AnswerSlot<T>) -> FileAnswer,
1034) -> Answer<T> {
1035    let (answer, action) = super::services::file_request(request, answer);
1036    act(action);
1037    answer
1038}
1039
1040/// Shows the system's picker for images and gives the ones the user picked,
1041/// prepared as `request` says, none when cancelled (TS:
1042/// `Picker.pickImages`), to await in a task.
1043pub fn pick_images(request: crate::picker::PickRequest) -> Answer<Vec<crate::picker::PickedFile>> {
1044    let (answer, action) = super::services::pick_images(request);
1045    act(action);
1046    answer
1047}
1048
1049/// Shows the system's picker for files of any type (the open dialog on the
1050/// desktops, the document picker on iOS and Android, a file input on the web;
1051/// TS: `Picker.pickFiles`), to await in a task: the files the user picked,
1052/// their bytes as they are; none when cancelled ([`crate::picker`]).
1053pub fn pick_files(
1054    request: crate::picker::FilePickRequest,
1055) -> Answer<Vec<crate::picker::PickedFile>> {
1056    let (answer, action) = super::services::pick_files(request);
1057    act(action);
1058    answer
1059}
1060
1061/// Whether the app may show notifications (TS: `Notifications.permission`),
1062/// without asking the user. To await in a task.
1063pub fn notification_permission() -> Answer<crate::notifications::NotificationPermission> {
1064    let (answer, slot) = Answer::new();
1065    act(Action::Notification(
1066        super::NotificationAction::Permission {
1067            ask: false,
1068            answer: slot,
1069        },
1070    ));
1071    answer
1072}
1073
1074/// Asks the user to let the app show notifications, once (TS:
1075/// `Notifications.requestPermission`), and answers with the permission. To
1076/// await in a task.
1077pub fn request_notification_permission() -> Answer<crate::notifications::NotificationPermission> {
1078    let (answer, slot) = Answer::new();
1079    act(Action::Notification(
1080        super::NotificationAction::Permission {
1081            ask: true,
1082            answer: slot,
1083        },
1084    ));
1085    answer
1086}
1087
1088/// Shows `notification` (TS: `Notifications.show`), answering whether the
1089/// system took it: not without the permission. To await in a task.
1090pub fn show_notification(notification: crate::notifications::Notification) -> Answer<bool> {
1091    let (answer, slot) = Answer::new();
1092    act(Action::Notification(super::NotificationAction::Show {
1093        notification,
1094        answer: slot,
1095    }));
1096    answer
1097}
1098
1099/// Removes the notification called `id`, shown or waiting to show (TS:
1100/// `Notifications.close`).
1101pub fn close_notification(id: impl Into<String>) {
1102    act(Action::Notification(super::NotificationAction::Close(
1103        id.into(),
1104    )));
1105}
1106
1107/// Removes every notification of the app's, shown or waiting to show, those
1108/// an earlier run of the app left included where the platform can reach
1109/// them (TS: `Notifications.closeAll`): what signing out clears.
1110pub fn close_all_notifications() {
1111    act(Action::Notification(super::NotificationAction::CloseAll));
1112}
1113
1114/// Shows `count` on the app's icon, 0 clears it (TS: `Notifications.setBadge`).
1115pub fn set_badge(count: u32) {
1116    act(Action::Notification(super::NotificationAction::SetBadge(
1117        count,
1118    )));
1119}
1120
1121/// The id of the next notification the user presses (TS:
1122/// `Notifications.on("press", ...)`), those that started the app first. To
1123/// await in a task.
1124pub fn next_notification_press() -> Answer<String> {
1125    let (answer, slot) = Answer::new();
1126    act(Action::Notification(super::NotificationAction::NextPress(
1127        slot,
1128    )));
1129    answer
1130}
1131
1132/// The next files the system opens the app with (TS:
1133/// `Application.on("openFiles", ...)`, GPUI's `on_open_urls` for files):
1134/// files of the types the app declares (`nsh.json` `fileTypes`) the user
1135/// opened with it (Open With, a double click, a drop on its icon) at
1136/// launch or while it runs, as absolute paths. Those that came before
1137/// anything listened, the files that launched the app included, come at
1138/// once (at most [`crate::file_type::MAX_PENDING`]). Links of the app's
1139/// schemes come apart ([`next_url_scheme_open`]). One call waits at a time:
1140/// a newer call takes the next files and the one before gets none. To
1141/// await in a task.
1142pub fn next_open_files() -> Answer<Vec<std::path::PathBuf>> {
1143    let (answer, slot) = Answer::new();
1144    act(Action::NextOpenFiles(slot));
1145    answer
1146}
1147
1148/// The next later launch of the app (TS: `Application.on("secondInstance",
1149/// ...)`): with `nsh.json` `"singleInstance": true`, a second launch on
1150/// Windows or Linux hands the running instance its arguments and working
1151/// directory and exits; those that came before anything listened first
1152/// ([`crate::single_instance`]). The app has already heard `reopen`;
1153/// nothing is brought forward implicitly. Never on macOS (Launch Services activates the running app
1154/// instead), iOS, Android or the web. To await in a task.
1155pub fn next_second_instance() -> Answer<crate::single_instance::SecondInstance> {
1156    let (answer, slot) = Answer::new();
1157    act(Action::NextSecondInstance(slot));
1158    answer
1159}
1160
1161/// The next link that opens the app (TS: `UrlScheme.on("open", ...)`): a
1162/// URL of a scheme the app claims (`nsh.json` `schemes`,
1163/// [`crate::url_scheme`]). Every call waiting when a link comes gets it, as
1164/// TS's `open` listeners all do.
1165///
1166/// A task that called it is a listener for as long as it lives: its next
1167/// call first gets the links that came since its last one, at most the
1168/// last [`crate::url_scheme::MAX_PENDING`] (16). So a loop hears every
1169/// link, those that came while it handled the one before included. Await
1170/// it in a loop, or in a task that ends once it stops listening: a task
1171/// that calls it again much later gets every link that came meanwhile,
1172/// though others may have handled them long ago.
1173///
1174/// Links that came while nothing listened, the one that launched the app
1175/// included, go to the first call that asks (at most 16 are kept); a
1176/// listener that starts later does not get the links that came before it.
1177/// A link a call of [`next_url_scheme_open_for`] waits for goes to that
1178/// call alone. To await in a task.
1179pub fn next_url_scheme_open() -> Answer<String> {
1180    let (answer, slot) = Answer::new();
1181    let executor = executor();
1182    let listener = executor.current_task();
1183    executor.act(Action::NextUrlSchemeOpen(listener, slot));
1184    answer
1185}
1186
1187/// The next link of `scheme` (without `:`, compared ignoring case) that
1188/// opens the app while this call waits, for the caller alone: a module
1189/// that waits for one link, as a sign-in session for the provider's
1190/// redirect, takes it without the app hearing it and without taking the
1191/// app's other links. While it waits, a link of `scheme` goes to it and to
1192/// no [`next_url_scheme_open`] or `UrlScheme.on("open", ...)` listener,
1193/// and it does not become the app's address ([`app_url`]); links of other
1194/// schemes go to the app as before. Links that came before the call are
1195/// the app's, never this call's. Calls waiting for the same scheme take
1196/// its links in the order they were made. The app must claim `scheme`
1197/// (`nsh.json` `schemes`, or `https` with its web links), else no link of
1198/// it comes. The wait claims the whole scheme: waiting for `https` takes
1199/// every `https` link of the app meanwhile (its Universal Links and App
1200/// Links), so a callback should use a scheme of the app's own; matching by
1201/// host or path would be another function. The wait starts at the call,
1202/// not at the first poll, so a module calls it before it opens what will
1203/// send the link. Dropping the answer (a task cancelled, the losing branch
1204/// of a `select!`) ends the wait. To await in a task.
1205pub fn next_url_scheme_open_for(scheme: impl Into<String>) -> Answer<String> {
1206    let (answer, slot) = Answer::new();
1207    act(Action::NextUrlSchemeOpenFor(
1208        scheme.into().to_ascii_lowercase(),
1209        slot,
1210    ));
1211    answer
1212}
1213
1214/// The next address the app moves to without making the move itself (TS:
1215/// `UrlScheme.on("change", ...)`): on the web, the browser's back or
1216/// forward to an entry the app's pages do not account for, or an address
1217/// the user typed ([`crate::url_scheme::AppUrlChange`]). [`app_url`] reads
1218/// it already. Moves while nothing listened since the app started are not
1219/// kept; once something listened, at most
1220/// [`crate::url_scheme::MAX_PENDING`] wait. One call waits at a time: a
1221/// newer call takes the next move and the one before gets none, so an app
1222/// awaits it in one task (TS's `change` listeners share one). To await in a
1223/// task.
1224pub fn next_app_url_change() -> Answer<crate::url_scheme::AppUrlChange> {
1225    let (answer, slot) = Answer::new();
1226    act(Action::NextAppUrlChange(slot));
1227    answer
1228}
1229
1230/// The app's address (TS: `UrlScheme.url()`): on the web the page's, on
1231/// the native platforms the last link that opened the app; what
1232/// [`set_app_url`] set after it; `None` when there is none
1233/// ([`crate::url_scheme`]). To await in a task.
1234pub fn app_url() -> Answer<Option<String>> {
1235    let (answer, slot) = Answer::new();
1236    act(Action::AppUrl(slot));
1237    answer
1238}
1239
1240/// Sets the app's address (TS: `UrlScheme.setUrl`): on the web it replaces
1241/// the current history entry's; the native platforms keep it for
1242/// [`app_url`] ([`crate::url_scheme`]). An address longer than
1243/// [`crate::url_scheme::MAX_URL_LEN`] or with whitespace is an error, as
1244/// TS's `TypeError`; on the web a URL is resolved against the page's base,
1245/// as TS's is, and one of another origin than the page's is an error.
1246pub fn set_app_url(url: impl Into<String>) -> Result<(), String> {
1247    set_app_url_with(url, crate::url_scheme::HistoryBehavior::Replace)
1248}
1249
1250/// [`set_app_url`], saying how the address meets the history (TS:
1251/// `UrlScheme.setUrl(url, { history })`): on the web
1252/// [`HistoryBehavior::Push`](crate::url_scheme::HistoryBehavior::Push)
1253/// makes it an entry of its own after the current one, so the browser's
1254/// back goes back to the address before it; the native platforms keep it
1255/// for [`app_url`] either way.
1256pub fn set_app_url_with(
1257    url: impl Into<String>,
1258    history: crate::url_scheme::HistoryBehavior,
1259) -> Result<(), String> {
1260    let mut url = url.into();
1261    crate::url_scheme::check_address(&url)?;
1262    // Where the app is the page (the web), as TS's `setUrl` there.
1263    if try_os() == Some(Os::Web)
1264        && let Some(base) = with_data(|d| d.ambient.app_url.as_ref().and_then(|a| a.page_base()))
1265    {
1266        url = crate::url_scheme::resolve_on_page(&url, &base)?;
1267    }
1268    act(Action::SetAppUrl(url, history));
1269    Ok(())
1270}
1271
1272/// `UrlScheme.setUrl`'s part in the core: the address again, in order with
1273/// what came since the VM wrote it, and the web's history entry.
1274pub(crate) fn set_app_url_from_js(url: String, history: crate::url_scheme::HistoryBehavior) {
1275    act(Action::SetAppUrl(url, history));
1276}
1277
1278/// Whether a web view's ref gives its page trusted input here (TS:
1279/// `WebView.inputAvailable()`, [`ElementRef::send_input`](super::ElementRef::send_input)):
1280/// the platform delivers it (macOS, Windows) and the app's capabilities grant
1281/// `webview.input`. Elsewhere `send_input` does nothing. To await in a
1282/// task.
1283pub fn web_input_available() -> Answer<bool> {
1284    let (answer, slot) = Answer::new();
1285    act(Action::WebInputAvailable(slot));
1286    answer
1287}
1288
1289/// Whether a web view's ref runs scripts and answers with their results
1290/// here (TS: `WebView.evaluateAvailable()`,
1291/// [`ElementRef::evaluate`](super::ElementRef::evaluate)): the platform has
1292/// it and the app's capabilities grant `webview`. Elsewhere `evaluate`
1293/// fails with `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`. To await in a task.
1294pub fn web_evaluate_available() -> Answer<bool> {
1295    let (answer, slot) = Answer::new();
1296    act(Action::WebEvaluateAvailable(slot));
1297    answer
1298}
1299
1300/// Whether a web view shows a page here (TS: `WebView.available()`): the
1301/// platform shows web views and the app's capabilities grant `webview`.
1302/// Where it answers `false`, a web view reports `onError` (`code`
1303/// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` where the platform shows none,
1304/// `ERR_ACCESS_DENIED` where `webview` is not granted). A web engine that
1305/// fails only when a web view starts (Windows without the WebView2
1306/// runtime) answers `true` and reports the error on the web view. To
1307/// await in a task.
1308pub fn web_view_available() -> Answer<bool> {
1309    let (answer, slot) = Answer::new();
1310    act(Action::WebViewAvailable(slot));
1311    answer
1312}
1313
1314/// Calls function `name` of the app's host with `args` (TS: `host.call`),
1315/// to await in a task: what it returns, or why the call failed. The host
1316/// is the embedding app (the native app around the view, whose handlers
1317/// answer: `HostChannel::handle` in Rust, `handle` in Swift and Java), or
1318/// on the web the page that runs the app (`createPlayer`'s `host`, the
1319/// module nsh.json's `web.host` names). A call waits
1320/// [`DEFAULT_CALL_TIMEOUT`](crate::host_channel::DEFAULT_CALL_TIMEOUT)
1321/// ([`host_call_with`] says otherwise), on the app's clock. `name` must
1322/// be granted by `capabilities.host` in nsh.json ([`HostError::Denied`]);
1323/// where nothing embeds the app it fails with [`HostError::Unavailable`].
1324///
1325/// [`HostError::Denied`]: crate::host_channel::HostError::Denied
1326/// [`HostError::Unavailable`]: crate::host_channel::HostError::Unavailable
1327pub async fn host_call(
1328    name: impl Into<String>,
1329    args: crate::JsonValue,
1330) -> Result<crate::JsonValue, crate::host_channel::HostError> {
1331    host_call_with(name, args, crate::host_channel::HostCallOptions::default()).await
1332}
1333
1334/// [`host_call`] as `options` say (TS: `host.call(name, args, options)`).
1335pub async fn host_call_with(
1336    name: impl Into<String>,
1337    args: crate::JsonValue,
1338    options: crate::host_channel::HostCallOptions,
1339) -> Result<crate::JsonValue, crate::host_channel::HostError> {
1340    use crate::host_channel::HostError;
1341    let name = name.into();
1342    // One so long the clock never gets there waits as `ZERO` does.
1343    let timeout = options.timeout;
1344    let deadline = (!timeout.is_zero())
1345        .then(|| crate::time::now().checked_add(timeout))
1346        .flatten();
1347    let (answer, action) = super::services::host_call(name.clone(), args);
1348    act(action);
1349    let Some(at) = deadline else {
1350        return answer.await;
1351    };
1352    // On the app's clock, as its timers: a manual clock moves it.
1353    let answered = {
1354        let mut answer = std::pin::pin!(answer);
1355        let mut delay = std::pin::pin!(timer_until(at));
1356        std::future::poll_fn(|cx| {
1357            if let std::task::Poll::Ready(result) = answer.as_mut().poll(cx) {
1358                return std::task::Poll::Ready(Some(result));
1359            }
1360            if delay.as_mut().poll(cx).is_ready() {
1361                return std::task::Poll::Ready(None);
1362            }
1363            std::task::Poll::Pending
1364        })
1365        .await
1366    };
1367    answered.unwrap_or_else(|| {
1368        // The answer went with the block: the core drops its slot now,
1369        // and a late reply finds none (`Core::answer_host`).
1370        act(Action::ForgetHostCalls);
1371        Err(HostError::TimedOut { name, timeout })
1372    })
1373}
1374
1375/// Hands `args` to function `name` of the app's host, with no answer (TS:
1376/// `host.post`): its handler of `name` gets it, as [`host_call`]'s calls.
1377/// Where nothing embeds the app, or the host has no handler of `name`, the
1378/// post goes nowhere; a name `capabilities.host` does not grant, or no
1379/// valid one, is refused and logged.
1380pub fn host_post(name: impl Into<String>, args: crate::JsonValue) {
1381    act(Action::HostPost {
1382        name: name.into(),
1383        args,
1384    });
1385}
1386
1387/// Runs `listener` with the data of every event `event` the app's host
1388/// sends while the current owner lives (TS: `host.on`): the embedding
1389/// app's (`HostChannel::send` in Rust, `send` in Swift and Java) and on
1390/// the web the page's (`player.hostEvent`). An event that comes while no
1391/// listener of its name is there is kept (at most
1392/// [`MAX_QUEUED_EVENTS`](crate::host_channel::MAX_QUEUED_EVENTS), the
1393/// oldest going first) until one is added, which hears it after the
1394/// render that added it: a listener added once the app loaded something
1395/// still hears what the host sent at its start. An event a listener heard
1396/// is not replayed to the ones added later. Events need no capability.
1397pub fn on_host_event(event: impl Into<String>, listener: impl Fn(&crate::JsonValue) + 'static) {
1398    let owner = Owner::current();
1399    let listener: super::host_events::HostListener =
1400        Rc::new(move |data: &crate::JsonValue| owner.run(|| listener(data)));
1401    let listeners = &executor().host_events;
1402    let id = listeners.borrow_mut().add(event.into(), listener);
1403    let subscription = super::host_events::HostSubscription::new(listeners, id);
1404    cleanup(move || drop(subscription));
1405}
1406
1407/// The size in pixels of the image at `src` (TS: `Image.getSize`).
1408pub fn image_size(src: impl Into<String>) -> Answer<Result<ImageSize, String>> {
1409    let (answer, action) = super::services::image_size(src.into());
1410    act(action);
1411    answer
1412}
1413
1414/// Loads the image at `src` ahead of showing it (TS: `Image.prefetch`).
1415pub fn prefetch_image(src: impl Into<String>) -> super::Prefetch {
1416    let (answer, action) = super::services::prefetch(src.into());
1417    act(action);
1418    answer
1419}
1420
1421/// Makes an HTTP request (in a task: await its response; TS: `fetch`) with
1422/// the engine's network stack, the one JS's `fetch` uses: the platform's
1423/// on native targets and the browser's on the web, under the app's
1424/// `capabilities.network`. `request` is a URL (`GET`) or an
1425/// [`HttpRequest`](crate::platform::HttpRequest); the URL is absolute.
1426/// The whole body arrives with the response. An `asset:/` URL, as
1427/// [`FileAsset::uri`](super::FileAsset::uri) and `assets!()` give it, is a
1428/// file the app ships: the engine answers it from the host's assets, with
1429/// no capability needed.
1430pub fn fetch(request: impl Into<crate::platform::HttpRequest>) -> super::Fetch {
1431    let (answer, action) = super::services::fetch(request.into());
1432    act(action);
1433    answer
1434}
1435
1436/// Asks for the app to show in `locale` ([`crate::i18n::set_locale`]).
1437pub(crate) fn act_locale(locale: Option<crate::platform::Locale>) {
1438    act(Action::Locale(locale));
1439}
1440
1441/// Tells the core that translations changed in place
1442/// ([`crate::i18n::add_translations`]), so menus can re-localize if the
1443/// selected language changed.
1444pub(crate) fn act_translations_changed(before: crate::i18n::Translations) {
1445    act_if_running(Action::TranslationsChanged(before));
1446}
1447
1448/// Shows the surface in `appearance` whatever the system's (TS:
1449/// `setColorScheme`).
1450pub fn set_color_scheme(appearance: Appearance) {
1451    act(Action::Appearance(appearance));
1452}
1453
1454/// Draws the bar of every scroll view and list whose `scrollbar` is `true`
1455/// with the built-in bar `source` makes of `theme` (the UI set's, which
1456/// `source` gets back: [`BuiltInScrollbar::app_theme`](super::BuiltInScrollbar::app_theme)),
1457/// or (`None`, the default) with the platform's indicator. A view whose `scrollbar` is a theme shows the bar
1458/// of the UI set that makes one
1459/// ([`Registry::scrollbars_from`](super::Registry::scrollbars_from)).
1460/// `nsh-base`'s `set_scrollbar_theme` calls it.
1461pub fn set_builtin_scrollbars(source: super::ScrollbarSource, theme: Option<super::AnyValue>) {
1462    act(Action::BuiltInScrollbars(source, theme));
1463}
1464
1465// --- Tasks and timers --------------------------------------------------------
1466
1467/// A running task ([`spawn`]): it ends with the owner it was made under, or
1468/// when [`Spawned::cancel`] is called. Awaiting it gives its output.
1469pub struct Spawned<T>(task::Task<T>);
1470
1471impl<T> Spawned<T> {
1472    /// Ends the task now.
1473    pub fn cancel(self) {
1474        self.0.handle().cancel();
1475    }
1476}
1477
1478impl<T> Future for Spawned<T> {
1479    type Output = T;
1480
1481    fn poll(
1482        mut self: std::pin::Pin<&mut Self>,
1483        cx: &mut std::task::Context<'_>,
1484    ) -> std::task::Poll<T> {
1485        std::pin::Pin::new(&mut self.0).poll(cx)
1486    }
1487}
1488
1489/// Runs `future` on the engine thread (TS: an `async` function): it changes
1490/// what it wants by writing signals, and ends with the current owner. It
1491/// runs under that owner: what it makes is the owner's.
1492pub fn spawn<T: 'static>(future: impl Future<Output = T> + 'static) -> Spawned<T> {
1493    let executor = executor();
1494    let owner = Owner::current();
1495    let cancel = Rc::new(Cell::new(None));
1496    // Made outside the block and moved in: a task cancelled before its
1497    // first poll drops it too.
1498    let release = Release(cancel.clone());
1499    let task = task::spawn_future(
1500        &executor,
1501        Owned {
1502            owner,
1503            future: Box::pin(async move {
1504                let _release = release;
1505                future.await
1506            }),
1507        },
1508    );
1509    let handle = task.handle();
1510    // Taken back from the owner when the task ends first (it finished or
1511    // was cancelled), so a long-lived owner does not keep one per task.
1512    cancel.set(super::reactive::removable_cleanup(move || handle.cancel()));
1513    Spawned(task)
1514}
1515
1516/// Takes a task's cleanup back from its owner as the task's future goes
1517/// (it finished, or was dropped when cancelled).
1518struct Release(Rc<Cell<Option<super::reactive::RemovableCleanup>>>);
1519
1520impl Drop for Release {
1521    fn drop(&mut self) {
1522        if let Some(cancel) = self.0.take() {
1523            cancel.remove();
1524        }
1525    }
1526}
1527
1528/// Runs `f` on the platform's main thread (the UI thread), for APIs that
1529/// only work there (AppKit's status items, UIKit): after the commit of this
1530/// turn, after its views are mounted. Await the result on the engine
1531/// thread; dropping it does not stop `f`. Without a main thread of its own
1532/// (headless tests, the web, where the engine runs on the page's thread)
1533/// `f` runs on the engine thread, at the end of the commit; elsewhere it
1534/// runs later, while the engine goes on, so only the awaited result tells
1535/// that `f` ran. `f` runs outside the reactive graph: it returns a value,
1536/// and the caller writes signals after awaiting it. A panic in `f` is a
1537/// [`MainThreadError::Panicked`](crate::main_thread::MainThreadError)
1538/// (the web runtime aborts on a panic). A function that is not `async` calls
1539/// [`ModuleCx::run_on_main_thread`](super::ModuleCx::run_on_main_thread).
1540pub fn run_on_main_thread<R: Send + 'static>(
1541    f: impl FnOnce() -> R + Send + 'static,
1542) -> crate::main_thread::OnMainThread<R> {
1543    let (task, result) = crate::main_thread::task(f);
1544    act(Action::MainThread(task));
1545    result
1546}
1547
1548/// A future polled under `owner` ([`Owner::scope`]).
1549/// `future`, polled under `owner`, boxed for the executor.
1550pub(super) fn owned(
1551    owner: Owner,
1552    future: impl Future<Output = ()> + 'static,
1553) -> std::pin::Pin<Box<dyn Future<Output = ()>>> {
1554    Box::pin(Owned {
1555        owner,
1556        future: Box::pin(future),
1557    })
1558}
1559
1560struct Owned<F> {
1561    owner: Owner,
1562    future: std::pin::Pin<Box<F>>,
1563}
1564
1565impl<F: Future> Future for Owned<F> {
1566    type Output = F::Output;
1567
1568    fn poll(
1569        self: std::pin::Pin<&mut Self>,
1570        cx: &mut std::task::Context<'_>,
1571    ) -> std::task::Poll<F::Output> {
1572        let this = self.get_mut();
1573        this.owner.scope(|| this.future.as_mut().poll(cx))
1574    }
1575}
1576
1577/// Runs `f` once after `delay` (TS: `setTimeout`; cancelling the task is
1578/// `clearTimeout`), while the current owner lives.
1579pub fn set_timeout(delay: Duration, f: impl FnOnce() + 'static) -> Spawned<()> {
1580    let owner = Owner::current();
1581    spawn(async move {
1582        timer(delay).await;
1583        owner.run(f);
1584    })
1585}
1586
1587/// Runs `f` every `period` (TS: `setInterval`), while the current owner
1588/// lives. Late wakes do not pile up runs.
1589pub fn set_interval(period: Duration, f: impl Fn() + 'static) -> Spawned<()> {
1590    let owner = Owner::current();
1591    spawn(async move {
1592        let mut next = crate::time::now() + period;
1593        loop {
1594            timer_until(next).await;
1595            next = (next + period).max(crate::time::now());
1596            owner.run(&f);
1597        }
1598    })
1599}
1600
1601/// Runs `f` when the next display frame starts, with its time (TS:
1602/// `requestAnimationFrame`).
1603pub fn request_animation_frame(f: impl FnOnce(Instant) + 'static) -> Spawned<()> {
1604    let owner = Owner::current();
1605    spawn(async move {
1606        let at = next_frame().await;
1607        owner.run(move || f(at));
1608    })
1609}
1610
1611/// Waits `delay` (in a task; TS: what `setTimeout` waits for).
1612pub fn timer(delay: Duration) -> Delay {
1613    timer_until(crate::time::now() + delay)
1614}
1615
1616/// Waits until `at` (in a task).
1617pub fn timer_until(at: Instant) -> Delay {
1618    Delay {
1619        at,
1620        timer: None,
1621        #[cfg(not(target_arch = "wasm32"))]
1622        elsewhere: None,
1623    }
1624}
1625
1626/// What [`timer`] and [`timer_until`] wait for. In the engine's tasks the
1627/// core keeps it and the engine's loop wakes for it, as for JS's timers
1628/// (on time, with no other thread involved); awaited off the engine's
1629/// thread (in [`background`]), it is tokio's.
1630#[derive(Debug)]
1631pub struct Delay {
1632    at: Instant,
1633    /// Its timer in the core, which dropping the delay takes back (a task
1634    /// cancelled before its time).
1635    timer: Option<task::TimerKey>,
1636    #[cfg(not(target_arch = "wasm32"))]
1637    elsewhere: Option<std::pin::Pin<Box<tokio::time::Sleep>>>,
1638}
1639
1640impl Future for Delay {
1641    type Output = ();
1642
1643    fn poll(
1644        mut self: std::pin::Pin<&mut Self>,
1645        cx: &mut std::task::Context<'_>,
1646    ) -> std::task::Poll<()> {
1647        #[cfg(not(target_arch = "wasm32"))]
1648        if let Some(sleep) = &mut self.elsewhere {
1649            return sleep.as_mut().poll(cx);
1650        }
1651        if crate::time::now() >= self.at {
1652            // Its timer goes too if it has not fired yet (the task was
1653            // polled for something else).
1654            self.timer = None;
1655            return std::task::Poll::Ready(());
1656        }
1657        if let Some(timer) = &self.timer {
1658            timer.set_waker(cx.waker());
1659            return std::task::Poll::Pending;
1660        }
1661        match super::reactive::try_with_data(|d| d.ambient.executor.clone()).flatten() {
1662            Some(executor) => {
1663                self.timer = Some(executor.add_timer(self.at, cx.waker().clone()));
1664                std::task::Poll::Pending
1665            }
1666            #[cfg(not(target_arch = "wasm32"))]
1667            None => {
1668                let at = self.at;
1669                let sleep = self
1670                    .elsewhere
1671                    .insert(Box::pin(tokio::time::sleep_until(at.into())));
1672                sleep.as_mut().poll(cx)
1673            }
1674            // WebAssembly runs everything on the engine's thread.
1675            #[cfg(target_arch = "wasm32")]
1676            None => std::task::Poll::Pending,
1677        }
1678    }
1679}
1680
1681/// The next display frame's start (in a task; TS: what
1682/// `requestAnimationFrame` waits for). Awaited in a loop, it runs once per
1683/// frame.
1684pub fn next_frame() -> Answer<Instant> {
1685    let (answer, action) = super::services::frame();
1686    act(action);
1687    answer
1688}
1689
1690/// Runs `f` once the app has handled every event emitted so far
1691/// ([`super::Scope::emit`]) and the props it set in answer have reached the
1692/// components: a view that shows a value of its own until the app's comes
1693/// back (a drag's, before `onChange` returns as `value`) lets go of it here,
1694/// with no frame of the app's earlier value between. In a TSX app that is
1695/// the commit after the one that hands the events to JS, before the views
1696/// render (JS's handlers and the ops they queue run in between); with a
1697/// Rust owner, whose listeners run when the event is emitted, the commit
1698/// after the one that renders what they changed. What `f` changes renders
1699/// in that commit, which goes out in the batch of the app's answer. It runs
1700/// under the current owner, once: not when that owner is disposed first
1701/// (the view went).
1702///
1703/// Time does not tell: [`set_timeout`] with no delay and [`next_frame`]
1704/// run before the app has answered when the event came in the same turn
1705/// (a timer due now fires before the turn's commit, which is where JS
1706/// first hears the event), and later than needed otherwise (a frame
1707/// after). `after_answer` follows the events themselves, whatever the
1708/// clock. It costs nothing when unused: no closure kept, no extra commit
1709/// round.
1710pub fn after_answer(f: impl FnOnce() + 'static) {
1711    executor().after_answer(task::AfterAnswer {
1712        owner: Owner::current(),
1713        f: Box::new(f),
1714    });
1715}
1716
1717/// Runs `f`, with no owner, once the components of the commit being made
1718/// (the one in progress, else the next) have rendered, before its batch
1719/// goes out: after every view the update made or took down, so `f` sees the
1720/// whole update. What it asks for (an announcement) and what it changes
1721/// go out in the same batch. A task or a timer runs a commit later, too
1722/// late for what has to go with the views it is about.
1723///
1724/// The core's part of `nsh_base::Toast`'s announcement, which tells a
1725/// toast the app moved (took down and made again in one update) from a
1726/// new one.
1727#[doc(hidden)]
1728pub fn after_render(f: impl FnOnce() + 'static) {
1729    executor().after_render(task::AfterAnswer {
1730        owner: Owner::detached(),
1731        f: Box::new(f),
1732    });
1733}
1734
1735/// Runs blocking `f` on the runtime's blocking threads (in a task: await
1736/// its result; `tokio::task::spawn_blocking`), starting at once, whether
1737/// called from a task, a render, an effect or a handler. Not in
1738/// WebAssembly: code that should also run on the web uses the engine's
1739/// services instead ([`fetch`], [`timer`]).
1740#[cfg(not(target_arch = "wasm32"))]
1741pub fn blocking<R: Send + 'static>(
1742    f: impl FnOnce() -> R + Send + 'static,
1743) -> tokio::task::JoinHandle<R> {
1744    // Tasks are polled in the runtime's context; outside a task the
1745    // surface's runtime is the one they would be.
1746    match tokio::runtime::Handle::try_current() {
1747        Ok(runtime) => runtime.spawn_blocking(f),
1748        Err(_) => match executor().runtime() {
1749            Some(runtime) => runtime.spawn_blocking(f),
1750            None => tokio::task::spawn_blocking(f),
1751        },
1752    }
1753}
1754
1755/// Runs `future` on the runtime's threads (in a task: await its result;
1756/// `tokio::spawn`): `Send` work that should not hold the engine thread.
1757/// Not in WebAssembly, which has no threads.
1758#[cfg(not(target_arch = "wasm32"))]
1759pub fn background<F>(future: F) -> tokio::task::JoinHandle<F::Output>
1760where
1761    F: Future + Send + 'static,
1762    F::Output: Send + 'static,
1763{
1764    tokio::spawn(future)
1765}
1766
1767// --- Handles -----------------------------------------------------------------
1768
1769/// An animated value starting at `value` (TS: `createAnimatedValue`): bind
1770/// it to styles, drags, scroll offsets or drawings, animate it from handlers
1771/// and tasks. A `Copy` handle the current owner keeps, as a signal is (with
1772/// no owner, it lives as long as the surface).
1773pub fn animated_value(value: f32) -> super::AnimatedValue {
1774    super::AnimatedValue::new(&executor(), value)
1775}
1776
1777/// Animated values for a view's opacity and transform, and motions to
1778/// play on them (TS: `createMotion`): bind it with
1779/// [`super::Styled::bind_motion`]. A `Copy` handle the current owner keeps.
1780pub fn motion() -> super::Motion {
1781    super::Motion::new(&executor())
1782}
1783
1784/// A handle for an element (TS: `ref`): put it on the element with
1785/// [`super::Element::element_ref`], call its commands from handlers and
1786/// tasks. A `Copy` handle the current owner keeps, as a signal is.
1787pub fn element_ref() -> super::ElementRef {
1788    super::ElementRef::new(&executor())
1789}
1790
1791/// A handle for a component this view renders (TS: a `ref` to a
1792/// component): put it on the component's element with
1793/// [`super::ComponentElement::component_ref`]; [`super::ComponentRef::api`]
1794/// is the API its view registered. A `Copy` handle the current owner keeps.
1795pub fn component_ref<C: super::Component>() -> super::ComponentRef<C> {
1796    super::ComponentRef::new(&executor())
1797}
1798
1799/// How a keyboard shortcut fires ([`on_key_with`]; TS: `keymap.bind`'s
1800/// options).
1801#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1802pub struct KeyOptions {
1803    /// Where it fires ([`KeyScope`]).
1804    pub scope: KeyScope,
1805    /// While a text input (or a web view) has the keyboard focus: by
1806    /// default unless the input uses the keystroke itself.
1807    pub when: crate::keymap::When,
1808    /// Fires again on the auto-repeats of a held key (default: once until
1809    /// the key is released).
1810    pub repeat: bool,
1811    /// Lets the key go on after the handler runs, as if nothing were bound
1812    /// (default: the platform consumes it). Tab still moves the focus: a
1813    /// component closes its popup on Tab and the focus moves on as it
1814    /// would ([`crate::keymap::KeyMatch::Notify`]).
1815    pub pass_through: bool,
1816    /// The keys of the view with the keyboard focus: a component binds
1817    /// them while its part has the focus or its popup is open (a menu
1818    /// button's Return opens its menu). Return and Space reach such a
1819    /// binding before the focused control's press; others of those keys
1820    /// give way to the control the focus is on (default)
1821    /// ([`crate::keymap::KeyBinding::for_focus`]).
1822    pub for_focus: bool,
1823    /// What it takes from the control with the keyboard focus
1824    /// ([`crate::keymap::OverFocused`]; default: nothing, a focused
1825    /// component's own bindings and press win). `Always`: it comes before
1826    /// the views' bindings of the keystroke, so it takes a key a focused
1827    /// component binds itself (a query editor's mod+enter over the
1828    /// editor's own) while it is kept. `Pointer`: Return and Space from a
1829    /// control a pointer gave the focus (a press, a popup a press used
1830    /// giving it back), where they would press it; one the keyboard
1831    /// focused still takes them.
1832    pub over_focused: crate::keymap::OverFocused,
1833}
1834
1835/// Where a keyboard shortcut fires ([`on_key_with`]; TS: `keymap.bind`'s
1836/// `scope`).
1837#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1838pub enum KeyScope {
1839    /// The window the shortcut is made in: the window around the component,
1840    /// or the window the core finds its component in. A shortcut made in the
1841    /// app root (outside every window) is app-wide.
1842    #[default]
1843    Window,
1844    /// Every window: the app's own shortcuts, made in the app root.
1845    App,
1846}
1847
1848/// Whether shortcuts follow Apple's conventions here (`mod` is Command):
1849/// the OS, or for a browser the platform it runs on
1850/// ([`crate::keymap::apple_keys`]).
1851pub fn apple_keys() -> bool {
1852    let (os, apple) = with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
1853        .expect("the core sets the environment")
1854        .with_untracked(|e| (e.os, e.apple_keyboard));
1855    crate::keymap::apple_keys(os, apple)
1856}
1857
1858/// [`apple_keys`] where an engine runs, else `None` (as [`try_os`]).
1859pub fn try_apple_keys() -> Option<bool> {
1860    super::reactive::try_with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
1861        .flatten()
1862        .map(|env| env.with_untracked(|e| crate::keymap::apple_keys(e.os, e.apple_keyboard)))
1863}
1864
1865/// Runs `handler` when `keystroke` is pressed while the current owner
1866/// lives (TS: `keymap.bind`): `"mod+k"` (`mod` is Command on Apple
1867/// platforms, Control elsewhere), `"shift+mod+l"`, `"escape"`, ... (the
1868/// keystrokes of `nsh/keymap`). The handler gets the keystroke as written.
1869/// By default it belongs to the window bound in ([`super::desktop::current_window`];
1870/// in a component JS places in a window, that window), or to every window
1871/// when bound in the app root; [`KeyOptions::scope`] makes the choice
1872/// explicit. It fires only for keys pressed there, and a key it does not
1873/// take goes on as usual. Desktop platforms fire them; elsewhere they are
1874/// kept but no key does.
1875///
1876/// # Panics
1877///
1878/// On a keystroke that is not one, or one the platform keeps (Command+Q
1879/// on Apple platforms, Alt+F4 elsewhere, ...), as TS's `bind` throws.
1880///
1881/// The panic is not fatal to the app: like any panic in a component, it
1882/// ends the component that made the call (its error boundary hears it, or
1883/// it is logged) and the engine goes on. To take keystrokes from user
1884/// settings, check them first with
1885/// [`Shortcut::parse`](crate::desktop::Shortcut::parse).
1886#[track_caller]
1887pub fn on_key(keystroke: &str, handler: impl Fn(&str) + 'static) {
1888    on_key_with(keystroke, KeyOptions::default(), handler);
1889}
1890
1891/// [`on_key`] that fires as `options` say.
1892///
1893/// # Panics
1894///
1895/// As [`on_key`].
1896#[track_caller]
1897pub fn on_key_with(keystroke: &str, options: KeyOptions, handler: impl Fn(&str) + 'static) {
1898    let os = os();
1899    let parsed = crate::keymap::Keystroke::parse_with(keystroke, apple_keys())
1900        .unwrap_or_else(|e| panic!("on_key: {e}"));
1901    if let Some(why) = parsed.reserved(os) {
1902        panic!("on_key: {keystroke:?} cannot be bound: {why}");
1903    }
1904    let owner = Owner::current();
1905    let handler: super::keys::KeyHandler = Rc::new(move |k: &str| owner.run(|| handler(k)));
1906    // It belongs to the window whose tree binds it (`current_window`); with
1907    // no window around it in Rust (a component JS placed in a `Window`),
1908    // the core finds the window its owner's component shows in. An app-wide
1909    // binding (`KeyScope::App`) belongs to every window.
1910    let (window, app) = match options.scope {
1911        KeyScope::App => (None, true),
1912        KeyScope::Window => (
1913            super::use_context::<super::desktop::WindowRef>().and_then(|w| w.dialog_root()),
1914            false,
1915        ),
1916    };
1917    let keys = executor().keys.clone();
1918    let id = keys.borrow_mut().add(
1919        |id| {
1920            crate::keymap::KeyBinding::new(id, parsed, options.when, options.repeat)
1921                .passing_through(options.pass_through)
1922                .focus_keys(options.for_focus)
1923                .over_focused(options.over_focused)
1924        },
1925        keystroke.into(),
1926        handler,
1927        window,
1928        app,
1929        owner,
1930    );
1931    let weak = Rc::downgrade(&keys);
1932    cleanup(move || {
1933        if let Some(keys) = weak.upgrade() {
1934            let removed = keys.borrow_mut().remove(id);
1935            drop(removed);
1936        }
1937    });
1938}
1939
1940/// Watches the scroll view or list `target` names while the current owner
1941/// lives: `handler` hears its offset, content size and viewport (zoomed, as
1942/// `on_scroll` reports them) when it is first found and whenever one of
1943/// them changes, whether or not anything listens to its `on_scroll`. A
1944/// view of the app's own that follows a scroll view it did not make (a
1945/// scroll bar) watches it this way.
1946///
1947/// `target` is asked again in every commit (untracked), so a ref set later
1948/// in the same render is found when its element is mounted; while it names
1949/// no scroll view, nothing is heard. The handler runs at the end of the
1950/// commit round that saw the change, and what it changes goes out in the
1951/// same batch.
1952pub fn watch_scroll(
1953    target: impl Fn() -> Option<NodeId> + 'static,
1954    handler: impl Fn(&crate::element::ScrollEvent) + 'static,
1955) {
1956    let owner = Owner::current();
1957    let handler = Rc::new(move |e: &crate::element::ScrollEvent| owner.run(|| handler(e)));
1958    add_watch(Rc::new(target), handler);
1959}
1960
1961impl super::ElementRef {
1962    /// Listens to the keyboard focus coming into the element: onto it or
1963    /// an element inside it, from outside (GPUI's `on_focus_in` of a focus
1964    /// handle; the element enters `focus-within`). Moving between elements
1965    /// inside it is no new coming in. The content of an overlay is inside
1966    /// the element the overlay is in, wherever it shows: a popup's trigger
1967    /// and the popup are both inside the view holding them.
1968    ///
1969    /// It listens while the current owner lives, to whatever element
1970    /// carries the ref, and runs at the end of the commit round the focus
1971    /// moved in (what it changes goes out in the same batch). The focus is
1972    /// what the platform reports: an input's, or a view's that Tab or
1973    /// `focus()` reached where the keyboard moves between views (macOS,
1974    /// the web).
1975    pub fn on_focus_in(&self, listener: impl Fn() + 'static) {
1976        let element = *self;
1977        watch_focus(
1978            move || element.node(),
1979            move |within| {
1980                if within {
1981                    listener();
1982                }
1983            },
1984        );
1985    }
1986
1987    /// Listens to the keyboard focus leaving the element: going from it
1988    /// or an element inside it to one outside, or to none (GPUI's
1989    /// `on_focus_out`; the element leaves `focus-within`). An element
1990    /// removed with the focus inside it, or one that stops carrying the
1991    /// ref, is left too, and the focus coming into the next element that
1992    /// carries the ref is heard by [`Self::on_focus_in`]. As
1993    /// [`Self::on_focus_in`] otherwise.
1994    pub fn on_focus_out(&self, listener: impl Fn() + 'static) {
1995        let element = *self;
1996        watch_focus(
1997            move || element.node(),
1998            move |within| {
1999                if !within {
2000                    listener();
2001                }
2002            },
2003        );
2004    }
2005}
2006
2007/// Watches the focus coming into and leaving `target` while the current
2008/// owner lives.
2009fn watch_focus(target: impl Fn() -> Option<NodeId> + 'static, handler: impl Fn(bool) + 'static) {
2010    let owner = Owner::current();
2011    let handler = Rc::new(move |within: bool| owner.run(|| handler(within)));
2012    let watches = executor().watches.clone();
2013    let id = watches.borrow_mut().add_focus(Rc::new(target), handler);
2014    let weak = Rc::downgrade(&watches);
2015    cleanup(move || {
2016        if let Some(watches) = weak.upgrade() {
2017            let removed = watches.borrow_mut().remove_focus(id);
2018            drop(removed);
2019        }
2020    });
2021}
2022
2023impl super::NodeRef {
2024    /// Scrolls the scroll view (or list, along its axis) to a content
2025    /// offset, as [`super::ElementRef::scroll_to`] does: for a view holding
2026    /// a node, not a ref (a prop a JS `ref` fills, a watch's target).
2027    pub fn scroll_to(&self, offset: crate::geometry::Point<Points>, animated: bool) {
2028        act(Action::Command(
2029            self.0,
2030            Command::ScrollTo {
2031                x: offset.x,
2032                y: offset.y,
2033                animated,
2034            },
2035        ));
2036    }
2037}
2038
2039/// Watches the order the tree has the elements `elements` gives in, while
2040/// the current owner lives: `handler` hears it as indices into that list
2041/// (`[2, 0, 1]`: the third element comes first; elements carried by no
2042/// node in the tree last, in the order given) whenever it differs from the
2043/// list's own. `nsh-base`'s roving focus keeps a group's items (a
2044/// toolbar's) in order this way: components render in the order the core
2045/// makes them, which is not the tree's (an item inside a group renders
2046/// after the toolbar's later children).
2047///
2048/// The core looks at the end of a commit round: in the round the watch is
2049/// made in, after [`super::OrderWatch::invalidate`] (an element came), and
2050/// after a round that moved a node inside the subtree the elements share
2051/// (an app's keyed reorder of them), asking `elements` untracked; what the
2052/// handler changes goes out in the same batch. A round that moved nothing
2053/// there and invalidated nothing costs nothing: a list of rows reordered,
2054/// each row with a group of its own, costs those groups nothing.
2055#[doc(hidden)]
2056pub fn watch_order(
2057    elements: impl Fn() -> Vec<super::ElementRef> + 'static,
2058    handler: impl Fn(&[usize]) + 'static,
2059) -> super::OrderWatch {
2060    let owner = Owner::current();
2061    let handler = Rc::new(move |order: &[usize]| owner.run(|| handler(order)));
2062    let watches = executor().watches.clone();
2063    let (id, dirty) = watches.borrow_mut().add_order(Rc::new(elements), handler);
2064    let weak = Rc::downgrade(&watches);
2065    cleanup(move || {
2066        if let Some(watches) = weak.upgrade() {
2067            let removed = watches.borrow_mut().remove_order(id);
2068            drop(removed);
2069        }
2070    });
2071    super::OrderWatch::new(dirty)
2072}
2073
2074fn add_watch(target: Rc<dyn Fn() -> Option<NodeId>>, handler: super::watch::ScrollHandler) {
2075    let watches = executor().watches.clone();
2076    let id = watches.borrow_mut().add(target, handler);
2077    let weak = Rc::downgrade(&watches);
2078    cleanup(move || {
2079        if let Some(watches) = weak.upgrade() {
2080            let removed = watches.borrow_mut().remove(id);
2081            drop(removed);
2082        }
2083    });
2084}
2085
2086/// `keystroke` as menus and hints show it here (TS: `keymap.label`):
2087/// `"⇧⌘L"` on Apple platforms (and in a browser on one), `"Ctrl+Shift+L"`
2088/// elsewhere, for `"mod+shift+l"`.
2089///
2090/// # Panics
2091///
2092/// On a keystroke that is not one.
2093///
2094/// The panic is not fatal to the app: like any panic in a component, it
2095/// ends the component that made the call (its error boundary hears it, or
2096/// it is logged) and the engine goes on. To take keystrokes from user
2097/// settings, check them first with
2098/// [`Shortcut::parse`](crate::desktop::Shortcut::parse).
2099#[track_caller]
2100pub fn key_label(keystroke: &str) -> String {
2101    let parsed = crate::keymap::Keystroke::parse_with(keystroke, apple_keys())
2102        .unwrap_or_else(|e| panic!("key_label: {e}"));
2103    keystroke_label(parsed)
2104}
2105
2106/// A parsed keystroke as menus and hints show it here ([`key_label`]):
2107/// the keys to press, Ctrl for Command where Ctrl stands in for it
2108/// ([`crate::platform::Environment::ctrl_for_command`]).
2109pub fn keystroke_label(keystroke: crate::keymap::Keystroke) -> String {
2110    let (os, apple, ctrl) = with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
2111        .expect("the core sets the environment")
2112        .with_untracked(|e| {
2113            (
2114                e.os,
2115                crate::keymap::apple_keys(e.os, e.apple_keyboard),
2116                e.ctrl_for_command,
2117            )
2118        });
2119    keystroke.pressed(ctrl).label(os, apple)
2120}
2121
2122/// Listens to the Android back button while the current owner lives (TS:
2123/// `BackHandler.on("press", f)`): when no modal is
2124/// shown, `f` runs before the stack pops, newest listener first, and returns
2125/// true when it handled the press. While one listens, a back gesture does
2126/// not preview the pop.
2127pub fn on_back_press(f: impl Fn() -> bool + 'static) {
2128    let owner = Owner::current();
2129    let listener: super::back::BackListener = Rc::new(move || owner.run(&f));
2130    let back = &executor().back;
2131    let id = back.borrow_mut().add(listener);
2132    let subscription = super::back::Subscription::new(back, id);
2133    cleanup(move || drop(subscription));
2134}
2135
2136/// Follows the system's back gesture while the current owner lives (TS:
2137/// `BackHandler.on("progress", f)`): `f` hears each step of a gesture no
2138/// modal takes, from its start to its end (the back press follows, as
2139/// [`on_back_press`]'s listeners hear it) or its cancel, as AndroidX's
2140/// `OnBackPressedCallback` does. While one listens, the stacks leave the
2141/// gesture to the app: none previews its pop, so a view the app moves with
2142/// the finger (a drawer closing, a sheet going down) is the only one that
2143/// does. Android 14 and later (predictive back) report it; elsewhere it
2144/// never comes.
2145pub fn on_back_progress(f: impl Fn(&crate::BackProgressEvent) + 'static) {
2146    let owner = Owner::current();
2147    let listener: super::back::BackProgressListener = Rc::new(move |e| owner.run(|| f(e)));
2148    let progress = &executor().back_progress;
2149    let id = progress.borrow_mut().add(listener);
2150    let subscription = super::back::Subscription::new(progress, id);
2151    cleanup(move || drop(subscription));
2152}
2153
2154pub(crate) fn title_bar() -> crate::geometry::Edges<crate::geometry::Points> {
2155    env(|e| e.title_bar)
2156}
2157
2158pub(crate) fn window_state() -> Option<crate::desktop::WindowState> {
2159    env(|e| e.window_state)
2160}
2161
2162pub(crate) fn displays() -> Vec<crate::desktop::Display> {
2163    displays_signal().with(|d| d.to_vec())
2164}
2165
2166/// The displays' signal, made empty on first use (whatever reads it before
2167/// the platform reports displays follows them when it does).
2168fn displays_signal() -> Signal<Arc<[crate::desktop::Display]>> {
2169    if let Some(signal) = with_data(|d| d.ambient.displays) {
2170        return signal;
2171    }
2172    let signal = Owner::detached().run(|| super::signal(Arc::from(Vec::new())));
2173    with_data(|d| d.ambient.displays = Some(signal));
2174    signal
2175}
2176
2177/// Whether the platform's performance monitor measures (TS:
2178/// `fpsEnabled()`), as the platform reports it: reading it in a binding
2179/// subscribes it.
2180pub fn fps_enabled() -> bool {
2181    perf_monitor_signal().get()
2182}
2183
2184/// Turns the platform's performance monitor on or off (TS:
2185/// `setFpsEnabled`): the macOS panel, the other platforms' `nsh::fps`
2186/// log lines, as `--fps` and `NSH_FPS=1` do at launch. Platforms without a
2187/// monitor ignore it; [`fps_enabled`] follows what the platform did.
2188pub fn set_fps_enabled(enabled: bool) {
2189    act(super::services::perf_monitor(enabled));
2190}
2191
2192/// What the performance monitor measured over the last second (TS:
2193/// `perfStats()`): its frame rate and more, read once a second while it
2194/// measures ([`fps_enabled`]), `None` while it does not (and until its first
2195/// second). Reading it in a binding subscribes it.
2196pub fn perf_stats() -> Option<crate::platform::PerfStats> {
2197    perf_stats_signal().get()
2198}
2199
2200/// The performance stats' signal, none until the engine reports some.
2201fn perf_stats_signal() -> Signal<Option<crate::platform::PerfStats>> {
2202    if let Some(signal) = with_data(|d| d.ambient.perf_stats) {
2203        return signal;
2204    }
2205    let signal = Owner::detached().run(|| super::signal(None));
2206    with_data(|d| d.ambient.perf_stats = Some(signal));
2207    signal
2208}
2209
2210/// How the performance monitor shows (TS: `setFpsMode`), now and whenever it
2211/// shows later: its whole panel ([`crate::FpsMode::Expanded`], the
2212/// default), collapsed to its frame rate, or nothing while it still
2213/// measures. A click on the panel switches between the first two. macOS's
2214/// panel takes it; platforms without a panel ignore it.
2215pub fn set_fps_mode(mode: crate::FpsMode) {
2216    act(super::services::perf_monitor_mode(mode));
2217}
2218
2219/// The performance monitor's signal, off until the platform reports it.
2220fn perf_monitor_signal() -> Signal<bool> {
2221    if let Some(signal) = with_data(|d| d.ambient.perf_monitor) {
2222        return signal;
2223    }
2224    let signal = Owner::detached().run(|| super::signal(false));
2225    with_data(|d| d.ambient.perf_monitor = Some(signal));
2226    signal
2227}
2228
2229/// The main window's close presses, none until the platform reports one.
2230pub(crate) fn main_close_press_signal() -> Signal<(u64, crate::desktop::CloseReason)> {
2231    if let Some(signal) = with_data(|d| d.ambient.main_close_press) {
2232        return signal;
2233    }
2234    let signal =
2235        Owner::detached().run(|| super::signal((0, crate::desktop::CloseReason::default())));
2236    with_data(|d| d.ambient.main_close_press = Some(signal));
2237    signal
2238}
2239
2240/// The views' menu handlers.
2241pub(crate) fn view_menus() -> Rc<std::cell::RefCell<super::menus::ViewMenus>> {
2242    executor().menus.clone()
2243}
2244
2245pub(crate) fn desktop_command(command: crate::desktop::DesktopCommand) {
2246    act(Action::Command(
2247        crate::ROOT_ID,
2248        Command::Desktop(Box::new(command)),
2249    ));
2250}
2251
2252/// Sets the distance every overlay without a `margin` of its own (menus,
2253/// submenus, popovers, tooltips, hover cards, popups) keeps from the edges
2254/// of the window's safe area: placed, flipped and shrunk within it, so
2255/// none touches the window's edge. Default
2256/// [`crate::overlay::DEFAULT_SNAP_TO_WINDOW_MARGIN`] (8 points); `0` lets them
2257/// reach the edges. TS: `setSnapToWindowMargin(points)` from `nsh`.
2258pub fn set_snap_to_window_margin(margin: crate::geometry::Points) {
2259    act(Action::SnapToWindowMargin(margin));
2260}
2261
2262/// Asks the core whether the app launches at login (`enabled` `None`) or
2263/// to change it ([`Action::LoginItem`]).
2264pub(crate) fn login_item_request(
2265    enabled: Option<bool>,
2266) -> Answer<Result<bool, crate::desktop::LaunchAtLoginError>> {
2267    let (answer, slot) = Answer::new();
2268    act(Action::LoginItem(enabled, slot));
2269    answer
2270}
2271
2272#[cfg(test)]
2273mod tests {
2274    use super::*;
2275    use crate::{element::Runtime, geometry::px};
2276
2277    #[test]
2278    fn captured_text_measurer_works_without_runtime_entry() {
2279        let runtime = Runtime::default();
2280        runtime.set_measure(Rc::new(|_, text| crate::canvas::TextMetrics {
2281            width: px(text.chars().count() as f32),
2282            ..Default::default()
2283        }));
2284        let measure = {
2285            let _entered = runtime.enter();
2286            text_measurer()
2287        };
2288        assert_eq!(measure("16px sans-serif", "选择 text"), px(7.0));
2289    }
2290}