summaryrefslogtreecommitdiffstats
path: root/src/app.rs
blob: 74c46ba56ee674f5a51d02d8914330e6e053541b (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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//! broot's app is mainly a stack of AppState.
//! Commands parsed from the input are submitted to the current
//! appstate, which replies with a stateCmdResult which may
//! be
//! - a transition to a new state
//! - a pop to get back to the previous one
//! - an operation which keeps the state
//! - a request to quit broot
//! - a request to launch an executable (thus leaving broot)
use std::io::{self, Write};
use std::result::Result;

use crate::app_context::AppContext;
use crate::browser_states::BrowserState;
use crate::command_parsing::parse_command_sequence;
use crate::commands::Command;
use crate::event::EventSource;
use crate::errors::ProgramError;
use crate::errors::TreeBuildError;
use crate::external::Launchable;
use crate::input::Input;
use crate::screens::Screen;
use crate::skin::Skin;
use crate::spinner::Spinner;
use crate::status::Status;
use crate::task_sync::TaskLifetime;

/// Result of applying a command to a state
pub enum AppStateCmdResult {
    Quit,
    Keep,
    Launch(Launchable),
    DisplayError(String),
    NewState(Box<dyn AppState>, Command),
    PopStateAndReapply, // the state asks the command be executed on a previous state
    PopState,
    RefreshState,
}

impl AppStateCmdResult {
    pub fn verb_not_found(text: &str) -> AppStateCmdResult {
        AppStateCmdResult::DisplayError(format!("verb not found: {:?}", &text))
    }
    pub fn from_optional_state(
        os: Result<Option<BrowserState>, TreeBuildError>,
        cmd: Command,
    ) -> AppStateCmdResult {
        match os {
            Ok(Some(os)) => AppStateCmdResult::NewState(Box::new(os), cmd),
            Ok(None) => AppStateCmdResult::Keep,
            Err(e) => AppStateCmdResult::DisplayError(e.to_string()),
        }
    }
}

/// a whole application state, stackable to allow reverting
///  to a previous one
pub trait AppState {
    fn apply(
        &mut self,
        cmd: &mut Command,
        screen: &mut Screen,
        con: &AppContext,
    ) -> io::Result<AppStateCmdResult>;
    fn refresh(&mut self, screen: &Screen, con: &AppContext) -> Command;
    fn has_pending_tasks(&self) -> bool;
    fn do_pending_task(&mut self, screen: &mut Screen, tl: &TaskLifetime);
    fn display(&mut self, screen: &mut Screen, con: &AppContext) -> io::Result<()>;
    fn write_status(&self, screen: &mut Screen, cmd: &Command, con: &AppContext) -> io::Result<()>;
    fn write_flags(&self, screen: &mut Screen, con: &AppContext) -> io::Result<()>;
}

pub struct App {
    states: Vec<Box<dyn AppState>>, // stack: the last one is current
    quitting: bool,
    launch_at_end: Option<Launchable>, // what must be launched after end
}

impl App {
    pub fn new() -> App {
        App {
            states: Vec::new(),
            quitting: false,
            launch_at_end: None,
        }
    }

    pub fn push(&mut self, new_state: Box<dyn AppState>) {
        self.states.push(new_state);
    }

    fn mut_state(&mut self) -> &mut Box<dyn AppState> {
        match self.states.last_mut() {
            Some(s) => s,
            None => {
                panic!("No path has been pushed");
            }
        }
    }
    fn state(&self) -> &Box<dyn AppState> {
        match self.states.last() {
            Some(s) => s,
            None => {
                panic!("No path has been pushed");
            }
        }
    }

    /// execute all the pending tasks until there's none remaining or
    ///  the allowed lifetime is expired (usually when the user typed a new key)
    fn do_pending_tasks(
        &mut self,
        cmd: &Command,
        screen: &mut Screen,
        con: &AppContext,
        tl: TaskLifetime,
    ) -> io::Result<()> {
        let has_task = self.state().has_pending_tasks();
        if has_task {
            loop {
                self.mut_state().display(screen, con)?;
                self.state().write_status(screen, &cmd, con)?;
                screen.write_spinner(true)?;
                if tl.is_expired() {
                    break;
                }
                self.mut_state().do_pending_task(screen, &tl);
                if !self.state().has_pending_tasks() {
                    break;
                }
            }
            screen.write_spinner(false)?;
        }
        self.mut_state().display(screen, con)?;
        self.mut_state().write_status(screen, &cmd, con)?;
        Ok(())
    }

    /// apply a command, and returns a command, which may be the same (modified or not)
    ///  or a new one.
    /// This normally mutates self
    fn apply_command(
        &mut self,
        cmd: Command,
        screen: &mut Screen,
        con: &AppContext,
    ) -> io::Result<Command> {
        let mut cmd = cmd;
        debug!("action: {:?}", &cmd.action);
        screen.read_size(con)?;
        screen.write_input(&cmd)?;
        self.state().write_flags(screen, con)?;
        screen.write_spinner(false)?;
        match self.mut_state().apply(&mut cmd, screen, con)? {
            AppStateCmdResult::Quit => {
                debug!("cmd result quit");
                self.quitting = true;
            }
            AppStateCmdResult::Launch(launchable) => {
                self.launch_at_end = Some(launchable);
                self.quitting = true;
            }
            AppStateCmdResult::NewState(boxed_state, new_cmd) => {
                self.push(boxed_state);
                cmd = new_cmd;
                self.state().write_status(screen, &cmd, con)?;
            }
            AppStateCmdResult::RefreshState => {
                cmd = self.mut_state().refresh(screen, con);
            }
            AppStateCmdResult::PopState => {
                if self.states.len() == 1 {
                    debug!("quitting on last pop state");
                    self.quitting = true;
                } else {
                    self.states.pop();
                    cmd = self.mut_state().refresh(screen, con);
                    self.state().write_status(screen, &cmd, con)?;
                }
            }
            AppStateCmdResult::PopStateAndReapply => {
                if self.states.len() == 1 {
                    debug!("quitting on last pop state");
                    self.quitting = true;
                } else {
                    self.states.pop();
                    debug!("about to reapply {:?}", &cmd);
                    return self.apply_command(cmd, screen, con);
                }
            }
            AppStateCmdResult::DisplayError(txt) => {
                screen.write_status_err(&txt)?;
            }
            AppStateCmdResult::Keep => {
                self.state().write_status(screen, &cmd, con)?;
            }
        }
        screen.write_input(&cmd)?;
        self.state().write_flags(screen, con)?;
        Ok(cmd)
    }

    /// This is the main loop of the application
    pub fn run(mut self, con: &AppContext, skin: Skin) -> Result<Option<Launchable>, ProgramError> {
        let mut screen = Screen::new(con, skin)?;

        // create the initial state
        if let Some(bs) = BrowserState::new(
            con.launch_args.root.clone(),
            con.launch_args.tree_options.clone(),
            &screen,
            &TaskLifetime::unlimited(),
        )? {
            self.push(Box::new(bs));
        } else {
            unreachable!();
        }

        let mut cmd = Command::new();

        // if some commands were passed to the application
        //  we execute them before even starting listening for events
        if let Some(unparsed_commands) = &con.launch_args.commands {
            let commands = parse_command_sequence(unparsed_commands, con)?;
            for arg_cmd in &commands {
                cmd = (*arg_cmd).clone();
                cmd = self.apply_command(cmd, &mut screen, con)?;
                self.do_pending_tasks(&cmd, &mut screen, con, TaskLifetime::unlimited())?;
                if self.quitting {
                    return Ok(self.launch_at_end.take());
                }
            }
        }