🎉 Store custom fonts (ttfs) and use them to write texts (wasm) (#6050)

This commit is contained in:
Belén Albeza 2025-03-14 12:45:15 +01:00 committed by GitHub
parent e4c9b736f7
commit eb6d2fb0eb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 386 additions and 140 deletions

View file

@ -0,0 +1,48 @@
use std::fmt;
use uuid::Uuid;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum FontStyle {
Normal,
Italic,
}
impl From<u8> for FontStyle {
fn from(value: u8) -> Self {
match value {
0 => Self::Normal,
1 => Self::Italic,
_ => Self::Normal,
}
}
}
impl fmt::Display for FontStyle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let txt = match self {
Self::Normal => "normal",
Self::Italic => "italic",
};
write!(f, "{}", txt)
}
}
#[derive(Debug, Clone, PartialEq, Copy)]
pub struct FontFamily {
id: Uuid,
style: FontStyle,
weight: u32,
}
impl FontFamily {
pub fn new(id: Uuid, weight: u32, style: FontStyle) -> Self {
Self { id, style, weight }
}
}
impl fmt::Display for FontFamily {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {} {}", self.id, self.weight, self.style)
}
}

View file

@ -4,6 +4,8 @@ use skia_safe::{
textlayout::{FontCollection, ParagraphBuilder},
};
use super::FontFamily;
#[derive(Debug, PartialEq, Clone)]
pub struct TextContent {
paragraphs: Vec<Paragraph>,
@ -38,15 +40,18 @@ impl TextContent {
self.paragraphs.push(p);
}
pub fn add_leaf(&mut self, text: &str) -> Result<(), String> {
pub fn add_leaf(
&mut self,
text: String,
font_family: FontFamily,
font_size: f32,
) -> Result<(), String> {
let paragraph = self
.paragraphs
.last_mut()
.ok_or("No paragraph to add text leaf to")?;
paragraph.add_leaf(TextLeaf {
text: text.to_owned(),
});
paragraph.add_leaf(TextLeaf::new(text, font_family, font_size));
Ok(())
}
@ -100,15 +105,29 @@ impl Paragraph {
#[derive(Debug, PartialEq, Clone)]
pub struct TextLeaf {
text: String,
font_family: FontFamily,
font_size: f32,
}
impl TextLeaf {
pub fn new(text: String, font_family: FontFamily, font_size: f32) -> Self {
Self {
text,
font_family,
font_size,
}
}
pub fn to_style(&self) -> skia::textlayout::TextStyle {
let mut style = skia::textlayout::TextStyle::default();
// TODO: read text style info from the shape
style.set_color(skia::Color::BLACK);
style.set_font_size(16.0);
style.set_font_size(self.font_size);
style.set_font_families(&[self.serialized_font_family()]);
style
}
fn serialized_font_family(&self) -> String {
format!("{}", self.font_family)
}
}