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