Merge craft/line-breaker

# Conflicts:
#	crates/epaint/src/text/text_layout.rs
This commit is contained in:
aiongg committed 2026-10-21 06:54:35 +00:00
commit 8a7d419396
8 files changed
+690 -115

No files matched your search

+60 -1
View File
@@ -11,7 +11,7 @@ use epaint::{
mutex::RwLock,
stats::PaintStats,
tessellator,
text::{FontInsert, FontPriority, Fonts, FontsView, ViewportKey},
text::{FontInsert, FontPriority, Fonts, FontsView, LineBreaker, ViewportKey},
vec2,
};
@@ -405,6 +405,7 @@ struct ContextImpl {
glyph_rasterizers: Vec<GlyphRasterizer>,
font_providers: Vec<Arc<dyn FontProvider>>,
missing_glyph_policy: MissingGlyphPolicy,
line_breaker: Option<Arc<dyn LineBreaker>>,
/// Set when the rasterizers or providers change, acted on at the start of the next pass.
///
@@ -641,6 +642,9 @@ impl ContextImpl {
fonts.set_glyph_rasterizers(self.glyph_rasterizers.clone());
fonts
});
if let Some(line_breaker) = &self.line_breaker {
fonts.set_line_breaker(Arc::clone(line_breaker));
}
{
profiling::scope!("Fonts::begin_pass");
@@ -905,6 +909,18 @@ impl Context {
}
}
/// Find where rows of text may end with this [`LineBreaker`],
/// e.g. one that knows where Thai words end, or the Japanese kinsoku rules.
///
/// The default is [`crate::text::SimpleLineBreaker`].
///
/// The line breaker takes effect at the start of the next pass.
pub fn set_line_breaker(&self, line_breaker: Arc<dyn LineBreaker>) {
self.write(|ctx| ctx.line_breaker = Some(line_breaker));
self.apply_font_changes_now_if_unused();
self.request_repaint();
}
/// See [`Self::set_missing_glyph_policy`].
pub fn missing_glyph_policy(&self) -> MissingGlyphPolicy {
self.read(|ctx| ctx.missing_glyph_policy)
@@ -5174,6 +5190,49 @@ mod test {
output.drop_without_applying_deltas();
}
/// The line breaker set on the context decides where text wraps, from the next pass on.
#[test]
fn test_line_breaker_is_used_for_layout() {
use crate::text::{LineBreak, LineBreaker};
use epaint::{Color32, FontId};
/// Rows may only end before byte `self.0`.
struct OnlyAt(usize);
impl LineBreaker for OnlyAt {
fn line_breaks(&self, _text: &str, _language: Option<&str>, out: &mut Vec<LineBreak>) {
out.push(LineBreak::soft(self.0));
}
}
fn rows(ctx: &Context) -> Vec<String> {
let mut rows = Vec::new();
let output = ctx.run_ui(Default::default(), |ui| {
let font_id = FontId::default();
let width = ui.fonts_mut(|fonts| {
let galley = fonts.layout_no_wrap(
"abc def ".to_owned(),
font_id.clone(),
Color32::WHITE,
);
galley.size().x + 1.0
});
let galley = ui.fonts_mut(|fonts| {
fonts.layout("abc def ghi".to_owned(), font_id, Color32::WHITE, width)
});
rows = galley.rows.iter().map(|row| row.row.text()).collect();
});
output.drop_without_applying_deltas();
rows
}
let ctx = Context::default();
ctx.set_fonts(FontDefinitions::empty());
assert_eq!(rows(&ctx), ["abc def ", "ghi"]);
ctx.set_line_breaker(alloc::sync::Arc::new(OnlyAt(3)));
assert_eq!(rows(&ctx), ["abc", " def ghi"]);
}
#[test]
fn test_root_ui_with_begin_and_end_pass() {
let ctx = Context::default();
+2 -1
View File
@@ -473,7 +473,8 @@ pub mod text {
pub use crate::text_selection::CCursorRange;
pub use epaint::text::{
ByteIndex, ByteRange, CharIndex, CharRange, FontData, FontDefinitions, FontFamily, Fonts,
Galley, LayoutJob, LayoutSection, TextFormat, TextWrapping, cursor::CCursor,
Galley, LayoutJob, LayoutSection, LineBreak, LineBreakKind, LineBreaker, SimpleLineBreaker,
TextFormat, TextWrapping, cursor::CCursor,
};
}
+28 -2
View File
@@ -4,8 +4,8 @@ use crate::{
Color32, ColorImage, TextureAtlas,
text::{
FontDefinitions, FontFamily, FontId, FontInsert, FontPriority, FontProvider, Galley,
GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest, LayoutJob, RasterizedGlyph,
TextOptions, VariationCoords,
GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest, LayoutJob, LineBreaker,
RasterizedGlyph, SimpleLineBreaker, TextOptions, VariationCoords,
face_store::{FaceStore, FontFaceKey},
family::{Family, FamilyKey},
font_face::{FontFace, GlyphInfo, ShapedCluster, ShapedGlyph},
@@ -147,6 +147,29 @@ impl Fonts {
self.fonts.discovered_fonts()
}
/// Find where rows may end with this [`LineBreaker`]. The default is [`SimpleLineBreaker`].
#[inline]
pub fn with_line_breaker(mut self, line_breaker: Arc<dyn LineBreaker>) -> Self {
self.set_line_breaker(line_breaker);
self
}
/// Find where rows may end with this [`LineBreaker`]. The default is [`SimpleLineBreaker`].
///
/// Setting the one already in use is a no-op, so this is safe to call every frame.
pub fn set_line_breaker(&mut self, line_breaker: Arc<dyn LineBreaker>) {
if !Arc::ptr_eq(&self.fonts.line_breaker, &line_breaker) {
self.fonts.line_breaker = line_breaker;
self.galley_caches.clear();
}
}
/// See [`Self::set_line_breaker`].
#[inline]
pub fn line_breaker(&self) -> &Arc<dyn LineBreaker> {
&self.fonts.line_breaker
}
/// What to do with characters that nothing can draw. See [`MissingGlyphPolicy`].
#[inline]
pub fn with_missing_glyph_policy(mut self, policy: MissingGlyphPolicy) -> Self {
@@ -499,6 +522,8 @@ pub(crate) struct FontsImpl {
missing_glyph_policy: MissingGlyphPolicy,
pub(crate) line_breaker: Arc<dyn LineBreaker>,
/// Draws the synthetic tofu box for families that have no font at all.
///
/// Kept as a [`GlyphRasterizer`] so its glyphs share the atlas cache with the other rasterized glyphs.
@@ -519,6 +544,7 @@ impl FontsImpl {
glyph_rasterizers: Vec::new(),
font_providers: Default::default(),
missing_glyph_policy: Default::default(),
line_breaker: Arc::new(SimpleLineBreaker),
synthetic_tofu: GlyphRasterizer::new(
"epaint::synthetic_tofu",
|request: &GlyphRasterizerRequest<'_>| Some(synthetic_tofu(request.font_size_px)),
+1
View File
@@ -180,6 +180,7 @@ impl GalleyCache {
},
round_output_to_gui: job.round_output_to_gui,
keep_trailing_whitespace: job.keep_trailing_whitespace,
language: job.language.clone(),
};
// Add overlapping sections:
+159
View File
@@ -0,0 +1,159 @@
//! Where a row of text may end. See [`LineBreaker`].
use super::unicode::{is_cjk, is_cjk_break_allowed};
/// A place where a row of text may end: the next row starts at byte [`Self::offset`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LineBreak {
/// Byte offset into the paragraph text where the next row starts.
///
/// Must be on a char boundary. `0` and the length of the text mean nothing and are ignored.
pub offset: usize,
pub kind: LineBreakKind,
}
impl LineBreak {
/// The row must end here.
#[inline]
pub fn hard(offset: usize) -> Self {
Self {
offset,
kind: LineBreakKind::Hard,
}
}
/// The row may end here.
#[inline]
pub fn soft(offset: usize) -> Self {
Self::soft_with_penalty(offset, 0)
}
/// The row may end here, if no soft break with a lower `penalty` fits on the row.
#[inline]
pub fn soft_with_penalty(offset: usize, penalty: u8) -> Self {
Self {
offset,
kind: LineBreakKind::Soft { penalty },
}
}
}
/// See [`LineBreak`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LineBreakKind {
/// The row must end here, as after U+2028 LINE SEPARATOR (UAX #14 mandatory break).
///
/// Honoured only right after a character of UAX #14 class BK, CR, LF or NL,
/// and only when [`crate::text::LayoutJob::break_on_newline`] is set.
/// Anywhere else it is a soft break with penalty `0`.
Hard,
/// The row may end here.
///
/// A row that is too wide ends at the last soft break on it with the lowest `penalty`.
/// UAX #14 break opportunities all have penalty `0`;
/// higher penalties are for fallbacks such as breaking after a `-` in a URL.
Soft { penalty: u8 },
}
/// Finds where rows of text may end: UAX #14 line breaking, dictionary or model-based word
/// breaking for Thai, Khmer and the like, kinsoku rules for Japanese, and so on.
///
/// When a word is wider than the wrap width and there is no break opportunity in it,
/// epaint breaks it between grapheme clusters (UAX #29), so an emoji ZWJ sequence or a letter
/// with its marks stays whole. With [`crate::text::TextWrapping::break_anywhere`], a row ends
/// at its last grapheme cluster boundary that fits, wherever the soft breaks are.
///
/// The default is [`SimpleLineBreaker`]. Install another with
/// [`crate::text::Fonts::set_line_breaker`] (`egui::Context::set_line_breaker` in egui).
///
/// ## Example
/// A line breaker on top of `craft_text::segment`, whose `Break::offset` is also the byte
/// offset where the next line starts:
///
/// ```ignore
/// use epaint::text::{LineBreak, LineBreaker};
///
/// struct CraftLineBreaker;
///
/// impl LineBreaker for CraftLineBreaker {
/// fn line_breaks(&self, text: &str, language: Option<&str>, out: &mut Vec<LineBreak>) {
/// let options = craft_text::segment::Options::for_language(language);
/// out.extend(
/// craft_text::segment::line_breaks(text, &options)
/// .into_iter()
/// .map(|b| {
/// if b.mandatory {
/// LineBreak::hard(b.offset)
/// } else {
/// LineBreak::soft(b.offset)
/// }
/// }),
/// );
/// }
/// }
///
/// ctx.set_line_breaker(std::sync::Arc::new(CraftLineBreaker));
/// ```
pub trait LineBreaker: Send + Sync {
/// Append to `out` the places where a row of `text` may end.
///
/// `text` is one paragraph: when [`crate::text::LayoutJob::break_on_newline`] is set
/// (the default) it has no `\n`. `language` is [`crate::text::LayoutJob::language`],
/// a BCP 47 tag such as `"th"` or `"ja-JP"`, if the job has one.
///
/// The breaks may come in any order. A break that isn't on a char boundary is ignored.
fn line_breaks(&self, text: &str, language: Option<&str>, out: &mut Vec<LineBreak>);
}
/// The default [`LineBreaker`]: a few rules that work for most European languages and
/// for Chinese and Japanese, with no language data.
///
/// * After whitespace other than a no-break space.
/// * Between two CJK ideographs or kana, unless the next char may not start a row
/// (closing brackets and punctuation, small kana, `ー` and the like).
/// * Before a CJK ideograph or kana.
/// * With penalty `1`, after a `-`.
/// * With penalty `2`, after other ASCII punctuation, e.g. in URLs.
///
/// It does not know where Thai, Lao, Khmer or Burmese words end, so text in those scripts
/// wraps between grapheme clusters.
#[derive(Clone, Copy, Debug, Default)]
pub struct SimpleLineBreaker;
impl LineBreaker for SimpleLineBreaker {
fn line_breaks(&self, text: &str, _language: Option<&str>, out: &mut Vec<LineBreak>) {
const NON_BREAKING_SPACE: char = '\u{A0}';
let mut chars = text.char_indices().peekable();
while let Some((_, chr)) = chars.next() {
let Some(&(next_offset, next)) = chars.peek() else {
break; // The end of the text is no break opportunity.
};
let penalty = if (chr.is_whitespace() && chr != NON_BREAKING_SPACE)
|| (is_cjk(chr) && is_cjk_break_allowed(next))
{
0
} else if chr == '-' {
1
} else if chr.is_ascii_punctuation() {
2
} else if is_cjk(next) {
0
} else {
continue;
};
out.push(LineBreak::soft_with_penalty(next_offset, penalty));
}
}
}
/// A character after which UAX #14 requires a line break (classes BK, CR, LF and NL).
///
/// `\r` is one only when it isn't followed by `\n`; that is up to the [`LineBreaker`].
pub(crate) fn is_mandatory_break(chr: char) -> bool {
matches!(
chr,
'\n' | '\r' | '\u{0B}' | '\u{0C}' | '\u{85}' | '\u{2028}' | '\u{2029}'
)
}
+2
View File
@@ -15,6 +15,7 @@ mod glyph_atlas;
mod glyph_rasterizer;
pub mod grapheme;
mod index;
mod line_break;
mod styled_metrics;
mod text_layout;
mod text_layout_types;
@@ -32,6 +33,7 @@ pub use {
has_emoji_presentation,
},
index::{ByteIndex, ByteRange, ByteRangeExt, CharIndex, CharRange, CharRangeExt},
line_break::{LineBreak, LineBreakKind, LineBreaker, SimpleLineBreaker},
text_layout_types::*,
};
+429 -111
View File
@@ -14,16 +14,19 @@ use crate::{
face_store::FontFaceKey,
fonts::FontsImpl,
styled_metrics::StyledMetrics,
unicode::{is_cjk, is_cjk_break_allowed, is_combining_mark},
unicode::{is_cjk, is_combining_mark},
},
};
use unicode_segmentation::UnicodeSegmentation as _;
use super::{
ByteRangeExt as _, FallbackAlign, Galley, Glyph, LayoutJob, LayoutSection, PlacedRow, Row,
RowVisuals, TextDirection, VariationCoords,
ByteRangeExt as _, FallbackAlign, Galley, Glyph, LayoutJob, LayoutSection, LineBreakKind,
LineBreaker, PlacedRow, Row, RowVisuals, TextDirection, VariationCoords,
family::FamilyKey,
font_face::{ClusterGlyph, FontFace, GlyphInfo, ShapedCluster, ShapedGlyph},
glyph_atlas::{GlyphAllocation, OutlineGlyph, RasterGlyphAllocation},
line_break::is_mandatory_break,
};
// ----------------------------------------------------------------------------
@@ -139,7 +142,13 @@ pub(crate) fn layout(fonts: &mut FontsImpl, pixels_per_point: f32, job: Arc<Layo
let intrinsic_size = calculate_intrinsic_size(point_scale, &job, &paragraphs);
let mut elided = false;
let mut rows = rows_from_paragraphs(paragraphs, &job, pixels_per_point, &mut elided);
let mut rows = rows_from_paragraphs(
paragraphs,
&job,
pixels_per_point,
fonts.line_breaker.as_ref(),
&mut elided,
);
if elided && let Some(last_placed) = rows.last_mut() {
let last_row = Arc::make_mut(&mut last_placed.row);
replace_last_glyph_with_overflow_character(fonts, pixels_per_point, &job, last_row);
@@ -171,7 +180,13 @@ pub(crate) fn layout(fonts: &mut FontsImpl, pixels_per_point: f32, job: Arc<Layo
job.halign
};
let is_last_row = i + 1 == num_rows;
let justify_row = justify && !placed_row.ends_with_newline && !is_last_row;
let ends_with_hard_break = placed_row
.row
.glyphs
.last()
.is_some_and(|glyph| is_mandatory_break(glyph.chr));
let justify_row =
justify && !placed_row.ends_with_newline && !ends_with_hard_break && !is_last_row;
if justify || halign != Align::LEFT {
halign_and_justify_row(
point_scale,
@@ -881,6 +896,7 @@ fn rows_from_paragraphs(
paragraphs: Vec<Paragraph>,
job: &LayoutJob,
pixels_per_point: f32,
line_breaker: &dyn LineBreaker,
elided: &mut bool,
) -> Vec<PlacedRow> {
let num_paragraphs = paragraphs.len();
@@ -913,8 +929,18 @@ fn rows_from_paragraphs(
// `last_glyph.max_x()`, so that side-by-side galleys have the same
// spacing as characters within a single galley.
let paragraph_width = paragraph.cursor_x_px / pixels_per_point;
if paragraph_width <= job.effective_wrap_width() {
// Early-out optimization: the whole paragraph fits on one row.
let fits = paragraph_width <= job.effective_wrap_width();
let may_break_hard =
job.break_on_newline && paragraph.glyphs.iter().any(|g| is_mandatory_break(g.chr));
// Early-out optimization: don't look for breaks in a paragraph that fits on one row.
let breaks = (!fits || may_break_hard)
.then(|| break_opportunities(&paragraph, job, line_breaker))
.filter(|breaks| !fits || breaks.iter().any(|after| after.hard));
if let Some(breaks) = breaks {
line_break(&paragraph, &breaks, job, &mut rows, elided);
let placed_row = rows.last_mut().unwrap();
placed_row.ends_with_newline = !is_last_paragraph;
} else {
rows.push(PlacedRow {
pos: pos2(0.0, f32::NAN),
row: Arc::new(Row {
@@ -927,10 +953,6 @@ fn rows_from_paragraphs(
}),
ends_with_newline: !is_last_paragraph,
});
} else {
line_break(&paragraph, job, &mut rows, elided);
let placed_row = rows.last_mut().unwrap();
placed_row.ends_with_newline = !is_last_paragraph;
}
}
}
@@ -938,8 +960,94 @@ fn rows_from_paragraphs(
rows
}
/// Where a row may end after a glyph.
#[derive(Clone, Copy, Default)]
struct BreakAfter {
/// The lowest penalty of the soft breaks the [`LineBreaker`] found here.
penalty: Option<u8>,
/// The row must end here.
hard: bool,
/// The next glyph starts a new grapheme cluster.
cluster_end: bool,
}
/// What may follow each glyph of `paragraph`: one entry per glyph.
fn break_opportunities(
paragraph: &Paragraph,
job: &LayoutJob,
line_breaker: &dyn LineBreaker,
) -> Vec<BreakAfter> {
// There is one glyph per char, so the text of the glyphs is the text of the paragraph.
let text: String = paragraph.glyphs.iter().map(|glyph| glyph.chr).collect();
let glyph_starts: Vec<usize> = text.char_indices().map(|(offset, _)| offset).collect();
let glyph_before = |offset: usize| match glyph_starts.binary_search(&offset) {
Ok(next_glyph) => next_glyph.checked_sub(1),
Err(_) => None, // Not on a char boundary, or the end of the text.
};
let mut after = vec![BreakAfter::default(); glyph_starts.len()];
for (offset, _) in text.grapheme_indices(true) {
if let Some(glyph) = glyph_before(offset) {
after[glyph].cluster_end = true;
}
}
let mut breaks = Vec::new();
line_breaker.line_breaks(&text, job.language.as_deref(), &mut breaks);
for line_break in breaks {
let Some(glyph) = glyph_before(line_break.offset) else {
continue;
};
let penalty = match line_break.kind {
LineBreakKind::Hard
if job.break_on_newline && is_mandatory_break(paragraph.glyphs[glyph].chr) =>
{
after[glyph].hard = true;
continue;
}
LineBreakKind::Hard => 0,
LineBreakKind::Soft { penalty } => penalty,
};
let entry = &mut after[glyph].penalty;
*entry = Some(entry.map_or(penalty, |p| p.min(penalty)));
}
after
}
/// The glyphs `range` of `paragraph` as a row, moved left by `row_start_x`.
fn row_of_glyphs(paragraph: &Paragraph, range: Range<usize>, row_start_x: f32) -> PlacedRow {
let glyphs: Vec<Glyph> = paragraph.glyphs[range]
.iter()
.copied()
.map(|mut glyph| {
glyph.pos.x -= row_start_x;
glyph
})
.collect();
let section_index_at_start = glyphs[0].section_index;
let paragraph_max_x = glyphs.last().unwrap().max_x();
PlacedRow {
pos: pos2(0.0, f32::NAN),
row: Arc::new(Row {
section_index_at_start,
glyphs,
rtl_paragraph: paragraph.rtl,
visual_order: Vec::new(),
visuals: Default::default(),
size: vec2(paragraph_max_x, 0.0),
}),
ends_with_newline: false,
}
}
/// `breaks` has one entry per glyph of `paragraph`, see [`break_opportunities`].
fn line_break(
paragraph: &Paragraph,
breaks: &[BreakAfter],
job: &LayoutJob,
out_rows: &mut Vec<PlacedRow>,
elided: &mut bool,
@@ -953,7 +1061,7 @@ fn line_break(
let mut row_start_x = 0.0;
let mut row_start_idx = 0;
for i in 0..paragraph.glyphs.len() {
for (i, &after) in breaks.iter().enumerate() {
if job.wrap.max_rows <= out_rows.len() {
*elided = true;
break;
@@ -985,30 +1093,11 @@ fn line_break(
first_row_indentation = 0.0;
} else if let Some(last_kept_index) = row_break_candidates.get(job.wrap.break_anywhere)
{
let glyphs: Vec<Glyph> = paragraph.glyphs[row_start_idx..=last_kept_index]
.iter()
.copied()
.map(|mut glyph| {
glyph.pos.x -= row_start_x;
glyph
})
.collect();
let section_index_at_start = glyphs[0].section_index;
let paragraph_max_x = glyphs.last().unwrap().max_x();
out_rows.push(PlacedRow {
pos: pos2(0.0, f32::NAN),
row: Arc::new(Row {
section_index_at_start,
glyphs,
rtl_paragraph: paragraph.rtl,
visual_order: Vec::new(),
visuals: Default::default(),
size: vec2(paragraph_max_x, 0.0),
}),
ends_with_newline: false,
});
out_rows.push(row_of_glyphs(
paragraph,
row_start_idx..last_kept_index + 1,
row_start_x,
));
// Start a new row:
row_start_idx = last_kept_index + 1;
@@ -1019,7 +1108,18 @@ fn line_break(
}
}
row_break_candidates.add(i, &paragraph.glyphs[i..]);
if after.hard && i + 1 < paragraph.glyphs.len() {
if job.wrap.max_rows <= out_rows.len() {
*elided = true;
break;
}
out_rows.push(row_of_glyphs(paragraph, row_start_idx..i + 1, row_start_x));
row_start_idx = i + 1;
row_start_x = paragraph.glyphs[row_start_idx].pos.x;
row_break_candidates.forget_before_idx(row_start_idx);
} else {
row_break_candidates.add(i, after);
}
}
if row_start_idx < paragraph.glyphs.len() {
@@ -1726,62 +1826,33 @@ fn add_row_hline(
// ----------------------------------------------------------------------------
/// Keeps track of good places to break a long row of text.
/// Will focus primarily on spaces, secondarily on things like `-`
#[derive(Clone, Copy, Default)]
#[derive(Clone, Default)]
struct RowBreakCandidates {
/// Breaking at ` ` or other whitespace
/// is always the primary candidate.
space: Option<usize>,
/// The last soft break of each penalty, by increasing penalty.
soft: Vec<(u8, usize)>,
/// Logograms (single character representing a whole word) or kana (Japanese hiragana and katakana) are good candidates for line break.
cjk: Option<usize>,
/// Breaking anywhere before a CJK character is acceptable too.
pre_cjk: Option<usize>,
/// Breaking at a dash is a super-
/// good idea.
dash: Option<usize>,
/// This is nicer for things like URLs, e.g. www.
/// example.com.
punctuation: Option<usize>,
/// Breaking after just random character is some
/// times necessary.
/// The last break between two grapheme clusters, for when a word doesn't fit on a row.
any: Option<usize>,
}
impl RowBreakCandidates {
fn add(&mut self, index: usize, glyphs: &[Glyph]) {
let chr = glyphs[0].chr;
const NON_BREAKING_SPACE: char = '\u{A0}';
if chr.is_whitespace() && chr != NON_BREAKING_SPACE {
self.space = Some(index);
} else if is_cjk(chr) && (glyphs.len() == 1 || is_cjk_break_allowed(glyphs[1].chr)) {
self.cjk = Some(index);
} else if chr == '-' {
self.dash = Some(index);
} else if chr.is_ascii_punctuation() {
self.punctuation = Some(index);
} else if glyphs.len() > 1 && is_cjk(glyphs[1].chr) {
self.pre_cjk = Some(index);
fn add(&mut self, index: usize, after: BreakAfter) {
if let Some(penalty) = after.penalty {
match self.soft.binary_search_by_key(&penalty, |&(p, _)| p) {
Ok(i) => self.soft[i].1 = index,
Err(i) => self.soft.insert(i, (penalty, index)),
}
}
if after.cluster_end {
self.any = Some(index);
}
self.any = Some(index);
}
fn word_boundary(&self) -> Option<usize> {
[self.space, self.cjk, self.pre_cjk]
.into_iter()
.max()
.flatten()
}
fn has_good_candidate(&self, break_anywhere: bool) -> bool {
if break_anywhere {
self.any.is_some()
} else {
self.word_boundary().is_some()
self.soft.first().is_some_and(|&(penalty, _)| penalty == 0)
}
}
@@ -1789,39 +1860,14 @@ impl RowBreakCandidates {
if break_anywhere {
self.any
} else {
self.word_boundary()
.or(self.dash)
.or(self.punctuation)
.or(self.any)
self.soft.first().map(|&(_, index)| index).or(self.any)
}
}
fn forget_before_idx(&mut self, index: usize) {
let Self {
space,
cjk,
pre_cjk,
dash,
punctuation,
any,
} = self;
if space.is_some_and(|s| s < index) {
*space = None;
}
if cjk.is_some_and(|s| s < index) {
*cjk = None;
}
if pre_cjk.is_some_and(|s| s < index) {
*pre_cjk = None;
}
if dash.is_some_and(|s| s < index) {
*dash = None;
}
if punctuation.is_some_and(|s| s < index) {
*punctuation = None;
}
if any.is_some_and(|s| s < index) {
*any = None;
self.soft.retain(|&(_, i)| index <= i);
if self.any.is_some_and(|i| i < index) {
self.any = None;
}
}
}
@@ -1854,8 +1900,6 @@ fn segment_into_runs(
levels: Option<&[u8]>,
out: &mut Vec<TextRun>,
) {
use unicode_segmentation::UnicodeSegmentation as _;
out.clear();
for (byte_offset, grapheme_str) in text.grapheme_indices(true) {
@@ -4277,4 +4321,278 @@ mod tests {
let details: Vec<_> = glyphs.iter().map(|g| (g.chr, g.advance_width)).collect();
(galley.size().x, glyphs.len(), details)
}
// ------------------------------------------------------------------------
// Line breaking
/// Allows rows to end only at the given breaks, and remembers the language it was asked about.
#[derive(Default)]
struct BreakAt {
breaks: Vec<LineBreak>,
languages: crate::mutex::Mutex<Vec<Option<String>>>,
}
impl BreakAt {
fn soft(offsets: &[usize]) -> Self {
Self {
breaks: offsets
.iter()
.map(|&offset| LineBreak::soft(offset))
.collect(),
..Default::default()
}
}
}
impl LineBreaker for BreakAt {
fn line_breaks(&self, _text: &str, language: Option<&str>, out: &mut Vec<LineBreak>) {
self.languages.lock().push(language.map(str::to_owned));
out.extend_from_slice(&self.breaks);
}
}
/// No fonts, so every grapheme cluster is a box of the same width.
fn tofu_fonts(line_breaker: Arc<dyn LineBreaker>) -> FontsImpl {
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::empty());
fonts.line_breaker = line_breaker;
fonts
}
/// `job.text` wrapped at `glyphs` and a half glyph widths: the text of each row.
fn wrapped_rows(fonts: &mut FontsImpl, mut job: LayoutJob, glyphs: u32) -> Vec<String> {
let one = layout_simple(fonts, "x").size().x;
job.wrap.max_width = one * glyphs as f32 + 0.5 * one;
let galley = layout(fonts, 1.0, Arc::new(job));
galley.rows.iter().map(|row| row.row.text()).collect()
}
fn simple_job(text: &str) -> LayoutJob {
LayoutJob::simple(
text.to_owned(),
FontId::proportional(14.0),
Color32::WHITE,
f32::INFINITY,
)
}
/// [`SimpleLineBreaker`] wraps text where epaint always did: these rows are what
/// epaint made before line breakers could be swapped.
#[test]
fn simple_line_breaker_keeps_the_old_breaks() {
#[rustfmt::skip]
const CASES: &[(&str, bool, u32, &str)] = &[
("The quick brown fox jumps over the lazy dog", false, 3, "The| |qui|ck |bro|wn |fox| |jum|ps |ove|r |the| |laz|y |dog"),
("The quick brown fox jumps over the lazy dog", false, 5, "The |quick| |brown| fox |jumps| |over |the |lazy |dog"),
("The quick brown fox jumps over the lazy dog", false, 7, "The |quick |brown |fox |jumps |over |the |lazy |dog"),
("The quick brown fox jumps over the lazy dog", false, 10, "The quick |brown fox |jumps |over the |lazy dog"),
("The quick brown fox jumps over the lazy dog", true, 3, "The| qu|ick| br|own| fo|x j|ump|s o|ver| th|e l|azy| do|g"),
("The quick brown fox jumps over the lazy dog", true, 5, "The q|uick |brown| fox |jumps| over| the |lazy |dog"),
("The quick brown fox jumps over the lazy dog", true, 7, "The qui|ck brow|n fox j|umps ov|er the |lazy do|g"),
("The quick brown fox jumps over the lazy dog", true, 10, "The quick |brown fox |jumps over| the lazy |dog"),
("well-known self-contained hyphen-ated", false, 3, "wel|l-|kno|wn |sel|f-|con|tai|ned| |hyp|hen|-|ate|d"),
("well-known self-contained hyphen-ated", false, 5, "well-|known| |self-|conta|ined |hyphe|n-|ated"),
("well-known self-contained hyphen-ated", false, 7, "well-|known |self-|contain|ed |hyphen-|ated"),
("well-known self-contained hyphen-ated", false, 10, "well-|known |self-|contained |hyphen-|ated"),
("see www.example.com/path?q=1 or a-b.c", false, 3, "see| |www|.|exa|mpl|e.|com|/|pat|h?|q=|1 |or |a-|b.c"),
("see www.example.com/path?q=1 or a-b.c", false, 5, "see |www.|examp|le.|com/|path?|q=1 |or |a-b.c"),
("see www.example.com/path?q=1 or a-b.c", false, 7, "see |www.|example|.com/|path?q=|1 or |a-b.c"),
("see www.example.com/path?q=1 or a-b.c", false, 10, "see |www.|example.|com/path?|q=1 or |a-b.c"),
("一二三,四五六:七八九?十一二!三四五)六七八", false, 3, "一二|三,四|五六:|七八|九?十|一二!|三四|五)六|七八"),
("一二三,四五六:七八九?十一二!三四五)六七八", false, 5, "一二三,四|五六:七八|九?十一|二!三四|五)六七八"),
("一二三,四五六:七八九?十一二!三四五)六七八", false, 7, "一二三,四五|六:七八九?十|一二!三四五)|六七八"),
("一二三,四五六:七八九?十一二!三四五)六七八", false, 10, "一二三,四五六:七八|九?十一二!三四五)|六七八"),
("一二三,四五六:七八九?十一二!三四五)六七八", true, 3, "一二三|,四五|六:七|八九?|十一二|!三四|五)六|七八"),
("一二三,四五六:七八九?十一二!三四五)六七八", true, 5, "一二三,四|五六:七八|九?十一二|!三四五)|六七八"),
("一二三,四五六:七八九?十一二!三四五)六七八", true, 7, "一二三,四五六|:七八九?十一|二!三四五)六|七八"),
("一二三,四五六:七八九?十一二!三四五)六七八", true, 10, "一二三,四五六:七八|九?十一二!三四五)|六七八"),
("日本語のテキストとEnglish wordsの混在-です", false, 3, "日本語|のテキ|ストと|Eng|lis|h |wor|dsの|混在|-です"),
("日本語のテキストとEnglish wordsの混在-です", false, 5, "日本語のテ|キストと|Engli|sh |words|の混在-で|す"),
("日本語のテキストとEnglish wordsの混在-です", false, 7, "日本語のテキス|トと|English| wordsの|混在-です"),
("日本語のテキストとEnglish wordsの混在-です", false, 10, "日本語のテキストと|English |wordsの混在-で|す"),
("Supercalifragilisticexpialidocious", false, 3, "Sup|erc|ali|fra|gil|ist|ice|xpi|ali|doc|iou|s"),
("Supercalifragilisticexpialidocious", false, 5, "Super|calif|ragil|istic|expia|lidoc|ious"),
("Supercalifragilisticexpialidocious", false, 7, "Superca|lifragi|listice|xpialid|ocious"),
("Supercalifragilisticexpialidocious", false, 10, "Supercalif|ragilistic|expialidoc|ious"),
("a\u{a0}b c\u{a0}d e\u{a0}f\u{a0}g", false, 3, "a\u{a0}b| |c\u{a0}d| |e\u{a0}f|\u{a0}g"),
("a\u{a0}b c\u{a0}d e\u{a0}f\u{a0}g", false, 5, "a\u{a0}b |c\u{a0}d |e\u{a0}f\u{a0}g"),
("a\u{a0}b c\u{a0}d e\u{a0}f\u{a0}g", false, 10, "a\u{a0}b c\u{a0}d |e\u{a0}f\u{a0}g"),
("a\u{a0}b c\u{a0}d e\u{a0}f\u{a0}g", true, 3, "a\u{a0}b| c\u{a0}|d e|\u{a0}f\u{a0}|g"),
];
let mut fonts = tofu_fonts(Arc::new(SimpleLineBreaker));
for &(text, break_anywhere, glyphs, expected) in CASES {
let mut job = simple_job(text);
job.wrap.break_anywhere = break_anywhere;
let rows = wrapped_rows(&mut fonts, job, glyphs).join("|");
assert_eq!(
rows, expected,
"{text:?} at {glyphs} glyphs, break_anywhere: {break_anywhere}"
);
}
}
#[test]
fn rows_end_only_where_the_line_breaker_allows() {
// Allowed: before "def" and before "ghi". Not at the spaces.
let text = "abc def ghi jkl";
let mut fonts = tofu_fonts(Arc::new(BreakAt::soft(&[4, 8])));
assert_eq!(
wrapped_rows(&mut fonts, simple_job(text), 9),
["abc def ", "ghi jkl"]
);
assert_eq!(
wrapped_rows(&mut fonts, simple_job(text), 5),
["abc ", "def ", "ghi j", "kl"]
);
// A lower penalty wins over a later break:
let mut fonts = tofu_fonts(Arc::new(BreakAt {
breaks: vec![LineBreak::soft(4), LineBreak::soft_with_penalty(8, 1)],
..Default::default()
}));
assert_eq!(
wrapped_rows(&mut fonts, simple_job("abc def ghi"), 9),
["abc ", "def ghi"]
);
// Too long a piece breaks between grapheme clusters:
let mut fonts = tofu_fonts(Arc::new(BreakAt::soft(&[])));
assert_eq!(
wrapped_rows(&mut fonts, simple_job("abcdefgh"), 3),
["abc", "def", "gh"]
);
}
#[test]
fn line_breaker_gets_the_paragraph_and_its_language() {
let line_breaker = Arc::new(BreakAt::soft(&[]));
let mut fonts = tofu_fonts(Arc::<BreakAt>::clone(&line_breaker));
let mut job = simple_job("ภาษาไทย ภาษาไทย");
job.language = Some("th".to_owned());
wrapped_rows(&mut fonts, job, 5);
assert_eq!(*line_breaker.languages.lock(), [Some("th".to_owned())]);
// A paragraph that fits on one row has no breaks to look for:
line_breaker.languages.lock().clear();
wrapped_rows(&mut fonts, simple_job("ไทย"), 5);
assert!(line_breaker.languages.lock().is_empty());
}
#[test]
fn hard_breaks_end_the_row() {
let text = "abc\u{2028}def ghi";
let after_separator = "abc\u{2028}".len();
let line_breaker = Arc::new(BreakAt {
breaks: vec![
LineBreak::hard(after_separator),
LineBreak::hard(text.len()),
],
..Default::default()
});
let mut fonts = tofu_fonts(line_breaker);
// Even when the paragraph fits on one row:
assert_eq!(
wrapped_rows(&mut fonts, simple_job(text), 20),
["abc\u{2028}", "def ghi"]
);
// Only after a line separator:
let mut fonts = tofu_fonts(Arc::new(BreakAt {
breaks: vec![LineBreak::hard(2)],
..Default::default()
}));
assert_eq!(
wrapped_rows(&mut fonts, simple_job("abcd\u{2028}"), 20),
["abcd\u{2028}"]
);
assert_eq!(
wrapped_rows(&mut fonts, simple_job("abcd\u{2028}"), 3),
["ab", "cd\u{2028}"]
);
// Only with `break_on_newline`; otherwise it is a soft break:
let mut fonts = tofu_fonts(Arc::new(BreakAt {
breaks: vec![LineBreak::hard(after_separator)],
..Default::default()
}));
let mut job = simple_job(text);
job.break_on_newline = false;
assert_eq!(wrapped_rows(&mut fonts, job.clone(), 20), [text]);
assert_eq!(
wrapped_rows(&mut fonts, job, 6),
["abc\u{2028}", "def gh", "i"]
);
}
/// With no break opportunity in a word, the row breaks between grapheme clusters:
/// never inside an emoji ZWJ sequence, a flag, or a letter with its marks.
#[test]
fn emergency_breaks_keep_grapheme_clusters_whole() {
use crate::text::grapheme::cluster_around;
let texts = [
"👨\u{200D}👩\u{200D}👧\u{200D}👦👩\u{200D}🔬🇯🇵🇰🇷👍🏽",
"e\u{301}e\u{301}\u{323}a\u{308}o\u{302}\u{301}u\u{328}",
"ที่นี่มีน้ำใสสะอาด",
"नमस्ते क्षत्रिय",
"ကျွန်တော်မြန်မာစာ",
];
// With the default fonts, the emoji in a sequence the emoji font has no ligature for
// are glyphs of their own, each with its own width.
let line_breakers = [
Arc::new(SimpleLineBreaker) as Arc<dyn LineBreaker>,
Arc::new(BreakAt::soft(&[])),
];
for (definitions, line_breaker) in [FontDefinitions::empty(), FontDefinitions::default()]
.into_iter()
.flat_map(|definitions| line_breakers.clone().map(|lb| (definitions.clone(), lb)))
{
let mut fonts = FontsImpl::new(TextOptions::default(), definitions);
fonts.line_breaker = line_breaker;
for text in texts {
for break_anywhere in [false, true] {
for glyphs in 1..8 {
let mut job = simple_job(text);
job.wrap.break_anywhere = break_anywhere;
let rows = wrapped_rows(&mut fonts, job, glyphs);
assert_eq!(rows.concat(), text);
let mut row_start = 0;
for row in &rows[..rows.len() - 1] {
row_start += row.chars().count();
assert!(
cluster_around(text, CharIndex(row_start)).is_none(),
"{text:?} at {glyphs} glyphs: {rows:?}"
);
}
}
}
}
}
}
/// Rows that end where a line breaker says still get reordered for right-to-left text.
#[test]
fn rtl_rows_are_reordered_after_custom_breaks() {
// Letters are two bytes each. Break only before "ה", inside the second word.
let text = "אבג דהו זחט";
let before_he = "אבג ד".len();
let mut fonts = tofu_fonts(Arc::new(BreakAt::soft(&[before_he])));
let one = layout_simple(&mut fonts, "x").size().x;
let mut job = simple_job(text);
job.wrap.max_width = 6.5 * one;
let galley = layout(&mut fonts, 1.0, Arc::new(job));
let texts: Vec<String> = galley.rows.iter().map(|row| row.row.text()).collect();
assert_eq!(texts, ["אבג ד", "הו זחט"]);
for placed in &galley.rows {
assert!(placed.row.rtl_paragraph);
}
assert_visual_order(&galley.rows[0].row, &[4, 3, 2, 1, 0]);
assert_visual_order(&galley.rows[1].row, &[5, 4, 3, 2, 1, 0]);
// Right-aligned, like the rest of a right-to-left paragraph:
assert!(
(galley.rows[0].rect().right() - galley.rows[1].rect().right()).abs() < 0.01,
"{:?} {:?}",
galley.rows[0].rect(),
galley.rows[1].rect()
);
}
}
@@ -118,6 +118,12 @@ pub struct LayoutJob {
/// If `true`, trailing whitespace is included in the row width used for alignment.
/// This is desirable for text editors where the user expects to see their spaces.
pub keep_trailing_whitespace: bool,
/// The language of the text, as a BCP 47 tag (`"th"`, `"ja-JP"`), if known.
///
/// Passed to the [`crate::text::LineBreaker`], which may break rows differently
/// for some languages, e.g. Korean word by word. Default: `None` (unknown).
pub language: Option<String>,
}
impl Default for LayoutJob {
@@ -135,6 +141,7 @@ impl Default for LayoutJob {
justify: false,
round_output_to_gui: true,
keep_trailing_whitespace: false,
language: None,
}
}
}
@@ -345,6 +352,7 @@ impl core::hash::Hash for LayoutJob {
justify,
round_output_to_gui,
keep_trailing_whitespace,
language,
} = self;
text.hash(state);
@@ -358,6 +366,7 @@ impl core::hash::Hash for LayoutJob {
justify.hash(state);
round_output_to_gui.hash(state);
keep_trailing_whitespace.hash(state);
language.hash(state);
}
}