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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use std::cmp::min;
use std::path::PathBuf;
use std::sync::Arc;
use image::Rgb;
use log::info;
use tuikit::attr::*;
use tuikit::event::Event;
use tuikit::prelude::*;
use tuikit::term::Term;
use crate::config::Colors;
use crate::constant_strings_paths::{
FILTER_PRESENTATION, HELP_FIRST_SENTENCE, HELP_SECOND_SENTENCE,
};
use crate::content_window::ContentWindow;
use crate::fileinfo::fileinfo_attr;
use crate::fm_error::{FmError, FmResult};
use crate::mode::{InputSimple, MarkAction, Mode, Navigate, NeedConfirmation};
use crate::preview::{Preview, TextKind, Window};
use crate::selectable_content::SelectableContent;
use crate::status::Status;
use crate::tab::Tab;
use crate::trash::TrashInfo;
pub const MIN_WIDTH_FOR_DUAL_PANE: usize = 100;
pub struct EventReader {
term: Arc<Term>,
}
impl EventReader {
pub fn new(term: Arc<Term>) -> Self {
Self { term }
}
pub fn poll_event(&self) -> FmResult<Event> {
Ok(self.term.poll_event()?)
}
}
macro_rules! impl_preview {
($text:ident, $tab:ident, $length:ident, $canvas:ident, $line_number_width:ident) => {
for (i, line) in (*$text).window($tab.window.top, $tab.window.bottom, $length) {
let row = Self::calc_line_row(i, $tab);
$canvas.print(row, $line_number_width + 3, line)?;
}
};
}
struct WinTab<'a> {
status: &'a Status,
tab: &'a Tab,
disk_space: &'a str,
colors: &'a Colors,
}
impl<'a> Draw for WinTab<'a> {
fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
match self.tab.mode {
Mode::Navigate(Navigate::Jump) => self.destination(canvas, &self.status.flagged),
Mode::Navigate(Navigate::History) => self.destination(canvas, &self.tab.history),
Mode::Navigate(Navigate::Shortcut) => self.destination(canvas, &self.tab.shortcut),
Mode::Navigate(Navigate::Trash) => self.trash(canvas, &self.status.trash),
Mode::InputCompleted(_) => self.completion(self.tab, canvas),
Mode::NeedConfirmation(confirmed_mode) => {
self.confirmation(self.status, self.tab, confirmed_mode, canvas)
}
Mode::Preview => self.preview(self.tab, canvas),
Mode::InputSimple(InputSimple::Marks(_)) => self.marks(self.status, self.tab, canvas),
_ => self.files(self.status, self.tab, canvas),
}?;
self.cursor(self.tab, canvas)?;
self.first_line(self.tab, self.disk_space, canvas)?;
Ok(())
}
}
impl<'a> Widget for WinTab<'a> {}
impl<'a> WinTab<'a> {
const EDIT_BOX_OFFSET: usize = 9;
const SORT_CURSOR_OFFSET: usize = 37;
const ATTR_LINE_NR: Attr = color_to_attr(Color::CYAN);
const ATTR_YELLOW: Attr = color_to_attr(Color::YELLOW);
const ATTR_YELLOW_BOLD: Attr = Attr {
fg: Color::YELLOW,
bg: Color::Default,
effect: Effect::BOLD,
};
const FIRST_LINE_COLORS: [Attr; 6] = [
color_to_attr(Color::Rgb(231, 162, 156)),
color_to_attr(Color::Rgb(144, 172, 186)),
color_to_attr(Color::Rgb(214, 125, 83)),
color_to_attr(Color::Rgb(91, 152, 119)),
color_to_attr(Color::Rgb(152, 87, 137)),
color_to_attr(Color::Rgb(230, 189, 87)),
];
fn first_line(&self, tab: &Tab, disk_space: &str, canvas: &mut dyn Canvas) -> FmResult<()> {
self.draw_colored_strings(0, 0, self.create_first_row(tab, disk_space)?, canvas)
}
fn second_line(&self, status: &Status, tab: &Tab, canvas: &mut dyn Canvas) -> FmResult<()> {
match tab.mode {
Mode::Normal => {
if !status.display_full {
if let Some(file) = tab.path_content.selected() {
let owner_size = file.owner.len();
let group_size = file.group.len();
let mut attr = fileinfo_attr(status, file, self.colors);
attr.effect ^= Effect::REVERSE;
canvas.print_with_attr(
1,
0,
&file.format(owner_size, group_size)?,
attr,
)?;
}
} else {
canvas.print_with_attr(
1,
0,
&format!("{}", &status.selected_non_mut().path_content.filter),
Self::ATTR_YELLOW_BOLD,
)?;
}
}
Mode::InputSimple(InputSimple::Filter) => {
canvas.print_with_attr(1, 0, FILTER_PRESENTATION, Self::ATTR_YELLOW_BOLD)?;
}
_ => (),
}
Ok(())
}
fn create_first_row(&self, tab: &Tab, disk_space: &str) -> FmResult<Vec<String>> {
let first_row = match tab.mode {
Mode::Normal => {
vec![
format!("{} ", tab.path_content.path.display()),
format!("{} files ", tab.path_content.true_len()),
format!("{} ", tab.path_content.used_space()),
format!("Avail: {} ", disk_space),
format!("{} ", &tab.path_content.git_string()?),
]
}
Mode::NeedConfirmation(confirmed_action) => {
vec![format!("{} (y/n)", confirmed_action)]
}
Mode::Preview => match &tab.preview {
Preview::Text(text_content) => {
if matches!(text_content.kind, TextKind::HELP) {
vec![
HELP_FIRST_SENTENCE.to_owned(),
HELP_SECOND_SENTENCE.to_owned(),
]
} else {
Self::default_preview_first_line(tab)
}
}
_ => Self::default_preview_first_line(tab),
},
Mode::InputSimple(InputSimple::Marks(MarkAction::Jump)) => {
vec!["Jump to...".to_owned()]
}
Mode::InputSimple(InputSimple::Marks(MarkAction::New)) => {
vec!["Save mark...".to_owned()]
}
_ => {
vec![
format!("{}", tab.mode.clone()),
format!("{}", tab.input.string()),
]
}
};
Ok(first_row)
}
fn default_preview_first_line(tab: &Tab) -> Vec<String> {
match tab.path_content.selected() {
Some(fileinfo) => {
let mut strings = vec![
format!("{}", tab.mode.clone()),
format!("{}", fileinfo.path.to_string_lossy()),
];
if !tab.preview.is_empty() {
strings.push(format!(" {} / {}", tab.window.bottom, tab.preview.len()));
};
strings
}
None => vec!["".to_owned()],
}
}
fn draw_colored_strings(
&self,
row: usize,
offset: usize,
strings: Vec<String>,
canvas: &mut dyn Canvas,
) -> FmResult<()> {
let mut col = 0;
for (text, attr) in std::iter::zip(strings.iter(), Self::FIRST_LINE_COLORS.iter().cycle()) {
canvas.print_with_attr(row, offset + col, text, *attr)?;
col += text.len()
}
Ok(())
}
fn files(&self, status: &Status, tab: &Tab, canvas: &mut dyn Canvas) -> FmResult<()> {
let len = tab.path_content.content.len();
for (i, (file, string)) in std::iter::zip(
tab.path_content.content.iter(),
tab.path_content.strings(status.display_full).iter(),
)
.enumerate()
.take(min(len, tab.window.bottom + 1))
.skip(tab.window.top)
{
let row = i + ContentWindow::WINDOW_MARGIN_TOP - tab.window.top;
let mut attr = fileinfo_attr(status, file, self.colors);
if status.flagged.contains(&file.path) {
attr.effect |= Effect::BOLD | Effect::UNDERLINE;
}
canvas.print_with_attr(row, 0, string, attr)?;
}
self.second_line(status, tab, canvas)?;
Ok(())
}
fn cursor(&self, tab: &Tab, canvas: &mut dyn Canvas) -> FmResult<()> {
match tab.mode {
Mode::Normal
| Mode::InputSimple(InputSimple::Marks(_))
| Mode::Navigate(_)
| Mode::Preview => {
canvas.show_cursor(false)?;
}
Mode::InputSimple(InputSimple::Sort) => {
canvas.set_cursor(0, Self::SORT_CURSOR_OFFSET)?;
}
Mode::InputSimple(_) | Mode::InputCompleted(_) => {
canvas.show_cursor(true)?;
canvas.set_cursor(0, tab.input.cursor_index + Self::EDIT_BOX_OFFSET)?;
}
Mode::NeedConfirmation(confirmed_action) => {
canvas.set_cursor(0, confirmed_action.cursor_offset())?;
}
}
Ok(())
}
fn destination(
&self,
canvas: &mut dyn Canvas,
selectable: &impl SelectableContent<PathBuf>,
) -> FmResult<()> {
canvas.print(0, 0, "Go to...")?;
for (row, path) in selectable.content().iter().enumerate() {
let mut attr = Attr::default();
if row == selectable.index() {
attr.effect |= Effect::REVERSE;
}
let _ = canvas.print_with_attr(
row + ContentWindow::WINDOW_MARGIN_TOP,
4,
path.to_str()
.ok_or_else(|| FmError::custom("display", "Unreadable filename"))?,
attr,
);
}
Ok(())
}
fn trash(
&self,
canvas: &mut dyn Canvas,
selectable: &impl SelectableContent<TrashInfo>,
) -> FmResult<()> {
canvas.print(1, 0, "Restore the selected file")?;
for (row, trashinfo) in selectable.content().iter().enumerate() {
let mut attr = Attr::default();
if row == selectable.index() {
attr.effect |= Effect::REVERSE;
}
let _ = canvas.print_with_attr(
row + ContentWindow::WINDOW_MARGIN_TOP,
4,
&format!("{}", trashinfo),
attr,
);
}
Ok(())
}
fn completion(&self, tab: &Tab, canvas: &mut dyn Canvas) -> FmResult<()> {
canvas.set_cursor(0, tab.input.cursor_index + Self::EDIT_BOX_OFFSET)?;
for (row, candidate) in tab.completion.proposals.iter().enumerate() {
let mut attr = Attr::default();
if row == tab.completion.index {
attr.effect |= Effect::REVERSE;
}
canvas.print_with_attr(row + ContentWindow::WINDOW_MARGIN_TOP, 4, candidate, attr)?;
}
Ok(())
}
fn confirmation(
&self,
status: &Status,
tab: &Tab,
confirmed_mode: NeedConfirmation,
canvas: &mut dyn Canvas,
) -> FmResult<()> {
info!("confirmed action: {:?}", confirmed_mode);
match confirmed_mode {
NeedConfirmation::EmptyTrash => {
for (row, trashinfo) in status.trash.content.iter().enumerate() {
canvas.print_with_attr(
row + ContentWindow::WINDOW_MARGIN_TOP + 2,
4,
&format!("{}", trashinfo),
Attr::default(),
)?;
}
}
NeedConfirmation::Copy | NeedConfirmation::Delete | NeedConfirmation::Move => {
for (row, path) in status.flagged.content.iter().enumerate() {
canvas.print_with_attr(
row + ContentWindow::WINDOW_MARGIN_TOP + 2,
4,
path.to_str()
.ok_or_else(|| FmError::custom("display", "Unreadable filename"))?,
Attr::default(),
)?;
}
}
}
let confirmation_string = match confirmed_mode {
NeedConfirmation::Copy => {
format!(
"Files will be copied to {}",
tab.path_content.path_to_str()?
)
}
NeedConfirmation::Delete => "Files will deleted permanently".to_owned(),
NeedConfirmation::Move => {
format!("Files will be moved to {}", tab.path_content.path_to_str()?)
}
NeedConfirmation::EmptyTrash => "Trash will be emptied".to_owned(),
};
canvas.print_with_attr(2, 3, &confirmation_string, Self::ATTR_YELLOW_BOLD)?;
Ok(())
}
fn print_line_number(
row_position_in_canvas: usize,
line_number_to_print: usize,
canvas: &mut dyn Canvas,
) -> FmResult<usize> {
Ok(canvas.print_with_attr(
row_position_in_canvas,
0,
&line_number_to_print.to_string(),
Self::ATTR_LINE_NR,
)?)
}
fn preview(&self, tab: &Tab, canvas: &mut dyn Canvas) -> FmResult<()> {
let length = tab.preview.len();
let line_number_width = length.to_string().len();
match &tab.preview {
Preview::Syntaxed(syntaxed) => {
for (i, vec_line) in (*syntaxed).window(tab.window.top, tab.window.bottom, length) {
let row_position = Self::calc_line_row(i, tab);
Self::print_line_number(row_position, i + 1, canvas)?;
for token in vec_line.iter() {
token.print(canvas, row_position, line_number_width)?;
}
}
}
Preview::Binary(bin) => {
let line_number_width_hex = format!("{:x}", bin.len() * 16).len();
for (i, line) in (*bin).window(tab.window.top, tab.window.bottom, length) {
let row = Self::calc_line_row(i, tab);
canvas.print_with_attr(
row,
0,
&format_line_nr_hex(i + 1 + tab.window.top, line_number_width_hex),
Self::ATTR_LINE_NR,
)?;
line.print(canvas, row, line_number_width_hex + 1);
}
}
Preview::Thumbnail(image) => {
let (width, height) = canvas.size()?;
if let Ok(scaled_image) = (*image).resized_rgb8(width as u32 / 2, height as u32 - 3)
{
let (width, _) = scaled_image.dimensions();
for (i, pixel) in scaled_image.pixels().enumerate() {
let (r, g, b) = pixel_values(pixel);
let (row, col) = pixel_position(i, width);
print_pixel(canvas, row, col, r, g, b)?;
}
} else {
canvas.print(
3,
3,
&format!("Not a displayable image: {:?}", image.img_path),
)?;
}
}
Preview::Archive(text) => impl_preview!(text, tab, length, canvas, line_number_width),
Preview::Directory(text) => impl_preview!(text, tab, length, canvas, line_number_width),
Preview::Exif(text) => impl_preview!(text, tab, length, canvas, line_number_width),
Preview::Media(text) => impl_preview!(text, tab, length, canvas, line_number_width),
Preview::Pdf(text) => impl_preview!(text, tab, length, canvas, line_number_width),
Preview::Text(text) => impl_preview!(text, tab, length, canvas, line_number_width),
Preview::Empty => (),
}
Ok(())
}
fn marks(&self, status: &Status, tab: &Tab, canvas: &mut dyn Canvas) -> FmResult<()> {
canvas.print_with_attr(2, 1, "mark path", Self::ATTR_YELLOW)?;
for (i, line) in status.marks.as_strings().iter().enumerate() {
let row = Self::calc_line_row(i, tab) + 2;
canvas.print(row, 3, line)?;
}
Ok(())
}
fn calc_line_row(i: usize, status: &Tab) -> usize {
i + ContentWindow::WINDOW_MARGIN_TOP - status.window.top
}
}
pub struct Display {
term: Arc<Term>,
colors: Colors,
}
impl Display {
const SELECTED_BORDER: Attr = color_to_attr(Color::LIGHT_BLUE);
const INERT_BORDER: Attr = color_to_attr(Color::Default);
pub fn new(term: Arc<Term>, colors: Colors) -> Self {
Self { term, colors }
}
pub fn show_cursor(&self) -> FmResult<()> {
Ok(self.term.show_cursor(true)?)
}
pub fn display_all(&mut self, status: &Status) -> FmResult<()> {
self.term.clear()?;
let (width, _) = self.term.term_size()?;
let disk_spaces = status.disk_spaces_per_tab();
if status.dual_pane && width > MIN_WIDTH_FOR_DUAL_PANE {
self.draw_dual_pane(status, &disk_spaces.0, &disk_spaces.1)?
} else {
self.draw_single_pane(status, &disk_spaces.0)?
}
Ok(self.term.present()?)
}
fn draw_dual_pane(
&mut self,
status: &Status,
disk_space_tab_0: &str,
disk_space_tab_1: &str,
) -> FmResult<()> {
let win_left = WinTab {
status,
tab: &status.tabs[0],
disk_space: disk_space_tab_0,
colors: &self.colors,
};
let win_right = WinTab {
status,
tab: &status.tabs[1],
disk_space: disk_space_tab_1,
colors: &self.colors,
};
let (left_border, right_border) = if status.index == 0 {
(Self::SELECTED_BORDER, Self::INERT_BORDER)
} else {
(Self::INERT_BORDER, Self::SELECTED_BORDER)
};
let hsplit = HSplit::default()
.split(Win::new(&win_left).border(true).border_attr(left_border))
.split(Win::new(&win_right).border(true).border_attr(right_border));
Ok(self.term.draw(&hsplit)?)
}
fn draw_single_pane(&mut self, status: &Status, disk_space_tab_0: &str) -> FmResult<()> {
let win_left = WinTab {
status,
tab: &status.tabs[0],
disk_space: disk_space_tab_0,
colors: &self.colors,
};
let win = Win::new(&win_left)
.border(true)
.border_attr(Self::SELECTED_BORDER);
Ok(self.term.draw(&win)?)
}
pub fn height(&self) -> FmResult<usize> {
let (_, height) = self.term.term_size()?;
Ok(height)
}
}
fn format_line_nr_hex(line_nr: usize, width: usize) -> String {
format!("{:0width$x}", line_nr)
}
const fn color_to_attr(color: Color) -> Attr {
Attr {
fg: color,
bg: Color::Default,
effect: Effect::empty(),
}
}
const fn pixel_values(pixel: &Rgb<u8>) -> (u8, u8, u8) {
let [r, g, b] = pixel.0;
(r, g, b)
}
const fn pixel_position(i: usize, width: u32) -> (usize, usize) {
let col = 2 * (i % width as usize);
let row = i / width as usize + 3;
(row, col)
}
fn print_pixel(
canvas: &mut dyn Canvas,
row: usize,
col: usize,
r: u8,
g: u8,
b: u8,
) -> FmResult<()> {
canvas.print_with_attr(
row,
col,
"██",
Attr {
fg: Color::Rgb(r, g, b),
bg: Color::Rgb(r, g, b),
..Default::default()
},
)?;
Ok(())
}