use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
use icedwright_protocol::{
AnnotationSource, RawAnnotation, RawCall, RawKey, RawNode, RawTree, RawValue, RawWindow,
RawWindowInfo, WidgetId, WindowId,
};
use icedwright_types::role::{
AnyRole, Checkable, Editable, Expandable, HasValue, Leveled, Pressable, RangeValue, RoleKind,
RoleType, SelectableItem,
};
use icedwright_types::{
Checked, CursorSeen, Point, Rect, ScaleFactor, Size, StateName, StateValue,
};
use crate::build::named_from_content;
use crate::infer::infer;
use crate::tree::SemanticTree;
const ROW: f32 = 24.0;
const INDENT: f32 = 8.0;
const WIDTH: f32 = 800.0;
const HEIGHT: f32 = 600.0;
#[derive(Debug, Clone)]
enum Spec {
Node {
annotation: Box<RawAnnotation>,
widget_id: Option<WidgetId>,
bounds: Option<Rect>,
children: Vec<Spec>,
},
Text {
content: String,
bounds: Option<Rect>,
},
Overlay {
depth: u16,
children: Vec<Spec>,
},
}
#[derive(Debug, Clone)]
struct WindowSpec {
title: String,
size: Option<Size>,
children: Vec<Spec>,
}
#[derive(Debug, Clone)]
#[must_use = "a TreeBuilder does nothing until built"]
pub struct TreeBuilder {
windows: Vec<WindowSpec>,
}
#[derive(Debug, Clone)]
#[must_use = "a NodeBuilder does nothing until returned to its parent"]
pub struct NodeBuilder<R: RoleKind = AnyRole> {
annotation: RawAnnotation,
widget_id: Option<WidgetId>,
bounds: Option<Rect>,
children: Vec<Spec>,
role: PhantomData<fn() -> R>,
}
fn node_spec<R: RoleKind>(builder: NodeBuilder<R>) -> Spec {
Spec::Node {
annotation: Box::new(builder.annotation),
widget_id: builder.widget_id,
bounds: builder.bounds,
children: builder.children,
}
}
fn new_node<R: RoleKind>(name: &str) -> NodeBuilder<R> {
let annotation = RawAnnotation {
role: R::ROLE,
name: (!name.is_empty()).then(|| name.to_owned()),
..RawAnnotation::default()
};
NodeBuilder {
annotation,
widget_id: None,
bounds: None,
children: Vec::new(),
role: PhantomData,
}
}
macro_rules! children_methods {
() => {
pub fn child<R2: RoleType>(
mut self,
role: R2,
name: &str,
build: impl FnOnce(NodeBuilder<R2>) -> NodeBuilder<R2>,
) -> Self {
let _ = role;
self.children_mut()
.push(node_spec(build(new_node::<R2>(name))));
self
}
pub fn generic(
mut self,
build: impl FnOnce(NodeBuilder<AnyRole>) -> NodeBuilder<AnyRole>,
) -> Self {
self.children_mut()
.push(node_spec(build(new_node::<AnyRole>(""))));
self
}
pub fn text(mut self, content: &str) -> Self {
self.children_mut().push(Spec::Text {
content: content.to_owned(),
bounds: None,
});
self
}
pub fn text_at(mut self, content: &str, bounds: Rect) -> Self {
self.children_mut().push(Spec::Text {
content: content.to_owned(),
bounds: Some(bounds),
});
self
}
};
}
impl TreeBuilder {
pub fn window(title: &str) -> Self {
Self {
windows: vec![WindowSpec {
title: title.to_owned(),
size: None,
children: Vec::new(),
}],
}
}
pub fn and_window(mut self, title: &str) -> Self {
self.windows.push(WindowSpec {
title: title.to_owned(),
size: None,
children: Vec::new(),
});
self
}
pub fn size(mut self, width: f32, height: f32) -> Self {
if let Some(window) = self.windows.last_mut() {
window.size = Some(Size::new(width, height));
}
self
}
pub fn overlay(
mut self,
depth: u16,
build: impl FnOnce(NodeBuilder<AnyRole>) -> NodeBuilder<AnyRole>,
) -> Self {
let layer = build(new_node::<AnyRole>(""));
self.children_mut().push(Spec::Overlay {
depth,
children: layer.children,
});
self
}
fn children_mut(&mut self) -> &mut Vec<Spec> {
if self.windows.is_empty() {
self.windows.push(WindowSpec {
title: String::new(),
size: None,
children: Vec::new(),
});
}
let index = self.windows.len() - 1;
&mut self.windows[index].children
}
children_methods!();
#[must_use]
pub fn raw(&self) -> RawTree {
let windows = self
.windows
.iter()
.enumerate()
.map(|(index, window)| {
let width = window.size.map_or(WIDTH, |s| s.width);
let (children, used) = layout(&window.children, 0.0, 0.0, width);
let height = window.size.map_or(used.max(HEIGHT), |s| s.height);
let id = WindowId(u64::try_from(index).unwrap_or(u64::MAX));
let size = Size::new(width, height);
RawWindow {
id: Some(id),
info: Some(RawWindowInfo {
id,
title: window.title.clone(),
size,
scale_factor: ScaleFactor::default(),
}),
root: RawNode::new(RawCall::Group, Rect::new(Point::ORIGIN, size))
.with_children(children),
}
})
.collect();
RawTree { windows }
}
#[must_use]
pub fn build(&self) -> SemanticTree {
infer(&self.raw())
}
}
fn layout(specs: &[Spec], x: f32, y: f32, width: f32) -> (Vec<RawNode>, f32) {
let mut nodes = Vec::with_capacity(specs.len());
let mut cursor = y;
let mut overlays = Vec::new();
for spec in specs {
match spec {
Spec::Text { content, bounds } => {
let bounds =
bounds.unwrap_or(Rect::new(Point::new(x, cursor), Size::new(width, ROW)));
cursor += ROW;
nodes.push(RawNode::new(
RawCall::Text {
content: content.clone(),
},
bounds,
));
}
Spec::Node {
annotation,
widget_id,
bounds,
children,
} => {
let (mut kids, used) =
layout(children, x + INDENT, cursor + ROW, width - 2.0 * INDENT);
let label = annotation
.name
.clone()
.filter(|_| children.is_empty())
.filter(|_| annotation.role.is_some_and(named_from_content));
let height = if label.is_some() {
2.0 * ROW
} else {
ROW + (used - (cursor + ROW))
};
let placed =
bounds.unwrap_or(Rect::new(Point::new(x, cursor), Size::new(width, height)));
cursor += height;
if let Some(label) = label {
let inner = Rect::new(
Point::new(placed.x + 1.0, placed.y + 1.0),
Size::new(
(placed.width - 2.0).max(1.0),
(placed.height - 2.0).max(1.0),
),
);
kids.push(RawNode::new(RawCall::Text { content: label }, inner));
}
let mut node = RawNode::new(RawCall::Annotation(annotation.clone()), placed)
.with_children(kids);
node.widget_id = widget_id.clone();
nodes.push(node);
}
Spec::Overlay { depth, children } => overlays.push((*depth, children)),
}
}
for (depth, children) in overlays {
let (kids, _) = layout(children, 0.0, 0.0, WIDTH);
nodes.push(
RawNode::new(
RawCall::Overlay { depth },
Rect::new(Point::ORIGIN, Size::new(WIDTH, HEIGHT)),
)
.with_children(kids),
);
}
(nodes, cursor)
}
impl<R: RoleKind> NodeBuilder<R> {
fn children_mut(&mut self) -> &mut Vec<Spec> {
&mut self.children
}
children_methods!();
fn state(mut self, state: StateName, value: impl Into<StateValue>) -> Self {
self.annotation.states.push((state, value.into()));
self
}
pub fn bounds(mut self, x: f32, y: f32, width: f32, height: f32) -> Self {
self.bounds = Some(Rect::new(Point::new(x, y), Size::new(width, height)));
self
}
pub fn component(mut self, kind: &'static str) -> Self {
self.annotation.source = AnnotationSource::Component;
self.annotation.kind = Some(Cow::Borrowed(kind));
self
}
pub fn kind(mut self, kind: &'static str) -> Self {
self.annotation.kind = Some(Cow::Borrowed(kind));
self
}
pub fn name(mut self, name: &str) -> Self {
self.annotation.name = Some(name.to_owned());
self
}
pub fn description(mut self, text: &str) -> Self {
self.annotation.description = Some(text.to_owned());
self
}
pub fn tooltip(mut self, text: &str) -> Self {
self.annotation.tooltip = Some(text.to_owned());
self
}
pub fn test_id(mut self, id: &str) -> Self {
self.annotation.test_id = Some(id.to_owned());
self
}
pub fn widget_id(mut self, id: &str) -> Self {
self.widget_id = Some(WidgetId::Custom(id.to_owned()));
self
}
pub fn prop(mut self, key: &str, value: &str) -> Self {
self.annotation
.props
.insert(key.to_owned(), value.to_owned());
self
}
pub fn text_size(mut self, size: f32) -> Self {
self.annotation.text_size = Some(size);
self
}
pub fn carets(mut self, carets: impl IntoIterator<Item = (usize, Point)>) -> Self {
self.annotation.carets = carets.into_iter().collect();
self
}
pub fn cursor_seen(mut self, seen: CursorSeen) -> Self {
self.annotation.cursor_seen = Some(seen);
self
}
pub fn key(mut self, key: &str) -> Self {
self.annotation.key = Some(RawKey::Name(key.to_owned()));
self
}
pub fn labelled_by(mut self, key: &str) -> Self {
self.annotation
.labelled_by
.push(RawKey::Name(key.to_owned()));
self
}
pub fn label_for(mut self, key: &str) -> Self {
self.annotation.label_for.push(RawKey::Name(key.to_owned()));
self
}
pub fn described_by(mut self, key: &str) -> Self {
self.annotation
.described_by
.push(RawKey::Name(key.to_owned()));
self
}
pub fn controls(mut self, key: &str) -> Self {
self.annotation.controls.push(RawKey::Name(key.to_owned()));
self
}
pub fn owns(mut self, key: &str) -> Self {
self.annotation.owns.push(RawKey::Name(key.to_owned()));
self
}
pub fn position(mut self, index: u32, of: u32) -> Self {
self.annotation.position = Some((index, of));
self
}
pub fn disabled(self, on: bool) -> Self {
self.state(StateName::Disabled, on)
}
pub fn current(self, on: bool) -> Self {
self.state(StateName::Current, on)
}
pub fn busy(self, on: bool) -> Self {
self.state(StateName::Busy, on)
}
pub fn hidden(self, on: bool) -> Self {
self.state(StateName::Hidden, on)
}
pub fn modal(self, on: bool) -> Self {
self.state(StateName::Modal, on)
}
pub fn required(self, on: bool) -> Self {
self.state(StateName::Required, on)
}
pub fn invalid(self, on: bool) -> Self {
self.state(StateName::Invalid, on)
}
pub fn readonly(self, on: bool) -> Self {
self.state(StateName::Readonly, on)
}
pub fn focused(self, on: bool) -> Self {
self.state(StateName::Focusable, true)
.state(StateName::Focused, on)
}
pub fn checked(self, state: impl Into<Checked>) -> Self
where
R: Checkable,
{
self.state(StateName::Checked, state.into())
}
pub fn pressed(self, on: bool) -> Self
where
R: Pressable,
{
self.state(StateName::Pressed, on)
}
pub fn expanded(self, on: bool) -> Self
where
R: Expandable,
{
self.state(StateName::Expanded, on)
}
pub fn selected(self, on: bool) -> Self
where
R: SelectableItem,
{
self.state(StateName::Selected, on)
}
pub fn level(mut self, level: u16) -> Self
where
R: Leveled,
{
self.annotation.level = Some(level);
self
}
pub fn value(mut self, text: &str) -> Self
where
R: HasValue,
{
self.annotation.value = Some(RawValue::Text(text.to_owned()));
self
}
pub fn range(mut self, now: f64, range: RangeInclusive<f64>) -> Self
where
R: RangeValue,
{
self.annotation.value = Some(RawValue::Number {
now,
min: Some(*range.start()),
max: Some(*range.end()),
step: None,
});
self
}
pub fn placeholder(mut self, text: &str) -> Self
where
R: Editable,
{
self.annotation.placeholder = Some(text.to_owned());
self
}
pub fn multiline(self, on: bool) -> Self
where
R: Editable,
{
self.state(StateName::Multiline, on)
}
}