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 || inner_min < outer_min {
270            outer_min - inner_min
271        } else if inner_max > outer_max {
272            outer_max - inner_max
273        } else {
274            0.0
275        }
276    }
277
278    sui_core::Vector::new(
279        axis_offset(inner.x(), inner.max_x(), outer.x(), outer.max_x()),
280        axis_offset(inner.y(), inner.max_y(), outer.y(), outer.max_y()),
281    )
282}
283
284/// Paint one unwrapped line using SUI's shared optical baseline alignment path.
285pub fn paint_single_line_aligned_text(
286    ctx: &mut PaintCtx,
287    rect: Rect,
288    text: &str,
289    style: &TextStyle,
290    line_height: f32,
291    horizontal_alignment: f32,
292) {
293    let horizontal_mode = HorizontalTextAlignmentMode::Optical;
294    if let Some(aligned) = aligned_text_layout_for_text_with_mode_and_wrap(
295        ctx,
296        rect,
297        text,
298        style,
299        line_height,
300        horizontal_alignment,
301        horizontal_mode,
302        TextWrap::NoWrap,
303    ) {
304        ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
305        return;
306    }
307
308    let fallback_rect = aligned_text_rect_for_text_with_mode(
309        ctx,
310        rect,
311        text,
312        style,
313        line_height,
314        horizontal_alignment,
315        horizontal_mode,
316    );
317    ctx.draw_text(fallback_rect, text.to_string(), style.clone());
318}
319
320/// Greedy word-wrap `text` to `max_width`, using `measure` for run widths.
321///
322/// Explicit newlines are preserved. Words longer than `max_width` are kept on
323/// their own line rather than split, which matches common UI metadata wrapping.
324pub fn wrap_text_lines(
325    text: &str,
326    max_width: f32,
327    mut measure: impl FnMut(&str) -> f32,
328) -> Vec<String> {
329    let mut lines = Vec::new();
330    let space_width = measure(" ");
331
332    for paragraph in text.split('\n') {
333        if paragraph.is_empty() {
334            lines.push(String::new());
335            continue;
336        }
337
338        let mut current = String::new();
339        let mut current_width = 0.0_f32;
340        for word in paragraph.split(' ') {
341            let word_width = measure(word);
342            if current.is_empty() {
343                current.push_str(word);
344                current_width = word_width;
345            } else if current_width + space_width + word_width <= max_width {
346                current.push(' ');
347                current.push_str(word);
348                current_width += space_width + word_width;
349            } else {
350                lines.push(std::mem::take(&mut current));
351                current.push_str(word);
352                current_width = word_width;
353            }
354        }
355        lines.push(current);
356    }
357
358    lines
359}
360
361fn paragraph_alignment(
362    horizontal_alignment: f32,
363    horizontal_mode: HorizontalTextAlignmentMode,
364) -> TextAlign {
365    if horizontal_mode == HorizontalTextAlignmentMode::Optical {
366        return TextAlign::Left;
367    }
368
369    let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
370    if horizontal_alignment <= 0.0 {
371        TextAlign::Left
372    } else if horizontal_alignment >= 1.0 {
373        TextAlign::Right
374    } else {
375        TextAlign::Center
376    }
377}
378
379pub(crate) fn aligned_text_rect_for_layout(
380    ctx: &PaintCtx,
381    rect: Rect,
382    layout: &TextLayout,
383    line_height: f32,
384    horizontal_alignment: f32,
385) -> Rect {
386    aligned_text_rect_for_layout_with_mode(
387        ctx,
388        rect,
389        layout,
390        line_height,
391        horizontal_alignment,
392        HorizontalTextAlignmentMode::Advance,
393    )
394}
395
396pub(crate) fn aligned_text_rect_for_layout_with_mode(
397    ctx: &PaintCtx,
398    rect: Rect,
399    layout: &TextLayout,
400    line_height: f32,
401    horizontal_alignment: f32,
402    horizontal_mode: HorizontalTextAlignmentMode,
403) -> Rect {
404    let measurement = layout.measurement();
405    let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
406    let height = line_height.max(measurement.height).min(rect.height());
407    let y = layout
408        .lines()
409        .first()
410        .map(|line| {
411            rect.y() + (rect.height() * 0.5) - line.baseline - visual_center(ctx, measurement)
412        })
413        .unwrap_or_else(|| vertically_centered_text_rect_y(ctx, rect, measurement, height));
414
415    Rect::new(placement.rect_x, y, placement.rect_width, height)
416}
417
418fn horizontal_placement(
419    rect: Rect,
420    measurement: TextMeasurement,
421    horizontal_alignment: f32,
422    horizontal_mode: HorizontalTextAlignmentMode,
423) -> HorizontalPlacement {
424    let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
425    let (width, origin_shift) = match horizontal_mode {
426        HorizontalTextAlignmentMode::Advance => (measurement.width, 0.0),
427        HorizontalTextAlignmentMode::Optical => {
428            let bounds = measurement.bounds;
429            if bounds.width().is_finite() && bounds.width() > 0.0 {
430                (bounds.width(), -bounds.x())
431            } else {
432                (measurement.width, 0.0)
433            }
434        }
435    };
436    let rect_width = width.min(rect.width()).max(0.0);
437    let rect_x = rect.x() + ((rect.width() - rect_width).max(0.0) * horizontal_alignment);
438
439    HorizontalPlacement {
440        rect_x,
441        rect_width,
442        origin_x: rect_x + origin_shift,
443    }
444}
445
446pub(crate) fn vertically_centered_text_rect_y(
447    ctx: &PaintCtx,
448    rect: Rect,
449    measurement: TextMeasurement,
450    height: f32,
451) -> f32 {
452    let visual_center = visual_center(ctx, measurement);
453    let baseline = rect.y() + (rect.height() * 0.5) - visual_center;
454    let leading_above = ((height - (measurement.ascent + measurement.descent)).max(0.0)) * 0.5;
455
456    baseline - measurement.ascent - leading_above
457}
458
459fn visual_center(ctx: &PaintCtx, measurement: TextMeasurement) -> f32 {
460    let optical_centering = window_render_options(ctx.window_id())
461        .map(|options| options.optical_vertical_text_alignment_enabled)
462        .unwrap_or(true);
463    let top = if optical_centering {
464        -measurement.cap_height.unwrap_or(measurement.ascent)
465    } else {
466        -measurement.ascent
467    };
468    let bottom = if optical_centering {
469        measurement.descent * 0.5
470    } else {
471        measurement.descent
472    };
473    (top + bottom) * 0.5
474}
475
476#[cfg(test)]
477mod tests {
478    use super::wrap_text_lines;
479
480    #[test]
481    fn wrap_text_lines_preserves_newlines_and_keeps_long_words() {
482        let lines = wrap_text_lines("alpha beta\nsuperlongword gamma", 10.0, |text| {
483            text.chars().count() as f32
484        });
485
486        assert_eq!(
487            lines,
488            vec![
489                "alpha beta".to_string(),
490                "superlongword".to_string(),
491                "gamma".to_string(),
492            ]
493        );
494    }
495}