use std::collections::{BTreeSet, HashMap, HashSet};
use crate::collection::Collection;
use crate::component::WindowConfig;
use crate::control::WindowCommand;
use std::sync::{Mutex, OnceLock};
#[cfg(feature = "image-support")]
use std::sync::{
Arc,
atomic::{AtomicU64, Ordering},
};
pub fn intern_key(key: &str) -> &'static str {
fn pool() -> &'static Mutex<HashMap<String, &'static str>> {
static POOL: OnceLock<Mutex<HashMap<String, &'static str>>> = OnceLock::new();
POOL.get_or_init(|| Mutex::new(HashMap::new()))
}
let mut pool = pool()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(existing) = pool.get(key) {
return existing;
}
let leaked: &'static str = Box::leak(key.to_owned().into_boxed_str());
pool.insert(leaked.to_owned(), leaked);
leaked
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseButton {
Left,
Right,
Middle,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyInfo {
pub key: String,
pub shift: bool,
pub ctrl: bool,
pub alt: bool,
}
impl KeyInfo {
pub fn new(key: impl Into<String>, shift: bool, ctrl: bool, alt: bool) -> Self {
Self {
key: key.into(),
shift,
ctrl,
alt,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
Click,
Dblclick,
Mousedown(MouseButton),
Mouseup(MouseButton),
Mouseenter,
Mouseleave,
Mousemove {
x: f32,
y: f32,
},
Keydown(KeyInfo),
Keyup(KeyInfo),
TextChange(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Size {
#[default]
Auto,
Px(f32),
Percent(f32),
}
impl Size {
pub fn resolve(self, content: f32, available: f32) -> f32 {
let value = match self {
Size::Auto => content,
Size::Px(value) => value,
Size::Percent(percent) => available * percent / 100.0,
};
value.max(0.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Align {
#[default]
Start,
Center,
End,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Offset {
Px(f32),
Percent(f32),
}
impl Offset {
pub fn resolve(self, available: f32) -> f32 {
match self {
Offset::Px(value) => value,
Offset::Percent(percent) => available * percent / 100.0,
}
}
}
impl Default for Offset {
fn default() -> Self {
Offset::Px(0.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Overflow {
#[default]
Visible,
Hidden,
Auto,
Scroll,
}
impl Overflow {
pub const fn clips(self) -> bool {
!matches!(self, Overflow::Visible)
}
pub const fn scrollable(self) -> bool {
matches!(self, Overflow::Auto | Overflow::Scroll)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WhiteSpace {
#[default]
Normal,
Nowrap,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Position {
#[default]
Flow,
Absolute,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Edges {
pub top: f32,
pub right: f32,
pub bottom: f32,
pub left: f32,
}
impl Edges {
pub const ZERO: Self = Self {
top: 0.0,
right: 0.0,
bottom: 0.0,
left: 0.0,
};
pub const fn all(value: f32) -> Self {
Self {
top: value,
right: value,
bottom: value,
left: value,
}
}
pub const fn horizontal(self) -> f32 {
self.left + self.right
}
pub const fn vertical(self) -> f32 {
self.top + self.bottom
}
pub const fn is_zero(self) -> bool {
self.top == 0.0 && self.right == 0.0 && self.bottom == 0.0 && self.left == 0.0
}
pub const fn scaled(self, factor: f32) -> Self {
Self {
top: self.top * factor,
right: self.right * factor,
bottom: self.bottom * factor,
left: self.left * factor,
}
}
pub const fn plus(self, other: Self) -> Self {
Self {
top: self.top + other.top,
right: self.right + other.right,
bottom: self.bottom + other.bottom,
left: self.left + other.left,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Resize {
#[default]
None,
Horizontal,
Vertical,
Both,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ButtonType {
#[default]
Submit,
Button,
Reset,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Cursor {
#[default]
Default,
Pointer,
Text,
NotAllowed,
Wait,
Progress,
Help,
Crosshair,
Move,
Grab,
Grabbing,
EwResize,
NsResize,
NeswResize,
NwseResize,
}
impl Cursor {
pub fn from_name(name: &str) -> Option<Self> {
match name.trim().to_ascii_lowercase().as_str() {
"default" => Some(Self::Default),
"pointer" => Some(Self::Pointer),
"text" => Some(Self::Text),
"not-allowed" => Some(Self::NotAllowed),
"wait" => Some(Self::Wait),
"progress" => Some(Self::Progress),
"help" => Some(Self::Help),
"crosshair" => Some(Self::Crosshair),
"move" => Some(Self::Move),
"grab" => Some(Self::Grab),
"grabbing" => Some(Self::Grabbing),
"ew-resize" => Some(Self::EwResize),
"ns-resize" => Some(Self::NsResize),
"nesw-resize" => Some(Self::NeswResize),
"nwse-resize" => Some(Self::NwseResize),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum RequiredIndicator {
#[default]
Asterisk,
None,
Accent(u32),
}
fn size_or_auto_impl(value: &str) -> Option<Size> {
let value = value.trim();
if value.is_empty() || value.eq_ignore_ascii_case("auto") {
return Some(Size::Auto);
}
if let Some(percent) = value.strip_suffix('%') {
return percent.trim().parse::<f32>().ok().map(Size::Percent);
}
let number = value.strip_suffix("px").unwrap_or(value).trim();
number.parse::<f32>().ok().map(Size::Px)
}
pub fn parse_size_or_auto(value: &str) -> Size {
size_or_auto_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid size value: \"{value}\"");
Size::Auto
})
}
fn offset_impl(value: &str) -> Option<Offset> {
let value = value.trim();
if let Some(percent) = value.strip_suffix('%') {
return percent.trim().parse::<f32>().ok().map(Offset::Percent);
}
let number = value.strip_suffix("px").unwrap_or(value).trim();
number.parse::<f32>().ok().map(Offset::Px)
}
pub fn parse_offset(value: &str) -> Offset {
offset_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid offset value: \"{value}\"");
Offset::default()
})
}
fn align_impl(value: &str, start: &str, end: &str) -> Option<Align> {
match value.trim().to_ascii_lowercase().as_str() {
value if value == start => Some(Align::Start),
"center" => Some(Align::Center),
value if value == end => Some(Align::End),
_ => None,
}
}
pub fn parse_align_x(value: &str) -> Align {
align_impl(value, "left", "right").unwrap_or_else(|| {
debug_assert!(false, "invalid position-x value: \"{value}\"");
Align::Start
})
}
pub fn parse_align_y(value: &str) -> Align {
align_impl(value, "top", "bottom").unwrap_or_else(|| {
debug_assert!(false, "invalid position-y value: \"{value}\"");
Align::Start
})
}
pub fn parse_justify(value: &str) -> Align {
align_impl(value, "start", "end").unwrap_or_else(|| {
debug_assert!(false, "invalid justify-content value: \"{value}\"");
Align::Start
})
}
pub fn parse_align_items(value: &str) -> Align {
match align_impl(value, "start", "end") {
Some(align) => align,
None => {
eprintln!("warning: invalid align-items value: {value:?}, using 'start'");
Align::Start
}
}
}
fn overflow_impl(value: &str) -> Option<Overflow> {
match value.trim().to_ascii_lowercase().as_str() {
"visible" => Some(Overflow::Visible),
"hidden" => Some(Overflow::Hidden),
"auto" => Some(Overflow::Auto),
"scroll" => Some(Overflow::Scroll),
_ => None,
}
}
pub fn parse_overflow(value: &str) -> Overflow {
overflow_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid overflow value: \"{value}\"");
Overflow::Visible
})
}
fn white_space_impl(value: &str) -> Option<WhiteSpace> {
match value.trim().to_ascii_lowercase().as_str() {
"normal" | "wrap" => Some(WhiteSpace::Normal),
"nowrap" | "no-wrap" => Some(WhiteSpace::Nowrap),
_ => None,
}
}
pub fn parse_white_space(value: &str) -> WhiteSpace {
white_space_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid white-space value: \"{value}\"");
WhiteSpace::Normal
})
}
fn position_impl(value: &str) -> Option<Position> {
match value.trim().to_ascii_lowercase().as_str() {
"flow" | "static" | "relative" => Some(Position::Flow),
"absolute" => Some(Position::Absolute),
_ => None,
}
}
pub fn parse_position(value: &str) -> Position {
position_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid position value: \"{value}\"");
Position::Flow
})
}
fn px_impl(value: &str) -> Option<f32> {
let value = value.trim();
let number = value.strip_suffix("px").unwrap_or(value).trim();
number.parse::<f32>().ok()
}
pub fn parse_px(value: &str) -> f32 {
px_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid pixel value: \"{value}\"");
0.0
})
}
fn color_impl(value: &str) -> Option<u32> {
let raw = value.trim();
let digits = raw
.strip_prefix('#')
.or_else(|| raw.strip_prefix("0x"))
.unwrap_or(raw);
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let byte = |text: &str| u8::from_str_radix(text, 16).ok();
let (r, g, b, a) = match digits.len() {
3 => (
byte(&digits[0..1])? * 17,
byte(&digits[1..2])? * 17,
byte(&digits[2..3])? * 17,
0xFF,
),
4 => (
byte(&digits[0..1])? * 17,
byte(&digits[1..2])? * 17,
byte(&digits[2..3])? * 17,
byte(&digits[3..4])? * 17,
),
6 => (
byte(&digits[0..2])?,
byte(&digits[2..4])?,
byte(&digits[4..6])?,
0xFF,
),
8 => (
byte(&digits[0..2])?,
byte(&digits[2..4])?,
byte(&digits[4..6])?,
byte(&digits[6..8])?,
),
_ => return None,
};
Some(((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | a as u32)
}
pub fn parse_color(value: &str) -> Option<u32> {
let parsed = color_impl(value);
debug_assert!(
parsed.is_some(),
"invalid color value: \"{value}\" (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)"
);
parsed
}
pub fn parse_bool(value: &str) -> bool {
matches!(value.trim(), "true" | "1" | "yes" | "on")
}
fn required_indicator_impl(value: &str) -> Option<RequiredIndicator> {
match value.trim() {
"" | "*" => Some(RequiredIndicator::Asterisk),
"none" => Some(RequiredIndicator::None),
other => color_impl(other).map(RequiredIndicator::Accent),
}
}
pub fn parse_required_indicator(value: &str) -> RequiredIndicator {
required_indicator_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid required-indicator value: \"{value}\"");
RequiredIndicator::Asterisk
})
}
fn button_type_impl(value: &str) -> Option<ButtonType> {
match value.trim().to_ascii_lowercase().as_str() {
"" | "submit" => Some(ButtonType::Submit),
"button" => Some(ButtonType::Button),
"reset" => Some(ButtonType::Reset),
_ => None,
}
}
pub fn parse_button_type(value: &str) -> ButtonType {
button_type_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid button type value: \"{value}\"");
ButtonType::Submit
})
}
fn resize_impl(value: &str) -> Option<Resize> {
match value.trim().to_ascii_lowercase().as_str() {
"" | "none" => Some(Resize::None),
"horizontal" => Some(Resize::Horizontal),
"vertical" => Some(Resize::Vertical),
"both" => Some(Resize::Both),
_ => None,
}
}
pub fn parse_resize(value: &str) -> Resize {
resize_impl(value).unwrap_or_else(|| {
debug_assert!(false, "invalid resize value: \"{value}\"");
Resize::None
})
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Style {
pub width: Size,
pub height: Size,
pub min_width: Option<Size>,
pub min_height: Option<Size>,
pub max_width: Option<Size>,
pub max_height: Option<Size>,
pub flex_grow: f32,
pub flex_shrink: f32,
pub position: Position,
pub overflow_x: Overflow,
pub overflow_y: Overflow,
pub white_space: Option<WhiteSpace>,
pub align_x: Align,
pub align_y: Align,
pub offset_x: Offset,
pub offset_y: Offset,
pub justify_content: Align,
pub align_items: Align,
pub padding: Edges,
pub margin: Edges,
pub background: Option<u32>,
pub font_color: Option<u32>,
pub font_size: Option<f32>,
pub border_color: Option<u32>,
pub border_size: f32,
pub visible: bool,
pub required: bool,
pub invalid: bool,
pub required_indicator: RequiredIndicator,
pub z: i32,
}
impl Default for Style {
fn default() -> Self {
Self {
width: Size::Auto,
height: Size::Auto,
min_width: None,
min_height: None,
max_width: None,
max_height: None,
flex_grow: 0.0,
flex_shrink: 1.0,
position: Position::Flow,
overflow_x: Overflow::Visible,
overflow_y: Overflow::Visible,
white_space: None,
align_x: Align::Start,
align_y: Align::Start,
offset_x: Offset::Px(0.0),
offset_y: Offset::Px(0.0),
justify_content: Align::Start,
align_items: Align::Start,
padding: Edges::ZERO,
margin: Edges::ZERO,
background: None,
font_color: None,
font_size: None,
border_color: None,
border_size: 0.0,
visible: true,
required: false,
invalid: false,
required_indicator: RequiredIndicator::Asterisk,
z: 0,
}
}
}
impl Style {
pub fn inset(&self) -> Edges {
self.padding.plus(Edges::all(self.border_size))
}
pub fn resolve_width(&self, content: f32, available: f32) -> f32 {
let mut value = self.width.resolve(content, available);
if let Some(min) = self.min_width {
value = value.max(min.resolve(content, available));
}
if let Some(max) = self.max_width {
value = value.min(max.resolve(content, available));
}
value.max(0.0)
}
pub fn resolve_height(&self, content: f32, available: f32) -> f32 {
let mut value = self.height.resolve(content, available);
if let Some(min) = self.min_height {
value = value.max(min.resolve(content, available));
}
if let Some(max) = self.max_height {
value = value.min(max.resolve(content, available));
}
value.max(0.0)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SelectOption {
pub label: String,
pub value: String,
}
#[cfg(feature = "image-support")]
static NEXT_IMAGE_ID: AtomicU64 = AtomicU64::new(1);
#[cfg(feature = "image-support")]
#[derive(Clone, PartialEq)]
pub struct ImageData {
pub(crate) key: Arc<str>,
pub(crate) bytes: Arc<[u8]>,
pub(crate) width: u32,
pub(crate) height: u32,
}
#[cfg(all(feature = "image-support", feature = "devtools"))]
impl serde::Serialize for ImageData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("ImageData", 3)?;
state.serialize_field("width", &self.width)?;
state.serialize_field("height", &self.height)?;
state.serialize_field("key", &*self.key)?;
state.end()
}
}
#[cfg(feature = "image-support")]
impl ImageData {
pub fn from_png(bytes: Vec<u8>) -> crate::Result<Self> {
Self::from_png_limited(bytes, 8 * 1024 * 1024, 4096)
}
pub fn from_png_limited(
bytes: Vec<u8>,
max_bytes: usize,
max_dimension: u32,
) -> crate::Result<Self> {
if bytes.len() > max_bytes {
return Err(crate::Error::Image(format!(
"файл слишком большой: {} байт (максимум {max_bytes})",
bytes.len()
)));
}
const SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
if bytes.len() < 24 || &bytes[..8] != SIGNATURE || &bytes[12..16] != b"IHDR" {
return Err(crate::Error::Image(
"файл не является PNG с корректным заголовком IHDR".to_owned(),
));
}
let width = u32::from_be_bytes(bytes[16..20].try_into().unwrap_or_default());
let height = u32::from_be_bytes(bytes[20..24].try_into().unwrap_or_default());
if width == 0 || height == 0 || width > max_dimension || height > max_dimension {
return Err(crate::Error::Image(format!(
"недопустимое разрешение {width}x{height} (максимум {max_dimension} px)"
)));
}
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes.as_slice()));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder
.read_info()
.map_err(|error| crate::Error::Image(error.to_string()))?;
let mut buffer = vec![0; reader.output_buffer_size()];
reader
.next_frame(&mut buffer)
.map_err(|error| crate::Error::Image(error.to_string()))?;
let id = NEXT_IMAGE_ID.fetch_add(1, Ordering::Relaxed);
Ok(Self {
key: Arc::from(format!("runtime-image-{id}")),
bytes: Arc::from(bytes),
width,
height,
})
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
}
#[cfg(feature = "image-support")]
impl std::fmt::Debug for ImageData {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ImageData")
.field("key", &self.key)
.field("bytes", &self.bytes.len())
.field("width", &self.width)
.field("height", &self.height)
.finish()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum NodeKind {
Column,
Row,
TitleBar,
Window,
Text {
content: String,
},
#[cfg(feature = "image-support")]
Image {
src: &'static str,
data: &'static [u8],
width: u32,
height: u32,
alt: String,
},
#[cfg(feature = "image-support")]
RuntimeImage {
image: ImageData,
alt: String,
},
Button {
disabled: bool,
button_type: ButtonType,
},
TextField {
value: String,
placeholder: String,
disabled: bool,
multiline: bool,
resize: Resize,
masked: bool,
},
#[cfg(feature = "elements-checkbox")]
Checkbox {
label: String,
checked: bool,
disabled: bool,
},
#[cfg(feature = "elements-radio")]
Radio {
label: String,
value: String,
selected: bool,
disabled: bool,
},
#[cfg(feature = "elements-select")]
Select {
value: String,
options: Vec<SelectOption>,
disabled: bool,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct VElement {
pub key: &'static str,
pub kind: NodeKind,
pub style: Style,
pub tag: &'static str,
pub attrs: Vec<(&'static str, String)>,
pub window: Option<WindowConfig>,
pub children: Vec<VElement>,
}
impl VElement {
pub fn leaf(key: &'static str, kind: NodeKind) -> Self {
Self {
key,
kind,
style: Style::default(),
tag: "",
attrs: Vec::new(),
window: None,
children: Vec::new(),
}
}
pub fn container(key: &'static str, kind: NodeKind, children: Vec<VElement>) -> Self {
Self {
key,
kind,
style: Style::default(),
tag: "",
attrs: Vec::new(),
window: None,
children,
}
}
pub fn with_style(mut self, style: Style) -> Self {
self.style = style;
self
}
pub fn with_window(mut self, config: WindowConfig) -> Self {
self.window = Some(config);
self
}
pub fn window_config(&self) -> Option<&WindowConfig> {
self.window.as_ref()
}
pub fn with_tag(mut self, tag: &'static str) -> Self {
self.tag = tag;
self
}
pub fn with_attr(mut self, name: &'static str, value: impl Into<String>) -> Self {
self.attrs.push((name, value.into()));
self
}
pub fn with_attrs(mut self, attrs: Vec<(&'static str, String)>) -> Self {
self.attrs = attrs;
self
}
pub fn attr(&self, name: &str) -> Option<&str> {
self.attrs
.iter()
.find(|(key, _)| *key == name)
.map(|(_, value)| value.as_str())
}
pub fn to_json(&self) -> serde_json::Value {
let children: Vec<_> = self.children.iter().map(VElement::to_json).collect();
serde_json::json!({
"tag": self.tag,
"key": self.key,
"attrs": &self.attrs,
"children": children,
})
}
pub fn get(&self, key: &str) -> Option<&VElement> {
if self.key == key {
return Some(self);
}
self.children.iter().find_map(|child| child.get(key))
}
pub fn find_by_tag(&self, tag: &str) -> Option<&VElement> {
if self.tag == tag {
return Some(self);
}
self.children
.iter()
.find_map(|child| child.find_by_tag(tag))
}
pub fn find_by_attr(&self, name: &str, value: &str) -> Option<&VElement> {
if self.attr(name) == Some(value) {
return Some(self);
}
self.children
.iter()
.find_map(|child| child.find_by_attr(name, value))
}
pub fn get_mut(&mut self, key: &str) -> Option<&mut VElement> {
if self.key == key {
return Some(self);
}
self.children
.iter_mut()
.find_map(|child| child.get_mut(key))
}
pub fn content(&self) -> Option<&str> {
match &self.kind {
NodeKind::Text { content } => Some(content),
_ => None,
}
}
pub fn descendants(&self) -> Collection<&VElement> {
let mut nodes = Collection::new();
self.collect_descendants(&mut nodes);
nodes
}
fn collect_descendants<'a>(&'a self, out: &mut Collection<&'a VElement>) {
out.push(self);
for child in &self.children {
child.collect_descendants(out);
}
}
pub fn find_by_content(&self, content: &str) -> Option<&VElement> {
if self.content() == Some(content) {
return Some(self);
}
self.children
.iter()
.find_map(|child| child.find_by_content(content))
}
pub fn find_containing(&self, needle: &str) -> Option<&VElement> {
if self
.content()
.is_some_and(|content| content.contains(needle))
{
return Some(self);
}
self.children
.iter()
.find_map(|child| child.find_containing(needle))
}
fn find_titlebar(&self) -> Option<&VElement> {
if matches!(self.kind, NodeKind::TitleBar) {
return Some(self);
}
self.children.iter().find_map(VElement::find_titlebar)
}
fn collect_plain_text(&self, out: &mut String) {
match &self.kind {
NodeKind::Text { content } => out.push_str(content),
NodeKind::Button { .. } | NodeKind::TextField { .. } => {}
#[cfg(feature = "elements-checkbox")]
NodeKind::Checkbox { .. } => {}
#[cfg(feature = "elements-radio")]
NodeKind::Radio { .. } => {}
#[cfg(feature = "elements-select")]
NodeKind::Select { .. } => {}
_ => {
for child in &self.children {
child.collect_plain_text(out);
}
}
}
}
pub fn collect_plain_text_public(&self, out: &mut String) {
self.collect_plain_text(out)
}
pub fn titlebar_text(&self) -> Option<String> {
let bar = self.find_titlebar()?;
let mut text = String::new();
bar.collect_plain_text(&mut text);
let trimmed = text.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_owned())
}
}
}
pub trait VNode {
fn key(&self) -> &'static str;
fn kind(&self) -> &NodeKind;
fn kind_mut(&mut self) -> &mut NodeKind;
fn style(&self) -> &Style;
fn style_mut(&mut self) -> &mut Style;
fn tag(&self) -> &'static str;
fn attrs(&self) -> &[(&'static str, String)];
fn children(&self) -> &[VElement];
fn attr(&self, name: &str) -> Option<&str> {
self.attrs()
.iter()
.find(|(key, _)| *key == name)
.map(|(_, value)| value.as_str())
}
fn text(&self) -> Option<&str> {
match self.kind() {
NodeKind::Text { content } => Some(content),
_ => None,
}
}
fn set_text(&mut self, value: impl Into<String>) {
if let NodeKind::Text { content } = self.kind_mut() {
*content = value.into();
}
}
fn visible(&self) -> bool {
self.style().visible
}
fn set_visible(&mut self, value: bool) {
self.style_mut().visible = value;
}
fn disabled(&self) -> bool {
match self.kind() {
NodeKind::Button { disabled, .. } | NodeKind::TextField { disabled, .. } => *disabled,
#[cfg(feature = "elements-checkbox")]
NodeKind::Checkbox { disabled, .. } => *disabled,
#[cfg(feature = "elements-radio")]
NodeKind::Radio { disabled, .. } => *disabled,
#[cfg(feature = "elements-select")]
NodeKind::Select { disabled, .. } => *disabled,
_ => false,
}
}
fn set_disabled(&mut self, value: bool) {
match self.kind_mut() {
NodeKind::Button { disabled, .. } | NodeKind::TextField { disabled, .. } => {
*disabled = value;
}
#[cfg(feature = "elements-checkbox")]
NodeKind::Checkbox { disabled, .. } => *disabled = value,
#[cfg(feature = "elements-radio")]
NodeKind::Radio { disabled, .. } => *disabled = value,
#[cfg(feature = "elements-select")]
NodeKind::Select { disabled, .. } => *disabled = value,
_ => {}
}
}
fn value(&self) -> Option<&str> {
match self.kind() {
NodeKind::TextField { value, .. } => Some(value),
#[cfg(feature = "elements-select")]
NodeKind::Select { value, .. } => Some(value),
_ => None,
}
}
fn set_value(&mut self, new_value: impl Into<String>) {
let new_value = new_value.into();
match self.kind_mut() {
NodeKind::TextField { value, .. } => {
*value = new_value;
}
#[cfg(feature = "elements-select")]
NodeKind::Select { value, .. } => {
*value = new_value;
}
_ => {}
}
}
fn checked(&self) -> bool {
#[cfg(feature = "elements-checkbox")]
{
matches!(self.kind(), NodeKind::Checkbox { checked: true, .. })
}
#[cfg(not(feature = "elements-checkbox"))]
{
false
}
}
fn set_checked(&mut self, value: bool) {
#[cfg(feature = "elements-checkbox")]
if let NodeKind::Checkbox { checked, .. } = self.kind_mut() {
*checked = value;
}
#[cfg(not(feature = "elements-checkbox"))]
let _ = value;
}
fn selected(&self) -> bool {
#[cfg(feature = "elements-radio")]
{
matches!(self.kind(), NodeKind::Radio { selected: true, .. })
}
#[cfg(not(feature = "elements-radio"))]
{
false
}
}
fn set_selected(&mut self, value: bool) {
#[cfg(feature = "elements-radio")]
if let NodeKind::Radio { selected, .. } = self.kind_mut() {
*selected = value;
}
#[cfg(not(feature = "elements-radio"))]
let _ = value;
}
fn options(&self) -> &[SelectOption] {
match self.kind() {
#[cfg(feature = "elements-select")]
NodeKind::Select { options, .. } => options,
_ => &[],
}
}
fn set_options(&mut self, value: Vec<SelectOption>) {
#[cfg(feature = "elements-select")]
if let NodeKind::Select { options, .. } = self.kind_mut() {
*options = value;
}
#[cfg(not(feature = "elements-select"))]
let _ = value;
}
fn act(&self, command: WindowCommand) {
crate::control::request(command);
}
}
pub trait VWindow: VNode {
fn config(&self) -> Option<&WindowConfig>;
fn close(&self) {
self.act(WindowCommand::Close);
}
fn minimize(&self) {
self.act(WindowCommand::Minimize);
}
fn maximize(&self) {
self.act(WindowCommand::Maximize);
}
fn restore(&self) {
self.act(WindowCommand::Restore);
}
fn toggle_maximize(&self) {
self.act(WindowCommand::ToggleMaximize);
}
fn show(&self) {
self.act(WindowCommand::Show);
}
fn hide(&self) {
self.act(WindowCommand::Hide);
}
fn open_modal(&self) {
self.act(WindowCommand::OpenModal);
}
fn open_window(&self) {
self.act(WindowCommand::OpenWindow);
}
fn open(&self, id: &str) {
self.act(WindowCommand::Open(id.to_owned()));
}
fn close_window(&self, id: &str) {
self.act(WindowCommand::CloseWindow(id.to_owned()));
}
fn show_window(&self, id: &str) {
self.act(WindowCommand::ShowWindow(id.to_owned()));
}
fn hide_window(&self, id: &str) {
self.act(WindowCommand::HideWindow(id.to_owned()));
}
fn is_maximized(&self) -> bool {
crate::control::is_maximized()
}
}
impl VNode for VElement {
fn key(&self) -> &'static str {
self.key
}
fn kind(&self) -> &NodeKind {
&self.kind
}
fn kind_mut(&mut self) -> &mut NodeKind {
&mut self.kind
}
fn style(&self) -> &Style {
&self.style
}
fn style_mut(&mut self) -> &mut Style {
&mut self.style
}
fn tag(&self) -> &'static str {
self.tag
}
fn attrs(&self) -> &[(&'static str, String)] {
&self.attrs
}
fn children(&self) -> &[VElement] {
&self.children
}
}
impl VWindow for VElement {
fn config(&self) -> Option<&WindowConfig> {
self.window.as_ref()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Op {
SetContent {
key: &'static str,
content: String,
},
SetLabel {
key: &'static str,
label: String,
},
SetDisabled {
key: &'static str,
disabled: bool,
},
SetValue {
key: &'static str,
value: String,
},
SetPlaceholder {
key: &'static str,
placeholder: String,
},
SetMasked {
key: &'static str,
masked: bool,
},
SetChecked {
key: &'static str,
checked: bool,
},
SetSelected {
key: &'static str,
selected: bool,
},
SetOptions {
key: &'static str,
options: Vec<SelectOption>,
},
Insert {
key: &'static str,
},
Remove {
key: &'static str,
},
Replace {
key: &'static str,
},
}
impl Op {
pub fn key(&self) -> &'static str {
match self {
Self::SetContent { key, .. }
| Self::SetLabel { key, .. }
| Self::SetDisabled { key, .. }
| Self::SetValue { key, .. }
| Self::SetPlaceholder { key, .. }
| Self::SetMasked { key, .. }
| Self::SetChecked { key, .. }
| Self::SetSelected { key, .. }
| Self::SetOptions { key, .. }
| Self::Insert { key }
| Self::Remove { key }
| Self::Replace { key } => key,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Patch {
pub ops: Vec<Op>,
pub changed: BTreeSet<&'static str>,
}
impl Patch {
pub fn is_empty(&self) -> bool {
self.ops.is_empty()
}
}
pub fn diff(old: &VElement, new: &VElement) -> Patch {
let mut patch = Patch::default();
diff_node(old, new, &mut patch);
patch
}
fn diff_node(old: &VElement, new: &VElement, patch: &mut Patch) {
if old.key != new.key {
debug_assert!(false, "diff_node вызван для разных ключей");
patch.ops.push(Op::Replace { key: new.key });
patch.changed.insert(new.key);
return;
}
if !kind_compatible(&old.kind, &new.kind) {
patch.ops.push(Op::Replace { key: new.key });
patch.changed.insert(new.key);
return;
}
if old.style != new.style {
patch.changed.insert(new.key);
}
if old.attrs != new.attrs {
patch.changed.insert(new.key);
}
diff_kind(&old.kind, &new.kind, new.key, patch);
diff_children(old, new, patch);
}
fn kind_compatible(a: &NodeKind, b: &NodeKind) -> bool {
match (a, b) {
(NodeKind::Column, NodeKind::Column)
| (NodeKind::Row, NodeKind::Row)
| (NodeKind::TitleBar, NodeKind::TitleBar)
| (NodeKind::Window, NodeKind::Window)
| (NodeKind::Text { .. }, NodeKind::Text { .. })
| (NodeKind::Button { .. }, NodeKind::Button { .. })
| (NodeKind::TextField { .. }, NodeKind::TextField { .. }) => true,
#[cfg(feature = "image-support")]
(NodeKind::Image { src: src_a, .. }, NodeKind::Image { src: src_b, .. }) => src_a == src_b,
#[cfg(feature = "image-support")]
(NodeKind::RuntimeImage { image: a, .. }, NodeKind::RuntimeImage { image: b, .. }) => {
a.key == b.key
}
#[cfg(feature = "elements-checkbox")]
(NodeKind::Checkbox { .. }, NodeKind::Checkbox { .. }) => true,
#[cfg(feature = "elements-radio")]
(NodeKind::Radio { .. }, NodeKind::Radio { .. }) => true,
#[cfg(feature = "elements-select")]
(NodeKind::Select { .. }, NodeKind::Select { .. }) => true,
_ => false,
}
}
fn diff_kind(old: &NodeKind, new: &NodeKind, key: &'static str, patch: &mut Patch) {
match (old, new) {
(NodeKind::Text { content: a }, NodeKind::Text { content: b }) => {
if a != b {
patch.ops.push(Op::SetContent {
key,
content: b.clone(),
});
patch.changed.insert(key);
}
}
#[cfg(feature = "image-support")]
(
NodeKind::Image {
data: data_a,
alt: alt_a,
..
},
NodeKind::Image {
data: data_b,
alt: alt_b,
..
},
) => {
if data_a != data_b || alt_a != alt_b {
patch.changed.insert(key);
}
}
#[cfg(feature = "image-support")]
(
NodeKind::RuntimeImage {
image: image_a,
alt: alt_a,
},
NodeKind::RuntimeImage {
image: image_b,
alt: alt_b,
},
) => {
if image_a != image_b || alt_a != alt_b {
patch.changed.insert(key);
}
}
(
NodeKind::Button {
disabled: disabled_a,
button_type: type_a,
},
NodeKind::Button {
disabled: disabled_b,
button_type: button_type_b,
},
) => {
if disabled_a != disabled_b {
patch.ops.push(Op::SetDisabled {
key,
disabled: *disabled_b,
});
patch.changed.insert(key);
}
if type_a != button_type_b {
patch.changed.insert(key);
}
}
(
NodeKind::TextField {
value: value_a,
placeholder: placeholder_a,
disabled: disabled_a,
multiline: multiline_a,
resize: resize_a,
masked: masked_a,
},
NodeKind::TextField {
value: value_b,
placeholder: placeholder_b,
disabled: disabled_b,
multiline: multiline_b,
resize: resize_b,
masked: masked_b,
},
) => {
if value_a != value_b {
patch.ops.push(Op::SetValue {
key,
value: value_b.clone(),
});
patch.changed.insert(key);
}
if placeholder_a != placeholder_b {
patch.ops.push(Op::SetPlaceholder {
key,
placeholder: placeholder_b.clone(),
});
patch.changed.insert(key);
}
if disabled_a != disabled_b {
patch.ops.push(Op::SetDisabled {
key,
disabled: *disabled_b,
});
patch.changed.insert(key);
}
if multiline_a != multiline_b {
patch.changed.insert(key);
}
if resize_a != resize_b {
patch.changed.insert(key);
}
if masked_a != masked_b {
patch.ops.push(Op::SetMasked {
key,
masked: *masked_b,
});
patch.changed.insert(key);
}
}
#[cfg(feature = "elements-checkbox")]
(
NodeKind::Checkbox {
label: label_a,
checked: checked_a,
disabled: disabled_a,
},
NodeKind::Checkbox {
label: label_b,
checked: checked_b,
disabled: disabled_b,
},
) => {
if label_a != label_b {
patch.ops.push(Op::SetLabel {
key,
label: label_b.clone(),
});
patch.changed.insert(key);
}
if checked_a != checked_b {
patch.ops.push(Op::SetChecked {
key,
checked: *checked_b,
});
patch.changed.insert(key);
}
if disabled_a != disabled_b {
patch.ops.push(Op::SetDisabled {
key,
disabled: *disabled_b,
});
patch.changed.insert(key);
}
}
#[cfg(feature = "elements-radio")]
(
NodeKind::Radio {
label: label_a,
value: value_a,
selected: selected_a,
disabled: disabled_a,
},
NodeKind::Radio {
label: label_b,
value: value_b,
selected: selected_b,
disabled: disabled_b,
},
) => {
if label_a != label_b {
patch.ops.push(Op::SetLabel {
key,
label: label_b.clone(),
});
patch.changed.insert(key);
}
if value_a != value_b {
patch.changed.insert(key);
}
if selected_a != selected_b {
patch.ops.push(Op::SetSelected {
key,
selected: *selected_b,
});
patch.changed.insert(key);
}
if disabled_a != disabled_b {
patch.ops.push(Op::SetDisabled {
key,
disabled: *disabled_b,
});
patch.changed.insert(key);
}
}
#[cfg(feature = "elements-select")]
(
NodeKind::Select {
value: value_a,
options: options_a,
disabled: disabled_a,
},
NodeKind::Select {
value: value_b,
options: options_b,
disabled: disabled_b,
},
) => {
if value_a != value_b {
patch.ops.push(Op::SetValue {
key,
value: value_b.clone(),
});
patch.changed.insert(key);
}
if options_a != options_b {
patch.ops.push(Op::SetOptions {
key,
options: options_b.clone(),
});
patch.changed.insert(key);
}
if disabled_a != disabled_b {
patch.ops.push(Op::SetDisabled {
key,
disabled: *disabled_b,
});
patch.changed.insert(key);
}
}
(NodeKind::Column, NodeKind::Column)
| (NodeKind::Row, NodeKind::Row)
| (NodeKind::TitleBar, NodeKind::TitleBar)
| (NodeKind::Window, NodeKind::Window) => {}
_ => debug_assert!(false, "несовместимые типы должны фильтроваться раньше"),
}
}
fn diff_children(old: &VElement, new: &VElement, patch: &mut Patch) {
let old_by_key: HashMap<&'static str, &VElement> = old
.children
.iter()
.map(|child| (child.key, child))
.collect();
let mut matched = HashSet::new();
for new_child in &new.children {
match old_by_key.get(new_child.key) {
Some(old_child) => {
matched.insert(new_child.key);
diff_node(old_child, new_child, patch);
}
None => {
patch.ops.push(Op::Insert { key: new_child.key });
patch.changed.insert(new_child.key);
}
}
}
for old_child in &old.children {
if !matched.contains(old_child.key) {
patch.ops.push(Op::Remove { key: old_child.key });
patch.changed.insert(old_child.key);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_align_items_accepts_center() {
assert_eq!(parse_align_items("center"), Align::Center);
assert_eq!(parse_align_items("start"), Align::Start);
assert_eq!(parse_align_items("end"), Align::End);
}
#[test]
fn invalid_align_items_returns_start_not_panic() {
let result = std::panic::catch_unwind(|| {
parse_align_items("ыефке")
});
assert!(
result.is_ok(),
"parse_align_items panicked on invalid value"
);
assert_eq!(result.unwrap(), Align::Start);
}
}