Skip to main content

sui/
app.rs

1use crate::{
2    Application, CommandController, CommandCtx, CommandKey, EmbeddedSvgImageResource, FontHandle,
3    ImageHandle, RegisteredFont, RegisteredImage, Result, Runtime, Widget, WindowBuilder,
4    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    /// Subscribe an application-scoped typed command handler.
52    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
53    where
54        T: Send + Sync + 'static,
55        F: FnMut(&mut CommandCtx, &T) + 'static,
56    {
57        self.application = self.application.on_command(key, handler);
58        self
59    }
60
61    /// Add a window by title and root widget.
62    pub fn main_window<W>(self, title: impl Into<String>, root: W) -> Self
63    where
64        W: Widget + 'static,
65    {
66        self.window(Window::new(title).root(root))
67    }
68
69    /// Mutably access the application's resource registry.
70    pub fn resources(&mut self) -> ResourceRegistry<'_> {
71        ResourceRegistry {
72            application: &mut self.application,
73        }
74    }
75
76    /// Configure resources while preserving builder-style application setup.
77    pub fn with_resources(
78        mut self,
79        configure: impl FnOnce(&mut ResourceRegistry<'_>) -> Result<()>,
80    ) -> Result<Self> {
81        configure(&mut self.resources())?;
82        Ok(self)
83    }
84
85    /// Set initial render options for every window when the app starts.
86    pub fn render_options(mut self, options: WindowRenderOptions) -> Self {
87        self.application = self.application.with_window_render_options(options);
88        self
89    }
90
91    /// Configure renderer feathering when the WGPU renderer is enabled.
92    #[cfg(feature = "wgpu")]
93    pub fn feathering(mut self, enabled: bool) -> Self {
94        self.application = self.application.with_feathering_enabled(enabled);
95        self
96    }
97
98    /// Configure renderer feather width when the WGPU renderer is enabled.
99    #[cfg(feature = "wgpu")]
100    pub fn feather_width(mut self, width: f32) -> Self {
101        self.application = self.application.with_feather_width(width);
102        self
103    }
104
105    /// Attach a shared registry for app-owned WGPU textures rendered through
106    /// SUI's normal image composition path.
107    #[cfg(feature = "wgpu")]
108    pub fn external_texture_registry(
109        mut self,
110        registry: crate::WgpuExternalTextureRegistry,
111    ) -> Self {
112        self.application = self.application.with_external_texture_registry(registry);
113        self
114    }
115
116    /// Return the configured app-owned texture registry, if one is attached.
117    #[cfg(feature = "wgpu")]
118    pub fn configured_external_texture_registry(
119        &self,
120    ) -> Option<&crate::WgpuExternalTextureRegistry> {
121        self.application.external_texture_registry()
122    }
123
124    /// Build the runtime without starting a platform event loop.
125    ///
126    /// This is the right entrypoint for tests, headless rendering, embedding,
127    /// and custom platform integrations.
128    pub fn build(self) -> Result<Runtime> {
129        self.application.build()
130    }
131
132    /// Run the app on the default desktop/web platform event loop.
133    #[cfg(any(feature = "desktop", feature = "web"))]
134    pub fn run(self) -> Result<()> {
135        self.application.run()
136    }
137
138    /// Run the app and receive a cloneable, thread-safe command handle once the
139    /// event loop is ready.
140    ///
141    /// Background tasks normally send typed window/application commands. A bare
142    /// [`UiHandle::wake`] only schedules controller wake hooks and never creates
143    /// a widget event.
144    #[cfg(any(feature = "desktop", feature = "web"))]
145    pub fn run_with_handle(self, on_ready: impl FnOnce(UiHandle)) -> Result<()> {
146        self.application
147            .run_with(|commands| on_ready(UiHandle::new(commands)))
148    }
149
150    #[cfg(all(target_os = "android", feature = "mobile"))]
151    pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
152        self.application.run_android(android_app)
153    }
154
155    #[cfg(all(target_os = "android", feature = "mobile"))]
156    pub fn run_android_with_handle(
157        self,
158        android_app: AndroidApp,
159        on_ready: impl FnOnce(UiHandle),
160    ) -> Result<()> {
161        self.application
162            .run_android_with(android_app, |commands| on_ready(UiHandle::new(commands)))
163    }
164
165    /// Convert back to the lower-level application builder.
166    ///
167    /// This is intended for debug tooling and migration code. Regular demos and
168    /// applications should prefer [`App`] methods directly.
169    pub fn into_application(self) -> Application {
170        self.application
171    }
172}
173
174impl From<App> for Application {
175    fn from(app: App) -> Self {
176        app.into_application()
177    }
178}
179
180/// User-facing window builder.
181pub struct Window {
182    builder: WindowBuilder,
183}
184
185impl Window {
186    /// Create a window with a title and the default SUI icon.
187    pub fn new(title: impl Into<String>) -> Self {
188        Self {
189            builder: WindowBuilder::new().title(title),
190        }
191    }
192
193    /// Set the window root widget.
194    pub fn root<W>(mut self, root: W) -> Self
195    where
196        W: Widget + 'static,
197    {
198        self.builder = self.builder.root(root);
199        self
200    }
201
202    /// Attach a controller owned by this window rather than by its widget tree.
203    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
204        self.builder = self.builder.controller(controller);
205        self
206    }
207
208    /// Subscribe a lifecycle-safe handler owned by this window.
209    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
210    where
211        T: Send + Sync + 'static,
212        F: FnMut(&mut CommandCtx, &T) + 'static,
213    {
214        self.builder = self.builder.on_command(key, handler);
215        self
216    }
217
218    /// Set a platform icon.
219    pub fn icon(mut self, icon: WindowIcon) -> Self {
220        self.builder = self.builder.icon(icon);
221        self
222    }
223
224    /// Set an SVG platform icon.
225    pub fn icon_svg(mut self, svg: impl Into<Vec<u8>>) -> Self {
226        self.builder = self.builder.icon_svg(svg);
227        self
228    }
229
230    /// Remove the platform icon.
231    pub fn without_icon(mut self) -> Self {
232        self.builder = self.builder.without_icon();
233        self
234    }
235
236    pub(crate) fn into_window_builder(self) -> WindowBuilder {
237        self.builder
238    }
239}
240
241/// Resource registration facade for user code.
242///
243/// Resource handles are stable, cheap to copy, and safe to store in widget
244/// state. Register resources during app construction and pass handles through
245/// UI state instead of moving raw image/font blobs through render paths.
246pub struct ResourceRegistry<'a> {
247    application: &'a mut Application,
248}
249
250impl ResourceRegistry<'_> {
251    /// Register a font with an explicit stable handle.
252    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
253        self.application.register_font(handle, font)
254    }
255
256    /// Register font bytes and allocate a stable handle.
257    pub fn font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
258        self.application.register_font_bytes(data)
259    }
260
261    /// Register an image with an explicit stable handle.
262    pub fn image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
263        self.application.register_image(handle, image)
264    }
265
266    /// Register RGBA8 pixels and allocate an image handle.
267    pub fn rgba_image(
268        &mut self,
269        width: u32,
270        height: u32,
271        data: impl Into<Vec<u8>>,
272    ) -> Result<ImageHandle> {
273        self.application.register_rgba_image(width, height, data)
274    }
275
276    /// Register SVG bytes at their intrinsic size and allocate an image handle.
277    pub fn svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
278        self.application.register_svg_image(data)
279    }
280
281    /// Register SVG bytes at their intrinsic size with an explicit handle.
282    pub fn svg_image_with_handle(
283        &mut self,
284        handle: ImageHandle,
285        data: impl AsRef<[u8]>,
286    ) -> Result<()> {
287        self.application
288            .register_svg_image_with_handle(handle, data)
289    }
290
291    /// Rasterize SVG bytes at an explicit size and allocate an image handle.
292    pub fn svg_image_at_size(
293        &mut self,
294        width: u32,
295        height: u32,
296        data: impl AsRef<[u8]>,
297    ) -> Result<ImageHandle> {
298        self.application
299            .register_svg_image_at_size(width, height, data)
300    }
301
302    /// Rasterize SVG bytes at an explicit size and handle.
303    pub fn svg_image_at_size_with_handle(
304        &mut self,
305        handle: ImageHandle,
306        width: u32,
307        height: u32,
308        data: impl AsRef<[u8]>,
309    ) -> Result<()> {
310        self.application
311            .register_svg_image_at_size_with_handle(handle, width, height, data)
312    }
313
314    /// Register one compile-time embedded SVG resource.
315    pub fn embedded_svg_image(&mut self, resource: EmbeddedSvgImageResource) -> Result<()> {
316        self.application.register_embedded_svg_image(resource)
317    }
318
319    /// Register multiple compile-time embedded SVG resources.
320    pub fn embedded_svg_images(
321        &mut self,
322        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
323    ) -> Result<()> {
324        self.application.register_embedded_svg_images(resources)
325    }
326}
327
328/// Cloneable, thread-safe UI command handle for background work.
329#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
330#[derive(Clone)]
331pub struct UiHandle {
332    commands: CommandSender,
333}
334
335#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
336impl UiHandle {
337    #[cfg_attr(
338        not(any(
339            feature = "desktop",
340            feature = "web",
341            all(target_os = "android", feature = "mobile")
342        )),
343        allow(dead_code)
344    )]
345    fn new(commands: CommandSender) -> Self {
346        Self { commands }
347    }
348
349    /// Schedule controller wake hooks without synthesizing a widget event.
350    pub fn wake(&self) {
351        self.commands.wake();
352    }
353
354    pub fn send<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T)
355    where
356        T: Send + Sync + 'static,
357    {
358        self.commands.send(target, key, payload);
359    }
360
361    pub fn send_widget<T>(
362        &self,
363        window_id: crate::WindowId,
364        widget_id: crate::WidgetId,
365        key: CommandKey<T>,
366        payload: T,
367    ) where
368        T: Send + Sync + 'static,
369    {
370        self.commands
371            .send_widget(window_id, widget_id, key, payload);
372    }
373
374    pub fn send_focused<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T)
375    where
376        T: Send + Sync + 'static,
377    {
378        self.commands.send_focused(window_id, key, payload);
379    }
380
381    pub fn send_window<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T)
382    where
383        T: Send + Sync + 'static,
384    {
385        self.commands.send_window(window_id, key, payload);
386    }
387
388    pub fn send_application<T>(&self, key: CommandKey<T>, payload: T)
389    where
390        T: Send + Sync + 'static,
391    {
392        self.commands.send_application(key, payload);
393    }
394
395    pub fn broadcast_window<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T)
396    where
397        T: Send + Sync + 'static,
398    {
399        self.commands.broadcast_window(window_id, key, payload);
400    }
401
402    pub fn broadcast_application<T>(&self, key: CommandKey<T>, payload: T)
403    where
404        T: Send + Sync + 'static,
405    {
406        self.commands.broadcast_application(key, payload);
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413    use crate::{Constraints, MeasureCtx, Size};
414
415    struct TestWidget;
416
417    impl Widget for TestWidget {
418        fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
419            Size::new(32.0, 24.0)
420        }
421    }
422
423    #[test]
424    fn app_builds_window_after_registering_resources() -> Result<()> {
425        let mut app = App::new();
426        let image = {
427            let mut resources = app.resources();
428            resources.rgba_image(1, 1, vec![255, 0, 0, 255])?
429        };
430
431        let runtime = app
432            .main_window(format!("Image {image:?}"), TestWidget)
433            .build()?;
434
435        assert_eq!(runtime.window_ids().len(), 1);
436        Ok(())
437    }
438
439    #[test]
440    fn app_with_resources_preserves_builder_style() -> Result<()> {
441        let runtime = App::new()
442            .with_resources(|resources| {
443                resources.rgba_image(1, 1, vec![0, 255, 0, 255])?;
444                Ok(())
445            })?
446            .window(Window::new("Resource setup").root(TestWidget))
447            .build()?;
448
449        assert_eq!(runtime.window_ids().len(), 1);
450        Ok(())
451    }
452}