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 with a configured desktop platform host.
139    ///
140    /// Optional native-surface libraries use this to attach platform
141    /// extensions while preserving the renderer configuration stored in this
142    /// application builder.
143    #[cfg(any(feature = "desktop", feature = "web"))]
144    pub fn run_with_platform(self, platform: crate::DesktopPlatform) -> Result<()> {
145        self.application.run_with_platform(platform)
146    }
147
148    /// Run the app and receive a cloneable, thread-safe command handle once the
149    /// event loop is ready.
150    ///
151    /// Background tasks normally send typed window/application commands. A bare
152    /// [`UiHandle::wake`] only schedules controller wake hooks and never creates
153    /// a widget event.
154    #[cfg(any(feature = "desktop", feature = "web"))]
155    pub fn run_with_handle(self, on_ready: impl FnOnce(UiHandle)) -> Result<()> {
156        self.application
157            .run_with(|commands| on_ready(UiHandle::new(commands)))
158    }
159
160    /// Run with a configured platform host and receive a UI command handle
161    /// once its event loop is ready.
162    #[cfg(any(feature = "desktop", feature = "web"))]
163    pub fn run_with_platform_and_handle(
164        self,
165        platform: crate::DesktopPlatform,
166        on_ready: impl FnOnce(UiHandle),
167    ) -> Result<()> {
168        self.application
169            .run_with_platform_and_handle(platform, |commands| {
170                on_ready(UiHandle::new(commands));
171            })
172    }
173
174    #[cfg(all(target_os = "android", feature = "mobile"))]
175    pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
176        self.application.run_android(android_app)
177    }
178
179    #[cfg(all(target_os = "android", feature = "mobile"))]
180    pub fn run_android_with_handle(
181        self,
182        android_app: AndroidApp,
183        on_ready: impl FnOnce(UiHandle),
184    ) -> Result<()> {
185        self.application
186            .run_android_with(android_app, |commands| on_ready(UiHandle::new(commands)))
187    }
188
189    /// Convert back to the lower-level application builder.
190    ///
191    /// This is intended for debug tooling and migration code. Regular demos and
192    /// applications should prefer [`App`] methods directly.
193    pub fn into_application(self) -> Application {
194        self.application
195    }
196}
197
198impl From<App> for Application {
199    fn from(app: App) -> Self {
200        app.into_application()
201    }
202}
203
204/// User-facing window builder.
205pub struct Window {
206    builder: WindowBuilder,
207}
208
209impl Window {
210    /// Create a window with a title and the default SUI icon.
211    pub fn new(title: impl Into<String>) -> Self {
212        Self {
213            builder: WindowBuilder::new().title(title),
214        }
215    }
216
217    /// Set the window root widget.
218    pub fn root<W>(mut self, root: W) -> Self
219    where
220        W: Widget + 'static,
221    {
222        self.builder = self.builder.root(root);
223        self
224    }
225
226    /// Attach a controller owned by this window rather than by its widget tree.
227    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
228        self.builder = self.builder.controller(controller);
229        self
230    }
231
232    /// Subscribe a lifecycle-safe handler owned by this window.
233    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
234    where
235        T: Send + Sync + 'static,
236        F: FnMut(&mut CommandCtx, &T) + 'static,
237    {
238        self.builder = self.builder.on_command(key, handler);
239        self
240    }
241
242    /// Set a platform icon.
243    pub fn icon(mut self, icon: WindowIcon) -> Self {
244        self.builder = self.builder.icon(icon);
245        self
246    }
247
248    /// Set an SVG platform icon.
249    pub fn icon_svg(mut self, svg: impl Into<Vec<u8>>) -> Self {
250        self.builder = self.builder.icon_svg(svg);
251        self
252    }
253
254    /// Remove the platform icon.
255    pub fn without_icon(mut self) -> Self {
256        self.builder = self.builder.without_icon();
257        self
258    }
259
260    /// Request an initial logical client size for the native window.
261    pub fn initial_size(mut self, size: crate::Size) -> Self {
262        self.builder = self.builder.initial_size(size);
263        self
264    }
265
266    /// Request an initial physical desktop position for the native window.
267    ///
268    /// Desktop hosts may adjust or ignore an unsafe position after monitor
269    /// topology changes.
270    pub fn initial_position(mut self, position: crate::Point) -> Self {
271        self.builder = self.builder.initial_position(position);
272        self
273    }
274
275    pub(crate) fn into_window_builder(self) -> WindowBuilder {
276        self.builder
277    }
278}
279
280/// Resource registration facade for user code.
281///
282/// Resource handles are stable, cheap to copy, and safe to store in widget
283/// state. Register resources during app construction and pass handles through
284/// UI state instead of moving raw image/font blobs through render paths.
285pub struct ResourceRegistry<'a> {
286    application: &'a mut Application,
287}
288
289impl ResourceRegistry<'_> {
290    /// Register a font with an explicit stable handle.
291    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
292        self.application.register_font(handle, font)
293    }
294
295    /// Register font bytes and allocate a stable handle.
296    pub fn font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
297        self.application.register_font_bytes(data)
298    }
299
300    /// Register an image with an explicit stable handle.
301    pub fn image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
302        self.application.register_image(handle, image)
303    }
304
305    /// Register RGBA8 pixels and allocate an image handle.
306    pub fn rgba_image(
307        &mut self,
308        width: u32,
309        height: u32,
310        data: impl Into<Vec<u8>>,
311    ) -> Result<ImageHandle> {
312        self.application.register_rgba_image(width, height, data)
313    }
314
315    /// Register SVG bytes at their intrinsic size and allocate an image handle.
316    pub fn svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
317        self.application.register_svg_image(data)
318    }
319
320    /// Register SVG bytes at their intrinsic size with an explicit handle.
321    pub fn svg_image_with_handle(
322        &mut self,
323        handle: ImageHandle,
324        data: impl AsRef<[u8]>,
325    ) -> Result<()> {
326        self.application
327            .register_svg_image_with_handle(handle, data)
328    }
329
330    /// Rasterize SVG bytes at an explicit size and allocate an image handle.
331    pub fn svg_image_at_size(
332        &mut self,
333        width: u32,
334        height: u32,
335        data: impl AsRef<[u8]>,
336    ) -> Result<ImageHandle> {
337        self.application
338            .register_svg_image_at_size(width, height, data)
339    }
340
341    /// Rasterize SVG bytes at an explicit size and handle.
342    pub fn svg_image_at_size_with_handle(
343        &mut self,
344        handle: ImageHandle,
345        width: u32,
346        height: u32,
347        data: impl AsRef<[u8]>,
348    ) -> Result<()> {
349        self.application
350            .register_svg_image_at_size_with_handle(handle, width, height, data)
351    }
352
353    /// Register one compile-time embedded SVG resource.
354    pub fn embedded_svg_image(&mut self, resource: EmbeddedSvgImageResource) -> Result<()> {
355        self.application.register_embedded_svg_image(resource)
356    }
357
358    /// Register multiple compile-time embedded SVG resources.
359    pub fn embedded_svg_images(
360        &mut self,
361        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
362    ) -> Result<()> {
363        self.application.register_embedded_svg_images(resources)
364    }
365}
366
367/// Cloneable, thread-safe UI command handle for background work.
368#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
369#[derive(Clone)]
370pub struct UiHandle {
371    commands: CommandSender,
372}
373
374#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
375impl UiHandle {
376    #[cfg_attr(
377        not(any(
378            feature = "desktop",
379            feature = "web",
380            all(target_os = "android", feature = "mobile")
381        )),
382        allow(dead_code)
383    )]
384    fn new(commands: CommandSender) -> Self {
385        Self { commands }
386    }
387
388    /// Schedule controller wake hooks without synthesizing a widget event.
389    pub fn wake(&self) {
390        self.commands.wake();
391    }
392
393    pub fn send<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T)
394    where
395        T: Send + Sync + 'static,
396    {
397        self.commands.send(target, key, payload);
398    }
399
400    pub fn send_widget<T>(
401        &self,
402        window_id: crate::WindowId,
403        widget_id: crate::WidgetId,
404        key: CommandKey<T>,
405        payload: T,
406    ) where
407        T: Send + Sync + 'static,
408    {
409        self.commands
410            .send_widget(window_id, widget_id, key, payload);
411    }
412
413    pub fn send_focused<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T)
414    where
415        T: Send + Sync + 'static,
416    {
417        self.commands.send_focused(window_id, key, payload);
418    }
419
420    pub fn send_window<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T)
421    where
422        T: Send + Sync + 'static,
423    {
424        self.commands.send_window(window_id, key, payload);
425    }
426
427    pub fn send_application<T>(&self, key: CommandKey<T>, payload: T)
428    where
429        T: Send + Sync + 'static,
430    {
431        self.commands.send_application(key, payload);
432    }
433
434    pub fn broadcast_window<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T)
435    where
436        T: Send + Sync + 'static,
437    {
438        self.commands.broadcast_window(window_id, key, payload);
439    }
440
441    pub fn broadcast_application<T>(&self, key: CommandKey<T>, payload: T)
442    where
443        T: Send + Sync + 'static,
444    {
445        self.commands.broadcast_application(key, payload);
446    }
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452    use crate::{Constraints, MeasureCtx, Size};
453
454    struct TestWidget;
455
456    impl Widget for TestWidget {
457        fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
458            Size::new(32.0, 24.0)
459        }
460    }
461
462    #[test]
463    #[cfg(feature = "wgpu")]
464    fn application_uses_plain_renderer_configuration_defaults() {
465        let app = Application::new();
466        let options = sui_render_wgpu::FeatheringOptions::default();
467        assert_eq!(app.feathering_enabled(), options.enabled);
468        assert_eq!(app.feather_width(), options.width);
469    }
470
471    #[test]
472    fn app_builds_window_after_registering_resources() -> Result<()> {
473        let mut app = App::new();
474        let image = {
475            let mut resources = app.resources();
476            resources.rgba_image(1, 1, vec![255, 0, 0, 255])?
477        };
478
479        let runtime = app
480            .main_window(format!("Image {image:?}"), TestWidget)
481            .build()?;
482
483        assert_eq!(runtime.window_ids().len(), 1);
484        Ok(())
485    }
486
487    #[test]
488    fn app_with_resources_preserves_builder_style() -> Result<()> {
489        let runtime = App::new()
490            .with_resources(|resources| {
491                resources.rgba_image(1, 1, vec![0, 255, 0, 255])?;
492                Ok(())
493            })?
494            .window(Window::new("Resource setup").root(TestWidget))
495            .build()?;
496
497        assert_eq!(runtime.window_ids().len(), 1);
498        Ok(())
499    }
500}