mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-10-03 10:48:12 +08:00
Make the data model use Item and List types universally, with nodes authored as rank-polymorphic kernels (#4335)
* Add rank polymorphism node audit classifying all 271 nodes
* Implement StaticType for Item<T>
* Generate Item and mapped List wire variants for nodes declaring an Item<T> primary input
* Migrate nine nodes to Item element-wise kernels, dissolving the blending trait boilerplate
* Document the Item kernel implementation and staging plan
* Route Item<Vector> through TaggedValue::TypeDefault
* Add executor integration tests covering the Item and List wire variants
* Collapse element-wise Item/List wire pairs to the List form for conversion insertion
* Migrate sixteen vector modifier nodes to Item element-wise kernels
* Migrate Sample Image, Extend Image to Bounds, and Dehaze to Item element-wise kernels
* Fix bevel_with_transform test to actually exercise the transform attribute
* Implement From<T> for Item<T>
* Register PromoteNode rank adapters wrapping bare values into Item wires
* Insert PromoteNode adapters for Item/List wire pair fields in the preprocessor
* Define a real promote node backing the PromoteNode registry identifiers
* Zip ranked Item connectors by frame slot in the mapped element-wise variant
* Register ItemToListNode singleton raise adapters
* Resolve Item wires against List connectors by inserting promotion adapters at construction
* Rank the Offset Points distance connector and prove mixed-rank resolution end-to-end
* Implement Clampable for Item and List wires with per-variant clamp bounds
* Rank the Round Corners radius connector, exercising hard bounds on a ranked wire
* Implement ApplyTransform for Item
* Add Item wire implementations to the Transform node, keeping rank-0 chains rank 0
* Detect element-wise nodes by lazy primary connectors declaring Output = Item
* Convert Transform to an Item kernel with ranked parameters, delivering the broadcast milestone
* Rename Apply Transform to Bake Transform, baking item transforms on Vector, DAffine2, and DVec2
* Promote bare wires onto Item connectors at resolution via WrapItemNode adapters
* Rank the numeric, vector, and boolean parameters across the migrated element-wise nodes
* Rank the enum, integer, and seed parameters, registering their rank adapters via a consolidated macro
* Amend the audit with the DashPattern value type resolution
* Migrate the string family to Item element-wise kernels
* Unwrap Item wires into bare legacy connectors at resolution via UnwrapItemNode adapters
* Shadow owned node parameters in bodies instead of mut in signatures
* Migrate the math family and string measure nodes to Item element-wise kernels
* Convert the comparison and clamp nodes to Item kernels, dropping unreachable &str rows
* Flat-map expander kernels returning List under the mapped variant's frame
* Migrate the expander nodes to Item kernels flat-mapping under the frame
* Remove the unused peel_list helper
* Rank the raster adjustment and blending kernels, recontextualizing shader nodes onto an Item stand-in
Migrate the 16 adjustment nodes, Mix, Color Overlay, and Gradient Map from whole-List kernels to rank-0 Item kernels, letting the macro derive the List-mapped (zip) variants. Move the Adjust and Blend per-element seams off List onto the element types (add the Raster<CPU> impls, drop the now-dead List impls).
Shader nodes keep their bodies verbatim: PerPixelAdjust re-emits the identical kernel against a transparent no_std Item stand-in, so every Item<T> connector and .element() call resolves to a zero-cost identity on the GPU while the uniform buffer stays bare repr(C). The macro peels Item off ranked uniform params, wraps the fetched texel and uniforms at the entry point, and unwraps the result. This drops the shader_node/Item incompatibility guard. Register rank adapters for the adjustment enums.
* Update the rank polymorphism roadmap for the landed shader-node and adjustments chunk
* Rename the GPU Item stand-in to ShaderItem, aliased as Item at its shader-node import sites
* Flip the vector shape generators to emit rank-0 Item<Vector>
The shape generators (Rectangle, Circle, Ellipse, Arc, Spiral, Polygon, Star, Arrow, Line, Grid, QR Code) each produced exactly one shape wrapped in a singleton List<Vector>. Emit Item<Vector> directly so they connect to the rank-0 content connector of the migrated Transform node. Downstream List consumers receive the value through the existing Item to List promotion.
Relax the element-wise validation so a `()` (generator) primary may return Item<T> without being element-wise. Adapt the Repeat on Points test, which still takes a List content connector, by raising the generator's Item output through a singleton wrapper node.
* Parse ranked Item<T> parameter defaults against the bare element type
A ranked `Item<T>` parameter's default value is a bare, unranked `T` (promoted to the wire at resolution), but the preprocessor was handed the wrapped `Item<T>` type and could not parse the literal, flooding the console with warnings and dropping the defaults. Key the field's default_type metadata off the peeled element type for concrete ranked parameters, leaving generic `Item<T>` primaries and skip_impl nodes untouched.
* Parse an element-wise primary's scalar default against the bare element type
An element-wise node's primary reports its default_type as the List wire form so an unconnected primary defaults to an empty list. But when the primary carries a scalar `#[default]` (such as Root's radicand), that literal must parse as a bare element, not a List. Key the primary's default_type off the bare element type when it has a Default value source, keeping the List form otherwise.
* Add the DashPattern value type for stroke dash sequences
Introduce a rank-0 DashPattern value type (a Vec<f64> of alternating dash and gap lengths) so a stroke's dash pattern is a single frameable value rather than a rank-1 List<f64>. Register it as an auto-generated TaggedValue variant, parse its default from a comma or space separated string, and register its rank adapters. Not yet wired into the Stroke node.
* Rank the Fill and Stroke nodes element-wise and give Stroke a DashPattern connector
Migrate Fill and Stroke to element-wise Item<V> primaries (over Vector and Graphic element types) via a new element-level VectorItemMut trait, so styling one shape yields one shape and rank is preserved instead of promoting the input to a singleton List and emitting a List. The macro derives the List-mapped variant for genuine collections.
Wire the Stroke dash sequence to the new rank-0 DashPattern value type, collapsing the old content x paint x dash cartesian and dropping the IntoF64Vec trait. Update the stroke properties dash widget, the drawing tool, and graph-operation plumbing to read and write DashPattern, and migrate legacy F64Array, F64, and String dash inputs on document open.
Assign Colors stays a whole-collection node: each element's gradient position depends on its index among all siblings, which the element frame does not expose, so it keeps its List primary and the VectorListIterMut trait.
* Register rank adapters for the ranked Stroke enum parameters
The element-wise Stroke node ranks its align, cap, and paint order parameters as Item<StrokeAlign>, Item<StrokeCap>, and Item<PaintOrder>, but those enums lacked promotion adapters, so a bare default enum value could not be promoted to its Item wire and no Stroke variant resolved ("No construct found for node"). Register their rank adapters alongside StrokeJoin.
* Display Item wires in the Data panel without a List's ID column
Add a TableItemLayout impl for Item<T> and recognize Item wire types when introspecting graph data. An Item holds a single element, so it renders as a one-row table of the element plus its attributes with no leading index column, and it labels as its element type T rather than a List's T[]. Add ItemAttributeValues::get_any for the attribute widget dispatch.
* Register MonitorNode for Item wire types so the Data panel introspects them directly
Graph introspection wraps the inspected output in a generic MonitorNode typed to the wire. Without Item<T> monitor registrations, an Item<Vector> output could only be monitored after an Item to List promotion, so the Data panel captured and displayed a List<Vector> despite the connector being Item<Vector>. Register monitors for the Item types the element-wise nodes emit, and add the matching Data panel downcast entries.
* Color and double Item/List wires and cleave layer-stack connectors in the node graph
* Route wire color and rank through hidden nodes and refresh them on type changes
* Rework the DashPattern connector conversions with element-wise promotion and an explicit reducer node
* Rank the remaining value, context, aggregation, and transform nodes onto Item<T> wires
* Back DashPattern with a List<f64> so the Data panel can introspect its lengths
* Carry a single Item<T> through varargs so the Read context nodes emit Item<T> not List<T>
* Relax rank validation for aggregation shapes, add element adapters, and match variants by fewest promotions
* Rank the remaining bare and unnecessarily-List connectors across the node catalog
* Add Graphic::None and the FillChoice paint value, making colors and gradients plain values
* Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill
* Restore generator frame-from-params ranking to the roadmap as a planned stage
* Rename the ranked-field adapter identifier from PromoteNode to FieldAdapterNode to reflect its full contract
* Unload only the wires whose displayed style changed when types update
* Peel wire rank in the editor's semantic type checks so rank-0 layers are recognized
* Restore the whole-List Transform variant so rank-1 content wires resolve again
* Register the Item wire forms for the Memoize and Context Modification infrastructure nodes
* Give every ranked connector a field adapter and add numeric cast variants for legacy wires
* Key a ranked param's type default off its Item wire form when no literal default exists
* Inherit the layer's content value when splicing a node into an empty chain
* Migrate stale List-form TypeDefault inputs to the definition's current default
* Generate the mapped wire variant only when the element-wise node has a frame source
* Let a bare wire feed a List connector via a wrap-raise adapter, costed as two rank steps
* Add a zip companion to the whole-List Transform so ranked List parameters pair per slot
* Add the Sum, Average, Minimum, Maximum, Any, and All list reducers
* Convert the measure family to element-wise Item kernels per the audit classification
* Prefer the bare element value over the Item type default so ranked params keep their widgets
* Rename GradientStopsUI to GradientUI
* Split Fill's optional transform into a _has_transform bool and a ranked _transform matrix
* Rename the migration-only OptionalDAffine2 TaggedValue to LegacyOptionalDAffine2
* Flow byte buffers as Item<Resource> instead of List<u8> across the byte nodes
* Macro-generate the list-content wire variant, retiring the hand-written Transform-zip, Area, and Centroid companions
* Let ()-primary generators take ranked params and frame over them via the mapped variant, ranking Circle's radius
* Rank the vector shape generators' params to Item, adding a rank-aware input grab to the introspection harness
* Rank the value, color, and text generator params to Item
* Rank the raster, web-request, and context-reader generator params to Item
* Fix the repeat and brush test wirings left behind by the param-ranking sweeps
* Delete the vestigial Some, Unwrap Option, and Size Of debug nodes
* Delete the Attach Attribute node, folding its role into Write Attribute
* Add the Filter and Sort list companion nodes
* Guard the removed-definition migration swap target with a test
* Add the Box Corners value type in place of the rectangle corner radius list
* Split Text to Vector's per-glyph mode into a Text to Vector Glyphs node
* Rank the Combine Channels node's channel connectors to Item
* Make Map Points an element-wise node
* Delete the deprecated Upload Texture node
* Update the implementation roadmap to reflect the landed stages
* Let monitor introspection read rank-0 wires, locking in the layer coercion promotion path
* Prefer the rank-0 default when disconnecting a rank-capable input
* Make Path Modify an element-wise node
* Wrap node paths in a NodeIdPath newtype so they flow as a single Item
* Give Item<Raster<CPU>> a default so an unconnected Brush background resolves
* Stop the Brush node from setting layer attributes its paint operation doesn't produce
* Present-gate Flatten Path's adopted layer path like its fill and stroke
* Gate carried layer attributes on static column presence, not runtime values
* Give the remaining graphic Item<T> types a default so unconnected primaries resolve
* Dispatch a ranked param's Properties widget from its rank-0 element type
* Make Extract Transform an element-wise node, restoring the Origins to Polyline body
* Rename Flatten Path to Combine Paths
* Stamp Legacy Layer Extend's adopted layer path as a readable NodeIdPath
* Drop the dead List<u8> and List<NodeId> wire rows
* Rank Flatten Graphic's Fully Flatten toggle to Item
* Update the implementation roadmap with the endgame scope
* Make Combine Paths a reducer that collapses the whole frame into one path
* Stop type-converter nodes from carrying the source's unrelated attributes
* Format the Origins to Polyline regression test
* Wrap the Brush node's trace in a BrushTrace newtype so it flows as one value
* Make Switch a framed element-wise select, bundling whole collections
* Widen and align element-type coverage across the list and graphic nodes
* Register the compiler's cache chain pair for every ranked enum and newtype wire
* Fix wire colors for Passthrough outputs, bundled lists, and bools, and widen list wires
* Represent List wire types structurally with Type::List, replacing name-parsed rank promotion
* Treat scope and data fields as environment, rank scope wires as Item, and feed the render boundary through a context vararg
* Delete the vestigial Clone debug node
* Reinstate Upload Texture as an element-wise node and fix the GPU variants' scope executor and rank adapters
* Rename Combine Paths back to Flatten Path, deferring that rename to its own PR
* Deduplicate the promotion adapter registrations into the field adapter macro
* Rank Write Attribute's value connector to Item<AttributeValueDyn>, retiring the UnwrapItem bridge
* Vertical wire styling
* Store the editor layer path attribute as a bare NodeIdPath, not an Item<NodeIdPath>
* Rank Context Modification's features connector to Item<ContextFeatures>, dropping the dead memoize row
* Rank Path Modify's modification parameter to Item<Box<VectorModification>>
* Rename the field adapter node family to input adapter
* Drop the dead bare scalar rows from Context Modification's implementations list
* Move the dynamic executor's test module into its own file
* Drop the registry's unreachable bare rows for Memoize, the cache chain, and ConvertNode
* Materialize stored TaggedValues as ranked Item wires at the source
* Remove the bare-wire promotion and adapter machinery made dead by ranked value materialization
* Plant the input adapter for List-only inputs, composing position conversion from standard rows
* Consolidate Into/Convert conversions into the input adapter umbrella and rename the rank adapter identifiers
* Fix grouped layers gaining a phantom None stack element from the FillChoice default hijacking every List<Graphic> disconnect
* Enforce ranked node inputs in the macro, rejecting bare wire declarations
* Remove the unit Context => () machinery rows, leaving () purely as the no-primary sentinel
* Add a --signatures rank-audit mode to node-docs for the ranked-wire migration
* Remove the node-docs --signatures rank-audit mode now that ranked wires are enforced
* Migrate legacy no-color values on the Black & White, Color Overlay, and Empty Image color inputs
* Rewrite the element-wise accessor wire type at the primary input, not raw index 0
* Register the cache chain for Resource wires, replacing the lone hand-written Monitor row
* Gate the remaining Raster<GPU> registry rows behind the gpu feature
* Let List<DVec2> wires erase to ListDyn for the attribute reader and element counter
* Rename Extract Element to Item at Index, Count Elements to List Length, and Omit Element to Remove at Index
* Store paint picks as plain color/gradient values, removing the FillChoice value type
* Code review restructuring
* Sort by the consumed sort_key attribute or natural element order, adding the Sort Key node
* Remove the new list-combinator and reducer nodes to defer them to a follow-up PR
* Parse Fill and Stroke color defaults through the paint wire's Graphic element
* Emit ranked implementation-row default types structurally so their element TypeIds survive to default-literal parsing
* Exempt the deliberate no-paint choice from the stale List-form TypeDefault migration
* Migrate the legacy 4-input Fill directly to the split has-transform shape
* Upgrade the demo artwork
* Fix the valid AI review findings: Item eq/hash contract, table-era no-paint migration, quantize List rows, and other smaller issues
* Remove the rank polymorphism working documents
* Hash Item attribute values directly instead of debug-formatting them, speeding up cached evaluation
* Replace the data panel's dead bare-wire downcast arms with full coverage of the ranked monitor row types
* Derive PartialEq for Item now that attributes participate in equality
* Extend the data panel's attribute dispatchers with the newly supported scalar and choice enum types
* Add List monitor rows for the framed numeric conversion outputs so inspecting them resolves, with matching data panel arms
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "text-nodes"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Text operation nodes for Graphene"
|
||||
authors = ["Graphite Authors <contact@graphite.art>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
serde = ["dep:serde", "core-types/serde", "vector-types/serde"]
|
||||
wasm = ["core-types/wasm", "tsify", "wasm-bindgen"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
titlecase = { workspace = true }
|
||||
fancy-regex = { workspace = true }
|
||||
unicode-segmentation = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,5 @@
|
||||
use graphene_resource::Resource;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const FALLBACK_FONT_BYTES: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
|
||||
pub static FALLBACK_FONT_RESOURCE: LazyLock<Resource> = LazyLock::new(|| Resource::new(FALLBACK_FONT_BYTES));
|
||||
@@ -0,0 +1,71 @@
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
|
||||
/// A font type (storing font family and font style)
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Eq, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Font {
|
||||
#[cfg_attr(feature = "serde", serde(rename = "fontFamily"))]
|
||||
pub font_family: String,
|
||||
#[cfg_attr(feature = "serde", serde(rename = "fontStyle", deserialize_with = "migrate_font_style"))]
|
||||
pub font_style: String,
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Font {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.font_family.hash(state);
|
||||
self.font_style.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheHash for Font {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.font_family.cache_hash(state);
|
||||
self.font_style.cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Font {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.font_family == other.font_family && self.font_style == other.font_style
|
||||
}
|
||||
}
|
||||
|
||||
impl Font {
|
||||
pub fn new(font_family: String, font_style: String) -> Self {
|
||||
Self { font_family, font_style }
|
||||
}
|
||||
|
||||
pub fn new_with_default_style(font_family: String) -> Self {
|
||||
Self::new(font_family, core_types::consts::DEFAULT_FONT_STYLE.into())
|
||||
}
|
||||
|
||||
pub fn named_weight(weight: u32) -> &'static str {
|
||||
// From https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping
|
||||
match weight {
|
||||
100 => "Thin",
|
||||
200 => "Extra Light",
|
||||
300 => "Light",
|
||||
400 => "Regular",
|
||||
500 => "Medium",
|
||||
600 => "Semi Bold",
|
||||
700 => "Bold",
|
||||
800 => "Extra Bold",
|
||||
900 => "Black",
|
||||
950 => "Extra Black",
|
||||
_ => "Regular",
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for Font {
|
||||
fn default() -> Self {
|
||||
Self::new(core_types::consts::DEFAULT_FONT_FAMILY.into(), core_types::consts::DEFAULT_FONT_STYLE.into())
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
fn migrate_font_style<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
|
||||
use serde::Deserialize;
|
||||
String::deserialize(deserializer).map(|name| if name == "Normal (400)" { "Regular (400)".to_string() } else { name })
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_TYPE, Ctx};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::unescape_string;
|
||||
|
||||
// ===========
|
||||
// Format JSON
|
||||
// ===========
|
||||
|
||||
/// Reformats a JSON string with control over indentation, line breaking, and spacing. Trailing commas are tolerated. Otherwise-invalid JSON input is returned unchanged.
|
||||
#[node_macro::node(name("Format JSON"), category("Text: JSON"))]
|
||||
fn format_json(
|
||||
_: impl Ctx,
|
||||
/// The JSON string to reformat.
|
||||
#[name("JSON")]
|
||||
json: Item<String>,
|
||||
/// Removes optional spaces within curly brackets and after colons and commas.
|
||||
compact: Item<bool>,
|
||||
/// Break arrays and objects across multiple lines when they exceed the line break length.
|
||||
#[default(true)]
|
||||
#[name("Multi-Line")]
|
||||
multi_line: Item<bool>,
|
||||
/// The indentation string used for each nesting level. Escape sequences like `\t` (the tab character) are supported. Two or four spaces are also common choices.
|
||||
#[default("\\t")]
|
||||
indent: Item<String>,
|
||||
/// The maximum line length before a container (array or object) is broken across lines. Set this to 0 to always break containers. (Requires *Multi-Line* to take effect.)
|
||||
///
|
||||
/// This is not a maximum line length guarantee. Deep nesting and long keys or values may exceed this length.
|
||||
#[default(120)]
|
||||
break_length: Item<u32>,
|
||||
/// Always break a container (array or object) across lines if it holds another container, even if it would fit within the break length. (Requires *Multi-Line* to take effect.)
|
||||
#[default(true)]
|
||||
break_nested: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut json = json;
|
||||
let (compact, multi_line, break_length, break_nested) = (*compact.element(), *multi_line.element(), *break_length.element(), *break_nested.element());
|
||||
let indent = indent.element().clone();
|
||||
|
||||
let cleaned = strip_trailing_commas(json.element());
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&cleaned) else { return json };
|
||||
let indent = unescape_string(indent);
|
||||
let colon = if compact { ":" } else { ": " };
|
||||
let comma_space = if compact { "," } else { ", " };
|
||||
let line_width = break_length as usize;
|
||||
|
||||
let result = if multi_line {
|
||||
format_value(&value, 0, &indent, colon, comma_space, compact, break_nested, line_width)
|
||||
} else {
|
||||
format_inline(&value, colon, comma_space, compact)
|
||||
};
|
||||
|
||||
*json.element_mut() = result;
|
||||
json
|
||||
}
|
||||
|
||||
/// Strips trailing commas before `]` and `}` to accept JSON-with-trailing-commas input.
|
||||
/// Respects string literals so commas inside strings are left untouched.
|
||||
fn strip_trailing_commas(json: &str) -> String {
|
||||
let mut output = String::with_capacity(json.len());
|
||||
let mut chars = json.chars().peekable();
|
||||
let mut in_string = false;
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
if in_string {
|
||||
output.push(c);
|
||||
|
||||
// Skip escaped characters inside strings
|
||||
if c == '\\'
|
||||
&& let Some(escaped) = chars.next()
|
||||
{
|
||||
output.push(escaped);
|
||||
} else if c == '"' {
|
||||
in_string = false;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
match c {
|
||||
'"' => {
|
||||
in_string = true;
|
||||
output.push(c);
|
||||
}
|
||||
',' => {
|
||||
// Skip any whitespace after the comma
|
||||
while chars.peek().is_some_and(|c| c.is_ascii_whitespace()) {
|
||||
chars.next();
|
||||
}
|
||||
|
||||
// Drop trailing commas (before `]` or `}`), but keep all others
|
||||
if !chars.peek().is_some_and(|&c| c == ']' || c == '}') {
|
||||
output.push(',');
|
||||
}
|
||||
}
|
||||
_ => output.push(c),
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// Formats a JSON value as a single unbroken line.
|
||||
fn format_inline(value: &serde_json::Value, colon: &str, comma_space: &str, compact: bool) -> String {
|
||||
match value {
|
||||
serde_json::Value::Array(arr) => {
|
||||
let inner: Vec<String> = arr.iter().map(|v| format_inline(v, colon, comma_space, compact)).collect();
|
||||
format!("[{}]", inner.join(comma_space))
|
||||
}
|
||||
serde_json::Value::Object(obj) => {
|
||||
let inner: Vec<String> = obj
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{}{}{}", serde_json::to_string(k).unwrap_or_default(), colon, format_inline(v, colon, comma_space, compact)))
|
||||
.collect();
|
||||
let joined = inner.join(comma_space);
|
||||
if compact || joined.is_empty() { format!("{{{joined}}}") } else { format!("{{ {joined} }}") }
|
||||
}
|
||||
other => serde_json::to_string(other).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats a JSON value, optionally breaking containers across lines when they contain other containers or exceed the line break length limit.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn format_value(value: &serde_json::Value, depth: usize, indent: &str, colon: &str, comma_space: &str, compact: bool, break_nested: bool, line_width: usize) -> String {
|
||||
// Checks whether any direct child of a container is itself a container.
|
||||
let contains_containers = |value: &serde_json::Value| {
|
||||
// Checks whether a JSON value is a container (array or object).
|
||||
let is_container = |value: &serde_json::Value| matches!(value, serde_json::Value::Array(_) | serde_json::Value::Object(_));
|
||||
|
||||
match value {
|
||||
serde_json::Value::Array(arr) => arr.iter().any(is_container),
|
||||
serde_json::Value::Object(obj) => obj.values().any(is_container),
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
|
||||
match value {
|
||||
serde_json::Value::Array(arr) if !arr.is_empty() => {
|
||||
// Try inline if children are all leaves (or break_nested is off) and it fits
|
||||
if !break_nested || !contains_containers(value) {
|
||||
let inline = format_inline(value, colon, comma_space, compact);
|
||||
let current_indent_width = indent.len() * depth;
|
||||
if current_indent_width + inline.len() <= line_width {
|
||||
return inline;
|
||||
}
|
||||
}
|
||||
|
||||
// Break across lines
|
||||
let child_indent = indent.repeat(depth + 1);
|
||||
let closing_indent = indent.repeat(depth);
|
||||
let items: Vec<String> = arr
|
||||
.iter()
|
||||
.map(|v| format!("{child_indent}{}", format_value(v, depth + 1, indent, colon, comma_space, compact, break_nested, line_width)))
|
||||
.collect();
|
||||
format!("[\n{}\n{closing_indent}]", items.join(",\n"))
|
||||
}
|
||||
serde_json::Value::Object(obj) if !obj.is_empty() => {
|
||||
// Try inline if children are all leaves (or break_nested is off) and it fits
|
||||
if !break_nested || !contains_containers(value) {
|
||||
let inline = format_inline(value, colon, comma_space, compact);
|
||||
let current_indent_width = indent.len() * depth;
|
||||
if current_indent_width + inline.len() <= line_width {
|
||||
return inline;
|
||||
}
|
||||
}
|
||||
|
||||
// Break across lines
|
||||
let child_indent = indent.repeat(depth + 1);
|
||||
let closing_indent = indent.repeat(depth);
|
||||
let entries: Vec<String> = obj
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
let key = serde_json::to_string(k).unwrap_or_default();
|
||||
let val = format_value(v, depth + 1, indent, colon, comma_space, compact, break_nested, line_width);
|
||||
format!("{child_indent}{key}{colon}{val}")
|
||||
})
|
||||
.collect();
|
||||
format!("{{\n{}\n{closing_indent}}}", entries.join(",\n"))
|
||||
}
|
||||
other => serde_json::to_string(other).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
// ================
|
||||
// Query JSON (All)
|
||||
// ================
|
||||
|
||||
/// Extracts a single matched value from a JSON string using a path expression (see that parameter's description for its syntax). If no matches are found, an empty string is returned. If multiple values are matched, the first is returned. To read all matches, use the **Query JSON All** node.
|
||||
///
|
||||
/// This is useful in conjunction with the nodes:
|
||||
/// • **String to Number**: convert numeric query results to numbers.
|
||||
/// • **String Value** → **Equals**: convert "true", "false", or "null" query results to bools.
|
||||
#[node_macro::node(name("Query JSON"), category("Text: JSON"))]
|
||||
fn query_json(
|
||||
_: impl Ctx,
|
||||
/// The JSON string to extract a value from.
|
||||
#[name("JSON")]
|
||||
json: Item<String>,
|
||||
/// Determines which contained value to extract from within the JSON.
|
||||
///
|
||||
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
|
||||
///
|
||||
/// Examples:
|
||||
/// Use `[2]` or `[-1]` to get the last value, and `[1]` or `[-2]` for the middle value, of `["a", "b", "c"]`.
|
||||
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
|
||||
/// Use chained accessors like `.fonts[0].name` to query deeper.
|
||||
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
|
||||
path: Item<String>,
|
||||
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
|
||||
#[default(true)]
|
||||
unquote_strings: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut json = json;
|
||||
let path = path.element().clone();
|
||||
let unquote_strings = *unquote_strings.element();
|
||||
|
||||
let cleaned = strip_trailing_commas(json.element());
|
||||
|
||||
let result = match (serde_json::from_str::<Value>(&cleaned), parse_json_path(path.trim())) {
|
||||
(Ok(value), Some(segments)) => {
|
||||
let mut results = Vec::new();
|
||||
resolve_all(&value, &segments, !unquote_strings, &mut results);
|
||||
|
||||
results.into_iter().next().map(|(text, _ty)| text).unwrap_or_default()
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
|
||||
*json.element_mut() = result;
|
||||
json
|
||||
}
|
||||
|
||||
/// Extracts every matched value from a JSON string using a path expression (see that parameter's description for its syntax). A list of zero or more resultant strings is produced. The `[]` path accessor is used to read more than one value.
|
||||
///
|
||||
/// Each item carries a `type` attribute holding the matched value's JSON type (`"string"`, `"number"`, `"bool"`, `"null"`, `"object"`, or `"array"`).
|
||||
///
|
||||
/// This is useful in conjunction with the nodes:
|
||||
/// • **Index Elements**: access the `N`th query result.
|
||||
/// • **String to Number**: convert numeric query results to numbers.
|
||||
/// • **String Value** → **Equals**: convert "true", "false", or "null" query results to bools.
|
||||
#[node_macro::node(name("Query JSON All"), category("Text: JSON"))]
|
||||
fn query_json_all(
|
||||
_: impl Ctx,
|
||||
/// The JSON string to extract values from.
|
||||
#[name("JSON")]
|
||||
json: Item<String>,
|
||||
/// Determines which contained values to extract from within the JSON.
|
||||
///
|
||||
/// The path syntax is like JavaScript's accessor syntax that follows an array/object value. It also supports negative indexing to count backwards from the end. Additionally, `[]` accesses all array and object values instead of just one.
|
||||
///
|
||||
/// Examples:
|
||||
/// Use `[2]` or `[-1]` to get the last value, and `[1]` or `[-2]` for the middle value, of `["a", "b", "c"]`.
|
||||
/// Use `.size` or `["size"]` to get the `size` property of `{ "size": 10 }`. The latter form is required if the key contains spaces or special characters like `["this key with spaces!"]`.
|
||||
/// Use chained accessors like `.fonts[0].name` to query deeper.
|
||||
/// Use the `[]` accessor to query all elements, like `.fonts[].weights[]` to get every weight of every font.
|
||||
path: Item<String>,
|
||||
/// Strips the surrounding double quotes from string values, returning the raw text. Other types are never wrapped in quotes.
|
||||
#[default(true)]
|
||||
unquote_strings: Item<bool>,
|
||||
) -> List<String> {
|
||||
let cleaned = strip_trailing_commas(json.element());
|
||||
let Ok(value): Result<Value, _> = serde_json::from_str(&cleaned) else { return List::new() };
|
||||
let Some(segments) = parse_json_path(path.element().trim()) else { return List::new() };
|
||||
|
||||
let mut results = Vec::new();
|
||||
resolve_all(&value, &segments, !*unquote_strings.element(), &mut results);
|
||||
|
||||
results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attribute(ATTR_TYPE, ty.to_string())).collect()
|
||||
}
|
||||
|
||||
/// A parsed segment of a JSON access path.
|
||||
enum JsonPathSegment {
|
||||
/// Access an object key, e.g. `.name` or `["my key"]`.
|
||||
Key(String),
|
||||
/// Access an array element by index, e.g. `[0]` or `[-1]`.
|
||||
Index(i32),
|
||||
/// Iterate all elements of an array or object values, e.g. `[]`.
|
||||
IterateAll,
|
||||
}
|
||||
|
||||
/// Parses a JSON access path like `users[0].name` or `.["my key"][].value` into segments.
|
||||
/// Returns `None` on syntax errors.
|
||||
fn parse_json_path(path: &str) -> Option<Vec<JsonPathSegment>> {
|
||||
let mut segments = Vec::new();
|
||||
let mut chars = path.chars().peekable();
|
||||
|
||||
// Skip optional leading dot
|
||||
if chars.peek() == Some(&'.') {
|
||||
chars.next();
|
||||
|
||||
if chars.peek() == Some(&'.') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
while chars.peek().is_some() {
|
||||
if chars.peek() == Some(&'[') {
|
||||
chars.next(); // consume '['
|
||||
|
||||
if chars.peek() == Some(&']') {
|
||||
// Empty brackets: iterate all
|
||||
chars.next();
|
||||
segments.push(JsonPathSegment::IterateAll);
|
||||
} else if matches!(chars.peek(), Some(&'"') | Some(&'\'')) {
|
||||
// Quoted key: ["my key"] or ['my key']
|
||||
let closing_quote = chars.next().unwrap(); // consume opening quote
|
||||
let mut key = String::new();
|
||||
while let Some(&c) = chars.peek() {
|
||||
if c == closing_quote {
|
||||
chars.next(); // consume closing quote
|
||||
break;
|
||||
}
|
||||
if c == '\\' {
|
||||
chars.next();
|
||||
match chars.next() {
|
||||
Some('"') => key.push('"'),
|
||||
Some('\'') => key.push('\''),
|
||||
Some('\\') => key.push('\\'),
|
||||
Some('/') => key.push('/'),
|
||||
Some('b') => key.push('\x08'),
|
||||
Some('f') => key.push('\x0C'),
|
||||
Some('n') => key.push('\n'),
|
||||
Some('r') => key.push('\r'),
|
||||
Some('t') => key.push('\t'),
|
||||
Some('u') => {
|
||||
// Decode a 4-hex-digit Unicode escape sequence, only consuming verified hex digits
|
||||
let mut hex_digits = [0_u8; 4];
|
||||
let mut count = 0;
|
||||
for digit in &mut hex_digits {
|
||||
match chars.peek() {
|
||||
Some(c) if c.is_ascii_hexdigit() => {
|
||||
*digit = chars.next().unwrap() as u8;
|
||||
count += 1;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
|
||||
let hex = &hex_digits[..count];
|
||||
if count == 4
|
||||
&& let Ok(hex_str) = core::str::from_utf8(hex)
|
||||
&& let Ok(code_point) = u32::from_str_radix(hex_str, 16)
|
||||
&& let Some(byte) = char::from_u32(code_point)
|
||||
{
|
||||
key.push(byte);
|
||||
} else {
|
||||
key.push('\\');
|
||||
key.push('u');
|
||||
for &byte in hex {
|
||||
key.push(byte as char);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(other) => {
|
||||
key.push('\\');
|
||||
key.push(other);
|
||||
}
|
||||
None => key.push('\\'),
|
||||
}
|
||||
} else {
|
||||
key.push(c);
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
// Require the closing ']'
|
||||
if chars.peek() == Some(&']') {
|
||||
chars.next();
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
segments.push(JsonPathSegment::Key(key));
|
||||
} else {
|
||||
// Numeric index: [0] or [-1]
|
||||
let mut num_str = String::new();
|
||||
while let Some(&c) = chars.peek() {
|
||||
if c == ']' {
|
||||
chars.next();
|
||||
break;
|
||||
}
|
||||
num_str.push(c);
|
||||
chars.next();
|
||||
}
|
||||
if let Ok(index) = num_str.trim().parse::<i32>() {
|
||||
segments.push(JsonPathSegment::Index(index));
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
} else if chars.peek() == Some(&'.') {
|
||||
// Dot separator before next key
|
||||
chars.next();
|
||||
|
||||
if chars.peek() == Some(&'.') || chars.peek().is_none() {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
// Bare key: read until dot or bracket
|
||||
let mut key = String::new();
|
||||
while let Some(&c) = chars.peek() {
|
||||
if c == '.' || c == '[' {
|
||||
break;
|
||||
}
|
||||
key.push(c);
|
||||
chars.next();
|
||||
}
|
||||
if !key.is_empty() {
|
||||
segments.push(JsonPathSegment::Key(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(segments)
|
||||
}
|
||||
|
||||
/// Converts a JSON value to its string representation.
|
||||
/// Strings are quoted by default to produce valid JSON syntax. When `quote_strings` is false, surrounding quotes are stripped.
|
||||
fn json_value_to_string(value: &serde_json::Value, quote_strings: bool) -> String {
|
||||
match value {
|
||||
serde_json::Value::String(s) if !quote_strings => s.clone(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a short JSON-type name (`"string"`, `"number"`, `"bool"`, `"null"`, `"object"`, `"array"`) for a parsed value.
|
||||
fn json_value_type_name(value: &serde_json::Value) -> &'static str {
|
||||
match value {
|
||||
serde_json::Value::String(_) => "string",
|
||||
serde_json::Value::Number(_) => "number",
|
||||
serde_json::Value::Bool(_) => "bool",
|
||||
serde_json::Value::Null => "null",
|
||||
serde_json::Value::Object(_) => "object",
|
||||
serde_json::Value::Array(_) => "array",
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigates a JSON value by one path segment, returning the resulting value (or `None` if the path is invalid).
|
||||
fn json_navigate<'a>(value: &'a serde_json::Value, segment: &JsonPathSegment) -> Option<&'a serde_json::Value> {
|
||||
match segment {
|
||||
JsonPathSegment::Key(key) => value.as_object().and_then(|obj| obj.get(key)),
|
||||
JsonPathSegment::Index(index) => {
|
||||
let arr = value.as_array()?;
|
||||
let resolved = if *index < 0 { arr.len().checked_sub(index.unsigned_abs() as usize)? } else { *index as usize };
|
||||
arr.get(resolved)
|
||||
}
|
||||
JsonPathSegment::IterateAll => None, // Handled by resolve_all
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively resolves a path against a JSON value, fanning out at each `[]` and collecting leaf results.
|
||||
fn resolve_all(value: &serde_json::Value, segments: &[JsonPathSegment], quote_strings: bool, results: &mut Vec<(String, &'static str)>) {
|
||||
// Find the next IterateAll in the remaining segments
|
||||
let Some(iterate_position) = segments.iter().position(|s| matches!(s, JsonPathSegment::IterateAll)) else {
|
||||
// No more [] segments, navigate the rest linearly
|
||||
let mut current = value;
|
||||
for segment in segments {
|
||||
let Some(next) = json_navigate(current, segment) else { return };
|
||||
current = next;
|
||||
}
|
||||
results.push((json_value_to_string(current, quote_strings), json_value_type_name(current)));
|
||||
return;
|
||||
};
|
||||
|
||||
// Navigate to the array/object before the []
|
||||
let mut current = value;
|
||||
for segment in &segments[..iterate_position] {
|
||||
let Some(next) = json_navigate(current, segment) else { return };
|
||||
current = next;
|
||||
}
|
||||
|
||||
// Fan out over elements and recurse with the remaining path
|
||||
let remaining = &segments[iterate_position + 1..];
|
||||
match current {
|
||||
serde_json::Value::Array(arr) => {
|
||||
for element in arr {
|
||||
resolve_all(element, remaining, quote_strings, results);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Object(obj) => {
|
||||
for element in obj.values() {
|
||||
resolve_all(element, remaining, quote_strings, results);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,894 @@
|
||||
pub mod fallback;
|
||||
mod font;
|
||||
pub mod json;
|
||||
pub mod markers;
|
||||
mod path_builder;
|
||||
pub mod regex;
|
||||
mod text_context;
|
||||
mod to_path;
|
||||
|
||||
use convert_case::{Boundary, Converter, pattern};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::{SignedInteger, TextArea};
|
||||
use core_types::{Context, Ctx, DeriveCtx, ExtractVarArgs};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
// Re-export for convenience
|
||||
pub use core_types as gcore;
|
||||
pub use fallback::FALLBACK_FONT_RESOURCE;
|
||||
pub use font::*;
|
||||
pub use markers::{ATTR_FONT, ATTR_TEXT_ALIGN};
|
||||
pub use text_context::{TextContext, for_each_styled_glyph_run};
|
||||
pub use to_path::*;
|
||||
pub use vector_types;
|
||||
|
||||
/// Alignment of lines of type within a text block.
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum TextAlign {
|
||||
#[default]
|
||||
#[icon("TextAlignLeft")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Left"))]
|
||||
AlignLeft,
|
||||
#[icon("TextAlignCenter")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Center"))]
|
||||
AlignCenter,
|
||||
#[icon("TextAlignRight")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Right"))]
|
||||
AlignRight,
|
||||
#[icon("TextJustifyLeft")]
|
||||
JustifyLeft,
|
||||
#[icon("TextJustifyCenter")]
|
||||
JustifyCenter,
|
||||
#[icon("TextJustifyRight")]
|
||||
JustifyRight,
|
||||
#[icon("TextJustifyAll")]
|
||||
JustifyAll,
|
||||
}
|
||||
|
||||
impl From<TextAlign> for parley::Alignment {
|
||||
fn from(val: TextAlign) -> Self {
|
||||
match val {
|
||||
TextAlign::AlignLeft => parley::Alignment::Left,
|
||||
TextAlign::AlignCenter => parley::Alignment::Center,
|
||||
TextAlign::AlignRight => parley::Alignment::Right,
|
||||
_ => parley::Alignment::Justify,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextAlign {
|
||||
/// What `parley::Alignment` to apply as a post-correction to the last line of a paragraph, or `None` if parley's default already handles it.
|
||||
///
|
||||
/// `JustifyLeft` returns `None` because parley already left-aligns the last line of a `Justify` layout. The other justify modes need
|
||||
/// the last line shifted (`Center`/`Right`) or its inter-word spaces redistributed (`Justify` / `JustifyAll`).
|
||||
pub fn last_line_correction(self) -> Option<parley::Alignment> {
|
||||
match self {
|
||||
Self::JustifyCenter => Some(parley::Alignment::Center),
|
||||
Self::JustifyRight => Some(parley::Alignment::Right),
|
||||
Self::JustifyAll => Some(parley::Alignment::Justify),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// CSS `(text-align, text-align-last)` values approximating this alignment for the `contenteditable` text overlay.
|
||||
pub fn css(self) -> (&'static str, &'static str) {
|
||||
match self {
|
||||
Self::AlignLeft => ("left", "auto"),
|
||||
Self::AlignCenter => ("center", "auto"),
|
||||
Self::AlignRight => ("right", "auto"),
|
||||
Self::JustifyLeft => ("justify", "auto"),
|
||||
Self::JustifyCenter => ("justify", "center"),
|
||||
Self::JustifyRight => ("justify", "right"),
|
||||
Self::JustifyAll => ("justify", "justify"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone, Copy, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TypesettingConfig {
|
||||
pub font_size: f64,
|
||||
pub line_height_ratio: f64,
|
||||
pub letter_spacing: f64,
|
||||
pub letter_tilt: f64,
|
||||
pub max_width: Option<f64>,
|
||||
pub max_height: Option<f64>,
|
||||
pub align: TextAlign,
|
||||
}
|
||||
|
||||
impl Default for TypesettingConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_size: 24.,
|
||||
line_height_ratio: 1.2,
|
||||
letter_spacing: 0.,
|
||||
letter_tilt: 0.,
|
||||
max_width: None,
|
||||
max_height: None,
|
||||
align: TextAlign::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts escape sequence representations (`\n`, `\r`, `\t`, `\0`, `\\`) into their corresponding control characters.
|
||||
/// Unrecognized escape sequences (e.g. `\x`) are preserved as-is.
|
||||
fn unescape_string(input: String) -> String {
|
||||
let mut result = String::with_capacity(input.len());
|
||||
let mut chars = input.chars();
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '\\' {
|
||||
match chars.next() {
|
||||
Some('n') => result.push('\n'),
|
||||
Some('r') => result.push('\r'),
|
||||
Some('t') => result.push('\t'),
|
||||
Some('0') => result.push('\0'),
|
||||
Some('\\') => result.push('\\'),
|
||||
Some(unrecognized) => result.extend(['\\', unrecognized]),
|
||||
None => result.push('\\'),
|
||||
}
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Converts control characters (newline, carriage return, tab, null, backslash) back into their escape sequence representations.
|
||||
fn escape_string(input: String) -> String {
|
||||
let mut result = String::with_capacity(input.len());
|
||||
|
||||
for c in input.chars() {
|
||||
match c {
|
||||
'\n' => result.push_str("\\n"),
|
||||
'\r' => result.push_str("\\r"),
|
||||
'\t' => result.push_str("\\t"),
|
||||
'\0' => result.push_str("\\0"),
|
||||
'\\' => result.push_str("\\\\"),
|
||||
other => result.push(other),
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, dyn_any::DynAny, node_macro::ChoiceType, serde::Serialize, serde::Deserialize)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum StringCapitalization {
|
||||
/// "on the origin of species" — Converts all letters to lower case.
|
||||
#[default]
|
||||
#[label("lower case")]
|
||||
LowerCase,
|
||||
/// "ON THE ORIGIN OF SPECIES" — Converts all letters to upper case.
|
||||
#[label("UPPER CASE")]
|
||||
UpperCase,
|
||||
/// "On The Origin Of Species" — Converts the first letter of every word to upper case.
|
||||
#[label("Capital Case")]
|
||||
CapitalCase,
|
||||
/// "On the Origin of Species" — Converts the first letter of significant words to upper case.
|
||||
#[label("Headline Case")]
|
||||
HeadlineCase,
|
||||
/// "On the origin of species" — Converts the first letter of every word to lower case, except the initial word which is made upper case.
|
||||
#[label("Sentence case")]
|
||||
SentenceCase,
|
||||
/// "on The Origin Of Species" — Converts the first letter of every word to upper case, except the initial word which is made lower case.
|
||||
#[label("camel Case")]
|
||||
CamelCase,
|
||||
}
|
||||
|
||||
/// Constructs a string value which may be set to any plain text.
|
||||
#[node_macro::node(category("Value"))]
|
||||
fn string_value(_: impl Ctx, _primary: (), string: Item<TextArea>) -> Item<String> {
|
||||
string
|
||||
}
|
||||
|
||||
/// Type-asserts a value to be a string.
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn as_string(_: impl Ctx, value: Item<String>) -> Item<String> {
|
||||
value
|
||||
}
|
||||
|
||||
/// Joins two strings together.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: Item<String>, second: Item<TextArea>) -> Item<String> {
|
||||
let mut first = first;
|
||||
first.element_mut().push_str(second.element());
|
||||
first
|
||||
}
|
||||
|
||||
/// Replaces all occurrences of "From" with "To" in the input string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_replace(_: impl Ctx, string: Item<String>, from: Item<TextArea>, to: Item<TextArea>) -> Item<String> {
|
||||
let mut string = string;
|
||||
let result = string.element().replace(from.element().as_str(), to.element());
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Extracts a substring from the input string, starting at "Start" and ending before "End".
|
||||
///
|
||||
/// Negative indices count from the end of the string. If the index of "Start" equals or exceeds "End", the result is an empty string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_slice(_: impl Ctx, string: Item<String>, start: Item<SignedInteger>, end: Item<SignedInteger>) -> Item<String> {
|
||||
let mut string = string;
|
||||
let (start, end) = (*start.element(), *end.element());
|
||||
|
||||
let total_graphemes = string.element().graphemes(true).count();
|
||||
|
||||
let start = if start < 0. {
|
||||
total_graphemes.saturating_sub(start.abs() as usize)
|
||||
} else {
|
||||
(start as usize).min(total_graphemes)
|
||||
};
|
||||
let end = if end <= 0. {
|
||||
total_graphemes.saturating_sub(end.abs() as usize)
|
||||
} else {
|
||||
(end as usize).min(total_graphemes)
|
||||
};
|
||||
|
||||
let result = if start >= end {
|
||||
String::new()
|
||||
} else {
|
||||
string.element().graphemes(true).skip(start).take(end - start).collect()
|
||||
};
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Clips the string to a maximum character length, optionally appending a suffix (like "…") when truncation occurs. Strings already within the limit are not modified.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_truncate(
|
||||
_: impl Ctx,
|
||||
/// The string to truncate.
|
||||
string: Item<String>,
|
||||
/// The maximum number of characters allowed, including the suffix if one is appended.
|
||||
#[default(80)]
|
||||
length: Item<u32>,
|
||||
/// A suffix appended to indicate truncation occurred, unless empty. Its length counts towards the character budget.
|
||||
#[default("…")]
|
||||
suffix: Item<String>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let max_length = *length.element() as usize;
|
||||
let grapheme_count = string.element().graphemes(true).count();
|
||||
|
||||
if grapheme_count <= max_length {
|
||||
return string;
|
||||
}
|
||||
|
||||
let suffix: String = suffix.element().graphemes(true).take(max_length).collect();
|
||||
let keep = max_length - suffix.graphemes(true).count();
|
||||
|
||||
let mut truncated: String = string.element().graphemes(true).take(keep).collect();
|
||||
truncated.push_str(&suffix);
|
||||
|
||||
*string.element_mut() = truncated;
|
||||
string
|
||||
}
|
||||
|
||||
/// Formats a number as a string with control over decimal places, decimal separator, and thousands grouping.
|
||||
#[node_macro::node(category("Text"), properties("format_number_properties"))]
|
||||
fn format_number(
|
||||
_: impl Ctx,
|
||||
/// The number to format as a string.
|
||||
number: Item<f64>,
|
||||
/// The amount of digits after the decimal point. The value is rounded to fit. Set to 0 to show only whole numbers.
|
||||
#[default(2)]
|
||||
decimal_places: Item<u32>,
|
||||
/// The character(s) used as the decimal point.
|
||||
#[default(".")]
|
||||
decimal_separator: Item<String>,
|
||||
/// Always show the exact number of decimal places, even if they are trailing zeros.
|
||||
#[default(true)]
|
||||
fixed_decimals: Item<bool>,
|
||||
/// Whether to group digits with a thousands separator.
|
||||
use_thousands_separator: Item<bool>,
|
||||
/// The character(s) inserted between digit groups.
|
||||
#[default(",")]
|
||||
thousands_separator: Item<String>,
|
||||
/// Don't group 4-digit numbers with a thousands separator (only start grouping at 10,000 and above).
|
||||
#[name("Start at 10,000")]
|
||||
start_at_10000: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let (number, attributes) = number.into_parts();
|
||||
let (decimal_places, fixed_decimals, use_thousands_separator, start_at_10000) =
|
||||
(*decimal_places.element(), *fixed_decimals.element(), *use_thousands_separator.element(), *start_at_10000.element());
|
||||
let decimal_separator = decimal_separator.element().clone();
|
||||
let thousands_separator = thousands_separator.element().clone();
|
||||
|
||||
// Find the maximum meaningful decimal precision by detecting where float noise begins.
|
||||
// This works correctly whether the value originated as f32 or f64, since we find the
|
||||
// shortest decimal representation that round-trips back to the same f64 value.
|
||||
let requested_places = decimal_places as usize;
|
||||
let max_places = {
|
||||
let whole_digits = if number == 0. { 1 } else { (number.abs().log10().floor() as usize).saturating_add(1) };
|
||||
let upper_bound = 17_usize.saturating_sub(whole_digits);
|
||||
let mut meaningful = upper_bound;
|
||||
for p in 0..=upper_bound {
|
||||
let s = format!("{number:.p$}");
|
||||
if s.parse::<f64>() == Ok(number) {
|
||||
meaningful = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
meaningful
|
||||
};
|
||||
let places = requested_places.min(max_places);
|
||||
let formatted = format!("{number:.places$}");
|
||||
|
||||
// If the user requested more decimal places than the float can represent, pad with zeros
|
||||
let extra_zeros = requested_places.saturating_sub(places);
|
||||
|
||||
// Split into sign, whole, and decimal parts
|
||||
let (sign, unsigned) = if let Some(rest) = formatted.strip_prefix('-') { ("-", rest) } else { ("", formatted.as_str()) };
|
||||
|
||||
let (whole_string, decimal_string) = match unsigned.split_once('.') {
|
||||
Some((w, d)) => {
|
||||
let padded = if extra_zeros > 0 { format!("{d}{:0>width$}", "", width = extra_zeros) } else { d.to_string() };
|
||||
(w.to_string(), Some(padded))
|
||||
}
|
||||
None => (unsigned.to_string(), None),
|
||||
};
|
||||
|
||||
// Apply thousands grouping to the whole number part
|
||||
let grouped_whole = if use_thousands_separator && !thousands_separator.is_empty() {
|
||||
let skip = start_at_10000 && whole_string.len() <= 4;
|
||||
if skip {
|
||||
whole_string.clone()
|
||||
} else {
|
||||
let mut result = String::new();
|
||||
for (i, ch) in whole_string.chars().rev().enumerate() {
|
||||
if i > 0 && i % 3 == 0 {
|
||||
result.push_str(&thousands_separator.chars().rev().collect::<String>());
|
||||
}
|
||||
result.push(ch);
|
||||
}
|
||||
result.chars().rev().collect()
|
||||
}
|
||||
} else {
|
||||
whole_string
|
||||
};
|
||||
|
||||
// Build the final string
|
||||
let result = match decimal_string {
|
||||
None if fixed_decimals && requested_places > 0 => {
|
||||
let zeros = "0".repeat(requested_places);
|
||||
format!("{sign}{grouped_whole}{decimal_separator}{zeros}")
|
||||
}
|
||||
None => format!("{sign}{grouped_whole}"),
|
||||
Some(decimal_string) if fixed_decimals => format!("{sign}{grouped_whole}{decimal_separator}{decimal_string}"),
|
||||
Some(decimal_string) => {
|
||||
let trimmed = decimal_string.trim_end_matches('0');
|
||||
if trimmed.is_empty() {
|
||||
format!("{sign}{grouped_whole}")
|
||||
} else {
|
||||
format!("{sign}{grouped_whole}{decimal_separator}{trimmed}")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
|
||||
/// Parses a string into a number. Falls back to the chosen value if the string is not a valid number.
|
||||
#[node_macro::node(category("Text"), name("String to Number"))]
|
||||
fn string_to_number(
|
||||
_: impl Ctx,
|
||||
/// The string containing a number. Surrounding whitespace is ignored, a decimal point (.) may be included, sign prefixes (+/-) are respected, and scientific notation (e.g. "1e-3") is supported.
|
||||
string: Item<String>,
|
||||
/// The value of the result if the string cannot be parsed as a valid number.
|
||||
fallback: Item<f64>,
|
||||
) -> Item<f64> {
|
||||
let (string, attributes) = string.into_parts();
|
||||
|
||||
Item::from_parts(string.trim().parse::<f64>().unwrap_or(*fallback.element()), attributes)
|
||||
}
|
||||
|
||||
/// Removes leading and/or trailing whitespace from a string. Common whitespace characters include spaces, tabs, and newlines.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_trim(
|
||||
_: impl Ctx,
|
||||
/// The string that may contain leading and trailing whitespace that should be removed.
|
||||
string: Item<String>,
|
||||
/// Whether the start of the string should have its whitespace removed.
|
||||
#[default(true)]
|
||||
start: Item<bool>,
|
||||
/// Whether the end of the string should have its whitespace removed.
|
||||
#[default(true)]
|
||||
end: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let (start, end) = (*start.element(), *end.element());
|
||||
|
||||
let result = match (start, end) {
|
||||
(true, true) => string.element().trim().to_string(),
|
||||
(true, false) => string.element().trim_start().to_string(),
|
||||
(false, true) => string.element().trim_end().to_string(),
|
||||
(false, false) => return string,
|
||||
};
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Converts between literal escape sequences and their corresponding control characters within a string.
|
||||
///
|
||||
/// Unescape: `\n` (newline), `\r` (carriage return), `\t` (tab), `\0` (null), and `\\` (backslash) are converted into the actual special characters.
|
||||
/// Escape: the actual special characters are converted back into their escape sequence representations.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_escape(
|
||||
_: impl Ctx,
|
||||
/// The string that contains either literal escape sequences or control characters to be converted to the opposite representation.
|
||||
string: Item<String>,
|
||||
/// Convert the control characters back into their escape sequence representations.
|
||||
#[default(true)]
|
||||
unescape: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let input = std::mem::take(string.element_mut());
|
||||
|
||||
let result = if *unescape.element() { unescape_string(input) } else { escape_string(input) };
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Reverses the sequence of characters making up the string so it reads back-to-front. ("Backwards text" becomes "txet sdrawkcaB".)
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_reverse(
|
||||
_: impl Ctx,
|
||||
/// The string to be reversed.
|
||||
string: Item<String>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let result: String = string.element().graphemes(true).rev().collect();
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Repeats the string a given number of times, optionally with a separator between each repetition.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_repeat(
|
||||
_: impl Ctx,
|
||||
/// The string to be repeated.
|
||||
string: Item<String>,
|
||||
/// The number of times the string should appear in the output.
|
||||
#[default(2)]
|
||||
#[hard(1..)]
|
||||
count: Item<u32>,
|
||||
/// The string placed between each repetition.
|
||||
#[default("\\n")]
|
||||
separator: Item<String>,
|
||||
/// Whether to convert escape sequences found in the separator into their corresponding characters:
|
||||
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
|
||||
#[default(true)]
|
||||
separator_escaping: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let separator = separator.element().clone();
|
||||
let separator = if *separator_escaping.element() { unescape_string(separator) } else { separator };
|
||||
|
||||
let count = *count.element() as usize;
|
||||
|
||||
let mut result = String::with_capacity((string.element().len() + separator.len()) * count);
|
||||
for i in 0..count {
|
||||
if i > 0 {
|
||||
result.push_str(&separator);
|
||||
}
|
||||
result.push_str(string.element());
|
||||
}
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Pads the string to a target length by filling with the given repeated substring. If the string already meets or exceeds the target length, it is returned unchanged.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_pad(
|
||||
_: impl Ctx,
|
||||
/// The string to be padded to a target length.
|
||||
string: Item<String>,
|
||||
/// The target character length after padding. When "Up To" is set, this length concerns only the portion before (or after) that substring.
|
||||
#[default(10)]
|
||||
length: Item<u32>,
|
||||
/// The repeated substring used to fill the remaining space. A multi-charcter substring may end partway through its final repetition.
|
||||
#[default("#")]
|
||||
padding: Item<String>,
|
||||
/// Pad only the length of the string encountered before the start of the first (or after the end of the last) occurrence of this substring, if given and present (otherwise the full string is considered).
|
||||
///
|
||||
/// For example, this can pad numbers with leading zeros to align them before the decimal point.
|
||||
up_to: Item<String>,
|
||||
/// Pad at the end of the string instead of the start.
|
||||
from_end: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let target_length = *length.element() as usize;
|
||||
let padding = padding.element().clone();
|
||||
let up_to = up_to.element().clone();
|
||||
let from_end = *from_end.element();
|
||||
|
||||
if padding.is_empty() {
|
||||
return string;
|
||||
}
|
||||
|
||||
// Split the string at the "up to" substring if provided, and only pad that portion
|
||||
if !up_to.is_empty()
|
||||
&& let Some(position) = if from_end { string.element().rfind(&*up_to) } else { string.element().find(&*up_to) }
|
||||
{
|
||||
let (before, after) = string.element().split_at(position);
|
||||
|
||||
if from_end {
|
||||
// Pad the portion after the substring
|
||||
let after_substring = &after[up_to.len()..];
|
||||
let current_length = after_substring.graphemes(true).count();
|
||||
if current_length >= target_length {
|
||||
return string;
|
||||
}
|
||||
let pad_length = target_length - current_length;
|
||||
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
|
||||
let result = format!("{before}{up_to}{after_substring}{padding}");
|
||||
|
||||
*string.element_mut() = result;
|
||||
return string;
|
||||
} else {
|
||||
// Pad the portion before the substring
|
||||
let current_length = before.graphemes(true).count();
|
||||
if current_length >= target_length {
|
||||
return string;
|
||||
}
|
||||
let pad_length = target_length - current_length;
|
||||
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
|
||||
let result = format!("{padding}{before}{after}");
|
||||
|
||||
*string.element_mut() = result;
|
||||
return string;
|
||||
}
|
||||
}
|
||||
|
||||
let current_length = string.element().graphemes(true).count();
|
||||
if current_length >= target_length {
|
||||
return string;
|
||||
}
|
||||
|
||||
let pad_length = target_length - current_length;
|
||||
let padding: String = padding.graphemes(true).cycle().take(pad_length).collect();
|
||||
|
||||
let result = if from_end { string.element().clone() + &padding } else { padding + string.element() };
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Checks whether the string contains the given substring. Optionally restricts the match to only the start and/or end of the string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_contains(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The substring to search for.
|
||||
substring: Item<String>,
|
||||
/// Only match if the substring appears at the start of the string.
|
||||
at_start: Item<bool>,
|
||||
/// Only match if the substring appears at the end of the string.
|
||||
at_end: Item<bool>,
|
||||
) -> Item<bool> {
|
||||
let (string, attributes) = string.into_parts();
|
||||
let substring = substring.element().as_str();
|
||||
let (at_start, at_end) = (*at_start.element(), *at_end.element());
|
||||
|
||||
let result = match (at_start, at_end) {
|
||||
(true, true) => string.starts_with(substring) && string.ends_with(substring),
|
||||
(true, false) => string.starts_with(substring),
|
||||
(false, true) => string.ends_with(substring),
|
||||
(false, false) => string.contains(substring),
|
||||
};
|
||||
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
|
||||
/// Similar to the **String Contains** node, this searches within the input string for the first (or last) occurrence of a substring and returns the index of where that begins, or -1 if not found.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_find_index(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The substring to search for.
|
||||
substring: Item<String>,
|
||||
/// Find the start index of the last occurrence instead of the first.
|
||||
from_end: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
let (string, attributes) = string.into_parts();
|
||||
let substring = substring.element().as_str();
|
||||
let from_end = *from_end.element();
|
||||
|
||||
if substring.is_empty() {
|
||||
let result = if from_end { string.graphemes(true).count() as f64 } else { 0. };
|
||||
return Item::from_parts(result, attributes);
|
||||
}
|
||||
|
||||
let result = if from_end {
|
||||
// Search backwards by finding all byte-level matches and taking the last one
|
||||
string
|
||||
.rmatch_indices(substring)
|
||||
.next()
|
||||
.map_or(-1., |(byte_index, _)| string[..byte_index].graphemes(true).count() as f64)
|
||||
} else {
|
||||
string
|
||||
.match_indices(substring)
|
||||
.next()
|
||||
.map_or(-1., |(byte_index, _)| string[..byte_index].graphemes(true).count() as f64)
|
||||
};
|
||||
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
|
||||
/// Counts the number of occurrences of a substring within the string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_occurrences(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The substring to count occurrences of.
|
||||
substring: Item<String>,
|
||||
/// Whether to count overlapping occurrences, using the substring as a sliding window.
|
||||
///
|
||||
/// For example, "aa" occurs twice in "aaaa" without overlapping but three times with overlapping.
|
||||
overlapping: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
let (string, attributes) = string.into_parts();
|
||||
let substring = substring.element().as_str();
|
||||
|
||||
if substring.is_empty() {
|
||||
return Item::from_parts(0., attributes);
|
||||
}
|
||||
|
||||
// NON-OVERLAPPING: Simple linear scan.
|
||||
// O(n), where n = string length
|
||||
if !*overlapping.element() {
|
||||
return Item::from_parts(string.matches(substring).count() as f64, attributes);
|
||||
}
|
||||
|
||||
// OVERLAPPING: KMP (Knuth-Morris-Pratt) algorithm.
|
||||
// O(n + m), where n = string length, m = substring length
|
||||
|
||||
let pattern: Vec<char> = substring.chars().collect();
|
||||
let text: Vec<char> = string.chars().collect();
|
||||
|
||||
// Build the KMP failure function:
|
||||
// For each position in the pattern, the length of the longest proper prefix that is also a suffix.
|
||||
// This lets us skip ahead on mismatches instead of restarting from scratch.
|
||||
let mut failure = vec![0_usize; pattern.len()];
|
||||
let mut k = 0;
|
||||
for i in 1..pattern.len() {
|
||||
while k > 0 && pattern[k] != pattern[i] {
|
||||
k = failure[k - 1];
|
||||
}
|
||||
|
||||
if pattern[k] == pattern[i] {
|
||||
k += 1;
|
||||
}
|
||||
|
||||
failure[i] = k;
|
||||
}
|
||||
|
||||
// Scan the text, advancing the pattern cursor without ever backtracking in the text
|
||||
let mut count: usize = 0;
|
||||
let mut pattern_cursor = 0;
|
||||
for &text_char in &text {
|
||||
while pattern_cursor > 0 && pattern[pattern_cursor] != text_char {
|
||||
pattern_cursor = failure[pattern_cursor - 1];
|
||||
}
|
||||
|
||||
if pattern[pattern_cursor] == text_char {
|
||||
pattern_cursor += 1;
|
||||
}
|
||||
|
||||
if pattern_cursor == pattern.len() {
|
||||
count += 1;
|
||||
|
||||
// Reset using failure function to allow overlapping matches
|
||||
pattern_cursor = failure[pattern_cursor - 1];
|
||||
}
|
||||
}
|
||||
|
||||
Item::from_parts(count as f64, attributes)
|
||||
}
|
||||
|
||||
/// Converts a string's capitalization style to another of the common upper and lower case patterns, optionally joining words with a chosen separator.
|
||||
#[node_macro::node(category("Text"), properties("string_capitalization_properties"))]
|
||||
fn string_capitalization(
|
||||
_: impl Ctx,
|
||||
/// The string to have its letter capitalization converted.
|
||||
string: Item<String>,
|
||||
/// The capitalization style to apply.
|
||||
capitalization: Item<StringCapitalization>,
|
||||
/// Whether to split the string into words and reconnect with the chosen joiner. When disabled, the existing word structure separators are preserved.
|
||||
use_joiner: Item<bool>,
|
||||
/// The string placed between each word.
|
||||
joiner: Item<String>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let capitalization = *capitalization.element();
|
||||
let use_joiner = *use_joiner.element();
|
||||
let joiner = joiner.element().clone();
|
||||
let input = std::mem::take(string.element_mut());
|
||||
|
||||
// When the joiner is enabled, apply word-level casing and optionally reconnect words with the selected joiner
|
||||
let result = if use_joiner {
|
||||
match capitalization {
|
||||
// Simple case mappings that preserve the string's existing structure
|
||||
StringCapitalization::LowerCase => input.to_lowercase(),
|
||||
StringCapitalization::UpperCase => input.to_uppercase(),
|
||||
|
||||
// Word-aware capitalizations that split on word boundaries and rejoin with the joiner
|
||||
StringCapitalization::CapitalCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(&joiner).convert(&input),
|
||||
StringCapitalization::HeadlineCase => {
|
||||
// First split into words with convert_case so word boundaries like "AlphaNumeric" are detected consistently with other modes,
|
||||
// then apply the titlecase crate for smart capitalization (lowercasing short words like "of", "the", etc.),
|
||||
// then rejoin with the custom joiner without mangling the capitalization
|
||||
let spaced = Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::capital).set_delim(" ").convert(&input);
|
||||
let headline = titlecase::titlecase(&spaced);
|
||||
Converter::new().set_boundaries(&[Boundary::SPACE]).set_pattern(pattern::noop).set_delim(&joiner).convert(&headline)
|
||||
}
|
||||
StringCapitalization::SentenceCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::sentence).set_delim(&joiner).convert(&input),
|
||||
StringCapitalization::CamelCase => Converter::new().set_boundaries(&Boundary::defaults()).set_pattern(pattern::camel).set_delim(&joiner).convert(&input),
|
||||
}
|
||||
}
|
||||
// When the joiner is disabled, apply only character-level casing while preserving the string's existing structure
|
||||
else {
|
||||
match capitalization {
|
||||
StringCapitalization::LowerCase => input.to_lowercase(),
|
||||
StringCapitalization::UpperCase => input.to_uppercase(),
|
||||
StringCapitalization::CapitalCase => {
|
||||
let mut capitalize_next = true;
|
||||
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
|
||||
if c.is_whitespace() || c == '_' || c == '-' {
|
||||
capitalize_next = true;
|
||||
result.push(c);
|
||||
} else if capitalize_next {
|
||||
capitalize_next = false;
|
||||
result.extend(c.to_uppercase());
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
result
|
||||
})
|
||||
}
|
||||
StringCapitalization::HeadlineCase => titlecase::titlecase(&input),
|
||||
StringCapitalization::SentenceCase => {
|
||||
let mut chars = input.chars();
|
||||
match chars.next() {
|
||||
Some(first) => first.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
StringCapitalization::CamelCase => {
|
||||
let mut capitalize_next = false;
|
||||
input.chars().fold(String::with_capacity(input.len()), |mut result, c| {
|
||||
if c.is_whitespace() || c == '_' || c == '-' {
|
||||
capitalize_next = true;
|
||||
result.push(c);
|
||||
} else if capitalize_next {
|
||||
capitalize_next = false;
|
||||
result.extend(c.to_uppercase());
|
||||
} else {
|
||||
result.extend(c.to_lowercase());
|
||||
}
|
||||
result
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
|
||||
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
|
||||
/// Counts the number of characters in a string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_length(_: impl Ctx, string: Item<String>) -> Item<f64> {
|
||||
let (string, attributes) = string.into_parts();
|
||||
|
||||
Item::from_parts(string.graphemes(true).count() as f64, attributes)
|
||||
}
|
||||
|
||||
/// Splits a string into a list of substrings based on the specified delimiter. This is the inverse of the **String Join** node.
|
||||
///
|
||||
/// For example, splitting "a, b, c" with delimiter ", " produces `["a", "b", "c"]`.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_split(
|
||||
_: impl Ctx,
|
||||
/// The string to split into substrings.
|
||||
string: Item<String>,
|
||||
/// The character(s) that separate the substrings. These are not included in the outputs.
|
||||
#[default("\\n")]
|
||||
delimiter: Item<String>,
|
||||
/// Whether to convert escape sequences found in the delimiter into their corresponding characters:
|
||||
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
|
||||
#[default(true)]
|
||||
delimiter_escaping: Item<bool>,
|
||||
) -> List<String> {
|
||||
let delimiter = delimiter.element().clone();
|
||||
let delimiter = if *delimiter_escaping.element() { unescape_string(delimiter) } else { delimiter };
|
||||
|
||||
string.element().split(&delimiter).map(str::to_string).map(Item::new_from_element).collect()
|
||||
}
|
||||
|
||||
/// Joins a list of strings together with a separator between each pair. This is the inverse of the **String Split** node.
|
||||
///
|
||||
/// For example, joining `["a", "b", "c"]` with separator ", " produces "a, b, c".
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_join(
|
||||
_: impl Ctx,
|
||||
/// The list of strings to join together.
|
||||
strings: List<String>,
|
||||
/// The text placed between each pair of strings.
|
||||
#[default(", ")]
|
||||
separator: Item<String>,
|
||||
/// Whether to convert escape sequences found in the separator into their corresponding characters:
|
||||
/// "\n" (newline), "\r" (carriage return), "\t" (tab), "\0" (null), and "\\" (backslash).
|
||||
#[default(true)]
|
||||
separator_escaping: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let (separator, separator_escaping) = (separator.into_element(), separator_escaping.into_element());
|
||||
let separator = if separator_escaping { unescape_string(separator) } else { separator };
|
||||
|
||||
let joined = strings.iter_element_values().map(|s| s.as_str()).collect::<Vec<_>>().join(&separator);
|
||||
|
||||
Item::new_from_element(joined)
|
||||
}
|
||||
|
||||
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn map_string(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
strings: List<String>,
|
||||
#[expose]
|
||||
#[implementations(Context -> Item<String>)]
|
||||
mapped: impl Node<Context<'_>, Output = Item<String>>,
|
||||
) -> Result<List<String>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
let mut result = List::new();
|
||||
|
||||
for (i, row) in strings.into_iter().enumerate() {
|
||||
let scoped = ctx.push_vararg(&row);
|
||||
let mapped_string = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
|
||||
|
||||
result.push(mapped_string);
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Reads the current string from within a **Map String** node's loop.
|
||||
#[node_macro::node(category("Context"))]
|
||||
fn read_string(ctx: impl Ctx + ExtractVarArgs) -> Item<String> {
|
||||
let Ok(var_arg) = ctx.vararg(0) else { return Item::new_from_element(String::new()) };
|
||||
let var_arg = var_arg as &dyn std::any::Any;
|
||||
|
||||
var_arg.downcast_ref::<Item<String>>().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Converts a value to a JSON string representation.
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn serialize<T: serde::Serialize>(_: impl Ctx, #[implementations(String, bool, f64, u32, u64, DVec2, DAffine2)] value: Item<T>) -> Item<String> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let result = serde_json::to_string(&value).unwrap_or_else(|_| "Serialization Error".to_string());
|
||||
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Attribute markers whose value types live in this crate, with their name
|
||||
//! constants for the string-keyed legacy readers and writers.
|
||||
|
||||
use core_types::attribute::Attribute;
|
||||
|
||||
core_types::attribute! {
|
||||
/// Text item's font, as a resource of the loaded font file.
|
||||
pub Font("font"): &graphene_resource::Resource;
|
||||
/// Text item's horizontal alignment of lines within the block.
|
||||
pub TextAlign("text_align"): crate::TextAlign;
|
||||
}
|
||||
|
||||
pub const ATTR_FONT: &str = Font::NAME;
|
||||
pub const ATTR_TEXT_ALIGN: &str = TextAlign::NAME;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attribute::info;
|
||||
use std::any::TypeId;
|
||||
|
||||
#[test]
|
||||
fn the_census_carries_this_crates_names() {
|
||||
assert_eq!(info("font").unwrap().value_type, TypeId::of::<&'static graphene_resource::Resource>());
|
||||
assert_eq!(info("text_align").unwrap().value_type, TypeId::of::<crate::TextAlign>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_font_default_is_the_empty_resource() {
|
||||
assert!(<Font as Attribute>::default().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_EDITOR_TEXT_FRAME, ATTR_TRANSFORM};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use parley::GlyphRun;
|
||||
use skrifa::GlyphId;
|
||||
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
use skrifa::raw::FontRef as ReadFontsRef;
|
||||
use skrifa::{MetadataProvider, OutlineGlyph};
|
||||
use vector_types::ATTR_EDITOR_CLICK_TARGET;
|
||||
use vector_types::subpath::{ManipulatorGroup, Subpath};
|
||||
use vector_types::vector::{PointId, Vector};
|
||||
|
||||
pub struct PathBuilder {
|
||||
current_subpath: Subpath<PointId>,
|
||||
origin: DVec2,
|
||||
glyph_subpaths: Vec<Subpath<PointId>>,
|
||||
pub vector_list: List<Vector>,
|
||||
/// Per-glyph AABBs collected in single-item mode, published as `ATTR_EDITOR_CLICK_TARGET` in `finalize()`.
|
||||
merged_click_target_bboxes: Vec<[DVec2; 2]>,
|
||||
/// Per-glyph baselines, parallel to `merged_click_target_bboxes`. Groups glyphs by line for the widening pass.
|
||||
merged_click_target_baselines: Vec<f64>,
|
||||
/// Per-glyph AABBs in glyph-local space (multi-item mode), widened in `finalize()` to fill gaps.
|
||||
per_glyph_bboxes: Vec<Option<[DVec2; 2]>>,
|
||||
/// Text frame size, stamped per item as `ATTR_EDITOR_TEXT_FRAME` relative to each item's origin.
|
||||
text_frame_size: DVec2,
|
||||
/// First glyph's baseline offset (pre-height-filter). Used for the empty placeholder item so
|
||||
/// `local_transforms` stays stable when all glyphs are clipped during a resize drag.
|
||||
first_glyph_offset: DVec2,
|
||||
scale: f64,
|
||||
id: PointId,
|
||||
}
|
||||
|
||||
impl PathBuilder {
|
||||
pub fn new(per_glyph_items: bool, scale: f64, text_frame_size: DVec2, first_glyph_offset: DVec2) -> Self {
|
||||
Self {
|
||||
current_subpath: Subpath::new(Vec::new(), false),
|
||||
glyph_subpaths: Vec::new(),
|
||||
vector_list: if per_glyph_items { List::new() } else { List::new_from_element(Vector::default()) },
|
||||
merged_click_target_bboxes: Vec::new(),
|
||||
merged_click_target_baselines: Vec::new(),
|
||||
per_glyph_bboxes: Vec::new(),
|
||||
text_frame_size,
|
||||
first_glyph_offset,
|
||||
scale,
|
||||
id: PointId::ZERO,
|
||||
origin: DVec2::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn point(&self, x: f32, y: f32) -> DVec2 {
|
||||
DVec2::new(self.origin.x + x as f64, self.origin.y - y as f64) * self.scale
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_glyph(
|
||||
&mut self,
|
||||
glyph: &OutlineGlyph<'_>,
|
||||
size: f32,
|
||||
normalized_coords: &[NormalizedCoord],
|
||||
glyph_offset: DVec2,
|
||||
style_skew: Option<DAffine2>,
|
||||
skew: DAffine2,
|
||||
per_glyph_items: bool,
|
||||
) -> bool {
|
||||
let location_ref = LocationRef::new(normalized_coords);
|
||||
let settings = DrawSettings::unhinted(Size::new(size), location_ref);
|
||||
glyph.draw(settings, self).unwrap();
|
||||
let has_geometry = !self.glyph_subpaths.is_empty();
|
||||
|
||||
// Apply transforms in correct order: style-based skew first, then user-requested skew
|
||||
// This ensures font synthesis (italic) is applied before user transformations
|
||||
for glyph_subpath in &mut self.glyph_subpaths {
|
||||
if let Some(style_skew) = style_skew {
|
||||
glyph_subpath.apply_transform(style_skew);
|
||||
}
|
||||
|
||||
glyph_subpath.apply_transform(skew);
|
||||
}
|
||||
|
||||
let glyph_bbox = subpaths_bounding_box(&self.glyph_subpaths);
|
||||
|
||||
if per_glyph_items {
|
||||
// Frame in item-local space: top-left at `-glyph_offset` so the item transform cancels it
|
||||
// back to the layer-local frame origin, regardless of which glyph survived
|
||||
let frame_in_item_local = DAffine2::from_scale_angle_translation(self.text_frame_size, 0., -glyph_offset);
|
||||
|
||||
let item = Item::new_from_element(Vector::from_subpaths(core::mem::take(&mut self.glyph_subpaths), false))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(glyph_offset))
|
||||
.with_attribute(ATTR_EDITOR_TEXT_FRAME, frame_in_item_local);
|
||||
self.vector_list.push(item);
|
||||
|
||||
// Defer click target creation to `finalize()` where adjacent AABBs get widened
|
||||
self.per_glyph_bboxes.push(glyph_bbox);
|
||||
} else {
|
||||
for subpath in self.glyph_subpaths.drain(..) {
|
||||
// Unwrapping here is ok because `self.vector_list` is initialized with a single `List<Vector>` item
|
||||
self.vector_list.element_mut(0).unwrap().append_subpath(subpath, false);
|
||||
}
|
||||
if let Some(bbox) = glyph_bbox {
|
||||
self.merged_click_target_bboxes.push(bbox);
|
||||
self.merged_click_target_baselines.push(glyph_offset.y);
|
||||
}
|
||||
}
|
||||
|
||||
has_geometry
|
||||
}
|
||||
|
||||
pub fn render_glyph_run(&mut self, glyph_run: &GlyphRun<'_, ()>, letter_tilt: f64, per_glyph_items: bool, x_offset: f32, space_extra: f32) {
|
||||
let mut run_x = glyph_run.offset() + x_offset;
|
||||
let run_y = glyph_run.baseline();
|
||||
|
||||
let run = glyph_run.run();
|
||||
|
||||
// User-requested letter tilt applied around baseline to avoid vertical displacement
|
||||
// Translation ensures rotation point is at the baseline, not origin
|
||||
let skew = if per_glyph_items {
|
||||
DAffine2::from_cols_array(&[1., 0., -letter_tilt.to_radians().tan(), 1., 0., 0.])
|
||||
} else {
|
||||
DAffine2::from_translation(DVec2::new(0., run_y as f64))
|
||||
* DAffine2::from_cols_array(&[1., 0., -letter_tilt.to_radians().tan(), 1., 0., 0.])
|
||||
* DAffine2::from_translation(DVec2::new(0., -run_y as f64))
|
||||
};
|
||||
|
||||
let synthesis = run.synthesis();
|
||||
|
||||
// Font synthesis (e.g., synthetic italic) applied separately from user transforms
|
||||
// This preserves the distinction between font styling and user transformations
|
||||
let style_skew = synthesis.skew().map(|angle| {
|
||||
if per_glyph_items {
|
||||
DAffine2::from_cols_array(&[1., 0., -angle.to_radians().tan() as f64, 1., 0., 0.])
|
||||
} else {
|
||||
DAffine2::from_translation(DVec2::new(0., run_y as f64))
|
||||
* DAffine2::from_cols_array(&[1., 0., -angle.to_radians().tan() as f64, 1., 0., 0.])
|
||||
* DAffine2::from_translation(DVec2::new(0., -run_y as f64))
|
||||
}
|
||||
});
|
||||
|
||||
let font = run.font();
|
||||
let font_size = run.font_size();
|
||||
|
||||
let normalized_coords = run.normalized_coords().iter().map(|coord| NormalizedCoord::from_bits(*coord)).collect::<Vec<_>>();
|
||||
|
||||
// TODO: This can be cached for better performance
|
||||
let font_collection_ref = font.data.as_ref();
|
||||
let font_ref = ReadFontsRef::from_index(font_collection_ref, font.index).unwrap();
|
||||
let outlines = font_ref.outline_glyphs();
|
||||
|
||||
for glyph in glyph_run.glyphs() {
|
||||
let glyph_offset = DVec2::new((run_x + glyph.x) as f64, (run_y - glyph.y) as f64);
|
||||
run_x += glyph.advance;
|
||||
|
||||
let glyph_id = GlyphId::from(glyph.id);
|
||||
if let Some(glyph_outline) = outlines.get(glyph_id) {
|
||||
if !per_glyph_items {
|
||||
self.origin = glyph_offset;
|
||||
}
|
||||
let drew_geometry = self.draw_glyph(&glyph_outline, font_size, &normalized_coords, glyph_offset, style_skew, skew, per_glyph_items);
|
||||
|
||||
if !drew_geometry && space_extra != 0. && glyph.advance > 0. {
|
||||
run_x += space_extra;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finalize(mut self) -> List<Vector> {
|
||||
// Empty list = all glyphs clipped by height. Create a placeholder with the same item-0
|
||||
// transform a populated list would have so `local_transforms` stays stable mid-drag.
|
||||
// TODO: Remove this hack and move the attribute up to the parent return value when <https://github.com/GraphiteEditor/Graphite/issues/3779> is done.
|
||||
if self.vector_list.is_empty() {
|
||||
let frame_in_item_local = DAffine2::from_scale_angle_translation(self.text_frame_size, 0., -self.first_glyph_offset);
|
||||
let item = Item::new_from_element(Vector::default())
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(self.first_glyph_offset))
|
||||
.with_attribute(ATTR_EDITOR_TEXT_FRAME, frame_in_item_local);
|
||||
self.vector_list.push(item);
|
||||
}
|
||||
|
||||
// Widen per-glyph AABBs to close horizontal gaps, then publish as click targets
|
||||
if !self.per_glyph_bboxes.is_empty() {
|
||||
// Project glyph-local AABBs into layer-local for the widening pass
|
||||
let entries: Vec<(usize, DVec2, [DVec2; 2])> = self
|
||||
.per_glyph_bboxes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, bbox)| {
|
||||
let bbox = (*bbox)?;
|
||||
let offset = self.vector_list.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index).translation;
|
||||
Some((index, offset, [bbox[0] + offset, bbox[1] + offset]))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut layer_bboxes: Vec<[DVec2; 2]> = entries.iter().map(|entry| entry.2).collect();
|
||||
let baselines: Vec<f64> = entries.iter().map(|entry| entry.1.y).collect();
|
||||
widen_horizontal_gaps(&mut layer_bboxes, &baselines);
|
||||
|
||||
// Project back to glyph-local and stamp as click targets
|
||||
for (entry, widened) in entries.iter().zip(layer_bboxes.iter()) {
|
||||
let glyph_local = [widened[0] - entry.1, widened[1] - entry.1];
|
||||
let rect = Subpath::new_rectangle(glyph_local[0], glyph_local[1]);
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, entry.0, Some(Vector::from_subpaths([rect], false)));
|
||||
}
|
||||
}
|
||||
|
||||
// Glyph separation off: widen the accumulated AABBs and bundle as one override `Vector`
|
||||
if !self.merged_click_target_bboxes.is_empty() {
|
||||
let mut bboxes = self.merged_click_target_bboxes;
|
||||
widen_horizontal_gaps(&mut bboxes, &self.merged_click_target_baselines);
|
||||
|
||||
let widened_subpaths: Vec<_> = bboxes.iter().map(|[min, max]| Subpath::new_rectangle(*min, *max)).collect();
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, 0, Some(Vector::from_subpaths(widened_subpaths, false)));
|
||||
}
|
||||
|
||||
// Fill in text frame for items that don't have one yet (single-item mode, where item 0 = identity)
|
||||
let frame = DAffine2::from_scale(self.text_frame_size);
|
||||
for index in 0..self.vector_list.len() {
|
||||
if self.vector_list.attribute::<DAffine2>(ATTR_EDITOR_TEXT_FRAME, index).is_none() {
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_TEXT_FRAME, index, frame);
|
||||
}
|
||||
}
|
||||
|
||||
self.vector_list
|
||||
}
|
||||
}
|
||||
|
||||
/// Widen AABBs horizontally so same-line neighbors fill inter-glyph gaps.
|
||||
/// The shorter glyph (higher min.y) widens toward its taller neighbor; equal heights split the gap.
|
||||
/// Assumes input is in reading order. Linear runtime.
|
||||
fn widen_horizontal_gaps(bboxes: &mut [[DVec2; 2]], baselines: &[f64]) {
|
||||
for i in 0..bboxes.len().saturating_sub(1) {
|
||||
// Skip cross-line pairs (loose epsilon since baselines come from layout floats)
|
||||
if (baselines[i] - baselines[i + 1]).abs() > 1e-4 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let gap = bboxes[i + 1][0].x - bboxes[i][1].x;
|
||||
if gap <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let left_top = bboxes[i][0].y;
|
||||
let right_top = bboxes[i + 1][0].y;
|
||||
|
||||
if left_top > right_top {
|
||||
bboxes[i][1].x += gap;
|
||||
} else if right_top > left_top {
|
||||
bboxes[i + 1][0].x -= gap;
|
||||
} else {
|
||||
let half = gap / 2.;
|
||||
bboxes[i][1].x += half;
|
||||
bboxes[i + 1][0].x -= half;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn subpaths_bounding_box(subpaths: &[Subpath<PointId>]) -> Option<[DVec2; 2]> {
|
||||
subpaths
|
||||
.iter()
|
||||
.filter_map(|subpath| subpath.bounding_box())
|
||||
.reduce(|[a_min, a_max], [b_min, b_max]| [a_min.min(b_min), a_max.max(b_max)])
|
||||
}
|
||||
|
||||
impl OutlinePen for PathBuilder {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
if !self.current_subpath.is_empty() {
|
||||
self.glyph_subpaths.push(std::mem::replace(&mut self.current_subpath, Subpath::new(Vec::new(), false)));
|
||||
}
|
||||
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_anchor_with_id(self.point(x, y), self.id.next_id()));
|
||||
}
|
||||
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_anchor_with_id(self.point(x, y), self.id.next_id()));
|
||||
}
|
||||
|
||||
fn quad_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32) {
|
||||
let [handle, anchor] = [self.point(x1, y1), self.point(x2, y2)];
|
||||
self.current_subpath.last_manipulator_group_mut().unwrap().out_handle = Some(handle);
|
||||
self.current_subpath.push_manipulator_group(ManipulatorGroup::new_with_id(anchor, None, None, self.id.next_id()));
|
||||
}
|
||||
|
||||
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32) {
|
||||
let [handle1, handle2, anchor] = [self.point(x1, y1), self.point(x2, y2), self.point(x3, y3)];
|
||||
self.current_subpath.last_manipulator_group_mut().unwrap().out_handle = Some(handle1);
|
||||
self.current_subpath
|
||||
.push_manipulator_group(ManipulatorGroup::new_with_id(anchor, Some(handle2), None, self.id.next_id()));
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.current_subpath.set_closed(true);
|
||||
self.glyph_subpaths.push(std::mem::replace(&mut self.current_subpath, Subpath::new(Vec::new(), false)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::SignedInteger;
|
||||
use core_types::{ATTR_END, ATTR_NAME, ATTR_START, Ctx};
|
||||
|
||||
/// Checks whether the string contains a match for the given regular expression pattern. Optionally restricts the match to only the start and/or end of the string.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
fn regex_contains(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
/// Only match if the pattern appears at the start of the string.
|
||||
at_start: Item<bool>,
|
||||
/// Only match if the pattern appears at the end of the string.
|
||||
at_end: Item<bool>,
|
||||
) -> Item<bool> {
|
||||
let (string, attributes) = string.into_parts();
|
||||
let pattern = pattern.element();
|
||||
let (case_insensitive, multiline, at_start, at_end) = (*case_insensitive.element(), *multiline.element(), *at_start.element(), *at_end.element());
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let anchored_pattern = match (at_start, at_end) {
|
||||
(true, true) => format!("{flags}\\A(?:{pattern})\\z"),
|
||||
(true, false) => format!("{flags}\\A(?:{pattern})"),
|
||||
(false, true) => format!("{flags}(?:{pattern})\\z"),
|
||||
(false, false) => format!("{flags}{pattern}"),
|
||||
};
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&anchored_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return Item::from_parts(false, attributes);
|
||||
};
|
||||
|
||||
Item::from_parts(regex.is_match(&string).unwrap_or(false), attributes)
|
||||
}
|
||||
|
||||
/// Replaces matches of a regular expression pattern in the string. The replacement string can reference captures: `$0` for the whole match and `$1`, `$2`, etc. for capture groups.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
fn regex_replace(
|
||||
_: impl Ctx,
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// The replacement string. Use `$0` for the whole match and `$1`, `$2`, etc. for capture groups.
|
||||
replacement: Item<String>,
|
||||
/// Replace all matches. When disabled, only the first match is replaced.
|
||||
#[default(true)]
|
||||
replace_all: Item<bool>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
) -> Item<String> {
|
||||
let mut string = string;
|
||||
let pattern = pattern.element().clone();
|
||||
let replacement = replacement.element().clone();
|
||||
let (replace_all, case_insensitive, multiline) = (*replace_all.element(), *case_insensitive.element(), *multiline.element());
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::warn!("Invalid regex pattern: {pattern}");
|
||||
return string;
|
||||
};
|
||||
|
||||
let result = if replace_all {
|
||||
regex.replace_all(string.element(), replacement.as_str()).into_owned()
|
||||
} else {
|
||||
regex.replace(string.element(), replacement.as_str()).into_owned()
|
||||
};
|
||||
|
||||
*string.element_mut() = result;
|
||||
string
|
||||
}
|
||||
|
||||
/// Finds a regex match in the string and returns its components. The result is a list where the first item is the whole match (`$0`) and subsequent items are the capture groups (`$1`, `$2`, etc., if any).
|
||||
///
|
||||
/// The match index selects which non-overlapping occurrence to return (0 for the first match). Returns an empty list if no match is found at the given index.
|
||||
///
|
||||
/// Each item carries `start` and `end` byte-offset attributes pointing into the original string, plus a `name` attribute holding
|
||||
/// the capture group's name (empty for unnamed groups, and for index 0 which is the whole match).
|
||||
#[node_macro::node(category(""))]
|
||||
fn regex_find(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.
|
||||
match_index: Item<SignedInteger>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
) -> List<String> {
|
||||
let string = string.element();
|
||||
let pattern = pattern.element();
|
||||
let (match_index, case_insensitive, multiline) = (*match_index.element(), *case_insensitive.element(), *multiline.element());
|
||||
|
||||
if pattern.is_empty() {
|
||||
return List::new();
|
||||
}
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return List::new();
|
||||
};
|
||||
|
||||
// Capture group names indexed positionally; index 0 (the whole match) is always None.
|
||||
let capture_names: Vec<Option<String>> = regex.capture_names().map(|name| name.map(str::to_string)).collect();
|
||||
|
||||
// Collect all matches since we need to support negative indexing
|
||||
let matches: Vec<_> = regex.captures_iter(string).filter_map(|c| c.ok()).collect();
|
||||
|
||||
let match_index = match_index as i32;
|
||||
let resolved_index = if match_index < 0 {
|
||||
let from_end = (-match_index) as usize;
|
||||
if from_end > matches.len() {
|
||||
return List::new();
|
||||
}
|
||||
matches.len() - from_end
|
||||
} else {
|
||||
match_index as usize
|
||||
};
|
||||
|
||||
let Some(captures) = matches.get(resolved_index) else {
|
||||
return List::new();
|
||||
};
|
||||
|
||||
// Index 0 is the whole match, 1+ are capture groups
|
||||
(0..captures.len())
|
||||
.map(|i| {
|
||||
let captured = captures.get(i);
|
||||
let text = captured.map_or(String::new(), |m| m.as_str().to_string());
|
||||
let start = captured.map_or(0_u64, |m| m.start() as u64);
|
||||
let end = captured.map_or(0_u64, |m| m.end() as u64);
|
||||
let name = capture_names.get(i).cloned().flatten().unwrap_or_default();
|
||||
Item::new_from_element(text)
|
||||
.with_attribute(ATTR_START, start)
|
||||
.with_attribute(ATTR_END, end)
|
||||
.with_attribute(ATTR_NAME, name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Finds all non-overlapping matches of a regular expression pattern in the string, returning a list of the matched substrings.
|
||||
///
|
||||
/// Each item carries `start` and `end` byte-offset attributes pointing into the original string.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
fn regex_find_all(
|
||||
_: impl Ctx,
|
||||
/// The string to search within.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to search for.
|
||||
pattern: Item<String>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
) -> List<String> {
|
||||
let string = string.element();
|
||||
let pattern = pattern.element();
|
||||
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
|
||||
|
||||
if pattern.is_empty() {
|
||||
return List::new();
|
||||
}
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return List::new();
|
||||
};
|
||||
|
||||
regex
|
||||
.find_iter(string)
|
||||
.filter_map(|m| m.ok())
|
||||
.map(|m| {
|
||||
Item::new_from_element(m.as_str().to_string())
|
||||
.with_attribute(ATTR_START, m.start() as u64)
|
||||
.with_attribute(ATTR_END, m.end() as u64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Splits a string into a list of substrings pulled from between separator characters as matched by a regular expression.
|
||||
///
|
||||
/// For example, splitting "Three, two, one... LIFTOFF" with pattern `\W+` (non-word characters) produces `["Three", "two", "one", "LIFTOFF"]`.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
fn regex_split(
|
||||
_: impl Ctx,
|
||||
/// The string to split into substrings.
|
||||
string: Item<String>,
|
||||
/// The regular expression pattern to split on. Matches are consumed and not included in the output.
|
||||
pattern: Item<String>,
|
||||
/// Match letters regardless of case.
|
||||
case_insensitive: Item<bool>,
|
||||
/// Make `^` and `$` match the start and end of each line, not just the whole string.
|
||||
multiline: Item<bool>,
|
||||
) -> List<String> {
|
||||
let pattern = pattern.element().clone();
|
||||
let (case_insensitive, multiline) = (*case_insensitive.element(), *multiline.element());
|
||||
|
||||
if pattern.is_empty() {
|
||||
return List::new_from_item(string);
|
||||
}
|
||||
|
||||
let flags = match (case_insensitive, multiline) {
|
||||
(false, false) => "",
|
||||
(true, false) => "(?i)",
|
||||
(false, true) => "(?m)",
|
||||
(true, true) => "(?im)",
|
||||
};
|
||||
let full_pattern = format!("{flags}{pattern}");
|
||||
|
||||
let Ok(regex) = fancy_regex::Regex::new(&full_pattern) else {
|
||||
log::error!("Invalid regex pattern: {pattern}");
|
||||
return List::new_from_item(string);
|
||||
};
|
||||
|
||||
regex.split(string.element()).filter_map(|s| s.ok()).map(|s| s.to_string()).map(Item::new_from_element).collect()
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,189 @@
|
||||
use super::TypesettingConfig;
|
||||
use super::path_builder::PathBuilder;
|
||||
use core::cell::RefCell;
|
||||
use core_types::list::List;
|
||||
use glam::DVec2;
|
||||
use graphene_resource::{Resource, ResourceHash};
|
||||
use parley::fontique::{Blob, FamilyId, FontInfo};
|
||||
use parley::{AlignmentOptions, FontContext, GlyphRun, Layout, LayoutContext, LineHeight, PositionedLayoutItem, StyleProperty};
|
||||
use std::collections::HashMap;
|
||||
use vector_types::Vector;
|
||||
|
||||
thread_local! {
|
||||
static THREAD_TEXT: RefCell<TextContext> = RefCell::new(TextContext::default());
|
||||
}
|
||||
|
||||
/// Iterates the glyph runs of a laid-out text in reading order, computing each line's last-line alignment correction
|
||||
/// (`x_offset` and per-space `space_extra`) and skipping runs clipped by `max_height`. Shared by the vector shaper and the
|
||||
/// SVG/Vello text renderers so the alignment logic lives in one place.
|
||||
pub fn for_each_styled_glyph_run(layout: &Layout<()>, text: &str, typesetting: TypesettingConfig, mut visit: impl FnMut(&GlyphRun<'_, ()>, f32, f32)) {
|
||||
let alignment_width = typesetting.max_width.map(|w| w as f32).unwrap_or_else(|| layout.full_width());
|
||||
let last_line_correction = typesetting.align.last_line_correction();
|
||||
|
||||
for line in layout.lines() {
|
||||
let range = line.text_range();
|
||||
// Parley always includes a hard-break `\n` as the last byte of the preceding line's range, so the line is at the end of
|
||||
// a paragraph if it's the very last line of the buffer or its text ends with `\n`.
|
||||
let is_last_para_line = range.end == text.len() || text.get(range.clone()).is_some_and(|s| s.ends_with('\n'));
|
||||
|
||||
let mut x_offset = 0.;
|
||||
let mut space_extra = 0.;
|
||||
|
||||
if is_last_para_line && let Some(correction) = last_line_correction {
|
||||
let metrics = line.metrics();
|
||||
let content_advance = metrics.advance - metrics.trailing_whitespace;
|
||||
let free_space = alignment_width - content_advance;
|
||||
|
||||
match correction {
|
||||
parley::Alignment::Center => x_offset = free_space * 0.5,
|
||||
parley::Alignment::Right => x_offset = free_space,
|
||||
parley::Alignment::Justify => {
|
||||
// Exclude trailing-whitespace clusters from the divisor so the redistribution stretches only the internal spaces.
|
||||
// Parley's `trailing_whitespace` is in advance units, not bytes, so we re-derive the byte boundary here to filter cluster ranges.
|
||||
let line_text = text.get(range.clone()).unwrap_or("");
|
||||
let trailing_len = line_text.len() - line_text.trim_end().len();
|
||||
let visible_end_index = range.end - trailing_len;
|
||||
|
||||
let space_count: usize = line
|
||||
.runs()
|
||||
.map(|run| run.clusters().filter(|c| c.is_space_or_nbsp() && c.text_range().start < visible_end_index).count())
|
||||
.sum();
|
||||
if space_count > 0 {
|
||||
space_extra = free_space / space_count as f32;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
for item in line.items() {
|
||||
if let PositionedLayoutItem::GlyphRun(glyph_run) = item
|
||||
&& typesetting.max_height.filter(|&max_height| glyph_run.baseline() > max_height as f32).is_none()
|
||||
{
|
||||
visit(&glyph_run, x_offset, space_extra);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unified thread-local text processing context that combines font and layout management
|
||||
/// for efficient text rendering operations.
|
||||
#[derive(Default)]
|
||||
pub struct TextContext {
|
||||
font_context: FontContext,
|
||||
layout_context: LayoutContext<()>,
|
||||
font_info_cache: HashMap<ResourceHash, (FamilyId, FontInfo)>,
|
||||
}
|
||||
|
||||
impl TextContext {
|
||||
/// Access the thread-local TextContext instance for text processing operations
|
||||
pub fn with_thread_local<F, R>(f: F) -> R
|
||||
where
|
||||
F: FnOnce(&mut TextContext) -> R,
|
||||
{
|
||||
THREAD_TEXT.with_borrow_mut(f)
|
||||
}
|
||||
|
||||
/// Get or cache font information for the given font resource.
|
||||
fn get_font_info(&mut self, font: &Resource) -> Option<(String, FontInfo)> {
|
||||
let hash = font.hash();
|
||||
if let Some((family_id, font_info)) = self.font_info_cache.get(&hash)
|
||||
&& let Some(family_name) = self.font_context.collection.family_name(*family_id)
|
||||
{
|
||||
return Some((family_name.to_string(), font_info.clone()));
|
||||
}
|
||||
|
||||
let families = self.font_context.collection.register_fonts(Blob::new(font.into()), None);
|
||||
|
||||
families.first().and_then(|(family_id, fonts_info)| {
|
||||
fonts_info.first().and_then(|font_info| {
|
||||
self.font_context.collection.family_name(*family_id).map(|family_name| {
|
||||
self.font_info_cache.insert(hash, (*family_id, font_info.clone()));
|
||||
(family_name.to_string(), font_info.clone())
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a text layout from the given font resource and typesetting configuration.
|
||||
pub fn layout_text(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig) -> Option<Layout<()>> {
|
||||
let (font_family, font_info) = self.get_font_info(font)?;
|
||||
|
||||
const DISPLAY_SCALE: f32 = 1.;
|
||||
let mut builder = self.layout_context.ranged_builder(&mut self.font_context, text, DISPLAY_SCALE, false);
|
||||
|
||||
builder.push_default(StyleProperty::FontSize(typesetting.font_size as f32));
|
||||
builder.push_default(StyleProperty::LetterSpacing(typesetting.letter_spacing as f32));
|
||||
builder.push_default(StyleProperty::FontFamily(parley::FontFamily::Single(parley::FontFamilyName::Named(std::borrow::Cow::Owned(
|
||||
font_family,
|
||||
)))));
|
||||
builder.push_default(StyleProperty::FontWeight(font_info.weight()));
|
||||
builder.push_default(StyleProperty::FontStyle(font_info.style()));
|
||||
builder.push_default(StyleProperty::FontWidth(font_info.width()));
|
||||
builder.push_default(LineHeight::FontSizeRelative(typesetting.line_height_ratio as f32));
|
||||
|
||||
let mut layout: Layout<()> = builder.build(text);
|
||||
|
||||
layout.break_all_lines(typesetting.max_width.map(|mw| mw as f32));
|
||||
layout.align(typesetting.align.into(), AlignmentOptions::default());
|
||||
|
||||
Some(layout)
|
||||
}
|
||||
|
||||
/// Convert text to vector paths using the specified font and typesetting configuration
|
||||
pub fn to_path(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> List<Vector> {
|
||||
let Some(layout) = self.layout_text(text, font, typesetting) else {
|
||||
return List::new_from_element(Vector::default());
|
||||
};
|
||||
|
||||
let text_frame_size = DVec2::new(
|
||||
typesetting.max_width.unwrap_or_else(|| layout.full_width() as f64),
|
||||
typesetting.max_height.unwrap_or_else(|| layout.height() as f64),
|
||||
);
|
||||
|
||||
// First glyph offset (pre-height-filter) so the empty placeholder item in `per_glyph_items`
|
||||
// mode keeps the same item 0's transform, preventing `local_transforms` from jumping mid-drag
|
||||
let first_glyph_offset = layout
|
||||
.lines()
|
||||
.flat_map(|line| line.items())
|
||||
.find_map(|item| match item {
|
||||
PositionedLayoutItem::GlyphRun(run) => run.glyphs().next().map(|glyph| DVec2::new((run.offset() + glyph.x) as f64, (run.baseline() - glyph.y) as f64)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut path_builder = PathBuilder::new(per_glyph_items, layout.scale() as f64, text_frame_size, first_glyph_offset);
|
||||
|
||||
for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
|
||||
path_builder.render_glyph_run(glyph_run, typesetting.letter_tilt, per_glyph_items, x_offset, space_extra);
|
||||
});
|
||||
|
||||
path_builder.finalize()
|
||||
}
|
||||
|
||||
/// Calculate the bounding box of text using the specified font and typesetting configuration
|
||||
pub fn bounding_box(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig, for_clipping_test: bool) -> DVec2 {
|
||||
let Some(layout) = self.layout_text(text, font, typesetting) else {
|
||||
return DVec2::ZERO;
|
||||
};
|
||||
|
||||
let layout_width = layout.full_width() as f64;
|
||||
let layout_height = layout.height() as f64;
|
||||
|
||||
if for_clipping_test {
|
||||
return DVec2::new(layout_width, layout_height);
|
||||
}
|
||||
|
||||
let width = typesetting.max_width.unwrap_or(layout_width);
|
||||
let height = typesetting.max_height.unwrap_or(layout_height);
|
||||
|
||||
DVec2::new(width, height)
|
||||
}
|
||||
|
||||
/// Check if text lines are being clipped due to height constraints
|
||||
pub fn lines_clipping(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig) -> bool {
|
||||
let Some(max_height) = typesetting.max_height else { return false };
|
||||
let bounds = self.bounding_box(text, font, typesetting, true);
|
||||
max_height < bounds.y
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use super::TypesettingConfig;
|
||||
use super::text_context::TextContext;
|
||||
use crate::markers::{ATTR_FONT, ATTR_TEXT_ALIGN};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_EDITOR_LAYER_PATH, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_resource::Resource;
|
||||
use vector_types::Vector;
|
||||
|
||||
pub fn to_path(text: &str, font: &Resource, typesetting: TypesettingConfig, per_glyph_items: bool) -> List<Vector> {
|
||||
TextContext::with_thread_local(|ctx| ctx.to_path(text, font, typesetting, per_glyph_items))
|
||||
}
|
||||
|
||||
pub fn bounding_box(text: &str, font: &Resource, typesetting: TypesettingConfig, for_clipping_test: bool) -> DVec2 {
|
||||
TextContext::with_thread_local(|ctx| ctx.bounding_box(text, font, typesetting, for_clipping_test))
|
||||
}
|
||||
|
||||
pub fn lines_clipping(text: &str, font: &Resource, typesetting: TypesettingConfig) -> bool {
|
||||
TextContext::with_thread_local(|ctx| ctx.lines_clipping(text, font, typesetting))
|
||||
}
|
||||
|
||||
/// Shapes a single styled string item into vector geometry, reading its font and typesetting from the item's
|
||||
/// attributes (as set by the 'Text' node) and re-applying its transform and blending attributes onto the produced
|
||||
/// paths. With `separate_glyphs`, each glyph becomes its own item; otherwise a single compound path is produced.
|
||||
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> List<Vector> {
|
||||
let text = item.element();
|
||||
if text.is_empty() {
|
||||
return List::new();
|
||||
}
|
||||
|
||||
// Use fallback font when none is explicitly attached.
|
||||
let font: Resource = {
|
||||
let font: Resource = item.attribute_cloned_or_default(ATTR_FONT);
|
||||
if font.is_empty() { super::FALLBACK_FONT_RESOURCE.clone() } else { font }
|
||||
};
|
||||
|
||||
let defaults = TypesettingConfig::default();
|
||||
let typesetting = TypesettingConfig {
|
||||
font_size: item.attribute_cloned_or(ATTR_FONT_SIZE, defaults.font_size),
|
||||
line_height_ratio: item.attribute_cloned_or(ATTR_LINE_HEIGHT, defaults.line_height_ratio),
|
||||
letter_spacing: item.attribute_cloned_or(ATTR_LETTER_SPACING, defaults.letter_spacing),
|
||||
letter_tilt: item.attribute_cloned_or(ATTR_LETTER_TILT, defaults.letter_tilt),
|
||||
max_width: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, defaults.max_width),
|
||||
max_height: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, defaults.max_height),
|
||||
align: item.attribute_cloned_or(ATTR_TEXT_ALIGN, defaults.align),
|
||||
};
|
||||
|
||||
let vectors = to_path(text, &font, typesetting, separate_glyphs);
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let layer_path = item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).cloned();
|
||||
let blend_mode = item.attribute::<BlendMode>(ATTR_BLEND_MODE).copied();
|
||||
let opacity = item.attribute::<f64>(ATTR_OPACITY).copied();
|
||||
let opacity_fill = item.attribute::<f64>(ATTR_OPACITY_FILL).copied();
|
||||
|
||||
let mut result = List::new();
|
||||
for mut produced in vectors.into_iter() {
|
||||
if transform != DAffine2::IDENTITY {
|
||||
let local = produced.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
produced.set_attribute(ATTR_TRANSFORM, transform * local);
|
||||
}
|
||||
if let Some(layer_path) = &layer_path {
|
||||
produced.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
|
||||
}
|
||||
if let Some(blend_mode) = blend_mode {
|
||||
produced.set_attribute(ATTR_BLEND_MODE, blend_mode);
|
||||
}
|
||||
if let Some(opacity) = opacity {
|
||||
produced.set_attribute(ATTR_OPACITY, opacity);
|
||||
}
|
||||
if let Some(opacity_fill) = opacity_fill {
|
||||
produced.set_attribute(ATTR_OPACITY_FILL, opacity_fill);
|
||||
}
|
||||
result.push(produced);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Shapes each string item of a styled `List<String>` into vector geometry, flattening the per-item results.
|
||||
pub fn shape_text_list(strings: &List<String>, separate_glyphs: bool) -> List<Vector> {
|
||||
let mut result = List::new();
|
||||
|
||||
for index in 0..strings.len() {
|
||||
let Some(item) = strings.clone_item(index) else { continue };
|
||||
for produced in shape_text_item(&item, separate_glyphs).into_iter() {
|
||||
result.push(produced);
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
Reference in New Issue
Block a user