use crate::vector_font::VectorFont;
#[doc(hidden)]
pub const MEASURE_FONT_PX: f64 = 64.0;
#[derive(Clone, Debug, PartialEq)]
pub enum Anchor {
Offset(f64),
Named(String),
}
impl Anchor {
pub fn named(s: &str) -> Self {
Anchor::Named(s.to_string())
}
fn resolve(&self, extent: f64, axis_x: bool) -> f64 {
match self {
Anchor::Offset(n) => -n,
Anchor::Named(name) => {
let s = name.as_str();
if axis_x {
match s {
"left" => 0.0,
"center" => -extent * 0.5,
"right" => -extent,
_ => 0.0,
}
} else {
match s {
"top" => -extent,
"middle" | "center" => -extent * 0.5,
"bottom" => 0.0,
_ => 0.0,
}
}
}
}
}
}
impl Default for Anchor {
fn default() -> Self {
Anchor::Offset(0.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LineHeight {
Normal,
Factor(f64),
}
impl LineHeight {
pub fn parse(s: &str) -> Self {
if s == "normal" {
return LineHeight::Normal;
}
match parse_float(s) {
Some(n) if n.is_finite() => LineHeight::Factor(n),
_ => LineHeight::Normal,
}
}
fn resolve_canvas(&self, font_size: f64) -> f64 {
match self {
LineHeight::Normal => font_size * 1.2,
LineHeight::Factor(n) => n * font_size,
}
}
}
fn parse_float(s: &str) -> Option<f64> {
let t = s.trim_start();
let bytes = t.as_bytes();
let mut end = 0;
let mut seen_digit = false;
let mut seen_dot = false;
let mut seen_exp = false;
while end < bytes.len() {
let c = bytes[end];
match c {
b'+' | b'-' if end == 0 => {}
b'+' | b'-' if seen_exp && matches!(bytes[end - 1], b'e' | b'E') => {}
b'0'..=b'9' => seen_digit = true,
b'.' if !seen_dot && !seen_exp => seen_dot = true,
b'e' | b'E' if seen_digit && !seen_exp => seen_exp = true,
_ => break,
}
end += 1;
}
if !seen_digit {
return None;
}
let mut slice = &t[..end];
while !slice.is_empty()
&& matches!(slice.as_bytes()[slice.len() - 1], b'e' | b'E' | b'+' | b'-')
{
slice = &slice[..slice.len() - 1];
}
slice.parse::<f64>().ok()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TextAlign {
#[default]
Left,
Center,
Right,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct LayoutParams {
pub text: String,
pub font_size: f64,
pub font_family: String,
pub font_weight: String,
pub font_style: String,
pub letter_spacing: f64,
pub line_height: LineHeight,
pub anchor_x: Anchor,
pub anchor_y: Anchor,
pub text_align: TextAlign,
pub max_width: f64,
}
impl Default for LayoutParams {
fn default() -> Self {
LayoutParams {
text: String::new(),
font_size: 1.0,
font_family: "monospace".to_string(),
font_weight: "normal".to_string(),
font_style: "normal".to_string(),
letter_spacing: 0.0,
line_height: LineHeight::Normal,
anchor_x: Anchor::Offset(0.0),
anchor_y: Anchor::Offset(0.0),
text_align: TextAlign::Left,
max_width: f64::INFINITY,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct LaidOutGlyph {
pub ch: char,
pub bounds: [f64; 4],
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct TextRenderInfo {
pub parameters: LayoutParams,
pub glyph_bounds: Vec<f32>,
pub glyphs: Vec<LaidOutGlyph>,
pub glyph_count: usize,
pub block_bounds: [f64; 4],
pub visible_bounds: [f64; 4],
pub line_height: f64,
pub ascender: f64,
pub descender: f64,
}
pub fn empty_render_info(params: LayoutParams) -> TextRenderInfo {
TextRenderInfo {
parameters: params,
glyph_bounds: Vec::new(),
glyphs: Vec::new(),
glyph_count: 0,
block_bounds: [0.0; 4],
visible_bounds: [0.0; 4],
line_height: 0.0,
ascender: 0.0,
descender: 0.0,
}
}
fn split_lines(text: &str) -> Vec<String> {
text.split('\n').map(|s| s.to_string()).collect()
}
fn split_words_keeping_gaps(paragraph: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut in_space = false;
for ch in paragraph.chars() {
let is_space = is_js_whitespace(ch);
if is_space != in_space {
out.push(std::mem::take(&mut cur));
in_space = is_space;
}
cur.push(ch);
}
out.push(cur);
out
}
fn is_js_whitespace(ch: char) -> bool {
matches!(
ch,
'\t' | '\n' | '\u{0b}' | '\u{0c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
..='\u{200a}'
| '\u{2028}'
| '\u{2029}'
| '\u{202f}'
| '\u{205f}'
| '\u{3000}'
| '\u{feff}'
)
}
fn trim_start_js(s: &str) -> &str {
s.trim_start_matches(is_js_whitespace)
}
fn break_lines(text: &str, max_width: f64, measure: &mut dyn FnMut(&str) -> f64) -> Vec<String> {
if !max_width.is_finite() || max_width <= 0.0 {
return split_lines(text);
}
let mut lines: Vec<String> = Vec::new();
for paragraph in split_lines(text) {
if paragraph.is_empty() {
lines.push(String::new());
continue;
}
let mut line = String::new();
for word in split_words_keeping_gaps(¶graph) {
let test = format!("{line}{word}");
let w = measure(&test);
if !line.is_empty() && w > max_width {
lines.push(std::mem::take(&mut line));
line = trim_start_js(&word).to_string();
} else {
line = test;
}
}
if !line.is_empty() || paragraph.is_empty() {
lines.push(line);
}
}
if lines.is_empty() {
vec![String::new()]
} else {
lines
}
}
fn finish(
params: LayoutParams,
glyphs: Vec<LaidOutGlyph>,
mut block: [f64; 4],
line_height: f64,
ascender: f64,
descender: f64,
) -> TextRenderInfo {
if glyphs.is_empty() {
block = [0.0; 4];
}
let [block_min_x, block_min_y, block_max_x, block_max_y] = block;
let block_width = block_max_x - block_min_x;
let block_height = block_max_y - block_min_y;
let offset_x = params.anchor_x.resolve(block_width, true) - block_min_x;
let offset_y = params.anchor_y.resolve(block_height, false) - block_min_y;
let mut glyph_bounds = Vec::with_capacity(glyphs.len() * 4);
for g in &glyphs {
glyph_bounds.push((g.bounds[0] + offset_x) as f32);
glyph_bounds.push((g.bounds[1] + offset_y) as f32);
glyph_bounds.push((g.bounds[2] + offset_x) as f32);
glyph_bounds.push((g.bounds[3] + offset_y) as f32);
}
let anchored = [
block_min_x + offset_x,
block_min_y + offset_y,
block_max_x + offset_x,
block_max_y + offset_y,
];
TextRenderInfo {
parameters: params,
glyph_bounds,
glyph_count: glyphs.len(),
glyphs,
block_bounds: anchored,
visible_bounds: anchored,
line_height,
ascender,
descender,
}
}
fn measure_run_width_no_ctx(s: &str, scale: f64) -> f64 {
if s.is_empty() {
return 0.0;
}
s.chars().count() as f64 * 0.6 * scale
}
pub fn layout_text(params: LayoutParams) -> TextRenderInfo {
let font_size = params.font_size;
let scale = font_size / MEASURE_FONT_PX;
let line_advance = params.line_height.resolve_canvas(font_size);
let lines = break_lines(¶ms.text, params.max_width, &mut |s| {
measure_run_width_no_ctx(s, scale)
});
let mut glyphs: Vec<LaidOutGlyph> = Vec::new();
let mut block = [
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
];
let mut baseline_y = 0.0f64;
for line in &lines {
let line_width = 0.0f64;
let align_offset = match params.text_align {
TextAlign::Center => (params.max_width - line_width) * 0.5,
TextAlign::Right => params.max_width - line_width,
TextAlign::Left => 0.0,
};
let mut pen_x = align_offset;
for ch in line.chars() {
let char_width = MEASURE_FONT_PX * 0.6 * scale;
let advance = char_width + params.letter_spacing;
let min_x = pen_x;
let max_x = pen_x + char_width;
let min_y = baseline_y - font_size * 0.2;
let max_y = baseline_y + font_size * 0.8;
glyphs.push(LaidOutGlyph {
ch,
bounds: [min_x, min_y, max_x, max_y],
});
block[0] = block[0].min(min_x);
block[1] = block[1].min(min_y);
block[2] = block[2].max(max_x);
block[3] = block[3].max(max_y);
pen_x += advance;
}
baseline_y -= line_advance;
}
finish(
params,
glyphs,
block,
line_advance,
font_size * 0.8,
-font_size * 0.2,
)
}
fn vec_line_advance(line_height: LineHeight, font: &VectorFont, font_size: f64) -> f64 {
let scale = font_size / font.units_per_em;
let natural = (font.ascender - font.descender + font.line_gap) * scale;
match line_height {
LineHeight::Normal => natural,
LineHeight::Factor(n) if n.is_finite() => n * font_size,
LineHeight::Factor(_) => natural,
}
}
pub(crate) fn vec_measure_run(font: &VectorFont, s: &str, letter_spacing: f64, scale: f64) -> f64 {
let chars: Vec<char> = s.chars().collect();
let mut w = 0.0;
for i in 0..chars.len() {
w += font.advance_width(chars[i]) * scale;
if i + 1 < chars.len() {
w += font.kerning(chars[i], chars[i + 1]) * scale + letter_spacing;
}
}
w
}
pub fn layout_text_vector(params: LayoutParams, font: Option<&VectorFont>) -> TextRenderInfo {
let Some(font) = font else {
return empty_render_info(params);
};
let font_size = params.font_size;
let scale = font_size / font.units_per_em;
let ascender = font.ascender * scale;
let descender = font.descender * scale;
let line_advance = vec_line_advance(params.line_height, font, font_size);
let letter_spacing = params.letter_spacing;
let lines = break_lines(¶ms.text, params.max_width, &mut |s| {
vec_measure_run(font, s, letter_spacing, scale)
});
let mut glyphs: Vec<LaidOutGlyph> = Vec::new();
let mut block = [
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
];
let mut baseline_y = 0.0f64;
for line in &lines {
let line_width = vec_measure_run(font, line, letter_spacing, scale);
let align_offset = match params.text_align {
TextAlign::Center => (params.max_width - line_width) * 0.5,
TextAlign::Right => params.max_width - line_width,
TextAlign::Left => 0.0,
};
let mut pen_x = align_offset;
let chars: Vec<char> = line.chars().collect();
for i in 0..chars.len() {
let ch = chars[i];
if i > 0 {
pen_x += font.kerning(chars[i - 1], ch) * scale;
}
let advance = font.advance_width(ch) * scale;
let bbox = if ch == ' ' {
None
} else {
font.bounding_box(ch)
};
let (min_x, min_y, max_x, max_y) = match bbox {
Some(b) => (
pen_x + b.x1 * scale,
baseline_y + b.y1 * scale,
pen_x + b.x2 * scale,
baseline_y + b.y2 * scale,
),
None => (
pen_x,
baseline_y + descender,
pen_x + advance,
baseline_y + ascender,
),
};
glyphs.push(LaidOutGlyph {
ch,
bounds: [min_x, min_y, max_x, max_y],
});
block[0] = block[0].min(min_x);
block[1] = block[1].min(min_y);
block[2] = block[2].max(max_x);
block[3] = block[3].max(max_y);
pen_x += advance + letter_spacing;
}
baseline_y -= line_advance;
}
finish(params, glyphs, block, line_advance, ascender, descender)
}