sinomo-ui 0.4.1

Public Rust facade for the SUI workspace.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use crate::{
    Application, CommandController, CommandCtx, CommandKey, EmbeddedSvgImageResource, FontHandle,
    ImageHandle, RegisteredFont, RegisteredImage, Result, Runtime, Widget, WindowBuilder,
    WindowIcon, WindowRenderOptions,
};

#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
use crate::{CommandSender, CommandTarget};

#[cfg(all(target_os = "android", feature = "mobile"))]
use crate::AndroidApp;

/// User-facing SUI application builder.
///
/// `App` is the recommended entrypoint for Rust applications. It keeps the
/// public surface small while still producing the same runtime used by lower
/// level integration and debug tools. The builder is intentionally owned and
/// value-oriented: construct it on any thread, register resources up front,
/// add windows, then build or run it on the UI thread.
pub struct App {
    application: Application,
}

impl Default for App {
    fn default() -> Self {
        Self {
            application: Application::new(),
        }
    }
}

impl App {
    /// Create an empty application with SUI's built-in widget resources
    /// already registered.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a window to the application.
    pub fn window(mut self, window: Window) -> Self {
        self.application = self.application.window(window.into_window_builder());
        self
    }

    /// Attach an application-scoped service outside the widget tree.
    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
        self.application = self.application.controller(controller);
        self
    }

    /// Subscribe an application-scoped typed command handler.
    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
    where
        T: Send + Sync + 'static,
        F: FnMut(&mut CommandCtx, &T) + 'static,
    {
        self.application = self.application.on_command(key, handler);
        self
    }

    /// Add a window by title and root widget.
    pub fn main_window<W>(self, title: impl Into<String>, root: W) -> Self
    where
        W: Widget + 'static,
    {
        self.window(Window::new(title).root(root))
    }

    /// Mutably access the application's resource registry.
    pub fn resources(&mut self) -> ResourceRegistry<'_> {
        ResourceRegistry {
            application: &mut self.application,
        }
    }

    /// Configure resources while preserving builder-style application setup.
    pub fn with_resources(
        mut self,
        configure: impl FnOnce(&mut ResourceRegistry<'_>) -> Result<()>,
    ) -> Result<Self> {
        configure(&mut self.resources())?;
        Ok(self)
    }

    /// Set initial render options for every window when the app starts.
    pub fn render_options(mut self, options: WindowRenderOptions) -> Self {
        self.application = self.application.with_window_render_options(options);
        self
    }

    /// Configure renderer feathering when the WGPU renderer is enabled.
    #[cfg(feature = "wgpu")]
    pub fn feathering(mut self, enabled: bool) -> Self {
        self.application = self.application.with_feathering_enabled(enabled);
        self
    }

    /// Configure renderer feather width when the WGPU renderer is enabled.
    #[cfg(feature = "wgpu")]
    pub fn feather_width(mut self, width: f32) -> Self {
        self.application = self.application.with_feather_width(width);
        self
    }

    /// Attach a shared registry for app-owned WGPU textures rendered through
    /// SUI's normal image composition path.
    #[cfg(feature = "wgpu")]
    pub fn external_texture_registry(
        mut self,
        registry: crate::WgpuExternalTextureRegistry,
    ) -> Self {
        self.application = self.application.with_external_texture_registry(registry);
        self
    }

    /// Return the configured app-owned texture registry, if one is attached.
    #[cfg(feature = "wgpu")]
    pub fn configured_external_texture_registry(
        &self,
    ) -> Option<&crate::WgpuExternalTextureRegistry> {
        self.application.external_texture_registry()
    }

    /// Build the runtime without starting a platform event loop.
    ///
    /// This is the right entrypoint for tests, headless rendering, embedding,
    /// and custom platform integrations.
    pub fn build(self) -> Result<Runtime> {
        self.application.build()
    }

    /// Run the app on the default desktop/web platform event loop.
    #[cfg(any(feature = "desktop", feature = "web"))]
    pub fn run(self) -> Result<()> {
        self.application.run()
    }

    /// Run the app with a configured desktop platform host.
    ///
    /// Optional native-surface libraries use this to attach platform
    /// extensions while preserving the renderer configuration stored in this
    /// application builder.
    #[cfg(any(feature = "desktop", feature = "web"))]
    pub fn run_with_platform(self, platform: crate::DesktopPlatform) -> Result<()> {
        self.application.run_with_platform(platform)
    }

    /// Run the app and receive a cloneable, thread-safe command handle once the
    /// event loop is ready.
    ///
    /// Background tasks normally send typed window/application commands. A bare
    /// [`UiHandle::wake`] only schedules controller wake hooks and never creates
    /// a widget event.
    #[cfg(any(feature = "desktop", feature = "web"))]
    pub fn run_with_handle(self, on_ready: impl FnOnce(UiHandle)) -> Result<()> {
        self.application
            .run_with(|commands| on_ready(UiHandle::new(commands)))
    }

    /// Run with a configured platform host and receive a UI command handle
    /// once its event loop is ready.
    #[cfg(any(feature = "desktop", feature = "web"))]
    pub fn run_with_platform_and_handle(
        self,
        platform: crate::DesktopPlatform,
        on_ready: impl FnOnce(UiHandle),
    ) -> Result<()> {
        self.application
            .run_with_platform_and_handle(platform, |commands| {
                on_ready(UiHandle::new(commands));
            })
    }

    #[cfg(all(target_os = "android", feature = "mobile"))]
    pub fn run_android(self, android_app: AndroidApp) -> Result<()> {
        self.application.run_android(android_app)
    }

    #[cfg(all(target_os = "android", feature = "mobile"))]
    pub fn run_android_with_handle(
        self,
        android_app: AndroidApp,
        on_ready: impl FnOnce(UiHandle),
    ) -> Result<()> {
        self.application
            .run_android_with(android_app, |commands| on_ready(UiHandle::new(commands)))
    }

    /// Convert back to the lower-level application builder.
    ///
    /// This is intended for debug tooling and migration code. Regular demos and
    /// applications should prefer [`App`] methods directly.
    pub fn into_application(self) -> Application {
        self.application
    }
}

impl From<App> for Application {
    fn from(app: App) -> Self {
        app.into_application()
    }
}

/// User-facing window builder.
pub struct Window {
    builder: WindowBuilder,
}

impl Window {
    /// Create a window with a title and the default SUI icon.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            builder: WindowBuilder::new().title(title),
        }
    }

    /// Set the window root widget.
    pub fn root<W>(mut self, root: W) -> Self
    where
        W: Widget + 'static,
    {
        self.builder = self.builder.root(root);
        self
    }

    /// Attach a controller owned by this window rather than by its widget tree.
    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
        self.builder = self.builder.controller(controller);
        self
    }

    /// Subscribe a lifecycle-safe handler owned by this window.
    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
    where
        T: Send + Sync + 'static,
        F: FnMut(&mut CommandCtx, &T) + 'static,
    {
        self.builder = self.builder.on_command(key, handler);
        self
    }

    /// Set a platform icon.
    pub fn icon(mut self, icon: WindowIcon) -> Self {
        self.builder = self.builder.icon(icon);
        self
    }

    /// Set an SVG platform icon.
    pub fn icon_svg(mut self, svg: impl Into<Vec<u8>>) -> Self {
        self.builder = self.builder.icon_svg(svg);
        self
    }

    /// Remove the platform icon.
    pub fn without_icon(mut self) -> Self {
        self.builder = self.builder.without_icon();
        self
    }

    /// Request an initial logical client size for the native window.
    pub fn initial_size(mut self, size: crate::Size) -> Self {
        self.builder = self.builder.initial_size(size);
        self
    }

    /// Request an initial physical desktop position for the native window.
    ///
    /// Desktop hosts may adjust or ignore an unsafe position after monitor
    /// topology changes.
    pub fn initial_position(mut self, position: crate::Point) -> Self {
        self.builder = self.builder.initial_position(position);
        self
    }

    pub(crate) fn into_window_builder(self) -> WindowBuilder {
        self.builder
    }
}

/// Resource registration facade for user code.
///
/// Resource handles are stable, cheap to copy, and safe to store in widget
/// state. Register resources during app construction and pass handles through
/// UI state instead of moving raw image/font blobs through render paths.
pub struct ResourceRegistry<'a> {
    application: &'a mut Application,
}

impl ResourceRegistry<'_> {
    /// Register a font with an explicit stable handle.
    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
        self.application.register_font(handle, font)
    }

    /// Register font bytes and allocate a stable handle.
    pub fn font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
        self.application.register_font_bytes(data)
    }

    /// Register an image with an explicit stable handle.
    pub fn image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
        self.application.register_image(handle, image)
    }

    /// Register RGBA8 pixels and allocate an image handle.
    pub fn rgba_image(
        &mut self,
        width: u32,
        height: u32,
        data: impl Into<Vec<u8>>,
    ) -> Result<ImageHandle> {
        self.application.register_rgba_image(width, height, data)
    }

    /// Register SVG bytes at their intrinsic size and allocate an image handle.
    pub fn svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
        self.application.register_svg_image(data)
    }

    /// Register SVG bytes at their intrinsic size with an explicit handle.
    pub fn svg_image_with_handle(
        &mut self,
        handle: ImageHandle,
        data: impl AsRef<[u8]>,
    ) -> Result<()> {
        self.application
            .register_svg_image_with_handle(handle, data)
    }

    /// Rasterize SVG bytes at an explicit size and allocate an image handle.
    pub fn svg_image_at_size(
        &mut self,
        width: u32,
        height: u32,
        data: impl AsRef<[u8]>,
    ) -> Result<ImageHandle> {
        self.application
            .register_svg_image_at_size(width, height, data)
    }

    /// Rasterize SVG bytes at an explicit size and handle.
    pub fn svg_image_at_size_with_handle(
        &mut self,
        handle: ImageHandle,
        width: u32,
        height: u32,
        data: impl AsRef<[u8]>,
    ) -> Result<()> {
        self.application
            .register_svg_image_at_size_with_handle(handle, width, height, data)
    }

    /// Register one compile-time embedded SVG resource.
    pub fn embedded_svg_image(&mut self, resource: EmbeddedSvgImageResource) -> Result<()> {
        self.application.register_embedded_svg_image(resource)
    }

    /// Register multiple compile-time embedded SVG resources.
    pub fn embedded_svg_images(
        &mut self,
        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
    ) -> Result<()> {
        self.application.register_embedded_svg_images(resources)
    }
}

/// Cloneable, thread-safe UI command handle for background work.
///
/// Each send returns the command's sequence number, as
/// [`CommandSender`]'s do.
#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
#[derive(Clone)]
pub struct UiHandle {
    commands: CommandSender,
}

#[cfg(any(feature = "desktop", feature = "web", feature = "mobile"))]
impl UiHandle {
    #[cfg_attr(
        not(any(
            feature = "desktop",
            feature = "web",
            all(target_os = "android", feature = "mobile")
        )),
        allow(dead_code)
    )]
    fn new(commands: CommandSender) -> Self {
        Self { commands }
    }

    /// Schedule controller wake hooks without synthesizing a widget event.
    pub fn wake(&self) {
        self.commands.wake();
    }

    pub fn send<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T) -> u64
    where
        T: Send + Sync + 'static,
    {
        self.commands.send(target, key, payload)
    }

    pub fn send_widget<T>(
        &self,
        window_id: crate::WindowId,
        widget_id: crate::WidgetId,
        key: CommandKey<T>,
        payload: T,
    ) -> u64
    where
        T: Send + Sync + 'static,
    {
        self.commands
            .send_widget(window_id, widget_id, key, payload)
    }

    pub fn send_focused<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T) -> u64
    where
        T: Send + Sync + 'static,
    {
        self.commands.send_focused(window_id, key, payload)
    }

    pub fn send_window<T>(&self, window_id: crate::WindowId, key: CommandKey<T>, payload: T) -> u64
    where
        T: Send + Sync + 'static,
    {
        self.commands.send_window(window_id, key, payload)
    }

    pub fn send_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
    where
        T: Send + Sync + 'static,
    {
        self.commands.send_application(key, payload)
    }

    pub fn broadcast_window<T>(
        &self,
        window_id: crate::WindowId,
        key: CommandKey<T>,
        payload: T,
    ) -> u64
    where
        T: Send + Sync + 'static,
    {
        self.commands.broadcast_window(window_id, key, payload)
    }

    pub fn broadcast_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
    where
        T: Send + Sync + 'static,
    {
        self.commands.broadcast_application(key, payload)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Constraints, MeasureCtx, Size};

    struct TestWidget;

    impl Widget for TestWidget {
        fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
            Size::new(32.0, 24.0)
        }
    }

    #[test]
    #[cfg(feature = "wgpu")]
    fn application_uses_plain_renderer_configuration_defaults() {
        let app = Application::new();
        let options = sui_render_wgpu::FeatheringOptions::default();
        assert_eq!(app.feathering_enabled(), options.enabled);
        assert_eq!(app.feather_width(), options.width);
    }

    #[test]
    fn app_builds_window_after_registering_resources() -> Result<()> {
        let mut app = App::new();
        let image = {
            let mut resources = app.resources();
            resources.rgba_image(1, 1, vec![255, 0, 0, 255])?
        };

        let runtime = app
            .main_window(format!("Image {image:?}"), TestWidget)
            .build()?;

        assert_eq!(runtime.window_ids().len(), 1);
        Ok(())
    }

    #[test]
    fn app_with_resources_preserves_builder_style() -> Result<()> {
        let runtime = App::new()
            .with_resources(|resources| {
                resources.rgba_image(1, 1, vec![0, 255, 0, 255])?;
                Ok(())
            })?
            .window(Window::new("Resource setup").root(TestWidget))
            .build()?;

        assert_eq!(runtime.window_ids().len(), 1);
        Ok(())
    }
}