use std::any::Any;
use std::fmt;
use crate::align::{Align, Anchors, SelfAlign};
use crate::canvas::Canvas;
use crate::error::{Error, Result};
use crate::event::{EventArgs, EventCtx, KeyEvent, PointerEvent, WheelEvent};
use crate::geometry::{Bounds, PointF, RectF, SizeF};
use crate::paint::PaintCtx;
use crate::platform::CursorShape;
use crate::prop::{PropInfo, PropKind, PropValue};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ComponentId {
pub(crate) index: u32,
pub(crate) generation: u32,
}
impl ComponentId {
pub fn to_u64(self) -> u64 {
(self.generation as u64) << 32 | self.index as u64
}
pub fn from_u64(value: u64) -> Self {
Self { index: value as u32, generation: (value >> 32) as u32 }
}
}
impl fmt::Display for ComponentId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}v{}", self.index, self.generation)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ControlState {
pub hover: bool,
pub pressed: bool,
pub focused: bool,
pub checked: bool,
pub disabled: bool,
}
pub trait Component: Any {
fn class_name(&self) -> &'static str;
fn inner(&self) -> Option<&dyn Component> {
None
}
fn inner_mut(&mut self) -> Option<&mut dyn Component> {
None
}
fn class_chain(&self, out: &mut Vec<&'static str>) {
out.push(self.class_name());
if let Some(inner) = self.inner() {
inner.class_chain(out);
}
}
fn control(&self) -> Option<&ControlBase> {
self.inner().and_then(|i| i.control())
}
fn control_mut(&mut self) -> Option<&mut ControlBase> {
self.inner_mut().and_then(|i| i.control_mut())
}
fn props(&self) -> &'static [PropInfo] {
&[]
}
fn default_event(&self) -> Option<&'static str> {
self.inner().and_then(|c| c.default_event())
}
fn get_prop(&self, _name: &str) -> Option<PropValue> {
None
}
fn set_prop(&mut self, name: &str, _value: PropValue) -> Result<()> {
Err(Error::UnknownProperty(name.to_string()))
}
fn notification(&mut self, freed: ComponentId) {
if let Some(inner) = self.inner_mut() {
inner.notification(freed);
}
}
fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
if let Some(inner) = self.inner() {
inner.paint(canvas, ctx);
}
}
fn transparent_background(&self) -> bool {
self.inner().is_some_and(|i| i.transparent_background())
}
fn opaque(&self, style: &crate::theme::ResolvedStyle) -> bool {
self.inner().is_some_and(|i| i.opaque(style))
}
fn paint_after(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
if let Some(inner) = self.inner() {
inner.paint_after(canvas, ctx);
}
}
fn paint_is_pure(&self) -> bool {
false
}
fn provided(&self) -> Option<crate::providers::Provided<'_>> {
None
}
fn resized(&mut self, ctx: &mut EventCtx<'_>) {
if let Some(inner) = self.inner_mut() {
inner.resized(ctx);
}
}
fn click(&mut self, ctx: &mut EventCtx<'_>) {
match self.inner_mut() {
Some(inner) => inner.click(ctx),
None => ctx.fire("on_click", EventArgs::None),
}
}
fn pointer_down(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
if let Some(inner) = self.inner_mut() {
inner.pointer_down(ctx, event);
}
}
fn pointer_up(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
if let Some(inner) = self.inner_mut() {
inner.pointer_up(ctx, event);
}
}
fn pointer_move(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
if let Some(inner) = self.inner_mut() {
inner.pointer_move(ctx, event);
}
}
fn pointer_enter(&mut self, ctx: &mut EventCtx<'_>) {
if let Some(inner) = self.inner_mut() {
inner.pointer_enter(ctx);
}
}
fn pointer_leave(&mut self, ctx: &mut EventCtx<'_>) {
if let Some(inner) = self.inner_mut() {
inner.pointer_leave(ctx);
}
}
fn wheel(&mut self, ctx: &mut EventCtx<'_>, event: &WheelEvent) {
if let Some(inner) = self.inner_mut() {
inner.wheel(ctx, event);
}
}
fn gesture(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::GestureEvent) {
if let Some(inner) = self.inner_mut() {
inner.gesture(ctx, event);
}
}
fn key_down(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
if let Some(inner) = self.inner_mut() {
inner.key_down(ctx, event);
}
}
fn key_up(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
if let Some(inner) = self.inner_mut() {
inner.key_up(ctx, event);
}
}
fn shortcut(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
if let Some(inner) = self.inner_mut() {
inner.shortcut(ctx, event);
}
}
fn platform_hooks(&self) -> Option<&dyn PlatformHooks> {
self.inner().and_then(|i| i.platform_hooks())
}
fn platform_hooks_mut(&mut self) -> Option<&mut dyn PlatformHooks> {
self.inner_mut().and_then(|i| i.platform_hooks_mut())
}
fn design_hooks(&self) -> Option<&dyn DesignHooks> {
self.inner().and_then(|i| i.design_hooks())
}
fn design_hooks_mut(&mut self) -> Option<&mut dyn DesignHooks> {
self.inner_mut().and_then(|i| i.design_hooks_mut())
}
fn contains_point(&self, local: PointF, size: SizeF) -> bool {
self.inner().map_or(true, |i| i.contains_point(local, size))
}
fn hit_slop(&self) -> f32 {
self.inner().map_or(0.0, |i| i.hit_slop())
}
fn scroll_axes(&self) -> (bool, bool) {
self.inner().map_or((false, false), |i| i.scroll_axes())
}
fn drag_item(&self, _ui: &crate::Ui) -> Option<(String, String)> {
None
}
fn drag_visual(&self, _ui: &crate::Ui, _source: ComponentId) -> Option<crate::DragVisual> {
None
}
fn drop_accepts(&self, _ui: &crate::Ui, _id: ComponentId, _data: &str) -> bool {
false
}
fn drop_hover(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
fn drop_leave(&mut self, _ctx: &mut EventCtx<'_>) {}
fn drop_receive(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
fn drag_ended(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _end: crate::DragEnd) {}
fn accepts_text(&self) -> bool {
self.inner().is_some_and(|i| i.accepts_text())
}
fn captures_key(&self, event: &KeyEvent) -> bool {
self.inner().is_some_and(|i| i.captures_key(event))
}
fn mnemonic_text(&self) -> Option<&str> {
self.inner().and_then(|i| i.mnemonic_text())
}
fn mnemonic_focuses_child(&self) -> bool {
self.inner().is_some_and(|i| i.mnemonic_focuses_child())
}
fn text_input(&mut self, ctx: &mut EventCtx<'_>, text: &str) {
if let Some(inner) = self.inner_mut() {
inner.text_input(ctx, text);
}
}
fn focus_enter(&mut self, ctx: &mut EventCtx<'_>) {
if let Some(inner) = self.inner_mut() {
inner.focus_enter(ctx);
}
}
fn focus_exit(&mut self, ctx: &mut EventCtx<'_>) {
if let Some(inner) = self.inner_mut() {
inner.focus_exit(ctx);
}
}
fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
if let Some(inner) = self.inner_mut() {
inner.property_changed(ctx, name);
}
}
fn change_args(&self, name: &str, value: &PropValue) -> Option<EventArgs> {
match self.inner() {
Some(inner) => inner.change_args(name, value),
None => Some(EventArgs::Value(value.clone())),
}
}
fn paint_only_property(&self, name: &str) -> bool {
self.inner().is_some_and(|inner| inner.paint_only_property(name))
}
fn timer_interval(&self) -> Option<f64> {
self.inner().and_then(|i| i.timer_interval())
}
fn timer_precision(&self) -> crate::TimerPrecision {
self.inner().map(|i| i.timer_precision()).unwrap_or_default()
}
fn timer_background(&self) -> bool {
self.inner().is_some_and(|i| i.timer_background())
}
fn timer_late(&mut self, late: f64) {
if let Some(inner) = self.inner_mut() {
inner.timer_late(late);
}
}
fn frame(&mut self, ctx: &mut EventCtx<'_>) -> bool {
self.inner_mut().is_some_and(|inner| inner.frame(ctx))
}
fn timer(&mut self, ctx: &mut EventCtx<'_>) {
match self.inner_mut() {
Some(inner) => inner.timer(ctx),
None => ctx.fire("on_timer", EventArgs::None),
}
}
fn arrange(&self, area: RectF, children: &[ArrangeItem]) -> Option<Vec<RectF>> {
self.inner().and_then(|i| i.arrange(area, children))
}
fn auto_height(&self, ui: &crate::Ui, id: ComponentId, width: f32) -> Option<f32> {
self.inner().and_then(|i| i.auto_height(ui, id, width))
}
fn closes_on_outside_press(&self) -> bool {
false
}
fn dies_with(&self) -> Option<ComponentId> {
self.inner().and_then(|i| i.dies_with())
}
fn access_items(&self, ui: &crate::Ui, id: ComponentId) -> Vec<crate::automation::AccessItem> {
self.inner().map_or_else(Vec::new, |i| i.access_items(ui, id))
}
fn access_action(&mut self, ctx: &mut EventCtx<'_>, index: usize, action: crate::automation::ItemAction) -> bool {
self.inner_mut().is_some_and(|i| i.access_action(ctx, index, action))
}
fn attach(&self) -> Option<(ComponentId, f32, f32)> {
self.inner().and_then(|i| i.attach())
}
fn event_info(&self, event: &str) -> Vec<(&'static str, String)> {
self.inner().map(|i| i.event_info(event)).unwrap_or_default()
}
fn message(&mut self, ctx: &mut EventCtx<'_>, message: &dyn Any) {
if let Some(inner) = self.inner_mut() {
inner.message(ctx, message);
}
}
fn methods(&self) -> &'static [MethodInfo] {
&[]
}
fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
let class = self.class_name();
match self.inner_mut() {
Some(inner) => inner.invoke(ctx, method, args),
None => Err(format!("{class} não tem o método '{method}'")),
}
}
}
pub trait PlatformHooks {
fn taskbar(&self) -> Option<crate::taskbar::TaskbarSpec> {
None
}
fn tray(&self) -> Option<crate::tray::TraySpec> {
None
}
fn native_view(&self) -> Option<NativeView> {
None
}
fn take_native_commands(&self) -> Vec<NativeCommand> {
Vec::new()
}
fn connection(&self) -> Option<Connection> {
None
}
fn files_dropped(&mut self, _ctx: &mut EventCtx<'_>, _paths: &[String]) -> bool {
false
}
}
pub trait DesignHooks {
fn design_grip(&self, _local: PointF) -> Option<usize> {
None
}
fn design_drag(&mut self, _grip: usize, _delta: PointF, _begin: bool) -> Option<(Option<ComponentId>, &'static str, PropValue)> {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ArrangeItem {
pub id: ComponentId,
pub size: SizeF,
pub margins: Bounds,
pub span: u32,
pub spacing: f32,
}
impl ArrangeItem {
pub fn of(id: ComponentId, cb: &ControlBase) -> Self {
ArrangeItem { id, size: SizeF::new(cb.width(), cb.height()), margins: cb.margins(), span: cb.column_span(), spacing: cb.spacing_scale() }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum NativeView {
Web { url: String, html: String, generation: u64, navigation: Vec<String>, sandbox: String },
}
#[derive(Clone, Debug, PartialEq)]
pub struct WebMessage {
pub text: String,
pub url: String,
}
pub fn navigation_allowed(allowed: &[String], url: &str) -> bool {
allowed.is_empty()
|| url.starts_with("about:")
|| url.starts_with("data:")
|| allowed.iter().any(|a| {
let a = a.trim_end_matches('/');
url == a || url.starts_with(&format!("{a}/")) || url.starts_with(&format!("{a}?")) || (a.matches('/').count() <= 2 && url_origin(url) == url_origin(a))
})
}
pub fn url_origin(url: &str) -> String {
let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase())
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MethodInfo {
pub name: &'static str,
pub args: &'static [PropKind],
pub returns: Option<PropKind>,
pub params: &'static [&'static str],
}
impl MethodInfo {
pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
Self { name, args, returns, params: &[] }
}
pub const fn params(self, names: &'static [&'static str]) -> Self {
Self { params: names, ..self }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum NativeCommand {
Eval(String),
Back,
Forward,
Reload,
}
#[derive(Clone, Debug, PartialEq)]
pub struct NativeViewSlot {
pub id: ComponentId,
pub rect: crate::RectF,
pub clip: Option<crate::RectF>,
pub visible: bool,
pub view: NativeView,
pub commands: Vec<NativeCommand>,
}
pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
let mut out: Vec<PropInfo> = Vec::new();
let mut seen = std::collections::HashSet::new();
let mut push = |info: &PropInfo| {
if seen.insert(info.name) {
out.push(*info);
}
};
let mut layer = Some(component);
while let Some(l) = layer {
l.props().iter().for_each(&mut push);
layer = l.inner();
}
if component.control().is_some() {
ControlBase::PROPS.iter().for_each(&mut push);
}
out
}
pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
let mut layer = Some(component);
while let Some(l) = layer {
if let Some(info) = l.props().iter().find(|p| p.name == name) {
return Some(*info);
}
layer = l.inner();
}
if component.control().is_some() {
return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
}
None
}
pub const VALUE_PROPERTIES: [&str; 19] = [
"text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
"angle", "pressed", "position", "low", "high",
];
pub fn is_value_property(info: &PropInfo) -> bool {
match info.name {
"tab_index" | "expanded" => true,
name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
}
}
pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
let mut layer = Some(component);
while let Some(l) = layer {
if let Some(v) = l.get_prop(name) {
return Some(v);
}
layer = l.inner();
}
component.control().and_then(|cb| cb.get_prop(name))
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AnchorRef {
pub(crate) parent: SizeF,
pub(crate) rect: RectF,
}
#[derive(Clone, Debug)]
pub struct ControlBase {
left: f32,
top: f32,
width: f32,
height: f32,
margins: Bounds,
padding: Bounds,
align: Align,
anchors: Anchors,
visible: bool,
enabled: bool,
hit_test: bool,
clip_children: bool,
captures_wheel: bool,
can_focus: bool,
draggable: bool,
accepts_drops: bool,
drag: Option<Box<DragDecl>>,
tab_stop: bool,
pan_on_touch: bool,
pub(crate) popup_menu: Option<ComponentId>,
cursor: CursorShape,
opacity: f32,
rotation: f32,
translate: PointF,
cache_layer: bool,
aspect_ratio: f32,
max_width: f32,
min_width: f32,
min_height: f32,
max_height: f32,
self_align: SelfAlign,
auto_size: bool,
column_span: u32,
pub(crate) text_scale: f32,
pub(crate) spacing_scale: f32,
shadow: Option<crate::canvas::Shadow>,
tag: i64,
style: String,
theme: String,
hint: String,
state: ControlState,
pub(crate) bounds: RectF,
pub(crate) anchor_ref: Option<AnchorRef>,
pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
pub(crate) design_hidden: bool,
pub(crate) design_only: bool,
pub(crate) keep_left_to_right: bool,
pub(crate) colors: ColorOverride,
pub(crate) font: FontOverride,
scroll_offset: PointF,
pub(crate) laid_out_scroll: PointF,
pub(crate) safe_area: Bounds,
pub(crate) content_size: SizeF,
}
impl Default for ControlBase {
fn default() -> Self {
Self::new(100.0, 100.0)
}
}
impl ControlBase {
pub const PROPS: &'static [PropInfo] = &[
PropInfo::new("left", PropKind::Float, "Layout"),
PropInfo::new("top", PropKind::Float, "Layout"),
PropInfo::new("width", PropKind::Float, "Layout"),
PropInfo::new("height", PropKind::Float, "Layout"),
PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout"),
PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout"),
PropInfo::new("margins", PropKind::Bounds, "Layout"),
PropInfo::new("padding", PropKind::Bounds, "Layout"),
PropInfo::new("visible", PropKind::Bool, "Behavior"),
PropInfo::new("enabled", PropKind::Bool, "Behavior"),
PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
PropInfo::new("draggable", PropKind::Bool, "Behavior"),
PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
PropInfo::new("drag_data", PropKind::String, "Behavior"),
PropInfo::new("drag_label", PropKind::String, "Behavior"),
PropInfo::new("drag_image", PropKind::Component, "Behavior"),
PropInfo::new("drop_types", PropKind::String, "Behavior"),
PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior"),
PropInfo::new("opacity", PropKind::Float, "Appearance"),
PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
PropInfo::new("rotation", PropKind::Angle, "Layout"),
PropInfo::new("translate_x", PropKind::Float, "Appearance"),
PropInfo::new("translate_y", PropKind::Float, "Appearance"),
PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
PropInfo::new("max_width", PropKind::Float, "Layout"),
PropInfo::new("min_width", PropKind::Float, "Layout"),
PropInfo::new("min_height", PropKind::Float, "Layout"),
PropInfo::new("max_height", PropKind::Float, "Layout"),
PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout"),
PropInfo::new("auto_size", PropKind::Bool, "Layout"),
PropInfo::new("column_span", PropKind::Int, "Layout"),
PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
PropInfo::new("style", PropKind::String, "Appearance"),
PropInfo::new("theme", PropKind::String, "Appearance"),
PropInfo::new("fill", PropKind::Color, "Appearance"),
PropInfo::new("border_color", PropKind::Color, "Appearance"),
PropInfo::new("text_color", PropKind::Color, "Appearance"),
PropInfo::new("accent_color", PropKind::Color, "Appearance"),
PropInfo::new("success_color", PropKind::Color, "Appearance"),
PropInfo::new("warning_color", PropKind::Color, "Appearance"),
PropInfo::new("danger_color", PropKind::Color, "Appearance"),
PropInfo::new("font_family", PropKind::String, "Font"),
PropInfo::new("font_size", PropKind::Float, "Font"),
PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
PropInfo::new("font_italic", PropKind::Bool, "Font"),
PropInfo::new("font_underline", PropKind::Bool, "Font"),
PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
PropInfo::new("hint", PropKind::String, "Behavior"),
PropInfo::new("tag", PropKind::Int, "Misc"),
PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
PropInfo::new("on_click", PropKind::Event, "Events"),
PropInfo::new("on_dbl_click", PropKind::Event, "Events"),
PropInfo::new("on_long_press", PropKind::Event, "Events"),
PropInfo::new("on_pointer_down", PropKind::Event, "Events"),
PropInfo::new("on_pointer_up", PropKind::Event, "Events"),
PropInfo::new("on_pointer_move", PropKind::Event, "Events"),
PropInfo::new("on_pointer_enter", PropKind::Event, "Events"),
PropInfo::new("on_pointer_leave", PropKind::Event, "Events"),
PropInfo::new("on_wheel", PropKind::Event, "Events"),
PropInfo::new("on_gesture", PropKind::Event, "Events"),
PropInfo::new("on_key_down", PropKind::Event, "Events"),
PropInfo::new("on_key_press", PropKind::Event, "Events"),
PropInfo::new("on_key_up", PropKind::Event, "Events"),
PropInfo::new("on_enter", PropKind::Event, "Events"),
PropInfo::new("on_exit", PropKind::Event, "Events"),
PropInfo::new("on_resize", PropKind::Event, "Events"),
PropInfo::new("on_drag_start", PropKind::Event, "Events"),
PropInfo::new("on_drag_over", PropKind::Event, "Events"),
PropInfo::new("on_drag_drop", PropKind::Event, "Events"),
PropInfo::new("on_drag_end", PropKind::Event, "Events"),
];
pub fn new(width: f32, height: f32) -> Self {
Self {
left: 0.0,
top: 0.0,
width,
height,
margins: Bounds::ZERO,
padding: Bounds::ZERO,
align: Align::None,
anchors: Anchors::default(),
visible: true,
enabled: true,
hit_test: true,
clip_children: false,
captures_wheel: false,
can_focus: false,
draggable: false,
accepts_drops: false,
drag: None,
tab_stop: true,
pan_on_touch: true,
popup_menu: None,
cursor: CursorShape::Default,
opacity: 1.0,
rotation: 0.0,
translate: PointF::ZERO,
cache_layer: false,
aspect_ratio: 0.0,
max_width: 0.0,
min_width: 0.0,
min_height: 0.0,
max_height: 0.0,
self_align: SelfAlign::Stretch,
auto_size: false,
column_span: 1,
text_scale: 1.0,
spacing_scale: 1.0,
shadow: None,
tag: 0,
style: String::new(),
theme: String::new(),
hint: String::new(),
state: ControlState::default(),
bounds: RectF::new(0.0, 0.0, width, height),
anchor_ref: None,
follow: None,
design_hidden: false,
design_only: false,
keep_left_to_right: false,
colors: ColorOverride::default(),
font: FontOverride::default(),
scroll_offset: PointF::ZERO,
laid_out_scroll: PointF::ZERO,
content_size: SizeF::ZERO,
safe_area: Bounds::default(),
}
}
pub fn left(&self) -> f32 {
self.left
}
pub fn top(&self) -> f32 {
self.top
}
pub fn width(&self) -> f32 {
self.width
}
pub fn height(&self) -> f32 {
self.height
}
pub fn position(&self) -> PointF {
PointF::new(self.left, self.top)
}
pub fn size(&self) -> SizeF {
SizeF::new(self.width, self.height)
}
pub fn margins(&self) -> Bounds {
if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
}
pub fn padding(&self) -> Bounds {
if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
}
pub fn align(&self) -> Align {
self.align
}
pub fn anchors(&self) -> Anchors {
self.anchors
}
pub fn visible(&self) -> bool {
self.visible
}
pub fn design_only(&self) -> bool {
self.design_only
}
pub fn colors(&self) -> ColorOverride {
self.colors
}
pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
self.colors = colors;
self
}
pub fn set_design_only(&mut self, on: bool) -> &mut Self {
self.design_only = on;
self
}
pub fn keep_left_to_right(&self) -> bool {
self.keep_left_to_right
}
pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
self.keep_left_to_right = on;
self
}
pub fn enabled(&self) -> bool {
self.enabled
}
pub fn hit_test(&self) -> bool {
self.hit_test
}
pub fn clip_children(&self) -> bool {
self.clip_children
}
pub fn captures_wheel(&self) -> bool {
self.captures_wheel
}
pub fn draggable(&self) -> bool {
self.draggable
}
pub fn set_draggable(&mut self, v: bool) -> &mut Self {
self.draggable = v;
self
}
pub fn accepts_drops(&self) -> bool {
self.accepts_drops
}
pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
self.accepts_drops = v;
self
}
pub fn drag_data(&self) -> &str {
self.drag.as_ref().map_or("", |d| d.data.as_str())
}
pub fn drag_label(&self) -> &str {
self.drag.as_ref().map_or("", |d| d.label.as_str())
}
pub fn drag_image(&self) -> Option<ComponentId> {
self.drag.as_ref().and_then(|d| d.image)
}
pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
d.image = None;
}
}
pub fn drop_types(&self) -> &str {
self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
}
fn drag_decl(&mut self) -> &mut DragDecl {
self.drag.get_or_insert_with(Default::default)
}
pub fn can_focus(&self) -> bool {
self.can_focus
}
pub fn tab_stop(&self) -> bool {
self.tab_stop
}
pub fn popup_menu(&self) -> Option<ComponentId> {
self.popup_menu
}
pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
self.popup_menu = menu;
self
}
pub fn pan_on_touch(&self) -> bool {
self.pan_on_touch
}
pub fn cursor(&self) -> CursorShape {
self.cursor
}
pub fn opacity(&self) -> f32 {
self.opacity
}
pub fn cache_layer(&self) -> bool {
self.cache_layer
}
pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
self.cache_layer = on;
self
}
pub fn rotation(&self) -> f32 {
self.rotation
}
pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
self.shadow
}
pub fn aspect_ratio(&self) -> f32 {
self.aspect_ratio
}
pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
self
}
pub fn max_width(&self) -> f32 {
self.max_width
}
pub fn set_max_width(&mut self, width: f32) -> &mut Self {
self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
self
}
pub fn min_width(&self) -> f32 {
self.min_width
}
pub fn set_min_width(&mut self, width: f32) -> &mut Self {
self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
self
}
pub fn min_height(&self) -> f32 {
self.min_height
}
pub fn set_min_height(&mut self, height: f32) -> &mut Self {
self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
self
}
pub fn max_height(&self) -> f32 {
self.max_height
}
pub fn set_max_height(&mut self, height: f32) -> &mut Self {
self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
self
}
pub fn clamp_width(&self, available: f32) -> f32 {
let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
w.max(self.min_width)
}
pub fn clamp_height(&self, height: f32) -> f32 {
let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
h.max(self.min_height)
}
pub fn self_align(&self) -> SelfAlign {
self.self_align
}
pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
self.self_align = align;
self
}
pub fn band_width(&self, available: f32) -> f32 {
match self.self_align {
SelfAlign::Stretch => self.clamp_width(available),
_ if self.max_width > 0.0 => self.clamp_width(available),
_ => self.clamp_width(self.width),
}
}
pub fn band_height(&self, available: f32) -> f32 {
match self.self_align {
SelfAlign::Stretch => self.clamp_height(available),
_ if self.max_height > 0.0 => self.clamp_height(available),
_ => self.clamp_height(self.height),
}
}
pub fn band_offset(&self, available: f32, size: f32) -> f32 {
let spare = (available - size).max(0.0);
match self.self_align {
SelfAlign::Start => 0.0,
SelfAlign::End => spare,
SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
}
}
pub fn auto_size(&self) -> bool {
self.auto_size
}
pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
self.auto_size = on;
self
}
pub fn column_span(&self) -> u32 {
self.column_span.max(1)
}
pub fn set_column_span(&mut self, span: u32) -> &mut Self {
self.column_span = span.max(1);
self
}
pub fn text_scale(&self) -> f32 {
self.text_scale
}
pub fn spacing_scale(&self) -> f32 {
self.spacing_scale
}
pub fn tag(&self) -> i64 {
self.tag
}
pub fn style(&self) -> &str {
&self.style
}
pub fn theme_name(&self) -> &str {
&self.theme
}
pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
self.theme = v.into();
self
}
pub fn hint(&self) -> &str {
&self.hint
}
pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
self.hint = v.into();
self
}
pub fn state(&self) -> ControlState {
self.state
}
pub fn bounds(&self) -> RectF {
self.bounds
}
pub fn scroll_offset(&self) -> PointF {
self.scroll_offset
}
pub fn laid_out_scroll(&self) -> PointF {
self.laid_out_scroll
}
pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
self.scroll_offset = offset;
self
}
pub fn content_size(&self) -> SizeF {
self.content_size
}
pub fn set_left(&mut self, v: f32) -> &mut Self {
self.left = v;
self.anchor_ref = None;
self
}
pub fn set_top(&mut self, v: f32) -> &mut Self {
self.top = v;
self.anchor_ref = None;
self
}
pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
self.set_left(left).set_top(top)
}
pub fn set_width(&mut self, v: f32) -> &mut Self {
self.width = v.max(0.0);
self.anchor_ref = None;
self
}
pub fn set_height(&mut self, v: f32) -> &mut Self {
self.height = v.max(0.0);
self.anchor_ref = None;
self
}
pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
self.set_width(width).set_height(height)
}
pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
self.set_position(left, top).set_size(width, height)
}
pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
self.margins = v.into();
self
}
pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
self.padding = v.into();
self
}
pub fn set_align(&mut self, v: Align) -> &mut Self {
self.align = v;
self.anchor_ref = None;
self
}
pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
self.anchors = v;
self.anchor_ref = None;
self
}
pub fn set_visible(&mut self, v: bool) -> &mut Self {
self.visible = v;
self
}
pub fn set_enabled(&mut self, v: bool) -> &mut Self {
self.enabled = v;
self
}
pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
self.hit_test = v;
self
}
pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
self.clip_children = v;
self
}
pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
self.captures_wheel = v;
self
}
pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
self.can_focus = v;
self
}
pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
self.pan_on_touch = v;
self
}
pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
self.tab_stop = v;
self
}
pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
self.cursor = v;
self
}
pub fn set_opacity(&mut self, v: f32) -> &mut Self {
self.opacity = v.clamp(0.0, 1.0);
self
}
pub fn translate(&self) -> PointF {
self.translate
}
pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
self
}
pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
self
}
pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
self.shadow = shadow;
self
}
pub fn set_tag(&mut self, v: i64) -> &mut Self {
self.tag = v;
self
}
pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
self.style = v.into();
self
}
pub fn state_mut(&mut self) -> &mut ControlState {
&mut self.state
}
pub fn get_prop(&self, name: &str) -> Option<PropValue> {
Some(match name {
"left" => self.left.into(),
"top" => self.top.into(),
"width" => self.width.into(),
"height" => self.height.into(),
"align" => self.align.into(),
"anchors" => self.anchors.into(),
"margins" => self.margins.into(),
"padding" => self.padding.into(),
"visible" => self.visible.into(),
"enabled" => self.enabled.into(),
"hit_test" => self.hit_test.into(),
"clip_children" => self.clip_children.into(),
"captures_wheel" => self.captures_wheel.into(),
"can_focus" => self.can_focus.into(),
"draggable" => self.draggable.into(),
"accepts_drops" => self.accepts_drops.into(),
"drag_data" => self.drag_data().into(),
"drag_label" => self.drag_label().into(),
"drag_image" => PropValue::Component(self.drag_image()),
"drop_types" => self.drop_types().into(),
"tab_stop" => self.tab_stop.into(),
"cursor" => PropValue::enum_value(self.cursor),
"opacity" => self.opacity.into(),
"cache_layer" => self.cache_layer.into(),
"rotation" => self.rotation.into(),
"translate_x" => self.translate.x.into(),
"translate_y" => self.translate.y.into(),
"aspect_ratio" => self.aspect_ratio.into(),
"max_width" => self.max_width.into(),
"min_width" => self.min_width.into(),
"min_height" => self.min_height.into(),
"max_height" => self.max_height.into(),
"self_align" => PropValue::enum_value(self.self_align),
"auto_size" => self.auto_size.into(),
"column_span" => (self.column_span() as i64).into(),
"shadow" => crate::prop::PropType::to_value(&self.shadow),
"style" => self.style.clone().into(),
"fill" => crate::prop::PropType::to_value(&self.colors.fill),
"border_color" => crate::prop::PropType::to_value(&self.colors.border),
"text_color" => crate::prop::PropType::to_value(&self.colors.text),
"accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
"success_color" => crate::prop::PropType::to_value(&self.colors.success),
"warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
"danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
"font_family" => self.font.family.clone().into(),
"font_size" => crate::prop::PropType::to_value(&self.font.size),
"font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
"font_italic" => self.font.italic.into(),
"font_underline" => self.font.underline.into(),
"font_strikeout" => self.font.strikeout.into(),
"theme" => self.theme.clone().into(),
"hint" => self.hint.clone().into(),
"tag" => self.tag.into(),
"popup_menu" => PropValue::Component(self.popup_menu),
_ => return None,
})
}
pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
match name {
"left" => self.set_left(value.to_f32()?),
"top" => self.set_top(value.to_f32()?),
"width" => self.set_width(value.to_f32()?),
"height" => self.set_height(value.to_f32()?),
"align" => self.set_align(value.to_enum()?),
"anchors" => self.set_anchors(value.to_anchors()?),
"margins" => self.set_margins(value.to_bounds()?),
"padding" => self.set_padding(value.to_bounds()?),
"visible" => self.set_visible(value.to_bool()?),
"enabled" => self.set_enabled(value.to_bool()?),
"hit_test" => self.set_hit_test(value.to_bool()?),
"clip_children" => self.set_clip_children(value.to_bool()?),
"captures_wheel" => self.set_captures_wheel(value.to_bool()?),
"can_focus" => self.set_can_focus(value.to_bool()?),
"draggable" => self.set_draggable(value.to_bool()?),
"accepts_drops" => self.set_accepts_drops(value.to_bool()?),
"drag_data" => {
self.drag_decl().data = value.to_str()?.to_string();
self
}
"drag_label" => {
self.drag_decl().label = value.to_str()?.to_string();
self
}
"drag_image" => {
self.drag_decl().image = value.to_component()?;
self
}
"drop_types" => {
self.drag_decl().drop_types = value.to_str()?.to_string();
self
}
"tab_stop" => self.set_tab_stop(value.to_bool()?),
"cursor" => self.set_cursor(value.to_enum()?),
"opacity" => self.set_opacity(value.to_f32()?),
"cache_layer" => self.set_cache_layer(value.to_bool()?),
"rotation" => self.set_rotation(value.to_f32()?),
"translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
"translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
"aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
"max_width" => self.set_max_width(value.to_f32()?),
"min_width" => self.set_min_width(value.to_f32()?),
"min_height" => self.set_min_height(value.to_f32()?),
"max_height" => self.set_max_height(value.to_f32()?),
"self_align" => self.set_self_align(value.to_enum()?),
"auto_size" => self.set_auto_size(value.to_bool()?),
"column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
"shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
"style" => self.set_style(value.to_str()?),
"fill" => {
self.colors.fill = crate::prop::PropType::from_value(value)?;
self
}
"border_color" => {
self.colors.border = crate::prop::PropType::from_value(value)?;
self
}
"text_color" => {
self.colors.text = crate::prop::PropType::from_value(value)?;
self
}
"accent_color" => {
self.colors.accent = crate::prop::PropType::from_value(value)?;
self
}
"success_color" => {
self.colors.success = crate::prop::PropType::from_value(value)?;
self
}
"warning_color" => {
self.colors.warning = crate::prop::PropType::from_value(value)?;
self
}
"danger_color" => {
self.colors.danger = crate::prop::PropType::from_value(value)?;
self
}
"font_family" => {
self.font.family = value.to_str()?.to_string();
self
}
"font_size" => {
self.font.size = crate::prop::PropType::from_value(value)?;
self
}
"font_weight" => {
self.font.weight = font_weight_named(value.to_str()?)?;
self
}
"font_italic" => {
self.font.italic = value.to_bool()?;
self
}
"font_underline" => {
self.font.underline = value.to_bool()?;
self
}
"font_strikeout" => {
self.font.strikeout = value.to_bool()?;
self
}
"theme" => self.set_theme_name(value.to_str()?),
"hint" => self.set_hint(value.to_str()?),
"tag" => self.set_tag(value.to_i64()?),
"popup_menu" => {
self.popup_menu = value.to_component()?;
self
}
_ => return Err(Error::UnknownProperty(name.to_string())),
};
Ok(())
}
}
pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
use crate::canvas::FontWeight::*;
let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
Some(0) => Ok(None),
Some(i) => Ok(Some(all[i - 1])),
None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FontOverride {
pub family: String,
pub size: Option<f32>,
pub weight: Option<crate::canvas::FontWeight>,
pub italic: bool,
pub underline: bool,
pub strikeout: bool,
}
impl FontOverride {
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
pub fn over(&self, parent: &FontOverride) -> FontOverride {
FontOverride {
family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
size: self.size.or(parent.size),
weight: self.weight.or(parent.weight),
italic: self.italic || parent.italic,
underline: self.underline || parent.underline,
strikeout: self.strikeout || parent.strikeout,
}
}
pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
if !self.family.is_empty() {
font.family = self.family.clone();
}
if let Some(size) = self.size.filter(|s| *s > 0.0) {
font.size = size;
}
if let Some(weight) = self.weight {
font.weight = weight;
}
font.italic |= self.italic;
font.underline |= self.underline;
font.strikeout |= self.strikeout;
}
}
impl ControlBase {
pub fn font(&self) -> &FontOverride {
&self.font
}
pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
self.font = font;
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ColorOverride {
pub fill: Option<crate::Color>,
pub border: Option<crate::Color>,
pub text: Option<crate::Color>,
pub accent: Option<crate::Color>,
pub success: Option<crate::Color>,
pub warning: Option<crate::Color>,
pub danger: Option<crate::Color>,
}
impl ColorOverride {
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
pub(crate) fn recolors_theme(&self) -> bool {
!self.is_empty()
}
pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
use crate::Color;
let mut t = theme.clone();
let mut set = |name: &str, c: Color| {
t.colors.insert(name.to_string(), c);
};
if let Some(a) = self.accent {
let dark = luminance(a) < 0.5;
set("primary", a);
set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
set("focus_ring", a);
set("selection", a.with_opacity(0.25));
set("primary_soft", a.with_opacity(0.1));
set("primary_container", a.lerp(Color::WHITE, 0.82));
}
if let Some(c) = self.fill {
let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
set("surface", c);
set("background", c);
set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
}
if let Some(c) = self.text {
set("text", c);
set("text_muted", c.with_opacity(0.65));
for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
set(on, c);
}
}
if let Some(c) = self.border {
set("border", c);
set("track", c);
}
for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
if let Some(c) = color {
set(token, c);
set(&format!("{token}_soft"), c.with_opacity(0.1));
set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
if token == "success" {
set("meter_low", c);
} else if token == "danger" {
set("meter_high", c);
} else {
set("meter_mid", c);
}
}
}
t
}
}
pub(crate) fn luminance(c: crate::Color) -> f32 {
(0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Connection {
pub from: ComponentId,
pub from_at: (f32, f32),
pub to: ComponentId,
pub to_at: (f32, f32),
}
impl Connection {
pub const STUB: f32 = 16.0;
fn normal(at: (f32, f32)) -> PointF {
let (x, y) = at;
let d = [(x, PointF::new(-1.0, 0.0)), (1.0 - x, PointF::new(1.0, 0.0)), (y, PointF::new(0.0, -1.0)), (1.0 - y, PointF::new(0.0, 1.0))];
d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
}
pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
let mut points = vec![p0, s0];
if n0.x != 0.0 {
let mx = (s0.x + s1.x) / 2.0;
points.push(PointF::new(mx, s0.y));
points.push(PointF::new(mx, s1.y));
} else {
let my = (s0.y + s1.y) / 2.0;
points.push(PointF::new(s0.x, my));
points.push(PointF::new(s1.x, my));
}
points.push(s1);
points.push(p1);
points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
points
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DragDecl {
pub data: String,
pub label: String,
pub drop_types: String,
pub image: Option<ComponentId>,
}