sinomo-ui-runtime 0.5.0

Retained runtime and widget contracts for SUI.
Documentation
use std::sync::Arc;

use sui_core::{Error, FontHandle, ImageHandle, Point, Result, Size, WindowId};
use sui_scene::RegisteredImage;
use sui_text::RegisteredFont;

use crate::{
    Runtime, WindowState,
    command::{CommandController, CommandCtx, CommandKey, CommandListeners, CommandSender},
    logo::DEFAULT_SUI_LOGO_SVG,
    widget::{Widget, WidgetPod},
};

pub struct WindowBuilder {
    title: String,
    icon: Option<WindowIcon>,
    initial_size: Option<Size>,
    initial_position: Option<Point>,
    root: Option<WidgetPod>,
    command_listeners: CommandListeners,
}

impl WindowBuilder {
    pub fn new() -> Self {
        Self {
            title: "SUI Window".to_string(),
            icon: Some(WindowIcon::sui()),
            initial_size: None,
            initial_position: None,
            root: None,
            command_listeners: CommandListeners::default(),
        }
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    pub fn icon(mut self, icon: WindowIcon) -> Self {
        self.icon = Some(icon);
        self
    }

    pub fn icon_svg(mut self, svg: impl Into<Vec<u8>>) -> Self {
        self.icon = Some(WindowIcon::from_svg(svg));
        self
    }

    pub fn without_icon(mut self) -> Self {
        self.icon = None;
        self
    }

    /// Request an initial logical client size for the native window.
    pub fn initial_size(mut self, size: Size) -> Self {
        self.initial_size = Some(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: Point) -> Self {
        self.initial_position = Some(position);
        self
    }

    pub fn root<W>(mut self, root: W) -> Self
    where
        W: Widget + 'static,
    {
        self.root = Some(WidgetPod::new(root));
        self
    }

    /// Attach a non-widget controller whose lifetime is exactly this window's
    /// lifetime.
    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
        self.command_listeners.push_controller(controller);
        self
    }

    /// Subscribe a window-scoped handler to a typed command.
    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.command_listeners.push_subscription(key, handler);
        self
    }

    pub(crate) fn build(
        self,
        window_id: WindowId,
        command_sender: CommandSender,
    ) -> Result<WindowState> {
        let root = self
            .root
            .ok_or_else(|| Error::new("window root widget must be set before building"))?;

        Ok(WindowState::new(
            window_id,
            self.title,
            self.icon,
            self.initial_size,
            self.initial_position,
            root,
            self.command_listeners,
            command_sender,
        ))
    }
}

impl Default for WindowBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WindowIcon {
    Svg {
        data: Arc<[u8]>,
    },
    Rgba8 {
        width: u32,
        height: u32,
        data: Arc<[u8]>,
    },
}

impl WindowIcon {
    pub fn sui() -> Self {
        Self::from_svg(DEFAULT_SUI_LOGO_SVG)
    }

    pub fn from_svg(svg: impl Into<Vec<u8>>) -> Self {
        Self::Svg {
            data: Arc::from(svg.into()),
        }
    }

    pub fn from_rgba8(width: u32, height: u32, data: impl Into<Vec<u8>>) -> Result<Self> {
        if width == 0 || height == 0 {
            return Err(Error::new("window icon dimensions must be non-zero"));
        }

        let data = data.into();
        let expected_len = (width as usize)
            .checked_mul(height as usize)
            .and_then(|pixels| pixels.checked_mul(4))
            .ok_or_else(|| Error::new("window icon dimensions overflow RGBA buffer length"))?;

        if data.len() != expected_len {
            return Err(Error::new(format!(
                "window icon RGBA buffer length mismatch: expected {expected_len}, got {}",
                data.len()
            )));
        }

        Ok(Self::Rgba8 {
            width,
            height,
            data: Arc::from(data),
        })
    }

    pub fn as_svg(&self) -> Option<&[u8]> {
        match self {
            Self::Svg { data } => Some(data),
            Self::Rgba8 { .. } => None,
        }
    }

    pub fn as_rgba8(&self) -> Option<(u32, u32, &[u8])> {
        match self {
            Self::Svg { .. } => None,
            Self::Rgba8 {
                width,
                height,
                data,
            } => Some((*width, *height, data)),
        }
    }
}

impl Default for WindowIcon {
    fn default() -> Self {
        Self::sui()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmbeddedSvgImageResource {
    handle: ImageHandle,
    data: &'static [u8],
    size: Option<(u32, u32)>,
}

impl EmbeddedSvgImageResource {
    pub const fn new(handle: ImageHandle, data: &'static [u8]) -> Self {
        Self {
            handle,
            data,
            size: None,
        }
    }

    pub const fn at_size(
        handle: ImageHandle,
        width: u32,
        height: u32,
        data: &'static [u8],
    ) -> Self {
        Self {
            handle,
            data,
            size: Some((width, height)),
        }
    }

    pub const fn handle(self) -> ImageHandle {
        self.handle
    }

    pub const fn data(self) -> &'static [u8] {
        self.data
    }

    pub const fn size(self) -> Option<(u32, u32)> {
        self.size
    }

    pub fn registered_image(self) -> Result<RegisteredImage> {
        match self.size {
            Some((width, height)) => RegisteredImage::from_svg_at_size(width, height, self.data),
            None => RegisteredImage::from_svg(self.data),
        }
    }
}

#[derive(Default)]
pub struct Application {
    windows: Vec<WindowBuilder>,
    resources: crate::resources::ResourceStore,
    command_listeners: CommandListeners,
}

impl Application {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn window(mut self, window: WindowBuilder) -> Self {
        self.windows.push(window);
        self
    }

    /// Attach an application-scoped non-widget controller.
    pub fn controller(mut self, controller: impl CommandController + 'static) -> Self {
        self.command_listeners.push_controller(controller);
        self
    }

    /// Subscribe an application-scoped handler to a typed command.
    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.command_listeners.push_subscription(key, handler);
        self
    }

    pub fn register_font(&mut self, handle: FontHandle, font: RegisteredFont) -> Result<()> {
        self.resources.register_font(handle, font)
    }

    pub fn register_font_bytes(&mut self, data: impl Into<Vec<u8>>) -> Result<FontHandle> {
        self.resources.register_font_bytes(data)
    }

    pub fn register_image(&mut self, handle: ImageHandle, image: RegisteredImage) -> Result<()> {
        self.resources.register_image(handle, image)
    }

    pub fn register_svg_image_with_handle(
        &mut self,
        handle: ImageHandle,
        data: impl AsRef<[u8]>,
    ) -> Result<()> {
        self.resources.register_svg_image_with_handle(handle, data)
    }

    pub fn register_rgba_image(
        &mut self,
        width: u32,
        height: u32,
        data: impl Into<Vec<u8>>,
    ) -> Result<ImageHandle> {
        self.resources.register_rgba_image(width, height, data)
    }

    pub fn register_svg_image(&mut self, data: impl AsRef<[u8]>) -> Result<ImageHandle> {
        self.resources.register_svg_image(data)
    }

    pub fn register_svg_image_at_size_with_handle(
        &mut self,
        handle: ImageHandle,
        width: u32,
        height: u32,
        data: impl AsRef<[u8]>,
    ) -> Result<()> {
        self.resources
            .register_svg_image_at_size_with_handle(handle, width, height, data)
    }

    pub fn register_svg_image_at_size(
        &mut self,
        width: u32,
        height: u32,
        data: impl AsRef<[u8]>,
    ) -> Result<ImageHandle> {
        self.resources
            .register_svg_image_at_size(width, height, data)
    }

    pub fn register_embedded_svg_image(
        &mut self,
        resource: EmbeddedSvgImageResource,
    ) -> Result<()> {
        self.resources.register_embedded_svg_image(resource)
    }

    pub fn register_embedded_svg_images(
        &mut self,
        resources: impl IntoIterator<Item = EmbeddedSvgImageResource>,
    ) -> Result<()> {
        self.resources.register_embedded_svg_images(resources)
    }

    pub fn build(self) -> Result<Runtime> {
        let mut runtime = Runtime::with_resources(self.resources);
        runtime.command_listeners = self.command_listeners;

        for window in self.windows {
            runtime.add_window(window)?;
        }

        Ok(runtime)
    }
}