1use std::hash::{Hash, Hasher};
8
9use cranpose_core::hash::default;
10
11#[derive(Debug, Clone)]
13pub struct LineLayout {
14 pub start_offset: usize,
16 pub end_offset: usize,
18 pub y: f32,
20 pub height: f32,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct GlyphLayout {
27 pub line_index: usize,
29 pub start_offset: usize,
31 pub end_offset: usize,
33 pub x: f32,
35 pub y: f32,
37 pub width: f32,
39 pub height: f32,
41}
42
43#[derive(Debug, Clone)]
50pub struct TextLayoutData {
51 pub width: f32,
53 pub height: f32,
55 pub line_height: f32,
57 pub glyph_x_positions: Vec<f32>,
59 pub char_to_byte: Vec<usize>,
61 pub lines: Vec<LineLayout>,
63 pub glyph_layouts: Vec<GlyphLayout>,
65}
66
67#[derive(Debug, Clone)]
68pub struct TextLayoutResult {
69 pub width: f32,
71 pub height: f32,
73 pub line_height: f32,
75 glyph_x_positions: Vec<f32>,
79 char_to_byte: Vec<usize>,
82 pub lines: Vec<LineLayout>,
84 glyph_layouts: Vec<GlyphLayout>,
86 text_hash: u64,
88}
89
90impl TextLayoutResult {
91 pub fn new(text: &str, data: TextLayoutData) -> Self {
93 Self {
94 width: data.width,
95 height: data.height,
96 line_height: data.line_height,
97 glyph_x_positions: data.glyph_x_positions,
98 char_to_byte: data.char_to_byte,
99 lines: data.lines,
100 glyph_layouts: data.glyph_layouts,
101 text_hash: Self::hash_text(text),
102 }
103 }
104
105 pub fn get_cursor_x(&self, byte_offset: usize) -> f32 {
108 let char_idx = self
110 .char_to_byte
111 .iter()
112 .position(|&b| b > byte_offset)
113 .map(|i| i.saturating_sub(1))
114 .unwrap_or(self.char_to_byte.len().saturating_sub(1));
115
116 self.glyph_x_positions
118 .get(char_idx)
119 .copied()
120 .unwrap_or(self.width)
121 }
122
123 pub fn get_offset_for_x(&self, x: f32) -> usize {
126 if self.glyph_x_positions.is_empty() {
127 return 0;
128 }
129
130 let char_idx = match self
132 .glyph_x_positions
133 .binary_search_by(|pos| pos.partial_cmp(&x).unwrap_or(std::cmp::Ordering::Equal))
134 {
135 Ok(i) => i,
136 Err(i) => {
137 if i == 0 {
139 0
140 } else if i >= self.glyph_x_positions.len() {
141 self.glyph_x_positions.len() - 1
142 } else {
143 let before = self.glyph_x_positions[i - 1];
144 let after = self.glyph_x_positions[i];
145 if (x - before) < (after - x) { i - 1 } else { i }
146 }
147 }
148 };
149
150 self.char_to_byte.get(char_idx).copied().unwrap_or(0)
152 }
153
154 pub fn is_valid_for(&self, text: &str) -> bool {
156 self.text_hash == Self::hash_text(text)
157 }
158
159 pub fn glyph_layouts(&self) -> &[GlyphLayout] {
161 &self.glyph_layouts
162 }
163
164 fn hash_text(text: &str) -> u64 {
165 let mut hasher = default::new();
166 text.hash(&mut hasher);
167 hasher.finish()
168 }
169
170 pub fn monospaced(text: &str, char_width: f32, line_height: f32) -> Self {
172 let mut glyph_x_positions = Vec::new();
173 let mut char_to_byte = Vec::new();
174 let mut glyph_layouts = Vec::new();
175 let mut cursor_x = 0.0;
176
177 for (byte_offset, _c) in text.char_indices() {
178 glyph_x_positions.push(cursor_x);
179 char_to_byte.push(byte_offset);
180 cursor_x += char_width;
181 }
182 glyph_x_positions.push(cursor_x);
184 char_to_byte.push(text.len());
185
186 let mut line_x = 0.0;
187 let mut line_y = 0.0;
188 let mut line_index = 0usize;
189 for (byte_offset, c) in text.char_indices() {
190 if c == '\n' {
191 line_index = line_index.saturating_add(1);
192 line_y += line_height;
193 line_x = 0.0;
194 continue;
195 }
196 let glyph_start = byte_offset;
197 let glyph_end = glyph_start + c.len_utf8();
198 glyph_layouts.push(GlyphLayout {
199 line_index,
200 start_offset: glyph_start,
201 end_offset: glyph_end,
202 x: line_x,
203 y: line_y,
204 width: char_width,
205 height: line_height,
206 });
207 line_x += char_width;
208 }
209
210 let line_texts: Vec<&str> = text.split('\n').collect();
212 let line_count = line_texts.len();
213 let mut lines = Vec::with_capacity(line_count);
214 let mut line_start = 0;
215 let mut y = 0.0;
216 let mut max_width: f32 = 0.0;
217
218 for (i, line_text) in line_texts.iter().enumerate() {
219 let line_end = if i == line_count - 1 {
220 text.len()
221 } else {
222 line_start + line_text.len()
223 };
224
225 let line_width = line_text.chars().count() as f32 * char_width;
227 max_width = max_width.max(line_width);
228
229 lines.push(LineLayout {
230 start_offset: line_start,
231 end_offset: line_end,
232 y,
233 height: line_height,
234 });
235
236 line_start = line_end + 1; y += line_height;
238 }
239
240 if lines.is_empty() {
242 lines.push(LineLayout {
243 start_offset: 0,
244 end_offset: 0,
245 y: 0.0,
246 height: line_height,
247 });
248 }
249
250 Self::new(
251 text,
252 TextLayoutData {
253 width: max_width,
254 height: lines.len() as f32 * line_height,
255 line_height,
256 glyph_x_positions,
257 char_to_byte,
258 lines,
259 glyph_layouts,
260 },
261 )
262 }
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 #[test]
270 fn test_monospaced_layout() {
271 let layout = TextLayoutResult::monospaced("Hello", 10.0, 20.0);
272
273 assert_eq!(layout.get_cursor_x(0), 0.0); assert_eq!(layout.get_cursor_x(5), 50.0); }
277
278 #[test]
279 fn test_get_offset_for_x() {
280 let layout = TextLayoutResult::monospaced("Hello", 10.0, 20.0);
281
282 let offset = layout.get_offset_for_x(25.0);
284 assert!(offset == 2 || offset == 3);
285 }
286
287 #[test]
288 fn test_multiline() {
289 let layout = TextLayoutResult::monospaced("Hi\nWorld", 10.0, 20.0);
290
291 assert_eq!(layout.lines.len(), 2);
292 assert_eq!(layout.lines[0].start_offset, 0);
293 assert_eq!(layout.lines[1].start_offset, 3); }
295
296 #[test]
297 fn test_validity() {
298 let layout = TextLayoutResult::monospaced("Hello", 10.0, 20.0);
299
300 assert!(layout.is_valid_for("Hello"));
301 assert!(!layout.is_valid_for("World"));
302 }
303}