Skip to main content

compose_rust/
measure.rs

1//! Asking the Renderer how big something will be, while the Host is laying it out.
2//!
3//! A Host that lays out a page itself (a flexbox, a grid, text flowing around a picture)
4//! needs to know how wide a run of text is before it can decide where anything goes, and
5//! only the side that draws the letters can say: the font, the density, the system's font
6//! scale and the design system's type scale are all the Renderer's. So the Host asks, in
7//! the middle of its own work, and the Renderer answers on the same call stack.
8//!
9//! One call carries many questions. A sidebar lays out a couple of hundred labels, and a
10//! flexbox asks each of them for its narrowest width, its widest width and its height at a
11//! given width, so one call per question would pay the crossing six hundred times.
12//!
13//! The questions travel the way a batch does: fixed-length records first, then the strings
14//! and run lists they point at. The answers come back as fixed-length records in an array
15//! the Host owns. Nothing is serialised and nothing is copied on the way across.
16//!
17//! Application code does not call the boundary. A layout engine asks [`measurer`] for a
18//! [`Measurer`], which it gets only while the Host is inside one of its own calls, which is
19//! the only time the Renderer is standing still on the other end of the same thread.
20
21use crate::font_features::FontFeature;
22use crate::fonts::{FONT_REF_LEN, FONT_REF_SYSTEM, FontRefs};
23use crate::protocol::ProtocolError;
24use crate::schema::{OverflowWrap, TypeRole, WordBreak};
25use crate::spans::{SPAN_FONT_ENTRY_LEN, SPAN_FONT_OFFSET_AT, SPAN_LEN, TextSpans};
26use std::marker::PhantomData;
27
28/// Bytes of one request record, whichever kind it is.
29pub const MEASURE_RECORD_LEN: usize = 88;
30/// Bytes of one result record.
31pub const MEASURE_RESULT_LEN: usize = 32;
32
33/// A run of text, its style and a width constraint.
34pub const MEASURE_TEXT: u16 = 1;
35/// A node the Renderer has already applied, and size constraints.
36pub const MEASURE_NODE: u16 = 2;
37
38// Where each field of a request record starts. Both kinds start with the kind.
39pub const MEASURE_KIND_AT: usize = 0;
40
41pub const TEXT_TYPE_ROLE_AT: usize = 2;
42pub const TEXT_TEXT_OFFSET_AT: usize = 4;
43pub const TEXT_TEXT_LENGTH_AT: usize = 8;
44pub const TEXT_SPANS_OFFSET_AT: usize = 12;
45pub const TEXT_SPANS_COUNT_AT: usize = 16;
46pub const TEXT_SPAN_FONTS_OFFSET_AT: usize = 20;
47pub const TEXT_SPAN_FONTS_COUNT_AT: usize = 24;
48pub const TEXT_FONT_OFFSET_AT: usize = 28;
49pub const TEXT_FONT_COUNT_AT: usize = 32;
50pub const TEXT_FONT_SIZE_AT: usize = 36;
51pub const TEXT_FONT_WEIGHT_AT: usize = 40;
52pub const TEXT_ITALIC_AT: usize = 42;
53pub const TEXT_WRAP_AT: usize = 43;
54pub const TEXT_LETTER_SPACING_AT: usize = 44;
55pub const TEXT_LINE_HEIGHT_AT: usize = 48;
56pub const TEXT_MAX_LINES_AT: usize = 52;
57pub const TEXT_TAB_SIZE_AT: usize = 56;
58pub const TEXT_WORD_BREAK_AT: usize = 57;
59pub const TEXT_OVERFLOW_WRAP_AT: usize = 58;
60pub const TEXT_ABSOLUTE_SIZE_AT: usize = 59;
61pub const TEXT_CONSTRAINT_AT: usize = 60;
62pub const TEXT_WIDTH_AT: usize = 64;
63pub const TEXT_ZOOM_AT: usize = 68;
64pub const TEXT_FONT_FEATURES_OFFSET_AT: usize = 72;
65pub const TEXT_FONT_FEATURES_COUNT_AT: usize = 76;
66/// Where the runs' own font feature table starts: the `SpanFontFeatures` blob as it is,
67/// its entry count first and every offset inside it counted from its own start.
68pub const TEXT_SPAN_FEATURES_OFFSET_AT: usize = 80;
69/// How many bytes that table takes. Zero where no run names a feature.
70pub const TEXT_SPAN_FEATURES_LENGTH_AT: usize = 84;
71
72pub const NODE_ID_AT: usize = 4;
73pub const NODE_MIN_WIDTH_AT: usize = 8;
74pub const NODE_MAX_WIDTH_AT: usize = 12;
75pub const NODE_MIN_HEIGHT_AT: usize = 16;
76pub const NODE_MAX_HEIGHT_AT: usize = 20;
77pub const NODE_ZOOM_AT: usize = 24;
78
79/// The narrowest the text can be: its longest piece that cannot be broken.
80pub const CONSTRAINT_MIN_CONTENT: u32 = 1;
81/// The text with no line broken except where it says so.
82pub const CONSTRAINT_MAX_CONTENT: u32 = 2;
83/// The text broken into lines no wider than the given width.
84pub const CONSTRAINT_AT_MOST: u32 = 3;
85
86// Where each field of a result record starts.
87pub const RESULT_WIDTH_AT: usize = 0;
88pub const RESULT_HEIGHT_AT: usize = 4;
89pub const RESULT_FIRST_BASELINE_AT: usize = 8;
90pub const RESULT_LAST_BASELINE_AT: usize = 12;
91pub const RESULT_LAST_LINE_WIDTH_AT: usize = 16;
92pub const RESULT_LINE_COUNT_AT: usize = 20;
93pub const RESULT_FLAGS_AT: usize = 24;
94pub const RESULT_STATUS_AT: usize = 28;
95
96/// The text had more lines than `max_lines` allowed, and some were not shown.
97pub const FLAG_TRUNCATED: u32 = 1;
98
99pub const RESULT_OK: u32 = 0;
100/// The node is not in the Renderer's table: never sent, removed, or sent in the batch the
101/// Host is computing right now, which the Renderer applies only once the call returns.
102pub const RESULT_UNKNOWN_NODE: u32 = 1;
103/// The record points outside the buffer, or is a kind or value the Renderer does not know.
104pub const RESULT_MALFORMED: u32 = 2;
105
106/// The request buffer as a whole cannot be read: shorter than its records, or null.
107pub const MEASURE_UNREADABLE: i32 = -1;
108/// The call came from a thread other than the Renderer's UI thread, and nothing was
109/// measured. The same number `run` gives for the same mistake.
110pub const MEASURE_OFF_UI_THREAD: i32 = -4;
111/// There is nothing to measure with yet: the Renderer has not composed its first frame,
112/// so it has no density, no fonts and no design system. Also what a build with no
113/// renderer answers.
114pub const MEASURE_UNAVAILABLE: i32 = -5;
115
116/// Hash input for the record layouts above, so a Renderer generated from another layout
117/// is refused at the handshake rather than reading the wrong bytes.
118pub(crate) const SCHEMA_DESCRIPTOR: &str = concat!(
119    "measure=v1;record=88;result=32;",
120    "text=kind@0,type_role@2,text@4,spans@12,span_fonts@20,font@28,font_size@36,",
121    "font_weight@40,italic@42,wrap@43,letter_spacing@44,line_height@48,max_lines@52,",
122    "tab_size@56,word_break@57,overflow_wrap@58,absolute_size@59,constraint@60,width@64,",
123    "zoom@68,font_features@72,span_features@80;",
124    "node=kind@0,node@4,min_width@8,max_width@12,min_height@16,max_height@20,zoom@24;",
125    "result=width@0,height@4,first_baseline@8,last_baseline@12,last_line_width@16,",
126    "line_count@20,flags@24,status@28;",
127    "fontref=12,kind@0,value@4,length@8;spanfont=12,span@0,offset@4,count@8;",
128);
129
130/// The Renderer's answer to one request, in dp.
131#[repr(C)]
132#[derive(Clone, Copy, Debug, Default, PartialEq)]
133pub struct MeasureResult {
134    pub width: f32,
135    pub height: f32,
136    /// NaN where there is no baseline.
137    pub first_baseline: f32,
138    pub last_baseline: f32,
139    /// How wide the last line is, which is where inline content after the text starts.
140    /// NaN for a node.
141    pub last_line_width: f32,
142    /// Zero for a node.
143    pub line_count: u32,
144    pub flags: u32,
145    pub status: u32,
146}
147
148const _: () = assert!(std::mem::size_of::<MeasureResult>() == MEASURE_RESULT_LEN);
149
150impl MeasureResult {
151    /// What a refused call leaves in every slot: no size, and a status that says it was
152    /// not measured.
153    pub const REFUSED: Self = Self {
154        width: 0.0,
155        height: 0.0,
156        first_baseline: f32::NAN,
157        last_baseline: f32::NAN,
158        last_line_width: f32::NAN,
159        line_count: 0,
160        flags: 0,
161        status: RESULT_MALFORMED,
162    };
163
164    pub fn status(&self) -> MeasureStatus {
165        match self.status {
166            RESULT_OK => MeasureStatus::Ok,
167            RESULT_UNKNOWN_NODE => MeasureStatus::UnknownNode,
168            RESULT_MALFORMED => MeasureStatus::Malformed,
169            other => MeasureStatus::Other(other),
170        }
171    }
172
173    /// Whether `max_lines` cut the text short.
174    pub fn truncated(&self) -> bool {
175        self.flags & FLAG_TRUNCATED != 0
176    }
177}
178
179/// How one request went.
180#[derive(Clone, Copy, Debug, Eq, PartialEq)]
181pub enum MeasureStatus {
182    Ok,
183    UnknownNode,
184    Malformed,
185    /// A status this build does not know, from a Renderer newer than it.
186    Other(u32),
187}
188
189/// How wide the text may be.
190#[derive(Clone, Copy, Debug, PartialEq)]
191pub enum TextConstraint {
192    /// The narrowest it can be: CSS `min-content`.
193    MinContent,
194    /// As wide as it is with no line broken except where it says so: CSS `max-content`.
195    MaxContent,
196    /// Lines broken to fit this many dp.
197    AtMost(f32),
198}
199
200/// How a run of text is set, as the Renderer reads it.
201///
202/// The same fields a `Text` carries, meaning the same things: the Renderer resolves both
203/// with one function, so text measured with a style is the size the same text drawn with
204/// the same properties turns out to be.
205#[derive(Clone, Debug, PartialEq)]
206pub struct TextStyle {
207    pub type_role: TypeRole,
208    /// The fonts to try, for text with no role. Ignored where there is a role.
209    pub font: FontRefs,
210    /// OpenType font features, such as tabular numbers.
211    pub font_features: Vec<FontFeature>,
212    /// `None` takes the role's size, or 14 for text with no role.
213    pub font_size: Option<f32>,
214    /// `None` takes the role's weight, or 400 for text with no role.
215    pub font_weight: Option<u16>,
216    pub italic: bool,
217    /// `None` takes the role's spacing, or none for text with no role.
218    pub letter_spacing: Option<f32>,
219    /// `None` is the font's own line height.
220    pub line_height: Option<f32>,
221    /// `None` is no limit.
222    pub max_lines: Option<u32>,
223    /// Whether lines break at the width given. `false` is CSS `nowrap` and `pre`.
224    pub wrap: bool,
225    /// How many spaces' width apart the tab stops are.
226    pub tab_size: u8,
227    pub word_break: Option<WordBreak>,
228    pub overflow_wrap: Option<OverflowWrap>,
229    /// Sizes are CSS pixels: the system's font scale does not enlarge them.
230    pub absolute_size: bool,
231}
232
233impl Default for TextStyle {
234    fn default() -> Self {
235        Self {
236            type_role: TypeRole::Body,
237            font: FontRefs::default(),
238            font_features: Vec::new(),
239            font_size: None,
240            font_weight: None,
241            italic: false,
242            letter_spacing: None,
243            line_height: None,
244            max_lines: None,
245            wrap: true,
246            tab_size: 8,
247            word_break: None,
248            overflow_wrap: None,
249            absolute_size: false,
250        }
251    }
252}
253
254impl TextStyle {
255    /// Text set by the design system's rung `role`.
256    pub fn role(role: TypeRole) -> Self {
257        Self {
258            type_role: role,
259            ..Self::default()
260        }
261    }
262}
263
264/// The size a node may take, in dp. `f32::INFINITY` is no limit.
265#[derive(Clone, Copy, Debug, PartialEq)]
266pub struct NodeConstraints {
267    pub min_width: f32,
268    pub max_width: f32,
269    pub min_height: f32,
270    pub max_height: f32,
271}
272
273impl NodeConstraints {
274    /// Any size at all.
275    pub const UNBOUNDED: Self = Self {
276        min_width: 0.0,
277        max_width: f32::INFINITY,
278        min_height: 0.0,
279        max_height: f32::INFINITY,
280    };
281
282    /// Exactly this width, any height.
283    pub const fn width(width: f32) -> Self {
284        Self {
285            min_width: width,
286            max_width: width,
287            min_height: 0.0,
288            max_height: f32::INFINITY,
289        }
290    }
291}
292
293/// The fields of one record, kept until the buffer is laid out.
294#[derive(Clone, Copy, Debug)]
295struct PendingRecord {
296    bytes: [u8; MEASURE_RECORD_LEN],
297}
298
299/// Where an entry of a side table keeps the list it points at.
300#[derive(Clone, Copy)]
301struct SideTable {
302    entry_len: usize,
303    list_offset_at: usize,
304    list_count_at: usize,
305}
306
307/// A set of questions for one call, built up and then asked at once.
308///
309/// Reused across frames: clearing keeps every buffer's capacity, so once warm, asking the
310/// same number of questions allocates nothing.
311#[derive(Debug, Default)]
312pub struct MeasureRequests {
313    records: Vec<PendingRecord>,
314    /// The strings and lists the records point at, counted from the start of this area
315    /// until the buffer is laid out.
316    payload: Vec<u8>,
317    /// Payload positions holding an offset that is counted from the start of the payload
318    /// and has to be counted from the start of the buffer instead.
319    payload_patches: Vec<u32>,
320    /// The laid out buffer.
321    buffer: Vec<u8>,
322    /// The zoom the requests asked from here on are measured at, where it was set.
323    zoom: Option<f32>,
324}
325
326impl MeasureRequests {
327    pub fn new() -> Self {
328        Self::default()
329    }
330
331    /// Measures the requests asked from here on at zoom `zoom`: the zoom of the page
332    /// region they belong to, which is the operating system's text size times the
333    /// application's own zoom. The Renderer measures them at its density times `zoom`,
334    /// with no font scale of its own, and answers in the region's CSS pixels.
335    ///
336    /// A Host can hold several regions at different zooms, which is why this travels with
337    /// every request rather than being the Renderer's state. Never set, it is one.
338    pub fn set_zoom(&mut self, zoom: f32) {
339        self.zoom = Some(zoom);
340    }
341
342    /// Forgets every question, keeping the room they took.
343    pub fn clear(&mut self) {
344        self.records.clear();
345        self.payload.clear();
346        self.payload_patches.clear();
347        self.buffer.clear();
348    }
349
350    /// How many questions there are.
351    pub fn len(&self) -> usize {
352        self.records.len()
353    }
354
355    pub fn is_empty(&self) -> bool {
356        self.records.is_empty()
357    }
358
359    /// Asks how big `text`, with `spans` laid over it and set in `style`, is under
360    /// `constraint`. Returns the index its answer will have.
361    pub fn text(
362        &mut self,
363        text: &str,
364        spans: &TextSpans,
365        style: &TextStyle,
366        constraint: TextConstraint,
367    ) -> usize {
368        let mut record = [0u8; MEASURE_RECORD_LEN];
369        put_u16(&mut record, MEASURE_KIND_AT, MEASURE_TEXT);
370        put_u16(&mut record, TEXT_TYPE_ROLE_AT, style.type_role as u16);
371
372        let text_at = self.payload.len() as u32;
373        self.payload.extend_from_slice(text.as_bytes());
374        put_u32(&mut record, TEXT_TEXT_OFFSET_AT, text_at);
375        put_u32(&mut record, TEXT_TEXT_LENGTH_AT, text.len() as u32);
376
377        let runs = spans.as_bytes();
378        let spans_at = self.payload.len() as u32;
379        self.payload.extend_from_slice(runs);
380        put_u32(&mut record, TEXT_SPANS_OFFSET_AT, spans_at);
381        put_u32(
382            &mut record,
383            TEXT_SPANS_COUNT_AT,
384            (runs.len() / SPAN_LEN) as u32,
385        );
386
387        // Both font tables are copied as they are, records and names together, and only the
388        // offsets inside them are moved: a request costs no allocation once warm.
389        let (entries_at, entries) = self.copy_span_font_table(spans.font_table());
390        put_u32(&mut record, TEXT_SPAN_FONTS_OFFSET_AT, entries_at);
391        put_u32(&mut record, TEXT_SPAN_FONTS_COUNT_AT, entries);
392        let (font_at, fonts) = self.copy_font_list(style.font.as_bytes());
393        put_u32(&mut record, TEXT_FONT_OFFSET_AT, font_at);
394        put_u32(&mut record, TEXT_FONT_COUNT_AT, fonts);
395
396        put_f32(
397            &mut record,
398            TEXT_FONT_SIZE_AT,
399            style.font_size.unwrap_or(0.0),
400        );
401        put_u16(
402            &mut record,
403            TEXT_FONT_WEIGHT_AT,
404            style.font_weight.unwrap_or(0),
405        );
406        record[TEXT_ITALIC_AT] = u8::from(style.italic);
407        record[TEXT_WRAP_AT] = u8::from(style.wrap);
408        put_f32(
409            &mut record,
410            TEXT_LETTER_SPACING_AT,
411            style.letter_spacing.unwrap_or(f32::NAN),
412        );
413        put_f32(
414            &mut record,
415            TEXT_LINE_HEIGHT_AT,
416            style.line_height.unwrap_or(f32::NAN),
417        );
418        put_u32(&mut record, TEXT_MAX_LINES_AT, style.max_lines.unwrap_or(0));
419        record[TEXT_TAB_SIZE_AT] = style.tab_size;
420        record[TEXT_WORD_BREAK_AT] = style.word_break.map_or(0, |value| value as u8);
421        record[TEXT_OVERFLOW_WRAP_AT] = style.overflow_wrap.map_or(0, |value| value as u8);
422        record[TEXT_ABSOLUTE_SIZE_AT] = u8::from(style.absolute_size);
423        let (constraint, width) = match constraint {
424            TextConstraint::MinContent => (CONSTRAINT_MIN_CONTENT, 0.0),
425            TextConstraint::MaxContent => (CONSTRAINT_MAX_CONTENT, 0.0),
426            TextConstraint::AtMost(width) => (CONSTRAINT_AT_MOST, width),
427        };
428        put_u32(&mut record, TEXT_CONSTRAINT_AT, constraint);
429        put_f32(&mut record, TEXT_WIDTH_AT, width);
430        put_f32(&mut record, TEXT_ZOOM_AT, self.zoom.unwrap_or(0.0));
431        let features_at = self.payload.len() as u32;
432        for feature in &style.font_features {
433            self.payload.extend_from_slice(&feature.to_bytes());
434        }
435        put_u32(&mut record, TEXT_FONT_FEATURES_OFFSET_AT, features_at);
436        put_u32(
437            &mut record,
438            TEXT_FONT_FEATURES_COUNT_AT,
439            style.font_features.len() as u32,
440        );
441        // The run feature table travels whole: its offsets count from its own start, so
442        // it is copied as it is and the Renderer reads it with the same function it reads
443        // the `SpanFontFeatures` property with.
444        let table = spans.feature_table();
445        let span_features_at = self.payload.len() as u32;
446        self.payload.extend_from_slice(table);
447        put_u32(&mut record, TEXT_SPAN_FEATURES_OFFSET_AT, span_features_at);
448        put_u32(
449            &mut record,
450            TEXT_SPAN_FEATURES_LENGTH_AT,
451            table.len() as u32,
452        );
453        self.records.push(PendingRecord { bytes: record });
454        self.records.len() - 1
455    }
456
457    /// Asks how big the node `node_id`, which the Renderer has already applied, is under
458    /// `constraints`. Returns the index its answer will have.
459    pub fn node(&mut self, node_id: u32, constraints: NodeConstraints) -> usize {
460        let mut record = [0u8; MEASURE_RECORD_LEN];
461        put_u16(&mut record, MEASURE_KIND_AT, MEASURE_NODE);
462        put_u32(&mut record, NODE_ID_AT, node_id);
463        put_f32(&mut record, NODE_MIN_WIDTH_AT, constraints.min_width);
464        put_f32(&mut record, NODE_MAX_WIDTH_AT, constraints.max_width);
465        put_f32(&mut record, NODE_MIN_HEIGHT_AT, constraints.min_height);
466        put_f32(&mut record, NODE_MAX_HEIGHT_AT, constraints.max_height);
467        put_f32(&mut record, NODE_ZOOM_AT, self.zoom.unwrap_or(0.0));
468        self.records.push(PendingRecord { bytes: record });
469        self.records.len() - 1
470    }
471
472    /// Copies a `Font` property blob into the payload without its count, moving every
473    /// name it points at to where it now sits, and answers where the records start and how
474    /// many there are.
475    fn copy_font_list(&mut self, blob: &[u8]) -> (u32, u32) {
476        let at = self.payload.len();
477        if blob.len() < 4 {
478            return (at as u32, 0);
479        }
480        let count = read_u32(blob, 0);
481        self.payload.extend_from_slice(&blob[4..]);
482        // Everything in the blob moved from `offset` to `at - 4 + offset`.
483        let moved = (at as u32).wrapping_sub(4);
484        self.move_font_records(at, count, moved);
485        (at as u32, count)
486    }
487
488    /// Copies a `SpanFonts` table without its count, moving every offset inside it, and
489    /// answers where the entries start and how many there are.
490    fn copy_span_font_table(&mut self, table: &[u8]) -> (u32, u32) {
491        self.copy_side_table(
492            table,
493            SideTable {
494                entry_len: SPAN_FONT_ENTRY_LEN,
495                list_offset_at: SPAN_FONT_OFFSET_AT,
496                list_count_at: 8,
497            },
498        )
499    }
500
501    /// Copies a side table of fixed-size entries without its count. Each entry points at a
502    /// list of font records elsewhere in the table: the entry's list offset is moved to
503    /// where the list now sits, the names the list points at move with it, and every moved
504    /// field is marked to be counted from the start of the buffer. Answers where the
505    /// entries start and how many there are.
506    fn copy_side_table(&mut self, table: &[u8], layout: SideTable) -> (u32, u32) {
507        let at = self.payload.len();
508        if table.len() < 4 {
509            return (at as u32, 0);
510        }
511        let entries = read_u32(table, 0);
512        self.payload.extend_from_slice(&table[4..]);
513        let moved = (at as u32).wrapping_sub(4);
514        for entry in 0..entries as usize {
515            let start = at + entry * layout.entry_len;
516            let field = start + layout.list_offset_at;
517            if field + 4 > self.payload.len() {
518                break;
519            }
520            let list = read_u32(&self.payload, field).wrapping_add(moved);
521            self.payload[field..field + 4].copy_from_slice(&list.to_le_bytes());
522            self.payload_patches.push(field as u32);
523            let count = read_u32(&self.payload, start + layout.list_count_at);
524            self.move_font_records(list as usize, count, moved);
525        }
526        (at as u32, entries)
527    }
528
529    /// Moves the name offset of every family named by name among the `count` records at
530    /// `at`, and marks it to be counted from the start of the buffer.
531    fn move_font_records(&mut self, at: usize, count: u32, moved: u32) {
532        for index in 0..count as usize {
533            let record = at + index * FONT_REF_LEN;
534            if record + FONT_REF_LEN > self.payload.len() {
535                break;
536            }
537            if read_u32(&self.payload, record) != FONT_REF_SYSTEM {
538                continue;
539            }
540            let field = record + 4;
541            let name = read_u32(&self.payload, field).wrapping_add(moved);
542            self.payload[field..field + 4].copy_from_slice(&name.to_le_bytes());
543            self.payload_patches.push(field as u32);
544        }
545    }
546
547    /// The buffer these requests are sent as: the records, then the payload, every offset
548    /// counted from its start.
549    pub fn encoded(&mut self) -> &[u8] {
550        self.finish().0
551    }
552
553    /// Lays the records and the payload out as one buffer, every offset counted from its
554    /// start, and answers with it and the number of records.
555    fn finish(&mut self) -> (&[u8], u32) {
556        let base = (self.records.len() * MEASURE_RECORD_LEN) as u32;
557        self.buffer.clear();
558        self.buffer.reserve(base as usize + self.payload.len());
559        for record in &self.records {
560            let mut bytes = record.bytes;
561            if u16::from_le_bytes([bytes[0], bytes[1]]) == MEASURE_TEXT {
562                for field in [
563                    TEXT_TEXT_OFFSET_AT,
564                    TEXT_SPANS_OFFSET_AT,
565                    TEXT_SPAN_FONTS_OFFSET_AT,
566                    TEXT_FONT_OFFSET_AT,
567                    TEXT_FONT_FEATURES_OFFSET_AT,
568                    TEXT_SPAN_FEATURES_OFFSET_AT,
569                ] {
570                    let value = read_u32(&bytes, field) + base;
571                    put_u32(&mut bytes, field, value);
572                }
573            }
574            self.buffer.extend_from_slice(&bytes);
575        }
576        let payload_at = self.buffer.len();
577        self.buffer.extend_from_slice(&self.payload);
578        for &patch in &self.payload_patches {
579            let at = payload_at + patch as usize;
580            let value = read_u32(&self.buffer, at) + base;
581            self.buffer[at..at + 4].copy_from_slice(&value.to_le_bytes());
582        }
583        (&self.buffer, self.records.len() as u32)
584    }
585}
586
587/// The right to ask, for the length of one Host call.
588///
589/// Not `Send`: the Renderer answers on its UI thread only, and the Host call this was
590/// handed out in is on that thread.
591pub struct Measurer {
592    _on_this_thread: PhantomData<*const ()>,
593}
594
595/// Why nothing was measured.
596#[derive(Clone, Debug, Eq, PartialEq)]
597pub enum MeasureError {
598    /// Not inside a Host call, so the Renderer is not waiting on this thread to answer.
599    OutsideHostCall,
600    /// The Renderer refused the whole call. The answers were left at zero size, and the
601    /// layout carries on with them.
602    Refused(ProtocolError),
603}
604
605/// A measurer, if the Host is inside one of its own calls on this thread, which is the
606/// only time there is a Renderer standing still to answer.
607pub fn measurer() -> Result<Measurer, MeasureError> {
608    if crate::boundary::in_host_call() {
609        Ok(Measurer {
610            _on_this_thread: PhantomData,
611        })
612    } else {
613        Err(MeasureError::OutsideHostCall)
614    }
615}
616
617impl Measurer {
618    /// Asks every question in `requests` in one call and puts the answers in `results`, in
619    /// the order they were asked.
620    ///
621    /// A request the Renderer could not answer says so in its own status, and the rest are
622    /// answered. A call the Renderer refused as a whole leaves every answer at zero size
623    /// and comes back as an error, which the layout is free to carry on past: nothing
624    /// stops, and the next frame asks again.
625    pub fn measure(
626        &mut self,
627        requests: &mut MeasureRequests,
628        results: &mut Vec<MeasureResult>,
629    ) -> Result<(), MeasureError> {
630        let (buffer, count) = requests.finish();
631        results.clear();
632        results.resize(count as usize, MeasureResult::default());
633        self.measure_encoded(buffer, count, results)
634    }
635
636    /// The same, for a request buffer encoded by hand. `results` must have one slot per
637    /// record.
638    pub fn measure_encoded(
639        &mut self,
640        buffer: &[u8],
641        count: u32,
642        results: &mut [MeasureResult],
643    ) -> Result<(), MeasureError> {
644        if results.len() < count as usize {
645            return Err(MeasureError::Refused(ProtocolError::LengthOverflow));
646        }
647        if count == 0 {
648            return Ok(());
649        }
650        let length = u32::try_from(buffer.len())
651            .map_err(|_| MeasureError::Refused(ProtocolError::LengthOverflow))?;
652        let status =
653            crate::boundary::renderer_measure(buffer.as_ptr(), length, count, results.as_mut_ptr());
654        if status < 0 {
655            for result in results.iter_mut().take(count as usize) {
656                *result = MeasureResult::REFUSED;
657            }
658            report_refusal(status);
659            return Err(MeasureError::Refused(ProtocolError::MeasureRefused(status)));
660        }
661        Ok(())
662    }
663}
664
665/// Says once per kind of refusal what went wrong, on standard error. A refusal is the
666/// Renderer's or the Host's bug rather than the application's, and a layout that silently
667/// had every size at zero is the hardest kind of wrong to find.
668fn report_refusal(status: i32) {
669    use std::sync::atomic::{AtomicU32, Ordering};
670    static SAID: AtomicU32 = AtomicU32::new(0);
671    let bit = 1u32 << (status.unsigned_abs().min(31));
672    if SAID.fetch_or(bit, Ordering::Relaxed) & bit != 0 {
673        return;
674    }
675    let reason = match status {
676        MEASURE_UNREADABLE => "the request buffer could not be read",
677        MEASURE_OFF_UI_THREAD => "the call was made off the Renderer's UI thread",
678        MEASURE_UNAVAILABLE => {
679            "the Renderer has nothing to measure with yet (no first frame, or no renderer)"
680        }
681        _ => "the Renderer gave no reason",
682    };
683    eprintln!(
684        "compose-rust: a measure call was refused with status {status}: {reason}. Every \
685         size in it is zero and the layout carried on."
686    );
687}
688
689fn put_u16(bytes: &mut [u8], at: usize, value: u16) {
690    bytes[at..at + 2].copy_from_slice(&value.to_le_bytes());
691}
692
693fn put_u32(bytes: &mut [u8], at: usize, value: u32) {
694    bytes[at..at + 4].copy_from_slice(&value.to_le_bytes());
695}
696
697fn put_f32(bytes: &mut [u8], at: usize, value: f32) {
698    bytes[at..at + 4].copy_from_slice(&value.to_bits().to_le_bytes());
699}
700
701fn read_u32(bytes: &[u8], at: usize) -> u32 {
702    u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]])
703}
704
705// ---------------------------------------------------------------------------------------
706// The mock renderer's answers.
707//
708// A test of the Host has no Renderer to ask, and wants answers it can predict. These are
709// the same rules the stand-in renderer's C answers by: every character is half the font
710// size wide, a line is one and a quarter font sizes tall, the first baseline sits one font
711// size down, and lines break at spaces. No node is known, because nothing applies a tree.
712// ---------------------------------------------------------------------------------------
713
714/// The font size the mock takes for text that does not give one.
715pub const FAKE_FONT_SIZE: f32 = 14.0;
716
717/// Answers a measure call the way the mock renderer does. Refuses a call from a thread
718/// that is not inside a Host call, which is what "off the UI thread" means to a Renderer
719/// that has no UI thread of its own.
720///
721/// # Safety
722/// `requests` must address `length` readable bytes, and `results` writable room for
723/// `count` results.
724#[doc(hidden)]
725pub unsafe extern "C" fn fake_measure(
726    requests: *const u8,
727    length: u32,
728    count: u32,
729    results: *mut MeasureResult,
730) -> i32 {
731    if !crate::boundary::in_host_call() {
732        return MEASURE_OFF_UI_THREAD;
733    }
734    if requests.is_null() || results.is_null() {
735        return MEASURE_UNREADABLE;
736    }
737    // SAFETY: the caller promises `length` readable bytes.
738    let buffer = unsafe { std::slice::from_raw_parts(requests, length as usize) };
739    // SAFETY: the caller promises room for `count` results.
740    let results = unsafe { std::slice::from_raw_parts_mut(results, count as usize) };
741    fake_measure_slices(buffer, results)
742}
743
744/// The mock's rules over slices, for whoever already has them.
745#[doc(hidden)]
746pub fn fake_measure_slices(buffer: &[u8], results: &mut [MeasureResult]) -> i32 {
747    let count = results.len();
748    if buffer.len() < count * MEASURE_RECORD_LEN {
749        return MEASURE_UNREADABLE;
750    }
751    for (index, result) in results.iter_mut().enumerate() {
752        let record = &buffer[index * MEASURE_RECORD_LEN..(index + 1) * MEASURE_RECORD_LEN];
753        *result = fake_one(buffer, record);
754    }
755    0
756}
757
758fn fake_one(buffer: &[u8], record: &[u8]) -> MeasureResult {
759    let malformed = MeasureResult {
760        status: RESULT_MALFORMED,
761        ..MeasureResult::REFUSED
762    };
763    match u16::from_le_bytes([record[0], record[1]]) {
764        MEASURE_NODE => MeasureResult {
765            status: RESULT_UNKNOWN_NODE,
766            ..MeasureResult::REFUSED
767        },
768        MEASURE_TEXT => {
769            let at = read_u32(record, TEXT_TEXT_OFFSET_AT) as usize;
770            let length = read_u32(record, TEXT_TEXT_LENGTH_AT) as usize;
771            let Some(text) = at
772                .checked_add(length)
773                .and_then(|end| buffer.get(at..end))
774                .and_then(|bytes| std::str::from_utf8(bytes).ok())
775            else {
776                return malformed;
777            };
778            let size = f32::from_bits(read_u32(record, TEXT_FONT_SIZE_AT));
779            let size = if size > 0.0 { size } else { FAKE_FONT_SIZE };
780            let line_height = f32::from_bits(read_u32(record, TEXT_LINE_HEIGHT_AT));
781            let line_height = if line_height.is_nan() || line_height <= 0.0 {
782                size * 1.25
783            } else {
784                line_height
785            };
786            let max_lines = read_u32(record, TEXT_MAX_LINES_AT);
787            let wrap = record[TEXT_WRAP_AT] != 0;
788            let advance = size * 0.5;
789            let width = f32::from_bits(read_u32(record, TEXT_WIDTH_AT));
790            let lines = match read_u32(record, TEXT_CONSTRAINT_AT) {
791                CONSTRAINT_MIN_CONTENT => {
792                    fake_lines(text, if wrap { 0.0 } else { f32::INFINITY }, advance)
793                }
794                CONSTRAINT_MAX_CONTENT => fake_lines(text, f32::INFINITY, advance),
795                CONSTRAINT_AT_MOST if width >= 0.0 => {
796                    fake_lines(text, if wrap { width } else { f32::INFINITY }, advance)
797                }
798                _ => return malformed,
799            };
800            let shown = if max_lines == 0 {
801                lines.len()
802            } else {
803                lines.len().min(max_lines as usize)
804            };
805            let widest = lines[..shown].iter().copied().fold(0.0f32, f32::max);
806            MeasureResult {
807                width: widest,
808                height: shown as f32 * line_height,
809                first_baseline: size,
810                last_baseline: (shown.max(1) - 1) as f32 * line_height + size,
811                last_line_width: lines[shown.max(1) - 1],
812                line_count: shown as u32,
813                flags: if shown < lines.len() {
814                    FLAG_TRUNCATED
815                } else {
816                    0
817                },
818                status: RESULT_OK,
819            }
820        }
821        _ => malformed,
822    }
823}
824
825/// The widths of the lines `text` breaks into at `width`, breaking at spaces and at
826/// newlines. A width of zero puts every word on its own line.
827fn fake_lines(text: &str, width: f32, advance: f32) -> Vec<f32> {
828    let mut lines = Vec::new();
829    for paragraph in text.split('\n') {
830        let mut line = 0usize;
831        for word in paragraph.split(' ') {
832            let word_length = word.chars().count();
833            let joined = if line == 0 {
834                word_length
835            } else {
836                line + 1 + word_length
837            };
838            if line != 0 && joined as f32 * advance > width {
839                lines.push(line as f32 * advance);
840                line = word_length;
841            } else {
842                line = joined;
843            }
844        }
845        lines.push(line as f32 * advance);
846    }
847    lines
848}
849
850#[cfg(test)]
851mod side_table_tests {
852    use super::*;
853
854    /// One entry (index, list offset, list count) followed by one system font record
855    /// and its name, laid out as the table is on the wire.
856    fn table() -> Vec<u8> {
857        let mut t = Vec::new();
858        t.extend_from_slice(&1u32.to_le_bytes());
859        t.extend_from_slice(&7u32.to_le_bytes());
860        t.extend_from_slice(&(4 + SPAN_FONT_ENTRY_LEN as u32).to_le_bytes());
861        t.extend_from_slice(&1u32.to_le_bytes());
862        let name_at = 4 + SPAN_FONT_ENTRY_LEN as u32 + FONT_REF_LEN as u32;
863        t.extend_from_slice(&FONT_REF_SYSTEM.to_le_bytes());
864        t.extend_from_slice(&name_at.to_le_bytes());
865        t.resize(4 + SPAN_FONT_ENTRY_LEN + FONT_REF_LEN, 0);
866        t.extend_from_slice(b"name");
867        t
868    }
869
870    #[test]
871    fn pr2_side_table_copy_moves_offsets_and_keeps_the_bytes() {
872        let mut requests = MeasureRequests::new();
873        requests.payload.extend_from_slice(&[0xAA; 10]);
874        let table = table();
875        let (at, entries) = requests.copy_span_font_table(&table);
876        assert_eq!((at, entries), (10, 1));
877        let moved = 10u32 - 4;
878        let copied = &requests.payload[10..];
879        assert_eq!(copied.len(), table.len() - 4);
880        assert_eq!(
881            read_u32(copied, 0),
882            7,
883            "fields that are not offsets are untouched"
884        );
885        assert_eq!(
886            read_u32(copied, SPAN_FONT_OFFSET_AT),
887            table_u32(&table, 4 + SPAN_FONT_OFFSET_AT) + moved
888        );
889        assert_eq!(read_u32(copied, 8), 1);
890        let record = SPAN_FONT_ENTRY_LEN;
891        assert_eq!(
892            read_u32(copied, record + 4),
893            table_u32(&table, 4 + record + 4) + moved
894        );
895        assert_eq!(&copied[copied.len() - 4..], b"name");
896        assert_eq!(requests.payload_patches.len(), 2);
897        assert_eq!(
898            requests.copy_span_font_table(&[]),
899            (requests.payload.len() as u32, 0)
900        );
901    }
902
903    fn table_u32(table: &[u8], at: usize) -> u32 {
904        read_u32(table, at)
905    }
906}