use std::collections::HashMap;
use torin::prelude::*;
#[derive(Clone)]
struct DemoNode {
parent: Option<usize>,
children: Vec<usize>,
height: u16,
node: Node,
}
#[derive(Default)]
pub struct DemoDOM {
nodes: HashMap<usize, DemoNode>,
}
impl DemoDOM {
pub fn add(&mut self, node_id: usize, parent: Option<usize>, children: Vec<usize>, node: Node) {
let parent_height = parent
.map(|p| self.nodes.get(&p).unwrap().height)
.unwrap_or(0);
let height = parent_height + 1;
self.nodes.insert(
node_id,
DemoNode {
parent,
children,
height,
node,
},
);
}
pub fn set_node(&mut self, node_id: usize, node: Node) {
self.nodes.get_mut(&node_id).unwrap().node = node;
}
pub fn remove(&mut self, node_id: usize) {
let node = self.nodes.remove(&node_id).unwrap();
if let Some(DemoNode { children, .. }) = node.parent.and_then(|p| self.nodes.get_mut(&p)) {
children.retain(|c| *c != node_id);
}
for child in node.children {
self.remove(child);
}
}
}
impl DOMAdapter<usize> for DemoDOM {
fn children_of(&mut self, node_id: &usize) -> Vec<usize> {
self.nodes
.get(node_id)
.map(|c| c.children.clone())
.unwrap_or_default()
}
fn parent_of(&self, node_id: &usize) -> Option<usize> {
self.nodes.get(node_id).and_then(|c| c.parent)
}
fn height(&self, node_id: &usize) -> Option<u16> {
self.nodes.get(node_id).map(|c| c.height)
}
fn get_node(&self, node_id: &usize) -> Option<Node> {
self.nodes.get(node_id).map(|c| c.node.clone())
}
fn is_node_valid(&mut self, _node_id: &usize) -> bool {
true
}
fn root_id(&self) -> usize {
0 }
}
fn main() {
let mut layout = Torin::<usize>::new();
let mut demo_dom = DemoDOM::default();
demo_dom.add(
0, None, vec![1], Node::from_size_and_alignments_and_direction(
Size::Pixels(Length::new(200.0)),
Size::Pixels(Length::new(200.0)),
Alignment::Center,
Alignment::Center,
Direction::Horizontal,
),
);
demo_dom.add(
1, Some(0), vec![2], Node::from_size_and_direction(
Size::Pixels(Length::new(100.0)),
Size::Pixels(Length::new(100.0)),
Direction::Vertical,
),
);
demo_dom.add(
2, Some(1), vec![], Node::from_size_and_direction(
Size::Percentage(Length::new(50.0)),
Size::Percentage(Length::new(50.0)),
Direction::Vertical,
),
);
layout.measure(
0, Rect::new(Point2D::new(0.0, 0.0), Size2D::new(1000.0, 1000.0)), &mut None::<NoopMeasurer>,
&mut demo_dom,
);
demo_dom.set_node(
1, Node::from_size_and_direction(
Size::Percentage(Length::new(80.0)), Size::Percentage(Length::new(80.0)), Direction::Vertical,
),
);
layout.invalidate(1);
println!("Initial measurement");
for (id, node) in &layout.results {
println!("{id:?} -> {:?}", node.area);
}
layout.find_best_root(&mut demo_dom);
layout.measure(
0, Rect::new(Point2D::new(0.0, 0.0), Size2D::new(1000.0, 1000.0)), &mut None::<NoopMeasurer>,
&mut demo_dom,
);
println!("\nSecond measurement");
for (id, node) in &layout.results {
println!("{id:?} -> {:?}", node.area);
}
}