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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
pub use crate::builder::CliBuilder;

use core::fmt::Debug;

#[cfg(not(feature = "history"))]
use core::marker::PhantomData;

use crate::{
    buffer::Buffer,
    codes,
    command::RawCommand,
    editor::Editor,
    input::{ControlInput, Input, InputGenerator},
    service::{Autocomplete, CommandProcessor, Help, ProcessError},
    token::Tokens,
    writer::{WriteExt, Writer},
};

#[cfg(feature = "autocomplete")]
use crate::autocomplete::Request;

#[cfg(feature = "help")]
use crate::{help::HelpRequest, service::HelpError};

#[cfg(feature = "history")]
use crate::history::History;

use embedded_io::{Error, Write};

const PROMPT: &str = "$ ";

pub struct CliHandle<'a, W: Write<Error = E>, E: embedded_io::Error> {
    writer: Writer<'a, W, E>,
}

impl<'a, W, E> CliHandle<'a, W, E>
where
    W: Write<Error = E>,
    E: embedded_io::Error,
{
    pub fn writer(&mut self) -> &mut Writer<'a, W, E> {
        &mut self.writer
    }

    fn new(writer: Writer<'a, W, E>) -> Self {
        Self { writer }
    }
}

impl<'a, W, E> Debug for CliHandle<'a, W, E>
where
    W: Write<Error = E>,
    E: embedded_io::Error,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CliHandle").finish()
    }
}

#[cfg(feature = "history")]
enum NavigateHistory {
    Older,
    Newer,
}

enum NavigateInput {
    Backward,
    Forward,
}

#[doc(hidden)]
pub struct Cli<W: Write<Error = E>, E: Error, CommandBuffer: Buffer, HistoryBuffer: Buffer> {
    editor: Option<Editor<CommandBuffer>>,
    #[cfg(feature = "history")]
    history: History<HistoryBuffer>,
    input_generator: Option<InputGenerator>,
    prompt: &'static str,
    writer: W,
    #[cfg(not(feature = "history"))]
    _ph: PhantomData<HistoryBuffer>,
}

impl<W, E, CommandBuffer, HistoryBuffer> Debug for Cli<W, E, CommandBuffer, HistoryBuffer>
where
    W: Write<Error = E>,
    E: embedded_io::Error,
    CommandBuffer: Buffer,
    HistoryBuffer: Buffer,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Cli")
            .field("editor", &self.editor)
            .field("input_generator", &self.input_generator)
            .field("prompt", &self.prompt)
            .finish()
    }
}

impl<W, E, CommandBuffer, HistoryBuffer> Cli<W, E, CommandBuffer, HistoryBuffer>
where
    W: Write<Error = E>,
    E: embedded_io::Error,
    CommandBuffer: Buffer,
    HistoryBuffer: Buffer,
{
    #[allow(unused_variables)]
    pub fn new(
        writer: W,
        command_buffer: CommandBuffer,
        history_buffer: HistoryBuffer,
    ) -> Result<Self, E> {
        let mut cli = Self {
            editor: Some(Editor::new(command_buffer)),
            #[cfg(feature = "history")]
            history: History::new(history_buffer),
            input_generator: Some(InputGenerator::new()),
            prompt: PROMPT,
            writer,
            #[cfg(not(feature = "history"))]
            _ph: PhantomData,
        };

        cli.writer.flush_str(cli.prompt)?;

        Ok(cli)
    }

    /// Each call to process byte can be done with different
    /// command set and/or command processor.
    /// In process callback you can change some outside state
    /// so next calls will use different processor
    pub fn process_byte<C: Autocomplete + Help, P: CommandProcessor<W, E>>(
        &mut self,
        b: u8,
        processor: &mut P,
    ) -> Result<(), E> {
        if let (Some(mut editor), Some(mut input_generator)) =
            (self.editor.take(), self.input_generator.take())
        {
            let result = input_generator
                .accept(b)
                .map(|input| match input {
                    Input::Control(control) => {
                        self.on_control_input::<C, _>(&mut editor, control, processor)
                    }
                    Input::Char(text) => self.on_text_input(&mut editor, text),
                })
                .unwrap_or(Ok(()));

            self.editor = Some(editor);
            self.input_generator = Some(input_generator);
            result
        } else {
            Ok(())
        }
    }

    pub fn write(
        &mut self,
        f: impl FnOnce(&mut Writer<'_, W, E>) -> Result<(), E>,
    ) -> Result<(), E> {
        self.clear_line(true)?;

        let mut cli_writer = Writer::new(&mut self.writer);

        f(&mut cli_writer)?;

        // we should write back input that was there before writing
        if cli_writer.is_dirty() {
            self.writer.write_str(codes::CRLF)?;
        }
        self.writer.write_str(self.prompt)?;
        if let Some(editor) = self.editor.as_mut() {
            self.writer.flush_str(editor.text())?;
        }

        Ok(())
    }

    fn clear_line(&mut self, clear_prompt: bool) -> Result<(), E> {
        self.writer.write_str("\r")?;
        self.writer.write_bytes(codes::CLEAR_LINE)?;

        if !clear_prompt {
            self.writer.write_str(self.prompt)?;
        }

        self.writer.flush()
    }

    fn on_text_input(&mut self, editor: &mut Editor<CommandBuffer>, text: &str) -> Result<(), E> {
        let is_inside = editor.cursor() < editor.len();
        if let Some(c) = editor.insert(text) {
            if is_inside {
                // text is always one char
                debug_assert_eq!(c.chars().count(), 1);
                self.writer.write_bytes(codes::INSERT_CHAR)?;
            }
            self.writer.flush_str(c)?;
        }
        Ok(())
    }

    fn on_control_input<C: Autocomplete + Help, P: CommandProcessor<W, E>>(
        &mut self,
        editor: &mut Editor<CommandBuffer>,
        control: ControlInput,
        processor: &mut P,
    ) -> Result<(), E> {
        match control {
            ControlInput::Enter => {
                self.writer.write_str(codes::CRLF)?;

                #[cfg(feature = "history")]
                self.history.push(editor.text());
                let text = editor.text_mut();

                let tokens = Tokens::new(text);
                self.process_input::<C, _>(tokens, processor)?;

                editor.clear();

                self.writer.flush_str(self.prompt)?;
            }
            ControlInput::Tab => {
                #[cfg(feature = "autocomplete")]
                self.process_autocomplete::<C>(editor)?;
            }
            ControlInput::Backspace => {
                if editor.move_left() {
                    editor.remove();
                    self.writer.flush_bytes(codes::CURSOR_BACKWARD)?;
                    self.writer.flush_bytes(codes::DELETE_CHAR)?;
                }
            }
            ControlInput::Down =>
            {
                #[cfg(feature = "history")]
                self.navigate_history(editor, NavigateHistory::Newer)?
            }
            ControlInput::Up =>
            {
                #[cfg(feature = "history")]
                self.navigate_history(editor, NavigateHistory::Older)?
            }
            ControlInput::Forward => self.navigate_input(editor, NavigateInput::Forward)?,
            ControlInput::Back => self.navigate_input(editor, NavigateInput::Backward)?,
        }

        Ok(())
    }

    fn navigate_input(
        &mut self,
        editor: &mut Editor<CommandBuffer>,
        dir: NavigateInput,
    ) -> Result<(), E> {
        match dir {
            NavigateInput::Backward if editor.move_left() => {
                self.writer.flush_bytes(codes::CURSOR_BACKWARD)?;
            }
            NavigateInput::Forward if editor.move_right() => {
                self.writer.flush_bytes(codes::CURSOR_FORWARD)?;
            }
            _ => return Ok(()),
        }
        Ok(())
    }

    #[cfg(feature = "history")]
    fn navigate_history(
        &mut self,
        editor: &mut Editor<CommandBuffer>,
        dir: NavigateHistory,
    ) -> Result<(), E> {
        let history_elem = match dir {
            NavigateHistory::Older => self.history.next_older(),
            NavigateHistory::Newer => self.history.next_newer().or(Some("")),
        };
        if let Some(element) = history_elem {
            editor.clear();
            editor.insert(element);
            self.clear_line(false)?;

            self.writer.flush_str(editor.text())?;
        }
        Ok(())
    }

    #[cfg(feature = "autocomplete")]
    fn process_autocomplete<C: Autocomplete>(
        &mut self,
        editor: &mut Editor<CommandBuffer>,
    ) -> Result<(), E> {
        let initial_cursor = editor.cursor();
        editor.autocompletion(|request, autocompletion| {
            C::autocomplete(request.clone(), autocompletion);
            match request {
                Request::CommandName(name) if "help".starts_with(name) => {
                    // SAFETY: "help" starts with name, so name cannot be longer
                    let autocompleted = unsafe { "help".get_unchecked(name.len()..) };
                    autocompletion.merge_autocompletion(autocompleted)
                }
                _ => {}
            }
        });
        if editor.cursor() > initial_cursor {
            let autocompleted = editor.text_range(initial_cursor..);
            self.writer.flush_str(autocompleted)?;
        }
        Ok(())
    }

    fn process_command<P: CommandProcessor<W, E>>(
        &mut self,
        command: RawCommand<'_>,
        handler: &mut P,
    ) -> Result<(), E> {
        let cli_writer = Writer::new(&mut self.writer);
        let mut handle = CliHandle::new(cli_writer);

        let res = handler.process(&mut handle, command);

        if handle.writer.is_dirty() {
            self.writer.write_str(codes::CRLF)?;
        }
        self.writer.flush()?;

        if let Err(e) = res {
            self.process_error(e)?;
        }

        Ok(())
    }

    #[allow(clippy::extra_unused_type_parameters)]
    fn process_input<C: Help, P: CommandProcessor<W, E>>(
        &mut self,
        tokens: Tokens<'_>,
        handler: &mut P,
    ) -> Result<(), E> {
        #[cfg(feature = "help")]
        if let Some(request) = HelpRequest::from_tokens(&tokens) {
            self.process_help::<C>(request)?;
        }

        if let Some(command) = RawCommand::from_tokens(&tokens) {
            self.process_command(command, handler)?;
        };

        Ok(())
    }

    fn process_error(&mut self, _error: ProcessError<'_, E>) -> Result<(), E> {
        //TODO: proper handling
        self.writer
            .flush_str("Error occured during command processing\r\n")
    }

    #[cfg(feature = "help")]
    fn process_help<C: Help>(&mut self, request: HelpRequest<'_>) -> Result<(), E> {
        let mut writer = Writer::new(&mut self.writer);
        let err = C::help(request.clone(), &mut writer);

        if let (Err(HelpError::UnknownCommand), HelpRequest::Command(command)) = (err, request) {
            writer.write_str("error: unrecognized command '")?;
            writer.write_str(command)?;
            writer.write_str("'")?;
        }

        if writer.is_dirty() {
            self.writer.write_str(codes::CRLF)?;
        }
        self.writer.flush()?;

        Ok(())
    }
}