cfait 1.1.8

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
// SPDX-License-Identifier: GPL-3.0-or-later
// Handles event subscriptions (keyboard, window) for the GUI.
use crate::gui::message::Message;
use crate::gui::state::{AppState, Focus, GuiApp, SidebarMode};
use iced::{Subscription, event, keyboard, window};
use std::sync::atomic::{AtomicBool, Ordering};

pub static LAST_MOUSE_POS: std::sync::LazyLock<std::sync::RwLock<iced::Point>> =
    std::sync::LazyLock::new(|| std::sync::RwLock::new(iced::Point::new(0.0, 0.0)));

// Tracks the Command/Ctrl modifier state statelessly so Mouse events can check it
static CMD_HELD: AtomicBool = AtomicBool::new(false);

/// Whether Ctrl (or Cmd on macOS) is currently held, for mouse-click shortcuts.
pub fn cmd_held() -> bool {
    CMD_HELD.load(Ordering::Relaxed)
}

// Tracks the current focus statelessly so keyboard event handlers can check it
pub static ACTIVE_FOCUS: std::sync::LazyLock<std::sync::RwLock<Focus>> =
    std::sync::LazyLock::new(|| std::sync::RwLock::new(Focus::default()));

/// Maps a digit character (1-5) to the corresponding sidebar tab message.
/// Uses `modified_key` (the logical character with modifiers like Shift applied,
/// except Ctrl) so it matches the character the user actually typed on their
/// layout — e.g. on programmer Dvorak, "1" is Shift+key, and this still matches.
fn digit_sidebar_message(modified_key: &keyboard::Key) -> Option<Message> {
    let s = match modified_key.as_ref() {
        keyboard::Key::Character(s) => s,
        _ => return None,
    };
    let mode = match s {
        "1" => SidebarMode::Calendars,
        "2" => SidebarMode::Categories,
        "3" => SidebarMode::Locations,
        "4" => SidebarMode::Goals,
        "5" => SidebarMode::Journal,
        _ => return None,
    };
    Some(Message::SidebarModeChanged(mode))
}

pub fn subscription(app: &GuiApp) -> Subscription<Message> {
    let mut subs = Vec::new();

    // Start background syncing worker
    subs.push(crate::gui::async_ops::worker_subscription(app.ctx.clone()));

    match app.state {
        AppState::Active => {
            // Use a static function to handle hotkeys so we don't capture `app`
            // This avoids the "expected fn pointer, found closure" error
            subs.push(event::listen_with(handle_hotkey));
        }
        AppState::Help(_, _) => {
            subs.push(event::listen_with(handle_help_hotkey));
        }
        AppState::Settings => {
            subs.push(event::listen_with(handle_settings_hotkey));
        }
        AppState::Onboarding => {
            subs.push(event::listen_with(handle_onboarding_hotkey));
        }
        _ => {}
    }

    // Track window metrics
    subs.push(event::listen_with(|evt, _status, _window_id| match evt {
        iced::Event::Window(window::Event::Resized(size)) => Some(Message::WindowResized(size)),
        iced::Event::Window(window::Event::Focused) => Some(Message::WindowFocused(true)),
        iced::Event::Window(window::Event::Unfocused) => Some(Message::WindowFocused(false)),
        _ => None,
    }));

    // Auto-refresh subscription (configurable)
    if app.auto_refresh_interval_mins > 0 {
        subs.push(
            iced::time::every(std::time::Duration::from_secs(
                app.auto_refresh_interval_mins as u64 * 60,
            ))
            .map(|_| Message::Refresh),
        );
    }

    // Tick every minute if there is an active task running, so the timer updates visually
    let has_running_tasks = app.tasks.iter().any(|item| {
        if let crate::store::TaskListItem::Task(t) = item {
            t.last_started_at.is_some()
        } else {
            false
        }
    });
    if has_running_tasks {
        subs.push(iced::time::every(std::time::Duration::from_secs(60)).map(|_| Message::Tick));
    }

    Subscription::batch(subs)
}

fn handle_settings_hotkey(
    evt: iced::Event,
    _status: iced::event::Status,
    _id: iced::window::Id,
) -> Option<Message> {
    if let iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = evt {
        match key.as_ref() {
            keyboard::Key::Named(keyboard::key::Named::Tab) => {
                Some(Message::CycleFocus(!modifiers.shift()))
            }
            keyboard::Key::Named(keyboard::key::Named::Escape) => Some(Message::CancelSettings),
            _ => None,
        }
    } else {
        None
    }
}

fn handle_onboarding_hotkey(
    evt: iced::Event,
    _status: iced::event::Status,
    _id: iced::window::Id,
) -> Option<Message> {
    if let iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = evt {
        match key.as_ref() {
            keyboard::Key::Named(keyboard::key::Named::Tab) => {
                Some(Message::CycleFocus(!modifiers.shift()))
            }
            _ => None,
        }
    } else {
        None
    }
}

fn handle_help_hotkey(
    evt: iced::Event,
    status: iced::event::Status,
    _id: iced::window::Id,
) -> Option<Message> {
    if status == iced::event::Status::Captured {
        return None;
    }
    if let iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = evt {
        match key.as_ref() {
            keyboard::Key::Named(keyboard::key::Named::Escape) => Some(Message::CloseHelp),
            keyboard::Key::Named(keyboard::key::Named::Tab) => {
                Some(Message::SwitchHelpTab(!modifiers.shift()))
            }
            keyboard::Key::Named(keyboard::key::Named::ArrowRight) => {
                Some(Message::SwitchHelpTab(true))
            }
            keyboard::Key::Named(keyboard::key::Named::ArrowLeft) => {
                Some(Message::SwitchHelpTab(false))
            }
            keyboard::Key::Character(s) if s == "q" || s == "?" || s == "/" => {
                Some(Message::CloseHelp)
            }
            keyboard::Key::Character("l") => Some(Message::SwitchHelpTab(true)),
            keyboard::Key::Character("h") => Some(Message::SwitchHelpTab(false)),
            _ => None,
        }
    } else {
        None
    }
}

fn handle_hotkey(
    evt: iced::Event,
    status: iced::event::Status,
    _id: iced::window::Id,
) -> Option<Message> {
    use iced::keyboard::key::Named;

    // Track modifier state globally for mouse events
    if let iced::Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = &evt {
        CMD_HELD.store(
            modifiers.control() || modifiers.command(),
            Ordering::Relaxed,
        );
    }

    if let iced::Event::Mouse(iced::mouse::Event::CursorMoved { position }) = &evt
        && let Ok(mut pos) = LAST_MOUSE_POS.write()
    {
        *pos = *position;
    }

    // Handle Ctrl + Scroll (Zoom In/Out)
    if let iced::Event::Mouse(iced::mouse::Event::WheelScrolled { delta }) = &evt
        && CMD_HELD.load(Ordering::Relaxed)
    {
        match delta {
            iced::mouse::ScrollDelta::Lines { y, .. }
            | iced::mouse::ScrollDelta::Pixels { y, .. } => {
                if *y > 0.0 {
                    return Some(Message::ZoomIn);
                } else if *y < 0.0 {
                    return Some(Message::ZoomOut);
                }
            }
        }
    }

    // Handle Ctrl + Middle Click (Zoom Reset)
    if let iced::Event::Mouse(iced::mouse::Event::ButtonPressed(iced::mouse::Button::Middle)) = &evt
        && CMD_HELD.load(Ordering::Relaxed)
    {
        return Some(Message::ZoomReset);
    }

    // Allow certain keys to bypass capture (e.g. Escape to unfocus, Ctrl+S to save)
    if status == iced::event::Status::Captured {
        if let iced::Event::Keyboard(keyboard::Event::KeyPressed {
            key,
            modifiers,
            modified_key,
            ..
        }) = &evt
        {
            if *key == keyboard::Key::Named(Named::Escape) {
                return Some(Message::EscCaptured);
            }
            let is_cmd = modifiers.control() || modifiers.command();
            if is_cmd && let keyboard::Key::Character(s) = key.as_ref() {
                match s.to_lowercase().as_str() {
                    "s" => {
                        if modifiers.shift() {
                            return Some(Message::SaveTaskKeepEditing);
                        } else {
                            return Some(Message::SubmitTask);
                        }
                    }
                    "n" => return Some(Message::StartCreateWithDescription),
                    "e" => return Some(Message::KeyboardEditTree),
                    "," => return Some(Message::OpenSettings),
                    "z" => {
                        if modifiers.shift() {
                            return Some(Message::Redo);
                        } else {
                            return Some(Message::Undo);
                        }
                    }
                    "y" => return Some(Message::Redo),
                    _ => {}
                }
            }

            // Ctrl/Cmd + digit: switch sidebar tab by logical character
            // (matches the typed digit on any layout; works even from a text field)
            if is_cmd && let Some(msg) = digit_sidebar_message(modified_key) {
                return Some(msg);
            }

            // If we are definitely not in a text input, steal navigation keys back from Iced's Scrollables/Buttons.
            // Only Named keys belong here: scrollables/buttons capture arrows, enter, and space,
            // but never character keys. Character keys in this block would only ever be stolen
            // from text editors/inputs (which capture them), which is a bug.
            if let Ok(focus) = ACTIVE_FOCUS.read()
                && (*focus == Focus::MainList || *focus == Focus::Sidebar)
            {
                match key.as_ref() {
                    keyboard::Key::Named(Named::ArrowDown) => return Some(Message::SelectNext),
                    keyboard::Key::Named(Named::ArrowUp) => return Some(Message::SelectPrev),
                    keyboard::Key::Named(Named::ArrowRight) => return Some(Message::ArrowRight),
                    keyboard::Key::Named(Named::ArrowLeft) => return Some(Message::ArrowLeft),
                    keyboard::Key::Named(Named::Enter) => return Some(Message::EnterPressed),
                    keyboard::Key::Named(Named::Space) => {
                        if modifiers.shift() {
                            return Some(Message::ShiftSpaceSelected);
                        } else {
                            return Some(Message::ToggleSelected);
                        }
                    }
                    _ => {}
                }
            }
        }
        return None;
    }

    if let iced::Event::Keyboard(keyboard::Event::KeyPressed {
        key,
        modifiers,
        modified_key,
        ..
    }) = evt
    {
        // Catch zoom shortcuts and other modifiers BEFORE we ignore modifier combinations.
        let is_cmd = modifiers.command() || modifiers.control();

        if is_cmd {
            if let keyboard::Key::Character(s) = key.as_ref() {
                match s.to_lowercase().as_str() {
                    "+" | "=" => return Some(Message::ZoomIn),
                    "-" => return Some(Message::ZoomOut),
                    "0" => return Some(Message::ZoomReset),
                    "b" => return Some(Message::ToggleSidebar),
                    "d" => return Some(Message::KeyboardDuplicateTask),
                    "s" => {
                        if modifiers.shift() {
                            return Some(Message::SaveTaskKeepEditing);
                        } else {
                            return Some(Message::SubmitTask);
                        }
                    }
                    "n" => return Some(Message::StartCreateWithDescription),
                    "e" => {
                        if let Ok(focus) = ACTIVE_FOCUS.read()
                            && *focus == Focus::AddTaskInput
                        {
                            return Some(Message::StartCreateWithDescription);
                        }
                        return Some(Message::KeyboardEditTree);
                    }
                    "m" => return Some(Message::ToggleEditorMaximize),
                    "," => return Some(Message::OpenSettings),
                    "p" => return Some(Message::ToggleSortStandardByPriorityToggle),
                    "z" => {
                        if modifiers.shift() {
                            return Some(Message::Redo);
                        } else {
                            return Some(Message::Undo);
                        }
                    }
                    "y" => return Some(Message::Redo),
                    _ => {}
                }
            } else if let keyboard::Key::Named(Named::Delete) = key.as_ref() {
                return Some(Message::KeyboardDeleteTaskTree);
            }

            // Ctrl/Cmd + digit: switch sidebar tab by logical character
            // (matches the typed digit on any layout; works even from a text field)
            if let Some(msg) = digit_sidebar_message(&modified_key) {
                return Some(msg);
            }
        }

        // Ignore if Ctrl/Alt/Cmd is held for everything else
        if modifiers.command() || modifiers.control() || modifiers.alt() {
            return None;
        }

        // Bare digit: switch sidebar tab by logical character (matches the typed
        // digit on any layout, e.g. Shift+key on programmer Dvorak)
        if let Some(msg) = digit_sidebar_message(&modified_key) {
            return Some(msg);
        }

        match key.as_ref() {
            // 1. Handle character-based keys first
            keyboard::Key::Character(s) => {
                let s_lower = s.to_lowercase();
                // Match on lowercase char + shift state tuple for alphabetic keys
                match (s_lower.as_ref(), modifiers.shift()) {
                    ("j", false) => Some(Message::SelectNext),
                    ("k", false) => Some(Message::SelectPrev),
                    ("e", false) => Some(Message::EditSelected),
                    ("e", true) => Some(Message::EditSelectedDescription),
                    ("s", false) => Some(Message::ToggleActiveSelected),
                    ("s", true) => Some(Message::StopSelected),
                    ("x", false) => Some(Message::CancelSelected),
                    ("y", false) => Some(Message::YankSelected),
                    ("y", true) => Some(Message::ToggleYankLock),
                    ("f", false) => Some(Message::FocusSelected),
                    ("c", false) => Some(Message::KeyboardLinkChild),
                    ("c", true) => Some(Message::KeyboardCreateChild),
                    ("t", false) => Some(Message::KeyboardAddSession),
                    ("t", true) => Some(Message::KeyboardToggleSessions),
                    ("b", false) => Some(Message::KeyboardAddDependency),
                    ("l", false) => Some(Message::KeyboardAddRelation),
                    ("l", true) => Some(Message::KeyboardToggleDetails),
                    ("g", false) => Some(Message::KeyboardOpenLocations),
                    ("o", false) => Some(Message::KeyboardOpenUrl),
                    ("a", false) => Some(Message::FocusInput),
                    ("h", true) => Some(Message::ToggleHideCompletedToggle),
                    ("m", false) => Some(Message::CategoryMatchModeToggle),
                    ("m", true) => Some(Message::MoveSelected),
                    ("z", false) => Some(Message::KeyboardToggleTreeCollapse),
                    ("q", false) => Some(Message::CloseWindow),
                    ("w", false) => Some(Message::ToggleQuickFilter),
                    ("r", false) => Some(Message::Refresh),
                    ("r", true) => Some(Message::JumpToRandomTask),

                    ("/", false) => Some(Message::FocusSearch),
                    ("/", true) => Some(Message::OpenHelp(crate::help::HelpTab::Shortcuts)),
                    ("?", _) => Some(Message::OpenHelp(crate::help::HelpTab::Shortcuts)),
                    // Fallback to match exact char for symbols
                    _ => match s {
                        "*" => Some(Message::ClearAllFilters),
                        "+" | "=" => Some(Message::ChangePrioritySelected(1)),
                        "-" => Some(Message::ChangePrioritySelected(-1)),
                        "." | ">" => Some(Message::DemoteSelected),
                        "," | "<" => Some(Message::PromoteSelected),
                        _ => None,
                    },
                }
            }

            // 2. Handle Named keys
            keyboard::Key::Named(Named::ArrowDown) => Some(Message::SelectNext),
            keyboard::Key::Named(Named::ArrowUp) => Some(Message::SelectPrev),
            keyboard::Key::Named(Named::ArrowRight) => Some(Message::ArrowRight),
            keyboard::Key::Named(Named::ArrowLeft) => Some(Message::ArrowLeft),
            keyboard::Key::Named(Named::PageDown) => Some(Message::SelectNextPage),
            keyboard::Key::Named(Named::PageUp) => Some(Message::SelectPrevPage),
            keyboard::Key::Named(Named::Enter) => Some(Message::EnterPressed),
            keyboard::Key::Named(Named::Space) => {
                if modifiers.shift() {
                    Some(Message::ShiftSpaceSelected)
                } else {
                    Some(Message::ToggleSelected)
                }
            }
            keyboard::Key::Named(Named::Escape) => Some(Message::EscapePressed),
            keyboard::Key::Named(Named::Delete) => {
                // Handled in is_cmd block for Ctrl+Delete, so here it's just Delete
                Some(Message::DeleteSelected)
            }
            keyboard::Key::Named(Named::Tab) => Some(Message::CycleFocus(!modifiers.shift())),

            _ => None,
        }
    } else {
        None
    }
}