Skip to main content

cove_cli/sidebar/
app.rs

1// ── Sidebar application ──
2
3use std::collections::HashMap;
4use std::io::{self, stdout};
5
6use crossterm::cursor;
7use crossterm::execute;
8use crossterm::terminal::{self, DisableLineWrap, EnableLineWrap};
9use ratatui::Terminal;
10use ratatui::backend::CrosstermBackend;
11
12use crate::sidebar::context::ContextManager;
13use crate::sidebar::event::{self, Action};
14use crate::sidebar::state::{StateDetector, WindowState};
15use crate::sidebar::ui::SidebarWidget;
16use crate::tmux::{self, WindowInfo};
17
18// ── Types ──
19
20struct SidebarApp {
21    windows: Vec<WindowInfo>,
22    states: HashMap<u32, WindowState>,
23    selected: usize,
24    tick: u64,
25    detector: StateDetector,
26    context_mgr: ContextManager,
27}
28
29// ── Constants ──
30
31const REFRESH_EVERY: u64 = 2;
32
33// ── Public API ──
34
35pub fn run() -> Result<(), String> {
36    // No alternate screen — render in-place in tmux pane (matches bash behavior)
37    let mut stdout = stdout();
38    execute!(stdout, cursor::Hide, DisableLineWrap).map_err(|e| format!("terminal: {e}"))?;
39    terminal::enable_raw_mode().map_err(|e| format!("terminal: {e}"))?;
40
41    let result = run_loop();
42
43    // Cleanup
44    terminal::disable_raw_mode().ok();
45    execute!(stdout, cursor::Show, EnableLineWrap).ok();
46
47    result
48}
49
50// ── Helpers ──
51
52fn run_loop() -> Result<(), String> {
53    let backend = CrosstermBackend::new(io::stdout());
54    let mut terminal = Terminal::new(backend).map_err(|e| format!("terminal: {e}"))?;
55
56    let mut app = SidebarApp {
57        windows: Vec::new(),
58        states: HashMap::new(),
59        selected: 0,
60        tick: 0,
61        detector: StateDetector::new(),
62        context_mgr: ContextManager::new(),
63    };
64
65    loop {
66        // Refresh window list periodically
67        if app.tick % REFRESH_EVERY == 0 {
68            refresh_windows(&mut app);
69        }
70
71        // Detect states every tick
72        app.states = app.detector.detect(&app.windows);
73
74        // Context orchestration: prefetch, drain, handle selection changes
75        let detector = &app.detector;
76        app.context_mgr
77            .tick(&app.windows, &app.states, app.selected, &|idx| {
78                detector.pane_id(idx).map(str::to_string)
79            });
80
81        // Prepare context for rendering
82        let context = app
83            .windows
84            .get(app.selected)
85            .and_then(|win| app.context_mgr.get(&win.name));
86        let context_loading = app
87            .windows
88            .get(app.selected)
89            .is_some_and(|win| app.context_mgr.is_loading(&win.name));
90
91        // Render
92        terminal
93            .draw(|frame| {
94                let area = frame.area();
95                let widget = SidebarWidget {
96                    windows: &app.windows,
97                    states: &app.states,
98                    selected: app.selected,
99                    tick: app.tick,
100                    context,
101                    context_loading,
102                };
103                frame.render_widget(widget, area);
104            })
105            .map_err(|e| format!("render: {e}"))?;
106
107        // Handle events
108        let actions = event::poll();
109        let mut moved = false;
110
111        for action in actions {
112            match action {
113                Action::Up => {
114                    if app.selected > 0 {
115                        app.selected -= 1;
116                        moved = true;
117                    }
118                }
119                Action::Down => {
120                    if app.selected + 1 < app.windows.len() {
121                        app.selected += 1;
122                        moved = true;
123                    }
124                }
125                Action::Select => {
126                    if let Some(win) = app.windows.get(app.selected) {
127                        let _ = tmux::select_window(win.index);
128                        refresh_windows(&mut app);
129                        app.tick = 0;
130                        continue;
131                    }
132                }
133                Action::Quit => return Ok(()),
134                Action::Tick => {}
135            }
136        }
137
138        // Single tmux call after all queued keys are processed
139        if moved {
140            if let Some(win) = app.windows.get(app.selected) {
141                let _ = tmux::select_window_sidebar(win.index);
142            }
143            // Skip next refresh so select-window has time to take effect
144            app.tick = 1;
145        } else {
146            app.tick += 1;
147        }
148    }
149}
150
151fn refresh_windows(app: &mut SidebarApp) {
152    if let Ok(windows) = tmux::list_windows() {
153        // Sync selected to the tmux-active window
154        let active_pos = windows.iter().position(|w| w.is_active).unwrap_or(0);
155
156        app.selected = active_pos;
157        app.windows = windows;
158
159        // Clamp
160        if app.selected >= app.windows.len() && !app.windows.is_empty() {
161            app.selected = app.windows.len() - 1;
162        }
163    }
164}