use crate::color::{Color, TextStyle};
use crate::event::{EventResult, UiEvent};
use crate::geometry::{Edges, Pos, Rect, Size};
pub struct PopupRequest {
pub factory: Box<dyn FnOnce() -> Box<dyn Widget>>,
pub anchor: Rect,
pub modal: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Cursor {
#[default]
Default,
Pointer,
Text,
ResizeHorizontal,
ResizeVertical,
Grab,
}
pub struct MountCtx {
pub id: String,
pub invalidation: crate::signal::Invalidation,
}
impl MountCtx {
pub fn new(id: impl Into<String>, invalidation: crate::signal::Invalidation) -> Self {
Self {
id: id.into(),
invalidation,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Role(pub &'static str);
impl Role {
pub const PANEL: Role = Role("panel");
pub const WINDOW: Role = Role("window");
pub const TEXT: Role = Role("text");
pub const BUTTON: Role = Role("button");
pub const TEXT_INPUT: Role = Role("text_input");
pub const LIST: Role = Role("list");
pub const LIST_ITEM: Role = Role("list_item");
pub const SCROLLBAR: Role = Role("scrollbar");
pub const SWITCH: Role = Role("switch");
pub const SLIDER: Role = Role("slider");
pub const CHECKBOX: Role = Role("checkbox");
pub const ALERT: Role = Role("alert");
pub const ROW: Role = Role("row");
pub const CELL: Role = Role("cell");
pub const TREE_ITEM: Role = Role("tree_item");
pub const TABLE: Role = Role("table");
pub const TREE: Role = Role("tree");
pub const COLUMN_HEADER: Role = Role("column_header");
pub const COMBOBOX: Role = Role("combobox");
pub const PROGRESS: Role = Role("progress");
pub const RADIO_GROUP: Role = Role("radio_group");
pub const MENU: Role = Role("menu");
pub const MENU_BAR: Role = Role("menu_bar");
pub const SPLITTER: Role = Role("splitter");
pub const fn as_str(self) -> &'static str {
self.0
}
}
impl Default for Role {
fn default() -> Self {
Role::PANEL
}
}
impl std::fmt::Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Axis {
#[default]
Horizontal,
Vertical,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Dimension {
#[default]
Auto,
Px(f32),
Flex(f32),
Percent(f32),
}
impl Dimension {
pub fn resolve(&self, available: f32, content: f32) -> f32 {
match *self {
Dimension::Auto => content,
Dimension::Px(v) => v,
Dimension::Flex(_) => content,
Dimension::Percent(p) => available * (p / 100.0),
}
}
pub fn flex_factor(&self) -> Option<f32> {
match *self {
Dimension::Flex(f) if f > 0.0 => Some(f),
_ => None,
}
}
pub fn is_flex(&self) -> bool {
matches!(self, Dimension::Flex(f) if *f > 0.0)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Align {
Start,
Center,
End,
#[default]
Stretch,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Justify {
#[default]
Start,
Center,
End,
SpaceBetween,
SpaceAround,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FlexItem {
pub width: Dimension,
pub height: Dimension,
pub min_width: Dimension,
pub max_width: Dimension,
pub min_height: Dimension,
pub max_height: Dimension,
}
impl FlexItem {
pub const NO_LIMITS: Self = Self {
width: Dimension::Auto,
height: Dimension::Auto,
min_width: Dimension::Px(0.0),
max_width: Dimension::Auto,
min_height: Dimension::Px(0.0),
max_height: Dimension::Auto,
};
pub const fn fill() -> Self {
Self {
width: Dimension::Flex(1.0),
height: Dimension::Flex(1.0),
..Self::NO_LIMITS
}
}
pub const fn fixed(w: f32, h: f32) -> Self {
Self {
width: if w > 0.0 {
Dimension::Px(w)
} else {
Dimension::Auto
},
height: if h > 0.0 {
Dimension::Px(h)
} else {
Dimension::Auto
},
..Self::NO_LIMITS
}
}
pub const fn width(w: f32) -> Self {
Self {
width: Dimension::Px(w),
height: Dimension::Auto,
..Self::NO_LIMITS
}
}
pub const fn height(h: f32) -> Self {
Self {
width: Dimension::Auto,
height: Dimension::Px(h),
..Self::NO_LIMITS
}
}
pub const fn grow(factor: f32) -> Self {
Self {
width: Dimension::Flex(factor),
height: Dimension::Flex(factor),
..Self::NO_LIMITS
}
}
pub const fn min_width(mut self, w: f32) -> Self {
self.min_width = Dimension::Px(w);
self
}
pub const fn max_width(mut self, w: f32) -> Self {
self.max_width = Dimension::Px(w);
self
}
pub const fn min_height(mut self, h: f32) -> Self {
self.min_height = Dimension::Px(h);
self
}
pub const fn max_height(mut self, h: f32) -> Self {
self.max_height = Dimension::Px(h);
self
}
pub const fn min(mut self, v: f32) -> Self {
self.min_width = Dimension::Px(v);
self.min_height = Dimension::Px(v);
self
}
pub const fn max(mut self, v: f32) -> Self {
self.max_width = Dimension::Px(v);
self.max_height = Dimension::Px(v);
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Axis2(u8);
impl Axis2 {
pub const NONE: Axis2 = Axis2(0);
pub const H: Axis2 = Axis2(1);
pub const V: Axis2 = Axis2(2);
pub const BOTH: Axis2 = Axis2(3);
pub const fn contains(self, other: Axis2) -> bool {
self.0 & other.0 != 0
}
pub const fn union(self, other: Axis2) -> Axis2 {
Axis2(self.0 | other.0)
}
pub const fn any(self) -> bool {
self.0 != 0
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Constraints {
pub max: Size,
pub min: Size,
pub unbounded: Axis2,
}
impl Constraints {
pub const fn loose(max: Size) -> Self {
Self {
max,
min: Size::ZERO,
unbounded: Axis2::NONE,
}
}
pub const fn tight(size: Size) -> Self {
Self {
max: size,
min: size,
unbounded: Axis2::NONE,
}
}
pub fn unbounded_main(axis: crate::Axis, cross: Size) -> Self {
match axis {
crate::Axis::Vertical => Self {
max: Size::new(cross.w, f32::INFINITY),
min: Size::ZERO,
unbounded: Axis2::V,
},
crate::Axis::Horizontal => Self {
max: Size::new(f32::INFINITY, cross.h),
min: Size::ZERO,
unbounded: Axis2::H,
},
}
}
pub fn is_unbounded(&self, axis: crate::Axis) -> bool {
match axis {
crate::Axis::Horizontal => self.unbounded.contains(Axis2::H),
crate::Axis::Vertical => self.unbounded.contains(Axis2::V),
}
}
pub fn constrain(&self, size: Size) -> Size {
let safe = Size::new(
if size.w.is_finite() { size.w } else { 0.0 },
if size.h.is_finite() { size.h } else { 0.0 },
);
let clamped = safe.max(self.min).min(self.max);
Size::new(
if clamped.w.is_finite() {
clamped.w
} else {
0.0
},
if clamped.h.is_finite() {
clamped.h
} else {
0.0
},
)
}
}
pub trait TextMetrics {
fn measure_text(&self, text: &str, style: &TextStyle) -> Size;
fn line_height(&self, style: &TextStyle) -> f32;
fn ink_bounds(&self, style: &TextStyle) -> (f32, f32) {
(0.0, self.line_height(style))
}
fn scale(&self) -> f32;
fn measure_with(&self, text: &str, style: &TextStyle, avail_width: f32) -> Size {
let line_h = self.line_height(style);
let lines = crate::wrap(text, avail_width, |s| self.measure_text(s, style).w);
let w = lines
.iter()
.map(|l| self.measure_text(&l.text, style).w)
.fold(0.0f32, f32::max);
Size::new(w, line_h * lines.len() as f32)
}
}
pub fn ink_margin_for(metrics: &dyn TextMetrics, style: &TextStyle) -> f32 {
let (_, ink_depth) = metrics.ink_bounds(style);
let line_h = metrics.line_height(style);
const MIN_INK_MARGIN: f32 = 2.0;
(ink_depth - line_h)
.max(MIN_INK_MARGIN)
.min(line_h.max(0.0))
}
fn gradient_t(rect: Rect, dir: (f32, f32), x: f32, y: f32) -> f32 {
let (dx, dy) = dir;
let len2 = dx * dx + dy * dy;
if len2 <= f32::EPSILON {
return 0.0;
}
let proj = |px: f32, py: f32| ((px - rect.x) * dx + (py - rect.y) * dy) / len2;
let corners = [
proj(rect.x, rect.y),
proj(rect.right(), rect.y),
proj(rect.x, rect.bottom()),
proj(rect.right(), rect.bottom()),
];
let t_min = corners.iter().cloned().fold(f32::MAX, f32::min);
let t_max = corners.iter().cloned().fold(f32::MIN, f32::max);
let span = t_max - t_min;
if span <= f32::EPSILON {
return 0.0;
}
((proj(x, y) - t_min) / span).clamp(0.0, 1.0)
}
pub const GRADIENT_STEPS: usize = 32;
pub const AA_SAMPLES: usize = 4;
pub trait RenderCtx: TextMetrics {
fn begin_frame(&mut self) {}
fn animation(&self, _key: u64) -> f32 {
1.0
}
fn set_animations(&mut self, _snapshot: &crate::animation::AnimSnapshot) {}
fn push_transform(&mut self, _origin: Pos, _scale: f32) {}
fn pop_transform(&mut self) {}
fn upload_texture(
&mut self,
_width: u32,
_height: u32,
_rgba: &[u8],
) -> crate::image::TextureId {
crate::image::TextureId::INVALID
}
fn draw_image(
&mut self,
_rect: Rect,
_texture: crate::image::TextureId,
_style: crate::image::ImageStyle,
) {
}
fn retain_texture(&mut self, _id: crate::image::TextureId) {}
fn release_texture(&mut self, _id: crate::image::TextureId) {}
fn is_hovered(&self, _id: &str) -> bool {
false
}
fn set_hovered(&mut self, _id: Option<&str>) {}
fn background_color(&self) -> Color {
Color::rgba(0.0, 0.0, 0.0, 1.0)
}
fn size(&self) -> Size;
fn fill_rect(&mut self, rect: Rect, color: Color);
fn stroke_rect(&mut self, rect: Rect, color: Color, width: f32);
fn draw_text(&mut self, origin: Pos, text: &str, style: &TextStyle) -> f32;
fn draw_char(&mut self, pos: Pos, ch: char, style: &TextStyle) -> f32 {
let mut buf = [0u8; 4];
let s = ch.encode_utf8(&mut buf);
self.draw_text(pos, s, style)
}
fn fill_round_rect(&mut self, rect: Rect, color: Color, radius: f32) {
let r = radius.clamp(0.0, rect.w.min(rect.h) * 0.5);
if r <= 0.5 {
self.fill_rect(rect, color);
return;
}
self.fill_rect(
Rect::new(rect.x, rect.y + r, rect.w, rect.h - 2.0 * r),
color,
);
let rows = r.ceil() as i32;
for i in 0..rows {
let mut inset_sum = 0.0f32;
for k in 0..AA_SAMPLES {
let dy = r - (i as f32 + (k as f32 + 0.5) / AA_SAMPLES as f32);
inset_sum += r - (r * r - dy * dy).max(0.0).sqrt();
}
let inset = inset_sum / AA_SAMPLES as f32;
self.fill_round_row(rect, rect.y + i as f32, inset, color);
self.fill_round_row(rect, rect.bottom() - 1.0 - i as f32, inset, color);
}
}
fn fill_gradient_round_rect(
&mut self,
rect: Rect,
from: Color,
to: Color,
dir: (f32, f32),
radius: f32,
) {
let r = radius.clamp(0.0, rect.w.min(rect.h) * 0.5);
if r <= 0.5 {
self.fill_gradient_rect_dir(rect, from, to, dir);
return;
}
self.fill_gradient_rect_dir(
Rect::new(rect.x, rect.y + r, rect.w, rect.h - 2.0 * r),
from,
to,
dir,
);
let steps = (r.ceil() as i32).max(1);
for i in 0..steps {
let dy = r - (i as f32 + 0.5);
let inset = r - (r * r - dy * dy).max(0.0).sqrt();
let row = Rect::new(rect.x + inset, rect.y + i as f32, rect.w - 2.0 * inset, 1.0);
let n = 8;
for k in 0..n {
let t0 = k as f32 / n as f32;
let t1 = (k + 1) as f32 / n as f32;
let x0 = row.x + row.w * t0;
let x1 = row.x + row.w * t1;
let t = gradient_t(rect, dir, (x0 + x1) * 0.5, row.y + 0.5);
self.fill_rect(Rect::new(x0, row.y, x1 - x0, 1.0), from.lerp(to, t));
}
let y = rect.bottom() - 1.0 - i as f32;
let row = Rect::new(rect.x + inset, y, rect.w - 2.0 * inset, 1.0);
for k in 0..n {
let t0 = k as f32 / n as f32;
let t1 = (k + 1) as f32 / n as f32;
let x0 = row.x + row.w * t0;
let x1 = row.x + row.w * t1;
let t = gradient_t(rect, dir, (x0 + x1) * 0.5, y + 0.5);
self.fill_rect(Rect::new(x0, y, x1 - x0, 1.0), from.lerp(to, t));
}
}
}
fn stroke_round_rect(&mut self, rect: Rect, color: Color, width: f32, radius: f32) {
let w = width.max(0.0);
if w <= 0.0 || rect.is_empty() {
return;
}
let r = radius.clamp(0.0, rect.w.min(rect.h) * 0.5);
if r <= 0.5 {
self.stroke_rect(rect, color, w);
return;
}
self.fill_rect(Rect::new(rect.x + r, rect.y, rect.w - 2.0 * r, w), color);
self.fill_rect(
Rect::new(rect.x + r, rect.bottom() - w, rect.w - 2.0 * r, w),
color,
);
self.fill_rect(Rect::new(rect.x, rect.y + r, w, rect.h - 2.0 * r), color);
self.fill_rect(
Rect::new(rect.right() - w, rect.y + r, w, rect.h - 2.0 * r),
color,
);
let steps = (r.ceil() as i32).max(1);
for i in 0..steps {
let dy = r - (i as f32 + 0.5);
let outer = (r * r - dy * dy).max(0.0).sqrt();
let inner_r = (r - w).max(0.0);
let inner = if dy.abs() <= inner_r {
(inner_r * inner_r - dy * dy).max(0.0).sqrt()
} else {
0.0
};
let band = (outer - inner).max(0.0);
if band <= 0.0 {
continue;
}
self.fill_rect(
Rect::new(rect.x + r - outer, rect.y + i as f32, band, 1.0),
color,
);
self.fill_rect(
Rect::new(rect.right() - r + inner, rect.y + i as f32, band, 1.0),
color,
);
let y = rect.bottom() - 1.0 - i as f32;
self.fill_rect(Rect::new(rect.x + r - outer, y, band, 1.0), color);
self.fill_rect(Rect::new(rect.right() - r + inner, y, band, 1.0), color);
}
}
fn fill_round_row(&mut self, rect: Rect, y: f32, inset: f32, color: Color) {
let x0 = rect.x + inset;
let x1 = rect.right() - inset;
if x1 <= x0 {
return;
}
let left_px = x0.floor();
let right_px = x1.ceil();
let left_frac = (x0 - left_px).clamp(0.0, 1.0);
let right_frac = (right_px - x1).clamp(0.0, 1.0);
if left_frac > 0.001 {
self.fill_rect(
Rect::new(left_px, y, 1.0, 1.0),
color.with_alpha(color.a * (1.0 - left_frac)),
);
}
if right_frac > 0.001 {
self.fill_rect(
Rect::new(right_px - 1.0, y, 1.0, 1.0),
color.with_alpha(color.a * (1.0 - right_frac)),
);
}
let body_x0 = left_px + if left_frac > 0.001 { 1.0 } else { 0.0 };
let body_x1 = right_px - if right_frac > 0.001 { 1.0 } else { 0.0 };
if body_x1 > body_x0 {
self.fill_rect(Rect::new(body_x0, y, body_x1 - body_x0, 1.0), color);
}
}
fn fill_gradient_rect_dir(&mut self, rect: Rect, from: Color, to: Color, dir: (f32, f32)) {
if rect.is_empty() || (from.a <= 0.0 && to.a <= 0.0) {
return;
}
let (dx, dy) = dir;
let len2 = dx * dx + dy * dy;
if len2 <= f32::EPSILON {
self.fill_rect(rect, from);
return;
}
let proj = |x: f32, y: f32| -> f32 { ((x - rect.x) * dx + (y - rect.y) * dy) / len2 };
let corners = [
proj(rect.x, rect.y),
proj(rect.right(), rect.y),
proj(rect.x, rect.bottom()),
proj(rect.right(), rect.bottom()),
];
let t_min = corners.iter().cloned().fold(f32::MAX, f32::min);
let t_max = corners.iter().cloned().fold(f32::MIN, f32::max);
let span = t_max - t_min;
if span <= f32::EPSILON {
self.fill_rect(rect, from);
return;
}
let vertical = dx.abs() >= dy.abs();
let extent = if vertical { rect.w } else { rect.h };
let count = (extent.round() as i32).clamp(1, 512);
let steps = (GRADIENT_STEPS as i32).max(1);
let _ = steps;
for i in 0..count {
let a0 = i as f32 / count as f32;
let a1 = (i + 1) as f32 / count as f32;
let t = if vertical {
let cx = rect.x + rect.w * (a0 + a1) * 0.5;
((proj(cx, rect.y + rect.h * 0.5) - t_min) / span).clamp(0.0, 1.0)
} else {
let cy = rect.y + rect.h * (a0 + a1) * 0.5;
((proj(rect.x + rect.w * 0.5, cy) - t_min) / span).clamp(0.0, 1.0)
};
let c = from.lerp(to, t);
if vertical {
let x0 = (rect.w * a0).round();
let x1 = (rect.w * a1).round();
if x1 > x0 {
self.fill_rect(Rect::new(rect.x + x0, rect.y, x1 - x0, rect.h), c);
}
} else {
let y0 = (rect.h * a0).round();
let y1 = (rect.h * a1).round();
if y1 > y0 {
self.fill_rect(Rect::new(rect.x, rect.y + y0, rect.w, y1 - y0), c);
}
}
}
}
fn fill_gradient_rect(&mut self, rect: Rect, from: Color, to: Color, horizontal: bool) {
let dir = if horizontal { (1.0, 0.0) } else { (0.0, 1.0) };
self.fill_gradient_rect_dir(rect, from, to, dir);
}
fn push_clip(&mut self, rect: Rect);
fn pop_clip(&mut self);
fn push_opacity(&mut self, _opacity: f32) {}
fn pop_opacity(&mut self) {}
fn theme(&self) -> &crate::theme::Theme {
&crate::theme::DARK_THEME
}
}
pub struct EventCtx {
pub focus: Option<String>,
pub focus_request: Option<String>,
#[doc(hidden)]
pub redraw: bool,
#[doc(hidden)]
pub relayout: bool,
pub viewport: Size,
#[doc(hidden)]
pub commands: Vec<crate::command::Command>,
pub phase: crate::event::EventPhase,
pub target: String,
pub stop_propagation: bool,
#[doc(hidden)]
pub relayout_from: Option<String>,
#[doc(hidden)]
pub propagate: bool,
pub pointer_capture: Option<crate::event::PointerCapture>,
#[doc(hidden)]
pub focus_vetoed: bool,
#[doc(hidden)]
pub ime_candidate: Option<Pos>,
#[doc(hidden)]
pub popup_requests: Vec<PopupRequest>,
pub close_popup_requests: Vec<String>,
#[doc(hidden)]
pub anim_requests: Vec<(u64, crate::animation::Animate)>,
pub scale: f32,
}
impl EventCtx {
pub fn new(focus: Option<String>, viewport: Size) -> Self {
Self {
focus,
focus_request: None,
redraw: false,
relayout: false,
viewport,
commands: Vec::new(),
phase: crate::event::EventPhase::Target,
target: String::new(),
stop_propagation: false,
relayout_from: None,
propagate: false,
pointer_capture: None,
focus_vetoed: false,
ime_candidate: None,
popup_requests: Vec::new(),
close_popup_requests: Vec::new(),
anim_requests: Vec::new(),
scale: 1.0,
}
}
pub fn set_ime_candidate(&mut self, pos: Pos) {
self.ime_candidate = Some(pos);
}
pub fn veto_focus(&mut self) {
self.focus_vetoed = true;
}
pub fn stop_propagation(&mut self) {
self.stop_propagation = true;
}
pub fn allow_propagation(&mut self) {
self.propagate = true;
}
pub fn set_pointer_capture(&mut self, id: impl Into<String>) {
self.pointer_capture = Some(crate::event::PointerCapture::Capture(id.into()));
}
pub fn release_pointer_capture(&mut self) {
self.pointer_capture = Some(crate::event::PointerCapture::Release);
}
pub fn scale(&self) -> f32 {
self.scale
}
pub fn is_target(&self) -> bool {
self.phase == crate::event::EventPhase::Target
}
pub fn emit_app(&mut self, name: impl Into<String>, args: crate::json::Json) {
self.commands.push(crate::command::Command::app(name, args));
}
pub fn emit_node(
&mut self,
target: impl Into<String>,
action: impl Into<String>,
args: crate::json::Json,
) {
self.commands
.push(crate::command::Command::node(target, action, args));
}
pub fn emit(&mut self, cmd: crate::command::Command) {
self.commands.push(cmd);
}
pub fn request_focus(&mut self, id: impl Into<String>) {
self.focus_request = Some(id.into());
}
pub fn request_redraw(&mut self) {
self.redraw = true;
}
pub fn request_relayout(&mut self) {
self.relayout = true;
self.redraw = true;
}
pub fn is_focused(&self, id: &str) -> bool {
self.focus.as_deref() == Some(id)
}
pub fn request_popup(&mut self, factory: Box<dyn FnOnce() -> Box<dyn Widget>>, anchor: Rect) {
self.popup_requests.push(PopupRequest {
factory,
anchor,
modal: false,
});
self.redraw = true;
}
pub fn request_close_popup(&mut self, id: impl Into<String>) {
self.close_popup_requests.push(id.into());
self.redraw = true;
}
pub fn start_animation(&mut self, key: u64, anim: crate::animation::Animate) {
self.anim_requests.push((key, anim));
self.redraw = true;
}
pub fn emit_command(&mut self, cmd: crate::command::Command) {
match cmd {
crate::command::Command::App { name, args } => self.emit_app(name, args),
node @ crate::command::Command::Node { .. } => self.commands.push(node),
}
}
pub fn request_modal_popup(
&mut self,
factory: Box<dyn FnOnce() -> Box<dyn Widget>>,
anchor: Rect,
) {
self.popup_requests.push(PopupRequest {
factory,
anchor,
modal: true,
});
self.redraw = true;
}
pub fn finish(&mut self, result: EventResult) -> EventResult {
let mut out = result;
if self.relayout {
out = out.merge(EventResult::Relayout);
} else if self.redraw {
out = out.merge(EventResult::Redraw);
}
out
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InputKind {
None,
Text,
Number,
Bool,
}
impl InputKind {
pub fn arg_name(self) -> &'static str {
match self {
InputKind::None => "",
InputKind::Text => "text",
InputKind::Number => "value",
InputKind::Bool => "flag",
}
}
pub fn accepts(self, value: &crate::json::Json) -> bool {
use crate::json::Json;
match self {
InputKind::None => matches!(value, Json::Null),
InputKind::Text => matches!(value, Json::Str(_)),
InputKind::Number => matches!(value, Json::Num(_)),
InputKind::Bool => matches!(value, Json::Bool(_)),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ActionSpec {
pub name: String,
pub input: InputKind,
pub arg_name: Option<&'static str>,
}
impl ActionSpec {
pub fn new(name: impl Into<String>, input: InputKind) -> Self {
Self {
name: name.into(),
input,
arg_name: None,
}
}
pub fn named(name: impl Into<String>, input: InputKind, arg_name: &'static str) -> Self {
Self {
name: name.into(),
input,
arg_name: Some(arg_name),
}
}
pub fn arg_name(&self) -> &str {
self.arg_name.unwrap_or_else(|| self.input.arg_name())
}
pub fn to_json(&self) -> crate::json::Json {
let obj = crate::json::Json::obj().set("name", self.name.clone()).set(
"input",
match self.input {
InputKind::None => "none",
InputKind::Text => "text",
InputKind::Number => "number",
InputKind::Bool => "bool",
},
);
match self.arg_name {
Some(name) => obj.set("arg", name),
None => obj,
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Semantics {
pub label: String,
pub value: String,
pub description: String,
pub role: Role,
pub actions: Vec<ActionSpec>,
pub props: Vec<(String, String)>,
pub disabled: bool,
pub exposed_to_ai: bool,
pub sensitive: bool,
pub focused: bool,
pub state: crate::json::Json,
pub expanded: Option<bool>,
pub active_descendant: Option<String>,
pub checked: Option<bool>,
pub selected: Option<bool>,
pub level: Option<u32>,
pub value_range: Option<(f64, f64)>,
pub value_step: Option<f64>,
pub labelled_by: Vec<String>,
pub described_by: Vec<String>,
pub live: LiveRegion,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LiveRegion {
#[default]
Off,
Polite,
Assertive,
}
impl LiveRegion {
pub fn as_str(self) -> &'static str {
match self {
LiveRegion::Off => "off",
LiveRegion::Polite => "polite",
LiveRegion::Assertive => "assertive",
}
}
}
impl Default for Semantics {
fn default() -> Self {
Self {
label: String::new(),
value: String::new(),
description: String::new(),
role: Role(""),
actions: Vec::new(),
props: Vec::new(),
disabled: false,
exposed_to_ai: false,
sensitive: false,
focused: false,
state: crate::json::Json::Null,
expanded: None,
active_descendant: None,
checked: None,
selected: None,
level: None,
value_range: None,
value_step: None,
labelled_by: Vec::new(),
described_by: Vec::new(),
live: LiveRegion::Off,
}
}
}
impl Semantics {
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
pub fn value(mut self, value: impl Into<String>) -> Self {
self.value = value.into();
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = description.into();
self
}
pub fn expanded(mut self, expanded: bool) -> Self {
self.expanded = Some(expanded);
self
}
pub fn focused(mut self, focused: bool) -> Self {
self.focused = focused;
self
}
pub fn active_descendant(mut self, id: impl Into<String>) -> Self {
self.active_descendant = Some(id.into());
self
}
pub fn checked(mut self, checked: bool) -> Self {
self.checked = Some(checked);
self
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = Some(selected);
self
}
pub fn level(mut self, level: u32) -> Self {
self.level = Some(level);
self
}
pub fn value_range(mut self, min: f64, max: f64) -> Self {
if min.is_finite() && max.is_finite() && min <= max {
self.value_range = Some((min, max));
}
self
}
pub fn value_step(mut self, step: f64) -> Self {
if step.is_finite() && step > 0.0 {
self.value_step = Some(step);
}
self
}
pub fn labelled_by(mut self, id: impl Into<String>) -> Self {
self.labelled_by.push(id.into());
self
}
pub fn described_by(mut self, id: impl Into<String>) -> Self {
self.described_by.push(id.into());
self
}
pub fn live(mut self, live: LiveRegion) -> Self {
self.live = live;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn exposed(mut self, exposed: bool) -> Self {
self.exposed_to_ai = exposed;
self
}
pub fn sensitive(mut self, sensitive: bool) -> Self {
self.sensitive = sensitive;
self
}
pub fn state(mut self, key: impl Into<String>, value: impl Into<crate::json::Json>) -> Self {
let key = key.into();
self.state = self.state.clone().set(&key, value.into());
self
}
pub fn action(mut self, name: impl Into<String>) -> Self {
self.actions.push(ActionSpec::new(name, InputKind::None));
self
}
pub fn action_spec(mut self, name: impl Into<String>, input: InputKind) -> Self {
self.actions.push(ActionSpec::new(name, input));
self
}
pub fn action_spec_named(
mut self,
name: impl Into<String>,
input: InputKind,
arg_name: &'static str,
) -> Self {
self.actions.push(ActionSpec::named(name, input, arg_name));
self
}
pub fn prop(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.props.push((key.into(), value.into()));
self
}
}
pub trait Widget {
fn id(&self) -> &str;
fn role(&self) -> Role {
Role::PANEL
}
fn flex(&self) -> FlexItem {
FlexItem::default()
}
fn focusable(&self) -> bool {
false
}
fn revision(&self) -> u64 {
0
}
fn on_mount(&mut self, _ctx: &mut MountCtx) {}
fn on_unmount(&mut self) {}
fn release_textures(&mut self, _out: &mut Vec<crate::image::TextureId>) {}
fn is_open(&self) -> bool {
true
}
fn wants_tab(&self) -> bool {
false
}
fn a11y_virtual_children(&self) -> Vec<crate::tree::NodeInfo> {
Vec::new()
}
fn cache_key(&self) -> Option<u64> {
None
}
fn wants_tick(&self) -> bool {
false
}
fn is_modal(&self) -> bool {
false
}
fn is_disabled(&self) -> bool {
false
}
fn children_clip(&self, _cell_rect: Rect) -> Option<Rect> {
None
}
fn clip(&self) -> Option<Rect> {
None
}
fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
None
}
fn cursor(&self) -> Cursor {
Cursor::Default
}
fn cursor_at(&self, _pos: Pos) -> Cursor {
self.cursor()
}
fn children(&self) -> &[Box<dyn Widget>] {
&[]
}
fn children_mut(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
None
}
fn children_mut_for_traversal(&mut self) -> Option<&mut Vec<Box<dyn Widget>>> {
self.children_mut()
}
fn layout_version(&self) -> u64 {
0
}
fn measure(
&mut self,
metrics: &dyn TextMetrics,
constraints: Constraints,
cache: &mut crate::layout::LayoutCache,
) -> Size;
fn arrange(
&mut self,
rect: Rect,
metrics: &dyn TextMetrics,
cache: &mut crate::layout::LayoutCache,
);
fn rect(&self) -> Rect;
fn event(&mut self, _ctx: &mut EventCtx, _event: &UiEvent) -> EventResult {
EventResult::Ignored
}
fn render(&mut self, _ctx: &mut dyn RenderCtx);
fn semantics(&self) -> Semantics {
Semantics::default()
}
fn padding(&self) -> Edges {
Edges::ZERO
}
fn ink_overflow(&self, _metrics: &dyn TextMetrics) -> Option<f32> {
None
}
fn always_paints(&self) -> bool {
false
}
fn needs_paint(&self, dirty: &crate::tree::DirtyRegion) -> bool {
self.always_paints() || dirty.intersects(self.rect())
}
}
#[cfg(test)]
mod event_ctx_scale_tests {
use super::*;
#[test]
fn event_ctx_scale_defaults_to_one() {
let ctx = EventCtx::new(None, Size::new(100.0, 100.0));
assert_eq!(
ctx.scale(),
1.0,
"默认 scale 必须是 1.0,否则现有测试会变尺寸"
);
}
#[test]
fn event_ctx_scale_is_settable() {
let mut ctx = EventCtx::new(None, Size::new(100.0, 100.0));
ctx.scale = 1.25;
assert_eq!(ctx.scale(), 1.25);
}
}