ghostscope-ui 0.1.5

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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, Paragraph},
    Frame,
};
use std::time::Instant;

use super::{
    debug_source_style, push_debug_source_count_spans, LoadingProgress, LoadingState,
    ModuleLoadStatus, ModuleState, ProgressRenderer,
};

const MAX_WELCOME_DEBUG_SOURCE_DETAILS: usize = 8;
const MAX_WELCOME_MISSING_EXAMPLES: usize = 3;

/// Enhanced Loading UI component with detailed progress tracking
#[derive(Clone, Debug)]
pub struct LoadingUI {
    start_time: Instant,
    spinner_chars: Vec<char>,
    current_spinner_idx: usize,
    pub progress: LoadingProgress,
}

impl LoadingUI {
    pub fn new() -> Self {
        Self {
            start_time: Instant::now(),
            spinner_chars: vec!['', '', '', '', '', '', '', '', '', ''],
            current_spinner_idx: 0,
            progress: LoadingProgress::new(),
        }
    }

    /// Update spinner animation based on elapsed time
    pub fn update(&mut self) {
        let elapsed = self.start_time.elapsed();
        // Update spinner every 100ms
        let frames = (elapsed.as_millis() / 100) as usize;
        self.current_spinner_idx = frames % self.spinner_chars.len();
    }

    /// Get current spinner character
    fn current_spinner(&self) -> char {
        self.spinner_chars[self.current_spinner_idx]
    }

    /// Get formatted elapsed time
    fn elapsed_time(&self) -> String {
        let elapsed = self.start_time.elapsed();
        let total_seconds = elapsed.as_secs_f64();
        if total_seconds < 60.0 {
            format!("{total_seconds:.1}s")
        } else {
            let minutes = (total_seconds / 60.0).floor() as u64;
            let remaining_seconds = total_seconds - (minutes as f64) * 60.0;
            format!("{minutes}m{remaining_seconds:.1}s")
        }
    }

    /// Render enhanced loading screen with DWARF loading progress
    pub fn render_dwarf_loading(
        f: &mut Frame,
        loading_ui: &mut LoadingUI,
        loading_state: &LoadingState,
        pid: Option<u32>,
    ) {
        loading_ui.update();

        // Clear the entire screen
        f.render_widget(Clear, f.area());

        // Create main layout - more space for content
        let main_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Fill(1),
                Constraint::Length(19), // Height for loading box - increased for wrap support
                Constraint::Fill(1),
            ])
            .split(f.area());

        let horizontal_chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Fill(1),
                Constraint::Length(78), // Width for loading box - increased
                Constraint::Fill(1),
            ])
            .split(main_chunks[1]);

        let loading_area = horizontal_chunks[1];

        // Main loading container with enhanced styling
        let loading_block = Block::default()
            .title(" Ghostscope Tracer ")
            .title_alignment(Alignment::Center)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(Color::Cyan));

        f.render_widget(loading_block, loading_area);

        // Inner content area
        let inner_area = loading_area.inner(ratatui::layout::Margin {
            vertical: 1,
            horizontal: 2,
        });

        // Create content layout
        let content_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(2), // Header line (2 lines for potential wrap)
                Constraint::Length(1), // Copyright line
                Constraint::Length(1), // License line
                Constraint::Length(1), // Empty line
                Constraint::Length(1), // Loading status line
                Constraint::Length(1), // Empty line
                Constraint::Length(1), // Progress bar
                Constraint::Length(1), // Empty line
                Constraint::Length(4), // Recently loaded modules (4 lines)
                Constraint::Length(1), // Current loading status
                Constraint::Length(1), // Stats line
            ])
            .split(inner_area);

        // Header - with wrap support for narrow terminals
        use ratatui::text::Text;
        use ratatui::widgets::Wrap;

        let header_text = Text::from(vec![Line::from(vec![
            Span::styled("🔍 ", Style::default().fg(Color::Yellow)),
            Span::styled(
                format!("Ghostscope v{} - A DWARF-aware eBPF tracer with cgdb-like TUI - explore live processes at runtime", env!("CARGO_PKG_VERSION")),
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ),
        ])]);
        let header_paragraph = Paragraph::new(header_text)
            .alignment(Alignment::Center)
            .wrap(Wrap { trim: true });
        f.render_widget(header_paragraph, content_chunks[0]);

        // Copyright
        let copyright_line = Line::from(Span::styled(
            "Copyright (C) 2025 Ghostscope Project",
            Style::default().fg(Color::Gray),
        ));
        let copyright_paragraph = Paragraph::new(copyright_line).alignment(Alignment::Center);
        f.render_widget(copyright_paragraph, content_chunks[1]);

        // License
        let license_line = Line::from(Span::styled(
            "Licensed under GPL License",
            Style::default().fg(Color::Gray),
        ));
        let license_paragraph = Paragraph::new(license_line).alignment(Alignment::Center);
        f.render_widget(license_paragraph, content_chunks[2]);

        // Loading status with PID
        let status_message = if let Some(pid) = pid {
            format!("Loading debug information for PID {pid}...")
        } else {
            loading_state.message().to_string()
        };

        let status_line = Line::from(vec![
            Span::styled(
                format!("{} ", loading_ui.current_spinner()),
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(status_message, Style::default().fg(Color::White)),
        ]);
        let status_paragraph = Paragraph::new(status_line).alignment(Alignment::Center);
        f.render_widget(status_paragraph, content_chunks[4]);

        // Progress bar - only show if we have modules
        if !loading_ui.progress.modules.is_empty() {
            ProgressRenderer::render_progress_bar(f, content_chunks[6], &loading_ui.progress);
        }

        // Recently loaded modules
        ProgressRenderer::render_recent_modules(f, content_chunks[8], &loading_ui.progress, 4);

        // Current loading status
        ProgressRenderer::render_current_status(f, content_chunks[9], &loading_ui.progress);

        // Stats line
        ProgressRenderer::render_stats(f, content_chunks[10], &loading_ui.progress);
    }

    /// Generate styled welcome message for command panel
    pub fn create_welcome_message(&self, total_time: f64) -> Vec<ratatui::text::Line<'static>> {
        use ratatui::style::{Color, Modifier, Style};
        use ratatui::text::{Line, Span};

        let total_stats = self.progress.total_stats();
        let total_modules = self.progress.total_modules();
        let failed_count = self.progress.failed_count;
        let successful_modules = total_modules - failed_count;

        let mut lines = vec![
            Line::from(Span::styled(
                format!("🔍 Ghostscope v{}", env!("CARGO_PKG_VERSION")),
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                "Licensed under GPL",
                Style::default().fg(Color::Gray),
            )),
            Line::from(""),
            Line::from(Span::styled(
                "✅ Debug Information Loaded:",
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            )),
        ];

        // Module loading stats in white
        if failed_count > 0 {
            lines.push(Line::from(Span::styled(
                format!(
                    "{successful_modules} modules loaded successfully ({failed_count} failed) in {total_time:.1} seconds"
                ),
                Style::default().fg(Color::White),
            )));
        } else {
            lines.push(Line::from(Span::styled(
                format!(
                    "{successful_modules} modules loaded successfully in {total_time:.1} seconds"
                ),
                Style::default().fg(Color::White),
            )));
        }

        // DWARF statistics in yellow
        let functions = total_stats.functions;
        let variables = total_stats.variables;
        let types = total_stats.types;
        lines.push(Line::from(Span::styled(
            format!("{functions} functions, {variables} variables, {types} types indexed"),
            Style::default().fg(Color::Yellow),
        )));

        if self.progress.debug_sources.has_counts() {
            let mut source_spans = vec![Span::styled(
                "• Debug sources: ",
                Style::default().fg(Color::White),
            )];
            push_debug_source_count_spans(&mut source_spans, &self.progress.debug_sources);
            lines.push(Line::from(source_spans));
            append_debug_source_details(&mut lines, &self.progress);
        }

        // Empty line
        lines.push(Line::from(""));

        // Bug reporting info in gray
        lines.push(Line::from(Span::styled(
            "For bug reporting instructions, please see:",
            Style::default().fg(Color::Gray),
        )));

        // GitHub URL in white
        lines.push(Line::from(Span::styled(
            "https://github.com/swananan/ghostscope/issues",
            Style::default().fg(Color::White),
        )));

        lines
    }

    /// Generate completion summary for command panel (backward compatibility)
    pub fn generate_completion_summary(&self, total_time: f64) -> Vec<String> {
        // Convert styled lines back to strings for backward compatibility
        self.create_welcome_message(total_time)
            .into_iter()
            .map(|line| {
                line.spans
                    .into_iter()
                    .map(|span| span.content.to_string())
                    .collect::<String>()
            })
            .collect()
    }

    /// Render the simple loading screen (fallback for non-DWARF loading)
    pub fn render_simple(
        f: &mut Frame,
        loading_ui: &mut LoadingUI,
        message: &str,
        progress: Option<f64>,
    ) {
        loading_ui.update();

        // Clear the entire screen
        f.render_widget(Clear, f.area());

        // Create centered layout
        let vertical_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Fill(1),
                Constraint::Length(8), // Height for loading box
                Constraint::Fill(1),
            ])
            .split(f.area());

        let horizontal_chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Fill(1),
                Constraint::Length(60), // Width for loading box
                Constraint::Fill(1),
            ])
            .split(vertical_chunks[1]);

        let loading_area = horizontal_chunks[1];

        // Main loading container
        let loading_block = Block::default()
            .title(" Ghostscope ")
            .title_alignment(Alignment::Center)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(Color::Cyan));

        f.render_widget(loading_block, loading_area);

        // Inner content area
        let inner_area = loading_area.inner(ratatui::layout::Margin {
            vertical: 1,
            horizontal: 2,
        });

        let content_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(1), // Spinner line
                Constraint::Length(1), // Message line
                Constraint::Length(1), // Empty line
                Constraint::Length(1), // Progress bar (if present)
                Constraint::Length(1), // Time line
            ])
            .split(inner_area);

        // Spinner and status line
        let spinner_line = Line::from(vec![
            Span::styled(
                format!("{} ", loading_ui.current_spinner()),
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "Loading Ghostscope...",
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ),
        ]);

        let spinner_paragraph = Paragraph::new(spinner_line).alignment(Alignment::Center);
        f.render_widget(spinner_paragraph, content_chunks[0]);

        // Message line
        let message_paragraph = Paragraph::new(Line::from(Span::styled(
            message,
            Style::default().fg(Color::Gray),
        )))
        .alignment(Alignment::Center);
        f.render_widget(message_paragraph, content_chunks[1]);

        // Progress bar (if progress is provided)
        if let Some(progress_value) = progress {
            use ratatui::widgets::{Gauge, Padding};
            let progress_bar = Gauge::default()
                .block(
                    Block::default()
                        .borders(Borders::NONE)
                        .padding(Padding::horizontal(1)),
                )
                .gauge_style(Style::default().fg(Color::Cyan))
                .ratio(progress_value.clamp(0.0, 1.0))
                .label(format!("{:.0}%", progress_value * 100.0));
            f.render_widget(progress_bar, content_chunks[3]);
        }

        // Elapsed time
        let time_line = Line::from(Span::styled(
            format!("Elapsed: {}", loading_ui.elapsed_time()),
            Style::default().fg(Color::DarkGray),
        ));
        let time_paragraph = Paragraph::new(time_line).alignment(Alignment::Center);
        f.render_widget(time_paragraph, content_chunks[4]);
    }

    /// Render a smaller loading indicator in a specific area
    pub fn render_inline(f: &mut Frame, area: Rect, loading_ui: &mut LoadingUI, message: &str) {
        loading_ui.update();

        let spinner_text = format!("{} {}", loading_ui.current_spinner(), message);
        let paragraph = Paragraph::new(Line::from(Span::styled(
            spinner_text,
            Style::default().fg(Color::Yellow),
        )));

        f.render_widget(paragraph, area);
    }
}

fn append_debug_source_details(lines: &mut Vec<Line<'static>>, progress: &LoadingProgress) {
    let debug_source_modules: Vec<&ModuleLoadStatus> = progress
        .modules
        .iter()
        .filter(|module| matches!(module.state, ModuleState::Completed))
        .filter(|module| {
            module.stats.as_ref().is_some_and(|stats| {
                stats.debug_source != "missing" && stats.debug_source_path.is_some()
            })
        })
        .collect();

    if !debug_source_modules.is_empty() {
        lines.push(Line::from(Span::styled(
            "• Debug source files:",
            Style::default().fg(Color::White),
        )));

        for module in debug_source_modules
            .iter()
            .take(MAX_WELCOME_DEBUG_SOURCE_DETAILS)
        {
            if let Some(stats) = &module.stats {
                if let Some(path) = stats.debug_source_path.as_deref() {
                    lines.push(Line::from(vec![
                        Span::raw("  "),
                        Span::styled(
                            format!("{:<10}", stats.debug_source),
                            debug_source_style(&stats.debug_source),
                        ),
                        Span::styled("  ", Style::default().fg(Color::DarkGray)),
                        Span::styled(
                            shorten_middle(&module_file_name(&module.path), 34),
                            Style::default().fg(Color::White),
                        ),
                        Span::styled("  ", Style::default().fg(Color::DarkGray)),
                        Span::styled(shorten_path(path, 80), Style::default().fg(Color::Gray)),
                    ]));
                }
            }
        }

        if debug_source_modules.len() > MAX_WELCOME_DEBUG_SOURCE_DETAILS {
            lines.push(Line::from(Span::styled(
                format!(
                    "  ... {} more module(s) omitted",
                    debug_source_modules.len() - MAX_WELCOME_DEBUG_SOURCE_DETAILS
                ),
                Style::default().fg(Color::DarkGray),
            )));
        }
    }

    if progress.debug_sources.missing > 0 {
        lines.push(Line::from(vec![
            Span::styled("• Missing DWARF: ", Style::default().fg(Color::Yellow)),
            Span::styled(
                missing_module_hint(progress),
                Style::default().fg(Color::Yellow),
            ),
        ]));
    }
}

fn missing_module_hint(progress: &LoadingProgress) -> String {
    let missing_modules: Vec<&ModuleLoadStatus> = progress
        .modules
        .iter()
        .filter(|module| matches!(module.state, ModuleState::Completed))
        .filter(|module| {
            module
                .stats
                .as_ref()
                .is_some_and(|stats| stats.debug_source == "missing")
        })
        .collect();

    let count = missing_modules.len();
    if count == 0 {
        return "0 modules".to_string();
    }

    let examples: Vec<String> = missing_modules
        .iter()
        .take(MAX_WELCOME_MISSING_EXAMPLES)
        .map(|module| module_file_name(&module.path))
        .collect();

    let mut message = format!("{count} module{}", if count == 1 { "" } else { "s" });
    if !examples.is_empty() {
        message.push_str(&format!(" ({})", examples.join(", ")));
        if count > examples.len() {
            message.push_str(&format!(" +{} more", count - examples.len()));
        }
    }
    message
}

fn module_file_name(path: &str) -> String {
    std::path::Path::new(path)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(path)
        .to_string()
}

fn shorten_path(path: &str, max_width: usize) -> String {
    let width = path.chars().count();
    if width <= max_width {
        return path.to_string();
    }

    if max_width <= 3 {
        return ".".repeat(max_width);
    }

    let suffix: String = path.chars().skip(width - (max_width - 3)).collect();
    format!("...{suffix}")
}

fn shorten_middle(value: &str, max_width: usize) -> String {
    let width = value.chars().count();
    if width <= max_width {
        return value.to_string();
    }

    if max_width <= 3 {
        return ".".repeat(max_width);
    }

    let prefix_width = (max_width - 3) / 2;
    let suffix_width = max_width - 3 - prefix_width;
    let prefix: String = value.chars().take(prefix_width).collect();
    let suffix: String = value.chars().skip(width - suffix_width).collect();
    format!("{prefix}...{suffix}")
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::loading::ModuleStats;

    #[test]
    fn welcome_message_includes_debug_sources_and_paths() {
        let mut loading_ui = LoadingUI::new();

        loading_ui
            .progress
            .add_module("/usr/local/openresty/luajit/lib/libluajit-5.1.so.2.1.ROLLING".to_string());
        loading_ui.progress.complete_module(
            "/usr/local/openresty/luajit/lib/libluajit-5.1.so.2.1.ROLLING",
            ModuleStats {
                functions: 42,
                variables: 7,
                types: 11,
                debug_source: "embedded".to_string(),
                debug_source_path: Some(
                    "/usr/local/openresty/luajit/lib/libluajit-5.1.so.2.1.ROLLING".to_string(),
                ),
            },
        );

        loading_ui
            .progress
            .add_module("/usr/lib/x86_64-linux-gnu/libcrypt.so.1.1.0".to_string());
        loading_ui.progress.complete_module(
            "/usr/lib/x86_64-linux-gnu/libcrypt.so.1.1.0",
            ModuleStats {
                functions: 0,
                variables: 0,
                types: 0,
                debug_source: "missing".to_string(),
                debug_source_path: None,
            },
        );

        let text = plain_text(&loading_ui.create_welcome_message(1.25));

        assert!(text.contains("Debug sources: embedded:1"));
        assert!(text.contains("missing:1"));
        assert!(text.contains("Debug source files:"));
        assert!(text.contains("embedded"));
        assert!(text.contains("libluajit-5.1.so.2.1.ROLLING  /usr/local/openresty/luajit/lib/"));
        assert!(text.contains("Missing DWARF: 1 module (libcrypt.so.1.1.0)"));
    }

    fn plain_text(lines: &[Line<'static>]) -> String {
        lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }
}