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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use crossterm::{
    terminal,
    cursor,
    ExecutableCommand,
    QueueableCommand,
    csi,
    Command as ctCommand,
};
use std::error::Error;
use std::fmt;
use std::io;
use std::io::Write;
use rustyline::error::ReadlineError;
use std::any::Any;

pub struct DynamicContext {
    value: Option<Box<dyn Any>>,
}

impl DynamicContext {
    pub fn new() -> Self {
        DynamicContext { value: None }
    }

    pub fn set<T: 'static>(&mut self, value: T) {
        self.value = Some(Box::new(value));
    }

    pub fn get<T: 'static>(&self) -> Option<&T> {
        self.value.as_ref().and_then(|v| v.downcast_ref::<T>())
    }

    pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.value.as_mut().and_then(|v| v.downcast_mut::<T>())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SetScrollingRegion(pub u16, pub u16);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SetScrollingAll();

#[derive(Debug)]
pub enum CrosstermError {
  UnimplementedInWindows,
}

impl std::error::Error for CrosstermError {}

impl fmt::Display for CrosstermError {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      CrosstermError::UnimplementedInWindows => write!(f, 
          "This command is unimplemented for Windows"),
    }
  }
}


/// A command that restricts terminal output scrolling within the given 
/// starting and ending rows.
impl ctCommand for SetScrollingRegion {
    fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
        write!(f, csi!("{};{}r"), self.0, self.1)
    }

    #[cfg(windows)]
    fn execute_winapi(&self) -> Result<(), CrosstermError> {
        Err(CrosstermError::UnimplementedInWindows)
    }
}

/// Enables scrolling for the entire screen.  
/// This is called after running SetScrollingRegion
/// to re-enable terminal scrolling for the entire screen.  
impl ctCommand for SetScrollingAll {
    fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
        write!(f, csi!("r"))
    }

    #[cfg(windows)]
    fn execute_winapi(&self) -> Result<(), CrosstermError> {
        Err(CrosstermError::UnimplementedInWindows)
    }
}


/// Runs the actual command loop, providing readline output via rustyline.
/// The context arg allows for the passing of additional 'context' information
/// to maintain a state during subcalls if needed.
pub fn command_loop(commands: &Vec<Command>, context: &mut DynamicContext) -> Result<(), Box<dyn Error>>{
    setup_screen()?;

    println!("info: type 'help' to for a list of commands");
    let help_str = build_help_str(&commands);
    loop { // command loop
        if let Err(err) = setup_screen(){
            eprintln!("error during screen setup: {}", err.to_string());
        }
        let mut rl = rustyline::Editor::<()>::new().unwrap();
        match rl.readline(">> "){
            Ok(line)=>{
                if line.is_empty(){continue}

                let mut input_split = line.split(' ').collect::<Vec<_>>(); // TODO needs better
                                                                           // tokenization
                let input_command = input_split.remove(0);
                let input_args = &input_split;
                
                // check for the help command
                if input_command.eq("help") || input_command.eq("?") {
                    write_output(help_str.clone(), None)?;
                    continue;
                }
                if input_command.eq("exit") {
                    break;
                }

                for cmd in commands.into_iter().filter(|cmd| cmd.command.eq(input_command)) {
                    let output = (cmd.func)(&input_args, context);
                    match output {
                        Err(err) => eprintln!("error executing '{}': {}", input_command, err.to_string()),
                        Ok(output_str) => write_output(output_str, None).expect("error writing output"),
                    }
                }
            },
            Err(ReadlineError::Interrupted) => std::process::exit(0),
            Err(err)=>{
                eprintln!("error during readline: {}",err.to_string());
                break;
            }
        }
    }

    Ok(())
}

fn build_help_str(commands: &Vec<Command>) -> String {
    let mut help_output = String::from("---help output------------\n");
    commands.into_iter().for_each(|cmd| help_output.push_str(&format!("{}\n", cmd.help_output)));
    help_output.push_str("exit - exit the current prompt");
    help_output
}


/// This function will print a line to the screen, one line above the
/// bottom-most row of the terminal.  
/// Optionally, a prefix can be provided in case you would like to add
/// additional context to the output line.
pub fn write_output(output: String, prefix: Option<String>)->Result<(),Box<dyn Error>>{
    let mut sout = io::stdout().lock();

    // return order (columns, rows)
    let size = crossterm::terminal::size()?;
    let stdout_end = size.1-1;
    let mut final_output = String::new();

    // add the prefix to the output if it was provided
    if let Some(line) = prefix {
        final_output.push_str(line.as_str());
        final_output.push_str(": ");
    }

    final_output.push_str(output.as_str());

    sout.queue(cursor::SavePosition)?;

    // restrict scrolling to a specific area of the screen
    // this is run every time in case the screen size changes at some point
    sout.queue(SetScrollingRegion(1,stdout_end))?
        .queue(terminal::ScrollUp(1))? 
        .queue(cursor::MoveTo(0, stdout_end-1))?; // move to the line right above stdin

    print!("{}", final_output);
    sout.queue(SetScrollingAll())?
        .queue(cursor::RestorePosition)?;
    sout.flush()?;
    Ok(())
}

/// Sets the cursor location to the bottom-most row and the column to 1.  
/// This gets run automatically in command_loop().
pub fn setup_screen()->Result<(),Box<dyn Error>>{
    let size = crossterm::terminal::size()?;
    let mut sout = std::io::stdout().lock();
    sout.execute(cursor::MoveToRow(size.1))?;
    Ok(())
}

pub struct Command<'r> {
    pub command: &'r str,
    pub func: fn(&[&str], &mut DynamicContext)->Result<String, Box<dyn Error>>,
    pub help_output: &'r str,
}