cfait 1.0.7

Powerful, fast and elegant task / TODO manager. (GUI & TUI, CalDAV & local)
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
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
// SPDX-License-Identifier: GPL-3.0-or-later
// File: ./src/tui/state.rs
// Manages the application state for the TUI.
use crate::context::AppContext;
use crate::model::{CalendarListEntry, Task};
use crate::store::{FilterOptions, TaskListItem, TaskStore};
use crate::system::SystemEvent;
use crate::tui::action::SidebarMode;
use ratatui::widgets::ListState;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::mpsc; // Add import

#[derive(PartialEq, Clone, Copy)]
pub enum Focus {
    Sidebar,
    Main,
}

#[derive(PartialEq, Clone, Copy)]
pub enum InputMode {
    Normal,
    Creating,
    Searching,
    Editing,
    EditingDescription,
    Moving,
    SelectingExportSource,
    Exporting,
    Snoozing,
    RelationshipBrowsing,
    AddingSession,
    ManagingSessions,
    ActionMenu,
    Help(crate::help::HelpTab),
}

pub struct AppState {
    // Data
    pub ctx: Arc<dyn AppContext>,
    pub store: TaskStore,
    pub tasks: Vec<TaskListItem>,
    pub calendars: Vec<CalendarListEntry>,

    // UI State
    pub list_state: ListState,
    pub cal_state: ListState,
    pub active_focus: Focus,
    pub mode: InputMode,
    pub message: String,
    pub loading: bool,

    // Filter State
    pub sidebar_mode: SidebarMode,
    pub active_cal_href: Option<String>,
    pub hidden_calendars: HashSet<String>,
    pub disabled_calendars: HashSet<String>,
    pub local_mode_enabled: bool,
    pub selected_categories: HashSet<String>,
    pub selected_locations: HashSet<String>, // NEW
    pub match_all_categories: bool,
    pub hide_completed: bool,
    pub hide_fully_completed_tags: bool,
    pub hide_aliases_in_sidebar: bool,
    pub strikethrough_completed: bool,
    pub show_priority_numbers: bool,
    pub sort_cutoff_months: Option<u32>,
    pub sort_standard_by_priority: bool,

    pub theme: crate::config::AppTheme,

    pub quick_filter_term: String,
    pub quick_filter_icon: String,
    pub show_quick_filter: bool,

    // Cached sidebar values (derived from the last filter result)
    pub cached_categories: Vec<crate::store::AggregateItem>,
    pub cached_locations: Vec<crate::store::AggregateItem>,

    pub urgent_days: u32,
    pub urgent_prio: u8,
    pub default_priority: u8,
    pub start_grace_period_days: u32,

    // Snooze configuration
    pub snooze_short_mins: u32,
    pub snooze_long_mins: u32,

    // Input Buffers
    pub input_buffer: String,
    pub active_search_query: String, // Holds the committed search term
    pub cursor_position: usize,
    pub edit_scroll_offset: u16,
    pub edit_scroll_x: u16,
    pub editing_uid: Option<String>,
    pub move_selection_state: ListState,
    pub move_targets: Vec<CalendarListEntry>,
    pub export_source_selection_state: ListState,
    pub export_source_calendars: Vec<CalendarListEntry>,
    pub export_selection_state: ListState,
    pub export_targets: Vec<CalendarListEntry>,

    pub yanked_uid: Option<String>,
    pub yank_lock_active: bool,
    pub creating_child_of: Option<String>,
    pub creating_with_desc: bool,
    pub new_task_title: String,
    pub tag_aliases: HashMap<String, Vec<String>>,

    // Relationship browsing state
    pub relationship_items: Vec<(String, String, String)>, // (uid, display_name, rel_type)
    pub relationship_selection_state: ListState,

    // Session management state (for quick-log and session editor)
    pub session_items: Vec<(usize, String)>,
    pub session_selection_state: ListState,

    // Action menu state
    pub available_actions: Vec<crate::config::TaskAction>,
    pub action_menu_items: Vec<crate::config::TaskAction>,
    pub action_selection_state: ListState,
    pub action_filter: String,

    // Track unsynced status
    pub unsynced_changes: bool,
    pub alarm_actor_tx: Option<mpsc::Sender<SystemEvent>>,
    pub active_alarm: Option<(Task, String)>, // (Task, AlarmUID) to render popup

    // Expanded Done Groups (keys are parent UIDs; empty string for root group)
    pub expanded_done_groups: HashSet<String>,
    pub expanded_tags: HashSet<String>,
    pub expanded_locations: HashSet<String>,

    pub needs_redraw: bool,
}

impl Default for AppState {
    fn default() -> Self {
        // Backwards compatible default for codepaths that still call `AppState::default()`.
        // This uses the platform default context; prefer constructing with an explicit context.
        Self::new()
    }
}

impl AppState {
    /// Creates a new AppState with the default platform context.
    pub fn new() -> Self {
        // Provide a convenient no-arg constructor that uses the platform default context.
        // Call sites that need test isolation or custom roots should call `new_with_ctx`.
        let ctx = Arc::new(crate::context::StandardContext::new(None));
        Self::new_with_ctx(ctx)
    }

    /// Creates a new AppState with an explicit AppContext.
    pub fn new_with_ctx(ctx: Arc<dyn AppContext>) -> Self {
        let mut l_state = ListState::default();
        l_state.select(Some(0));
        let mut c_state = ListState::default();
        c_state.select(Some(0));

        Self {
            ctx: ctx.clone(),
            store: TaskStore::new(ctx.clone()),
            tasks: vec![],
            calendars: vec![],
            list_state: l_state,
            cal_state: c_state,
            active_focus: Focus::Main,
            mode: InputMode::Normal,
            message: "Loading...".to_string(),
            loading: true,

            sidebar_mode: SidebarMode::Calendars,
            active_cal_href: None,
            hidden_calendars: HashSet::new(),
            disabled_calendars: HashSet::new(),
            local_mode_enabled: true,
            selected_categories: HashSet::new(),
            selected_locations: HashSet::new(), // Init
            match_all_categories: true,
            hide_completed: false,
            strikethrough_completed: false,
            hide_fully_completed_tags: false,
            hide_aliases_in_sidebar: true,
            show_priority_numbers: true,
            quick_filter_term: "is:ready".to_string(),
            quick_filter_icon: "f0fa9".to_string(),
            show_quick_filter: true,
            sort_cutoff_months: Some(2),
            sort_standard_by_priority: false,
            theme: crate::config::AppTheme::default(),
            // Initialize sidebar caches as empty; they will be populated by refresh_filtered_view()
            cached_categories: Vec::new(),
            cached_locations: Vec::new(),
            urgent_days: 1,
            urgent_prio: 1,
            default_priority: 5,
            start_grace_period_days: 1,

            snooze_short_mins: 60,
            snooze_long_mins: 1440,

            input_buffer: String::new(),
            active_search_query: String::new(),
            cursor_position: 0,
            edit_scroll_offset: 0,
            edit_scroll_x: 0,
            editing_uid: None,
            move_selection_state: ListState::default(),
            move_targets: Vec::new(),
            yanked_uid: None,
            yank_lock_active: false,
            creating_child_of: None,
            creating_with_desc: false,
            new_task_title: String::new(),

            tag_aliases: HashMap::new(),
            export_source_selection_state: ListState::default(),
            export_source_calendars: Vec::new(),
            export_selection_state: ListState::default(),
            export_targets: Vec::new(),

            relationship_items: Vec::new(),
            relationship_selection_state: ListState::default(),
            session_items: Vec::new(),
            session_selection_state: ListState::default(),

            available_actions: Vec::new(),
            action_menu_items: Vec::new(),
            action_selection_state: ListState::default(),
            action_filter: String::new(),

            unsynced_changes: false, // Default false
            alarm_actor_tx: None,
            active_alarm: None,

            // Track expanded completed groups (keys are parent UIDs, empty string for roots)
            expanded_done_groups: HashSet::new(),
            expanded_tags: HashSet::new(),
            expanded_locations: HashSet::new(),
            needs_redraw: false,
        }
    }

    pub fn get_filtered_calendars(&self) -> Vec<&CalendarListEntry> {
        self.calendars
            .iter()
            .filter(|c| self.local_mode_enabled || !c.href.starts_with("local://"))
            .filter(|c| !self.disabled_calendars.contains(&c.href))
            .filter(|c| {
                if c.href == crate::storage::LOCAL_TRASH_HREF || c.href == "local://recovery" {
                    self.store
                        .calendars
                        .get(&c.href)
                        .is_some_and(|map| !map.is_empty())
                } else {
                    true
                }
            })
            .collect()
    }

    pub fn refresh_filtered_view(&mut self) {
        let search_term = if self.mode == InputMode::Searching {
            &self.input_buffer
        } else {
            &self.active_search_query
        };

        let cutoff_date = if let Some(months) = self.sort_cutoff_months {
            let now = chrono::Utc::now();
            let days = months as i64 * 30;
            Some(now + chrono::Duration::days(days))
        } else {
            None
        };

        let mut effective_hidden = self.hidden_calendars.clone();
        effective_hidden.extend(self.disabled_calendars.clone());
        if !self.local_mode_enabled {
            for href in self.store.calendars.keys() {
                if href.starts_with("local://") {
                    effective_hidden.insert(href.clone());
                }
            }
        }

        // Load config to get limits
        let config = crate::config::Config::load(self.ctx.as_ref()).unwrap_or_default();

        // Use the store.filter() that returns a FilterResult so we can populate
        // both the task list and the sidebar caches for categories/locations.
        let filter_res = self.store.filter(FilterOptions {
            active_cal_href: None, // Logic handled by hidden_calendars
            hidden_calendars: &effective_hidden,
            selected_categories: &self.selected_categories,
            selected_locations: &self.selected_locations,
            match_all_categories: self.match_all_categories,
            search_term,
            hide_completed_global: self.hide_completed,
            hide_fully_completed_tags: self.hide_fully_completed_tags,
            hide_aliases_in_sidebar: self.hide_aliases_in_sidebar,
            cutoff_date,
            min_duration: None,
            max_duration: None,
            include_unset_duration: true,
            urgent_days: self.urgent_days,
            urgent_prio: self.urgent_prio,
            default_priority: self.default_priority,
            start_grace_period_days: self.start_grace_period_days,
            sort_standard_by_priority: self.sort_standard_by_priority,
            sort_preset: config.sort_preset,
            expanded_done_groups: &self.expanded_done_groups,
            expanded_tags: &self.expanded_tags,
            expanded_locations: &self.expanded_locations,
            max_done_roots: config.max_done_roots,
            max_done_subtasks: config.max_done_subtasks,
            tag_aliases: &config.tag_aliases,
        });

        self.tasks = filter_res.items;
        self.cached_categories = filter_res.categories;
        self.cached_locations = filter_res.locations;

        let len = self.tasks.len();
        if len == 0 {
            self.list_state.select(None);
        } else {
            let current = self.list_state.selected().unwrap_or(0);
            if current >= len {
                self.list_state.select(Some(len - 1)); // Clamp
            } else {
                self.list_state.select(Some(current));
            }
        }
    }

    pub fn get_selected_task(&self) -> Option<&Task> {
        if let Some(idx) = self.list_state.selected() {
            match &self.tasks.get(idx) {
                Some(TaskListItem::Task(task)) => Some(task),
                _ => None,
            }
        } else {
            None
        }
    }

    /// Get the task at a specific index, returning None for control items
    pub fn get_task_at_index(&self, idx: usize) -> Option<&Task> {
        match &self.tasks.get(idx) {
            Some(TaskListItem::Task(task)) => Some(task),
            _ => None,
        }
    }

    /// Find the index of a task by UID, ignoring control items
    pub fn find_task_index_by_uid(&self, uid: &str) -> Option<usize> {
        self.tasks.iter().position(|item| {
            if let TaskListItem::Task(task) = item {
                task.uid == uid
            } else {
                false
            }
        })
    }

    /// Get all real tasks (excluding control items)
    pub fn get_all_real_tasks(&self) -> Vec<&Task> {
        self.tasks
            .iter()
            .filter_map(|item| {
                if let TaskListItem::Task(task) = item {
                    Some(task.as_ref())
                } else {
                    None
                }
            })
            .collect()
    }

    // --- INPUT HELPERS ---
    pub fn move_cursor_left(&mut self) {
        let cursor_moved_left = self.cursor_position.saturating_sub(1);
        self.cursor_position = self.clamp_cursor(cursor_moved_left);
    }
    pub fn move_cursor_right(&mut self) {
        let cursor_moved_right = self.cursor_position.saturating_add(1);
        self.cursor_position = self.clamp_cursor(cursor_moved_right);
    }
    pub fn enter_char(&mut self, new_char: char) {
        // Safe insertion for UTF-8 strings
        let byte_index = self
            .input_buffer
            .char_indices()
            .map(|(i, _)| i)
            .nth(self.cursor_position)
            .unwrap_or(self.input_buffer.len());

        self.input_buffer.insert(byte_index, new_char);
        self.move_cursor_right();
    }
    pub fn delete_char(&mut self) {
        if self.cursor_position != 0 {
            let current_index = self.cursor_position;
            let before = self.input_buffer.chars().take(current_index - 1);
            let after = self.input_buffer.chars().skip(current_index);
            self.input_buffer = before.chain(after).collect();
            self.move_cursor_left();
        }
    }
    pub fn reset_input(&mut self) {
        self.input_buffer.clear();
        self.cursor_position = 0;
    }
    fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
        new_cursor_pos.clamp(0, self.input_buffer.chars().count())
    }

    // --- HELPER FOR SIDEBAR LENGTH ---
    fn get_sidebar_len(&self) -> usize {
        match self.sidebar_mode {
            SidebarMode::Calendars => self.get_filtered_calendars().len(),
            SidebarMode::Categories => self.cached_categories.len(),
            SidebarMode::Locations => self.cached_locations.len(),
        }
    }

    // --- NAVIGATION ---
    pub fn next(&mut self) {
        match self.active_focus {
            Focus::Main => {
                if self.tasks.is_empty() {
                    return;
                }
                let i = match self.list_state.selected() {
                    Some(i) => {
                        if i >= self.tasks.len() - 1 {
                            0
                        } else {
                            i + 1
                        }
                    }
                    None => 0,
                };
                self.list_state.select(Some(i));
            }
            Focus::Sidebar => {
                let len = self.get_sidebar_len();
                if len == 0 {
                    return;
                }
                let i = match self.cal_state.selected() {
                    Some(i) => {
                        if i >= len - 1 {
                            0
                        } else {
                            i + 1
                        }
                    }
                    None => 0,
                };
                self.cal_state.select(Some(i));
            }
        }
    }
    pub fn previous(&mut self) {
        match self.active_focus {
            Focus::Main => {
                if self.tasks.is_empty() {
                    return;
                }
                let i = match self.list_state.selected() {
                    Some(i) => {
                        if i == 0 {
                            self.tasks.len() - 1
                        } else {
                            i - 1
                        }
                    }
                    None => 0,
                };
                self.list_state.select(Some(i));
            }
            Focus::Sidebar => {
                let len = self.get_sidebar_len();
                if len == 0 {
                    return;
                }
                let i = match self.cal_state.selected() {
                    Some(i) => {
                        if i == 0 {
                            len - 1
                        } else {
                            i - 1
                        }
                    }
                    None => 0,
                };
                self.cal_state.select(Some(i));
            }
        }
    }
    pub fn jump_forward(&mut self, step: usize) {
        match self.active_focus {
            Focus::Main => {
                if !self.tasks.is_empty() {
                    let current = self.list_state.selected().unwrap_or(0);
                    self.list_state
                        .select(Some((current + step).min(self.tasks.len() - 1)));
                }
            }
            Focus::Sidebar => {
                let len = self.get_sidebar_len();
                if len > 0 {
                    let current = self.cal_state.selected().unwrap_or(0);
                    self.cal_state.select(Some((current + step).min(len - 1)));
                }
            }
        }
    }
    pub fn jump_backward(&mut self, step: usize) {
        match self.active_focus {
            Focus::Main => {
                if !self.tasks.is_empty() {
                    let current = self.list_state.selected().unwrap_or(0);
                    self.list_state.select(Some(current.saturating_sub(step)));
                }
            }
            Focus::Sidebar => {
                let len = self.get_sidebar_len();
                if len > 0 {
                    let current = self.cal_state.selected().unwrap_or(0);
                    self.cal_state.select(Some(current.saturating_sub(step)));
                }
            }
        }
    }
    pub fn toggle_focus(&mut self) {
        self.active_focus = match self.active_focus {
            Focus::Main => Focus::Sidebar,
            Focus::Sidebar => Focus::Main,
        }
    }
    pub fn next_move_target(&mut self) {
        if self.move_targets.is_empty() {
            return;
        }
        let i = match self.move_selection_state.selected() {
            Some(i) => {
                if i >= self.move_targets.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.move_selection_state.select(Some(i));
    }

    pub fn previous_move_target(&mut self) {
        if self.move_targets.is_empty() {
            return;
        }
        let i = match self.move_selection_state.selected() {
            Some(i) => {
                if i == 0 {
                    self.move_targets.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.move_selection_state.select(Some(i));
    }
    pub fn next_export_source(&mut self) {
        if self.export_source_calendars.is_empty() {
            return;
        }
        let i = match self.export_source_selection_state.selected() {
            Some(i) => {
                if i >= self.export_source_calendars.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.export_source_selection_state.select(Some(i));
    }

    pub fn previous_export_source(&mut self) {
        if self.export_source_calendars.is_empty() {
            return;
        }
        let i = match self.export_source_selection_state.selected() {
            Some(i) => {
                if i == 0 {
                    self.export_source_calendars.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.export_source_selection_state.select(Some(i));
    }

    pub fn next_export_target(&mut self) {
        if self.export_targets.is_empty() {
            return;
        }
        let i = match self.export_selection_state.selected() {
            Some(i) => {
                if i >= self.export_targets.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.export_selection_state.select(Some(i));
    }

    pub fn previous_export_target(&mut self) {
        if self.export_targets.is_empty() {
            return;
        }
        let i = match self.export_selection_state.selected() {
            Some(i) => {
                if i == 0 {
                    self.export_targets.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.export_selection_state.select(Some(i));
    }
}

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

    fn dummy_task() -> Task {
        Task::new("test", &HashMap::new(), None)
    }

    #[test]
    fn test_navigation_next_wraps() {
        let mut state = AppState::new();
        // Add 3 dummy tasks
        state.tasks = vec![
            TaskListItem::Task(Box::new(dummy_task())),
            TaskListItem::Task(Box::new(dummy_task())),
            TaskListItem::Task(Box::new(dummy_task())),
        ];

        // Start at 0
        state.list_state.select(Some(0));

        state.next(); // 1
        assert_eq!(state.list_state.selected(), Some(1));

        state.next(); // 2
        assert_eq!(state.list_state.selected(), Some(2));

        state.next(); // Wrap to 0
        assert_eq!(state.list_state.selected(), Some(0));
    }

    #[test]
    fn test_navigation_previous_wraps() {
        let mut state = AppState::new();
        state.tasks = vec![
            TaskListItem::Task(Box::new(dummy_task())),
            TaskListItem::Task(Box::new(dummy_task())),
            TaskListItem::Task(Box::new(dummy_task())),
        ];

        state.list_state.select(Some(0));

        state.previous(); // Wrap to last (2)
        assert_eq!(state.list_state.selected(), Some(2));

        state.previous(); // 1
        assert_eq!(state.list_state.selected(), Some(1));
    }

    #[test]
    fn test_navigation_empty_list_safety() {
        let mut state = AppState::new();
        state.tasks = vec![]; // Empty

        // Should not panic
        state.next();
        state.previous();

        // Selection should stay None or safe default, but definitely no panic
    }

    #[test]
    fn test_cursor_clamping() {
        let mut state = AppState::new();
        state.input_buffer = "abc".to_string(); // len 3
        state.cursor_position = 0;

        state.move_cursor_right(); // 1
        state.move_cursor_right(); // 2
        state.move_cursor_right(); // 3 (after 'c')
        state.move_cursor_right(); // Should stay 3

        assert_eq!(state.cursor_position, 3);

        state.move_cursor_left(); // 2
        state.move_cursor_left(); // 1
        state.move_cursor_left(); // 0
        state.move_cursor_left(); // Should stay 0

        assert_eq!(state.cursor_position, 0);
    }
}