From 1baba43903709d5ad5d83ce9580eb1c661d4b344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?charlotte=20=F0=9F=8C=B8?= Date: Tue, 1 Dec 2026 14:35:50 -0800 Subject: [PATCH] Text and formatting additions. --- crates/processing_ffi/src/lib.rs | 4 +- crates/processing_node/src/lib.rs | 4 +- crates/processing_pyo3/processing_py/math.py | 41 ++++++++++++ crates/processing_pyo3/src/graphics.rs | 52 +++++++++++--- crates/processing_pyo3/src/lib.rs | 26 ++++--- crates/processing_render/src/lib.rs | 67 ++++++++++++++++--- .../processing_render/src/render/command.rs | 1 + crates/processing_render/src/render/mod.rs | 16 ++++- crates/processing_render/src/text/font.rs | 3 +- crates/processing_wasm/src/lib.rs | 4 +- 10 files changed, 178 insertions(+), 40 deletions(-) diff --git a/crates/processing_ffi/src/lib.rs b/crates/processing_ffi/src/lib.rs index b0b153ef..a12dbaa6 100644 --- a/crates/processing_ffi/src/lib.rs +++ b/crates/processing_ffi/src/lib.rs @@ -1135,7 +1135,7 @@ pub extern "C" fn processing_end_contour(graphics_id: u64) { pub unsafe extern "C" fn processing_load_font(path_ptr: *const std::ffi::c_char) -> u64 { error::clear_error(); let path = unsafe { std::ffi::CStr::from_ptr(path_ptr) }.to_string_lossy(); - error::check(|| font_load(&path).map(|e| e.to_bits())).unwrap_or(0) + error::check(|| font_load(&path, None).map(|e| e.to_bits())).unwrap_or(0) } /// Create a font handle from an existing font family name. @@ -1147,7 +1147,7 @@ pub unsafe extern "C" fn processing_load_font(path_ptr: *const std::ffi::c_char) pub unsafe extern "C" fn processing_create_font(name_ptr: *const std::ffi::c_char) -> u64 { error::clear_error(); let name = unsafe { std::ffi::CStr::from_ptr(name_ptr) }.to_string_lossy(); - error::check(|| font_create(&name).map(|e| e.to_bits())).unwrap_or(0) + error::check(|| font_create(&name, None).map(|e| e.to_bits())).unwrap_or(0) } /// Query the number of variable font axes for a font. diff --git a/crates/processing_node/src/lib.rs b/crates/processing_node/src/lib.rs index 34d9b2f9..b4ec1bc7 100644 --- a/crates/processing_node/src/lib.rs +++ b/crates/processing_node/src/lib.rs @@ -924,12 +924,12 @@ pub fn js_end_contour(graphics_id: BigInt) -> Result<()> { #[napi(js_name = "loadFont")] pub fn js_load_font(path: String) -> Result { - check(font_load(&path)).map(id) + check(font_load(&path, None)).map(id) } #[napi(js_name = "createFont")] pub fn js_create_font(name: String) -> Result { - check(font_create(&name)).map(id) + check(font_create(&name, None)).map(id) } #[napi(js_name = "fontVariationCount")] diff --git a/crates/processing_pyo3/processing_py/math.py b/crates/processing_pyo3/processing_py/math.py index de9bbf8a..c4fe5435 100644 --- a/crates/processing_pyo3/processing_py/math.py +++ b/crates/processing_pyo3/processing_py/math.py @@ -1,6 +1,7 @@ """Processing math methods and vector/quaternion types.""" import math as _math import random as _random +from decimal import Decimal as _Decimal from .processing_py import math as _native_math # extend native math so glob imports work @@ -149,6 +150,46 @@ def random_seed(seed): _random.seed(seed) +def _nf(num, left, right, group=False, plus=""): + if isinstance(num, (list, tuple)): + return [_nf(n, left, right, group, plus) for n in num] + if num != num or num in (float("inf"), float("-inf")): + return str(num) + sign = "-" if num < 0 else plus + num = abs(num) + if right is not None: + text = f"{num:.{int(right)}f}" + elif float(num).is_integer(): + text = str(int(num)) + else: + text = format(_Decimal(repr(float(num))), "f") + whole, _, fraction = text.partition(".") + whole = whole.zfill(int(left or 0)) + if group: + whole = f"{int(whole):,}" + return sign + whole + ("." + fraction if fraction else "") + + +def nf(num, left=None, right=None): + """Number to text: at least `left` digits before the point (zero padded), exactly `right` after.""" + return _nf(num, left, right) + + +def nfc(num, right=None): + """Like `nf()`, with commas between thousands.""" + return _nf(num, None, right, group=True) + + +def nfp(num, left=None, right=None): + """Like `nf()`, with a `+` in front of positive numbers.""" + return _nf(num, left, right, plus="+") + + +def nfs(num, left=None, right=None): + """Like `nf()`, with a space in front of positive numbers.""" + return _nf(num, left, right, plus=" ") + + def bezier_point(a, b, c, d, t): u = 1.0 - t return a * u * u * u + 3 * b * t * u * u + 3 * c * t * t * u + d * t * t * t diff --git a/crates/processing_pyo3/src/graphics.rs b/crates/processing_pyo3/src/graphics.rs index 74b9041c..51111159 100644 --- a/crates/processing_pyo3/src/graphics.rs +++ b/crates/processing_pyo3/src/graphics.rs @@ -1823,14 +1823,18 @@ impl Graphics { // --- Font --- - pub fn load_font(&self, path: &str) -> PyResult { - font_load(path) + /// `size` is the text size `text_font(font)` sets along with the font. + #[pyo3(signature = (path, size=None))] + pub fn load_font(&self, path: &str, size: Option) -> PyResult { + font_load(path, size) .map(|entity| Font { entity }) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - pub fn create_font(&self, name: &str) -> PyResult { - font_create(name) + /// `size` is the text size `text_font(font)` sets along with the font. + #[pyo3(signature = (name, size=None))] + pub fn create_font(&self, name: &str, size: Option) -> PyResult { + font_create(name, size) .map(|entity| Font { entity }) .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } @@ -1839,10 +1843,29 @@ impl Graphics { font_list().map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - #[pyo3(signature = (font=None))] - pub fn text_font(&self, font: Option<&Font>) -> PyResult<()> { - graphics_text_font(self.entity, font.map(|f| f.entity)) - .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + /// `font` is a `Font` or a family name; `None` restores the default font. + #[pyo3(signature = (font=None, size=None))] + pub fn text_font(&self, font: Option<&Bound<'_, PyAny>>, size: Option) -> PyResult<()> { + let result = match font { + None => graphics_text_font(self.entity, None), + Some(font) => { + if let Ok(name) = font.extract::() { + graphics_text_font_family(self.entity, &name) + } else { + let font = font.cast::().map_err(|_| { + pyo3::exceptions::PyTypeError::new_err( + "text_font() expects a Font or a font name", + ) + })?; + graphics_text_font(self.entity, Some(font.borrow().entity)) + } + } + }; + result.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?; + match size { + Some(size) => self.text_size(Some(size)).map(|_| ()), + None => Ok(()), + } } // --- Text --- @@ -2022,9 +2045,16 @@ impl Graphics { .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } - pub fn text_size(&self, size: f32) -> PyResult<()> { - graphics_record_command(self.entity, DrawCommand::TextSize(size)) - .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) + /// Sets the text size; with no argument, returns the current one. + #[pyo3(signature = (size=None))] + pub fn text_size(&self, size: Option) -> PyResult> { + match size { + Some(size) => { + graphics_record_command(self.entity, DrawCommand::TextSize(size)).map(|_| None) + } + None => graphics_text_size(self.entity).map(Some), + } + .map_err(|e| PyRuntimeError::new_err(format!("{e}"))) } #[pyo3(signature = (h, v=None))] diff --git a/crates/processing_pyo3/src/lib.rs b/crates/processing_pyo3/src/lib.rs index feac7b7c..d98ba6f3 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -2255,8 +2255,8 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module)] - fn text_size(module: &Bound<'_, PyModule>, size: f32) -> PyResult<()> { + #[pyo3(pass_module, signature = (size=None))] + fn text_size(module: &Bound<'_, PyModule>, size: Option) -> PyResult> { graphics!(module).text_size(size) } @@ -2273,9 +2273,13 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module, signature = (font=None))] - fn text_font(module: &Bound<'_, PyModule>, font: Option<&Font>) -> PyResult<()> { - graphics!(module).text_font(font) + #[pyo3(pass_module, signature = (font=None, size=None))] + fn text_font( + module: &Bound<'_, PyModule>, + font: Option<&Bound<'_, PyAny>>, + size: Option, + ) -> PyResult<()> { + graphics!(module).text_font(font, size) } #[pyfunction] @@ -2377,15 +2381,15 @@ pub mod processing_py { } #[pyfunction] - #[pyo3(pass_module)] - fn load_font(module: &Bound<'_, PyModule>, path: &str) -> PyResult { - graphics!(module).load_font(path) + #[pyo3(pass_module, signature = (path, size=None))] + fn load_font(module: &Bound<'_, PyModule>, path: &str, size: Option) -> PyResult { + graphics!(module).load_font(path, size) } #[pyfunction] - #[pyo3(pass_module)] - fn create_font(module: &Bound<'_, PyModule>, name: &str) -> PyResult { - graphics!(module).create_font(name) + #[pyo3(pass_module, signature = (name, size=None))] + fn create_font(module: &Bound<'_, PyModule>, name: &str, size: Option) -> PyResult { + graphics!(module).create_font(name, size) } #[pyfunction] diff --git a/crates/processing_render/src/lib.rs b/crates/processing_render/src/lib.rs index ec6447cf..897ded5a 100644 --- a/crates/processing_render/src/lib.rs +++ b/crates/processing_render/src/lib.rs @@ -2727,12 +2727,12 @@ pub fn compute_destroy(entity: Entity) -> error::Result<()> { /// /// Reading fonts from the filesystem is not available on wasm; callers should /// register font bytes through another path there. -pub fn font_load(path: &str) -> error::Result { +pub fn font_load(path: &str, size: Option) -> error::Result { use text::font::{Font, TextContext}; #[cfg(target_arch = "wasm32")] { - let _ = path; + let _ = (path, size); return Err(error::ProcessingError::FontLoadError( "loading fonts from a file is not supported on wasm".to_string(), )); @@ -2740,10 +2740,39 @@ pub fn font_load(path: &str) -> error::Result { #[cfg(not(target_arch = "wasm32"))] { - let data = std::fs::read(path) - .map_err(|e| error::ProcessingError::FontLoadError(format!("{}: {}", path, e)))?; + use bevy::asset::{AssetPath, io::AssetSourceId}; + use processing_core::config::{Config, ConfigKey}; app_mut(|app| { + // read through the asset server, so paths resolve like images do + let asset_path = AssetPath::parse(path); + let source = match app + .world() + .resource::() + .get(ConfigKey::AssetRootPath) + { + Some(_) => AssetSourceId::from("assets_directory"), + None => asset_path.source().clone_owned(), + }; + let server = app.world().resource::().clone(); + let failed = |e: &dyn std::fmt::Display| { + error::ProcessingError::FontLoadError(format!("{path}: {e}")) + }; + let data = bevy::tasks::block_on(async { + let source = server.get_source(source).map_err(|e| failed(&e))?; + let mut reader = source + .reader() + .read(asset_path.path()) + .await + .map_err(|e| failed(&e))?; + let mut data = Vec::new(); + reader + .read_to_end(&mut data) + .await + .map_err(|e| failed(&e))?; + error::Result::Ok(data) + })?; + let text_cx = app.world().resource::().clone(); let family_name = text_cx @@ -2751,14 +2780,14 @@ pub fn font_load(path: &str) -> error::Result { .ok_or(error::ProcessingError::FontLoadError( "Could not determine font family name".to_string(), ))?; - let entity = app.world_mut().spawn(Font { family_name }).id(); + let entity = app.world_mut().spawn(Font { family_name, size }).id(); Ok(entity) }) } } /// Create a font handle for a family name; an unknown family falls back to the default font. -pub fn font_create(name: &str) -> error::Result { +pub fn font_create(name: &str, size: Option) -> error::Result { use text::font::{DEFAULT_FONT_FAMILY, Font, TextContext}; app_mut(|app| { @@ -2767,7 +2796,7 @@ pub fn font_create(name: &str) -> error::Result { warn!("font {name:?} is not installed, using the default font"); DEFAULT_FONT_FAMILY.to_string() }); - let entity = app.world_mut().spawn(Font { family_name }).id(); + let entity = app.world_mut().spawn(Font { family_name, size }).id(); Ok(entity) }) } @@ -2824,6 +2853,28 @@ pub fn graphics_text_font( graphics_record_command(graphics_entity, DrawCommand::TextFont(font_entity)) } +/// Sets the font by family name; an unknown family falls back to the default font. +pub fn graphics_text_font_family(graphics_entity: Entity, name: &str) -> error::Result<()> { + use text::font::{DEFAULT_FONT_FAMILY, TextContext}; + + let family = app_mut(|app| { + let text_cx = app.world().resource::().clone(); + Ok(text_cx.resolve_family(name).unwrap_or_else(|| { + warn_once!("font {name:?} is not installed, using the default font"); + DEFAULT_FONT_FAMILY.to_string() + })) + })?; + graphics_record_command(graphics_entity, DrawCommand::TextFontFamily(family)) +} + +/// The current text size, including changes queued this frame. +pub fn graphics_text_size(graphics_entity: Entity) -> error::Result { + app_mut(|app| { + let (params, _) = text_query_state(app, graphics_entity, None, None)?; + Ok(params.text_size) + }) +} + pub fn graphics_text_style(graphics_entity: Entity, style: u8) -> error::Result<()> { use render::command::TextStyle; graphics_record_command( @@ -2924,7 +2975,7 @@ fn text_query_state( cmd => render::apply_text_style_command(&mut style, cmd.clone(), |entity| { world .get::(entity) - .map(|f| f.family_name.clone()) + .map(|f| (f.family_name.clone(), f.size)) }), } } diff --git a/crates/processing_render/src/render/command.rs b/crates/processing_render/src/render/command.rs index 054b5677..53d99c23 100644 --- a/crates/processing_render/src/render/command.rs +++ b/crates/processing_render/src/render/command.rs @@ -758,6 +758,7 @@ pub enum DrawCommand { radius: f32, }, TextFont(Option), + TextFontFamily(String), TextStyle(TextStyle), TextWeight(f32), TextVariation { diff --git a/crates/processing_render/src/render/mod.rs b/crates/processing_render/src/render/mod.rs index 249874d8..6fc3a822 100644 --- a/crates/processing_render/src/render/mod.rs +++ b/crates/processing_render/src/render/mod.rs @@ -123,18 +123,24 @@ impl BatchState { pub(crate) fn apply_text_style_command( style: &mut StyleStack, cmd: DrawCommand, - font_family: impl Fn(Entity) -> Option, + font: impl Fn(Entity) -> Option<(String, Option)>, ) { match cmd { DrawCommand::TextFont(font_entity) => { if let Some(entity) = font_entity { - if let Some(family) = font_family(entity) { + if let Some((family, size)) = font(entity) { style.text_font_family = Some(family); + // a sized font brings its size, as in Processing + if let Some(size) = size { + style.text_size = size; + style.text_leading = None; + } } } else { style.text_font_family = None; } } + DrawCommand::TextFontFamily(family) => style.text_font_family = Some(family), DrawCommand::TextStyle(text_style) => style.text_style = text_style, DrawCommand::TextWeight(weight) => style.text_weight = Some(weight), DrawCommand::TextVariation { tag, value } => { @@ -1324,6 +1330,7 @@ pub fn flush_draw_commands( ); } cmd @ (DrawCommand::TextFont(_) + | DrawCommand::TextFontFamily(_) | DrawCommand::TextStyle(_) | DrawCommand::TextWeight(_) | DrawCommand::TextVariation { .. } @@ -1337,7 +1344,10 @@ pub fn flush_draw_commands( | DrawCommand::TextWrap(_) | DrawCommand::TextGlyphColors(_)) => { apply_text_style_command(&mut state.style, cmd, |entity| { - p_fonts.get(entity).ok().map(|f| f.family_name.clone()) + p_fonts + .get(entity) + .ok() + .map(|f| (f.family_name.clone(), f.size)) }); } DrawCommand::Text { diff --git a/crates/processing_render/src/text/font.rs b/crates/processing_render/src/text/font.rs index 55afafb7..c182b638 100644 --- a/crates/processing_render/src/text/font.rs +++ b/crates/processing_render/src/text/font.rs @@ -3,10 +3,11 @@ use std::sync::{Arc, Mutex}; use bevy::prelude::*; use parley::{FontContext, LayoutContext}; -/// Font component: the resolved family name. +/// Font component: the resolved family name and the size `text_font` applies with it. #[derive(Component)] pub struct Font { pub family_name: String, + pub size: Option, } /// Shared parley font and layout contexts. diff --git a/crates/processing_wasm/src/lib.rs b/crates/processing_wasm/src/lib.rs index 897e8409..84fdc95c 100644 --- a/crates/processing_wasm/src/lib.rs +++ b/crates/processing_wasm/src/lib.rs @@ -794,12 +794,12 @@ pub fn js_end_contour(graphics_id: u64) -> Result<(), JsValue> { #[wasm_bindgen(js_name = "loadFont")] pub fn js_load_font(path: &str) -> Result { - check(font_load(path).map(|e| e.to_bits())) + check(font_load(path, None).map(|e| e.to_bits())) } #[wasm_bindgen(js_name = "createFont")] pub fn js_create_font(name: &str) -> Result { - check(font_create(name).map(|e| e.to_bits())) + check(font_create(name, None).map(|e| e.to_bits())) } #[wasm_bindgen(js_name = "fontVariationCount")]