use std::collections::BTreeSet;
use std::ops::Range;
use std::sync::Arc;
use canvist_model::BlockId;
use canvist_model::Selection;
use super::DecorationKind;
use super::DisplayItem;
use super::DisplayList;
use super::DisplayOptions;
use super::RectKind;
use super::SlotKind;
use super::TextRun;
use super::fade;
use super::fade::Fade;
use super::motion;
use crate::BlockStyle;
use crate::Caret;
use crate::Color;
use crate::DocumentLayout;
use crate::Rect;
use crate::TableRole;
use crate::document::Marker;
use crate::document::Origin;
use crate::document::Row;
use crate::document::RowKind;
use crate::document::Span;
use crate::style::StyleId;
use crate::text::ItemKind;
use crate::text::Line;
use crate::text::Piece;
use crate::text::RunStyle;
use crate::text::TextLayout;
use crate::text::slice;
#[cfg(feature = "ink")]
use crate::theme::INK_WIDTH;
use crate::theme::LeafStyle;
use crate::theme::MarkerKind;
use crate::theme::Motion;
impl DocumentLayout {
#[must_use]
pub fn display_list(&self, options: &DisplayOptions) -> DisplayList {
let mut builder = Builder::new(self, options);
let rows: Vec<usize> = self.rows_between(options.top, options.bottom).collect();
builder.containers(&rows);
for &index in &rows {
builder.row_background(index);
}
for &index in &rows {
builder.inline_backgrounds(index);
}
for (range, color) in &options.highlights {
builder.selection(range, *color, RectKind::Range);
}
if let Some(selection) = &options.selection {
builder.selection(
selection,
self.theme().chrome().selection,
RectKind::Selection,
);
}
for &index in &rows {
builder.row_content(index);
}
builder.placeholders(&rows, &options.placeholders);
builder.finish(options.caret)
}
}
const PLACEHOLDER_ALPHA: f32 = 0.4;
const DECORATION_THICKNESS: f32 = 1.0 / 16.0;
const UNDERLINE_OFFSET: f32 = 0.1;
const STRIKE_OFFSET: f32 = 0.3;
const SQUIGGLE_OFFSET: f32 = 0.15;
#[derive(Clone, Copy)]
struct LineBox {
top: f32,
height: f32,
baseline: f32,
}
struct Builder<'a> {
layout: &'a DocumentLayout,
list: DisplayList,
time: Option<f32>,
settling: &'a [(BlockId, Range<u32>, f32)],
foreground: Vec<DisplayItem>,
}
impl<'a> Builder<'a> {
fn new(layout: &'a DocumentLayout, options: &'a DisplayOptions) -> Self {
let height = options.bottom - options.top;
let bounds = Rect::new(0.0, options.top, layout.options().width, height);
Self {
layout,
list: DisplayList {
fonts: layout.cache().fonts().fonts().to_vec(),
items: Vec::new(),
bounds,
animated: false,
points: Vec::new(),
},
time: options.time,
settling: &options.settling,
foreground: Vec::new(),
}
}
}
impl Builder<'_> {
fn finish(mut self, caret: Option<Caret>) -> DisplayList {
self.list.items.append(&mut self.foreground);
if let Some(rect) = caret.and_then(|caret| self.layout.caret_rect(caret)) {
self.list.items.push(DisplayItem::Rect {
rect,
color: self.layout.theme().chrome().caret,
radius: 0.0,
kind: RectKind::Caret,
block: None,
});
}
self.list
}
fn push_rect(&mut self, rect: Rect, color: Color, radius: f32, kind: RectKind, block: BlockId) {
self.list.items.push(DisplayItem::Rect {
rect,
color,
radius,
kind,
block: Some(block),
});
}
fn push_box(&mut self, rect: Rect, style: &BlockStyle, block: BlockId) {
if let Some(color) = style.background {
self.push_rect(rect, color, style.radius, RectKind::Background, block);
}
if let Some(border) = style.border_left {
let bar = Rect::new(rect.x, rect.y, border.width, rect.height);
self.push_rect(bar, border.color, 0.0, RectKind::Border, block);
}
}
fn containers(&mut self, rows: &[usize]) {
let layout = self.layout;
let mut tables = Vec::new();
for index in visible_spans(layout, rows) {
let span = &layout.spans()[index as usize];
let style = layout.styles().get(span.style);
self.push_box(layout.span_rect(span), style, span.block);
if let Some(TableRole::Table { rule }) = style.table {
tables.push((index, rule));
}
}
for (index, rule) in tables {
let block = layout.spans()[index as usize].block;
for line in layout.grid_lines(index, self.list.bounds) {
self.push_rect(line, rule.color, 0.0, RectKind::Border, block);
}
}
}
fn row_background(&mut self, index: usize) {
let layout = self.layout;
let row = &layout.rows()[index];
let style = layout.style_of(row);
let rect = layout.row_rect(index);
self.push_box(rect, style, row.block);
if row.kind != RowKind::Leaf {
return;
}
let origin = layout.origin(index);
let content = Rect::new(
origin.x,
origin.y,
crate::document::content_width(style, row.width),
rect.height - style.padding.vertical(),
);
match style.leaf {
LeafStyle::Rule { color, .. } => {
self.push_rect(content, color, 0.0, RectKind::Rule, row.block);
}
LeafStyle::Slot { .. } => {
self.foreground.push(DisplayItem::Slot {
kind: SlotKind::Block,
block: row.block,
offset: None,
rect: content,
});
}
#[cfg(feature = "ink")]
LeafStyle::Ink { stroke, .. } => self.ink(row, content, stroke, style.text.color),
#[cfg(not(feature = "ink"))]
LeafStyle::Ink { .. } => {}
}
}
#[cfg(feature = "ink")]
fn ink(&mut self, row: &Row, content: Rect, width: f32, color: Color) {
let Some(drawing) = &row.ink else {
return;
};
let scale = content.width / INK_WIDTH;
for stroke in &drawing.strokes {
let start = self.list.points.len() as u32;
self.list.points.extend(
stroke
.points
.chunks_exact(2)
.flat_map(|point| [content.x + point[0] * scale, content.y + point[1] * scale]),
);
let points = start..self.list.points.len() as u32;
let width = stroke.width.unwrap_or(width) * scale;
self.list.items.push(DisplayItem::Stroke {
bounds: stroke_bounds(self.list.stroke_points(&points), width),
points,
width,
color: stroke.color.unwrap_or(color),
block: row.block,
});
}
}
fn inline_backgrounds(&mut self, index: usize) {
let layout = self.layout;
let row = &layout.rows()[index];
let Some(text) = &row.layout else {
return;
};
let origin = layout.origin(index);
for line in &text.lines {
let backgrounds = line
.pieces
.iter()
.filter_map(|piece| piece_background(text, line, piece, origin));
for (rect, color) in backgrounds {
self.push_rect(rect, color, 0.0, RectKind::Highlight, row.block);
}
}
}
fn selection(&mut self, selection: &Selection, color: Color, kind: RectKind) {
for rect in self.layout.selection_rects(selection) {
self.list.items.push(DisplayItem::Rect {
rect,
color,
radius: 0.0,
kind,
block: None,
});
}
}
fn row_content(&mut self, index: usize) {
let layout = self.layout;
let row = &layout.rows()[index];
self.markers(index, row);
let Some(text) = &row.layout else {
return;
};
let origin = layout.origin(index);
let (fades, animated) = fade::fades(row.block, text, self.settling, self.time);
self.list.animated |= animated;
for (index, line) in text.lines.iter().enumerate() {
for piece in &line.pieces {
self.piece(row.block, text, (index, line), piece, origin, &fades);
}
}
}
fn piece(
&mut self,
block: BlockId,
text: &TextLayout,
(line_index, line): (usize, &Line),
piece: &Piece,
origin: Origin,
fades: &[Fade],
) {
let item = &text.items[piece.item as usize];
let baseline = origin.y + line.top + line.baseline;
let x = origin.x + piece.x;
if let ItemKind::Embed(embed) = &item.kind
&& embed.label.is_none()
{
self.foreground.push(DisplayItem::Slot {
kind: SlotKind::Embed(embed.kind),
block,
offset: Some(text.in_document(item.range.start)),
rect: Rect::new(
x,
baseline - embed.ascent,
embed.width,
embed.ascent + embed.descent,
),
});
return;
}
let Some((source, range, style)) = run_source(text, piece) else {
return;
};
let baseline = baseline - style.style.baseline_shift;
let motion = style.style.motion;
if motion != Motion::None {
self.list.animated = true;
if let (Some(time), false, true) = (self.time, piece.rtl, cfg!(feature = "kinetic")) {
let glyphs = Glyphs {
block,
text,
line: (line_index, line),
origin,
baseline,
};
self.kinetic(&glyphs, piece, style, time);
self.decorations(block, style, x, baseline, piece.width);
return;
}
}
let run = TextRun {
block,
source,
range,
font: style.font,
x,
baseline,
width: piece.width,
color: style.style.color,
letter_spacing: style.style.letter_spacing,
rtl: piece.rtl,
bounds: Rect::new(x, origin.y + line.top, piece.width, line.height),
};
if fades.is_empty() || !matches!(item.kind, ItemKind::Text { .. }) {
self.list.items.push(DisplayItem::Text(run));
} else {
let parts = fade::split(run, item, &text.text, fades);
self.list
.items
.extend(parts.into_iter().map(DisplayItem::Text));
}
self.decorations(block, style, x, baseline, piece.width);
}
#[cold]
#[inline(never)]
fn kinetic(&mut self, glyphs: &Glyphs<'_>, piece: &Piece, style: &RunStyle, time: f32) {
use unicode_segmentation::UnicodeSegmentation;
let text = glyphs.text;
let (line_index, line) = glyphs.line;
let source = slice(&text.text, &piece.range);
let caret = |offset: u32| {
glyphs.origin.x + text.caret_x(line_index, offset, crate::Affinity::Downstream)
};
for (index, (start, grapheme)) in source.grapheme_indices(true).enumerate() {
if grapheme.trim().is_empty() {
continue;
}
let start = piece.range.start + start as u32;
let end = start + grapheme.len() as u32;
let x = caret(start);
let width = caret(end) - x;
let ((dx, dy), color) = motion::glyph(
style.style.motion,
time,
index,
style.style.font.size,
style.style.color,
);
self.list.items.push(DisplayItem::Text(TextRun {
block: glyphs.block,
source: text.text.clone(),
range: start..end,
font: style.font,
x: x + dx,
baseline: glyphs.baseline + dy,
width,
color,
letter_spacing: style.style.letter_spacing,
rtl: false,
bounds: Rect::new(x + dx, glyphs.origin.y + line.top + dy, width, line.height),
}));
}
}
fn placeholders(&mut self, rows: &[usize], placeholders: &[(BlockId, Arc<str>)]) {
if placeholders.is_empty() {
return;
}
let layout = self.layout;
for &index in rows {
let row = &layout.rows()[index];
let Some((_, text)) = placeholders.iter().find(|(block, _)| *block == row.block) else {
continue;
};
let Some(empty) = row.layout.as_ref().filter(|layout| layout.text.is_empty()) else {
continue;
};
let style = &empty.styles[0];
let line = self.first_line_box(index, layout.style_of(row));
let origin = layout.origin(index);
let width = crate::document::content_width(layout.style_of(row), row.width);
let color = style.style.color;
let alpha = (f32::from(color.a) * PLACEHOLDER_ALPHA).round() as u8;
self.list.items.push(DisplayItem::Text(TextRun {
block: row.block,
source: text.clone(),
range: 0..text.len() as u32,
font: style.font,
x: origin.x,
baseline: line.baseline,
width,
color: Color::rgba(color.r, color.g, color.b, alpha),
letter_spacing: style.style.letter_spacing,
rtl: false,
bounds: Rect::new(origin.x, line.top, width, line.height),
}));
}
}
fn decorations(&mut self, block: BlockId, style: &RunStyle, x: f32, baseline: f32, width: f32) {
let decorations = style.style.decorations;
let size = style.style.font.size;
let thickness = (size * DECORATION_THICKNESS).max(1.0);
let color = decorations.color.unwrap_or(style.style.color);
let lines = [
(
decorations.underline,
DecorationKind::Underline,
baseline + size * UNDERLINE_OFFSET,
),
(
decorations.strike,
DecorationKind::Strike,
baseline - size * STRIKE_OFFSET,
),
(
decorations.squiggle,
DecorationKind::Squiggle,
baseline + size * SQUIGGLE_OFFSET,
),
];
for (_, kind, y) in lines.into_iter().filter(|line| line.0) {
self.foreground.push(DisplayItem::Decoration {
kind,
x,
y,
width,
thickness,
color,
block,
});
}
}
fn markers(&mut self, index: usize, row: &Row) {
let layout = self.layout;
if let Some(marker) = &row.marker {
let edge = row.x + border_width(layout.style_of(row));
self.marker(index, row.block, row.style, edge, marker);
}
let mut span = row.span;
while let Some(current) = span {
let candidate: &Span = &layout.spans()[current as usize];
if candidate.first_row as usize != index {
break;
}
if let Some(marker) = &candidate.marker {
let edge = candidate.x + border_width(layout.styles().get(candidate.style));
self.marker(index, candidate.block, candidate.style, edge, marker);
}
span = candidate.parent;
}
}
fn marker(&mut self, index: usize, block: BlockId, style: StyleId, edge: f32, marker: &Marker) {
let layout = self.layout;
let style = layout.styles().get(style);
let line = self.first_line_box(index, style);
let right = edge - layout.theme().markers().gap;
if marker.kind == MarkerKind::Task {
self.checkbox(block, marker.checked, right, line);
} else {
self.marker_label(block, marker, style, right, line);
}
}
fn first_line_box(&self, index: usize, style: &BlockStyle) -> LineBox {
let layout = self.layout;
let origin = layout.origin(index);
let first = layout.rows()[index]
.layout
.as_ref()
.and_then(|text| text.lines.first());
match first {
Some(line) => {
LineBox {
top: origin.y + line.top,
height: line.height,
baseline: origin.y + line.top + line.baseline,
}
}
None => {
LineBox {
top: origin.y,
height: style.text.line_height_px(),
baseline: origin.y + style.text.font.size,
}
}
}
}
fn checkbox(&mut self, block: BlockId, checked: bool, right: f32, line: LineBox) {
let size = self.layout.theme().markers().checkbox;
self.foreground.push(DisplayItem::Slot {
kind: SlotKind::Checkbox { checked },
block,
offset: None,
rect: Rect::new(
right - size,
line.top + (line.height - size) / 2.0,
size,
size,
),
});
}
fn marker_label(
&mut self,
block: BlockId,
marker: &Marker,
style: &BlockStyle,
right: f32,
line: LineBox,
) {
let layout = self.layout;
let Some(text) = layout.marker_text(marker) else {
return;
};
let cache = layout.cache();
let Some(font) = cache.fonts().find(&style.text.font) else {
return;
};
let Some(width) = cache.get(font, &text).map(|measured| measured.width) else {
return;
};
let color = layout.theme().markers().color.unwrap_or(style.text.color);
self.list.items.push(DisplayItem::Text(TextRun {
block,
range: 0..text.len() as u32,
source: text,
font,
x: right - width,
baseline: line.baseline,
width,
color,
letter_spacing: 0.0,
rtl: false,
bounds: Rect::new(right - width, line.top, width, line.height),
}));
}
}
fn visible_spans(layout: &DocumentLayout, rows: &[usize]) -> BTreeSet<u32> {
let mut visible = BTreeSet::new();
for &index in rows {
let mut span = layout.rows()[index].span;
while let Some(current) = span
&& visible.insert(current)
{
span = layout.spans()[current as usize].parent;
}
}
visible
}
fn piece_background(
text: &TextLayout,
line: &Line,
piece: &Piece,
origin: Origin,
) -> Option<(Rect, Color)> {
let item = &text.items[piece.item as usize];
let style = match &item.kind {
ItemKind::Embed(embed) => embed.label.as_ref().map_or(item.style, |label| label.style),
_ => item.style,
};
let run = &text.styles[style as usize];
let color = run.style.background?;
if piece.width <= 0.0 || item.kind == ItemKind::Break {
return None;
}
let baseline = origin.y + line.top + line.baseline - run.style.baseline_shift;
let rect = Rect::new(
origin.x + piece.x,
baseline - run.metrics.ascent,
piece.width,
run.metrics.ascent + run.metrics.descent,
);
Some((rect, color))
}
fn run_source<'a>(
text: &'a TextLayout,
piece: &Piece,
) -> Option<(Arc<str>, Range<u32>, &'a RunStyle)> {
let item = &text.items[piece.item as usize];
match &item.kind {
ItemKind::Text { .. } => {
let blank = slice(&text.text, &piece.range)
.bytes()
.all(|byte| byte == b' ');
let style = &text.styles[item.style as usize];
(!blank).then(|| (text.text.clone(), piece.range.clone(), style))
}
ItemKind::Embed(embed) => {
embed.label.as_ref().map(|label| {
let range = 0..label.text.len() as u32;
(
label.text.clone(),
range,
&text.styles[label.style as usize],
)
})
}
ItemKind::Tab | ItemKind::Break => None,
}
}
#[cfg(feature = "ink")]
fn stroke_bounds(points: &[f32], width: f32) -> Rect {
let (mut left, mut top, mut right, mut bottom) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
for point in points.chunks_exact(2) {
left = left.min(point[0]);
right = right.max(point[0]);
top = top.min(point[1]);
bottom = bottom.max(point[1]);
}
if left > right {
return Rect::default();
}
let half = width / 2.0;
Rect::new(
left - half,
top - half,
right - left + width,
bottom - top + width,
)
}
struct Glyphs<'a> {
block: BlockId,
text: &'a TextLayout,
line: (usize, &'a Line),
origin: Origin,
baseline: f32,
}
fn border_width(style: &BlockStyle) -> f32 {
style.border_left.map_or(0.0, |border| border.width)
}