par-term 0.30.7

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! Fuzzy command history search overlay UI.
//!
//! Provides a searchable popup for browsing and selecting from command history,
//! with fuzzy matching and ranked results with match highlighting.

use crate::command_history::CommandHistoryEntry;
use crate::ui_constants::{
    CMD_HISTORY_WINDOW_DEFAULT_HEIGHT, CMD_HISTORY_WINDOW_DEFAULT_WIDTH,
    CMD_HISTORY_WINDOW_MAX_HEIGHT,
};
use egui::{Context, Window};
use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;
use std::collections::VecDeque;

/// Command history UI manager using egui
pub struct CommandHistoryUI {
    /// Whether the command history window is currently visible
    pub visible: bool,

    /// Current search query
    search_query: String,

    /// Index of currently selected entry in filtered results
    selected_index: Option<usize>,

    /// Cached command history entries (refreshed when shown)
    cached_entries: Vec<CommandHistoryEntry>,

    /// Fuzzy matcher instance
    matcher: SkimMatcherV2,

    /// Whether the search input should request focus
    request_focus: bool,
}

/// Action to take after showing the UI
#[derive(Debug, Clone)]
pub enum CommandHistoryAction {
    /// No action needed
    None,
    /// Insert the selected command into the terminal
    Insert(String),
}

impl Default for CommandHistoryUI {
    fn default() -> Self {
        Self::new()
    }
}

/// A matched entry with score and match indices for highlighting
struct MatchedEntry {
    index: usize,
    score: i64,
    indices: Vec<usize>,
}

impl CommandHistoryUI {
    /// Create a new command history UI
    pub fn new() -> Self {
        Self {
            visible: false,
            search_query: String::new(),
            selected_index: None,
            cached_entries: Vec::new(),
            matcher: SkimMatcherV2::default(),
            request_focus: false,
        }
    }

    /// Open the command history UI
    pub fn open(&mut self) {
        self.visible = true;
        self.search_query.clear();
        self.request_focus = true;
        self.selected_index = if self.cached_entries.is_empty() {
            None
        } else {
            Some(0)
        };
    }

    /// Close the command history UI
    pub fn close(&mut self) {
        self.visible = false;
        self.search_query.clear();
        self.selected_index = None;
    }

    /// Toggle visibility
    pub fn toggle(&mut self) {
        if self.visible {
            self.close();
        } else {
            self.open();
        }
    }

    /// Update cached entries from persistent command history
    pub fn update_entries(&mut self, entries: &VecDeque<CommandHistoryEntry>) {
        self.cached_entries = entries.iter().cloned().collect();
        // Reset selection if out of bounds
        if let Some(idx) = self.selected_index
            && idx >= self.cached_entries.len()
        {
            self.selected_index = if self.cached_entries.is_empty() {
                None
            } else {
                Some(0)
            };
        }
    }

    /// Navigate selection up
    pub fn select_previous(&mut self) {
        if let Some(idx) = self.selected_index
            && idx > 0
        {
            self.selected_index = Some(idx - 1);
        }
    }

    /// Get the command text of the currently selected entry (if any).
    /// Re-runs fuzzy matching to resolve the filtered index.
    pub fn selected_command(&self) -> Option<String> {
        let idx = self.selected_index?;
        let matches = self.get_matched_entries();
        matches
            .get(idx)
            .map(|m| self.cached_entries[m.index].command.clone())
    }

    /// Navigate selection down
    pub fn select_next(&mut self, filtered_count: usize) {
        if let Some(idx) = self.selected_index {
            if idx < filtered_count.saturating_sub(1) {
                self.selected_index = Some(idx + 1);
            }
        } else if filtered_count > 0 {
            self.selected_index = Some(0);
        }
    }

    /// Get fuzzy-matched and ranked entries based on current search query
    fn get_matched_entries(&self) -> Vec<MatchedEntry> {
        if self.search_query.is_empty() {
            // No query: return all entries in order (newest first)
            return self
                .cached_entries
                .iter()
                .enumerate()
                .map(|(i, _)| MatchedEntry {
                    index: i,
                    score: 0,
                    indices: Vec::new(),
                })
                .collect();
        }

        let mut matches: Vec<MatchedEntry> = self
            .cached_entries
            .iter()
            .enumerate()
            .filter_map(|(i, entry)| {
                self.matcher
                    .fuzzy_indices(&entry.command, &self.search_query)
                    .map(|(score, indices)| MatchedEntry {
                        index: i,
                        score,
                        indices,
                    })
            })
            .collect();

        // Sort by score descending (best matches first)
        matches.sort_by(|a, b| b.score.cmp(&a.score));
        matches
    }

    /// Show the command history window and return any action to take
    pub fn show(&mut self, ctx: &Context) -> CommandHistoryAction {
        if !self.visible {
            return CommandHistoryAction::None;
        }

        let mut action = CommandHistoryAction::None;
        let mut open = true;

        // Calculate center position for initial placement
        let screen_rect = ctx.content_rect();
        let default_pos = egui::pos2(
            (screen_rect.width() - CMD_HISTORY_WINDOW_DEFAULT_WIDTH) / 2.0,
            (screen_rect.height() - CMD_HISTORY_WINDOW_DEFAULT_HEIGHT) / 2.0,
        );

        let matched_entries = self.get_matched_entries();

        Window::new("Command History Search")
            .resizable(true)
            .collapsible(false)
            .default_width(CMD_HISTORY_WINDOW_DEFAULT_WIDTH)
            .default_height(CMD_HISTORY_WINDOW_DEFAULT_HEIGHT)
            .max_height(CMD_HISTORY_WINDOW_MAX_HEIGHT)
            .default_pos(default_pos)
            .open(&mut open)
            .show(ctx, |ui| {
                // Search bar
                ui.horizontal(|ui| {
                    ui.label("Search:");
                    let response = ui.text_edit_singleline(&mut self.search_query);
                    if self.request_focus {
                        response.request_focus();
                        self.request_focus = false;
                    }
                });

                ui.separator();

                // Results count
                ui.horizontal(|ui| {
                    ui.label(format!(
                        "{} / {} commands",
                        matched_entries.len(),
                        self.cached_entries.len()
                    ));
                });

                ui.separator();

                // Entry list
                egui::ScrollArea::vertical()
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        if matched_entries.is_empty() {
                            ui.label("No matching commands");
                        } else {
                            for (filtered_idx, matched) in matched_entries.iter().enumerate() {
                                let entry = &self.cached_entries[matched.index];
                                let is_selected = self.selected_index == Some(filtered_idx);

                                // Build highlighted text
                                let layout_job = build_highlighted_label(
                                    &entry.command,
                                    &matched.indices,
                                    is_selected,
                                    entry.exit_code,
                                    entry.timestamp_ms,
                                );

                                let response = ui.selectable_label(is_selected, layout_job);

                                if response.clicked() {
                                    self.selected_index = Some(filtered_idx);
                                }

                                if response.double_clicked() {
                                    action = CommandHistoryAction::Insert(entry.command.clone());
                                    self.visible = false;
                                }

                                // Show tooltip with full command and metadata on hover
                                // Auto-scroll to selected item
                                let response = response.on_hover_text(format_tooltip(entry));
                                if is_selected {
                                    response.scroll_to_me(Some(egui::Align::Center));
                                }
                            }
                        }
                    });

                ui.separator();

                // Action buttons
                ui.horizontal(|ui| {
                    if ui.button("Insert Selected").clicked()
                        && let Some(idx) = self.selected_index
                        && let Some(matched) = matched_entries.get(idx)
                    {
                        let entry = &self.cached_entries[matched.index];
                        action = CommandHistoryAction::Insert(entry.command.clone());
                        self.visible = false;
                    }

                    if ui.button("Close").clicked() {
                        self.visible = false;
                    }
                });

                // Keyboard hints
                ui.separator();
                ui.horizontal(|ui| {
                    ui.label("Hints:");
                    ui.label("\u{f062}\u{f063} Navigate");
                    ui.label("Enter Insert");
                    ui.label("Esc Close");
                });
            });

        // Handle window close
        if !open {
            self.visible = false;
        }

        action
    }
}

impl crate::traits::OverlayComponent for CommandHistoryUI {
    type Action = CommandHistoryAction;

    fn show(&mut self, ctx: &egui::Context) -> Self::Action {
        CommandHistoryUI::show(self, ctx)
    }

    fn is_visible(&self) -> bool {
        self.visible
    }

    fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }
}

/// Build an egui LayoutJob with fuzzy match highlighting
fn build_highlighted_label(
    command: &str,
    match_indices: &[usize],
    is_selected: bool,
    exit_code: Option<i32>,
    timestamp_ms: u64,
) -> egui::text::LayoutJob {
    let mut job = egui::text::LayoutJob::default();

    // Exit code indicator
    let status_color = match exit_code {
        Some(0) => egui::Color32::from_rgb(100, 200, 100), // Green for success
        Some(_) => egui::Color32::from_rgb(200, 100, 100), // Red for failure
        None => egui::Color32::from_rgb(150, 150, 150),    // Gray for unknown
    };
    // Use Nerd Font PUA codepoints (confirmed in SymbolsNerdFontMono-Regular):
    // U+F05D = fa-check-circle, U+F057 = fa-times-circle
    // Unknown exit code falls back to ASCII '?' (always renderable)
    let status_char = match exit_code {
        Some(0) => "\u{f05d} ",
        Some(_) => "\u{f057} ",
        None => "? ",
    };
    job.append(
        status_char,
        0.0,
        egui::TextFormat {
            color: status_color,
            ..Default::default()
        },
    );

    // Command text with highlighting
    let normal_color = if is_selected {
        egui::Color32::WHITE
    } else {
        egui::Color32::from_rgb(220, 220, 220)
    };
    let highlight_color = egui::Color32::from_rgb(255, 200, 0); // Yellow highlight

    let chars: Vec<char> = command.chars().collect();
    // Truncate display for very long commands
    let display_len = chars.len().min(120);

    let mut i = 0;
    while i < display_len {
        let is_match = match_indices.contains(&i);
        let color = if is_match {
            highlight_color
        } else {
            normal_color
        };

        // Batch consecutive chars with same highlight state
        let start = i;
        while i < display_len && match_indices.contains(&i) == is_match {
            i += 1;
        }

        let text: String = chars[start..i].iter().collect();
        let format = if is_match {
            egui::TextFormat {
                color,
                underline: egui::Stroke::new(1.0, highlight_color),
                ..Default::default()
            }
        } else {
            egui::TextFormat {
                color,
                ..Default::default()
            }
        };
        job.append(&text, 0.0, format);
    }

    if chars.len() > 120 {
        job.append(
            "...",
            0.0,
            egui::TextFormat {
                color: egui::Color32::GRAY,
                ..Default::default()
            },
        );
    }

    // Timestamp suffix
    let time_str = format_relative_time(timestamp_ms);
    job.append(
        &format!("  {time_str}"),
        0.0,
        egui::TextFormat {
            color: egui::Color32::from_rgb(120, 120, 120),
            ..Default::default()
        },
    );

    job
}

/// Format a tooltip with full command details
fn format_tooltip(entry: &CommandHistoryEntry) -> String {
    let mut parts = vec![entry.command.clone()];
    if let Some(code) = entry.exit_code {
        parts.push(format!("Exit: {code}"));
    }
    if let Some(ms) = entry.duration_ms {
        parts.push(format!("Duration: {}ms", ms));
    }
    parts.push(format_relative_time(entry.timestamp_ms));
    parts.join("\n")
}

/// Format a timestamp as relative time (e.g., "5m ago")
fn format_relative_time(timestamp_ms: u64) -> String {
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    let time = UNIX_EPOCH + Duration::from_millis(timestamp_ms);
    if let Ok(elapsed) = SystemTime::now().duration_since(time) {
        let secs = elapsed.as_secs();
        if secs < 60 {
            format!("{secs}s ago")
        } else if secs < 3600 {
            format!("{}m ago", secs / 60)
        } else if secs < 86400 {
            format!("{}h ago", secs / 3600)
        } else {
            format!("{}d ago", secs / 86400)
        }
    } else {
        "just now".to_string()
    }
}