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,
SplitButton,
TextInput,
PasswordInput,
SearchInput,
TextArea,
Checkbox,
Switch,
Select,
RadioGroup,
Slider,
NumberInput,
ColorWell,
Progress,
Spinner,
Separator,
Image,
Icon,
FileIcon,
GpuSurface,
ScrollView,
List,
Table,
Tree,
Tabs,
DocumentTabs,
Group,
Split,
Popover,
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
| WidgetKind::Split
| WidgetKind::Popover
)
}
pub fn scrolls(self) -> bool {
matches!(self, WidgetKind::ScrollView | WidgetKind::List | WidgetKind::Table | WidgetKind::Tree)
}
pub fn has_rows(self) -> bool {
matches!(self, WidgetKind::List | WidgetKind::Table | WidgetKind::Tree)
}
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::Tree => "Tree",
WidgetKind::Tabs => "Tabs",
WidgetKind::DocumentTabs => "DocumentTabs",
WidgetKind::Group => "Group",
WidgetKind::Popover => "Popover",
WidgetKind::Split => "Split",
WidgetKind::Fragment => "Fragment",
WidgetKind::Text => "Text",
WidgetKind::Button => "Button",
WidgetKind::ToggleButton => "ToggleButton",
WidgetKind::MenuButton => "MenuButton",
WidgetKind::SplitButton => "SplitButton",
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::ColorWell => "ColorWell",
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 FileLookup {
#[default]
Disk,
FileName,
Folder,
}
#[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,
Prominent,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Suggestion {
pub title: String,
pub detail: Option<String>,
}
#[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, Default, PartialEq, Eq)]
pub struct RowMoves {
pub onto_rows: bool,
pub between_rows: bool,
}
impl RowMoves {
pub fn onto_rows() -> RowMoves {
RowMoves { onto_rows: true, between_rows: false }
}
pub fn between_rows() -> RowMoves {
RowMoves { onto_rows: false, between_rows: true }
}
pub fn and_between_rows(self) -> RowMoves {
RowMoves { between_rows: true, ..self }
}
pub fn and_onto_rows(self) -> RowMoves {
RowMoves { onto_rows: true, ..self }
}
pub fn target(&self, dragged: &[RowKey], proposed: RowDrop<RowKey>) -> Option<RowDrop<RowKey>> {
let target = match proposed {
RowDrop::On(row) if !self.onto_rows => RowDrop::Before(row),
RowDrop::Before(row) if !self.between_rows => RowDrop::On(row),
other => other,
};
match target {
RowDrop::On(row) if dragged.contains(&row) => None,
_ if !self.onto_rows && !self.between_rows => None,
target => Some(target),
}
}
pub fn tree_target(
&self,
dragged: &[RowKey],
over: Option<RowKey>,
proposed: RowDrop<RowKey>,
row: impl Fn(RowKey) -> Option<crate::TreeRow>,
) -> Option<RowDrop<RowKey>> {
let inside_dragged = |key: RowKey| {
let mut at = Some(key);
while let Some(r) = at {
if dragged.contains(&r) {
return true;
}
at = row(r).and_then(|r| r.parent);
}
false
};
if over.is_some_and(inside_dragged) {
return None;
}
let target = self.target(dragged, proposed)?;
match target {
RowDrop::On(r) if !row(r).is_some_and(|r| r.expandable) => None,
RowDrop::On(r) | RowDrop::Before(r) if inside_dragged(r) => None,
target => Some(target),
}
}
pub fn tree_proposal(
key: RowKey,
x: Option<f32>,
y: f32,
height: f32,
indent: crate::TreeIndent,
next: Option<RowKey>,
row: impl Fn(RowKey) -> Option<crate::TreeRow>,
) -> RowDrop<RowKey> {
let Some(me) = row(key) else { return RowDrop::End };
let next_row = next.and_then(&row);
let after = || {
if let (Some(next), Some(n)) = (next, next_row)
&& n.parent == Some(key)
{
return RowDrop::Before(next);
}
let shallowest = next_row.map_or(0, |n| n.depth).min(me.depth);
let level = match x {
Some(x) if indent.per_level > 0.0 => {
let level = ((x - indent.start) / indent.per_level + 0.5).floor();
(level.max(0.0) as u32).clamp(shallowest, me.depth)
}
_ => me.depth,
};
if let (Some(next), Some(n)) = (next, next_row)
&& level == n.depth
{
return RowDrop::Before(next);
}
let mut at = me;
while at.depth > level {
match at.parent.and_then(&row) {
Some(parent) => at = parent,
None => break,
}
}
at.parent.map_or(RowDrop::End, RowDrop::On)
};
match me.expandable {
true if y < height / 4.0 => RowDrop::Before(key),
true if y > height * 3.0 / 4.0 => after(),
true => RowDrop::On(key),
false if y < height / 2.0 => RowDrop::Before(key),
false => after(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RowDrop<K> {
On(K),
Before(K),
End,
}
impl<K> RowDrop<K> {
pub fn map<J>(self, f: impl FnOnce(K) -> J) -> RowDrop<J> {
match self {
RowDrop::On(k) => RowDrop::On(f(k)),
RowDrop::Before(k) => RowDrop::Before(f(k)),
RowDrop::End => RowDrop::End,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RowKey(pub u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TreeRow {
pub row: RowKey,
pub parent: Option<RowKey>,
pub depth: u32,
pub expandable: bool,
pub expanded: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TreeIndent {
pub start: f32,
pub per_level: f32,
}
impl TreeIndent {
pub fn at(self, depth: u32) -> f32 {
self.start + self.per_level * depth as f32
}
}
#[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,
pub fills_row: 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),
Error(Option<String>),
ReadOnly(bool),
Lines(u32),
LineWrap(bool),
FollowsEnd(bool),
InputPurpose(InputPurpose),
Checked(bool),
Mixed(bool),
Enabled(bool),
TextStyle(TextStyle),
ButtonRole(ButtonRole),
ButtonStyle(ButtonStyle),
Options(Vec<String>),
SelectedIndex(Option<usize>),
Number(f64),
ColorValue(Color),
Range {
min: f64,
max: f64,
},
Step(Option<f64>),
WrapAround(bool),
Orientation(Orientation),
PaneMinimums([f32; 2]),
PanesShown([bool; 2]),
Tooltip(String),
ContextMenu(Vec<MenuEntry>),
ContextMenuOnOpen(Option<crate::services::MenuOnOpen>),
Menu(Vec<MenuEntry>),
MenuOnOpen(Option<crate::services::MenuOnOpen>),
Modal {
owner: Option<NodeId>,
modality: Modality,
},
Image(ImageSource),
ImageFit(ImageFit),
Icon(String),
VectorIcon(Option<crate::VectorIcon>),
IconSize(f32),
File(PathBuf),
Thumbnail(bool),
FileLookup(FileLookup),
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),
PopoverShown(bool),
Suggestions(Vec<Suggestion>),
SearchOnReturn(bool),
Header(bool),
HeaderEdge(HeaderEdge),
SidebarPane(bool),
ClickThrough(bool),
Rows(Vec<RowKey>),
TreeRows(Vec<TreeRow>),
TreeLoading(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>),
Transparent(bool),
FileDrop(Option<FileDrop>),
Hover(bool),
DoubleClick(bool),
Click(bool),
RowFiles(Vec<(RowKey, PathBuf)>),
RowMoves(RowMoves),
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::VectorIcon(_)
| 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,
FileLookup,
crate::draw::Color,
ButtonRole,
ButtonStyle,
TabsStyle,
HeaderEdge,
DocumentTabsStyle,
Orientation,
ScrollAxes,
SelectionMode,
SortOrder,
ListStyle,
InputPurpose,
ImageSource,
Pixels,
ImageFit,
Modality,
Cursor,
Size,
crate::VectorIcon
);