use egui::Rect;
use super::shares;
use crate::NodeIndex;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LinearDir {
#[default]
Horizontal,
Vertical,
}
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(default)
)]
pub struct LinearNode {
pub rect: Rect,
pub dir: LinearDir,
pub(crate) children: Vec<NodeIndex>,
pub(crate) shares: Vec<f32>,
pub fully_collapsed: bool,
pub collapsed_leaf_count: i32,
}
impl Default for LinearNode {
fn default() -> Self {
Self::new(LinearDir::default(), Vec::new(), Vec::new())
}
}
impl LinearNode {
pub fn new(dir: LinearDir, children: Vec<NodeIndex>, shares: Vec<f32>) -> Self {
assert_eq!(
children.len(),
shares.len(),
"a linear node has one share per child"
);
Self {
rect: Rect::NOTHING,
dir,
children,
shares,
fully_collapsed: false,
collapsed_leaf_count: 0,
}
}
#[inline]
pub fn set_rect(&mut self, new_rect: Rect) {
self.rect = new_rect;
}
pub fn rect(&self) -> Rect {
self.rect
}
pub fn children(&self) -> &[NodeIndex] {
&self.children
}
pub fn shares(&self) -> &[f32] {
&self.shares
}
pub fn len(&self) -> usize {
self.children.len()
}
pub fn is_empty(&self) -> bool {
self.children.is_empty()
}
pub fn position(&self, child: NodeIndex) -> Option<usize> {
self.children.iter().position(|&c| c == child)
}
pub fn fraction(&self, index: usize) -> f32 {
shares::fraction(&self.shares, index)
}
pub fn boundary(&self, index: usize) -> f32 {
shares::boundary(&self.shares, index)
}
pub fn set_shares(&mut self, shares: Vec<f32>) {
assert_eq!(
shares.len(),
self.children.len(),
"a linear node has one share per child"
);
assert!(
shares.iter().all(|s| s.is_finite() && *s >= 0.0),
"shares are finite and not negative"
);
self.shares = shares;
}
pub(crate) fn normalize_shares(&mut self) {
shares::normalize(&mut self.shares);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn node(shares: &[f32]) -> LinearNode {
LinearNode::new(
LinearDir::Horizontal,
(0..shares.len()).map(NodeIndex).collect(),
shares.to_vec(),
)
}
#[test]
fn fractions_and_boundaries() {
let n = node(&[1.0, 2.0, 1.0]);
assert_eq!(n.fraction(1), 0.5);
assert_eq!(n.boundary(0), 0.25);
assert_eq!(n.boundary(1), 0.75);
assert!((n.boundary(2) - 1.0).abs() < 1e-6);
}
#[test]
fn a_boundary_moves_its_pair_only() {
let mut n = node(&[0.25, 0.5, 0.25]);
shares::move_boundary(&mut n.shares, 1, 0.1, 0.05);
assert_eq!(n.shares()[0], 0.25);
assert!((n.shares()[1] - 0.6).abs() < 1e-6);
assert!((n.shares()[2] - 0.15).abs() < 1e-6);
shares::move_boundary(&mut n.shares, 1, 1.0, 0.05);
assert!((n.shares()[2] - 0.05).abs() < 1e-6);
assert_eq!(n.shares()[0], 0.25);
}
#[test]
fn an_even_pair() {
let mut n = node(&[2.0, 1.0, 1.0]);
shares::even_pair(&mut n.shares, 0);
assert_eq!(n.shares(), &[0.375, 0.375, 0.25]);
}
}