New Typography type

This commit is contained in:
Adam
2025-09-07 21:16:05 -07:00
parent 485152bf8d
commit 08b25f689e
13 changed files with 356 additions and 71 deletions

View File

@@ -1,4 +1,4 @@
use crate::{Color, gradient::GradientStops};
use crate::{Color, gradient::GradientStops, text::Typography};
use glam::{DAffine2, DVec2};
#[derive(Clone, Copy, Default, Debug, PartialEq)]
@@ -38,3 +38,9 @@ impl BoundingBox for GradientStops {
RenderBoundingBox::Infinite
}
}
impl BoundingBox for Typography {
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
let bbox = DVec2::new(self.layout.full_width() as f64, self.layout.height() as f64);
RenderBoundingBox::Rectangle([transform.transform_point2(DVec2::ZERO), transform.transform_point2(bbox)])
}
}

View File

@@ -7,3 +7,10 @@ pub const LAYER_OUTLINE_STROKE_WEIGHT: f64 = 0.5;
// Fonts
pub const DEFAULT_FONT_FAMILY: &str = "Cabin";
pub const DEFAULT_FONT_STYLE: &str = "Regular (400)";
// Load Source Sans Pro font data
// TODO: Grab this from the node_modules folder (either with `include_bytes!` or ideally at runtime) instead of checking the font file into the repo.
// TODO: And maybe use the WOFF2 version (if it's supported) for its smaller, compressed file size.
pub const SOURCE_SANS_FONT_DATA: &[u8] = include_bytes!("text/source-sans-pro-regular.ttf");
pub const SOURCE_SANS_FONT_FAMILY: &str = "Source Sans Pro";
pub const SOURCE_SANS_FONT_STYLE: &str = "Regular (400)";

View File

@@ -3,6 +3,7 @@ use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::gradient::GradientStops;
use crate::raster_types::{CPU, GPU, Raster};
use crate::table::{Table, TableRow};
use crate::text::Typography;
use crate::uuid::NodeId;
use crate::vector::Vector;
use crate::{Artboard, Color, Ctx};
@@ -11,7 +12,7 @@ use glam::{DAffine2, DVec2};
use std::hash::Hash;
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
#[derive(Clone, Debug, Hash, PartialEq, DynAny, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Debug, Hash, PartialEq, DynAny)]
pub enum Graphic {
Graphic(Table<Graphic>),
Vector(Table<Vector>),
@@ -19,6 +20,26 @@ pub enum Graphic {
RasterGPU(Table<Raster<GPU>>),
Color(Table<Color>),
Gradient(Table<GradientStops>),
Typography(Table<Typography>),
}
impl serde::Serialize for Graphic {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let default: Table<Graphic> = Table::new();
default.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for Graphic {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Graphic::Graphic(Table::new()))
}
}
impl Default for Graphic {
@@ -232,6 +253,7 @@ impl Graphic {
Graphic::RasterGPU(raster) => raster.iter().all(|row| row.alpha_blending.clip),
Graphic::Color(color) => color.iter().all(|row| row.alpha_blending.clip),
Graphic::Gradient(gradient) => gradient.iter().all(|row| row.alpha_blending.clip),
Graphic::Typography(typography) => typography.iter().all(|row| row.alpha_blending.clip),
}
}
@@ -256,6 +278,7 @@ impl BoundingBox for Graphic {
Graphic::Graphic(graphic) => graphic.bounding_box(transform, include_stroke),
Graphic::Color(color) => color.bounding_box(transform, include_stroke),
Graphic::Gradient(gradient) => gradient.bounding_box(transform, include_stroke),
Graphic::Typography(typography) => typography.bounding_box(transform, include_stroke),
}
}
}
@@ -507,34 +530,15 @@ pub fn migrate_graphic<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Res
elements: Vec<(Graphic, Option<NodeId>)>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OlderTable<T> {
id: Vec<u64>,
#[serde(alias = "instances", alias = "instance")]
element: Vec<T>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OldTable<T> {
id: Vec<u64>,
#[serde(alias = "instances", alias = "instance")]
element: Vec<T>,
transform: Vec<DAffine2>,
alpha_blending: Vec<AlphaBlending>,
}
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum GraphicFormat {
enum EitherFormat {
OldGraphicGroup(OldGraphicGroup),
OlderTableOldGraphicGroup(OlderTable<OldGraphicGroup>),
OldTableOldGraphicGroup(OldTable<OldGraphicGroup>),
OldTableGraphicGroup(OldTable<GraphicGroup>),
Table(serde_json::Value),
}
Ok(match GraphicFormat::deserialize(deserializer)? {
GraphicFormat::OldGraphicGroup(old) => {
Ok(match EitherFormat::deserialize(deserializer)? {
EitherFormat::OldGraphicGroup(old) => {
let mut graphic_table = Table::new();
for (graphic, source_node_id) in old.elements {
graphic_table.push(TableRow {
@@ -546,43 +550,7 @@ pub fn migrate_graphic<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Res
}
graphic_table
}
GraphicFormat::OlderTableOldGraphicGroup(old) => old
.element
.into_iter()
.flat_map(|element| {
element.elements.into_iter().map(move |(graphic, source_node_id)| TableRow {
element: graphic,
transform: element.transform,
alpha_blending: element.alpha_blending,
source_node_id,
})
})
.collect(),
GraphicFormat::OldTableOldGraphicGroup(old) => old
.element
.into_iter()
.flat_map(|element| {
element.elements.into_iter().map(move |(graphic, source_node_id)| TableRow {
element: graphic,
transform: element.transform,
alpha_blending: element.alpha_blending,
source_node_id,
})
})
.collect(),
GraphicFormat::OldTableGraphicGroup(old) => old
.element
.into_iter()
.flat_map(|element| {
element.elements.into_iter().map(move |(graphic, source_node_id)| TableRow {
element: graphic,
transform: Default::default(),
alpha_blending: Default::default(),
source_node_id,
})
})
.collect(),
GraphicFormat::Table(value) => {
EitherFormat::Table(value) => {
// Try to deserialize as either table format
if let Ok(old_table) = serde_json::from_value::<Table<GraphicGroup>>(value.clone()) {
let mut graphic_table = Table::new();

View File

@@ -1,6 +1,7 @@
use crate::gradient::GradientStops;
use crate::raster_types::{CPU, GPU, Raster};
use crate::table::Table;
use crate::text::Typography;
use crate::vector::Vector;
use crate::{Artboard, Color, Graphic};
@@ -31,6 +32,7 @@ impl RenderComplexity for Graphic {
Self::RasterGPU(table) => table.render_complexity(),
Self::Color(table) => table.render_complexity(),
Self::Gradient(table) => table.render_complexity(),
Self::Typography(table) => table.render_complexity(),
}
}
}
@@ -65,3 +67,9 @@ impl RenderComplexity for GradientStops {
1
}
}
impl RenderComplexity for Typography {
fn render_complexity(&self) -> usize {
1
}
}

View File

@@ -1,10 +1,23 @@
mod font_cache;
mod to_path;
use std::{
borrow::Cow,
collections::{HashMap, hash_map::Entry},
fmt,
sync::{Arc, Mutex},
};
use dyn_any::DynAny;
pub use font_cache::*;
use graphene_core_shaders::color::Color;
use parley::{Layout, StyleProperty};
use rustc_hash::FxHasher;
use std::hash::{Hash, Hasher};
pub use to_path::*;
use crate::{consts::*, table::Table, vector::Vector};
/// Alignment of lines of type within a text block.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash, DynAny, specta::Type, node_macro::ChoiceType)]
@@ -29,3 +42,142 @@ impl From<TextAlign> for parley::Alignment {
}
}
}
#[derive(Clone, DynAny)]
pub struct Typography {
pub layout: Layout<()>,
pub font_family: String,
pub color: Color,
pub stroke: Option<(Color, f64)>,
}
impl fmt::Debug for Typography {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Typography")
.field("font_family", &self.font_family)
.field("color", &self.color)
.field("stroke", &self.stroke)
.finish()
}
}
impl PartialEq for Typography {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Hash for Typography {
fn hash<H: Hasher>(&self, state: &mut H) {
self.layout.len().hash(state);
}
}
impl Typography {
pub fn to_vector(&self) -> Table<Vector> {
Table::new()
}
}
#[derive(Clone)]
pub struct NewFontCacheWrapper(pub Arc<Mutex<NewFontCache>>);
impl fmt::Debug for NewFontCacheWrapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("font cache").finish()
}
}
impl PartialEq for NewFontCacheWrapper {
fn eq(&self, _other: &Self) -> bool {
log::error!("Font cache should not be compared");
false
}
}
unsafe impl dyn_any::StaticType for NewFontCacheWrapper {
type Static = NewFontCacheWrapper;
}
pub struct NewFontCache {
pub font_context: parley::FontContext,
pub layout_context: parley::LayoutContext<()>,
pub font_mapping: HashMap<Font, (String, parley::fontique::FontInfo)>,
pub hash: u64,
}
impl NewFontCache {
pub fn new() -> Self {
let mut new = NewFontCache {
font_context: parley::FontContext::new(),
layout_context: parley::LayoutContext::new(),
font_mapping: HashMap::new(),
hash: 0,
};
let source_sans_font = Font::new(SOURCE_SANS_FONT_FAMILY.to_string(), SOURCE_SANS_FONT_STYLE.to_string());
new.register_font(source_sans_font, SOURCE_SANS_FONT_DATA.to_vec());
new
}
pub fn register_font(&mut self, font: Font, data: Vec<u8>) {
match self.font_mapping.entry(font) {
Entry::Occupied(occupied_entry) => {
log::error!("Trying to register font that already is added: {:?}", occupied_entry.key());
}
Entry::Vacant(vacant_entry) => {
let registered_font = self.font_context.collection.register_fonts(parley::fontique::Blob::from(data), None);
if registered_font.len() > 1 {
log::error!("Registered multiple fonts for {:?}. Only the first is accessible", vacant_entry.key());
};
match registered_font.into_iter().next() {
Some((family_id, font_info)) => {
let Some(family_name) = self.font_context.collection.family_name(family_id) else {
log::error!("Could not get family name for font: {:?}", vacant_entry.key());
return;
};
let Some(font_info) = font_info.into_iter().next() else {
log::error!("Could not get font info for font: {:?}", vacant_entry.key());
return;
};
let mut hasher = FxHasher::default(); // or FxHasher::new()
// Hash the Font for a unique id and add it to the cached hash
vacant_entry.key().hash(&mut hasher);
let hash_value = hasher.finish();
self.hash = self.hash.wrapping_add(hash_value);
vacant_entry.insert((family_name.to_string(), font_info));
}
None => log::error!("Could not register font for {:?}", vacant_entry.key()),
}
}
}
}
pub fn generate_typography(&mut self, font: &Font, font_size: f32, text: &str) -> Option<Typography> {
let Some((font_family, font_info)) = self.font_mapping.get(font) else {
log::error!("Font not loaded: {:?}", font);
return None;
};
let font_family = font_family.to_string();
let mut builder = self.layout_context.ranged_builder(&mut self.font_context, text, 1., false);
builder.push_default(StyleProperty::FontStack(parley::FontStack::Single(parley::FontFamily::Named(Cow::Owned(font_family.clone())))));
builder.push_default(StyleProperty::FontSize(font_size));
builder.push_default(StyleProperty::FontWeight(font_info.weight()));
builder.push_default(StyleProperty::FontStyle(font_info.style()));
builder.push_default(StyleProperty::FontWidth(font_info.width()));
let mut layout: Layout<()> = builder.build(text);
layout.break_all_lines(None);
// layout.align(None, parley::Alignment::Start, AlignmentOptions::);
Some(Typography {
layout,
font_family,
color: Color::BLACK,
stroke: None,
})
}
}

Binary file not shown.