1use std::time::{Duration, Instant};
2
3use anyhow::Result;
4use crossterm::event::KeyModifiers;
5use ratatui::widgets::ListState;
6
7use crate::db::Database;
8use crate::model::{
9 AppData, EmptyQueueBehavior, EstimateCompleteBehavior, Priority, StoredSession, TimerMode,
10 TimerState,
11};
12use crate::sound;
13use crate::storage;
14use crate::timer::{Timer, TimerConfig};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum FocusTab {
18 Dashboard,
19 Tasks,
20 Stats,
21 Settings,
22 Help,
23}
24
25impl FocusTab {
26 pub const fn all() -> [FocusTab; 5] {
27 [
28 FocusTab::Dashboard,
29 FocusTab::Tasks,
30 FocusTab::Stats,
31 FocusTab::Settings,
32 FocusTab::Help,
33 ]
34 }
35 pub fn label(&self) -> &'static str {
36 match self {
37 FocusTab::Dashboard => "Dashboard",
38 FocusTab::Tasks => "Tasks",
39 FocusTab::Stats => "Stats",
40 FocusTab::Settings => "Settings",
41 FocusTab::Help => "Help",
42 }
43 }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum InputMode {
48 Normal,
49 Editing,
50}
51
52#[derive(Debug, Clone)]
53pub enum Popup {
54 AddTask,
55 EditTask(u64),
56 ConfirmDelete(u64),
57 EmptyQueueChoice,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum InputField {
62 Title,
63 Notes,
64 Estimate,
65 Priority,
66 DueDate,
67 Tags,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum TaskFilter {
72 All,
73 Pending,
74 Done,
75 Today,
76}
77
78impl TaskFilter {
79 pub fn label(&self) -> &'static str {
80 match self {
81 TaskFilter::All => "All",
82 TaskFilter::Pending => "Open",
83 TaskFilter::Done => "Done",
84 TaskFilter::Today => "Today",
85 }
86 }
87
88 pub fn next(self) -> Self {
89 match self {
90 TaskFilter::All => TaskFilter::Pending,
91 TaskFilter::Pending => TaskFilter::Done,
92 TaskFilter::Done => TaskFilter::Today,
93 TaskFilter::Today => TaskFilter::All,
94 }
95 }
96}
97
98use crate::ui::{IconMode, IconSet};
99
100pub mod theme;
101pub use theme::*;
102
103pub mod settings;
104pub use settings::*;
105pub mod keys;
106pub mod popups;
107pub mod task_ops;
108pub mod timer_ops;
109
110pub struct App {
111 pub db: Database,
112 pub data: AppData,
113 pub timer: Timer,
114 pub tab: FocusTab,
115 pub input_mode: InputMode,
116 pub input_buffer: String,
117 pub input_buffer2: String,
118 pub input_due_date: String,
119 pub input_tags: String,
120 pub input_number: u32,
121 pub input_priority: Priority,
122 pub input_field: InputField,
123 pub popup: Option<Popup>,
124 pub task_state: ListState,
125 pub settings_state: SettingsState,
126 pub status: Option<String>,
127 pub status_error: bool,
128 pub last_status_set: Instant,
129 pub should_quit: bool,
130 pub theme: Theme,
131 pub icons: IconSet,
132 pub active_task: Option<u64>,
133 pub zen_mode: bool,
134 pub task_filter: TaskFilter,
135 pub active_tag_filter: Option<String>,
136 pub task_search: String,
137 pub searching: bool,
138 pub weekly_chart: Vec<(String, u32)>,
139 pub heatmap_data: Vec<(String, u32)>,
140 pub session_counts: (u32, u32, u32),
141 pub chart_dirty: bool,
142 pub data_version: u64,
143 pub recent_sessions: Vec<StoredSession>,
144 pub stats_session_selected: usize,
145 pub dashboard_task_selected: usize,
146 pub calendar_date: chrono::NaiveDate,
147}
148
149impl App {
150 pub fn new() -> Result<Self> {
151 let db = Database::open()?;
152 let mut data = db.load_app_data().unwrap_or_default();
153 let _ = storage::ensure_today_reset(&db, &mut data);
154 let config = TimerConfig::from_app_data(&data);
155 let mut timer = Timer::new(config);
156 let (completed, mode) = db.load_timer_state();
157 timer.completed_focus_sessions = completed;
158 timer.configure(mode);
159 let recent_sessions = db.recent_sessions(15).unwrap_or_default();
160 let mut task_state = ListState::default();
161 if !data.tasks.is_empty() {
162 task_state.select(Some(0));
163 }
164 let weekly_chart = storage::minutes_by_date(&db, 7).unwrap_or_default();
165 let heatmap_data = storage::focus_heatmap(&db).unwrap_or_default();
166 let session_counts = db.session_counts_by_mode().unwrap_or((0, 0, 0));
167 let theme = Theme::from_variant(data.theme);
168 let icons = IconSet::detect();
169 let active_task = data.active_task_id.filter(|id| {
170 data.tasks
171 .iter()
172 .find(|t| t.id == *id)
173 .is_some_and(|t| t.status != crate::model::TaskStatus::Done)
174 });
175 if active_task != data.active_task_id {
176 data.active_task_id = active_task;
177 }
178 let welcome = match icons.mode() {
179 IconMode::Ascii => {
180 "Welcome to Void! Using text icons (set VOID_USE_NERD_FONTS=1 if your terminal has a Nerd Font)."
181 }
182 IconMode::Nerd => "Welcome to Void! Press 5 or 'h' for help.",
183 };
184 Ok(Self {
185 db,
186 data,
187 timer,
188 tab: FocusTab::Dashboard,
189 input_mode: InputMode::Normal,
190 input_buffer: String::new(),
191 input_buffer2: String::new(),
192 input_due_date: String::new(),
193 input_tags: String::new(),
194 input_number: 25,
195 input_priority: Priority::Medium,
196 input_field: InputField::Title,
197 popup: None,
198 task_state,
199 settings_state: SettingsState::new(),
200 status: Some(welcome.into()),
201 status_error: false,
202 last_status_set: Instant::now(),
203 should_quit: false,
204 theme,
205 icons,
206 active_task,
207 zen_mode: false,
208 task_filter: TaskFilter::All,
209 active_tag_filter: None,
210 task_search: String::new(),
211 searching: false,
212 weekly_chart,
213 heatmap_data,
214 session_counts,
215 chart_dirty: false,
216 data_version: 0,
217 recent_sessions,
218 stats_session_selected: 0,
219 dashboard_task_selected: 0,
220 calendar_date: chrono::Local::now().date_naive(),
221 })
222 }
223
224 pub fn queue_empty(&self) -> bool {
225 storage::queue_empty(&self.data)
226 }
227
228 pub fn daily_goal_met(&self) -> bool {
229 storage::today_focus_minutes(&self.data) >= self.data.daily_goal_minutes
230 }
231
232 fn persist_timer_state(&mut self) {
233 let completed = self.timer.completed_focus_sessions;
234 let mode = self.timer.mode;
235 self.persist(|db| db.persist_timer_state(completed, mode));
236 }
237
238 fn refresh_recent_sessions(&mut self) {
239 match self.db.recent_sessions(15) {
240 Ok(sessions) => self.recent_sessions = sessions,
241 Err(e) => self.set_status(format!("Error loading sessions: {e}"), true),
242 }
243 if self.stats_session_selected >= self.recent_sessions.len() {
244 self.stats_session_selected = self.recent_sessions.len().saturating_sub(1);
245 }
246 }
247
248 pub fn tick_rate(&self) -> Duration {
249 match self.timer.state {
250 TimerState::Running => Duration::from_millis(50),
251 TimerState::Paused => Duration::from_millis(100),
252 TimerState::Idle => Duration::from_millis(100),
253 _ => Duration::from_millis(200),
254 }
255 }
256
257 pub fn window_title(&self) -> String {
258 let (main, tenths, _) = crate::canvas_timer::format_time_stack(&self.timer);
259 let state = match self.timer.state {
260 TimerState::Running => self.icons.play,
261 TimerState::Paused => self.icons.pause,
262 TimerState::Finished => self.icons.check,
263 TimerState::Idle => self.icons.idle,
264 };
265 format!(
266 "Void {} {}{} · {}",
267 state,
268 main,
269 tenths,
270 self.timer.mode.label()
271 )
272 }
273
274 pub fn bump_data(&mut self) {
275 self.data_version = self.data_version.wrapping_add(1);
276 self.chart_dirty = true;
277 self.refresh_recent_sessions();
278 self.clamp_dashboard_task_selection();
279 }
280
281 fn persist<F>(&mut self, op: F)
282 where
283 F: FnOnce(&Database) -> anyhow::Result<()>,
284 {
285 if let Err(e) = op(&self.db) {
286 self.set_status(format!("Save error: {e}"), true);
287 }
288 }
289
290 fn persist_data<F>(&mut self, op: F)
291 where
292 F: FnOnce(&Database, &mut AppData) -> anyhow::Result<()>,
293 {
294 if let Err(e) = op(&self.db, &mut self.data) {
295 self.set_status(format!("Save error: {e}"), true);
296 }
297 }
298
299 fn persist_setting(&mut self, key: &str, value: impl AsRef<str>) {
300 self.persist(|db| db.set_setting(key, value.as_ref()));
301 }
302
303 pub fn refresh_chart_if_needed(&mut self) {
304 if self.chart_dirty {
305 match storage::minutes_by_date(&self.db, 7) {
306 Ok(data) => self.weekly_chart = data,
307 Err(e) => self.set_status(format!("Chart error: {e}"), true),
308 }
309 match storage::focus_heatmap(&self.db) {
310 Ok(data) => self.heatmap_data = data,
311 Err(e) => self.set_status(format!("Heatmap error: {e}"), true),
312 }
313 match self.db.session_counts_by_mode() {
314 Ok(counts) => self.session_counts = counts,
315 Err(e) => self.set_status(format!("Stats error: {e}"), true),
316 }
317 self.chart_dirty = false;
318 }
319 }
320
321 pub fn reload_heatmap(&mut self) {
322 if let Ok(data) = storage::focus_heatmap(&self.db) {
323 self.heatmap_data = data;
324 }
325 }
326
327 fn sync_timer_config_to_data(&mut self) {
328 self.data.focus_minutes = self.timer.config.focus_minutes;
329 self.data.short_break_minutes = self.timer.config.short_break_minutes;
330 self.data.long_break_minutes = self.timer.config.long_break_minutes;
331 self.data.long_break_every = self.timer.config.long_break_every;
332 }
333
334 fn elapsed_minutes(&self, skipped: bool) -> u32 {
335 let secs = self.timer.current_elapsed_seconds();
336 if skipped {
337 secs.div_ceil(60).max(1)
338 } else {
339 (secs / 60).max(1)
340 }
341 }
342
343 pub fn hint(&self) -> String {
344 match self.tab {
345 FocusTab::Dashboard => "[j/k]tasks [f]ocus [Enter]status [x]done [s]tart [z]zen".into(),
346 FocusTab::Tasks => {
347 "[f]ocus [a]dd [e]dit [d]el [Enter]status [t]oday [g]filter [/]search".into()
348 }
349 FocusTab::Stats => "[j/k] sessions [d] delete [+/-] minutes [E] end session".into(),
350 FocusTab::Settings => "[↑↓] nav [Enter] toggle/export [-/+] change values".into(),
351 FocusTab::Help => "Press Tab or 1-5 to leave help".into(),
352 }
353 }
354
355 pub fn set_status(&mut self, msg: impl Into<String>, error: bool) {
356 self.status = Some(msg.into());
357 self.status_error = error;
358 self.last_status_set = Instant::now();
359 }
360
361 fn check_queue_empty(&mut self) {
362 if self.queue_empty() {
363 self.on_queue_empty();
364 }
365 }
366
367 fn on_queue_empty(&mut self) {
368 match self.data.empty_queue_behavior {
369 EmptyQueueBehavior::FreeFocus => {
370 self.set_status(
371 "All tasks done — free focus. Sessions log as general focus. [E] end session",
372 false,
373 );
374 }
375 EmptyQueueBehavior::PauseTimer => {
376 if self.timer.state == TimerState::Running {
377 self.pause_timer();
378 } else if self.timer.state != TimerState::Paused {
379 self.timer.reset();
380 }
381 self.set_status("All tasks done — timer paused. [E] end session", false);
382 }
383 EmptyQueueBehavior::AskEachTime => {
384 self.popup = Some(Popup::EmptyQueueChoice);
385 self.set_status(
386 "All tasks done — [Enter] free focus [p] pause [a] add task",
387 false,
388 );
389 }
390 }
391 }
392
393 pub fn export_backup(&mut self) {
394 match self.db.export_json() {
395 Ok(path) => self.set_status(format!("Exported backup to {}", path.display()), false),
396 Err(e) => self.set_status(format!("Export failed: {e}"), true),
397 }
398 }
399
400 pub fn open_add_task(&mut self) {
401 self.input_buffer.clear();
402 self.input_buffer2.clear();
403 self.input_due_date.clear();
404 self.input_tags.clear();
405 self.input_number = 25;
406 self.input_priority = Priority::Medium;
407 self.input_field = InputField::Title;
408 self.popup = Some(Popup::AddTask);
409 self.input_mode = InputMode::Editing;
410 }
411
412 pub fn open_edit_task(&mut self) {
413 let Some(id) = self.selected_task_id() else {
414 self.set_status("No task selected.", true);
415 return;
416 };
417 if let Some(t) = self.data.tasks.iter().find(|t| t.id == id).cloned() {
418 self.input_buffer = t.title;
419 self.input_buffer2 = t.notes;
420 self.input_due_date = t.due_date.unwrap_or_default();
421 self.input_tags = t.tags.join(", ");
422 self.input_number = t.estimated_minutes;
423 self.input_priority = t.priority;
424 self.input_field = InputField::Title;
425 self.popup = Some(Popup::EditTask(id));
426 self.input_mode = InputMode::Editing;
427 }
428 }
429
430 pub fn open_confirm_delete(&mut self) {
431 if let Some(id) = self.selected_task_id() {
432 self.popup = Some(Popup::ConfirmDelete(id));
433 } else {
434 self.set_status("No task to delete.", true);
435 }
436 }
437
438 fn popup_due_date(&self) -> Result<Option<String>, String> {
439 let allow_past = matches!(self.popup, Some(crate::app::Popup::EditTask(_)));
440 storage::normalize_due_date(&self.input_due_date, allow_past)
441 }
442
443 pub fn cycle_tag_filter(&mut self) {
444 let mut tags: Vec<String> = self
445 .data
446 .tasks
447 .iter()
448 .flat_map(|t| t.tags.clone())
449 .collect();
450 tags.sort();
451 tags.dedup();
452
453 if tags.is_empty() {
454 self.set_status("No tags available to filter.", true);
455 return;
456 }
457
458 self.active_tag_filter = match &self.active_tag_filter {
459 None => Some(tags[0].clone()),
460 Some(current) => {
461 if let Some(idx) = tags.iter().position(|t| t == current) {
462 if idx + 1 < tags.len() {
463 Some(tags[idx + 1].clone())
464 } else {
465 None
466 }
467 } else {
468 None
469 }
470 }
471 };
472
473 let msg = match &self.active_tag_filter {
474 Some(t) => format!("Filtered by tag: #{}", t),
475 None => "Tag filter cleared.".to_string(),
476 };
477 self.set_status(msg, false);
478
479 self.clamp_dashboard_task_selection();
480 let len = self.filtered_task_indices().len();
481 if len == 0 {
482 self.task_state.select(None);
483 } else {
484 let sel = self.task_state.selected().unwrap_or(0).min(len - 1);
485 self.task_state.select(Some(sel));
486 }
487 }
488
489 fn popup_tags(&self) -> Vec<String> {
490 storage::parse_tags(&self.input_tags)
491 }
492
493 pub fn selected_task_id(&self) -> Option<u64> {
494 let indices = self.filtered_task_indices();
495 self.task_state
496 .selected()
497 .and_then(|i| indices.get(i).copied())
498 .and_then(|idx| self.data.tasks.get(idx).map(|t| t.id))
499 }
500}