Skip to main content

remedy_ui/
lib.rs

1//! RemedyUI for apps.
2//!
3//! ```no_run
4//! use remedy_ui::{App, AppConfig, WindowSpec};
5//!
6//! remedy_ui::run(AppConfig::new("Example"), |app: &App| {
7//!     app.open(WindowSpec::new("Hello"), |ui, _window| {
8//!         ui.root().child(ui.el("label").text("Hello"));
9//!     });
10//! })
11//! .ok();
12//! ```
13//!
14//! [`run`] starts the platform's bridge (Windows, macOS, Linux, Android, or a browser page with
15//! the `web` feature, where it returns once the app has started) and drives every window:
16//! input goes to the window's [`Ui`], each frame runs the view pipeline into the window's
17//! compositor, and frames are presented with the GPU renderer (feature `gpu`, on by default)
18//! or, when no GPU works, the CPU renderer with damage-only presents. App code acts through an
19//! [`App`] handle and [`Window`] handles; what they ask happens right after the event that
20//! asked. Window geometry can persist under a key, timers run app code later, and the app
21//! keeps running with no windows when it says so (tray apps).
22//!
23//! The [`guide`] holds the guides, porting guides and recipes, starting with
24//! [`guide::getting_started`].
25
26#[cfg(feature = "widgets")]
27mod confirm;
28#[cfg(feature = "customize")]
29mod customizations;
30mod geometry;
31pub mod guide;
32mod instance;
33
34#[cfg(feature = "widgets")]
35mod movable;
36// A player's picture-in-picture window on the desktop.
37#[cfg(all(feature = "playback", not(any(target_arch = "wasm32", target_os = "android", target_os = "ios"))))]
38mod pip;
39#[cfg(feature = "widgets")]
40pub mod router;
41mod runner;
42mod secure;
43/// Driving an app in tests on the in-memory host: find by role and name, press, type.
44#[cfg(all(feature = "headless", feature = "widgets"))]
45pub mod testing;
46#[cfg(all(feature = "web", target_arch = "wasm32", target_os = "unknown"))]
47mod web_fonts;
48
49// The README's code is compiled with the doctests, so it cannot drift from the API either.
50#[cfg(doctest)]
51#[doc = include_str!("../../../README.md")]
52struct ReadmeDoctests;
53
54/// The runner's own words (what the place of content popped out to its own window says) in
55/// every language the engine ships, from `i18n/remedy-ui/*.ftl`. Apps reword them, or add a language,
56/// with [`remedy_ui_engine::view::strings::add_messages`] under the name `remedy-ui`.
57pub static STRINGS: remedy_ui_engine::view::strings::Strings = remedy_ui_engine::engine_strings!("remedy-ui");
58
59#[cfg(feature = "widgets")]
60pub use confirm::ConfirmSpec;
61pub use geometry::{GEOMETRY_KEY, GeometryStore};
62pub use instance::{InstanceReply, ReplyLater};
63#[cfg(feature = "widgets")]
64pub use movable::{Movable, movable};
65/// Editions: which default behaviors the app follows ([`AppConfig::edition`]).
66pub use remedy_ui_core::Edition;
67pub use runner::{
68    App, AppConfig, BackgroundJob, Cancelled, CloseReason, Completion, GPU_PROMOTE_FRAME_COST,
69    GPU_PROMOTE_FRAME_STALL, GraphicsAdapter, Leaving, RendererChoice, RendererKind, Runner,
70    SINGLE_INSTANCE_REPLY, Window, WindowSpec, bundled_fonts,
71};
72
73/// The web bridge: where the app shows in the page ([`web::WebConfig`], [`web::Mount`], set
74/// with [`AppConfig::web`]), and the page's files (picked, dropped, downloaded). Its types
75/// are on every target, so app code sets them without `cfg`; starting an app in a page is
76/// [`run`]'s, on `wasm32-unknown-unknown`.
77#[cfg(feature = "web")]
78pub use remedy_ui_bridge_web as web;
79pub use remedy_ui_core as core;
80/// Semantics: roles, names, states and actions that screen readers, tests and agents read
81/// (`Semantics`, `Role`, `Action`).
82pub use remedy_ui_core::a11y;
83/// The Android bridge: the app's entry point (`remedy_ui::android::main!`), the system log.
84#[cfg(target_os = "android")]
85pub mod android {
86    pub use remedy_ui_platform::bridge_android::*;
87    // An exported macro lives at its crate's root: here it is beside the bridge it starts.
88    pub use remedy_ui_platform::main;
89}
90#[cfg(feature = "headless")]
91pub use remedy_ui_platform::bridge_headless as headless;
92#[cfg(feature = "gpu-embed")]
93pub use remedy_ui_platform::embed_gpu as gpu_embed;
94/// Agents: assistants read and operate the window under the person's consent.
95#[cfg(feature = "agents")]
96pub use remedy_ui_widgets::automation as agents;
97/// What people change about the app: theme, shortcuts, toolbars and menus, and text.
98#[cfg(feature = "customize")]
99pub use remedy_ui_widgets::customize;
100#[cfg(feature = "devtools")]
101pub use remedy_ui_widgets::devtools;
102#[cfg(feature = "code")]
103pub use remedy_ui_widgets::doc_code as code;
104#[cfg(feature = "pages")]
105pub use remedy_ui_widgets::doc_pages as pages;
106#[cfg(feature = "rich")]
107pub use remedy_ui_widgets::doc_rich as rich;
108/// Prism, the effects system (feature `effects`): the `.rfx` language and its compiler
109/// ([`effects::Effect::compile`]), the built-in effect library ([`effects::library`]), and
110/// effects as elements ([`effects::effect_view`]) drawn by the GPU kernel or the CPU renderer.
111#[cfg(feature = "effects")]
112pub mod effects {
113    pub use remedy_ui_engine::effects::*;
114    pub use remedy_ui_engine::media_effects::*;
115
116    /// What the `effect` markup element takes ([`register_markup`]): `name`, a built-in effect
117    /// ([`LIBRARY`]); and, optionally, `param`, one of its parameters, driven live by `value`,
118    /// a number signal the app exposes.
119    #[cfg(feature = "markup")]
120    pub const MARKUP_PARAMS: &[crate::markup::spec::Param] = &[
121        crate::markup::spec::Param { name: "name", kind: crate::markup::spec::Kind::Word, required: true },
122        crate::markup::spec::Param { name: "param", kind: crate::markup::spec::Kind::Word, required: false },
123        crate::markup::spec::Param {
124            name: "value",
125            kind: crate::markup::spec::Kind::Number,
126            required: false,
127        },
128    ];
129
130    /// Builds the `effect` markup element from its call: the built-in effect `name` in an
131    /// element, under the window's ambient policy, with what the file put inside it drawn over
132    /// it. A name that is not a built-in effect draws nothing. Markup is data from anyone, so
133    /// only built-in effects are offered: no effect source reaches the compiler from a file.
134    /// For build-time markup, pass it as the custom element's path.
135    #[cfg(feature = "markup")]
136    pub fn markup_element(ui: &crate::Ui, call: crate::markup::Call) -> crate::El {
137        let effect = call.label("name").and_then(library);
138        let mut el = match effect {
139            Some(e) => {
140                let (el, view) = effect_view(ui, Instance::new(e));
141                match (call.label("param").map(str::to_owned), call.number("value")) {
142                    (Some(param), Some(value)) => el.bind_named("effect value", move || {
143                        let _ = view.set(&param, value.get() as f32);
144                    }),
145                    _ => el,
146                }
147            }
148            None => ui.el("effect"),
149        };
150        for c in call.children {
151            el = el.child(c);
152        }
153        el
154    }
155
156    /// Adds the `effect` element to what `.rui` files may use:
157    /// `effect(name: "fire", param: "intensity", value: $heat) { … }`.
158    ///
159    /// ```
160    /// use remedy_ui::markup::{Markup, Scope, Widgets, build_markup};
161    /// let mut widgets = Widgets::new();
162    /// remedy_ui::effects::register_markup(&mut widgets);
163    /// let m = Markup::parse("hero.rui", r#"effect(name: "aurora") { text(text: "Hello") }"#)
164    ///     .map_err(|e| e.to_string())?;
165    /// assert!(remedy_ui::markup::check(&m, &Scope::new(), &widgets).is_ok());
166    /// # let _ = build_markup;
167    /// # Ok::<(), String>(())
168    /// ```
169    #[cfg(feature = "markup")]
170    pub fn register_markup(widgets: &mut crate::markup::Widgets) {
171        widgets.register("effect", MARKUP_PARAMS, true, markup_element);
172    }
173}
174pub use remedy_ui_core::host;
175pub use remedy_ui_core::input;
176pub use remedy_ui_core::layout;
177/// Drawing: display lists, paths, brushes, transforms and images, for painters
178/// (`El::paint`), canvases and page sources.
179pub use remedy_ui_engine::paint;
180/// `#[derive(Store)]`: field accessors for a reactive [`reactive::Store`].
181#[cfg(feature = "macros")]
182pub use remedy_ui_macros::Store;
183#[cfg(feature = "anim")]
184pub use remedy_ui_media::media_anim as anim;
185#[cfg(feature = "image")]
186pub use remedy_ui_media::media_image as image;
187#[cfg(feature = "svg")]
188pub use remedy_ui_media::media_image::svg;
189/// Decoding in a sandboxed helper process: images and animations whose decoder crashes,
190/// hangs or runs away with memory take down only the helper.
191#[cfg(feature = "isolated")]
192pub use remedy_ui_media::media_isolated as isolated;
193#[cfg(feature = "video")]
194pub use remedy_ui_media::media_video as video;
195#[cfg(feature = "playback")]
196pub use remedy_ui_media_playback as playback;
197#[cfg(feature = "webview")]
198pub use remedy_ui_platform::embed_webview as webview;
199/// The GPU renderer's own bounds (feature `gpu`): errors kept, the health file, how long it
200/// waits for swapchains, presents and video ([`gpu::set_gpu_limits`]). What both renderers
201/// draw is bounded by [`paint::set_paint_limits`].
202#[cfg(feature = "gpu")]
203pub mod gpu {
204    pub use remedy_ui_engine::render_gpu::{
205        GpuLimits, MAX_HEALTH_ENTRIES, MAX_HEALTH_LINE, MAX_KEPT_ERRORS, MAX_VIDEO_IMPORTS, SWAPCHAIN_WAIT,
206        VIDEO_FENCE_WAIT, gpu_limits, health::PRESENT_HANG, set_gpu_limits,
207    };
208}
209/// Motion: elements animate a property, style value, offset or scale to a target with a
210/// spring or an easing curve on the frame clock (`El::animate`), interruptibly and instantly
211/// under reduced motion; `Transition`s for content that appears and leaves.
212pub mod motion {
213    pub use remedy_ui_engine::view::Transition;
214    pub use remedy_ui_engine::view::motion::*;
215}
216pub use remedy_ui_core::reactive;
217pub use remedy_ui_core::style;
218/// Scripted widgets, independent of any language: the widget interface, the element protocol,
219/// limits and the engine registry.
220#[cfg(feature = "board")]
221pub use remedy_ui_engine::script;
222/// Scripted widgets in RemedyLua.
223#[cfg(feature = "script-lua")]
224pub use remedy_ui_engine::script_lua;
225/// Scripted widgets in WebAssembly.
226#[cfg(feature = "script-wasm")]
227pub use remedy_ui_engine::script_wasm;
228pub use remedy_ui_engine::view;
229/// Content that comes and goes, fails or loads, where apps build screens: [`show`] (content
230/// shown while a condition holds), [`catch_errors`] (an error boundary that takes a builder
231/// closure for its content, so a retry builds it again) and [`suspense`] (a placeholder
232/// while resources load), with what they return and hand to callbacks.
233pub use remedy_ui_engine::view::{CaughtError, Retry, Show, SuspenseBoundary, catch_errors, show, suspense};
234pub use remedy_ui_engine::view::{
235    El, EnterKey, FieldKind, InputPurpose, PaintCx, PointerCaps, TextField, Ui, WindowDirection,
236};
237/// Desktop services: starting with the session, URL schemes, jump lists and recent files,
238/// power (battery, sleep and resume, keeping awake), showing files in the file manager, and
239/// the user's usual folders. Notifications, badges and the tray are on [`App`].
240#[cfg(feature = "desktop")]
241pub use remedy_ui_platform::services_desktop as desktop;
242#[cfg(feature = "i18n")]
243pub use remedy_ui_platform::services_i18n as i18n;
244/// The HTTP client, natively and in a browser page.
245#[cfg(feature = "net")]
246pub use remedy_ui_platform::services_net as net;
247/// Importing the localStorage a web version of the app saved: a web view's store on disk
248/// (WebView2, Android System WebView), read losslessly and read-only, or the page's own in a
249/// browser.
250#[cfg(feature = "webstorage")]
251pub use remedy_ui_platform::services_webstorage as webstorage;
252pub use remedy_ui_text as text;
253#[cfg(feature = "widgets")]
254pub use remedy_ui_widgets::base as widgets;
255#[cfg(feature = "board")]
256pub use remedy_ui_widgets::board;
257#[cfg(feature = "data")]
258pub use remedy_ui_widgets::data;
259#[cfg(feature = "extra")]
260pub use remedy_ui_widgets::extra;
261#[cfg(feature = "forms")]
262pub use remedy_ui_widgets::forms;
263#[cfg(feature = "music")]
264pub use remedy_ui_widgets::music;
265#[cfg(feature = "nav")]
266pub use remedy_ui_widgets::nav;
267/// `.rui` markup: screens as data, compiled at build time or loaded for people's own layouts.
268#[cfg(feature = "markup")]
269pub use remedy_ui_widgets::rui as markup;
270#[cfg(feature = "spell")]
271pub use remedy_ui_widgets::spell;
272#[cfg(feature = "stage")]
273pub use remedy_ui_widgets::stage;
274#[cfg(feature = "widgets")]
275pub use remedy_ui_widgets::themes;
276#[cfg(feature = "update")]
277pub use remedy_ui_widgets::update;
278#[cfg(feature = "viz")]
279pub use remedy_ui_widgets::viz;
280#[cfg(feature = "term")]
281pub use remedy_ui_widgets_term as term;
282
283/// Why the app could not run.
284#[derive(Clone, Debug, PartialEq, Eq)]
285#[non_exhaustive]
286pub enum RunError {
287    /// [`AppConfig::single_instance`] could not claim or reach the running instance.
288    SingleInstance {
289        /// Why, in the platform's words.
290        reason: String,
291    },
292    /// The platform's bridge could not start its event loop, or the loop failed.
293    Bridge {
294        /// Why, in the platform's words.
295        reason: String,
296    },
297    /// RemedyUI has no bridge for this platform.
298    UnsupportedPlatform,
299    /// This platform's bridge is a feature the app did not turn on (`web` for browser pages).
300    NeedsFeature {
301        /// The `remedy-ui` feature to turn on.
302        feature: &'static str,
303    },
304}
305
306impl std::fmt::Display for RunError {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        match self {
309            RunError::SingleInstance { reason } => {
310                write!(f, "the app could not run as a single instance: {reason}")
311            }
312            RunError::Bridge { reason } => write!(f, "the app could not run: {reason}"),
313            RunError::UnsupportedPlatform => {
314                write!(f, "the app could not run: RemedyUI has no bridge for this platform yet")
315            }
316            RunError::NeedsFeature { feature } => {
317                write!(f, "the app could not run: this platform needs remedy-ui's `{feature}` feature")
318            }
319        }
320    }
321}
322
323impl std::error::Error for RunError {}
324
325/// Runs the app on this platform's bridge until it quits. `setup` runs once the platform is
326/// ready, to open the first windows.
327pub fn run(config: AppConfig, setup: impl FnOnce(&App) + 'static) -> Result<(), RunError> {
328    // Keepalive requests (an app's last saves) finish as the app quits, as in a closing page.
329    #[cfg(all(feature = "net", not(target_arch = "wasm32")))]
330    let _keepalive = KeepaliveOnExit(config.keepalive_grace);
331    // On Android they also finish when the app goes out of sight: the process is kept from
332    // being frozen until they end.
333    #[cfg(all(feature = "net", target_os = "android"))]
334    remedy_ui_platform::services_net::on_keepalive(remedy_ui_platform::bridge_android::hold_process);
335    #[cfg(target_os = "android")]
336    remedy_ui_platform::bridge_android::set_held_grace(config.keepalive_grace);
337    // SVG files show wherever images do.
338    #[cfg(feature = "svg")]
339    remedy_ui_media::media_image::svg::install();
340    let inbox = instance::SharedInbox::default();
341    // A browser settles the instance across tabs asynchronously: the first tab starts the
342    // app once the browser grants it the instance.
343    #[cfg(all(feature = "web", target_arch = "wasm32", target_os = "unknown"))]
344    if config.single_instance {
345        let name = config.name.clone();
346        let web = config.web.clone();
347        let runner = Runner::new(config, setup).with_inbox(inbox.clone());
348        let args = remedy_ui_bridge_web::launch_args();
349        return remedy_ui_bridge_web::run_single_instance(&name, args, web, runner, move |a| {
350            instance::deliver(&inbox, a, None)
351        })
352        .map_err(|e| RunError::SingleInstance { reason: e.reason().to_owned() });
353    }
354    #[cfg(windows)]
355    remedy_ui_platform::bridge_windows::set_instance_wait(config.single_instance_wait);
356    #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))]
357    remedy_ui_platform::bridge_linux::set_drop_waits(config.drop_waits.0, config.drop_waits.1);
358    if config.single_instance {
359        let args: Vec<String> = std::env::args().skip(1).collect();
360        let wait = config
361            .single_instance_reply
362            .map(|reply| instance::ReplyWait { reply, exit: config.single_instance_exit });
363        match instance::claim(&config.name, &args, wait, inbox.clone())
364            .map_err(|reason| RunError::SingleInstance { reason })?
365        {
366            instance::Claimed::First => {}
367            // The running instance answered: this launch ends with its code.
368            instance::Claimed::HandedOver(Some(code)) => std::process::exit(code),
369            // Another instance runs and has our arguments.
370            instance::Claimed::HandedOver(None) => return Ok(()),
371        }
372    }
373    #[cfg(all(feature = "web", target_arch = "wasm32", target_os = "unknown"))]
374    let web = config.web.clone();
375    let runner = Runner::new(config, setup).with_inbox(inbox);
376    #[cfg(windows)]
377    {
378        remedy_ui_platform::bridge_windows::run(runner)
379            .map_err(|e| RunError::Bridge { reason: e.reason().to_owned() })
380    }
381    #[cfg(target_os = "macos")]
382    {
383        remedy_ui_platform::bridge_macos::run(runner)
384            .map_err(|e| RunError::Bridge { reason: e.reason().to_owned() })
385    }
386    #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))]
387    {
388        remedy_ui_platform::bridge_linux::run(runner)
389            .map_err(|e| RunError::Bridge { reason: e.reason().to_owned() })
390    }
391    // The activity comes from the app's `remedy_ui::android::main!` entry point.
392    #[cfg(target_os = "android")]
393    {
394        remedy_ui_platform::bridge_android::run(runner)
395            .map_err(|e| RunError::Bridge { reason: e.reason().to_owned() })
396    }
397    #[cfg(target_os = "ios")]
398    {
399        drop(runner);
400        Err(RunError::UnsupportedPlatform)
401    }
402    // A browser page: the app starts and this returns; the browser runs it from then on.
403    #[cfg(all(feature = "web", target_arch = "wasm32", target_os = "unknown"))]
404    {
405        remedy_ui_bridge_web::run_with(web, runner)
406            .map_err(|e| RunError::Bridge { reason: e.reason().to_owned() })
407    }
408    #[cfg(all(not(feature = "web"), target_arch = "wasm32", target_os = "unknown"))]
409    {
410        drop(runner);
411        Err(RunError::NeedsFeature { feature: "web" })
412    }
413    #[cfg(not(any(windows, unix, all(target_arch = "wasm32", target_os = "unknown"))))]
414    {
415        drop(runner);
416        Err(RunError::UnsupportedPlatform)
417    }
418}
419
420#[cfg(all(feature = "net", not(target_arch = "wasm32")))]
421struct KeepaliveOnExit(std::time::Duration);
422
423#[cfg(all(feature = "net", not(target_arch = "wasm32")))]
424impl Drop for KeepaliveOnExit {
425    fn drop(&mut self) {
426        remedy_ui_platform::services_net::finish_keepalive(self.0);
427    }
428}
429
430/// Opens a window showing every preview's variations side by side (devtools).
431#[cfg(feature = "devtools")]
432pub fn show_previews(previews: Vec<remedy_ui_widgets::devtools::Preview>) -> Result<(), RunError> {
433    let (theme, _) = remedy_ui_widgets::devtools::tool_style();
434    let config = AppConfig::new("RemedyUI previews").theme(theme, remedy_ui_themes_sheet);
435    run(config, move |app| {
436        app.open(WindowSpec::new("Previews").size(1100.0, 800.0), move |ui, _| {
437            let (theme, sheet) = remedy_ui_widgets::devtools::tool_style();
438            ui.set_theme(theme, sheet);
439            ui.root().child(remedy_ui_widgets::devtools::gallery(ui, &previews));
440        });
441    })
442}
443
444#[cfg(feature = "devtools")]
445fn remedy_ui_themes_sheet(_: &remedy_ui_core::style::Theme) -> remedy_ui_core::style::StyleSheet {
446    remedy_ui_widgets::devtools::tool_style().1
447}