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