diff --git a/ROADMAP.md b/ROADMAP.md index c35d4b20..8da77eb0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -60,7 +60,8 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent renderer in its own crate (layering allows it below L6), with output in SVG/PDF as rasters or projected vectors. The largest single gap. 50–80 h. 4. **Advanced type:** CJK composition for vertical type (ruby, mojikumi, proportional vertical metrics, manual - tate-chu-yoko), Optical Margin Alignment, the composer/hyphenation options, tab leaders, a + tate-chu-yoko), Optical Margin Alignment, the hyphenation and justification options (the Every-line/Single-line + composer choice is done), tab leaders, a spell-check dictionary (open licence), Touch Type and Snap to Glyph. Vertical point, area and path type have initial support. 35–48 h across type core and advanced. 5. **Brushes, symbols and libraries:** brush options depth; original brush, symbol and graphic-style libraries @@ -138,7 +139,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist - **Geometry and effects:** - Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). -- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). +- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). - **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). @@ -175,7 +176,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out, EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, Asset Export, clipboard flavours, File Info. Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, polish | 3–6 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open) | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options (with Width/Height), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, Hebrew/Arabic bidirectional text and Paragraph Direction done; tab leaders, spell check, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options (with Width/Height), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder and Color Adjustments; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; brushes/symbols in progress | 23–37 | @@ -210,7 +211,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters | 6–10 | | Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 20% | ~55 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery; Document Raster Effects Settings and raster effects in PDF are done | 28–42 | | 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 | -| Type core | 9 | 79% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); composer/hyphenation options, Optical Margin Alignment, hidden characters, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 15–20 | +| Type core | 9 | 79% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, hidden characters, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 | | Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko, Character Alignment on the ICF top and bottom), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support | 20–28 | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 | | Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), Image Trace View modes (Outlines, Source Image) (Vector Halftone is done) | 6–10 | diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index e3b54a84..e19312f2 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -82,8 +82,8 @@ pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes}; pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource}; pub use style_libs::StyleLibrary; pub use text::{ - AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, - PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, WrapShape, + AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, + PathAlign, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, WrapShape, }; pub use vectorcraft_color as color; pub use vectorcraft_geom as geom; diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index fb0d246e..fd1ba214 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -285,6 +285,24 @@ fn default_align_on() -> char { /// Distance between default tab stops when no explicit stop applies (½ inch). pub const DEFAULT_TAB_INTERVAL: f64 = 36.0; +/// Paragraph composer (Paragraph panel menu): how lines are broken. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Composer { + /// Break each line as soon as it is full. + SingleLine, + /// Total fit over the whole paragraph (Illustrator's default): justified lines get even word + /// spacing, ragged lines an even rag. + #[default] + EveryLine, +} + +impl Composer { + fn is_default(&self) -> bool { + *self == Self::default() + } +} + /// Paragraph attributes (the Paragraph panel). /// /// Saved through [`ParaStyleFile`], which keeps files with text openable by builds from before @@ -299,6 +317,8 @@ pub struct ParaStyle { pub space_before: f64, pub space_after: f64, pub hyphenate: bool, + /// Line breaking: Single-line or Every-line Composer. + pub composer: Composer, /// Tab stops (Tabs panel), sorted by position. pub tabs: Vec, /// Paragraph style (Paragraph Styles panel) these attributes come from; None = Normal. @@ -341,6 +361,8 @@ struct ParaStyleFile { space_after: f64, #[serde(default)] hyphenate: bool, + #[serde(default, skip_serializing_if = "Composer::is_default")] + composer: Composer, #[serde(default, skip_serializing_if = "Vec::is_empty")] tabs: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -370,6 +392,7 @@ impl From for ParaStyleFile { space_before, space_after, hyphenate, + composer, tabs, style_name, mojikumi, @@ -387,6 +410,7 @@ impl From for ParaStyleFile { space_before, space_after, hyphenate, + composer, tabs, style_name, mojikumi, @@ -407,6 +431,7 @@ impl From for ParaStyle { space_before, space_after, hyphenate, + composer, tabs, style_name, mojikumi, @@ -423,6 +448,7 @@ impl From for ParaStyle { space_before, space_after, hyphenate, + composer, tabs, style_name, mojikumi, diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 3cee0f4a..02d7d62e 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -2,7 +2,7 @@ //! Character/Paragraph attributes. use serde_json::{Value, json}; -use vectorcraft_doc::NodeKind; +use vectorcraft_doc::{Composer, NodeKind}; use vectorcraft_geom::{Rect, Vec2}; use super::*; @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt, hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (where characters smaller than the largest on their line line up with it), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\")}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt, hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (where characters smaller than the largest on their line line up with it), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default)}", has_doc, set_format ), @@ -219,10 +219,19 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "leadingModel", "charAlign", "burasagari", + "composer", ]; if !keys.iter().any(|k| p.get(*k).is_some()) { return Err(bad(C, "nothing to change")); } + let composer = match p.get("composer") { + None | Some(Value::Null) => None, + Some(v) => Some(match v.as_str() { + Some("singleLine") => Composer::SingleLine, + Some("everyLine") => Composer::EveryLine, + _ => return Err(bad(C, "composer must be \"singleLine\" or \"everyLine\"")), + }), + }; let (position, small_caps) = super::docsetup::script_params(p, &s.doc()?.doc.setup, C)?; let char_align = super::textedit::char_align_param(p, C)?; let mojikumi = match p.get("mojikumi") { @@ -329,6 +338,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = burasagari { para.burasagari = v; } + if let Some(v) = composer { + para.composer = v; + } super::typecmd::refresh_bounds(t); } Ok(()) diff --git a/crates/engine/src/tests_panelcmds.rs b/crates/engine/src/tests_panelcmds.rs index b2374343..1844a810 100644 --- a/crates/engine/src/tests_panelcmds.rs +++ b/crates/engine/src/tests_panelcmds.rs @@ -248,6 +248,16 @@ fn text_set_format() { let NodeKind::Text(t) = node(&s, id).kind else { panic!() }; assert_eq!(t.first_style().kerning, None); assert!(s.execute("text.setFormat", &json!({"ids": [id.0]})).is_err()); + // Paragraph composer: Every-line by default, undoable. + assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine); + s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "singleLine"})).unwrap(); + let NodeKind::Text(t) = node(&s, id).kind else { panic!() }; + assert_eq!(t.para.composer, vectorcraft_doc::Composer::SingleLine); + assert!(s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "best"})).is_err()); + assert!(s.execute("text.setFormat", &json!({"ids": [id.0], "composer": 1})).is_err()); + s.execute("edit.undo", &json!({})).unwrap(); + let NodeKind::Text(t) = node(&s, id).kind else { panic!() }; + assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine); } #[test] diff --git a/crates/format/tests/native_v3.rs b/crates/format/tests/native_v3.rs index 8ca0d21d..f9ec96a1 100644 --- a/crates/format/tests/native_v3.rs +++ b/crates/format/tests/native_v3.rs @@ -7,7 +7,7 @@ use std::io::Write as _; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{ColorProfiles, Document, ImageBlob, ImageObject, Node, NodeKind, OpacityMask, Symbol}; +use vectorcraft_doc::{ColorProfiles, Composer, Document, ImageBlob, ImageObject, Node, NodeKind, OpacityMask, Symbol}; use vectorcraft_format::{FormatError, SaveOptions, VERSION, is_compressed, load, preview, save, save_with, sniff}; use vectorcraft_geom::Affine; use vectorcraft_testkit::fixtures; @@ -111,6 +111,41 @@ fn keys_from_newer_versions_round_trip() { check_native_roundtrip(&d).unwrap(); } +/// The paragraph composer is saved only when it isn't the default (Every-line) and reads back. +#[test] +fn text_composer_round_trips() { + let d = rich_doc(); + let composers = |d: &Document| { + let mut v = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + v.push(t.para.composer); + } + }); + v + }; + assert_eq!(composers(&d), [Composer::SingleLine]); + let bytes = save(&d, false); + assert!(String::from_utf8_lossy(&bytes).contains("\"composer\":\"singleLine\"")); + assert_eq!(composers(&load(&bytes).unwrap()), [Composer::SingleLine]); + // Files without the key (older files, Every-line text) read as Every-line. + fn strip(v: &mut Value) { + match v { + Value::Object(m) => { + m.remove("composer"); + m.values_mut().for_each(strip); + } + Value::Array(a) => a.iter_mut().for_each(strip), + _ => {} + } + } + let mut v = json_of(&bytes); + strip(&mut v); + let d2 = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + assert_eq!(composers(&d2), [Composer::EveryLine]); + assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer")); +} + /// A document as the first version wrote it (format name `drawcraft`, anchors as maps). const V1_FILE: &str = r#"{"format":"drawcraft","version":1,"generator":"DrawCraft 0.1.0","document":{"version":1,"title":"Old","artboards":[{"id":1,"name":"Artboard 1","rect":{"x0":0.0,"y0":0.0,"x1":100.0,"y1":80.0}}], "layers":[{"id":1,"name":"Layer 1","visible":true,"locked":false,"opacity":1.0,"kind":{"type":"layer","children":[ diff --git a/crates/testkit/src/fixtures.rs b/crates/testkit/src/fixtures.rs index 23dd3d17..0e946feb 100644 --- a/crates/testkit/src/fixtures.rs +++ b/crates/testkit/src/fixtures.rs @@ -112,7 +112,9 @@ pub fn rich_session() -> Session { exec(&mut s, "effect.apply", json!({"effect": "distort.roughen", "params": {"size": 3, "detail": 5, "seed": 7}})); let l = id_of(&exec(&mut s, "shape.line", json!({"x1": 20, "y1": 300, "x2": 200, "y2": 350}))); exec(&mut s, "stroke.set", json!({"weight": 3, "endArrow": "Arrow"})); - let _ = id_of(&exec(&mut s, "text.create", json!({"x": 250, "y": 300, "text": "VectorCraft", "size": 30}))); + let tx = id_of(&exec(&mut s, "text.create", json!({"x": 250, "y": 300, "text": "VectorCraft", "size": 30}))); + // A non-default paragraph composer, so format round trips cover it. + exec(&mut s, "text.setFormat", json!({"ids": [tx.0], "composer": "singleLine"})); exec(&mut s, "layer.new", json!({"name": "Top"})); let d = rect(&mut s, 350.0, 200.0, 80.0, 80.0); let e = ellipse(&mut s, 380.0, 230.0, 80.0, 80.0); diff --git a/crates/text/src/composer.rs b/crates/text/src/composer.rs index 03b594f8..cea1c5d4 100644 --- a/crates/text/src/composer.rs +++ b/crates/text/src/composer.rs @@ -1,9 +1,17 @@ -//! Every-line composer: a Knuth–Plass style total-fit line breaker for justified paragraphs. +//! Every-line composer: a Knuth–Plass style total-fit line breaker. //! -//! Boxes are the paragraph's glyphs, glue is its spaces (word spacing may stretch to 150% and -//! shrink to 80%), and penalties are break opportunities after hyphens/dashes/CJK and at -//! hyphenation points. The breaks minimise the sum of squared (badness + penalty) demerits over -//! the whole paragraph, so loose lines are traded for evenly spaced ones. +//! Boxes are the paragraph's glyphs, glue is its spaces, and penalties are break opportunities +//! after hyphens/dashes/CJK and at hyphenation points. The breaks minimise the sum of squared +//! (badness + penalty) demerits over the whole paragraph, plus a demerit when neighbouring lines +//! fall in fitness classes more than one apart (a tight line next to a loose one). +//! +//! - **Justified** lines: word spacing may stretch to 150% and shrink to 80%; the badness comes +//! from the stretch/shrink ratio, so loose lines are traded for evenly spaced ones. +//! - **Ragged** lines (left/centre/right aligned): spaces keep their width, so a line never +//! shrinks (it must fit). The badness comes from the line's leftover space measured against a +//! rag zone of a sixth of the line width, so the rag is even rather than full lines followed by +//! a short one, and hyphenating costs less. The last line costs nothing unless it is shorter +//! than a third of the width (a word or two left dangling). use crate::shape::SGlyph; @@ -12,6 +20,21 @@ const SHRINK: f64 = 0.2; const HYPHEN_PENALTY: f64 = 50.0; const DOUBLE_HYPHEN_DEMERITS: f64 = 3000.0; const LINE_PENALTY: f64 = 10.0; +/// Demerits for adjacent lines whose fitness classes differ by more than one. +const ADJ_DEMERITS_JUSTIFIED: f64 = 10_000.0; +const ADJ_DEMERITS_RAGGED: f64 = 1_000.0; +/// Ragged lines only gain from hyphenation by filling the rag, so it costs less than in +/// justified text (where it also evens the word spacing). +const HYPHEN_PENALTY_RAGGED: f64 = 25.0; +/// Ragged text: leftover space is measured in units of this fraction of the line width. +const RAG_ZONE: f64 = 1.0 / 6.0; +/// Ragged text: a last line shorter than this fraction of the width is penalised, by how much +/// shorter it is in units of `SHORT_LAST_ZONE` of the width. +const SHORT_LAST: f64 = 1.0 / 3.0; +const SHORT_LAST_ZONE: f64 = 1.0 / 3.0; +/// Give up (fall back to the single-line composer) beyond this many active breakpoints. +const MAX_ACTIVE: usize = 4096; +const EPS: f64 = 1e-6; /// A place a line may end: glyph index `end` (exclusive), plus the width of the hyphen that is /// added when breaking there (0 = no hyphen). @@ -21,24 +44,56 @@ pub(crate) struct Breakpoint { pub hyphen: f64, } +/// How a paragraph is composed. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Params { + /// The last line is justified too (Justify All). + pub justify_last: bool, + /// Left/centre/right aligned text: spaces keep their width and lines are scored by their rag. + pub ragged: bool, + /// Maximum stretch ratio (justified) or leftover space in rag zones (ragged) of a line. + pub tolerance: f64, + /// Lines from this index on all have the same width, so their line numbers are interchangeable + /// (keeps the number of active breakpoints small). + pub uniform_from: usize, +} + struct Node { pos: usize, + /// Line number of the next line, clamped to `uniform_from`. line: usize, + fitness: u8, demerits: f64, hyphenated: bool, prev: Option, } +/// Fitness class 0 (tight) … 3 (very loose) of a line with adjustment ratio `r`. +fn fitness(r: f64, ragged: bool) -> u8 { + let bounds = if ragged { [0.15, 0.4, 0.75] } else { [-0.5, 0.5, 1.0] }; + if r < bounds[0] { + 0 + } else if r <= bounds[1] { + 1 + } else if r <= bounds[2] { + 2 + } else { + 3 + } +} + /// Compose the paragraph `g` into lines. `width(k)` is the available width of line `k`; -/// `cands` are the break opportunities in increasing order (the paragraph end is added). -/// `justify_last`: the last line is justified too (Justify All). Returns `(end, hyphen)` per line, -/// or `None` if no set of breaks fits within `tolerance` (maximum stretch ratio). +/// `start_credit(i)` is the width a wrapped line starting at glyph `i` gives back (Mojikumi sets +/// an opening bracket there flush with the line's start); `cands` are the break opportunities +/// in increasing order (the paragraph end is added). +/// Returns `(end, hyphen)` per line, or `None` if no set of breaks fits within the tolerance +/// (the caller then falls back to single-line breaking). pub(crate) fn compose( g: &[SGlyph], width: &dyn Fn(usize) -> f64, + start_credit: &dyn Fn(usize) -> f64, cands: &[Breakpoint], - justify_last: bool, - tolerance: f64, + p: &Params, ) -> Option> { let n = g.len(); if n == 0 { @@ -51,68 +106,93 @@ pub(crate) fn compose( w[i + 1] = w[i] + gl.adv; sp[i + 1] = sp[i] + if gl.is_space() { gl.adv } else { 0.0 }; } + if !w[n].is_finite() { + return None; + } // Trailing spaces are dropped at a break. let trim = |mut b: usize, a: usize| { - while b > a && g[b - 1].is_space() { + while b > a && g.get(b - 1).is_some_and(SGlyph::is_space) { b -= 1; } b }; let mut all: Vec = cands.iter().copied().filter(|c| c.end > 0 && c.end < n).collect(); all.push(Breakpoint { end: n, hyphen: 0.0 }); - let mut nodes = vec![Node { pos: 0, line: 0, demerits: 0.0, hyphenated: false, prev: None }]; + let (adj_demerits, hyphen_penalty) = + if p.ragged { (ADJ_DEMERITS_RAGGED, HYPHEN_PENALTY_RAGGED) } else { (ADJ_DEMERITS_JUSTIFIED, HYPHEN_PENALTY) }; + let mut nodes = vec![Node { pos: 0, line: 0, fitness: 1, demerits: 0.0, hyphenated: false, prev: None }]; let mut active: Vec = vec![0]; for bp in &all { let last = bp.end == n; - let mut best: Vec<(usize, f64, usize)> = vec![]; // (line, demerits, from) + let mut best: Vec<(usize, u8, f64, usize)> = vec![]; // (line, fitness, demerits, from) let mut keep = Vec::with_capacity(active.len()); for &ai in &active { - let a = &nodes[ai]; + let Some(a) = nodes.get(ai) else { continue }; let t = trim(bp.end, a.pos); - let natural = w[t] - w[a.pos] + bp.hyphen; - let spaces = sp[t] - sp[a.pos]; + let credit = if a.pos > 0 { start_credit(a.pos) } else { 0.0 }; + let natural = w[t] - w[a.pos] - credit + bp.hyphen; let lw = width(a.line); - let ratio = if natural < lw { - if last && !justify_last { - 0.0 - } else if spaces > 0.0 { - (lw - natural) / (spaces * STRETCH) - } else { - f64::INFINITY + // Adjustment ratio, badness and whether the line ends the active node's reach. + let ratio = if p.ragged { + if natural > lw + EPS { + // Ragged lines never shrink; longer lines from this node only get worse. + continue; + } + if last && !p.justify_last { + ((lw * SHORT_LAST - natural) / (lw * SHORT_LAST_ZONE).max(1.0)).max(0.0) + } else { + (lw - natural).max(0.0) / (lw * RAG_ZONE).max(1.0) } - } else if natural > lw { - if spaces > 0.0 { (lw - natural) / (spaces * SHRINK) } else { f64::NEG_INFINITY } } else { - 0.0 + let spaces = sp[t] - sp[a.pos]; + if natural < lw { + if last && !p.justify_last { + 0.0 + } else if spaces > 0.0 { + (lw - natural) / (spaces * STRETCH) + } else { + f64::INFINITY + } + } else if natural > lw { + if spaces > 0.0 { (lw - natural) / (spaces * SHRINK) } else { f64::NEG_INFINITY } + } else { + 0.0 + } }; if ratio < -1.0 { // Too long already; longer lines from this node only get worse. continue; } keep.push(ai); - if ratio > tolerance && !(last && ratio.is_infinite() && justify_last) { + let free_last = last && (p.ragged || !p.justify_last); + if ratio > p.tolerance && !(last && (p.ragged || (ratio.is_infinite() && p.justify_last))) { continue; } let badness = if ratio.is_finite() { (100.0 * ratio.abs().powi(3)).min(10_000.0) } else { 10_000.0 }; - let penalty = if bp.hyphen > 0.0 { HYPHEN_PENALTY } else { 0.0 }; + let penalty = if bp.hyphen > 0.0 { hyphen_penalty } else { 0.0 }; let mut d = (LINE_PENALTY + badness).powi(2) + penalty * penalty; if bp.hyphen > 0.0 && a.hyphenated { d += DOUBLE_HYPHEN_DEMERITS; } + // A ragged last line's length says nothing about the rag: it keeps its neighbour's class. + let fit = if p.ragged && free_last { a.fitness } else { fitness(ratio, p.ragged) }; + if a.prev.is_some() && fit.abs_diff(a.fitness) > 1 { + d += adj_demerits; + } let total = a.demerits + d; - let line = a.line + 1; - match best.iter_mut().find(|b| b.0 == line) { - Some(b) if b.1 <= total => {} - Some(b) => *b = (line, total, ai), - None => best.push((line, total, ai)), + let line = (a.line + 1).min(p.uniform_from); + match best.iter_mut().find(|b| b.0 == line && b.1 == fit) { + Some(b) if b.2 <= total => {} + Some(b) => *b = (line, fit, total, ai), + None => best.push((line, fit, total, ai)), } } active = keep; - for (line, demerits, from) in best { - nodes.push(Node { pos: bp.end, line, demerits, hyphenated: bp.hyphen > 0.0, prev: Some(from) }); + for (line, fitness, demerits, from) in best { + nodes.push(Node { pos: bp.end, line, fitness, demerits, hyphenated: bp.hyphen > 0.0, prev: Some(from) }); active.push(nodes.len() - 1); } - if active.is_empty() { + if active.is_empty() || active.len() > MAX_ACTIVE { return None; } } @@ -120,10 +200,14 @@ pub(crate) fn compose( let mut out = vec![]; let mut cur = Some(end); while let Some(i) = cur { - if nodes[i].prev.is_some() { - out.push((nodes[i].pos, nodes[i].hyphenated)); + let nd = nodes.get(i)?; + if nd.prev.is_some() { + out.push((nd.pos, nd.hyphenated)); + } + cur = nd.prev; + if out.len() > n { + return None; } - cur = nodes[i].prev; } out.reverse(); Some(out) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index cbd3e49b..752d23f8 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -9,7 +9,7 @@ use vectorcraft_doc::{ }; use vectorcraft_geom::{ArcPath, PathData}; -use crate::composer::{Breakpoint, compose}; +use crate::composer::{Breakpoint, Params, compose}; use crate::fontdb::FontDb; use crate::hyphen::hyphen_points; use crate::shape::{Punct, SGlyph, Tcy, cap_x_heights, hyphen_glyph, is_cjk, no_line_end, no_line_start, punct, shape_range, style_metrics}; @@ -914,14 +914,18 @@ fn candidates(text: &str, g: &[SGlyph], hyphenate: bool) -> Vec { v } -/// Every-line composition of paragraph glyphs `sg` if applicable (justified area text with uniform -/// line metrics); `None` falls back to the greedy single-line composer. -fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>) -> Option> { - let justified = !matches!(para.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right); +/// Paragraphs longer than this (glyphs) are always broken line by line. +const MAX_COMPOSE_GLYPHS: usize = 200_000; + +/// Every-line composition of paragraph glyphs `sg` if applicable (area text with uniform line +/// metrics, justified or ragged); `None` falls back to the greedy single-line composer. +fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>, rtl: bool) -> Option> { + let ragged = matches!(para.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right); + let composer = cx.opts.composer.unwrap_or(para.composer); // A paragraph whose commas or full stops may hang is composed line by line (as the Japanese // single-line composer does). let may_hang = para.burasagari != Burasagari::None && sg.iter().any(hangs); - if cx.opts.composer != Composer::EveryLine || !justified || pen.regions.is_none() || sg.len() < 2 || may_hang { + if composer != Composer::EveryLine || pen.regions.is_none() || sg.len() < 2 || sg.len() > MAX_COMPOSE_GLYPHS || may_hang { return None; } let m = Metrics::of(&sg[0]); @@ -948,9 +952,21 @@ fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>) -> } let last = *widths.last()?; let width = |k: usize| widths.get(k).copied().unwrap_or(last); + // Lines from `uniform_from` on are interchangeable (same width). + let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1); let cands = candidates(cx.text, sg, para.hyphenate); let justify_last = para.justify == Justify::JustifyAll; - compose(sg, &width, &cands, justify_last, 1.0).or_else(|| compose(sg, &width, &cands, justify_last, 4.0)) + let params = |tolerance| Params { justify_last, ragged, tolerance, uniform_from }; + // Ragged: first look for breaks that leave at most one rag zone (a sixth of the width) on + // each line, then accept any lines that fit. + let (strict, loose) = if ragged { (1.0, f64::INFINITY) } else { (1.0, 4.0) }; + // The same rule as the line loop below: an opening bracket starting a wrapped line gives up + // the space before it. + let start_credit = |i: usize| { + let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf; + sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0) + }; + compose(sg, &width, &start_credit, &cands, ¶ms(strict)).or_else(|| compose(sg, &width, &start_credit, &cands, ¶ms(loose))) } fn flow(cx: &mut Ctx<'_>, paras: &[Range], para: &ParaStyle, regions: Option<&[Region]>) { @@ -985,7 +1001,7 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range], para: &ParaStyle, regions: Opt pen.pending += para.space_before; } let n = sg.len(); - let composed = compose_para(cx, &sg, para, &pen); + let composed = compose_para(cx, &sg, para, &pen, rtl); let mut li_para = 0; let mut i = 0; loop { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7833601a..bb8a5457 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -31,15 +31,8 @@ pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::FirstBaseline; -/// Paragraph composer (Paragraph panel menu). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum Composer { - /// Break each line as soon as it is full. - SingleLine, - /// Knuth–Plass total fit over the paragraph (justified area text only). - #[default] - EveryLine, -} +/// Paragraph composer; stored per text object in [`vectorcraft_doc::ParaStyle::composer`]. +pub use vectorcraft_doc::Composer; /// Layout parameters that the document model doesn't store per object (Area Type Options, /// composer, OpenType features). [`layout`] takes rows/columns/inset/first baseline from the object. @@ -55,7 +48,8 @@ pub struct LayoutOptions { pub first_baseline: FirstBaseline, /// Minimum first-baseline offset in points. pub first_baseline_min: f64, - pub composer: Composer, + /// Overrides the object's paragraph composer (`None` = use `ParaStyle::composer`). + pub composer: Option, pub features: OtFeatures, } @@ -68,7 +62,7 @@ impl Default for LayoutOptions { inset: 0.0, first_baseline: FirstBaseline::Ascent, first_baseline_min: 0.0, - composer: Composer::EveryLine, + composer: None, features: OtFeatures::default(), } } diff --git a/crates/text/src/tests_typo.rs b/crates/text/src/tests_typo.rs index dcd91800..55dcc9e3 100644 --- a/crates/text/src/tests_typo.rs +++ b/crates/text/src/tests_typo.rs @@ -227,7 +227,7 @@ fn composer_lines_never_exceed_frame() { for (hy, composer) in [(false, Composer::EveryLine), (true, Composer::EveryLine), (false, Composer::SingleLine), (true, Composer::SingleLine)] { let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, 180.0, 2000.0), Justify::JustifyLeft); t.para.hyphenate = hy; - let l = layout_with(db(), &t, &LayoutOptions { composer, ..Default::default() }); + let l = layout_with(db(), &t, &LayoutOptions { composer: Some(composer), ..Default::default() }); assert!(l.lines.len() > 10); for (i, li) in l.lines.iter().enumerate() { assert!(li.x1 - li.x0 <= 180.0 + 1e-6, "{composer:?} hy={hy} line {i} too wide: {li:?}"); @@ -246,7 +246,7 @@ fn composer_lines_never_exceed_frame() { fn every_line_composer_is_more_even() { let t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, 190.0, 2000.0), Justify::JustifyLeft); let spread = |c: Composer| { - let l = layout_with(db(), &t, &LayoutOptions { composer: c, ..Default::default() }); + let l = layout_with(db(), &t, &LayoutOptions { composer: Some(c), ..Default::default() }); // Worst word-space stretch (space glyph advance) over all justified lines. let mut worst: f64 = 0.0; for li in &l.lines[..l.lines.len() - 1] { @@ -269,7 +269,7 @@ fn burasagari_keeps_the_every_line_composer_for_latin_text() { // A measure where the two composers break the copy differently. let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, 300.0, 4000.0), Justify::JustifyLeft); let ends = |t: &TextObject, c: Composer| { - let l = layout_with(db(), t, &LayoutOptions { composer: c, ..Default::default() }); + let l = layout_with(db(), t, &LayoutOptions { composer: Some(c), ..Default::default() }); l.lines.iter().map(|li| li.glyph_end).collect::>() }; let every_line = ends(&t, Composer::EveryLine); @@ -278,6 +278,102 @@ fn burasagari_keeps_the_every_line_composer_for_latin_text() { assert_eq!(ends(&t, Composer::EveryLine), every_line); } +/// Width of `s` set on one line. +fn natural_width(s: &str, size: f64) -> f64 { + let l = layout(db(), &TextObject::point(Point::ZERO, s, style(size))); + l.lines[0].x1 - l.lines[0].x0 +} + +/// The text of each line. +fn line_texts(t: &TextObject, l: &TextLayout) -> Vec { + let text = t.plain_text(); + l.lines.iter().map(|li| text[li.start..li.end].trim_end().to_string()).collect() +} + +/// Ragged text: Every-line breaks before a word that would fit, to avoid leaving a lone short +/// word on the last line (single-line keeps filling the first line). Auto alignment is ragged +/// too, in either paragraph direction: set right to left, the lines break the same and stay +/// flush right. +#[test] +fn every_line_composer_balances_ragged_lines() { + use vectorcraft_doc::ParaDirection; + const S: &str = "Destroy all creatures with toughness X or less."; + let w = natural_width("Destroy all creatures with toughness X or", 12.0) + 2.0; + assert!(w < natural_width(S, 12.0), "the sentence needs two lines"); + let cases = [ + (Justify::Left, None), + (Justify::Center, None), + (Justify::Right, None), + (Justify::Auto, None), + (Justify::Auto, Some(ParaDirection::RightToLeft)), + (Justify::Left, Some(ParaDirection::RightToLeft)), + ]; + for (justify, direction) in cases { + let mut t = area(S, style(12.0), Rect::new(0.0, 0.0, w, 400.0), justify); + t.para.direction = direction; + t.para.composer = Composer::SingleLine; + let greedy = line_texts(&t, &layout(db(), &t)); + assert_eq!(greedy, ["Destroy all creatures with toughness X or", "less."], "{justify:?} {direction:?}"); + t.para.composer = Composer::EveryLine; + let every = line_texts(&t, &layout(db(), &t)); + assert_eq!(every, ["Destroy all creatures with toughness X", "or less."], "{justify:?} {direction:?}"); + // Burasagari (new type's Standard) leaves Latin text to the every-line composer. + t.para.burasagari = vectorcraft_doc::Burasagari::Standard; + assert_eq!(line_texts(&t, &layout(db(), &t)), every, "{justify:?} {direction:?} with burasagari"); + if (justify, direction) == (Justify::Auto, Some(ParaDirection::RightToLeft)) { + let l = layout(db(), &t); + assert!(l.lines.iter().all(|li| li.rtl && (li.x1 - w).abs() < 1e-6), "right to left Auto is flush right: {:?}", l.lines); + } + // The options override wins over the object's setting. + let forced = layout_with(db(), &t, &LayoutOptions { composer: Some(Composer::SingleLine), ..Default::default() }); + assert_eq!(line_texts(&t, &forced), greedy); + } +} + +/// Every-line evens the rag of a long ragged paragraph: the spread of the line ends is no worse +/// than greedy breaking, every line fits, and nothing is lost. +#[test] +fn every_line_composer_evens_the_rag() { + for (width, hy) in [(150.0, false), (190.0, false), (240.0, true), (310.0, false)] { + let mut t = area(©.repeat(2), style(12.0), Rect::new(0.0, 0.0, width, 4000.0), Justify::Left); + t.para.hyphenate = hy; + let rag = |c: Composer| { + let mut t = t.clone(); + t.para.composer = c; + let l = layout(db(), &t); + assert!(!l.overflow); + for li in &l.lines { + assert!(li.x1 - li.x0 <= width + 1e-6, "{c:?} {width}: line too wide {li:?}"); + } + let clusters: std::collections::BTreeSet<(usize, usize)> = l.glyphs.iter().filter(|g| g.len > 0).map(|g| (g.byte, g.len)).collect(); + assert_eq!(clusters.iter().map(|c| c.1).sum::(), COPY.len() * 2, "every character placed"); + // Leftover space of all lines but the last: its sum of squares (how ragged) and the + // sum of squared differences between neighbours (how jagged). + let slack: Vec = l.lines[..l.lines.len() - 1].iter().map(|li| width - (li.x1 - li.x0)).collect(); + let jag: f64 = slack.windows(2).map(|p| (p[0] - p[1]).powi(2)).sum(); + (slack.iter().map(|s| s * s).sum::(), jag, l.lines.len()) + }; + let ((kp, kp_jag, kp_lines), (greedy, greedy_jag, greedy_lines)) = (rag(Composer::EveryLine), rag(Composer::SingleLine)); + assert!(kp <= greedy + 1e-6, "{width}: every-line rag {kp} vs greedy {greedy}"); + assert!(kp_jag <= greedy_jag + 1e-6, "{width}: every-line jag {kp_jag} vs greedy {greedy_jag}"); + assert!(kp_lines <= greedy_lines + 1, "{width}: {kp_lines} lines vs {greedy_lines}"); + } +} + +/// Single-line breaking is the greedy breaker: each line takes as many words as fit. +#[test] +fn single_line_composer_is_greedy() { + let width = 190.0; + let mut t = area(COPY, style(12.0), Rect::new(0.0, 0.0, width, 2000.0), Justify::Left); + t.para.composer = Composer::SingleLine; + let l = layout(db(), &t); + let lines = line_texts(&t, &l); + for pair in lines.windows(2) { + let next_word = pair[1].split(' ').next().unwrap(); + assert!(natural_width(&format!("{} {next_word}", pair[0]), 12.0) > width - 1e-6, "{pair:?}"); + } +} + #[test] fn hyphenation_rules() { assert_eq!(hyphen::hyphenate_word("typography"), "typo-gra-phy"); @@ -404,17 +500,22 @@ fn uncovered_characters_do_not_break_layout() { #[test] fn layout_10k_area_text_is_fast() { let text: String = COPY.chars().cycle().take(10_000).collect(); - let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), Justify::JustifyLeft); - t.para.hyphenate = true; - let _ = layout(db(), &t); - let n = 5; - let start = std::time::Instant::now(); - for _ in 0..n { - let l = layout(db(), &t); - assert!(!l.overflow); + for (justify, composer) in + [(Justify::JustifyLeft, Composer::EveryLine), (Justify::Left, Composer::EveryLine), (Justify::Left, Composer::SingleLine)] + { + let mut t = area(&text, style(10.0), Rect::new(0.0, 0.0, 400.0, 20_000.0), justify); + t.para.hyphenate = true; + t.para.composer = composer; + let _ = layout(db(), &t); + let n = 5; + let start = std::time::Instant::now(); + for _ in 0..n { + let l = layout(db(), &t); + assert!(!l.overflow); + } + let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; + eprintln!("layout of 10k chars ({justify:?}, {composer:?}, hyphenated): {per:.3} ms"); + let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 }; + assert!(per < budget, "{justify:?} {composer:?}: {per} ms"); } - let per = start.elapsed().as_secs_f64() * 1000.0 / n as f64; - eprintln!("layout of 10k chars (justified, hyphenated): {per:.3} ms"); - let budget = if cfg!(debug_assertions) { 400.0 } else { 10.0 }; - assert!(per < budget, "{per} ms"); } diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 25ea8dbb..6788de17 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -1,9 +1,10 @@ //! Paragraph panel: seven alignment buttons, Paragraph Direction (with the Indic options), indents, -//! space before/after, Hyphenate and Mojikumi Set (with the East Asian options). +//! space before/after, Hyphenate and Mojikumi Set (with the East Asian options); the panel menu +//! picks the Single-line or Every-line Composer. use egui::{Ui, vec2}; use serde_json::{Value, json}; -use vectorcraft_doc::{Justify, NodeKind, ParaDirection, ParaStyle}; +use vectorcraft_doc::{Composer, Justify, NodeKind, ParaDirection, ParaStyle}; use super::character::text_style; use super::{pstate, set_pstate}; @@ -181,14 +182,20 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { }); } ui.separator(); - menu_item(ui, tl!("Single-line Composer"), false, false); - menu_item(ui, tl!("Every-line Composer"), false, true); + let composer = style.as_ref().map(|(_, p)| p.composer); + for (c, label, id) in + [(Composer::SingleLine, tl!("Single-line Composer"), "singleLine"), (Composer::EveryLine, tl!("Every-line Composer"), "everyLine")] + { + if menu_item(ui, label, has, composer == Some(c)) { + format(app, json!({ "composer": id })); + } + } ui.separator(); if menu_item(ui, tl!("Reset Panel"), has, false) { para_cmd(app, "text.setStyle", json!({"justify": "auto"})); format( app, - json!({"leftIndent": 0, "rightIndent": 0, "firstLineIndent": 0, "spaceBefore": 0, "spaceAfter": 0, "hyphenate": false, "direction": "auto", "leadingModel": "romanBaseline", "burasagari": "standard"}), + json!({"leftIndent": 0, "rightIndent": 0, "firstLineIndent": 0, "spaceBefore": 0, "spaceAfter": 0, "hyphenate": false, "direction": "auto", "leadingModel": "romanBaseline", "burasagari": "standard", "composer": "everyLine"}), ); } } diff --git a/docs/mcp.md b/docs/mcp.md index c029656d..5e57c32a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2549,6 +2549,20 @@ canvas as they export. `object.blend.expand` and `object.blend.release` keep the opacity mask and appearance (Release on a group around the keys and spine when the blend has any), and `object.expand` with `object: true` expands the blends in the selection. +## Paragraph composer + +`text.setFormat {ids?, composer: "singleLine"|"everyLine"}` sets how a text object's lines are broken (the Paragraph +panel menu's Single-line and Every-line Composer; stored in the paragraph attributes as `para.composer`, saved only +when it is Single-line). Every-line, the default, picks the breaks of the whole paragraph together in area type: +justified text gets even word spacing, ragged text (left, centre or right aligned) an even rag, so it may move a word +that fits to the next line to avoid a lone short word on the last line or a full line next to a short one. +Single-line fills each line as far as it goes. Point type and type on a path have no line width, so both composers +give the same result there; paragraphs that mix type sizes fall back to Single-line. + +```json +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"ids":[7],"composer":"singleLine"}}} +``` + ## Editing envelopes `object.envelope.editContents {editing}` switches between editing the envelope and its contents (the menu item reads