use sui_core::{Color, Point, Rect, Size};
use sui_layout::LayoutContext;
use sui_runtime::{MeasureCtx, PaintCtx, window_render_options};
use sui_text::{
TextAlign, TextDocument, TextLayout, TextLayoutRequest, TextMeasurement, TextStyle, TextWrap,
};
use unicode_segmentation::UnicodeSegmentation;
pub(crate) struct AlignedTextLayout {
pub(crate) rect: Rect,
origin: Point,
layout: TextLayout,
color: Color,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HorizontalTextAlignmentMode {
Advance,
Optical,
}
#[derive(Debug, Clone, Copy)]
struct HorizontalPlacement {
rect_x: f32,
rect_width: f32,
origin_x: f32,
}
pub(crate) fn aligned_text_rect_for_text(
ctx: &PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
line_height: f32,
horizontal_alignment: f32,
) -> Rect {
aligned_text_rect_for_text_with_mode(
ctx,
rect,
text,
style,
line_height,
horizontal_alignment,
HorizontalTextAlignmentMode::Advance,
)
}
pub(crate) fn aligned_text_rect_for_text_with_mode(
ctx: &PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
line_height: f32,
horizontal_alignment: f32,
horizontal_mode: HorizontalTextAlignmentMode,
) -> Rect {
if let Some(aligned) = aligned_text_layout_for_text_with_mode(
ctx,
rect,
text,
style,
line_height,
horizontal_alignment,
horizontal_mode,
) {
return aligned.rect;
}
let fallback_measurement = || TextMeasurement {
width: text.chars().count() as f32 * style.font_size * 0.56,
height: style.line_height,
bounds: Rect::ZERO,
ascent: style.font_size,
descent: 0.0,
cap_height: Some(style.font_size),
};
let measurement = ctx
.measure_text(text.to_string(), style.clone())
.ok()
.unwrap_or_else(fallback_measurement);
let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
let height = line_height.max(measurement.height).min(rect.height());
let y = vertically_centered_text_rect_y(ctx, rect, measurement, height);
Rect::new(placement.rect_x, y, placement.rect_width, height)
}
pub(crate) fn aligned_text_layout_for_text_with_mode(
ctx: &PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
line_height: f32,
horizontal_alignment: f32,
horizontal_mode: HorizontalTextAlignmentMode,
) -> Option<AlignedTextLayout> {
aligned_text_layout_for_text_with_mode_and_wrap(
ctx,
rect,
text,
style,
line_height,
horizontal_alignment,
horizontal_mode,
TextWrap::Word,
)
}
fn aligned_text_layout_for_text_with_mode_and_wrap(
ctx: &PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
line_height: f32,
horizontal_alignment: f32,
horizontal_mode: HorizontalTextAlignmentMode,
wrap: TextWrap,
) -> Option<AlignedTextLayout> {
let color = style.color;
let mut layout_style = style.clone();
layout_style.color = Color::WHITE;
let mut document = TextDocument::from_plain_text(text.to_string(), layout_style);
let paragraph_align = paragraph_alignment(horizontal_alignment, horizontal_mode);
for paragraph in &mut document.paragraphs {
paragraph.style.align = paragraph_align;
paragraph.style.wrap = wrap;
}
let layout = ctx
.layout_text_document(
TextLayoutRequest::new(document)
.with_box_size(Size::new(rect.width().max(1.0), rect.height().max(1.0))),
)
.ok()?;
let measurement = layout.measurement();
let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
let aligned_rect = aligned_text_rect_for_layout_with_mode(
ctx,
rect,
&layout,
line_height,
horizontal_alignment,
horizontal_mode,
);
Some(AlignedTextLayout {
origin: Point::new(placement.origin_x, aligned_rect.y()),
rect: aligned_rect,
layout,
color,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerticalAlign {
Top,
#[default]
Center,
Bottom,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextPlacement {
pub horizontal: TextAlign,
pub vertical: VerticalAlign,
}
impl TextPlacement {
pub const fn new(horizontal: TextAlign, vertical: VerticalAlign) -> Self {
Self {
horizontal,
vertical,
}
}
pub const START: Self = Self::new(TextAlign::Start, VerticalAlign::Center);
pub const CENTER: Self = Self::new(TextAlign::Center, VerticalAlign::Center);
pub const END: Self = Self::new(TextAlign::End, VerticalAlign::Center);
pub const TOP_START: Self = Self::new(TextAlign::Start, VerticalAlign::Top);
}
impl From<TextAlign> for TextPlacement {
fn from(horizontal: TextAlign) -> Self {
Self::new(horizontal, VerticalAlign::Center)
}
}
pub(crate) const fn alignment_fraction(align: TextAlign) -> f32 {
match align {
TextAlign::Start | TextAlign::Left | TextAlign::Justified => 0.0,
TextAlign::Center => 0.5,
TextAlign::End | TextAlign::Right => 1.0,
}
}
pub trait TextShaper {
fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout>;
}
impl TextShaper for LayoutContext {
fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
self.layout_document(request)
}
}
impl TextShaper for MeasureCtx {
fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
self.layout().layout_document(request)
}
}
impl TextShaper for PaintCtx {
fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
self.layout_text_document(request)
}
}
#[derive(Debug, Clone, Default)]
pub struct Paragraph {
text: String,
style: TextStyle,
align: TextAlign,
layout: Option<TextLayout>,
box_width: f32,
}
impl Paragraph {
pub fn new(
shaper: &(impl TextShaper + ?Sized),
text: impl Into<String>,
style: &TextStyle,
align: TextAlign,
max_width: f32,
) -> Self {
let text = text.into();
let width = if max_width.is_finite() {
max_width.max(1.0)
} else {
f32::INFINITY
};
let request = |paragraph_align| {
let mut layout_style = style.clone();
layout_style.color = Color::WHITE;
let mut document = TextDocument::from_plain_text(text.clone(), layout_style);
for paragraph in &mut document.paragraphs {
paragraph.style.align = paragraph_align;
paragraph.style.wrap = TextWrap::Word;
}
TextLayoutRequest::new(document).with_box_size(Size::new(width, f32::INFINITY))
};
let mut layout = shaper.shape_document(request(TextAlign::Left)).ok();
if !matches!(align, TextAlign::Left | TextAlign::Start)
&& layout
.as_ref()
.is_some_and(|layout| layout.lines().len() > 1)
{
layout = shaper.shape_document(request(align)).ok().or(layout);
}
let box_width = layout
.as_ref()
.map_or(0.0, |layout| layout.box_size().width);
Self {
text,
style: style.clone(),
align,
layout,
box_width,
}
}
pub fn text(&self) -> &str {
&self.text
}
pub fn size(&self) -> Size {
self.layout.as_ref().map_or_else(
|| Size::new(0.0, self.style.line_height),
|layout| {
let measurement = layout.measurement();
Size::new(measurement.width, measurement.height)
},
)
}
pub fn line_count(&self) -> usize {
self.layout
.as_ref()
.map_or(0, |layout| layout.lines().len())
}
pub fn paint(&self, ctx: &mut PaintCtx, rect: Rect, vertical: VerticalAlign) {
self.paint_with_color(ctx, rect, vertical, self.style.color);
}
pub fn paint_with_color(
&self,
ctx: &mut PaintCtx,
rect: Rect,
vertical: VerticalAlign,
color: Color,
) {
let Some(layout) = &self.layout else {
if !self.text.is_empty() {
let style = TextStyle {
color,
..self.style.clone()
};
ctx.draw_text(rect, self.text.clone(), style);
}
return;
};
let origin = paragraph_origin(
ctx,
rect,
layout,
alignment_fraction(self.align),
self.box_width,
vertical,
);
ctx.draw_text_layout_with_color(origin, layout, color);
}
}
pub(crate) fn paragraph_origin(
ctx: &PaintCtx,
rect: Rect,
layout: &TextLayout,
horizontal: f32,
box_width: f32,
vertical: VerticalAlign,
) -> Point {
let measurement = layout.measurement();
let lines = layout.lines();
let left_aligned = lines.len() <= 1
|| layout
.paragraphs()
.iter()
.all(|paragraph| matches!(paragraph.style.align, TextAlign::Left | TextAlign::Start));
let x = if left_aligned {
horizontal_placement(
rect,
measurement,
horizontal,
HorizontalTextAlignmentMode::Optical,
)
.origin_x
} else {
rect.x() + (rect.width() - box_width) * horizontal
};
let (height, lone_line) = match lines {
[line] => (measurement.height, Some(line)),
[first, second, ..] if rect.height() < second.rect.max_y() => {
(first.rect.max_y(), Some(first))
}
_ => (measurement.height, None),
};
let room = (rect.height() - height).max(0.0);
let y = match vertical {
VerticalAlign::Top => rect.y(),
VerticalAlign::Bottom => rect.y() + room,
VerticalAlign::Center => match lone_line {
Some(line) => {
rect.y() + rect.height() * 0.5 - line.baseline - visual_center(ctx, measurement)
}
None => rect.y() + room * 0.5,
},
};
Point::new(x, y)
}
pub fn paint_text(
ctx: &mut PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
placement: impl Into<TextPlacement>,
) {
let placement = placement.into();
let paragraph = Paragraph::new(ctx, text, style, placement.horizontal, rect.width());
paragraph.paint(ctx, rect, placement.vertical);
}
pub fn paint_text_line(
ctx: &mut PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
align: TextAlign,
) {
let horizontal = alignment_fraction(align);
let horizontal_mode = HorizontalTextAlignmentMode::Optical;
if let Some(aligned) = aligned_text_layout_for_text_with_mode_and_wrap(
ctx,
rect,
text,
style,
style.line_height,
horizontal,
horizontal_mode,
TextWrap::NoWrap,
) {
ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
return;
}
let fallback_rect = aligned_text_rect_for_text_with_mode(
ctx,
rect,
text,
style,
style.line_height,
horizontal,
horizontal_mode,
);
ctx.draw_text(fallback_rect, text.to_string(), style.clone());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextOverflow {
#[default]
Clip,
Ellipsis,
}
const ELLIPSIS: &str = "\u{2026}";
const FIT_TOLERANCE: f32 = 0.01;
#[derive(Debug, Clone, Default)]
pub struct ElidedLine {
text: String,
style: TextStyle,
elided: bool,
width: f32,
}
impl ElidedLine {
pub fn new(
shaper: &(impl TextShaper + ?Sized),
text: &str,
style: &TextStyle,
max_width: f32,
) -> Self {
let line_end = text.find(['\n', '\r']);
let line = &text[..line_end.unwrap_or(text.len())];
let more_lines = line_end.is_some();
let fitted = |text: String, elided: bool, width: f32| Self {
text,
style: style.clone(),
elided,
width,
};
let fits = |width: f32| width <= max_width + FIT_TOLERANCE;
let Some(full) = single_line_layout(shaper, line, style) else {
return fitted(line.to_string(), more_lines, 0.0);
};
let full_width = full.measurement().width;
if !more_lines && (!max_width.is_finite() || fits(full_width)) {
return fitted(line.to_string(), false, full_width);
}
let width_of = |text: &str| {
single_line_layout(shaper, text, style).map(|layout| layout.measurement().width)
};
let ellipsis_width = width_of(ELLIPSIS).unwrap_or(0.0);
let boundaries = line
.grapheme_indices(true)
.map(|(start, _)| start)
.chain([line.len()])
.collect::<Vec<_>>();
let mut widths = vec![0.0_f32; boundaries.len() - 1];
for cluster in full.clusters() {
let index = boundaries
.partition_point(|&boundary| boundary <= cluster.byte_range.start)
.saturating_sub(1);
if let Some(width) = widths.get_mut(index) {
*width += cluster.rect.width();
}
}
let budget = max_width - ellipsis_width;
let mut kept = 0;
let mut kept_width = 0.0;
for width in &widths {
if kept_width + width > budget + FIT_TOLERANCE {
break;
}
kept_width += width;
kept += 1;
}
if !more_lines {
kept = kept.min(widths.len().saturating_sub(1));
}
while kept > 0 {
let start = line[..boundaries[kept]].trim_end();
if start.is_empty() {
break;
}
let shown = format!("{start}{ELLIPSIS}");
match width_of(&shown) {
Some(width) if fits(width) => return fitted(shown, true, width),
Some(_) => kept -= 1,
None => return fitted(shown, true, 0.0),
}
}
if fits(ellipsis_width) || line.is_empty() {
return fitted(ELLIPSIS.to_string(), true, ellipsis_width);
}
let first = line.graphemes(true).next().unwrap_or(line);
fitted(first.to_string(), true, width_of(first).unwrap_or(0.0))
}
pub fn text(&self) -> &str {
&self.text
}
pub fn is_elided(&self) -> bool {
self.elided
}
pub fn width(&self) -> f32 {
self.width
}
pub fn paint(&self, ctx: &mut PaintCtx, rect: Rect, align: TextAlign) {
self.paint_with_color(ctx, rect, align, self.style.color);
}
pub fn paint_with_color(&self, ctx: &mut PaintCtx, rect: Rect, align: TextAlign, color: Color) {
let style = TextStyle {
color,
..self.style.clone()
};
let overflows = self.width > rect.width() + FIT_TOLERANCE;
if overflows {
let slack = style.line_height.max(rect.height());
ctx.push_clip_rect(Rect::new(
rect.x(),
rect.y() - slack,
rect.width().max(0.0),
rect.height() + slack * 2.0,
));
}
paint_text_line(ctx, rect, &self.text, &style, align);
if overflows {
ctx.pop_clip();
}
}
}
pub fn paint_text_line_elided(
ctx: &mut PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
align: TextAlign,
) {
ElidedLine::new(ctx, text, style, rect.width()).paint(ctx, rect, align);
}
fn single_line_layout(
shaper: &(impl TextShaper + ?Sized),
text: &str,
style: &TextStyle,
) -> Option<TextLayout> {
let mut layout_style = style.clone();
layout_style.color = Color::WHITE;
let mut document = TextDocument::from_plain_text(text.to_string(), layout_style);
for paragraph in &mut document.paragraphs {
paragraph.style.align = TextAlign::Left;
paragraph.style.wrap = TextWrap::NoWrap;
}
shaper.shape_document(TextLayoutRequest::new(document)).ok()
}
pub(crate) fn paint_aligned_text_contained(
ctx: &mut PaintCtx,
rect: Rect,
text: &str,
style: &TextStyle,
line_height: f32,
horizontal_alignment: f32,
) {
let horizontal_mode = HorizontalTextAlignmentMode::Optical;
if let Some(aligned) = aligned_text_layout_for_text_with_mode(
ctx,
rect,
text,
style,
line_height,
horizontal_alignment,
horizontal_mode,
) {
let painted = painted_layout_rect(aligned.origin, &aligned.layout);
let offset = containment_offset(painted, rect);
ctx.draw_text_layout_with_color(aligned.origin + offset, &aligned.layout, aligned.color);
return;
}
let fallback_rect = aligned_text_rect_for_text_with_mode(
ctx,
rect,
text,
style,
line_height,
horizontal_alignment,
horizontal_mode,
);
ctx.draw_text(
fallback_rect.translate(containment_offset(fallback_rect, rect)),
text.to_string(),
style.clone(),
);
}
fn painted_layout_rect(origin: Point, layout: &TextLayout) -> Rect {
let measurement = layout.measurement();
let bounds = measurement.bounds;
let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
bounds.width()
} else {
measurement.width
};
Rect::new(
origin.x + bounds.x(),
origin.y + ((layout.box_size().height - measurement.height).max(0.0) * 0.5),
width,
layout.style().line_height.max(measurement.height),
)
}
fn containment_offset(inner: Rect, outer: Rect) -> sui_core::Vector {
fn axis_offset(inner_min: f32, inner_max: f32, outer_min: f32, outer_max: f32) -> f32 {
let inner_size = inner_max - inner_min;
let outer_size = outer_max - outer_min;
if inner_size > outer_size || inner_min < outer_min {
outer_min - inner_min
} else if inner_max > outer_max {
outer_max - inner_max
} else {
0.0
}
}
sui_core::Vector::new(
axis_offset(inner.x(), inner.max_x(), outer.x(), outer.max_x()),
axis_offset(inner.y(), inner.max_y(), outer.y(), outer.max_y()),
)
}
pub fn wrap_text_lines(
text: &str,
max_width: f32,
mut measure: impl FnMut(&str) -> f32,
) -> Vec<String> {
let mut lines = Vec::new();
let space_width = measure(" ");
for paragraph in text.split('\n') {
if paragraph.is_empty() {
lines.push(String::new());
continue;
}
let mut current = String::new();
let mut current_width = 0.0_f32;
for word in paragraph.split(' ') {
let word_width = measure(word);
if current.is_empty() {
current.push_str(word);
current_width = word_width;
} else if current_width + space_width + word_width <= max_width {
current.push(' ');
current.push_str(word);
current_width += space_width + word_width;
} else {
lines.push(std::mem::take(&mut current));
current.push_str(word);
current_width = word_width;
}
}
lines.push(current);
}
lines
}
fn paragraph_alignment(
horizontal_alignment: f32,
horizontal_mode: HorizontalTextAlignmentMode,
) -> TextAlign {
if horizontal_mode == HorizontalTextAlignmentMode::Optical {
return TextAlign::Left;
}
let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
if horizontal_alignment <= 0.0 {
TextAlign::Left
} else if horizontal_alignment >= 1.0 {
TextAlign::Right
} else {
TextAlign::Center
}
}
pub(crate) fn aligned_text_rect_for_layout(
ctx: &PaintCtx,
rect: Rect,
layout: &TextLayout,
line_height: f32,
horizontal_alignment: f32,
) -> Rect {
aligned_text_rect_for_layout_with_mode(
ctx,
rect,
layout,
line_height,
horizontal_alignment,
HorizontalTextAlignmentMode::Advance,
)
}
pub(crate) fn aligned_text_rect_for_layout_with_mode(
ctx: &PaintCtx,
rect: Rect,
layout: &TextLayout,
line_height: f32,
horizontal_alignment: f32,
horizontal_mode: HorizontalTextAlignmentMode,
) -> Rect {
let measurement = layout.measurement();
let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
let height = line_height.max(measurement.height).min(rect.height());
let y = layout
.lines()
.first()
.map(|line| {
rect.y() + (rect.height() * 0.5) - line.baseline - visual_center(ctx, measurement)
})
.unwrap_or_else(|| vertically_centered_text_rect_y(ctx, rect, measurement, height));
Rect::new(placement.rect_x, y, placement.rect_width, height)
}
fn horizontal_placement(
rect: Rect,
measurement: TextMeasurement,
horizontal_alignment: f32,
horizontal_mode: HorizontalTextAlignmentMode,
) -> HorizontalPlacement {
let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
let (width, origin_shift) = match horizontal_mode {
HorizontalTextAlignmentMode::Advance => (measurement.width, 0.0),
HorizontalTextAlignmentMode::Optical => {
let bounds = measurement.bounds;
if bounds.width().is_finite() && bounds.width() > 0.0 {
(bounds.width(), -bounds.x())
} else {
(measurement.width, 0.0)
}
}
};
let rect_width = width.min(rect.width()).max(0.0);
let rect_x = rect.x() + ((rect.width() - rect_width).max(0.0) * horizontal_alignment);
HorizontalPlacement {
rect_x,
rect_width,
origin_x: rect_x + origin_shift,
}
}
pub(crate) fn vertically_centered_text_rect_y(
ctx: &PaintCtx,
rect: Rect,
measurement: TextMeasurement,
height: f32,
) -> f32 {
let visual_center = visual_center(ctx, measurement);
let baseline = rect.y() + (rect.height() * 0.5) - visual_center;
let leading_above = ((height - (measurement.ascent + measurement.descent)).max(0.0)) * 0.5;
baseline - measurement.ascent - leading_above
}
fn visual_center(ctx: &PaintCtx, measurement: TextMeasurement) -> f32 {
let optical_centering = window_render_options(ctx.window_id())
.map(|options| options.optical_vertical_text_alignment_enabled)
.unwrap_or(true);
let top = if optical_centering {
-measurement.cap_height.unwrap_or(measurement.ascent)
} else {
-measurement.ascent
};
let bottom = if optical_centering {
measurement.descent * 0.5
} else {
measurement.descent
};
(top + bottom) * 0.5
}
#[cfg(test)]
mod tests {
use super::wrap_text_lines;
use std::{cell::RefCell, rc::Rc};
use sui_core::{Color, Point, Rect, Size};
use sui_layout::Constraints;
use sui_runtime::{Application, MeasureCtx, PaintCtx, Widget, WindowBuilder};
use sui_scene::SceneCommand;
use sui_text::{TextAlign, TextStyle};
use super::{
ELLIPSIS, ElidedLine, HorizontalTextAlignmentMode, Paragraph, TextPlacement, VerticalAlign,
aligned_text_layout_for_text_with_mode, paint_text, paint_text_line_elided,
};
use unicode_segmentation::UnicodeSegmentation;
type Paint = Box<dyn Fn(&mut PaintCtx)>;
type Measure = Box<dyn Fn(&mut MeasureCtx)>;
struct Probe {
measure: Option<Measure>,
paint: Paint,
}
impl Widget for Probe {
fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
if let Some(measure) = &self.measure {
measure(ctx);
}
constraints.clamp(Size::new(400.0, 600.0))
}
fn paint(&self, ctx: &mut PaintCtx) {
(self.paint)(ctx);
}
}
#[derive(Debug, Clone, PartialEq)]
struct Drawn {
text: String,
origin: Point,
first_baseline: f32,
size: Size,
line_starts: Vec<f32>,
}
fn render(probe: Probe) -> Vec<Drawn> {
let mut runtime = Application::new()
.window(WindowBuilder::new().title("Text").root(probe))
.build()
.unwrap();
let window_id = runtime.window_ids()[0];
let output = runtime.render(window_id).unwrap();
let registry = output.frame.text_layout_registry.as_ref();
let mut drawn = Vec::new();
output.frame.scene.visit_commands(&mut |command| {
if let SceneCommand::DrawShapedText(text) = command
&& let Some(layout) = text.resolve(registry)
{
drawn.push(Drawn {
text: layout.text().to_string(),
origin: text.origin,
first_baseline: text.origin.y + layout.lines()[0].baseline,
size: Size::new(layout.measurement().width, layout.measurement().height),
line_starts: layout.lines().iter().map(|line| line.rect.x()).collect(),
});
}
});
drawn
}
fn style() -> TextStyle {
TextStyle::new(Color::BLACK)
}
const PARAGRAPH: &str = "several words that wrap onto more than one line of text here";
#[test]
fn a_single_line_is_placed_as_before() {
for (align, fraction) in [
(TextAlign::Start, 0.0),
(TextAlign::Center, 0.5),
(TextAlign::End, 1.0),
] {
let drawn = render(Probe {
measure: None,
paint: Box::new(move |ctx| {
let rect = Rect::new(20.0, 30.0, 300.0, 44.0);
paint_text(ctx, rect, "Label", &style(), align);
let before = aligned_text_layout_for_text_with_mode(
ctx,
rect.translate(sui_core::Vector::new(0.0, 100.0)),
"Label",
&style(),
style().line_height,
fraction,
HorizontalTextAlignmentMode::Optical,
)
.unwrap();
ctx.draw_text_layout_with_color(before.origin, &before.layout, Color::BLACK);
}),
});
let [now, before] = &drawn[..] else {
panic!("two texts are drawn: {drawn:?}");
};
assert!(
(now.origin.x - before.origin.x).abs() < 0.001,
"{align:?}: {now:?} vs {before:?}"
);
assert!(
(now.first_baseline + 100.0 - before.first_baseline).abs() < 0.001,
"{align:?}: {now:?} vs {before:?}"
);
}
}
#[test]
fn several_lines_are_placed_as_a_block() {
let rect = Rect::new(10.0, 20.0, 160.0, 300.0);
let placed = |vertical| {
render(Probe {
measure: None,
paint: Box::new(move |ctx| {
paint_text(
ctx,
rect,
PARAGRAPH,
&style(),
TextPlacement::new(TextAlign::Start, vertical),
);
}),
})
.remove(0)
};
let top = placed(VerticalAlign::Top);
assert!(top.line_starts.len() > 2, "{top:?}");
let height = top.size.height;
assert!((top.origin.y - rect.y()).abs() < 0.001, "{top:?}");
let center = placed(VerticalAlign::Center);
assert!(
(center.origin.y - (rect.y() + (rect.height() - height) * 0.5)).abs() < 0.001,
"{center:?}"
);
let bottom = placed(VerticalAlign::Bottom);
assert!(
(bottom.origin.y - (rect.max_y() - height)).abs() < 0.001,
"{bottom:?}"
);
let shorter = Rect::new(10.0, 20.0, 160.0, height * 0.9);
let overflowing = render(Probe {
measure: None,
paint: Box::new(move |ctx| {
paint_text(ctx, shorter, PARAGRAPH, &style(), TextAlign::Start);
}),
})
.remove(0);
assert!(
(overflowing.origin.y - shorter.y()).abs() < 0.001,
"{overflowing:?}"
);
let one_line = Rect::new(10.0, 20.0, 160.0, 12.0);
let drawn = render(Probe {
measure: None,
paint: Box::new(move |ctx| {
paint_text(ctx, one_line, PARAGRAPH, &style(), TextAlign::Start);
paint_text(ctx, one_line, "several", &style(), TextAlign::Start);
}),
});
let [wrapped, alone] = &drawn[..] else {
panic!("two texts are drawn: {drawn:?}");
};
assert!(wrapped.line_starts.len() > 1, "{wrapped:?}");
assert!(
(wrapped.first_baseline - alone.first_baseline).abs() < 0.001,
"{wrapped:?} vs {alone:?}"
);
}
#[test]
fn centered_lines_are_centered_one_by_one() {
let drawn = render(Probe {
measure: None,
paint: Box::new(|ctx| {
paint_text(
ctx,
Rect::new(0.0, 0.0, 160.0, 300.0),
PARAGRAPH,
&style(),
TextAlign::Center,
);
}),
})
.remove(0);
let first = drawn.line_starts[0];
assert!(
drawn
.line_starts
.iter()
.any(|start| (start - first).abs() > 1.0),
"lines of different widths start at different places: {drawn:?}"
);
}
#[test]
fn a_paragraph_paints_the_layout_it_measured() {
let measured = Rc::new(RefCell::new(Paragraph::default()));
let laid_out = Rc::clone(&measured);
let painted = Rc::clone(&measured);
let drawn = render(Probe {
measure: Some(Box::new(move |ctx| {
*laid_out.borrow_mut() =
Paragraph::new(ctx, PARAGRAPH, &style(), TextAlign::Start, 160.0);
})),
paint: Box::new(move |ctx| {
let paragraph = painted.borrow();
let rect = Rect::from_origin_size(Point::new(5.0, 7.0), paragraph.size());
paragraph.paint(ctx, rect, VerticalAlign::Top);
}),
})
.remove(0);
let paragraph = measured.borrow();
assert!(paragraph.line_count() > 2);
assert_eq!(drawn.text, PARAGRAPH);
assert_eq!(drawn.size, paragraph.size());
assert!((drawn.origin.y - 7.0).abs() < 0.001, "{drawn:?}");
}
fn fit(texts: &[&str], widths: &[f32]) -> Vec<(String, f32, ElidedLine)> {
let fitted = Rc::new(RefCell::new(Vec::new()));
let results = Rc::clone(&fitted);
let texts = texts
.iter()
.map(|text| text.to_string())
.collect::<Vec<_>>();
let widths = widths.to_vec();
render(Probe {
measure: Some(Box::new(move |ctx| {
let mut results = results.borrow_mut();
results.clear();
for text in &texts {
for &width in &widths {
let line = ElidedLine::new(ctx, text, &style(), width);
results.push((text.clone(), width, line));
}
}
})),
paint: Box::new(|_| {}),
});
fitted.take()
}
fn full_width(text: &str) -> f32 {
fit(&[text], &[f32::INFINITY])[0].2.width()
}
#[test]
fn an_elided_line_keeps_text_that_fits() {
let text = "Channels";
let width = full_width(text);
for max_width in [width, width + 40.0, f32::INFINITY] {
let (_, _, line) = &fit(&[text], &[max_width])[0];
assert_eq!(line.text(), text);
assert!(!line.is_elided());
assert!((line.width() - width).abs() < 0.001, "{line:?}");
}
}
#[test]
fn an_elided_line_cuts_between_characters_and_ends_in_an_ellipsis() {
let texts = [
"The user asks to reply exactly V5_OK",
"Cafe\u{301} cre\u{300}me bru\u{302}le\u{301}e",
"\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467} family \u{1F44D}\u{1F3FD} ok",
"\u{5E9}\u{5DC}\u{5D5}\u{5DD} \u{5E2}\u{5D5}\u{5DC}\u{5DD} \u{5D8}\u{5D5}\u{5D1}",
"Mixed \u{5E2}\u{5D1}\u{5E8}\u{5D9}\u{5EA} and English text",
];
let ellipsis = full_width(ELLIPSIS);
let widths = (0..=60).map(|step| step as f32 * 6.0).collect::<Vec<_>>();
for (text, max_width, line) in fit(&texts, &widths) {
let width = full_width(&text);
if !line.is_elided() {
assert!(
width <= max_width + 0.01,
"{text:?} in {max_width}: {line:?}"
);
assert_eq!(line.text(), text);
continue;
}
assert!(width > max_width, "{text:?} in {max_width} fits: {line:?}");
if max_width < ellipsis {
let first = text.graphemes(true).next().unwrap();
assert_eq!(line.text(), first, "{text:?} in {max_width}");
continue;
}
assert!(
line.width() <= max_width + 0.01,
"{text:?} in {max_width}: {line:?}"
);
let start = line
.text()
.strip_suffix(ELLIPSIS)
.unwrap_or_else(|| panic!("{text:?} in {max_width}: {line:?}"));
assert!(text.starts_with(start), "{text:?} in {max_width}: {line:?}");
assert!(
text.grapheme_indices(true)
.any(|(index, _)| index == start.len())
|| start.is_empty(),
"{text:?} in {max_width} is cut inside a character: {line:?}"
);
assert_eq!(start, start.trim_end(), "{text:?} in {max_width}: {line:?}");
}
}
#[test]
fn an_elided_line_keeps_as_many_characters_as_fit() {
let text = "abcdefghijklmnopqrstuvwxyz";
let width = full_width(text);
for (_, max_width, line) in fit(&[text], &[width * 0.3, width * 0.6, width - 1.0]) {
let kept = line.text().strip_suffix(ELLIPSIS).unwrap();
let one_more = format!("{}{ELLIPSIS}", &text[..kept.len() + 1]);
assert!(
full_width(&one_more) > max_width,
"one more character would have fit in {max_width}: {line:?}"
);
}
}
#[test]
fn an_elided_line_shows_the_first_line_of_several() {
let (_, _, line) = &fit(&["First line\nSecond line"], &[f32::INFINITY])[0];
assert_eq!(line.text(), "First line\u{2026}");
assert!(line.is_elided());
}
#[test]
fn a_line_too_narrow_for_an_ellipsis_shows_its_first_character_clipped() {
let rect = Rect::new(20.0, 30.0, 2.0, 20.0);
let clips = Rc::new(RefCell::new(Vec::new()));
let mut runtime = Application::new()
.window(WindowBuilder::new().title("Text").root(Probe {
measure: None,
paint: Box::new(move |ctx| {
paint_text_line_elided(ctx, rect, "Channels", &style(), TextAlign::Start);
}),
}))
.build()
.unwrap();
let window_id = runtime.window_ids()[0];
let output = runtime.render(window_id).unwrap();
let registry = output.frame.text_layout_registry.as_ref();
let mut stack = Vec::new();
output
.frame
.scene
.visit_commands(&mut |command| match command {
SceneCommand::PushClip { rect } => stack.push(*rect),
SceneCommand::PopClip => {
stack.pop();
}
SceneCommand::DrawShapedText(text) => {
let layout = text.resolve(registry).unwrap();
clips
.borrow_mut()
.push((layout.text().to_string(), stack.last().copied()));
}
_ => {}
});
let [(text, Some(clip))] = &clips.borrow()[..] else {
panic!("one clipped text is drawn: {:?}", clips.borrow());
};
assert_eq!(text, "C");
assert_eq!((clip.x(), clip.width()), (rect.x(), rect.width()));
assert!(
clip.y() < rect.y() && clip.max_y() > rect.max_y(),
"{clip:?}"
);
}
#[test]
fn wrap_text_lines_preserves_newlines_and_keeps_long_words() {
let lines = wrap_text_lines("alpha beta\nsuperlongword gamma", 10.0, |text| {
text.chars().count() as f32
});
assert_eq!(
lines,
vec![
"alpha beta".to_string(),
"superlongword".to_string(),
"gamma".to_string(),
]
);
}
}