summaryrefslogtreecommitdiffstats
path: root/src/commands/command_line.rs
blob: ff3c694a9b5be5d11f7ef7238db5a0722b49bff2 (plain)
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
use crate::commands::{self, JoshutoCommand, JoshutoRunnable};
use crate::context::JoshutoContext;
use crate::error::JoshutoResult;
use crate::util::textfield::TextField;
use crate::ui::TuiBackend;

#[derive(Clone, Debug)]
pub struct CommandLine {
    pub prefix: String,
    pub suffix: String,
}

impl CommandLine {
    pub fn new(prefix: String, suffix: String) -> Self {
        CommandLine { prefix, suffix }
    }
    pub const fn command() -> &'static str {
        "console"
    }

    pub fn readline(
        &self,
        context: &mut JoshutoContext,
        backend: &mut TuiBackend,
    ) -> JoshutoResult<()> {
        let mut textfield = TextField::new(backend, &context.events);
        let user_input: Option<String> = textfield.readline();

        if let Some(s) = user_input {
            let trimmed = s.trim_start();
            match trimmed.find(' ') {
                Some(ind) => {
                    let (cmd, xs) = trimmed.split_at(ind);
                    let xs = xs.trim_start();
                    let args: Vec<String> = vec![String::from(xs)];
                    let command = commands::from_args(cmd.to_string(), args)?;
                    command.execute(context, backend)
                }
                None => commands::from_args(String::from(trimmed), Vec::new())?
                    .execute(context, backend),
            }
        } else {
            Ok(())
        }
    }
}

impl JoshutoCommand for CommandLine {}

impl std::fmt::Display for CommandLine {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}: {} {}", Self::command(), self.prefix, self.suffix)
    }
}

impl JoshutoRunnable for CommandLine {
    fn execute(&self, context: &mut JoshutoContext, backend: &mut TuiBackend) -> JoshutoResult<()> {
        let res = self.readline(context, backend);
        ncurses::doupdate();
        res
    }
}