use crate::color::Color;
use crate::event::Cursor;
use crate::id::{ById, hash};
use crate::layout::{Align, Flow, Length};
use crate::text::{Face, Font, Rule, TextSystem, cluster};
use crate::told::Role;
use crate::ui::{Icon, Measure, Picture, Ui};
use std::ops::Range;
pub(crate) const PAD: f32 = 3.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Kind {
Page,
Paragraph,
Heading(u8),
Code(u32),
Quote,
List { numbered: bool, tight: bool },
Item { number: u32, ticked: Option<bool> },
Rule,
Table,
Row { head: bool },
Cell(Align),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Block {
pub kind: Kind,
pub parent: u32,
pub end: u32,
pub pieces: [u32; 2],
pub words: [u32; 2],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Thing {
Words,
Named(u32),
Icon(Icon),
Picture(Picture, [f32; 2]),
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct Look {
pub bold: bool,
pub italic: bool,
pub mono: bool,
pub rule: Rule,
pub link: u32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Stretch {
pub words: [u32; 2],
pub look: Look,
pub thing: Thing,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Writing {
pub words: String,
pub blocks: Vec<Block>,
pub pieces: Vec<Stretch>,
pub languages: Vec<String>,
}
pub(crate) const THING: char = '\u{fffc}';
pub(crate) fn finish(writing: &mut Writing) {
for at in (0..writing.blocks.len()).rev() {
let block = writing.blocks[at];
let end = block.end.max(at as u32 + 1);
writing.blocks[at].end = end;
if let Some(parent) = writing.blocks.get_mut(block.parent as usize) {
(parent.end, parent.words[1]) = (parent.end.max(end), parent.words[1].max(block.words[1]));
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Piece<'a> {
words: &'a str,
look: Look,
size: f32,
face: Option<Face>,
color: Option<Color>,
back: Option<Color>,
thing: Thing,
}
impl<'a> Piece<'a> {
pub const fn words(words: &'a str) -> Self {
let look = Look { bold: false, italic: false, mono: false, rule: Rule::None, link: 0 };
Piece { words, look, size: 0.0, face: None, color: None, back: None, thing: Thing::Words }
}
pub const fn icon(icon: Icon) -> Piece<'static> {
Piece { thing: Thing::Icon(icon), ..Piece::words("") }
}
pub const fn picture(picture: Picture, width: f32, height: f32) -> Piece<'static> {
Piece { thing: Thing::Picture(picture, [width, height]), ..Piece::words("") }
}
pub const fn bold(mut self) -> Self {
self.look.bold = true;
self
}
pub const fn italic(mut self) -> Self {
self.look.italic = true;
self
}
pub const fn code(mut self) -> Self {
self.look.mono = true;
self
}
pub const fn size(mut self, size: f32) -> Self {
self.size = size;
self
}
pub const fn face(mut self, face: Face) -> Self {
self.face = Some(face);
self
}
pub const fn color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
pub const fn back(mut self, color: Color) -> Self {
self.back = Some(color);
self
}
pub const fn underlined(mut self) -> Self {
self.look.rule = Rule::Under;
self
}
pub const fn struck(mut self) -> Self {
self.look.rule = Rule::Through;
self
}
pub const fn link(mut self) -> Self {
self.look.link = 1;
self
}
}
pub(crate) fn face_of(face: Face, look: Look) -> Face {
let face = if look.mono { Face::Mono } else { face };
let face = match (look.bold, face) {
(false, face) | (true, face @ Face::Bold) => face,
(true, Face::Regular) => Face::Bold,
(true, face) => face.weight(700),
};
match (look.italic, face) {
(false, face) => face,
(true, Face::Regular) => Face::Italic,
(true, face) => face.italic(),
}
}
#[derive(Clone, Copy)]
pub(crate) struct Bit {
pub words: [u32; 2],
pub font: Font,
pub color: Color,
pub back: Color,
pub link: u32,
pub thing: Thing,
pub stops: u32,
pub x: f32,
pub wide: f32,
pub above: f32,
pub below: f32,
}
impl Bit {
pub fn new(words: [u32; 2], font: Font, color: Color, back: Color, link: u32, thing: Thing) -> Bit {
Bit { words, font, color, back, link, thing, stops: 0, x: 0.0, wide: 0.0, above: 0.0, below: 0.0 }
}
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Row {
pub frags: [u32; 2],
pub left: f32,
pub top: f32,
pub high: f32,
pub base: f32,
pub words: [u32; 2],
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Frag {
pub bit: u32,
pub words: [u32; 2],
pub first: u32,
pub x: f32,
pub into: f32,
pub wide: f32,
pub high: f32,
pub y: f32,
pub part: u32,
}
#[derive(Default)]
pub(crate) struct Laid {
pub bits: Vec<Bit>,
pub stops: Vec<f32>,
pub rows: Vec<Row>,
pub frags: Vec<Frag>,
}
pub(crate) fn heights(system: &mut dyn TextSystem, font: Font, scale: f32, fonts: &mut Vec<(Font, [f32; 2])>) -> [f32; 2] {
let plain = Font { rule: Rule::None, ..font };
if let Some((_, known)) = fonts.iter().find(|(known, _)| *known == plain) {
return *known;
}
let metrics = system.metrics(plain, scale);
let lift = metrics.lift(true);
let both = [metrics.ascent - lift, metrics.descent + lift];
fonts.push((plain, both));
both
}
impl Laid {
pub fn measure(&mut self, bits: Range<usize>, text: &str, system: &mut dyn TextSystem, scale: f32, fonts: &mut Vec<(Font, [f32; 2])>) -> f32 {
let (mut x, mut at) = (0.0, bits.start);
while at < bits.end {
let first = self.bits[at];
let alone = !matches!(first.thing, Thing::Words) || first.back != Color::NONE;
let mut end = at + 1;
while !alone
&& end < bits.end
&& self.bits[end].font == first.font
&& self.bits[end].back == Color::NONE
&& self.bits[end].thing == Thing::Words
&& self.bits[end].words[0] == self.bits[end - 1].words[1]
{
end += 1;
}
x = self.measure_run(at..end, x, text, system, scale, fonts);
at = end;
}
x
}
fn measure_run(&mut self, run: Range<usize>, x: f32, text: &str, system: &mut dyn TextSystem, scale: f32, fonts: &mut Vec<(Font, [f32; 2])>) -> f32 {
let (first, last) = (self.bits[run.start], self.bits[run.end - 1]);
let pad = if first.back == Color::NONE { 0.0 } else { PAD };
let mut ends = Vec::new();
let whole = match first.thing {
Thing::Words | Thing::Named(_) => system.measure(&text[first.words[0] as usize..last.words[1] as usize], first.font, scale, Some(&mut ends)),
Thing::Icon(_) => first.font.size,
Thing::Picture(_, [wide, _]) => wide,
};
let (heights, mut count) = (heights(system, first.font, scale, fonts), 0);
for at in run {
let bit = &mut self.bits[at];
let words = matches!(bit.thing, Thing::Words | Thing::Named(_));
let letters = if words { text[bit.words[0] as usize..bit.words[1] as usize].chars().count() } else { 0 };
let before = if count == 0 { 0.0 } else { ends[count - 1] };
let own = &ends[count..count + letters];
let wide = match (words, own.last()) {
(false, _) => whole,
(true, last) => last.map_or(0.0, |end| end - before),
};
[bit.above, bit.below] = heights;
(bit.x, bit.stops, bit.wide) = (x + pad + before, self.stops.len() as u32, wide);
self.stops.extend(own.iter().map(|end| end - before));
count += letters;
}
x + pad + whole + pad
}
pub fn x_at(&self, text: &str, row: usize, at: u32) -> f32 {
let row = self.rows[row];
let frags = &self.frags[row.frags[0] as usize..row.frags[1] as usize];
let Some(frag) = frags.iter().find(|frag| at < frag.words[1]) else { return frags.last().map_or(0.0, |frag| frag.x + frag.wide) };
if at <= frag.words[0] || !matches!(self.bits[frag.bit as usize].thing, Thing::Words | Thing::Named(_)) {
return frag.x + if at <= frag.words[0] { 0.0 } else { frag.wide };
}
let count = text[frag.words[0] as usize..at as usize].chars().count() as u32;
frag.x + self.stops[(frag.first + count - 1) as usize] - frag.into
}
pub fn at_x(&self, text: &str, row: usize, x: f32) -> u32 {
let row = self.rows[row];
for frag in &self.frags[row.frags[0] as usize..row.frags[1] as usize] {
if x >= frag.x + frag.wide {
continue;
}
return match self.bits[frag.bit as usize].thing {
Thing::Words | Thing::Named(_) => self.at_in(text, frag, x),
_ => frag.words[(x >= frag.x + frag.wide / 2.0) as usize],
};
}
row.words[1]
}
fn at_in(&self, text: &str, frag: &Frag, x: f32) -> u32 {
let words = &text[frag.words[0] as usize..frag.words[1] as usize];
let (mut at, mut left, mut count) = (0, frag.x, 0);
while at < words.len() {
let next = at + cluster(&words[at..]);
count += words[at..next].chars().count() as u32;
let right = frag.x + self.stops[(frag.first + count - 1) as usize] - frag.into;
if x < (left + right) / 2.0 {
return frag.words[0] + at as u32;
}
(at, left) = (next, right);
}
frag.words[1]
}
}
#[derive(Clone, Copy, PartialEq)]
struct At {
bit: u32,
byte: u32,
stop: u32,
x: f32,
}
#[derive(Clone, Copy)]
pub(crate) struct Room {
pub above: f32,
pub below: f32,
pub high: f32,
pub left: f32,
pub wide: f32,
pub side: Align,
}
struct Breaker<'a> {
laid: &'a mut Laid,
text: &'a str,
room: Room,
scale: f32,
start: At,
top: f32,
space: Option<(At, At)>,
end: u32,
}
pub(crate) fn lay(laid: &mut Laid, bits: Range<u32>, text: &str, from: u32, room: Room, top: f32, scale: f32) -> f32 {
let start = laid.bits.get(bits.start as usize).filter(|_| !bits.is_empty()).map_or(At { bit: bits.start, byte: from, stop: 0, x: 0.0 }, |bit| At {
bit: bits.start,
byte: bit.words[0],
stop: bit.stops,
x: 0.0,
});
let mut breaker = Breaker { laid, text, room, scale, start, top, space: None, end: bits.end };
for at in bits.clone() {
let bit = breaker.laid.bits[at as usize];
match bit.thing {
Thing::Words | Thing::Named(_) => breaker.words(at, bit),
_ => breaker.thing(at, bit),
}
}
let last = bits.end.checked_sub(1).filter(|_| !bits.is_empty()).map(|at| breaker.laid.bits[at as usize]);
let end = last.map_or(start, |bit| At { bit: bits.end, byte: bit.words[1], stop: bit.stops, x: bit.x + bit.wide });
breaker.row(end, end);
breaker.top - top
}
impl Breaker<'_> {
fn words(&mut self, at: u32, bit: Bit) {
let text = self.text;
let mut left = bit.x;
for (count, (byte, letter)) in text[bit.words[0] as usize..bit.words[1] as usize].char_indices().enumerate() {
let stop = bit.stops + count as u32;
let right = bit.x + self.laid.stops[stop as usize];
let here = At { bit: at, byte: bit.words[0] + byte as u32, stop, x: left };
let after = At { bit: at, byte: here.byte + letter.len_utf8() as u32, stop: stop + 1, x: right };
match letter {
'\n' => self.row(here, after),
' ' => self.space = Some((here, after)),
_ if right - self.start.x > self.room.wide && here != self.start && right > left => self.full(here),
_ => {}
}
left = right;
}
}
fn thing(&mut self, at: u32, bit: Bit) {
let here = At { bit: at, byte: bit.words[0], stop: bit.stops, x: bit.x };
if bit.x + bit.wide.min(self.room.wide) - self.start.x > self.room.wide && here != self.start {
self.full(here);
}
}
fn full(&mut self, here: At) {
match self.space.take() {
Some((end, next)) => self.row(end, next),
None => self.row(here, here),
}
}
fn row(&mut self, end: At, next: At) {
let first = self.laid.frags.len() as u32;
for at in self.start.bit..end.bit.saturating_add(1).min(self.end) {
self.frag(at, end);
}
let frags = first as usize..self.laid.frags.len();
let (mut above, mut below) = (self.room.above, self.room.below);
for frag in &self.laid.frags[frags.clone()] {
let bit = &self.laid.bits[frag.bit as usize];
match bit.thing {
Thing::Picture(..) => above = above.max(frag.high),
_ => (above, below) = (above.max(bit.above), below.max(bit.below)),
}
}
let pixel = |units: f32| (units * self.scale).round() / self.scale;
let high = ((above + below).max(self.room.high) * self.scale).ceil() / self.scale;
let base = pixel((high - above - below) / 2.0 + above);
let wide = end.x - self.start.x;
let shift = pixel((self.room.wide - wide).max(0.0) * [0.0, 0.5, 1.0, 0.0][self.room.side as usize]);
for frag in &mut self.laid.frags[frags] {
let bit = &self.laid.bits[frag.bit as usize];
frag.x += shift;
frag.y = pixel(match bit.thing {
Thing::Picture(..) => base - frag.high,
Thing::Icon(_) => base - bit.above + (bit.above + bit.below - frag.high) / 2.0,
_ => base - bit.above,
});
}
let row = Row { frags: [first, self.laid.frags.len() as u32], left: self.room.left, top: self.top, high, base, words: [self.start.byte, end.byte] };
self.laid.rows.push(row);
(self.start, self.space, self.top) = (next, None, self.top + high);
}
fn frag(&mut self, at: u32, end: At) {
let bit = self.laid.bits[at as usize];
let from = if at == self.start.bit { self.start } else { At { bit: at, byte: bit.words[0], stop: bit.stops, x: bit.x } };
let words = !matches!(bit.thing, Thing::Icon(_) | Thing::Picture(..));
let (to, right) = if at == end.bit { (end.byte, end.x) } else { (bit.words[1], bit.x + bit.wide) };
if words && to <= from.byte || !words && at == end.bit {
return;
}
let wide = if words { right - from.x } else { bit.wide.min(self.room.wide) };
let high = match bit.thing {
Thing::Picture(_, [w, h]) => h * wide / w.max(1.0),
Thing::Icon(_) => bit.font.size,
_ => 0.0,
};
let part = match self.laid.frags.last() {
Some(last) if bit.link != 0 && self.laid.bits[last.bit as usize].link == bit.link => last.part + 1,
_ => 0,
};
let frag = Frag { bit: at, words: [from.byte, if words { to } else { bit.words[1] }], first: from.stop, x: from.x - self.start.x, into: from.x - bit.x, wide, high, y: 0.0, part };
self.laid.frags.push(frag);
}
}
pub(crate) struct Shape<'a> {
pub laid: &'a Laid,
pub text: &'a str,
pub links: &'a [[u32; 2]],
pub picked: [u32; 2],
pub keyed: bool,
}
pub(crate) type Target = (u32, u32);
impl Ui {
pub(crate) fn link_states(&mut self, shape: &Shape, targets: &[Target]) -> (Vec<u32>, u32) {
let (mut lit, mut pressed) = (Vec::new(), 0);
for (_, frag) in targets {
let frag = shape.laid.frags[*frag as usize];
let link = shape.laid.bits[frag.bit as usize].link;
let id = self.id(("link", link, frag.part));
let state = if frag.part == 0 { self.press(id) } else { self.interact(id) };
if state.hovered {
self.set_cursor(Cursor::Hand);
}
if state.hovered || state.focused {
lit.push(link);
}
pressed = if state.clicked { link } else { pressed };
}
(lit, pressed)
}
pub(crate) fn link_boxes(&mut self, shape: &Shape, targets: &[Target], corner: [f32; 2]) {
for (row, frag) in targets {
let (row, frag) = (shape.laid.rows[*row as usize], shape.laid.frags[*frag as usize]);
let link = shape.laid.bits[frag.bit as usize].link;
let place = [corner[0] + row.left + frag.x, corner[1] + row.top];
let target = self.el().key(("link", link, frag.part)).at(place[0], place[1]).size(frag.wide, row.high).radius(2.0).sense();
if frag.part > 0 {
target.show();
continue;
}
let state = target.focusable().show();
let [from, to] = shape.links.get(link as usize - 1).copied().unwrap_or_default();
self.tell(&state, Role::Link, None, shape.text.get(from as usize..to as usize).unwrap_or(""));
}
}
pub(crate) fn write_rows(&mut self, shape: &Shape, rows: Range<usize>, corner: [f32; 2], lit: &[u32]) {
for at in rows {
let row = shape.laid.rows[at];
let corner = [corner[0] + row.left, corner[1] + row.top];
self.write_picked(shape, at, corner);
for frag in &shape.laid.frags[row.frags[0] as usize..row.frags[1] as usize] {
self.write_frag(shape, frag, corner, lit);
}
}
}
fn write_picked(&mut self, shape: &Shape, at: usize, corner: [f32; 2]) {
let ([from, to], row) = (shape.picked, shape.laid.rows[at]);
if from >= to || to <= row.words[0] || from > row.words[1] {
return;
}
let left = shape.laid.x_at(shape.text, at, from.max(row.words[0]));
let right = if to > row.words[1] { shape.laid.x_at(shape.text, at, row.words[1]) + 4.0 } else { shape.laid.x_at(shape.text, at, to) };
let color = self.theme.accent.alpha(if shape.keyed { 0.35 } else { 0.2 });
self.el().at(corner[0] + left, corner[1]).size(right - left, row.high).fill(color).show();
}
fn write_frag(&mut self, shape: &Shape, frag: &Frag, [x, y]: [f32; 2], lit: &[u32]) {
let bit = shape.laid.bits[frag.bit as usize];
let (x, y) = (x + frag.x, y + frag.y);
if bit.back != Color::NONE {
let (before, after) = (if frag.into <= 0.0 { PAD } else { 0.0 }, if frag.words[1] >= bit.words[1] { PAD } else { 0.0 });
self.el().at(x - before, y).size(frag.wide + before + after, bit.above + bit.below).fill(bit.back).radius(3.0).show();
}
match bit.thing {
Thing::Icon(icon) => _ = self.el().icon(icon, frag.high, bit.color).at(x, y).show(),
Thing::Picture(picture, _) => _ = self.el().picture(picture).size(frag.wide, frag.high).at(x, y).show(),
_ => {
let font = if bit.link != 0 && lit.contains(&bit.link) { bit.font.underlined() } else { bit.font };
self.el().text(&shape.text[frag.words[0] as usize..frag.words[1] as usize], font, bit.color).select(None, false).at(x, y).show();
}
}
}
}
#[derive(Default)]
pub(crate) struct Writings {
pub kept: Option<Box<dyn std::any::Any>>,
pub settle: Option<fn(&mut Ui)>,
}
#[derive(Default)]
pub(crate) struct Kept {
pub paragraphs: ById<Paragraph>,
pub documents: ById<crate::document::Shown>,
}
#[derive(Default)]
pub(crate) struct Paragraph {
key: u64,
text: String,
links: Vec<[u32; 2]>,
laid: Laid,
width: f32,
high: f32,
long: f32,
used: bool,
}
fn forget_unused(ui: &mut Ui) {
let Some(kept) = ui.writings.kept.as_mut().and_then(|kept| kept.downcast_mut::<Kept>()) else { return };
kept.paragraphs.retain(|_, paragraph| std::mem::take(&mut paragraph.used));
kept.documents.retain(|_, shown| std::mem::take(&mut shown.used));
}
impl Ui {
pub(crate) fn take_writings(&mut self) -> Box<Kept> {
self.writings.settle = Some(forget_unused);
self.writings.kept.take().and_then(|kept| kept.downcast::<Kept>().ok()).unwrap_or_default()
}
pub(crate) fn keep_writings(&mut self, kept: Box<Kept>) {
self.writings.kept = Some(kept);
}
pub fn rich(&mut self, pieces: &[Piece]) -> Option<usize> {
let (id, at) = (self.next_id(), self.tree.specs.len() as u32);
let read = self.rooms.get(&id).copied().unwrap_or([self.size().w, 0.0, 0.0]);
let mut kept = self.take_writings();
let paragraph = kept.paragraphs.entry(id).or_default();
self.lay_paragraph(paragraph, pieces, read[0]);
self.measures.push(Measure { at, within: at, id, read: [read[0], paragraph.high, 0.0] });
self.el().flow(Flow::Layers).w(Length::Grow(1.0)).h(Length::Px(paragraph.high)).open();
self.el().w(Length::Px(paragraph.long)).show();
let rows = 0..paragraph.laid.rows.len();
let shape = Shape { laid: ¶graph.laid, text: ¶graph.text, links: ¶graph.links, picked: [0; 2], keyed: false };
let frags = shape.laid.frags.iter().enumerate();
let targets: Vec<Target> = frags.filter(|(_, frag)| shape.laid.bits[frag.bit as usize].link != 0).map(|(at, _)| (row_of(shape.laid, at as u32), at as u32)).collect();
let (lit, pressed) = self.link_states(&shape, &targets);
let words = self.el().flow(Flow::Layers).w(Length::Grow(1.0)).h(Length::Px(paragraph.high)).open();
self.tell(&words, Role::Text, None, ¶graph.text);
self.write_rows(&shape, rows, [0.0; 2], &lit);
self.close();
self.link_boxes(&shape, &targets, [0.0; 2]);
self.close();
paragraph.used = true;
self.keep_writings(kept);
pressed.checked_sub(1).map(|link| link as usize)
}
fn lay_paragraph(&mut self, paragraph: &mut Paragraph, pieces: &[Piece], width: f32) {
let (t, scale) = (self.theme, self.scale);
let key = pieces.iter().fold(hash((t.font.size.to_bits(), t.font.face, t.text, t.accent, t.hover, scale.to_bits())), |key, piece| crate::id::fold(key, piece_key(piece)));
if key != paragraph.key {
(paragraph.key, paragraph.width) = (key, -1.0);
paragraph.text.clear();
paragraph.links.clear();
let laid = &mut paragraph.laid;
laid.bits.clear();
laid.stops.clear();
for piece in pieces {
let start = paragraph.text.len() as u32;
paragraph.text.push_str(piece.words);
let words = [start, paragraph.text.len() as u32];
let font = Font { face: face_of(piece.face.unwrap_or(t.font.face), piece.look), size: if piece.size > 0.0 { piece.size } else { t.font.size }, rule: piece.look.rule };
let link = if piece.look.link != 0 { paragraph.links.len() as u32 + 1 } else { 0 };
let color = piece.color.unwrap_or(if link != 0 { t.accent } else { t.text });
let back = piece.back.unwrap_or(if piece.look.mono { t.hover } else { Color::NONE });
laid.bits.push(Bit::new(words, font, color, back, link, piece.thing));
paragraph.links.push(words);
}
paragraph.long = laid.measure(0..laid.bits.len(), ¶graph.text, self.text.as_mut(), scale, &mut Vec::new());
}
if width == paragraph.width {
return;
}
let laid = &mut paragraph.laid;
(laid.rows, laid.frags, paragraph.width) = (Vec::new(), Vec::new(), width);
let [above, below] = heights(self.text.as_mut(), t.font, scale, &mut Vec::new());
let room = Room { above, below, high: 0.0, left: 0.0, wide: width.max(1.0), side: Align::Start };
paragraph.high = lay(laid, 0..laid.bits.len() as u32, ¶graph.text, 0, room, 0.0, scale);
}
}
pub(crate) fn row_of(laid: &Laid, frag: u32) -> u32 {
laid.rows.partition_point(|row| row.frags[1] <= frag) as u32
}
fn piece_key(piece: &Piece) -> u64 {
let look = piece.look;
let flags = look.bold as u64 | (look.italic as u64) << 1 | (look.mono as u64) << 2 | (look.rule as u64) << 3 | (look.link as u64) << 5;
let thing = match piece.thing {
Thing::Icon(icon) => hash((icon.path, icon.view.to_bits(), icon.stroke.to_bits())),
Thing::Picture(picture, [wide, high]) => hash((picture.0, wide.to_bits(), high.to_bits())),
_ => 0,
};
hash((piece.words, flags, piece.size.to_bits(), piece.face, piece.color, piece.back, thing))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::text::BuiltInFont;
fn rows_of(pieces: &[(&str, Font)], wide: f32) -> Vec<Vec<String>> {
let mut laid = Laid::default();
let mut text = String::new();
for (words, font) in pieces {
let start = text.len() as u32;
text.push_str(words);
laid.bits.push(Bit::new([start, text.len() as u32], *font, Color::WHITE, Color::NONE, 0, Thing::Words));
}
laid.measure(0..laid.bits.len(), &text, &mut BuiltInFont, 1.0, &mut Vec::new());
let room = Room { above: 0.0, below: 0.0, high: 0.0, left: 0.0, wide, side: Align::Start };
let count = laid.bits.len() as u32;
lay(&mut laid, 0..count, &text, 0, room, 0.0, 1.0);
let frags = |row: &Row| laid.frags[row.frags[0] as usize..row.frags[1] as usize].iter().map(|frag| text[frag.words[0] as usize..frag.words[1] as usize].to_string()).collect();
laid.rows.iter().map(frags).collect()
}
#[test]
fn pieces_break_into_rows_together_at_spaces() {
let (plain, bold) = (Font::new(8.0), Font::new(8.0).bold());
assert_eq!(rows_of(&[("fix the ", plain), ("jump", bold), (" arc", plain)], 60.0), [vec!["fix the"], vec!["jump", " arc"]]);
assert_eq!(rows_of(&[("abcdefghij", plain)], 24.0), [vec!["abcd"], vec!["efgh"], vec!["ij"]]);
assert_eq!(rows_of(&[("one\n", plain), ("two", bold)], 100.0), [vec!["one"], vec!["two"]]);
assert_eq!(rows_of(&[("aa ", plain), ("bb", bold), ("cc", plain)], 36.0), [vec!["aa"], vec!["bb", "cc"]]);
}
#[test]
fn places_in_a_row_are_found_both_ways() {
let mut laid = Laid::default();
let text = "ab cd";
laid.bits.push(Bit::new([0, 2], Font::new(8.0), Color::WHITE, Color::NONE, 0, Thing::Words));
laid.bits.push(Bit::new([2, 5], Font::new(8.0).bold(), Color::WHITE, Color::NONE, 0, Thing::Words));
laid.measure(0..2, text, &mut BuiltInFont, 1.0, &mut Vec::new());
let room = Room { above: 0.0, below: 0.0, high: 0.0, left: 0.0, wide: 100.0, side: Align::Start };
lay(&mut laid, 0..2, text, 0, room, 0.0, 1.0);
assert_eq!([0, 1, 2, 3, 5].map(|at| laid.x_at(text, 0, at)), [0.0, 6.0, 12.0, 19.0, 33.0]);
assert_eq!([-5.0, 2.0, 4.0, 13.0, 16.0, 40.0].map(|x| laid.at_x(text, 0, x)), [0, 0, 1, 2, 3, 5]);
}
#[test]
fn a_face_takes_what_a_look_adds() {
let bold = Look { bold: true, ..Look::default() };
assert_eq!([face_of(Face::Regular, bold), face_of(Face::Bold, bold), face_of(Face::Regular, Look { mono: true, ..bold })], [Face::Bold, Face::Bold, Face::Mono.weight(700)]);
assert_eq!(face_of(Face::Regular, Look { italic: true, ..Look::default() }), Face::Italic);
assert_eq!(face_of(Face::Bold, Look { italic: true, ..Look::default() }), Face::Bold.italic());
}
}