Skip to main content

crabshell_ui/
rich.rs

1//! Styled spans for [`Text::rich`](crate::Text::rich), and the markup
2//! subset of the Desktop Notifications spec, parsed into spans.
3
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use crate::style::Color;
7
8/// A run of text in a [`Text::rich`](crate::Text::rich), with its own
9/// settings. What a span doesn't set comes from the text: its inherited
10/// font, color and decorations.
11#[derive(Clone, Debug, Default, PartialEq)]
12pub struct Span {
13  /// The text. A line break in it starts a new line.
14  pub text: String,
15  /// Weight 700 on the text's font.
16  pub bold: bool,
17  /// The text's font, italic.
18  pub italic: bool,
19  /// A line under the span.
20  pub underline: bool,
21  /// A line through the span.
22  pub strikethrough: bool,
23  /// The span's color, or the text's for `None`.
24  pub color: Option<Color>,
25  /// A URL handed to the text's [`on_link`](crate::Text::on_link) when
26  /// the span is clicked. It draws as its other settings say.
27  pub link: Option<String>,
28}
29
30impl Span {
31  /// A span showing `text` as the text around it does.
32  pub fn new(text: impl Into<String>) -> Span {
33    Span {
34      text: text.into(),
35      ..Span::default()
36    }
37  }
38
39  /// Draws the span in weight 700.
40  pub fn bold(mut self) -> Span {
41    self.bold = true;
42    self
43  }
44
45  /// Draws the span in the italic face.
46  pub fn italic(mut self) -> Span {
47    self.italic = true;
48    self
49  }
50
51  /// Draws a line under the span.
52  pub fn underline(mut self) -> Span {
53    self.underline = true;
54    self
55  }
56
57  /// Draws a line through the span.
58  pub fn strikethrough(mut self) -> Span {
59    self.strikethrough = true;
60    self
61  }
62
63  /// Draws the span in `color`.
64  pub fn color(mut self, color: Color) -> Span {
65    self.color = Some(color);
66    self
67  }
68
69  /// Makes the span a link to `url`.
70  pub fn link(mut self, url: impl Into<String>) -> Span {
71    self.link = Some(url.into());
72    self
73  }
74}
75
76/// The longest body [`parse_markup`] reads, in bytes.
77pub const MARKUP_CAP: usize = 64 * 1024;
78
79/// Turns a notification body in the Desktop Notifications spec's markup
80/// into spans: `<b>`, `<i>`, `<u>`, `<a href="...">` and
81/// `<img src="..." alt="..."/>`, nested in any order, with the five XML
82/// entities and numeric character references. It never reads general
83/// HTML.
84///
85/// Unknown tags are dropped and their text kept. A `<` that doesn't start
86/// a tag, a bad entity and a close tag nothing opened stay or go as plain
87/// text; a tag left open lasts to the end. An `img` shows its `alt`, and
88/// its `src` is never read. A link is kept only for an `href` starting
89/// with `http:`, `https:` or `mailto:`; any other `a` is plain text, since
90/// a notification can come from any program. Links are underlined. A body
91/// over [`MARKUP_CAP`] bytes is cut before it is read, logged once.
92pub fn parse_markup(body: &str) -> Vec<Span> {
93  static CUT_LOGGED: AtomicBool = AtomicBool::new(false);
94  let mut body = body;
95  if body.len() > MARKUP_CAP {
96    let mut end = MARKUP_CAP;
97    while !body.is_char_boundary(end) {
98      end -= 1;
99    }
100    if !CUT_LOGGED.swap(true, Ordering::Relaxed) {
101      tracing::warn!(
102        bytes = body.len(),
103        "a markup body is over 64 KiB, so only its first 64 KiB are shown"
104      );
105    }
106    body = &body[..end];
107  }
108  let mut out = Markup::default();
109  let mut rest = body;
110  while let Some(at) = rest.find(['<', '&']) {
111    out.text(&rest[..at]);
112    rest = &rest[at..];
113    let used = if rest.starts_with('&') {
114      entity(rest).map(|(ch, len)| {
115        out.push(ch.encode_utf8(&mut [0; 4]));
116        len
117      })
118    } else {
119      tag(rest).map(|(tag, len)| {
120        out.tag(tag);
121        len
122      })
123    };
124    // Not an entity or a tag: the character is plain text.
125    let used = used.unwrap_or_else(|| {
126      out.push(&rest[..1]);
127      1
128    });
129    rest = &rest[used..];
130  }
131  out.text(rest);
132  out.spans
133}
134
135/// The spans so far and the tags open. Each open tag is kept as its kind,
136/// and each kind keeps where its open tags are, so styling a piece of text
137/// and closing a tag take the same time however deep the nesting goes.
138#[derive(Default)]
139struct Markup {
140  spans: Vec<Span>,
141  /// The kind of each open tag: `B`, `I`, `U` or `A`, outermost first.
142  open: Vec<usize>,
143  /// For each kind, where its open tags are in `open`.
144  at: [Vec<usize>; 4],
145  /// Each open `a`'s link, outermost first, with a number of its own.
146  links: Vec<(usize, Option<String>)>,
147  /// How many `a`s opened, which numbers them.
148  opened: usize,
149  /// The last span's bold, italic and underline, and the number of the
150  /// `a` its link came from.
151  last: Option<(bool, bool, bool, Option<usize>)>,
152}
153
154const B: usize = 0;
155const I: usize = 1;
156const U: usize = 2;
157const A: usize = 3;
158
159impl Markup {
160  /// Adds text, unless it is empty.
161  fn text(&mut self, text: &str) {
162    if !text.is_empty() {
163      self.push(text);
164    }
165  }
166
167  /// Adds text in the open tags' style, joined to the last span if it
168  /// looks the same.
169  fn push(&mut self, text: &str) {
170    let open = |kind: usize| !self.at[kind].is_empty();
171    let (number, link) = match self.links.last() {
172      Some((number, Some(link))) => (Some(*number), Some(link)),
173      _ => (None, None),
174    };
175    let style = (open(B), open(I), open(U) || link.is_some(), number);
176    let same = match (self.last, self.spans.last()) {
177      (Some(last), _) if last == style => true,
178      // Two links to the same place look the same; the text decides.
179      (Some((bold, italic, underline, _)), Some(span)) => {
180        (bold, italic, underline) == (style.0, style.1, style.2) && span.link.as_ref() == link
181      }
182      _ => false,
183    };
184    if let (true, Some(last)) = (same, self.spans.last_mut()) {
185      last.text.push_str(text);
186    } else {
187      self.spans.push(Span {
188        text: text.to_owned(),
189        bold: style.0,
190        italic: style.1,
191        underline: style.2,
192        strikethrough: false,
193        color: None,
194        link: link.cloned(),
195      });
196    }
197    self.last = Some(style);
198  }
199
200  fn tag(&mut self, tag: Tag) {
201    match tag {
202      Tag::Open(kind, link) => {
203        self.at[kind].push(self.open.len());
204        self.open.push(kind);
205        if kind == A {
206          self.links.push((self.opened, link));
207          self.opened += 1;
208        }
209      }
210      // Closing a tag closes any opened inside it and left open.
211      Tag::Close(kind) => {
212        let Some(&from) = self.at[kind].last() else {
213          return;
214        };
215        while self.open.len() > from {
216          let closed = self.open.pop().expect("open holds the tag closed");
217          self.at[closed].pop();
218          if closed == A {
219            self.links.pop();
220          }
221        }
222      }
223      Tag::Image(alt) => self.text(&alt),
224      Tag::Unknown => {}
225    }
226  }
227}
228
229enum Tag {
230  /// A kind, `B`, `I`, `U` or `A`, and an `a`'s link.
231  Open(usize, Option<String>),
232  Close(usize),
233  Image(String),
234  Unknown,
235}
236
237/// Reads the tag `text` starts with, and how many bytes it takes; `None`
238/// if the `<` doesn't start one.
239fn tag(text: &str) -> Option<(Tag, usize)> {
240  let bytes = text.as_bytes();
241  let mut at = 1;
242  let close = bytes.get(at) == Some(&b'/');
243  if close {
244    at += 1;
245  }
246  let name_start = at;
247  if !bytes.get(at)?.is_ascii_alphabetic() {
248    return None;
249  }
250  while bytes.get(at).is_some_and(u8::is_ascii_alphanumeric) {
251    at += 1;
252  }
253  let name = text[name_start..at].to_ascii_lowercase();
254  let mut attributes = Vec::new();
255  let mut empty = false;
256  loop {
257    while bytes.get(at).is_some_and(u8::is_ascii_whitespace) {
258      at += 1;
259    }
260    match bytes.get(at)? {
261      b'>' => {
262        at += 1;
263        break;
264      }
265      b'/' if bytes.get(at + 1) == Some(&b'>') => {
266        at += 2;
267        empty = true;
268        break;
269      }
270      // Attributes need whitespace after the name or the last value.
271      _ if !bytes[at - 1].is_ascii_whitespace() => return None,
272      _ => {
273        let (attribute, len) = attribute(&text[at..])?;
274        attributes.push(attribute);
275        at += len;
276      }
277    }
278  }
279  let value = |key: &str| {
280    attributes
281      .iter()
282      .find(|(name, _)| name.eq_ignore_ascii_case(key))
283      .map(|(_, value)| value.clone())
284  };
285  let tag = match (close, name.as_str()) {
286    (false, "img") => Tag::Image(value("alt").unwrap_or_default()),
287    // `<b/>` opens and closes at once, so it does nothing.
288    _ if empty => Tag::Unknown,
289    (false, "a") => Tag::Open(A, value("href").filter(|href| safe_link(href))),
290    (false, "b") => Tag::Open(B, None),
291    (false, "i") => Tag::Open(I, None),
292    (false, "u") => Tag::Open(U, None),
293    (true, "a") => Tag::Close(A),
294    (true, "b") => Tag::Close(B),
295    (true, "i") => Tag::Close(I),
296    (true, "u") => Tag::Close(U),
297    _ => Tag::Unknown,
298  };
299  Some((tag, at))
300}
301
302/// Reads `name="value"`, `name='value'` or `name=value` with its entities
303/// replaced, or a bare `name`. A `<` or the end of the text ends it with
304/// `None`, so a stray `<` is read once, never again for each one after it.
305fn attribute(text: &str) -> Option<((String, String), usize)> {
306  let name_len = text
307    .find(|ch: char| ch.is_ascii_whitespace() || matches!(ch, '=' | '>' | '/' | '<' | '"' | '\''))
308    .unwrap_or(text.len());
309  if name_len == 0 {
310    return None;
311  }
312  let name = text[..name_len].to_owned();
313  let rest = &text[name_len..];
314  let Some(rest) = rest.strip_prefix('=') else {
315    return Some(((name, String::new()), name_len));
316  };
317  let (raw, len) = match rest.chars().next()? {
318    quote @ ('"' | '\'') => {
319      let end = rest[1..].find([quote, '<'])? + 1;
320      if !rest[end..].starts_with(quote) {
321        return None;
322      }
323      (&rest[1..end], end + 1)
324    }
325    _ => {
326      let end = rest
327        .find(|ch: char| ch.is_ascii_whitespace() || matches!(ch, '>' | '<' | '"' | '\''))
328        .unwrap_or(rest.len());
329      (&rest[..end], end)
330    }
331  };
332  if rest[len..].is_empty() {
333    return None;
334  }
335  Some(((name, decode(raw)), name_len + 1 + len))
336}
337
338/// `text` with its entities replaced; a bad one stays as written.
339fn decode(text: &str) -> String {
340  let mut out = String::with_capacity(text.len());
341  let mut rest = text;
342  while let Some(at) = rest.find('&') {
343    out.push_str(&rest[..at]);
344    rest = &rest[at..];
345    match entity(rest) {
346      Some((ch, len)) => {
347        out.push(ch);
348        rest = &rest[len..];
349      }
350      None => {
351        out.push('&');
352        rest = &rest[1..];
353      }
354    }
355  }
356  out.push_str(rest);
357  out
358}
359
360/// Reads the entity `text` starts with, and how many bytes it takes: one
361/// of the five XML ones, or `&#N;` or `&#xN;` naming a character.
362fn entity(text: &str) -> Option<(char, usize)> {
363  // The longest is `&#x10FFFF;`; a short look keeps a body of stray `&`s
364  // from being read again for each one.
365  let end = text.bytes().take(12).position(|byte| byte == b';')?;
366  let ch = match &text[1..end] {
367    "amp" => '&',
368    "lt" => '<',
369    "gt" => '>',
370    "quot" => '"',
371    "apos" => '\'',
372    name => {
373      let number = name.strip_prefix('#')?;
374      let (digits, radix) = match number.strip_prefix(['x', 'X']) {
375        Some(hex) => (hex, 16),
376        None => (number, 10),
377      };
378      // `from_str_radix` would take a leading `+`.
379      if !digits.chars().all(|ch| ch.is_digit(radix)) {
380        return None;
381      }
382      let code = u32::from_str_radix(digits, radix).ok()?;
383      // NUL isn't a character XML allows.
384      char::from_u32(code).filter(|&ch| ch != '\0')?
385    }
386  };
387  Some((ch, end + 1))
388}
389
390/// Whether `href` is a link a notification may hand out: `http:`,
391/// `https:` or `mailto:`, in any case.
392fn safe_link(href: &str) -> bool {
393  ["http:", "https:", "mailto:"].iter().any(|scheme| {
394    href
395      .get(..scheme.len())
396      .is_some_and(|start| start.eq_ignore_ascii_case(scheme))
397  })
398}