use super::{super::backend::*, depth::*, iterator::*, kind::*, list::*, node::*, path::*};
use {
cursive::{style::*, utils::span::*, *},
std::cmp::*,
};
pub struct TreeModel<BackendT>
where
BackendT: TreeBackend,
{
pub roots: NodeList<BackendT>,
pub context: BackendT::Context,
}
impl<BackendT> TreeModel<BackendT>
where
BackendT: TreeBackend,
{
pub fn new(context: BackendT::Context) -> Self {
Self { roots: Default::default(), context }
}
pub fn is_empty(&self) -> bool {
self.roots.0.is_empty()
}
pub fn iter(&self, only_expanded: bool) -> NodeIterator<'_, BackendT> {
self.roots.iter(only_expanded)
}
pub fn at_path(&self, path: NodePath) -> Option<&Node<BackendT>> {
self.roots.at_path(path)
}
pub fn at_path_mut(&mut self, path: NodePath) -> Option<&mut Node<BackendT>> {
self.roots.at_path_mut(path)
}
pub fn at_row(&self, row: usize) -> Option<&Node<BackendT>> {
let mut iterator = self.iter(true);
let mut current_row: usize = 0;
while let Some(node) = iterator.next() {
let next_row = current_row + node.label_size.y;
if (row >= current_row) && (row < next_row) {
return Some(node);
}
current_row = next_row;
}
None
}
pub fn path(&self, node: &Node<BackendT>) -> Option<NodePath> {
let mut path = Default::default();
if self.roots.fill_path(&mut path, node) { Some(path) } else { None }
}
pub fn extents(&self) -> Vec2 {
let mut extents = Vec2::default();
let mut iterator = self.iter(true);
while let Some(node) = iterator.next() {
extents.x = max(extents.x, node.depth * 2 + 2 + node.label_size.x);
extents.y += node.label_size.y;
}
extents
}
pub fn add_root<IdT, LabelT>(&mut self, kind: NodeKind, id: IdT, label: LabelT)
where
IdT: Into<BackendT::ID>,
LabelT: Into<SpannedString<Style>>,
{
self.roots.add(0, kind, id, label);
}
pub fn insert_root<IdT, LabelT>(&mut self, index: usize, kind: NodeKind, id: IdT, label: LabelT)
where
IdT: Into<BackendT::ID>,
LabelT: Into<SpannedString<Style>>,
{
self.roots.insert(index, 0, kind, id, label);
}
pub fn expand(&mut self, depth: Option<usize>) -> Result<(), BackendT::Error>
where
BackendT::Context: Clone,
{
self.roots.expand(depth, self.context.clone())
}
pub fn collapse(&mut self, depth: Option<usize>) {
self.roots.collapse(depth);
}
pub fn populate(&mut self, mut depth: Option<usize>) -> Result<(), BackendT::Error>
where
BackendT::Context: Clone,
{
if depth.is_zero() {
return Ok(());
}
self.roots = BackendT::roots(self.context.clone())?;
depth.decrease();
if !depth.is_zero() {
for node in &mut self.roots {
node.populate(depth, self.context.clone())?;
}
}
Ok(())
}
pub fn clear(&mut self) {
self.roots.0.clear();
}
}