use std::sync::Arc;
use canvist_model::Block;
use canvist_model::BlockId;
use canvist_model::BlockTypeId;
use canvist_model::Content;
use canvist_model::Document;
use canvist_model::Value;
use rustc_hash::FxHashMap;
use super::grid::Grid;
#[cfg(feature = "ink")]
use super::ink::InkDrawing;
use crate::geometry::to_units;
use crate::style::StyleId;
use crate::style::Styles;
use crate::style::attr;
use crate::style::attr_px;
use crate::text::Align;
use crate::text::Direction;
use crate::text::Previous;
use crate::text::TextLayout;
use crate::theme::INK_WIDTH;
use crate::theme::LeafStyle;
use crate::theme::MarkerKind;
#[cfg(feature = "tables")]
use crate::theme::TableRole;
use crate::theme::TextStyle;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RowKind {
Text,
Leaf,
Empty,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Marker {
pub(crate) kind: MarkerKind,
pub(crate) ordinal: i64,
pub(crate) depth: usize,
pub(crate) checked: bool,
}
#[derive(Clone, Debug)]
pub(crate) struct Row {
pub(crate) block: BlockId,
pub(crate) key: u32,
pub(crate) block_type: BlockTypeId,
pub(crate) kind: RowKind,
pub(crate) style: StyleId,
pub(crate) parent_kind: Option<BlockTypeId>,
pub(crate) parent_style: Option<StyleId>,
pub(crate) x: f32,
pub(crate) width: f32,
pub(crate) lead: i64,
pub(crate) height: i64,
pub(crate) span: Option<u32>,
pub(crate) rev: u32,
pub(crate) direction: Direction,
pub(crate) align: Align,
pub(crate) layout: Option<Arc<TextLayout>>,
pub(crate) previous: Option<Previous>,
pub(crate) marker: Option<Marker>,
pub(crate) table: Option<u32>,
pub(crate) grid_y: i64,
#[cfg(feature = "ink")]
pub(crate) ink: Option<Arc<InkDrawing>>,
}
impl Row {
pub(crate) fn table(&self) -> Option<u32> {
self.table.filter(|_| cfg!(feature = "tables"))
}
pub(crate) fn needs_layout(&self) -> bool {
self.kind == RowKind::Text && self.layout.is_none()
}
fn into_current_layout(
self,
block: &Block,
style: StyleId,
content_width: f32,
) -> Option<Arc<TextLayout>> {
if self.rev != block.rev() || self.style != style {
return None;
}
self.layout
.filter(|layout| layout.width.to_bits() == content_width.to_bits())
}
}
#[derive(Clone, Debug)]
pub(crate) struct Span {
pub(crate) block: BlockId,
pub(crate) key: u32,
pub(crate) block_type: BlockTypeId,
pub(crate) style: StyleId,
pub(crate) x: f32,
pub(crate) width: f32,
pub(crate) first_row: u32,
pub(crate) last_row: u32,
pub(crate) top: i64,
pub(crate) bottom: i64,
pub(crate) parent: Option<u32>,
pub(crate) marker: Option<Marker>,
pub(crate) grid: Option<GridPart>,
}
impl Span {
pub(crate) fn grid_part(&self) -> Option<&GridPart> {
self.grid.as_ref().filter(|_| cfg!(feature = "tables"))
}
}
#[cfg_attr(
not(feature = "tables"),
allow(dead_code, reason = "only the `tables` feature builds grids")
)]
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum GridPart {
Table(Box<Grid>),
Row { table: u32, row: u32 },
Cell { table: u32, cell: u32 },
}
impl GridPart {
pub(crate) fn table_mut(&mut self) -> Option<&mut u32> {
match self {
Self::Table(_) => None,
Self::Row { table, .. } | Self::Cell { table, .. } => Some(table),
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct RootExtent {
pub(crate) block: BlockId,
pub(crate) rows: u32,
pub(crate) spans: u32,
pub(crate) style: StyleId,
pub(crate) closing: i64,
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Seed {
pub(crate) pending: i64,
pub(crate) previous_after: Option<f32>,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Flat {
pub(crate) rows: Vec<Row>,
pub(crate) spans: Vec<Span>,
pub(crate) row_of: FxHashMap<BlockId, u32>,
pub(crate) row_slots: Vec<u32>,
pub(crate) span_of: FxHashMap<BlockId, u32>,
pub(crate) span_slots: Vec<u32>,
pub(crate) roots: Vec<RootExtent>,
pub(crate) tail: i64,
}
impl Flat {
pub(crate) fn grid(&self, table: Option<u32>) -> Option<(usize, &Grid)> {
let span = self.spans.get(table? as usize)?;
match span.grid_part() {
Some(GridPart::Table(grid)) => Some((span.first_row as usize, grid)),
_ => None,
}
}
pub(crate) fn extent(&self, index: usize) -> i64 {
let Some(row) = self.rows.get(index) else {
return 0;
};
let Some((first, grid)) = self.grid(row.table()) else {
return row.lead + row.height;
};
let last = self
.spans
.get(row.table.unwrap_or_default() as usize)
.map_or(first, |span| span.last_row as usize);
let lead = if index == first { grid.lead } else { 0 };
let height = if index == last { grid.height } else { 0 };
lead + height
}
}
pub(crate) fn flatten(doc: &Document, styles: &mut Styles, width: f32, previous: Flat) -> Flat {
let capacity = previous.rows.len();
let mut by_key: Vec<Option<Row>> = Vec::new();
by_key.resize_with(previous.row_slots.len(), || None);
for row in previous.rows {
let key = row.key as usize;
if let Some(slot) = by_key.get_mut(key) {
*slot = Some(row);
}
}
let flattener = Flattener {
doc,
styles,
previous_index: previous.row_of,
previous: by_key,
flat: Flat {
rows: Vec::with_capacity(capacity),
row_of: FxHashMap::with_capacity_and_hasher(capacity, rustc_hash::FxBuildHasher),
row_slots: Vec::with_capacity(capacity),
..Flat::default()
},
pending: 0,
#[cfg(feature = "tables")]
in_table: false,
};
flattener.run(doc.children(None), width, Seed::default())
}
pub(crate) fn flatten_roots(
doc: &Document,
styles: &mut Styles,
region: &Region<'_>,
previous: Vec<Row>,
) -> Flat {
let previous_index = previous
.iter()
.enumerate()
.map(|(index, row)| (row.block, index as u32))
.collect();
let flattener = Flattener {
doc,
styles,
previous_index,
previous: previous.into_iter().map(Some).collect(),
flat: Flat::default(),
pending: 0,
#[cfg(feature = "tables")]
in_table: false,
};
flattener.run(region.roots, region.width, region.seed)
}
pub(crate) struct Region<'a> {
pub(crate) roots: &'a [BlockId],
pub(crate) width: f32,
pub(crate) seed: Seed,
}
const AVERAGE_GLYPH_WIDTH_EM: f32 = 0.5;
#[derive(Clone, Copy)]
pub(super) struct Frame {
pub(super) x: f32,
pub(super) width: f32,
pub(super) span: Option<u32>,
pub(super) lists: usize,
}
pub(super) struct Placement {
pub(super) style: StyleId,
pub(super) parent_kind: Option<BlockTypeId>,
pub(super) parent_style: Option<StyleId>,
pub(super) frame: Frame,
pub(super) marker: Option<Marker>,
}
pub(super) struct Flattener<'a> {
pub(super) doc: &'a Document,
pub(super) styles: &'a mut Styles,
previous: Vec<Option<Row>>,
previous_index: FxHashMap<BlockId, u32>,
pub(super) flat: Flat,
pub(super) pending: i64,
#[cfg(feature = "tables")]
pub(super) in_table: bool,
}
impl Flattener<'_> {
fn run(mut self, ids: &[BlockId], width: f32, seed: Seed) -> Flat {
let frame = Frame {
x: 0.0,
width,
span: None,
lists: 0,
};
let mut previous_after = seed.previous_after;
self.pending = seed.pending;
for &id in ids {
let Some(block) = self.doc.block(id) else {
continue;
};
previous_after = Some(self.root(block, frame, previous_after));
}
self.flat.tail = self.pending;
self.flat
}
fn root(&mut self, block: &Block, frame: Frame, previous_after: Option<f32>) -> f32 {
let style = self.styles.resolve(block, None, None);
let resolved = self.styles.get(style);
let (before, after) = (resolved.space_before, resolved.space_after);
if let Some(previous_after) = previous_after {
self.pending += to_units(f32::max(previous_after, before));
}
let (rows, spans) = (self.flat.rows.len(), self.flat.spans.len());
let placement = Placement {
style,
parent_kind: None,
parent_style: None,
frame,
marker: None,
};
self.block(block, placement);
self.flat.roots.push(RootExtent {
block: block.id(),
rows: (self.flat.rows.len() - rows) as u32,
spans: (self.flat.spans.len() - spans) as u32,
style,
closing: self.pending,
});
after
}
fn children(&mut self, parent: Option<&Block>, parent_style: Option<StyleId>, frame: Frame) {
let doc = self.doc;
let parent_kind = parent.map(Block::kind);
let marker_kind = parent_style.and_then(|style| self.styles.get(style).marker);
let start = parent.map_or(1, |parent| self.int_attr(parent, "start").unwrap_or(1));
let open = parent.is_none_or(|parent| is_open(doc, parent));
let shown = if open { usize::MAX } else { 1 };
let mut previous_after = None;
for (index, &id) in doc
.children(parent.map(Block::id))
.iter()
.enumerate()
.take(shown)
{
let Some(block) = doc.block(id) else {
continue;
};
let style = self.styles.resolve(block, parent_kind, parent_style);
let resolved = self.styles.get(style);
let (before, after) = (resolved.space_before, resolved.space_after);
if let Some(after) = previous_after {
self.pending += to_units(f32::max(after, before));
}
let marker = marker_kind
.filter(|&kind| kind != MarkerKind::Disclosure || index == 0)
.map(|kind| {
let checked = if kind == MarkerKind::Disclosure {
open
} else {
self.bool_attr(block, "checked")
};
Marker {
kind,
ordinal: start + index as i64,
depth: frame.lists.saturating_sub(1),
checked,
}
});
let placement = Placement {
style,
parent_kind,
parent_style,
frame,
marker,
};
self.block(block, placement);
previous_after = Some(after);
}
}
pub(super) fn block(&mut self, block: &Block, placement: Placement) {
let kind = match block.content() {
Content::Inline(_) => RowKind::Text,
Content::Leaf => RowKind::Leaf,
Content::Blocks(children) if children.is_empty() => RowKind::Empty,
Content::Blocks(_) => {
#[cfg(feature = "tables")]
if let (Some(TableRole::Table { rule }), false) =
(self.styles.get(placement.style).table, self.in_table)
{
self.table(block, placement, rule.width);
return;
}
self.container(block, placement);
return;
}
};
self.row(block, kind, placement);
}
pub(super) fn container(&mut self, block: &Block, placement: Placement) {
let Placement {
style,
frame,
marker,
..
} = placement;
let resolved = self.styles.get(style);
let (inset_left, inset_right) = (resolved.inset_left(), resolved.inset_right());
let (padding_top, padding_bottom) = (resolved.padding.top, resolved.padding.bottom);
let lists = frame.lists + usize::from(resolved.marker.is_some());
let first_row = self.flat.rows.len() as u32;
let pending_before = self.pending;
let index = self.push_span(block, style, frame, marker);
let inner = Frame {
x: frame.x + inset_left,
width: (frame.width - inset_left - inset_right).max(0.0),
span: Some(index),
lists,
};
self.pending += to_units(padding_top);
self.children(Some(block), Some(style), inner);
self.pending += to_units(padding_bottom);
let top = self
.flow_lead(first_row as usize)
.map_or(0, |lead| lead - pending_before);
let rows = &self.flat.rows;
let last_row = (rows.len() as u32).saturating_sub(1).max(first_row);
let span = &mut self.flat.spans[index as usize];
span.top = top;
span.last_row = last_row;
span.bottom = self.pending;
}
pub(super) fn push_span(
&mut self,
block: &Block,
style: StyleId,
frame: Frame,
marker: Option<Marker>,
) -> u32 {
let index = self.flat.spans.len() as u32;
let key = self.flat.span_slots.len() as u32;
let first_row = self.flat.rows.len() as u32;
self.flat.span_slots.push(index);
self.flat.span_of.insert(block.id(), key);
self.flat.spans.push(Span {
block: block.id(),
key,
block_type: block.kind(),
style,
x: frame.x,
width: frame.width,
first_row,
last_row: first_row,
top: 0,
bottom: 0,
parent: frame.span,
marker,
grid: None,
});
index
}
fn row(&mut self, block: &Block, kind: RowKind, placement: Placement) {
let content_width = self.content_width(placement.style, placement.frame.width);
let previous = self
.take_previous(block.id())
.filter(|_| kind == RowKind::Text);
let (layout, height) = match previous {
Some(old) => {
let height = old.height;
(
old.into_current_layout(block, placement.style, content_width),
height,
)
}
None => (None, self.initial_height(block, kind, &placement)),
};
let index = self.flat.rows.len() as u32;
let key = self.flat.row_slots.len() as u32;
self.flat.row_slots.push(index);
self.flat.rows.push(Row {
block: block.id(),
key,
block_type: block.kind(),
kind,
style: placement.style,
parent_kind: placement.parent_kind,
parent_style: placement.parent_style,
x: placement.frame.x,
width: placement.frame.width,
lead: self.pending,
height,
span: placement.frame.span,
rev: block.rev(),
direction: direction(self.doc, block),
align: align(self.doc, block),
layout,
previous: None,
marker: placement.marker,
table: None,
grid_y: 0,
#[cfg(feature = "ink")]
ink: self.ink(block, placement.style),
});
self.flat.row_of.insert(block.id(), key);
self.pending = 0;
}
fn take_previous(&mut self, id: BlockId) -> Option<Row> {
let index = *self.previous_index.get(&id)?;
self.previous.get_mut(index as usize).and_then(Option::take)
}
#[cfg(feature = "ink")]
fn ink(&self, block: &Block, style: StyleId) -> Option<Arc<InkDrawing>> {
let is_ink = matches!(self.styles.get(style).leaf, LeafStyle::Ink { .. });
if !(is_ink && matches!(block.content(), Content::Leaf)) {
return None;
}
InkDrawing::from_attrs(block.attrs())
}
fn content_width(&self, style: StyleId, width: f32) -> f32 {
let style = self.styles.get(style);
(width - style.inset_left() - style.inset_right()).max(0.0)
}
fn initial_height(&self, block: &Block, kind: RowKind, placement: &Placement) -> i64 {
let resolved = self.styles.get(placement.style);
let padding = resolved.padding.vertical();
let content = match kind {
RowKind::Empty => 0.0,
RowKind::Leaf => {
let width = self.content_width(placement.style, placement.frame.width);
leaf_height(block, resolved.leaf, width)
}
RowKind::Text => {
let width = self.content_width(placement.style, placement.frame.width);
estimated_text_height(block, &resolved.text, width)
}
};
to_units(padding + content)
}
fn int_attr(&self, block: &Block, key: &str) -> Option<i64> {
let defaults = &self.doc.schema().block(block.kind()).attrs;
attr(block.attrs(), defaults, key).and_then(Value::as_int)
}
fn bool_attr(&self, block: &Block, key: &str) -> bool {
let defaults = &self.doc.schema().block(block.kind()).attrs;
attr(block.attrs(), defaults, key)
.and_then(Value::as_bool)
.unwrap_or(false)
}
}
pub(crate) fn is_open(doc: &Document, block: &Block) -> bool {
let defaults = &doc.schema().block(block.kind()).attrs;
attr(block.attrs(), defaults, "open").and_then(Value::as_bool) != Some(false)
}
pub(crate) fn direction(doc: &Document, block: &Block) -> Direction {
let defaults = &doc.schema().block(block.kind()).attrs;
match attr(block.attrs(), defaults, "dir").and_then(Value::as_str) {
Some("rtl") => Direction::Rtl,
Some("ltr") => Direction::Ltr,
_ => Direction::Auto,
}
}
pub(crate) fn align(doc: &Document, block: &Block) -> Align {
let defaults = &doc.schema().block(block.kind()).attrs;
Align::from_attr(attr(block.attrs(), defaults, "textAlign").and_then(Value::as_str))
}
fn leaf_height(block: &Block, leaf: LeafStyle, width: f32) -> f32 {
match leaf {
LeafStyle::Rule { thickness, .. } => thickness,
LeafStyle::Slot { height } => attr_px(block.attrs(), "height").unwrap_or(height),
LeafStyle::Ink { height, .. } => {
attr_px(block.attrs(), "height").unwrap_or(height) * width / INK_WIDTH
}
}
}
fn estimated_text_height(block: &Block, text: &TextStyle, width: f32) -> f32 {
let length = block.inline().map_or(0, canvist_model::InlineText::len) as f32;
let average = text.font.size * AVERAGE_GLYPH_WIDTH_EM + text.letter_spacing;
let lines = (length * average / width.max(1.0)).ceil().max(1.0);
lines * text.line_height_px()
}