canvist_layout 0.2.2

Incremental text and block layout for the canvist editor: line breaking, bidi, hit testing, display lists, and SVG/HTML renderers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Laying out the inline content of one text block.
//!
//! Layout runs in two phases so a whole relayout pass shares one measurer
//! call: [`prepare`] itemizes the text and queues missing measurements, the
//! caller flushes the cache, then [`finish`] breaks lines, computes CSS line
//! boxes, and reorders each line for bidi.

use std::ops::Range;
use std::sync::Arc;

use canvist_model::InlineText;
use unicode_bidi::BidiInfo;
use unicode_bidi::Level;

use self::breaking::RawLine;
pub(crate) use self::items::Direction;
pub(crate) use self::items::Item;
pub(crate) use self::items::ItemContext;
pub(crate) use self::items::ItemKind;
use self::items::Itemized;
pub(crate) use self::items::is_newline;
pub(crate) use self::items::slice;
use crate::FontId;
use crate::FontMetrics;
use crate::LayoutError;
use crate::LineBox;
use crate::geometry::snap;
use crate::measure::MeasureCache;
use crate::theme::TextStyle;

mod breaking;
mod breaks;
mod incremental;
mod items;
mod kerning;
mod query;

pub(crate) use self::incremental::Previous;
pub(crate) use self::incremental::TextEdit;

/// A text style used in one block, with its interned font and metrics.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RunStyle {
	pub(crate) style: TextStyle,
	pub(crate) font: FontId,
	pub(crate) metrics: FontMetrics,
	pub(crate) line_box: LineBox,
}

impl RunStyle {
	/// Height above and below the baseline of an inline box in this style.
	pub(crate) fn line_box(&self) -> (f32, f32) {
		(self.line_box.above, self.line_box.below)
	}

	/// [`RunStyle::line_box`] moved by the baseline shift, as CSS moves an
	/// inline box with `vertical-align`.
	pub(crate) fn shifted_line_box(&self) -> (f32, f32) {
		let shift = self.style.baseline_shift;
		(self.line_box.above + shift, self.line_box.below - shift)
	}
}

/// Where lines sit in the content box, from a block's `textAlign`
/// attribute.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Align {
	/// The paragraph's start edge: left, or right for right-to-left text.
	#[default]
	Start,
	/// The left edge.
	Left,
	/// Centred.
	Center,
	/// The right edge.
	Right,
	/// Both edges, by widening spaces on every line that wraps; the last
	/// line and lines ending in a forced break align to the start.
	Justify,
}

impl Align {
	/// The alignment a `textAlign` attribute value names, TipTap's `left`,
	/// `center`, `right`, or `justify`.
	pub(crate) fn from_attr(value: Option<&str>) -> Self {
		match value {
			Some("left") => Self::Left,
			Some("center") => Self::Center,
			Some("right") => Self::Right,
			Some("justify") => Self::Justify,
			_ => Self::Start,
		}
	}
}

/// A run of one item on one line, positioned in visual order.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Piece {
	/// Byte range in the block text.
	pub(crate) range: Range<u32>,
	/// Index of the item the piece belongs to.
	pub(crate) item: u32,
	/// Left edge relative to the block's content box.
	pub(crate) x: f32,
	/// Advance width.
	pub(crate) width: f32,
	/// Whether the piece runs right to left.
	pub(crate) rtl: bool,
}

/// One laid-out line.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Line {
	/// Byte range including trailing spaces and any forced break.
	pub(crate) range: Range<u32>,
	/// The last caret offset on the line.
	pub(crate) caret_end: u32,
	/// Whether the line ended at a soft wrap.
	pub(crate) soft: bool,
	/// Top edge relative to the block's content box.
	pub(crate) top: f32,
	/// Line box height.
	pub(crate) height: f32,
	/// Baseline position relative to `top`.
	pub(crate) baseline: f32,
	/// Width of the content, excluding hanging white space.
	pub(crate) width: f32,
	/// Pieces in visual order, left to right.
	pub(crate) pieces: Vec<Piece>,
}

/// The layout of one text block's inline content.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct TextLayout {
	pub(crate) text: Arc<str>,
	pub(crate) styles: Vec<RunStyle>,
	pub(crate) items: Vec<Item>,
	pub(crate) lines: Vec<Line>,
	/// The width lines were broken to.
	pub(crate) width: f32,
	/// The sum of line heights.
	pub(crate) height: f32,
	/// Whether the paragraph direction is right to left.
	pub(crate) rtl: bool,
	/// Whether lines were reordered for bidi.
	pub(crate) bidi: bool,
	/// How lines sit in the content box.
	pub(crate) align: Align,
	/// Text laid out with the block that is not part of the document:
	/// provisional text and adornments, in order. Offsets in `text`, lines,
	/// and items include it; [`TextLayout::laid_out`] and
	/// [`TextLayout::in_document`] convert.
	pub(crate) inserted: Vec<Inserted>,
}

/// Text laid out in a block without being part of the document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Inserted {
	/// The document offset it shows at.
	pub(crate) at: u32,
	/// The bytes it takes in the laid-out text.
	pub(crate) range: Range<u32>,
	/// An adornment shows between the upstream and downstream carets at
	/// `at`; provisional text shows before both, as it will once final.
	pub(crate) adornment: bool,
}

/// A block whose measurements have been queued.
pub(crate) enum Draft {
	/// The whole block is laid out from scratch.
	Full {
		text: Arc<str>,
		itemized: Itemized,
		align: Align,
	},
	/// Only the part around an edit is laid out again.
	Partial(incremental::Partial),
}

/// What phase one needs to know about a block.
pub(crate) struct Block<'a> {
	pub(crate) base: &'a TextStyle,
	pub(crate) inline: &'a InlineText,
	pub(crate) direction: Direction,
	/// How lines sit in the content box.
	pub(crate) align: Align,
	/// The content width lines will be broken to.
	pub(crate) width: f32,
	/// The block's previous layout and the edit since, when it has one.
	pub(crate) previous: Option<Previous>,
}

/// Phase one: itemize the block and queue its measurements. A block with a
/// previous layout re-itemizes only around its edit when it can.
pub(crate) fn prepare(context: &mut ItemContext<'_>, block: Block<'_>) -> Draft {
	let Block {
		base,
		inline,
		direction,
		align,
		width,
		previous,
	} = block;
	let partial = previous
		.filter(|previous| previous.layout.align == align)
		.and_then(|previous| incremental::prepare(context, base, inline, previous, width));

	if let Some(partial) = partial {
		return partial;
	}

	let itemized = items::itemize(context, base, inline, direction);

	if inline.as_str().contains('\t') {
		context.cache.request(itemized.styles[0].font, " ");
	}

	Draft::Full {
		text: Arc::from(inline.as_str()),
		itemized,
		align,
	}
}

/// Phase two: lay out a prepared block at `width` once the cache is flushed.
pub(crate) fn finish(
	draft: Draft,
	cache: &MeasureCache,
	width: f32,
	tab_size: u32,
) -> Result<TextLayout, LayoutError> {
	let (text, itemized, align) = match draft {
		Draft::Full {
			text,
			itemized,
			align,
		} => (text, itemized, align),
		Draft::Partial(partial) => return incremental::finish(partial, cache, tab_size),
	};

	let Itemized {
		mut styles,
		items: drafts,
		rtl,
		bidi,
	} = itemized;
	let mut items = items::measure_items(&text, drafts, &mut styles, cache)?;
	let count = items.len();
	kerning::apply(&text, &mut items, 0..count, cache)?;
	let space = tab_space(&text, &styles[0], cache)?;
	let tabs = breaking::TabStops {
		interval: space * tab_size as f32,
		space,
	};
	let raw = breaking::break_lines(&text, &mut items, width, tabs);
	let mut layout = TextLayout {
		text,
		styles,
		items,
		lines: Vec::new(),
		width,
		height: 0.0,
		rtl,
		bidi,
		align,
		inserted: Vec::new(),
	};

	layout.stack_lines(raw, bidi);

	Ok(layout)
}

/// The base embedding level of a paragraph.
fn paragraph_level(rtl: bool) -> Level {
	if rtl { Level::rtl() } else { Level::ltr() }
}

/// How the lines of `layout` are filled.
fn line_settings(
	layout: &TextLayout,
	cache: &MeasureCache,
	tab_size: u32,
) -> Result<breaking::Lines, LayoutError> {
	let space = tab_space(&layout.text, &layout.styles[0], cache)?;

	Ok(breaking::Lines {
		available: layout.width,
		tabs: breaking::TabStops {
			interval: space * tab_size as f32,
			space,
		},
	})
}

/// The advance of a space in the base style, which spaces tab stops. Text
/// without tabs never queued that measurement, so it gets zero.
fn tab_space(text: &str, base: &RunStyle, cache: &MeasureCache) -> Result<f32, LayoutError> {
	if !text.contains('\t') {
		return Ok(0.0);
	}

	let space = cache
		.get(base.font, " ")
		.ok_or(LayoutError::MissingMeasurement)?;

	Ok(space.width + base.style.letter_spacing)
}

impl TextLayout {
	/// Turn `raw` lines into positioned lines stacked from the top, reordering
	/// them for bidi when the block needs it, and set the block height.
	fn stack_lines(&mut self, raw: Vec<RawLine>, bidi: bool) {
		let info = bidi.then(|| BidiInfo::new(&self.text, Some(paragraph_level(self.rtl))));

		self.lines = self.position_lines(raw, 0.0, info.as_ref());
		self.height = self.lines.last().map_or(0.0, |line| line.top + line.height);
	}

	/// Position left-to-right `raw` lines, stacked from `top`.
	fn build_lines(&self, raw: Vec<RawLine>, top: f32) -> Vec<Line> {
		self.position_lines(raw, top, None)
	}

	/// Position `raw` lines stacked from `top`, reordering them with `info`
	/// when it is given.
	fn position_lines(
		&self,
		raw: Vec<RawLine>,
		top: f32,
		info: Option<&BidiInfo<'_>>,
	) -> Vec<Line> {
		let strut = self.styles[0].line_box();
		let mut top = top;

		raw.into_iter()
			.map(|raw| {
				let mut line = Line {
					pieces: self.pieces(&raw.range, info),
					range: raw.range,
					caret_end: raw.caret_end,
					soft: raw.soft,
					top,
					height: 0.0,
					baseline: 0.0,
					width: 0.0,
				};

				self.place(strut, &mut line);
				top += line.height;
				line
			})
			.collect()
	}

	/// The pieces of the line covering `range`, in visual order when the
	/// block needs bidi reordering.
	fn pieces(&self, range: &Range<u32>, info: Option<&BidiInfo<'_>>) -> Vec<Piece> {
		let logical = logical_pieces(&self.text, &self.items, range);

		match info {
			Some(info) => visual_pieces(&self.text, &self.items, info, range, &logical),
			None => logical,
		}
	}

	/// Position `line`'s pieces and compute its line box, which is at least
	/// as tall as `strut`.
	fn place(&self, strut: (f32, f32), line: &mut Line) {
		let total: f32 = line.pieces.iter().map(|piece| piece.width).sum();
		let hang = hanging_width(&self.text, &self.items, line);
		let (mut x, gap) = self.alignment(line, total, hang);
		let content_end = content_end(&self.text, &line.range);
		let (mut above, mut below) = strut;

		for piece in &mut line.pieces {
			piece.x = x;
			x += piece.width;

			if gap > 0.0 {
				let widened =
					gap * justifiable_spaces(&self.text, &piece.range, content_end) as f32;
				piece.width += widened;
				x += widened;
			}

			let item = &self.items[piece.item as usize];

			let (item_above, item_below) = match &item.kind {
				ItemKind::Text { .. } => self.styles[item.style as usize].shifted_line_box(),
				ItemKind::Embed(embed) => (embed.ascent, embed.descent),
				ItemKind::Tab | ItemKind::Break => continue,
			};

			above = above.max(item_above);
			below = below.max(item_below);
		}

		line.width = (total - hang).max(0.0) + 0.0;
		line.baseline = snap(above);
		line.height = snap(above + below);
	}

	/// Where `line`'s first piece starts, and the extra width each space
	/// gets when the line is justified.
	///
	/// White space hanging at the line's logical end is left out of the
	/// width being aligned, as CSS Text 3 says. It sits at the visual right
	/// of left-to-right lines and the visual left of right-to-left ones.
	fn alignment(&self, line: &Line, total: f32, hang: f32) -> (f32, f32) {
		let content = (total - hang).max(0.0);
		let free = (self.width - content).max(0.0);
		let leading_hang = if self.rtl { hang } else { 0.0 };
		let start = if self.rtl { Align::Right } else { Align::Left };

		let align = match self.align {
			Align::Start => return (if self.rtl { self.width - total } else { 0.0 }, 0.0),
			Align::Justify if line.soft => {
				let end = content_end(&self.text, &line.range);
				let spaces = justifiable_spaces(&self.text, &line.range, end);

				if spaces > 0 {
					return (-leading_hang, free / spaces as f32);
				}

				start
			}
			Align::Justify => start,
			other => other,
		};

		let visible_left = match align {
			Align::Center => free / 2.0,
			Align::Right => free,
			_ => 0.0,
		};

		(visible_left - leading_hang, 0.0)
	}
}

/// Where the content of the line covering `range` ends: before the white
/// space and forced break hanging at its end.
fn content_end(text: &str, range: &Range<u32>) -> usize {
	range.start as usize + slice(text, range).trim_end_matches([' ', '\n']).len()
}

/// How many spaces in `range`, part of a line whose content ends at
/// `content_end`, widen to justify it: every space except the hanging ones.
fn justifiable_spaces(text: &str, range: &Range<u32>, content_end: usize) -> usize {
	let start = range.start as usize;
	let end = (range.end as usize).min(content_end);

	if start >= end {
		return 0;
	}

	text[start..end]
		.bytes()
		.filter(|&byte| byte == b' ')
		.count()
}

/// Pieces of every item intersecting `range`, in logical order.
fn logical_pieces(text: &str, items: &[Item], range: &Range<u32>) -> Vec<Piece> {
	let first = items.partition_point(|item| item.range.end <= range.start);

	items[first..]
		.iter()
		.enumerate()
		.take_while(|(_, item)| item.range.start < range.end)
		.map(|(index, item)| {
			let start = item.range.start.max(range.start);
			let end = item.range.end.min(range.end);
			Piece {
				range: start..end,
				item: (first + index) as u32,
				x: 0.0,
				width: item.span(text, start, end),
				rtl: false,
			}
		})
		.collect()
}

/// Reorder `logical` pieces of one line into visual order with UAX #9,
/// splitting pieces whose characters resolve to different levels.
fn visual_pieces(
	text: &str,
	items: &[Item],
	info: &BidiInfo<'_>,
	line: &Range<u32>,
	logical: &[Piece],
) -> Vec<Piece> {
	let mut visual = Vec::with_capacity(logical.len());
	let line_range = line.start as usize..line.end as usize;

	for paragraph in &info.paragraphs {
		let start = paragraph.range.start.max(line_range.start);
		let end = paragraph.range.end.min(line_range.end);

		if start >= end {
			continue;
		}

		let (levels, runs) = info.visual_runs(paragraph, start..end);

		for run in runs {
			let rtl = levels.get(run.start).is_some_and(Level::is_rtl);
			let run = run.start as u32..run.end as u32;
			let mut parts: Vec<Piece> = logical
				.iter()
				.filter_map(|piece| {
					let start = piece.range.start.max(run.start);
					let end = piece.range.end.min(run.end);
					(start < end).then(|| {
						Piece {
							range: start..end,
							item: piece.item,
							x: 0.0,
							width: items[piece.item as usize].span(text, start, end),
							rtl,
						}
					})
				})
				.collect();

			if rtl {
				parts.reverse();
			}

			visual.extend(parts);
		}
	}

	visual
}

/// The width of white space hanging at the logical end of `line`.
fn hanging_width(text: &str, items: &[Item], line: &Line) -> f32 {
	let mut ordered: Vec<&Piece> = line.pieces.iter().collect();
	ordered.sort_by_key(|piece| piece.range.start);
	let mut hang = 0.0;

	for piece in ordered.into_iter().rev() {
		let item = &items[piece.item as usize];

		if item.kind == ItemKind::Break {
			continue;
		}

		if item.is_space(text) {
			hang += piece.width;
			continue;
		}

		let trailing = item.trailing_space(text, piece.range.start);

		// Without trailing spaces nothing hangs, and measuring the rest of a
		// word on every line it wraps across would cost quadratic time.
		if trailing > 0.0 {
			let beyond = item.span(text, piece.range.end, item.range.end);
			hang += (trailing - beyond).max(0.0);
		}

		break;
	}

	hang
}