Refactor the text layouting ♻

This commit is contained in:
Laurenz 2019-10-14 23:33:29 +02:00
parent c768b8b61f
commit 5473e3903a
2 changed files with 103 additions and 78 deletions

View File

@ -14,6 +14,7 @@ pub struct StackLayouter {
/// The context for the [`StackLayouter`]. /// The context for the [`StackLayouter`].
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub struct StackContext { pub struct StackContext {
/// The space to layout the boxes in.
pub space: LayoutSpace, pub space: LayoutSpace,
} }

View File

@ -1,4 +1,4 @@
use toddle::query::{FontQuery, SharedFontLoader}; use toddle::query::{SharedFontLoader, FontQuery, FontClass};
use toddle::tables::{CharMap, Header, HorizontalMetrics}; use toddle::tables::{CharMap, Header, HorizontalMetrics};
use super::*; use super::*;
@ -13,82 +13,106 @@ pub struct TextContext<'a, 'p> {
pub style: &'a TextStyle, pub style: &'a TextStyle,
} }
/// Layout one piece of text without any breaks as one continous box. /// Layouts text into a box.
///
/// There is no complex layout involved. The text is simply laid out left-
/// to-right using the correct font for each character.
pub fn layout_text(text: &str, ctx: TextContext) -> LayoutResult<Layout> { pub fn layout_text(text: &str, ctx: TextContext) -> LayoutResult<Layout> {
let mut loader = ctx.loader.borrow_mut(); TextLayouter::new(text, ctx).layout()
}
let mut actions = Vec::new();
let mut active_font = std::usize::MAX; /// Layouts text into boxes.
let mut buffer = String::new(); struct TextLayouter<'a, 'p> {
let mut width = Size::zero(); ctx: TextContext<'a, 'p>,
text: &'a str,
// Walk the characters. actions: LayoutActionList,
for character in text.chars() { buffer: String,
// Retrieve the best font for this character. active_font: usize,
let mut font = None; width: Size,
let mut classes = ctx.style.classes.clone(); classes: Vec<FontClass>,
for class in &ctx.style.fallback { }
classes.push(class.clone());
impl<'a, 'p> TextLayouter<'a, 'p> {
font = loader.get(FontQuery { /// Create a new text layouter.
chars: &[character], fn new(text: &'a str, ctx: TextContext<'a, 'p>) -> TextLayouter<'a, 'p> {
classes: &classes, TextLayouter {
}); ctx,
text,
if font.is_some() { actions: LayoutActionList::new(),
break; buffer: String::new(),
} active_font: std::usize::MAX,
width: Size::zero(),
classes.pop(); classes: ctx.style.classes.clone(),
} }
}
let (font, index) = match font {
Some(f) => f, /// Layout the text
None => return Err(LayoutError::NoSuitableFont(character)), fn layout(mut self) -> LayoutResult<Layout> {
}; for c in self.text.chars() {
let (index, char_width) = self.select_font(c)?;
// Create a conversion function between font units and sizes.
let font_unit_ratio = 1.0 / (font.read_table::<Header>()?.units_per_em as f32); self.width += char_width;
let font_unit_to_size = |x| Size::pt(font_unit_ratio * x);
if self.active_font != index {
// Add the char width to the total box width. if !self.buffer.is_empty() {
let glyph = font self.actions.add(LayoutAction::WriteText(self.buffer));
.read_table::<CharMap>()? self.buffer = String::new();
.get(character) }
.expect("layout text: font should have char");
self.actions.add(LayoutAction::SetFont(index, self.ctx.style.font_size));
let glyph_width = font_unit_to_size( self.active_font = index;
font.read_table::<HorizontalMetrics>()? }
.get(glyph)
.expect("layout text: font should have glyph") self.buffer.push(c);
.advance_width as f32, }
);
if !self.buffer.is_empty() {
let char_width = glyph_width * ctx.style.font_size; self.actions.add(LayoutAction::WriteText(self.buffer));
width += char_width; }
// Change the font if necessary. Ok(Layout {
if active_font != index { dimensions: Size2D::new(self.width, Size::pt(self.ctx.style.font_size)),
if !buffer.is_empty() { actions: self.actions.into_vec(),
actions.push(LayoutAction::WriteText(buffer)); debug_render: false,
buffer = String::new(); })
} }
actions.push(LayoutAction::SetFont(index, ctx.style.font_size)); /// Select the best font for a character and return its index along with
active_font = index; /// the width of the char in the font.
} fn select_font(&mut self, c: char) -> LayoutResult<(usize, Size)> {
let mut loader = self.ctx.loader.borrow_mut();
buffer.push(character);
} for class in &self.ctx.style.fallback {
self.classes.push(class.clone());
// Write the remaining characters.
if !buffer.is_empty() { let query = FontQuery {
actions.push(LayoutAction::WriteText(buffer)); chars: &[c],
} classes: &self.classes,
};
Ok(Layout {
dimensions: Size2D::new(width, Size::pt(ctx.style.font_size)), if let Some((font, index)) = loader.get(query) {
actions, let font_unit_ratio = 1.0 / (font.read_table::<Header>()?.units_per_em as f32);
debug_render: false, let font_unit_to_size = |x| Size::pt(font_unit_ratio * x);
})
let glyph = font
.read_table::<CharMap>()?
.get(c)
.expect("layout text: font should have char");
let glyph_width = font
.read_table::<HorizontalMetrics>()?
.get(glyph)
.expect("layout text: font should have glyph")
.advance_width as f32;
let char_width = font_unit_to_size(glyph_width) * self.ctx.style.font_size;
return Ok((index, char_width));
}
self.classes.pop();
}
Err(LayoutError::NoSuitableFont(c))
}
} }