presentar-terminal 0.3.5

Terminal backend for Presentar UI framework with zero-allocation rendering
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
//! cbtop-bench: Headless benchmarking tool for cbtop widgets.
//!
//! This tool enables automated performance testing, CI/CD integration,
//! and deterministic output capture without requiring a terminal display.
//!
//! # Usage
//!
//! ```bash
//! # Basic benchmark
//! cbtop-bench --widget cpu-grid --width 80 --height 24 --frames 1000
//!
//! # Deterministic mode for CI
//! cbtop-bench --deterministic --output metrics.json
//!
//! # Full benchmark suite
//! cbtop-bench suite --all --output results/
//! ```

use clap::{Parser, Subcommand};
use presentar_core::Rect;
use presentar_terminal::tools::bench::{
    BenchmarkHarness, BenchmarkResult, DeterministicContext, PerformanceTargets, RenderMetrics,
};
use presentar_terminal::{
    BrailleGraph, CpuGrid, GraphMode, MemoryBar, MemorySegment, ProcessTable,
};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::Instant;

/// Headless benchmarking tool for cbtop widgets.
#[derive(Parser)]
#[command(
    name = "cbtop-bench",
    version,
    about = "Headless benchmarking for cbtop widgets"
)]
struct Cli {
    /// Widget to benchmark.
    #[arg(long)]
    widget: Option<String>,

    /// Terminal width.
    #[arg(long, default_value = "80")]
    width: u16,

    /// Terminal height.
    #[arg(long, default_value = "24")]
    height: u16,

    /// Number of benchmark frames.
    #[arg(long, default_value = "1000")]
    frames: u32,

    /// Warmup frames.
    #[arg(long, default_value = "100")]
    warmup: u32,

    /// Enable deterministic mode.
    #[arg(long)]
    deterministic: bool,

    /// Output file (JSON metrics).
    #[arg(long, short)]
    output: Option<PathBuf>,

    /// Output format (json, csv, text).
    #[arg(long, default_value = "text")]
    format: String,

    /// Validate against performance targets.
    #[arg(long)]
    validate: bool,

    /// Use strict performance targets.
    #[arg(long)]
    strict: bool,

    /// Verbose output.
    #[arg(long, short)]
    verbose: bool,

    /// Subcommand.
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Run full benchmark suite.
    Suite {
        /// Run all widgets.
        #[arg(long)]
        all: bool,

        /// Output directory.
        #[arg(long)]
        output: PathBuf,
    },
    /// Compare two widgets.
    Compare {
        /// First widget.
        #[arg(long)]
        widget_a: String,

        /// Second widget.
        #[arg(long)]
        widget_b: String,
    },
    /// Generate snapshot for pixel-perfect testing.
    Snapshot {
        /// Widget to snapshot.
        #[arg(long)]
        widget: String,

        /// Output file.
        #[arg(long)]
        output: PathBuf,
    },
    /// Validate results against targets.
    Validate {
        /// Results JSON file.
        #[arg(long)]
        results: PathBuf,
    },
}

fn main() {
    let cli = Cli::parse();

    match &cli.command {
        Some(Commands::Suite { all, output }) => {
            run_suite(*all, output, &cli);
        }
        Some(Commands::Compare { widget_a, widget_b }) => {
            run_compare(widget_a, widget_b, &cli);
        }
        Some(Commands::Snapshot { widget, output }) => {
            run_snapshot(widget, output, &cli);
        }
        Some(Commands::Validate { results }) => {
            run_validate(results, &cli);
        }
        None => {
            if let Some(ref widget) = cli.widget {
                run_single_benchmark(widget, &cli);
            } else {
                // Default: run all widgets
                run_suite(true, &PathBuf::from("bench_results"), &cli);
            }
        }
    }
}

fn run_single_benchmark(widget_name: &str, cli: &Cli) {
    let start = Instant::now();

    if cli.verbose {
        eprintln!("Benchmarking widget: {}", widget_name);
        eprintln!(
            "  Dimensions: {}x{}, Warmup: {}, Frames: {}",
            cli.width, cli.height, cli.warmup, cli.frames
        );
    }

    let result = benchmark_widget(widget_name, cli);

    if cli.verbose {
        eprintln!("  Completed in {:?}", start.elapsed());
    }

    output_result(&result, cli);

    if cli.validate {
        validate_result(&result, cli);
    }
}

fn benchmark_widget(widget_name: &str, cli: &Cli) -> BenchmarkResult {
    let mut harness = BenchmarkHarness::new(cli.width, cli.height)
        .with_frames(cli.warmup, cli.frames)
        .with_deterministic(cli.deterministic);

    let bounds = Rect::new(0.0, 0.0, cli.width as f32, cli.height as f32);

    match widget_name.to_lowercase().as_str() {
        "cpu-grid" | "cpugrid" => {
            let ctx = DeterministicContext::new();
            let mut widget = CpuGrid::new(ctx.cpu_usage.clone())
                .with_columns(8)
                .compact();
            harness.benchmark(&mut widget, bounds)
        }
        "braille-graph" | "braillegraph" | "graph" => {
            let data: Vec<f64> = (0..60)
                .map(|i| (i as f64 * 0.1).sin() * 50.0 + 50.0)
                .collect();
            let mut widget = BrailleGraph::new(data).with_mode(GraphMode::Braille);
            harness.benchmark(&mut widget, bounds)
        }
        "memory-bar" | "memorybar" => {
            use presentar_core::Color;
            let mut widget = MemoryBar::new(32_000_000_000);
            widget.add_segment(MemorySegment::new(
                "Used",
                18_200_000_000,
                Color::new(0.3, 0.7, 1.0, 1.0),
            ));
            widget.add_segment(MemorySegment::new(
                "Cached",
                8_000_000_000,
                Color::new(0.5, 0.5, 0.5, 1.0),
            ));
            widget.add_segment(MemorySegment::new(
                "Free",
                5_800_000_000,
                Color::new(0.2, 0.8, 0.3, 1.0),
            ));
            harness.benchmark(&mut widget, bounds)
        }
        "process-table" | "processtable" => {
            let mut widget = ProcessTable::new();
            // Add some test processes
            use presentar_terminal::{ProcessEntry, ProcessState};
            widget.set_processes(vec![
                ProcessEntry {
                    pid: 1,
                    user: "root".to_string(),
                    cpu_percent: 0.1,
                    mem_percent: 0.5,
                    command: "systemd".to_string(),
                    cmdline: Some("/sbin/init".to_string()),
                    state: ProcessState::Sleeping,
                    oom_score: Some(0),
                    cgroup: None,
                    nice: Some(0),
                },
                ProcessEntry {
                    pid: 1000,
                    user: "noah".to_string(),
                    cpu_percent: 45.2,
                    mem_percent: 8.3,
                    command: "claude".to_string(),
                    cmdline: Some("claude-code".to_string()),
                    state: ProcessState::Running,
                    oom_score: Some(100),
                    cgroup: None,
                    nice: Some(0),
                },
            ]);
            harness.benchmark(&mut widget, bounds)
        }
        _ => {
            eprintln!("Unknown widget: {}", widget_name);
            eprintln!("Available widgets: cpu-grid, braille-graph, memory-bar, process-table");
            std::process::exit(1);
        }
    }
}

fn output_result(result: &BenchmarkResult, cli: &Cli) {
    let output = match cli.format.as_str() {
        "json" => result.to_json(),
        "csv" => {
            format!(
                "{}\n{}",
                RenderMetrics::csv_header(),
                result
                    .metrics
                    .to_csv_row(&result.widget_name, result.width, result.height)
            )
        }
        _ => format_text_output(result),
    };

    if let Some(ref path) = cli.output {
        let mut file = fs::File::create(path).expect("Failed to create output file");
        file.write_all(output.as_bytes())
            .expect("Failed to write output");
        if cli.verbose {
            eprintln!("Results written to: {}", path.display());
        }
    } else {
        println!("{}", output);
    }
}

fn format_text_output(result: &BenchmarkResult) -> String {
    let metrics = &result.metrics;
    let ft = &metrics.frame_times;

    format!(
        r#"
╔══════════════════════════════════════════════════════════════════╗
║                    BENCHMARK RESULTS                              ║
╠══════════════════════════════════════════════════════════════════╣
║  Widget: {:<54} ║
║  Dimensions: {}x{:<52} ║
╠══════════════════════════════════════════════════════════════════╣
║  FRAME TIME STATISTICS                                            ║
║  ────────────────────────────────────────────────────────────────║
║  Frames:     {:<54} ║
║  Min:        {:<50} µs ║
║  Max:        {:<50} µs ║
║  Mean:       {:<48.1} µs ║
║  P50:        {:<50} µs ║
║  P95:        {:<50} µs ║
║  P99:        {:<50} µs ║
║  Std Dev:    {:<48.1} µs ║
╠══════════════════════════════════════════════════════════════════╣
║  TARGET COMPLIANCE                                                ║
║  ────────────────────────────────────────────────────────────────║
║  60fps (16.67ms): {:<48} ║
║  1ms p99:         {:<48} ║
╚══════════════════════════════════════════════════════════════════╝
"#,
        result.widget_name,
        result.width,
        result.height,
        metrics.frame_count,
        ft.min_us,
        ft.max_us,
        ft.mean_us,
        ft.p50_us,
        ft.p95_us,
        ft.p99_us,
        ft.stddev_us,
        if ft.max_us <= 16_667 {
            "✓ PASS"
        } else {
            "✗ FAIL"
        },
        if ft.p99_us <= 1_000 {
            "✓ PASS"
        } else {
            "✗ FAIL"
        },
    )
}

fn validate_result(result: &BenchmarkResult, cli: &Cli) {
    let targets = if cli.strict {
        PerformanceTargets::strict()
    } else {
        PerformanceTargets::default()
    };

    if result.meets_targets(&targets) {
        if cli.verbose {
            eprintln!("✓ Performance targets met");
        }
    } else {
        eprintln!("✗ Performance targets NOT met");
        eprintln!(
            "  Max frame: {}µs (target: {}µs)",
            result.metrics.frame_times.max_us, targets.max_frame_us
        );
        eprintln!(
            "  P99 frame: {}µs (target: {}µs)",
            result.metrics.frame_times.p99_us, targets.p99_frame_us
        );
        std::process::exit(1);
    }
}

fn run_suite(all: bool, output_dir: &PathBuf, cli: &Cli) {
    let widgets = if all {
        vec!["cpu-grid", "braille-graph", "memory-bar", "process-table"]
    } else {
        vec!["cpu-grid"]
    };

    fs::create_dir_all(output_dir).expect("Failed to create output directory");

    let mut all_results = Vec::new();

    for widget in widgets {
        if cli.verbose {
            eprintln!("Benchmarking: {}", widget);
        }

        let result = benchmark_widget(widget, cli);
        all_results.push(result.clone());

        // Write individual result
        let path = output_dir.join(format!("{}.json", widget));
        let json = result.to_json();
        fs::write(&path, json).expect("Failed to write result");
    }

    // Write summary CSV
    let csv_path = output_dir.join("summary.csv");
    let mut csv = String::from(RenderMetrics::csv_header());
    csv.push('\n');
    for result in &all_results {
        csv.push_str(
            &result
                .metrics
                .to_csv_row(&result.widget_name, result.width, result.height),
        );
        csv.push('\n');
    }
    fs::write(&csv_path, csv).expect("Failed to write CSV summary");

    // Write summary JSON
    let summary_path = output_dir.join("summary.json");
    let summary_json = format!(
        r#"{{
  "total_widgets": {},
  "all_passed": {},
  "results": [{}]
}}"#,
        all_results.len(),
        all_results
            .iter()
            .all(|r| r.meets_targets(&PerformanceTargets::default())),
        all_results
            .iter()
            .map(|r| format!("\"{}\"", r.widget_name))
            .collect::<Vec<_>>()
            .join(", ")
    );
    fs::write(&summary_path, summary_json).expect("Failed to write summary JSON");

    println!("Suite complete. Results in: {}", output_dir.display());
    println!("  - Individual results: <widget>.json");
    println!("  - Summary CSV: summary.csv");
    println!("  - Summary JSON: summary.json");
}

fn run_compare(widget_a: &str, widget_b: &str, cli: &Cli) {
    let mut harness = BenchmarkHarness::new(cli.width, cli.height)
        .with_frames(cli.warmup, cli.frames)
        .with_deterministic(cli.deterministic);

    let bounds = Rect::new(0.0, 0.0, cli.width as f32, cli.height as f32);

    // Create widgets for comparison
    let ctx = DeterministicContext::new();
    let data: Vec<f64> = (0..60)
        .map(|i| (i as f64 * 0.1).sin() * 50.0 + 50.0)
        .collect();

    let result = match (
        widget_a.to_lowercase().as_str(),
        widget_b.to_lowercase().as_str(),
    ) {
        ("braille", "block") => {
            let mut braille = BrailleGraph::new(data.clone()).with_mode(GraphMode::Braille);
            let mut block = BrailleGraph::new(data).with_mode(GraphMode::Block);
            harness.compare(&mut braille, &mut block, bounds)
        }
        _ => {
            eprintln!(
                "Comparison not implemented for: {} vs {}",
                widget_a, widget_b
            );
            eprintln!("Available comparisons: braille vs block");
            std::process::exit(1);
        }
    };

    println!("Comparison: {} vs {}", widget_a, widget_b);
    println!("{}", result.summary());
    println!();
    println!(
        "  {} faster: {}",
        if result.a_is_faster() {
            widget_a
        } else {
            widget_b
        },
        if result.a_is_faster() {
            format!("{:.2}x", result.speedup_ratio())
        } else {
            format!("{:.2}x", 1.0 / result.speedup_ratio())
        }
    );
}

fn run_snapshot(widget_name: &str, output_path: &PathBuf, cli: &Cli) {
    let result = benchmark_widget(widget_name, cli);

    fs::write(output_path, &result.final_frame).expect("Failed to write snapshot");

    if cli.verbose {
        eprintln!("Snapshot written to: {}", output_path.display());
    }
}

fn run_validate(results_path: &PathBuf, cli: &Cli) {
    let content = fs::read_to_string(results_path).expect("Failed to read results file");

    // Simple validation - check for "meets_targets": true
    let targets = if cli.strict {
        PerformanceTargets::strict()
    } else {
        PerformanceTargets::default()
    };

    if content.contains("\"meets_targets\": true") || content.contains("all_passed\": true") {
        println!("✓ All benchmarks passed performance targets");
        if cli.verbose {
            println!("  Max frame target: {}µs", targets.max_frame_us);
            println!("  P99 frame target: {}µs", targets.p99_frame_us);
        }
    } else {
        eprintln!("✗ Some benchmarks failed performance targets");
        std::process::exit(1);
    }
}