use std::fmt;
use azul_layout::text3::api::{layout_text, TextLayoutDirection, TextLayoutOptions};
use crate::{ParsedFont, PlacedGlyph, Pt};
pub const MAX_LINE_BYTES: usize = 65_536;
pub const MAX_LINE_FONT_SIZE: f32 = 100_000.0;
#[derive(Debug, Clone, PartialEq)]
pub struct PlacedLine {
pub glyphs: Vec<PlacedGlyph>,
pub width: Pt,
}
impl PlacedLine {
pub fn empty() -> Self {
Self { glyphs: Vec::new(), width: Pt(0.0) }
}
pub fn is_empty(&self) -> bool {
self.glyphs.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShapeLineError {
TooLong {
len: usize,
max: usize,
},
LineBreak,
InvalidSize,
Shaping,
}
impl fmt::Display for ShapeLineError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ShapeLineError::TooLong { len, max } => {
write!(f, "text of {len} bytes is longer than the limit of {max} bytes")
}
ShapeLineError::LineBreak => write!(f, "text contains a line break"),
ShapeLineError::InvalidSize => {
write!(f, "font size must be above 0 and at most {MAX_LINE_FONT_SIZE} pt")
}
ShapeLineError::Shaping => write!(f, "the font could not shape the text"),
}
}
}
impl std::error::Error for ShapeLineError {}
pub fn shape_line(font: &ParsedFont, text: &str, size: Pt) -> Result<PlacedLine, ShapeLineError> {
LineShaper::new(font).shape(text, size)
}
#[derive(Debug, Clone)]
pub struct LineShaper {
font: azul_css::props::basic::FontRef,
}
impl LineShaper {
pub fn new(font: &ParsedFont) -> Self {
Self { font: azul_layout::parsed_font_to_font_ref(font.as_azul().clone()) }
}
pub fn shape(&self, text: &str, size: Pt) -> Result<PlacedLine, ShapeLineError> {
if !(size.0 > 0.0 && size.0 <= MAX_LINE_FONT_SIZE) {
return Err(ShapeLineError::InvalidSize);
}
if text.len() > MAX_LINE_BYTES {
return Err(ShapeLineError::TooLong { len: text.len(), max: MAX_LINE_BYTES });
}
if text.chars().any(is_line_break) {
return Err(ShapeLineError::LineBreak);
}
if text.is_empty() {
return Ok(PlacedLine::empty());
}
let options = TextLayoutOptions {
direction: TextLayoutDirection::Auto,
..TextLayoutOptions::create(size.0)
};
let layout = layout_text(text, std::slice::from_ref(&self.font), &options)
.ok_or(ShapeLineError::Shaping)?;
let lines = layout.lines.as_ref();
if lines.len() > 1 {
return Err(ShapeLineError::LineBreak);
}
let Some(line) = lines.first() else {
return Ok(PlacedLine::empty());
};
let mut glyphs = Vec::new();
let mut width = 0.0f32;
for g in line.glyphs.as_ref() {
width = width.max(g.x + g.advance);
let cluster = text
.get(g.cluster_start as usize..g.cluster_end as usize)
.unwrap_or("");
if g.tab || (!cluster.is_empty() && cluster.chars().all(char::is_control)) {
continue;
}
let cluster = if g.first_in_cluster { cluster } else { "" };
glyphs.push(PlacedGlyph {
font: 0,
gid: g.glyph_id,
x: g.x + g.offset_x,
y: g.offset_y,
text: cluster.to_string(),
});
}
let width = if width.is_finite() { width.max(0.0) } else { 0.0 };
Ok(PlacedLine { glyphs, width: Pt(width) })
}
}
fn is_line_break(c: char) -> bool {
matches!(c, '\n' | '\r' | '\u{0B}' | '\u{0C}' | '\u{85}' | '\u{2028}' | '\u{2029}')
}