termscp 1.0.0

termscp is a feature rich terminal file transfer and explorer with support for SCP/SFTP/FTP/Kube/S3/WebDAV
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use std::path::{Path, PathBuf};

use tui_realm_stdlib::components::Input;
use tuirealm::command::{Cmd, CmdResult, Direction, Position};
use tuirealm::component::{AppComponent, Component};
use tuirealm::event::{Event, Key, KeyEvent, NoUserEvent};
use tuirealm::props::{
    AttrValue, Attribute, BorderType, Borders, Color, HorizontalAlignment, InputType, PropValue,
    Style, Title,
};
use tuirealm::state::{State, StateValue};

use crate::ui::activities::filetransfer::{Msg, TransferMsg, UiMsg};

pub const ATTR_FILES: &str = "files";

#[derive(Default)]
struct OwnStates {
    /// Path and name of the files
    files: Vec<(String, String)>,
    search: Option<String>,
    last_suggestion: Option<String>,
}

impl OwnStates {
    pub fn set_files(&mut self, files: Vec<String>) {
        self.files = files
            .into_iter()
            .map(|f| {
                (
                    f.clone(),
                    PathBuf::from(&f)
                        .file_name()
                        .map(|x| x.to_string_lossy().to_string())
                        .unwrap_or(f),
                )
            })
            .collect();
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
enum Suggestion {
    /// No suggestion
    None,
    /// Suggest a string
    Suggest(String),
    /// Rescan at `path` is required to satisfy the user input
    Rescan(PathBuf),
}

impl From<CmdResult> for Suggestion {
    fn from(value: CmdResult) -> Self {
        match value {
            CmdResult::Batch(v) if v.len() == 1 => {
                if let CmdResult::Submit(State::Single(StateValue::String(s))) = v.first().unwrap()
                {
                    Suggestion::Suggest(s.clone())
                } else {
                    Suggestion::None
                }
            }
            CmdResult::Batch(v) if v.len() == 2 => {
                if let CmdResult::Submit(State::Single(StateValue::String(s))) = v.get(1).unwrap() {
                    Suggestion::Rescan(PathBuf::from(s))
                } else {
                    Suggestion::None
                }
            }
            _ => Suggestion::None,
        }
    }
}

impl From<Suggestion> for CmdResult {
    fn from(value: Suggestion) -> Self {
        match value {
            Suggestion::None => CmdResult::NoChange,
            Suggestion::Suggest(s) => CmdResult::Batch(vec![CmdResult::Submit(State::Single(
                StateValue::String(s),
            ))]),
            Suggestion::Rescan(p) => CmdResult::Batch(vec![
                CmdResult::NoChange,
                CmdResult::Submit(State::Single(StateValue::String(
                    p.to_string_lossy().to_string(),
                ))),
            ]),
        }
    }
}

impl OwnStates {
    /// Return the current suggestion if any, otherwise return search
    pub fn computed_search(&self) -> String {
        match (&self.search, &self.last_suggestion) {
            (_, Some(s)) => s.clone(),
            (Some(s), _) => s.clone(),
            _ => String::new(),
        }
    }

    /// Suggest files based on the input
    pub fn suggest(&mut self, input: &str) -> Suggestion {
        debug!(
            "Suggesting for: {input}; files {files:?}",
            files = self.files
        );

        let is_path = PathBuf::from(input).is_absolute();

        // case 1. search if any file starts with the input; get first if suggestion is `None`, otherwise get first after suggestion
        let suggestions: Vec<&String> = self
            .files
            .iter()
            .filter(|(path, file_name)| {
                if is_path {
                    path.contains(input)
                } else {
                    file_name.contains(input)
                }
            })
            .map(|(path, _)| path)
            .collect();

        debug!("Suggestions for {input}: {:?}", suggestions);

        // case 1. if suggestions not empty; then suggest next
        if !suggestions.is_empty() {
            let suggestion;
            if let Some(last_suggestion) = self.last_suggestion.take() {
                suggestion = (*suggestions
                    .iter()
                    .skip_while(|f| **f != &last_suggestion)
                    .nth(1)
                    .unwrap_or_else(|| suggestions.first().unwrap()))
                .clone();
            } else {
                suggestion = suggestions.first().map(ToString::to_string).unwrap();
            }

            debug!("Suggested: {suggestion}");
            self.last_suggestion = Some(suggestion.clone());

            return Suggestion::Suggest(suggestion);
        }

        self.last_suggestion = None;

        // case 2. otherwise convert suggest to a path and get the parent
        // to rescan the files
        let input_as_path = if input.starts_with('/') {
            input.to_string()
        } else {
            format!("./{}", input)
        };

        let p = PathBuf::from(input_as_path);
        let parent = p
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("/"));

        // if path is `.`, then return None
        if parent == Path::new(".") {
            return Suggestion::None;
        }

        debug!("Rescan required at: {}", parent.display());

        Suggestion::Rescan(parent)
    }
}

pub struct GotoPopup {
    input: Input,
    states: OwnStates,
}

impl GotoPopup {
    pub fn new(color: Color, files: Vec<String>) -> Self {
        let mut states = OwnStates::default();
        states.set_files(files);

        Self {
            input: Input::default()
                .borders(
                    Borders::default()
                        .color(color)
                        .modifiers(BorderType::Rounded),
                )
                .foreground(color)
                .input_type(InputType::Text)
                .placeholder(tuirealm::props::SpanStatic::styled(
                    "/foo/bar/buzz",
                    Style::default().fg(Color::Rgb(128, 128, 128)),
                ))
                .title(
                    Title::from("Go to… (Press <TAB> for autocompletion)")
                        .alignment(HorizontalAlignment::Center),
                ),
            states,
        }
    }
}

impl Component for GotoPopup {
    fn view(
        &mut self,
        frame: &mut tuirealm::ratatui::Frame,
        area: tuirealm::ratatui::prelude::Rect,
    ) {
        self.input.view(frame, area);
    }

    fn attr(&mut self, attr: Attribute, value: AttrValue) {
        match attr {
            Attribute::Custom(ATTR_FILES) => {
                let files = value
                    .unwrap_payload()
                    .unwrap_vec()
                    .into_iter()
                    .map(PropValue::unwrap_str)
                    .collect();

                self.states.set_files(files);
                // call perform Change
                self.perform(Cmd::Change);
            }
            _ => self.input.attr(attr, value),
        }
    }

    fn query<'a>(&'a self, attr: Attribute) -> Option<tuirealm::props::QueryResult<'a>> {
        self.input.query(attr)
    }

    fn state(&self) -> State {
        State::Single(StateValue::String(self.states.computed_search()))
    }

    fn perform(&mut self, cmd: Cmd) -> CmdResult {
        match cmd {
            Cmd::Change => {
                let input = self
                    .states
                    .search
                    .as_ref()
                    .cloned()
                    .unwrap_or_else(|| self.input.state().unwrap_single().unwrap_string());
                let suggest = self.states.suggest(&input);
                if let Suggestion::Suggest(suggestion) = suggest.clone() {
                    self.input
                        .attr(Attribute::Value, AttrValue::String(suggestion.clone()));
                }

                suggest.into()
            }
            cmd => {
                let res = self.input.perform(cmd);
                if let CmdResult::Changed(State::Single(StateValue::String(new_text))) = &res {
                    self.states.search = Some(new_text.clone());
                }
                res
            }
        }
    }
}

impl AppComponent<Msg, NoUserEvent> for GotoPopup {
    fn on(&mut self, ev: &Event<NoUserEvent>) -> Option<Msg> {
        match ev {
            Event::Keyboard(KeyEvent {
                code: Key::Left, ..
            }) => {
                self.perform(Cmd::Move(Direction::Left));
                Some(Msg::None)
            }
            Event::Keyboard(KeyEvent {
                code: Key::Right, ..
            }) => {
                self.perform(Cmd::Move(Direction::Right));
                Some(Msg::None)
            }
            Event::Keyboard(KeyEvent {
                code: Key::Home, ..
            }) => {
                self.perform(Cmd::GoTo(Position::Begin));
                Some(Msg::None)
            }
            Event::Keyboard(KeyEvent { code: Key::End, .. }) => {
                self.perform(Cmd::GoTo(Position::End));
                Some(Msg::None)
            }
            Event::Keyboard(KeyEvent {
                code: Key::Delete, ..
            }) => {
                self.perform(Cmd::Cancel);
                Some(Msg::None)
            }
            Event::Keyboard(KeyEvent {
                code: Key::Backspace,
                ..
            }) => {
                self.perform(Cmd::Delete);
                Some(Msg::None)
            }
            Event::Keyboard(KeyEvent {
                code: Key::Char(ch),
                ..
            }) => {
                self.perform(Cmd::Type(*ch));
                Some(Msg::None)
            }
            Event::Keyboard(KeyEvent { code: Key::Tab, .. }) => {
                if let Suggestion::Rescan(path) = Suggestion::from(self.perform(Cmd::Change)) {
                    Some(Msg::Transfer(TransferMsg::RescanGotoFiles(path)))
                } else {
                    Some(Msg::None)
                }
            }
            Event::Keyboard(KeyEvent {
                code: Key::Enter, ..
            }) => match self.state() {
                State::Single(StateValue::String(i)) => Some(Msg::Transfer(TransferMsg::GoTo(i))),
                _ => Some(Msg::None),
            },
            Event::Keyboard(KeyEvent { code: Key::Esc, .. }) => {
                Some(Msg::Ui(UiMsg::CloseGotoPopup))
            }
            _ => None,
        }
    }
}

#[cfg(test)]
mod test {

    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn test_should_convert_from_and_back_cmd_result() {
        let s = Suggestion::Suggest("foo".to_string());
        let cmd: CmdResult = s.clone().into();
        let s2: Suggestion = cmd.into();
        assert_eq!(s, s2);

        let s = Suggestion::Rescan(PathBuf::from("/foo/bar"));
        let cmd: CmdResult = s.clone().into();
        let s2: Suggestion = cmd.into();
        assert_eq!(s, s2);
    }

    #[test]
    fn test_should_suggest_next() {
        let mut states = OwnStates {
            files: vec![
                ("/home/foo".to_string(), "foo".to_string()),
                ("/home/bar".to_string(), "bar".to_string()),
                ("/home/buzz".to_string(), "buzz".to_string()),
                ("/home/fizz".to_string(), "fizz".to_string()),
            ],
            search: None,
            last_suggestion: None,
        };

        let s = states.suggest("f");
        assert_eq!(Suggestion::Suggest("/home/foo".to_string()), s);
        let s = states.suggest("f");
        assert_eq!(Suggestion::Suggest("/home/fizz".to_string()), s);

        let s = states.suggest("f");
        assert_eq!(Suggestion::Suggest("/home/foo".to_string()), s);
    }

    #[test]
    #[cfg(posix)]
    fn test_should_suggest_absolute_path() {
        let mut states = OwnStates {
            files: vec![
                ("/home/foo".to_string(), "foo".to_string()),
                ("/home/bar".to_string(), "bar".to_string()),
                ("/home/buzz".to_string(), "buzz".to_string()),
                ("/home/fizz".to_string(), "fizz".to_string()),
            ],
            search: None,
            last_suggestion: None,
        };

        let s = states.suggest("/home/f");
        assert_eq!(Suggestion::Suggest("/home/foo".to_string()), s);
    }

    #[test]
    fn test_should_suggest_rescan() {
        let mut states = OwnStates {
            files: vec![
                ("/home/foo".to_string(), "foo".to_string()),
                ("/home/bar".to_string(), "bar".to_string()),
                ("/home/buzz".to_string(), "buzz".to_string()),
                ("/home/fizz".to_string(), "fizz".to_string()),
            ],
            search: None,
            last_suggestion: None,
        };

        let s = states.suggest("/home/user");
        assert_eq!(Suggestion::Rescan(PathBuf::from("/home")), s);
    }

    #[test]
    fn test_should_suggest_none() {
        let mut states = OwnStates {
            files: vec![
                ("/home/foo".to_string(), "foo".to_string()),
                ("/home/bar".to_string(), "bar".to_string()),
                ("/home/buzz".to_string(), "buzz".to_string()),
                ("/home/fizz".to_string(), "fizz".to_string()),
            ],
            search: None,
            last_suggestion: None,
        };

        let s = states.suggest("");
        assert_eq!(Suggestion::Suggest("/home/foo".to_string()), s);
    }

    #[test]
    fn test_should_suggest_none_if_dot() {
        let mut states = OwnStates {
            files: vec![
                ("/home/foo".to_string(), "foo".to_string()),
                ("/home/bar".to_string(), "bar".to_string()),
                ("/home/buzz".to_string(), "buzz".to_string()),
                ("/home/fizz".to_string(), "fizz".to_string()),
            ],
            search: None,
            last_suggestion: None,
        };

        let s = states.suggest("./th");
        assert_eq!(Suggestion::None, s);
    }
}