Skip to main content

compose_rust/
spans.rs

1//! Runs of different treatment inside one `Text`.
2//!
3//! Not a widget. A paragraph with a bold phrase and a link in it is one piece of text, and
4//! splitting it into three widgets to say so would break line wrapping at the seams: the
5//! renderer would wrap each piece on its own and the phrase would never share a line with
6//! what surrounds it.
7//!
8//! So the spans travel beside the string, as a blob of fixed-length records in the same
9//! shape a `Canvas` carries its commands. Nothing new crosses the boundary to do it.
10//!
11//! Markdown is a convenience on this side. [`TextSpans::from_markdown`] turns a small,
12//! closed subset into spans, and the Renderer never hears the word.
13
14use crate::font_features::{
15    FONT_FEATURE_LEN, FONT_FEATURE_TAG_AT, FONT_FEATURE_VALUE_AT, FontFeature, MAX_FONT_FEATURES,
16};
17use crate::fonts::{FONT_REF_LEN, FontRefs};
18use crate::schema::{Paint, TypeRole};
19use std::rc::Rc;
20
21/// Bytes of one span record: two ranges' worth of offsets, a role, flags, the text's paint,
22/// the background's paint and a handler. Four-byte aligned throughout, which is the
23/// protocol's invariant.
24pub const SPAN_LEN: usize = 36;
25
26/// Where each field of a span record starts. The Kotlin decoder is generated from these, so
27/// the two sides read the same bytes.
28pub const SPAN_START_AT: usize = 0;
29pub const SPAN_LENGTH_AT: usize = 4;
30pub const SPAN_ROLE_AT: usize = 8;
31pub const SPAN_FLAGS_AT: usize = 10;
32pub const SPAN_COLOR_AT: usize = 12;
33pub const SPAN_BACKGROUND_AT: usize = 20;
34pub const SPAN_HANDLER_AT: usize = 28;
35
36/// Bytes of one entry in a span font table: which run, then where its font list starts
37/// and how many candidates it holds.
38///
39/// The table is a blob of its own, beside the runs rather than inside their records, so a
40/// run record is the same 36 bytes whether or not anything names a font.
41pub const SPAN_FONT_ENTRY_LEN: usize = 12;
42pub const SPAN_FONT_SPAN_AT: usize = 0;
43pub const SPAN_FONT_OFFSET_AT: usize = 4;
44pub const SPAN_FONT_COUNT_AT: usize = 8;
45
46/// Bytes of one entry in a span font feature table: which run, then where its feature
47/// records start and how many there are.
48///
49/// The table is a blob of its own, beside the runs rather than inside their records, so a
50/// run record is the same 36 bytes whether or not anything names a font feature. It opens
51/// with the number of entries as a `u32`, the entries follow, and the 8-byte feature
52/// records (the ones `FontFeatureSettings` carries) come after them. Every offset counts
53/// from the start of the blob and is a multiple of four.
54pub const SPAN_FEATURE_ENTRY_LEN: usize = 12;
55pub const SPAN_FEATURE_SPAN_AT: usize = 0;
56pub const SPAN_FEATURE_OFFSET_AT: usize = 4;
57pub const SPAN_FEATURE_COUNT_AT: usize = 8;
58
59pub const FLAG_BOLD: u16 = 1;
60pub const FLAG_ITALIC: u16 = 2;
61pub const FLAG_UNDERLINE: u16 = 4;
62pub const FLAG_STRIKETHROUGH: u16 = 8;
63
64/// One run, given in bytes into the string rather than characters.
65///
66/// Bytes because that is what the string is measured in on both sides, and a character
67/// count would have to be recomputed against a UTF-8 buffer at every use.
68#[derive(Clone, Copy, Debug, Default, PartialEq)]
69pub struct TextSpan {
70    pub start: u32,
71    pub length: u32,
72    pub type_role: Option<TypeRole>,
73    pub color: Option<Paint>,
74    /// What is painted behind this run's letters, and only behind them.
75    ///
76    /// The word that actually changed inside a changed line is what this is for: the line
77    /// is the node's own background, and this marks the part of it that differs. A run
78    /// that wraps is painted on each line it reaches. There is no shape and no inset,
79    /// because nothing yet needs one, and when something does it is the design system's
80    /// to say.
81    pub background: Option<Paint>,
82    pub bold: bool,
83    pub italic: bool,
84    pub underline: bool,
85    pub strikethrough: bool,
86    /// The handler a press on this run reports to, if it is a link.
87    pub on_click: Option<u64>,
88}
89
90impl TextSpan {
91    /// A run of the given bytes with nothing said about it yet.
92    pub const fn new(start: u32, length: u32) -> Self {
93        Self {
94            start,
95            length,
96            type_role: None,
97            color: None,
98            background: None,
99            bold: false,
100            italic: false,
101            underline: false,
102            strikethrough: false,
103            on_click: None,
104        }
105    }
106
107    pub const fn bold(mut self) -> Self {
108        self.bold = true;
109        self
110    }
111
112    pub const fn italic(mut self) -> Self {
113        self.italic = true;
114        self
115    }
116
117    pub const fn underline(mut self) -> Self {
118        self.underline = true;
119        self
120    }
121
122    pub const fn strikethrough(mut self) -> Self {
123        self.strikethrough = true;
124        self
125    }
126
127    pub const fn with_role(mut self, role: TypeRole) -> Self {
128        self.type_role = Some(role);
129        self
130    }
131
132    pub const fn with_color(mut self, color: Paint) -> Self {
133        self.color = Some(color);
134        self
135    }
136
137    /// Paints behind this run. A role first, as everywhere else a colour is taken: the
138    /// diff's word backgrounds are roles, so they follow the scheme and the system.
139    pub const fn with_background(mut self, background: Paint) -> Self {
140        self.background = Some(background);
141        self
142    }
143
144    fn flags(&self) -> u16 {
145        let mut flags = 0;
146        if self.bold {
147            flags |= FLAG_BOLD;
148        }
149        if self.italic {
150            flags |= FLAG_ITALIC;
151        }
152        if self.underline {
153            flags |= FLAG_UNDERLINE;
154        }
155        if self.strikethrough {
156            flags |= FLAG_STRIKETHROUGH;
157        }
158        flags
159    }
160
161    fn write_into(&self, out: &mut Vec<u8>) {
162        out.extend_from_slice(&self.start.to_le_bytes());
163        out.extend_from_slice(&self.length.to_le_bytes());
164        out.extend_from_slice(&self.type_role.map_or(0, u16::from).to_le_bytes());
165        out.extend_from_slice(&self.flags().to_le_bytes());
166        // Zero is "none" for both paints, which no real paint encodes to: every kind
167        // has a non-zero tag in its high word.
168        let paint = self.color.map_or(0, Paint::to_bits);
169        out.extend_from_slice(&(paint as u32).to_le_bytes());
170        out.extend_from_slice(&((paint >> 32) as u32).to_le_bytes());
171        let background = self.background.map_or(0, Paint::to_bits);
172        out.extend_from_slice(&(background as u32).to_le_bytes());
173        out.extend_from_slice(&((background >> 32) as u32).to_le_bytes());
174        let handler = self.on_click.unwrap_or(0);
175        out.extend_from_slice(&(handler as u32).to_le_bytes());
176        out.extend_from_slice(&((handler >> 32) as u32).to_le_bytes());
177    }
178}
179
180/// What a marker turns its body into: the bytes that open and close it, and the span the
181/// enclosed run becomes.
182type Marked = (&'static [u8], fn(u32, u32) -> TextSpan);
183
184/// An encoded list of spans, ready to travel.
185///
186/// Shared rather than copied, for the same reason a draw list is: the same list redrawn
187/// every frame compares equal and produces no mutation at all.
188#[derive(Clone, Default, PartialEq)]
189pub struct TextSpans {
190    bytes: Option<Rc<[u8]>>,
191    /// The font table for runs that name one, which only text with no role reads.
192    fonts: Option<Rc<[u8]>>,
193    /// The font feature table for runs that name features of their own, which text takes
194    /// with or without a role.
195    features: Option<Rc<[u8]>>,
196}
197
198impl std::fmt::Debug for TextSpans {
199    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        formatter
201            .debug_struct("TextSpans")
202            .field("spans", &(self.as_bytes().len() / SPAN_LEN))
203            .field("fonts", &self.font_entry_count())
204            .field("features", &self.feature_entry_count())
205            .finish()
206    }
207}
208
209impl TextSpans {
210    pub fn new(spans: impl IntoIterator<Item = TextSpan>) -> Self {
211        let mut bytes = Vec::new();
212        for span in spans {
213            span.write_into(&mut bytes);
214        }
215        Self::from_bytes(bytes)
216    }
217
218    /// Runs, each with the fonts it is set in where the text has no role.
219    ///
220    /// An empty list leaves that run in the text's own font. A run of text that has a
221    /// role is always in the theme's font, whatever it names here.
222    pub fn new_with_fonts(spans: impl IntoIterator<Item = (TextSpan, FontRefs)>) -> Self {
223        let mut bytes = Vec::new();
224        let mut named: Vec<(u32, FontRefs)> = Vec::new();
225        for (index, (span, fonts)) in spans.into_iter().enumerate() {
226            span.write_into(&mut bytes);
227            if !fonts.is_empty() {
228                named.push((index as u32, fonts));
229            }
230        }
231        let mut spans = Self::from_bytes(bytes);
232        spans.fonts = encode_font_table(&named);
233        spans
234    }
235
236    /// Runs, each with the OpenType features it is set with, such as
237    /// `FontFeature::TABULAR_NUMS` on the one run that is a number.
238    ///
239    /// An empty list leaves that run with the features of the text it is in. A run that
240    /// names features takes the text's as well, and where both name a tag the run's value
241    /// is the one used. Unlike a font, features are taken by a run with a role and by a
242    /// run of text that has one: they pick a form of the font and leave the font alone.
243    /// At most `MAX_FONT_FEATURES` (16) are taken for one run; a longer list is still
244    /// sent, so the Renderer can say what is wrong with it.
245    pub fn new_with_features(
246        spans: impl IntoIterator<Item = (TextSpan, impl AsRef<[FontFeature]>)>,
247    ) -> Self {
248        let mut bytes = Vec::new();
249        let mut named: Vec<(u32, Vec<FontFeature>)> = Vec::new();
250        for (index, (span, features)) in spans.into_iter().enumerate() {
251            span.write_into(&mut bytes);
252            let slice = features.as_ref();
253            if !slice.is_empty() {
254                named.push((index as u32, slice.to_vec()));
255            }
256        }
257        let mut spans = Self::from_bytes(bytes);
258        spans.features = encode_feature_table(&named);
259        spans
260    }
261
262    /// Adopts an already encoded list, which is what the protocol vectors carry.
263    pub fn from_bytes(bytes: impl Into<Rc<[u8]>>) -> Self {
264        let bytes = bytes.into();
265        Self {
266            bytes: (!bytes.is_empty()).then_some(bytes),
267            fonts: None,
268            features: None,
269        }
270    }
271
272    /// The same runs with an already encoded font table beside them.
273    pub fn with_font_table(mut self, table: impl Into<Rc<[u8]>>) -> Self {
274        let table = table.into();
275        self.fonts = (!table.is_empty()).then_some(table);
276        self
277    }
278
279    /// The same runs with an already encoded font feature table beside them, as
280    /// [`encode_feature_table`] lays one out. An empty table is no table.
281    pub fn with_feature_table(mut self, table: impl Into<Rc<[u8]>>) -> Self {
282        let table = table.into();
283        self.features = (!table.is_empty()).then_some(table);
284        self
285    }
286
287    pub fn as_bytes(&self) -> &[u8] {
288        self.bytes.as_deref().unwrap_or(&[])
289    }
290
291    /// The `SpanFonts` blob: a count, then one entry per run that names fonts, then the
292    /// font lists themselves. Every offset in it counts from the start of the blob.
293    pub fn font_table(&self) -> &[u8] {
294        self.fonts.as_deref().unwrap_or(&[])
295    }
296
297    /// The `SpanFontFeatures` blob: a count, then one entry per run that names features,
298    /// then the feature records themselves. Every offset in it counts from the start of
299    /// the blob. Empty where no run names a feature, and then nothing is sent.
300    pub fn feature_table(&self) -> &[u8] {
301        self.features.as_deref().unwrap_or(&[])
302    }
303
304    /// The same table, shared rather than copied, for a widget to keep and compare.
305    pub(crate) fn shared_feature_table(&self) -> Option<Rc<[u8]>> {
306        self.features.clone()
307    }
308
309    pub fn is_empty(&self) -> bool {
310        self.bytes.is_none()
311    }
312
313    /// How many runs name fonts.
314    pub fn font_entry_count(&self) -> usize {
315        let table = self.font_table();
316        if table.len() < 4 {
317            return 0;
318        }
319        u32::from_le_bytes([table[0], table[1], table[2], table[3]]) as usize
320    }
321
322    /// The fonts each run that names any is set in, by the run's index.
323    pub fn span_fonts(&self) -> Vec<(u32, Vec<crate::fonts::FontRef>)> {
324        let table = self.font_table();
325        let word = |at: usize| -> Option<u32> {
326            let slice = table.get(at..at + 4)?;
327            Some(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
328        };
329        (0..self.font_entry_count())
330            .filter_map(|entry| {
331                let at = 4 + entry * SPAN_FONT_ENTRY_LEN;
332                let span = word(at + SPAN_FONT_SPAN_AT)?;
333                let offset = word(at + SPAN_FONT_OFFSET_AT)? as usize;
334                let count = word(at + SPAN_FONT_COUNT_AT)? as usize;
335                let refs = (0..count)
336                    .filter_map(|index| {
337                        crate::fonts::decode_record(table, offset + index * FONT_REF_LEN)
338                    })
339                    .collect();
340                Some((span, refs))
341            })
342            .collect()
343    }
344
345    /// How many runs name font features, as the table's own count says.
346    pub fn feature_entry_count(&self) -> usize {
347        let table = self.feature_table();
348        if table.len() < 4 {
349            return 0;
350        }
351        u32::from_le_bytes([table[0], table[1], table[2], table[3]]) as usize
352    }
353
354    /// The font features each run that names any is set with, by the run's index, in the
355    /// order the table lists them.
356    ///
357    /// Empty where there is no table and where the table cannot be read by the rules the
358    /// Renderer holds it to: an entry or a feature list that runs past the end, an offset
359    /// that is not a multiple of four, more than `MAX_FONT_FEATURES` features for one run,
360    /// or a run named twice. The Renderer reports such a table and draws the text without
361    /// any of it, so nothing is read out of half of one here either.
362    pub fn span_features(&self) -> Vec<(u32, Vec<FontFeature>)> {
363        decode_feature_table(self.feature_table()).unwrap_or_default()
364    }
365
366    /// The runs this list holds, decoded again.
367    pub fn spans(&self) -> impl Iterator<Item = TextSpan> + '_ {
368        self.as_bytes().chunks_exact(SPAN_LEN).map(|record| {
369            let word = |at: usize| {
370                u32::from_le_bytes([record[at], record[at + 1], record[at + 2], record[at + 3]])
371            };
372            let half = |at: usize| u16::from_le_bytes([record[at], record[at + 1]]);
373            let flags = half(SPAN_FLAGS_AT);
374            let paint = u64::from(word(SPAN_COLOR_AT)) | (u64::from(word(SPAN_COLOR_AT + 4)) << 32);
375            let background = u64::from(word(SPAN_BACKGROUND_AT))
376                | (u64::from(word(SPAN_BACKGROUND_AT + 4)) << 32);
377            let handler =
378                u64::from(word(SPAN_HANDLER_AT)) | (u64::from(word(SPAN_HANDLER_AT + 4)) << 32);
379            TextSpan {
380                start: word(SPAN_START_AT),
381                length: word(SPAN_LENGTH_AT),
382                type_role: TypeRole::try_from(half(SPAN_ROLE_AT)).ok(),
383                color: Paint::from_bits(paint),
384                background: Paint::from_bits(background),
385                bold: flags & FLAG_BOLD != 0,
386                italic: flags & FLAG_ITALIC != 0,
387                underline: flags & FLAG_UNDERLINE != 0,
388                strikethrough: flags & FLAG_STRIKETHROUGH != 0,
389                on_click: (handler != 0).then_some(handler),
390            }
391        })
392    }
393
394    /// Turns a small, closed subset of markdown into a plain string and its spans.
395    ///
396    /// `**bold**`, `*italic*` and `` `code` ``, and nothing else. It is a convenience, not
397    /// a parser: anything it does not recognise is left in the string exactly as written,
398    /// because silently eating a character a reader typed is worse than showing it.
399    ///
400    /// Links are not here. A link needs a handler, and a handler is something the screen
401    /// has rather than something a string can name.
402    pub fn from_markdown(source: &str) -> (String, Self) {
403        let mut text = String::with_capacity(source.len());
404        let mut spans = Vec::new();
405        let bytes = source.as_bytes();
406        let mut at = 0;
407        while at < bytes.len() {
408            let (marker, span_of): Marked = if bytes[at..].starts_with(b"**") {
409                (b"**", |start, length| TextSpan::new(start, length).bold())
410            } else if bytes[at] == b'*' {
411                (b"*", |start, length| TextSpan::new(start, length).italic())
412            } else if bytes[at] == b'`' {
413                (b"`", |start, length| {
414                    TextSpan::new(start, length).with_role(TypeRole::Mono)
415                })
416            } else {
417                text.push(source[at..].chars().next().expect("a char boundary"));
418                at += source[at..].chars().next().map_or(1, char::len_utf8);
419                continue;
420            };
421            let body = at + marker.len();
422            let Some(end) = find(&bytes[body..], marker).map(|offset| body + offset) else {
423                // No closing marker, so this is not a marker at all.
424                text.push_str(&source[at..body]);
425                at = body;
426                continue;
427            };
428            let start = text.len() as u32;
429            text.push_str(&source[body..end]);
430            spans.push(span_of(start, text.len() as u32 - start));
431            at = end + marker.len();
432        }
433        (text, Self::new(spans))
434    }
435}
436
437/// Lays out a span font table: the count, one entry per run, and after them each run's
438/// font records, each followed by the names its records point at.
439fn encode_font_table(named: &[(u32, FontRefs)]) -> Option<Rc<[u8]>> {
440    if named.is_empty() {
441        return None;
442    }
443    let mut entries = Vec::with_capacity(named.len() * SPAN_FONT_ENTRY_LEN);
444    let mut lists: Vec<u8> = Vec::new();
445    let lists_at = 4 + named.len() * SPAN_FONT_ENTRY_LEN;
446    for (span, fonts) in named {
447        let offset = (lists_at + lists.len()) as u32;
448        let count = fonts.len() as u32;
449        entries.extend_from_slice(&span.to_le_bytes());
450        entries.extend_from_slice(&offset.to_le_bytes());
451        entries.extend_from_slice(&count.to_le_bytes());
452        let names_at = offset + count * FONT_REF_LEN as u32;
453        fonts.write_relocated(&mut lists, names_at);
454    }
455    let mut table = Vec::with_capacity(lists_at + lists.len());
456    table.extend_from_slice(&(named.len() as u32).to_le_bytes());
457    table.extend_from_slice(&entries);
458    table.extend_from_slice(&lists);
459    Some(table.into())
460}
461
462/// Lays out a span font feature table: the count, one entry per run, and after them
463/// each run's 8-byte feature records.
464///
465/// `named` pairs a run's index in its run list with that run's features. A run with no
466/// features gets no entry, and a list with no entry at all is no table, so text that names
467/// no feature sends nothing. Each run is named at most once: the Renderer reports a table
468/// that names a run twice, or names a run the text does not have, and draws the text
469/// without span features.
470pub fn encode_feature_table(named: &[(u32, Vec<FontFeature>)]) -> Option<Rc<[u8]>> {
471    let entry_count = named
472        .iter()
473        .filter(|(_, features)| !features.is_empty())
474        .count();
475    if entry_count == 0 {
476        return None;
477    }
478    let lists_at = 4 + entry_count * SPAN_FEATURE_ENTRY_LEN;
479    let mut entries = Vec::with_capacity(entry_count * SPAN_FEATURE_ENTRY_LEN);
480    let mut lists: Vec<u8> = Vec::new();
481    for (span, features) in named {
482        if features.is_empty() {
483            continue;
484        }
485        let offset = (lists_at + lists.len()) as u32;
486        let count = features.len() as u32;
487        entries.extend_from_slice(&span.to_le_bytes());
488        entries.extend_from_slice(&offset.to_le_bytes());
489        entries.extend_from_slice(&count.to_le_bytes());
490        for feature in features {
491            lists.extend_from_slice(&feature.to_bytes());
492        }
493    }
494    let mut table = Vec::with_capacity(lists_at + lists.len());
495    table.extend_from_slice(&(entry_count as u32).to_le_bytes());
496    table.extend_from_slice(&entries);
497    table.extend_from_slice(&lists);
498    Some(table.into())
499}
500
501/// Reads a span font feature table back, or `None` where it breaks a rule of its layout.
502/// An empty blob is a table with no entries.
503fn decode_feature_table(table: &[u8]) -> Option<Vec<(u32, Vec<FontFeature>)>> {
504    if table.is_empty() {
505        return Some(Vec::new());
506    }
507    let word = |at: usize| -> Option<u32> {
508        let bytes = table.get(at..at.checked_add(4)?)?;
509        Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
510    };
511    let entry_count = word(0)? as usize;
512    // Checked before anything is allocated or walked, so a count that is only a large
513    // number costs nothing.
514    let entries_end = entry_count
515        .checked_mul(SPAN_FEATURE_ENTRY_LEN)?
516        .checked_add(4)?;
517    if entries_end > table.len() {
518        return None;
519    }
520    let mut decoded: Vec<(u32, Vec<FontFeature>)> = Vec::with_capacity(entry_count);
521    for entry in 0..entry_count {
522        let at = 4 + entry * SPAN_FEATURE_ENTRY_LEN;
523        let span = word(at + SPAN_FEATURE_SPAN_AT)?;
524        let offset = word(at + SPAN_FEATURE_OFFSET_AT)? as usize;
525        let count = word(at + SPAN_FEATURE_COUNT_AT)? as usize;
526        if count > MAX_FONT_FEATURES || offset % 4 != 0 || offset < entries_end {
527            return None;
528        }
529        let end = offset.checked_add(count * FONT_FEATURE_LEN)?;
530        if end > table.len() || decoded.iter().any(|(seen, _)| *seen == span) {
531            return None;
532        }
533        let features = table[offset..end]
534            .chunks_exact(FONT_FEATURE_LEN)
535            .map(|record| {
536                let tag_at = FONT_FEATURE_TAG_AT;
537                let value_at = FONT_FEATURE_VALUE_AT;
538                FontFeature::new(
539                    &[
540                        record[tag_at],
541                        record[tag_at + 1],
542                        record[tag_at + 2],
543                        record[tag_at + 3],
544                    ],
545                    u32::from_le_bytes([
546                        record[value_at],
547                        record[value_at + 1],
548                        record[value_at + 2],
549                        record[value_at + 3],
550                    ]),
551                )
552            })
553            .collect();
554        decoded.push((span, features));
555    }
556    Some(decoded)
557}
558
559fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
560    haystack
561        .windows(needle.len())
562        .position(|window| window == needle)
563}