todotxt-tui 0.2.0

Todo.txt TUI is a highly customizable terminal-based application for managing your todo tasks. It follows the todo.txt format and offers a wide range of configuration options to suit your needs.
Documentation
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
mod container;
mod render_trait;
pub mod widget;

use crate::{
    config::Config, layout::widget::State, todo::ToDo, ui::HandleEvent, Result, ToDoError,
};
use container::Container;
use crossterm::event::KeyEvent;
use std::{fmt::Debug, sync::Arc, sync::Mutex};
use widget::{widget_type::WidgetType, Widget};

pub use render_trait::Render;

use std::str::FromStr;
use tui::{
    backend::Backend,
    layout::{Constraint, Direction, Rect},
    Frame,
};

// Define separators
const ITEM_SEPARATOR: char = ',';
const ARG_SEPARATOR: char = ':';
const START_CONTAINER: char = '[';
const END_CONTAINER: char = ']';

const LEFT: Site = Site {
    direction: Direction::Horizontal,
    function: Container::previous_item,
};
const RIGHT: Site = Site {
    direction: Direction::Horizontal,
    function: Container::next_item,
};
const UP: Site = Site {
    direction: Direction::Vertical,
    function: Container::previous_item,
};
const DOWN: Site = Site {
    direction: Direction::Vertical,
    function: Container::next_item,
};

struct Site {
    direction: Direction,
    function: fn(&mut Container) -> bool,
}

struct Holder {
    container: usize,    // container
    widgets: Vec<usize>, // widget
}
impl Holder {
    fn new(l: &Layout) -> Holder {
        Holder {
            container: l.act,
            widgets: l.containers.iter().map(|c| c.get_index()).collect(),
        }
    }
    fn unfocus(&self, l: &mut Layout) {
        match l.containers[self.container].get_widget_mut(self.widgets[self.container]) {
            Some(widget) if widget.get_base().focus => widget.unfocus(),
            _ => {}
        }
    }
    fn set_old_back(&self, l: &mut Layout) {
        l.act = self.container;
        l.containers
            .iter_mut()
            .zip(self.widgets.iter())
            .for_each(|(c, i)| {
                c.set_index(*i);
            });
    }
}

/// Represents the layout of the user interface.
///
/// The `Layout` struct defines the layout of the user interface for the todo-tui application. It
/// consists of a tree of containers and widgets, which are used to organize and display the various
/// components of the application.
#[derive(Debug)]
pub struct Layout {
    containers: Vec<Container>,
    act: usize,
}

impl Layout {
    /// Parse and convert a string value to a `Constraint`.
    ///
    /// # Parameters
    ///
    /// - `value`: A string slice representing the layout constraint.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the converted `Constraint` or an error if parsing fails.
    fn value_from_string(value: Option<&str>) -> Result<Constraint> {
        Ok(match value {
            Some(value) => match value.find('%') {
                Some(i) if i + 1 < value.len() => {
                    return Err(ToDoError::ParseUnknownValue(value.to_string()))
                }
                Some(i) => Constraint::Percentage(value[..i].parse()?),
                None => Constraint::Length(value.parse()?),
            },
            None => Constraint::Percentage(50),
        })
    }

    fn process_item(
        item: &str,
        container: &mut Container,
        data: Arc<Mutex<ToDo>>,
        config: &Config,
    ) -> Result<Option<Constraint>> {
        log::trace!("Process item: {item}");
        let s = item.to_lowercase();
        let x: Vec<&str> = s.splitn(2, ARG_SEPARATOR).map(|s| s.trim()).collect();
        let x = (x[0], if x.len() > 1 { Some(x[1]) } else { None });
        match x.0 {
            "direction" => {
                match x.1 {
                    None | Some("vertical") => container.set_direction(Direction::Vertical),
                    Some("horizontal") => container.set_direction(Direction::Horizontal),
                    Some(direction) => {
                        return Err(ToDoError::ParseInvalidDirection(direction.to_owned()))
                    }
                }
                Ok(None)
            }
            "size" => Ok(Some(Self::value_from_string(x.1)?)),
            _ => {
                container.add_widget(Widget::new(
                    WidgetType::from_str(x.0)?,
                    data.clone(),
                    config,
                )?);
                Ok(Some(Self::value_from_string(x.1)?))
            }
        }
    }

    /// Create a new `Layout` from a template string.
    ///
    /// This function parses a template string and creates a new `Layout` instance based on the
    /// specified template. The template string defines the layout of the user interface, including
    /// the arrangement of containers and widgets.
    ///
    /// # Parameters
    ///
    /// - `template`: A string containing the layout template.
    /// - `data`: An `Arc<Mutex<ToDo>>` representing the shared to-do data.
    ///
    /// # Returns
    ///
    /// A `Result<Self>` result containing the created `Layout` if successful, or an error if
    /// parsing fails.
    pub fn from_str(template: &str, data: Arc<Mutex<ToDo>>, config: &Config) -> Result<Self> {
        // Find first '[' and move start of template to it (start of first container)
        let index = match template.find('[') {
            Some(i) => i,
            None => return Err(ToDoError::ParseNotStart),
        };
        let template = &template[index + 1..];
        log::debug!("Layout from str: {}", template);

        let mut string = String::new();

        let mut constraints_stack: Vec<Vec<Constraint>> = Vec::new();
        constraints_stack.push(Vec::new());
        let mut containers: Vec<Container> = Vec::new();
        let mut layout = Layout {
            act: Container::add_container(&mut containers, Container::default()),
            containers,
        };

        for ch in template.chars() {
            match ch {
                START_CONTAINER => {
                    if !string.is_empty() {
                        return Err(ToDoError::ParseUnknowBeforeContainer(string));
                    }
                    if layout.act().item_count() >= constraints_stack.last().unwrap().len() {
                        constraints_stack
                            .last_mut()
                            .unwrap()
                            .push(Constraint::Percentage(50));
                    }
                    let mut cont = Container::default();
                    cont.parent = Some(layout.act);
                    cont.set_direction(match layout.act().get_direction() {
                        Direction::Horizontal => Direction::Vertical,
                        Direction::Vertical => Direction::Horizontal,
                    });
                    layout.act = Container::add_container(&mut layout.containers, cont);
                    constraints_stack.push(Vec::new());
                }
                END_CONTAINER => {
                    log::trace!(
                        "Act: {}, Constraints: {:?}",
                        layout.act,
                        constraints_stack.last()
                    );
                    layout
                        .act_mut()
                        .set_constraints(constraints_stack.pop().unwrap());
                    layout.act = match layout.act().parent {
                        Some(parent) => parent,
                        // We are at root. Return created layout.
                        None => {
                            Container::actualize_layout(&mut layout);
                            layout.act_mut().actual_mut().unwrap().focus();
                            return Ok(layout);
                        }
                    };
                    string.clear();
                }
                ITEM_SEPARATOR => {
                    // Skip leading ITEM_SEPARATOR
                    if !string.is_empty() {
                        if let Some(constrain) =
                            Self::process_item(&string, layout.act_mut(), data.clone(), config)?
                        {
                            constraints_stack.last_mut().unwrap().push(constrain);
                        }
                        string.clear();
                    }
                }
                ' ' => {}
                '\n' => {}
                _ => string.push(ch),
            };
        }
        Err(ToDoError::ParseNotEnd)
    }

    fn act(&self) -> &Container {
        &self.containers[self.act]
    }

    fn act_mut(&mut self) -> &mut Container {
        &mut self.containers[self.act]
    }

    fn walk_in_container(&mut self, f: &impl Fn(&mut Container) -> bool) -> bool {
        if f(self.act_mut()) {
            Container::actualize_layout(self);
            match self.act_mut().actual_mut() {
                Some(widget) => widget.focus() || self.walk_in_container(f),
                None => true,
            }
        } else {
            false
        }
    }

    /// Change the focus within the layout.
    ///
    /// # Parameters
    ///
    /// - `next`: An `Option<RcCon>` representing the new container to focus.
    fn change_focus(&mut self, direction: &Direction, f: &impl Fn(&mut Container) -> bool) -> bool {
        log::trace!(
            "Layout::change_focus: direction {:?}, act {}",
            &direction,
            self.act
        );
        let old = Holder::new(self);
        while *self.act().get_direction() != *direction {
            match self.act().parent {
                Some(index) => self.act = index,
                None => return false,
            }
        }
        if f(self.act_mut()) {
            Container::actualize_layout(self);
            if match self.act_mut().actual_mut() {
                Some(widget) => widget.focus() || self.walk_in_container(f),
                None => true,
            } {
                old.unfocus(self);
                true
            } else {
                log::trace!(
                    "Revert to cont: {}, widget: {}",
                    old.container,
                    old.widgets[old.container]
                );
                old.set_old_back(self);
                false
            }
        } else {
            match self.act().parent {
                // check if there is upper container that can handle change
                Some(index) => {
                    self.act = index;
                    if self.change_focus(direction, f) {
                        old.unfocus(self);
                        true
                    } else {
                        old.set_old_back(self);
                        false
                    }
                }
                None => {
                    old.set_old_back(self);
                    false
                }
            }
        }
    }

    /// This method moves the focus to the container or widget to the `Site`
    /// of the currently focused element within the layout.
    fn move_focus(&mut self, site: &Site) -> bool {
        let ret = self.change_focus(&site.direction, &site.function);
        Container::actualize_layout(self);
        log::debug!(
            "Moved: {ret}, act widget: {}, container: {}, position: {}",
            self.get_active_widget(),
            self.act,
            self.act().get_index(),
        );
        ret
    }

    /// Move the focus to the left.
    pub fn left(&mut self) -> bool {
        self.move_focus(&LEFT)
    }

    /// Move the focus to the right.
    pub fn right(&mut self) -> bool {
        self.move_focus(&RIGHT)
    }

    /// Move the focus upwards.
    pub fn up(&mut self) -> bool {
        self.move_focus(&UP)
    }

    /// Move the focus downwards.
    pub fn down(&mut self) -> bool {
        self.move_focus(&DOWN)
    }

    /// Handle a key event.
    ///
    /// This method is used to handle key events within the layout. It passes the key event to the
    /// currently focused widget or container for processing.
    ///
    /// # Parameters
    ///
    /// - `event`: A reference to the `KeyEvent` to be handled.
    pub fn handle_key(&mut self, event: &KeyEvent) -> bool {
        match self.act_mut().actual_mut() {
            Some(widget) => widget.handle_key(&event.code),
            None => panic!("Actual is not widget"),
        }
    }

    pub fn get_active_widget(&self) -> WidgetType {
        match self.act().get_active_type() {
            Some(widget_type) => widget_type,
            None => panic!("Actual is not widget"),
        }
    }

    pub fn click(&mut self, column: u16, row: u16) {
        log::debug!("Click on column {column}, row {row}");
        let cont_act_index = self.act().get_index();
        let indexes = match self
            .containers
            .iter_mut()
            .enumerate()
            .flat_map(|(layout_index, container)| {
                container
                    .get_widgets_mut()
                    .into_iter()
                    .enumerate()
                    .map(move |(widget_index, widget)| (layout_index, widget_index, widget))
            })
            .find(|(_, _, w)| {
                let chunk = &w.get_base().chunk;
                let x = chunk.x < column && column < chunk.x + chunk.width;
                let y = chunk.y < row && row < chunk.y + chunk.height;
                x && y
            }) {
            Some((layout_index, cont_index, widget)) => {
                widget.click(column.into(), row.into());
                if self.act == layout_index && cont_act_index == cont_index {
                    None
                } else if widget.focus() {
                    Some((layout_index, cont_index))
                } else {
                    None
                }
            }
            None => {
                log::error!("There is no chunk laying on column {column}, row {row}");
                None
            }
        };

        if let Some((layout_index, cont_index)) = indexes {
            if let Some(w) = self.act_mut().actual_mut() {
                w.unfocus()
            }
            self.act = layout_index;
            self.act_mut().set_index(cont_index);
            Container::actualize_layout(self);
        }
    }

    pub fn search(&mut self, to_search: String) {
        log::debug!("search to_search={to_search}");
        match self.act_mut().actual_mut() {
            Some(w) => w.search_event(to_search),
            None => panic!("Actual to search is not a widget"),
        }
    }

    pub fn clean_search(&mut self) {
        log::debug!("clean_search");
        match self.act_mut().actual_mut() {
            Some(w) => w.clear_search(),
            None => panic!("Actual to search is not a widget"),
        }
    }
}

impl Render for Layout {
    fn render<B: Backend>(&self, f: &mut Frame<B>) {
        self.containers[0].render(f, &self.containers);
    }

    fn unfocus(&mut self) {
        match self.act_mut().actual_mut() {
            Some(w) => w.unfocus(),
            None => panic!("Actual to unfocus is not a widget"),
        }
    }

    fn focus(&mut self) -> bool {
        match self.act_mut().actual_mut() {
            Some(w) => w.focus(),
            None => panic!("Actual to focus is not a widget"),
        }
    }

    fn update_chunk(&mut self, chunk: Rect) {
        Container::update_chunk(chunk, &mut self.containers, 0);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn mock_layout() -> Layout {
        let mock_layout = r#"
        [
            Direction: Horizontal,
            Size: 50%,
            [
                List: 50%,
                Preview,
            ],
            [ Direction: Vertical,
              Done,
              [ 
                Contexts,
                Projects,
              ],
            ],
        ]
        "#;
        Layout::from_str(
            mock_layout,
            Arc::new(Mutex::new(ToDo::default())),
            &Config::default(),
        )
        .unwrap()
    }

    #[test]
    fn test_basic_movement() -> Result<()> {
        let mut l = mock_layout();
        assert_eq!(l.get_active_widget(), WidgetType::List);

        assert!(l.right());
        assert_eq!(l.get_active_widget(), WidgetType::Done);
        assert!(l.left());
        assert_eq!(l.get_active_widget(), WidgetType::List);
        assert!(l.right());
        assert_eq!(l.get_active_widget(), WidgetType::Done);
        assert!(!l.right());
        assert_eq!(l.get_active_widget(), WidgetType::Done);
        assert!(l.down());
        assert_eq!(l.get_active_widget(), WidgetType::Context);
        assert!(l.right());
        assert_eq!(l.get_active_widget(), WidgetType::Project);
        assert!(!l.down());
        assert_eq!(l.get_active_widget(), WidgetType::Project);
        assert!(l.left());
        assert_eq!(l.get_active_widget(), WidgetType::Context);
        assert!(l.left());
        assert_eq!(l.get_active_widget(), WidgetType::List);
        assert!(l.right());
        assert_eq!(l.get_active_widget(), WidgetType::Context);
        assert!(l.left());
        assert_eq!(l.get_active_widget(), WidgetType::List);
        assert!(!l.up());
        assert_eq!(l.get_active_widget(), WidgetType::List);

        Ok(())
    }

    #[test]
    fn test_from_string() -> Result<()> {
        let str_layout = r#"
            [
              dIrEcTiOn:HoRiZoNtAl,
              Size: 50%,
              List: 50%,
              [
                Done,
                Hashtags: 50%,
              ],
              Projects: 50%,
            ]
            
            Direction: ERROR,
        "#;

        let mut layout = Layout::from_str(
            str_layout,
            Arc::new(Mutex::new(ToDo::default())),
            &Config::default(),
        )?;
        assert_eq!(layout.containers.len(), 2);

        assert_eq!(*layout.containers[0].get_direction(), Direction::Horizontal);
        assert_eq!(layout.containers[0].parent, None);
        while layout.containers[0].previous_item() {}
        assert_eq!(
            layout.containers[0].get_active_type(),
            Some(WidgetType::List)
        );
        assert!(layout.containers[0].next_item());
        assert_eq!(layout.containers[0].get_active_type(), None);
        assert!(layout.containers[0].next_item());
        assert_eq!(
            layout.containers[0].get_active_type(),
            Some(WidgetType::Project)
        );
        assert!(!layout.containers[0].next_item());

        assert_eq!(*layout.containers[1].get_direction(), Direction::Vertical);
        assert_eq!(layout.containers[1].parent, Some(0));
        while layout.containers[1].previous_item() {}
        assert_eq!(
            layout.containers[1].get_active_type(),
            Some(WidgetType::Done)
        );
        assert!(layout.containers[1].next_item());
        assert_eq!(
            layout.containers[1].get_active_type(),
            Some(WidgetType::Hashtag)
        );
        assert!(!layout.containers[1].next_item());

        Ok(())
    }
}