1use sui_core::{Color, Point, Rect, Size};
2use sui_runtime::{PaintCtx, window_render_options};
3use sui_text::{
4 TextAlign, TextDocument, TextLayout, TextLayoutRequest, TextMeasurement, TextStyle, TextWrap,
5};
6
7pub(crate) struct AlignedTextLayout {
8 pub(crate) rect: Rect,
9 origin: Point,
10 layout: TextLayout,
11 color: Color,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub(crate) enum HorizontalTextAlignmentMode {
16 Advance,
17 Optical,
18}
19
20#[derive(Debug, Clone, Copy)]
21struct HorizontalPlacement {
22 rect_x: f32,
23 rect_width: f32,
24 origin_x: f32,
25}
26
27pub(crate) fn aligned_text_rect_for_text(
28 ctx: &PaintCtx,
29 rect: Rect,
30 text: &str,
31 style: &TextStyle,
32 line_height: f32,
33 horizontal_alignment: f32,
34) -> Rect {
35 aligned_text_rect_for_text_with_mode(
36 ctx,
37 rect,
38 text,
39 style,
40 line_height,
41 horizontal_alignment,
42 HorizontalTextAlignmentMode::Advance,
43 )
44}
45
46pub(crate) fn aligned_text_rect_for_text_with_mode(
47 ctx: &PaintCtx,
48 rect: Rect,
49 text: &str,
50 style: &TextStyle,
51 line_height: f32,
52 horizontal_alignment: f32,
53 horizontal_mode: HorizontalTextAlignmentMode,
54) -> Rect {
55 if let Some(aligned) = aligned_text_layout_for_text_with_mode(
56 ctx,
57 rect,
58 text,
59 style,
60 line_height,
61 horizontal_alignment,
62 horizontal_mode,
63 ) {
64 return aligned.rect;
65 }
66
67 let fallback_measurement = || TextMeasurement {
68 width: text.chars().count() as f32 * style.font_size * 0.56,
69 height: style.line_height,
70 bounds: Rect::ZERO,
71 ascent: style.font_size,
72 descent: 0.0,
73 cap_height: Some(style.font_size),
74 };
75 let measurement = ctx
76 .measure_text(text.to_string(), style.clone())
77 .ok()
78 .unwrap_or_else(fallback_measurement);
79 let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
80 let height = line_height.max(measurement.height).min(rect.height());
81 let y = vertically_centered_text_rect_y(ctx, rect, measurement, height);
82
83 Rect::new(placement.rect_x, y, placement.rect_width, height)
84}
85
86pub(crate) fn aligned_text_layout_for_text_with_mode(
87 ctx: &PaintCtx,
88 rect: Rect,
89 text: &str,
90 style: &TextStyle,
91 line_height: f32,
92 horizontal_alignment: f32,
93 horizontal_mode: HorizontalTextAlignmentMode,
94) -> Option<AlignedTextLayout> {
95 aligned_text_layout_for_text_with_mode_and_wrap(
96 ctx,
97 rect,
98 text,
99 style,
100 line_height,
101 horizontal_alignment,
102 horizontal_mode,
103 TextWrap::Word,
104 )
105}
106
107fn aligned_text_layout_for_text_with_mode_and_wrap(
108 ctx: &PaintCtx,
109 rect: Rect,
110 text: &str,
111 style: &TextStyle,
112 line_height: f32,
113 horizontal_alignment: f32,
114 horizontal_mode: HorizontalTextAlignmentMode,
115 wrap: TextWrap,
116) -> Option<AlignedTextLayout> {
117 let color = style.color;
118 let mut layout_style = style.clone();
119 layout_style.color = Color::WHITE;
120 let mut document = TextDocument::from_plain_text(text.to_string(), layout_style);
121 let paragraph_align = paragraph_alignment(horizontal_alignment, horizontal_mode);
122 for paragraph in &mut document.paragraphs {
123 paragraph.style.align = paragraph_align;
124 paragraph.style.wrap = wrap;
125 }
126 let layout = ctx
127 .layout_text_document(
128 TextLayoutRequest::new(document)
129 .with_box_size(Size::new(rect.width().max(1.0), rect.height().max(1.0))),
130 )
131 .ok()?;
132 let measurement = layout.measurement();
133 let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
134 let aligned_rect = aligned_text_rect_for_layout_with_mode(
135 ctx,
136 rect,
137 &layout,
138 line_height,
139 horizontal_alignment,
140 horizontal_mode,
141 );
142 Some(AlignedTextLayout {
143 origin: Point::new(placement.origin_x, aligned_rect.y()),
144 rect: aligned_rect,
145 layout,
146 color,
147 })
148}
149
150pub fn paint_aligned_text(
157 ctx: &mut PaintCtx,
158 rect: Rect,
159 text: &str,
160 style: &TextStyle,
161 line_height: f32,
162 horizontal_alignment: f32,
163) {
164 paint_aligned_text_with_mode(
165 ctx,
166 rect,
167 text,
168 style,
169 line_height,
170 horizontal_alignment,
171 HorizontalTextAlignmentMode::Optical,
172 );
173}
174
175pub(crate) fn paint_aligned_text_with_mode(
176 ctx: &mut PaintCtx,
177 rect: Rect,
178 text: &str,
179 style: &TextStyle,
180 line_height: f32,
181 horizontal_alignment: f32,
182 horizontal_mode: HorizontalTextAlignmentMode,
183) {
184 if let Some(aligned) = aligned_text_layout_for_text_with_mode(
185 ctx,
186 rect,
187 text,
188 style,
189 line_height,
190 horizontal_alignment,
191 horizontal_mode,
192 ) {
193 ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
194 return;
195 }
196
197 let fallback_rect = aligned_text_rect_for_text_with_mode(
198 ctx,
199 rect,
200 text,
201 style,
202 line_height,
203 horizontal_alignment,
204 horizontal_mode,
205 );
206 ctx.draw_text(fallback_rect, text.to_string(), style.clone());
207}
208
209pub fn paint_single_line_aligned_text(
211 ctx: &mut PaintCtx,
212 rect: Rect,
213 text: &str,
214 style: &TextStyle,
215 line_height: f32,
216 horizontal_alignment: f32,
217) {
218 let horizontal_mode = HorizontalTextAlignmentMode::Optical;
219 if let Some(aligned) = aligned_text_layout_for_text_with_mode_and_wrap(
220 ctx,
221 rect,
222 text,
223 style,
224 line_height,
225 horizontal_alignment,
226 horizontal_mode,
227 TextWrap::NoWrap,
228 ) {
229 ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
230 return;
231 }
232
233 let fallback_rect = aligned_text_rect_for_text_with_mode(
234 ctx,
235 rect,
236 text,
237 style,
238 line_height,
239 horizontal_alignment,
240 horizontal_mode,
241 );
242 ctx.draw_text(fallback_rect, text.to_string(), style.clone());
243}
244
245pub fn wrap_text_lines(
250 text: &str,
251 max_width: f32,
252 mut measure: impl FnMut(&str) -> f32,
253) -> Vec<String> {
254 let mut lines = Vec::new();
255 let space_width = measure(" ");
256
257 for paragraph in text.split('\n') {
258 if paragraph.is_empty() {
259 lines.push(String::new());
260 continue;
261 }
262
263 let mut current = String::new();
264 let mut current_width = 0.0_f32;
265 for word in paragraph.split(' ') {
266 let word_width = measure(word);
267 if current.is_empty() {
268 current.push_str(word);
269 current_width = word_width;
270 } else if current_width + space_width + word_width <= max_width {
271 current.push(' ');
272 current.push_str(word);
273 current_width += space_width + word_width;
274 } else {
275 lines.push(std::mem::take(&mut current));
276 current.push_str(word);
277 current_width = word_width;
278 }
279 }
280 lines.push(current);
281 }
282
283 lines
284}
285
286fn paragraph_alignment(
287 horizontal_alignment: f32,
288 horizontal_mode: HorizontalTextAlignmentMode,
289) -> TextAlign {
290 if horizontal_mode == HorizontalTextAlignmentMode::Optical {
291 return TextAlign::Left;
292 }
293
294 let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
295 if horizontal_alignment <= 0.0 {
296 TextAlign::Left
297 } else if horizontal_alignment >= 1.0 {
298 TextAlign::Right
299 } else {
300 TextAlign::Center
301 }
302}
303
304pub(crate) fn aligned_text_rect_for_layout(
305 ctx: &PaintCtx,
306 rect: Rect,
307 layout: &TextLayout,
308 line_height: f32,
309 horizontal_alignment: f32,
310) -> Rect {
311 aligned_text_rect_for_layout_with_mode(
312 ctx,
313 rect,
314 layout,
315 line_height,
316 horizontal_alignment,
317 HorizontalTextAlignmentMode::Advance,
318 )
319}
320
321pub(crate) fn aligned_text_rect_for_layout_with_mode(
322 ctx: &PaintCtx,
323 rect: Rect,
324 layout: &TextLayout,
325 line_height: f32,
326 horizontal_alignment: f32,
327 horizontal_mode: HorizontalTextAlignmentMode,
328) -> Rect {
329 let measurement = layout.measurement();
330 let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
331 let height = line_height.max(measurement.height).min(rect.height());
332 let y = layout
333 .lines()
334 .first()
335 .map(|line| {
336 rect.y() + (rect.height() * 0.5) - line.baseline - visual_center(ctx, measurement)
337 })
338 .unwrap_or_else(|| vertically_centered_text_rect_y(ctx, rect, measurement, height));
339
340 Rect::new(placement.rect_x, y, placement.rect_width, height)
341}
342
343fn horizontal_placement(
344 rect: Rect,
345 measurement: TextMeasurement,
346 horizontal_alignment: f32,
347 horizontal_mode: HorizontalTextAlignmentMode,
348) -> HorizontalPlacement {
349 let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
350 let (width, origin_shift) = match horizontal_mode {
351 HorizontalTextAlignmentMode::Advance => (measurement.width, 0.0),
352 HorizontalTextAlignmentMode::Optical => {
353 let bounds = measurement.bounds;
354 if bounds.width().is_finite() && bounds.width() > 0.0 {
355 (bounds.width(), -bounds.x())
356 } else {
357 (measurement.width, 0.0)
358 }
359 }
360 };
361 let rect_width = width.min(rect.width()).max(0.0);
362 let rect_x = rect.x() + ((rect.width() - rect_width).max(0.0) * horizontal_alignment);
363
364 HorizontalPlacement {
365 rect_x,
366 rect_width,
367 origin_x: rect_x + origin_shift,
368 }
369}
370
371pub(crate) fn vertically_centered_text_rect_y(
372 ctx: &PaintCtx,
373 rect: Rect,
374 measurement: TextMeasurement,
375 height: f32,
376) -> f32 {
377 let visual_center = visual_center(ctx, measurement);
378 let baseline = rect.y() + (rect.height() * 0.5) - visual_center;
379 let leading_above = ((height - (measurement.ascent + measurement.descent)).max(0.0)) * 0.5;
380
381 baseline - measurement.ascent - leading_above
382}
383
384fn visual_center(ctx: &PaintCtx, measurement: TextMeasurement) -> f32 {
385 let optical_centering = window_render_options(ctx.window_id())
386 .map(|options| options.optical_vertical_text_alignment_enabled)
387 .unwrap_or(true);
388 let top = if optical_centering {
389 -measurement.cap_height.unwrap_or(measurement.ascent)
390 } else {
391 -measurement.ascent
392 };
393 let bottom = if optical_centering {
394 measurement.descent * 0.5
395 } else {
396 measurement.descent
397 };
398 (top + bottom) * 0.5
399}
400
401#[cfg(test)]
402mod tests {
403 use super::wrap_text_lines;
404
405 #[test]
406 fn wrap_text_lines_preserves_newlines_and_keeps_long_words() {
407 let lines = wrap_text_lines("alpha beta\nsuperlongword gamma", 10.0, |text| {
408 text.chars().count() as f32
409 });
410
411 assert_eq!(
412 lines,
413 vec![
414 "alpha beta".to_string(),
415 "superlongword".to_string(),
416 "gamma".to_string(),
417 ]
418 );
419 }
420}