ghostscope-ui 0.1.1

Terminal user interface that streams GhostScope traces with async input handling.
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
use std::collections::HashMap;
use std::time::Instant;

/// File completion cache for command auto-completion
#[derive(Debug)]
pub struct FileCompletionCache {
    /// All source files with full paths
    all_files: Vec<String>,

    /// Index by basename for fast lookup: "main.c" -> [file_index, ...]
    by_basename: HashMap<String, Vec<usize>>,

    /// Index by directory for path-based completion: "src" -> [file_index, ...]
    by_directory: HashMap<String, Vec<usize>>,

    /// Quick hash for change detection
    quick_hash: u64,

    /// Number of files cached
    cached_count: usize,

    /// Last time this cache was used
    last_used: Instant,
}

impl Default for FileCompletionCache {
    fn default() -> Self {
        Self {
            all_files: Vec::new(),
            by_basename: HashMap::new(),
            by_directory: HashMap::new(),
            quick_hash: 0,
            cached_count: 0,
            last_used: Instant::now(),
        }
    }
}

impl FileCompletionCache {
    /// Create new file completion cache from source files
    pub fn new(source_files: &[String]) -> Self {
        let mut cache = Self::default();
        cache.rebuild_cache(source_files);
        cache
    }

    /// Get file completion for the given input
    pub fn get_file_completion(&mut self, input: &str) -> Option<String> {
        self.last_used = Instant::now();

        // Extract command and file part
        let (command_prefix, file_part) = extract_file_context(input)?;

        tracing::debug!(
            "File completion for command '{}', file part '{}'",
            command_prefix,
            file_part
        );

        // Get completion candidates
        let candidates = self.find_completion_candidates(file_part);

        if candidates.is_empty() {
            return None;
        }

        if candidates.len() == 1 {
            // Single match - return the completion
            let full_path = &self.all_files[candidates[0]];
            Some(self.calculate_completion(file_part, full_path))
        } else {
            // Multiple matches - find common prefix
            self.find_common_completion_prefix(file_part, &candidates)
        }
    }

    /// Sync cache from source panel files, returns true if updated
    pub fn sync_from_source_panel(&mut self, source_files: &[String]) -> bool {
        let new_count = source_files.len();
        let new_hash = Self::calculate_quick_hash(source_files);

        // Quick check: no change if count and hash match
        if new_count == self.cached_count && new_hash == self.quick_hash {
            return false;
        }

        tracing::debug!(
            "File completion cache updating: {} -> {} files",
            self.cached_count,
            new_count
        );
        self.rebuild_cache(source_files);
        true
    }

    /// Check if cache has been unused for too long
    pub fn should_cleanup(&self) -> bool {
        self.last_used.elapsed().as_secs() > 300 // 5 minutes
    }

    /// Get all cached file paths (for source panel reuse)
    pub fn get_all_files(&self) -> &[String] {
        &self.all_files
    }

    /// Set all files and rebuild cache
    pub fn set_all_files(&mut self, files: Vec<String>) {
        self.rebuild_cache(&files);
    }

    /// Get number of cached files
    pub fn len(&self) -> usize {
        self.all_files.len()
    }

    /// Check if cache is empty
    pub fn is_empty(&self) -> bool {
        self.all_files.is_empty()
    }

    /// Rebuild the entire cache
    fn rebuild_cache(&mut self, source_files: &[String]) {
        self.all_files.clear();
        self.by_basename.clear();
        self.by_directory.clear();

        self.all_files.extend_from_slice(source_files);
        self.cached_count = source_files.len();
        self.quick_hash = Self::calculate_quick_hash(source_files);

        // Build basename index
        for (idx, file_path) in self.all_files.iter().enumerate() {
            if let Some(basename) = Self::extract_basename(file_path) {
                self.by_basename
                    .entry(basename.to_string())
                    .or_default()
                    .push(idx);
            }

            // Build directory index
            if let Some(dir) = Self::extract_directory(file_path) {
                self.by_directory
                    .entry(dir.to_string())
                    .or_default()
                    .push(idx);
            }
        }

        tracing::debug!(
            "File completion cache rebuilt: {} files, {} basenames, {} directories",
            self.cached_count,
            self.by_basename.len(),
            self.by_directory.len()
        );
    }

    /// Find completion candidates based on input
    fn find_completion_candidates(&self, file_input: &str) -> Vec<usize> {
        if file_input.is_empty() {
            return Vec::new();
        }

        let mut candidates = Vec::new();
        let file_input_lower = file_input.to_lowercase();

        // Strategy 1: Exact prefix match on relative paths
        for (idx, full_path) in self.all_files.iter().enumerate() {
            if let Some(relative) = Self::make_relative_path(full_path) {
                if relative.to_lowercase().starts_with(&file_input_lower) {
                    candidates.push(idx);
                }
            }
        }

        // Strategy 2: If no prefix matches, try basename matching
        if candidates.is_empty() {
            for (idx, full_path) in self.all_files.iter().enumerate() {
                if let Some(basename) = Self::extract_basename(full_path) {
                    if basename.to_lowercase().starts_with(&file_input_lower) {
                        candidates.push(idx);
                    }
                }
            }
        }

        // Strategy 3: If still no matches, try contains matching
        if candidates.is_empty() {
            for (idx, full_path) in self.all_files.iter().enumerate() {
                if full_path.to_lowercase().contains(&file_input_lower) {
                    candidates.push(idx);
                }
            }
        }

        // Limit candidates to avoid performance issues
        candidates.truncate(100);
        candidates
    }

    /// Calculate completion string for a single match
    fn calculate_completion(&self, user_input: &str, full_path: &str) -> String {
        tracing::debug!(
            "calculate_completion: user_input='{}', full_path='{}'",
            user_input,
            full_path
        );

        // Extract the part that user hasn't typed yet
        if let Some(relative) = Self::make_relative_path(full_path) {
            tracing::debug!("relative path: '{}'", relative);
            if relative
                .to_lowercase()
                .starts_with(&user_input.to_lowercase())
            {
                let completion = relative[user_input.len()..].to_string();
                tracing::debug!("relative match: completion='{}'", completion);
                return completion;
            }
        }

        // Fallback: return basename if prefix doesn't match
        if let Some(basename) = Self::extract_basename(full_path) {
            tracing::debug!("basename: '{}'", basename);
            if basename
                .to_lowercase()
                .starts_with(&user_input.to_lowercase())
            {
                let completion = basename[user_input.len()..].to_string();
                tracing::debug!("basename match: completion='{}'", completion);
                return completion;
            }
        }

        tracing::debug!("no match found, returning empty");
        String::new()
    }

    /// Find common prefix among multiple candidates
    fn find_common_completion_prefix(
        &self,
        user_input: &str,
        candidates: &[usize],
    ) -> Option<String> {
        if candidates.len() < 2 {
            return None;
        }

        // Get completion strings for all candidates
        let completions: Vec<String> = candidates
            .iter()
            .map(|&idx| {
                let full_path = &self.all_files[idx];
                self.calculate_completion(user_input, full_path)
            })
            .collect();

        // Find common prefix
        if let Some(first) = completions.first() {
            let mut common_len = first.len();

            for completion in &completions[1..] {
                let matching_chars = first
                    .chars()
                    .zip(completion.chars())
                    .take_while(|(a, b)| a.eq_ignore_ascii_case(b))
                    .count();
                common_len = common_len.min(matching_chars);
            }

            if common_len > 0 {
                let common_prefix = &first[..common_len];
                // Don't complete with just whitespace or single character
                if common_prefix.trim().len() > 1 {
                    return Some(common_prefix.to_string());
                }
            }
        }

        None
    }

    /// Calculate quick hash for change detection
    fn calculate_quick_hash(files: &[String]) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        files.len().hash(&mut hasher);

        // Hash first 10 files for quick comparison
        files.iter().take(10).for_each(|f| f.hash(&mut hasher));

        hasher.finish()
    }

    /// Extract basename from full path
    fn extract_basename(path: &str) -> Option<&str> {
        path.rsplit('/').next()
    }

    /// Extract directory from full path
    fn extract_directory(path: &str) -> Option<&str> {
        if let Some(last_slash) = path.rfind('/') {
            let dir = &path[..last_slash];
            if let Some(second_last_slash) = dir.rfind('/') {
                Some(&dir[second_last_slash + 1..])
            } else {
                Some(dir)
            }
        } else {
            None
        }
    }

    /// Convert full path to relative path for completion
    fn make_relative_path(full_path: &str) -> Option<&str> {
        // Simple heuristic: find common path prefixes to strip
        // For now, just strip everything before src/, lib/, include/, or similar
        let common_dirs = ["src/", "lib/", "include/", "tests/", "test/"];

        for dir in &common_dirs {
            if let Some(pos) = full_path.find(dir) {
                return Some(&full_path[pos..]);
            }
        }

        // Fallback: use basename
        Self::extract_basename(full_path)
    }
}

/// Extract command prefix and file part from input
pub fn extract_file_context(input: &str) -> Option<(&str, &str)> {
    let input = input.trim();

    if let Some(file_part) = input.strip_prefix("info line ") {
        return Some(("info line ", extract_file_part_from_line_spec(file_part)));
    }

    if let Some(file_part) = input.strip_prefix("i l ") {
        return Some(("i l ", extract_file_part_from_line_spec(file_part)));
    }

    if let Some(file_part) = input.strip_prefix("trace ") {
        // For trace command, only provide file completion if it contains path chars
        // This avoids triggering completion for function names
        if contains_path_chars(file_part) {
            return Some(("trace ", extract_file_part_from_line_spec(file_part)));
        }
    }

    // Support file completion for source command
    if let Some(file_part) = input.strip_prefix("source ") {
        return Some(("source ", file_part));
    }

    // Support file completion for save traces command
    if let Some(file_part) = input.strip_prefix("save traces ") {
        // Skip filter keywords
        let file_part = file_part
            .strip_prefix("enabled ")
            .or_else(|| file_part.strip_prefix("disabled "))
            .unwrap_or(file_part);
        if !file_part.is_empty() {
            return Some(("save traces ", file_part));
        }
    }

    // Support abbreviations
    if let Some(file_part) = input.strip_prefix("s ") {
        // Not "s t" which is save traces abbreviation
        if !file_part.starts_with("t ") {
            return Some(("s ", file_part));
        }
    }

    if let Some(file_part) = input.strip_prefix("s t ") {
        // Skip filter keywords for save traces abbreviation
        let file_part = file_part
            .strip_prefix("enabled ")
            .or_else(|| file_part.strip_prefix("disabled "))
            .unwrap_or(file_part);
        if !file_part.is_empty() {
            return Some(("s t ", file_part));
        }
    }

    None
}

/// Extract file part from "file:line" specification
fn extract_file_part_from_line_spec(spec: &str) -> &str {
    // Split on ':' and take the file part
    spec.split(':').next().unwrap_or(spec)
}

/// Check if input contains path-like characters
fn contains_path_chars(input: &str) -> bool {
    input.contains('/') || input.contains('.')
}

/// Check if input needs file completion
pub fn needs_file_completion(input: &str) -> bool {
    extract_file_context(input).is_some()
}

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

    #[test]
    fn test_extract_file_context() {
        assert_eq!(
            extract_file_context("info line main.c:42"),
            Some(("info line ", "main.c"))
        );

        assert_eq!(
            extract_file_context("i l src/utils.h:10"),
            Some(("i l ", "src/utils.h"))
        );

        assert_eq!(
            extract_file_context("trace main.c:100"),
            Some(("trace ", "main.c"))
        );

        assert_eq!(
            extract_file_context("trace function_name"),
            None // No path chars
        );

        assert_eq!(extract_file_context("help"), None);
    }

    #[test]
    fn test_file_completion_basic() {
        let files = vec![
            "/full/path/to/src/main.c".to_string(),
            "/full/path/to/src/utils.c".to_string(),
            "/full/path/to/include/header.h".to_string(),
        ];

        let mut cache = FileCompletionCache::new(&files);

        // Test exact match
        assert_eq!(
            cache.get_file_completion("info line main."),
            Some("c".to_string())
        );

        // Test prefix match
        assert_eq!(
            cache.get_file_completion("i l src/mai"),
            Some("n.c".to_string())
        );
    }

    #[test]
    fn test_file_completion_multiple_matches() {
        let files = vec![
            "/path/src/main.c".to_string(),
            "/path/src/main.h".to_string(),
            "/path/src/manager.c".to_string(),
        ];

        let mut cache = FileCompletionCache::new(&files);

        // Should return common prefix
        assert_eq!(
            cache.get_file_completion("info line mai"),
            Some("n.".to_string()) // Common prefix of "main.c", "main.h"
        );
    }

    #[test]
    fn test_needs_file_completion() {
        assert!(needs_file_completion("info line main.c"));
        assert!(needs_file_completion("i l src/utils.h:42"));
        assert!(needs_file_completion("trace file.c:100"));
        assert!(!needs_file_completion("trace function_name"));
        assert!(!needs_file_completion("help"));
        assert!(!needs_file_completion("enable 1"));
    }
}