diff --git a/Cargo.lock b/Cargo.lock index cec8e7aef7..cb0c72cc0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6775,6 +6775,7 @@ dependencies = [ "craft-stream-codecs", "craft-xml", "crc32fast", + "encoding_rs", "flate2", "hayro-ccitt", "heic-rs", diff --git a/ROADMAP.md b/ROADMAP.md index 2fb84ab127..b2ebdb0545 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -138,6 +138,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). diff --git a/apps/vectorcraft-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index eddd04f1b7..1be921baf3 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin>> { }) } -async fn sleep(ms: i32) { +pub(crate) async fn sleep(ms: i32) { let promise = js_sys::Promise::new(&mut |resolve, _| { if let Some(window) = web_sys::window() { let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs new file mode 100644 index 0000000000..7583248701 --- /dev/null +++ b/apps/vectorcraft-web/src/demand.rs @@ -0,0 +1,139 @@ +//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most +//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after +//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures. + +/// The wait after a face's first failed fetch before it is fetched again (ms). +const RETRY_MS: i32 = 30_000; +/// Failed fetches of a face after which it is not fetched again this session. +pub(crate) const MAX_TRIES: u32 = 5; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum State { + Idle, + /// Being fetched, after `tries` failed fetches. + Loading { + tries: u32, + }, + Loaded, + /// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or + /// at once when the clock reads earlier than `failed_at`. + Failed { + tries: u32, + failed_at: f64, + retry_at: f64, + }, +} + +/// The fetch state of each face of a web font list, by index. +#[derive(Debug, Default)] +pub(crate) struct Demand { + states: Vec, +} + +impl Demand { + /// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not + /// loaded, not being fetched, and not waiting to be fetched again. They are marked as being + /// fetched. + pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec { + let mut out = Vec::new(); + for &i in wanted { + if self.states.len() <= i { + self.states.resize(i + 1, State::Idle); + } + let Some(state) = self.states.get_mut(i) else { continue }; + let tries = match *state { + State::Idle => Some(0), + State::Loading { .. } | State::Loaded => None, + State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries), + }; + if let Some(tries) = tries { + *state = State::Loading { tries }; + out.push(i); + } + } + out + } + + /// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`. + /// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it + /// loaded or has failed [`MAX_TRIES`] times. + pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option { + let state = self.states.get_mut(i)?; + let State::Loading { tries } = *state else { return None }; + if ok { + *state = State::Loaded; + return None; + } + let tries = tries + 1; + let wait = RETRY_MS << (tries - 1).min(4); + *state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) }; + (tries < MAX_TRIES).then_some(wait) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_face_is_fetched_once_and_kept() { + let mut d = Demand::default(); + assert_eq!(d.start(&[2], 0.0), [2]); + assert!(d.start(&[2], 1.0).is_empty(), "already being fetched"); + assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry"); + assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again"); + assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own"); + assert_eq!(d.finished(7, false, 4.0), None, "a face never started"); + } + + #[test] + fn a_failed_face_waits_longer_after_each_failure_and_then_stops() { + let mut d = Demand::default(); + let mut now = 0.0; + // The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first. + for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) { + assert_eq!(d.start(&[0], now), [0], "at {now}"); + assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}"); + assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}"); + now += f64::from(wait); + } + // The fifth fetch, and after it fails, none. + assert_eq!(d.start(&[0], now), [0]); + assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures"); + assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures"); + // A later success after failures keeps the face. + let mut d = Demand::default(); + d.start(&[1], 0.0); + assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS)); + assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]); + assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); + assert!(d.start(&[1], 1e12).is_empty()); + } + + /// While a face is fetched again after a failure, neither the interface asking for its script + /// again nor the retry timer starts a second fetch of it. + #[test] + fn a_face_being_fetched_again_is_not_fetched_twice_at_once() { + let mut d = Demand::default(); + d.start(&[0], 0.0); + assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS)); + let retry = f64::from(RETRY_MS); + assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice"); + assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again"); + assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer"); + assert_eq!(d.finished(0, true, retry + 2_000.0), None); + assert!(d.start(&[0], 1e12).is_empty(), "loaded"); + } + + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the + /// retry back: the timer that asks for it has waited already. + #[test] + fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() { + let mut d = Demand::default(); + let failed_at = 1e12; + d.start(&[0], failed_at); + assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS)); + assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting"); + assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour"); + } +} diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index 2677c11edf..873474f6c3 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -1,17 +1,22 @@ //! Craft-fonts faces served beside the wasm (`fonts//…`, copied by //! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup` -//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks -//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped: -//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing. +//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and +//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the +//! interface's own text needs its script. The browser checks each file against its SHA-256 +//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With +//! `WEB_FONTS` empty (built without craft-fonts) these do nothing. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; +use vectorcraft_text::craft_fonts::demand_fonts; use vectorcraft_text::{FontDb, WEB_FONTS, WebFont}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use wasm_bindgen_futures::JsFuture; +use crate::demand::Demand; + /// Per startup face: the page shows its loading text meanwhile. const STARTUP_TIMEOUT_MS: i32 = 20_000; /// Per background face. @@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4; thread_local! { /// The background fetch runs once per page, though a graphics restart creates the app again. static BACKGROUND_STARTED: Cell = const { Cell::new(false) }; + /// The `demand` faces' fetches. + static DEMAND: RefCell = RefCell::new(Demand::default()); + /// The running app's context, asked for a frame when a `demand` face arrives (none before the + /// app starts: its first frame looks through the faces loaded by then). + static REPAINT: RefCell> = const { RefCell::new(None) }; +} + +/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or +/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those +/// characters with it from then on. Set as the interface's missing-glyph handler +/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name +/// before the app starts. +pub fn want_chars(chars: &[char]) { + let wanted = demand_fonts(WEB_FONTS, chars.iter().copied()); + if !wanted.is_empty() { + fetch_demand(&wanted); + } +} + +/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. +/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. +fn fetch_demand(wanted: &[usize]) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) { + let Some(f) = WEB_FONTS.get(i) else { continue }; + wasm_bindgen_futures::spawn_local(async move { + let ok = load(f, BACKGROUND_TIMEOUT_MS).await; + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms())); + if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { + ctx.request_repaint(); + } + if let Some(wait) = retry { + // A second longer, so a clock the browser coarsens still reads the wait as over. + crate::api::sleep(wait.saturating_add(1_000)).await; + fetch_demand(&[i]); + } + }); + } } /// Fetch and register the `startup` faces (one after the other). Returns how many loaded. pub async fn load_startup_fonts() -> usize { let mut loaded = 0; - for f in WEB_FONTS.iter().filter(|f| f.startup) { + for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) { if load(f, STARTUP_TIMEOUT_MS).await { loaded += 1; } @@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize { } /// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for -/// a frame after each so the font menus and the canvas pick it up. Only the first call does -/// anything. +/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches +/// anything; each call makes `ctx` the context a `demand` face asks for a frame. pub fn spawn_background_fonts(ctx: egui::Context) { + REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone())); if BACKGROUND_STARTED.with(|s| s.replace(true)) { return; } - let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect()); + let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect()); let next = Rc::new(Cell::new(0usize)); for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) { let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone()); diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 457d8d4640..b71b51b566 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -21,6 +21,8 @@ #[cfg(target_arch = "wasm32")] mod api; +#[cfg(any(target_arch = "wasm32", test))] +mod demand; #[cfg(target_arch = "wasm32")] mod fonts; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 2de7f3b481..6d9e0cadd5 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -81,6 +81,11 @@ pub fn start() { return; }; detect_language(); + // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the + // startup fonts, without holding up the start. Text in those scripts painted later (a saved + // interface language, another one chosen, a layer or file name) has its face fetched then. + vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); + crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. let locks = WebLocks::start(RECOVERY_PREFIX).await; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9f6ce7b710..a8209b9b42 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -59,6 +59,9 @@ chrono = { workspace = true } craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" +# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in +# Cargo.lock (vectorcraft-eps), so this adds no new crate. +encoding_rs = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d41b1f7161..d2e551e867 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -821,6 +821,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. +pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 7437abc0b5..03fb17f436 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,6 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub use packaging::{fold_source, print_hidden}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 6099386b98..9de16ca200 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -6,8 +6,10 @@ //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. mod check; +mod fold; mod roles; +pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; @@ -15,6 +17,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index da8f7f25dd..9507a17daa 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; -use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; +use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks}; use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; @@ -14,7 +14,7 @@ use crate::{Result, Session}; const CHECK: &str = "addon.packaging.check"; /// How far apart the ends of two lines may be and still be joined, in points. -const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); +pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); pub fn specs() -> Vec { vec![cmd!( @@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind { } } -fn check(s: &mut Session, p: &Value) -> Result { - let select = switch_or(p, "select", false, CHECK)?; - let tolerance = match length_given(p, "tolerance", CHECK)? { - None => TOLERANCE.1, - Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, - Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), - }; +/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or +/// `document`), the lines, and the ids of those on a non-printing layer. +pub(super) struct Lines { + pub scope: &'static str, + pub lines: Vec, + pub non_printing: Vec, +} + +/// The tolerance `p` gives for `cmd`, or the default. +pub(super) fn tolerance(p: &Value, cmd: &str) -> Result { + match length_given(p, "tolerance", cmd)? { + None => Ok(TOLERANCE.1), + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t), + Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + } +} + +/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while +/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines +/// are left out in every scope, members of a selected group included. +pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, CHECK)?; + let roots = checked_ids_or_selection(s, p, cmd)?; let d = &s.doc()?.doc; - // Hidden lines are left out in every scope, members of a selected group included. let shown = |ids: Vec| ids.into_iter().filter(|id| d.is_visible(*id)).collect::>(); - let (scope, targets) = match (given, roots.is_empty()) { - (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), - (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), - (false, true) => ("document", shown_targets(d)), - }; + Ok(match (given, roots.is_empty()) { + (true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)), + (false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)), + (false, true) => document_lines(d), + }) +} + +/// Every shown fold line of `d`. +pub(super) fn document_lines(d: &Document) -> Lines { + lines_of(d, "document", shown_targets(d)) +} + +fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { let table = RoleTable::of(d); let mut lines = vec![]; let mut non_printing = vec![]; @@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result { segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); lines.push(FoldLine { path, kind: kind(role), key: id.0 }); } - let (found, mut issues) = blanks(&lines, tolerance); - if !non_printing.is_empty() { - issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + Lines { scope, lines, non_printing } +} + +/// The blanks `lines` make and their issues, the non-printing one last. +pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec, Vec) { + let (found, mut issues) = blanks(&lines.lines, tolerance); + if !lines.non_printing.is_empty() { + issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None }); } - let ok = !issues.iter().any(|i| i.code.is_error()); - let rows: Vec = issues + (found, issues) +} + +/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with. +pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec { + issues .iter() .map(|i| { let mut row = json!({ @@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result { } row }) - .collect(); + .collect() +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = tolerance(p, CHECK)?; + let lines = lines(s, p, CHECK)?; + let scope = lines.scope; + let (found, issues) = found(&lines, tolerance); + let d = &s.doc()?.doc; + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows = issue_rows(&issues, scope); if select { let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); ids.sort_unstable_by_key(|id| id.0); diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs new file mode 100644 index 0000000000..068b2375c9 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -0,0 +1,110 @@ +//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by +//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the +//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::{Blank, Issue, fold, pick}; + +use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or}; +use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance}; +use super::roles::{RoleTable, can_carry}; +use crate::{Result, Session}; + +const FOLD: &str = "addon.packaging.fold"; + +pub fn specs() -> Vec { + vec![cmd!( + query "addon.packaging.fold", + "Fold", + [], + None, + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + has_doc, + fold_command + )] +} + +/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the +/// whole document): what the Fold Preview window folds. +pub fn fold_source(d: &Document) -> (Vec, Vec) { + found(&document_lines(d), TOLERANCE.1) +} + +/// The objects the print on a folded blank leaves out: the layers that do not print and, unless +/// `fold_lines`, every object with a line role. +pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec { + fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => out.push(n.id), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)), + _ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id), + _ => {} + } + } + let table = RoleTable::of(d); + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out)); + out +} + +fn fold_command(s: &mut Session, p: &Value) -> Result { + let tolerance = tolerance(p, FOLD)?; + let amount = number_or(p, "amount", 1.0, FOLD)?; + if !(0.0..=1.0).contains(&amount) { + return Err(bad(FOLD, "`amount` must be from 0 to 1")); + } + let base = match p.get("base") { + None | Some(Value::Null) => None, + Some(v) => { + let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?; + Some(vectorcraft_geom::Point::new(x, y)) + } + }; + let lines = lines(s, p, FOLD)?; + let (blanks, issues) = found(&lines, tolerance); + let ok = !issues.iter().any(|i| i.code.is_error()); + let picked = pick(&blanks, base); + if base.is_some() && picked.is_none() { + return Err(bad(FOLD, "`base` is in no panel")); + } + let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?))); + let Some((index, blank, f)) = folded else { + return Ok(json!({ + "ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [], + "issues": issue_rows(&issues, lines.scope), + })); + }; + let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]); + let panels: Vec = blank + .panels + .iter() + .zip(&f.panels) + .map(|(panel, placed)| { + json!({ + "outline": panel.outline.to_bezpath().to_svg(), + "frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t}, + "parent": placed.parent, + "depth": placed.depth, + }) + }) + .collect(); + let hinges: Vec = f + .hinges + .iter() + .map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap})) + .collect(); + Ok(json!({ + "ok": ok, + "blank": index, + "blanks": blanks.len(), + "base": f.base, + "panels": panels, + "hinges": hinges, + "collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::>(), + "issues": issue_rows(&issues, lines.scope), + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs new file mode 100644 index 0000000000..4c423021f5 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -0,0 +1,157 @@ +//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn fold(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.fold", &p).unwrap() +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only). +fn middle(d: &str) -> [f64; 2] { + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + let ((x0, x1), (y0, y1)) = (span(0), span(1)); + [(x0 + x1) / 2.0, (y0 + y1) / 2.0] +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn a_tray_folds_its_walls_up_round_the_base() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}"); + let panels = r["panels"].as_array().unwrap(); + assert_eq!(panels.len(), 5); + let base = r["base"].as_u64().unwrap() as usize; + let frame = &panels[base]["frame"]; + assert!( + near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]), + "{frame}" + ); + assert!(panels[base]["parent"].is_null()); + assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); + for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { + assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); + // Each wall stands square to the base, below it (away from the print), its print facing out: + // away from the base's middle (190, 190), toward the side the wall lies on. + let [cx, cy] = middle(p["outline"].as_str().unwrap()); + let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"])); + let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy); + let (dx, dy) = (cx - 190.0, 190.0 - cy); + let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] }; + assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}"); + assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}"); + } + let hinges = r["hinges"].as_array().unwrap(); + assert_eq!(hinges.len(), 4); + assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}"); + assert_eq!(r["collisions"], json!([])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step"); + + // Flat, every frame is the flat blank's own. + let r = fold(&mut s, json!({ "amount": 0 })); + for p in r["panels"].as_array().unwrap() { + assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}"); + } +} + +#[test] +fn the_base_is_the_panel_under_a_point() { + let mut s = session(); + tray(&mut s); + // The left wall: x 100 to 140, y 140 to 240. + let r = fold(&mut s, json!({ "base": [120, 190] })); + let base = r["base"].as_u64().unwrap() as usize; + let panels = r["panels"].as_array().unwrap(); + assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0])); + // The tray's base is now a child of the wall, and the other walls its children. + let depths: Vec = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect(); + let mut sorted = depths.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}"); + let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string(); + assert!(e.contains("`base` is in no panel"), "{e}"); +} + +#[test] +fn bad_values_are_refused() { + let mut s = session(); + tray(&mut s); + for (p, want) in [ + (json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"), + (json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"), + (json!({ "amount": "1" }), "`amount` must be a number"), + (json!({ "base": [1] }), "`base` must be a point"), + (json!({ "base": "middle" }), "`base` must be a point"), + (json!({ "tolerance": 50 }), "`tolerance` must be from"), + ] { + let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn without_a_blank_nothing_is_folded_and_the_issues_say_why() { + let mut s = session(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}"); + assert_eq!(r["panels"], json!([])); + assert_eq!(r["issues"][0]["code"], "noCut"); +} + +#[test] +fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let art = path(&mut s, "M150 150 L200 150 L200 200 Z"); + let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let hidden: Vec = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect(); + for id in creases.iter().chain([&outline, ¬es]) { + assert!(hidden.contains(id), "{id} in {hidden:?}"); + } + assert!(!hidden.contains(&art)); + let shown: Vec = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect(); + assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out"); + let (blanks, issues) = cmd::fold_source(d); + assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5)); + assert!(issues.is_empty(), "{issues:?}"); +} diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 486a5633a7..096f90bf36 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index 7d8afc92d4..78261a8804 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -3,8 +3,8 @@ use serde_json::Value; -use super::super::utf16_order_without_mark; -use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param}; +use super::super::{text_param, utf16_order_without_mark}; +use super::{Point, Rect, Result, bad, fileio, shapes, switch_or}; /// Text files as `file.place` reports them (not a format `document.open` reads). pub(super) const FORMAT: fileio::Format = fileio::Format { @@ -22,13 +22,68 @@ pub(super) const FORMAT: fileio::Format = fileio::Format { /// document may give. pub(super) const MAX_TEXT: usize = 4 << 20; +/// A character set of Text Import Options (`text.characterSet`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum CharacterSet { + /// UTF-8, or UTF-16 with or without a byte-order mark ([`decode`]). + #[default] + Unicode, + /// The platform's 8-bit character set: Windows-1252, or Mac Roman on a Mac. + Ansi, + ShiftJis, + Gb2312, + ChineseBig5, + Cyrillic, + Gb18030, + Greek, + Turkish, + Baltic, + CentralEuropean, +} + +/// Each character set by its `text.characterSet` value. +const CHARACTER_SETS: [(&str, CharacterSet); 11] = [ + ("unicode", CharacterSet::Unicode), + ("ansi", CharacterSet::Ansi), + ("shiftJis", CharacterSet::ShiftJis), + ("gb2312", CharacterSet::Gb2312), + ("chineseBig5", CharacterSet::ChineseBig5), + ("cyrillic", CharacterSet::Cyrillic), + ("gb18030", CharacterSet::Gb18030), + ("greek", CharacterSet::Greek), + ("turkish", CharacterSet::Turkish), + ("baltic", CharacterSet::Baltic), + ("centralEuropean", CharacterSet::CentralEuropean), +]; + +impl CharacterSet { + /// The Encoding Standard decoder of a set other than Unicode and ANSI, for a file from a Mac + /// when `mac`: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic on a Mac), and + /// Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both + /// platforms. + fn encoding(self, mac: bool) -> Option<&'static encoding_rs::Encoding> { + Some(match self { + Self::Unicode | Self::Ansi => return None, + Self::ShiftJis => encoding_rs::SHIFT_JIS, + Self::Gb2312 => encoding_rs::GBK, + Self::ChineseBig5 => encoding_rs::BIG5, + Self::Cyrillic if mac => encoding_rs::X_MAC_CYRILLIC, + Self::Cyrillic => encoding_rs::WINDOWS_1251, + Self::Gb18030 => encoding_rs::GB18030, + Self::Greek => encoding_rs::WINDOWS_1253, + Self::Turkish => encoding_rs::WINDOWS_1254, + Self::Baltic => encoding_rs::WINDOWS_1257, + Self::CentralEuropean => encoding_rs::WINDOWS_1250, + }) + } +} + /// Text Import Options (`file.place`'s `text` param). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct TextOptions { - /// Decode as the platform's 8-bit character set (Windows-1252 or Mac Roman) instead of - /// Unicode. - ansi: bool, - /// The file comes from a Mac (its 8-bit character set is Mac Roman). + /// The character set the file's bytes are decoded as. + character_set: CharacterSet, + /// The file comes from a Mac (its ANSI set is Mac Roman, its Cyrillic set x-mac-cyrillic). mac: bool, /// Join the lines of each block of text (blank lines end paragraphs). remove_line_returns: bool, @@ -45,11 +100,13 @@ impl TextOptions { if !t.is_object() { return Err(bad(cmd, "text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?}")); } - let choice = |key: &str, values: [&str; 2]| match str_param(t, key) { - None => Ok(false), - Some(v) if v == values[0] => Ok(false), - Some(v) if v == values[1] => Ok(true), - Some(v) => Err(bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", values[0], values[1]))), + // The index of `text[key]` in `values`; 0 when it is omitted or null. + let choice = |key: &str, values: &[&str]| -> Result { + let Some(v) = text_param(t, key, cmd)? else { return Ok(0) }; + values.iter().position(|x| *x == v).ok_or_else(|| { + let (last, rest) = values.split_last().map_or(("", &[][..]), |(last, rest)| (*last, rest)); + bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", rest.join("\", \""), last)) + }) }; let spaces_to_tab = match t.get("replaceSpaces") { None | Some(Value::Null) => None, @@ -58,11 +115,12 @@ impl TextOptions { as usize, ), }; + let set = choice("characterSet", &CHARACTER_SETS.map(|(name, _)| name))?; Ok(Self { - ansi: choice("characterSet", ["unicode", "ansi"])?, - mac: choice("platform", ["windows", "mac"])?, - remove_line_returns: bool_or(t, "removeLineReturns", false), - remove_paragraph_returns: bool_or(t, "removeParagraphReturns", false), + character_set: CHARACTER_SETS.get(set).map_or(CharacterSet::Unicode, |(_, s)| *s), + mac: choice("platform", &["windows", "mac"])? == 1, + remove_line_returns: switch_or(t, "removeLineReturns", false, cmd)?, + remove_paragraph_returns: switch_or(t, "removeParagraphReturns", false, cmd)?, spaces_to_tab, }) } @@ -80,10 +138,15 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result /// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the /// file has an even length, reads as valid UTF-16 with no NUL character in the byte order /// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit -/// set), or the platform's 8-bit character set. +/// set), the platform's 8-bit character set, or another set's decoder +/// ([`CharacterSet::encoding`]), which reads a byte-order mark as ordinary bytes and a malformed +/// sequence as U+FFFD. fn decode(bytes: &[u8], o: TextOptions) -> String { + if let Some(encoding) = o.character_set.encoding(o.mac) { + return encoding.decode_without_bom_handling(bytes).0.into_owned(); + } let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() }; - if o.ansi { + if o.character_set == CharacterSet::Ansi { return eight_bit(bytes); } let utf16 = |rest: &[u8], le: bool| { @@ -278,22 +341,76 @@ mod tests { assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, 0xE9, 0], unicode), "hé", "UTF-16 LE"); assert_eq!(decode(&[0xFE, 0xFF, 0, b'h', 0x20, 0xAC], unicode), "h€", "UTF-16 BE"); assert_eq!(decode(&[b'c', b'a', b'f', 0xE9, 0x80], unicode), "café€", "not UTF-8: Windows-1252"); - let ansi = TextOptions { ansi: true, ..TextOptions::default() }; + let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() }; assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é"); - let mac = TextOptions { ansi: true, mac: true, ..TextOptions::default() }; + let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() }; assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€"); } + /// The other character sets decode by their Encoding Standard decoders: the platform matters + /// for Cyrillic alone, a byte-order mark is read as ordinary bytes, and a malformed sequence + /// reads as U+FFFD. + #[test] + fn decodes_the_other_character_sets() { + let cases: [(CharacterSet, &[u8], &str); 9] = [ + (CharacterSet::ShiftJis, &[0x93, 0xFA, 0x96, 0x7B], "日本"), + (CharacterSet::Gb2312, &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + (CharacterSet::ChineseBig5, &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + (CharacterSet::Cyrillic, &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + (CharacterSet::Gb18030, &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + (CharacterSet::Greek, &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + (CharacterSet::Turkish, &[0xDD, 0x73, 0x74], "İst"), + (CharacterSet::Baltic, &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + (CharacterSet::CentralEuropean, &[0xA3, 0xF3, 0x64, 0x9F], "Łódź"), + ]; + for (set, bytes, text) in cases { + let windows = TextOptions { character_set: set, ..TextOptions::default() }; + assert_eq!(decode(bytes, windows), text, "{set:?}"); + if set != CharacterSet::Cyrillic { + assert_eq!(decode(bytes, TextOptions { mac: true, ..windows }), text, "{set:?} from a Mac"); + } + } + let mac_cyrillic = TextOptions { character_set: CharacterSet::Cyrillic, mac: true, ..TextOptions::default() }; + assert_eq!(decode(&[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], mac_cyrillic), "Привет"); + let shift_jis = TextOptions { character_set: CharacterSet::ShiftJis, ..TextOptions::default() }; + assert_eq!(decode(&[0x82, 0x22], shift_jis), "\u{FFFD}\"", "a lead byte before ASCII"); + assert_eq!(decode(&[b'a', 0x82], shift_jis), "a\u{FFFD}", "a lead byte at the end"); + let central = TextOptions { character_set: CharacterSet::CentralEuropean, ..TextOptions::default() }; + assert_eq!(decode(&[0xEF, 0xBB, 0xBF, b'A'], central), "A", "a UTF-8 byte-order mark is read as windows-1250"); + assert_eq!(decode(&[0xFF, 0xFE, b'A', 0], shift_jis), "\u{FFFD}\u{FFFD}A\0", "a UTF-16 byte-order mark is read as Shift JIS"); + } + #[test] fn options_parse_and_reject_bad_values() { let p = serde_json::json!({"text": {"characterSet": "ansi", "platform": "mac", "removeLineReturns": true, "replaceSpaces": 4}}); let o = TextOptions::parse(&p, "file.place").unwrap(); - assert_eq!(o, TextOptions { ansi: true, mac: true, remove_line_returns: true, remove_paragraph_returns: false, spaces_to_tab: Some(4) }); + assert_eq!( + o, + TextOptions { + character_set: CharacterSet::Ansi, + mac: true, + remove_line_returns: true, + remove_paragraph_returns: false, + spaces_to_tab: Some(4) + } + ); + for (name, set) in CHARACTER_SETS { + let o = TextOptions::parse(&serde_json::json!({"text": {"characterSet": name}}), "file.place").unwrap(); + assert_eq!(o.character_set, set, "{name}"); + } assert_eq!(TextOptions::parse(&serde_json::json!({}), "file.place").unwrap(), TextOptions::default()); - for bad in - [serde_json::json!({"text": 3}), serde_json::json!({"text": {"platform": "amiga"}}), serde_json::json!({"text": {"replaceSpaces": 1}})] - { + for bad in [ + serde_json::json!({"text": 3}), + serde_json::json!({"text": {"platform": "amiga"}}), + serde_json::json!({"text": {"replaceSpaces": 1}}), + serde_json::json!({"text": {"characterSet": 3}}), + serde_json::json!({"text": {"platform": true}}), + serde_json::json!({"text": {"removeLineReturns": "yes"}}), + serde_json::json!({"text": {"removeParagraphReturns": 1}}), + ] { assert!(TextOptions::parse(&bad, "file.place").is_err(), "{bad}"); } + let null = serde_json::json!({"text": {"characterSet": null, "platform": null, "removeLineReturns": null}}); + assert_eq!(TextOptions::parse(&null, "file.place").unwrap(), TextOptions::default(), "null leaves the default"); } } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 9ea619e366..12cf0740f0 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -41,6 +41,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.removeBackground", "addon.image.removeColorMask", "addon.packaging.check", + "addon.packaging.fold", "addon.packaging.roles", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index cc89a8261b..980682f57e 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -135,6 +135,36 @@ fn text_files_report_and_queue_with_their_options() { assert!(close(frame, Rect::new(50.0, 60.0, 130.0, 100.0)), "{frame:?}"); } +/// Text Import Options' other character sets place their text as area type, and an unknown +/// character set is refused with the list of sets and places nothing. +#[test] +fn text_files_place_in_the_other_character_sets() { + let mut s = session(); + let cases: [(&str, &str, &[u8], &str); 11] = [ + ("shiftJis", "windows", &[0x93, 0xFA, 0x96, 0x7B], "日本"), + ("gb2312", "windows", &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + ("chineseBig5", "mac", &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + ("cyrillic", "windows", &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("cyrillic", "mac", &[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("gb18030", "windows", &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + ("greek", "windows", &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + ("turkish", "mac", &[0xDD, 0x73, 0x74], "İst"), + ("baltic", "windows", &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + ("centralEuropean", "windows", &[0xA3, 0xF3, 0x64, 0x9F, b'\r', b'\n', 0xA3], "Łódź\nŁ"), + ("shiftJis", "windows", &[0x82, 0x22], "\u{FFFD}\""), + ]; + for (set, platform, bytes, text) in cases { + let r = place_text(&mut s, bytes, json!({"text": {"characterSet": set, "platform": platform}})); + assert_eq!(placed(&s, &r).0, text, "{set} on {platform}"); + } + let undo = s.doc().unwrap().history.undo.len(); + let bad = json!({"name": "a.txt", "dataBase64": "YQ==", "text": {"characterSet": "latin9"}}); + let err = s.execute("file.place", &bad).unwrap_err().to_string(); + let list = r#""unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + assert!(err.contains(&format!("text.characterSet `latin9`: use {list}")), "{err}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing placed"); +} + /// An RTF file with a font table, a color table, a bold run, an italic run, a superscript and a /// centered, indented second paragraph. const LETTER_RTF: &str = concat!( diff --git a/crates/engine/tests/text_import_fuzz.rs b/crates/engine/tests/text_import_fuzz.rs index 1ea656a158..c8417b73fc 100644 --- a/crates/engine/tests/text_import_fuzz.rs +++ b/crates/engine/tests/text_import_fuzz.rs @@ -17,7 +17,9 @@ proptest! { fn any_bytes_place_as_text_without_panics( bytes in prop::collection::vec(prop_oneof![any::(), Just(b'\r'), Just(b'\n'), Just(b' ')], 0..400), bom in prop::sample::select(vec![&b""[..], b"\xEF\xBB\xBF", b"\xFF\xFE", b"\xFE\xFF"]), - ansi in any::(), + set in prop::sample::select(vec![ + "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean", + ]), mac in any::(), lines in any::(), paras in any::(), @@ -31,7 +33,7 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let text = json!({ - "characterSet": if ansi { "ansi" } else { "unicode" }, + "characterSet": set, "platform": if mac { "mac" } else { "windows" }, "removeLineReturns": lines, "removeParagraphReturns": paras, diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 298bc426e5..da9ed36a18 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1170,6 +1170,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", diff --git a/crates/text/build.rs b/crates/text/build.rs index 412c471c11..5402ddbe07 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -125,16 +125,19 @@ fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { missing.push(format!("{} {}", e.family, e.style)); continue; }; - let (Some(file), Some(sha)) = (row.get(2), row.get(6)) else { + let (Some(file), Some(scripts), Some(sha)) = (row.get(2), row.get(3), row.get(6)) else { return Err(format!("malformed manifest row for {} {}", e.family, e.style)); }; let integrity = web_fonts::sri(sha).ok_or_else(|| format!("bad sha256 for {} {}", e.family, e.style))?; + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, - " WebFont {{ family: {:?}, style: {:?}, startup: {}, url: {:?}, integrity: {:?} }},", + " WebFont {{ family: {:?}, style: {:?}, startup: {}, demand: {}, scripts: &[{}], url: {:?}, integrity: {:?} }},", e.family, e.style, e.startup, + e.demand, + scripts.join(", "), web_fonts::url(sha, file), integrity, ); diff --git a/crates/text/build/web_fonts.rs b/crates/text/build/web_fonts.rs index ccd387afab..ac58913afc 100644 --- a/crates/text/build/web_fonts.rs +++ b/crates/text/build/web_fonts.rs @@ -5,8 +5,11 @@ /// One line of `web-fonts.txt`: `when | family | style`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Listed<'a> { - /// `startup` (fetched before the app starts) rather than `background`. + /// `startup` (fetched before the app starts). pub startup: bool, + /// `demand` (fetched when the interface needs a character of one of the face's scripts). + /// Neither this nor `startup`: `background`. + pub demand: bool, pub family: &'a str, pub style: &'a str, } @@ -23,15 +26,16 @@ pub fn parse_list(text: &str) -> Result>, String> { let [when, family, style] = fields.as_slice() else { return Err(format!("web-fonts.txt line {}: expected `when | family | style`", i + 1)); }; - let startup = match *when { - "startup" => true, - "background" => false, - other => return Err(format!("web-fonts.txt line {}: `{other}` is neither startup nor background", i + 1)), + let (startup, demand) = match *when { + "startup" => (true, false), + "background" => (false, false), + "demand" => (false, true), + other => return Err(format!("web-fonts.txt line {}: `{other}` is not startup, background or demand", i + 1)), }; if family.is_empty() || style.is_empty() { return Err(format!("web-fonts.txt line {}: empty family or style", i + 1)); } - out.push(Listed { startup, family, style }); + out.push(Listed { startup, demand, family, style }); } Ok(out) } @@ -105,12 +109,14 @@ mod tests { #[test] fn list_parsing() { - let l = parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\n").unwrap(); + let l = + parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\ndemand | NanumGothic | Regular\n").unwrap(); assert_eq!( l, [ - Listed { startup: true, family: "Noto Sans Arabic", style: "Regular" }, - Listed { startup: false, family: "Amiri", style: "Bold Italic" } + Listed { startup: true, demand: false, family: "Noto Sans Arabic", style: "Regular" }, + Listed { startup: false, demand: false, family: "Amiri", style: "Bold Italic" }, + Listed { startup: false, demand: true, family: "NanumGothic", style: "Regular" } ] ); assert!(parse_list("soon | A | B").unwrap_err().contains("line 1")); diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index b15b77ec72..24eef3de40 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -19,8 +19,13 @@ pub struct CraftFont { pub struct WebFont { pub family: &'static str, pub style: &'static str, - /// Fetched before the app starts (a fallback the first frame needs), else in the background. + /// Fetched before the app starts (a fallback the first frame needs). pub startup: bool, + /// Fetched only when the interface needs a character of one of [`WebFont::scripts`] (see + /// [`demand_fonts`]). With neither this nor `startup`, fetched in the background. + pub demand: bool, + /// ISO 15924 scripts the face is for (its craft-fonts manifest row), e.g. `"Hang"`. + pub scripts: &'static [&'static str], /// Site-relative URL, `fonts//`. pub url: &'static str, /// Subresource Integrity value, `sha256-`; the browser rejects other bytes. @@ -106,10 +111,65 @@ pub fn japanese_ui_fonts(bold: bool) -> Vec<&'static CraftFont> { v } +/// The script of `c` that a `demand` web face is fetched for: `"Hang"` for Hangul (jamo, +/// compatibility jamo, syllables and the halfwidth forms) and `"Deva"` for Devanagari (with its +/// extended blocks and the Vedic extensions). `None` for every other character. +pub fn demand_script(c: char) -> Option<&'static str> { + match c as u32 { + 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC => Some("Hang"), + 0x0900..=0x097F | 0x1CD0..=0x1CFF | 0xA8E0..=0xA8FF | 0x11B00..=0x11B5F => Some("Deva"), + _ => None, + } +} + +/// The indexes in `fonts` of the `demand` faces for the scripts of `chars` (by +/// [`demand_script`]), each once, in `fonts` order. +pub fn demand_fonts(fonts: &[WebFont], chars: impl IntoIterator) -> Vec { + let mut scripts: Vec<&str> = Vec::new(); + for s in chars.into_iter().filter_map(demand_script) { + if !scripts.contains(&s) { + scripts.push(s); + } + } + fonts.iter().enumerate().filter(|(_, f)| f.demand && f.scripts.iter().any(|s| scripts.contains(s))).map(|(i, _)| i).collect() +} + #[cfg(test)] mod tests { use super::*; + fn web_font(family: &'static str, startup: bool, demand: bool, scripts: &'static [&'static str]) -> WebFont { + WebFont { family, style: "Regular", startup, demand, scripts, url: "", integrity: "" } + } + + #[test] + fn demand_scripts_of_hangul_and_devanagari() { + for c in ['한', '국', 'ㄱ', 'ᄀ', 'ᄀ'] { + assert_eq!(demand_script(c), Some("Hang"), "{c}"); + } + for c in ['ह', 'ि', '्', '़', '।', '\u{A8F2}'] { + assert_eq!(demand_script(c), Some("Deva"), "{c}"); + } + for c in ['A', 'é', 'ا', 'ก', 'ა', '日', 'ロ', '中'] { + assert_eq!(demand_script(c), None, "{c}"); + } + } + + #[test] + fn demand_fonts_follow_the_scripts_painted() { + let fonts = [ + web_font("Arabic", true, false, &["Arab"]), + web_font("Picked", false, false, &["Hang"]), + web_font("Korean", false, true, &["Hang", "Kore"]), + web_font("Devanagari", false, true, &["Deva"]), + ]; + assert_eq!(demand_fonts(&fonts, "한국어".chars()), [2], "Korean fetches only the Korean face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी".chars()), [3], "Hindi fetches only the Devanagari face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी 한국어 Layer".chars()), [2, 3], "each once, in list order"); + assert!(demand_fonts(&fonts, "English العربية 日本語".chars()).is_empty(), "other scripts fetch nothing"); + assert!(demand_fonts(&[], "한국어".chars()).is_empty(), "built without craft-fonts: nothing to fetch"); + } + #[test] fn document_fonts_keep_script_priority_and_include_every_face_once() { let font = |family, style, scripts| CraftFont { family, style, scripts, bytes: &[] }; @@ -157,7 +217,9 @@ mod tests { .collect(); assert_eq!(WEB_FONTS.len(), listed.len()); for (l, w) in listed.iter().zip(WEB_FONTS) { - assert_eq!((l.family, l.style, l.startup), (w.family, w.style, w.startup)); + assert_eq!((l.family, l.style, l.startup, l.demand), (w.family, w.style, w.startup, w.demand)); + let face = CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style); + assert_eq!(face.map(|f| f.scripts), Some(w.scripts), "{} {}: the manifest's scripts", w.family, w.style); let (dir, name) = w.url.strip_prefix("fonts/").and_then(|r| r.split_once('/')).unwrap(); assert!(dir.len() == 16 && dir.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "{}", w.url); assert!(name.ends_with(".ttf") || name.ends_with(".otf"), "{}", w.url); @@ -169,5 +231,11 @@ mod tests { let expected: Vec<_> = ["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); assert_eq!(startup, expected); + // Korean and Devanagari faces are fetched only on demand, never at startup or in the + // background queue every session runs. + let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect(); + let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); + assert_eq!(demand, expected); + assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand))); } } diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 1e1a195db0..7a2a23f089 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1505,6 +1505,19 @@ fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)] Some(builder.build()) } +/// The family of [`private_use_font`]. +pub const PRIVATE_USE_FAMILY: &str = "Private Use Sans"; + +/// The character [`private_use_font`] maps: the first code point of Supplementary Private Use +/// Area-A, which no bundled or craft-fonts face covers. +pub const PRIVATE_USE_CHAR: char = '\u{F0000}'; + +/// A face that maps only [`PRIVATE_USE_CHAR`] to the bundled Source Sans 3 `H` outline, for tests +/// that need a character no other font covers, with or without craft-fonts. +pub fn private_use_font() -> Option> { + remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) +} + /// The family of [`large_cmap_font`]. pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans"; diff --git a/crates/text/web-fonts.txt b/crates/text/web-fonts.txt index 7dbb8953b3..235ba98e13 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -2,6 +2,8 @@ # One face per line: when | family | style (family and style as in craft-fonts' fonts/manifest.txt). # startup = fetched before the app starts (fallbacks the first frame needs) # background = fetched after the app starts (fonts users pick by name) +# demand = fetched only when the interface language or the interface's own text needs one of +# the face's scripts (Korean, Hindi) # Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook). startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular @@ -36,3 +38,5 @@ background | Reem Kufi | Regular background | Aref Ruqaa | Regular background | Aref Ruqaa | Bold background | Gulzar | Regular +demand | NanumGothic | Regular +demand | Noto Sans Devanagari | Regular diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 2dbff773f9..1bfb46f93b 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -34,6 +34,18 @@ pub enum LineKind { Perforation, } +impl LineKind { + /// The angle (degrees) a line of this kind folds at: 90 for a Crease or a Perforation, -90 for + /// a Partial Cut. A positive angle folds away from the printed side; none for a Cut. + pub fn fold_angle(self) -> Option { + match self { + LineKind::Cut => None, + LineKind::Crease | LineKind::Perforation => Some(90.0), + LineKind::PartialCut => Some(-90.0), + } + } +} + /// A fold line: the path (document coordinates), its kind, and a key the issues name it by. #[derive(Clone, Debug)] pub struct FoldLine { @@ -57,10 +69,18 @@ pub struct Panel { pub area: f64, } +impl Panel { + /// A point inside the panel, or the middle of its bounds for one too thin to find one in. + pub fn point_inside(&self) -> Option { + point_in(&self.outline) + } +} + /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. +/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is +/// ([`LineKind::fold_angle`]). #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, @@ -69,6 +89,7 @@ pub struct Hinge { pub to: Point, pub keys: Vec, pub straight: bool, + pub angle: f64, } /// What can be wrong with fold lines, in the order [`blanks`] lists them. @@ -1276,7 +1297,9 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let ((p0, p1), longest) = + group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1308,7 +1331,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1426,7 +1449,7 @@ impl Context<'_> { /// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of /// the larger tie, and the tie goes to the one whose inside point is highest on the page, then /// leftmost. -fn base_panel(panels: &[Panel]) -> Option { +pub fn base_panel(panels: &[Panel]) -> Option { let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); if !top.is_finite() { return None; @@ -1440,5 +1463,9 @@ fn base_panel(panels: &[Panel]) -> Option { .map(|(i, _)| i) } +mod pose; +pub mod raster; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs new file mode 100644 index 0000000000..650ab54291 --- /dev/null +++ b/crates/three-d/src/fold/pose.rs @@ -0,0 +1,407 @@ +//! A blank folded into its 3D shape ([`fold`]). +//! +//! The flat blank lies at z = 0 with document x to the right and document y flipped so y points up; +//! the printed side faces +z. The base panel stays in place. The other panels are reached from it +//! through a breadth-first tree of hinges, each panel's hinges taken in the order of their ends (y, +//! then x, the first end first), so the tree does not depend on the order the lines were drawn in. A child +//! panel turns about its hinge by the hinge's angle times the fold amount; a positive angle moves it +//! toward -z, away from the printed side, whichever way the hinge was drawn. Hinges outside the tree +//! close a loop of panels: [`FoldedHinge::gap`] says how far apart their two placements end up when +//! the blank is folded all the way. + +use std::collections::{HashSet, VecDeque}; + +use vectorcraft_geom::{PathData, PathEl, Point, Shape as _}; + +use super::{Blank, base_panel, point_in}; + +/// Most points a panel's outline is flattened to; a panel with more is left out of the collision +/// test and the preview. +pub const MAX_POLYGON_POINTS: usize = 1 << 16; + +type V3 = [f64; 3]; + +fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn add(a: V3, b: V3) -> V3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +fn scale(a: V3, s: f64) -> V3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn length(a: V3) -> f64 { + dot(a, a).sqrt() +} + +/// A document point on the flat blank (y flipped so it points up, z = 0). +pub(super) fn flat(p: Point) -> V3 { + [p.x, -p.y, 0.0] +} + +/// Where a panel is: a rotation `m` (rows) and a translation `t`, taking a point of the flat +/// blank (see [`flat`]) to its place in 3D. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + pub m: [[f64; 3]; 3], + pub t: [f64; 3], +} + +impl Pose { + /// The flat blank's own place. + pub const IDENTITY: Pose = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] }; + + /// Where the flat point `v` goes. + pub fn apply(&self, v: [f64; 3]) -> [f64; 3] { + add(self.turn(v), self.t) + } + + /// The direction `v` turned by the rotation alone. + pub fn turn(&self, v: [f64; 3]) -> [f64; 3] { + let [a, b, c] = self.m; + [dot(a, v), dot(b, v), dot(c, v)] + } + + /// Where the document point `p` goes. + pub fn place(&self, p: Point) -> [f64; 3] { + self.apply(flat(p)) + } + + /// The direction the printed side faces. + pub fn normal(&self) -> [f64; 3] { + self.turn([0.0, 0.0, 1.0]) + } + + /// This pose followed, in the flat blank's terms, by a right-handed turn of `theta` radians + /// about the line through `at` along the unit direction `axis`: the pose of a panel hinged to + /// this one there. + fn turned_about(&self, at: V3, axis: V3, theta: f64) -> Pose { + let (s, c) = theta.sin_cos(); + let [x, y, z] = axis; + // Rodrigues' rotation matrix. + let r = [ + [c + x * x * (1.0 - c), x * y * (1.0 - c) - z * s, x * z * (1.0 - c) + y * s], + [y * x * (1.0 - c) + z * s, c + y * y * (1.0 - c), y * z * (1.0 - c) - x * s], + [z * x * (1.0 - c) - y * s, z * y * (1.0 - c) + x * s, c + z * z * (1.0 - c)], + ]; + let mut m = [[0.0; 3]; 3]; + for (i, row) in m.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = (0..3).map(|k| self.m[i][k] * r[k][j]).sum(); + } + } + // p ↦ self(r (p - at) + at) = (self.m r) p + self.m (at - r at) + self.t + let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; + Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } + } +} + +/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no +/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it +/// and the base. +#[derive(Clone, Debug)] +pub struct FoldedPanel { + pub pose: Pose, + pub parent: Option, + pub depth: usize, +} + +/// A folded hinge: its panels, its angle (degrees, before the fold amount), whether it is in the +/// fold tree and, for one that is not, how far apart its two placements end up with every hinge at +/// its full angle, whatever the fold amount (`gap`, points), and whether that is close enough to call +/// it closed. +#[derive(Clone, Debug)] +pub struct FoldedHinge { + pub a: usize, + pub b: usize, + pub angle: f64, + pub tree: bool, + pub closes: bool, + pub gap: f64, +} + +/// A blank folded at one amount. +#[derive(Clone, Debug)] +pub struct Folded { + pub base: usize, + pub panels: Vec, + /// The panels in breadth-first order from the base, the panels not joined to it last. + pub order: Vec, + pub hinges: Vec, + /// Pairs of panels (`a` < `b`) that pass through each other. + pub collisions: Vec<(usize, usize)>, +} + +/// The panel of `blank` that `p` (document coordinates) lies in. +pub fn panel_at(blank: &Blank, p: Point) -> Option { + blank.panels.iter().position(|panel| panel.outline.to_bezpath().winding(p) != 0) +} + +/// Which of `blanks` to fold, and about which of its panels: the blank and panel `at` (document +/// coordinates) lies in, or, without a point, the blank with the largest panel (the first of equals) +/// and its base panel. `None` when `at` lies in no panel, or no blank has a panel. +pub fn pick(blanks: &[Blank], at: Option) -> Option<(usize, usize)> { + match at { + Some(p) => blanks.iter().enumerate().find_map(|(i, b)| Some((i, panel_at(b, p)?))), + None => { + let largest = |b: &Blank| b.panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); + let (i, b) = + blanks.iter().enumerate().filter(|(_, b)| !b.panels.is_empty()).fold(None, |best: Option<(usize, &Blank)>, (i, b)| match best { + Some((_, kept)) if largest(kept) >= largest(b) => best, + _ => Some((i, b)), + })?; + Some((i, base_panel(&b.panels)?)) + } + } +} + +/// `blank` folded about its panel `base` (the largest when `None`) by `amount` (0, flat, to 1, every +/// hinge at its angle). `tolerance` (points) is how far apart a closing hinge's placements may end +/// up and still close (or 0.5% of its length, when that is more), and how far apart two panels in +/// one plane may lie and still be stacked rather than crossing. `None` when the blank has no +/// panels, `base` is not one of them, or `amount` is not from 0 to 1. +pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> Option { + let base = match base { + Some(b) => b, + None => base_panel(&blank.panels)?, + }; + if base >= blank.panels.len() || !(0.0..=1.0).contains(&amount) { + return None; + } + let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.01 }; + let n = blank.panels.len(); + // Each panel's hinges, by the place they start (y, then x), then by the other panel. + let mut by_panel: Vec> = vec![vec![]; n]; + for (i, h) in blank.hinges.iter().enumerate() { + for p in [h.a, h.b] { + if let Some(list) = by_panel.get_mut(p) { + list.push(i); + } + } + } + // A hinge's ends, the one first by (y, x) first. + let ends = |i: &usize| { + blank.hinges.get(*i).map_or([f64::INFINITY; 4], |h| { + let (s, e) = if (h.from.y, h.from.x) <= (h.to.y, h.to.x) { (h.from, h.to) } else { (h.to, h.from) }; + [s.y, s.x, e.y, e.x] + }) + }; + for list in &mut by_panel { + list.sort_by(|a, b| { + let (ka, kb) = (ends(a), ends(b)); + ka.iter().zip(&kb).fold(std::cmp::Ordering::Equal, |o, (x, y)| o.then(x.total_cmp(y))).then(a.cmp(b)) + }); + } + let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); + let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // Closing hinges are measured with every hinge at its full angle, so a blank that closes when + // folded is not reported open part of the way there. + let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let measured = full.as_deref().unwrap_or(&panels); + let hinges = blank + .hinges + .iter() + .zip(&tree) + .map(|(h, &tree)| { + let (pa, pb) = (measured.get(h.a).map(|p| p.pose), measured.get(h.b).map(|p| p.pose)); + let gap = match (pa, pb) { + (Some(pa), Some(pb)) if !tree => [h.from, h.to].iter().map(|&e| length(sub(pa.place(e), pb.place(e)))).fold(0.0, f64::max), + _ => 0.0, + }; + let closes = tree || gap <= tolerance.max(0.005 * h.from.distance(h.to)); + FoldedHinge { a: h.a, b: h.b, angle: h.angle, tree, closes, gap } + }) + .collect(); + let collisions = collisions(blank, &panels, tolerance); + Some(Folded { base, panels, order, hinges, collisions }) +} + +/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not +/// joined to the base last). +fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { + let n = blank.panels.len(); + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut reached = vec![false; n]; + let mut tree = vec![false; blank.hinges.len()]; + let mut order = Vec::with_capacity(n); + let mut queue = VecDeque::from([base]); + if let Some(r) = reached.get_mut(base) { + *r = true; + } + while let Some(p) = queue.pop_front() { + order.push(p); + let Some(parent) = panels.get(p).cloned() else { continue }; + for &hi in by_panel.get(p).map(Vec::as_slice).unwrap_or_default() { + let Some(h) = blank.hinges.get(hi) else { continue }; + let child = if h.a == p { h.b } else { h.a }; + if reached.get(child) != Some(&false) { + continue; + } + let (mut from, mut to) = (flat(h.from), flat(h.to)); + let len = length(sub(to, from)); + if !(len.is_finite() && len > 0.0) { + continue; + } + // The parent on the left of the hinge's direction, the child on its right. The side is + // read next to the hinge, so a parent with a notch or an arm past the hinge's line still + // turns the child the right way; the panel's inside point is the fallback. + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + Some(left) => left, + None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), + }; + if !left { + std::mem::swap(&mut from, &mut to); + } + let axis = scale(sub(to, from), 1.0 / len); + let theta = (h.angle * amount).to_radians(); + if !theta.is_finite() { + continue; + } + if let Some(slot) = panels.get_mut(child) { + *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + } + if let Some(r) = reached.get_mut(child) { + *r = true; + } + if let Some(t) = tree.get_mut(hi) { + *t = true; + } + queue.push_back(child); + } + } + order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); + (panels, tree, order) +} + +/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) +/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and +/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset +/// tells them apart. The nearest offset is tried first. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { + let bp = outline.to_bezpath(); + let mid = scale(add(from, to), 0.5); + let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; + let doc = |v: V3| Point::new(v[0], -v[1]); + let mut offsets = [1e-3, 0.25, len * 0.01]; + offsets.sort_by(f64::total_cmp); + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); + (l != r).then_some(l) + }) +} + +/// The rings of `path` flattened to `tolerance`, in document coordinates; `None` past +/// [`MAX_POLYGON_POINTS`] points. +pub fn polygon(path: &PathData, tolerance: f64) -> Option>> { + let mut rings: Vec> = vec![]; + let mut count = 0usize; + let mut fits = true; + vectorcraft_geom::flatten(path.to_bezpath(), tolerance, |el| { + if !fits { + return; + } + match el { + PathEl::MoveTo(p) => rings.push(vec![p]), + PathEl::LineTo(p) => match rings.last_mut() { + Some(r) => r.push(p), + None => rings.push(vec![p]), + }, + _ => return, + } + count += 1; + fits = count <= MAX_POLYGON_POINTS; + }); + rings.retain(|r| r.len() >= 3); + (fits && rings.iter().flatten().all(|p| p.is_finite())).then_some(rings) +} + +/// A panel placed in 3D: its rings, the plane it lies in (unit normal and offset) and its bounds. +struct Placed { + rings: Vec>, + normal: V3, + offset: f64, + lo: V3, + hi: V3, +} + +/// The pairs of `panels` that pass through each other. Two panels hinged to each other are not +/// tested, nor two in parallel planes (stacked in one plane, or apart). +fn collisions(blank: &Blank, panels: &[FoldedPanel], tolerance: f64) -> Vec<(usize, usize)> { + let placed: Vec> = blank + .panels + .iter() + .zip(panels) + .map(|(panel, f)| { + let rings: Vec> = + polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| f.pose.place(p)).collect()).collect(); + let all = rings.iter().flatten(); + let lo = all.clone().fold([f64::INFINITY; 3], |a, p| [a[0].min(p[0]), a[1].min(p[1]), a[2].min(p[2])]); + let hi = all.fold([f64::NEG_INFINITY; 3], |a, p| [a[0].max(p[0]), a[1].max(p[1]), a[2].max(p[2])]); + let normal = f.pose.normal(); + let offset = dot(normal, f.pose.t); + Some(Placed { rings, normal, offset, lo, hi }) + }) + .collect(); + let hinged: HashSet<(usize, usize)> = blank.hinges.iter().map(|h| (h.a.min(h.b), h.a.max(h.b))).collect(); + let mut out = vec![]; + for (i, a) in placed.iter().enumerate() { + let Some(a) = a else { continue }; + for (j, b) in placed.iter().enumerate().skip(i + 1) { + let Some(b) = b else { continue }; + if hinged.contains(&(i, j)) || (0..3).any(|k| a.hi[k] + tolerance < b.lo[k] || b.hi[k] + tolerance < a.lo[k]) { + continue; + } + let line = cross(a.normal, b.normal); + let along = length(line); + if along.is_nan() || along <= 1e-9 { + continue; + } + let u = scale(line, 1.0 / along); + let on_a = crossings(&a.rings, b.normal, b.offset, u, tolerance); + let on_b = crossings(&b.rings, a.normal, a.offset, u, tolerance); + if on_a.iter().any(|x| on_b.iter().any(|y| x.1.min(y.1) - x.0.max(y.0) > tolerance)) { + out.push((i, j)); + } + } + } + out +} + +/// Where `rings` cross the plane `normal · p = offset`: the spans of the line along `u` that lie +/// inside them, by their place along `u`. A panel with no point more than `tolerance` to one side +/// of the plane only touches it, and crosses it nowhere; otherwise points within `tolerance` of it +/// count as on its positive side. +fn crossings(rings: &[Vec], normal: V3, offset: f64, u: V3, tolerance: f64) -> Vec<(f64, f64)> { + let side = |p: V3| dot(normal, p) - offset; + let sides = rings.iter().flatten().map(|&p| side(p)); + let (above, below) = sides.fold((false, false), |(a, b), s| (a || s > tolerance, b || s < -tolerance)); + if !(above && below) { + return vec![]; + } + let mut at = vec![]; + for ring in rings { + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if (sp >= -tolerance) != (sq >= -tolerance) { + let t = (sp / (sp - sq)).clamp(0.0, 1.0); + at.push(dot(u, add(p, scale(sub(q, p), t)))); + } + } + } + at.retain(|x| x.is_finite()); + at.sort_by(f64::total_cmp); + at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect() +} diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs new file mode 100644 index 0000000000..9cccbaf6d9 --- /dev/null +++ b/crates/three-d/src/fold/raster.rs @@ -0,0 +1,495 @@ +//! Draws a [`Folded`] blank as pixels: each panel's outline is projected through the view and filled +//! by scanline, with a depth buffer, and each pixel takes its color from a raster of the flat print +//! (the printed side) or from the inside color (the back), shaded by the panel's slope to a fixed +//! light. The inverse of the panel's projective map gives the flat point under every pixel, so the +//! print is drawn without seams under perspective. With perspective, each panel is cut at a near +//! plane in front of the eye before it is projected. + +use vectorcraft_geom::{Point, Rect}; + +use super::pose::{Folded, polygon}; +use super::{Blank, Panel}; + +/// Most pixels a side of the view or of the print raster may have. +pub const MAX_SIDE: u32 = 4096; +/// Most pixels the view may have in all (2,048 × 1,024; 32 MiB of buffers). +pub const MAX_PIXELS: u32 = 1 << 21; +/// The share of the eye's distance a panel is cut at in front of the eye. +const NEAREST: f64 = 1e-3; +/// How far apart (points of view depth) two panels may be and still tie. +const TIE: f64 = 1e-4; +/// The light's direction: above, to the left of and toward the viewer. +const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; + +type V3 = [f64; 3]; + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// The view: its size in pixels, its turn (degrees: `rotate_x` tips the top toward the viewer, +/// `rotate_y` turns the right side toward the viewer), its scale (pixels per point at the center's +/// depth), how far it is moved (pixels), its perspective (the field of view in degrees; 0 for none) +/// and the 3D point at its middle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub width: u32, + pub height: u32, + pub rotate_x: f64, + pub rotate_y: f64, + pub scale: f64, + pub pan: [f64; 2], + pub perspective: f64, + pub center: [f64; 3], +} + +impl Camera { + /// The turn from 3D to the view's own axes (x right, y up, z toward the viewer), as rows. + fn rotation(&self) -> [[f64; 3]; 3] { + let (sx, cx) = self.rotate_x.to_radians().sin_cos(); + let (sy, cy) = (-self.rotate_y).to_radians().sin_cos(); + // Rx · Ry + [[cy, 0.0, sy], [sx * sy, cx, -sx * cy], [-cx * sy, sx, cx * cy]] + } + + /// The point `p` in the view's own axes, its middle at the origin. + pub fn to_view(&self, p: V3) -> V3 { + let r = self.rotation(); + let d = [p[0] - self.center[0], p[1] - self.center[1], p[2] - self.center[2]]; + [dot(r[0], d), dot(r[1], d), dot(r[2], d)] + } + + /// The distance (points) from the eye to the view's middle and the focal length (pixels) under + /// perspective; `None` without it. + fn eye(&self) -> Option<(f64, f64)> { + if self.perspective <= 0.0 || self.perspective >= 180.0 { + return None; + } + let half = f64::from(self.width.min(self.height)) / 2.0; + let focal = half / (self.perspective.to_radians() / 2.0).tan(); + let eye = focal / self.scale; + (focal.is_finite() && eye.is_finite() && eye > 0.0).then_some((eye, focal)) + } + + fn usable(&self) -> bool { + let finite = + [self.rotate_x, self.rotate_y, self.scale, self.pan[0], self.pan[1], self.perspective].iter().chain(&self.center).all(|v| v.is_finite()); + let pixels = u64::from(self.width) * u64::from(self.height); + finite && self.scale > 0.0 && (1..=MAX_SIDE).contains(&self.width) && (1..=MAX_SIDE).contains(&self.height) && pixels <= u64::from(MAX_PIXELS) + } +} + +/// One level of the print raster: premultiplied RGBA, 4 bytes a pixel. +#[derive(Clone, Debug)] +pub struct Level { + pub width: u32, + pub height: u32, + pub pixels: Vec, +} + +impl Level { + /// The color at pixel `(x, y)`, clamped to the edges. + fn at(&self, x: i64, y: i64) -> [f32; 4] { + let x = x.clamp(0, i64::from(self.width) - 1); + let y = y.clamp(0, i64::from(self.height) - 1); + let i = usize::try_from((y * i64::from(self.width) + x) * 4).unwrap_or(usize::MAX); + match self.pixels.get(i..i.saturating_add(4)) { + Some(&[r, g, b, a]) => [f32::from(r), f32::from(g), f32::from(b), f32::from(a)], + _ => [0.0; 4], + } + } + + /// The color at `(x, y)` (pixels), between the four nearest pixels. + fn sample(&self, x: f64, y: f64) -> [f32; 4] { + let (fx, fy) = (x - 0.5, y - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.at(x0, y0), self.at(x0 + 1, y0), self.at(x0, y0 + 1), self.at(x0 + 1, y0 + 1)); + let mut out = [0.0; 4]; + for (k, o) in out.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bottom = c[k] + (d[k] - c[k]) * tx; + *o = top + (bottom - top) * ty; + } + out + } + + /// This level at half its size, rounded up, each pixel the mean of the pixels it covers weighted + /// by the area of the full print they cover. A pixel of this level is `step` pixels of the full + /// print (`base` pixels across and down) on a side, and fewer in the last column and row when + /// `base` is not a multiple of `step`. + fn half(&self, base: (u32, u32), step: u32) -> Option { + let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2)); + if (w, h) == (self.width, self.height) { + return None; + } + // The pixels of the full print that column or row `i` of this level covers, or 0 past it. + let covers = |i: u32, side: u32| u64::from(side).saturating_sub(u64::from(i) * u64::from(step)).min(u64::from(step)) as f32; + let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..h { + for x in 0..w { + let mut sum = [0.0f32; 4]; + let mut area = 0.0; + for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { + if sx >= self.width || sy >= self.height { + continue; + } + let a = covers(sx, base.0) * covers(sy, base.1); + let p = self.at(i64::from(sx), i64::from(sy)); + for (s, c) in sum.iter_mut().zip(p) { + *s += c * a; + } + area += a; + } + for s in sum { + pixels.push(if area > 0.0 { (s / area).round() as u8 } else { 0 }); + } + } + } + Some(Level { width: w, height: h, pixels }) + } +} + +/// The flat print: the document rect it covers and its raster at full size and halved again and +/// again down to one pixel. +#[derive(Clone, Debug)] +pub struct Print { + pub region: Rect, + pub levels: Vec, +} + +impl Print { + /// The print of `region` from `pixels` (premultiplied RGBA, `width` × `height`); `None` when + /// the sizes do not agree, a side is 0 or more than [`MAX_SIDE`], or the region is empty. + pub fn new(region: Rect, width: u32, height: u32, pixels: Vec) -> Option { + let fits = (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height); + let empty = !(region.width() > 0.0 && region.height() > 0.0 && region.is_finite()); + if !fits || empty || pixels.len() != width as usize * height as usize * 4 { + return None; + } + let mut levels = vec![Level { width, height, pixels }]; + let mut step = 1; + while let Some(next) = levels.last().and_then(|l| l.half((width, height), step)) { + levels.push(next); + step *= 2; + } + Some(Print { region, levels }) + } + + /// The print's color (premultiplied, 0 to 255) at document point `p`, from the level whose + /// pixels are closest to `footprint` points across; transparent outside the region. + fn sample(&self, p: Point, footprint: f64) -> [f32; 4] { + let Some(base) = self.levels.first() else { return [0.0; 4] }; + if !self.region.contains(p) { + return [0.0; 4]; + } + let per_point = f64::from(base.width) / self.region.width(); + let level = if footprint.is_finite() && footprint > 0.0 { (footprint * per_point).log2().floor().max(0.0) as usize } else { 0 }; + let level = level.min(self.levels.len() - 1); + let Some(l) = self.levels.get(level) else { return [0.0; 4] }; + // Each level halves the one before it, so a pixel of level n covers 2ⁿ of the first's. + let shrink = f64::from(1u32 << level); + let sx = f64::from(base.width) / self.region.width() / shrink; + let sy = f64::from(base.height) / self.region.height() / shrink; + l.sample((p.x - self.region.x0) * sx, (p.y - self.region.y0) * sy) + } +} + +/// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of +/// its printed side where the print has no art (straight RGBA; the board is opaque, so their alpha +/// is not used), and the view. +pub struct Scene<'a> { + pub blank: &'a Blank, + pub folded: &'a Folded, + pub print: Option<&'a Print>, + pub inside: [u8; 4], + pub outside: [u8; 4], + pub camera: Camera, +} + +/// A drawn view: premultiplied RGBA, 4 bytes a pixel, transparent where no panel is; and for each +/// pixel the panel drawn there plus 1 (0 for none). +#[derive(Clone, Debug)] +pub struct Image { + pub width: u32, + pub height: u32, + pub pixels: Vec, + pub panels: Vec, +} + +impl Image { + /// The panel drawn at pixel `(x, y)`. + pub fn panel_at(&self, x: u32, y: u32) -> Option { + if x >= self.width || y >= self.height { + return None; + } + let i = y as usize * self.width as usize + x as usize; + self.panels.get(i).and_then(|&p| usize::from(p).checked_sub(1)) + } +} + +/// The 3D bounds of `blank`'s panels folded as `folded` places them (low and high corners). +pub fn bounds(blank: &Blank, folded: &Folded) -> Option<(V3, V3)> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for (panel, f) in blank.panels.iter().zip(&folded.panels) { + let Some(b) = panel.outline.bounds() else { continue }; + for c in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)] { + let p = f.pose.place(c); + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + } + lo.iter().chain(&hi).all(|v| v.is_finite()).then_some((lo, hi)) +} + +/// A panel ready to fill: its projective map from the flat blank to the view and back, its depth +/// plane in view terms, and its color factors. +struct Mapped { + /// Flat (u, v, 1) → (x w, y w, w) in pixels, as rows. + forward: [[f64; 3]; 3], + /// The inverse of `forward`. + inverse: [[f64; 3]; 3], + /// View depth at flat (u, v): u a + v b + c. + depth: [f64; 3], + printed: bool, + shade: f32, +} + +fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 { + [dot(m[0], v), dot(m[1], v), dot(m[2], v)] +} + +fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { + let [[a, b, c], [d, e, f], [g, h, i]] = *m; + let co = [e * i - f * h, f * g - d * i, d * h - e * g]; + let det = a * co[0] + b * co[1] + c * co[2]; + if !(det.is_finite() && det.abs() > 1e-300) { + return None; + } + let inv = [ + [co[0] / det, (c * h - b * i) / det, (b * f - c * e) / det], + [co[1] / det, (a * i - c * g) / det, (c * d - a * f) / det], + [co[2] / det, (b * g - a * h) / det, (a * e - b * d) / det], + ]; + inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) +} + +fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { + let r = camera.rotation(); + let turn = |v: V3| mul(&r, f.pose.turn(v)); + let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); + let o = camera.to_view(f.pose.t); + let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); + let normal = turn([0.0, 0.0, 1.0]); + let (w, k, printed) = match camera.eye() { + Some((eye, focal)) => ([-a[2], -b[2], eye - o[2]], focal, dot(normal, [-o[0], -o[1], eye - o[2]]) > 0.0), + None => ([0.0, 0.0, 1.0], camera.scale, normal[2] > 0.0), + }; + let x = [cx * w[0] + k * a[0], cx * w[1] + k * b[0], cx * w[2] + k * o[0]]; + let y = [cy * w[0] - k * a[1], cy * w[1] - k * b[1], cy * w[2] - k * o[1]]; + let forward = [x, y, w]; + let inverse = invert(&forward)?; + let facing = if printed { normal } else { [-normal[0], -normal[1], -normal[2]] }; + let shade = (0.6 + 0.4 * dot(facing, LIGHT).max(0.0)) as f32; + Some(Mapped { forward, inverse, depth: [a[2], b[2], o[2]], printed, shade }) +} + +/// `ring` (flat points) cut to the side of the plane `w · (u, v, 1) ≥ near`. +fn clip(ring: &[[f64; 2]], w: V3, near: f64) -> Vec<[f64; 2]> { + let at = |p: [f64; 2]| dot(w, [p[0], p[1], 1.0]) - near; + let mut out = Vec::with_capacity(ring.len() + 4); + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (dp, dq) = (at(p), at(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp >= 0.0) != (dq >= 0.0) { + let t = dp / (dp - dq); + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]); + } + } + out +} + +/// The buffers [`render`] fills. +struct Target { + width: usize, + height: usize, + color: Vec, + depth: Vec, + rank: Vec, + panel: Vec, +} + +/// One panel's fill: its map, rank (for ties), panel number and colors. +struct Fill<'a> { + mapped: &'a Mapped, + rank: u16, + panel: u16, + print: Option<&'a Print>, + inside: [f32; 4], + outside: [f32; 4], +} + +impl Fill<'_> { + /// The document point under pixel center `(x, y)`, or `None` behind the eye. + fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { + let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); + (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) + } + + /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. + fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { + let base = if self.mapped.printed { + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let under = 1.0 - p[3] / 255.0; + [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] + } else { + self.inside + }; + let s = self.mapped.shade; + [base[0] * s, base[1] * s, base[2] * s, base[3]] + } + + /// Fill the span of row `row` from `x0` to `x1` (pixel coordinates) into `target`. + fn span(&self, target: &mut Target, row: usize, x0: f64, x1: f64) { + let first = (x0 - 0.5).ceil().max(0.0); + let last = ((x1 - 0.5).ceil() - 1.0).min(target.width as f64 - 1.0); + if first > last { + return; + } + let y = row as f64 + 0.5; + for col in first as usize..=last as usize { + let x = col as f64 + 0.5; + let Some((u, v)) = self.flat_at(x, y) else { continue }; + let [a, b, c] = self.mapped.depth; + let z = u * a + v * b + c; + let i = row * target.width + col; + let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; + let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + if !wins { + continue; + } + // The print's footprint is the longer of a pixel's two sides in flat terms. + let across = |dx: f64, dy: f64| self.flat_at(x + dx, y + dy).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + let footprint = across(1.0, 0.0).max(across(0.0, 1.0)); + let color = self.color(u, v, footprint); + if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) { + for (o, c) in px.iter_mut().zip(color) { + *o = c.round().clamp(0.0, 255.0) as u8; + } + } + if let Some(d) = target.depth.get_mut(i) { + *d = z; + } + if let Some(r) = target.rank.get_mut(i) { + *r = self.rank; + } + if let Some(p) = target.panel.get_mut(i) { + *p = self.panel; + } + } + } + + /// Fill the projected `rings` (pixel coordinates), even-odd, into `target`. + fn rings(&self, target: &mut Target, rings: &[Vec<[f64; 2]>]) { + let ys = rings.iter().flatten().map(|p| p[1]); + let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); + if !(lo.is_finite() && hi.is_finite()) { + return; + } + let first = (lo - 0.5).ceil().max(0.0); + let last = (hi - 0.5).floor().min(target.height as f64 - 1.0); + if first > last { + return; + } + let mut xs = vec![]; + for row in first as usize..=last as usize { + let y = row as f64 + 0.5; + xs.clear(); + for ring in rings { + for (k, p) in ring.iter().enumerate() { + let Some(q) = ring.get((k + 1) % ring.len()) else { continue }; + if (p[1] <= y) != (q[1] <= y) { + xs.push(p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1])); + } + } + } + xs.retain(|x| x.is_finite()); + xs.sort_by(f64::total_cmp); + for &[a, b] in xs.as_chunks::<2>().0 { + self.span(target, row, a, b); + } + } + } +} + +/// The board color `c` as drawn: its RGB, opaque. +fn opaque(c: [u8; 4]) -> [f32; 4] { + [f32::from(c[0]), f32::from(c[1]), f32::from(c[2]), 255.0] +} + +/// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a +/// point. +fn flat_rings(panel: &Panel, scale: f64) -> Option>> { + let b = panel.outline.bounds()?; + let tolerance = (0.25 / scale).max((b.width() + b.height()) * 1e-5).max(1e-6); + Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) +} + +/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more +/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than +/// [`super::MAX_POLYGON_POINTS`] points, are left out. +pub fn render(scene: &Scene) -> Option { + let camera = scene.camera; + if !camera.usable() { + return None; + } + let (width, height) = (camera.width as usize, camera.height as usize); + let pixels = width * height; + let mut target = + Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; + let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); + let near = camera.eye().map(|(eye, _)| eye * NEAREST); + for (rank, &pi) in scene.folded.order.iter().enumerate() { + let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; + let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let projected: Vec> = rings + .iter() + .map(|r| match near { + Some(near) => clip(r, mapped.forward[2], near), + None => r.clone(), + }) + .filter(|r| r.len() >= 3) + .map(|r| { + r.into_iter() + .filter_map(|[u, v]| { + let [x, y, w] = mul(&mapped.forward, [u, v, 1.0]); + let p = [x / w, y / w]; + (w > 0.0 && p[0].is_finite() && p[1].is_finite()).then_some(p) + }) + .collect::>() + }) + .filter(|r| r.len() >= 3) + .collect(); + let fill = Fill { + mapped: &mapped, + rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), + print: scene.print, + inside, + outside, + }; + fill.rings(&mut target, &projected); + } + Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs new file mode 100644 index 0000000000..8639615a53 --- /dev/null +++ b/crates/three-d/src/fold/raster/tests.rs @@ -0,0 +1,257 @@ +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::*; + +fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) +} + +fn panel(subpaths: Vec) -> Panel { + Panel { outline: PathData::new(subpaths), area: 0.0 } +} + +/// A blank of `panels` and a fold that places each at `poses`, in the order given. +fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { + let n = panels.len(); + let folded = Folded { + base: 0, + panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + order: (0..n).collect(), + hinges: vec![], + collisions: vec![], + }; + (Blank { panels, hinges: vec![], holes: vec![] }, folded) +} + +/// Facing the printed side, 100 × 100 pixels, one pixel a point, the flat square 0..100 filling it. +fn front() -> Camera { + Camera { width: 100, height: 100, rotate_x: 0.0, rotate_y: 0.0, scale: 1.0, pan: [0.0; 2], perspective: 0.0, center: [50.0, -50.0, 0.0] } +} + +fn moved(z: f64) -> Pose { + Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY } +} + +fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// A 2 × 2 print of the square 0..100: red, green on top; blue, white below. +fn quads() -> Print { + let px = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]]; + Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 2, 2, px.concat()).expect("a print") +} + +const WHITE: [u8; 4] = [255, 255, 255, 255]; + +#[test] +fn a_flat_panel_takes_the_print_s_color_under_each_pixel() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + assert_eq!(pixel(&img, 5, 5), [lit(255.0), 0, 0, 255], "top left is red"); + assert_eq!(pixel(&img, 94, 5), [0, lit(255.0), 0, 255], "top right is green"); + assert_eq!(pixel(&img, 5, 94), [0, 0, lit(255.0), 255], "bottom left is blue"); + assert_eq!(img.panel_at(50, 50), Some(0)); + // Where the print has no art, the board's printed side shows. + let empty = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1, 1, vec![0; 4]).expect("a print"); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&empty), inside: [0, 0, 0, 255], outside: [200, 100, 50, 255], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]); +} + +#[test] +fn the_board_is_opaque_whatever_the_alpha_of_its_colors() { + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for a in [0, 128] { + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: [200, 100, 50, a], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255], "outside alpha {a}"); + } + // A transparent inside color draws opaque too, on the nearer of two panels seen from the back. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(5.0)]); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 200, 0, 0], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn a_print_squeezed_only_up_and_down_on_screen_samples_a_halved_level() { + // 64 × 64, rows alternating black and white: halved, they average to gray. + let mut px = vec![]; + for y in 0..64 { + for _ in 0..64 { + px.extend(if y % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // Tipped 80°: about 5.8 points a pixel up and down, 1 across. + let camera = Camera { rotate_x: 80.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let reds: Vec = (0..img.height) + .flat_map(|y| (0..img.width).map(move |x| (x, y))) + .filter(|&(x, y)| img.panel_at(x, y).is_some()) + .map(|(x, y)| pixel(&img, x, y)[0]) + .collect(); + assert!(!reds.is_empty()); + let (lo, hi) = (reds.iter().min().copied().unwrap_or(0), reds.iter().max().copied().unwrap_or(0)); + assert!(hi - lo <= 2, "an even gray, not black and white rows: {lo} to {hi}"); +} + +#[test] +fn the_back_of_a_panel_shows_the_inside_color() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 200, 0, 255], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let draw = |z: f64| { + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(z)]); + render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn") + }; + assert_eq!(draw(5.0).panel_at(50, 50), Some(1), "panel 1 is in front"); + assert_eq!(draw(-5.0).panel_at(50, 50), Some(0), "panel 1 is behind"); + assert_eq!(draw(0.0).panel_at(50, 50), Some(1), "a tie goes to the panel later in the order"); + // Panels that cross: each shows where it is nearer. + let tilted = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]], t: [0.0, 0.0, -25.0] }; + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, tilted]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(20, 50), Some(0), "the tilted panel is behind on the left"); + assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); +} + +#[test] +fn a_hole_in_a_panel_is_left_empty() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), None); + assert_eq!(pixel(&img, 50, 50), [0; 4]); + assert_eq!(img.panel_at(10, 50), Some(0)); +} + +#[test] +fn a_panel_past_the_eye_at_a_wide_perspective_is_cut_at_the_near_plane() { + // A long panel standing out of the page toward the viewer, through the eye. + let toward = Pose { m: [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], t: [0.0, -50.0, 0.0] }; + let (b, f) = scene_of(vec![panel(vec![square(0.0, -1000.0, 100.0, 1000.0)])], vec![toward]); + for perspective in [1.0, 60.0, 160.0, 179.0] { + let camera = Camera { perspective, scale: 8.0, rotate_x: 30.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let drawn = img.panels.iter().filter(|&&p| p != 0).count(); + assert!(drawn > 0, "{perspective}°: some of it shows"); + assert_eq!(img.pixels.len(), 100 * 100 * 4); + } +} + +#[test] +fn unusable_views_and_prints_are_refused() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for camera in [ + Camera { width: 0, ..front() }, + Camera { height: MAX_SIDE + 1, ..front() }, + Camera { width: MAX_SIDE, height: MAX_PIXELS / MAX_SIDE + 1, ..front() }, + Camera { scale: 0.0, ..front() }, + Camera { rotate_x: f64::NAN, ..front() }, + Camera { center: [f64::INFINITY, 0.0, 0.0], ..front() }, + ] { + assert!(render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera }).is_none(), "{camera:?}"); + } + let region = Rect::new(0.0, 0.0, 10.0, 10.0); + assert!(Print::new(region, 2, 2, vec![0; 15]).is_none(), "too few bytes"); + assert!(Print::new(region, 0, 2, vec![]).is_none()); + assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none()); + assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region"); + let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print"); + assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::>(), vec![(8, 4), (4, 2), (2, 1), (1, 1)]); +} + +#[test] +fn halving_an_odd_sized_print_keeps_its_last_row_and_column() { + // 3 × 3, transparent but for an opaque white last column and last row. + let mut px = vec![0u8; 3 * 3 * 4]; + for i in [2, 5, 6, 7, 8] { + px[i * 4..i * 4 + 4].copy_from_slice(&[255; 4]); + } + let p = Print::new(Rect::new(0.0, 0.0, 30.0, 30.0), 3, 3, px).expect("a print"); + let half = &p.levels[1]; + assert_eq!((half.width, half.height), (2, 2)); + // The bottom right pixel of the half level covers only the corner pixel. + assert_eq!(&half.pixels[12..16], &[255; 4]); + assert_eq!(&half.pixels[0..4], &[0; 4], "the top left covers four transparent pixels"); +} + +#[test] +fn a_print_far_smaller_on_screen_samples_a_halved_level() { + // Columns alternate black and white: halved, they average to gray. + let mut px = vec![]; + for _ in 0..4 { + for x in 0..4 { + px.extend(if x % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 4, 4, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 2 pixels: 2 print pixels a view pixel. + let camera = Camera { width: 2, height: 2, scale: 0.02, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 0); + assert!((80..=150).contains(&r), "gray, not a black or white column: {r}"); +} + +#[test] +fn a_print_sixteen_times_smaller_on_screen_samples_a_level_halved_four_times() { + // 64 × 64, columns in bands of 4 alternating black and white: halved twice, they still alternate; + // halved four times, they average to gray. + let mut px = vec![]; + for _ in 0..64 { + for x in 0..64 { + px.extend(if (x / 4) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + assert_eq!(print.levels.len(), 7, "64 down to 1"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 3 pixels: about 21 print pixels a view pixel. + let camera = Camera { width: 3, height: 3, scale: 0.03, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 1); + assert!((90..=140).contains(&r), "gray, not a black or white band: {r}"); +} + +#[test] +fn a_halved_level_weighs_an_odd_last_column_by_the_area_it_covers() { + // 9 × 9, black but for a white last column: a ninth of the print, so the one-pixel level is + // a ninth white (255 / 9 is about 28), not half. + let mut px = vec![]; + for _ in 0..9 { + for x in 0..9 { + px.extend(if x == 8 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 9, 9, px).expect("a print"); + assert_eq!(print.levels.iter().map(|l| (l.width, l.height)).collect::>(), vec![(9, 9), (5, 5), (3, 3), (2, 2), (1, 1)]); + assert_eq!(print.levels.last().map(|l| l.pixels.clone()), Some(vec![28, 28, 28, 255])); +} + +#[test] +fn the_bounds_take_in_every_folded_panel() { + let (b, f) = + scene_of(vec![panel(vec![square(0.0, 0.0, 10.0, 10.0)]), panel(vec![square(0.0, 0.0, 10.0, 10.0)])], vec![Pose::IDENTITY, moved(-7.0)]); + let (lo, hi) = bounds(&b, &f).expect("bounds"); + assert_eq!((lo, hi), ([0.0, -10.0, -7.0], [10.0, 0.0, 0.0])); +} diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index ef014300c0..8031a0b2a1 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -913,4 +913,323 @@ proptest! { sorted.sort_by_key(|i| i.code); prop_assert_eq!(sorted, issues); } + + /// Random fold lines fold at any amount without a panic, every pose finite and every panel + /// keeping its shape. + #[test] + fn random_blanks_fold_to_finite_poses( + segs in proptest::collection::vec((1u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..8), + amount in 0.0f64..=1.0, + ) { + let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation]; + let mut lines: Vec = segs + .iter() + .enumerate() + .map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64)) + .collect(); + lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99)); + let (blanks, _) = blanks(&lines, TOL); + for b in &blanks { + let Some(f) = fold(b, None, amount, TOL) else { continue }; + prop_assert_eq!(f.panels.len(), b.panels.len()); + prop_assert_eq!(f.order.len(), b.panels.len()); + for p in &f.panels { + prop_assert!(p.pose.m.iter().flatten().chain(&p.pose.t).all(|v| v.is_finite())); + let n = p.pose.normal(); + prop_assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-9); + } + } + } +} + +/// The 3D corners of panel `i` of `b` folded as `f` places them. +fn corners(b: &Blank, f: &Folded, i: usize) -> Vec<[f64; 3]> { + let rings = polygon(&b.panels[i].outline, 0.01).expect("a polygon"); + rings.into_iter().flatten().map(|p| f.panels[i].pose.place(p)).collect() +} + +fn flat_center(b: &Blank, i: usize) -> [f64; 3] { + let c = point_in(&b.panels[i].outline).expect("a point inside"); + [c.x, -c.y, 0.0] +} + +#[test] +fn a_slotted_box_folds_every_panel_onto_a_face_of_the_box_with_the_print_outside() { + let (b, issues) = check(¬ched_box()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + // The base panel is the leftmost of the two largest body panels: x 20 to 120, y 30 to 110. + let base = &b.panels[f.base]; + assert_eq!(base.outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((20.0, 30.0))); + // The box: the base panel's face (z = 0), 60 deep (the narrow body panels' width). + let (lo, hi) = ([20.0, -110.0, -60.0], [120.0, -30.0, 0.0]); + let middle = [70.0, -70.0, -30.0]; + for i in 0..b.panels.len() { + let points = corners(b, &f, i); + let face = (0..3).find_map(|k| [lo[k], hi[k]].into_iter().find(|&at| points.iter().all(|p| (p[k] - at).abs() < 1e-6)).map(|at| (k, at))); + let (k, at) = face.unwrap_or_else(|| panic!("panel {i} lies on no face of the box: {points:?}")); + for p in &points { + for j in 0..3 { + assert!(p[j] > lo[j] - 1e-6 && p[j] < hi[j] + 1e-6, "panel {i} reaches out of the box: {p:?}"); + } + } + // The printed side faces out of the box. + let n = f.panels[i].pose.normal(); + assert!((n[k].abs() - 1.0).abs() < 1e-9, "panel {i} is square to its face: {n:?}"); + assert!(n[k] * (at - middle[k]) > 0.0, "panel {i}'s print faces out: {n:?}"); + } + assert!(f.hinges.iter().all(|h| h.tree && h.closes && (h.angle - 90.0).abs() < 1e-12), "{:?}", f.hinges); + assert!(f.collisions.is_empty(), "the stacked flaps and the glue flap do not cross: {:?}", f.collisions); + assert_eq!(f.order.first(), Some(&f.base)); + assert_eq!(f.order.len(), 13); +} + +#[test] +fn at_amount_0_the_blank_is_flat() { + let (b, _) = check(¬ched_box()); + let f = fold(&b[0], None, 0.0, TOL).expect("folds"); + for p in &f.panels { + for (row, want) in p.pose.m.iter().zip(Pose::IDENTITY.m) { + assert!(row.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", p.pose); + } + assert!(p.pose.t.iter().all(|v| v.abs() < 1e-9), "{:?}", p.pose); + } +} + +/// A 100 × 60 rectangle split by a line of `kind` at x = 60 (drawn upward when `up`), turned by +/// `quarter` quarter turns about the origin and mirrored in x when `mirror`. +fn two_panels(kind: LineKind, quarter: u8, mirror: bool, up: bool) -> Vec { + let at = |(x, y): (f64, f64)| { + let x = if mirror { -x } else { x }; + (0..quarter).fold((x, y), |(x, y), _| (-y, x)) + }; + let outline: Vec<(f64, f64)> = [(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)].into_iter().map(at).collect(); + let (a, b) = if up { ((60.0, 60.0), (60.0, 0.0)) } else { ((60.0, 0.0), (60.0, 60.0)) }; + vec![cut(&outline, 1), line(kind, &[at(a), at(b)], false, 2)] +} + +#[test] +fn a_crease_folds_away_from_the_print_and_a_partial_cut_toward_it_however_it_is_drawn() { + for quarter in 0..4 { + for mirror in [false, true] { + for up in [false, true] { + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::Perforation, -1.0), (LineKind::PartialCut, 1.0)] { + let case = format!("{kind:?}, {quarter} quarter turns, mirrored {mirror}, drawn up {up}"); + let (b, issues) = check(&two_panels(kind, quarter, mirror, up)); + assert!(issues.is_empty(), "{case}: {issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let h = &b.hinges[0]; + let hinge = [(h.from.x + h.to.x) / 2.0, -(h.from.y + h.to.y) / 2.0, 0.0]; + let c = flat_center(b, child); + let away = [c[0] - hinge[0], c[1] - hinge[1], 0.0]; + let along = [h.to.x - h.from.x, h.from.y - h.to.y]; + let off_line = (along[0] * away[1] - along[1] * away[0]).abs() / along[0].hypot(along[1]); + let placed = f.panels[child].pose.apply(c); + // The child stands up out of the plane: behind it for a crease, in front of it + // for a partial cut, at its distance from the hinge. + assert!(placed[2] * sign > 0.0, "{case}: {placed:?}"); + assert!((placed[2].abs() - off_line).abs() < 1e-6, "{case}: {placed:?} {off_line}"); + // Its printed side faces away from the base panel after a crease, back toward + // it after a partial cut. + let n = f.panels[child].pose.normal(); + assert!((n[0] * away[0] + n[1] * away[1]) * -sign > 0.0, "{case}: {n:?}"); + // Half way, the child is half way round. + let half = fold(b, None, 0.5, TOL).expect("folds"); + let z = half.panels[child].pose.normal()[2]; + assert!((z - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{case}: {z}"); + } + } + } + } +} + +/// A 100 × 100 square divided into four panels by a crease across it each way. +fn crossed() -> Vec { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + crease((50.0, 0.0), (50.0, 100.0), 2), + crease((0.0, 50.0), (100.0, 50.0), 3), + ] +} + +#[test] +fn a_loop_of_hinges_closes_when_flat_and_reports_its_gap_when_folded() { + let (b, issues) = check(&crossed()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (4, 4)); + let folded = fold(b, None, 1.0, TOL).expect("folds"); + let closing: Vec<&FoldedHinge> = folded.hinges.iter().filter(|h| !h.tree).collect(); + assert_eq!(closing.len(), 1, "three hinges make the tree, one closes the loop"); + assert!(!closing[0].closes && closing[0].gap > 10.0, "{closing:?}"); + // The gap is measured folded all the way, whatever the amount: flat or half way, the loop is + // still reported open by the same gap. + for amount in [0.0, 0.5] { + let part = fold(b, None, amount, TOL).expect("folds"); + let h = part.hinges.iter().find(|h| !h.tree).expect("a closing hinge"); + assert!(!h.closes && (h.gap - closing[0].gap).abs() < 1e-9, "{amount}: {h:?}"); + } + // The base is the top-left panel: four equal panels tie, and the highest, then leftmost, wins. + assert_eq!(b.panels[folded.base].outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((0.0, 0.0))); +} + +#[test] +fn hinges_that_start_at_one_point_fold_the_same_in_any_line_order() { + // About the bottom-right panel, its two hinges both start at the middle of the square. + let lines = crossed(); + let orders = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [1, 2, 0], [1, 0, 2], [2, 0, 1]]; + let mut seen = None; + for order in orders { + let lines: Vec = order.iter().map(|&i| lines[i].clone()).collect(); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{order:?}: {issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(75.0, 75.0)).expect("the bottom-right panel"); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + let closing = f.hinges.iter().zip(&b.hinges).find(|(h, _)| !h.tree).map(|(_, h)| ((h.from.x + h.to.x) / 2.0, (h.from.y + h.to.y) / 2.0)); + let top_left = panel_at(b, p(25.0, 25.0)).expect("the top-left panel"); + let placed = f.panels[top_left].pose.place(p(25.0, 25.0)).map(|v| (v * 1e6).round()); + let got = (closing, placed); + assert_eq!(seen.get_or_insert(got), &got, "{order:?}"); + } +} + +/// A 100 × 60 rectangle: the left 60 pt is one panel, the right is split across at y = 30, and the +/// line between them bends by `lean` pt over its lower half. +fn leaning(lean: f64) -> Vec { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + crease((60.0, 0.0), (60.0, 30.0), 2), + crease((60.0, 30.0), (60.0 + lean, 60.0), 3), + crease((60.0, 30.0), (100.0, 30.0), 4), + ] +} + +#[test] +fn a_loop_closes_within_the_tolerance_or_half_a_percent_of_its_hinge() { + // Both right panels turn about one line, so the hinge between them closes exactly. + let gap = |lean: f64, amount: f64| { + let (b, issues) = check(&leaning(lean)); + assert!(issues.is_empty(), "{lean}: {issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (3, 3)); + let base = panel_at(b, p(30.0, 30.0)).expect("the left panel"); + let f = fold(b, Some(base), amount, TOL).expect("folds"); + let h = f.hinges.iter().find(|h| !h.tree).expect("a closing hinge").clone(); + (h.closes, h.gap) + }; + let (closes, at) = gap(0.0, 1.0); + assert!(closes && at < 1e-9, "{at}"); + // A small lean opens it by more than the 0.1 pt tolerance but less than 0.5% of its 40 pt + // length (0.2 pt): still closed. + let (closes, at) = gap(0.1, 1.0); + assert!(closes && at > TOL && at <= 0.2, "{at}"); + // A larger lean opens it past both, flat or folded. + for amount in [0.0, 1.0] { + let (closes, at) = gap(1.0, amount); + assert!(!closes && at > 0.2, "{amount}: {at}"); + } +} + +#[test] +fn a_panel_no_hinge_joins_stays_flat_where_it_is() { + let lines = vec![ + cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1), + crease((50.0, 49.95), (50.0, 50.0), 2), + ]; + let (b, _) = check(&lines); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (2, 0)); + let f = fold(b, None, 1.0, TOL).expect("folds"); + let loose = 1 - f.base; + assert_eq!(f.panels[loose].parent, None); + assert_eq!(f.panels[loose].pose, Pose::IDENTITY); + assert_eq!(f.order, vec![f.base, loose], "the loose panel comes last"); +} + +#[test] +fn a_child_of_a_notched_panel_folds_away_from_the_print() { + // The base is an L: a 30 × 140 strip with an 80 pt arm along its top running right to x = 300. + // The child, below the arm past a 2 pt slot, is hinged to the strip along x = 30. + let lines = vec![ + cut(&[(0.0, 0.0), (300.0, 0.0), (300.0, 80.0), (30.0, 80.0), (30.0, 82.0), (300.0, 82.0), (300.0, 140.0), (0.0, 140.0)], 1), + crease((30.0, 82.0), (30.0, 140.0), 2), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(15.0, 110.0)).expect("the L"); + let child = panel_at(b, p(150.0, 110.0)).expect("the child"); + // The L's inside point lies in its arm, on the child's side of the hinge's line. + let inside = b.panels[base].point_inside().expect("a point inside"); + assert!(inside.x > 30.0, "{inside:?}"); + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::PartialCut, 1.0)] { + let mut lines = lines.clone(); + lines[1].kind = kind; + let (b, _) = check(&lines); + let f = fold(&b[0], Some(base), 1.0, TOL).expect("folds"); + let placed = f.panels[child].pose.place(p(150.0, 110.0)); + assert!(placed[2] * sign > 99.0, "{kind:?}: {placed:?}"); + } +} + +#[test] +fn a_lid_folded_over_the_base_crosses_the_taller_wall_opposite() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. + let lines = vec![ + cut(&[(0.0, 0.0), (310.0, 0.0), (310.0, 50.0), (0.0, 50.0)], 1), + crease((120.0, 0.0), (120.0, 50.0), 2), + crease((150.0, 0.0), (150.0, 50.0), 3), + crease((250.0, 0.0), (250.0, 50.0), 4), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(200.0, 25.0)).expect("the base panel"); + let (lid, wall) = (panel_at(b, p(60.0, 25.0)).unwrap(), panel_at(b, p(280.0, 25.0)).unwrap()); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + assert_eq!(f.collisions, vec![(lid.min(wall), lid.max(wall))]); + // Half folded, nothing crosses yet. + assert!(fold(b, Some(base), 0.4, TOL).expect("folds").collisions.is_empty()); +} + +#[test] +fn the_base_is_the_panel_under_a_point_and_the_same_in_any_input_order() { + let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), crease((50.0, 0.0), (50.0, 60.0), 2)]; + let (b, _) = check(&lines); + assert_eq!(panel_at(&b[0], p(500.0, 500.0)), None, "a point outside every panel"); + let right = panel_at(&b[0], p(75.0, 30.0)).expect("the right panel"); + assert_eq!(fold(&b[0], Some(right), 1.0, TOL).expect("folds").base, right); + let mut reversed = lines.clone(); + reversed.reverse(); + let (r, _) = check(&reversed); + for blank in [&b[0], &r[0]] { + let f = fold(blank, None, 1.0, TOL).expect("folds"); + // Equal panels: the leftmost wins. + assert_eq!(blank.panels[f.base].outline.bounds().map(|r| r.x0.round()), Some(0.0)); + } + assert!(fold(&b[0], Some(9), 1.0, TOL).is_none(), "no panel 9"); + assert!(fold(&b[0], None, 1.5, TOL).is_none(), "past 1"); + assert!(fold(&b[0], None, f64::NAN, TOL).is_none()); + assert!(fold(&Blank::default(), None, 1.0, TOL).is_none(), "no panels"); +} + +#[test] +fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { + let (b, _) = check(&two_panels(LineKind::PartialCut, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, -90.0); + let (b, _) = check(&two_panels(LineKind::Perforation, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, 90.0); + // A crease and a short partial cut on one line: the crease is the longer piece. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + line(LineKind::PartialCut, &[(60.0, 0.0), (60.0, 10.0)], false, 2), + crease((60.0, 10.0), (60.0, 60.0), 3), + ]; + let (b, _) = check(&lines); + assert_eq!(b[0].hinges.len(), 1); + assert_eq!(b[0].hinges[0].angle, 90.0); } diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 5b37b52abf..3f4d2e4551 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -4,7 +4,8 @@ //! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that //! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu //! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each -//! with a Select button; each document's list is kept until that document changes. +//! with a Select button; each document's list is kept until that document changes. Its Fold Preview +//! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`). use std::collections::HashMap; use std::sync::{Arc, Weak}; @@ -26,6 +27,8 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that shows the Fold Preview window. +pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. pub const ROLES: &[(&str, &str)] = &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; @@ -47,6 +50,8 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Item::Sep, Item::Cmd("Check Fold Lines", CHECK, Value::Null), + Item::Sep, + Item::Cmd("Fold Preview", PREVIEW, json!({})), ] } @@ -160,6 +165,11 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::flat_button(ui, tl!("Check"), width).clicked() { run_check(app, ui.ctx(), json!({})); } + if widgets::flat_button(ui, tl!("Fold Preview"), width).clicked() + && let Err(e) = app.run(PREVIEW, json!({})) + { + app.status(e); + } let Some(checked) = last_check(app, ui.ctx()) else { return }; ui.add_space(4.0); dim_label(ui, &crate::i18n::msg(&checked.summary())); @@ -285,5 +295,7 @@ pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +pub mod preview; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs new file mode 100644 index 0000000000..97a8ebd988 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -0,0 +1,705 @@ +//! The Fold Preview window: the document's blank folded into its 3D shape +//! ([`vectorcraft_three_d::fold::fold`]), with the printed art on the outside of each panel and the +//! board's inside color on the back, drawn by [`vectorcraft_three_d::fold::raster::render`]. +//! +//! The window folds the blank that the document's shown fold lines make, about its largest panel +//! or the panel the user double-clicked. Its print is a raster of the document with the fold lines +//! and the layers that do not print left out ([`vectorcraft_engine::cmd::print_hidden`]), rendered +//! once per document revision, off the UI thread on native builds ([`crate::thumb_worker`]), and +//! sampled through each panel's projective map when the fold, the view or the print changes. Dragging turns the view, a Shift-drag +//! keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a +//! panel makes it the base, and the arrow keys turn the view by 5° when it has the keyboard focus. +//! The settings live in `UiState::fold_preview` (`ui.inspect`); `ui.foldPreview` sets them. + +use std::sync::Arc; + +use egui::{Color32, Rect, Sense, Ui, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect as DRect}; +use vectorcraft_three_d::fold::raster::{self, Camera, Image, MAX_PIXELS, MAX_SIDE, Print}; +use vectorcraft_three_d::fold::{Blank, Folded, fold, pick}; + +use crate::VectorcraftApp; +use crate::thumb_worker::{Settle, ThumbWorker}; +use crate::widgets::{self, dim_label}; + +/// The window's id (`window.panel {panel: "foldPreview"}`). +pub const ID: &str = "foldPreview"; + +/// The view presets: label, id, the turn about x (the top toward the viewer) and about y (the +/// right side toward the viewer), in degrees. +pub const VIEWS: [(&str, &str, f64, f64); 7] = [ + ("Front", "front", 0.0, 0.0), + ("Back", "back", 0.0, 180.0), + ("Left", "left", 0.0, -90.0), + ("Right", "right", 0.0, 90.0), + ("Top", "top", 90.0, 0.0), + ("Bottom", "bottom", -90.0, 0.0), + ("Three-Quarter", "threeQuarter", 25.0, 35.0), +]; + +/// The tolerance the window folds with (points), as Check Fold Lines' default. +const TOLERANCE: f64 = 0.1; +/// The share of the view's shorter side the folded blank fills at a zoom of 1. +const FIT: f64 = 0.45; +/// The print raster's longest side, in pixels, and the fewest pixels it gives a point. +const PRINT_SIDE: f64 = 2048.0; +/// Degrees the view turns for each point dragged, and for each arrow key press. +const DRAG_TURN: f64 = 0.5; +const KEY_TURN: f64 = 5.0; + +/// The window's settings (kept with the UI state). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Settings { + /// How far the blank is folded: 0 flat, 1 every hinge at its angle. + pub amount: f64, + /// The view's turn, in degrees (see [`VIEWS`]). + pub rotate_x: f64, + pub rotate_y: f64, + /// The zoom: 1 fits the folded blank in the view. + pub zoom: f64, + /// How far the view is moved, in points. + pub pan: [f64; 2], + /// The field of view in degrees; 0 for none. + pub perspective: f64, + /// The board's inside color: `#rrggbb`, the name of a swatch, or empty for white. + pub inside: String, + /// Draw the fold lines on the print. + pub show_fold_lines: bool, + /// The base panel: the one under this point (document coordinates); the largest when `None`. + pub base: Option<[f64; 2]>, +} + +impl Default for Settings { + fn default() -> Self { + let (_, _, rotate_x, rotate_y) = VIEWS[6]; + Self { + amount: 1.0, + rotate_x, + rotate_y, + zoom: 1.0, + pan: [0.0; 2], + perspective: 0.0, + inside: String::new(), + show_fold_lines: false, + base: None, + } + } +} + +impl Settings { + /// The view preset these settings show, if any. + fn view(&self) -> Option<&'static (&'static str, &'static str, f64, f64)> { + VIEWS.iter().find(|v| (v.2 - self.rotate_x).abs() < 1e-9 && (v.3 - self.rotate_y).abs() < 1e-9) + } + + /// These settings with every value in the range `ui.foldPreview` allows: saved UI state is read + /// as it was stored. A value that is not a number takes its default. + fn clamped(mut self) -> Self { + let within = |v: f64, lo: f64, hi: f64, or: f64| if v.is_finite() { v.clamp(lo, hi) } else { or }; + let turn = |v: f64| if (-180.0..=180.0).contains(&v) { v } else { wrapped(v) }; + let fresh = Settings::default(); + self.amount = within(self.amount, 0.0, 1.0, fresh.amount); + self.zoom = within(self.zoom, 0.1, 8.0, fresh.zoom); + self.perspective = within(self.perspective, 0.0, 160.0, fresh.perspective); + (self.rotate_x, self.rotate_y) = (turn(self.rotate_x), turn(self.rotate_y)); + self.pan = self.pan.map(|v| if v.is_finite() { v } else { 0.0 }); + self.base = self.base.filter(|b| b.iter().all(|v| v.is_finite())); + self + } +} + +/// `angle` (degrees) brought into -180 to 180. +fn wrapped(angle: f64) -> f64 { + let a = (angle + 180.0).rem_euclid(360.0) - 180.0; + if a.is_finite() { a } else { 0.0 } +} + +/// What the print raster shows: the document, its revision, whether the fold lines are drawn, and +/// the region and size. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PrintKey { + uid: u64, + revision: u64, + fold_lines: bool, + region: [u64; 4], + width: u32, + height: u32, +} + +/// The last frame drawn: its size in pixels and how long the fold and the drawing took (ms). +#[derive(Clone, Copy, Debug, Default)] +struct Frame { + width: u32, + height: u32, + fold_ms: f64, + draw_ms: f64, +} + +/// A document's blanks and whether its fold lines have an error, by (uid, revision). +type Blanks = ((u64, u64), Arc>, bool); + +/// What a fold folds: the document (uid, revision), the blank, the base panel and the amount's bits. +type FoldKey = (u64, u64, usize, usize, u64); + +/// What the last image shows: the fold, the camera, the inside color and the print. +#[derive(Clone, Copy, Debug, PartialEq)] +struct DrawKey { + fold: FoldKey, + camera: Camera, + inside: [u8; 4], + print: Option, +} + +#[derive(Default)] +struct Cache { + blanks: Option, + /// The last fold, what it folds and how long it took (ms). + folded: Option<(FoldKey, Arc, f64)>, + /// What the texture shows. + drawn: Option, + /// Folds worked out and images rendered (tests count them). + folds: u64, + renders: u64, + /// The print shown and what it shows. + print: Option<(PrintKey, Arc)>, + /// Renders the print off the UI thread (None: on this thread). + worker: Option>, + worker_started: bool, + pending: Option, + settle: Settle, + tex: Option, + /// The last frame's image, for double-click picking, and the screen rect it filled. + image: Option<(Image, Rect)>, + frame: Option, + /// Prints rendered (tests count them). + prints: u64, +} + +thread_local! { + static CACHE: crate::graphics::TexCache = crate::graphics::TexCache::default(); + static RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); +} + +/// The board's inside color (straight RGBA) for `inside`: white when it is empty, a swatch of `d` +/// with a plain color, or else `#rrggbb`; `None` for anything else. +fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { + if inside.is_empty() { + return Some([255; 4]); + } + match d.swatch(inside).map(|s| &s.paint) { + Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)), + _ => None, + } +} + +/// The document rect a print of `blank` covers: its panels' bounds, with a point to spare. +fn print_region(blank: &Blank) -> Option { + let r = blank.panels.iter().filter_map(|p| p.outline.bounds()).reduce(|a, b| a.union(b))?; + let r = r.inflate(1.0, 1.0); + (r.width() > 0.0 && r.height() > 0.0 && r.is_finite()).then_some(r) +} + +/// The pixel size of the print of `region`: its longest side [`PRINT_SIDE`]. +fn print_size(region: DRect) -> (u32, u32, f64) { + let scale = PRINT_SIDE / region.width().max(region.height()); + let side = |len: f64| ((len * scale).ceil() as u32).clamp(1, MAX_SIDE); + (side(region.width()), side(region.height()), scale) +} + +impl Cache { + /// The blanks of document `uid` at `revision`, worked out again only when it changed. + fn blanks(&mut self, uid: u64, revision: u64, d: &vectorcraft_engine::doc::Document) -> (Arc>, bool) { + if let Some((key, blanks, errors)) = &self.blanks + && *key == (uid, revision) + { + return (blanks.clone(), *errors); + } + let (blanks, issues) = vectorcraft_engine::cmd::fold_source(d); + let errors = issues.iter().any(|i| i.code.is_error()); + let blanks = Arc::new(blanks); + self.blanks = Some(((uid, revision), blanks.clone(), errors)); + (blanks, errors) + } + + /// `blank` folded about `panel` by `amount` (what `key` names), worked out again only when the + /// key changed, and how long that took (ms). + fn fold(&mut self, key: FoldKey, blank: &Blank, panel: usize, amount: f64) -> Option<(Arc, f64)> { + if let Some((k, f, ms)) = &self.folded + && *k == key + { + return Some((f.clone(), *ms)); + } + let t0 = crate::now_ms(); + let f = Arc::new(fold(blank, Some(panel), amount, TOLERANCE)?); + let ms = crate::now_ms() - t0; + self.folded = Some((key, f.clone(), ms)); + self.folds += 1; + Some((f, ms)) + } + + /// Bring the print up to `key`: on the worker when there is one, else here, and not before the + /// document has settled unless there is no print of it yet. + fn update_print(&mut self, ctx: &egui::Context, doc: &Arc, key: PrintKey, region: DRect, scale: f64) { + if !self.worker_started { + self.worker_started = true; + self.worker = ThumbWorker::spawn(ctx, "fold-preview"); + } + let done = match self.worker.as_ref().map(ThumbWorker::poll) { + Some(Some(done)) => done, + Some(None) => { + (self.worker, self.pending) = (None, None); + vec![] + } + None => vec![], + }; + for d in done { + if self.pending == Some(d.key) { + self.pending = None; + } + if let Some(img) = d.img { + self.keep_print(d.key, img); + } + } + let shown = self.print.as_ref().map(|(k, _)| *k); + if shown == Some(key) || self.pending == Some(key) { + return; + } + let have = shown.is_some_and(|k| k.uid == key.uid); + if have && !self.settle.settled(ctx, key.uid, key.revision, ctx.input(|i| i.time)) { + return; + } + let opts = vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines), + ..Default::default() + }; + if let Some(w) = &self.worker { + let (doc, opts) = (doc.clone(), opts.clone()); + if w.submit((), key, Box::new(move |r| Some(r.render_region_with(&doc, region, scale, &opts)))) { + self.pending = Some(key); + return; + } + self.worker = None; + } + let img = RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, scale, &opts)); + self.keep_print(key, img); + } + + /// The print to draw for `want`: the one shown when it is of the same document, blank region and + /// Show Fold Lines setting (an older revision while the new one renders), else none. + fn print_for(&self, want: &PrintKey) -> Option<(PrintKey, Arc)> { + let same = |k: &PrintKey| (k.uid, k.fold_lines, k.region) == (want.uid, want.fold_lines, want.region); + self.print.as_ref().filter(|(k, _)| same(k)).map(|(k, p)| (*k, p.clone())) + } + + fn keep_print(&mut self, key: PrintKey, img: vectorcraft_render::Rendered) { + let region = + DRect::new(f64::from_bits(key.region[0]), f64::from_bits(key.region[1]), f64::from_bits(key.region[2]), f64::from_bits(key.region[3])); + if let Some(print) = Print::new(region, img.width, img.height, img.pixels) { + self.print = Some((key, Arc::new(print))); + self.prints += 1; + } + } +} + +/// `ui.foldPreview {amount?, view?, rotateX?, rotateY?, zoom?, perspective?, inside?, +/// showFoldLines?, base?}`: set the window's settings, show it, and answer with them and the last +/// frame's size and times. A value of the wrong kind or out of range is an error, and nothing is +/// set. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + let mut set = app.ui.fold_preview.clone(); + let number = |key: &str, lo: f64, hi: f64| -> Result, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(n) if (lo..=hi).contains(&n) => Ok(Some(n)), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + }, + } + }; + if let Some(a) = number("amount", 0.0, 1.0)? { + set.amount = a; + } + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => { + let (_, _, x, y) = v + .as_str() + .and_then(|v| VIEWS.iter().find(|view| view.1 == v)) + .ok_or_else(|| format!("`view` must be one of {}", VIEWS.iter().map(|v| v.1).collect::>().join(", ")))?; + (set.rotate_x, set.rotate_y) = (*x, *y); + } + } + if let Some(x) = number("rotateX", -180.0, 180.0)? { + set.rotate_x = x; + } + if let Some(y) = number("rotateY", -180.0, 180.0)? { + set.rotate_y = y; + } + if let Some(z) = number("zoom", 0.1, 8.0)? { + set.zoom = z; + } + if let Some(v) = number("perspective", 0.0, 160.0)? { + set.perspective = v; + } + match p.get("inside") { + None | Some(Value::Null) => {} + Some(v) => { + let inside = v.as_str().filter(|inside| { + inside.is_empty() + || app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() + || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()) + }); + let Some(inside) = inside else { + return Err(format!("`inside` must be #rrggbb, the name of a swatch with a plain color, or empty for white, not {v}")); + }; + set.inside = inside.to_string(); + } + } + match p.get("showFoldLines") { + None | Some(Value::Null) => {} + Some(v) => set.show_fold_lines = v.as_bool().ok_or("`showFoldLines` must be true or false")?, + } + match p.get("base") { + None => {} + Some(Value::Null) => set.base = None, + Some(v) => { + let a = v.as_array().filter(|a| a.len() == 2); + let xy: Option> = a.map(|a| a.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect()); + let Some(&[x, y]) = xy.as_deref() else { return Err("`base` must be a point: [x, y], or null".into()) }; + let blanks = app.session.active().map(|st| vectorcraft_engine::cmd::fold_source(&st.doc).0).unwrap_or_default(); + if pick(&blanks, Some(Point::new(x, y))).is_none() { + return Err("`base` is in no panel".into()); + } + set.base = Some([x, y]); + } + } + if p.get("view").is_some_and(|v| !v.is_null()) || p.get("zoom").is_some_and(|v| !v.is_null()) { + set.pan = [0.0; 2]; + } + app.ui.fold_preview = set; + crate::panel_docking::reveal_panel(app, ID)?; + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + Ok(state(app)) +} + +/// The window's settings and the last frame's size and times. +fn state(app: &VectorcraftApp) -> Value { + let frame = CACHE.with(|c| c.borrow().frame); + let mut out = serde_json::to_value(&app.ui.fold_preview).unwrap_or_default(); + if let Some(o) = out.as_object_mut() { + o.insert( + "frame".into(), + frame.map_or(Value::Null, |f| json!({"width": f.width, "height": f.height, "foldMs": f.fold_ms, "drawMs": f.draw_ms})), + ); + } + out +} + +/// The toolbar: the view presets, Perspective, Inside, Show Fold Lines and Reset. +fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) { + ui.horizontal_wrapped(|ui| { + let labels: Vec<&str> = VIEWS.iter().map(|v| v.0).collect(); + let current = set.view().map_or("", |v| v.0); + if let Some(i) = widgets::dropdown_named(ui, "fold-preview-view", Some(tl!("View")), current, &labels, 120.0) + && let Some(&(_, _, x, y)) = VIEWS.get(i) + { + (set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]); + } + let swatches: Vec = app.session.active().map_or_else(Vec::new, |st| { + st.doc.swatches.iter().filter(|s| matches!(s.paint, vectorcraft_color::Paint::Solid { .. })).map(|s| s.name.clone()).collect() + }); + let mut names: Vec<&str> = vec![tl!("White")]; + names.extend(swatches.iter().map(String::as_str)); + let shown = if set.inside.is_empty() { tl!("White") } else { set.inside.as_str() }; + ui.label(tl!("Inside")); + if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) { + set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_default(); + } + if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) { + set.show_fold_lines = !set.show_fold_lines; + } + if widgets::flat_button_fit(ui, tl!("Reset"), 48.0).clicked() { + let fresh = Settings::default(); + (set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective) = (fresh.rotate_x, fresh.rotate_y, 1.0, [0.0; 2], 0.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Perspective")); + widgets::slider(ui, egui::Slider::new(&mut set.perspective, 0.0..=160.0).suffix("°").fixed_decimals(0)); + }); +} + +/// The Fold and Zoom sliders. +fn sliders(ui: &mut Ui, set: &mut Settings) { + ui.horizontal(|ui| { + ui.label(tl!("Fold")); + let mut percent = set.amount * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 0.0..=100.0).suffix("%").fixed_decimals(0)).changed() { + set.amount = (percent / 100.0).clamp(0.0, 1.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Zoom")); + let mut percent = set.zoom * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 10.0..=800.0).suffix("%").fixed_decimals(0).logarithmic(true)).changed() { + set.zoom = (percent / 100.0).clamp(0.1, 8.0); + } + }); +} + +/// Turns, moves and zooms the view with the pointer, the wheel and the arrow keys, and picks the +/// base panel of `blank` (the blank `key` folds) on a double-click. +fn interact(ui: &Ui, response: &egui::Response, set: &mut Settings, blank: Option<(&Blank, FoldKey)>) { + if response.clicked() || response.drag_started() { + response.request_focus(); + } + let (shift, space) = ui.input(|i| (i.modifiers.shift, i.key_down(egui::Key::Space))); + let delta = response.drag_delta(); + if delta != egui::Vec2::ZERO { + if response.dragged_by(egui::PointerButton::Middle) || (space && response.dragged_by(egui::PointerButton::Primary)) { + set.pan[0] += f64::from(delta.x); + set.pan[1] += f64::from(delta.y); + } else if response.dragged_by(egui::PointerButton::Primary) { + let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y)); + if shift { + if dx.abs() >= dy.abs() { + dy = 0.0; + } else { + dx = 0.0; + } + } + set.rotate_y = wrapped(set.rotate_y + dx * DRAG_TURN); + set.rotate_x = wrapped(set.rotate_x + dy * DRAG_TURN); + } + } + if response.hovered() { + let scroll = f64::from(ui.input(|i| i.smooth_scroll_delta.y + (i.zoom_delta() - 1.0) * 200.0)); + if scroll != 0.0 { + set.zoom = (set.zoom * (scroll * 0.002).exp()).clamp(0.1, 8.0); + } + } + if response.has_focus() { + // The view keeps the arrow keys, so they turn it rather than move the focus on. + ui.memory_mut(|m| { + m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let presses = |key| ui.input_mut(|i| i.count_and_consume_key(egui::Modifiers::NONE, key)) as f64 * KEY_TURN; + let (left, right, up, down) = + (presses(egui::Key::ArrowLeft), presses(egui::Key::ArrowRight), presses(egui::Key::ArrowUp), presses(egui::Key::ArrowDown)); + if left + right + up + down > 0.0 { + set.rotate_y = wrapped(set.rotate_y + right - left); + set.rotate_x = wrapped(set.rotate_x + down - up); + } + } + if response.double_clicked() + && let Some(pos) = response.interact_pointer_pos() + && let Some((blank, key)) = blank + { + // The image on screen is the last one drawn; its panel numbers are used only while it shows + // the same blank of the same document revision. + let picked = CACHE.with(|c| { + let c = c.borrow(); + let shown = c.drawn.map(|d| (d.fold.0, d.fold.1, d.fold.2)); + if shown != Some((key.0, key.1, key.2)) { + return None; + } + let (img, rect) = c.image.as_ref()?; + let x = (pos.x - rect.left()) / rect.width() * img.width as f32; + let y = (pos.y - rect.top()) / rect.height() * img.height as f32; + img.panel_at(x.max(0.0) as u32, y.max(0.0) as u32) + }); + if let Some(p) = picked.and_then(|i| blank.panels.get(i)).and_then(|p| p.point_inside()) { + set.base = Some([p.x, p.y]); + } + } +} + +/// The status line under the view, in English (shown translated). +fn status(blanks: usize, folded: Option<(&Blank, &Folded)>, errors: bool) -> Vec { + let Some((blank, f)) = folded else { + return vec!["Check the fold lines first.".into()]; + }; + let mut out = vec![crate::i18n::fmt( + "Panels: {panels}, hinges: {hinges}", + &[("panels", &blank.panels.len().to_string()), ("hinges", &blank.hinges.len().to_string())], + )]; + if errors { + out.push("Check the fold lines first.".into()); + } + if blanks > 1 { + out.push(crate::i18n::fmt("Other blanks not shown: {count}", &[("count", &(blanks - 1).to_string())])); + } + if let Some(gap) = f.hinges.iter().filter(|h| !h.closes).map(|h| h.gap).reduce(f64::max) { + out.push(crate::i18n::fmt("A joint does not close by {gap} pt.", &[("gap", &format!("{gap:.1}"))])); + } + if !f.collisions.is_empty() { + out.push("Two panels pass through each other.".into()); + } + out +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + crate::panels::empty_state(ui, "box", tl!("No document"), tl!("Open a document to preview its folded shape.")); + return; + }; + let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone()); + let mut set = app.ui.fold_preview.clone().clamped(); + toolbar(app, ui, &mut set); + let (blanks, errors) = CACHE.with(|c| c.borrow_mut().blanks(uid, revision, &doc)); + let base_point = set.base.map(|[x, y]| Point::new(x, y)); + let picked = pick(&blanks, base_point).or_else(|| pick(&blanks, None)); + let folded = picked.and_then(|(b, panel)| { + let blank = blanks.get(b)?; + let key = (uid, revision, b, panel, set.amount.to_bits()); + let (f, ms) = CACHE.with(|c| c.borrow_mut().fold(key, blank, panel, set.amount))?; + Some((blank, f, key, ms)) + }); + + let bottom = ui.spacing().interact_size.y * 3.0 + 12.0; + let size = vec2(ui.available_width().max(64.0), (ui.available_height() - bottom).max(64.0)); + let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag()); + let view_name = set.view().map_or("", |v| v.0); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Fold Preview")); + info.current_text_value = Some(crate::i18n::t(view_name).to_string()); + info + }); + interact(ui, &response, &mut set, folded.as_ref().map(|(b, _, key, _)| (*b, *key))); + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, 2.0, t.pasteboard); + if let Some((blank, f, key, fold_ms)) = &folded { + draw(ui, rect, &doc, *key, blank, f, &set, *fold_ms); + } + if response.has_focus() { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } + for line in status(blanks.len(), folded.as_ref().map(|(b, f, ..)| (*b, &**f)), errors) { + dim_label(ui, &crate::i18n::msg(&line)); + } + sliders(ui, &mut set); + if set != app.ui.fold_preview { + app.ui.fold_preview = set; + } +} + +/// Draws `blank` folded as `f` (the fold `key` names) into `rect`, with the print of `doc`. The image +/// is rendered again only when the fold, the view, the inside color or the print changed. +#[allow(clippy::too_many_arguments)] +fn draw(ui: &Ui, rect: Rect, doc: &Arc, key: FoldKey, blank: &Blank, f: &Folded, set: &Settings, fold_ms: f64) { + // Pixels per point of the view, lowered when the window has more pixels than the view may have + // in all or along either side, so the image keeps the window's proportions. + let (w, h) = (f64::from(rect.width()), f64::from(rect.height())); + let mut ppp = f64::from(ui.ctx().pixels_per_point()); + let area = w * h * ppp * ppp; + if area > f64::from(MAX_PIXELS) { + ppp *= (f64::from(MAX_PIXELS) / area).sqrt(); + } + ppp = ppp.min(f64::from(MAX_SIDE) / w.max(h).max(1.0)); + let width = ((w * ppp).floor() as u32).clamp(1, MAX_SIDE); + let height = ((h * ppp).floor() as u32).clamp(1, MAX_SIDE); + let Some((lo, hi)) = raster::bounds(blank, f) else { return }; + let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0]; + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() / 2.0; + let mut fit = FIT * f64::from(width.min(height)) / radius.max(1e-6); + if set.perspective > 0.0 { + // The eye at two radii from the middle or farther, so at a zoom of 1 the whole blank is in + // front of it. + let focal = f64::from(width.min(height)) / 2.0 / (set.perspective.to_radians() / 2.0).tan(); + fit = fit.min(focal / (2.0 * radius.max(1e-6))); + } + let camera = Camera { + width, + height, + rotate_x: set.rotate_x, + rotate_y: set.rotate_y, + scale: fit * set.zoom, + pan: [set.pan[0] * ppp, set.pan[1] * ppp], + perspective: set.perspective, + center, + }; + let inside = inside_color(doc, &set.inside).unwrap_or([255; 4]); + // While the print of a new revision renders, the last one of the same blank and setting is + // drawn; a print of another document, blank or Show Fold Lines setting is not. + let print = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let region = print_region(blank)?; + let (pw, ph, scale) = print_size(region); + let pkey = PrintKey { + uid: key.0, + revision: key.1, + fold_lines: set.show_fold_lines, + region: [region.x0.to_bits(), region.y0.to_bits(), region.x1.to_bits(), region.y1.to_bits()], + width: pw, + height: ph, + }; + c.update_print(ui.ctx(), doc, pkey, region, scale); + c.print_for(&pkey) + }); + let draw_key = DrawKey { fold: key, camera, inside, print: print.as_ref().map(|(k, _)| *k) }; + let kept = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let Some(tex) = c.tex.as_ref().filter(|_| c.drawn == Some(draw_key)).map(|t| t.id()) else { return false }; + ui.painter().image(tex, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + if let Some((_, at)) = &mut c.image { + *at = rect; + } + true + }); + if kept { + return; + } + let t0 = crate::now_ms(); + let scene = raster::Scene { blank, folded: f, print: print.as_ref().map(|(_, p)| &**p), inside, outside: [255; 4], camera }; + let Some(img) = raster::render(&scene) else { return }; + let draw_ms = crate::now_ms() - t0; + let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + c.drawn = Some(draw_key); + c.renders += 1; + match &mut c.tex { + Some(tex) => tex.set(color, egui::TextureOptions::LINEAR), + None => c.tex = Some(ui.ctx().load_texture("fold-preview", color, egui::TextureOptions::LINEAR)), + } + if let Some(tex) = &c.tex { + let uv = Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + ui.painter().image(tex.id(), rect, uv, Color32::WHITE); + } + c.frame = Some(Frame { width: img.width, height: img.height, fold_ms, draw_ms }); + c.image = Some((img, rect)); + }); +} + +#[cfg(test)] +pub(crate) fn prints_rendered() -> u64 { + CACHE.with(|c| c.borrow().prints) +} + +#[cfg(test)] +pub(crate) fn last_image() -> Option { + CACHE.with(|c| c.borrow().image.as_ref().map(|(i, _)| i.clone())) +} + +/// The folds worked out and the images rendered so far. +#[cfg(test)] +pub(crate) fn work_done() -> (u64, u64) { + CACHE.with(|c| (c.borrow().folds, c.borrow().renders)) +} + +/// The screen rect the last image filled. +#[cfg(test)] +pub(crate) fn last_rect() -> Option { + CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs new file mode 100644 index 0000000000..c3c69c3f31 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -0,0 +1,505 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use std::sync::Arc; + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; + +use super::{Cache, ID, PrintKey, Settings, inside_color, last_image, last_rect, prints_rendered, show, status, work_done}; +use crate::{VectorcraftApp, menus}; + +/// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each +/// side) and a red square printed on the base, nothing selected → (app, the red square's id). +fn app() -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = [ + path(&mut app, "M140 140 L240 140"), + path(&mut app, "M240 140 L240 240"), + path(&mut app, "M240 240 L140 240"), + path(&mut app, "M140 240 L140 140"), + ]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + let red = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("paint.setFill", json!({ "color": "#ff0000" })).unwrap(); + app.run("paint.setStroke", json!({ "none": true })).unwrap(); + app.run("object.arrange.sendToBack", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, red) +} + +/// Draws the window in a 520 × 440 frame, twice (egui lays out on the first). +fn frame(app: &mut VectorcraftApp) { + frame_at(app, 1.0); +} + +/// [`frame`] at `zoom` pixels per point. +fn frame_at(app: &mut VectorcraftApp, zoom: f32) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(zoom); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(520.0, 440.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } +} + +fn color_at(img: &vectorcraft_three_d::fold::raster::Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// The color at the middle of the window's last image. +fn middle(img: &vectorcraft_three_d::fold::raster::Image) -> [u8; 4] { + color_at(img, img.width / 2, img.height / 2) +} + +#[test] +fn the_menu_item_and_the_panel_button_show_the_window_and_a_second_run_keeps_it() { + let (mut app, _) = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Fold Preview").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("ui.foldPreview"), &json!({}))); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "the window opens"); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "a second run leaves it open"); + let text = crate::tests_labels::painted_text(&mut app, super::super::show); + assert!(text.contains("Fold Preview"), "the Fold Lines panel has the button: {text}"); +} + +#[test] +fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { + let (mut app, _) = app(); + let r = app + .run( + "ui.foldPreview", + json!({"amount": 0.5, "view": "top", "zoom": 2, "perspective": 40, "inside": "#00ff00", "showFoldLines": true, "base": [120, 190]}), + ) + .unwrap(); + let want = Settings { + amount: 0.5, + rotate_x: 90.0, + rotate_y: 0.0, + zoom: 2.0, + pan: [0.0; 2], + perspective: 40.0, + inside: "#00ff00".into(), + show_fold_lines: true, + base: Some([120.0, 190.0]), + }; + assert_eq!(app.ui.fold_preview, want); + assert_eq!(r["rotateX"], 90.0, "{r}"); + assert!(r.get("frame").is_some(), "{r}"); + app.run("ui.foldPreview", json!({"rotateX": -30, "rotateY": 170, "base": null})).unwrap(); + assert_eq!((app.ui.fold_preview.rotate_x, app.ui.fold_preview.rotate_y, app.ui.fold_preview.base), (-30.0, 170.0, None)); + let kept = app.ui.fold_preview.clone(); + for (p, want) in [ + (json!({"amount": 2}), "`amount` must be a number from 0 to 1"), + (json!({"amount": "half"}), "`amount` must be a number from 0 to 1"), + (json!({"view": "sideways"}), "`view` must be one of"), + (json!({"rotateX": 200}), "`rotateX` must be a number from -180 to 180"), + (json!({"zoom": 0}), "`zoom` must be a number from 0.1 to 8"), + (json!({"perspective": 170}), "`perspective` must be a number from 0 to 160"), + (json!({"inside": "no such swatch"}), "`inside` must be #rrggbb"), + (json!({"inside": 7}), "`inside` must be #rrggbb"), + (json!({"showFoldLines": "yes"}), "`showFoldLines` must be true or false"), + (json!({"base": [1, "2"]}), "`base` must be a point"), + (json!({"base": [5, 5]}), "`base` is in no panel"), + (json!({"amount": 0.2, "zoom": 99}), "`zoom` must be a number"), + ] { + let e = app.run("ui.foldPreview", p.clone()).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + assert_eq!(app.ui.fold_preview, kept, "{p} sets nothing"); + } + // A swatch with a plain color names the inside. + app.run("ui.foldPreview", json!({"inside": "White"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "White"); + // So does one whose name starts with #, and a swatch's name comes before a #rrggbb that reads the same. + app.run("swatch.new", json!({"name": "#brand", "color": "#0000ff"})).unwrap(); + app.run("swatch.new", json!({"name": "#00ff00", "color": "#0000ff"})).unwrap(); + app.run("ui.foldPreview", json!({"inside": "#brand"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "#brand"); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255])); + // White, the default, stays white beside a swatch named #ffffff. + app.run("swatch.new", json!({"name": "#ffffff", "color": "#0000ff"})).unwrap(); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, &Settings::default().inside), Some([255; 4])); + assert_eq!(inside_color(doc, "#ffffff"), Some([0, 0, 255, 255])); + app.run("ui.foldPreview", json!({"inside": ""})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, ""); +} + +#[test] +fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs() { + let (mut app, _) = app(); + // Flat, from the front: the base's print, red, fills the middle. + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let before = prints_rendered(); + frame(&mut app); + assert!(prints_rendered() > before, "the print is rendered on this thread without a worker"); + let img = last_image().expect("a frame"); + let [r, g, b, a] = middle(&img); + assert!(r > 150 && g < 40 && b < 40 && a == 255, "red print: {:?}", [r, g, b, a]); + let state = app.run("ui.foldPreview", json!({})).unwrap(); + assert_eq!((state["frame"]["width"].as_u64(), state["frame"]["height"].as_u64()), (Some(u64::from(img.width)), Some(u64::from(img.height)))); + // From the back, the base's inside shows in the inside color. + app.run("ui.foldPreview", json!({"view": "back", "inside": "#00ff00"})).unwrap(); + frame(&mut app); + let [r, g, b, _] = middle(&last_image().expect("a frame")); + assert!(r < 40 && g > 150 && b < 40, "green inside: {:?}", [r, g, b]); + // Folded and seen from the front, the walls stand edge on: the base fills the same place. + app.run("ui.foldPreview", json!({"amount": 1, "view": "front"})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let [r, ..] = middle(&img); + assert!(r > 150, "the base still shows its print: {:?}", middle(&img)); + // The same print is not rendered again while the document does not change. + let prints = prints_rendered(); + frame(&mut app); + assert_eq!(prints_rendered(), prints); +} + +#[test] +fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() { + let (mut app, _) = app(); + // Without perspective, the base and the two walls behind it that face the viewer show. + let mut flat = None; + for perspective in [0, 60, 160] { + app.run("ui.foldPreview", json!({"amount": 1, "view": "threeQuarter", "zoom": 1, "perspective": perspective})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let mut shown: Vec = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter_map(|(x, y)| img.panel_at(x, y)).collect(); + shown.sort_unstable(); + shown.dedup(); + let flat = flat.get_or_insert_with(|| shown.clone()); + assert_eq!(flat.len(), 3); + assert_eq!(&shown, flat, "{perspective}°: the same panels show"); + let edge = (0..img.width).flat_map(|x| [(x, 0), (x, img.height - 1)]).chain((0..img.height).flat_map(|y| [(0, y), (img.width - 1, y)])); + assert!(edge.into_iter().all(|(x, y)| img.panel_at(x, y).is_none()), "{perspective}°: nothing reaches the edge of the view"); + } +} + +#[test] +fn a_window_with_more_pixels_than_the_view_may_have_is_drawn_smaller() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + frame_at(&mut app, 8.0); + let img = last_image().expect("a frame"); + assert!(u64::from(img.width) * u64::from(img.height) <= u64::from(vectorcraft_three_d::fold::raster::MAX_PIXELS), "{}×{}", img.width, img.height); + assert!(img.width > 1000, "still sharper than one pixel a point: {}", img.width); + let [r, ..] = middle(&img); + assert!(r > 150, "the base's print shows: {:?}", middle(&img)); +} + +#[test] +fn the_print_leaves_out_the_fold_lines_unless_they_are_shown() { + let (mut app, red) = app(); + // Without the red square, the base's middle shows the board with no art; with a crease drawn + // across the middle and the fold lines shown, the crease's color shows there. + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let mid = app.run("path.create", json!({ "d": "M140 190 L240 190" })).unwrap()["id"].as_u64().unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": [mid] })).unwrap(); + app.run("select.set", json!({ "ids": [mid] })).unwrap(); + app.run("stroke.set", json!({ "weight": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front", "zoom": 1})).unwrap(); + frame(&mut app); + let plain = middle(&last_image().expect("a frame")); + app.run("ui.foldPreview", json!({"showFoldLines": true})).unwrap(); + frame(&mut app); + let lined = middle(&last_image().expect("a frame")); + assert_ne!(plain, lined, "the crease shows only with Show Fold Lines on"); + assert!(plain[0] > 200 && plain[1] > 200 && plain[2] > 200, "the board is white where the print has no art: {plain:?}"); +} + +#[test] +fn the_window_says_when_there_is_nothing_to_fold() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Check the fold lines first."), "{text}"); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let text = crate::tests_labels::painted_text(&mut none, show); + assert!(text.contains("Open a document to preview its folded shape."), "{text}"); +} + +#[test] +fn the_settings_are_kept_with_the_ui_state() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0.25, "view": "left"})).unwrap(); + let saved: Value = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["fold_preview"]["amount"], 0.25, "{}", saved["fold_preview"]); + let back: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(back.fold_preview, app.ui.fold_preview); +} + +#[test] +fn saved_settings_out_of_range_are_brought_into_range() { + let (mut app, _) = app(); + app.ui.fold_preview = Settings { + amount: 3.0, + rotate_x: 200.0, + rotate_y: 180.0, + zoom: 0.0, + pan: [f64::NAN, 4.0], + perspective: -5.0, + base: Some([f64::INFINITY, 0.0]), + ..Settings::default() + }; + frame(&mut app); + let set = &app.ui.fold_preview; + assert_eq!( + (set.amount, set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective, set.base), + (1.0, -160.0, 180.0, 0.1, [0.0, 4.0], 0.0, None) + ); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Check the fold lines first."), "the blank folds: {text}"); + assert!(last_image().is_some(), "and is drawn"); +} + +/// A window kept open over frames, as the app draws it. +struct View { + ctx: egui::Context, + time: f64, +} + +impl View { + fn new(app: &mut VectorcraftApp) -> Self { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = View { ctx, time: 0.0 }; + v.idle(app); + v + } + + fn step(&mut self, app: &mut VectorcraftApp, events: Vec, modifiers: Modifiers) { + self.time += 0.05; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(520.0, 440.0)); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } + + fn idle(&mut self, app: &mut VectorcraftApp) { + for _ in 0..3 { + self.step(app, vec![], Modifiers::NONE); + } + } + + /// Presses `button` at `at`, drags by `by` in four steps and lets go, holding `modifiers`. + fn drag(&mut self, app: &mut VectorcraftApp, at: Pos2, by: egui::Vec2, button: PointerButton, modifiers: Modifiers) { + let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers }; + self.step(app, vec![Event::PointerMoved(at)], modifiers); + self.step(app, vec![press(at, true)], modifiers); + for k in 1..=4 { + self.step(app, vec![Event::PointerMoved(at + by * (k as f32 / 4.0))], modifiers); + } + self.step(app, vec![press(at + by, false)], modifiers); + self.idle(app); + } + + fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) { + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + self.step(app, vec![Event::PointerMoved(at)], Modifiers::NONE); + self.step(app, vec![press(true)], Modifiers::NONE); + self.step(app, vec![press(false)], Modifiers::NONE); + } + + fn key(&mut self, app: &mut VectorcraftApp, key: egui::Key) { + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + self.step(app, vec![press], Modifiers::NONE); + self.step(app, vec![], Modifiers::NONE); + } +} + +/// The app showing the tray flat from the front, in a [`View`], and the middle of the view. +fn front_view() -> (VectorcraftApp, View, Pos2) { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let view = View::new(&mut app); + let at = last_rect().expect("the view is drawn").center(); + (app, view, at) +} + +#[test] +fn a_drag_turns_the_view_and_a_shift_drag_keeps_to_one_axis() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_y <= 20.0 + 1e-9, "{set:?}"); + assert!(set.rotate_x > 2.0 && set.rotate_x <= 10.0 + 1e-9, "{set:?}"); + app.run("ui.foldPreview", json!({"view": "front"})).unwrap(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::SHIFT); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_x == 0.0, "only the larger move turns the view: {set:?}"); +} + +#[test] +fn a_middle_drag_moves_the_view_and_the_wheel_zooms_it() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(30.0, -10.0), PointerButton::Middle, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.pan[0] > 0.0 && set.pan[1] < 0.0, "{set:?}"); + assert_eq!((set.rotate_x, set.rotate_y), (0.0, 0.0), "the view does not turn"); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 60.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }; + view.step(&mut app, vec![Event::PointerMoved(at), wheel], Modifiers::NONE); + for _ in 0..20 { + view.step(&mut app, vec![], Modifiers::NONE); + } + assert!(app.ui.fold_preview.zoom > 1.05, "{:?}", app.ui.fold_preview); +} + +#[test] +fn the_arrow_keys_turn_the_focused_view_and_keep_the_focus() { + let (mut app, mut view, at) = front_view(); + view.click(&mut app, at); + view.idle(&mut app); + // Up first: the toolbar is above the view, where the focus would go if the view let it. + view.key(&mut app, egui::Key::ArrowUp); + view.key(&mut app, egui::Key::ArrowRight); + view.key(&mut app, egui::Key::ArrowRight); + let set = &app.ui.fold_preview; + assert_eq!((set.rotate_x, set.rotate_y), (-5.0, 10.0), "every press turns the view by 5°"); + // A focused view seen from the back stays there until a key turns it. + app.run("ui.foldPreview", json!({"view": "back"})).unwrap(); + view.idle(&mut app); + assert_eq!(app.ui.fold_preview.rotate_y, 180.0); +} + +#[test] +fn a_double_click_on_a_panel_makes_it_the_base() { + let (mut app, mut view, at) = front_view(); + // The left wall is the base; the middle of the view shows the tray's base panel. + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + view.click(&mut app, at); + let [x, y] = app.ui.fold_preview.base.expect("a base"); + assert!((140.0..240.0).contains(&x) && (140.0..240.0).contains(&y), "the base panel is picked: {x}, {y}"); +} + +#[test] +fn a_double_click_as_the_document_changes_picks_nothing_from_the_old_image() { + let (mut app, mut view, at) = front_view(); + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + view.step(&mut app, vec![press(true)], Modifiers::NONE); + // The document changes between the image on screen and the release that ends the double-click. + app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap(); + view.step(&mut app, vec![press(false)], Modifiers::NONE); + assert_eq!(app.ui.fold_preview.base, Some([120.0, 190.0]), "the base is kept"); +} + +#[test] +fn the_view_is_folded_and_drawn_again_only_when_something_changes() { + let (mut app, mut view, _) = front_view(); + let (folds, renders) = work_done(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders), "nothing changed: no fold and no render"); + app.run("ui.foldPreview", json!({"rotateY": 10})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders + 1), "a turn renders once and does not fold again"); + app.run("ui.foldPreview", json!({"amount": 0.5})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds + 1, renders + 2), "a new amount folds and renders once"); +} + +#[test] +fn a_short_wide_window_keeps_its_proportions() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(2200.0, 260.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + } + let (img, rect) = (last_image().expect("a frame"), last_rect().expect("a rect")); + let (image, window) = (f64::from(img.width) / f64::from(img.height), f64::from(rect.width() / rect.height())); + assert!(img.width <= vectorcraft_three_d::fold::raster::MAX_SIDE, "{}", img.width); + assert!((image - window).abs() / window < 0.02, "image {image}, window {window}"); +} + +#[test] +fn a_print_of_another_blank_or_setting_is_not_drawn_while_the_new_one_renders() { + let key = PrintKey { uid: 1, revision: 5, fold_lines: false, region: [0, 0, 10, 10], width: 1, height: 1 }; + let region = vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0); + let print = vectorcraft_three_d::fold::raster::Print::new(region, 1, 1, vec![255; 4]).expect("a print"); + let cache = Cache { print: Some((key, Arc::new(print))), ..Default::default() }; + assert!(cache.print_for(&PrintKey { revision: 6, ..key }).is_some(), "a newer revision of the same blank keeps the last print"); + for other in [PrintKey { uid: 2, ..key }, PrintKey { fold_lines: true, ..key }, PrintKey { region: [0, 0, 20, 10], ..key }] { + assert!(cache.print_for(&other).is_none(), "{other:?}"); + } +} + +#[test] +fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { + use vectorcraft_three_d::fold::{Blank, Folded, FoldedHinge}; + let hinge = |tree, closes, gap| FoldedHinge { a: 0, b: 1, angle: 90.0, tree, closes, gap }; + let f = Folded { + base: 0, + panels: vec![], + order: vec![], + hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], + collisions: vec![(0, 1)], + }; + let lines = status(3, Some((&Blank::default(), &f)), true); + assert_eq!( + lines, + [ + "Panels: 0, hinges: 0", + "Check the fold lines first.", + "Other blanks not shown: 2", + "A joint does not close by 12.3 pt.", + "Two panels pass through each other." + ] + ); + let f = Folded { hinges: vec![hinge(false, true, 0.05)], collisions: vec![], ..f }; + assert_eq!(status(1, Some((&Blank::default(), &f)), false), ["Panels: 0, hinges: 0"]); +} + +#[test] +fn the_window_says_when_folded_panels_pass_through_each_other() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. Folded + // about the base, the lid crosses the taller wall. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M0 0 L310 0 L310 50 L0 50 Z"); + let creases = [path(&mut app, "M120 0 L120 50"), path(&mut app, "M150 0 L150 50"), path(&mut app, "M250 0 L250 50")]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"base": [200, 25], "amount": 1})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Two panels pass through each other."), "{text}"); + assert!(!text.contains("A joint does not close"), "{text}"); +} diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index f8c3033a5e..e54085e304 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1382,7 +1382,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong)); if !held.is_empty() { - heading(ui, &format!("{}:", tl!("Remove Tool"))); + heading(ui, &crate::i18n::colon(tl!("Remove Tool"))); for tool in held.iter().filter_map(|id| tool_info(id)) { if widgets::menu_item(ui, tool.label, true, false) { actions.push(Action::RemoveTool(bar.name.clone(), tool.id)); @@ -1391,7 +1391,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & ui.separator(); } for (cat, tools) in crate::edit_toolbar::sections() { - heading(ui, &format!("{}:", tl!(cat))); + heading(ui, &crate::i18n::colon(tl!(cat))); for tool in tools { if widgets::menu_item(ui, tool.label, !held.contains(&tool.id), false) { actions.push(Action::AddTool(bar.name.clone(), tool.id)); diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 02515a3b89..b4abf8c6e2 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1073,7 +1073,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 3e95786f85..de7836f0a5 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -36,7 +36,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let mut rows = v.as_str() == Some("rows"); ui.add_space(4.0); egui::Grid::new("text-flow").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - let row = ui.label(egui::RichText::new(format!("{}:", tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); ui.label_inputs_by(row.id, |ui| { ui.horizontal(|ui| { if widgets::radio(ui, tl!("By Rows"), rows, true) { diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 140ace0fde..1a08c4d377 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -211,7 +211,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { Ok(o) => { let sample = o.label(72.0, false).unwrap_or_default(); let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(format!("{}: {sample}", tl!("Preview (1 inch on the page)"))).color(t.text)); + ui.label(RichText::new(format!("{} {sample}", crate::i18n::colon(tl!("Preview (1 inch on the page)")))).color(t.text)); } Err(e) => { ui.colored_label(Tokens::get(ui.ctx()).text, e); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index e9ffdc681e..987fceeea4 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -322,6 +322,13 @@ fn center_round(x: f64) -> f64 { (x * 1e4).round() / 1e4 } +/// The value screen readers give Blur Center at `c` (0 to 1 of the bounds): Horizontal and +/// Vertical in percent, each label followed by the UI language's colon. +pub(super) fn blur_center_value(c: [f64; 2]) -> String { + let percent = |v: f64| (v * 1000.0).round() / 10.0; + format!("{} {}%, {} {}%", crate::i18n::colon(tl!("Horizontal")), percent(c[0]), crate::i18n::colon(tl!("Vertical")), percent(c[1])) +} + /// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays /// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center /// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The @@ -339,9 +346,8 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover()); let id = ui.scope_id().with("radial-blur-center"); let resp = ui.interact(rect, id, Sense::click_and_drag()); - let percent = |v: f64| (v * 1000.0).round() / 10.0; let name = tl!("Blur Center").to_string(); - let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1])); + let value = blur_center_value(c); let enabled = ui.is_enabled(); resp.widget_info(|| egui::WidgetInfo { current_text_value: Some(value.clone()), @@ -396,7 +402,7 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { ui.vertical(|ui| { egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| { for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() { - let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!(label))).color(t.text)); ui.label_inputs_by(row.id, |ui| { if let Some(x) = widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0) diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 733ff22398..c57671803e 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -843,11 +843,17 @@ pub(crate) fn humanize(k: &str) -> String { } } -/// [`humanize`] translated where it is painted: the ":" stays outside the translated text. +/// A style attribute as the style dialogs list it: the [`humanized`] key, then its value. +pub(super) fn attribute_line(key: &str, value: &Value) -> String { + format!("{} {value}", humanized(key)) +} + +/// [`humanize`] translated where it is painted: the ":" stays outside the translated text and is +/// written as the UI language writes a label's colon ([`crate::i18n::colon`]). pub(super) fn humanized(k: &str) -> String { let h = humanize(k); match h.strip_suffix(':') { - Some(base) => format!("{}:", tl!(base)), + Some(base) => crate::i18n::colon(tl!(base)), None => tl!(&h).to_string(), } } diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 838ba066d9..766ae898ee 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -577,9 +577,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// `text` with the colon of a field label. +/// `text` with the colon of a field label, as the UI language writes it. fn colon(text: &str) -> String { - format!("{text}:") + crate::i18n::colon(text) } /// A checkbox bound to `d.fields[key]`, dimmed while the type picked has no use for it. @@ -977,6 +977,22 @@ mod tests { assert!(app.ui.dialog.is_none()); } + /// Field labels end in the UI language's colon: in French a no-break space and a colon (#7991). + #[test] + fn field_labels_use_the_language_colon() { + let mut app = app_with_graph("column"); + crate::menus::invoke(&mut app, COMMAND, json!({})); + set(&mut app, PAGE, json!("valueAxis")); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let mut h = harness(app); + h.run_steps(3); + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, "Suffix")); + let found = h.query_by_role_and_label(Role::TextInput, &want).is_some(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(found, "a text field named {want:?}"); + } + /// A Type button changes the graph's type and keeps its data. #[test] fn a_type_button_changes_the_graph_type_and_keeps_its_data() { diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 4978a6a1f6..82f0c7d78b 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -77,7 +77,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); if let Ok(attrs) = super::char_style_options::edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } }); diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index d63d43be89..9a9da0c164 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -952,7 +952,7 @@ pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 3a62eae1f4..3ffc496dd6 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -198,7 +198,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { && let Some(counts) = d.fields.get("__counts") && let (Some(before), Some(after)) = (counts["before"].as_u64(), counts["after"].as_u64()) { - ui.label(format!("{}: {before} → {after}", tl!("Anchor Points"))); + ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); } } false diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 950b15c763..c5a4c905a0 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -167,7 +167,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); - widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers"))); + widgets::dim_label(ui, &format!("{} × {} px · {} {}", count("width"), count("height"), crate::i18n::colon(tl!("Layers")), count("layers"))); // Offered only for a file with slices, with either conversion. let sliced = count("slices") > 0; ui.add_space(8.0); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index ff57bd6817..8efa96d89b 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -392,7 +392,8 @@ fn prominent_bar(ui: &mut Ui, d: &mut Dialog, rows: &[Value]) { let c = to_color(&rows[*i]).or_else(|| from_colors(&rows[*i]).first().copied()).unwrap_or_default(); chip(ui, r, c, false); let share = (widths[n] * 100.0).round(); - ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()).on_hover_text(format!("{} {}: {share}%", tl!("Color"), i + 1)); + ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()) + .on_hover_text(format!("{} {share}%", crate::i18n::colon(&format!("{} {}", tl!("Color"), i + 1)))); left = right; } let mut ended = false; diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 77c5980ec0..c7c98a5de0 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -733,7 +733,7 @@ pub(super) fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &s ui.painter().rect_filled(r, 3.0, Tokens::get(ui.ctx()).hover); } dot(ui, r.center(), changed); - response.on_hover_text(format!("{}: {default}", tl!("Reset to default"))).clicked() + response.on_hover_text(format!("{} {default}", crate::i18n::colon(tl!("Reset to default")))).clicked() } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 3d522b624a..dadab71c70 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -75,7 +75,8 @@ impl Light { /// The name screen readers give the light at `index`: its number, Rotation, Height and side. fn name(self, index: usize) -> String { let side = if self.behind { format!(", {}", tl!("Light behind the object")) } else { String::new() }; - format!("{} {}: {} {:.1}°, {} {:.1}°{side}", c3("Light"), index + 1, tl!("Rotation"), self.rotation, tl!("Height"), self.height) + let light = crate::i18n::colon(&format!("{} {}", c3("Light"), index + 1)); + format!("{light} {} {:.1}°, {} {:.1}°{side}", tl!("Rotation"), self.rotation, tl!("Height"), self.height) } } diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 111d400a3b..f76dcc164b 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -912,7 +912,7 @@ pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator s.clone(), other => other.to_string(), }; - ui.label(egui::RichText::new(format!("{}: {value}", label(c["option"].as_str().unwrap_or_default()))).color(t.text)); + ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text)); } } diff --git a/crates/ui-egui/src/dialogs/script_check.rs b/crates/ui-egui/src/dialogs/script_check.rs index 257227cc6f..e134cf1b39 100644 --- a/crates/ui-egui/src/dialogs/script_check.rs +++ b/crates/ui-egui/src/dialogs/script_check.rs @@ -271,7 +271,7 @@ fn report(ui: &mut egui::Ui, r: &Value, t: &Tokens) { for p in problems { let Some(label) = p["code"].as_str().and_then(problem_label) else { continue }; let label = match p["detail"].as_str() { - Some(detail) => format!("{label}: {detail}"), + Some(detail) => format!("{} {detail}", crate::i18n::colon(label)), None => label.to_string(), }; row(ui, t, &label, false, &place(p)); diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 1ebe084e02..ce6f62c6a2 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -98,7 +98,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let lines: Vec = options() .into_iter() .filter(|(key, ..)| d.bool(key)) - .map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0))) + .map(|(_, count, label)| format!("{} {}", crate::i18n::colon(label), r["replaced"][count].as_u64().unwrap_or(0))) .collect(); super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n")); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index b8d6a59887..dec8b5853c 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -178,6 +178,64 @@ fn effect_preview_is_kept_as_one_undo_step() { assert_eq!(app.session.doc().unwrap().doc, before); } +/// A field label's colon is written as the UI language writes it, in the generic parameter +/// dialogs and the effect dialogs alike (#7991): French puts a no-break space before it, Chinese +/// writes a full-width colon, and English is unchanged. +#[test] +fn field_label_colons_follow_the_ui_language() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let text = + app.run("text.create", json!({"x": 20, "y": 80, "text": "Hello", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap(); + // Each dialog, opened the way its menu item opens it, and the label it shows. + let entries = crate::menus::menu_entries(&app); + let clean_up = entries.iter().find(|e| e.path == ["Object", "Path"] && e.label == "Clean Up…").expect("listed"); + let clean_up = crate::menus::click_target(&clean_up.label, clean_up.command.as_deref().unwrap(), &clean_up.params); + let dialogs = [ + (clean_up.0, clean_up.1, "Stray Points"), + ("effect.dialog".to_string(), json!({"effect": "blur.radial"}), "Horizontal"), + ("text.areaOptions".to_string(), json!({}), "Text Flow"), + ]; + for (command, params, label) in dialogs { + app.run("select.set", json!({"ids": [text]})).unwrap(); + if command != "text.areaOptions" { + app.run("select.all", json!({})).unwrap(); + } + crate::menus::invoke(&mut app, &command, params); + assert!(app.ui.dialog.is_some(), "{command} opened no dialog"); + for (code, colon) in [("fr", "\u{a0}:"), ("zh-hans", ":"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}{colon}", crate::i18n::tr(lang, label)); + assert!(shown.lines().any(|l| l.trim() == want), "{command}, {code}: {want:?} in {shown}"); + if code == "fr" { + let bare: Vec<_> = shown.lines().map(str::trim).filter(|l| l.ends_with(':') && !l.ends_with("\u{a0}:")).collect(); + assert!(bare.is_empty(), "{command}: French labels with a bare colon: {bare:?}"); + } + } + app.ui.dialog = None; + } + assert_eq!(super::form::humanized("strayPoints"), "Stray Points:", "English is unchanged"); +} + +/// A label followed by its value takes the UI language's colon too (#7991): Blur Center's value for +/// screen readers, and a style's attribute list, which no longer shows a second colon. +#[test] +fn label_and_value_colons_follow_the_ui_language() { + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let center = super::effect::blur_center_value([0.5, 0.25]); + let attribute = super::form::attribute_line("fontSize", &json!(12)); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (h, v) = (crate::i18n::tr(fr, "Horizontal"), crate::i18n::tr(fr, "Vertical")); + assert_eq!(center, format!("{h}\u{a0}: 50%, {v}\u{a0}: 25%")); + assert_eq!(attribute, format!("{}\u{a0}: 12", crate::i18n::tr(fr, "Font Size"))); + assert_eq!(super::effect::blur_center_value([0.5, 0.25]), "Horizontal: 50%, Vertical: 25%"); + assert_eq!(super::form::attribute_line("fontSize", &json!(12)), "Font Size: 12"); +} + /// Drop Shadow's Color typed as text the effect can't draw: OK returns the error and keeps the /// dialog open, with Preview on or off, and the document stays as it was. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 06eef4d2c6..29a37ac4ad 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -678,6 +678,14 @@ fn simplify_dialog_preview_counts_and_cancel_restore_the_original() { let texts = frame(&ctx, &mut app, vec![]); let preview = texts.iter().find(|(t, _)| t == "Preview").map(|(_, r)| *r).expect("a Preview checkbox"); assert!(texts.iter().any(|(t, _)| t == "Anchor Points: 20 → 2"), "the reduction is visible: {texts:?}"); + // In French the label ends in a no-break space and a colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = frame(&ctx, &mut app, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}\u{a0}: 20 → 2", crate::i18n::tr(fr, "Anchor Points")); + assert!(french.iter().any(|(t, _)| *t == want), "{want:?} in {french:?}"); + frame(&ctx, &mut app, vec![]); assert!(app.session.in_interaction()); assert!(app.session.doc().unwrap().selection.anchors.is_empty()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len); diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index 99128cc321..f0fe62b40d 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -3,7 +3,7 @@ //! places it as area type (`file.place` with `text`) and remembers the options: the next text file //! starts from them, and is placed with them when Show Import Options is off. //! -//! Fields: `platform` (`windows` | `mac`), `characterSet` (`unicode` | `ansi`), +//! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]), //! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off), `spaces` (how many //! spaces make a tab, 2–100), and `__params` (the `file.place` params naming the file). @@ -22,6 +22,21 @@ pub(super) const SPEC: DialogSpec = /// The label column of the Encoding rows. const LABEL: f32 = 104.0; +/// The Character Set choices: `file.place`'s `text.characterSet` value and the menu label. +const CHARACTER_SETS: [(&str, &str); 11] = [ + ("unicode", "Unicode"), + ("ansi", "ANSI"), + ("shiftJis", "Shift JIS"), + ("gb2312", "GB2312"), + ("chineseBig5", "Chinese Big 5"), + ("cyrillic", "Cyrillic"), + ("gb18030", "GB18030"), + ("greek", "Greek"), + ("turkish", "Turkish"), + ("baltic", "Baltic"), + ("centralEuropean", "Central European"), +]; + /// Is the file `p` names (`path` or `name`) a text file? pub fn is_text(p: &Value) -> bool { let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default(); @@ -41,7 +56,8 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value { "__params": params, }); let last = &app.ui.text_import; - for (k, wanted) in [("platform", ["windows", "mac"]), ("characterSet", ["unicode", "ansi"])] { + let sets = CHARACTER_SETS.map(|(value, _)| value); + for (k, wanted) in [("platform", &["windows", "mac"][..]), ("characterSet", &sets[..])] { if let Some(v) = last.get(k).and_then(Value::as_str).filter(|v| wanted.contains(v)) { fields[k] = json!(v); } @@ -68,7 +84,7 @@ pub fn last_options(app: &VectorcraftApp) -> Value { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::subheader(ui, tl!("Encoding")); form::choice(ui, d, "platform", tl!("Platform:"), (LABEL, 180.0), &[("windows", "Windows"), ("mac", "Mac")]); - form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &[("unicode", "Unicode"), ("ansi", "ANSI")]); + form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &CHARACTER_SETS); ui.add_space(10.0); widgets::subheader(ui, tl!("Line Breaks")); for (key, label) in @@ -166,6 +182,39 @@ mod tests { assert_eq!(st.history.undo.len(), 1); } + /// Every character set is a choice: one confirmed last comes back on the next text file and + /// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options + /// off the remembered set is the one the file is placed with. + #[test] + fn a_remembered_character_set_comes_back_and_places_the_file() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(&[0x93, 0xFA, 0x96, 0x7B])}); + app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"}); + app.run("file.place", file.clone()).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("shiftJis")); + assert!(frame(&mut app).contains("Shift JIS"), "the remembered set is shown"); + let r = super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let n = st.doc.node(vectorcraft_engine::doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + assert_eq!(t.plain_text(), "日本"); + assert_eq!(last_options(&app)["characterSet"], "shiftJis", "remembered for Show Import Options off"); + app.ui.text_import = json!({"characterSet": "latin9"}); + app.run("file.place", file).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("unicode")); + let values: Vec<&str> = CHARACTER_SETS.iter().map(|(v, _)| *v).collect(); + let labels: Vec<&str> = CHARACTER_SETS.iter().map(|(_, l)| *l).collect(); + assert_eq!( + values, + ["unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean"] + ); + assert_eq!( + labels, + ["Unicode", "ANSI", "Shift JIS", "GB2312", "Chinese Big 5", "Cyrillic", "GB18030", "Greek", "Turkish", "Baltic", "Central European"] + ); + } + /// A text file dropped on a canvas is placed by the dialog's OK in the document it was dropped /// on, even when another document became active meanwhile. #[test] diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index d58351ac21..51155e710f 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -532,7 +532,7 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ctx: &egui::Context) { let inner = ui.available_width() - 10.0; for (cat, gs) in groups() { ui.add_space(6.0); - ui.label(egui::RichText::new(format!("{}:", tl!(cat))).size(12.0).color(t.text_strong)); + ui.label(egui::RichText::new(crate::i18n::colon(tl!(cat))).size(12.0).color(t.text_strong)); ui.add_space(4.0); for g in gs { // A flyout group: its tools framed together, as one toolbar button holds them. diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 8983199324..b13eb02120 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -354,6 +354,25 @@ fn tools_in_the_toolbar_are_dimmed_in_the_drawer() { assert_eq!(cell_at(&shown, drawer, "Artboard Tool").1, dim); } +/// The drawer's headings end in the UI language's colon: in French a no-break space and a colon +/// (#7991), in English a plain colon. +#[test] +fn drawer_headings_use_the_language_colon() { + let mut app = app(); + let ctx = ctx(); + app.run("window.editToolbar", json!({"open": true})).unwrap(); + for (code, colon) in [("fr", "\u{a0}:"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + frame(&mut app, &ctx, 0.0, vec![]); + let shown = frame(&mut app, &ctx, 0.1, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let drawer = drawer_rect(&ctx).unwrap(); + let want = format!("{}{colon}", crate::i18n::tr(lang, "Select")); + assert!(shown.iter().any(|(s, p, _)| s.trim() == want && drawer.contains(*p)), "{code}: {want:?}"); + } +} + /// #1018: tools drag from the drawer onto the toolbar (between two tools, or onto one to join /// its group), from the toolbar into the drawer, and within the toolbar, only while the drawer /// is open. @@ -578,6 +597,17 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { click(&mut app, &ctx, 40.0, items(&shown, "Lasso Tool")[0].0); assert_eq!(mine(&app), [["magicWand"]]); assert_eq!(slots(&app), shipped); + // In French the menu's headings end in a no-break space and a colon (#7991). + open(&mut app, 49.0); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + frame(&mut app, &ctx, 49.7, vec![]); + let french = frame(&mut app, &ctx, 49.8, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + for heading in ["Remove Tool", "Select"] { + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, heading)); + assert_eq!(items(&french, &want).len(), 1, "{want:?}"); + } } /// New Toolbar… in the drawer's menu opens the New Toolbar dialog, which asks for a name. diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 166d6ab885..df5d05fc95 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -100,7 +100,7 @@ fn plural_polish(n: u64) -> usize { pub static LANGUAGES: [LangInfo; 29] = [ LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() }, // Hindi shares the integer zero/one rule with French. Desktop UI fonts are loaded lazily - // from installed faces by ui_fonts; the web needs a Devanagari font in its font set. + // from installed faces by ui_fonts; the web fetches a Devanagari craft-fonts face on demand. LangInfo { code: "hi", name: "हिन्दी", @@ -623,6 +623,13 @@ pub fn t(s: &str) -> &str { tr(current(), s) } +/// `label`, already in the current language, followed by a field label's colon as the current +/// language writes it (its catalog row for ":"): French puts a no-break space before the colon, and +/// Chinese and Japanese write a full-width colon. +pub fn colon(label: &str) -> String { + format!("{label}{}", t(":")) +} + /// Translate an English UI string; unknown strings come back unchanged. pub fn tr(lang: Lang, s: &str) -> &str { lang.catalog().plain(s).unwrap_or(s) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b274713654..3d3811c403 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -408,6 +408,12 @@ font-technology Variable Променливи Character Alignment Подравняване на знаците Character / Paragraph Знак / Абзац Character Rotation Въртене на знак + Chinese Big 5 Китайски Big 5 + Cyrillic Кирилица + Greek Гръцки + Turkish Турски + Baltic Балтийски + Central European Централноевропейски Character Set: Набор от знаци: Character Style Стил на знак Character Style Options Опции за стил на знак @@ -7313,4 +7319,14 @@ breakText Glyphs Глифи @msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане. @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} + Fold Preview Преглед на сгъването + Fold Сгъване + Show Fold Lines Покажи линиите на сгъване + Three-Quarter Три четвърти + Open a document to preview its folded shape. Отворете документ, за да прегледате сгънатата му форма. +@msg Check the fold lines first. Първо проверете линиите на сгъване. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, панти: {hinges} +@msg Other blanks not shown: {count} Други разкрои не са показани: {count} +@msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. +@msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7c9f3edc1..b053827273 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3326,6 +3326,12 @@ antiAlias Sharp Oštro LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opcije izvoza teksta + Chinese Big 5 Kineski Big 5 + Cyrillic Ćirilica + Greek Grčki + Turkish Turski + Baltic Baltički + Central European Srednjoevropski Character Set: Skup znakova: Join the lines of each paragraph Spoji redove svakog pasusa Line Breaks Prelomi reda @@ -7368,4 +7374,14 @@ shape Open Otvoren @msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja. @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} + Fold Preview Pregled savijanja + Fold Savijanje + Show Fold Lines Prikaži linije savijanja + Three-Quarter Tri četvrtine + Open a document to preview its folded shape. Otvorite dokument da pregledate njegov savijeni oblik. +@msg Check the fold lines first. Prvo provjerite linije savijanja. +@msg Panels: {panels}, hinges: {hinges} Paneli: {panels}, šarke: {hinges} +@msg Other blanks not shown: {count} Ostali krojevi nisu prikazani: {count} +@msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. +@msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index db08353395..126ae03109 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -685,6 +685,12 @@ antiAlias Sharp Nítid Character options Opcions de caràcter Paragraph options Opcions de paràgraf Character Rotation Rotació de caràcters + Chinese Big 5 Xinès Big 5 + Cyrillic Ciríl·lic + Greek Grec + Turkish Turc + Baltic Bàltic + Central European Centreeuropeu Character Set: Joc de caràcters: Character Style Estil de caràcter Character Style Options Opcions de l’estil de caràcter @@ -8247,4 +8253,15 @@ breakText Glyphs Glifs @msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit. @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} + Fold Preview Previsualització del plegat + Fold Plegat + Show Fold Lines Mostra les línies de plegat + Three-Quarter Tres quarts + Open a document to preview its folded shape. Obre un document per previsualitzar-ne la forma plegada. +@msg Check the fold lines first. Primer comprova les línies de plegat. +@msg Panels: {panels}, hinges: {hinges} Panells: {panels}, frontisses: {hinges} +@msg Other blanks not shown: {count} Altres troquelats no mostrats: {count} +@msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. +@msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: utilitzeu "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d74925d666..086b9b2f90 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3414,6 +3414,12 @@ antiAlias Sharp Ostré LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Možnosti exportu textu + Chinese Big 5 Čínština Big 5 + Cyrillic Cyrilice + Greek Řečtina + Turkish Turečtina + Baltic Baltské jazyky + Central European Středoevropské jazyky Character Set: Znaková sada: Join the lines of each paragraph Spojit řádky každého odstavce Line Breaks Zalomení řádků @@ -10042,3 +10048,13 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Fold Preview Náhled skládání + Fold Složení + Show Fold Lines Zobrazit linie skladu + Three-Quarter Tři čtvrtě + Open a document to preview its folded shape. Otevřete dokument, abyste zobrazili náhled jeho složeného tvaru. +@msg Check the fold lines first. Nejprve zkontrolujte linie skladu. +@msg Panels: {panels}, hinges: {hinges} Panely: {panels}, panty: {hinges} +@msg Other blanks not shown: {count} Další přířezy nejsou zobrazeny: {count} +@msg A joint does not close by {gap} pt. Spoj se nezavírá o {gap} pt. +@msg Two panels pass through each other. Dva panely procházejí jeden druhým. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 12ab322253..eb7fa71fdc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5873,6 +5873,12 @@ antiAlias Sharp Skarp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Indstillinger for teksteksport + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Græsk + Turkish Tyrkisk + Baltic Baltisk + Central European Centraleuropæisk Character Set: Tegnsæt: Join the lines of each paragraph Forbind linjerne i hvert afsnit Line Breaks Linjeskift @@ -10140,4 +10146,14 @@ breakText Glyphs Glyffer @msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje. @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} + Fold Preview Forhåndsvisning af foldning + Fold Foldning + Show Fold Lines Vis foldelinjer + Three-Quarter Trekvart + Open a document to preview its folded shape. Åbn et dokument for at se dets foldede form. +@msg Check the fold lines first. Kontrollér foldelinjerne først. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, hængsler: {hinges} +@msg Other blanks not shown: {count} Andre emner vises ikke: {count} +@msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. +@msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1493f9c38d..84c9ca0788 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -402,6 +402,12 @@ font-technology Variable Variabel Character Alignment Zeichenausrichtung Character / Paragraph Zeichen / Absatz Character Rotation Zeichendrehung + Chinese Big 5 Chinesisch Big 5 + Cyrillic Kyrillisch + Greek Griechisch + Turkish Türkisch + Baltic Baltisch + Central European Mitteleuropäisch Character Set: Zeichensatz: Character Style Zeichenformat Character Style Options Zeichenformatoptionen @@ -9644,3 +9650,13 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Fold Preview Faltvorschau + Fold Falten + Show Fold Lines Faltlinien einblenden + Three-Quarter Dreiviertelansicht + Open a document to preview its folded shape. Öffnen Sie ein Dokument, um seine gefaltete Form in der Vorschau zu sehen. +@msg Check the fold lines first. Prüfen Sie zuerst die Faltlinien. +@msg Panels: {panels}, hinges: {hinges} Felder: {panels}, Scharniere: {hinges} +@msg Other blanks not shown: {count} Weitere Zuschnitte nicht angezeigt: {count} +@msg A joint does not close by {gap} pt. Eine Verbindung schließt um {gap} pt nicht. +@msg Two panels pass through each other. Zwei Felder durchdringen einander. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1171165348..74b1a19dec 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -398,6 +398,12 @@ font-technology Variable Μεταβλητές Character Alignment Στοίχιση χαρακτήρων Character / Paragraph Χαρακτήρας / Παράγραφος Character Rotation Περιστροφή χαρακτήρων + Chinese Big 5 Κινεζικά Big 5 + Cyrillic Κυριλλικά + Greek Ελληνικά + Turkish Τουρκικά + Baltic Βαλτικά + Central European Κεντρικής Ευρώπης Character Set: Σύνολο χαρακτήρων: Character Style Στυλ χαρακτήρων Character Style Options Επιλογές στυλ χαρακτήρων @@ -8221,4 +8227,15 @@ breakText Glyphs Γλύφοι @msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης. @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} + Fold Preview Προεπισκόπηση δίπλωσης + Fold Δίπλωση + Show Fold Lines Εμφάνιση γραμμών δίπλωσης + Three-Quarter Τρία τέταρτα + Open a document to preview its folded shape. Ανοίξτε ένα έγγραφο για να δείτε σε προεπισκόπηση το διπλωμένο σχήμα του. +@msg Check the fold lines first. Ελέγξτε πρώτα τις γραμμές δίπλωσης. +@msg Panels: {panels}, hinges: {hinges} Πάνελ: {panels}, μεντεσέδες: {hinges} +@msg Other blanks not shown: {count} Άλλα αναπτύγματα δεν εμφανίζονται: {count} +@msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. +@msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: χρησιμοποιήστε "{_1}" ή "{_2}" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2648d7c1f6..f0244278fd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -425,6 +425,12 @@ font-technology Variable Variables Character Alignment Alineación de caracteres Character / Paragraph Carácter / Párrafo Character Rotation Rotación de caracteres + Chinese Big 5 Chino Big 5 + Cyrillic Cirílico + Greek Griego + Turkish Turco + Baltic Báltico + Central European Centroeuropeo Character Set: Juego de caracteres: Character Style Estilo de carácter Character Style Options Opciones de estilo de carácter @@ -8208,4 +8214,15 @@ breakText Glyphs Glifos @msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido. @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} + Fold Preview Vista previa del plegado + Fold Plegado + Show Fold Lines Mostrar líneas de plegado + Three-Quarter Tres cuartos + Open a document to preview its folded shape. Abre un documento para previsualizar su forma plegada. +@msg Check the fold lines first. Comprueba primero las líneas de plegado. +@msg Panels: {panels}, hinges: {hinges} Paneles: {panels}, bisagras: {hinges} +@msg Other blanks not shown: {count} Otros troquelados no mostrados: {count} +@msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. +@msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: use "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bdf353326f..66ac99ffb1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3361,6 +3361,12 @@ antiAlias Sharp Terävä LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Tekstin vientiasetukset + Chinese Big 5 Kiina Big 5 + Cyrillic Kyrillinen + Greek Kreikka + Turkish Turkki + Baltic Balttilainen + Central European Keskieurooppalainen Character Set: Merkistö: Join the lines of each paragraph Yhdistä kunkin kappaleen rivit Line Breaks Rivinvaihdot @@ -8304,4 +8310,15 @@ breakText Glyphs Merkit @msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla. @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} + Fold Preview Taiton esikatselu + Fold Taitto + Show Fold Lines Näytä taittoviivat + Three-Quarter Kolme neljäsosaa + Open a document to preview its folded shape. Avaa asiakirja, niin voit esikatsella sen taitettua muotoa. +@msg Check the fold lines first. Tarkista ensin taittoviivat. +@msg Panels: {panels}, hinges: {hinges} Paneelit: {panels}, saranat: {hinges} +@msg Other blanks not shown: {count} Muita aihioita ei näytetä: {count} +@msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. +@msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: käytä arvoa "{_1}" tai "{_2}" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 34cdc7fb7d..b551e3cbe2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -426,6 +426,12 @@ font-technology Variable Variables Character Alignment Alignement des caractères Character / Paragraph Caractère / Paragraphe Character Rotation Rotation des caractères + Chinese Big 5 Chinois Big 5 + Cyrillic Cyrillique + Greek Grec + Turkish Turc + Baltic Balte + Central European Europe centrale Character Set: Jeu de caractères : Character Style Style de caractère Character Style Options Options de style de caractère @@ -10026,4 +10032,14 @@ breakText Glyphs Glyphes @msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage. @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) + Fold Preview Aperçu du pliage + Fold Pliage + Show Fold Lines Afficher les lignes de pliage + Three-Quarter Trois-quarts + Open a document to preview its folded shape. Ouvrez un document pour prévisualiser sa forme pliée. +@msg Check the fold lines first. Vérifiez d’abord les lignes de pliage. +@msg Panels: {panels}, hinges: {hinges} {panels} panneau(x), {hinges} charnière(s) +@msg Other blanks not shown: {count} {count} autre(s) flan(s) non affiché(s) +@msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. +@msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f56b6a78b1..9f6ce6b664 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -542,6 +542,11 @@ Character Color અક્ષર રંગ Character Direction અક્ષર દિશા Character Rotation અક્ષર પરિભ્રમણ + Chinese Big 5 ચાઇનીઝ Big 5 + Cyrillic સિરિલિક + Greek ગ્રીક + Baltic બાલ્ટિક + Central European મધ્ય યુરોપિયન Character Set: અક્ષર સેટ: Character Style Options અક્ષર સ્ટાઇલ વિકલ્પો Character Styles અક્ષર સ્ટાઇલ @@ -5052,6 +5057,16 @@ swatch [Registration] [રજિસ્ટ્રેશન] @msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી. @msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, હિન્જ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} + Fold Preview ફોલ્ડ પ્રિવ્યૂ + Fold ફોલ્ડ + Show Fold Lines ફોલ્ડ લાઇન્સ બતાવો + Three-Quarter ત્રણ-ચતુર્થાંશ + Open a document to preview its folded shape. તેનો ફોલ્ડ કરેલો આકાર જોવા દસ્તાવેજ ખોલો. +@msg Check the fold lines first. પહેલાં ફોલ્ડ લાઇન્સ ચેક કરો. +@msg Panels: {panels}, hinges: {hinges} પેનલ: {panels}, હિન્જ: {hinges} +@msg Other blanks not shown: {count} બીજા બ્લેન્ક બતાવ્યા નથી: {count} +@msg A joint does not close by {gap} pt. એક સાંધો {gap} pt થી બંધ થતો નથી. +@msg Two panels pass through each other. બે પેનલ એકબીજામાંથી પસાર થાય છે. Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 516fb898b5..3e144d045a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -801,6 +801,11 @@ antiAlias Sharp शार्प Character Direction कैरेक्टर दिशा Character options कैरेक्टर ऑप्शन्स Character Rotation कैरेक्टर रोटेशन + Chinese Big 5 चीनी Big 5 + Cyrillic सिरिलिक + Greek ग्रीक + Baltic बाल्टिक + Central European मध्य यूरोपीय Character Set: कैरेक्टर सेट: Character Style कैरेक्टर स्टाइल Character Style Options कैरेक्टर स्टाइल ऑप्शन्स @@ -9650,3 +9655,13 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Fold Preview फ़ोल्ड प्रीव्यू + Fold फ़ोल्ड + Show Fold Lines फ़ोल्ड लाइनें दिखाएँ + Three-Quarter तीन-चौथाई + Open a document to preview its folded shape. इसका फ़ोल्ड किया हुआ आकार देखने के लिए कोई डॉक्यूमेंट ओपन करें। +@msg Check the fold lines first. पहले फ़ोल्ड लाइनें चेक करें। +@msg Panels: {panels}, hinges: {hinges} पैनल: {panels}, हिंज: {hinges} +@msg Other blanks not shown: {count} दूसरे ब्लैंक नहीं दिखाए गए: {count} +@msg A joint does not close by {gap} pt. एक जोड़ {gap} pt से बंद नहीं होता। +@msg Two panels pass through each other. दो पैनल एक-दूसरे के आर-पार जाते हैं। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9753f0e478..977b6062b6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -584,6 +584,12 @@ font-technology Variable Változó Character options Karakterbeállítások Paragraph options Bekezdésbeállítások Character Rotation Karakterforgatás + Chinese Big 5 Kínai Big 5 + Cyrillic Cirill + Greek Görög + Turkish Török + Baltic Balti + Central European Közép-európai Character Set: Karakterkészlet: Character Style Karakterstílus Character Style Options Karakterstílus beállításai @@ -10030,3 +10036,13 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Fold Preview Hajtás előnézete + Fold Hajtás + Show Fold Lines Hajtásvonalak megjelenítése + Three-Quarter Háromnegyed + Open a document to preview its folded shape. Nyiss meg egy dokumentumot a hajtogatott alakja előnézetéhez. +@msg Check the fold lines first. Előbb ellenőrizd a hajtásvonalakat. +@msg Panels: {panels}, hinges: {hinges} Panelek: {panels}, zsanérok: {hinges} +@msg Other blanks not shown: {count} További kiterítékek nincsenek megjelenítve: {count} +@msg A joint does not close by {gap} pt. Egy illesztés {gap} pt-tal nem záródik. +@msg Two panels pass through each other. Két panel áthatol egymáson. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f6e69f53f3..97280c99bc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3105,6 +3105,12 @@ antiAlias Sharp Tajam LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opsi ekspor teks + Chinese Big 5 Tionghoa Big 5 + Cyrillic Sirilik + Greek Yunani + Turkish Turki + Baltic Baltik + Central European Eropa Tengah Character Set: Set karakter: Join the lines of each paragraph Gabungkan baris setiap paragraf Line Breaks Pemisah baris @@ -7330,4 +7336,14 @@ breakText Glyphs Glif @msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun. @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} + Fold Preview Pratinjau lipatan + Fold Lipat + Show Fold Lines Tampilkan garis lipat + Three-Quarter Tiga perempat + Open a document to preview its folded shape. Buka dokumen untuk melihat pratinjau bentuk terlipatnya. +@msg Check the fold lines first. Periksa garis lipat terlebih dahulu. +@msg Panels: {panels}, hinges: {hinges} Panel: {panels}, engsel: {hinges} +@msg Other blanks not shown: {count} Bentangan lain tidak ditampilkan: {count} +@msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. +@msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1ab62319a6..9465b6aca8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -427,6 +427,12 @@ font-technology Variable Variabili Character Alignment Allineamento caratteri Character / Paragraph Carattere / Paragrafo Character Rotation Rotazione caratteri + Chinese Big 5 Cinese Big 5 + Cyrillic Cirillico + Greek Greco + Turkish Turco + Baltic Baltico + Central European Centroeuropeo Character Set: Set di caratteri: Character Style Stile carattere Character Style Options Opzioni stile carattere @@ -9679,3 +9685,13 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Fold Preview Anteprima piegatura + Fold Piegatura + Show Fold Lines Mostra linee di piega + Three-Quarter Tre quarti + Open a document to preview its folded shape. Apri un documento per vederne in anteprima la forma piegata. +@msg Check the fold lines first. Verifica prima le linee di piega. +@msg Panels: {panels}, hinges: {hinges} Pannelli: {panels}, cerniere: {hinges} +@msg Other blanks not shown: {count} Altri fustellati non mostrati: {count} +@msg A joint does not close by {gap} pt. Una giunzione non si chiude di {gap} pt. +@msg Two panels pass through each other. Due pannelli si attraversano. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index abf3d8700f..91c85b9e27 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1265,6 +1265,12 @@ antiAlias Sharp シャープ Channel チャンネル Character / Paragraph 文字/段落 Character Rotation 文字回転 + Chinese Big 5 中国語 Big 5 + Cyrillic キリル文字 + Greek ギリシャ語 + Turkish トルコ語 + Baltic バルト言語 + Central European 中央ヨーロッパ言語 Character Set: 文字セット: Character Style Options 文字スタイルオプション Check Links リンクを確認 @@ -9746,3 +9752,13 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Fold Preview 折りプレビュー + Fold 折り + Show Fold Lines 折り線を表示 + Three-Quarter 斜め + Open a document to preview its folded shape. ドキュメントを開くと折った形をプレビューできます。 +@msg Check the fold lines first. 先に折り線をチェックしてください。 +@msg Panels: {panels}, hinges: {hinges} パネル: {panels}、ヒンジ: {hinges} +@msg Other blanks not shown: {count} 表示されていない他の展開図: {count} +@msg A joint does not close by {gap} pt. 継ぎ目が {gap} pt 閉じていません。 +@msg Two panels pass through each other. 2 つのパネルが互いを貫通しています。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 025980e1d7..6fa08c2bd6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5189,6 +5189,11 @@ antiAlias Sharp მკვეთრი Encoding: კოდირება: Line Endings: სტრიქონის დაბოლოებები: Text Export Options ტექსტის ექსპორტის პარამეტრები + Chinese Big 5 ჩინური Big 5 + Cyrillic კირილიცა + Greek ბერძნული + Baltic ბალტიური + Central European ცენტრალურევროპული Character Set: სიმბოლოთა ნაკრები: Join the lines of each paragraph თითოეული აბზაცის სტრიქონების შეერთება Line Breaks სტრიქონის წყვეტები @@ -10399,4 +10404,14 @@ font-script Japanese იაპონური @msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება. @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არაბეჭდვად შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} + Fold Preview მოკეცვის გადახედვა + Fold მოკეცვა + Show Fold Lines მოკეცვის ხაზების ჩვენება + Three-Quarter სამი მეოთხედი + Open a document to preview its folded shape. გახსენით დოკუმენტი მისი მოკეცილი ფორმის სანახავად. +@msg Check the fold lines first. ჯერ შეამოწმეთ მოკეცვის ხაზები. +@msg Panels: {panels}, hinges: {hinges} პანელები: {panels}, ანჯამები: {hinges} +@msg Other blanks not shown: {count} სხვა ნამზადები არ ჩანს: {count} +@msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. +@msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbef9e6743..b0182a55e1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1255,6 +1255,12 @@ antiAlias Sharp 날카롭게 Channel 채널 Character / Paragraph 문자 / 단락 Character Rotation 문자 회전 + Chinese Big 5 중국어 Big 5 + Cyrillic 키릴 자모 + Greek 그리스어 + Turkish 터키어 + Baltic 발트어 + Central European 중앙 유럽어 Character Set: 문자 집합: Character Style Options 문자 스타일 옵션 Check Links 링크 확인 @@ -9643,3 +9649,13 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Fold Preview 접기 미리 보기 + Fold 접기 + Show Fold Lines 접는 선 표시 + Three-Quarter 3/4 보기 + Open a document to preview its folded shape. 접은 모양을 미리 보려면 문서를 여세요. +@msg Check the fold lines first. 먼저 접는 선을 검사하세요. +@msg Panels: {panels}, hinges: {hinges} 패널: {panels}, 힌지: {hinges} +@msg Other blanks not shown: {count} 표시되지 않은 다른 전개도: {count} +@msg A joint does not close by {gap} pt. 이음매가 {gap} pt만큼 닫히지 않습니다. +@msg Two panels pass through each other. 두 패널이 서로 관통합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9434e0edf6..ab8455de30 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3748,6 +3748,12 @@ antiAlias Sharp Scherp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opties tekstexport + Chinese Big 5 Chinees Big 5 + Cyrillic Cyrillisch + Greek Grieks + Turkish Turks + Baltic Baltisch + Central European Centraal-Europees Character Set: Tekenset: Join the lines of each paragraph De regels van elke alinea samenvoegen Line Breaks Regeleinden @@ -10079,3 +10085,13 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Fold Preview Vouwvoorbeeld + Fold Vouwen + Show Fold Lines Vouwlijnen tonen + Three-Quarter Driekwart + Open a document to preview its folded shape. Open een document om de gevouwen vorm te bekijken. +@msg Check the fold lines first. Controleer eerst de vouwlijnen. +@msg Panels: {panels}, hinges: {hinges} Panelen: {panels}, scharnieren: {hinges} +@msg Other blanks not shown: {count} Andere uitslagen niet getoond: {count} +@msg A joint does not close by {gap} pt. Een naad sluit {gap} pt niet. +@msg Two panels pass through each other. Twee panelen gaan door elkaar heen. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14f104c5a7..9713139beb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3295,6 +3295,12 @@ antiAlias Sharp Ostre Encoding: Kodowanie: Line Endings: Znaki końca wiersza: Text Export Options Opcje eksportu tekstu + Chinese Big 5 Chiński Big 5 + Cyrillic Cyrylica + Greek Grecki + Turkish Turecki + Baltic Bałtycki + Central European Środkowoeuropejski Character Set: Zestaw znaków: Join the lines of each paragraph Połącz wiersze każdego akapitu Line Breaks Podziały wierszy @@ -9902,3 +9908,13 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Fold Preview Podgląd złożenia + Fold Złożenie + Show Fold Lines Pokaż linie zgięcia + Three-Quarter Trzy czwarte + Open a document to preview its folded shape. Otwórz dokument, aby zobaczyć podgląd jego złożonego kształtu. +@msg Check the fold lines first. Najpierw sprawdź linie zgięcia. +@msg Panels: {panels}, hinges: {hinges} Panele: {panels}, zawiasy: {hinges} +@msg Other blanks not shown: {count} Inne wykroje nie są pokazane: {count} +@msg A joint does not close by {gap} pt. Połączenie nie domyka się o {gap} pt. +@msg Two panels pass through each other. Dwa panele przechodzą przez siebie. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 958816322d..847946c680 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -394,6 +394,12 @@ antiAlias Sharp Nítido Character Alignment Alinhamento de Caracteres Character / Paragraph Caractere / Parágrafo Character Rotation Rotação de Caractere + Chinese Big 5 Chinês Big 5 + Cyrillic Cirílico + Greek Grego + Turkish Turco + Baltic Báltico + Central European Europa Central Character Set: Conjunto de Caracteres: Character Style Options Opções de Estilo de Caractere Character Styles Estilos de Caractere @@ -10113,3 +10119,13 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Fold Preview Visualização da Dobra + Fold Dobra + Show Fold Lines Mostrar Linhas de Dobra + Three-Quarter Três Quartos + Open a document to preview its folded shape. Abra um documento para visualizar sua forma dobrada. +@msg Check the fold lines first. Verifique primeiro as linhas de dobra. +@msg Panels: {panels}, hinges: {hinges} Painéis: {panels}, dobradiças: {hinges} +@msg Other blanks not shown: {count} Outras planificações não exibidas: {count} +@msg A joint does not close by {gap} pt. Uma junção não fecha por {gap} pt. +@msg Two panels pass through each other. Dois painéis se atravessam. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fb4ba8bf52..4ff987ee2b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -423,6 +423,12 @@ font-technology Variable Вариативные Character Alignment Выравнивание символов Character / Paragraph Символ / Абзац Character Rotation Поворот символов + Chinese Big 5 Китайская Big 5 + Cyrillic Кириллица + Greek Греческая + Turkish Турецкая + Baltic Балтийская + Central European Центральноевропейская Character Set: Набор символов: Character Style Стиль символа Character Style Options Параметры стиля символа @@ -10128,5 +10134,15 @@ shape Open Открытый @msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки. @msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} + Fold Preview Предпросмотр сгиба + Fold Сгиб + Show Fold Lines Показать линии сгиба + Three-Quarter Три четверти + Open a document to preview its folded shape. Откройте документ, чтобы просмотреть его в сложенном виде. +@msg Check the fold lines first. Сначала проверьте линии сгиба. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, шарниры: {hinges} +@msg Other blanks not shown: {count} Другие развёртки не показаны: {count} +@msg A joint does not close by {gap} pt. Стык не смыкается на {gap} pt. +@msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 67460b2306..ca3e9260cb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -415,6 +415,11 @@ font-technology Variable Variabla Character Alignment Teckenjustering Character / Paragraph Tecken / stycke Character Rotation Teckenrotation + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Grekisk + Baltic Baltisk + Central European Centraleuropeisk Character Set: Teckenuppsättning: Character Style Teckenstil Character Style Options Alternativ för teckenstil @@ -9732,4 +9737,14 @@ digits Hindi Hindi @msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje. @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} + Fold Preview Förhandsgranskning av falsning + Fold Falsning + Show Fold Lines Visa falslinjer + Three-Quarter Trekvarts + Open a document to preview its folded shape. Öppna ett dokument för att förhandsgranska dess falsade form. +@msg Check the fold lines first. Kontrollera falslinjerna först. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, gångjärn: {hinges} +@msg Other blanks not shown: {count} Andra ämnen visas inte: {count} +@msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. +@msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 4a92963da5..9fdcc038e9 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -617,6 +617,22 @@ fn monitor_profile_labels_are_in_complete_catalogs() { } } +/// Text Import Options' Character Set choices that name a script or a region (Shift JIS, GB2312 +/// and GB18030 are names of their own), and the error for an unknown character set. +#[test] +fn text_import_character_sets_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Chinese Big 5", "Cyrillic", "Greek", "Turkish", "Baltic", "Central European"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let unknown = r#"text.characterSet `x`: use "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, unknown), unknown, "{code}"); + } +} + /// The Control bar panel menu's items, its groups of options and the edges, and the label of the /// command that turns a group on or off. #[test] @@ -1124,6 +1140,36 @@ fn bundled_fonts_cover_the_catalogs() { assert!(missing.is_empty(), "characters without a glyph: {missing:#?}"); } +/// The faces the web build fetches on demand (`web-fonts.txt`: NanumGothic for Korean, Noto Sans +/// Devanagari for Hindi) cover every character of their scripts that a catalog or a language name +/// uses. Checked where the craft-fonts checkout has them (the desktop build embeds every face). +#[test] +fn web_demand_fonts_cover_the_catalogs() { + use vectorcraft_text::craft_fonts::demand_script; + let demand: Vec<_> = vectorcraft_text::WEB_FONTS.iter().filter(|w| w.demand).collect(); + if demand.is_empty() { + eprintln!("skipped: built without craft-fonts, or one without NanumGothic and Noto Sans Devanagari"); + return; + } + let mut chars: std::collections::BTreeSet = LANGUAGES.iter().flat_map(|l| l.name.chars()).collect(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + chars.extend(entries.iter().flat_map(|(_, _, tr)| tr.chars())); + } + let mut missing = std::collections::BTreeMap::new(); + for w in demand { + let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style) else { continue }; + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + db.add_font(f.bytes.to_vec()); + let face = db.face(f.family, f.style).expect("the craft-fonts face loads"); + let gone: String = chars.iter().filter(|c| demand_script(**c).is_some_and(|s| w.scripts.contains(&s)) && !face.covers(**c)).collect(); + if !gone.is_empty() { + missing.insert(w.family, gone); + } + } + assert!(missing.is_empty(), "characters the web's demand faces lack: {missing:#?}"); +} + /// The Traditional Chinese catalog holds no Simplified-only characters (a translation written /// in the wrong script would read as a typo to every user). #[test] @@ -2186,6 +2232,17 @@ fn georgian_rows_have_no_mtavruli() { assert!(caps.is_empty(), "Mtavruli in ka.tsv: {caps:?}"); } +/// A field label's colon follows the catalog's ":" row: French puts a no-break space before it, +/// Chinese and Japanese write a full-width colon, and English and German write a plain colon. +#[test] +fn label_colons_follow_the_language() { + for (code, want) in [("fr", "X\u{a0}:"), ("zh-hans", "X:"), ("zh-hant", "X:"), ("ja", "X:"), ("de", "X:"), ("en", "X:")] { + set_current(Lang::from_code(code).expect("registered")); + assert_eq!(colon("X"), want, "{code}"); + } + set_current(Lang::EN); +} + /// French rows follow the typography fr.tsv's header sets: a no-break space before : ; ? ! and inside /// « », and the typographic apostrophe ’ in elisions. Text in backticks is code and is not checked, and /// a straight apostrophe inside double quotes is a literal value. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7cf30fe7b8..9e67a2571a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -408,6 +408,12 @@ font-technology Variable Değişken Character Alignment Karakter Hizalaması Character / Paragraph Karakter / Paragraf Character Rotation Karakter Rotasyonu + Chinese Big 5 Çince Big 5 + Cyrillic Kiril + Greek Yunanca + Turkish Türkçe + Baltic Baltık + Central European Orta Avrupa Character Set: Karakter Seti: Character Style Karakter Stili Character Style Options Karakter Stili Seçenekleri @@ -10000,3 +10006,13 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Fold Preview Katlama Önizlemesi + Fold Katlama + Show Fold Lines Katlama Çizgilerini Göster + Three-Quarter Dörtte Üç + Open a document to preview its folded shape. Katlanmış şeklini önizlemek için bir belgeyi açın. +@msg Check the fold lines first. Önce katlama çizgilerini denetleyin. +@msg Panels: {panels}, hinges: {hinges} Paneller: {panels}, menteşeler: {hinges} +@msg Other blanks not shown: {count} Gösterilmeyen diğer açınımlar: {count} +@msg A joint does not close by {gap} pt. Bir birleşim {gap} pt kadar kapanmıyor. +@msg Two panels pass through each other. İki panel birbirinin içinden geçiyor. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dfc13c3827..60bc172495 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -421,6 +421,12 @@ font-technology Variable Варіативні Character Alignment Вирівнювання символів Character / Paragraph Символ / Абзац Character Rotation Поворот символів + Chinese Big 5 Китайська Big 5 + Cyrillic Кирилиця + Greek Грецька + Turkish Турецька + Baltic Балтійська + Central European Центральноєвропейська Character Set: Набір символів: Character Style Стиль символу Character Style Options Параметри стилю символу @@ -9655,3 +9661,13 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Fold Preview Перегляд згину + Fold Згин + Show Fold Lines Показати лінії згину + Three-Quarter Три чверті + Open a document to preview its folded shape. Відкрийте документ, щоб переглянути його у складеному вигляді. +@msg Check the fold lines first. Спершу перевірте лінії згину. +@msg Panels: {panels}, hinges: {hinges} Панелі: {panels}, шарніри: {hinges} +@msg Other blanks not shown: {count} Інші розгортки не показано: {count} +@msg A joint does not close by {gap} pt. Стик не змикається на {gap} pt. +@msg Two panels pass through each other. Дві панелі проходять одна крізь одну. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0fd00829cc..293551aeb8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -500,6 +500,12 @@ font-technology Variable Biến thiên Character options Tùy chọn ký tự Paragraph options Tùy chọn đoạn văn Character Rotation Xoay ký tự + Chinese Big 5 Tiếng Trung Big 5 + Cyrillic Chữ Kirin + Greek Tiếng Hy Lạp + Turkish Tiếng Thổ Nhĩ Kỳ + Baltic Vùng Baltic + Central European Trung Âu Character Set: Bộ ký tự: Character Style Kiểu ký tự Character Style Options Tùy chọn kiểu ký tự @@ -7766,6 +7772,16 @@ breakText Glyphs Glyph @msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào. @msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, bản lề: {hinges}, lỗi: {errors}, cảnh báo: {warnings} + Fold Preview Xem trước nếp gấp + Fold Gấp + Show Fold Lines Hiện đường gấp + Three-Quarter Ba phần tư + Open a document to preview its folded shape. Mở tài liệu để xem trước hình dạng đã gấp của nó. +@msg Check the fold lines first. Hãy kiểm tra đường gấp trước. +@msg Panels: {panels}, hinges: {hinges} Mặt: {panels}, bản lề: {hinges} +@msg Other blanks not shown: {count} Các khuôn trải khác không được hiển thị: {count} +@msg A joint does not close by {gap} pt. Một mối nối hở {gap} pt. +@msg Two panels pass through each other. Hai mặt xuyên qua nhau. # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm @@ -7885,3 +7901,4 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: hãy dùng "{_1}" hoặc "{_2}" diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9507e72514..6ac837bf96 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -374,6 +374,12 @@ antiAlias Sharp 锐利 Character Alignment 字符对齐 Character / Paragraph 字符/段落 Character Rotation 字符旋转 + Chinese Big 5 繁体中文 Big 5 + Cyrillic 西里尔文 + Greek 希腊文 + Turkish 土耳其文 + Baltic 波罗的海文 + Central European 中欧文 Character Set: 字符集: Character Style 字符样式 Character Style Options 字符样式选项 @@ -9884,4 +9890,14 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} + Fold Preview 折叠预览 + Fold 折叠 + Show Fold Lines 显示折线 + Three-Quarter 四分之三视图 + Open a document to preview its folded shape. 打开文档以预览其折叠后的形状。 +@msg Check the fold lines first. 请先检查折线。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},铰链:{hinges} +@msg Other blanks not shown: {count} 未显示的其他展开图:{count} +@msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 +@msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b55eb266a2..fa65e7cd45 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -389,6 +389,12 @@ font-technology Variable 可變 Character / Paragraph 字元/段落 Character Alignment 字元對齊 Character Rotation 字元旋轉 + Chinese Big 5 繁體中文 Big 5 + Cyrillic 西里爾文 + Greek 希臘文 + Turkish 土耳其文 + Baltic 波羅的海文 + Central European 中歐文 Character Set: 字元集: Character Style 字元樣式 Character Style Options 字元樣式選項 @@ -9696,4 +9702,14 @@ breakText Glyphs 字符 @msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} + Fold Preview 摺疊預覽 + Fold 摺疊 + Show Fold Lines 顯示摺線 + Three-Quarter 四分之三視圖 + Open a document to preview its folded shape. 開啟文件以預覽其摺疊後的形狀。 +@msg Check the fold lines first. 請先檢查摺線。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},鉸鏈:{hinges} +@msg Other blanks not shown: {count} 未顯示的其他展開圖:{count} +@msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 +@msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 350c3437ad..c112f3ac8c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -129,6 +129,7 @@ pub use services::{ }; use state::{GeometryStamp, InputGeneration, PendingScreenshot, QueuedScreenshot}; pub(crate) use state::{InputFrame, take_frame_once}; +pub use ui_fonts::on_missing_glyphs; pub struct VectorcraftApp { pub session: Session, diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 989ca7cc58..f21524ddf6 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -867,6 +867,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::trace_presets::open(app, p), "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), + "ui.foldPreview" => crate::addons::packaging::preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), "window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p), "ui.libraryPanel" => crate::panels::library_panel::command(app, p), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 8b174a3abd..cb9917ba39 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1171,6 +1171,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 8f98ee50c0..bfc6c5ecf0 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1378,6 +1378,7 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 { // Tall enough to show its Corners and Shared Edges sections, last in it, which the Corner // Tool's and Shared Edge Merge Tool's menu items open. crate::addons::pathtools::ID => egui::vec2(260.0, 660.0), + crate::addons::packaging::preview::ID => egui::vec2(520.0, 440.0), _ => egui::vec2(260.0, 360.0), } } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 8a3055c2aa..e96c374021 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -263,6 +263,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::packaging::ID => crate::addons::packaging::show(app, ui), + crate::addons::packaging::preview::ID => crate::addons::packaging::preview::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 1dce044f52..83fa16dff6 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -228,6 +228,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::packaging::ID, "Fold Lines", "scissors"), + (crate::addons::packaging::preview::ID, "Fold Preview", "box"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), @@ -719,6 +720,10 @@ pub struct UiState { /// Flattener Preview panel: highlight, overprints, preset and options (`ui.flattenerPreview`). #[serde(default)] pub flattener_preview: crate::panels::flattener_preview::Settings, + /// Fold Preview window: fold amount, view, zoom, perspective, inside color, fold lines and + /// base panel (`ui.foldPreview`). + #[serde(default)] + pub fold_preview: crate::addons::packaging::preview::Settings, /// Color Guide panel: Limit to Library, a swatch library id, "document" (the document's /// swatches) or "" (none) (`ui.colorGuideLimit`). #[serde(default)] @@ -1259,6 +1264,7 @@ impl Default for UiState { color_guide: Default::default(), library_panels: vec![], flattener_preview: Default::default(), + fold_preview: Default::default(), color_guide_limit: String::new(), color_guide_base: None, color_guide_spot: None, diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index ac3f260e95..73c1a30891 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -6,71 +6,154 @@ //! don't have, an installed font covering it is looked for (in the background on native) and added //! to egui's families as their last fallback, on the baseline of each family's first face, from //! the next frame on. Text the UI fonts cover costs no font loading or memory. On the web, which -//! has no system fonts, such characters stay missing-glyph boxes (Japanese too, unless built with -//! craft-fonts). +//! has no system fonts, the shell is told which characters no loaded font covers +//! ([`on_missing_glyphs`]) and fetches a face for them (Korean, Devanagari) when it has one; until +//! a face arrives they stay missing-glyph boxes (Japanese too, unless built with craft-fonts). +//! Characters no font covered are looked for again whenever the font database changes. use std::collections::HashSet; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use egui::epaint::Shape; use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily}; use egui::{FontData, FontDefinitions, FontFamily, FontId, FontTweak, LayerId}; use vectorcraft_text::{FontDb, FontFace}; +/// Called with the painted characters no loaded or installed font covers. +static MISSING_GLYPHS: OnceLock = OnceLock::new(); + +/// Have `f` called (on the UI thread, after a frame) with the characters the interface painted +/// that no loaded or installed font covers, so it can load a font for them: the web shell fetches +/// its `demand` craft-fonts faces. A character is reported again only after the fonts change and it +/// is still not covered. The first call sets it; later calls are ignored. +pub fn on_missing_glyphs(f: fn(&[char])) { + let _ = MISSING_GLYPHS.set(f); +} + +/// What one search for fallback faces found. +struct Found { + /// The faces covering the characters looked for, each once. + faces: Vec>, + /// The characters no face covers. + uncovered: Vec, + /// [`FontDb::generation`] when the search started. + generation: u64, +} + +/// Look in `db` for the faces covering `chars`, each through `lookup`. +fn search(db: &FontDb, chars: Vec, lookup: impl Fn(&FontDb, char) -> Option>) -> Found { + // Read before the lookups: when a font is added during them, the generation kept is older than + // the database's, and the characters not found are looked for again. + let generation = db.generation(); + let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); + for c in chars { + match lookup(db, c) { + Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), + Some(_) => {} + None => uncovered.push(c), + } + } + Found { faces, uncovered, generation } +} + #[derive(Default)] pub(crate) struct UiFonts { /// Characters looked at already: the UI fonts have them, a fallback was added (or is being /// looked for), or no font has them. seen: HashSet, + /// Characters no font covered at the last search: looked for again once the font database's + /// generation is no longer [`UiFonts::searched`]. + uncovered: HashSet, + /// The font database's generation when the last search started. + searched: u64, /// The fonts added to egui, by name. added: HashSet, /// The faces covering the characters being looked for (native: looked for on a thread). #[cfg(not(target_arch = "wasm32"))] - pending: Option>>>, + pending: Option>, + /// The search thread can't be created (tests). + #[cfg(all(test, not(target_arch = "wasm32")))] + spawn_fails: bool, } impl UiFonts { /// After a frame is laid out: add the fallback fonts found since the last frame, and look for /// fonts covering the characters this frame painted that the UI fonts lack. pub(crate) fn frame(&mut self, ctx: &egui::Context) { + self.frame_in(ctx, FontDb::global(), MISSING_GLYPHS.get().copied().unwrap_or(|_| {})); + } + + /// [`UiFonts::frame`] looking through `db`, reporting uncovered characters to `report`. + fn frame_in(&mut self, ctx: &egui::Context, db: &'static FontDb, report: fn(&[char])) { #[cfg(not(target_arch = "wasm32"))] - if let Some(faces) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { + if let Some(found) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { self.pending = None; - self.install(ctx, &faces); + self.found(ctx, found, report); + } + let mut missing = self.missing(ctx); + #[cfg(not(target_arch = "wasm32"))] + let idle = self.pending.is_none(); + #[cfg(target_arch = "wasm32")] + let idle = true; + // A font added since (a web face fetched for them) may cover them now. + let retry: Vec = + if idle && !self.uncovered.is_empty() && db.generation() != self.searched { self.uncovered.drain().collect() } else { vec![] }; + if !retry.is_empty() { + missing.extend_from_slice(&retry); + missing.sort_unstable(); + missing.dedup(); } - let missing = self.missing(ctx); if missing.is_empty() { return; } - let find = move || { - let mut faces: Vec> = vec![]; - for c in missing { - if let Some(f) = FontDb::global().face_covering(c) - && !faces.iter().any(|x| x.id() == f.id()) - { - faces.push(f); - } - } - faces - }; + #[cfg(not(target_arch = "wasm32"))] + let looked_for = missing.clone(); + let find = move || search(db, missing, FontDb::face_covering); // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). #[cfg(not(target_arch = "wasm32"))] { let (tx, rx) = std::sync::mpsc::channel(); let repaint = ctx.clone(); - let spawned = std::thread::Builder::new().name("ui-font-fallback".into()).spawn(move || { + let spawned = self.spawn_search(move || { // The receiver is gone only when the app is. let _ = tx.send(find()); repaint.request_repaint(); }); if spawned.is_ok() { self.pending = Some(rx); + } else { + // Not looked for: the characters met this frame are looked for when painted again, + // and the ones no font covered wait for the fonts to change again. + for c in looked_for.iter().filter(|c| !retry.contains(c)) { + self.seen.remove(c); + } + self.uncovered.extend(retry); } } // The web has only the loaded fonts to look through: quick, on this thread. #[cfg(target_arch = "wasm32")] - self.install(ctx, &find()); + self.found(ctx, find(), report); + } + + /// Run `search` on a thread of its own. + #[cfg(not(target_arch = "wasm32"))] + fn spawn_search(&self, search: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + #[cfg(test)] + if self.spawn_fails { + return Err(std::io::Error::other("no thread for the font search")); + } + std::thread::Builder::new().name("ui-font-fallback".into()).spawn(search).map(|_| ()) + } + + /// Add the faces a search found, and keep (and report) the characters it found no face for. + fn found(&mut self, ctx: &egui::Context, found: Found, report: fn(&[char])) { + self.install(ctx, &found.faces); + self.searched = found.generation; + if !found.uncovered.is_empty() { + report(&found.uncovered); + self.uncovered.extend(found.uncovered); + } } /// Characters painted this frame that the UI fonts lack and haven't been looked for, now @@ -135,8 +218,14 @@ impl UiFonts { /// Wait for the font search running, if any, and add what it found (tests). #[cfg(test)] pub(crate) fn finish(&mut self, ctx: &egui::Context) { - if let Some(faces) = self.pending.take().and_then(|rx| rx.recv().ok()) { - self.install(ctx, &faces); + self.finish_with(ctx, |_| {}); + } + + /// [`UiFonts::finish`], reporting uncovered characters to `report` (tests). + #[cfg(test)] + fn finish_with(&mut self, ctx: &egui::Context, report: fn(&[char])) { + if let Some(found) = self.pending.take().and_then(|rx| rx.recv().ok()) { + self.found(ctx, found, report); } } } @@ -399,8 +488,111 @@ mod tests { for c in installed { assert!(has_glyph(&ctx, c), "{c} has a glyph"); } - // Looked for once: a later frame starts no search. + // Looked for once: a later frame starts no search, unless characters no font covered are + // looked for again because the fonts changed (other tests add fonts meanwhile). + let searched = fonts.searched; frame(&ctx, &mut fonts, text); - assert!(fonts.pending.is_none()); + assert!(fonts.pending.is_none() || FontDb::global().generation() != searched, "a search with the fonts unchanged"); + } + + thread_local! { + static REPORTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + fn report(chars: &[char]) { + REPORTED.with(|r| r.borrow_mut().extend_from_slice(chars)); + } + + /// Run a frame painting `text` with fallbacks looked for in `db`, then wait for the search. + fn frame_in(ctx: &egui::Context, fonts: &mut UiFonts, text: &str, db: &'static FontDb) { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.label(text); + fonts.frame_in(ui.ctx(), db, report); + }); + out.textures_delta.clear(); + fonts.finish_with(ctx, report); + } + + /// A character painted while no font covers it is reported once, and draws once a font that + /// covers it is added (as the web fetches one), with no further search while the fonts stay + /// the same. The character is a private-use one, which no craft-fonts face covers either (the + /// database holds them when the build embeds craft-fonts). + #[test] + fn a_font_added_later_draws_characters_painted_before_it() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, PRIVATE_USE_FAMILY, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + // Scanned first, as the app's database is at startup: a first scan during the search would + // change the generation and start one more search. + db.families(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(!has_glyph(&ctx, PRIVATE_USE_CHAR), "no font covers the character yet"); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [PRIVATE_USE_CHAR], "reported once"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.pending.is_none() && REPORTED.with(|r| r.borrow().len()) == 1, "no new search while the fonts are the same"); + db.add_font(private_use_font().expect("the test face builds")); + assert!(db.face(PRIVATE_USE_FAMILY, "Regular").is_some()); + // The next frame looks again and adds the face; the one after draws with it. + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); + } + + /// A font added while a search runs (another thread loading one) leaves the search's generation + /// older than the database's, so the next frame looks again for the characters it did not find. + #[test] + fn a_font_added_during_a_search_has_its_characters_looked_for_again() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + let found = search(db, vec![PRIVATE_USE_CHAR], |db, c| { + let face = db.face_covering(c); + db.add_font(private_use_font().expect("the test face builds")); + face + }); + assert_eq!(found.uncovered, [PRIVATE_USE_CHAR], "the lookup ran before the font was added"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + fonts.found(&ctx, found, |_| {}); + // Painted before: the character is looked for again only because the fonts changed. + fonts.seen.insert(PRIVATE_USE_CHAR); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + } + + /// A search whose thread can't be created leaves its characters to be looked for later: a + /// character painted for the first time is looked for when it is painted again, and one no font + /// covered stays waiting for the fonts to change. + #[test] + fn a_search_that_cannot_start_keeps_its_characters() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + db.families(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts { spawn_fails: true, ..UiFonts::default() }; + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.pending.is_none() && !fonts.seen.contains(&PRIVATE_USE_CHAR), "not looked for yet"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "looked for when painted again"); + db.add_font(private_use_font().expect("the test face builds")); + fonts.spawn_fails = true; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "still waiting to be looked for again"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f78d8b375b..7eba21351a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -738,7 +738,7 @@ folder, then opens the dialog searching it. The web shows a status line instead disabled there. Text Import Options: placing a `.txt` file through the app (`file.place` with a file and no `text` options, the Place -dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: `unicode`/`ansi`, +dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: a `text.characterSet` value, `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces`, `spaces`). `ui.dialog.confirm` places the file as area type with those options (`file.place {text: {…}}`). diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 48250c14e6..e1f2b735f8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -336,7 +336,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | CorelDRAW `.cdr` | open | no | no | | -| Text `.txt` | place, export | place (Text Import Options) | yes | | +| Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | | Word `.doc` | place | place (area type with the same formatting as `.docx`, from the style sheet's styles and direct formatting; Word 97 and later) | no | `tests/textimport.rs`, `place/doc.rs`; fuzzed (`text_import_fuzz.rs`); pictures, headers, footers, notes, comments and text boxes are left out with a warning; encrypted and fast-saved documents are refused | diff --git a/docs/gaps.md b/docs/gaps.md index 2822e483b2..96a94b325c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Evidence:** Brazilian Portuguese catalog complete under the tests (menus, literals, messages; one|other plurals; #1914). Vietnamese catalog complete under the tests (menus, literals, messages; one plural form). Czech render-site bypasses reduced in file dialogs, diagnostics, preset names and contributor tooltips; gradient grammar and printer-mark context corrected (see [localization-parity.md](localization-parity.md)). Native review and the remaining missing-language work remain. - **Missing:** Arabic catalog and right-to-left layout; current gaps in other catalogs and native - review; Hindi wording/layout review and a web Devanagari font; a Korean UI font for the web. + review; Hindi wording/layout review. The web build fetches NanumGothic for Korean and Noto Sans + Devanagari for Hindi when the interface needs them (`crates/text/web-fonts.txt`, `demand`). Hindi now has a catalog and the pinned egui fork shapes Devanagari. Indonesian already has a catalog (see [localization-parity.md](localization-parity.md)); it is not an absent language. - **Estimate:** 50–85 h plus human review (Brazilian Portuguese completed 2026-10-14). diff --git a/docs/localization-hi.md b/docs/localization-hi.md index 743a1697ec..55c91c6505 100644 --- a/docs/localization-hi.md +++ b/docs/localization-hi.md @@ -131,9 +131,12 @@ The pinned egui fork shapes Devanagari with HarfRust. The desktop's existing `Ui finds an installed covering face, such as Nirmala UI, Kohinoor Devanagari or Noto Sans Devanagari. If a `CRAFT_FONTS_DIR` build includes a face tagged `Deva`, it is also installed at the end of each UI font family. No font binaries are added to this repository. Without either an embedded -or installed covering face, Hindi cannot display correctly. The web has no system fonts and -needs a Devanagari face supplied through craft-fonts; this catalog alone does not supply one. +or installed covering face, Hindi cannot display correctly. The web has no system fonts. A web +build made with craft-fonts serves Noto Sans Devanagari Regular beside the wasm and fetches it +when the interface language is Hindi or the interface paints Devanagari +(`crates/text/web-fonts.txt`, `demand`); until it arrives, Devanagari draws as missing-glyph boxes. +Other languages do not fetch it. Before release: native-speaker review of the draft (especially less common labels and error -messages), visual checks for clipped labels and matras at different UI scales, and a web-font -build. Reviewers should use this glossary to make terminology corrections consistently. +messages), and visual checks for clipped labels and matras at different UI scales, on the +desktop and on the web. Reviewers should use this glossary to make terminology corrections consistently. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 2625ed616c..66b73023bd 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -31,7 +31,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all (3,554 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review, layout and web font | +| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | @@ -39,13 +39,13 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Indonesian | `id` | 6,825 rows, 1,036 of them `@msg` and 47 `@msgplural` (counted 2026-11-14 on `main` at `676f0524cc`): the untranslated report lists 60 missing menu strings, 35 `tl!` literals and 13 undo labels for it; not in `COMPLETE_MESSAGES`, and checked against the same scanned messages it lacks 2,508; one plural form | most dialogs and tooltips; status and error messages partial | Latin | no | full | — (review) | | Japanese | `ja` | 4,004 / 4,020 (99.6%) | partial (3,562 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 98 messages without a Japanese row, 77 of which every complete-message language lacks; open #7116 and #7211 translate 35 of them) | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (3,563 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 52 missing messages for it, which open #7116, #7211 and #7378 translate) | Latin | contributor-written, not reviewed | full | — (review) | -| Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all (3,438 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 39 missing messages for it) | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build has no Korean UI font yet (craft-fonts); IME path exists | no (AI-drafted) | full | — (review; web font) | +| Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all (3,438 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 39 missing messages for it) | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build fetches NanumGothic from craft-fonts when the interface needs it; IME path exists | no (AI-drafted) | full | — (review) | | Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | dialogs and tooltips all; messages partial (1,750 `@msg` and 49 `@msgplural` rows, counted 2026-11-14: the untranslated report lists 1,875 messages without a Vietnamese row, 53 of which open #7211, #7378, #7405 and #7434 translate) | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) | **Historical 12-language score: ~82%** (equal weights: 100 + 85 + 100 + 0 + 0 + 100 + 100 + 100 + 100 + 98 + 100 + 100, over 12). **To `full` for all twelve: ~50–85 h** (historical estimate, not re-scored here). Hindi now has a catalog that the tests count as complete, and UI shaping; its remaining work is the rows the -untranslated report lists for it, native review, layout checking and the web font. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each +untranslated report lists for it, native review and layout checking. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each plus review. Native-speaker review is human work and isn't in the hours. ## Other shipped languages diff --git a/docs/mcp.md b/docs/mcp.md index 89a5a0727b..11c3165efa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8509,10 +8509,15 @@ the document; so does `object.expand`. ``` Placing a text file (`.txt`) sets it as area type: `file.place {path | name+dataBase64, text?: {characterSet?: -"unicode" | "ansi", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` +"unicode" | "ansi" | "shiftJis" | "gb2312" | "chineseBig5" | "cyrillic" | "gb18030" | "greek" | "turkish" | "baltic" | +"centralEuropean", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` (Text Import Options). Unicode reads UTF-8, or UTF-16 with a byte-order mark; ANSI reads Windows-1252 (Mac Roman on -`mac`). Unicode reads a file without a byte-order mark as UTF-16 by the rule `dataset.import` uses: at least half of -its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian +`mac`). The other sets use the WHATWG Encoding Standard's decoders: `shiftJis` Shift_JIS, `gb2312` GBK, `chineseBig5` +Big5, `cyrillic` windows-1251 (x-mac-cyrillic on `mac`), `gb18030` gb18030, and `greek`, `turkish`, `baltic` and +`centralEuropean` windows-1253, 1254, 1257 and 1250 on both platforms. They read a byte-order mark as ordinary bytes +and a malformed sequence as U+FFFD. An unknown set, or an option of the wrong type (`characterSet: 3`, +`removeLineReturns: "yes"`), is an error, and nothing is placed. Unicode reads a file without a byte-order mark as +UTF-16 by the rule `dataset.import` uses: at least half of its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian when more of its units start with a NUL byte than end with one, and little-endian otherwise. Any other file is read as UTF-8, else as the platform's 8-bit set: one with fewer NUL bytes, one with an odd length, one where both byte orders read a line break, and one that isn't valid UTF-16 in that order or holds a NUL character. `removeLineReturns` joins @@ -13694,10 +13699,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch` and `addon.packaging.check`. In the -desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, -Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the selection, and Check Fold Lines runs -`addon.packaging.check`. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and +`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, +Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the +selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`. ### Fold line roles @@ -13793,6 +13798,54 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold Preview + +`addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads +the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or +the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it +to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from +the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of +panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, +whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of +hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything +else is an error. The command does not change the document. + +Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b, +angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document +coordinates. `frame` gives where the flat blank's x and y directions, its printed side and its origin end up, in points, +with x to the right, y up and z toward the printed side of the flat blank. `kind` is `tree` for the hinges the panels +turn about and `closing` for the others. `collisions` lists the panels that pass through each other; panels stacked in +one plane, such as the top flaps of a closed box, are not listed. Without a blank (`ok` false), `blank` and `base` are +null and the lists are empty; `issues` are those of `addon.packaging.check`. + +The Fold Preview window (Object › Plug-ins › Packaging Tools › Fold Preview, or the Fold Lines panel's Fold Preview +button) shows the blank that the document's shown fold lines make, folded, with the document's printed art on the +outside of each panel and the board's inside color on the back. The print leaves out the fold lines, unless Show Fold +Lines is on, and the layers that do not print. Under the view, the Fold slider sets the amount and the Zoom slider the +zoom; a status line gives the panels and hinges and says when a joint does not close, when two panels pass through each +other, when other blanks are not shown and when the fold lines have an error. Dragging in the view turns it, a +Shift-drag keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a panel makes it +the base, and the arrow keys turn the view by 5° when it has the keyboard focus. The view is drawn at the display's +pixel density up to 2,097,152 pixels (2,048 × 1,024) and 4,096 pixels along a side, and at a lower density past either, +and the print is a raster whose longest side is 2,048 pixels, rendered again when the document changes. + +`ui.foldPreview` (`{amount?, view?: front|back|left|right|top|bottom|threeQuarter, rotateX?, rotateY?, zoom?, +perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the +window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side +toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to +160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`, or `""` for white; `base` is a point in a panel +of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice +the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. +VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the +fold lines hidden. Saved settings out of range are brought into range when the window is drawn. Result: the window's +settings, and `frame`: the last frame's `{width, height}` in pixels and how long the fold and the drawing took (`foldMs`, +`drawMs`), or null before the first frame. The view is folded and drawn again only when the document, the settings or +the window's size change. + +```json +{"name":"run_command","arguments":{"command":"ui.foldPreview","params":{"amount":0.5,"view":"threeQuarter","perspective":30}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c7d63b64a8..88d2d57f3e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1640,6 +1640,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Burasagari ([the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)) leaves a right-to-left paragraph's comma or full stop inside its line, which then ends at a break where it fits with the mark, and in a left-to-right line with right-to-left text and a tab it hangs a mark only when the mark is drawn at the line's right end and the rest of the line fits as drawn; otherwise the line ends at the latest break that fits as drawn. Both are VectorCraft's own rules (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/hang.rs`). Scores and estimates are unchanged. The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). + On the web, Korean and Hindi interface text draws with real glyphs: a web build made with craft-fonts fetches NanumGothic for Hangul (about 2 MB) or Noto Sans Devanagari (about 280 KB) only when the interface language or the interface's own text (a layer or file name, the language picker) needs that script. The frame after the face arrives adds it to the interface fonts, and the frame after that draws the characters painted before it with that face. Sessions in other languages do not download them at startup. After a failed fetch the next try comes about 30 seconds later, and the wait doubles after each further failure, for at most five tries (`crates/text/web-fonts.txt`, `apps/vectorcraft-web/src/fonts.rs`, `apps/vectorcraft-web/src/demand.rs`, `crates/ui-egui/src/ui_fonts.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. The Glyphs panel menu (with the East Asian options) offers Traditional, Expert, JIS 04, JIS 90, JIS 78 and JIS 83 Forms, Monospaced Full-Width, Half-Width, Third-Width and Quarter-Width Forms, and Revert To Default Forms ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); each draws the selected characters with the font's OpenType feature for that form (`trad`, `expt`, `jp04`, `jp90`, `jp78`, `jp83`, `fwid`, `hwid`, `twid`, `qwid`), one form at a time, and a form none of the faces that draw the selected text has a feature for (in `GSUB`, or for the width forms `GSUB` or `GPOS`) is disabled. A form other than the default takes away a character's glyph choice, and with a width form Proportional Metrics' `palt` is not applied and the font's pair kerning is off. `text.setFormat` and `text.setRangeStyle {glyphForm}` set it; the native file, character styles, the canvas, PDF and SVG (`font-feature-settings`) keep it (`tests::typo::glyph_forms_draw_the_fonts_east_asian_forms`, `typecmd::area_tests::glyph_form_is_one_character_attribute_saved_only_when_set`, `typecmd::area_tests::a_glyph_form_takes_away_the_characters_glyph_choice`, `features::tests::width_forms_turn_off_proportional_metrics`, `panels::glyphs` tests). Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. @@ -2107,6 +2108,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). + - Text Import Options' Character Set offers Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, the plain-text encodings [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-and-export-text.html) lists for placed text. `file.place {text: {characterSet}}` decodes each with its WHATWG Encoding Standard decoder. The mapping is VectorCraft's own: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with `platform: "mac"`), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD, and the last set confirmed is remembered (`crates/engine/src/tests/textimport.rs`, `crates/ui-egui/src/dialogs/text_import.rs`). - A Shift-click with the loaded place cursor opens the current file's import options (text, DXF, PDF page or embedded PSD) and OK places it at the click, with Show Import Options on or off and for a cursor loaded by `file.place.queue` ([Place multiple files](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). VectorCraft's own rules: a file without such a dialog places as a click does, Cancel leaves the file unplaced, a Shift-drag places at the dragged size, and headless the Shift-click places as a click (`crates/tools/src/place.rs`, `crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged.