seqtui 0.1.0

Fast TUI toolkit for viewing, translating, and manipulating biological sequences.
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
//! Application controller.
//!
//! This module orchestrates the main application loop:
//! - Terminal initialization and cleanup
//! - Event polling and handling
//! - State updates and rendering
//! - Background file loading with progress updates
//! - Background translation with progress updates
//!
//! The design supports:
//! - Async file loading (TUI shows spinner while parsing)
//! - Async translation (TUI shows progress while translating)
//! - Multiple views (help screen, translation settings)

use std::io::{self, Stdout};
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
use std::time::Duration;

use anyhow::Result;
use crossterm::{
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};

use crate::event::{apply_action, handle_event, poll_event, ActionResult};
use crate::formats::{parse_file_with_options, FileFormat};
use crate::genetic_code::GeneticCodes;
use crate::model::{Alignment, AppState, LoadingState, Sequence, SequenceType};
use crate::ui::{calculate_visible_dimensions, render};

/// Messages sent from the background loading thread.
pub enum LoadMessage {
    /// Loading completed successfully
    Complete(Alignment),
    /// Loading failed with an error (includes file path for context)
    Error { message: String, path: PathBuf },
    /// Progress update (for future use with streaming parsers)
    Progress { sequences_loaded: usize },
}

/// Messages sent from the background translation thread.
pub enum TranslateMessage {
    /// Translation progress update
    Progress { sequences_done: usize, total: usize },
    /// Translation completed successfully
    Complete(Alignment),
}

/// The main application controller.
pub struct App {
    /// Terminal backend
    terminal: Terminal<CrosstermBackend<Stdout>>,
    /// Application state
    state: AppState,
    /// Event poll timeout
    tick_rate: Duration,
    /// Receiver for background loading messages
    load_receiver: Option<Receiver<LoadMessage>>,
    /// Receiver for background translation messages
    translate_receiver: Option<Receiver<TranslateMessage>>,
}

impl App {
    /// Creates a new application with the given state.
    pub fn new(state: AppState) -> Result<Self> {
        // Setup terminal
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen)?;
        let backend = CrosstermBackend::new(stdout);
        let terminal = Terminal::new(backend)?;

        Ok(Self {
            terminal,
            state,
            tick_rate: Duration::from_millis(50),
            load_receiver: None,
            translate_receiver: None,
        })
    }

    /// Creates a new application and starts loading a file in the background.
    /// Optional `preset_translation` is (genetic_code_id, reading_frame) to preset translation settings.
    pub fn new_with_background_load(
        file_path: PathBuf,
        forced_format: Option<FileFormat>,
        preset_translation: Option<(u8, u8)>,
        fancy_ui: bool,
    ) -> Result<Self> {
        // Extract file name for display
        let file_name = file_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("alignment")
            .to_string();

        // Create initial state in loading mode
        let mut state = AppState::new_loading(file_name, file_path.clone());
        state.fancy_ui = fancy_ui;
        
        // Apply preset translation settings if provided
        if let Some((genetic_code, reading_frame)) = preset_translation {
            // Find the index of the genetic code in the list
            let codes = GeneticCodes::new();
            let code_index = codes.all().iter().position(|c| c.id == genetic_code).unwrap_or(0);
            
            state.translation_settings.genetic_code_id = genetic_code;
            state.translation_settings.selected_code_index = code_index;
            // Convert from 1-based to 0-based frame
            let frame = (reading_frame.saturating_sub(1) as usize).min(2);
            state.translation_settings.frame = frame;
            state.translation_settings.selected_frame = frame;
            state.translation_settings.has_translated = true; // Skip the settings dialog
        }

        // Setup terminal
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen)?;
        let backend = CrosstermBackend::new(stdout);
        let terminal = Terminal::new(backend)?;

        // Create channel for background loading
        let (tx, rx): (Sender<LoadMessage>, Receiver<LoadMessage>) = mpsc::channel();

        // Spawn background thread for loading
        let path_for_error = file_path.clone();
        thread::spawn(move || {
            match parse_file_with_options(&file_path, forced_format) {
                Ok(alignment) => {
                    let _ = tx.send(LoadMessage::Complete(alignment));
                }
                Err(e) => {
                    let _ = tx.send(LoadMessage::Error { 
                        message: e.to_string(), 
                        path: path_for_error,
                    });
                }
            }
        });

        Ok(Self {
            terminal,
            state,
            tick_rate: Duration::from_millis(50),
            load_receiver: Some(rx),
            translate_receiver: None,
        })
    }

    /// Starts background translation of the current alignment.
    fn start_background_translation(&mut self) {
        // Get translation parameters
        let genetic_code_id = self.state.translation_settings.genetic_code_id;
        let frame = self.state.translation_settings.frame;
        
        // Get the genetic code before spawning (avoids recreating all codes in thread)
        let codes = GeneticCodes::new();
        let code = codes.get(genetic_code_id)
            .unwrap_or_else(|| codes.default_code())
            .clone(); // Clone just the one code we need (64 bytes + name)
        
        // Clone the sequences for the background thread
        // Unfortunately we need to copy the data since we can't share references across threads
        let sequences: Vec<(String, Vec<u8>)> = self.state.alignment.sequences
            .iter()
            .map(|seq| (seq.id.clone(), seq.clone_bytes()))
            .collect();
        
        let total = sequences.len();
        
        // Set loading state
        self.state.loading_state = LoadingState::Translating {
            message: "Translating...".to_string(),
            sequences_done: 0,
            total,
        };
        
        // Create channel for translation messages
        let (tx, rx): (Sender<TranslateMessage>, Receiver<TranslateMessage>) = mpsc::channel();
        self.translate_receiver = Some(rx);
        
        // Spawn background thread for translation
        thread::spawn(move || {
            let mut translated_seqs = Vec::with_capacity(total);
            let progress_interval = (total / 20).max(1); // Update every 5%
            
            for (i, (id, data)) in sequences.into_iter().enumerate() {
                let aa_data = code.translate_sequence(&data, frame);
                translated_seqs.push(Sequence::from_bytes(id, aa_data));
                
                // Send progress update periodically
                if (i + 1) % progress_interval == 0 || i + 1 == total {
                    let _ = tx.send(TranslateMessage::Progress {
                        sequences_done: i + 1,
                        total,
                    });
                }
            }
            
            translated_seqs.shrink_to_fit();
            let mut alignment = Alignment::new(translated_seqs);
            alignment.sequence_type = SequenceType::AMINO_ACID;
            let _ = tx.send(TranslateMessage::Complete(alignment));
        });
    }

    /// Runs the main application loop.
    pub fn run(&mut self) -> Result<()> {
        // Initial viewport setup
        self.update_viewport_size()?;

        loop {
            // Check for background loading messages (non-blocking)
            if let Some(ref rx) = self.load_receiver {
                match rx.try_recv() {
                    Ok(LoadMessage::Complete(alignment)) => {
                        self.state.set_alignment(alignment);
                        self.load_receiver = None; // Done loading
                    }
                    Ok(LoadMessage::Error { message, path }) => {
                        self.state.set_loading_error(message, Some(path));
                        self.load_receiver = None;
                    }
                    Ok(LoadMessage::Progress { sequences_loaded }) => {
                        // Update progress in loading state
                        if let LoadingState::LoadingFile { sequences_loaded: ref mut sl, .. } = self.state.loading_state {
                            *sl = Some(sequences_loaded);
                        }
                    }
                    Err(mpsc::TryRecvError::Empty) => {
                        // No message yet, continue
                    }
                    Err(mpsc::TryRecvError::Disconnected) => {
                        // Sender dropped without sending - should not happen
                        self.state.set_loading_error("Loading thread terminated unexpectedly".to_string(), None);
                        self.load_receiver = None;
                    }
                }
            }

            // Check for background translation messages (non-blocking)
            if let Some(ref rx) = self.translate_receiver {
                match rx.try_recv() {
                    Ok(TranslateMessage::Progress { sequences_done, total }) => {
                        if let LoadingState::Translating { sequences_done: ref mut sd, total: ref mut t, .. } = self.state.loading_state {
                            *sd = sequences_done;
                            *t = total;
                        }
                    }
                    Ok(TranslateMessage::Complete(alignment)) => {
                        self.state.set_translated_alignment(alignment);
                        self.translate_receiver = None;
                    }
                    Err(mpsc::TryRecvError::Empty) => {
                        // No message yet, continue
                    }
                    Err(mpsc::TryRecvError::Disconnected) => {
                        // Sender dropped without sending - should not happen
                        self.state.loading_state = LoadingState::Ready;
                        self.state.status_message = Some("Translation failed unexpectedly".to_string());
                        self.translate_receiver = None;
                    }
                }
            }

            // Tick spinner animation if loading
            if self.state.loading_state.is_loading() {
                self.state.tick_spinner();
            }

            // Render
            self.terminal.draw(|frame| {
                render(frame, &self.state);
            })?;

            // Handle events
            if let Some(event) = poll_event(self.tick_rate) {
                let has_number_prefix = !self.state.number_buffer.is_empty();
                let has_error_popup = self.state.error_popup.is_some();
                let has_file_browser = self.state.file_browser.is_some();
                let action = handle_event(
                    event, 
                    &self.state.mode, 
                    self.state.show_help, 
                    self.state.pending_g, 
                    self.state.pending_z, 
                    has_number_prefix,
                    has_error_popup,
                    has_file_browser,
                );

                // Handle resize specially to update viewport
                if let crate::event::Action::Resize(_, _) = action {
                    self.update_viewport_size()?;
                }

                let result = apply_action(&mut self.state, action);

                // Check if translation should be started
                match result {
                    ActionResult::StartTranslation => {
                        self.start_background_translation();
                    }
                    ActionResult::LoadFile(path) => {
                        self.start_background_load(path);
                    }
                    ActionResult::Continue => {}
                }

                if self.state.should_quit {
                    break;
                }
            }
        }

        Ok(())
    }

    /// Starts a new background load for the given file path.
    fn start_background_load(&mut self, file_path: PathBuf) {
        // Close file browser
        self.state.close_file_browser();
        
        // Extract file name for display
        let file_name = file_path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("Unknown")
            .to_string();
        
        // Reset state for loading
        self.state.loading_state = LoadingState::LoadingFile {
            path: file_path.clone(),
            message: format!("Loading {}...", file_name),
            sequences_loaded: None,
        };
        self.state.status_message = None;
        
        // Create channel for background loading
        let (tx, rx): (Sender<LoadMessage>, Receiver<LoadMessage>) = mpsc::channel();
        
        // Store the path for error handling
        let path_for_error = file_path.clone();
        
        // Spawn background thread for loading
        thread::spawn(move || {
            match parse_file_with_options(&file_path, None) {
                Ok(alignment) => {
                    let _ = tx.send(LoadMessage::Complete(alignment));
                }
                Err(e) => {
                    let _ = tx.send(LoadMessage::Error { 
                        message: e.to_string(), 
                        path: path_for_error,
                    });
                }
            }
        });
        
        self.load_receiver = Some(rx);
    }

    /// Updates the viewport size based on terminal dimensions.
    fn update_viewport_size(&mut self) -> Result<()> {
        let size = self.terminal.size()?;
        let (visible_rows, visible_cols) = calculate_visible_dimensions(size.width, size.height);
        self.state.update_viewport_size(visible_rows, visible_cols);
        Ok(())
    }
}

impl Drop for App {
    fn drop(&mut self) {
        // Restore terminal
        let _ = disable_raw_mode();
        let _ = execute!(self.terminal.backend_mut(), LeaveAlternateScreen);
        let _ = self.terminal.show_cursor();
    }
}

/// Convenience function to run the application with an alignment file.
pub fn run_app(state: AppState) -> Result<()> {
    let mut app = App::new(state)?;
    app.run()
}

/// Convenience function to run the application with the file browser open.
/// Used when no file is provided on command line.
pub fn run_app_with_file_browser(fancy_ui: bool) -> Result<()> {
    use crate::model::{Alignment, FileBrowserState};
    
    let start_dir = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
    let mut state = AppState::new(Alignment::new(vec![]), "No file".to_string());
    state.fancy_ui = fancy_ui;
    state.file_browser = Some(FileBrowserState::new(start_dir, "Select a sequence file".to_string()));
    
    let mut app = App::new(state)?;
    app.run()
}

/// Convenience function to run the application with the file browser open in a given directory.
pub fn run_app_with_file_browser_at(start_dir: PathBuf, fancy_ui: bool) -> Result<()> {
    use crate::model::{Alignment, FileBrowserState};

    let start_dir = if start_dir.is_dir() {
        start_dir
    } else {
        std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
    };
    let mut state = AppState::new(Alignment::new(vec![]), "No file".to_string());
    state.fancy_ui = fancy_ui;
    state.file_browser = Some(FileBrowserState::new(start_dir, "Select a sequence file".to_string()));

    let mut app = App::new(state)?;
    app.run()
}

/// Convenience function to run the application with background loading.
/// Optional `preset_translation` is (genetic_code_id, reading_frame) to preset translation settings.
pub fn run_app_with_loading(
    file_path: PathBuf,
    forced_format: Option<FileFormat>,
    preset_translation: Option<(u8, u8)>,
    fancy_ui: bool,
) -> Result<()> {
    let mut app = App::new_with_background_load(file_path, forced_format, preset_translation, fancy_ui)?;
    app.run()
}

#[cfg(test)]
mod tests {
    use crate::model::{Alignment, Sequence};

    use super::*;

    #[test]
    fn test_app_state_creation() {
        let seqs = vec![
            Sequence::new("seq1", "ACGT"),
            Sequence::new("seq2", "TGCA"),
        ];
        let alignment = Alignment::new(seqs);
        let state = AppState::new(alignment, "test".to_string());

        assert_eq!(state.alignment.sequence_count(), 2);
        assert!(!state.should_quit);
    }
}