Skip to main content

oxinav_core/
viewer.rs

1//! Read-only file viewing: turning raw bytes into something displayable.
2//!
3//! The app reads a capped prefix of a file through the `Filesystem`
4//! abstraction and hands the bytes here. This module decides whether they are
5//! text or binary and prepares the exact string the view layer renders, so
6//! that the UI keeps no branching logic of its own.
7
8use crate::highlight::{detect_language, Language};
9use std::fmt::Write;
10
11/// The most bytes the viewer will hold for a single file.
12///
13/// Capped both so a multi-GB file is never slurped whole and so the modal
14/// stays responsive: everything read is laid out as one text widget, and a
15/// much larger cap makes opening the viewer visibly slow. Nothing depends on
16/// the exact value — it is safe to tune.
17pub const MAX_VIEW_BYTES: usize = 256 * 1024;
18
19/// The most bytes rendered as a hex dump.
20///
21/// A dump runs about five characters per byte, so [`MAX_VIEW_BYTES`] of
22/// binary would still hand the view layer megabytes of text to lay out in one
23/// widget. This smaller window is still far more than anyone reads by eye.
24pub const MAX_HEX_BYTES: usize = 64 * 1024;
25
26/// Bytes per line of the hex dump.
27const HEX_COLUMNS: usize = 16;
28
29/// What the viewer found in a file, already formatted for display.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum ViewerContent {
32    /// Readable text, ready to render as-is.
33    Text(String),
34    /// An offset/hex/ASCII dump of bytes that are not readable text.
35    Binary(String),
36}
37
38impl ViewerContent {
39    /// The text to render, whichever form the content took.
40    pub fn body(&self) -> &str {
41        match self {
42            Self::Text(text) | Self::Binary(text) => text,
43        }
44    }
45
46    /// A short word for the content's kind, for the viewer's status line.
47    pub const fn kind(&self) -> &'static str {
48        match self {
49            Self::Text(_) => "text",
50            Self::Binary(_) => "binary",
51        }
52    }
53}
54
55/// A file prepared for read-only viewing.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct FileView {
58    pub content: ViewerContent,
59    /// Whether the file held more than what `content` shows.
60    pub truncated: bool,
61    /// The language detected for text content, if any.
62    pub language: Option<Language>,
63}
64
65impl FileView {
66    /// Classify up to [`MAX_VIEW_BYTES`] of `bytes` and prepare them for
67    /// display, flagging truncation when more was supplied than that.
68    ///
69    /// Callers that read from a real file should hand over `MAX_VIEW_BYTES + 1`
70    /// bytes: the one extra byte is what distinguishes a file that exactly
71    /// fills the cap from one that overruns it.
72    pub fn from_bytes(bytes: &[u8]) -> Self {
73        let mut truncated = bytes.len() > MAX_VIEW_BYTES;
74        let head = &bytes[..bytes.len().min(MAX_VIEW_BYTES)];
75
76        let content = match decode_text(head, truncated) {
77            Some(text) => ViewerContent::Text(text),
78            None => {
79                // Binary gets the tighter cap, and dropping bytes to honour it
80                // is truncation just the same.
81                truncated |= head.len() > MAX_HEX_BYTES;
82                ViewerContent::Binary(hex_dump(&head[..head.len().min(MAX_HEX_BYTES)]))
83            }
84        };
85
86        Self {
87            content,
88            truncated,
89            language: None,
90        }
91    }
92
93    /// [`Self::from_bytes`], plus the language of text content, judged from
94    /// the file's `name` and its first line.
95    pub fn from_file(name: &str, bytes: &[u8]) -> Self {
96        let mut view = Self::from_bytes(bytes);
97        if let ViewerContent::Text(text) = &view.content {
98            view.language = detect_language(name, text.lines().next().unwrap_or(""));
99        }
100        view
101    }
102
103    pub const fn is_binary(&self) -> bool {
104        matches!(self.content, ViewerContent::Binary(_))
105    }
106
107    /// How many lines the body occupies, for sizing the viewer's scroll.
108    pub fn line_count(&self) -> usize {
109        self.content.body().lines().count()
110    }
111}
112
113/// Decode `bytes` as text, or `None` when they are not text.
114///
115/// Text means valid UTF-8 carrying no control characters beyond the ones that
116/// structure a document.
117fn decode_text(bytes: &[u8], truncated: bool) -> Option<String> {
118    let text = match std::str::from_utf8(bytes) {
119        Ok(text) => text,
120        // A multi-byte character sliced through by the read cap is an
121        // artefact of truncating, not evidence of binary content: keep the
122        // valid prefix and drop the partial character. Any other decode
123        // failure means these bytes really are not text.
124        Err(error) if truncated && error.error_len().is_none() => {
125            std::str::from_utf8(&bytes[..error.valid_up_to()]).ok()?
126        }
127        Err(_) => return None,
128    };
129
130    if text.chars().any(is_disallowed_control) {
131        return None;
132    }
133    Some(text.to_string())
134}
135
136/// Whether `c` is a control character that marks its content as binary. Tab,
137/// line feed and carriage return structure real text; NUL and the rest of the
138/// control range do not.
139fn is_disallowed_control(c: char) -> bool {
140    c.is_control() && !matches!(c, '\t' | '\n' | '\r')
141}
142
143/// Render `bytes` as `offset  hex bytes  |ascii|` lines, the classic dump
144/// layout, so binary content is inspectable instead of garbled.
145fn hex_dump(bytes: &[u8]) -> String {
146    let mut out = String::new();
147
148    for (row, chunk) in bytes.chunks(HEX_COLUMNS).enumerate() {
149        let offset = row * HEX_COLUMNS;
150        let _ = write!(out, "{offset:08x}  ");
151
152        for column in 0..HEX_COLUMNS {
153            match chunk.get(column) {
154                Some(byte) => {
155                    let _ = write!(out, "{byte:02x} ");
156                }
157                // Pad the final short row so the ASCII gutter stays aligned.
158                None => out.push_str("   "),
159            }
160            if column == HEX_COLUMNS / 2 - 1 {
161                out.push(' ');
162            }
163        }
164
165        out.push_str(" |");
166        for byte in chunk {
167            let printable = byte.is_ascii_graphic() || *byte == b' ';
168            out.push(if printable { *byte as char } else { '.' });
169        }
170        out.push_str("|\n");
171    }
172
173    out
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn from_file_detects_the_language_of_text() {
182        let view = FileView::from_file("Cargo.toml", b"[package]\nname = \"x\"\n");
183        assert_eq!(view.language.as_ref().map(|l| l.name()), Some("TOML"));
184
185        let script = FileView::from_file("deploy", b"#!/usr/bin/env bash\necho hi\n");
186        assert!(script.language.is_some());
187    }
188
189    #[test]
190    fn binary_content_has_no_language() {
191        let view = FileView::from_file("main.rs", &[0, 1, 2, 3, 0xff]);
192        assert!(view.is_binary());
193        assert_eq!(view.language, None);
194    }
195
196    #[test]
197    fn utf8_content_is_text() {
198        let view = FileView::from_bytes("hello\nwörld\tagain\r\n".as_bytes());
199
200        assert_eq!(
201            view.content,
202            ViewerContent::Text("hello\nwörld\tagain\r\n".to_string())
203        );
204        assert!(!view.truncated);
205    }
206
207    #[test]
208    fn empty_file_is_empty_text() {
209        let view = FileView::from_bytes(&[]);
210
211        assert_eq!(view.content, ViewerContent::Text(String::new()));
212        assert!(!view.truncated);
213    }
214
215    #[test]
216    fn invalid_utf8_is_binary() {
217        // A lone continuation byte is not valid UTF-8 anywhere.
218        let view = FileView::from_bytes(&[0xff, 0xfe, 0x41]);
219
220        assert!(view.is_binary());
221    }
222
223    #[test]
224    fn embedded_nul_is_binary_despite_valid_utf8() {
225        let view = FileView::from_bytes(b"ELF\0\x01\x02plain ascii");
226
227        assert!(view.is_binary());
228    }
229
230    #[test]
231    fn binary_content_renders_as_offset_hex_and_ascii() {
232        let view = FileView::from_bytes(b"\0AB");
233
234        assert_eq!(
235            view.content.body(),
236            "00000000  00 41 42                                          |.AB|\n"
237        );
238    }
239
240    #[test]
241    fn hex_dump_starts_a_new_line_every_sixteen_bytes() {
242        let mut bytes = vec![0u8; 20];
243        bytes[16] = b'x';
244        let view = FileView::from_bytes(&bytes);
245
246        let lines: Vec<&str> = view.content.body().lines().collect();
247        assert_eq!(lines.len(), 2);
248        assert!(lines[1].starts_with("00000010  78 00 00 00"));
249    }
250
251    #[test]
252    fn oversize_input_is_capped_and_flagged() {
253        let bytes = vec![b'a'; MAX_VIEW_BYTES + 1];
254        let view = FileView::from_bytes(&bytes);
255
256        assert!(view.truncated);
257        assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
258    }
259
260    #[test]
261    fn input_exactly_at_the_cap_is_not_flagged() {
262        let bytes = vec![b'a'; MAX_VIEW_BYTES];
263        let view = FileView::from_bytes(&bytes);
264
265        assert!(!view.truncated);
266        assert_eq!(view.content.body().len(), MAX_VIEW_BYTES);
267    }
268
269    #[test]
270    fn character_sliced_by_the_cap_still_reads_as_text() {
271        // Fill to one byte short of the cap, then straddle it with a
272        // two-byte character so the cap cuts the character in half.
273        let mut bytes = vec![b'a'; MAX_VIEW_BYTES - 1];
274        bytes.extend_from_slice("é".as_bytes());
275
276        let view = FileView::from_bytes(&bytes);
277
278        assert!(view.truncated);
279        assert!(!view.is_binary());
280        // The partial character is dropped rather than shown as garbage.
281        assert_eq!(view.content.body().len(), MAX_VIEW_BYTES - 1);
282    }
283
284    #[test]
285    fn oversize_binary_is_capped_to_the_hex_window_and_flagged() {
286        // NUL keeps this classified as binary at any length.
287        let bytes = vec![0u8; MAX_HEX_BYTES + 1];
288        let view = FileView::from_bytes(&bytes);
289
290        assert!(view.is_binary());
291        assert!(view.truncated);
292        assert_eq!(view.line_count(), MAX_HEX_BYTES / HEX_COLUMNS);
293    }
294
295    #[test]
296    fn line_count_reflects_the_body() {
297        let view = FileView::from_bytes(b"one\ntwo\nthree\n");
298
299        assert_eq!(view.line_count(), 3);
300    }
301}