kimun-notes 0.11.0

A terminal-based notes application
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
pub mod app;
pub mod app_screen;
pub mod cli;
pub mod components;
pub mod event_handler;
pub mod keys;
pub mod settings;
pub mod ui;

#[cfg(test)]
mod test_support;

use clap::Parser;
use color_eyre::Result;
use std::fs;
use std::path::{Path, PathBuf};

use tracing_subscriber::Layer;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::prelude::*;

#[derive(Parser)]
#[command(name = "kimun", about = "Kimün notes", version)]
struct Cli {
    /// Path to a custom config file
    #[arg(long, value_name = "FILE")]
    config: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<crate::cli::CliCommand>,
}

use crossterm::event::{
    DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, KeyboardEnhancementFlags,
    PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::terminal::{LeaveAlternateScreen, disable_raw_mode};
use ratatui::Terminal;
use ratatui::crossterm::event::EnableMouseCapture;
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{
    EnterAlternateScreen, enable_raw_mode, supports_keyboard_enhancement,
};
use ratatui::prelude::{Backend, CrosstermBackend};
use std::io;

use crate::app::App;
use crate::app_screen::browse::BrowseScreen;
use crate::app_screen::editor::EditorScreen;
use crate::app_screen::settings::SettingsScreen;
use crate::app_screen::start::StartScreen;
use crate::app_screen::{AppScreen, ScreenKind};
use crate::components::events::{AppEvent, AppTx, InputEvent, ScreenEvent};
use crate::event_handler::EventHandler;
use crate::keys::action_shortcuts::ActionShortcuts;
use crate::keys::key_event_to_combo;

/// Initialises file (and, in debug, stderr) logging.
///
/// Accepts `log_dir` as a parameter so it can be called from tests with a
/// controlled path. Returns `Some(guard)` on success; the caller must keep
/// the guard alive for the duration of the program. Returns `None` and prints
/// a warning to stderr on failure — startup is not aborted.
fn init_logging(log_dir: &Path) -> Option<tracing_appender::non_blocking::WorkerGuard> {
    if let Err(e) = fs::create_dir_all(log_dir) {
        eprintln!("kimun: could not create log directory: {e}");
        return None;
    }

    let log_path = log_dir.join("kimun.log");
    let file = match std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)
    {
        Ok(f) => f,
        Err(e) => {
            eprintln!("kimun: could not open log file: {e}");
            return None;
        }
    };

    let (writer, guard) = tracing_appender::non_blocking(file);

    #[cfg(debug_assertions)]
    let file_level_filter = LevelFilter::DEBUG;
    #[cfg(not(debug_assertions))]
    let file_level_filter = LevelFilter::WARN;

    let file_layer: Box<dyn Layer<tracing_subscriber::Registry> + Send + Sync> =
        tracing_subscriber::fmt::layer()
            .compact()
            .with_ansi(false)
            .with_writer(writer)
            .with_filter(file_level_filter)
            .boxed();

    // No stderr layer — writing to stderr corrupts the ratatui alternate screen.
    // Debug logs are captured in the log file at DEBUG level instead.
    let stderr_layer: Option<Box<dyn Layer<tracing_subscriber::Registry> + Send + Sync>> = None;

    let mut layers: Vec<Box<dyn Layer<tracing_subscriber::Registry> + Send + Sync>> =
        vec![file_layer];
    if let Some(s) = stderr_layer {
        layers.push(s);
    }

    // try_init instead of init so tests can call this without panicking on the
    // global-subscriber-already-set error.
    let _ = tracing_subscriber::registry().with(layers).try_init();

    // Forward log:: crate events into the tracing pipeline.
    tracing_log::LogTracer::init().ok();

    Some(guard)
}

// The nvim backend uses `tokio::task::block_in_place` during construction,
// which requires a multi-thread runtime. Keep this flavor explicit.
#[tokio::main(flavor = "multi_thread")]
async fn main() -> Result<()> {
    color_eyre::install()?;

    // Compute once, reuse for both init_logging and the panic hook.
    let log_dir: PathBuf = kimun_core::app_log_dir();
    // _guard declared early so it is dropped last (reverse declaration order).
    let _guard = init_logging(&log_dir);

    let log_path: PathBuf = log_dir.join("kimun.log");
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = crossterm::terminal::disable_raw_mode();
        let _ = crossterm::execute!(
            std::io::stderr(),
            crossterm::terminal::LeaveAlternateScreen,
            crossterm::event::DisableMouseCapture,
        );

        // Emit through tracing first (subscriber may still be active).
        tracing::error!("panic: {info}");

        // Direct fallback write — independent of the tracing subscriber.
        let parent = log_path.parent().unwrap_or(std::path::Path::new("."));
        let _ = fs::create_dir_all(parent);
        match std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
        {
            Ok(mut file) => {
                use std::io::Write;
                let _ = writeln!(file, "[PANIC] {info}");
                let bt = std::backtrace::Backtrace::force_capture();
                let _ = writeln!(file, "{bt}");
            }
            Err(e) => {
                eprintln!("kimun: could not write panic to log: {e}");
            }
        }

        default_hook(info);
    }));

    let cli = Cli::parse();

    if let Some(command) = cli.command {
        return crate::cli::run_cli(command, cli.config).await;
    }

    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(
        stdout,
        EnterAlternateScreen,
        EnableMouseCapture,
        EnableBracketedPaste
    )?;
    // Enable enhanced keyboard protocol when the terminal supports it (e.g. Kitty, WezTerm).
    // This is required to correctly receive F-keys and other special keys in those terminals.
    if supports_keyboard_enhancement().unwrap_or(false) {
        let _ = execute!(
            stdout,
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        );
    }
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;
    let mut events = EventHandler::new();
    let mut app = App::new(cli.config).await?;

    if let Err(e) = run_app(&mut terminal, &mut app, &mut events).await {
        tracing::error!("fatal error: {e}");
        return Err(e.into());
    }

    disable_raw_mode()?;
    let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture,
        DisableBracketedPaste
    )?;
    terminal.show_cursor()?;

    // Pin _guard liveness through end of scope, preventing NLL early-drop.
    let _ = &_guard;
    Ok(())
}

/// Build a fresh `NoteVault` for whatever workspace the settings currently
/// resolve to, wiring the configured cache path and the workspace's inbox
/// path. Returns `None` if no workspace is configured or the vault fails to
/// open.
async fn rebuild_vault(
    settings: &crate::settings::SharedSettings,
) -> Option<std::sync::Arc<kimun_core::NoteVault>> {
    let (workspace_path, cache_path, inbox_path) = {
        let s = settings.read().unwrap();
        let wp = s.resolve_workspace_path();
        let name = s.current_workspace_name();
        let cache = name.as_ref().map(|n| s.cache_path_for(n));
        let ip = s
            .workspace_config
            .as_ref()
            .and_then(|wc| wc.get_current_workspace())
            .map(|e| e.effective_inbox_path());
        (wp, cache, ip)
    };
    let workspace = workspace_path?;
    let mut config = kimun_core::VaultConfig::new(&workspace);
    if let Some(cp) = cache_path {
        config = config.with_db_path(cp);
    }
    kimun_core::NoteVault::new(config).await.ok().map(|mut v| {
        if let Some(ref ip) = inbox_path {
            v.set_inbox_path(kimun_core::nfs::VaultPath::new(ip));
        }
        std::sync::Arc::new(v)
    })
}

async fn switch_screen(app: &mut App, tx: &AppTx, new_screen: ScreenEvent) {
    if let Some(current) = app.current_screen.as_mut() {
        current.on_exit(tx).await;
    }

    let mut screen: Box<dyn AppScreen> = match new_screen {
        ScreenEvent::Start => Box::new(StartScreen::new(app.settings.clone(), app.vault.clone())),
        ScreenEvent::OpenSettings => Box::new(SettingsScreen::new(app.settings.clone())),
        ScreenEvent::OpenSettingsWithError(msg) => {
            Box::new(SettingsScreen::new_with_error(app.settings.clone(), msg))
        }
        ScreenEvent::OpenEditor(note_vault, vault_path) => Box::new(EditorScreen::new(
            note_vault,
            vault_path,
            app.settings.clone(),
        )),
        ScreenEvent::OpenBrowse(note_vault, vault_path) => Box::new(BrowseScreen::new(
            note_vault,
            vault_path,
            app.settings.clone(),
        )),
    };

    screen.on_enter(tx).await;
    app.current_screen = Some(screen);
}

// async fn switch_screen(app: &mut App, tx: &AppTx, new_screen: Box<dyn AppScreen>) {
//     if let Some(current) = app.current_screen.as_mut() {
//         current.on_exit(tx).await;
//     }
//     let mut screen = new_screen;
//     screen.on_enter(tx).await;
//     app.current_screen = Some(screen);
// }

async fn run_app<B: Backend>(
    terminal: &mut Terminal<B>,
    app: &mut App,
    events: &mut EventHandler,
) -> io::Result<()>
where
    io::Error: From<B::Error>,
{
    let tx = events.app_sender();

    if let Some(screen) = &mut app.current_screen {
        screen.on_enter(&tx).await;
    }

    loop {
        terminal.draw(|f| ui::ui(f, app))?;

        match events.next().await {
            AppEvent::Quit => {
                if let Some(screen) = app.current_screen.as_mut() {
                    screen.on_exit(&tx).await;
                }
                return Ok(());
            }
            AppEvent::Input(input) => {
                match input {
                    InputEvent::Key(key) => {
                        tracing::debug!(
                            "KEY: code={:?} mods={:?} kind={:?}",
                            key.code,
                            key.modifiers,
                            key.kind
                        );
                        // Global shortcuts — fire before any screen gets the event.
                        if let Some(combo) = key_event_to_combo(&key) {
                            let action = {
                                let s = app.settings.read().unwrap();
                                tracing::debug!(
                                    "COMBO: {} → {:?}",
                                    combo,
                                    s.key_bindings.get_action(&combo)
                                );
                                s.key_bindings.get_action(&combo)
                            };
                            match action {
                                Some(ActionShortcuts::Quit) => {
                                    tx.send(AppEvent::Quit).ok();
                                    continue;
                                }
                                Some(ActionShortcuts::OpenSettings) => {
                                    let already_on_settings = app
                                        .current_screen
                                        .as_ref()
                                        .map(|s| s.get_kind() == ScreenKind::Settings)
                                        .unwrap_or(false);
                                    if !already_on_settings {
                                        tx.send(AppEvent::OpenScreen(ScreenEvent::OpenSettings))
                                            .ok();
                                    }
                                    continue;
                                }
                                _ => {}
                            }
                        }
                        if let Some(screen) = &mut app.current_screen {
                            screen.handle_input(&InputEvent::Key(key), &tx);
                        }
                    }
                    InputEvent::Mouse(mouse_event) => {
                        if let Some(screen) = &mut app.current_screen {
                            screen.handle_input(&InputEvent::Mouse(mouse_event), &tx);
                        }
                    }
                    InputEvent::Paste(text) => {
                        if let Some(screen) = &mut app.current_screen {
                            screen.handle_input(&InputEvent::Paste(text), &tx);
                        }
                    }
                }
            }
            msg => handle_app_message(msg, app, &tx).await?,
        }
    }
}

async fn handle_app_message(msg: AppEvent, app: &mut App, tx: &AppTx) -> io::Result<()> {
    match msg {
        AppEvent::Redraw => {}
        AppEvent::OpenScreen(screen) => {
            switch_screen(app, tx, screen).await;
        }
        AppEvent::OpenPath(path) => {
            // We either handle the new path within the current screen, or we switch to a new screen for this path
            let unhandled = if let Some(screen) = app.current_screen.as_mut() {
                screen
                    .handle_app_message(AppEvent::OpenPath(path), tx)
                    .await
            } else {
                Some(AppEvent::OpenPath(path))
            };
            if let Some(AppEvent::OpenPath(path)) = unhandled {
                if let Some(vault) = app.vault.clone() {
                    if path.is_note() {
                        tx.send(AppEvent::OpenScreen(ScreenEvent::OpenEditor(vault, path)))
                            .ok();
                    } else {
                        tx.send(AppEvent::OpenScreen(ScreenEvent::OpenBrowse(vault, path)))
                            .ok();
                    }
                } else {
                    tx.send(AppEvent::OpenScreen(ScreenEvent::OpenSettings))
                        .ok();
                }
            }
        }
        AppEvent::SettingsSaved => {
            // Rebuild the vault so workspace path and inbox_path changes take effect.
            app.vault = rebuild_vault(&app.settings).await;
            tx.send(AppEvent::OpenScreen(ScreenEvent::Start)).ok();
        }
        AppEvent::CloseSettings => {
            tx.send(AppEvent::OpenScreen(ScreenEvent::Start)).ok();
        }
        AppEvent::VaultConflict(msg) => {
            // The vault has structural conflicts (e.g. case-insensitive path clashes).
            // Clear the workspace so the user is not stuck in a loop, then show
            // the settings screen with the error overlay pre-populated.
            {
                let mut s = app.settings.write().unwrap();
                s.clear_workspace();
                s.save_to_disk().ok();
            }
            app.vault = None;
            switch_screen(app, tx, ScreenEvent::OpenSettingsWithError(msg)).await;
        }
        AppEvent::WorkspaceSwitched(name) => {
            {
                let mut s = app.settings.write().unwrap();
                if let Some(ref mut wc) = s.workspace_config {
                    wc.global.current_workspace = name;
                }
                s.save_to_disk().ok();
            }
            app.vault = rebuild_vault(&app.settings).await;
            tx.send(AppEvent::OpenScreen(ScreenEvent::Start)).ok();
        }
        other => {
            if let Some(screen) = app.current_screen.as_mut() {
                screen.handle_app_message(other, tx).await;
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
    use tokio::sync::mpsc::unbounded_channel;

    use crate::components::events::{AppEvent, ScreenEvent};
    use crate::keys::action_shortcuts::ActionShortcuts;
    use crate::keys::key_event_to_combo;
    use crate::settings::AppSettings;

    /// Ctrl+P is the global shortcut for OpenSettings, handled in run_app before any screen.
    /// This test verifies that the keybinding lookup resolves to OpenSettings
    /// and that the app-level handler sends OpenScreen(OpenSettings).
    #[test]
    fn settings_keybinding_sends_open_settings() {
        let settings = AppSettings::default();
        let key = KeyEvent {
            code: KeyCode::Char('p'),
            modifiers: KeyModifiers::CONTROL,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };

        let combo = key_event_to_combo(&key).expect("Ctrl+P should produce a combo");
        let action = settings.key_bindings.get_action(&combo);
        assert_eq!(action, Some(ActionShortcuts::OpenSettings));

        // Simulate the app-level dispatch: on OpenSettings, send OpenScreen(OpenSettings).
        let (tx, mut rx) = unbounded_channel();
        tx.send(AppEvent::OpenScreen(ScreenEvent::OpenSettings))
            .ok();
        let msg = rx.try_recv().expect("should have a message");
        assert!(matches!(
            msg,
            AppEvent::OpenScreen(ScreenEvent::OpenSettings)
        ));
    }

    #[test]
    fn init_logging_returns_none_on_bad_path() {
        use crate::init_logging;
        // /nonexistent/readonly/path cannot be created; init_logging must return None
        // without panicking. This test exercises the early-return path before try_init
        // is called, so the global subscriber singleton is not set by this test.
        let result = init_logging(std::path::Path::new("/nonexistent/readonly/path"));
        assert!(result.is_none());
    }
}