command_vault/ui/
app.rs

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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use std::io::{self, Stdout};
use anyhow::Result;
use crossterm::{
    event::{self, Event, KeyCode, KeyModifiers},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    backend::CrosstermBackend,
    Terminal,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, Paragraph},
};
use crate::db::{Command, Database};
use crate::utils::params::{substitute_parameters, parse_parameters};
use crate::exec::{ExecutionContext, execute_shell_command};
use crate::ui::AddCommandApp;

pub struct App<'a> {
    pub commands: Vec<Command>,
    pub selected: Option<usize>,
    pub show_help: bool,
    pub message: Option<(String, Color)>,
    pub filter_text: String,
    pub filtered_commands: Vec<usize>,
    pub db: &'a mut Database,
    pub confirm_delete: Option<usize>, // Index of command pending deletion
    pub debug_mode: bool,
}

impl<'a> App<'a> {
    pub fn new(commands: Vec<Command>, db: &'a mut Database, debug_mode: bool) -> App<'a> {
        let filtered_commands: Vec<usize> = (0..commands.len()).collect();
        App {
            commands,
            selected: None,
            show_help: false,
            message: None,
            filter_text: String::new(),
            filtered_commands,
            db,
            confirm_delete: None,
            debug_mode,
        }
    }

    pub fn run(&mut self) -> Result<()> {
        let mut terminal = setup_terminal()?;
        let res = self.run_app(&mut terminal);
        restore_terminal(&mut terminal)?;
        res
    }

    fn run_app(&mut self, terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
        loop {
            terminal.draw(|f| self.ui(f))?;

            if let Event::Key(key) = event::read()? {
                match key.code {
                    KeyCode::Char('q') => {
                        if !self.filter_text.is_empty() {
                            self.filter_text.clear();
                            self.update_filtered_commands();
                        } else if self.confirm_delete.is_some() {
                            self.confirm_delete = None;
                        } else if self.show_help {
                            self.show_help = false;
                        } else {
                            return Ok(());
                        }
                    }
                    KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                        return Ok(());
                    }
                    KeyCode::Char('?') => {
                        self.show_help = !self.show_help;
                        continue; // Skip further processing when toggling help
                    }
                    _ if self.show_help => {
                        // If help is shown, ignore all other keys except those above
                        continue;
                    }
                    KeyCode::Char('c') => {
                        if let Some(selected) = self.selected {
                            if let Some(&idx) = self.filtered_commands.get(selected) {
                                if let Some(cmd) = self.commands.get(idx) {
                                    copy_to_clipboard(&cmd.command)?;
                                    self.message = Some(("Command copied to clipboard!".to_string(), Color::Green));
                                }
                            }
                        }
                    }
                    KeyCode::Char('y') => {
                        if let Some(selected) = self.selected {
                            if let Some(&idx) = self.filtered_commands.get(selected) {
                                if let Some(cmd) = self.commands.get(idx) {
                                    copy_to_clipboard(&cmd.command)?;
                                    self.message = Some(("Command copied to clipboard!".to_string(), Color::Green));
                                }
                            }
                        }
                    }
                    KeyCode::Enter => {
                        if let Some(selected) = self.selected {
                            if let Some(confirm_idx) = self.confirm_delete {
                                if confirm_idx == selected {
                                    if let Some(&filtered_idx) = self.filtered_commands.get(selected) {
                                        if let Some(command_id) = self.commands[filtered_idx].id {
                                            match self.db.delete_command(command_id) {
                                                Ok(_) => {
                                                    self.commands.remove(filtered_idx);
                                                    self.message = Some(("Command deleted successfully".to_string(), Color::Green));
                                                    self.update_filtered_commands();
                                                    // Update selection after deletion
                                                    if self.filtered_commands.is_empty() {
                                                        self.selected = None;
                                                    } else {
                                                        self.selected = Some(selected.min(self.filtered_commands.len() - 1));
                                                    }
                                                }
                                                Err(e) => {
                                                    self.message = Some((format!("Failed to delete command: {}", e), Color::Red));
                                                }
                                            }
                                            self.confirm_delete = None;
                                        }
                                    }
                                }
                            } else if let Some(&filtered_idx) = self.filtered_commands.get(selected) {
                                if let Some(cmd) = self.commands.get(filtered_idx) {
                                    // Exit TUI temporarily
                                    restore_terminal(terminal)?;
                                    
                                    // Re-enable colors after restoring terminal
                                    colored::control::set_override(true);

                                    // If command has parameters, substitute them with user input
                                    let current_params = parse_parameters(&cmd.command);
                                    let final_command = substitute_parameters(&cmd.command, &current_params, None)?;
                                    let ctx = ExecutionContext {
                                        command: final_command,
                                        directory: cmd.directory.clone(),
                                        test_mode: false,
                                        debug_mode: self.debug_mode,
                                    };
                                    execute_shell_command(&ctx)?;
                                    
                                    return Ok(());
                                }
                            }
                        }
                    }
                    KeyCode::Down | KeyCode::Char('j') => {
                        if let Some(selected) = self.selected {
                            if selected < self.filtered_commands.len() - 1 {
                                self.selected = Some(selected + 1);
                            }
                        } else if !self.filtered_commands.is_empty() {
                            self.selected = Some(0);
                        }
                    }
                    KeyCode::Up | KeyCode::Char('k') => {
                        if let Some(selected) = self.selected {
                            if selected > 0 {
                                self.selected = Some(selected - 1);
                            }
                        } else if !self.filtered_commands.is_empty() {
                            self.selected = Some(self.filtered_commands.len() - 1);
                        }
                    }
                    KeyCode::Char('/') => {
                        self.filter_text.clear();
                        self.message = Some(("Type to filter commands...".to_string(), Color::Blue));
                    }
                    KeyCode::Char('e') => {
                        if let Some(selected) = self.selected {
                            if let Some(&idx) = self.filtered_commands.get(selected) {
                                if let Some(cmd) = self.commands.get(idx).cloned() {
                                    // Exit TUI temporarily
                                    restore_terminal(terminal)?;
                                    
                                    // Create AddCommandApp with existing command data
                                    let mut add_app = AddCommandApp::new();
                                    add_app.set_command(cmd.command.clone());
                                    add_app.set_tags(cmd.tags.clone());
                                    
                                    let result = add_app.run();
                                    
                                    // Re-initialize terminal and force redraw
                                    let mut new_terminal = setup_terminal()?;
                                    new_terminal.clear()?;
                                    *terminal = new_terminal;
                                    terminal.draw(|f| self.ui(f))?;
                                    
                                    match result {
                                        Ok(Some((new_command, new_tags, _))) => {
                                            // Update command
                                            let updated_cmd = Command {
                                                id: cmd.id,
                                                command: new_command.clone(),
                                                timestamp: cmd.timestamp,
                                                directory: cmd.directory.clone(),
                                                tags: new_tags,
                                                parameters: crate::utils::params::parse_parameters(&new_command),
                                            };
                                            
                                            if let Err(e) = self.db.update_command(&updated_cmd) {
                                                self.message = Some((format!("Failed to update command: {}", e), Color::Red));
                                            } else {
                                                // Update local command list
                                                if let Some(cmd) = self.commands.get_mut(idx) {
                                                    *cmd = updated_cmd;
                                                }
                                                self.message = Some(("Command updated successfully!".to_string(), Color::Green));
                                            }
                                        }
                                        Ok(None) => {
                                            self.message = Some(("Edit cancelled".to_string(), Color::Yellow));
                                        }
                                        Err(e) => {
                                            self.message = Some((format!("Error during edit: {}", e), Color::Red));
                                        }
                                    }
                                }
                            }
                        }
                        continue;
                    }
                    KeyCode::Char('d') => {
                        if let Some(selected) = self.selected {
                            if let Some(&filtered_idx) = self.filtered_commands.get(selected) {
                                if let Some(command_id) = self.commands[filtered_idx].id {
                                    self.confirm_delete = Some(selected);
                                }
                            }
                        }
                    }
                    KeyCode::Char(c) => {
                        if c == '/' {  // Skip if it's the '/' character that started filter mode
                            self.filter_text.clear();
                            self.message = Some(("Type to filter commands...".to_string(), Color::Blue));
                        } else if c != '/' {  // Skip if it's the '/' character that started filter mode
                            self.filter_text.push(c);
                            self.update_filtered_commands();
                        }
                    }
                    KeyCode::Backspace if !self.filter_text.is_empty() => {
                        self.filter_text.pop();
                        self.update_filtered_commands();
                    }
                    KeyCode::Esc => {
                        if !self.filter_text.is_empty() {
                            self.filter_text.clear();
                            self.update_filtered_commands();
                        } else if self.confirm_delete.is_some() {
                            self.confirm_delete = None;
                            self.message = Some(("Delete operation cancelled".to_string(), Color::Yellow));
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    /// Update the filtered commands list based on the current filter text
    pub fn update_filtered_commands(&mut self) {
        let search_term = self.filter_text.to_lowercase();
        self.filtered_commands = (0..self.commands.len())
            .filter(|&i| {
                let cmd = &self.commands[i];
                cmd.command.to_lowercase().contains(&search_term) ||
                cmd.tags.iter().any(|tag| tag.to_lowercase().contains(&search_term)) ||
                cmd.directory.to_lowercase().contains(&search_term)
            })
            .collect();
        
        // Update selection
        if self.filtered_commands.is_empty() {
            self.selected = None;
        } else if let Some(selected) = self.selected {
            if selected >= self.filtered_commands.len() {
                self.selected = Some(self.filtered_commands.len() - 1);
            }
        }
    }

    fn ui(&mut self, f: &mut ratatui::Frame) {
        if self.show_help {
            let help_text = vec![
                "Command Vault Help",
                "",
                "Navigation:",
                "  ↑/k      - Move cursor up",
                "  ↓/j      - Move cursor down",
                "  q        - Quit (or clear filter/cancel delete/close help)",
                "  Ctrl+c   - Force quit",
                "",
                "Command Actions:",
                "  Enter    - Execute selected command",
                "  c/y      - Copy command to clipboard",
                "  e        - Edit selected command (text, tags, directory)",
                "  d        - Delete selected command (requires confirmation)",
                "",
                "Search and Filter:",
                "  /        - Start filtering commands",
                "  [type]   - Filter by command text, tags, or directory",
                "  Esc      - Clear filter or cancel current operation",
                "  Backspace- Remove last character from filter",
                "",
                "Display:",
                "  ?        - Toggle this help screen",
                "",
                "Command Format:",
                "  - (@param) Parameters are shown with @ prefix",
                "  - (#tag)  Tags are shown in green with # prefix",
                "  - (dir)   Working directory is shown if set",
                "  - (id)    Command IDs are shown in parentheses",
                "",
                "Tips:",
                "  - Use descriptive tags to organize commands",
                "  - Parameters (@param) allow dynamic input",
                "  - Filter works on commands, tags, and directories",
                "  - Working directory affects command execution",
                "",
                "Note:",
                "  - Debug mode can be enabled for troubleshooting",
                "  - All commands are executed in the current shell",
                "  - Command history is preserved in the database"
            ];

            let help_paragraph = Paragraph::new(help_text.join("\n"))
                .style(Style::default().fg(Color::White))
                .block(Block::default().borders(Borders::ALL).title("Help (press ? to close)"));

            // Center the help window
            let area = centered_rect(80, 80, f.size());
            f.render_widget(Clear, area); // Clear the background
            f.render_widget(help_paragraph, area);
            return;
        }

        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .margin(1)
            .constraints([
                Constraint::Length(3),  // Title
                Constraint::Min(0),     // Commands list
                Constraint::Length(1),  // Filter
                Constraint::Length(3),  // Status bar
            ])
            .split(f.size());

        // Title
        let title = Paragraph::new("Command Vault")
            .style(Style::default().fg(Color::Cyan))
            .block(Block::default().borders(Borders::ALL));
        f.render_widget(title, chunks[0]);

        // Commands list
        let commands: Vec<ListItem> = self.filtered_commands.iter()
            .map(|&i| {
                let cmd = &self.commands[i];
                let local_time = cmd.timestamp.with_timezone(&chrono::Local);
                let time_str = local_time.format("%Y-%m-%d %H:%M:%S").to_string();
                
                let mut spans = vec![
                    Span::styled(
                        format!("({}) ", cmd.id.unwrap_or(0)),
                        Style::default().fg(Color::DarkGray)
                    ),
                    Span::styled(
                        format!("[{}] ", time_str),
                        Style::default().fg(Color::Yellow)
                    ),
                    Span::raw(&cmd.command),
                ];

                if !cmd.tags.is_empty() {
                    spans.push(Span::raw(" "));
                    for tag in &cmd.tags {
                        spans.push(Span::styled(
                            format!("#{} ", tag),
                            Style::default().fg(Color::Green)
                        ));
                    }
                }

                ListItem::new(Line::from(spans))
            })
            .collect();

        let commands = List::new(commands)
            .block(Block::default().borders(Borders::ALL).title("Commands"))
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
        
        let commands_state = self.selected.map(|i| {
            let mut state = ratatui::widgets::ListState::default();
            state.select(Some(i));
            state
        });

        if let Some(state) = commands_state {
            f.render_stateful_widget(commands, chunks[1], &mut state.clone());
        } else {
            f.render_widget(commands, chunks[1]);
        }

        // Filter
        if !self.filter_text.is_empty() {
            let filter = Paragraph::new(format!("Filter: {}", self.filter_text))
                .style(Style::default().fg(Color::Yellow));
            f.render_widget(filter, chunks[2]);
        }

        // Status bar with help text or message
        let status = if let Some((msg, color)) = &self.message {
            vec![Span::styled(msg, Style::default().fg(*color))]
        } else if self.show_help {
            vec![
                Span::raw("Press "),
                Span::styled("q", Style::default().fg(Color::Yellow)),
                Span::raw(" to quit, "),
                Span::styled("↑↓/jk", Style::default().fg(Color::Yellow)),
                Span::raw(" to navigate, "),
                Span::styled("c", Style::default().fg(Color::Yellow)),
                Span::raw(" or "),
                Span::styled("y", Style::default().fg(Color::Yellow)),
                Span::raw(" to copy, "),
                Span::styled("?", Style::default().fg(Color::Yellow)),
                Span::raw(" for help"),
            ]
        } else {
            vec![
                Span::raw("Press "),
                Span::styled("?", Style::default().fg(Color::Yellow)),
                Span::raw(" for help"),
            ]
        };

        let status = Paragraph::new(Line::from(status))
            .block(Block::default().borders(Borders::ALL));
        f.render_widget(status, chunks[3]);

        // Render delete confirmation dialog if needed
        if let Some(idx) = self.confirm_delete {
            if let Some(&cmd_idx) = self.filtered_commands.get(idx) {
                if let Some(cmd) = self.commands.get(cmd_idx) {
                    let command_str = format!("Command: {}", cmd.command);
                    let id_str = format!("ID: {}", cmd.id.unwrap_or(0));
                    
                    let dialog_text = vec![
                        "Are you sure you want to delete this command?",
                        "",
                        &command_str,
                        &id_str,
                        "",
                        "Press Enter to confirm or Esc to cancel",
                    ];

                    let dialog = Paragraph::new(dialog_text.join("\n"))
                        .style(Style::default().fg(Color::White))
                        .block(Block::default()
                            .borders(Borders::ALL)
                            .border_style(Style::default().fg(Color::Red))
                            .title("Confirm Delete"));

                    // Center the dialog
                    let area = centered_rect(60, 40, f.size());
                    f.render_widget(Clear, area);
                    f.render_widget(dialog, area);
                }
            }
        }
    }
}

fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    // Calculate popup size based on percentage of screen size
    let popup_width = (r.width as f32 * (percent_x as f32 / 100.0)) as u16;
    let popup_height = (r.height as f32 * (percent_y as f32 / 100.0)) as u16;

    // Calculate popup position to center it
    let popup_x = ((r.width - popup_width) / 2) + r.x;
    let popup_y = ((r.height - popup_height) / 2) + r.y;

    Rect::new(popup_x, popup_y, popup_width, popup_height)
}

fn setup_terminal() -> Result<Terminal<CrosstermBackend<Stdout>>> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;
    terminal.hide_cursor()?;
    Ok(terminal)
}

fn restore_terminal(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
    terminal.show_cursor()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    disable_raw_mode()?;
    colored::control::set_override(true);
    Ok(())
}

fn copy_to_clipboard(text: &str) -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        use std::process::Command;
        let mut child = Command::new("pbcopy")
            .stdin(std::process::Stdio::piped())
            .spawn()?;
        
        if let Some(mut stdin) = child.stdin.take() {
            use std::io::Write;
            stdin.write_all(text.as_bytes())?;
        }
        
        child.wait()?;
    }
    
    #[cfg(target_os = "linux")]
    {
        use std::process::Command;
        let mut child = Command::new("xclip")
            .arg("-selection")
            .arg("clipboard")
            .stdin(std::process::Stdio::piped())
            .spawn()?;
        
        if let Some(mut stdin) = child.stdin.take() {
            use std::io::Write;
            stdin.write_all(text.as_bytes())?;
        }
        
        child.wait()?;
    }
    
    Ok(())
}