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
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
626
627
628
629
630
631
632
633
//! Network panel rendering and utilities.
//!
//! Provides network panel title building, traffic formatting,
//! and helper functions for rendering network metrics.

use presentar_core::Color;

// =============================================================================
// NETWORK TITLE BUILDING
// =============================================================================

/// Build network panel title string.
///
/// Format: "Network │ eth0 │ ↓1.5MB/s ↑500KB/s"
#[must_use]
pub fn build_network_title(interface: &str, rx_rate: u64, tx_rate: u64) -> String {
    let rx_str = format_traffic_rate(rx_rate);
    let tx_str = format_traffic_rate(tx_rate);
    format!("Network │ {} │ ↓{}{}", interface, rx_str, tx_str)
}

/// Build compact network title for narrow panels.
///
/// Format: "Net │ ↓1.5M ↑500K"
#[must_use]
pub fn build_network_title_compact(rx_rate: u64, tx_rate: u64) -> String {
    let rx_str = format_traffic_rate_short(rx_rate);
    let tx_str = format_traffic_rate_short(tx_rate);
    format!("Net │ ↓{}{}", rx_str, tx_str)
}

/// Build network panel title with connection count (GAP-NET-002).
///
/// Format: "Network │ eth0 │ ↓1.5MB/s ↑500KB/s │ 42 conn"
#[must_use]
pub fn build_network_title_with_conns(
    interface: &str,
    rx_rate: u64,
    tx_rate: u64,
    connection_count: usize,
) -> String {
    let rx_str = format_traffic_rate(rx_rate);
    let tx_str = format_traffic_rate(tx_rate);
    format!(
        "Network │ {} │ ↓{}{}{} conn",
        interface, rx_str, tx_str, connection_count
    )
}

/// Build compact network title with connection count.
///
/// Format: "Net │ ↓1.5M ↑500K │ 42"
#[must_use]
pub fn build_network_title_compact_with_conns(
    rx_rate: u64,
    tx_rate: u64,
    connection_count: usize,
) -> String {
    let rx_str = format_traffic_rate_short(rx_rate);
    let tx_str = format_traffic_rate_short(tx_rate);
    format!("Net │ ↓{}{}{}", rx_str, tx_str, connection_count)
}

// =============================================================================
// TRAFFIC FORMATTING
// =============================================================================

/// Format traffic rate as human-readable string.
///
/// # Examples
/// - 0 -> "0B/s"
/// - 1024 -> "1.0KB/s"
/// - 1048576 -> "1.0MB/s"
#[must_use]
pub fn format_traffic_rate(bytes_per_sec: u64) -> String {
    if bytes_per_sec == 0 {
        return "0B/s".to_string();
    }

    const KB: f64 = 1024.0;
    const MB: f64 = 1024.0 * 1024.0;
    const GB: f64 = 1024.0 * 1024.0 * 1024.0;

    let bytes = bytes_per_sec as f64;

    if bytes >= GB {
        format!("{:.1}GB/s", bytes / GB)
    } else if bytes >= MB {
        format!("{:.1}MB/s", bytes / MB)
    } else if bytes >= KB {
        format!("{:.1}KB/s", bytes / KB)
    } else {
        format!("{}B/s", bytes_per_sec)
    }
}

/// Format traffic rate in short form (no /s suffix).
///
/// # Examples
/// - 1024 -> "1.0K"
/// - 1048576 -> "1.0M"
#[must_use]
pub fn format_traffic_rate_short(bytes_per_sec: u64) -> String {
    if bytes_per_sec == 0 {
        return "0".to_string();
    }

    const KB: f64 = 1024.0;
    const MB: f64 = 1024.0 * 1024.0;
    const GB: f64 = 1024.0 * 1024.0 * 1024.0;

    let bytes = bytes_per_sec as f64;

    if bytes >= GB {
        format!("{:.1}G", bytes / GB)
    } else if bytes >= MB {
        format!("{:.1}M", bytes / MB)
    } else if bytes >= KB {
        format!("{:.0}K", bytes / KB)
    } else {
        format!("{}B", bytes_per_sec)
    }
}

/// Format total bytes transferred.
#[must_use]
pub fn format_total_bytes(bytes: u64) -> String {
    const KB: f64 = 1024.0;
    const MB: f64 = 1024.0 * 1024.0;
    const GB: f64 = 1024.0 * 1024.0 * 1024.0;
    const TB: f64 = 1024.0 * 1024.0 * 1024.0 * 1024.0;

    let b = bytes as f64;

    if b >= TB {
        format!("{:.2}TB", b / TB)
    } else if b >= GB {
        format!("{:.2}GB", b / GB)
    } else if b >= MB {
        format!("{:.1}MB", b / MB)
    } else if b >= KB {
        format!("{:.0}KB", b / KB)
    } else {
        format!("{}B", bytes)
    }
}

// =============================================================================
// NETWORK COLORS
// =============================================================================

/// Get color for download (RX) traffic.
#[must_use]
pub fn rx_color() -> Color {
    Color::new(0.3, 0.9, 0.5, 1.0) // Green
}

/// Get color for upload (TX) traffic.
#[must_use]
pub fn tx_color() -> Color {
    Color::new(0.9, 0.5, 0.3, 1.0) // Orange
}

/// Get color for traffic rate based on intensity.
#[must_use]
pub fn traffic_intensity_color(bytes_per_sec: u64) -> Color {
    const MB: u64 = 1024 * 1024;

    if bytes_per_sec > 100 * MB {
        Color::new(1.0, 0.4, 0.4, 1.0) // Very high - red
    } else if bytes_per_sec > 10 * MB {
        Color::new(1.0, 0.8, 0.3, 1.0) // High - yellow
    } else if bytes_per_sec > MB {
        Color::new(0.4, 0.9, 0.5, 1.0) // Moderate - green
    } else if bytes_per_sec > 0 {
        Color::new(0.5, 0.7, 0.5, 1.0) // Low - dim green
    } else {
        Color::new(0.4, 0.4, 0.4, 1.0) // Idle - gray
    }
}

// =============================================================================
// INTERFACE UTILITIES
// =============================================================================

/// Network interface type detection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterfaceType {
    /// Physical Ethernet
    Ethernet,
    /// Wireless
    Wifi,
    /// Loopback
    Loopback,
    /// Virtual/Bridge
    Virtual,
    /// VPN tunnel
    Vpn,
    /// Docker/Container
    Docker,
    /// Unknown type
    Unknown,
}

impl InterfaceType {
    /// Detect interface type from name.
    #[must_use]
    pub fn from_name(name: &str) -> Self {
        let lower = name.to_lowercase();

        if lower == "lo" {
            Self::Loopback
        } else if lower.starts_with("eth") || lower.starts_with("en") {
            Self::Ethernet
        } else if lower.starts_with("wl") || lower.starts_with("wifi") {
            Self::Wifi
        } else if lower.starts_with("docker") || lower.starts_with("br-") {
            Self::Docker
        } else if lower.starts_with("veth") || lower.starts_with("virbr") {
            Self::Virtual
        } else if lower.starts_with("tun") || lower.starts_with("tap") || lower.starts_with("wg") {
            Self::Vpn
        } else {
            Self::Unknown
        }
    }

    /// Get icon for interface type.
    #[must_use]
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Ethernet => "󰈀",
            Self::Wifi => "󰖩",
            Self::Loopback => "󰑐",
            Self::Virtual => "󰒍",
            Self::Vpn => "󰒃",
            Self::Docker => "󰡨",
            Self::Unknown => "󰈁",
        }
    }

    /// Get display name for interface type.
    #[must_use]
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Ethernet => "Ethernet",
            Self::Wifi => "Wi-Fi",
            Self::Loopback => "Loopback",
            Self::Virtual => "Virtual",
            Self::Vpn => "VPN",
            Self::Docker => "Docker",
            Self::Unknown => "Network",
        }
    }
}

// =============================================================================
// CONNECTION STATE
// =============================================================================

/// TCP connection state display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionState {
    Established,
    Listen,
    TimeWait,
    CloseWait,
    SynSent,
    SynRecv,
    FinWait1,
    FinWait2,
    Closing,
    LastAck,
    Closed,
}

impl ConnectionState {
    /// Get short display name.
    #[must_use]
    pub fn short_name(&self) -> &'static str {
        match self {
            Self::Established => "ESTAB",
            Self::Listen => "LISTEN",
            Self::TimeWait => "TIME_W",
            Self::CloseWait => "CLOSE_W",
            Self::SynSent => "SYN_S",
            Self::SynRecv => "SYN_R",
            Self::FinWait1 => "FIN_W1",
            Self::FinWait2 => "FIN_W2",
            Self::Closing => "CLOSING",
            Self::LastAck => "LAST_A",
            Self::Closed => "CLOSED",
        }
    }

    /// Get color for state.
    #[must_use]
    pub fn color(&self) -> Color {
        match self {
            Self::Established => Color::new(0.3, 0.9, 0.3, 1.0), // Green
            Self::Listen => Color::new(0.5, 0.7, 1.0, 1.0),      // Blue
            Self::TimeWait | Self::CloseWait => Color::new(0.8, 0.8, 0.3, 1.0), // Yellow
            Self::Closed => Color::new(0.5, 0.5, 0.5, 1.0),      // Gray
            _ => Color::new(0.7, 0.5, 0.3, 1.0),                 // Orange for others
        }
    }
}

// =============================================================================
// TESTS
// =============================================================================

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

    // =========================================================================
    // build_network_title tests
    // =========================================================================

    #[test]
    fn test_build_network_title_basic() {
        let title = build_network_title("eth0", 1024 * 1024, 512 * 1024);
        assert!(title.contains("Network"));
        assert!(title.contains("eth0"));
        assert!(title.contains(""));
        assert!(title.contains(""));
    }

    #[test]
    fn test_build_network_title_zero() {
        let title = build_network_title("lo", 0, 0);
        assert!(title.contains("lo"));
        assert!(title.contains("0B/s"));
    }

    #[test]
    fn test_build_network_title_high_traffic() {
        let title = build_network_title("eth0", 100 * 1024 * 1024, 50 * 1024 * 1024);
        assert!(title.contains("MB/s"));
    }

    // =========================================================================
    // build_network_title_compact tests
    // =========================================================================

    #[test]
    fn test_build_network_title_compact_basic() {
        let title = build_network_title_compact(1024 * 1024, 512 * 1024);
        assert!(title.contains("Net"));
        assert!(title.contains(""));
        assert!(title.contains(""));
        assert!(!title.contains("/s")); // Short format
    }

    #[test]
    fn test_build_network_title_compact_short() {
        let title = build_network_title_compact(0, 0);
        assert!(title.chars().count() < 20);
    }

    // =========================================================================
    // build_network_title_with_conns tests (GAP-NET-002)
    // =========================================================================

    #[test]
    fn test_build_network_title_with_conns_basic() {
        let title = build_network_title_with_conns("eth0", 1024 * 1024, 512 * 1024, 42);
        assert!(title.contains("Network"));
        assert!(title.contains("eth0"));
        assert!(title.contains("42 conn"));
    }

    #[test]
    fn test_build_network_title_with_conns_zero() {
        let title = build_network_title_with_conns("lo", 0, 0, 0);
        assert!(title.contains("0 conn"));
    }

    #[test]
    fn test_build_network_title_with_conns_high_count() {
        let title = build_network_title_with_conns("eth0", 1024, 1024, 1000);
        assert!(title.contains("1000 conn"));
    }

    #[test]
    fn test_build_network_title_compact_with_conns_basic() {
        let title = build_network_title_compact_with_conns(1024 * 1024, 512 * 1024, 42);
        assert!(title.contains("Net"));
        assert!(title.contains("42"));
        assert!(!title.contains("conn")); // Compact doesn't say "conn"
    }

    #[test]
    fn test_build_network_title_compact_with_conns_zero() {
        let title = build_network_title_compact_with_conns(0, 0, 0);
        assert!(title.contains("│ 0"));
    }

    // =========================================================================
    // format_traffic_rate tests
    // =========================================================================

    #[test]
    fn test_format_traffic_rate_zero() {
        assert_eq!(format_traffic_rate(0), "0B/s");
    }

    #[test]
    fn test_format_traffic_rate_bytes() {
        assert_eq!(format_traffic_rate(500), "500B/s");
    }

    #[test]
    fn test_format_traffic_rate_kb() {
        assert_eq!(format_traffic_rate(1024), "1.0KB/s");
    }

    #[test]
    fn test_format_traffic_rate_mb() {
        assert_eq!(format_traffic_rate(1024 * 1024), "1.0MB/s");
    }

    #[test]
    fn test_format_traffic_rate_gb() {
        assert_eq!(format_traffic_rate(1024 * 1024 * 1024), "1.0GB/s");
    }

    // =========================================================================
    // format_traffic_rate_short tests
    // =========================================================================

    #[test]
    fn test_format_traffic_rate_short_zero() {
        assert_eq!(format_traffic_rate_short(0), "0");
    }

    #[test]
    fn test_format_traffic_rate_short_kb() {
        assert_eq!(format_traffic_rate_short(1024), "1K");
    }

    #[test]
    fn test_format_traffic_rate_short_mb() {
        assert_eq!(format_traffic_rate_short(1024 * 1024), "1.0M");
    }

    #[test]
    fn test_format_traffic_rate_short_no_suffix() {
        let result = format_traffic_rate_short(5 * 1024 * 1024);
        assert!(!result.contains("/s"));
    }

    // =========================================================================
    // format_total_bytes tests
    // =========================================================================

    #[test]
    fn test_format_total_bytes_bytes() {
        assert_eq!(format_total_bytes(500), "500B");
    }

    #[test]
    fn test_format_total_bytes_kb() {
        let result = format_total_bytes(2048);
        assert!(result.contains("KB"));
    }

    #[test]
    fn test_format_total_bytes_mb() {
        let result = format_total_bytes(5 * 1024 * 1024);
        assert!(result.contains("MB"));
    }

    #[test]
    fn test_format_total_bytes_gb() {
        let result = format_total_bytes(10 * 1024 * 1024 * 1024);
        assert!(result.contains("GB"));
    }

    #[test]
    fn test_format_total_bytes_tb() {
        let result = format_total_bytes(2 * 1024 * 1024 * 1024 * 1024);
        assert!(result.contains("TB"));
    }

    // =========================================================================
    // color tests
    // =========================================================================

    #[test]
    fn test_rx_color_is_green() {
        let color = rx_color();
        assert!(color.g > 0.8);
    }

    #[test]
    fn test_tx_color_is_orange() {
        let color = tx_color();
        assert!(color.r > 0.8);
    }

    #[test]
    fn test_traffic_intensity_color_idle() {
        let color = traffic_intensity_color(0);
        assert!((color.r - color.g).abs() < 0.1, "Idle should be gray");
    }

    #[test]
    fn test_traffic_intensity_color_low() {
        let color = traffic_intensity_color(512 * 1024);
        assert!(color.g > 0.6);
    }

    #[test]
    fn test_traffic_intensity_color_high() {
        let color = traffic_intensity_color(50 * 1024 * 1024);
        assert!(color.r > 0.9);
    }

    #[test]
    fn test_traffic_intensity_color_very_high() {
        let color = traffic_intensity_color(200 * 1024 * 1024);
        assert!(color.r > 0.9 && color.g < 0.5);
    }

    // =========================================================================
    // InterfaceType tests
    // =========================================================================

    #[test]
    fn test_interface_type_from_name_ethernet() {
        assert_eq!(InterfaceType::from_name("eth0"), InterfaceType::Ethernet);
        assert_eq!(InterfaceType::from_name("enp0s3"), InterfaceType::Ethernet);
    }

    #[test]
    fn test_interface_type_from_name_wifi() {
        assert_eq!(InterfaceType::from_name("wlan0"), InterfaceType::Wifi);
        assert_eq!(InterfaceType::from_name("wlp2s0"), InterfaceType::Wifi);
    }

    #[test]
    fn test_interface_type_from_name_loopback() {
        assert_eq!(InterfaceType::from_name("lo"), InterfaceType::Loopback);
    }

    #[test]
    fn test_interface_type_from_name_docker() {
        assert_eq!(InterfaceType::from_name("docker0"), InterfaceType::Docker);
        assert_eq!(InterfaceType::from_name("br-abc123"), InterfaceType::Docker);
    }

    #[test]
    fn test_interface_type_from_name_vpn() {
        assert_eq!(InterfaceType::from_name("tun0"), InterfaceType::Vpn);
        assert_eq!(InterfaceType::from_name("wg0"), InterfaceType::Vpn);
    }

    #[test]
    fn test_interface_type_from_name_virtual() {
        assert_eq!(InterfaceType::from_name("veth123"), InterfaceType::Virtual);
        assert_eq!(InterfaceType::from_name("virbr0"), InterfaceType::Virtual);
    }

    #[test]
    fn test_interface_type_from_name_unknown() {
        assert_eq!(InterfaceType::from_name("custom0"), InterfaceType::Unknown);
    }

    #[test]
    fn test_interface_type_icon() {
        assert!(!InterfaceType::Ethernet.icon().is_empty());
        assert!(!InterfaceType::Wifi.icon().is_empty());
    }

    #[test]
    fn test_interface_type_display_name() {
        assert_eq!(InterfaceType::Ethernet.display_name(), "Ethernet");
        assert_eq!(InterfaceType::Wifi.display_name(), "Wi-Fi");
        assert_eq!(InterfaceType::Loopback.display_name(), "Loopback");
    }

    #[test]
    fn test_interface_type_derive_debug() {
        let itype = InterfaceType::Ethernet;
        let debug = format!("{:?}", itype);
        assert!(debug.contains("Ethernet"));
    }

    #[test]
    fn test_interface_type_derive_clone() {
        let itype = InterfaceType::Wifi;
        let cloned = itype;
        assert_eq!(itype, cloned);
    }

    // =========================================================================
    // ConnectionState tests
    // =========================================================================

    #[test]
    fn test_connection_state_short_name() {
        assert_eq!(ConnectionState::Established.short_name(), "ESTAB");
        assert_eq!(ConnectionState::Listen.short_name(), "LISTEN");
        assert_eq!(ConnectionState::TimeWait.short_name(), "TIME_W");
    }

    #[test]
    fn test_connection_state_color_established() {
        let color = ConnectionState::Established.color();
        assert!(color.g > 0.8, "Established should be green");
    }

    #[test]
    fn test_connection_state_color_listen() {
        let color = ConnectionState::Listen.color();
        assert!(color.b > 0.9, "Listen should be blue");
    }

    #[test]
    fn test_connection_state_color_closed() {
        let color = ConnectionState::Closed.color();
        assert!((color.r - color.g).abs() < 0.1, "Closed should be gray");
    }

    #[test]
    fn test_connection_state_derive_debug() {
        let state = ConnectionState::Established;
        let debug = format!("{:?}", state);
        assert!(debug.contains("Established"));
    }
}