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