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;
#[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 {
pub(crate) fn line_box(&self) -> (f32, f32) {
(self.line_box.above, self.line_box.below)
}
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)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Align {
#[default]
Start,
Left,
Center,
Right,
Justify,
}
impl Align {
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,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Piece {
pub(crate) range: Range<u32>,
pub(crate) item: u32,
pub(crate) x: f32,
pub(crate) width: f32,
pub(crate) rtl: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Line {
pub(crate) range: Range<u32>,
pub(crate) caret_end: u32,
pub(crate) soft: bool,
pub(crate) top: f32,
pub(crate) height: f32,
pub(crate) baseline: f32,
pub(crate) width: f32,
pub(crate) pieces: Vec<Piece>,
}
#[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>,
pub(crate) width: f32,
pub(crate) height: f32,
pub(crate) rtl: bool,
pub(crate) bidi: bool,
pub(crate) align: Align,
pub(crate) provisional: Option<Range<u32>>,
}
pub(crate) enum Draft {
Full {
text: Arc<str>,
itemized: Itemized,
align: Align,
},
Partial(incremental::Partial),
}
pub(crate) struct Block<'a> {
pub(crate) base: &'a TextStyle,
pub(crate) inline: &'a InlineText,
pub(crate) direction: Direction,
pub(crate) align: Align,
pub(crate) width: f32,
pub(crate) previous: Option<Previous>,
}
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,
}
}
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,
provisional: None,
};
layout.stack_lines(raw, bidi);
Ok(layout)
}
fn paragraph_level(rtl: bool) -> Level {
if rtl { Level::rtl() } else { Level::ltr() }
}
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,
},
})
}
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 {
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);
}
fn build_lines(&self, raw: Vec<RawLine>, top: f32) -> Vec<Line> {
self.position_lines(raw, top, None)
}
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()
}
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,
}
}
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);
}
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)
}
}
fn content_end(text: &str, range: &Range<u32>) -> usize {
range.start as usize + slice(text, range).trim_end_matches([' ', '\n']).len()
}
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()
}
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()
}
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
}
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);
let beyond = item.span(text, piece.range.end, item.range.end);
hang += (trailing - beyond).max(0.0);
break;
}
hang
}