summaryrefslogtreecommitdiffstats
path: root/src/commands/command_line.rs
blob: 577d988150a3ec9ba3dffeb9bf7156e073534073 (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
use crate::commands::{self, JoshutoCommand, JoshutoRunnable};
use crate::context::JoshutoContext;
use crate::error::JoshutoResult;
use crate::ui::widgets::TuiTextField;
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 = TuiTextField::default()
            .prompt(":")
            .prefix(self.prefix.as_str())
            .suffix(self.suffix.as_str());
        let user_input: Option<String> = textfield.get_input(backend, &context);

        if let Some(s) = user_input {
            let trimmed = s.trim_start();
            let command = commands::parse_command(trimmed)?;
            command.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<()> {
        self.readline(context, backend)
    }
}