nadir_debug/metrics.rs
1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! How wide a text is, and where a caret goes in it.
16
17use std::cell::RefCell;
18
19use nadir_render::{Font, PlacedGlyph, TextLayout};
20
21/// The measures of the debug UI's font, in UI units (a UI unit is a pixel
22/// of the font).
23pub trait TextMetrics {
24 /// The height of a line.
25 fn line_height(&self) -> f32;
26
27 /// Where the pen is before the character at `byte` of the one-line
28 /// `text`, from the text's start: the kerning before that character
29 /// included, and spaces taking their room. At `text.len()`, it is the
30 /// pen after the last character, the text's width. `byte` is a
31 /// character boundary of `text`, or its length.
32 fn caret_x(&self, text: &str, byte: usize) -> f32;
33}
34
35/// Where the pen is before `byte`, from a text's glyphs in order: each its
36/// byte, the pen before it, and its advance.
37pub(crate) fn caret_in(glyphs: impl IntoIterator<Item = (usize, f32, f32)>, byte: usize) -> f32 {
38 let mut end = 0.0;
39 for (start, pen, advance) in glyphs {
40 if start >= byte {
41 return pen;
42 }
43 end = pen + advance;
44 }
45 end
46}
47
48/// A [`Font`]'s measures: the text laid out as `Font::layout` lays it out,
49/// with no markup, so that a caret is where the glyphs are drawn.
50#[derive(Debug)]
51pub struct FontMetrics {
52 font: Font,
53 /// The last text laid out, reused.
54 placed: RefCell<Vec<PlacedGlyph>>,
55}
56
57impl FontMetrics {
58 /// The measures of `font`, a copy of the font the debug UI draws with.
59 pub fn new(font: Font) -> Self {
60 Self {
61 font,
62 placed: RefCell::new(Vec::new()),
63 }
64 }
65
66 /// The font.
67 pub fn font(&self) -> &Font {
68 &self.font
69 }
70}
71
72impl TextMetrics for FontMetrics {
73 fn line_height(&self) -> f32 {
74 self.font.line_height() as f32
75 }
76
77 fn caret_x(&self, text: &str, byte: usize) -> f32 {
78 let mut layout = TextLayout::new();
79 layout.markup = false;
80 let mut placed = self.placed.borrow_mut();
81 placed.clear();
82 self.font.layout(text, &layout, &mut placed);
83 // A glyph's rectangle is at the pen plus its offset.
84 let glyphs = placed.iter().map(|placed| {
85 let pen = placed.position.x - placed.glyph.offset().x;
86 (placed.byte, pen as f32, placed.glyph.advance() as f32)
87 });
88 caret_in(glyphs, byte)
89 }
90}
91
92#[cfg(test)]
93pub(crate) mod tests {
94 use super::*;
95
96 /// A font for tests: 8 high; a space 3 wide and every other character
97 /// 6, `A` then `V` kerned by -1, and the control characters taking no
98 /// room, as `Font::layout` places them.
99 pub(crate) struct Fixed;
100
101 impl Fixed {
102 /// The glyphs of `text`: (byte, pen, advance).
103 fn glyphs(text: &str) -> impl Iterator<Item = (usize, f32, f32)> + '_ {
104 let mut pen = 0.0;
105 let mut previous = None;
106 text.char_indices()
107 .filter(|(_, c)| !c.is_control())
108 .map(move |(byte, c)| {
109 if (previous, c) == (Some('A'), 'V') {
110 pen -= 1.0;
111 }
112 previous = Some(c);
113 let advance = if c == ' ' { 3.0 } else { 6.0 };
114 let glyph = (byte, pen, advance);
115 pen += advance;
116 glyph
117 })
118 }
119 }
120
121 impl TextMetrics for Fixed {
122 fn line_height(&self) -> f32 {
123 8.0
124 }
125
126 fn caret_x(&self, text: &str, byte: usize) -> f32 {
127 caret_in(Self::glyphs(text), byte)
128 }
129 }
130
131 #[test]
132 fn a_caret_is_at_the_pen_kerning_included_and_spaces_take_room() {
133 let text = "AV b ";
134 let at = |byte| Fixed.caret_x(text, byte);
135 // A 6, kerned -1 before V, then V 6, a space 3, b 6, a space 3.
136 assert_eq!(
137 [at(0), at(1), at(2), at(3), at(4), at(5)],
138 [0.0, 5.0, 11.0, 14.0, 20.0, 23.0]
139 );
140 assert_eq!(Fixed.caret_x("", 0), 0.0);
141 // Past every glyph: the pen after the last.
142 assert_eq!(caret_in([(0, 0.0, 6.0), (2, 6.0, 6.0)], 1), 6.0);
143 assert_eq!(caret_in([(0, 0.0, 6.0), (2, 6.0, 6.0)], 9), 12.0);
144 // A multi-byte character: the caret after it is at its byte end.
145 assert_eq!(Fixed.caret_x("éa", 2), 6.0);
146 }
147}