rpi-tui 0.36.2

Terminal User Interface for pi-rust
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
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
//! Alt screen search functionality.
//!
//! Provides search functionality for the alternate screen TUI.

use std::ops::Range;
use std::sync::{Arc, Mutex};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::utils::visible_width;

const UNSELECTED_MATCH: usize = usize::MAX;

/// Search state.
#[derive(Debug, Clone, Default)]
pub struct SearchState {
    /// Current search query.
    pub query: String,
    /// Current match index.
    pub match_index: usize,
    /// All match positions (line, column).
    pub matches: Vec<SearchMatch>,
    /// Whether search is active.
    pub active: bool,
}

/// A search match.
#[derive(Debug, Clone, Copy)]
pub struct SearchMatch {
    /// Line index.
    pub line: usize,
    /// Start byte offset in the line with ANSI escapes removed.
    pub column: usize,
    /// Matched byte length in the line with ANSI escapes removed.
    pub length: usize,
}

/// Alt screen search handler.
pub struct AltScreenSearch {
    state: Mutex<SearchState>,
    on_search: Mutex<Option<Arc<dyn Fn(&str) + Send + Sync>>>,
    on_match: Mutex<Option<Arc<dyn Fn(usize, usize) + Send + Sync>>>,
    on_close: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
}

impl AltScreenSearch {
    /// Create a new search handler.
    pub fn new() -> Self {
        Self {
            state: Mutex::new(SearchState::default()),
            on_search: Mutex::new(None),
            on_match: Mutex::new(None),
            on_close: Mutex::new(None),
        }
    }

    /// Set search callback.
    pub fn on_search(&self, callback: Arc<dyn Fn(&str) + Send + Sync>) {
        if let Ok(mut cb) = self.on_search.lock() {
            *cb = Some(callback);
        }
    }

    /// Set match callback.
    pub fn on_match(&self, callback: Arc<dyn Fn(usize, usize) + Send + Sync>) {
        if let Ok(mut cb) = self.on_match.lock() {
            *cb = Some(callback);
        }
    }

    /// Set close callback.
    pub fn on_close(&self, callback: Arc<dyn Fn() + Send + Sync>) {
        if let Ok(mut cb) = self.on_close.lock() {
            *cb = Some(callback);
        }
    }

    /// Check if search is active.
    pub fn is_active(&self) -> bool {
        self.state.lock().map(|s| s.active).unwrap_or(false)
    }

    /// Get current query.
    pub fn get_query(&self) -> String {
        self.state
            .lock()
            .map(|s| s.query.clone())
            .unwrap_or_default()
    }

    /// Get current match index.
    pub fn get_match_index(&self) -> usize {
        self.state
            .lock()
            .map(|s| selected_index(s.match_index))
            .unwrap_or(0)
    }

    /// Get total match count.
    pub fn get_match_count(&self) -> usize {
        self.state.lock().map(|s| s.matches.len()).unwrap_or(0)
    }

    /// Activate search.
    pub fn activate(&self) {
        if let Ok(mut state) = self.state.lock() {
            state.active = true;
            state.query.clear();
            state.matches.clear();
            state.match_index = UNSELECTED_MATCH;
        }
    }

    /// Deactivate search.
    pub fn deactivate(&self) {
        if let Ok(mut state) = self.state.lock() {
            state.active = false;
        }

        if let Ok(cb) = self.on_close.lock() {
            if let Some(callback) = cb.as_ref() {
                callback();
            }
        }
    }

    /// Toggle search.
    pub fn toggle(&self) {
        if self.is_active() {
            self.deactivate();
        } else {
            self.activate();
        }
    }

    /// Update search query.
    pub fn set_query(&self, query: &str) {
        if let Ok(mut state) = self.state.lock() {
            state.query = query.to_string();
            state.match_index = UNSELECTED_MATCH;
            state.matches.clear();
        }

        if let Ok(cb) = self.on_search.lock() {
            if let Some(callback) = cb.as_ref() {
                callback(query);
            }
        }
    }

    /// Add character to query.
    pub fn append_char(&self, c: char) {
        let new_query = format!("{}{}", self.get_query(), c);
        self.set_query(&new_query);
    }

    /// Remove last character from query.
    pub fn backspace(&self) {
        let mut query = self.get_query();
        if !query.is_empty() {
            query.pop();
            self.set_query(&query);
        }
    }

    /// Find matches in content.
    pub fn find_matches(&self, lines: &[String]) -> Vec<SearchMatch> {
        let (query, matches) = self.scan_lines(lines.iter().map(String::as_str));
        self.publish_matches(&query, matches.clone());
        matches
    }

    /// Search borrowed rows and retain only one copy of the matches.
    pub fn update_matches<'a>(&self, lines: impl IntoIterator<Item = &'a str>) {
        let (query, matches) = self.scan_lines(lines);
        self.publish_matches(&query, matches);
    }

    fn scan_lines<'a>(
        &self,
        lines: impl IntoIterator<Item = &'a str>,
    ) -> (String, Vec<SearchMatch>) {
        let query = self.get_query();
        if query.is_empty() {
            return (query, Vec::new());
        }
        let query_lower = query.to_lowercase();
        let mut matches = Vec::new();
        for (line_idx, line) in lines.into_iter().enumerate() {
            let stripped = crate::ansi::strip_ansi(line);
            for_each_match(&stripped, &query_lower, |range| {
                matches.push(SearchMatch {
                    line: line_idx,
                    column: range.start,
                    length: range.len(),
                });
            });
        }
        (query, matches)
    }

    fn publish_matches(&self, query: &str, matches: Vec<SearchMatch>) {
        if let Ok(mut state) = self.state.lock() {
            if state.query == query {
                if state.match_index >= matches.len() {
                    state.match_index = UNSELECTED_MATCH;
                }
                state.matches = matches;
            }
        }
    }

    /// Go to next match.
    pub fn next_match(&self) -> Option<SearchMatch> {
        self.move_match(false)
    }

    /// Go to previous match.
    pub fn previous_match(&self) -> Option<SearchMatch> {
        self.move_match(true)
    }

    fn move_match(&self, backwards: bool) -> Option<SearchMatch> {
        let match_result = {
            let mut state = self.state.lock().ok()?;
            let count = state.matches.len();
            if count == 0 {
                return None;
            }
            state.match_index = if backwards {
                match state.match_index {
                    0 | UNSELECTED_MATCH => count - 1,
                    index => index - 1,
                }
            } else {
                match state.match_index {
                    UNSELECTED_MATCH => 0,
                    index => (index + 1) % count,
                }
            };
            state.matches[state.match_index]
        };

        if let Ok(cb) = self.on_match.lock() {
            if let Some(callback) = cb.as_ref() {
                callback(match_result.line, match_result.column);
            }
        }

        Some(match_result)
    }

    /// Get current match.
    pub fn current_match(&self) -> Option<SearchMatch> {
        let state = self.state.lock().ok()?;
        if state.matches.is_empty() {
            return None;
        }
        state
            .matches
            .get(selected_index(state.match_index))
            .copied()
    }

    /// Render search bar.
    pub fn render(&self, width: usize) -> String {
        let state = self.state.lock().unwrap_or_else(|e| e.into_inner());

        let match_info = if state.matches.is_empty() {
            "No matches".to_string()
        } else {
            format!(
                "{}/{}",
                selected_index(state.match_index) + 1,
                state.matches.len()
            )
        };

        let prompt = "Search: ";
        let prompt_len = visible_width(prompt);
        let info_len = visible_width(&match_info) + 3; // +3 for " | "

        let available = width.saturating_sub(prompt_len + info_len);

        let query_display = query_tail(&state.query, available);

        // Build the search bar with styling
        format!(
            "\x1b[7m{}{}\x1b[0m \x1b[90m{}\x1b[0m",
            prompt, query_display, match_info
        )
    }

    /// Highlight matches in a line.
    pub fn highlight_line(&self, line: &str) -> String {
        let query = self.get_query();
        if query.is_empty() {
            return line.to_string();
        }

        let stripped = crate::ansi::strip_ansi(line);
        let mut ranges = Vec::new();
        for_each_match(&stripped, &query.to_lowercase(), |range| ranges.push(range));
        let mut ranges = ranges.into_iter().peekable();
        if ranges.peek().is_none() {
            return line.to_string();
        }

        let mut result = String::with_capacity(line.len());
        let mut raw_end = 0;
        let mut visible_end = 0;
        crate::ansi::for_each_visible_char(line, |raw_start, ch| {
            result.push_str(&line[raw_end..raw_start]);
            if ranges.peek().is_some_and(|range| {
                range.start == visible_end || (range.contains(&visible_end) && raw_start > raw_end)
            }) {
                result.push_str("\x1b[43m");
            }
            result.push(ch);
            raw_end = raw_start + ch.len_utf8();
            visible_end += ch.len_utf8();
            if ranges.peek().is_some_and(|range| range.end == visible_end) {
                ranges.next();
                result.push_str("\x1b[49m");
            }
        });
        result.push_str(&line[raw_end..]);
        result
    }
}

fn selected_index(index: usize) -> usize {
    if index == UNSELECTED_MATCH {
        0
    } else {
        index
    }
}

fn query_tail(query: &str, width: usize) -> String {
    if UnicodeWidthStr::width(query) <= width {
        return query.to_owned();
    }
    let ellipsis = &"..."[..width.min(3)];
    let mut remaining = width - ellipsis.len();
    let mut start = query.len();
    for (offset, grapheme) in query.grapheme_indices(true).rev() {
        let cells = UnicodeWidthStr::width(grapheme);
        if cells > remaining {
            break;
        }
        remaining -= cells;
        start = offset;
    }
    format!("{ellipsis}{}", &query[start..])
}

fn for_each_match(text: &str, query_lower: &str, mut visit: impl FnMut(Range<usize>)) {
    let lower = text.to_lowercase();
    let mut matches = lower.match_indices(query_lower).peekable();
    if text.is_ascii() {
        for (start, hit) in matches {
            visit(start..start + hit.len());
        }
        return;
    }
    if matches.peek().is_none() {
        return;
    }

    // Map each lowercase character boundary back to the original line.
    // Lowercasing İ, for example, expands it to i plus a combining mark.
    let mut boundaries = vec![(0, 0)];
    let mut lower_end = 0;
    for (start, ch) in text.char_indices() {
        lower_end += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
        boundaries.push((lower_end, start + ch.len_utf8()));
    }
    let mut last_end = 0;
    for (lower_start, hit) in matches {
        let start = boundaries.partition_point(|(offset, _)| *offset <= lower_start) - 1;
        let end = boundaries.partition_point(|(offset, _)| *offset < lower_start + hit.len());
        let range = boundaries[start].1..boundaries[end].1;
        if range.start >= last_end {
            last_end = range.end;
            visit(range);
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_search_activate() {
        let search = AltScreenSearch::new();
        search.activate();
        assert!(search.is_active());
    }

    #[test]
    fn test_search_query() {
        let search = AltScreenSearch::new();
        search.set_query("test");
        assert_eq!(search.get_query(), "test");
    }

    #[test]
    fn test_find_matches() {
        let search = AltScreenSearch::new();
        search.set_query("hello");

        let lines = vec![
            "hello world".to_string(),
            "foo bar".to_string(),
            "hello again".to_string(),
        ];

        let matches = search.find_matches(&lines);
        assert_eq!(matches.len(), 2);
        assert_eq!(matches[0].line, 0);
        assert_eq!(matches[1].line, 2);
    }

    #[test]
    fn test_next_match() {
        let search = AltScreenSearch::new();
        search.set_query("test");

        let lines = vec!["test one".to_string(), "test two".to_string()];

        search.find_matches(&lines);
        let m1 = search.next_match();
        assert_eq!(m1.unwrap().line, 0);

        let m2 = search.next_match();
        assert_eq!(m2.unwrap().line, 1);

        // Wraps around
        let m3 = search.next_match();
        assert_eq!(m3.unwrap().line, 0);
        assert_eq!(search.previous_match().unwrap().line, 1);
        assert_eq!(search.get_match_index(), 1);
        assert_eq!(search.current_match().unwrap().line, 1);
    }

    #[test]
    fn unicode_search_returns_original_byte_ranges_and_clears_empty_queries() {
        let search = AltScreenSearch::new();
        search.set_query("İ");
        let line = "中İ İt".to_owned();
        let matches = search.find_matches(std::slice::from_ref(&line));
        assert_eq!(matches.len(), 2);
        assert_eq!(matches[0].column, "中".len());
        assert!(matches
            .iter()
            .all(|hit| &line[hit.column..hit.column + hit.length] == "İ"));
        search.set_query("T");
        let matches = search.find_matches(std::slice::from_ref(&line));
        assert_eq!(matches[0].column, "中İ İ".len());
        search.backspace();
        search.update_matches([line.as_str()]);
        assert_eq!(search.get_match_count(), 0);
        assert!(search.next_match().is_none());
    }

    #[test]
    fn unicode_highlight_and_query_truncation_preserve_character_boundaries() {
        let search = AltScreenSearch::new();
        search.set_query("İ中");
        let line = "aİ\x1b[31m中\x1b[39mb";
        let highlighted = search.highlight_line(line);
        assert_eq!(crate::ansi::strip_ansi(&highlighted), "aİ中b");
        assert!(highlighted.contains("\x1b[43mİ"));
        assert!(highlighted.contains("\x1b[43m中\x1b[49m"));
        assert_eq!(query_tail("abc中👩‍💻", 5), "...👩‍💻");
    }
}