taskfinder 2.15.0

A terminal user interface that extracts and displays tasks from plain text files, hooking into your default terminal-based editor for editing.
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
#![forbid(unsafe_code)]

use std::fs;
use std::io::{self, Stdout, stdout};
use std::path::Path;

use chrono::{Local, NaiveDate};
use crossterm::{
    event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
    Frame, Terminal,
    backend::CrosstermBackend,
    layout::{Constraint, Layout},
    prelude::Stylize,
    symbols::border,
    text::Line,
    widgets::{Block, Borders, Padding, Paragraph, TableState},
};
use thiserror::Error;
use tui_dialog::Dialog;

pub mod config;
pub mod count;
pub mod files;
pub mod modes;
pub mod priority;
pub mod tasks;

#[cfg(test)]
mod test_helpers;

use config::{Config, ConfigError};
use count::TaskCount;
use files::{FileStatus, FileWithTasks, edit};
use modes::{
    Mode,
    config_mode::{self, ConfigMode, ConfigSetting},
    evergreen_mode::{self, EvergreenMode},
    files_mode::{self, DueFilter, FilesMode},
    help_mode::{
        self, CHANGELOG, EXAMPLE1, EXAMPLE2, EXAMPLE3, EXAMPLE4, EXAMPLE5, EXAMPLE6, Examples,
        HelpMode, USAGE,
    },
    log_mode::{self, GraphKind, LogMode, LogSubMode},
    tasks_mode::{self, RecurringStatus, TasksMode},
};
use priority::Priority;
use tasks::{CompletionStatus, RichTask};

pub const SIDEBAR_SIZE: u16 = 38;
pub const TASK_IDENTIFIERS: &[&str] = &[
    "[ ]", "- [ ]", "[]", "- []", "[x]", "- [x]", "[X]", "- [X]", "[/]", "- [/]", "[\\]", "- [\\]",
];

/// The errors that can occur.
#[derive(Error, Debug)]
pub enum TfError {
    #[error("IoError: {0}")]
    Io(#[from] io::Error),
    #[error("System time error")]
    SystemTime(#[from] std::time::SystemTimeError),
    #[error("Parsing error")]
    ParseInt(#[from] std::num::ParseIntError),
    #[error("No matching priority.")]
    NoMatchingPriority,
    #[error("Path does not exist.")]
    NoSuchPath,
    #[error("{0}")]
    ConfigError(#[from] config::ConfigError),
    #[error("Error exporting upcoming tasks: {0}")]
    ExportError(String),
    #[error("Error copying upcoming tasks to clipboard.")]
    ArboardError(#[from] arboard::Error),
}

/// The data and state of the app.
pub struct App {
    pub action: Action,
    pub mode: Mode,
    pub config: Config,
    pub filemode: FilesMode,
    pub logmode: LogMode,
    pub configmode: ConfigMode,
    pub helpmode: HelpMode,
    pub evergreenmode: EvergreenMode,
    pub taskmode: TasksMode,
    pub current_date: NaiveDate,
    pub message_to_user: Option<String>,
    pub exit: bool,
}

impl App {
    /// Initialize current mode of the app.
    pub fn mode_init(&mut self, mode: Mode) -> Result<(), TfError> {
        self.mode = mode;

        match self.mode {
            Mode::Files => {
                files_mode::refine_files(self)?;
                self.filemode.line_offset = 0;
            }
            Mode::Tasks => {
                // Need to first collect files, since tasks come from them.
                self.filemode.files = FileWithTasks::collect(&self.config)?;

                // Collect the tasks.
                self.taskmode.data = RichTask::collect(self)?;

                // Set the dates.
                self.taskmode.dates = tasks_mode::Dates::default();

                // Keep position in table (roughly at least), but protect against
                // out-of-bounds error
                if self.taskmode.data.is_empty() {
                    self.taskmode.table.select(None);
                } else if self.taskmode.table.selected() == Some(self.taskmode.data.len()) {
                    self.taskmode
                        .table
                        .select(Some(self.taskmode.data.len() - 1));
                }
            }
            Mode::Log => {
                // Set back to table, the default submode.
                self.logmode.submode = LogSubMode::Table;

                // Recalculate latest log data - this is an expensive operation;
                // only do it when log is opened, not during navigation of log.
                if let Some(v) = self.logmode.data.first_mut() {
                    let active_count =
                        TaskCount::extract(&FileWithTasks::collect(&self.config)?, &self.mode);
                    *v = active_count;
                }
            }
            Mode::Help => {
                self.helpmode.line_offset = 0;
            }
            Mode::Evergreen => {
                if self.config.evergreen_file != Path::new("").to_path_buf() {
                    self.evergreenmode.line_offset = 0;
                }
            }
            Mode::Config => {
                self.configmode.table.select(Some(0));
                self.configmode.setting = ConfigSetting::get(0);
                self.filemode.line_offset = 0;
            }
        };
        Ok(())
    }
}

/// What to do in response to user input.
#[non_exhaustive]
#[derive(Clone, PartialEq)]
pub enum Action {
    Wait,
    SwitchMode(Mode),
    EditFile,
    EditEvergreenFile,
    EditConfigOption,
    ResetConfigOption,
    ExportUpcomingTasks,
    FilterPriority(Priority),
    FilterComplete,
    FilterArchived,
    FilterStale,
    FilterRecurring,
    FilterTag,
    FilterTerm,
    FilterDueDate,
    FilterOverdue,
    UseFileModeTagDialog(KeyCode),
    UseFileModeSearchDialog(KeyCode),
    UseTaskModeTagDialog(KeyCode),
    UseTaskModeSearchDialog(KeyCode),
    UseConfigModeDialog(KeyCode),
    ClearFilters,
    ToggleGraph,
    ToggleGraphByCompletion,
    ToggleGraphByRecurring,
    ToggleVersionAndUsage,
    ToggleFileExamples(Examples),
    ScrollUp,
    ScrollDown,
    PageUp,
    PageDown,
    NextRow,
    PrevRow,
    NextFile,
    PrevFile,
    GoToTop,
    Exit,
}

fn main() {
    let args: Vec<String> = std::env::args().collect();

    if let Some(v) = args.get(1) {
        if ["help", "--help", "-h"].contains(&v.as_str()) {
            println!("tf {} ", std::env!("CARGO_PKG_VERSION"));
            println!(
                "Run taskfinder without any arguments (`tf`) and then press `h` within the TUI to view help."
            );
            return;
        } else if ["version", "--version", "-V", "-v"].contains(&v.as_str()) {
            println!("tf {} ", std::env!("CARGO_PKG_VERSION"));
            return;
        }
    }

    let config = match Config::create_or_get() {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Error configuring app: {e}");
            return;
        }
    };

    if config.priority_markers.len() != 5 {
        eprintln!(
            "{} Please fix before continuing.",
            ConfigError::IncorrectNumberOfPriorityMarkers
        );
        return;
    }

    // Get count of incomplete/partially complete Active tasks and all completed tasks.
    let current_active_count = match &FileWithTasks::collect(&config) {
        Ok(v) => TaskCount::extract(v, &Mode::Log),
        Err(e) => {
            eprintln!("Error getting current active task count from log: {e}");
            return;
        }
    };

    // Add that count to the data file.
    if let Err(e) = TaskCount::log(&config, current_active_count.clone()) {
        eprintln!("Error adding current task count to log: {e}");
        return;
    }

    // Get all log data, to store in app as default at start.
    let num_tasks_log = match fs::read_to_string(config.num_tasks_log.clone()) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Error reading task log: {e}");
            return;
        }
    };

    let mut task_counts = num_tasks_log
        .lines()
        .map(TaskCount::new)
        .collect::<Vec<TaskCount>>();

    // Add the current active count to the log at top.
    task_counts.push(current_active_count);
    task_counts.reverse();

    // Initialize the app.
    let mut app = App {
        action: Action::Wait,
        mode: config.start_mode,
        config: config.clone(),
        filemode: FilesMode {
            current_file: 0,
            files: vec![],
            // This starts off with what is in configuration, but can be changed in-app.
            completed: config.include_completed,
            due: DueFilter::Any,
            file_status: FileStatus::Active,
            priority: None,
            tag_dialog: Dialog::default(),
            search_dialog: Dialog::default(),
            line_offset: 0,
        },
        logmode: LogMode {
            submode: LogSubMode::Table,
            data: task_counts,
            table: TableState::default().with_selected(0),
        },
        configmode: ConfigMode {
            table: TableState::default().with_selected(0),
            setting: None,
            dialog: Dialog::default(),
        },
        helpmode: HelpMode {
            line_offset: 0,
            help_text: USAGE.to_string(),
        },
        evergreenmode: EvergreenMode { line_offset: 0 },
        taskmode: TasksMode {
            data: vec![],
            table: TableState::default().with_selected(0),
            file_status: FileStatus::Active,
            completion_status: CompletionStatus::Incomplete,
            recurring_status: RecurringStatus::All,
            tag_dialog: Dialog::default(),
            search_dialog: Dialog::default(),
            dates: tasks_mode::Dates::default(),
        },
        current_date: Local::now().date_naive(),
        message_to_user: None,
        exit: false,
    };

    // Initialize the terminal.
    let mut terminal = match Terminal::new(CrosstermBackend::new(stdout())) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Error creating new terminal interface: {e}");
            return;
        }
    };

    if let Err(e) = execute!(terminal.backend_mut(), EnterAlternateScreen) {
        eprintln!("Errow switching to alternate screen: {e}");
        return;
    }

    if let Err(e) = enable_raw_mode() {
        eprintln!("Error entering raw mode: {e}");
        return;
    }

    // Run the app.
    if let Err(e) = run(&mut app, &mut terminal) {
        eprintln!("Error running app: {e}");
        return;
    }

    // Restore the terminal to its original state, then exit.
    if let Err(e) = disable_raw_mode() {
        eprintln!("Error disabling raw mode: {e}");
        return;
    }

    if let Err(e) = execute!(terminal.backend_mut(), LeaveAlternateScreen) {
        eprintln!("Error leaving alternate screen: {e}");
    }
}

/// Run the application's main loop until the user quits.
fn run(app: &mut App, terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<(), TfError> {
    app.mode_init(app.mode)?;

    while !app.exit {
        // Redraw the frame every time.
        terminal.draw(|frame| render(frame, app))?;

        // If the date has changed since the app was started, extract and write new count to the
        // log and also update in-memory data.
        let now_date = Local::now().date_naive();
        if now_date > app.current_date {
            // Collect all files freshly - rather than using those currently at app.filemode.files,
            // in order to avoid any filtering user has in place.
            let files = &FileWithTasks::collect(&app.config)?;
            let active_count = TaskCount::extract(files, &Mode::Log);
            TaskCount::log(&app.config, active_count.clone())?;

            // Remove the now-old "now" row from in-memory log.
            app.logmode.data.remove(0);

            // Update the app's current date.
            app.current_date = now_date;

            // Store new count twice in memory - once for the count at start of day, once for
            // "now" (which will then be updated anytime during the same date when log mode is
            // opened).
            app.logmode.data.push(active_count.clone());
            app.logmode.data.push(active_count);
            app.logmode.data.sort_by_key(|t| t.date);
            app.logmode.data.reverse();
        }

        // Watch for use input and give it an Action.
        app.action = match event::read()? {
            // NOTE: it's important to check that the event is a key press event as
            // crossterm also emits key release and repeat events on Windows.
            Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
                // Clear any previous message to user.
                app.message_to_user = None;

                // Pass all `key_event.code`s to a dialog if open.
                if app.filemode.tag_dialog.open {
                    Action::UseFileModeTagDialog(key_event.code)
                } else if app.filemode.search_dialog.open {
                    Action::UseFileModeSearchDialog(key_event.code)
                } else if app.taskmode.tag_dialog.open {
                    Action::UseTaskModeTagDialog(key_event.code)
                } else if app.taskmode.search_dialog.open {
                    Action::UseTaskModeSearchDialog(key_event.code)
                } else if app.configmode.dialog.open {
                    Action::UseConfigModeDialog(key_event.code)
                // If a dialog is not open, handle key presses in other ways.
                } else {
                    match key_event.code {
                        // These commands are not mode-specific.
                        KeyCode::Char('q') => Action::Exit,
                        KeyCode::Char('f') => Action::SwitchMode(Mode::Files),
                        KeyCode::Char('t') => Action::SwitchMode(Mode::Tasks),
                        KeyCode::Char('l') => Action::SwitchMode(Mode::Log),
                        KeyCode::Char('x') => Action::SwitchMode(Mode::Config),
                        KeyCode::Char('h') => Action::SwitchMode(Mode::Help),
                        KeyCode::Char('e') => Action::SwitchMode(Mode::Evergreen),
                        // Everything else is by mode.
                        _ => match app.mode {
                            Mode::Files => match key_event.code {
                                KeyCode::Char('j') | KeyCode::Down => Action::ScrollDown,
                                KeyCode::Char('k') | KeyCode::Up => Action::ScrollUp,
                                KeyCode::PageDown => Action::PageDown,
                                KeyCode::Char('d')
                                    if key_event.modifiers == KeyModifiers::CONTROL =>
                                {
                                    Action::PageDown
                                }
                                KeyCode::PageUp => Action::PageUp,
                                KeyCode::Char('u')
                                    if key_event.modifiers == KeyModifiers::CONTROL =>
                                {
                                    Action::PageUp
                                }
                                KeyCode::Char('n') | KeyCode::Right => Action::NextFile,
                                KeyCode::Char('p') | KeyCode::Left => Action::PrevFile,
                                KeyCode::Enter => Action::EditFile,
                                KeyCode::Char('1') => Action::FilterPriority(Priority::One),
                                KeyCode::Char('2') => Action::FilterPriority(Priority::Two),
                                KeyCode::Char('3') => Action::FilterPriority(Priority::Three),
                                KeyCode::Char('4') => Action::FilterPriority(Priority::Four),
                                KeyCode::Char('5') => Action::FilterPriority(Priority::Five),
                                KeyCode::Char('#') => Action::FilterTag,
                                KeyCode::Char('/') => Action::FilterTerm,
                                KeyCode::Char('c') => Action::FilterComplete,
                                KeyCode::Char('s') => Action::FilterStale,
                                KeyCode::Char('a') => Action::FilterArchived,
                                KeyCode::Char('d') => Action::FilterDueDate,
                                KeyCode::Char('o') => Action::FilterOverdue,
                                KeyCode::Esc => Action::ClearFilters,
                                _ => Action::Wait,
                            },
                            Mode::Tasks => match key_event.code {
                                KeyCode::Home => Action::GoToTop,
                                KeyCode::Char('j') | KeyCode::Down => Action::NextRow,
                                KeyCode::Char('k') | KeyCode::Up => Action::PrevRow,
                                KeyCode::Enter => Action::EditFile,
                                KeyCode::Char('c') => Action::FilterComplete,
                                KeyCode::Char('a') => Action::FilterArchived,
                                KeyCode::Char('s') => Action::FilterStale,
                                KeyCode::Char('#') => Action::FilterTag,
                                KeyCode::Char('/') => Action::FilterTerm,
                                KeyCode::Char('r') => Action::FilterRecurring,
                                KeyCode::Esc => Action::ClearFilters,
                                KeyCode::Char('X') => Action::ExportUpcomingTasks,
                                _ => Action::Wait,
                            },
                            Mode::Log => match &app.logmode.submode {
                                LogSubMode::Table => match key_event.code {
                                    KeyCode::Char('j') | KeyCode::Down => Action::NextRow,
                                    KeyCode::Char('k') | KeyCode::Up => Action::PrevRow,
                                    KeyCode::PageDown => Action::PageDown,
                                    KeyCode::Char('d')
                                        if key_event.modifiers == KeyModifiers::CONTROL =>
                                    {
                                        Action::PageDown
                                    }
                                    KeyCode::PageUp => Action::PageUp,
                                    KeyCode::Char('u')
                                        if key_event.modifiers == KeyModifiers::CONTROL =>
                                    {
                                        Action::PageUp
                                    }
                                    KeyCode::Esc => Action::GoToTop,
                                    KeyCode::Char('g') => Action::ToggleGraph,
                                    _ => Action::Wait,
                                },
                                LogSubMode::Graph(_) => match key_event.code {
                                    KeyCode::Char('g') => Action::ToggleGraph,
                                    KeyCode::Char('c') => Action::ToggleGraphByCompletion,
                                    KeyCode::Char('r') => Action::ToggleGraphByRecurring,
                                    _ => Action::Wait,
                                },
                            },
                            Mode::Help => match key_event.code {
                                KeyCode::Char('j') | KeyCode::Down => Action::ScrollDown,
                                KeyCode::Char('k') | KeyCode::Up => Action::ScrollUp,
                                KeyCode::PageDown => Action::PageDown,
                                KeyCode::Char('d')
                                    if key_event.modifiers == KeyModifiers::CONTROL =>
                                {
                                    Action::PageDown
                                }
                                KeyCode::PageUp => Action::PageUp,
                                KeyCode::Char('u')
                                    if key_event.modifiers == KeyModifiers::CONTROL =>
                                {
                                    Action::PageUp
                                }
                                KeyCode::Char('v') => Action::ToggleVersionAndUsage,
                                KeyCode::Char('1') => {
                                    Action::ToggleFileExamples(Examples::Example1)
                                }
                                KeyCode::Char('2') => {
                                    Action::ToggleFileExamples(Examples::Example2)
                                }
                                KeyCode::Char('3') => {
                                    Action::ToggleFileExamples(Examples::Example3)
                                }
                                KeyCode::Char('4') => {
                                    Action::ToggleFileExamples(Examples::Example4)
                                }
                                KeyCode::Char('5') => {
                                    Action::ToggleFileExamples(Examples::Example5)
                                }
                                KeyCode::Char('6') => {
                                    Action::ToggleFileExamples(Examples::Example6)
                                }
                                _ => Action::Wait,
                            },
                            Mode::Evergreen => match key_event.code {
                                KeyCode::Char('j') | KeyCode::Down => Action::ScrollDown,
                                KeyCode::Char('k') | KeyCode::Up => Action::ScrollUp,
                                KeyCode::PageDown => Action::PageDown,
                                KeyCode::Char('d')
                                    if key_event.modifiers == KeyModifiers::CONTROL =>
                                {
                                    Action::PageDown
                                }
                                KeyCode::PageUp => Action::PageUp,
                                KeyCode::Char('u')
                                    if key_event.modifiers == KeyModifiers::CONTROL =>
                                {
                                    Action::PageUp
                                }
                                KeyCode::Enter => Action::EditEvergreenFile,
                                _ => Action::Wait,
                            },
                            Mode::Config => match key_event.code {
                                KeyCode::Char('j') | KeyCode::Down => Action::NextRow,
                                KeyCode::Char('k') | KeyCode::Up => Action::PrevRow,
                                KeyCode::Enter => Action::EditConfigOption,
                                KeyCode::Char('r') => Action::ResetConfigOption,
                                _ => Action::Wait,
                            },
                        },
                    }
                }
            }
            _ => Action::Wait,
        };

        // Do the user's requested action.
        match &app.action {
            Action::Wait => (),
            Action::SwitchMode(mode) => {
                if app.mode != *mode {
                    app.mode_init(*mode)?;
                }
            }
            Action::Exit => app.exit = true,
            Action::ScrollDown => match app.mode {
                Mode::Files => app.filemode.line_offset += 1,
                Mode::Help => app.helpmode.line_offset += 1,
                Mode::Evergreen => app.evergreenmode.line_offset += 1,
                _ => (),
            },
            Action::ScrollUp => match app.mode {
                Mode::Files => {
                    if app.filemode.line_offset > 0 {
                        app.filemode.line_offset -= 1;
                    }
                }
                Mode::Help => {
                    if app.helpmode.line_offset > 0 {
                        app.helpmode.line_offset -= 1;
                    }
                }
                Mode::Evergreen => {
                    if app.evergreenmode.line_offset > 0 {
                        app.evergreenmode.line_offset -= 1;
                    }
                }
                _ => (),
            },
            Action::PageDown => match app.mode {
                Mode::Files => app.filemode.line_offset += 20,
                Mode::Help => app.helpmode.line_offset += 20,
                Mode::Evergreen => app.evergreenmode.line_offset += 20,
                Mode::Log => {
                    let i = match app.logmode.table.selected() {
                        Some(i) => {
                            if i >= app.logmode.data.len() - 30 {
                                0
                            } else {
                                i + 30
                            }
                        }
                        None => 0,
                    };
                    app.logmode.table.select(Some(i));
                }
                _ => (),
            },
            Action::PageUp => match app.mode {
                Mode::Files => {
                    if app.filemode.line_offset >= 20 {
                        app.filemode.line_offset -= 20;
                    } else {
                        app.filemode.line_offset = 0;
                    }
                }
                Mode::Help => {
                    if app.helpmode.line_offset >= 20 {
                        app.helpmode.line_offset -= 20;
                    } else {
                        app.helpmode.line_offset = 0;
                    }
                }
                Mode::Evergreen => {
                    if app.evergreenmode.line_offset >= 20 {
                        app.evergreenmode.line_offset -= 20;
                    } else {
                        app.evergreenmode.line_offset = 0;
                    }
                }
                Mode::Log => {
                    let i = match app.logmode.table.selected() {
                        Some(i) => {
                            if i == 0 {
                                app.logmode.data.len() - 30
                            } else {
                                i.saturating_sub(30)
                            }
                        }
                        None => 0,
                    };
                    app.logmode.table.select(Some(i));
                }
                _ => (),
            },
            Action::EditEvergreenFile => {
                // Because edit calls another terminal program,
                // leave and enter alternate screen around it to ensure that
                // the screen gets cleared properly.
                // (Without this, there are remnants of taskfinder's
                // interface left over after exiting if a file is opened
                // at any point during its use.)
                execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
                edit(app.config.evergreen_file.clone(), None)?;
                execute!(terminal.backend_mut(), EnterAlternateScreen)?;
                // Force redraw of everything.
                terminal.clear()?;
                app.evergreenmode.line_offset = 0;
            }
            Action::EditConfigOption => {
                // Either change toggle setting or bring up dialog box to get input.
                if let Some(num) = app.configmode.table.selected()
                    && let Some(cs) = ConfigSetting::get(num)
                {
                    match cs {
                        // Open the dialog box, pre-filled with existing value.
                        ConfigSetting::Path => {
                            app.configmode.dialog.open = true;
                            app.configmode.dialog.working_input =
                                app.config.path.to_string_lossy().to_string();
                        }
                        // Open the dialog box, pre-filled with existing value.
                        ConfigSetting::FileExtensions => {
                            app.configmode.dialog.open = true;
                            app.configmode.dialog.working_input =
                                app.config.file_extensions.join(",");
                        }
                        // Open the dialog box, pre-filled with existing value.
                        ConfigSetting::DaysToStale => {
                            app.configmode.dialog.open = true;
                            app.configmode.dialog.working_input =
                                app.config.days_to_stale.to_string();
                        }
                        // Open the dialog box, pre-filled with existing value.
                        ConfigSetting::PriorityMarkers => {
                            app.configmode.dialog.open = true;
                            app.configmode.dialog.working_input =
                                app.config.priority_markers.join(",");
                        }
                        // Open the dialog box, pre-filled with existing value.
                        ConfigSetting::EvergreenFile => {
                            app.configmode.dialog.open = true;
                            app.configmode.dialog.working_input =
                                app.config.evergreen_file.to_string_lossy().to_string();
                        }
                        // A toggle; immediately change the setting.
                        ConfigSetting::IncludeComplete => {
                            app.config.include_completed = !app.config.include_completed;
                            app.message_to_user = Some("Setting updated.".to_string());
                            app.config.save()?;
                        }
                        // A toggle; immediately change the setting.
                        ConfigSetting::StartMode => {
                            app.configmode.dialog.working_input =
                                format!("{:?}", app.config.start_mode);
                            match app.config.start_mode {
                                Mode::Files => app.config.start_mode = Mode::Tasks,
                                Mode::Tasks => app.config.start_mode = Mode::Log,
                                Mode::Log => app.config.start_mode = Mode::Help,
                                Mode::Help => {
                                    if app.config.evergreen_file != Path::new("").to_path_buf() {
                                        app.config.start_mode = Mode::Evergreen;
                                    } else {
                                        app.config.start_mode = Mode::Config;
                                    }
                                }
                                Mode::Evergreen => app.config.start_mode = Mode::Config,
                                Mode::Config => {
                                    app.config.start_mode = Mode::Files;
                                }
                            }
                            app.message_to_user = Some("Setting updated.".to_string());
                            app.config.save()?;
                        }
                        // A toggle; immediately change the setting.
                        ConfigSetting::OverdueBlink => {
                            app.config.overdue_blink = !app.config.overdue_blink;
                            app.message_to_user = Some("Setting updated.".to_string());
                            app.config.save()?;
                        }
                    }
                };
            }
            Action::ResetConfigOption => {
                if let Some(num) = app.configmode.table.selected()
                    && let Some(cs) = ConfigSetting::get(num)
                {
                    match cs {
                        ConfigSetting::Path => {
                            app.config.path = Config::default_files_path()?;
                            files_mode::refine_files(app)?;
                        }
                        ConfigSetting::FileExtensions => {
                            app.config.file_extensions = Config::default_file_extensions();
                            files_mode::refine_files(app)?;
                        }
                        ConfigSetting::DaysToStale => {
                            app.config.days_to_stale = config::DEFAULT_DAYS_TO_STALE;
                        }
                        ConfigSetting::IncludeComplete => {
                            app.config.include_completed = config::DEFAULT_INCLUDE_COMPLETED;
                        }
                        ConfigSetting::PriorityMarkers => {
                            app.config.priority_markers = Config::default_priority_markers();
                        }
                        ConfigSetting::EvergreenFile => {
                            app.config.evergreen_file = Config::default_evergreen_file();
                        }
                        ConfigSetting::StartMode => {
                            app.config.start_mode = Mode::Files;
                        }
                        ConfigSetting::OverdueBlink => {
                            app.config.overdue_blink = config::DEFAULT_OVERDUE_BLINK;
                        }
                    }
                    app.config.save()?;
                    app.message_to_user = Some("Reset setting to default.".to_string());
                };
            }
            Action::ExportUpcomingTasks => match tasks_mode::export_upcoming_tasks(app) {
                Ok(()) => {
                    app.message_to_user = Some("Upcoming tasks successfully exported.".to_string())
                }

                Err(e) => app.message_to_user = Some(e.to_string()),
            },
            Action::ToggleVersionAndUsage => {
                let version = std::env!("CARGO_PKG_VERSION");
                let vcl = format!("Taskfinder version {version}\n\n{CHANGELOG}\n",);
                if app.helpmode.help_text == vcl {
                    app.helpmode.help_text = USAGE.to_string();
                } else {
                    app.helpmode.help_text = vcl;
                }
                app.helpmode.line_offset = 0;
            }
            Action::ToggleFileExamples(example) => {
                match example {
                    Examples::Example1 => {
                        if app.helpmode.help_text == EXAMPLE1 {
                            app.helpmode.help_text = USAGE.to_string();
                        } else {
                            app.helpmode.help_text = EXAMPLE1.to_string();
                        }
                    }
                    Examples::Example2 => {
                        if app.helpmode.help_text == EXAMPLE2 {
                            app.helpmode.help_text = USAGE.to_string();
                        } else {
                            app.helpmode.help_text = EXAMPLE2.to_string();
                        }
                    }
                    Examples::Example3 => {
                        if app.helpmode.help_text == EXAMPLE3 {
                            app.helpmode.help_text = USAGE.to_string();
                        } else {
                            app.helpmode.help_text = EXAMPLE3.to_string();
                        }
                    }
                    Examples::Example4 => {
                        if app.helpmode.help_text == EXAMPLE4 {
                            app.helpmode.help_text = USAGE.to_string();
                        } else {
                            app.helpmode.help_text = EXAMPLE4.to_string();
                        }
                    }
                    Examples::Example5 => {
                        if app.helpmode.help_text == EXAMPLE5 {
                            app.helpmode.help_text = USAGE.to_string();
                        } else {
                            app.helpmode.help_text = EXAMPLE5.to_string();
                        }
                    }
                    Examples::Example6 => {
                        if app.helpmode.help_text == EXAMPLE6 {
                            app.helpmode.help_text = USAGE.to_string();
                        } else {
                            app.helpmode.help_text = EXAMPLE6.to_string();
                        }
                    }
                }
                app.helpmode.line_offset = 0;
            }
            Action::NextRow => match app.mode {
                Mode::Tasks => {
                    let i = match app.taskmode.table.selected() {
                        Some(i) => {
                            if i >= app.taskmode.data.len() - 1 {
                                0
                            } else {
                                i + 1
                            }
                        }
                        None => 0,
                    };
                    app.taskmode.table.select(Some(i));
                }
                Mode::Log => {
                    let i = match app.logmode.table.selected() {
                        Some(i) => {
                            if i >= app.logmode.data.len() - 1 {
                                0
                            } else {
                                i + 1
                            }
                        }
                        None => 0,
                    };
                    app.logmode.table.select(Some(i));
                }
                Mode::Config => {
                    let i = match app.configmode.table.selected() {
                        Some(i) => {
                            if i >= app.config.table_rows().len() - 1 {
                                0
                            } else {
                                i + 1
                            }
                        }
                        None => 0,
                    };
                    // Set both the row of the TableState and the configmode.setting it corresponds to.
                    app.configmode.table.select(Some(i));
                    app.configmode.setting = ConfigSetting::get(i);
                }
                _ => (),
            },
            Action::PrevRow => match app.mode {
                Mode::Tasks => {
                    let i = match app.taskmode.table.selected() {
                        Some(i) => {
                            if i == 0 {
                                app.taskmode.data.len() - 1
                            } else {
                                i - 1
                            }
                        }
                        None => 0,
                    };
                    app.taskmode.table.select(Some(i));
                }
                Mode::Log => {
                    let i = match app.logmode.table.selected() {
                        Some(i) => {
                            if i == 0 {
                                app.logmode.data.len() - 1
                            } else {
                                i - 1
                            }
                        }
                        None => 0,
                    };
                    app.logmode.table.select(Some(i));
                }
                Mode::Config => {
                    let i = match app.configmode.table.selected() {
                        Some(i) => {
                            if i == 0 {
                                app.config.table_rows().len() - 1
                            } else {
                                i - 1
                            }
                        }
                        None => 0,
                    };
                    // Set both the row of the TableState and the configmode.setting it corresponds to.
                    app.configmode.table.select(Some(i));
                    app.configmode.setting = ConfigSetting::get(i);
                }
                _ => (),
            },
            Action::NextFile => {
                if app.filemode.files.is_empty() {
                    app.filemode.current_file = 0;
                } else if app.filemode.current_file == app.filemode.files.len() - 1 {
                    app.filemode.current_file = 0
                } else {
                    app.filemode.current_file += 1;
                }
                app.filemode.line_offset = 0;
            }
            Action::PrevFile => {
                if app.filemode.files.is_empty() {
                    app.filemode.current_file = 0;
                } else if app.filemode.current_file == 0 {
                    app.filemode.current_file = app.filemode.files.len() - 1;
                } else {
                    app.filemode.current_file -= 1;
                }
                app.filemode.line_offset = 0;
            }
            Action::ToggleGraph => {
                app.logmode.submode = match app.logmode.submode {
                    LogSubMode::Graph(_) => LogSubMode::Table,
                    LogSubMode::Table => LogSubMode::Graph(GraphKind::All),
                }
            }
            Action::ToggleGraphByCompletion => {
                app.logmode.submode = match app.logmode.submode {
                    LogSubMode::Graph(GraphKind::All) => {
                        LogSubMode::Graph(GraphKind::CompleteAndIncomplete)
                    }
                    LogSubMode::Graph(GraphKind::CompleteAndIncomplete) => {
                        LogSubMode::Graph(GraphKind::Incomplete)
                    }
                    LogSubMode::Graph(GraphKind::Incomplete) => {
                        LogSubMode::Graph(GraphKind::Complete)
                    }
                    LogSubMode::Graph(GraphKind::Complete) => LogSubMode::Graph(GraphKind::All),
                    _ => LogSubMode::Graph(GraphKind::CompleteAndIncomplete),
                }
            }
            Action::ToggleGraphByRecurring => {
                app.logmode.submode = match app.logmode.submode {
                    LogSubMode::Graph(GraphKind::All) => {
                        LogSubMode::Graph(GraphKind::RecurringAndNonRecurring)
                    }
                    LogSubMode::Graph(GraphKind::RecurringAndNonRecurring) => {
                        LogSubMode::Graph(GraphKind::IncompleteByRecurring)
                    }
                    LogSubMode::Graph(GraphKind::IncompleteByRecurring) => {
                        LogSubMode::Graph(GraphKind::CompleteByRecurring)
                    }
                    LogSubMode::Graph(GraphKind::CompleteByRecurring) => {
                        LogSubMode::Graph(GraphKind::All)
                    }
                    _ => LogSubMode::Graph(GraphKind::RecurringAndNonRecurring),
                }
            }
            Action::GoToTop => match app.mode {
                Mode::Log => app.logmode.table = TableState::default().with_selected(0),
                Mode::Tasks => app.taskmode.table = TableState::default().with_selected(0),
                _ => (),
            },
            Action::FilterPriority(priority) => {
                files_mode::filter_by_priority(app, *priority);
                files_mode::refine_files(app)?;
                app.filemode.line_offset = 0;
            }
            Action::FilterComplete => match app.mode {
                Mode::Tasks => {
                    app.taskmode.completion_status = match app.taskmode.completion_status {
                        CompletionStatus::Incomplete => CompletionStatus::Completed,
                        CompletionStatus::Completed => CompletionStatus::Incomplete,
                    };
                    app.taskmode.data = RichTask::collect(app)?;
                    if !app.taskmode.data.is_empty() {
                        app.taskmode.table.select(Some(0));
                    }
                }
                Mode::Files => {
                    app.filemode.completed = !app.filemode.completed;
                    files_mode::refine_files(app)?;
                    app.filemode.line_offset = 0;
                }
                _ => (),
            },
            Action::FilterArchived => match app.mode {
                Mode::Tasks => {
                    app.taskmode.file_status = match app.taskmode.file_status {
                        FileStatus::Stale => FileStatus::Active,
                        FileStatus::Active => FileStatus::Archived,
                        FileStatus::Archived => FileStatus::Active,
                    };
                    app.taskmode.data = RichTask::collect(app)?;
                    if !app.taskmode.data.is_empty() {
                        app.taskmode.table.select(Some(0));
                    }
                }
                Mode::Files => {
                    app.filemode.current_file = 0;
                    app.filemode.file_status = match app.filemode.file_status {
                        FileStatus::Archived => FileStatus::Active,
                        FileStatus::Stale => FileStatus::Archived,
                        FileStatus::Active => FileStatus::Archived,
                    };
                    files_mode::refine_files(app)?;
                    app.filemode.line_offset = 0;
                }
                _ => (),
            },
            Action::FilterStale => match app.mode {
                Mode::Tasks => {
                    app.taskmode.file_status = match app.taskmode.file_status {
                        FileStatus::Stale => FileStatus::Active,
                        FileStatus::Active => FileStatus::Stale,
                        FileStatus::Archived => FileStatus::Stale,
                    };
                    app.taskmode.data = RichTask::collect(app)?;
                    if !app.taskmode.data.is_empty() {
                        app.taskmode.table.select(Some(0));
                    }
                }
                Mode::Files => {
                    app.filemode.current_file = 0;
                    app.filemode.file_status = match app.filemode.file_status {
                        FileStatus::Stale => FileStatus::Active,
                        FileStatus::Active => FileStatus::Stale,
                        FileStatus::Archived => FileStatus::Stale,
                    };
                    app.filemode.completed = true;
                    files_mode::refine_files(app)?;
                    app.filemode.line_offset = 0;
                }
                _ => (),
            },
            Action::FilterRecurring => {
                app.taskmode.recurring_status = match app.taskmode.recurring_status {
                    RecurringStatus::All => RecurringStatus::Recurring,
                    RecurringStatus::Recurring => RecurringStatus::NonRecurring,
                    RecurringStatus::NonRecurring => RecurringStatus::All,
                };
                app.taskmode.data = RichTask::collect(app)?;
                if !app.taskmode.data.is_empty() {
                    app.taskmode.table.select(Some(0));
                }
            }
            Action::FilterDueDate => {
                match app.filemode.due {
                    DueFilter::Any | DueFilter::OverDue => {
                        app.filemode.due = DueFilter::WithDueDate
                    }
                    DueFilter::WithDueDate => app.filemode.due = DueFilter::Any,
                }
                app.filemode.current_file = 0;
                app.filemode.line_offset = 0;
                files_mode::refine_files(app)?;
            }
            Action::FilterOverdue => {
                match app.filemode.due {
                    DueFilter::Any | DueFilter::WithDueDate => {
                        app.filemode.due = DueFilter::OverDue
                    }
                    DueFilter::OverDue => app.filemode.due = DueFilter::Any,
                }
                app.filemode.current_file = 0;
                app.filemode.line_offset = 0;
                files_mode::refine_files(app)?;
            }
            Action::UseFileModeTagDialog(key_code) => {
                app.filemode.tag_dialog.key_action(key_code);
                if app.filemode.tag_dialog.submitted {
                    app.filemode.current_file = 0;
                    app.filemode.line_offset = 0;
                    app.mode = Mode::Files;
                    files_mode::refine_files(app)?;
                }
            }
            Action::UseFileModeSearchDialog(key_code) => {
                app.filemode.search_dialog.key_action(key_code);
                if app.filemode.search_dialog.submitted {
                    app.filemode.current_file = 0;
                    app.filemode.line_offset = 0;
                    app.mode = Mode::Files;
                    files_mode::refine_files(app)?;
                }
            }
            Action::UseTaskModeTagDialog(key_code) => {
                app.taskmode.tag_dialog.key_action(key_code);
                if app.taskmode.tag_dialog.submitted {
                    app.taskmode.tag_dialog.submitted_input = app
                        .taskmode
                        .tag_dialog
                        .submitted_input
                        .trim()
                        .to_lowercase();
                    app.taskmode.data = RichTask::collect(app)?;
                    // Reset selected row.
                    if app.taskmode.data.is_empty() {
                        app.taskmode.table.select(None);
                    } else {
                        app.taskmode.table.select(Some(0));
                    }
                }
            }
            Action::UseTaskModeSearchDialog(key_code) => {
                app.taskmode.search_dialog.key_action(key_code);
                if app.taskmode.search_dialog.submitted {
                    app.taskmode.search_dialog.submitted_input = app
                        .taskmode
                        .search_dialog
                        .submitted_input
                        .trim()
                        .to_lowercase();
                    app.taskmode.data = RichTask::collect(app)?;
                    // Reset selected row.
                    if app.taskmode.data.is_empty() {
                        app.taskmode.table.select(None)
                    } else {
                        app.taskmode.table.select(Some(0))
                    }
                }
            }
            Action::UseConfigModeDialog(key_code) => {
                app.configmode.dialog.key_action(key_code);
                if app.configmode.dialog.submitted {
                    match config_mode::submit_config_change(app) {
                        Ok(true) => app.message_to_user = Some("Setting updated.".to_string()),
                        Ok(false) => app.message_to_user = Some("No change made.".to_string()),
                        Err(e) => app.message_to_user = Some(format!("{e}")),
                    }
                }
            }
            Action::EditFile => match app.mode {
                Mode::Tasks => {
                    if !app.taskmode.data.is_empty()
                        && let Some(v) = app.taskmode.table.selected()
                    {
                        execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
                        edit(
                            app.taskmode.data[v].file_path.clone(),
                            Some(app.taskmode.data[v].task.line),
                        )?;
                        execute!(terminal.backend_mut(), EnterAlternateScreen)?;
                        // Force redraw of everything.
                        terminal.clear()?;
                        // Refresh files and tasks in case any changes were made.
                        app.filemode.files = FileWithTasks::collect(&app.config)?;
                        app.taskmode.data = RichTask::collect(app)?;
                        // Keep position in table (roughly at least), but protect against
                        // out-of-bounds error
                        if app.taskmode.data.is_empty() {
                            app.taskmode.table.select(None);
                        } else if app.taskmode.table.selected() == Some(app.taskmode.data.len()) {
                            app.taskmode.table.select(Some(app.taskmode.data.len() - 1));
                        }
                    }
                }
                Mode::Files => {
                    // Because edit calls another terminal program,
                    // leave and enter alternate screen around it to ensure that
                    // the screen gets cleared properly.
                    // (Without this, there are remnants of taskfinder's
                    // interface left over after exiting if a file is opened
                    // at any point during its use.)
                    if !app.filemode.files.is_empty() {
                        // Store the current file's head, so that we can try to return to it.
                        let current_head =
                            app.filemode.files[app.filemode.current_file].head[0].clone();
                        execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
                        edit(
                            app.filemode.files[app.filemode.current_file].file.clone(),
                            None,
                        )?;
                        execute!(terminal.backend_mut(), EnterAlternateScreen)?;
                        // Force redraw of everything.
                        terminal.clear()?;
                        files_mode::refine_files(app)?;
                        // Try to return to viewing file that was just closed, otherwise to first.
                        app.filemode.current_file = 0;
                        for (i, file) in app.filemode.files.iter().enumerate() {
                            if file.head[0] == current_head {
                                app.filemode.current_file = i
                            }
                        }
                        app.filemode.line_offset = 0;
                    }
                }
                _ => (),
            },
            Action::FilterTag => match app.mode {
                Mode::Tasks => app.taskmode.tag_dialog.open = true,
                Mode::Files => app.filemode.tag_dialog.open = true,
                _ => (),
            },
            Action::FilterTerm => match app.mode {
                Mode::Tasks => app.taskmode.search_dialog.open = true,
                Mode::Files => app.filemode.search_dialog.open = true,
                _ => (),
            },
            Action::ClearFilters => match app.mode {
                Mode::Tasks => {
                    app.taskmode.file_status = FileStatus::Active;
                    app.taskmode.completion_status = CompletionStatus::Incomplete;
                    app.taskmode.tag_dialog.submitted_input.clear();
                    app.taskmode.search_dialog.submitted_input.clear();
                    app.taskmode.recurring_status = RecurringStatus::All;
                    app.taskmode.data = RichTask::collect(app)?;
                    // Reset selected row.
                    if app.taskmode.data.is_empty() {
                        app.taskmode.table.select(None)
                    } else {
                        app.taskmode.table.select(Some(0))
                    }
                }
                Mode::Files => {
                    app.filemode.completed = app.config.include_completed;
                    app.filemode.due = DueFilter::Any;
                    app.filemode.file_status = FileStatus::Active;
                    app.filemode.priority = None;
                    app.filemode.current_file = 0;
                    app.filemode.line_offset = 0;
                    app.filemode.tag_dialog.submitted_input.clear();
                    app.filemode.search_dialog.submitted_input.clear();
                    files_mode::refine_files(app)?;
                }
                _ => (),
            },
        }

        // After the action has been processed, set to waiting so it will do nothing until next
        // action from user.
        app.action = Action::Wait;
    }
    Ok(())
}

fn render(frame: &mut Frame, app: &mut App) {
    // Layout the rectangles of the UI.
    let horizontal = Layout::horizontal([Constraint::Fill(1), Constraint::Length(SIDEBAR_SIZE)]);
    let vertical = Layout::vertical([Constraint::Percentage(38), Constraint::Percentage(62)]);

    let [left, right] = horizontal.areas(frame.area());
    let [top_right, bottom_right] = vertical.areas(right);

    // Main content.
    // The surrounding block of the main content.
    let main_block = Block::default()
        .title_top(Line::from(" Taskfinder ").bold().centered())
        .borders(Borders::ALL)
        .border_set(border::THICK)
        .padding(Padding::horizontal(1));

    // Top right - additional info related to main content.
    let info_block = Block::default()
        .borders(Borders::ALL)
        .border_set(border::THICK);

    // Bottom right - Controls menu
    let controls_block = Block::default()
        .title_top(Line::from(" Controls ").centered().bold())
        .title_bottom(Line::from(" q to quit ").centered())
        .borders(Borders::ALL)
        .border_set(border::THICK);

    // Controls content common to all modes.
    let mut controls_content: Vec<Line<'_>> = vec![
        Line::from("Mode".blue().bold().underlined()),
        vec!["f".blue(), " Files".into(), "   x".blue(), " Config".into()].into(),
        vec!["t".blue(), " Tasks".into(), "   h".blue(), " Help".into()].into(),
    ];

    // Only show evergreen mode if a file has been set in the configuration.
    if app.config.evergreen_file != Path::new("").to_path_buf() {
        controls_content.push(
            vec![
                "l".blue(),
                " Log".into(),
                "     e".blue(),
                " Evergreen ".into(),
            ]
            .into(),
        );
    } else {
        controls_content.push(vec!["l".blue(), " Log".into()].into());
    }

    match app.mode {
        Mode::Files => files_mode::render(
            app,
            frame,
            info_block,
            main_block,
            top_right,
            left,
            &mut controls_content,
            vertical,
        ),
        Mode::Tasks => tasks_mode::render(
            app,
            frame,
            info_block,
            main_block,
            top_right,
            left,
            &mut controls_content,
        ),
        Mode::Config => config_mode::render(
            app,
            frame,
            info_block,
            main_block,
            top_right,
            left,
            &mut controls_content,
        ),
        Mode::Log => log_mode::render(
            app,
            frame,
            info_block,
            main_block,
            top_right,
            left,
            &mut controls_content,
            vertical,
        ),
        Mode::Help => help_mode::render(
            app,
            frame,
            info_block,
            main_block,
            top_right,
            left,
            &mut controls_content,
        ),
        Mode::Evergreen => evergreen_mode::render(
            app,
            frame,
            info_block,
            main_block,
            top_right,
            left,
            &mut controls_content,
        ),
    }

    let controls = Paragraph::new(controls_content).block(controls_block);
    frame.render_widget(controls, bottom_right);
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{fs, str::FromStr};

    use priority::make_priority_map;
    use test_helpers::make_test_config;

    #[test]
    /// The readme links to the usage doc corresponding to the most recent release, and the tag
    /// should match the format of the version, so make sure it's there.
    fn readme_contains_current_version_tag() {
        let readme = fs::read_to_string(Path::new("README.md")).unwrap();
        assert!(readme.contains(std::env!("CARGO_PKG_VERSION")))
    }
    #[test]
    fn extract_correct_number_of_task_sets() {
        let config = make_test_config();
        let priority_map = make_priority_map(config.priority_markers);
        let file = Path::new("test_files/01_basics.txt");
        let file_with_tasks = FileWithTasks::extract(file, 365, priority_map)
            .unwrap()
            .unwrap();
        assert_eq!(file_with_tasks.task_sets.len(), 2);
    }

    #[test]
    fn extract_correct_number_of_tasks_in_task_set() {
        let config = make_test_config();
        let priority_map = make_priority_map(config.priority_markers);
        let file = Path::new("test_files/01_basics.txt");
        let task_sets = FileWithTasks::extract(file, 365, priority_map)
            .unwrap()
            .unwrap()
            .task_sets
            .clone();
        assert_eq!(task_sets[0].tasks.len(), 2);
        assert_eq!(task_sets[1].tasks.len(), 4);
    }

    #[test]
    fn tasks_ignored_with_no_todo_header() {
        let config = make_test_config();
        let priority_map = make_priority_map(config.priority_markers);
        let file = Path::new("test_files/no_tasks.txt");
        let task_sets = FileWithTasks::extract(file, 365, priority_map).unwrap();
        assert!(task_sets.is_none());
    }

    #[test]
    fn due_date_inheritance_is_correct() {
        let config = make_test_config();
        let priority_map = make_priority_map(config.priority_markers);
        let file_with_dates =
            FileWithTasks::extract(Path::new("test_files/03_dates.txt"), 365, priority_map)
                .unwrap()
                .unwrap();

        assert_eq!(
            file_with_dates.task_sets[0].due_date,
            Some(NaiveDate::from_str("2025-04-30").unwrap())
        );
        assert!(file_with_dates.task_sets[1].due_date.is_none());
        assert_eq!(
            file_with_dates.task_sets[0].tasks[0].due_date,
            Some(NaiveDate::from_str("2025-04-30").unwrap())
        );
        assert_eq!(
            file_with_dates.task_sets[0].tasks[1].due_date,
            Some(NaiveDate::from_str("2025-04-30").unwrap())
        );
    }

    #[test]
    fn recurring_status_is_correct() {
        let config = make_test_config();
        let priority_map = make_priority_map(config.priority_markers);
        let files = FileWithTasks::extract(Path::new("test_files/06_misc.txt"), 365, priority_map)
            .unwrap()
            .unwrap();
        assert!(!files.task_sets[1].tasks[0].recurring);
        assert!(!files.task_sets[1].tasks[1].recurring);
        assert!(files.task_sets[1].tasks[2].recurring);
        assert!(files.task_sets[1].tasks[3].recurring);
    }
}