1// Laying text out: paragraphs between mandatory breaks, each given its2// direction and levels by UAX #9 (text_scripts' bidi, else left to3// right) and shaped in runs of one style and level, then filled into4// lines in the text's order at UAX #14's opportunities (spaces at a5// line's end hang past it; a word wider than a line breaks between6// clusters, and with text_scripts words of Thai, Lao, Khmer and Myanmar7// between any two graphemes), each line's glyphs put in visual order by8// their levels (L1, L2), lines stacked by their faces' metrics and9// aligned on their paragraph's side.1011import std::string;12import std::vector;13import std::option;14import std::math;1516import text;17import font::face;18import shaping::shaper;19import shaping::plan;20import shaping::opentype;21import unicode::lines;22import unicode::graphemes;23import unicode::runs;24import unicode::tables;25import unicode::properties;2627// What lines are wider than at most: any width at all.28const UNLIMITED: f32 = 1000000000.0;2930// A shaped glyph, in pixels, before lines are known.31type ShapedGlyph = struct {32 face: u32,33 glyph: u32,34 size: f32,35 advance: f32,36 dx: f32,37 dy: f32,38 cluster: u64,39 span: u32,40 space: bool,41 level: u8, // its embedding level (UAX #9)42};4344// A line's glyphs and bytes, before it is placed.45type PendingLine = struct {46 first: u64,47 last: u64, // past its last glyph48 start: u64,49 end: u64,50 paragraph_start: u64, // for an empty line's style51 wrapped: bool = false, // ended by the width, not by the paragraph52 level: u8 = 0, // its paragraph's embedding level53 bidi: bool = false, // whether its glyphs' levels may differ from 054};5556// The text being laid out, its glyphs shaped and its lines found so far.57type Typesetter = struct {58 fonts: &Fonts,59 scripts: Option<ScriptHooks>,60 text: &[u8],61 spans: &[Span],62 glyphs: Vector<ShapedGlyph>,63 lines: Vector<PendingLine>,64};6566// The text broken at `width`; the layout as wide as `width`, or with67// `fit` as its widest line unless a line was broken at the width.68pub fn lay_out(69 fonts: &Fonts,70 text: &[u8],71 spans: &[Span],72 width: f32,73 align: Align,74 fit: bool75) -> Layout {76 if (text.length() > 0xFFFFFFFF) {77 panic "pkg::alloy::text: a layout's text must be under 4 GiB";78 }79 const limit = if (width <= 0.0 || width > UNLIMITED) UNLIMITED else width;80 const breaks = line_breaks(&text);81 var t = Typesetter {82 .fonts = &fonts,83 .scripts = fonts.scripts(),84 .text = &text,85 .spans = &spans,86 .glyphs = Vector<ShapedGlyph>::with_capacity(text.length()),87 .lines = Vector<PendingLine>::empty()88 };89 if (text.length() == 0) {90 t.lines.push(PendingLine {91 .first = 0,92 .last = 0,93 .start = 0,94 .end = 0,95 .paragraph_start = 0,96 .level = t.unmarked_level(spans[0].style.direction)97 });98 }99 var start: u64 = 0;100 var b: u64 = 0; // the first break past `start`101 var previous: Option<u8> = ::None; // the paragraph before's level, which an empty one takes102 while (start < text.length()) {103 // the paragraph runs to the next mandatory break, which the text's104 // end is105 var end = start;106 for (breaks.view()[b..]) |&next| {107 if (next.mandatory && next.at > start) {108 end = next.at;109 break;110 }111 }112 const content_end = without_newline(&text, start, end);113 const first_glyph = t.glyphs.length();114 const first_line = t.lines.length();115 const direction = spans[span_at(&spans, start) to u64].style.direction;116 var levels = t.paragraph_levels(start, content_end, direction);117 if (content_end == start && is_auto(direction) && previous is ::Some |before|) {118 levels.level = before;119 }120 previous = ::Some(levels.level);121 t.shape_paragraph(start, content_end, &levels);122 t.fill_lines(&breaks.view(), first_glyph, start, content_end, limit);123 for (t.lines.items()[first_line..]) |&var line| {124 line.level = levels.level;125 line.bidi = levels.bidi;126 }127 // an empty last line after a final newline128 if (end == text.length() && content_end < end) {129 const level = if (is_auto(direction)) levels.level else t.paragraph_levels(130 end,131 end,132 direction133 ).level;134 t.lines.push(PendingLine {135 .first = t.glyphs.length(),136 .last = t.glyphs.length(),137 .start = end,138 .end = end,139 .paragraph_start = end,140 .level = level141 });142 }143 start = end;144 while (b < breaks.length() && breaks.get(b).at <= start) {145 b += 1;146 }147 }148 const fixed = limit < UNLIMITED && !(fit && !t.wrapped());149 return t.place(if (fixed) width else 0.0, align);150}151152// The paragraph's end before its line break characters.153fn without_newline(text: &[u8], start: u64, end: u64) -> u64 {154 var e = end;155 while (e > start) {156 const c = text[e - 1];157 if (c == '\n' || c == '\r' || c == 0x0B || c == 0x0C) {158 e -= 1;159 } else if (e >= start + 2 && text[e - 2] == 0xC2 && c == 0x85) {160 e -= 2;161 } else if (162 e >= start + 3163 && text[e - 3] == 0xE2164 && text[e - 2] == 0x80165 && (c == 0xA8 || c == 0xA9)166 ) {167 e -= 3;168 } else {169 break;170 }171 }172 return e;173}174175// The span covering the offset, the first when none does.176fn span_at(spans: &[Span], at: u64) -> u32 {177 for (spans, [..spans.length()]) |&s, k| {178 if (at >= s.start && at < s.end) {179 return k to u32;180 }181 }182 return 0;183}184185// The first offset past `at` where a span starts or ends, `end` when186// none is before it: between two, the span at each offset is the same.187fn next_span_edge(spans: &[Span], at: u64, end: u64) -> u64 {188 var next = end;189 for (spans) |&s| {190 if (s.start > at && s.start < next) {191 next = s.start;192 }193 if (s.end > at && s.end < next) {194 next = s.end;195 }196 }197 return next;198}199200// A style's face in the fonts.201fn face_of(self t: &Typesetter, style: &TextStyle) -> u32 {202 return t.fonts.face_for(style.family, style.weight, style.size);203}204205fn style_of(self t: &Typesetter, glyph: &ShapedGlyph) -> &TextStyle {206 return &t.spans[glyph.span to u64].style;207}208209// A paragraph's embedding level, and its bytes' levels in runs, each210// to its end; whether any byte's level may differ from 0.211exp type ParagraphLevels = struct {212 exp level: u8,213 exp runs: Vector<LevelRun>,214 exp bidi: bool,215};216217exp type LevelRun = struct {218 exp end: u64,219 exp level: u8,220};221222// The levels of the paragraph's bytes (UAX #9, text_scripts'): all 0223// without it.224fn paragraph_levels(225 self t: &Typesetter,226 start: u64,227 end: u64,228 direction: Direction229) -> ParagraphLevels {230 if (t.scripts is ::Some |&h|) {231 return (h.levels)(&t.text, start, end, direction);232 }233 var out = ParagraphLevels { .level = 0, .runs = Vector<LevelRun>::empty(), .bidi = false };234 out.runs.push(LevelRun { .end = end, .level = 0 });235 return move out;236}237238fn is_auto(direction: Direction) -> bool => direction is ::Auto || direction is ::AutoRightToLeft;239240// The level of a paragraph with no strong character: 0 without241// text_scripts.242fn unmarked_level(self t: &Typesetter, direction: Direction) -> u8 => if (243 t.scripts is ::Some && (direction is ::RightToLeft || direction is ::AutoRightToLeft)244) 1 else 0;245246// Shapes the paragraph's runs of one span and level.247fn shape_paragraph(self t: &var Typesetter, start: u64, end: u64, levels: &ParagraphLevels) {248 const text = &t.text;249 const spans = &t.spans;250 var at = start;251 var r: u64 = 0; // the level run at `at`252 while (at < end) {253 const span = span_at(&spans, at);254 var span_end = next_span_edge(&spans, at, end);255 while (span_end < end && span_at(&spans, span_end) == span) {256 span_end = next_span_edge(&spans, span_end, end);257 }258 const style = &spans[span to u64].style;259 const primary = t.face_of(&style);260 while (at < span_end) {261 while (levels.runs.get(r).end <= at) {262 r += 1;263 }264 const level = levels.runs.get(r).level;265 const run_end = min(span_end, levels.runs.get(r).end);266 for (itemize(&text, at, run_end).view()) |&run| {267 for (t.face_runs(&style, primary, &run).view()) |&piece| {268 const face = &t.fonts.face(piece.face);269 const scale = style.size / face.units_per_em;270 const plan = &t.fonts.plan(271 piece.face,272 run.script,273 &style.language.view(),274 level % 2 == 1,275 &style.features.view()276 );277 const result = shape_with(&face, &plan, &text, piece.start, piece.end);278 for (result.infos.view(), result.positions.view()) |&info, &p| {279 const cluster = info.cluster to u64;280 t.glyphs.push(ShapedGlyph {281 .face = piece.face,282 .glyph = info.glyph,283 .size = style.size,284 .advance = p.x_advance * scale,285 .dx = p.x_offset * scale,286 .dy = p.y_offset * scale,287 .cluster = cluster,288 .span = span,289 .space = text[cluster] == ' ' || text[cluster] == '\t',290 .level = level291 });292 }293 }294 }295 at = run_end;296 }297 }298}299300// A part of a run shaped in one face.301type FacePiece = struct {302 start: u64,303 end: u64,304 face: u32,305};306307// The run in the style's face, `primary`, but for the grapheme clusters308// it lacks, which fallback gives other faces (all of an emoji run's,309// which an emoji font draws when there is one, unless the style's face310// is a color font).311fn face_runs(312 self t: &Typesetter,313 style: &TextStyle,314 primary: u32,315 run: &TextRun316) -> Vector<FacePiece> {317 var out = Vector<FacePiece>::empty();318 const face = &t.fonts.face(primary);319 const text = &t.text;320 const emoji = run.emoji && !face.colors.any();321 if (322 !emoji323 && ((run.ascii && face.covers_ascii()) || face.covers(&text, run.start, run.end))324 ) {325 out.push(FacePiece { .start = run.start, .end = run.end, .face = primary });326 return move out;327 }328 const wanted = Wanted {329 .script = run.script,330 .language = &style.language.view(),331 .weight = style.weight,332 .size = style.size,333 .emoji = run.emoji334 };335 var at = run.start;336 while (at < run.end) {337 const next = min(next_grapheme(&text, at), run.end);338 var chosen = primary;339 if (emoji || !face.covers(&text, at, next)) {340 if (t.fonts.fallback(&text, at, next, &wanted, primary) is ::Some |f|) {341 chosen = f;342 }343 }344 if (out.length() > 0 && out.last().face == chosen) {345 out.get_var(out.length() - 1).end = next;346 } else {347 out.push(FacePiece { .start = at, .end = next, .face = chosen });348 }349 at = next;350 }351 return move out;352}353354// Breaks the paragraph's glyphs, from `first`, into lines no wider than355// `limit`.356fn fill_lines(357 self t: &var Typesetter,358 breaks: &[LineBreak],359 first: u64,360 start: u64,361 end: u64,362 limit: f32363) {364 const glyphs = &t.glyphs.view();365 var line_first = first;366 var line_start = start;367 var x: f32 = 0.0;368 var candidate: Option<u64> = ::None; // a glyph the line may end before369 // the first break at or past the paragraph's first glyph370 var b: u64 = 0;371 if (first < glyphs.length()) {372 var high = breaks.length();373 while (b < high) {374 const middle = (b + high) / 2;375 if (breaks[middle].at < glyphs[first].cluster) {376 b = middle + 1;377 } else {378 high = middle;379 }380 }381 }382 for ([first..glyphs.length()]) |i| {383 const g = &glyphs[i];384 while (b < breaks.length() && breaks[b].at < g.cluster) {385 b += 1;386 }387 if (388 i > line_first389 && b < breaks.length()390 && breaks[b].at == g.cluster391 && g.cluster > line_start392 ) {393 candidate = ::Some(i);394 }395 if (x + g.advance > limit && !g.space && i > line_first) {396 var cut = i;397 if (candidate is ::Some |c| && c > line_first) {398 cut = c;399 if (t.scripts is ::Some && t.cluster_cut(c, i, true) is ::Some |k|) {400 cut = k;401 }402 } else if (t.cluster_cut(line_first, i, false) is ::Some |k|) {403 cut = k;404 }405 t.lines.push(PendingLine {406 .first = line_first,407 .last = cut,408 .start = line_start,409 .end = glyphs[cut].cluster,410 .paragraph_start = start,411 .wrapped = true412 });413 line_first = cut;414 line_start = glyphs[cut].cluster;415 candidate = ::None;416 x = 0.0;417 for (glyphs[cut..i]) |&before| {418 x += before.advance;419 }420 }421 x += g.advance;422 }423 t.lines.push(PendingLine {424 .first = line_first,425 .last = glyphs.length(),426 .start = line_start,427 .end = end,428 .paragraph_start = start429 });430}431432// The last glyph after `first`, up to `last`, starting a cluster on a433// grapheme boundary, which a line may end before: with `southeast_asian`,434// only one between two characters of UAX #14's class SA (Thai, Lao,435// Khmer, Myanmar...), which with text_scripts break between graphemes436// for want of a dictionary (F10 question 4).437fn cluster_cut(self t: &Typesetter, first: u64, last: u64, southeast_asian: bool) -> Option<u64> {438 const glyphs = &t.glyphs.view();439 const start = glyphs[first].cluster;440 const end = glyphs[last].cluster;441 var cut: Option<u64> = ::None;442 var state = GraphemeState::start();443 var previous_sa = false;444 var j = first + 1;445 var at = start;446 while (at <= end && at < t.text.length()) {447 const d = decode(&t.text, at);448 const value = properties(d.c);449 const class = line_class(value);450 const sa = class == LB_SA;451 if (at > start && state.breaks_before(value) && (!southeast_asian || (sa && previous_sa))) {452 while (j < last && glyphs[j].cluster < at) {453 j += 1;454 }455 if (glyphs[j].cluster == at && glyphs[j - 1].cluster < at) {456 cut = ::Some(j);457 }458 }459 state.advance(value);460 previous_sa = sa || (previous_sa && class == LB_CM);461 at += d.length;462 }463 return cut;464}465466// Whether a line was broken at the width.467fn wrapped(self t: &Typesetter) -> bool {468 for (t.lines.view()) |&line| {469 if (line.wrapped) {470 return true;471 }472 }473 return false;474}475476// Past the line's last glyph but the spaces it ends with.477fn visible_end(self t: &Typesetter, line: &PendingLine) -> u64 {478 var last = line.last;479 while (last > line.first && t.glyphs.get(last - 1).space) {480 last -= 1;481 }482 return last;483}484485// The lines placed, the layout `width` wide or, with 0, as its widest486// line.487fn place(self t: &Typesetter, width: f32, align: Align) -> Layout {488 var layout = Layout {489 .text = String::from(&t.text),490 .glyphs = Vector<PlacedGlyph>::with_capacity(t.glyphs.length()),491 .lines = Vector<Line>::with_capacity(t.lines.length()),492 .decorations = Vector<Decoration>::empty(),493 .width = 0.0,494 .height = 0.0,495 .graphemes = Vector<Grapheme>::with_capacity(t.text.length())496 };497 // read once, as the loops below write the layout498 const glyphs = &t.glyphs.view();499 const spans = &t.spans;500 const text = &t.text;501 // each line's width, its trailing spaces left out502 var widths = Vector<f32>::with_capacity(t.lines.length());503 for (t.lines.view()) |&line| {504 var w: f32 = 0.0;505 for (glyphs[line.first..t.visible_end(&line)]) |&g| {506 w += g.advance;507 }508 widths.push(w);509 layout.width = max(layout.width, w);510 }511 if (width > 0.0) {512 layout.width = width;513 }514 var order = Vector<u64>::empty(); // a line's glyphs in visual order, from its first515 var levels = Vector<u8>::empty(); // their levels, from its first, L1 applied516 var top: f32 = 0.0;517 for (t.lines.view(), widths.view()) |&line, line_width| {518 const m = t.metrics_of(&line);519 const baseline = top + (m.height - m.ascent - m.descent) * 0.5 + m.ascent;520 const rtl = line.level % 2 == 1;521 const offset = match (align) {522 ::Start if (rtl) layout.width - line_width else 0.0;523 ::Center (layout.width - line_width) * 0.5;524 ::End if (rtl) 0.0 else layout.width - line_width;525 ::Left 0.0;526 ::Right layout.width - line_width;527 };528 t.visual_order(&line, &var order, &var levels);529 // the spaces a line hangs past its end, at its left right to left530 const visible = t.visible_end(&line);531 var x = offset;532 if (rtl) {533 for (glyphs[visible..line.last]) |&g| {534 x -= g.advance;535 }536 }537 const glyphs_start = layout.glyphs.length();538 const graphemes_start = layout.graphemes.length();539 const count = line.last - line.first;540 const shown_order = &order.view();541 var k: u64 = 0;542 while (k < count) {543 // a cluster: its glyphs, then its graphemes' shares of them544 const first = line.first + shown(&shown_order, k);545 const cluster = glyphs[first].cluster;546 const odd = line.bidi && levels.get(first - line.first) % 2 == 1;547 var next = k;548 var advance: f32 = 0.0;549 while (next < count) {550 const g = &glyphs[line.first + shown(&shown_order, next)];551 if (g.cluster != cluster) {552 break;553 }554 layout.glyphs.push(PlacedGlyph {555 .face = g.face,556 .glyph = g.glyph,557 .size = g.size,558 .x = x + advance + g.dx,559 .y = baseline - g.dy,560 .cluster = g.cluster,561 .color = spans[g.span to u64].style.color562 });563 advance += g.advance;564 next += 1;565 }566 // the cluster ends where the text's next one starts567 var after = line.first + next;568 if (line.bidi) {569 after = first + 1;570 while (after < line.last && glyphs[after].cluster == cluster) {571 after += 1;572 }573 }574 const cluster_end = if (after < line.last) glyphs[after].cluster else line.end;575 const shares = layout.graphemes.length();576 var at = cluster;577 while (at < cluster_end) {578 const grapheme_end = min(next_grapheme(&text, at), cluster_end);579 layout.graphemes.push(Grapheme {580 .at = at to u32,581 .length = (grapheme_end - at) to u32,582 .leading = if (odd) x + advance else x,583 .trailing = if (odd) x else x + advance584 });585 at = grapheme_end;586 }587 // the cluster's advance shared between its graphemes, the588 // first on the right right to left589 const parts = layout.graphemes.length() - shares;590 if (parts == 1) {591 x += advance;592 k = next;593 continue;594 }595 for (layout.graphemes.items()[shares..], [..parts]) |&var g, j| {596 const slot = if (odd) parts - 1 - j else j;597 const left = x + advance * slot to f32 / parts to f32;598 const right = if (slot + 1 == parts) x + advance else x + advance * (599 slot + 1600 ) to f32 / parts to f32;601 g.leading = if (odd) right else left;602 g.trailing = if (odd) left else right;603 }604 if (odd && parts > 1) {605 var a = shares;606 var b = layout.graphemes.length() - 1;607 while (a < b) {608 const swapped = layout.graphemes.get(a);609 layout.graphemes.get_var(a) = layout.graphemes.get(b);610 layout.graphemes.get_var(b) = swapped;611 a += 1;612 b -= 1;613 }614 }615 x += advance;616 k = next;617 }618 t.decorate(&var layout, &line, &order.view(), glyphs_start, baseline);619 layout.lines.push(Line {620 .start = line.start,621 .end = line.end,622 .glyphs = [glyphs_start, layout.glyphs.length()],623 .top = top,624 .baseline = baseline,625 .height = m.height,626 .x = offset,627 .width = line_width,628 .direction = if (rtl) Direction::RightToLeft else Direction::LeftToRight,629 .graphemes = [graphemes_start, layout.graphemes.length()]630 });631 top += m.height;632 }633 layout.height = top;634 // layouts are kept: no room past what they hold635 layout.glyphs.shrink();636 layout.lines.shrink();637 layout.decorations.shrink();638 layout.graphemes.shrink();639 return move layout;640}641642// The line's glyphs in visual order, as indices from its first, and643// their levels: its whitespace at the end and before tabs back at the644// paragraph's level (L1), each run of a level reversed (L2).645fn visual_order(646 self t: &Typesetter,647 line: &PendingLine,648 order: &var Vector<u64>,649 levels: &var Vector<u8>650) {651 order.clear();652 levels.clear();653 if (!line.bidi) {654 return; // the text's own at level 0, which `place` takes without them655 }656 const h = if (t.scripts is ::Some |&h|) h else {657 return;658 };659 for ([..line.last - line.first]) |k| {660 order.push(k);661 }662 const glyphs = &t.glyphs.view()[line.first..line.last];663 var chars = Vector<u32>::with_capacity(glyphs.length());664 for (glyphs) |&g| {665 levels.push(g.level);666 chars.push(decode(&t.text, g.cluster).c);667 }668 (h.reorder)(&chars.view(), &var levels.items(), line.level, &var order.items());669}670671// A line's or a style's ascent, descent (both positive) and line height,672// in pixels.673type LineMetrics = struct {674 ascent: f32,675 descent: f32,676 height: f32,677};678679fn metrics(self t: &Typesetter, style: &TextStyle) -> LineMetrics {680 const face = &t.fonts.face(t.face_of(&style));681 const scale = style.size / face.units_per_em;682 const ascent = face.ascender * scale;683 const descent = -face.descender * scale;684 const natural = ascent + descent + face.line_gap * scale;685 return LineMetrics {686 .ascent = ascent,687 .descent = descent,688 .height = if (style.line_height > 0.0) style.line_height * style.size else natural689 };690}691692// The largest metrics of the line's styles; an empty line's are its693// paragraph's.694fn metrics_of(self t: &Typesetter, line: &PendingLine) -> LineMetrics {695 if (line.first == line.last) {696 return t.metrics(&t.spans[span_at(&t.spans, line.paragraph_start) to u64].style);697 }698 var m = LineMetrics { .ascent = 0.0, .descent = 0.0, .height = 0.0 };699 var measured: Option<u32> = ::None; // the span of the glyph before700 for (t.glyphs.view()[line.first..line.last]) |&g| {701 if (measured is ::Some |span| && span == g.span) {702 continue;703 }704 measured = ::Some(g.span);705 const style_metrics = t.metrics(&t.style_of(&g));706 m.ascent = max(m.ascent, style_metrics.ascent);707 m.descent = max(m.descent, style_metrics.descent);708 m.height = max(m.height, style_metrics.height);709 }710 return m;711}712713// The line's glyph shown `k`th from the left, from its first: by the714// order `visual_order` gave, or the text's where it gave none.715fn shown(order: &[u64], k: u64) -> u64 => if (order.length() == 0) k else order[k];716717// Underlines and strikethroughs along the line's runs of glyphs, in718// visual order, whose span asks for them, trailing spaces left out.719fn decorate(720 self t: &Typesetter,721 layout: &var Layout,722 line: &PendingLine,723 order: &[u64],724 placed: u64,725 baseline: f32726) {727 const glyphs = &t.glyphs.view();728 const visible = t.visible_end(&line) - line.first;729 const count = line.last - line.first;730 var k: u64 = 0;731 while (k < count) {732 if (shown(&order, k) >= visible) {733 k += 1;734 continue;735 }736 const span = glyphs[line.first + shown(&order, k)].span;737 var end = k;738 var right: f32 = 0.0;739 while (740 end < count741 && shown(&order, end) < visible742 && glyphs[line.first + shown(&order, end)].span == span743 ) {744 const g = &glyphs[line.first + shown(&order, end)];745 right = layout.glyphs.get(placed + end).x - g.dx + g.advance;746 end += 1;747 }748 const left = layout.glyphs.get(placed + k).x - glyphs[line.first + shown(&order, k)].dx;749 const style = &t.spans[span to u64].style;750 const face = &t.fonts.face(t.face_of(&style));751 const scale = style.size / face.units_per_em;752 if (style.underline) {753 layout.decorations.push(Decoration {754 .box = stroke(755 left,756 right,757 baseline - face.underline_position * scale,758 face.underline_thickness * scale759 ),760 .color = style.color761 });762 }763 if (style.strikethrough) {764 layout.decorations.push(Decoration {765 .box = stroke(766 left,767 right,768 baseline - face.strikeout_position * scale,769 face.strikeout_thickness * scale770 ),771 .color = style.color772 });773 }774 k = end;775 }776}777778// A decoration's box from `left` to `right` below `y`, a pixel thick at779// least.780fn stroke(left: f32, right: f32, y: f32, thickness: f32) -> TextBox {781 return TextBox { .x = left, .y = y, .width = right - left, .height = max(thickness, 1.0) };782}