use crate::geometry::{Color, Rect, Size};
use crate::text::style::*;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
pub struct Glyph {
pub id: u32,
pub x: f32,
pub y: f32,
pub advance: f32,
pub cluster: u32,
}
#[derive(Debug, Clone)]
pub struct TextRun {
pub text: String,
pub font_data: Arc<Vec<u8>>,
pub font_index: u32,
pub font_size: f32,
pub font_weight_bold: bool,
pub font_style_italic: bool,
pub color: Color,
pub advance: f32,
pub glyphs: Vec<Glyph>,
pub is_rtl: bool,
pub baseline_x: f32,
pub baseline_y: f32,
pub url: Option<String>,
pub decoration: TextDecoration,
pub baseline_shift: f32,
pub background_color: Option<Color>,
}
impl TextRun {
#[must_use]
pub fn split_at(&self, offsets: &[usize]) -> Vec<TextRun> {
let len = self.text.len();
let mut cuts: Vec<usize> = offsets.to_vec();
cuts.retain(|&o| {
o > 0
&& o < len
&& self.text.is_char_boundary(o)
&& self.glyphs.iter().any(|g| g.cluster as usize == o)
});
cuts.sort_unstable();
cuts.dedup();
if cuts.is_empty() {
return vec![self.clone()];
}
let mut bounds = cuts;
bounds.insert(0, 0);
bounds.push(len);
let mut out = Vec::with_capacity(bounds.len() - 1);
for w in bounds.windows(2) {
let (start, end) = (w[0], w[1]);
let glyphs: Vec<Glyph> = self
.glyphs
.iter()
.filter(|g| {
let c = g.cluster as usize;
c >= start && c < end
})
.map(|g| Glyph {
cluster: g.cluster - start as u32,
..g.clone()
})
.collect();
if glyphs.is_empty() {
continue;
}
let advance: f32 = glyphs.iter().map(|g| g.advance).sum();
let baseline_x = glyphs[0].x;
out.push(TextRun {
text: self.text[start..end].to_string(),
advance,
glyphs,
baseline_x,
..self.clone()
});
}
out
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LineMetrics {
pub ascent: f32,
pub descent: f32,
pub baseline: f32,
pub line_height: f32,
}
#[derive(Debug, Clone)]
pub struct TextLine {
pub runs: Vec<TextRun>,
pub bounds: Rect,
pub metrics: LineMetrics,
pub ink_bounds: Rect,
}
#[derive(Debug, Clone)]
pub struct TextLayout {
pub lines: Vec<TextLine>,
pub width: f64,
pub height: f64,
pub ink_bounds: Rect,
}
impl TextLayout {
pub fn ink_bounds(&self) -> Rect {
self.ink_bounds
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextMetrics {
pub width: f64,
pub height: f64,
pub actual_bounding_box_left: f64,
pub actual_bounding_box_right: f64,
pub font_bounding_box_ascent: f64,
pub font_bounding_box_descent: f64,
pub actual_bounding_box_ascent: f64,
pub actual_bounding_box_descent: f64,
pub em_height_ascent: f64,
pub em_height_descent: f64,
pub hanging_baseline: f64,
pub alphabetic_baseline: f64,
pub ideographic_baseline: f64,
pub line_height: f64,
}
pub struct TextMeasure {
pub size: Size,
pub metrics: TextMetrics,
pub layout: Arc<TextLayout>,
}