use crate::{widgets::Layout, Align, Direction};
use super::{Shape, Size};
#[derive(Debug)]
pub struct Aligner {
widths: Vec<usize>,
heights: Vec<usize>,
pub index: usize,
}
impl Aligner {
pub fn new(shapes: &Vec<Shape>) -> Self {
let mut widths = vec![];
let mut heights = vec![];
for shape in &shapes.clone() {
let shape_size: Size = super::calculate_size(shape);
widths.push(shape_size[0]);
heights.push(shape_size[1]);
}
Self {
index: 0,
widths,
heights,
}
}
pub fn align_shapes(&mut self, layout: &Layout, layout_shape: &Shape, shapes: &mut Vec<Shape>) {
for mut shape in shapes {
self.align_shape(layout, layout_shape, &mut shape);
}
}
pub fn align_shape(&mut self, layout: &Layout, layout_shape: &Shape, shape: &mut Shape) {
let shape_size: Size = super::calculate_size(shape);
let parent_size: Size = super::calculate_size(layout_shape);
let offset_width = self.widths[..self.index].iter().sum::<usize>() as isize;
let offset_height = self.heights[..self.index].iter().sum::<usize>() as isize;
let setoff_width = self.widths[self.index..].iter().sum::<usize>() as isize;
let setoff_height = self.heights[self.index..].iter().sum::<usize>() as isize;
let (x, y) = match layout.direction {
Direction::Column => (
match layout.wx_align {
Align::Left => offset_width,
Align::Center => {
let space: isize = (parent_size[0] as isize - self.widths.iter().sum::<usize>() as isize) / 2;
if self.index == 0 {
space
} else {
space + offset_width
}
}
Align::Right => parent_size[0] as isize - setoff_width,
_ => panic!("layout widgets alignment on the x axis is `Align::{:?}` but should be either `Align::Left`, `Align::Center` or `Align::Right`", layout.wx_align),
},
match layout.wy_align {
Align::Top => 0,
Align::Center => (parent_size[1] as isize - shape_size[1] as isize) / 2,
Align::Bottom => parent_size[1] as isize - shape_size[1] as isize,
_ => panic!("layout widgets alignment on the y axis is `Align::{:?}` but should be either `Align::Top`, `Align::Center` or `Align::Bottom`", layout.wy_align),
}
),
Direction::Row => (
match layout.wx_align {
Align::Left => 0,
Align::Center => (parent_size[0] as isize - shape_size[0] as isize) / 2,
Align::Right => parent_size[0] as isize - shape_size[0] as isize,
_ => panic!("layout widgets alignment on the x axis is `Align::{:?}` but should be either `Align::Left`, `Align::Center` or `Align::Right`", layout.wx_align),
},
match layout.wy_align {
Align::Top => offset_height,
Align::Center => {
let space: isize = (parent_size[1] as isize - self.heights.iter().sum::<usize>() as isize) / 2;
if self.index == 0 {
space
} else {
space + offset_height
}
}
Align::Bottom => parent_size[1] as isize - setoff_height as isize,
_ => panic!("layout widgets alignment on the y axis is `Align::{:?}` but should be either `Align::Top`, `Align::Center` or `Align::Bottom`", layout.wy_align),
}
)
};
let layout_position = layout_shape.points()[0];
shape.move_by([layout_position[0] + x, layout_position[1] + y]);
self.index += 1;
}
}