1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::collections::HashMap;
use std::ffi::OsString;
use std::io::Write;

use crossterm::event::{self, Event, KeyEvent};
use crossterm::{cursor, execute, queue, style, terminal, Result};

use crate::crawl::{DataType, PathSizeRecord, PathSizeRecorder};

mod handler;
mod render;

use handler::CommandResponse;

const INDENT_LEN: u16 = 2;

#[derive(Debug)]
pub(super) struct TreeNode {
  pub(super) path: OsString,
  pub(super) data_type: DataType,
  pub(super) size: u64,
  pub(super) is_expanded: bool,
  pub(super) children: Vec<TreeNode>,
}

impl TreeNode {
  // TODO(greg): allow this to happen incrementally
  fn from_recorder(recorder: PathSizeRecorder) -> TreeNode {
    let children = TreeNode::from_recorder_children(recorder.data.children);
    TreeNode {
      path: recorder.root.clone().into_os_string(),
      data_type: recorder.data_type,
      size: recorder.data.size,
      is_expanded: false,
      children,
    }
  }

  fn from_recorder_children(
    child_map: HashMap<OsString, PathSizeRecord>,
  ) -> Vec<TreeNode> {
    let mut child_nodes: Vec<TreeNode> = child_map
      .into_iter()
      .map(|(k, v)| TreeNode {
        path: k,
        data_type: v.data_type,
        size: v.size,
        is_expanded: false,
        children: TreeNode::from_recorder_children(v.children),
      })
      .collect();
    child_nodes.sort_by(|a, b| b.size.cmp(&a.size));
    child_nodes
  }
}

pub struct CrosstermCli {
  /// Contents of the crawled file tree
  pub(super) tree: TreeNode,
  /// Path in the file tree of the node pointed to by the cursor
  pub(super) current_path: Vec<usize>,
  /// Position on the screen of the cursor
  pub(super) cursor_pos: cursor::MoveTo,
  /// Path in the file tree of the node at the top of the screen
  pub(super) top_path: Vec<usize>,
}

impl CrosstermCli {
  pub fn from_recorder(recorder: PathSizeRecorder) -> CrosstermCli {
    CrosstermCli {
      tree: TreeNode::from_recorder(recorder),
      current_path: vec![],
      cursor_pos: cursor::MoveTo(1, 0), // start at column 1 to be on root node's expand toggle
      top_path: vec![],
    }
  }

  pub fn run<W>(mut self, w: &mut W) -> Result<()>
  where
    W: Write,
  {
    execute!(w, style::ResetColor, terminal::EnterAlternateScreen)?;
    terminal::enable_raw_mode()?;

    self.render(w)?;
    loop {
      match self.handle_key(read_key()?)? {
        CommandResponse::Quit => break,
        CommandResponse::RerenderScreen => self.render(w)?,
        CommandResponse::RerenderCursor => self.render_cursor(w)?,
        CommandResponse::NoOp => {},
      }
    }

    execute!(
      w,
      style::ResetColor,
      cursor::Show,
      terminal::LeaveAlternateScreen
    )?;

    terminal::disable_raw_mode()
  }

  pub(super) fn node_at_path(&self, path: &[usize]) -> &TreeNode {
    let mut curr_node = &self.tree;
    for c in path.as_ref() {
      curr_node = &curr_node.children[*c];
    }
    curr_node
  }

  pub(super) fn curr_node_mut(&mut self) -> &mut TreeNode {
    let mut curr_node = &mut self.tree;
    for c in &self.current_path {
      curr_node = &mut curr_node.children[*c];
    }
    curr_node
  }

  fn debug<W>(&self, w: &mut W, row: u16, msg: &str) -> Result<()>
  where
    W: Write,
  {
    queue!(
      w,
      cursor::MoveTo(35, row),
      style::Print(msg),
      self.cursor_pos,
    )
  }
}

fn read_key() -> Result<KeyEvent> {
  loop {
    if let Ok(Event::Key(ke)) = event::read() {
      return Ok(ke);
    }
  }
}