// nixos-config - My current NixOS configuration // // Copyright (C) 2025 Benedikt Peetz // SPDX-License-Identifier: GPL-3.0-or-later // // This file is part of my nixos-config. // // You should have received a copy of the License along with this program. // If not, see . use std::{cmp, collections::HashMap, fmt::Write, io::stderr, path::PathBuf, slice}; use anyhow::Result; use crossterm::{ cursor::{MoveToRow, MoveUp}, event::{ Event, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags, read, }, execute, style::Print, terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen}, }; use keymaps::map_tree::{Node, NodeValue, Trie}; use crate::mapping::{MapChild, map_key::MapKey}; use super::MappingsTrie; // macro_rules! dbg { // ($name:expr) => {{ // use std::io::Write; // // let mut opts = std::fs::File::options(); // opts.create(true).append(true); // // let mut file = opts.open("./debug").unwrap(); // let _ = writeln!(file, "{} = {:#?}", stringify!($name), $name); // // $name // }}; // } enum Status { Done(PathBuf), Stop, } impl MappingsTrie { fn render_trie(node: &Node) -> String { #[expect(clippy::too_many_arguments)] fn write_node( f: &mut String, node: &Node, indention: &str, location: &[MapKey], is_last: bool, is_root: bool, current_depth: usize, max_depth: u16, ) -> std::fmt::Result { let node_value = match &node.value() { None => match location.last() { Some(last) => format!("<{} ..>", last.part_path), None => "".to_owned(), }, Some(value) => value.to_string(), }; let new_idention = indention.to_string() + if is_root { "" } else if is_last { " " } else { "│ " }; let bullet = if is_last { String::from("└── ") } else { String::from("├── ") }; if is_root { writeln!(f, ": {node_value}")?; } else { writeln!( f, "{indention}{bullet}\x1b[1;33m{location}\x1b[0m: {node_value}", location = location.iter().map(ToString::to_string).collect::(), )?; }; match &node.value() { None if current_depth <= (max_depth as usize) => { let mut children_vec: Vec<_> = node.children().unwrap().iter().collect(); children_vec.sort_by_key(|(a, _)| *a); for (counter, (key, child)) in (1..).zip(children_vec.iter()) { let mut new_location = location.to_vec(); new_location.push((*key).to_owned()); write_node( f, child, &new_idention, &new_location, counter == children_vec.len(), false, current_depth + 1, max_depth, )?; } } None | Some(_) => { // Do nothing and stop the recursion } } Ok(()) } let max_depth = { fn collect_nodes_to( node: &Node, target_depth: u16, current_depth: u16, current_children: usize, ) -> usize { if target_depth == current_depth { return current_children + 1; } match node.children() { Some(children) => { 1 + children .values() .map(|child| { collect_nodes_to(child, target_depth, current_depth + 1, 0) }) .sum::() } None => current_children + 1, } } let (_, terminal_lines) = crossterm::terminal::size().unwrap_or((u16::MAX, u16::MAX)); let mut found_depth = 0; let mut previous_children_number = None; for depth in 0.. { let number_of_children = collect_nodes_to(node, depth, 0, 0); if number_of_children >= (terminal_lines as usize) { break; } else if previous_children_number == Some(number_of_children) { // We reached the end, increasing the depth does not mean more children. break; } else { previous_children_number = Some(number_of_children); found_depth = depth; } } found_depth - 1 }; let mut f = String::new(); write_node(&mut f, node, "", &[], false, true, 0, max_depth).unwrap(); f } pub fn interactive_start(&self, home_path: PathBuf) -> Result<()> { terminal::enable_raw_mode()?; execute!( stderr(), EnterAlternateScreen, PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES), MoveToRow(0) )?; let output = self.interactive_start_inner(home_path); execute!(stderr(), LeaveAlternateScreen, PopKeyboardEnhancementFlags)?; terminal::disable_raw_mode()?; match output? { Status::Done(path_buf) => { println!("{}", path_buf.display()) } Status::Stop => (), } Ok(()) } fn interactive_start_inner(&self, home_path: PathBuf) -> Result { macro_rules! done { ($state:ident, $last_length:ident) => {{ let value = match self.0.get(&$state).expect("Is some").value() { Some(value) => value, None => return Ok(Status::Stop), }; let path = home_path.join(&value.path); terminal::disable_raw_mode()?; execute!( stderr(), MoveUp($last_length as u16), Clear(ClearType::FromCursorDown), Print(format!("{}\n", path.display())) )?; terminal::enable_raw_mode()?; return Ok(Status::Done(path)); }}; } let mut state: Vec = vec![]; let mut last_length: usize = 1; while let (trie, matched) = self.0.try_get(&state) && matched == state { if trie.value().is_some() { done!(state, last_length); } else { if let Some(last) = state.last_mut() && let Some(mlast) = matched.last() { last.resolution = mlast.resolution; mlast.part_path.clone_into(&mut last.part_path); } } { terminal::disable_raw_mode()?; let string = Self::render_trie(trie); execute!( stderr(), MoveUp(last_length as u16), Clear(ClearType::FromCursorDown), Print(format!( "Current state: {}\n", self.current_progress(home_path.display().to_string(), &state) )), Print(&string) )?; last_length = string.lines().count() + 1; terminal::enable_raw_mode()?; } if let Event::Key(event) = read()? && event.kind == KeyEventKind::Press { match event.code { crossterm::event::KeyCode::Backspace => { state.pop(); } crossterm::event::KeyCode::Enter => done!(state, last_length), crossterm::event::KeyCode::Esc => break, crossterm::event::KeyCode::Char(char) => { if event.modifiers == KeyModifiers::CONTROL && char == 'c' { break; } else { state.push(MapKey { key: char, resolution: 0, part_path: String::new(), }); } } crossterm::event::KeyCode::Left | crossterm::event::KeyCode::Right | crossterm::event::KeyCode::Up | crossterm::event::KeyCode::Down | crossterm::event::KeyCode::Home | crossterm::event::KeyCode::End | crossterm::event::KeyCode::PageUp | crossterm::event::KeyCode::PageDown | crossterm::event::KeyCode::Tab | crossterm::event::KeyCode::BackTab | crossterm::event::KeyCode::Delete | crossterm::event::KeyCode::Insert | crossterm::event::KeyCode::F(_) | crossterm::event::KeyCode::Null | crossterm::event::KeyCode::CapsLock | crossterm::event::KeyCode::ScrollLock | crossterm::event::KeyCode::NumLock | crossterm::event::KeyCode::PrintScreen | crossterm::event::KeyCode::Pause | crossterm::event::KeyCode::Menu | crossterm::event::KeyCode::KeypadBegin | crossterm::event::KeyCode::Media(_) | crossterm::event::KeyCode::Modifier(_) => (), } } } Ok(Status::Stop) } fn current_progress(&self, home_path: String, state: &[MapKey]) -> String { state .iter() .map(|mk| &mk.part_path) .fold(home_path, |acc, part| format!("{acc}/{part}")) } }