datui-lib 0.4.4

Data Exploration in the Terminal (library)
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
//! The hex view: a takeover of the main area. A header line names the file, a header
//! row numbers the bytes, then a row of bytes per line (offset, hex, ASCII), with the
//! byte inspector beside them when there is room, and a status line at the foot. The
//! keys are on the footer.

use crate::app::hex_view::{ByteClass, Geometry, HexView, PromptKind, class, hex_x, readings};
use crate::render::context::RenderContext;
use crate::widgets::ui::Surface;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Widget};

pub fn render(area: Rect, buf: &mut Buffer, app: &mut crate::App, ctx: &RenderContext) {
    let has_specs = app.has_format_specs();
    if let Some(view) = app.hex.view.as_mut() {
        draw(area, buf, view, ctx, has_specs);
    }
}

/// The color of a byte of `class`.
fn class_color(class: ByteClass, ctx: &RenderContext) -> ratatui::style::Color {
    match class {
        ByteClass::Null => ctx.hex_null,
        ByteClass::Printable => ctx.hex_printable,
        ByteClass::Whitespace => ctx.hex_whitespace,
        ByteClass::Control => ctx.hex_control,
        ByteClass::High => ctx.hex_high,
        ByteClass::Ff => ctx.hex_ff,
    }
}

/// An offset as the offset column shows it.
pub fn offset_text(at: u64, digits: usize, decimal: bool) -> String {
    if decimal {
        format!("{at:>digits$}")
    } else {
        format!("{at:0digits$x}")
    }
}

/// Rows the prompt takes at the foot, frame included.
fn prompt_rows(view: &HexView) -> u16 {
    match view.prompt {
        None => 0,
        Some(PromptKind::Find) => 4,
        Some(_) if view.prompt_error.is_some() => 4,
        Some(_) => 3,
    }
}

/// Draw `view` into `area`.
pub fn draw(
    area: Rect,
    buf: &mut Buffer,
    view: &mut HexView,
    ctx: &RenderContext,
    has_specs: bool,
) {
    Clear.render(area, buf);
    if area.height < 3 || area.width < 8 {
        return;
    }
    let g = crate::glyphs::get();
    let prompt = prompt_rows(view).min(area.height.saturating_sub(3));
    let body_height = area.height - 2 - prompt;
    // Without room beside the bytes, an open inspector takes the rows under them, up
    // to half: the bytes keep the other half, and what does not fit is counted.
    let below = if !view.panel_fits(area.width) && view.inspector_open && !view.is_empty() {
        let lines =
            readings(view.slice(view.cursor, crate::app::hex_view::INSPECTED)).len() as u16 + 2;
        lines.min(body_height / 2)
    } else {
        0
    };
    // Header, byte numbers, status line, the prompt when one is open, and the
    // inspector when it is under the bytes.
    let rows = body_height.saturating_sub(1 + below) as usize;
    let geometry = view.lay_out(area.width, rows);

    header(Rect { height: 1, ..area }, buf, view, &geometry, ctx);
    let body = Rect {
        y: area.y + 1,
        height: body_height,
        ..area
    };
    let bytes_area = if geometry.panel {
        // The panel sits against the bytes, not at the far edge: on a wide screen the
        // readings stay next to the bytes they read.
        let used =
            crate::app::hex_view::row_width(geometry.shown, geometry.digits, geometry.ascii) + 2;
        Rect {
            width: (used as u16).min(body.width - crate::app::hex_view::PANEL_WIDTH - 1),
            ..body
        }
    } else {
        Rect {
            height: body.height - below,
            ..body
        }
    };
    column_numbers(
        Rect {
            height: 1,
            ..bytes_area
        },
        buf,
        view,
        &geometry,
        ctx,
    );
    let rows_area = Rect {
        y: bytes_area.y + 1,
        height: bytes_area.height.saturating_sub(1),
        ..bytes_area
    };
    if view.is_empty() {
        Paragraph::new(Span::styled("Empty file", Style::default().fg(ctx.dimmed))).render(
            Rect {
                height: 1,
                ..rows_area
            },
            buf,
        );
    } else {
        byte_rows(rows_area, buf, view, &geometry, ctx);
    }
    if geometry.panel {
        let x = body.x + bytes_area.width;
        for y in body.y..body.y + body.height {
            buf[(x, y)]
                .set_symbol(g.rule)
                .set_style(Style::default().fg(ctx.column_separator));
        }
        let panel = Rect {
            x: x + 1,
            width: crate::app::hex_view::PANEL_WIDTH,
            ..body
        };
        inspector(panel, buf, view, ctx);
    } else if below > 0 {
        let under = Rect {
            y: body.y + body.height - below,
            height: below,
            width: body.width.min(crate::app::hex_view::PANEL_WIDTH + 12),
            ..body
        };
        inspector(under, buf, view, ctx);
    }
    if prompt > 0 {
        let strip = Rect {
            y: area.y + area.height - 1 - prompt,
            height: prompt,
            ..area
        };
        prompt_strip(strip, buf, view, ctx);
    }
    status(
        Rect {
            y: area.y + area.height - 1,
            height: 1,
            ..area
        },
        buf,
        view,
        has_specs,
        ctx,
    );
    if let Some(picker) = &view.picker {
        crate::render::datatable_main::render_picker(
            area,
            buf,
            picker,
            (
                "Format",
                datui_cli::keys::Context::FormatPicker,
                "No spec matches",
            ),
            ctx,
        );
    }
}

fn header(area: Rect, buf: &mut Buffer, view: &HexView, geometry: &Geometry, ctx: &RenderContext) {
    let g = crate::glyphs::get();
    let dot = g.middot;
    let size = crate::numfmt::group_chrome(view.len() as usize);
    let mut text = format!(
        "Hex {dot} {} {dot} {size} {}",
        view.name(),
        if view.len() == 1 { "byte" } else { "bytes" }
    );
    let fixed = if view.record_size.is_some() {
        "fixed"
    } else {
        "auto"
    };
    text.push_str(&format!(" {dot} {} bytes/row ({fixed})", geometry.per_row));
    if geometry.shown < geometry.per_row {
        text.push_str(&format!(
            ", {} to {} shown",
            geometry.first_col,
            geometry.first_col + geometry.shown - 1
        ));
    }
    let style = Style::default().bg(ctx.controls_bg).fg(ctx.table_header);
    buf.set_style(area, style);
    Paragraph::new(crate::glyphs::fit_cells(&text, area.width as usize, g.ellipsis).into_owned())
        .style(style.add_modifier(Modifier::BOLD))
        .render(area, buf);
}

/// The header row: what the offsets count in, and each byte's place in the row.
fn column_numbers(
    area: Rect,
    buf: &mut Buffer,
    view: &HexView,
    geometry: &Geometry,
    ctx: &RenderContext,
) {
    let style = Style::default()
        .bg(ctx.table_header_bg)
        .fg(ctx.table_header);
    buf.set_style(area, style);
    // Hex is the default and needs no mark; decimal offsets say so.
    let label = if view.decimal { "decimal" } else { "offset" };
    let label = format!("{label:<width$}", width = geometry.digits);
    buf.set_stringn(area.x, area.y, &label, area.width as usize, style);
    let hex_start = area.x as usize + geometry.digits + 2;
    let col = (view.cursor % geometry.per_row as u64) as usize;
    let base = hex_x(geometry.first_col);
    for i in geometry.first_col..geometry.first_col + geometry.shown {
        let x = hex_start + hex_x(i) - base;
        if x + 2 > (area.x + area.width) as usize {
            break;
        }
        let text = format!("{:02x}", i % 256);
        let cell = if i == col {
            style.fg(ctx.accent).add_modifier(Modifier::BOLD)
        } else {
            style
        };
        buf.set_string(x as u16, area.y, text, cell);
    }
}

fn byte_rows(
    area: Rect,
    buf: &mut Buffer,
    view: &HexView,
    geometry: &Geometry,
    ctx: &RenderContext,
) {
    let g = crate::glyphs::get();
    let per = geometry.per_row as u64;
    let rows = (area.height as usize).min(geometry.rows);
    let lo = view.top;
    let hi = (view.top + per * rows as u64).min(view.len());
    let matches = view.matches_on_screen(lo, hi);
    let in_match = |at: u64| matches.iter().any(|&(s, e)| s <= at && at < e);
    let selection = view.selection();
    let selected = |at: u64| selection.is_some_and(|(s, e)| s <= at && at <= e);
    let cursor_style = ctx.cell_cursor_style();
    let match_style = ctx.find_match;
    let select_style = ctx.highlight_style();
    let hex_start = area.x + geometry.digits as u16 + 2;
    let base = hex_x(geometry.first_col);
    let ascii_start = hex_start as usize + crate::app::hex_view::hex_width(geometry.shown) + 2;
    let right = (area.x + area.width) as usize;
    let cursor_row = view.cursor / per;
    for r in 0..rows {
        let row_at = view.top + r as u64 * per;
        if row_at >= view.len() {
            break;
        }
        let y = area.y + r as u16;
        let offset_style = if row_at / per == cursor_row {
            Style::default().fg(ctx.accent).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(ctx.row_numbers)
        };
        buf.set_stringn(
            area.x,
            y,
            offset_text(row_at, geometry.digits, view.decimal),
            geometry.digits.min(area.width as usize),
            offset_style,
        );
        for i in geometry.first_col..geometry.first_col + geometry.shown {
            let at = row_at + i as u64;
            if at >= view.len() {
                break;
            }
            let b = view.bytes.as_slice()[at as usize];
            let color = class_color(class(b), ctx);
            let style = if at == view.cursor {
                cursor_style
            } else if in_match(at) {
                match_style
            } else if selected(at) {
                select_style.fg(color)
            } else {
                Style::default().fg(color)
            };
            let x = hex_start as usize + hex_x(i) - base;
            if x + 2 <= right {
                buf.set_string(x as u16, y, format!("{b:02x}"), style);
                // A marked range reads as one run: the gaps inside it are tinted too.
                let next = at + 1;
                if i + 1 < geometry.first_col + geometry.shown
                    && next < view.len()
                    && selected(at)
                    && selected(next)
                {
                    let gap_end = hex_start as usize + hex_x(i + 1) - base;
                    for gx in x + 2..gap_end.min(right) {
                        buf[(gx as u16, y)].set_style(select_style);
                    }
                }
            }
            if geometry.ascii {
                let ax = ascii_start + (i - geometry.first_col);
                if ax < right {
                    let symbol = match b {
                        0x20..=0x7e => (b as char).to_string(),
                        _ => g.hex_dot.to_string(),
                    };
                    buf[(ax as u16, y)].set_symbol(&symbol).set_style(style);
                }
            }
        }
    }
}

/// The readings at the cursor: a title, then a line per reading, little-endian and
/// big-endian side by side.
fn inspector(area: Rect, buf: &mut Buffer, view: &HexView, ctx: &RenderContext) {
    if area.height == 0 || area.width < 10 || view.is_empty() {
        return;
    }
    let g = crate::glyphs::get();
    let title = format!(
        "At {}",
        offset_text(view.cursor, 1, view.decimal).trim_start()
    );
    let title = if view.decimal {
        title
    } else {
        format!("At 0x{:x}", view.cursor)
    };
    crate::widgets::ui::SectionRule {
        title: &title,
        chip: None,
    }
    .render(Rect { height: 1, ..area }, buf, ctx);
    let label_w = 9usize;
    let value_w = (area.width as usize).saturating_sub(label_w + 2) / 2;
    let mut y = area.y + 1;
    let bottom = area.y + area.height;
    if y < bottom {
        let head = format!("{:label_w$} {:value_w$} {}", "", "LE", "BE",);
        buf.set_stringn(
            area.x,
            y,
            head,
            area.width as usize,
            Style::default().fg(ctx.dimmed),
        );
        y += 1;
    }
    let readings = readings(view.slice(view.cursor, crate::app::hex_view::INSPECTED));
    let fit = |text: &str, w: usize| crate::glyphs::fit_cells(text, w, g.ellipsis).into_owned();
    let marked = usize::from(view.selection().is_some());
    for (i, reading) in readings.iter().enumerate() {
        // Short of room, the last row counts the readings left rather than
        // half-drawing one.
        let left = readings.len() - i;
        let room = usize::from(bottom.saturating_sub(y)).saturating_sub(marked);
        if room < left && room <= 1 {
            if room == 1 {
                buf.set_stringn(
                    area.x,
                    y,
                    format!("{} {left} more", g.ellipsis),
                    area.width as usize,
                    Style::default().fg(ctx.dimmed),
                );
                y += 1;
            }
            break;
        }
        buf.set_stringn(
            area.x,
            y,
            format!("{:label_w$}", reading.label),
            label_w,
            Style::default().fg(ctx.label),
        );
        let x = area.x + label_w as u16 + 1;
        let full = (area.width as usize).saturating_sub(label_w + 1);
        match &reading.be {
            // Too long for the columns side by side: little-endian on this line, and
            // big-endian under it.
            Some(be)
                if crate::glyphs::display_width(&reading.le) > value_w
                    || crate::glyphs::display_width(be) > value_w =>
            {
                buf.set_string(x, y, fit(&reading.le, full), Style::default());
                if !be.is_empty() && y + 1 < bottom {
                    y += 1;
                    buf.set_string(
                        area.x,
                        y,
                        format!("{:>label_w$}", "BE"),
                        Style::default().fg(ctx.dimmed),
                    );
                    buf.set_string(x, y, fit(be, full), Style::default());
                }
            }
            Some(be) => {
                buf.set_string(x, y, fit(&reading.le, value_w), Style::default());
                buf.set_string(
                    x + value_w as u16 + 1,
                    y,
                    fit(be, value_w),
                    Style::default(),
                );
            }
            None => {
                buf.set_string(x, y, fit(&reading.le, full), Style::default());
            }
        }
        y += 1;
    }
    if let Some((first, last)) = view.selection()
        && y < bottom
    {
        let n = last - first + 1;
        buf.set_stringn(
            area.x,
            y,
            format!(
                "{:label_w$} {} {}",
                "marked",
                crate::numfmt::group_chrome(n as usize),
                if n == 1 { "byte" } else { "bytes" }
            ),
            area.width as usize,
            Style::default().fg(ctx.accent),
        );
    }
}

fn prompt_strip(area: Rect, buf: &mut Buffer, view: &HexView, ctx: &RenderContext) {
    let Some(kind) = view.prompt else {
        return;
    };
    let title = match kind {
        PromptKind::GoTo => "Go to Offset",
        PromptKind::Find => "Find Bytes",
        PromptKind::RecordSize => "Bytes per Row",
    };
    let mut surface = Surface::new(title);
    if view.prompt_error.is_some() {
        surface = surface.border_style(Style::default().fg(ctx.modal_border_error));
    }
    let content = surface.render(area, buf, ctx);
    if content.height == 0 {
        return;
    }
    (&view.input).render(
        Rect {
            height: 1,
            ..content
        },
        buf,
    );
    if content.height < 2 {
        return;
    }
    let second = Rect {
        y: content.y + 1,
        height: 1,
        ..content
    };
    if let Some(error) = &view.prompt_error {
        let g = crate::glyphs::get();
        Paragraph::new(Span::styled(
            crate::glyphs::fit_cells(error, second.width as usize, g.ellipsis).into_owned(),
            Style::default().fg(ctx.error),
        ))
        .render(second, buf);
        return;
    }
    if kind == PromptKind::Find {
        let g = crate::glyphs::get();
        let check = if view.utf16 {
            g.checkbox_on
        } else {
            g.checkbox_off
        };
        let line = Line::from(vec![
            Span::styled(
                format!("{check} UTF-16"),
                Style::default().fg(if view.utf16 {
                    ctx.accent
                } else {
                    ctx.text_secondary
                }),
            ),
            Span::styled(
                "   text, 0x..., or hex pairs; ?? is any byte",
                Style::default().fg(ctx.text_secondary),
            ),
        ]);
        Paragraph::new(line).render(second, buf);
    }
}

fn status(area: Rect, buf: &mut Buffer, view: &HexView, has_specs: bool, ctx: &RenderContext) {
    let g = crate::glyphs::get();
    let dot = g.middot;
    let len = view.len();
    let mut parts = Vec::new();
    if len > 0 {
        let at = if view.decimal {
            format!(
                "{} of {}",
                crate::numfmt::group_chrome(view.cursor as usize),
                crate::numfmt::group_chrome(len as usize)
            )
        } else {
            format!("0x{:x} of 0x{:x}", view.cursor, len)
        };
        parts.push(at);
        let percent = if len <= 1 {
            100.0
        } else {
            view.cursor as f64 * 100.0 / (len - 1) as f64
        };
        parts.push(format!("{percent:.1}%"));
    }
    if let Some((first, last)) = view.selection() {
        let n = last - first + 1;
        parts.push(format!(
            "marked {} {}",
            crate::numfmt::group_chrome(n as usize),
            if n == 1 { "byte" } else { "bytes" }
        ));
    }
    if let Some(found) = &view.found {
        match found.hit {
            Some(_) => parts.push(format!("found {}", found.pattern.label)),
            None => parts.push(format!("no match for {}", found.pattern.label)),
        }
        if let Some(stride) = found.stride {
            parts.push(format!("every {stride} bytes"));
        }
    }
    let mut text = parts.join(&format!(" {dot} "));
    if view.fallback {
        let said = if has_specs {
            "format unknown, B reads it with a spec"
        } else {
            "format unknown"
        };
        if text.is_empty() {
            text = said.to_string();
        } else {
            text = format!("{text} {dot} {said}");
        }
    }
    Paragraph::new(crate::glyphs::fit_cells(&text, area.width as usize, g.ellipsis).into_owned())
        .style(Style::default().fg(ctx.text_secondary))
        .render(area, buf);
}

#[cfg(test)]
mod tests;