Skip to main content

sui_runtime/
app.rs

1use std::sync::Arc;
2
3use sui_core::{Error, FontHandle, ImageHandle, Point, Result, Size, WindowId};
4use sui_scene::RegisteredImage;
5use sui_text::RegisteredFont;
6
7use crate::{
8    Runtime, WindowState,
9    command::{CommandController, CommandCtx, CommandKey, CommandListeners, CommandSender},
10    logo::DEFAULT_SUI_LOGO_SVG,
11    widget::{Widget, WidgetPod},
12};
13
14pub struct WindowBuilder {
15    title: String,
16    icon: Option<WindowIcon>,
17    initial_size: Option<Size>,
18    initial_position: Option<Point>,
19    root: Option<WidgetPod>,
20    command_listeners: CommandListeners,
21}
22
23impl WindowBuilder {
24    pub fn new() -> Self {
25        Self {
26            title: "SUI Window".to_string(),
27            icon: Some(WindowIcon::sui()),
28            initial_size: None,
29            initial_position: None,
30            root: None,
31            command_listeners: CommandListeners::default(),
32        }
33    }
34
35    pub fn title(mut self, title: impl Into<String>) -> Self {
36        self.title = title.into();
37        self
38    }
39
40    pub fn icon(mut self, icon: WindowIcon) -> Self {
41        self.icon = Some(icon);
42        self
43    }
44
45    pub fn icon_svg(mut self, svg: impl Into<Vec<u8>>) -> Self {
46        self.icon = Some(WindowIcon::from_svg(svg));
47        self
48    }
49
50    pub fn without_icon(mut self) -> Self {
51        self.icon = None;
52        self
53    }
54
55    /// Request an initial logical client size for the native window.
56    pub fn initial_size(mut self, size: Size) -> Self {
57        self.initial_size = Some(size);
58        self
59    }
60
61    /// Request an initial physical desktop position for the native window.
62    ///
63    /// Desktop hosts may adjust or ignore an unsafe position after monitor
64    /// topology changes.
65    pub fn initial_position(mut self, position: Point) -> Self {
66        self.initial_position = Some(position);
67        self
68    }
69
70    pub fn root<W>(mut self, root: W) -> Self
71    where
72        W: Widget + 'static,
73    {
74        self.root = Some(WidgetPod::new(root));
75        self
76    }
77
78    /// Attach a non-widget controller whose lifetime is exactly this window's
79    /// lifetime.
80    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
81        self.command_listeners.push_controller(controller);
82        self
83    }
84
85    /// Subscribe a window-scoped handler to a typed command.
86    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
87    where
88        T: Send + Sync + 'static,
89        F: FnMut(&mut CommandCtx, &T) + 'static,
90    {
91        self.command_listeners.push_subscription(key, handler);
92        self
93    }
94
95    pub(crate) fn build(
96        self,
97        window_id: WindowId,
98        command_sender: CommandSender,
99    ) -> Result<WindowState> {
100        let root = self
101            .root
102            .ok_or_else(|| Error::new("window root widget must be set before building"))?;
103
104        Ok(WindowState::new(
105            window_id,
106            self.title,
107            self.icon,
108            self.initial_size,
109            self.initial_position,
110            root,
111            self.command_listeners,
112            command_sender,
113        ))
114    }
115}
116
117impl Default for WindowBuilder {
118    fn default() -> Self {
119        Self::new()
120    }
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub enum WindowIcon {
125    Svg {
126        data: Arc<[u8]>,
127    },
128    Rgba8 {
129        width: u32,
130        height: u32,
131        data: Arc<[u8]>,
132    },
133}
134
135impl WindowIcon {
136    pub fn sui() -> Self {
137        Self::from_svg(DEFAULT_SUI_LOGO_SVG)
138    }
139
140    pub fn from_svg(svg: impl Into<Vec<u8>>) -> Self {
141        Self::Svg {
142            data: Arc::from(svg.into()),
143        }
144    }
145
146    pub fn from_rgba8(width: u32, height: u32, data: impl Into<Vec<u8>>) -> Result<Self> {
147        if width == 0 || height == 0 {
148            return Err(Error::new("window icon dimensions must be non-zero"));
149        }
150
151        let data = data.into();
152        let expected_len = (width as usize)
153            .checked_mul(height as usize)
154            .and_then(|pixels| pixels.checked_mul(4))
155            .ok_or_else(|| Error::new("window icon dimensions overflow RGBA buffer length"))?;
156
157        if data.len() != expected_len {
158            return Err(Error::new(format!(
159                "window icon RGBA buffer length mismatch: expected {expected_len}, got {}",
160                data.len()
161            )));
162        }
163
164        Ok(Self::Rgba8 {
165            width,
166            height,
167            data: Arc::from(data),
168        })
169    }
170
171    pub fn as_svg(&self) -> Option<&[u8]> {
172        match self {
173            Self::Svg { data } => Some(data),
174            Self::Rgba8 { .. } => None,
175        }
176    }
177
178    pub fn as_rgba8(&self) -> Option<(u32, u32, &[u8])> {
179        match self {
180            Self::Svg { .. } => None,
181            Self::Rgba8 {
182                width,
183                height,
184                data,
185            } => Some((*width, *height, data)),
186        }
187    }
188}
189
190impl Default for WindowIcon {
191    fn default() -> Self {
192        Self::sui()
193    }
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub struct EmbeddedSvgImageResource {
198    handle: ImageHandle,
199    data: &'static [u8],
200    size: Option<(u32, u32)>,
201}
202
203impl EmbeddedSvgImageResource {
204    pub const fn new(handle: ImageHandle, data: &'static [u8]) -> Self {
205        Self {
206            handle,
207            data,
208            size: None,
209        }
210    }
211
212    pub const fn at_size(
213        handle: ImageHandle,
214        width: u32,
215        height: u32,
216        data: &'static [u8],
217    ) -> Self {
218        Self {
219            handle,
220            data,
221            size: Some((width, height)),
222        }
223    }
224
225    pub const fn handle(self) -> ImageHandle {
226        self.handle
227    }
228
229    pub const fn data(self) -> &'static [u8] {
230        self.data
231    }
232
233    pub const fn size(self) -> Option<(u32, u32)> {
234        self.size
235    }
236
237    pub fn registered_image(self) -> Result<RegisteredImage> {
238        match self.size {
239            Some((width, height)) => RegisteredImage::from_svg_at_size(width, height, self.data),
240            None => RegisteredImage::from_svg(self.data),
241        }
242    }
243}
244
245#[derive(Default)]
246pub struct Application {
247    windows: Vec<WindowBuilder>,
248    resources: crate::resources::ResourceStore,
249    command_listeners: CommandListeners,
250}
251
252impl Application {
253    pub fn new() -> Self {
254        Self::default()
255    }
256
257    pub fn window(mut self, window: WindowBuilder) -> Self {
258        self.windows.push(window);
259        self
260    }
261
262    /// Attach an application-scoped non-widget controller.
263    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
264        self.command_listeners.push_controller(controller);
265        self
266    }
267
268    /// Subscribe an application-scoped handler to a typed command.
269    pub fn on_command<T, F>(mut self, key: CommandKey<T>, handler: F) -> Self
270    where
271        T: Send + Sync + 'static,
272        F: FnMut(&mut CommandCtx, &T) + 'static,
273    {
274        self.command_listeners.push_subscription(key, handler);
275        self
276    }
277
278    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
279        self.resources.register_font(handle, font)
280    }
281
282    pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
283        self.resources.register_font_bytes(data)
284    }
285
286    pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
287        self.resources.register_image(handle, image)
288    }
289
290    pub fn register_svg_image_with_handle(
291        &mut self,
292        handle: ImageHandle,
293        data: impl AsRef<[u8]>,
294    ) -> Result<()> {
295        self.resources.register_svg_image_with_handle(handle, data)
296    }
297
298    pub fn register_rgba_image(
299        &mut self,
300        width: u32,
301        height: u32,
302        data: impl Into<Vec<u8>>,
303    ) -> Result<ImageHandle> {
304        self.resources.register_rgba_image(width, height, data)
305    }
306
307    pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
308        self.resources.register_svg_image(data)
309    }
310
311    pub fn register_svg_image_at_size_with_handle(
312        &mut self,
313        handle: ImageHandle,
314        width: u32,
315        height: u32,
316        data: impl AsRef<[u8]>,
317    ) -> Result<()> {
318        self.resources
319            .register_svg_image_at_size_with_handle(handle, width, height, data)
320    }
321
322    pub fn register_svg_image_at_size(
323        &mut self,
324        width: u32,
325        height: u32,
326        data: impl AsRef<[u8]>,
327    ) -> Result<ImageHandle> {
328        self.resources
329            .register_svg_image_at_size(width, height, data)
330    }
331
332    pub fn register_embedded_svg_image(
333        &mut self,
334        resource: EmbeddedSvgImageResource,
335    ) -> Result<()> {
336        self.resources.register_embedded_svg_image(resource)
337    }
338
339    pub fn register_embedded_svg_images(
340        &mut self,
341        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
342    ) -> Result<()> {
343        self.resources.register_embedded_svg_images(resources)
344    }
345
346    pub fn build(self) -> Result<Runtime> {
347        let mut runtime = Runtime::with_resources(self.resources);
348        runtime.command_listeners = self.command_listeners;
349
350        for window in self.windows {
351            runtime.add_window(window)?;
352        }
353
354        Ok(runtime)
355    }
356}