Skip to main content

sui/
app.rs

1use crate::{
2    Application, CommandController, CommandCtx, CommandKey, EmbeddedSvgImageResource, FontHandle,
3    ImageHandle, RegisteredFont, RegisteredImage, Result, Runtime, UrlPolicy, Widget,
4    WindowBuilder, WindowIcon, WindowRenderOptions,
5};
6
7#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
8use crate::{CommandSender, CommandTarget};
9
10#[cfg(all(target_os = "android", feature = "mobile"))]
11use crate::AndroidApp;
12
13/// User-facing SUI application builder.
14///
15/// `App` is the recommended entrypoint for Rust applications. It keeps the
16/// public surface small while still producing the same runtime used by lower
17/// level integration and debug tools. The builder is intentionally owned and
18/// value-oriented: construct it on any thread, register resources up front,
19/// add windows, then build or run it on the UI thread.
20pub struct App {
21    application: Application,
22}
23
24impl Default for App {
25    fn default() -> Self {
26        Self {
27            application: Application::new(),
28        }
29    }
30}
31
32impl App {
33    /// Create an empty application with SUI's built-in widget resources
34    /// already registered.
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Add a window to the application.
40    pub fn window(mut self, window: Window) -> Self {
41        self.application = self.application.window(window.into_window_builder());
42        self
43    }
44
45    /// Attach an application-scoped service outside the widget tree.
46    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
47        self.application = self.application.controller(controller);
48        self
49    }
50
51    /// Decide which URLs `EventCtx::open_url` hands to the platform, in place
52    /// of the default that opens only `http`, `https`, and `mailto` URLs. See
53    /// [`UrlPolicy`].
54    pub fn url_policy(mut self, policy: UrlPolicy) -> Self {
55        self.application = self.application.url_policy(policy);
56        self
57    }
58
59    /// Subscribe an application-scoped typed command handler.
60    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
61    where
62        T: Send + Sync + 'static,
63        F: FnMut(&mut CommandCtx, &T) + 'static,
64    {
65        self.application = self.application.on_command(key, handler);
66        self
67    }
68
69    /// Add a window by title and root widget.
70    pub fn main_window<W>(self, title: impl Into<String>, root: W) -> Self
71    where
72        W: Widget + 'static,
73    {
74        self.window(Window::new(title).root(root))
75    }
76
77    /// Mutably access the application's resource registry.
78    pub fn resources(&mut self) -> ResourceRegistry<'_> {
79        ResourceRegistry {
80            application: &mut self.application,
81        }
82    }
83
84    /// Configure resources while preserving builder-style application setup.
85    pub fn with_resources(
86        mut self,
87        configure: impl FnOnce(&mut ResourceRegistry<'_>) -> Result<()>,
88    ) -> Result<Self> {
89        configure(&mut self.resources())?;
90        Ok(self)
91    }
92
93    /// Set initial render options for every window when the app starts.
94    pub fn render_options(mut self, options: WindowRenderOptions) -> Self {
95        self.application = self.application.with_window_render_options(options);
96        self
97    }
98
99    /// Configure renderer feathering when the WGPU renderer is enabled.
100    #[cfg(feature = "wgpu")]
101    pub fn feathering(mut self, enabled: bool) -> Self {
102        self.application = self.application.with_feathering_enabled(enabled);
103        self
104    }
105
106    /// Configure renderer feather width when the WGPU renderer is enabled.
107    #[cfg(feature = "wgpu")]
108    pub fn feather_width(mut self, width: f32) -> Self {
109        self.application = self.application.with_feather_width(width);
110        self
111    }
112
113    /// Attach a shared registry for app-owned WGPU textures rendered through
114    /// SUI's normal image composition path.
115    #[cfg(feature = "wgpu")]
116    pub fn external_texture_registry(
117        mut self,
118        registry: crate::WgpuExternalTextureRegistry,
119    ) -> Self {
120        self.application = self.application.with_external_texture_registry(registry);
121        self
122    }
123
124    /// Return the configured app-owned texture registry, if one is attached.
125    #[cfg(feature = "wgpu")]
126    pub fn configured_external_texture_registry(
127        &self,
128    ) -> Option<&crate::WgpuExternalTextureRegistry> {
129        self.application.external_texture_registry()
130    }
131
132    /// Build the runtime without starting a platform event loop.
133    ///
134    /// This is the right entrypoint for tests, headless rendering, embedding,
135    /// and custom platform integrations.
136    pub fn build(self) -> Result<Runtime> {
137        self.application.build()
138    }
139
140    /// Run the app on the default desktop/web platform event loop.
141    #[cfg(any(feature = "desktop", feature = "web"))]
142    pub fn run(self) -> Result<()> {
143        self.application.run()
144    }
145
146    /// Run the app with a configured desktop platform host.
147    ///
148    /// Optional native-surface libraries use this to attach platform
149    /// extensions while preserving the renderer configuration stored in this
150    /// application builder.
151    #[cfg(any(feature = "desktop", feature = "web"))]
152    pub fn run_with_platform(self, platform: crate::DesktopPlatform) -> Result<()> {
153        self.application.run_with_platform(platform)
154    }
155
156    /// Run the app and receive a cloneable, thread-safe command handle once the
157    /// event loop is ready.
158    ///
159    /// Background tasks normally send typed window/application commands. A bare
160    /// [`UiHandle::wake`] only schedules controller wake hooks and never creates
161    /// a widget event.
162    #[cfg(any(feature = "desktop", feature = "web"))]
163    pub fn run_with_handle(self, on_ready: impl FnOnce(UiHandle)) -> Result<()> {
164        self.application
165            .run_with(|commands| on_ready(UiHandle::new(commands)))
166    }
167
168    /// Start the app on the desktop without blocking and receive a UI command
169    /// handle once its event loop is ready.
170    ///
171    /// The caller drives the event loop by calling
172    /// [`PumpedDesktop::pump`](crate::PumpedDesktop::pump) repeatedly, which
173    /// lets another framework's event loop, such as a JavaScript runtime's,
174    /// own the main thread.
175    #[cfg(all(
176        feature = "desktop",
177        any(target_os = "windows", target_os = "macos", target_os = "linux")
178    ))]
179    pub fn start_pumped_with_handle(
180        self,
181        on_ready: impl FnOnce(UiHandle),
182    ) -> Result<crate::PumpedDesktop> {
183        self.application
184            .start_pumped_with(|commands| on_ready(UiHandle::new(commands)))
185    }
186
187    /// Start the app in the browser and receive a UI command handle once its
188    /// event loop is ready. The first window draws on `canvas`, or on the
189    /// page's element with id `sui-main-canvas`; `on_exit` runs when the app
190    /// exits, with the error it stopped with, if any.
191    #[cfg(all(feature = "web", target_arch = "wasm32"))]
192    pub fn start_web_with_handle(
193        self,
194        canvas: Option<crate::WebCanvas>,
195        on_ready: impl FnOnce(UiHandle),
196        on_exit: impl FnOnce(Result<()>) + 'static,
197    ) -> Result<()> {
198        self.application.start_web_with(
199            canvas,
200            |commands| on_ready(UiHandle::new(commands)),
201            on_exit,
202        )
203    }
204
205    /// Run with a configured platform host and receive a UI command handle
206    /// once its event loop is ready.
207    #[cfg(any(feature = "desktop", feature = "web"))]
208    pub fn run_with_platform_and_handle(
209        self,
210        platform: crate::DesktopPlatform,
211        on_ready: impl FnOnce(UiHandle),
212    ) -> Result<()> {
213        self.application
214            .run_with_platform_and_handle(platform, |commands| {
215                on_ready(UiHandle::new(commands));
216            })
217    }
218
219    #[cfg(all(target_os = "android", feature = "mobile"))]
220    pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
221        self.application.run_android(android_app)
222    }
223
224    #[cfg(all(target_os = "android", feature = "mobile"))]
225    pub fn run_android_with_handle(
226        self,
227        android_app: AndroidApp,
228        on_ready: impl FnOnce(UiHandle),
229    ) -> Result<()> {
230        self.application
231            .run_android_with(android_app, |commands| on_ready(UiHandle::new(commands)))
232    }
233
234    /// Convert back to the lower-level application builder.
235    ///
236    /// This is intended for debug tooling and migration code. Regular demos and
237    /// applications should prefer [`App`] methods directly.
238    pub fn into_application(self) -> Application {
239        self.application
240    }
241}
242
243impl From<App> for Application {
244    fn from(app: App) -> Self {
245        app.into_application()
246    }
247}
248
249/// User-facing window builder.
250pub struct Window {
251    builder: WindowBuilder,
252}
253
254impl Window {
255    /// Create a window with a title and the default SUI icon.
256    pub fn new(title: impl Into<String>) -> Self {
257        Self {
258            builder: WindowBuilder::new().title(title),
259        }
260    }
261
262    /// Set the window root widget.
263    pub fn root<W>(mut self, root: W) -> Self
264    where
265        W: Widget + 'static,
266    {
267        self.builder = self.builder.root(root);
268        self
269    }
270
271    /// Attach a controller owned by this window rather than by its widget tree.
272    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
273        self.builder = self.builder.controller(controller);
274        self
275    }
276
277    /// Subscribe a lifecycle-safe handler owned by this window.
278    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
279    where
280        T: Send + Sync + 'static,
281        F: FnMut(&mut CommandCtx, &T) + 'static,
282    {
283        self.builder = self.builder.on_command(key, handler);
284        self
285    }
286
287    /// Set a platform icon.
288    pub fn icon(mut self, icon: WindowIcon) -> Self {
289        self.builder = self.builder.icon(icon);
290        self
291    }
292
293    /// Set an SVG platform icon.
294    pub fn icon_svg(mut self, svg: impl Into<Vec<u8>>) -> Self {
295        self.builder = self.builder.icon_svg(svg);
296        self
297    }
298
299    /// Remove the platform icon.
300    pub fn without_icon(mut self) -> Self {
301        self.builder = self.builder.without_icon();
302        self
303    }
304
305    /// Request an initial logical client size for the native window.
306    pub fn initial_size(mut self, size: crate::Size) -> Self {
307        self.builder = self.builder.initial_size(size);
308        self
309    }
310
311    /// Request an initial physical desktop position for the native window.
312    ///
313    /// Desktop hosts may adjust or ignore an unsafe position after monitor
314    /// topology changes.
315    pub fn initial_position(mut self, position: crate::Point) -> Self {
316        self.builder = self.builder.initial_position(position);
317        self
318    }
319
320    pub(crate) fn into_window_builder(self) -> WindowBuilder {
321        self.builder
322    }
323}
324
325/// Resource registration facade for user code.
326///
327/// Resource handles are stable, cheap to copy, and safe to store in widget
328/// state. Register resources during app construction and pass handles through
329/// UI state instead of moving raw image/font blobs through render paths.
330pub struct ResourceRegistry<'a> {
331    application: &'a mut Application,
332}
333
334impl ResourceRegistry<'_> {
335    /// Register a font with an explicit stable handle.
336    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
337        self.application.register_font(handle, font)
338    }
339
340    /// Register a TrueType, OpenType, WOFF, or WOFF2 font and allocate a
341    /// stable handle. Fails when the data is not such a font.
342    pub fn font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
343        self.application.register_font_bytes(data)
344    }
345
346    /// Register an image with an explicit stable handle.
347    pub fn image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
348        self.application.register_image(handle, image)
349    }
350
351    /// Register RGBA8 pixels and allocate an image handle.
352    pub fn rgba_image(
353        &mut self,
354        width: u32,
355        height: u32,
356        data: impl Into<Vec<u8>>,
357    ) -> Result<ImageHandle> {
358        self.application.register_rgba_image(width, height, data)
359    }
360
361    /// Register SVG bytes at their intrinsic size and allocate an image handle.
362    pub fn svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
363        self.application.register_svg_image(data)
364    }
365
366    /// Register SVG bytes at their intrinsic size with an explicit handle.
367    pub fn svg_image_with_handle(
368        &mut self,
369        handle: ImageHandle,
370        data: impl AsRef<[u8]>,
371    ) -> Result<()> {
372        self.application
373            .register_svg_image_with_handle(handle, data)
374    }
375
376    /// Rasterize SVG bytes at an explicit size and allocate an image handle.
377    pub fn svg_image_at_size(
378        &mut self,
379        width: u32,
380        height: u32,
381        data: impl AsRef<[u8]>,
382    ) -> Result<ImageHandle> {
383        self.application
384            .register_svg_image_at_size(width, height, data)
385    }
386
387    /// Rasterize SVG bytes at an explicit size and handle.
388    pub fn svg_image_at_size_with_handle(
389        &mut self,
390        handle: ImageHandle,
391        width: u32,
392        height: u32,
393        data: impl AsRef<[u8]>,
394    ) -> Result<()> {
395        self.application
396            .register_svg_image_at_size_with_handle(handle, width, height, data)
397    }
398
399    /// Register one compile-time embedded SVG resource.
400    pub fn embedded_svg_image(&mut self, resource: EmbeddedSvgImageResource) -> Result<()> {
401        self.application.register_embedded_svg_image(resource)
402    }
403
404    /// Register multiple compile-time embedded SVG resources.
405    pub fn embedded_svg_images(
406        &mut self,
407        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
408    ) -> Result<()> {
409        self.application.register_embedded_svg_images(resources)
410    }
411}
412
413/// Cloneable, thread-safe UI command handle for background work.
414///
415/// Each send returns the command's sequence number, as
416/// [`CommandSender`]'s do.
417#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
418#[derive(Clone)]
419pub struct UiHandle {
420    commands: CommandSender,
421}
422
423#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
424impl UiHandle {
425    #[cfg_attr(
426        not(any(
427            feature = "desktop",
428            feature = "web",
429            all(target_os = "android", feature = "mobile")
430        )),
431        allow(dead_code)
432    )]
433    fn new(commands: CommandSender) -> Self {
434        Self { commands }
435    }
436
437    /// Schedule controller wake hooks without synthesizing a widget event.
438    pub fn wake(&self) {
439        self.commands.wake();
440    }
441
442    /// Ask the application to exit. `App::run` returns once the platform
443    /// loop finishes its current turn; this may be called from any thread.
444    pub fn request_exit(&self) {
445        self.commands.request_exit();
446    }
447
448    pub fn send<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T) -> u64
449    where
450        T: Send + Sync + 'static,
451    {
452        self.commands.send(target, key, payload)
453    }
454
455    pub fn send_widget<T>(
456        &self,
457        window_id: crate::WindowId,
458        widget_id: crate::WidgetId,
459        key: CommandKey<T>,
460        payload: T,
461    ) -> u64
462    where
463        T: Send + Sync + 'static,
464    {
465        self.commands
466            .send_widget(window_id, widget_id, key, payload)
467    }
468
469    pub fn send_focused<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T) -> u64
470    where
471        T: Send + Sync + 'static,
472    {
473        self.commands.send_focused(window_id, key, payload)
474    }
475
476    pub fn send_window<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T) -> u64
477    where
478        T: Send + Sync + 'static,
479    {
480        self.commands.send_window(window_id, key, payload)
481    }
482
483    pub fn send_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
484    where
485        T: Send + Sync + 'static,
486    {
487        self.commands.send_application(key, payload)
488    }
489
490    pub fn broadcast_window<T>(
491        &self,
492        window_id: crate::WindowId,
493        key: CommandKey<T>,
494        payload: T,
495    ) -> u64
496    where
497        T: Send + Sync + 'static,
498    {
499        self.commands.broadcast_window(window_id, key, payload)
500    }
501
502    pub fn broadcast_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
503    where
504        T: Send + Sync + 'static,
505    {
506        self.commands.broadcast_application(key, payload)
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513    use crate::{Constraints, MeasureCtx, Size};
514
515    struct TestWidget;
516
517    impl Widget for TestWidget {
518        fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
519            Size::new(32.0, 24.0)
520        }
521    }
522
523    #[test]
524    #[cfg(feature = "wgpu")]
525    fn application_uses_plain_renderer_configuration_defaults() {
526        let app = Application::new();
527        let options = sui_render_wgpu::FeatheringOptions::default();
528        assert_eq!(app.feathering_enabled(), options.enabled);
529        assert_eq!(app.feather_width(), options.width);
530    }
531
532    #[test]
533    fn app_builds_window_after_registering_resources() -> Result<()> {
534        let mut app = App::new();
535        let image = {
536            let mut resources = app.resources();
537            resources.rgba_image(1, 1, vec![255, 0, 0, 255])?
538        };
539
540        let runtime = app
541            .main_window(format!("Image {image:?}"), TestWidget)
542            .build()?;
543
544        assert_eq!(runtime.window_ids().len(), 1);
545        Ok(())
546    }
547
548    #[test]
549    fn app_with_resources_preserves_builder_style() -> Result<()> {
550        let runtime = App::new()
551            .with_resources(|resources| {
552                resources.rgba_image(1, 1, vec![0, 255, 0, 255])?;
553                Ok(())
554            })?
555            .window(Window::new("Resource setup").root(TestWidget))
556            .build()?;
557
558        assert_eq!(runtime.window_ids().len(), 1);
559        Ok(())
560    }
561}