Skip to main content

sui_widgets/
text_align.rs

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
150/// Paint text using SUI's shared optical baseline and horizontal alignment path.
151///
152/// `horizontal_alignment` is clamped to `0.0..=1.0`, where `0.0` is left,
153/// `0.5` is centered, and `1.0` is right aligned. Callers should normally pass
154/// `style.line_height` for `line_height`; the separate argument is retained for
155/// compatibility with controls that constrain a token line-height to their slot.
156pub 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_contained(
176    ctx: &mut PaintCtx,
177    rect: Rect,
178    text: &str,
179    style: &TextStyle,
180    line_height: f32,
181    horizontal_alignment: f32,
182) {
183    let horizontal_mode = HorizontalTextAlignmentMode::Optical;
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        let painted = painted_layout_rect(aligned.origin, &aligned.layout);
194        let offset = containment_offset(painted, rect);
195        ctx.draw_text_layout_with_color(aligned.origin + offset, &aligned.layout, aligned.color);
196        return;
197    }
198
199    let fallback_rect = aligned_text_rect_for_text_with_mode(
200        ctx,
201        rect,
202        text,
203        style,
204        line_height,
205        horizontal_alignment,
206        horizontal_mode,
207    );
208    ctx.draw_text(
209        fallback_rect.translate(containment_offset(fallback_rect, rect)),
210        text.to_string(),
211        style.clone(),
212    );
213}
214
215pub(crate) fn paint_aligned_text_with_mode(
216    ctx: &mut PaintCtx,
217    rect: Rect,
218    text: &str,
219    style: &TextStyle,
220    line_height: f32,
221    horizontal_alignment: f32,
222    horizontal_mode: HorizontalTextAlignmentMode,
223) {
224    if let Some(aligned) = aligned_text_layout_for_text_with_mode(
225        ctx,
226        rect,
227        text,
228        style,
229        line_height,
230        horizontal_alignment,
231        horizontal_mode,
232    ) {
233        ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
234        return;
235    }
236
237    let fallback_rect = aligned_text_rect_for_text_with_mode(
238        ctx,
239        rect,
240        text,
241        style,
242        line_height,
243        horizontal_alignment,
244        horizontal_mode,
245    );
246    ctx.draw_text(fallback_rect, text.to_string(), style.clone());
247}
248
249fn painted_layout_rect(origin: Point, layout: &TextLayout) -> Rect {
250    let measurement = layout.measurement();
251    let bounds = measurement.bounds;
252    let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
253        bounds.width()
254    } else {
255        measurement.width
256    };
257    Rect::new(
258        origin.x + bounds.x(),
259        origin.y + ((layout.box_size().height - measurement.height).max(0.0) * 0.5),
260        width,
261        layout.style().line_height.max(measurement.height),
262    )
263}
264
265fn containment_offset(inner: Rect, outer: Rect) -> sui_core::Vector {
266    fn axis_offset(inner_min: f32, inner_max: f32, outer_min: f32, outer_max: f32) -> f32 {
267        let inner_size = inner_max - inner_min;
268        let outer_size = outer_max - outer_min;
269        if inner_size > outer_size {
270            outer_min - inner_min
271        } else if inner_min < outer_min {
272            outer_min - inner_min
273        } else if inner_max > outer_max {
274            outer_max - inner_max
275        } else {
276            0.0
277        }
278    }
279
280    sui_core::Vector::new(
281        axis_offset(inner.x(), inner.max_x(), outer.x(), outer.max_x()),
282        axis_offset(inner.y(), inner.max_y(), outer.y(), outer.max_y()),
283    )
284}
285
286/// Paint one unwrapped line using SUI's shared optical baseline alignment path.
287pub fn paint_single_line_aligned_text(
288    ctx: &mut PaintCtx,
289    rect: Rect,
290    text: &str,
291    style: &TextStyle,
292    line_height: f32,
293    horizontal_alignment: f32,
294) {
295    let horizontal_mode = HorizontalTextAlignmentMode::Optical;
296    if let Some(aligned) = aligned_text_layout_for_text_with_mode_and_wrap(
297        ctx,
298        rect,
299        text,
300        style,
301        line_height,
302        horizontal_alignment,
303        horizontal_mode,
304        TextWrap::NoWrap,
305    ) {
306        ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
307        return;
308    }
309
310    let fallback_rect = aligned_text_rect_for_text_with_mode(
311        ctx,
312        rect,
313        text,
314        style,
315        line_height,
316        horizontal_alignment,
317        horizontal_mode,
318    );
319    ctx.draw_text(fallback_rect, text.to_string(), style.clone());
320}
321
322/// Greedy word-wrap `text` to `max_width`, using `measure` for run widths.
323///
324/// Explicit newlines are preserved. Words longer than `max_width` are kept on
325/// their own line rather than split, which matches common UI metadata wrapping.
326pub fn wrap_text_lines(
327    text: &str,
328    max_width: f32,
329    mut measure: impl FnMut(&str) -> f32,
330) -> Vec<String> {
331    let mut lines = Vec::new();
332    let space_width = measure(" ");
333
334    for paragraph in text.split('\n') {
335        if paragraph.is_empty() {
336            lines.push(String::new());
337            continue;
338        }
339
340        let mut current = String::new();
341        let mut current_width = 0.0_f32;
342        for word in paragraph.split(' ') {
343            let word_width = measure(word);
344            if current.is_empty() {
345                current.push_str(word);
346                current_width = word_width;
347            } else if current_width + space_width + word_width <= max_width {
348                current.push(' ');
349                current.push_str(word);
350                current_width += space_width + word_width;
351            } else {
352                lines.push(std::mem::take(&mut current));
353                current.push_str(word);
354                current_width = word_width;
355            }
356        }
357        lines.push(current);
358    }
359
360    lines
361}
362
363fn paragraph_alignment(
364    horizontal_alignment: f32,
365    horizontal_mode: HorizontalTextAlignmentMode,
366) -> TextAlign {
367    if horizontal_mode == HorizontalTextAlignmentMode::Optical {
368        return TextAlign::Left;
369    }
370
371    let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
372    if horizontal_alignment <= 0.0 {
373        TextAlign::Left
374    } else if horizontal_alignment >= 1.0 {
375        TextAlign::Right
376    } else {
377        TextAlign::Center
378    }
379}
380
381pub(crate) fn aligned_text_rect_for_layout(
382    ctx: &PaintCtx,
383    rect: Rect,
384    layout: &TextLayout,
385    line_height: f32,
386    horizontal_alignment: f32,
387) -> Rect {
388    aligned_text_rect_for_layout_with_mode(
389        ctx,
390        rect,
391        layout,
392        line_height,
393        horizontal_alignment,
394        HorizontalTextAlignmentMode::Advance,
395    )
396}
397
398pub(crate) fn aligned_text_rect_for_layout_with_mode(
399    ctx: &PaintCtx,
400    rect: Rect,
401    layout: &TextLayout,
402    line_height: f32,
403    horizontal_alignment: f32,
404    horizontal_mode: HorizontalTextAlignmentMode,
405) -> Rect {
406    let measurement = layout.measurement();
407    let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
408    let height = line_height.max(measurement.height).min(rect.height());
409    let y = layout
410        .lines()
411        .first()
412        .map(|line| {
413            rect.y() + (rect.height() * 0.5) - line.baseline - visual_center(ctx, measurement)
414        })
415        .unwrap_or_else(|| vertically_centered_text_rect_y(ctx, rect, measurement, height));
416
417    Rect::new(placement.rect_x, y, placement.rect_width, height)
418}
419
420fn horizontal_placement(
421    rect: Rect,
422    measurement: TextMeasurement,
423    horizontal_alignment: f32,
424    horizontal_mode: HorizontalTextAlignmentMode,
425) -> HorizontalPlacement {
426    let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
427    let (width, origin_shift) = match horizontal_mode {
428        HorizontalTextAlignmentMode::Advance => (measurement.width, 0.0),
429        HorizontalTextAlignmentMode::Optical => {
430            let bounds = measurement.bounds;
431            if bounds.width().is_finite() && bounds.width() > 0.0 {
432                (bounds.width(), -bounds.x())
433            } else {
434                (measurement.width, 0.0)
435            }
436        }
437    };
438    let rect_width = width.min(rect.width()).max(0.0);
439    let rect_x = rect.x() + ((rect.width() - rect_width).max(0.0) * horizontal_alignment);
440
441    HorizontalPlacement {
442        rect_x,
443        rect_width,
444        origin_x: rect_x + origin_shift,
445    }
446}
447
448pub(crate) fn vertically_centered_text_rect_y(
449    ctx: &PaintCtx,
450    rect: Rect,
451    measurement: TextMeasurement,
452    height: f32,
453) -> f32 {
454    let visual_center = visual_center(ctx, measurement);
455    let baseline = rect.y() + (rect.height() * 0.5) - visual_center;
456    let leading_above = ((height - (measurement.ascent + measurement.descent)).max(0.0)) * 0.5;
457
458    baseline - measurement.ascent - leading_above
459}
460
461fn visual_center(ctx: &PaintCtx, measurement: TextMeasurement) -> f32 {
462    let optical_centering = window_render_options(ctx.window_id())
463        .map(|options| options.optical_vertical_text_alignment_enabled)
464        .unwrap_or(true);
465    let top = if optical_centering {
466        -measurement.cap_height.unwrap_or(measurement.ascent)
467    } else {
468        -measurement.ascent
469    };
470    let bottom = if optical_centering {
471        measurement.descent * 0.5
472    } else {
473        measurement.descent
474    };
475    (top + bottom) * 0.5
476}
477
478#[cfg(test)]
479mod tests {
480    use super::wrap_text_lines;
481
482    #[test]
483    fn wrap_text_lines_preserves_newlines_and_keeps_long_words() {
484        let lines = wrap_text_lines("alpha beta\nsuperlongword gamma", 10.0, |text| {
485            text.chars().count() as f32
486        });
487
488        assert_eq!(
489            lines,
490            vec![
491                "alpha beta".to_string(),
492                "superlongword".to_string(),
493                "gamma".to_string(),
494            ]
495        );
496    }
497}