use core::ops::Range;
use glam::Vec2;
use super::Font;
use super::layout::TextAlign;
use crate::text::FontAtlas;
use crate::tree::inline::{InlineLayout, InlineRun, RunFont, Wrap};
#[derive(Clone, Copy, Debug)]
pub struct RichRun<'a> {
pub text: &'a str,
pub font: &'a Font,
pub size: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RichSegment {
pub run: usize,
pub text: Range<usize>,
pub x: f32,
pub width: f32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RichLine {
pub segments: Range<usize>,
pub top: f32,
pub baseline: f32,
pub height: f32,
pub width: f32,
pub rtl: bool,
}
#[derive(Clone, Debug)]
pub struct RichLayout {
inline: InlineLayout,
lines: Vec<RichLine>,
segments: Vec<RichSegment>,
}
impl RichLayout {
#[must_use]
pub fn new(runs: &[RichRun<'_>], line_height: f32, wrap: Option<f32>) -> Self {
let runs: Vec<InlineRun<'_>> = runs
.iter()
.map(|run| InlineRun::new(run.text, RunFont::Parsed(run.font), run.size, line_height))
.collect();
let wrap = wrap.map_or(Wrap::None, Wrap::Width);
let inline = InlineLayout::new(&runs, wrap, &FontAtlas::built_in());
let mut layout = Self {
inline,
lines: Vec::new(),
segments: Vec::new(),
};
layout.read();
layout
}
pub fn align(&mut self, width: f32, align: TextAlign) {
self.inline.align(width, align);
self.read();
}
#[must_use]
pub fn lines(&self) -> &[RichLine] {
&self.lines
}
#[must_use]
pub fn segments(&self) -> &[RichSegment] {
&self.segments
}
#[must_use]
pub fn line_segments(&self, line: &RichLine) -> &[RichSegment] {
&self.segments[line.segments.clone()]
}
#[must_use]
pub fn measure(&self) -> Vec2 {
self.inline.measure()
}
fn read(&mut self) {
self.segments = self
.inline
.fragments()
.iter()
.map(|fragment| RichSegment {
run: fragment.run,
text: fragment.text.clone(),
x: fragment.x,
width: fragment.width,
})
.collect();
self.lines = self
.inline
.lines()
.iter()
.map(|line| RichLine {
segments: line.fragments.clone(),
top: line.top,
baseline: line.baseline,
height: line.height,
width: line.width,
rtl: line.rtl,
})
.collect();
}
}
#[cfg(all(test, feature = "parsed-font"))]
mod tests;