1use std::ops::Range;
2use std::sync::Arc;
3use std::time::Instant;
4
5use crate::sanitize;
6use crate::theme::Theme;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub struct Rgb(pub u8, pub u8, pub u8);
10
11impl Rgb {
12 pub(crate) fn hex(self) -> String {
14 format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
15 }
16
17 #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a float `as u8` saturates into 0..=255")]
19 pub(crate) fn mix(self, other: Rgb, amount: f32) -> Rgb {
20 let channel = |from: u8, to: u8| (f32::from(from) + (f32::from(to) - f32::from(from)) * amount).round() as u8;
21 Rgb(channel(self.0, other.0), channel(self.1, other.1), channel(self.2, other.2))
22 }
23}
24
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26#[non_exhaustive]
27pub struct Style {
28 pub fg: Option<Rgb>,
29 pub bg: Option<Rgb>,
30 pub bold: bool,
31 pub italic: bool,
32 pub underline: bool,
33 pub strike: bool,
34 pub dim: bool,
35}
36
37impl Style {
38 pub fn fg(color: Rgb) -> Self {
39 Self::default().with_fg(color)
40 }
41
42 pub fn with_fg(self, color: Rgb) -> Self {
43 Self { fg: Some(color), ..self }
44 }
45
46 pub fn on(self, color: Rgb) -> Self {
47 Self { bg: Some(color), ..self }
48 }
49
50 pub fn bold(self) -> Self {
51 Self { bold: true, ..self }
52 }
53
54 pub fn italic(self) -> Self {
55 Self { italic: true, ..self }
56 }
57
58 pub fn underline(self) -> Self {
59 Self { underline: true, ..self }
60 }
61
62 pub fn strike(self) -> Self {
63 Self { strike: true, ..self }
64 }
65
66 pub fn dim(self) -> Self {
67 Self { dim: true, ..self }
68 }
69}
70
71#[derive(Clone, Debug, Default, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct Span {
74 pub text: String,
75 pub style: Style,
76 pub link: Option<Arc<str>>,
78 pub is_frame: bool,
81}
82
83impl Span {
84 pub fn new(text: impl Into<String>, style: Style) -> Self {
85 Self { text: text.into(), style, link: None, is_frame: false }
86 }
87
88 pub fn plain(text: impl Into<String>) -> Self {
89 Self::new(text, Style::default())
90 }
91
92 pub fn linked(self, target: impl Into<Arc<str>>) -> Self {
93 Self { link: Some(target.into()), ..self }
94 }
95
96 pub fn framed(self) -> Self {
97 Self { is_frame: true, ..self }
98 }
99
100 fn looks_like(&self, other: &Span) -> bool {
102 self.style == other.style && self.link == other.link && self.is_frame == other.is_frame
103 }
104
105 fn without_text(&self) -> Self {
107 Self { text: String::new(), style: self.style, link: self.link.clone(), is_frame: self.is_frame }
108 }
109}
110
111#[derive(Clone, Debug, Default, PartialEq, Eq)]
112pub struct Line {
113 pub spans: Vec<Span>,
114}
115
116impl Line {
117 pub fn new(spans: Vec<Span>) -> Self {
118 Self { spans }
119 }
120
121 pub(crate) fn joined<'a>(pieces: impl IntoIterator<Item = (&'a str, &'a Span)>) -> Self {
125 let pieces: Vec<(&str, &Span)> = pieces.into_iter().collect();
126 let runs = pieces.chunk_by(|(_, left), (_, right)| left.looks_like(right));
127 let mut spans = Vec::with_capacity(runs.clone().count());
128 spans.extend(runs.map(|run| {
129 let mut text = String::with_capacity(run.iter().map(|(piece, _)| piece.len()).sum());
130 text.extend(run.iter().map(|(piece, _)| *piece));
131 let (_, first) = run[0];
132 Span { text, ..first.without_text() }
133 }));
134 Self::new(spans)
135 }
136
137 pub fn blank() -> Self {
138 Self::default()
139 }
140
141 pub fn width(&self) -> usize {
142 crate::text::spans_width(&self.spans)
143 }
144
145 pub fn plain(&self) -> String {
147 crate::text::joined(&self.spans)
148 }
149
150 pub fn printable(&self) -> String {
152 sanitize::text(&self.plain())
153 }
154}
155
156#[derive(Clone, Debug, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct Picture {
160 pub png: Vec<u8>,
161 pub cols: u16,
162 pub rows: u16,
163 pub alt: String,
164 pub indent: Line,
167 pub concealed_text: Option<String>,
169}
170
171#[derive(Clone, Debug, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum Block {
174 Lines(Vec<Line>),
175 Picture(Picture),
176 DoubleHeight(Vec<Line>),
178}
179
180impl Block {
181 pub fn lines(&self) -> &[Line] {
183 match self {
184 Block::Lines(lines) | Block::DoubleHeight(lines) => lines,
185 Block::Picture(_) => &[],
186 }
187 }
188}
189
190#[derive(Clone, Debug, Default, PartialEq, Eq)]
191pub struct Document {
192 pub blocks: Vec<Block>,
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub struct CellSize {
198 pub width_px: u16,
199 pub height_px: u16,
200}
201
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204#[non_exhaustive]
205pub enum JumboTitle {
206 Picture,
208 DoubleHeight,
210}
211
212pub const MIN_WIDTH: usize = 8;
215
216#[derive(Clone, Copy, Debug, PartialEq)]
217#[non_exhaustive]
218pub struct Settings {
219 pub width: usize,
220 pub theme: Theme,
221 pub cell: Option<CellSize>,
222 pub hyperlinks: bool,
224 pub jumbo_title: Option<JumboTitle>,
225 pub diagram_deadline: Option<Instant>,
228}
229
230impl Default for Settings {
233 fn default() -> Self {
234 Self { width: 80, theme: crate::theme::MRK_DARK, cell: None, hyperlinks: false, jumbo_title: None, diagram_deadline: None }
235 }
236}
237
238#[cfg(test)]
240pub(crate) fn test_settings() -> Settings {
241 Settings { hyperlinks: true, ..Settings::default() }
242}
243
244pub fn plain(document: &Document) -> String {
247 document.blocks.iter().map(plain_block).collect()
248}
249
250pub fn printable(document: &Document) -> String {
252 sanitize::lines(&plain(document))
253}
254
255fn plain_block(block: &Block) -> String {
256 match block {
257 Block::Lines(lines) => lines.iter().map(|line| format!("{}\n", line.plain().trim_end())).collect(),
258 Block::Picture(picture) => format!("{}[picture: {} {}×{}]\n", picture.indent.plain(), picture.alt, picture.cols, picture.rows),
259 Block::DoubleHeight(lines) => lines.iter().map(|line| format!("{0}\n{0}\n", line.plain().trim_end())).collect(),
260 }
261}
262
263fn split_span(span: &Span, first: usize, ranges: &[Range<usize>], restyle: &impl Fn(Style) -> Style) -> Vec<Span> {
266 let end = first + span.text.chars().count();
267 let touching = ranges[ranges.partition_point(|range| range.end <= first)..].iter().take_while(|range| range.start < end);
268 let piece = |text: &str, style: Style| Span { text: text.to_owned(), style, ..span.without_text() };
269 let mut pieces = Vec::new();
270 let (mut at, mut rest) = (first, span.text.as_str());
271 for range in touching.map(|range| range.start.max(first)..range.end.min(end)) {
272 let (outside, tail) = split_chars(rest, range.start - at);
273 let (inside, tail) = split_chars(tail, range.len());
274 pieces.extend((!outside.is_empty()).then(|| piece(outside, span.style)));
275 pieces.push(piece(inside, restyle(span.style)));
276 (at, rest) = (range.end, tail);
277 }
278 if pieces.is_empty() || !rest.is_empty() {
279 pieces.push(piece(rest, span.style));
280 }
281 pieces
282}
283
284fn split_chars(text: &str, count: usize) -> (&str, &str) {
285 text.split_at(text.char_indices().nth(count).map_or(text.len(), |(index, _)| index))
286}
287
288fn normalized(ranges: &[Range<usize>]) -> Vec<Range<usize>> {
290 let mut sorted: Vec<Range<usize>> = ranges.iter().filter(|range| !range.is_empty()).cloned().collect();
291 sorted.sort_unstable_by_key(|range| range.start);
292 sorted.into_iter().fold(Vec::new(), |mut merged: Vec<Range<usize>>, range| {
293 match merged.last_mut() {
294 Some(last) if range.start <= last.end => last.end = last.end.max(range.end),
295 _ => merged.push(range),
296 }
297 merged
298 })
299}
300
301fn span_offsets(lines: &[Line]) -> impl Iterator<Item = usize> {
303 lines.iter().flat_map(|line| &line.spans).scan(0, |next, span| {
304 let first = *next;
305 *next += span.text.chars().count();
306 Some(first)
307 })
308}
309
310pub fn highlight(lines: &[Line], ranges: &[Range<usize>], restyle: impl Fn(Style) -> Style) -> Vec<Line> {
316 let ranges = normalized(ranges);
317 let mut offsets = span_offsets(lines);
318 lines
319 .iter()
320 .map(|line| {
321 let spans = line.spans.iter().zip(offsets.by_ref()).flat_map(|(span, first)| split_span(span, first, &ranges, &restyle));
322 Line::new(spans.collect())
323 })
324 .collect()
325}
326
327#[cfg(test)]
328mod tests {
329 #![allow(clippy::single_range_in_vec_init)]
330
331 use super::*;
332
333 const RED: Rgb = Rgb(255, 0, 0);
334
335 #[test]
336 fn printable_text_carries_no_escape_sequence_while_plain_keeps_the_input() {
337 let line = Line::new(vec![Span::plain("hi \x1b]52;c;AAAA\x07"), Span::plain(" there")]);
338
339 assert_eq!(line.plain(), "hi \x1b]52;c;AAAA\x07 there");
340 assert_eq!(line.printable(), "hi ]52;c;AAAA there");
341 }
342
343 #[test]
344 fn a_printable_document_keeps_its_line_breaks_and_loses_escape_sequences() {
345 let line = Line::new(vec![Span::plain("a\x1b[2J")]);
346 let document = Document { blocks: vec![Block::Lines(vec![line.clone(), line])] };
347
348 assert_eq!(printable(&document), "a[2J\na[2J\n");
349 }
350
351 #[test]
352 fn mix_moves_each_channel_toward_the_other_colour_and_rounds() {
353 let black = Rgb(0, 0, 0);
354
355 assert_eq!(black.mix(RED, 0.0), black);
356 assert_eq!(black.mix(RED, 1.0), RED);
357 assert_eq!(Rgb(10, 200, 0).mix(Rgb(20, 100, 255), 0.25), Rgb(13, 175, 64));
358 }
359
360 #[test]
361 fn plain_joins_spans_and_trims_trailing_padding() {
362 let line = Line::new(vec![Span::plain("a "), Span::plain("b ")]);
363 let document = Document { blocks: vec![Block::Lines(vec![line, Line::blank()])] };
364
365 assert_eq!(plain(&document), "a b\n\n");
366 }
367
368 #[test]
369 fn plain_draws_a_picture_after_its_indent() {
370 let picture = Picture {
371 png: Vec::new(),
372 cols: 4,
373 rows: 2,
374 alt: "flow".to_owned(),
375 indent: Line::new(vec![Span::plain("│ ")]),
376 concealed_text: None,
377 };
378
379 assert_eq!(plain(&Document { blocks: vec![Block::Picture(picture)] }), "│ [picture: flow 4×2]\n");
380 }
381
382 #[test]
383 fn plain_writes_a_double_height_line_on_its_two_rows() {
384 let document = Document { blocks: vec![Block::DoubleHeight(vec![Line::new(vec![Span::plain("Big ")])])] };
385
386 assert_eq!(plain(&document), "Big\nBig\n");
387 }
388
389 #[test]
390 fn hex_writes_two_digits_per_channel() {
391 assert_eq!(Rgb(0, 15, 255).hex(), "#000fff");
392 }
393
394 #[test]
395 fn joined_merges_neighbours_of_the_same_look_into_spans_of_exact_size() {
396 let (plain, red) = (Span::plain("a"), Span::new("b", Style::fg(RED)));
397
398 let line = Line::joined([("ab", &plain), ("c", &plain), ("d", &red), ("e", &plain)]);
399
400 assert_eq!(line.spans, [Span::plain("abc"), Span::new("d", Style::fg(RED)), Span::plain("e")]);
401 assert_eq!((line.spans.capacity(), line.spans[0].text.capacity()), (3, 3));
402 }
403
404 #[test]
405 fn joined_keeps_neighbours_with_different_links_apart() {
406 let (plain, linked) = (Span::plain("a"), Span::plain("b").linked("https://x.y"));
407
408 let line = Line::joined([("a", &plain), ("b", &linked), ("c", &linked)]);
409
410 assert_eq!(line.spans, [Span::plain("a"), Span::plain("bc").linked("https://x.y")]);
411 assert_eq!(Line::joined([("a", &plain), ("b", &plain.clone().framed())]).spans.len(), 2);
412 }
413
414 #[test]
415 fn line_width_counts_cells_not_bytes() {
416 let line = Line::new(vec![Span::plain("é漢")]);
417
418 assert_eq!(line.width(), 3);
419 }
420
421 #[test]
422 fn highlight_splits_spans_at_the_range_edges_and_keeps_links() {
423 let line =
424 Line::new(vec![Span::new("say hel", Style::fg(RED)), Span::new("lo world", Style::fg(RED).bold()).linked("https://x.y")]);
425
426 let lit = highlight(&[line], &[4..9], Style::underline);
427
428 assert_eq!(
429 lit[0].spans,
430 [
431 Span::new("say ", Style::fg(RED)),
432 Span::new("hel", Style::fg(RED).underline()),
433 Span::new("lo", Style::fg(RED).bold().underline()).linked("https://x.y"),
434 Span::new(" world", Style::fg(RED).bold()).linked("https://x.y"),
435 ]
436 );
437 }
438
439 #[test]
440 fn highlight_crosses_a_line_break_without_changing_the_text() {
441 let lines = [Line::new(vec![Span::plain("one two")]), Line::new(vec![Span::plain("three")])];
442
443 let lit = highlight(&lines, &[4..9], Style::bold);
444
445 assert_eq!(lit[0].spans, [Span::plain("one "), Span::new("two", Style::default().bold())]);
446 assert_eq!(lit[1].spans, [Span::new("th", Style::default().bold()), Span::plain("ree")]);
447 assert_eq!(lit.iter().map(Line::width).collect::<Vec<_>>(), [7, 5]);
448 }
449
450 #[test]
451 fn neighbouring_ranges_restyle_as_one_piece_and_a_range_over_a_whole_span_keeps_it_whole() {
452 let line = Line::new(vec![Span::plain("abcd"), Span::plain("ef")]);
453
454 let lit = highlight(&[line], &[1..2, 2..3, 4..6], Style::bold);
455
456 assert_eq!(
457 lit[0].spans,
458 [Span::plain("a"), Span::new("bc", Style::default().bold()), Span::plain("d"), Span::new("ef", Style::default().bold())]
459 );
460 }
461
462 #[test]
463 fn ranges_in_any_order_overlapping_or_repeated_cut_each_edge_once() {
464 let lines = [Line::new(vec![Span::plain("abcdef")])];
465 let bold = Style::default().bold();
466
467 let lit = highlight(&lines, &[4..5, 1..3, 2..3, 1..3, 5..5], Style::bold);
468
469 assert_eq!(lit[0].spans, [Span::plain("a"), Span::new("bc", bold), Span::plain("d"), Span::new("e", bold), Span::plain("f")]);
470 }
471
472 #[test]
473 fn an_empty_range_changes_nothing() {
474 let lines = [Line::new(vec![Span::plain("abc")])];
475
476 assert_eq!(highlight(&lines, &[1..1], Style::bold), lines);
477 }
478}