gitai/tui/
app.rs

1use super::input_handler::{InputResult, handle_input};
2use super::spinner::SpinnerState;
3use super::state::{Mode, TuiState};
4use super::ui::draw_ui;
5use crate::features::commit::{
6    CommitService, completion::CompletionService, format_commit_result, types::GeneratedMessage,
7};
8use anyhow::{Error, Result};
9use ratatui::{
10    Terminal,
11    backend::CrosstermBackend,
12    crossterm::{
13        event::{self, Event},
14        execute,
15        terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
16    },
17};
18
19use log::debug;
20use std::io;
21use std::panic;
22use std::sync::Arc;
23use std::time::Duration;
24
25pub struct TuiCommit {
26    pub state: TuiState,
27    service: Arc<CommitService>,
28    completion_service: Arc<CompletionService>,
29}
30
31impl TuiCommit {
32    pub fn new(
33        initial_messages: Vec<GeneratedMessage>,
34        custom_instructions: String,
35        service: Arc<CommitService>,
36        completion_service: Arc<CompletionService>,
37    ) -> Self {
38        let state = TuiState::new(initial_messages, custom_instructions);
39
40        Self {
41            state,
42            service,
43            completion_service,
44        }
45    }
46
47    #[allow(clippy::unused_async)]
48    pub async fn run(
49        initial_messages: Vec<GeneratedMessage>,
50        custom_instructions: String,
51        service: Arc<CommitService>,
52        completion_service: Arc<CompletionService>,
53    ) -> Result<()> {
54        let mut app = Self::new(
55            initial_messages,
56            custom_instructions,
57            service,
58            completion_service,
59        );
60
61        app.run_app().await.map_err(Error::from)
62    }
63
64    pub async fn run_app(&mut self) -> io::Result<()> {
65        // Setup
66        let default_hook = panic::take_hook();
67        panic::set_hook(Box::new(move |panic_info: &panic::PanicHookInfo| {
68            let _ = crossterm::terminal::disable_raw_mode();
69            default_hook(panic_info);
70        }));
71        enable_raw_mode()?;
72        let mut stdout = io::stdout();
73        execute!(stdout, EnterAlternateScreen)?;
74        let backend = CrosstermBackend::new(stdout);
75        let mut terminal = Terminal::new(backend)?;
76
77        // Run main loop
78        let result = self.main_loop(&mut terminal).await;
79
80        // Cleanup
81        disable_raw_mode()?;
82        execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
83        terminal.show_cursor()?;
84
85        // Handle result and display appropriate message
86        match result {
87            Ok(exit_status) => match exit_status {
88                ExitStatus::Committed(message) => {
89                    println!("{message}");
90                }
91                ExitStatus::Cancelled => {
92                    println!("Commit operation cancelled. Your changes remain staged.");
93                }
94                ExitStatus::Error(error_message) => {
95                    eprintln!("An error occurred: {error_message}");
96                }
97            },
98            Err(e) => {
99                eprintln!("An unexpected error occurred: {e}");
100                return Err(io::Error::other(e.to_string()));
101            }
102        }
103
104        Ok(())
105    }
106
107    #[allow(clippy::too_many_lines)]
108    async fn main_loop(
109        &mut self,
110        terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
111    ) -> anyhow::Result<ExitStatus> {
112        let (tx, mut rx) = tokio::sync::mpsc::channel::<Result<GeneratedMessage, anyhow::Error>>(1);
113        let (completion_tx, mut completion_rx) =
114            tokio::sync::mpsc::channel::<Result<Vec<String>, anyhow::Error>>(1);
115        let mut task_spawned = false;
116        let mut completion_task_spawned = false;
117
118        loop {
119            // Redraw only if dirty
120            if self.state.dirty {
121                terminal.draw(|f| draw_ui(f, &mut self.state))?;
122                self.state.dirty = false; // Reset dirty flag after redraw
123            }
124
125            // Spawn the task only once when entering the Generating mode
126            if self.state.mode == Mode::Generating && !task_spawned {
127                let service = self.service.clone();
128                let instructions = self.state.custom_instructions.clone();
129                let tx = tx.clone();
130
131                tokio::spawn(async move {
132                    debug!("Generating message...");
133                    let result = service.generate_message(&instructions).await;
134                    let _ = tx.send(result).await;
135                });
136
137                task_spawned = true; // Ensure we only spawn the task once
138            }
139
140            // Spawn completion task if there's a pending completion request
141            if let Some(prefix) = &self.state.pending_completion_prefix.clone()
142                && !completion_task_spawned
143            {
144                let _completion_service = self.completion_service.clone();
145                let prefix = prefix.clone();
146                let completion_tx = completion_tx.clone();
147
148                tokio::spawn(async move {
149                    debug!("Generating completion for prefix: {prefix}");
150                    // For now, generate some mock suggestions based on the prefix
151                    // In the future, this should call completion_service.complete_message
152                    let suggestions = vec![
153                        format!("{}: add new feature", prefix),
154                        format!("{}: fix bug", prefix),
155                        format!("{}: update documentation", prefix),
156                    ];
157                    let _ = completion_tx.send(Ok(suggestions)).await;
158                });
159
160                completion_task_spawned = true;
161                self.state.pending_completion_prefix = None; // Clear the pending request
162            }
163
164            // Check if a message has been received from the generation task
165            match rx.try_recv() {
166                Ok(result) => match result {
167                    Ok(new_message) => {
168                        self.state.messages.push(new_message);
169                        self.state.current_index = self.state.messages.len() - 1;
170
171                        self.state.update_message_textarea();
172                        self.state.mode = Mode::Normal; // Exit Generating mode
173                        self.state.spinner = None; // Stop the spinner
174                        self.state
175                            .set_status(String::from("New message generated successfully!"));
176                        task_spawned = false; // Reset for future regenerations
177                    }
178                    Err(e) => {
179                        self.state.mode = Mode::Normal; // Exit Generating mode
180                        self.state.spinner = None; // Stop the spinner
181                        self.state
182                            .set_status(format!("Failed to generate new message: {e}. Press 'r' to retry or 'Esc' to exit."));
183                        task_spawned = false; // Reset for future regenerations
184                    }
185                },
186                Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
187                    // No message available yet, continue the loop
188                }
189                Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
190                    // Handle the case where the sender has disconnected
191                    task_spawned = false;
192                }
193            }
194
195            // Check if completion suggestions have been received
196            match completion_rx.try_recv() {
197                Ok(result) => match result {
198                    Ok(suggestions) => {
199                        self.state.completion_suggestions = suggestions;
200                        self.state.completion_index = 0;
201                        completion_task_spawned = false;
202                    }
203                    Err(e) => {
204                        self.state
205                            .set_status(format!("Failed to get completions: {e}"));
206                        self.state.mode = Mode::EditingMessage;
207                        completion_task_spawned = false;
208                    }
209                },
210                Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
211                    // No completion available yet, continue the loop
212                }
213                Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
214                    // Handle the case where the sender has disconnected
215                    break;
216                }
217            }
218
219            // Poll for input events asynchronously
220            let event = tokio::task::spawn_blocking(|| {
221                if event::poll(Duration::from_millis(20)).unwrap_or(false) {
222                    if let Ok(Event::Key(key)) = event::read() {
223                        if key.kind == crossterm::event::KeyEventKind::Press {
224                            Some(key)
225                        } else {
226                            None
227                        }
228                    } else {
229                        None
230                    }
231                } else {
232                    None
233                }
234            })
235            .await
236            .expect("Failed to poll for input events");
237
238            if let Some(key) = event {
239                let input_result = handle_input(self, key).await;
240                match input_result {
241                    InputResult::Exit => return Ok(ExitStatus::Cancelled),
242                    InputResult::Commit(message) => match self.perform_commit(&message) {
243                        Ok(status) => return Ok(status),
244                        Err(e) => {
245                            self.state.set_status(format!("Commit failed: {e}"));
246                            self.state.dirty = true;
247                        }
248                    },
249                    InputResult::Continue => self.state.dirty = true,
250                }
251            }
252
253            // Update the spinner state and redraw if in generating mode
254            if self.state.mode == Mode::Generating
255                && self.state.last_spinner_update.elapsed() >= Duration::from_millis(100)
256            {
257                if let Some(spinner) = &mut self.state.spinner {
258                    spinner.tick();
259                    self.state.dirty = true; // Mark dirty to trigger redraw
260                }
261                self.state.last_spinner_update = std::time::Instant::now(); // Reset the update time
262            }
263        }
264
265        Ok(ExitStatus::Cancelled)
266    }
267
268    pub fn handle_regenerate(&mut self) {
269        self.state.mode = Mode::Generating;
270        self.state.spinner = Some(SpinnerState::new());
271    }
272
273    pub fn perform_commit(&self, message: &str) -> Result<ExitStatus, Error> {
274        match self.service.perform_commit(message, false, None) {
275            Ok(result) => {
276                let output = format_commit_result(&result, message);
277                Ok(ExitStatus::Committed(output))
278            }
279            Err(e) => Ok(ExitStatus::Error(e.to_string())),
280        }
281    }
282}
283
284#[allow(clippy::unused_async)]
285pub async fn run_tui_commit(
286    initial_messages: Vec<GeneratedMessage>,
287    custom_instructions: String,
288    service: Arc<CommitService>,
289    completion_service: Arc<CompletionService>,
290) -> Result<()> {
291    TuiCommit::run(
292        initial_messages,
293        custom_instructions,
294        service,
295        completion_service,
296    )
297    .await
298}
299
300pub enum ExitStatus {
301    Committed(String),
302    Cancelled,
303    Error(String),
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn test_panic_hook_setup() {
312        // Test that the panic hook code compiles and the closure is valid
313        // Note: Actual panic hook testing is challenging due to global state
314        #[allow(unused_variables)]
315        #[allow(clippy::no_effect_underscore_binding)]
316        let _closure = |panic_info: &panic::PanicHookInfo| {
317            let _ = crossterm::terminal::disable_raw_mode();
318        };
319        // If this compiles, the setup is correct
320    }
321}