use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use crate::any_value::Opaque;
use crate::custom::CustomProps;
use crate::draw::{Color, DisplayList};
use crate::geometry::{Point, Rect, Size};
use crate::services::{MenuEntry, Shortcut};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(pub(crate) u32);
impl NodeId {
pub fn raw(self) -> u32 {
self.0
}
pub fn from_raw(raw: u32) -> NodeId {
NodeId(raw)
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WidgetKind {
Window,
Container,
ToolbarItem,
Sidebar,
Fragment,
Text,
Button,
ToggleButton,
MenuButton,
TextInput,
PasswordInput,
SearchInput,
TextArea,
Checkbox,
Switch,
Select,
RadioGroup,
Slider,
NumberInput,
Progress,
Spinner,
Separator,
Image,
Icon,
FileIcon,
GpuSurface,
ScrollView,
List,
Table,
Tabs,
DocumentTabs,
Group,
Custom(&'static str),
Native,
}
impl WidgetKind {
pub fn is_native(self) -> bool {
self != WidgetKind::Fragment
}
pub fn is_container(self) -> bool {
matches!(
self,
WidgetKind::Window
| WidgetKind::Container
| WidgetKind::ToolbarItem
| WidgetKind::ScrollView
| WidgetKind::Tabs
| WidgetKind::Group
)
}
pub fn scrolls(self) -> bool {
matches!(self, WidgetKind::ScrollView | WidgetKind::List | WidgetKind::Table)
}
pub fn has_rows(self) -> bool {
matches!(self, WidgetKind::List | WidgetKind::Table)
}
pub fn name(self) -> &'static str {
match self {
WidgetKind::Window => "Window",
WidgetKind::Container => "Container",
WidgetKind::ToolbarItem => "ToolbarItem",
WidgetKind::Sidebar => "Sidebar",
WidgetKind::ScrollView => "ScrollView",
WidgetKind::List => "List",
WidgetKind::Table => "Table",
WidgetKind::Tabs => "Tabs",
WidgetKind::DocumentTabs => "DocumentTabs",
WidgetKind::Group => "Group",
WidgetKind::Fragment => "Fragment",
WidgetKind::Text => "Text",
WidgetKind::Button => "Button",
WidgetKind::ToggleButton => "ToggleButton",
WidgetKind::MenuButton => "MenuButton",
WidgetKind::TextInput => "TextInput",
WidgetKind::PasswordInput => "PasswordInput",
WidgetKind::SearchInput => "SearchInput",
WidgetKind::TextArea => "TextArea",
WidgetKind::Checkbox => "Checkbox",
WidgetKind::Switch => "Switch",
WidgetKind::Select => "Select",
WidgetKind::RadioGroup => "RadioGroup",
WidgetKind::Slider => "Slider",
WidgetKind::NumberInput => "NumberInput",
WidgetKind::Progress => "Progress",
WidgetKind::Spinner => "Spinner",
WidgetKind::Separator => "Separator",
WidgetKind::Image => "Image",
WidgetKind::Icon => "Icon",
WidgetKind::FileIcon => "FileIcon",
WidgetKind::GpuSurface => "GpuSurface",
WidgetKind::Custom(name) => name,
WidgetKind::Native => "Native",
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextStyle {
LargeTitle,
Title,
Headline,
#[default]
Body,
Callout,
Caption,
Monospace,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FontWeight {
#[default]
Regular,
Medium,
Semibold,
Bold,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAlign {
#[default]
Start,
Center,
End,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Truncation {
Start,
Middle,
#[default]
End,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HorizontalAlign {
#[default]
Left,
Center,
Right,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LayoutDirection {
#[default]
LeftToRight,
RightToLeft,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InputPurpose {
#[default]
Text,
Email,
Url,
Phone,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonRole {
#[default]
Normal,
Default,
Cancel,
Destructive,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HeaderEdge {
#[default]
Automatic,
Soft,
Hard,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TabsStyle {
#[default]
Automatic,
TabBar,
Navigation,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DocumentTabsStyle {
#[default]
Automatic,
Strip,
Window,
TitleRow,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonStyle {
#[default]
Automatic,
Bordered,
Borderless,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ImageSource {
File(PathBuf),
Pixels(Pixels),
}
#[derive(Clone, PartialEq)]
pub struct Pixels {
width: u32,
height: u32,
scale: f32,
rgba: Arc<[u8]>,
}
impl fmt::Debug for Pixels {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Pixels({}×{} @{}x)", self.width, self.height, self.scale)
}
}
impl Pixels {
pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Pixels {
let rgba = rgba.into();
let len = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4));
assert_eq!(Some(rgba.len()), len, "{width}×{height} RGBA8 pixels");
Pixels { width, height, scale: 1.0, rgba }
}
pub fn scale(mut self, scale: f32) -> Pixels {
assert!(scale > 0.0, "a scale above 0");
self.scale = scale;
self
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn scale_factor(&self) -> f32 {
self.scale
}
pub fn rgba(&self) -> &[u8] {
&self.rgba
}
pub fn size(&self) -> crate::Size {
crate::Size::new(self.width as f32 / self.scale, self.height as f32 / self.scale)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageFit {
Contain,
Stretch,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Cursor {
#[default]
Default,
Hidden,
Image { pixels: Pixels, hotspot: Point },
System(SystemCursor),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SystemCursor {
Text,
Wait,
Progress,
Pointer,
Crosshair,
NotAllowed,
Help,
Move,
ResizeNorthSouth,
ResizeEastWest,
ResizeNorthWestSouthEast,
ResizeNorthEastSouthWest,
}
impl SystemCursor {
pub fn css_name(self) -> &'static str {
match self {
SystemCursor::Text => "text",
SystemCursor::Wait => "wait",
SystemCursor::Progress => "progress",
SystemCursor::Pointer => "pointer",
SystemCursor::Crosshair => "crosshair",
SystemCursor::NotAllowed => "not-allowed",
SystemCursor::Help => "help",
SystemCursor::Move => "move",
SystemCursor::ResizeNorthSouth => "ns-resize",
SystemCursor::ResizeEastWest => "ew-resize",
SystemCursor::ResizeNorthWestSouthEast => "nwse-resize",
SystemCursor::ResizeNorthEastSouthWest => "nesw-resize",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Modality {
Window,
Application,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CurrentWindow(pub NodeId);
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct FileDrop {
pub extensions: Option<Vec<String>>,
pub folders: bool,
}
impl FileDrop {
pub fn files() -> FileDrop {
FileDrop { extensions: None, folders: false }
}
pub fn extensions<S: Into<String>>(extensions: impl IntoIterator<Item = S>) -> FileDrop {
FileDrop { extensions: Some(extensions.into_iter().map(Into::into).collect()), folders: false }
}
pub fn folders() -> FileDrop {
FileDrop { extensions: Some(Vec::new()), folders: true }
}
pub fn and_folders(mut self) -> FileDrop {
self.folders = true;
self
}
pub fn accepts(&self, path: &std::path::Path) -> bool {
if path.is_dir() {
return self.folders;
}
match &self.extensions {
None => true,
Some(extensions) => path
.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e))),
}
}
pub fn accepted(&self, paths: &[PathBuf]) -> Vec<PathBuf> {
paths.iter().filter(|p| self.accepts(p)).cloned().collect()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Orientation {
#[default]
Horizontal,
Vertical,
}
impl Orientation {
pub fn vertical(self) -> bool {
self == Orientation::Vertical
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ScrollAxes {
#[default]
Vertical,
Horizontal,
Both,
}
impl ScrollAxes {
pub fn horizontal(self) -> bool {
matches!(self, ScrollAxes::Horizontal | ScrollAxes::Both)
}
pub fn vertical(self) -> bool {
matches!(self, ScrollAxes::Vertical | ScrollAxes::Both)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RowKey(pub u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CellKey {
pub row: RowKey,
pub column: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ColumnData {
pub title: String,
pub width: Option<f32>,
pub expand: bool,
pub sortable: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SortOrder {
#[default]
Ascending,
Descending,
}
impl SortOrder {
pub fn reversed(self) -> SortOrder {
match self {
SortOrder::Ascending => SortOrder::Descending,
SortOrder::Descending => SortOrder::Ascending,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ColumnSort {
pub column: usize,
pub order: SortOrder,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SelectionMode {
#[default]
None,
Single,
Multiple,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ListStyle {
#[default]
Automatic,
Plain,
Framed,
}
impl ListStyle {
pub fn framed(self) -> bool {
self == ListStyle::Framed
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SidebarSectionData {
pub title: Option<String>,
pub items: Vec<SidebarItemData>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SidebarItemData {
pub title: String,
pub icon: Option<String>,
pub subtitle: Option<String>,
pub menu: Vec<crate::services::MenuEntry>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Prop {
Title(String),
FullScreen(bool),
MinSize(Size),
HeightFollowsContent(bool),
Maximized(bool),
Resizable(bool),
Text(String),
MaxLines(Option<u32>),
Truncation(Truncation),
TextColor(Color),
FontWeight(FontWeight),
Italic(bool),
TextAlign(HorizontalAlign),
LayoutDirection(LayoutDirection),
Selectable(bool),
Label(String),
Value(String),
Placeholder(String),
ReadOnly(bool),
Lines(u32),
LineWrap(bool),
InputPurpose(InputPurpose),
Checked(bool),
Mixed(bool),
Enabled(bool),
TextStyle(TextStyle),
ButtonRole(ButtonRole),
ButtonStyle(ButtonStyle),
Options(Vec<String>),
SelectedIndex(Option<usize>),
Number(f64),
Range {
min: f64,
max: f64,
},
Step(Option<f64>),
WrapAround(bool),
Orientation(Orientation),
Tooltip(String),
ContextMenu(Vec<MenuEntry>),
Menu(Vec<MenuEntry>),
Modal {
owner: Option<NodeId>,
modality: Modality,
},
Image(ImageSource),
ImageFit(ImageFit),
Icon(String),
IconSize(f32),
File(PathBuf),
Thumbnail(bool),
IconOnly(bool),
Running(bool),
Progress(Option<f64>),
ScrollAxes(ScrollAxes),
ScrollBars(bool),
TabTitles(Vec<String>),
TabIcons(Vec<String>),
TabsStyle(TabsStyle),
TabsClosable(bool),
TabsReorderable(bool),
NewTabButton(bool),
DocumentTabsStyle(DocumentTabsStyle),
Sections(Vec<SidebarSectionData>),
SidebarShown(bool),
Header(bool),
HeaderEdge(HeaderEdge),
Rows(Vec<RowKey>),
EstimatedRowHeight(f32),
Row(RowKey),
Columns(Vec<ColumnData>),
Sort(Option<ColumnSort>),
Cell(CellKey),
SelectionMode(SelectionMode),
ListStyle(ListStyle),
Selected(Vec<RowKey>),
Custom(CustomProps),
Drawing(DisplayList),
Native(Opaque),
TakesInput(bool),
PointerLock(bool),
KeyboardGrab(bool),
Cursor(Cursor),
TextInput(bool),
InputMethod(bool),
TextCursor(Option<Rect>),
FileDrop(Option<FileDrop>),
Hover(bool),
DoubleClick(bool),
RowFiles(Vec<(RowKey, PathBuf)>),
Keys(Vec<Shortcut>),
Tweak(Opaque),
}
impl Prop {
pub fn key(&self) -> std::mem::Discriminant<Prop> {
std::mem::discriminant(self)
}
pub fn affects_measure(&self, kind: WidgetKind) -> bool {
if kind == WidgetKind::NumberInput && matches!(self, Prop::Range { .. } | Prop::Number(_)) {
return true;
}
if kind == WidgetKind::MenuButton && matches!(self, Prop::Menu(_)) {
return true;
}
if kind == WidgetKind::TextArea && matches!(self, Prop::Lines(_)) {
return true;
}
if kind == WidgetKind::DocumentTabs
&& matches!(
self,
Prop::TabTitles(_) | Prop::TabsClosable(_) | Prop::NewTabButton(_) | Prop::DocumentTabsStyle(_)
)
{
return true;
}
matches!(
self,
Prop::Text(_)
| Prop::MaxLines(_)
| Prop::Truncation(_)
| Prop::FontWeight(_)
| Prop::Italic(_)
| Prop::Label(_)
| Prop::Placeholder(_)
| Prop::Options(_)
| Prop::SelectedIndex(_)
| Prop::TextStyle(_)
| Prop::ButtonRole(_)
| Prop::ButtonStyle(_)
| Prop::Orientation(_)
| Prop::Image(_)
| Prop::Icon(_)
| Prop::IconSize(_)
| Prop::IconOnly(_)
| Prop::Custom(_)
| Prop::Native(_)
| Prop::Tweak(_)
)
}
}
pub fn moved_index(index: usize, from: usize, to: usize) -> usize {
if index == from {
to
} else if from < index && index <= to {
index - 1
} else if to <= index && index < from {
index + 1
} else {
index
}
}
#[macro_export]
macro_rules! find_prop {
($props:expr, $variant:ident) => {
$props.iter().find_map(|p| match p {
$crate::Prop::$variant(v) => Some(v.clone()),
_ => None,
})
};
}
macro_rules! static_value {
($($t:ty),*) => {$(
impl mitsuami_reactive::IntoValue<$t> for $t {
fn into_value(self) -> mitsuami_reactive::Value<$t> {
mitsuami_reactive::Value::Static(self)
}
}
)*};
}
static_value!(
FileDrop,
TextStyle,
FontWeight,
TextAlign,
Truncation,
crate::draw::Color,
ButtonRole,
ButtonStyle,
TabsStyle,
HeaderEdge,
DocumentTabsStyle,
Orientation,
ScrollAxes,
SelectionMode,
SortOrder,
ListStyle,
InputPurpose,
ImageSource,
Pixels,
ImageFit,
Modality,
Cursor,
Size
);