mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 19:04:25 +01:00
Merge main into feat/arrows-brush-library
This commit is contained in:
commit
6e65339e0f
155 files changed
+12164
-581
No files matched your search
Generated
+1
@@ -6775,6 +6775,7 @@ dependencies = [
|
||||
"craft-stream-codecs",
|
||||
"craft-xml",
|
||||
"crc32fast",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
"heic-rs",
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -238,10 +238,12 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
|
||||
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_script_data(&mut h.session);
|
||||
prefs_dir::attach_metadata_templates_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
|
||||
@@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
|
||||
})
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -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<State>,
|
||||
}
|
||||
|
||||
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<usize> {
|
||||
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<i32> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,22 @@
|
||||
//! Craft-fonts faces served beside the wasm (`fonts/<sha16>/…`, 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<bool> = const { Cell::new(false) };
|
||||
/// The `demand` faces' fetches.
|
||||
static DEMAND: RefCell<Demand> = 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<Option<egui::Context>> = 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<Vec<&'static WebFont>> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect());
|
||||
let queue: Rc<Vec<&'static WebFont>> = 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());
|
||||
|
||||
@@ -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))]
|
||||
|
||||
@@ -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::<Vec<_>>());
|
||||
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;
|
||||
|
||||
@@ -73,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(
|
||||
@@ -83,8 +83,9 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
PickRequest::FolderAt(folder) => return d.folder(folder),
|
||||
};
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_));
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
|
||||
@@ -98,6 +99,37 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn a_folder_picker_asked_for_a_folder_starts_there() {
|
||||
/// The settings a dialog was given, by name.
|
||||
#[derive(Default)]
|
||||
struct Recorded(Vec<String>);
|
||||
impl DialogSettings for Recorded {
|
||||
fn parent(self, _: &winit::window::Window) -> Self {
|
||||
self
|
||||
}
|
||||
fn title(mut self, title: &str) -> Self {
|
||||
self.0.push(format!("title {title}"));
|
||||
self
|
||||
}
|
||||
fn filter(mut self, name: &str, _: &[impl ToString]) -> Self {
|
||||
self.0.push(format!("filter {name}"));
|
||||
self
|
||||
}
|
||||
fn folder(mut self, folder: &str) -> Self {
|
||||
self.0.push(format!("folder {folder}"));
|
||||
self
|
||||
}
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.0.push(format!("name {name}"));
|
||||
self
|
||||
}
|
||||
}
|
||||
assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]);
|
||||
assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty());
|
||||
}
|
||||
|
||||
/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the
|
||||
/// window and keeps it in front).
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -130,9 +162,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
|
||||
}
|
||||
let paths = match request {
|
||||
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
|
||||
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::Save(_) => dialog.save_file().into_iter().collect(),
|
||||
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
|
||||
}
|
||||
@@ -315,7 +347,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
let picked = dialog.pick_file();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
PickRequest::OpenMany => {
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => {
|
||||
let picked = dialog.pick_files();
|
||||
Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() })
|
||||
}
|
||||
@@ -334,7 +366,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
// on that nil; treat the pick as cancelled instead (#5980).
|
||||
Err(()) => Box::pin(async move { Vec::new() }),
|
||||
},
|
||||
PickRequest::Folder => {
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => {
|
||||
let picked = dialog.pick_folder();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
@@ -355,7 +387,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.and_then(|w| w.window_handle().ok())
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -363,6 +395,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))),
|
||||
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
|
||||
// Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows
|
||||
// dialogs run the window's events while they are open.
|
||||
@@ -410,6 +443,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
|
||||
@@ -554,6 +554,7 @@ fn main() -> std::process::ExitCode {
|
||||
// File Info's metadata templates live in their own folder next to the preferences.
|
||||
prefs_dir::attach_metadata_templates_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
|
||||
@@ -81,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people
|
||||
/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first
|
||||
/// needs them.
|
||||
pub fn attach_script_data(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Script Data") {
|
||||
session.attach_script_data(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
|
||||
/// now on there. After the preferences were restored: the folder is the one place the presets live.
|
||||
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -631,6 +631,8 @@ pub enum FirstBaseline {
|
||||
XHeight,
|
||||
/// The first line's leading.
|
||||
Leading,
|
||||
/// The top of the first line's ideographic em box touches the frame top.
|
||||
EmBoxHeight,
|
||||
/// Exactly `first_baseline_min` below the top.
|
||||
Fixed,
|
||||
}
|
||||
@@ -647,6 +647,20 @@ fn text_flow_is_saved_only_when_by_rows() {
|
||||
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err());
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from
|
||||
/// before it read their own first baseline as they did, Ascent when they have none.
|
||||
#[test]
|
||||
fn em_box_height_first_baseline_is_saved_and_read_back() {
|
||||
let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() };
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0)));
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(saved).unwrap(), set);
|
||||
let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0});
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(old).unwrap().first_baseline, FirstBaseline::Leading);
|
||||
assert_eq!(serde_json::from_value::<AreaOptions>(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent);
|
||||
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"firstBaseline": "emBox"})).is_err());
|
||||
}
|
||||
|
||||
/// 120 × 40 area type at (40, 40), its text drawn at twice its size.
|
||||
fn area_type() -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default());
|
||||
|
||||
@@ -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 }
|
||||
@@ -70,8 +73,9 @@ log = { workspace = true }
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "process"] }
|
||||
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`).
|
||||
# Already in Cargo.lock (walkdir), so this adds no new crate.
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
|
||||
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
|
||||
# (walkdir), so this adds no new crate.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
same-file = "1.0.6"
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
let mut v = roles::specs();
|
||||
v.extend(check::specs());
|
||||
v.extend(fold::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind {
|
||||
}
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<FoldLine>,
|
||||
pub non_printing: Vec<u64>,
|
||||
}
|
||||
|
||||
/// The tolerance `p` gives for `cmd`, or the default.
|
||||
pub(super) fn tolerance(p: &Value, cmd: &str) -> Result<f64> {
|
||||
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<Lines> {
|
||||
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<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
|
||||
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<NodeId>) -> 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<Value> {
|
||||
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<Blank>, Vec<Issue>) {
|
||||
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<Value> = 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<Value> {
|
||||
issues
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let mut row = json!({
|
||||
@@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<NodeId> = 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);
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Blank>, Vec<Issue>) {
|
||||
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<NodeId> {
|
||||
fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec<NodeId>) {
|
||||
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<Value> {
|
||||
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<Value> = 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<Value> = 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::<Vec<_>>(),
|
||||
"issues": issue_rows(&issues, lines.scope),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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<u64>) {
|
||||
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<f64> = 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<u64> = 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<u64> = 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<u64> = 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:?}");
|
||||
}
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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 pl
Line truncated
|
||||
"{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
Line truncated
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
|
||||
@@ -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<usize> {
|
||||
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<String>
|
||||
/// `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");
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that l
Line truncated
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that l
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -90,6 +90,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
list_installed
|
||||
),
|
||||
cmd!(
|
||||
query "script.grants",
|
||||
"List Script File Permissions",
|
||||
[],
|
||||
None,
|
||||
"{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}",
|
||||
always,
|
||||
grants
|
||||
),
|
||||
cmd!(
|
||||
query "script.grants.revoke",
|
||||
"Revoke Script File Permissions",
|
||||
[],
|
||||
None,
|
||||
"{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}",
|
||||
always,
|
||||
grants_revoke
|
||||
),
|
||||
cmd!(
|
||||
query "script.check",
|
||||
"Check Script",
|
||||
@@ -246,6 +264,18 @@ impl Session {
|
||||
self.scripts_dir = Some(dir);
|
||||
}
|
||||
|
||||
/// Keep each script's data folder (`Folder.userData`) in the folder `dir`, and the file access
|
||||
/// people allow scripts with Always in [`script::files::GRANTS_FILE`] beside it. The folders are
|
||||
/// made when a script first needs them.
|
||||
pub fn attach_script_data(&mut self, dir: std::path::PathBuf) {
|
||||
self.script_data_dir = Some(dir);
|
||||
}
|
||||
|
||||
/// The folder of the scripts' data folders ([`Session::attach_script_data`]); none on the web.
|
||||
pub fn script_data_dir(&self) -> Option<&std::path::Path> {
|
||||
self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
/// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders.
|
||||
pub fn scripts_dir(&self) -> Option<&std::path::Path> {
|
||||
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
@@ -335,6 +365,55 @@ fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"folder": folder, "scripts": scripts, "truncated": listing.truncated, "unreadable": listing.unreadable}))
|
||||
}
|
||||
|
||||
fn grants(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) };
|
||||
let file = dir.with_file_name(script::files::GRANTS_FILE);
|
||||
// A script or a granted path outside the automation read roots is named by its file name alone.
|
||||
let mut grants = script::files::stored_grants(dir);
|
||||
for g in &mut grants {
|
||||
for key in ["script", "path"] {
|
||||
if let Some(name) = g[key].as_str().and_then(hidden_name) {
|
||||
g[key] = json!(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let file = file.to_string_lossy();
|
||||
Ok(json!({"grants": grants, "file": super::fileio::shown_path(&file)}))
|
||||
}
|
||||
|
||||
fn grants_revoke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "script.grants.revoke";
|
||||
let path_of = |key: &str| match p.get(key) {
|
||||
None => Ok(None),
|
||||
// A path the request may not read (outside the automation read roots, a network path among
|
||||
// them) is compared as written, without looking it up.
|
||||
Some(Value::String(t)) if !t.is_empty() => Ok(Some(
|
||||
crate::file_access::check_read(t)
|
||||
.ok()
|
||||
.and_then(|()| std::fs::canonicalize(t).ok())
|
||||
.map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()),
|
||||
)),
|
||||
Some(_) => Err(bad(C, format!("`{key}` must be a path"))),
|
||||
};
|
||||
let (script_path, path) = (path_of("script")?, path_of("path")?);
|
||||
let all = match p.get("all") {
|
||||
None => false,
|
||||
Some(Value::Bool(true)) => true,
|
||||
Some(_) => return Err(bad(C, "`all` must be true")),
|
||||
};
|
||||
if all == (script_path.is_some() || path.is_some()) {
|
||||
return Err(bad(C, "give `all`, or `script` and `path` or one of them"));
|
||||
}
|
||||
// A running script holds the grants it started with until it ends.
|
||||
if s.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
let Some(dir) = s.script_data_dir() else { return Ok(json!({"removed": 0})) };
|
||||
let removed = script::files::revoke_grants(dir, script_path.as_deref(), path.as_deref())
|
||||
.map_err(|e| EngineError::Other(format!("the script file permissions could not be saved: {e}")))?;
|
||||
Ok(json!({"removed": removed}))
|
||||
}
|
||||
|
||||
/// The folder a script is in, which its included files are read from.
|
||||
struct Folder {
|
||||
dir: std::path::PathBuf,
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
|
||||
@@ -2796,6 +2796,44 @@ fn area_options_columns_change_layout() {
|
||||
assert!(s.execute("text.areaOptions", &json!({"firstBaseline": "nope"})).is_err());
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height: set, reported and undone like the other kinds, with Min as the
|
||||
/// least distance; setting it again adds no undo step, and the refusal of an unknown kind lists it.
|
||||
#[test]
|
||||
fn area_options_set_the_em_box_height_first_baseline() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "word ".repeat(20), "area": {"width": 300, "height": 120}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let first = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines[0].first_baseline,
|
||||
_ => panic!("area type"),
|
||||
};
|
||||
let ascent = first(&s);
|
||||
let r = s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap();
|
||||
assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(0.0)));
|
||||
let em_box = first(&s);
|
||||
assert!(em_box > 0.0 && (em_box - ascent).abs() > 0.1, "{em_box} {ascent}");
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no change, no undo step");
|
||||
// A Min nearer the top keeps the em box; one further down is the distance.
|
||||
s.execute("text.areaOptions", &json!({"firstBaselineMin": em_box / 2.0})).unwrap();
|
||||
assert!((first(&s) - em_box).abs() < 1e-9);
|
||||
let r = s.execute("text.areaOptions", &json!({"firstBaselineMin": 30})).unwrap();
|
||||
assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(30.0)));
|
||||
assert!((first(&s) - 30.0).abs() < 1e-9);
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent");
|
||||
assert!((first(&s) - ascent).abs() < 1e-9);
|
||||
let e = s.execute("text.areaOptions", &json!({"firstBaseline": "emBox"})).unwrap_err().to_string();
|
||||
assert!(e.contains("emBoxHeight"), "{e}");
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent");
|
||||
}
|
||||
|
||||
/// `rowGutter` sets a gutter between rows of its own, the reply passes it back, and a gutter
|
||||
/// given alone is the rows' and the columns' again.
|
||||
#[test]
|
||||
|
||||
@@ -25,7 +25,9 @@
|
||||
//! guard against other programs on the computer.
|
||||
//!
|
||||
//! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`)
|
||||
//! are read from, inside the roots.
|
||||
//! are read from, and the places its `File` and `Folder` objects read and write, inside the roots.
|
||||
//! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the
|
||||
//! files of the open documents.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::OsString;
|
||||
@@ -174,7 +176,7 @@ fn with_scope<T>(scope: Option<Scope>, f: impl FnOnce() -> T) -> T {
|
||||
/// Run `f` with `roots` in force on this thread (`None`: as things stand).
|
||||
pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -> T {
|
||||
match roots {
|
||||
Some(r) => with_scope(Some(Scope::Confined(r.clone())), f),
|
||||
Some(r) => with_gate_reads_exempt(false, || with_scope(Some(Scope::Confined(r.clone())), f)),
|
||||
None => f(),
|
||||
}
|
||||
}
|
||||
@@ -182,25 +184,111 @@ pub fn confine<T>(roots: Option<&Arc<AutomationRoots>>, f: impl FnOnce() -> T) -
|
||||
/// Run `f` with no roots in force on this thread: what the person at the keyboard does, and the
|
||||
/// app's own folders.
|
||||
pub fn unconfined<T>(f: impl FnOnce() -> T) -> T {
|
||||
with_scope(Some(Scope::Unconfined), f)
|
||||
with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f))
|
||||
}
|
||||
|
||||
/// This thread's scope, to carry to work it hands to another thread ([`ScopeHandle::run`]).
|
||||
thread_local! {
|
||||
/// Are reads on this thread exempt from the gate of the script command it runs? Only inside an
|
||||
/// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]).
|
||||
static GATE_READS_EXEMPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Puts the exemption it replaced back when dropped (also when `f` panics).
|
||||
struct RestoreExempt(bool);
|
||||
|
||||
impl Drop for RestoreExempt {
|
||||
fn drop(&mut self) {
|
||||
GATE_READS_EXEMPT.with(|e| e.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn with_gate_reads_exempt<T>(exempt: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = RestoreExempt(GATE_READS_EXEMPT.with(|e| e.replace(exempt)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to
|
||||
/// another thread ([`ScopeHandle::run`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ScopeHandle(Option<Scope>);
|
||||
pub struct ScopeHandle(Option<Scope>, Option<Arc<ScriptGate>>, bool);
|
||||
|
||||
impl ScopeHandle {
|
||||
/// The scope of the calling thread.
|
||||
pub fn capture() -> Self {
|
||||
Self(SCOPE.with(|s| s.borrow().clone()))
|
||||
Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
with_scope(self.0, f)
|
||||
let Self(scope, gate, exempt) = self;
|
||||
with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f)))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a command a running script runs (`vc.run`) may read and write: the places the script's
|
||||
/// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app
|
||||
/// were opened from or saved to. The automation roots apply as well. A path refused by its name
|
||||
/// alone ([`ScriptScope::refused_by_name`]) is refused here too.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ScriptGate {
|
||||
pub(crate) read: ScriptScope,
|
||||
pub(crate) write: ScriptScope,
|
||||
/// The paths of the open documents' files, as the documents hold them.
|
||||
pub(crate) documents: Vec<String>,
|
||||
}
|
||||
|
||||
impl ScriptGate {
|
||||
fn check(&self, path: &str, access: Access) -> Result<(), String> {
|
||||
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
|
||||
let allowed = real.is_some_and(|real| {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(&real) || self.write.allows(&real),
|
||||
Access::Write => self.write.allows(&real),
|
||||
};
|
||||
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))
|
||||
});
|
||||
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The gate of the script command this thread runs ([`with_script_gate`]).
|
||||
static GATE: RefCell<Option<Arc<ScriptGate>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Puts the gate it replaced back when dropped (also when `f` panics).
|
||||
struct RestoreGate(Option<Arc<ScriptGate>>);
|
||||
|
||||
impl Drop for RestoreGate {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
GATE.with(|g| *g.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
|
||||
fn with_gate<T>(gate: Option<Arc<ScriptGate>>, f: impl FnOnce() -> T) -> T {
|
||||
let _restore = RestoreGate(GATE.with(|g| g.replace(gate)));
|
||||
f()
|
||||
}
|
||||
|
||||
/// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or
|
||||
/// writes must pass the gate as well as the automation roots, also when the run itself is
|
||||
/// [`unconfined`] (one the person started). Reads of the app's own folders, inside an
|
||||
/// [`unconfined`] the command enters, are not checked; writes there are, so a script's command
|
||||
/// does not save into the app's libraries.
|
||||
pub(crate) fn with_script_gate<T>(gate: ScriptGate, f: impl FnOnce() -> T) -> T {
|
||||
with_gate(Some(Arc::new(gate)), || with_gate_reads_exempt(false, f))
|
||||
}
|
||||
|
||||
/// May `path` be read (or written) by the script command this thread runs? Always outside one,
|
||||
/// and for a read inside an [`unconfined`] the command entered.
|
||||
fn check_gate(path: &str, access: Access) -> Result<(), String> {
|
||||
if matches!(access, Access::Read) && GATE_READS_EXEMPT.with(std::cell::Cell::get) {
|
||||
return Ok(());
|
||||
}
|
||||
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access))
|
||||
}
|
||||
|
||||
/// The roots in force on this thread, if any.
|
||||
pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
match SCOPE.with(|s| s.borrow().clone()) {
|
||||
@@ -210,9 +298,11 @@ pub fn current() -> Option<Arc<AutomationRoots>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// May `path` be read here? Always, without roots in force.
|
||||
/// May `path` be read here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_read(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Read))?;
|
||||
check_gate(path, Access::Read)
|
||||
}
|
||||
|
||||
/// Is `path`, under a read root, written as an absolute path of another platform: outside Windows, one
|
||||
@@ -229,9 +319,11 @@ pub fn is_path_key(key: &str) -> bool {
|
||||
crate::cmd::key_location(key).is_some()
|
||||
}
|
||||
|
||||
/// May `path` be written here? Always, without roots in force.
|
||||
/// May `path` be written here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_write(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)?;
|
||||
WRITES.with(|w| {
|
||||
if let Some(paths) = w.borrow_mut().as_mut()
|
||||
&& !paths.iter().any(|(p, _)| p == path)
|
||||
@@ -323,6 +415,12 @@ fn inside(path: &Path, root: &Path) -> bool {
|
||||
root.components().all(|r| path.next().is_some_and(|p| same_component(p, r)))
|
||||
}
|
||||
|
||||
/// Is `path` `root` or inside it, both with their links followed, compared as [`AutomationRoots`]
|
||||
/// compares them?
|
||||
pub(crate) fn path_inside(path: &Path, root: &Path) -> bool {
|
||||
inside(path, root)
|
||||
}
|
||||
|
||||
fn same_component(a: Component, b: Component) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
@@ -374,10 +472,21 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> {
|
||||
/// The file opened is the path with its links followed, and after reading, the path is followed
|
||||
/// again and must still lead to the same place: a process that changes the folders twice in between
|
||||
/// can still win that race.
|
||||
///
|
||||
/// A scope can also be given more folders ([`ScriptScope::add`]) and single files
|
||||
/// ([`ScriptScope::add_file`]), and folders it keeps out even inside a granted folder
|
||||
/// ([`ScriptScope::fence`]), each but the places inside it that stay open. A granted file grants its
|
||||
/// own path only, also when a folder later takes its place.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct ScriptScope {
|
||||
/// The granted folders, made absolute with their links followed.
|
||||
roots: Vec<PathBuf>,
|
||||
/// The granted files, made absolute with their links followed.
|
||||
files: Vec<PathBuf>,
|
||||
/// The folders kept out, with their links followed.
|
||||
fenced: Vec<PathBuf>,
|
||||
/// The places inside a fenced folder that are not kept out.
|
||||
open: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Why a script's file was not read.
|
||||
@@ -396,18 +505,68 @@ pub(crate) enum ScriptRead {
|
||||
impl ScriptScope {
|
||||
/// The scope of a script run from a file in folder `dir`: that folder.
|
||||
pub(crate) fn of_folder(dir: &Path) -> Self {
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() }
|
||||
Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect(), ..Self::default() }
|
||||
}
|
||||
|
||||
/// Grants the folder `real`, a path with its links followed, with everything inside it.
|
||||
pub(crate) fn add(&mut self, real: PathBuf) {
|
||||
if !self.roots.contains(&real) {
|
||||
self.roots.push(real);
|
||||
}
|
||||
}
|
||||
|
||||
/// Grants the file `real`, a path with its links followed: that path and nothing below it.
|
||||
pub(crate) fn add_file(&mut self, real: PathBuf) {
|
||||
if !self.files.contains(&real) {
|
||||
self.files.push(real);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes back the grant of the folder (`folder`) or file `real` that [`ScriptScope::add`] or
|
||||
/// [`ScriptScope::add_file`] gave.
|
||||
pub(crate) fn remove(&mut self, real: &Path, folder: bool) {
|
||||
if folder { self.roots.retain(|r| r != real) } else { self.files.retain(|r| r != real) }
|
||||
}
|
||||
|
||||
/// Is nothing granted?
|
||||
fn is_empty(&self) -> bool {
|
||||
self.roots.is_empty() && self.files.is_empty()
|
||||
}
|
||||
|
||||
/// Keeps the folder `real` (links followed) and everything in it out, but for `open` and the
|
||||
/// places inside it.
|
||||
pub(crate) fn fence(&mut self, real: PathBuf, open: &[PathBuf]) {
|
||||
self.fenced.push(real);
|
||||
self.open.extend(open.iter().cloned());
|
||||
}
|
||||
|
||||
/// Leaves the place `real` (links followed) and everything in it open inside a fenced folder.
|
||||
pub(crate) fn fence_open(&mut self, real: PathBuf) {
|
||||
self.open.push(real);
|
||||
}
|
||||
|
||||
/// The granted folders, with their links followed.
|
||||
pub(crate) fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// Is the real path `real` a granted file or inside a granted folder, and not kept out? A place
|
||||
/// left open counts only inside the fenced folder: one that holds the fenced folder opens none of it.
|
||||
pub(crate) fn allows(&self, real: &Path) -> bool {
|
||||
(self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count())
|
||||
|| self.roots.iter().any(|r| inside(real, r)))
|
||||
&& !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o)))
|
||||
}
|
||||
|
||||
/// The scope of a script run from a file in the folder whose real path, with its links already
|
||||
/// followed, is `real`: that folder, which is not looked up again.
|
||||
pub(crate) fn of_real_folder(real: PathBuf) -> Self {
|
||||
Self { roots: vec![real] }
|
||||
Self { roots: vec![real], ..Self::default() }
|
||||
}
|
||||
|
||||
/// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or
|
||||
/// stream, or a computer on the network?
|
||||
fn refused_by_name(path: &Path) -> bool {
|
||||
pub(crate) fn refused_by_name(path: &Path) -> bool {
|
||||
let text = path.to_string_lossy();
|
||||
text.contains('\0')
|
||||
|| path.components().any(|c| c == Component::ParentDir)
|
||||
@@ -417,7 +576,7 @@ impl ScriptScope {
|
||||
/// The real path of the file at `path` and its first `max` bytes, at most.
|
||||
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
|
||||
use std::io::Read;
|
||||
if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let real = match std::fs::canonicalize(path) {
|
||||
@@ -428,7 +587,7 @@ impl ScriptScope {
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
if !self.roots.iter().any(|r| inside(&real, r)) {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
@@ -456,24 +615,24 @@ impl ScriptScope {
|
||||
self.roots.first().map(|r| crate::cmd::findfiles::plain(r.clone()))
|
||||
}
|
||||
|
||||
/// Does the absolute path `path` name a granted folder or a place inside one, by its names
|
||||
/// alone, without regard to case? A path that does not is refused before the file system is
|
||||
/// asked anything about it.
|
||||
/// Does the absolute path `path` name a granted file, a granted folder or a place inside one,
|
||||
/// by its names alone, without regard to case? A path that does not is refused before the file
|
||||
/// system is asked anything about it.
|
||||
fn names_inside(&self, path: &Path) -> bool {
|
||||
let lower = |c: Component| c.as_os_str().to_string_lossy().to_lowercase();
|
||||
path.is_absolute()
|
||||
&& self.roots.iter().any(|r| {
|
||||
let root = crate::cmd::findfiles::plain(r.clone());
|
||||
let mut names = path.components();
|
||||
root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c)))
|
||||
})
|
||||
let names_under = |r: &PathBuf| {
|
||||
let root = crate::cmd::findfiles::plain(r.clone());
|
||||
let mut names = path.components();
|
||||
root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c)))
|
||||
};
|
||||
path.is_absolute() && (self.roots.iter().any(names_under) || self.files.iter().any(names_under))
|
||||
}
|
||||
|
||||
/// The real path of the file or folder at `path`, which must be absolute: refused as
|
||||
/// [`ScriptScope::read`] refuses a path, and also when its names alone place it outside every
|
||||
/// granted folder, in which case the file system is not asked about it.
|
||||
pub(crate) fn locate(&self, path: &Path) -> Result<PathBuf, ScriptRead> {
|
||||
if self.roots.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
probed();
|
||||
@@ -490,22 +649,72 @@ impl ScriptScope {
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
if !self.roots.iter().any(|r| inside(&real, r)) {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Is the missing `path` inside a granted folder: does the nearest folder above it that exists
|
||||
/// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is
|
||||
/// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too,
|
||||
/// so a script cannot tell whether the folder a link leads to exists.
|
||||
/// The real path that writing to `path` writes: `path` with its links followed (the last
|
||||
/// name's too only when `follow`), and for a path that does not exist yet, its nearest existing
|
||||
/// folder's links followed and the rest appended. Refused as [`ScriptScope::locate`] refuses a
|
||||
/// path, also when a link on the way leads nowhere, and when the automation write roots in force
|
||||
/// ([`check_write`]) do not take it.
|
||||
pub(crate) fn target(&self, path: &Path, follow: bool) -> Result<PathBuf, ScriptRead> {
|
||||
if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
probed();
|
||||
if check_write(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return Err(ScriptRead::Refused) };
|
||||
let real = match std::fs::symlink_metadata(path) {
|
||||
Ok(_) if follow => std::fs::canonicalize(path).map_err(|_| ScriptRead::Refused)?,
|
||||
Ok(m) => {
|
||||
// Where case does not matter, the name given can differ in case from the name the
|
||||
// file system keeps, so a file or folder that is not a link is checked under the
|
||||
// kept name too.
|
||||
if !m.file_type().is_symlink() && !std::fs::canonicalize(path).is_ok_and(|kept| self.allows(&kept)) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
std::fs::canonicalize(parent).map_err(|_| ScriptRead::Refused)?.join(name)
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
let mut missing = vec![name.to_os_string()];
|
||||
let mut at = parent;
|
||||
loop {
|
||||
match std::fs::symlink_metadata(at) {
|
||||
Ok(_) => break,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(at.file_name().ok_or(ScriptRead::Refused)?.to_os_string());
|
||||
at = at.parent().ok_or(ScriptRead::Refused)?;
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
}
|
||||
}
|
||||
let mut real = std::fs::canonicalize(at).map_err(|_| ScriptRead::Refused)?;
|
||||
real.extend(missing.iter().rev());
|
||||
real
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
// The automation write roots take the place written as well as the path named.
|
||||
if !self.allows(&real) || check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Is the missing `path` inside a granted place: with the links of the nearest folder above it
|
||||
/// that exists followed, and the rest of its names appended, is it granted? On a file system
|
||||
/// where case matters, `MAIN/x` beside the granted `main` is outside, whether `MAIN` exists or
|
||||
/// not. A link above it that leads to nothing is outside too, so a script cannot tell whether
|
||||
/// the folder a link leads to exists.
|
||||
fn missing_inside(&self, path: &Path) -> bool {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.find(|a| std::fs::symlink_metadata(a).is_ok())
|
||||
.and_then(|a| std::fs::canonicalize(a).ok())
|
||||
.is_some_and(|real| self.roots.iter().any(|r| inside(&real, r)))
|
||||
let Some(found) = path.ancestors().skip(1).find(|a| std::fs::symlink_metadata(a).is_ok()) else { return false };
|
||||
let (Ok(real), Ok(rest)) = (std::fs::canonicalize(found), path.strip_prefix(found)) else { return false };
|
||||
self.allows(&real.join(rest))
|
||||
}
|
||||
|
||||
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it.
|
||||
@@ -548,7 +757,7 @@ impl ScriptScope {
|
||||
continue;
|
||||
}
|
||||
let Ok(target) = std::fs::canonicalize(entry.path()) else { continue };
|
||||
if !self.roots.iter().any(|r| inside(&target, r)) || check_read(&entry.path().to_string_lossy()).is_err() {
|
||||
if !self.allows(&target) || check_read(&entry.path().to_string_lossy()).is_err() {
|
||||
continue;
|
||||
}
|
||||
if out.len() >= max {
|
||||
|
||||
@@ -185,6 +185,10 @@ pub struct Session {
|
||||
/// The folder of the New Document profiles `file.new` starts documents from; `None`: none,
|
||||
/// every document starts with the defaults ([`Session::attach_new_doc_profiles`]).
|
||||
new_doc_profile_dir: Option<std::path::PathBuf>,
|
||||
/// The folder of each script's data folder (`Folder.userData`), beside which the grants file
|
||||
/// keeps the file access people allowed scripts; `None`: no folder
|
||||
/// ([`Session::attach_script_data`]).
|
||||
script_data_dir: Option<std::path::PathBuf>,
|
||||
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
|
||||
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
|
||||
plugin_output: Option<cmd::plugin::HandedIn>,
|
||||
|
||||
+1512
-58
File diff suppressed because it is too large.
Load diff
+152
-13
@@ -38,7 +38,8 @@
|
||||
//! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the
|
||||
//! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`.
|
||||
//!
|
||||
//! `File` and `Folder` read files inside the script's own folder ([`files`]).
|
||||
//! `File` and `Folder` read files inside the script's own folder, and write in the run's temporary
|
||||
//! folder, the script's data folder and what a person allowed it in a file dialog ([`files`]).
|
||||
//!
|
||||
//! A script with `#targetengine name` runs in that named engine, which the session keeps with the
|
||||
//! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each
|
||||
@@ -103,6 +104,31 @@ pub const MAX_ARGS_BYTES: usize = 1 << 20;
|
||||
const SLICE_HOST_CALLS: u32 = 256;
|
||||
/// The bytes that may cross between a script and the host in one run.
|
||||
const MAX_BRIDGE_BYTES: u64 = 4 << 30;
|
||||
/// The most files a run's report names in `written`; past them the report has `writtenMore`.
|
||||
pub const MAX_WRITTEN: usize = 4096;
|
||||
|
||||
/// The files a run wrote, as its report names them: at most [`MAX_WRITTEN`], each once, in the
|
||||
/// order they were first written, and whether it wrote more.
|
||||
#[derive(Default)]
|
||||
struct Written {
|
||||
paths: Vec<String>,
|
||||
seen: std::collections::HashSet<String>,
|
||||
more: bool,
|
||||
}
|
||||
|
||||
impl Written {
|
||||
fn add(&mut self, path: String) {
|
||||
if self.seen.contains(&path) {
|
||||
return;
|
||||
}
|
||||
if self.paths.len() >= MAX_WRITTEN {
|
||||
self.more = true;
|
||||
return;
|
||||
}
|
||||
self.seen.insert(path.clone());
|
||||
self.paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The version `vc.api.version` gives.
|
||||
pub const API_VERSION: &str = "1.0";
|
||||
@@ -259,9 +285,29 @@ struct KeptMap {
|
||||
struct KeptMaps {
|
||||
maps: std::collections::VecDeque<KeptMap>,
|
||||
bytes: usize,
|
||||
/// The SHA-256 of each source the engine's runs compiled (their scripts and what they
|
||||
/// evaluated), at most [`MAX_ENGINE_CODE`], and whether there were more: a later run's kept file
|
||||
/// grants are in force only for code they were kept for ([`files::Disk`]).
|
||||
code: std::collections::BTreeSet<String>,
|
||||
code_full: bool,
|
||||
}
|
||||
|
||||
/// The most sources whose SHA-256 a named engine keeps.
|
||||
pub const MAX_ENGINE_CODE: usize = 1024;
|
||||
|
||||
impl KeptMaps {
|
||||
/// Adds the sources `code` (and whether a run had more than it counted) to the engine's code.
|
||||
fn keep_code(&mut self, (code, more): (Vec<String>, bool)) {
|
||||
self.code_full |= more;
|
||||
for hash in code {
|
||||
if self.code.len() >= MAX_ENGINE_CODE && !self.code.contains(&hash) {
|
||||
self.code_full = true;
|
||||
} else {
|
||||
self.code.insert(hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option<Arc<str>>) {
|
||||
let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len());
|
||||
let limit = kept_map_bytes();
|
||||
@@ -705,7 +751,7 @@ struct Host {
|
||||
waiting: Cell<bool>,
|
||||
log: RefCell<Vec<Value>>,
|
||||
log_bytes: Cell<usize>,
|
||||
written: RefCell<Vec<String>>,
|
||||
written: RefCell<Written>,
|
||||
/// The run's number in its session, and the script's name, which its console lines carry.
|
||||
run: u64,
|
||||
name: Arc<str>,
|
||||
@@ -822,6 +868,7 @@ impl Host {
|
||||
return;
|
||||
}
|
||||
let mut kept = kept.borrow_mut();
|
||||
kept.keep_code(self.disk.borrow().code());
|
||||
kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone()));
|
||||
for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() {
|
||||
match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) {
|
||||
@@ -944,6 +991,35 @@ impl Host {
|
||||
Some(left)
|
||||
}
|
||||
|
||||
/// Adds `paths`, files the script's `File` and `Folder` objects wrote, to the report's `written`.
|
||||
fn note_written(&self, paths: Vec<String>) {
|
||||
let mut written = self.written.borrow_mut();
|
||||
for path in paths {
|
||||
written.add(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `writtenMore: true` to `report` when the run wrote more files than its `written` names.
|
||||
fn more_written(&self, report: &mut Value) {
|
||||
if self.written.borrow().more
|
||||
&& let Some(o) = report.as_object_mut()
|
||||
{
|
||||
o.insert("writtenMore".into(), json!(true));
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the files the script left open and adds every file written to the report's `written`.
|
||||
/// → the files it could not write.
|
||||
fn flush_files(&self) -> Vec<String> {
|
||||
let mut disk = self.disk.borrow_mut();
|
||||
let failed = disk.flush_all();
|
||||
disk.record_code();
|
||||
let paths = disk.take_written();
|
||||
drop(disk);
|
||||
self.note_written(paths);
|
||||
failed
|
||||
}
|
||||
|
||||
fn over(&self, limit: &str) -> HostError {
|
||||
HostError::Abort(limit.to_string())
|
||||
}
|
||||
@@ -1160,13 +1236,13 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
let before: Vec<(u64, Arc<crate::Document>, u64)> =
|
||||
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
|
||||
crate::file_access::start_recording_writes();
|
||||
let r = s.execute(id, params);
|
||||
// The command reads and writes only where the script's own files may, and the open documents' files.
|
||||
let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect());
|
||||
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
|
||||
// A file a command wrote before it failed is on disk all the same.
|
||||
let mut written = host.written.borrow_mut();
|
||||
for path in crate::file_access::finish_recording_writes(r.is_ok()) {
|
||||
if !written.contains(&path) {
|
||||
written.push(path);
|
||||
}
|
||||
written.add(path);
|
||||
}
|
||||
drop(written);
|
||||
match r {
|
||||
@@ -1733,6 +1809,32 @@ impl Session {
|
||||
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects'
|
||||
/// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no
|
||||
/// longer waits.
|
||||
pub fn script_picker(&self) -> Option<files::ScriptPicker> {
|
||||
if self.script_stop.is_set() {
|
||||
return None;
|
||||
}
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.disk.borrow().picker.clone())).flatten()
|
||||
}
|
||||
|
||||
/// Gives the file dialog the running script waits at its answer: the paths the person picked
|
||||
/// and allowed, or a denial. The next [`Session::script_pump`] goes on from the call. → false
|
||||
/// when no file dialog waits.
|
||||
pub fn script_pick(&mut self, answer: files::PickAnswer) -> bool {
|
||||
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false };
|
||||
with_job(k, |j| {
|
||||
let Some(data) = j.host.disk.borrow_mut().answer(answer) else { return false };
|
||||
j.host.note_written(j.host.disk.borrow_mut().take_written());
|
||||
if let Err(e) = j.realm.answer(data) {
|
||||
j.host.disk.borrow_mut().failed = Some(e);
|
||||
}
|
||||
true
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The name of the running script.
|
||||
pub fn script_name(&self) -> Option<String> {
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone()))
|
||||
@@ -1859,7 +1961,17 @@ impl Session {
|
||||
realm.set_limits(limits);
|
||||
realm
|
||||
}
|
||||
None => Realm::with_options(options, limits),
|
||||
None => {
|
||||
let mut realm = Realm::with_options(options, limits);
|
||||
// Code the run evaluates withdraws the kept file grants not kept for it, before it runs.
|
||||
let l = link.clone();
|
||||
realm.observe_code(move |units| {
|
||||
if let Ok(h) = current(&l) {
|
||||
h.disk.borrow_mut().saw_code(units);
|
||||
}
|
||||
});
|
||||
realm
|
||||
}
|
||||
};
|
||||
realm.share_interrupt(&self.script_stop);
|
||||
realm.set_data_limits(DataLimits::default());
|
||||
@@ -1879,7 +1991,7 @@ impl Session {
|
||||
waiting: Cell::new(false),
|
||||
log: RefCell::new(Vec::new()),
|
||||
log_bytes: Cell::new(0),
|
||||
written: RefCell::new(Vec::new()),
|
||||
written: RefCell::new(Written::default()),
|
||||
run: self.script_runs,
|
||||
name: console::line_name(&name),
|
||||
console: RefCell::default(),
|
||||
@@ -1888,7 +2000,20 @@ impl Session {
|
||||
commands: RefCell::default(),
|
||||
run_nanos: Cell::new(0),
|
||||
dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers),
|
||||
disk: RefCell::new(files::Disk::new(files.scope())),
|
||||
disk: RefCell::new(files::Disk::new(
|
||||
files.scope(),
|
||||
files::Setup {
|
||||
framed: self.script_frames,
|
||||
script: request.file.clone(),
|
||||
// The text with its included files, so a changed included file asks again.
|
||||
source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()),
|
||||
data_dir: self.script_data_dir.clone(),
|
||||
engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| {
|
||||
let m = m.borrow();
|
||||
(m.code.iter().cloned().collect(), m.code_full)
|
||||
}),
|
||||
},
|
||||
)),
|
||||
files: RefCell::new(files),
|
||||
script_map: RefCell::default(),
|
||||
eval_maps: RefCell::default(),
|
||||
@@ -1978,14 +2103,16 @@ impl Session {
|
||||
self.script_gone(key, console::Ending::Internal);
|
||||
return Some(Err(EngineError::Other(JOB_GONE.to_string())));
|
||||
};
|
||||
if let Some(e) = job.host.dialogs.take_failure() {
|
||||
let picker_failed = job.host.disk.borrow_mut().failed.take();
|
||||
if let Some(e) = job.host.dialogs.take_failure().or(picker_failed) {
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
// A canceled request ends a sleep or a wait at this pump.
|
||||
if vectorcraft_doc::cancel::check().is_err() {
|
||||
self.script_stop.set();
|
||||
}
|
||||
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
|
||||
let picking = job.host.disk.borrow().picker.is_some();
|
||||
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting() || picking) && !self.script_stop.is_set() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
@@ -2029,6 +2156,9 @@ impl Session {
|
||||
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
job.host.dialogs.stopped();
|
||||
job.host.disk.borrow_mut().picker = None;
|
||||
// The run fails already; a file it could not write is left out of `written`.
|
||||
let _ = job.host.flush_files();
|
||||
let fuel_left = job.realm.fuel_left();
|
||||
let (e, file) = located(&job.host, &job.realm, e);
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
@@ -2046,6 +2176,12 @@ impl Session {
|
||||
/// Makes the working copy the session's state: one undo step for each document whose art
|
||||
/// changed, nothing for the others.
|
||||
fn script_commit(&mut self, mut job: Job) -> Result<Value> {
|
||||
let unwritten = job.host.flush_files();
|
||||
if !unwritten.is_empty() {
|
||||
let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", "));
|
||||
let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 };
|
||||
return self.script_failed(job, &e);
|
||||
}
|
||||
// The working copy goes into the session; `job.world` holds the state before the run.
|
||||
job.world.swap(self);
|
||||
self.prefs = merged_prefs(&job.world.start_prefs, &self.prefs, &job.world.choices.prefs);
|
||||
@@ -2109,11 +2245,12 @@ impl Session {
|
||||
"ok": true,
|
||||
"name": job.name,
|
||||
"changed": changed_names,
|
||||
"written": *host.written.borrow(),
|
||||
"written": host.written.borrow().paths,
|
||||
"log": *host.log.borrow(),
|
||||
"fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(),
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
self.end_job(job, false);
|
||||
self.script_report = Some(report.clone());
|
||||
@@ -2140,6 +2277,7 @@ impl Session {
|
||||
|
||||
const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script";
|
||||
const INVALID_RESULT: &str = "the script left a document that cannot be kept";
|
||||
const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written";
|
||||
const JOB_GONE: &str = "the script's run is no longer available";
|
||||
const HISTORY_LOST: &str = "a failed command changed undo steps that could not be put back, so the script was stopped";
|
||||
// Text a script reads from the errors it catches, or that ends its run with its name and place.
|
||||
@@ -2168,12 +2306,13 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue
|
||||
"name": name,
|
||||
"line": e.line,
|
||||
"column": e.column,
|
||||
"written": *host.written.borrow(),
|
||||
"written": host.written.borrow().paths,
|
||||
"log": *host.log.borrow(),
|
||||
"fuelLeft": fuel_left,
|
||||
"fuelUsed": fuel_used,
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
if let (Some(file), Some(o)) = (file, report.as_object_mut()) {
|
||||
o.insert("file".into(), json!(file));
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ impl Session {
|
||||
scripts_dir: None,
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
script_data_dir: None,
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
plugin_grants_from_requests: false,
|
||||
|
||||
@@ -582,6 +582,39 @@ fn shape_builder_tool_drives_the_command() {
|
||||
assert_eq!(layer_children(&s), 1);
|
||||
}
|
||||
|
||||
/// A Shape Builder click that builds nothing puts the reason in the status bar and leaves the
|
||||
/// document, its undo history and the selection as they were; a click that merges shows no status.
|
||||
#[test]
|
||||
fn shape_builder_click_that_builds_nothing_shows_why() {
|
||||
use vectorcraft_tools::builder::{NO_REGION, SELECT_ALL_PATHS, SELECT_PATHS};
|
||||
let mut s = session();
|
||||
let (a, _) = two(&mut s);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("shapeBuilder", v).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap()
|
||||
};
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone(), st.is_dirty())
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let before = state(&s);
|
||||
assert_eq!(click(&mut s, 125.0, 50.0), vec![UiRequest::Status(SELECT_ALL_PATHS.into())]);
|
||||
assert_eq!(click(&mut s, 400.0, 400.0), vec![UiRequest::Status(NO_REGION.into())]);
|
||||
assert_eq!(state(&s), before, "nothing changed");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = state(&s);
|
||||
assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(SELECT_PATHS.into())]);
|
||||
assert_eq!(state(&s), before, "nothing changed");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(String::new())], "a click that merges clears the status");
|
||||
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
|
||||
assert!(click(&mut s, 25.0, 50.0).is_empty(), "the next merge shows no status");
|
||||
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge");
|
||||
}
|
||||
|
||||
/// A click of the Shape Builder merges over the map the tool built for the hover, as does the
|
||||
/// command over the same inputs with the same gap; another gap needs a map of its own.
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -245,10 +245,46 @@ fn files_are_checked_before_they_are_read() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A new empty folder for test `name`.
|
||||
fn fresh_folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder
|
||||
/// `dir` there once.
|
||||
fn start_allowed(s: &mut Session, dir: &std::path::Path, source: &str) {
|
||||
s.script_frames = true;
|
||||
assert_eq!(run(s, &format!("Folder.selectDialog('Folder');\n{source}")).unwrap()["running"], true);
|
||||
for _ in 0..10_000 {
|
||||
if s.script_picker().is_some() {
|
||||
let paths = vec![dir.to_string_lossy().into_owned()];
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false }));
|
||||
return;
|
||||
}
|
||||
assert!(s.script_pump().is_none(), "the run waits at its folder dialog");
|
||||
}
|
||||
panic!("the run did not open its folder dialog");
|
||||
}
|
||||
|
||||
/// Runs `source` in the app as [`start_allowed`] starts it, to its end.
|
||||
fn run_allowed(s: &mut Session, dir: &std::path::Path, source: &str) -> Result<Value> {
|
||||
start_allowed(s, dir, source);
|
||||
let r = loop {
|
||||
if let Some(r) = s.script_pump() {
|
||||
break r;
|
||||
}
|
||||
};
|
||||
s.script_frames = false;
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let dir = fresh_folder("batch");
|
||||
let path = dir.join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
let source = format!(
|
||||
@@ -257,24 +293,94 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() {
|
||||
{{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\
|
||||
{{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}"
|
||||
);
|
||||
let r = run(&mut s, &source).unwrap();
|
||||
let r = run_allowed(&mut s, &dir, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["Error"]), "{r}");
|
||||
assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay");
|
||||
assert!(path.exists());
|
||||
assert_eq!(r["written"], json!([p]), "{r}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_export_that_fails_names_no_file() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg");
|
||||
let dir = fresh_folder("no-folder");
|
||||
let path = dir.join("missing").join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}");
|
||||
let r = run(&mut s, &source).unwrap();
|
||||
let r = run_allowed(&mut s, &dir, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["Error"]), "{r}");
|
||||
assert!(!path.exists());
|
||||
assert_eq!(r["written"], json!([]), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The commands a script runs read and write only where its `File` and `Folder` objects may (its
|
||||
/// temporary folder and what a person allowed it, here), and the files of the open documents,
|
||||
/// also in a run the person started.
|
||||
#[test]
|
||||
fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() {
|
||||
let dir = fresh_folder("gate");
|
||||
let (inside, outside) = (dir.join("in"), dir.join("out"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let call = |id: &str, path: &std::path::Path| {
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let format = if id == "document.export" { ", format: 'svg'" } else { "" };
|
||||
format!(
|
||||
"try {{ vc.run('{id}', {{path: {p:?}{format}}}); vc.log('ok'); }} catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n"
|
||||
)
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let r = run(&mut s, &call("document.export", &outside.join("a.svg"))).unwrap();
|
||||
assert_eq!(r["log"], json!(["denied"]), "a script given as text writes nowhere: {r}");
|
||||
assert!(!outside.join("a.svg").exists());
|
||||
let source = format!("{}{}", call("document.export", &inside.join("b.svg")), call("document.export", &outside.join("c.svg")));
|
||||
let r = run_allowed(&mut s, &inside, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok", "denied"]), "{r}");
|
||||
assert!(inside.join("b.svg").exists() && !outside.join("c.svg").exists());
|
||||
let r = run(&mut s, "var t = Folder.temp.fsName + '/t.svg'; vc.run('document.export', {path: t, format: 'svg'}); vc.log(new File(t).exists);")
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([true]), "the run's temporary folder: {r}");
|
||||
let own = outside.join("own.svg");
|
||||
s.execute("document.save", &json!({"path": own.to_string_lossy()})).unwrap();
|
||||
std::fs::copy(&own, outside.join("copy.svg")).unwrap();
|
||||
let source = format!(
|
||||
"vc.run('shape.rectangle', {{x: 1, y: 1, width: 1, height: 1}});\n{}{}{}{}",
|
||||
call("document.save", &own),
|
||||
call("document.open", &own),
|
||||
call("document.open", &outside.join("copy.svg")),
|
||||
call("document.save", &outside.join("other.svg"))
|
||||
);
|
||||
let r = run(&mut s, &source).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}");
|
||||
assert!(!outside.join("other.svg").exists());
|
||||
let source = format!("{}{}", call("document.open", &own), call("document.open", &outside.join("copy.svg")));
|
||||
let r = crate::file_access::unconfined(|| run(&mut s, &source)).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok", "denied"]), "a run the person starts reads through the gate as well: {r}");
|
||||
std::fs::remove_file(&own).unwrap();
|
||||
let r = run(&mut s, &call("document.save", &own)).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}");
|
||||
assert!(own.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A command a script runs does not save into the app's own libraries; the same command run
|
||||
/// outside a script does.
|
||||
#[test]
|
||||
fn a_scripts_commands_do_not_save_into_the_apps_libraries() {
|
||||
let dir = fresh_folder("gate-library");
|
||||
let user = dir.join("user");
|
||||
let mut s = two_docs();
|
||||
s.swatch_libraries.set_user_dir(Some(user.to_string_lossy().into_owned()));
|
||||
let source = "try { vc.run('swatch.library.save', {user: true, name: 'Mine'}); vc.log('ok'); } \
|
||||
catch (e) { vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }";
|
||||
let r = run(&mut s, source).unwrap();
|
||||
assert_eq!(r["log"], json!(["denied"]), "{r}");
|
||||
assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder");
|
||||
s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap();
|
||||
assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -346,17 +452,18 @@ fn a_command_whose_result_cannot_cross_is_put_back() {
|
||||
|
||||
#[test]
|
||||
fn an_abandoned_run_reports_the_files_it_wrote() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let dir = fresh_folder("abandon");
|
||||
let path = dir.join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"));
|
||||
assert!(path.exists(), "the first slice exported");
|
||||
start_allowed(&mut s, &dir, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"));
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(path.exists(), "the slice after the dialog exported");
|
||||
assert!(s.script_abandon());
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}");
|
||||
assert!(s.script_failure_text().unwrap().contains(&p));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -886,19 +993,19 @@ fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
|
||||
|
||||
#[test]
|
||||
fn a_file_saved_before_a_failure_stays_written_and_is_named() {
|
||||
let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let dir = fresh_folder("save");
|
||||
let path = dir.join("out.svg");
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
let mut s = two_docs();
|
||||
let before = state(&s);
|
||||
let source =
|
||||
format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');");
|
||||
let e = run(&mut s, &source).unwrap_err().to_string();
|
||||
let e = run_allowed(&mut s, &dir, &source).unwrap_err().to_string();
|
||||
assert!(path.exists());
|
||||
assert!(e.contains(&p), "{e}");
|
||||
assert_eq!(s.script_report().unwrap()["written"], json!([p]));
|
||||
assert_eq!(state(&s), before, "the document does not keep the new path");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope
|
||||
@@ -923,16 +1030,13 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() {
|
||||
}
|
||||
};
|
||||
let mut s = two_docs();
|
||||
s.script_frames = true;
|
||||
let confined_target = outside.join("confined.svg");
|
||||
let started = crate::file_access::confine(Some(&roots), || run(&mut s, &export(&confined_target))).unwrap();
|
||||
assert_eq!(started["running"], true);
|
||||
crate::file_access::confine(Some(&roots), || start_allowed(&mut s, &dir, &export(&confined_target)));
|
||||
let r = crate::file_access::unconfined(|| finish(&mut s)).unwrap();
|
||||
assert_eq!(r["log"], json!(["Error"]), "a confined caller's run stays confined: {r}");
|
||||
assert!(!confined_target.exists());
|
||||
let user_target = outside.join("user.svg");
|
||||
let started = crate::file_access::unconfined(|| run(&mut s, &export(&user_target))).unwrap();
|
||||
assert_eq!(started["running"], true);
|
||||
crate::file_access::unconfined(|| start_allowed(&mut s, &dir, &export(&user_target)));
|
||||
let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap();
|
||||
assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}");
|
||||
assert!(user_target.exists());
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -1562,6 +1562,7 @@ impl Session {
|
||||
Action::Dialog(k, p) => ui.push(UiRequest::Dialog(k, p)),
|
||||
Action::Panel(panel) => ui.push(UiRequest::Panel(panel)),
|
||||
Action::SwitchTool(t) => ui.push(UiRequest::SwitchTool(t)),
|
||||
Action::Status(msg) => ui.push(UiRequest::Status(msg)),
|
||||
Action::Notify(what) => {
|
||||
let view = self.last_view;
|
||||
self.with_tool_cx(view, |t, cx| t.notify(cx, &what));
|
||||
|
||||
@@ -17,7 +17,9 @@ proptest! {
|
||||
fn any_bytes_place_as_text_without_panics(
|
||||
bytes in prop::collection::vec(prop_oneof![any::<u8>(), 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::<bool>(),
|
||||
set in prop::sample::select(vec![
|
||||
"unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean",
|
||||
]),
|
||||
mac in any::<bool>(),
|
||||
lines in any::<bool>(),
|
||||
paras in any::<bool>(),
|
||||
@@ -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,
|
||||
|
||||
@@ -5783,6 +5783,37 @@ fn an_empty_last_frame_keeps_the_style_of_the_last_paragraph() {
|
||||
assert_eq!(justify, [Justify::Left, Justify::Right]);
|
||||
}
|
||||
|
||||
/// Each First Baseline kind the text document holds, Em Box Height included, comes back with its
|
||||
/// minimum, without a warning.
|
||||
#[test]
|
||||
fn every_first_baseline_kind_comes_back_with_its_minimum() {
|
||||
use vectorcraft_doc::{FirstBaseline, TextKind, TextObject};
|
||||
for (kind, min) in [
|
||||
(FirstBaseline::Ascent, 0.0),
|
||||
(FirstBaseline::CapHeight, 6.0),
|
||||
(FirstBaseline::XHeight, 0.0),
|
||||
(FirstBaseline::Leading, 4.0),
|
||||
(FirstBaseline::EmBoxHeight, 0.0),
|
||||
(FirstBaseline::EmBoxHeight, 18.5),
|
||||
(FirstBaseline::Fixed, 40.0),
|
||||
] {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let layer = d.layers[0].id;
|
||||
let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "Area", style(12.0, Color::BLACK));
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 140.0, 160.0)) };
|
||||
area.xf = Affine::IDENTITY;
|
||||
area.area.first_baseline = kind;
|
||||
area.area.first_baseline_min = min;
|
||||
let n = text_node(&mut d, area);
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let warnings = export_ai_editing(&d, &opts()).unwrap().warnings;
|
||||
assert!(warnings.is_empty(), "{kind:?}: {warnings:?}");
|
||||
let back = read_back(&d);
|
||||
let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type") };
|
||||
assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (kind, min), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimum first baseline with the Ascent first baseline is reported, and kept with the others.
|
||||
/// An end bracket of an open path that the reader would read as none is reported, and one further
|
||||
/// from the path's end comes back.
|
||||
|
||||
@@ -1004,6 +1004,7 @@ impl TextDoc {
|
||||
FirstBaseline::CapHeight => Some(2),
|
||||
FirstBaseline::Leading => Some(3),
|
||||
FirstBaseline::XHeight => Some(4),
|
||||
FirstBaseline::EmBoxHeight => Some(5),
|
||||
};
|
||||
if let Some(k) = kind {
|
||||
data.push((10, dict(vec![(0, V::Int(k)), (1, real(o.first_baseline_min / scale))])));
|
||||
|
||||
@@ -345,8 +345,9 @@ impl AreaFrame {
|
||||
2 => F::CapHeight,
|
||||
3 => F::Leading,
|
||||
4 => F::XHeight,
|
||||
// Em Box Height (5) and Legacy (6) have no first baseline of their own here: the
|
||||
// first baseline stays as it was.
|
||||
5 => F::EmBoxHeight,
|
||||
// Legacy (6) has no first baseline of its own here: the first baseline stays as it
|
||||
// was.
|
||||
_ => return None,
|
||||
};
|
||||
Some((kind, length(b.get("1")).unwrap_or(0.0)))
|
||||
@@ -2944,12 +2945,12 @@ mod tests {
|
||||
#[test]
|
||||
fn area_frame_first_baseline_kinds_and_minimum_are_read() {
|
||||
use vectorcraft_doc::FirstBaseline as F;
|
||||
for (code, kind) in [(0, F::Fixed), (2, F::CapHeight), (3, F::Leading), (4, F::XHeight)] {
|
||||
for (code, kind) in [(0, F::Fixed), (2, F::CapHeight), (3, F::Leading), (4, F::XHeight), (5, F::EmBoxHeight)] {
|
||||
let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 2.0);
|
||||
assert_eq!((a.first_baseline, a.first_baseline_min), (kind, 60.0), "code {code}");
|
||||
}
|
||||
// A kind without its own first baseline here, or none known, leaves Ascent.
|
||||
for code in ["1", "5", "6", "7", "-1", "2.5", "(x)"] {
|
||||
for code in ["1", "6", "7", "-1", "2.5", "(x)"] {
|
||||
let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 1.0);
|
||||
assert_eq!((a.first_baseline, a.first_baseline_min), (F::Ascent, 0.0), "code {code}");
|
||||
}
|
||||
@@ -2980,9 +2981,10 @@ mod tests {
|
||||
};
|
||||
let placed = |options: &str| placed_in(&[options]);
|
||||
assert_eq!(placed("/10 << /0 2 /1 0 >>"), (false, vectorcraft_doc::FirstBaseline::CapHeight));
|
||||
assert_eq!(placed("/10 << /0 5 /1 0 >>"), (false, vectorcraft_doc::FirstBaseline::EmBoxHeight));
|
||||
// Without one (Ascent), or with one that isn't read, the line goes where the file has it.
|
||||
assert_eq!(placed(""), (true, vectorcraft_doc::FirstBaseline::Fixed));
|
||||
assert_eq!(placed("/10 << /0 5 /1 0 >>"), (true, vectorcraft_doc::FirstBaseline::Fixed));
|
||||
assert_eq!(placed("/10 << /0 6 /1 0 >>"), (true, vectorcraft_doc::FirstBaseline::Fixed));
|
||||
// Another frame of the thread keeping one doesn't count for the first.
|
||||
assert_eq!(placed_in(&["", "/10 << /0 2 /1 0 >>"]), (true, vectorcraft_doc::FirstBaseline::Fixed));
|
||||
}
|
||||
|
||||
@@ -38,6 +38,15 @@ pub(crate) fn native(interp: &mut Interp, name: &'static str, f: NativeFn, lengt
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// A built-in function object that may wait for the host ([`crate::interp::Pause`]), defined as
|
||||
/// `name` on `on` the way [`method`] defines one.
|
||||
pub(crate) fn pausable_method(interp: &mut Interp, on: ObjId, name: &'static str, f: crate::interp::PausableFn, length: u32) -> JsResult<()> {
|
||||
let proto = interp.intrinsics.function_proto;
|
||||
let m = alloc(interp, Class::Function(Func::Pausable { f, name }), Some(proto));
|
||||
interp.define(m, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?;
|
||||
interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN })
|
||||
}
|
||||
|
||||
pub(crate) fn method(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn, length: u32) -> JsResult<()> {
|
||||
let m = native(interp, name, f, length, NativeKind::Plain, false)?;
|
||||
interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN })
|
||||
@@ -478,6 +487,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
|
||||
units.extend(MID.encode_utf16());
|
||||
units.extend_from_slice(&body.flat());
|
||||
units.extend(TAIL.encode_utf16());
|
||||
interp.observe_code(&units);
|
||||
interp.source_units = interp.source_units.saturating_add(units.len());
|
||||
let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len()));
|
||||
let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() };
|
||||
@@ -513,7 +523,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) ->
|
||||
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
|
||||
return Ok(Value::String(Str::from_units(units.to_vec())));
|
||||
}
|
||||
Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Native { name, .. } | Func::Pausable { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Bound { .. }) => "function () { [native code] }".to_string(),
|
||||
None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")),
|
||||
@@ -557,6 +567,7 @@ fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
|
||||
interp.check_source_units(s.len()).map_err(|e| interp.compile_error_to_abrupt(e))?;
|
||||
interp.prepare_source(s.len())?;
|
||||
let units = s.flat();
|
||||
interp.observe_code(&units);
|
||||
let code = interp.compile_source(&units, false, CodeKind::Eval).map_err(|e| interp.compile_error_to_abrupt(e))?;
|
||||
interp.run_global(code, true)
|
||||
}
|
||||
|
||||
+453
-58
@@ -12,6 +12,11 @@
|
||||
//! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's
|
||||
//! `current`.
|
||||
//!
|
||||
//! `write` and `writeln` join their values as `String(value)` gives them, and `writeln` adds the
|
||||
//! line end `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF otherwise. The file
|
||||
//! dialogs are built-ins that ask the host's `pick` and may pause the run until the person answers
|
||||
//! ([`crate::interp::Pause`]); they give a `File`, a `Folder`, an array of `File`s or `null`.
|
||||
//!
|
||||
//! A method whose host call fails sets `error` and returns `false`, `null` or an empty string. A
|
||||
//! count or position that is not a finite number, a negative count and a seek mode other than 0, 1
|
||||
//! or 2 throw a `RangeError`; a method called on an object that is not a `File` or `Folder` throws
|
||||
@@ -19,10 +24,10 @@
|
||||
//! true value for; every entry takes fuel.
|
||||
|
||||
use crate::HostItem;
|
||||
use crate::builtins::{arg, constructor, data, method, native, put_at};
|
||||
use crate::builtins::{arg, constructor, data, method, native, pausable_method, put_at};
|
||||
use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes};
|
||||
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
|
||||
use crate::value::Value;
|
||||
use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause};
|
||||
use crate::value::{Value, index_key};
|
||||
|
||||
/// The objects of `File` and `Folder`, kept by the realm, and `Folder.current`.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -213,12 +218,19 @@ fn is_open(i: &Interp, o: ObjId) -> JsResult<Option<Value>> {
|
||||
Ok((this_run && matches!(h, Value::Number(n) if n >= 0.0)).then_some(h))
|
||||
}
|
||||
|
||||
/// Closes the object's open file, if it has one.
|
||||
fn close_open(i: &mut Interp, o: ObjId) -> JsResult<()> {
|
||||
/// Closes the object's open file, if it has one, which writes what the script wrote to it. → false
|
||||
/// after setting `error` when that could not be written; the file then stays open, so a later
|
||||
/// `close` tries again.
|
||||
fn close_open(i: &mut Interp, o: ObjId) -> JsResult<bool> {
|
||||
let mut written = true;
|
||||
if let Some(h) = is_open(i, o)? {
|
||||
host(i, "close", &[h])?;
|
||||
let r = host(i, "close", &[h])?;
|
||||
written = outcome(i, o, &r)?;
|
||||
}
|
||||
set_slot(i, o, HANDLE, Value::Number(-1.0))
|
||||
if written {
|
||||
set_slot(i, o, HANDLE, Value::Number(-1.0))?;
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
fn date(i: &mut Interp, ms: Value) -> JsResult<Value> {
|
||||
@@ -375,7 +387,10 @@ fn get_relative_uri(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsR
|
||||
|
||||
fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_path(i, &this, "changePath")?;
|
||||
close_open(i, o)?;
|
||||
// An object whose changes could not be written keeps its path; `error` says why.
|
||||
if !close_open(i, o)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
let p = parse(i, &arg(args, 0))?;
|
||||
let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?;
|
||||
set_slot(i, o, PATH, fs)?;
|
||||
@@ -409,30 +424,305 @@ fn to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Valu
|
||||
parsed(i, &this, "toString", "uri")
|
||||
}
|
||||
|
||||
/// A method that writes: it sets `error` and returns `false`.
|
||||
fn no_writes(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_path(i, &this, "write")?;
|
||||
let m = message(i, "noWrites")?;
|
||||
/// Whether the host's answer `r` is not `{error}`; when it is, the object's `error` is set to it.
|
||||
fn outcome(i: &mut Interp, o: ObjId, r: &Value) -> JsResult<bool> {
|
||||
let error = i.rooted(std::slice::from_ref(r), |i| field(i, r, "error"))?;
|
||||
if matches!(error, Value::String(_)) {
|
||||
set_slot(i, o, ERROR, error)?;
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Calls the host function `name` with the object's path and `args`. → whether it did the work.
|
||||
fn path_call(i: &mut Interp, this: &Value, what: &str, name: &str, args: &[Value]) -> JsResult<Value> {
|
||||
let (o, path) = this_path(i, this, what)?;
|
||||
let mut all = vec![path];
|
||||
all.extend_from_slice(args);
|
||||
let r = i.rooted(&all, |i| host(i, name, &all))?;
|
||||
Ok(Value::Bool(outcome(i, o, &r)?))
|
||||
}
|
||||
|
||||
/// `createAlias`: not available, so it sets `error` and returns `false`.
|
||||
fn create_alias(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_path(i, &this, "createAlias")?;
|
||||
let m = message(i, "noAlias")?;
|
||||
set_slot(i, o, ERROR, m)?;
|
||||
Ok(Value::Bool(false))
|
||||
}
|
||||
|
||||
/// A setter that writes: it sets `error` and changes nothing.
|
||||
fn no_writes_setter(i: &mut Interp, this: Value, args: &[Value], construct: bool) -> JsResult<Value> {
|
||||
no_writes(i, this, args, construct)?;
|
||||
/// Setting `hidden`: not available, so it sets `error` and changes nothing.
|
||||
fn set_hidden(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_path(i, &this, "hidden")?;
|
||||
let m = message(i, "noHidden")?;
|
||||
set_slot(i, o, ERROR, m)?;
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// A dialog method: it sets `error` and returns `null`.
|
||||
fn no_picker(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_path(i, &this, "dialog")?;
|
||||
let m = message(i, "noPicker")?;
|
||||
set_slot(i, o, ERROR, m)?;
|
||||
Ok(Value::Null)
|
||||
/// `remove()`: the file, or the folder when it is empty, deleted at once.
|
||||
fn remove(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_path(i, &this, "remove")?;
|
||||
// A file whose changes could not be written is not removed; `error` says why.
|
||||
if !close_open(i, o)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
path_call(i, &this, "remove", "remove", &[])
|
||||
}
|
||||
|
||||
fn null_static(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
Ok(Value::Null)
|
||||
/// `rename(name)`: the object's file or folder named `name`, in the same folder; the object takes
|
||||
/// the new path.
|
||||
fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, path) = this_path(i, &this, "rename")?;
|
||||
let name = Value::String(i.to_str(&arg(args, 0))?);
|
||||
if !close_open(i, o)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
let r = i.rooted(&[path.clone(), name.clone()], |i| host(i, "rename", &[path.clone(), name.clone()]))?;
|
||||
if !outcome(i, o, &r)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?;
|
||||
set_slot(i, o, PATH, fs)?;
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
|
||||
/// `copy(target)`: the file copied to `target`, a path or a `File`, replacing a file there.
|
||||
fn copy(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
this_path(i, &this, "copy")?;
|
||||
let p = parse(i, &arg(args, 0))?;
|
||||
let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?;
|
||||
i.rooted(std::slice::from_ref(&fs), |i| path_call(i, &this, "copy", "copy", std::slice::from_ref(&fs)))
|
||||
}
|
||||
|
||||
/// `Folder.prototype.create()`: the folder, with the folders above it that are missing.
|
||||
fn create(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
path_call(i, &this, "create", "create", &[])
|
||||
}
|
||||
|
||||
/// Setting `length`: the file cut, or filled with zero bytes, to that many bytes.
|
||||
fn set_length(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
this_path(i, &this, "length")?;
|
||||
let n = i.to_number(&arg(args, 0))?;
|
||||
if !n.is_finite() || n < 0.0 {
|
||||
return Err(i.throw(ErrorType::Range, "File.length: the length must be a finite number, 0 or more"));
|
||||
}
|
||||
path_call(i, &this, "length", "setLength", &[Value::Number(n.floor())])?;
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// Setting `readonly`.
|
||||
fn set_readonly(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
this_path(i, &this, "readonly")?;
|
||||
let on = arg(args, 0).truthy();
|
||||
path_call(i, &this, "readonly", "setReadonly", &[Value::Bool(on)])?;
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// The line end the object's `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF for
|
||||
/// anything else, without regard to case.
|
||||
fn line_end(i: &Interp, o: ObjId) -> JsResult<&'static str> {
|
||||
Ok(match slot(i, o, LINE_FEED)? {
|
||||
Value::String(s) => match s.to_rust_string().to_ascii_lowercase().as_str() {
|
||||
"windows" => "\r\n",
|
||||
"macintosh" => "\r",
|
||||
_ => "\n",
|
||||
},
|
||||
_ => "\n",
|
||||
})
|
||||
}
|
||||
|
||||
/// `write(...values)` and, with `line`, `writeln(...values)`: the values as `String(value)` gives
|
||||
/// them, written at the position of the object's open file. The values are joined only for an open
|
||||
/// file, and only while the text stays within twice the host's `maxWrite` UTF-16 code units: each
|
||||
/// character takes at least one byte and at most two code units, so a longer text cannot fit in a
|
||||
/// file, and the write sets `error` to the host's `tooLarge` and returns `false`.
|
||||
fn write_values(i: &mut Interp, this: &Value, args: &[Value], what: &str, line: bool) -> JsResult<Value> {
|
||||
let (o, _) = this_path(i, this, what)?;
|
||||
let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) };
|
||||
let c = classes(i)?;
|
||||
let max = match i.get_value(&Value::Object(c.host), &key("maxWrite"))? {
|
||||
Value::Number(n) if n.is_finite() && n >= 0.0 => (n as usize).saturating_mul(2),
|
||||
_ => usize::MAX,
|
||||
};
|
||||
// The values are joined as UTF-16 code units and made text once, so a surrogate pair split
|
||||
// between two values is one character.
|
||||
let mut joined: Vec<u16> = Vec::new();
|
||||
for a in args {
|
||||
i.use_fuel()?;
|
||||
let s = i.to_str(a)?;
|
||||
if joined.len().saturating_add(s.len()) > max {
|
||||
let m = message(i, "tooLarge")?;
|
||||
set_slot(i, o, ERROR, m)?;
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
joined.extend_from_slice(&s.flat());
|
||||
}
|
||||
let mut text = String::from_utf16_lossy(&joined);
|
||||
drop(joined);
|
||||
if line {
|
||||
text.push_str(line_end(i, o)?);
|
||||
}
|
||||
i.reserve_heap(string_bytes(text.len()))?;
|
||||
let text = Value::str(&text);
|
||||
let r = i.rooted(&[h.clone(), text.clone()], |i| host(i, "write", &[h.clone(), text.clone()]))?;
|
||||
Ok(Value::Bool(outcome(i, o, &r)?))
|
||||
}
|
||||
|
||||
fn write(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
write_values(i, &this, args, "write", false)
|
||||
}
|
||||
|
||||
fn writeln(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
write_values(i, &this, args, "writeln", true)
|
||||
}
|
||||
|
||||
// ---- file dialogs ----
|
||||
|
||||
/// Asks the host's `pick` for the dialog `kind` (`open`, `save` or `folder`), with the arguments
|
||||
/// `[kind, prompt, multi, start, types]`. `me` is the `File` or `Folder` whose `openDlg`, `saveDlg`
|
||||
/// or `selectDlg` was called, or `None` for the class's own dialog: the dialog starts at its path,
|
||||
/// and an `{error}` answer sets its `error`. The prompt is `String(prompt)`, or `""` for
|
||||
/// `undefined` and `null`. A `filter` that is a string gives the file types; one that is a function
|
||||
/// is called with each file picked ([`picked`]). The run may pause at `pick` until the person
|
||||
/// answers.
|
||||
fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Value, multi: bool, filter: &Value) -> JsResult<Pause> {
|
||||
let start = match me {
|
||||
None => Value::str(""),
|
||||
Some(me) => this_path(i, me, "dialog")?.1,
|
||||
};
|
||||
let prompt = match prompt {
|
||||
Value::Undefined | Value::Null => Value::str(""),
|
||||
p => Value::String(i.to_str(p)?),
|
||||
};
|
||||
let types = match filter {
|
||||
f @ Value::String(_) => f.clone(),
|
||||
_ => Value::str(""),
|
||||
};
|
||||
let pick = host_value(i, "pick")?;
|
||||
Ok(Pause {
|
||||
host: pick,
|
||||
args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types],
|
||||
keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()],
|
||||
resume: picked,
|
||||
})
|
||||
}
|
||||
|
||||
/// What a file dialog gives for `pick`'s `answer`, with `[folder, me, filter]` kept from
|
||||
/// [`ask_pick`]: the objects [`wrap`] makes, of which a `filter` that is a function keeps the
|
||||
/// files it gives a true value for, or `null` when it keeps none.
|
||||
fn picked(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult<Value> {
|
||||
let files = wrap(i, arg(keep, 0).truthy(), &arg(keep, 1), answer)?;
|
||||
let filter = arg(keep, 2);
|
||||
if !i.is_callable(&filter) {
|
||||
return Ok(files);
|
||||
}
|
||||
let Some(o) = files.as_object() else { return Ok(files) };
|
||||
let length = match &i.object(o)?.class {
|
||||
Class::Array { length, .. } => Some(*length),
|
||||
_ => None,
|
||||
};
|
||||
let Some(length) = length else {
|
||||
let kept = i.rooted(std::slice::from_ref(&files), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&files)))?;
|
||||
return Ok(if kept.truthy() { files } else { Value::Null });
|
||||
};
|
||||
i.rooted(std::slice::from_ref(&files), |i| {
|
||||
i.reserve_heap(OBJECT_BYTES)?;
|
||||
let array_proto = i.intrinsics.array_proto;
|
||||
let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(array_proto)));
|
||||
i.rooted(&[Value::Object(out)], |i| {
|
||||
let mut n = 0.0;
|
||||
for at in 0..length {
|
||||
i.use_fuel()?;
|
||||
let file = i.get_value(&files, &index_key(at))?;
|
||||
let kept = i.rooted(std::slice::from_ref(&file), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&file)))?;
|
||||
if kept.truthy() {
|
||||
put_at(i, out, n, file)?;
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
Ok(if n > 0.0 { Value::Object(out) } else { Value::Null })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The `File` (a `Folder` for a `folder` dialog) for each path `pick` gave in `answer`, an array of
|
||||
/// them for a list, `null` for `null`, and `null` after setting the `error` of `me`, when it is a
|
||||
/// `File` or `Folder`, for `{error}`.
|
||||
fn wrap(i: &mut Interp, folder: bool, me: &Value, answer: Value) -> JsResult<Value> {
|
||||
let c = classes(i)?;
|
||||
let proto = if folder { c.folder_proto } else { c.file_proto };
|
||||
match &answer {
|
||||
Value::String(_) => return instance(i, proto, answer.clone()),
|
||||
Value::Object(_) => {}
|
||||
_ => return Ok(Value::Null),
|
||||
}
|
||||
let error = i.rooted(std::slice::from_ref(&answer), |i| field(i, &answer, "error"))?;
|
||||
if matches!(error, Value::String(_)) {
|
||||
if let Some(o) = me.as_object()
|
||||
&& matches!(slot(i, o, PATH)?, Value::String(_))
|
||||
{
|
||||
set_slot(i, o, ERROR, error)?;
|
||||
}
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
i.rooted(std::slice::from_ref(&answer), |i| {
|
||||
let length = i.get_value(&answer, &key("length"))?;
|
||||
let n = i.to_number(&length)?;
|
||||
i.reserve_heap(OBJECT_BYTES)?;
|
||||
let array_proto = i.intrinsics.array_proto;
|
||||
let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(array_proto)));
|
||||
i.rooted(&[Value::Object(out)], |i| {
|
||||
let mut at = 0.0;
|
||||
while at < n {
|
||||
i.use_fuel()?;
|
||||
let fs = i.get_value(&answer, &crate::value::number_to_str(at).flat())?;
|
||||
let item = i.rooted(std::slice::from_ref(&fs), |i| instance(i, proto, fs.clone()))?;
|
||||
put_at(i, out, at, item)?;
|
||||
at += 1.0;
|
||||
}
|
||||
Ok(Value::Object(out))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `File.openDialog(prompt, filter, multiSelect)`.
|
||||
fn open_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult<Pause> {
|
||||
ask_pick(i, "open", None, &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1))
|
||||
}
|
||||
|
||||
/// `File.saveDialog(prompt, filter)`.
|
||||
fn save_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult<Pause> {
|
||||
ask_pick(i, "save", None, &arg(args, 0), false, &arg(args, 1))
|
||||
}
|
||||
|
||||
/// `File.prototype.openDlg(prompt, filter, multiSelect)`.
|
||||
fn open_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult<Pause> {
|
||||
ask_pick(i, "open", Some(&this), &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1))
|
||||
}
|
||||
|
||||
/// `File.prototype.saveDlg(prompt, filter)`.
|
||||
fn save_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult<Pause> {
|
||||
ask_pick(i, "save", Some(&this), &arg(args, 0), false, &arg(args, 1))
|
||||
}
|
||||
|
||||
/// `Folder.selectDialog(prompt)`.
|
||||
fn select_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult<Pause> {
|
||||
ask_pick(i, "folder", None, &arg(args, 0), false, &Value::Null)
|
||||
}
|
||||
|
||||
/// `Folder.prototype.selectDlg(prompt)`.
|
||||
fn select_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult<Pause> {
|
||||
ask_pick(i, "folder", Some(&this), &arg(args, 0), false, &Value::Null)
|
||||
}
|
||||
|
||||
/// Defines the file dialogs on `File`, `Folder` and their prototypes.
|
||||
fn dialogs(i: &mut Interp, file: ObjId, file_proto: ObjId, folder: ObjId, folder_proto: ObjId) -> JsResult<()> {
|
||||
pausable_method(i, file, "openDialog", open_dialog, 3)?;
|
||||
pausable_method(i, file, "saveDialog", save_dialog, 2)?;
|
||||
pausable_method(i, file_proto, "openDlg", open_dlg, 3)?;
|
||||
pausable_method(i, file_proto, "saveDlg", save_dlg, 2)?;
|
||||
pausable_method(i, folder, "selectDialog", select_dialog, 1)?;
|
||||
pausable_method(i, folder_proto, "selectDlg", select_dlg, 1)
|
||||
}
|
||||
|
||||
fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult<Value> {
|
||||
@@ -530,19 +820,18 @@ fn open(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value>
|
||||
Value::Undefined => "r".to_string(),
|
||||
m => i.to_str(&m)?.to_rust_string().to_lowercase(),
|
||||
};
|
||||
let refusal = match mode.as_str() {
|
||||
"r" => None,
|
||||
"w" | "e" | "a" => Some("noWrites"),
|
||||
_ => Some("badMode"),
|
||||
};
|
||||
if let Some(name) = refusal {
|
||||
let m = message(i, name)?;
|
||||
if !matches!(mode.as_str(), "r" | "w" | "e" | "a") {
|
||||
let m = message(i, "badMode")?;
|
||||
set_slot(i, o, ERROR, m)?;
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
close_open(i, o)?;
|
||||
// The object's earlier changes are written first; when they cannot be, it does not open again.
|
||||
if !close_open(i, o)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
let encoding = slot(i, o, ENCODING)?;
|
||||
let r = host(i, "open", &[path, encoding])?;
|
||||
let mode = Value::str(&mode);
|
||||
let r = host(i, "open", &[path, encoding, mode])?;
|
||||
let (error, id) = i.rooted(std::slice::from_ref(&r), |i| Ok((field(i, &r, "error")?, field(i, &r, "id")?)))?;
|
||||
if matches!(error, Value::String(_)) {
|
||||
set_slot(i, o, ERROR, error)?;
|
||||
@@ -559,8 +848,7 @@ fn close(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
if opened(i, o)?.is_none() {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
close_open(i, o)?;
|
||||
Ok(Value::Bool(true))
|
||||
Ok(Value::Bool(close_open(i, o)?))
|
||||
}
|
||||
|
||||
fn read(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -599,7 +887,12 @@ fn seek(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value>
|
||||
return Err(i.throw(ErrorType::Range, "File.seek: the mode must be 0, 1 or 2"));
|
||||
}
|
||||
let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) };
|
||||
host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)])
|
||||
let r = host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)])?;
|
||||
// A seek the host refuses sets `error` and gives `false`.
|
||||
if !outcome(i, o, &r)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn tell(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -669,7 +962,7 @@ fn set_current(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Va
|
||||
|
||||
/// `Folder.<place>`: a new `Folder` for the host's location `place`, or `null`.
|
||||
fn place(i: &mut Interp, place: &str) -> JsResult<Value> {
|
||||
let all = host(i, "locations", &[])?;
|
||||
let all = host(i, "locations", &[Value::str(place)])?;
|
||||
let fs = i.rooted(std::slice::from_ref(&all), |i| field(i, &all, place))?;
|
||||
if !matches!(fs, Value::String(_)) {
|
||||
return Ok(Value::Null);
|
||||
@@ -735,8 +1028,8 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
|
||||
method(i, proto, "changePath", change_path, 1)?;
|
||||
method(i, proto, "resolve", resolve, 0)?;
|
||||
method(i, proto, "execute", execute, 0)?;
|
||||
method(i, proto, "remove", no_writes, 0)?;
|
||||
method(i, proto, "rename", no_writes, 1)?;
|
||||
method(i, proto, "remove", remove, 0)?;
|
||||
method(i, proto, "rename", rename, 1)?;
|
||||
method(i, ctor, "encode", encode, 1)?;
|
||||
method(i, ctor, "decode", decode, 1)?;
|
||||
method(i, ctor, "isEncodingAvailable", encoding_available, 1)?;
|
||||
@@ -744,10 +1037,10 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
|
||||
data(i, ctor, "fs", system, HIDDEN)
|
||||
}
|
||||
|
||||
fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
|
||||
accessor(i, proto, "length", length, Some(no_writes_setter))?;
|
||||
accessor(i, proto, "hidden", hidden, Some(no_writes_setter))?;
|
||||
accessor(i, proto, "readonly", readonly, Some(no_writes_setter))?;
|
||||
fn file_members(i: &mut Interp, proto: ObjId) -> JsResult<()> {
|
||||
accessor(i, proto, "length", length, Some(set_length))?;
|
||||
accessor(i, proto, "hidden", hidden, Some(set_hidden))?;
|
||||
accessor(i, proto, "readonly", readonly, Some(set_readonly))?;
|
||||
accessor(i, proto, "creator", four_question_marks, None)?;
|
||||
accessor(i, proto, "type", four_question_marks, None)?;
|
||||
accessor(i, proto, "eof", eof, None)?;
|
||||
@@ -760,21 +1053,15 @@ fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
|
||||
method(i, proto, "readch", read_char, 0)?;
|
||||
method(i, proto, "seek", seek, 2)?;
|
||||
method(i, proto, "tell", tell, 0)?;
|
||||
method(i, proto, "write", no_writes, 1)?;
|
||||
method(i, proto, "writeln", no_writes, 1)?;
|
||||
method(i, proto, "copy", no_writes, 1)?;
|
||||
method(i, proto, "createAlias", no_writes, 1)?;
|
||||
method(i, proto, "openDlg", no_picker, 0)?;
|
||||
method(i, proto, "saveDlg", no_picker, 0)?;
|
||||
method(i, ctor, "openDialog", null_static, 0)?;
|
||||
method(i, ctor, "saveDialog", null_static, 0)
|
||||
method(i, proto, "write", write, 1)?;
|
||||
method(i, proto, "writeln", writeln, 1)?;
|
||||
method(i, proto, "copy", copy, 1)?;
|
||||
method(i, proto, "createAlias", create_alias, 1)
|
||||
}
|
||||
|
||||
fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> {
|
||||
method(i, proto, "getFiles", get_files, 1)?;
|
||||
method(i, proto, "create", no_writes, 0)?;
|
||||
method(i, proto, "selectDlg", no_picker, 0)?;
|
||||
method(i, ctor, "selectDialog", null_static, 0)?;
|
||||
method(i, proto, "create", create, 0)?;
|
||||
accessor(i, ctor, "current", get_current, Some(set_current))?;
|
||||
for (place, get) in PLACES.into_iter().zip(PLACE_GETTERS) {
|
||||
accessor(i, ctor, place, get, None)?;
|
||||
@@ -814,20 +1101,59 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul
|
||||
constructor(i, "Folder", folder, folder_proto)?;
|
||||
common(i, file, file_proto)?;
|
||||
common(i, folder, folder_proto)?;
|
||||
file_members(i, file, file_proto)?;
|
||||
folder_members(i, folder, folder_proto)
|
||||
file_members(i, file_proto)?;
|
||||
folder_members(i, folder, folder_proto)?;
|
||||
dialogs(i, file, file_proto, folder, folder_proto)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{Data, HostItem, JsValue, Realm};
|
||||
use crate::{Data, HostError, HostItem, JsValue, Progress, Realm};
|
||||
|
||||
/// A host whose paths are `/` and a name, where `/d` is a folder holding `a` and `b` and every
|
||||
/// other path is missing.
|
||||
fn realm() -> Realm {
|
||||
realm_with(|_| Vec::new())
|
||||
}
|
||||
|
||||
/// [`realm`] with a `pick` that waits where it can and throws where it cannot. → the arguments
|
||||
/// of each call, joined with `|`.
|
||||
fn dialog_realm() -> (Realm, Rc<RefCell<Vec<String>>>) {
|
||||
let asked: Rc<RefCell<Vec<String>>> = Rc::default();
|
||||
let calls = asked.clone();
|
||||
let r = realm_with(move |r| {
|
||||
let can_wait = r.wait_flag();
|
||||
let pick = move |a: Vec<Data>| -> Result<Data, HostError> {
|
||||
let text = |d: &Data| match d {
|
||||
Data::String(s) => s.clone(),
|
||||
Data::Bool(b) => b.to_string(),
|
||||
other => format!("{other:?}"),
|
||||
};
|
||||
calls.borrow_mut().push(a.iter().map(text).collect::<Vec<_>>().join("|"));
|
||||
if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }
|
||||
};
|
||||
vec![("pick".into(), HostItem::Function(Rc::new(pick)))]
|
||||
});
|
||||
(r, asked)
|
||||
}
|
||||
|
||||
/// Advances the run until it waits or ends. → its value when it ended.
|
||||
fn until_wait(r: &mut Realm) -> Option<JsValue> {
|
||||
for _ in 0..10_000 {
|
||||
match r.advance(1_000).unwrap() {
|
||||
Progress::Done(v) => return Some(v),
|
||||
Progress::Paused if r.waits() => return None,
|
||||
Progress::Paused => {}
|
||||
}
|
||||
}
|
||||
panic!("the run neither waited nor ended")
|
||||
}
|
||||
|
||||
fn realm_with(more: impl FnOnce(&Realm) -> Vec<(String, HostItem)>) -> Realm {
|
||||
let f = |g: fn(&[Data]) -> Data| HostItem::Function(Rc::new(move |a: Vec<Data>| Ok(g(&a))));
|
||||
let text = |a: &[Data], i: usize| match a.get(i) {
|
||||
Some(Data::String(s)) => s.clone(),
|
||||
@@ -847,7 +1173,7 @@ mod tests {
|
||||
("parent", Data::String("/".into())),
|
||||
])
|
||||
};
|
||||
let messages = ["notOpen", "noWrites", "noPicker", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into()))));
|
||||
let messages = ["notOpen", "badMode", "noAlias", "noHidden"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into()))));
|
||||
let stat = move |a: Vec<Data>| -> Result<Data, crate::HostError> {
|
||||
let dir = text(&a, 0) == "/d";
|
||||
Ok(obj(vec![("exists", Data::Bool(dir)), ("dir", Data::Bool(dir))]))
|
||||
@@ -857,7 +1183,7 @@ mod tests {
|
||||
Ok(obj(vec![("entries", Data::Array(vec![e("a"), e("b")]))]))
|
||||
};
|
||||
let mut r = Realm::new();
|
||||
let items: Vec<(String, HostItem)> = vec![
|
||||
let mut items: Vec<(String, HostItem)> = vec![
|
||||
("text".into(), HostItem::Object(messages.to_vec())),
|
||||
("system".into(), HostItem::Value(Data::String("Unix".into()))),
|
||||
("lineFeed".into(), HostItem::Value(Data::String("Unix".into()))),
|
||||
@@ -868,10 +1194,79 @@ mod tests {
|
||||
("tempName".into(), f(|_| Data::String("/tmp1".into()))),
|
||||
("locations".into(), f(|_| Data::Object(vec![]))),
|
||||
];
|
||||
items.extend(more(&r));
|
||||
r.define_file_classes(items).unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_pauses_the_run_and_its_answer_becomes_files() {
|
||||
let (mut r, asked) = dialog_realm();
|
||||
let v = r.run("[File.openDialog.length, File.prototype.saveDlg.length, String(Folder.selectDialog).indexOf('[native code]') > 0].join()");
|
||||
assert_eq!(v.unwrap(), JsValue::String("3,2,true".into()), "the dialogs are built-ins");
|
||||
r.start("var f = File.openDialog('Pick', 'Text:*.txt', 1); [f.length, f[0].name, f[1].fsName, f[1] instanceof File].join()").unwrap();
|
||||
assert_eq!(until_wait(&mut r), None);
|
||||
assert_eq!(*asked.borrow(), ["open|Pick|true||Text:*.txt"]);
|
||||
r.answer(Data::Array(vec![Data::String("/a".into()), Data::String("/b".into())])).unwrap();
|
||||
assert_eq!(until_wait(&mut r), Some(JsValue::String("2,a,/b,true".into())));
|
||||
r.start("var g = new Folder('d').selectDlg(5); [g.name, g instanceof Folder].join()").unwrap();
|
||||
assert_eq!(until_wait(&mut r), None);
|
||||
assert_eq!(asked.borrow()[1], "folder|5|false|/d|", "the folder's own dialog starts at its path");
|
||||
r.answer(Data::String("/e".into())).unwrap();
|
||||
assert_eq!(until_wait(&mut r), Some(JsValue::String("e,true".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canceled_dialog_gives_null_and_an_error_answer_sets_error() {
|
||||
let (mut r, asked) = dialog_realm();
|
||||
r.start(
|
||||
"var d = new File('x'); var a = File.saveDialog(); var b = d.saveDlg('Save', function () { return true; }); [a, b, d.error].join('|')",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(until_wait(&mut r), None);
|
||||
r.answer(Data::Null).unwrap();
|
||||
assert_eq!(until_wait(&mut r), None, "a canceled dialog lets the run go on to the next one");
|
||||
assert_eq!(asked.borrow()[1], "save|Save|false|/x|", "a filter that is not a string gives no file types");
|
||||
r.answer(Data::Object(vec![("error".into(), Data::String("denied".into()))])).unwrap();
|
||||
assert_eq!(until_wait(&mut r), Some(JsValue::String("||denied".into())));
|
||||
r.start("File.openDialog(); 'went on'").unwrap();
|
||||
assert_eq!(until_wait(&mut r), None);
|
||||
r.end();
|
||||
assert!(!r.waits() && !r.is_running(), "a run ended at a dialog drops it");
|
||||
assert_eq!(r.run("'next'").unwrap(), JsValue::String("next".into()));
|
||||
let e = r.run("File.openDialog()").unwrap_err();
|
||||
assert!(e.message.contains("cannot wait here"), "a run that cannot pause does not wait: {e:?}");
|
||||
let e = r.run("File.prototype.openDlg.call({})").unwrap_err();
|
||||
assert!(e.message.contains("is not a File or a Folder"), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_in_a_function_or_a_loop_resumes_where_it_was_called() {
|
||||
let (mut r, asked) = dialog_realm();
|
||||
let script = "var seen = [];
|
||||
function pickOne(n) {
|
||||
try { var f = File.openDialog('n' + n, function (f) { return f.name !== 'skip'; }); return f === null ? 'none' : f.name; }
|
||||
finally { seen.push('f' + n); }
|
||||
}
|
||||
for (var k = 0; k < 3; k++) seen.push(pickOne(k));
|
||||
var many = File.openDialog('m', function (f) { return f.name !== 'b'; }, true);
|
||||
var thrown;
|
||||
try { File.openDialog('t', function () { throw new Error('no'); }); } catch (e) { thrown = e.message; }
|
||||
seen.concat([many.length, many[1].name, thrown]).join()";
|
||||
r.start(script).unwrap();
|
||||
for answer in ["/a", "/skip", "/c"] {
|
||||
assert_eq!(until_wait(&mut r), None);
|
||||
r.answer(Data::String(answer.into())).unwrap();
|
||||
}
|
||||
assert_eq!(until_wait(&mut r), None);
|
||||
r.answer(Data::Array(["/a", "/b", "/c"].map(|p| Data::String(p.into())).to_vec())).unwrap();
|
||||
assert_eq!(until_wait(&mut r), None);
|
||||
r.collect_garbage();
|
||||
r.answer(Data::String("/a".into())).unwrap();
|
||||
assert_eq!(until_wait(&mut r), Some(JsValue::String("f0,a,f1,none,f2,c,2,c,no".into())));
|
||||
assert_eq!(asked.borrow().len(), 5, "each dialog asked once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_keep_their_classes_through_collections() {
|
||||
let mut r = realm();
|
||||
|
||||
@@ -177,11 +177,13 @@ pub(crate) enum NativeKind {
|
||||
/// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given.
|
||||
/// `Data` is a host function given [`crate::Data`], its arguments read as `read` says. `Eval` is a
|
||||
/// host function that gives source to run as global code ([`crate::HostItem::Evaluator`]); `end`
|
||||
/// is called when that code ends.
|
||||
/// is called when that code ends. `Pausable` is a built-in that may ask the host for a value the
|
||||
/// run to wait for ([`crate::interp::Pause`]).
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Func {
|
||||
Closure { code: Rc<Code>, env: EnvId },
|
||||
Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str },
|
||||
Pausable { f: crate::interp::PausableFn, name: &'static str },
|
||||
Host { f: Rc<HostFn>, name: Rc<str> },
|
||||
Data { f: DataFn, name: Rc<str>, read: crate::host::ArgRead },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str> },
|
||||
|
||||
@@ -447,7 +447,12 @@ impl Interp {
|
||||
Ok(units) => self.prepare_source(units.len().saturating_sub(floor)),
|
||||
Err(_) => Ok(()),
|
||||
};
|
||||
rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval)))
|
||||
rest.map(|()| {
|
||||
units.and_then(|units| {
|
||||
self.observe_code(&units);
|
||||
self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval)
|
||||
})
|
||||
})
|
||||
});
|
||||
let code = code.and_then(|c| c);
|
||||
self.source_tag = tag;
|
||||
|
||||
@@ -673,6 +673,24 @@ fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unkn
|
||||
assert_eq!(r.error_source(), 0, "a syntax error is in the script");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_code_observer_sees_every_source_evaluated_at_run_time() {
|
||||
let mut r = realm(10_000_000);
|
||||
let seen = Rc::new(RefCell::new(Vec::<String>::new()));
|
||||
let s = seen.clone();
|
||||
r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units)));
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap();
|
||||
assert_eq!(out, JsValue::Number(49.0));
|
||||
let want = ["1 + 1", "2", "(function anonymous(a\n) {\nreturn a\n})", "40 + 2"];
|
||||
assert_eq!(*seen.borrow(), want, "the script's own text is not observed");
|
||||
seen.borrow_mut().clear();
|
||||
r.run("eval(7); Function.prototype.toString.call(f)").unwrap();
|
||||
assert!(seen.borrow().is_empty(), "eval of a value that is not a string compiles nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() {
|
||||
let mut r = realm(10_000_000);
|
||||
|
||||
@@ -162,6 +162,34 @@ pub(crate) struct Frame {
|
||||
/// Where the exception being thrown was raised: the code and the instruction.
|
||||
type ThrowSite = (Rc<Code>, usize);
|
||||
|
||||
/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time.
|
||||
pub(crate) type CodeObserver = Rc<dyn Fn(&[u16])>;
|
||||
|
||||
/// A built-in function that may wait for the host ([`crate::heap::Func::Pausable`]): it is given
|
||||
/// `this` and the arguments, and gives the host call it makes.
|
||||
pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult<Pause>;
|
||||
|
||||
/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the
|
||||
/// answer, and gives the result of its call.
|
||||
pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult<Value>;
|
||||
|
||||
/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to
|
||||
/// `resume` with `keep`, at once when the host answers at once. When the host waits
|
||||
/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on
|
||||
/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it.
|
||||
pub(crate) struct Pause {
|
||||
pub(crate) host: Value,
|
||||
pub(crate) args: Vec<Value>,
|
||||
pub(crate) keep: Vec<Value>,
|
||||
pub(crate) resume: ResumeFn,
|
||||
}
|
||||
|
||||
/// A [`Pause`] whose host call waits for its answer.
|
||||
pub(crate) struct Resumption {
|
||||
resume: ResumeFn,
|
||||
keep: Vec<Value>,
|
||||
}
|
||||
|
||||
pub(crate) struct Interp {
|
||||
pub(crate) heap: Heap,
|
||||
pub(crate) stack: Vec<Value>,
|
||||
@@ -222,6 +250,9 @@ pub(crate) struct Interp {
|
||||
pub(crate) can_wait: Rc<std::cell::Cell<bool>>,
|
||||
/// A host function's call waits for its result: the value on top of the stack stands in for it.
|
||||
pub(crate) waiting: bool,
|
||||
/// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before
|
||||
/// the next instruction runs.
|
||||
pub(crate) resuming: Option<Resumption>,
|
||||
/// The message of the uncatchable error a host function ended the run with.
|
||||
pub(crate) host_abort: Option<String>,
|
||||
/// How much a value passed to or from a host function may carry.
|
||||
@@ -230,6 +261,9 @@ pub(crate) struct Interp {
|
||||
pub(crate) source_tag: u32,
|
||||
/// The sources [`crate::HostItem::Evaluator`] functions have given in this realm.
|
||||
pub(crate) evaluated: u32,
|
||||
/// Called with the source text given to `eval`, `Function` and evaluator functions, before it
|
||||
/// is compiled ([`crate::Realm::observe_code`]).
|
||||
pub(crate) code_observer: Option<CodeObserver>,
|
||||
/// The tag of the source the last run's error was raised in.
|
||||
pub(crate) error_tag: u32,
|
||||
/// Where `$.line` and `$.stack` find the file and line of a compiled line.
|
||||
@@ -470,10 +504,12 @@ impl Interp {
|
||||
in_slice: false,
|
||||
can_wait: Rc::default(),
|
||||
waiting: false,
|
||||
resuming: None,
|
||||
host_abort: None,
|
||||
data_limits: crate::DataLimits::default(),
|
||||
source_tag: crate::realm::UNKNOWN_SOURCE,
|
||||
evaluated: 0,
|
||||
code_observer: None,
|
||||
error_tag: crate::realm::UNKNOWN_SOURCE,
|
||||
locator: None,
|
||||
thrown_mark: None,
|
||||
@@ -679,6 +715,7 @@ impl Interp {
|
||||
let mut roots = Roots::default();
|
||||
roots.values.extend(self.stack.iter());
|
||||
roots.values.extend(self.temp_roots.iter());
|
||||
roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter()));
|
||||
roots.values.push(&self.last_thrown);
|
||||
roots.values.push(&self.last_error);
|
||||
roots.values.push(&self.passing);
|
||||
@@ -743,6 +780,14 @@ impl Interp {
|
||||
|
||||
fn step(&mut self) -> JsResult<Option<Value>> {
|
||||
self.tick()?;
|
||||
// A built-in that waited for the host takes the answer on top of the stack before the
|
||||
// instruction after its call runs; what it throws is thrown at that call.
|
||||
if let Some(r) = self.resuming.take() {
|
||||
let answer = self.pop()?;
|
||||
let v = self.resume(r, answer)?;
|
||||
self.push(v)?;
|
||||
return Ok(None);
|
||||
}
|
||||
let frame = self.frame_mut()?;
|
||||
let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") };
|
||||
frame.pc += 1;
|
||||
@@ -2162,6 +2207,16 @@ impl Interp {
|
||||
self.temp_roots.truncate(mark);
|
||||
return Ok(Prepared::Done(r?));
|
||||
}
|
||||
Func::Pausable { f: native, .. } => {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(this.clone());
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
let held = self.held_bytes;
|
||||
let r = native(self, this, &args).and_then(|p| self.ask(p));
|
||||
self.held_bytes = held;
|
||||
self.temp_roots.truncate(mark);
|
||||
return Ok(Prepared::Done(r?));
|
||||
}
|
||||
Func::Data { f, name, read } => {
|
||||
// The arguments are read before the function runs, and a result being built
|
||||
// keeps itself reachable.
|
||||
@@ -2387,6 +2442,41 @@ impl Interp {
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host
|
||||
/// function is called as the script's own code calls it, so it may wait; then the resume
|
||||
/// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands
|
||||
/// in for that answer is the call's result for now.
|
||||
fn ask(&mut self, p: Pause) -> JsResult<Value> {
|
||||
let Pause { host, args, keep, resume } = p;
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(host.clone());
|
||||
self.temp_roots.extend(args.iter().cloned());
|
||||
self.temp_roots.extend(keep.iter().cloned());
|
||||
let was_waiting = self.waiting;
|
||||
let answer = match self.func_of(&host) {
|
||||
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read),
|
||||
_ => self.call(&host, &Value::Undefined, &args),
|
||||
};
|
||||
self.temp_roots.truncate(mark);
|
||||
let answer = answer?;
|
||||
let r = Resumption { resume, keep };
|
||||
if self.waiting && !was_waiting {
|
||||
self.resuming = Some(r);
|
||||
return Ok(answer);
|
||||
}
|
||||
self.resume(r, answer)
|
||||
}
|
||||
|
||||
/// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function.
|
||||
fn resume(&mut self, r: Resumption, answer: Value) -> JsResult<Value> {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.push(answer.clone());
|
||||
self.temp_roots.extend(r.keep.iter().cloned());
|
||||
let v = (r.resume)(self, &r.keep, answer);
|
||||
self.temp_roots.truncate(mark);
|
||||
v
|
||||
}
|
||||
|
||||
/// Calls `f` from Rust and returns its result, running the loop again for a function written
|
||||
/// in JavaScript.
|
||||
pub(crate) fn call(&mut self, f: &Value, this: &Value, args: &[Value]) -> JsResult<Value> {
|
||||
@@ -2435,6 +2525,13 @@ impl Interp {
|
||||
crate::to_utf16(text, &self.remaining_source_options()).map_err(CompileError::Syntax)
|
||||
}
|
||||
|
||||
/// Gives `units`, source a script evaluates at run time, to the realm's code observer.
|
||||
pub(crate) fn observe_code(&self, units: &[u16]) {
|
||||
if let Some(f) = &self.code_observer {
|
||||
f(units);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses and compiles source for eval code or a script, counting it against the source
|
||||
/// limit.
|
||||
pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
|
||||
@@ -2473,6 +2570,7 @@ impl Interp {
|
||||
self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.prepare_source(s.len())?;
|
||||
let units = self.flat_reserved(s)?;
|
||||
self.observe_code(&units);
|
||||
let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
|
||||
let frame = self.frame()?;
|
||||
|
||||
+19
-5
@@ -251,6 +251,7 @@ impl Realm {
|
||||
interp.last_error = Value::Null;
|
||||
interp.host_abort = None;
|
||||
interp.waiting = false;
|
||||
interp.resuming = None;
|
||||
interp.error_tag = UNKNOWN_SOURCE;
|
||||
interp.thrown_mark = None;
|
||||
interp.finally_marks.clear();
|
||||
@@ -286,6 +287,7 @@ impl Realm {
|
||||
interp.temp_roots.clear();
|
||||
interp.join_stack.clear();
|
||||
interp.waiting = false;
|
||||
interp.resuming = None;
|
||||
interp.passing = Value::Undefined;
|
||||
match result {
|
||||
Ok(v) => Ok(interp.to_js_value(&v)),
|
||||
@@ -375,7 +377,9 @@ impl Realm {
|
||||
}
|
||||
|
||||
/// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next
|
||||
/// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that
|
||||
/// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the
|
||||
/// call, the built-in takes `d` first and gives its own result, and what it throws is thrown
|
||||
/// at its call. A result past the heap limit ends the run with that
|
||||
/// limit, and with no call waiting this gives an internal error.
|
||||
pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> {
|
||||
let interp = &mut self.interp;
|
||||
@@ -468,10 +472,12 @@ impl Realm {
|
||||
/// Adds the global constructors `File` and `Folder`, whose file system work the host functions
|
||||
/// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`,
|
||||
/// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`,
|
||||
/// `encode`, `decode`, `encodingAvailable`, `current` and `locations`, with the values `system`
|
||||
/// and `lineFeed` and the messages `text.notOpen`, `text.noWrites`, `text.noPicker` and
|
||||
/// `text.badMode`. Each object keeps its path, its `error` text, its open file's id, its
|
||||
/// encoding and its line feed in properties that are not enumerable.
|
||||
/// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file
|
||||
/// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and
|
||||
/// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`,
|
||||
/// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error`
|
||||
/// text, its open file's id, its encoding and its line feed in properties that are not
|
||||
/// enumerable.
|
||||
pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> {
|
||||
match crate::file_classes::install(&mut self.interp, items) {
|
||||
Ok(()) => Ok(()),
|
||||
@@ -543,6 +549,14 @@ impl Realm {
|
||||
self.interp.date_host.offset = std::rc::Rc::new(offset);
|
||||
}
|
||||
|
||||
/// Calls `observe` with the text of each source the realm's scripts evaluate at run time, before
|
||||
/// it is compiled: a string given to `eval` (direct or indirect), the parameters and body
|
||||
/// `Function` joins, and a source an evaluator host function
|
||||
/// ([`crate::HostItem::Evaluator`]) gives. Replaces an earlier observer.
|
||||
pub fn observe_code(&mut self, observe: impl Fn(&[u16]) + 'static) {
|
||||
self.interp.code_observer = Some(std::rc::Rc::new(observe));
|
||||
}
|
||||
|
||||
/// Collects garbage now and returns the heap's estimated size in bytes afterwards.
|
||||
pub fn collect_garbage(&mut self) -> usize {
|
||||
self.interp.collect_garbage();
|
||||
|
||||
@@ -803,7 +803,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.arrange.tile",
|
||||
"Tile",
|
||||
"",
|
||||
"{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}",
|
||||
"{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}",
|
||||
),
|
||||
(
|
||||
"window.arrange.floatInWindow",
|
||||
@@ -1120,7 +1120,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.navigatorPanelOptions",
|
||||
"Panel Options…",
|
||||
"",
|
||||
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
|
||||
"{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing",
|
||||
),
|
||||
(
|
||||
"ui.layersExpand",
|
||||
@@ -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",
|
||||
|
||||
@@ -125,16 +125,19 @@ fn web_font_entries(dir: &Path) -> Result<(String, Vec<String>), 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<String> = 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,
|
||||
);
|
||||
|
||||
@@ -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<Vec<Listed<'_>>, 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"));
|
||||
|
||||
@@ -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/<first 16 hex digits of the SHA-256>/<file name>`.
|
||||
pub url: &'static str,
|
||||
/// Subresource Integrity value, `sha256-<base64>`; 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<Item = char>) -> Vec<usize> {
|
||||
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)));
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ impl Metrics {
|
||||
FirstBaseline::CapHeight => self.cap,
|
||||
FirstBaseline::XHeight => self.xh,
|
||||
FirstBaseline::Leading => self.lead,
|
||||
FirstBaseline::EmBoxHeight => self.top,
|
||||
FirstBaseline::Fixed => 0.0,
|
||||
};
|
||||
v.max(min)
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
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";
|
||||
|
||||
|
||||
@@ -1360,6 +1360,40 @@ fn inset_and_first_baseline_options() {
|
||||
assert!(cap.lines[0].baseline < base.lines[0].baseline && cap.lines[0].baseline > 5.0);
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height: the top of the first line's ideographic em box (the one leading
|
||||
/// measured from em box top to top uses) touches the top of the type area inside the inset. On a
|
||||
/// line of several sizes the largest em box decides, and a Min further down sets the baseline.
|
||||
#[test]
|
||||
fn em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top() {
|
||||
let frame = Rect::new(0.0, 0.0, 300.0, 300.0);
|
||||
let em_box = |t: &TextObject, inset: f64, min: f64| {
|
||||
let opts = LayoutOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: min, inset, ..Default::default() };
|
||||
layout_with(db(), t, &opts).lines[0].baseline
|
||||
};
|
||||
// The em box top the EmBoxTop leading model sets a frame's first line at.
|
||||
let em_top = |t: &TextObject| {
|
||||
let mut t = t.clone();
|
||||
t.para.leading_model = vectorcraft_doc::LeadingModel::EmBoxTop;
|
||||
layout(db(), &t).lines[0].baseline
|
||||
};
|
||||
let t = area(COPY, style(12.0), frame, Justify::Left);
|
||||
let top = em_top(&t);
|
||||
assert!(top > 5.0 && top < 12.0, "{top}");
|
||||
let ascent = layout(db(), &t).lines[0].baseline;
|
||||
assert!((top - ascent).abs() > 0.1, "not the ascent: {top} {ascent}");
|
||||
assert!((em_box(&t, 0.0, 0.0) - top).abs() < 1e-9);
|
||||
assert!((em_box(&t, 10.0, 0.0) - (10.0 + top)).abs() < 1e-9, "measured from the inset");
|
||||
// A Min nearer the top than the em box changes nothing; one further down is the baseline.
|
||||
assert!((em_box(&t, 10.0, top / 2.0) - (10.0 + top)).abs() < 1e-9);
|
||||
assert!((em_box(&t, 10.0, 30.0) - 40.0).abs() < 1e-9);
|
||||
// 10 pt and 20 pt on the first line: the 20 pt em box top is at the top.
|
||||
let mut mixed = area("small Large", style(10.0), frame, Justify::Left);
|
||||
mixed.runs = vec![run("small ", 10.0), run("Large", 20.0)];
|
||||
let large = area("Large", style(20.0), frame, Justify::Left);
|
||||
assert!((em_box(&mixed, 0.0, 0.0) - em_box(&large, 0.0, 0.0)).abs() < 1e-9);
|
||||
assert!((em_box(&large, 0.0, 0.0) - 2.0 * top * 10.0 / 12.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// `LineInfo::first_baseline`: each line that starts a column has its baseline that far below the
|
||||
/// column's top inside the inset, for every first baseline option, with and without a minimum and
|
||||
/// an inset, in both leading models, and for lines of several sizes (each line in one size).
|
||||
@@ -1374,8 +1408,14 @@ fn lines_starting_a_column_sit_at_their_first_baseline() {
|
||||
let text: String = runs.iter().map(|r| r.text.as_str()).collect();
|
||||
let mut other_sizes = 0;
|
||||
for model in [vectorcraft_doc::LeadingModel::RomanBaseline, vectorcraft_doc::LeadingModel::EmBoxTop] {
|
||||
for first_baseline in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::Fixed]
|
||||
{
|
||||
for first_baseline in [
|
||||
FirstBaseline::Ascent,
|
||||
FirstBaseline::CapHeight,
|
||||
FirstBaseline::XHeight,
|
||||
FirstBaseline::Leading,
|
||||
FirstBaseline::EmBoxHeight,
|
||||
FirstBaseline::Fixed,
|
||||
] {
|
||||
for (first_baseline_min, inset) in [(0.0, 0.0), (18.0, 6.0)] {
|
||||
for height in [100.0, 120.0, 140.0] {
|
||||
let mut t = area(&text, style(12.0), Rect::new(0.0, 0.0, 420.0, height), Justify::Left);
|
||||
|
||||
@@ -142,6 +142,32 @@ fn fit_first_line_widens_a_vertical_frame_from_its_right_edge() {
|
||||
assert_eq!(layout(FontDb::global(), &t).lines.len(), 1);
|
||||
}
|
||||
|
||||
/// First Baseline Em Box Height in vertical area type: the first column's em box edge touches the
|
||||
/// frame's right edge inside the inset, as far in as leading measured from em box top to top sets
|
||||
/// it.
|
||||
#[test]
|
||||
fn em_box_height_sets_a_vertical_frames_first_column_at_its_em_box() {
|
||||
use vectorcraft_doc::{FirstBaseline, LeadingModel};
|
||||
let first = |fb: FirstBaseline, model: LeadingModel| {
|
||||
let mut t = vertical("§§");
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 100.0, 105.0).to_path(0.1)) };
|
||||
t.area.first_baseline = fb;
|
||||
t.area.inset = 5.0;
|
||||
t.para.leading_model = model;
|
||||
let l = layout(FontDb::global(), &t);
|
||||
(l.lines[0].baseline, l.lines[0].first_baseline)
|
||||
};
|
||||
let (baseline, distance) = first(FirstBaseline::EmBoxHeight, LeadingModel::RomanBaseline);
|
||||
let (em_top, _) = first(FirstBaseline::Ascent, LeadingModel::EmBoxTop);
|
||||
let (ascent, ascent_distance) = first(FirstBaseline::Ascent, LeadingModel::RomanBaseline);
|
||||
assert!((baseline - em_top).abs() < 1e-9, "{baseline} {em_top}");
|
||||
// Measured from the edge inside the inset, where a Fixed first baseline of 0 sits.
|
||||
let (edge, _) = first(FirstBaseline::Fixed, LeadingModel::RomanBaseline);
|
||||
assert!((baseline - distance - edge).abs() < 1e-9, "{baseline} {distance} {edge}");
|
||||
assert!((ascent - ascent_distance - edge).abs() < 1e-9, "{ascent} {ascent_distance} {edge}");
|
||||
assert!((baseline - ascent).abs() > 0.1, "not the ascent: {baseline} {ascent}");
|
||||
}
|
||||
|
||||
/// `baselines`: one per line that holds characters, along it for horizontal type and down the
|
||||
/// column's centre line for vertical type (where point type's anchor is); none on a path.
|
||||
#[test]
|
||||
|
||||
@@ -231,7 +231,7 @@ fn a_warichu_line_keeps_the_auto_leading_of_its_own_size() {
|
||||
#[test]
|
||||
fn the_first_baseline_measures_a_block_at_its_own_size() {
|
||||
use vectorcraft_doc::FirstBaseline;
|
||||
for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading] {
|
||||
for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::EmBoxHeight] {
|
||||
let baseline = |inside: CharStyle| {
|
||||
let mut t = area("", style(20.0), Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left);
|
||||
t.area.first_baseline = first;
|
||||
|
||||
@@ -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
|
||||
@@ -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<f64> {
|
||||
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> {
|
||||
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<u64>,
|
||||
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<usize> {
|
||||
pub fn base_panel(panels: &[Panel]) -> Option<usize> {
|
||||
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<usize> {
|
||||
.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;
|
||||
@@ -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<usize>,
|
||||
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<FoldedPanel>,
|
||||
/// The panels in breadth-first order from the base, the panels not joined to it last.
|
||||
pub order: Vec<usize>,
|
||||
pub hinges: Vec<FoldedHinge>,
|
||||
/// 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<usize> {
|
||||
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<Point>) -> 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<usize>, amount: f64, tolerance: f64) -> Option<Folded> {
|
||||
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<usize>> = 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<Option<V3>> = 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<usize>], centers: &[Option<V3>], base: usize, amount: f64) -> (Vec<FoldedPanel>, Vec<bool>, Vec<usize>) {
|
||||
let n = blank.panels.len();
|
||||
let mut panels: Vec<FoldedPanel> = 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<bool> {
|
||||
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<Vec<Vec<Point>>> {
|
||||
let mut rings: Vec<Vec<Point>> = 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<Vec<V3>>,
|
||||
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<Option<Placed>> = blank
|
||||
.panels
|
||||
.iter()
|
||||
.zip(panels)
|
||||
.map(|(panel, f)| {
|
||||
let rings: Vec<Vec<V3>> =
|
||||
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<V3>], 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()
|
||||
}
|
||||
@@ -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<u8>,
|
||||
}
|
||||
|
||||
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<Level> {
|
||||
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<Level>,
|
||||
}
|
||||
|
||||
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<u8>) -> Option<Print> {
|
||||
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<u8>,
|
||||
pub panels: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
/// The panel drawn at pixel `(x, y)`.
|
||||
pub fn panel_at(&self, x: u32, y: u32) -> Option<usize> {
|
||||
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<Mapped> {
|
||||
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<u8>,
|
||||
depth: Vec<f64>,
|
||||
rank: Vec<u16>,
|
||||
panel: Vec<u16>,
|
||||
}
|
||||
|
||||
/// 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<Vec<Vec<[f64; 2]>>> {
|
||||
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<Image> {
|
||||
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<Vec<[f64; 2]>> = 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::<Vec<_>>()
|
||||
})
|
||||
.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;
|
||||
@@ -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<SubPath>) -> 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<Panel>, poses: Vec<Pose>) -> (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<u8> = (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<_>>(), 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<_>>(), 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]));
|
||||
}
|
||||
@@ -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<FoldLine> = 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<FoldLine> {
|
||||
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<FoldLine> {
|
||||
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<FoldLine> = 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<FoldLine> {
|
||||
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);
|
||||
}
|
||||
@@ -211,8 +211,26 @@ pub struct ShapeBuilderTool {
|
||||
prepared: Option<Arc<PreparedMerge>>,
|
||||
/// A gesture made while the map of a large selection is being built on another thread.
|
||||
deferred: Option<Deferred>,
|
||||
/// The button went down with nothing selected: the release says what to select.
|
||||
empty_press: bool,
|
||||
/// The last gesture put one of [`SHAPE_BUILDER_STATUS`] in the status bar: the next gesture that
|
||||
/// builds something clears it.
|
||||
diagnosed: bool,
|
||||
}
|
||||
|
||||
/// The status a Shape Builder gesture gives when the selection holds no path or compound path.
|
||||
pub const SELECT_PATHS: &str = "Shape Builder: select paths or compound paths";
|
||||
|
||||
/// The status a Shape Builder gesture that touched nothing gives when it ends over a path or
|
||||
/// compound path that is not selected.
|
||||
pub const SELECT_ALL_PATHS: &str = "Shape Builder: select all paths you want to merge";
|
||||
|
||||
/// The status a Shape Builder gesture that touched nothing gives anywhere else.
|
||||
pub const NO_REGION: &str = "Shape Builder: no region under the pointer";
|
||||
|
||||
/// The status messages the Shape Builder tool gives.
|
||||
pub const SHAPE_BUILDER_STATUS: [&str; 3] = [SELECT_PATHS, SELECT_ALL_PATHS, NO_REGION];
|
||||
|
||||
/// A Shape Builder gesture made while the map of the selection was being built on another
|
||||
/// thread: the map key and the inputs it was made over, its pointer events, which [`Tool::poll`]
|
||||
/// replays once the map is there, and whether the release has come.
|
||||
@@ -455,6 +473,26 @@ impl ShapeBuilderTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a gesture released at `p` that touched nothing built nothing: the selection gives no path
|
||||
/// or compound path ([`SELECT_PATHS`]); the pointer is over a path or compound path that a click
|
||||
/// can pick and that is neither selected nor inside a selected object ([`SELECT_ALL_PATHS`]); or
|
||||
/// neither ([`NO_REGION`]).
|
||||
fn nothing_built(&mut self, cx: &ToolContext, p: Point) -> Action {
|
||||
self.diagnosed = true;
|
||||
if self.cache.get(cx, self.opts.open_filled_as_closed).shapes.is_empty() {
|
||||
return Action::Status(SELECT_PATHS.into());
|
||||
}
|
||||
let unselected = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| {
|
||||
let chain: Vec<NodeId> = h.ancestry.iter().copied().chain([h.leaf]).collect();
|
||||
let path = chain
|
||||
.iter()
|
||||
.filter_map(|id| cx.doc.node(*id))
|
||||
.any(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }));
|
||||
path && !chain.iter().any(|id| cx.selection.contains(*id))
|
||||
});
|
||||
Action::Status(if unselected { SELECT_ALL_PATHS } else { NO_REGION }.into())
|
||||
}
|
||||
|
||||
/// The cursor swatch preview: the swatch before the current fill, the current fill (ringed)
|
||||
/// and the swatch after it, side by side above the pointer.
|
||||
fn swatch_chips(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
@@ -479,7 +517,9 @@ impl Tool for ShapeBuilderTool {
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Down => {
|
||||
// While a merge is being computed, a press starts no gesture.
|
||||
// While a merge is being computed, a press starts no gesture. With nothing
|
||||
// selected, the release says what to select.
|
||||
self.empty_press = cx.selection.is_empty() && !self.editing();
|
||||
if cx.selection.is_empty() || self.editing() {
|
||||
return vec![];
|
||||
}
|
||||
@@ -564,7 +604,7 @@ impl Tool for ShapeBuilderTool {
|
||||
let press = points.first().copied().filter(|s| marquee.is_none() && !self.far && s.distance(p) <= cx.tol(CLICK_TOL_PX));
|
||||
let split = press.filter(|q| self.stroke_at(cx, *q, erase).is_some());
|
||||
if std::mem::take(&mut self.touched).is_empty() && split.is_none() {
|
||||
return vec![];
|
||||
return vec![self.nothing_built(cx, p)];
|
||||
}
|
||||
self.stroke = None;
|
||||
let roots = sorted_roots(cx.doc, &cx.selection.objects);
|
||||
@@ -590,11 +630,17 @@ impl Tool for ShapeBuilderTool {
|
||||
if self.opts.swatches {
|
||||
params["pickColorFrom"] = json!("swatches");
|
||||
}
|
||||
// The gesture builds something: the reason the last one built nothing goes.
|
||||
let mut acts: Vec<Action> = std::mem::take(&mut self.diagnosed).then(|| Action::Status(String::new())).into_iter().collect();
|
||||
// A large selection's merge is computed on another thread; `poll` applies it.
|
||||
if self.start_merge(cx, ¶ms) {
|
||||
return vec![];
|
||||
if !self.start_merge(cx, ¶ms) {
|
||||
acts.push(Action::Exec("shapeBuilder.merge".into(), params));
|
||||
}
|
||||
vec![Action::Exec("shapeBuilder.merge".into(), params)]
|
||||
acts
|
||||
}
|
||||
PointerKind::Up if std::mem::take(&mut self.empty_press) => {
|
||||
self.diagnosed = true;
|
||||
vec![Action::Status(SELECT_PATHS.into())]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
@@ -693,6 +739,7 @@ impl Tool for ShapeBuilderTool {
|
||||
|
||||
/// Choosing another tool or another document applies the merge being computed first.
|
||||
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
self.empty_press = false;
|
||||
self.finish_edit(cx)
|
||||
}
|
||||
|
||||
@@ -735,9 +782,11 @@ impl Tool for ShapeBuilderTool {
|
||||
|
||||
/// With Pick Color From Color Swatches, the Left and Right arrow keys pick the color swatch
|
||||
/// before or after the current fill. Escape during a drag cancels it: the release after it
|
||||
/// merges and deletes nothing.
|
||||
/// merges and deletes nothing, and Escape while a press with nothing selected is held keeps its
|
||||
/// release from showing a status.
|
||||
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
|
||||
(self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape)
|
||||
(self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right))
|
||||
|| ((self.dragging || self.empty_press) && key == ToolKey::Escape)
|
||||
}
|
||||
|
||||
/// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their
|
||||
@@ -753,6 +802,7 @@ impl Tool for ShapeBuilderTool {
|
||||
}
|
||||
if key == ToolKey::Escape {
|
||||
self.dragging = false;
|
||||
self.empty_press = false;
|
||||
self.points.clear();
|
||||
self.touched = Touched::default();
|
||||
// A gesture recorded while the map is being built is canceled with it.
|
||||
|
||||
@@ -471,6 +471,106 @@ fn shape_builder_hover_builds_a_small_map_at_once() {
|
||||
assert_eq!((t.cache.builds, t.cache.background), (1, 0));
|
||||
}
|
||||
|
||||
fn status(msg: &str) -> Vec<Action> {
|
||||
vec![Action::Status(msg.into())]
|
||||
}
|
||||
|
||||
/// A click or drag with nothing selected shows what to select when it is released, and Escape
|
||||
/// during the press keeps the release quiet.
|
||||
#[test]
|
||||
fn shape_builder_with_nothing_selected_says_what_to_select() {
|
||||
let (d, _, _) = two_rects();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = ShapeBuilderTool::default();
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty());
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS), "a click");
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0)).is_empty());
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Drag, 125.0, 50.0)).is_empty());
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_PATHS), "a drag");
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)).is_empty(), "a release without a press");
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0));
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape));
|
||||
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)).is_empty(), "a canceled press");
|
||||
assert!(!t.claims_key(&cx, ToolKey::Escape));
|
||||
}
|
||||
|
||||
/// With A of the overlapping squares A and B selected, a click on the part of B outside A builds
|
||||
/// nothing and says to select every path to merge; a click on empty canvas says there is no
|
||||
/// region; a click inside A still merges A alone and clears that status, and the click after it
|
||||
/// gives the merge alone.
|
||||
#[test]
|
||||
fn shape_builder_names_the_unselected_path_under_a_release_that_built_nothing() {
|
||||
let (d, a, _) = two_rects();
|
||||
let mut s = Selection::default();
|
||||
s.set([a]);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = ShapeBuilderTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0));
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_ALL_PATHS));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0));
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0));
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0));
|
||||
assert!(
|
||||
matches!(acts.as_slice(), [Action::Status(m), Action::Exec(id, v)] if m.is_empty() && id == "shapeBuilder.merge" && v["ids"] == json!([a.0])),
|
||||
"{acts:?}"
|
||||
);
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0));
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0));
|
||||
assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "shapeBuilder.merge"), "{acts:?}");
|
||||
// A locked or hidden B cannot be picked, so the release says there is no region.
|
||||
for hide in [false, true] {
|
||||
let (mut d, a, b) = two_rects();
|
||||
let n = d.node_mut(b).unwrap();
|
||||
if hide {
|
||||
n.visible = false;
|
||||
} else {
|
||||
n.locked = true;
|
||||
}
|
||||
let mut s = Selection::default();
|
||||
s.set([a]);
|
||||
let cx = crate::testutil::cx(&d, &s, &p);
|
||||
let mut t = ShapeBuilderTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0));
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(NO_REGION), "hidden: {hide}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection that holds no path or compound path says to select one.
|
||||
#[test]
|
||||
fn shape_builder_with_no_path_selected_says_to_select_paths() {
|
||||
let (mut d, a, _) = two_rects();
|
||||
d.node_mut(a).unwrap().locked = true;
|
||||
let mut s = Selection::default();
|
||||
s.set([a]);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = ShapeBuilderTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0));
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS));
|
||||
}
|
||||
|
||||
/// A gesture made while the map of a large selection is being built and released over nothing
|
||||
/// gives its status once, when it is replayed.
|
||||
#[test]
|
||||
fn shape_builder_replayed_gesture_over_nothing_gives_its_status_once() {
|
||||
let (d, s) = square_row(200);
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let mut t = ShapeBuilderTool::default();
|
||||
t.pointer(&cx, &ev(PointerKind::Move, 15.0, 10.0));
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Down, 450.0, 450.0)).is_empty());
|
||||
assert_eq!(t.cache.builds, 0, "the gesture did not wait for the map");
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 450.0, 450.0)).is_empty(), "the gesture waits for the map");
|
||||
assert!(t.editing());
|
||||
assert_eq!(t.finish_edit(&cx), status(NO_REGION));
|
||||
assert!(t.finish_edit(&cx).is_empty() && !t.editing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() {
|
||||
let (d, a, b) = two_rects();
|
||||
@@ -485,7 +585,7 @@ fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() {
|
||||
let Action::Exec(_, v) = &acts[0] else { panic!() };
|
||||
assert_eq!(v["erase"], true);
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0));
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)).is_empty());
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION), "the release edits nothing and says why");
|
||||
}
|
||||
|
||||
/// Squares A (0..100) and B (50..150 both ways), overlapping at a corner, selected.
|
||||
@@ -998,9 +1098,9 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer()
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, 0.5, 27.0));
|
||||
let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") };
|
||||
assert_eq!((&v["splitStroke"], &v["points"]), (&json!(true), &json!([[-1.0, 25.0]])));
|
||||
// A release farther away is a drag, which splits nothing.
|
||||
// A release farther away is a drag, which splits nothing and says it touched no region.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0));
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)).is_empty());
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)), status(NO_REGION));
|
||||
// So is a Straight Line drag that goes away and ends back near the press.
|
||||
t.set_option("selection", &json!("straightLine"));
|
||||
t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0));
|
||||
@@ -1008,11 +1108,12 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer()
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, -0.5, 25.5));
|
||||
assert!(!acts.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("splitStroke").is_some())), "{acts:?}");
|
||||
t.set_option("selection", &json!("freeform"));
|
||||
// A drag merges as before and sends no switch.
|
||||
// A drag merges as before and sends no switch; it clears the status the drag before it gave.
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0));
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 75.0));
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 75.0));
|
||||
let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") };
|
||||
let [Action::Status(m), Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") };
|
||||
assert!(m.is_empty(), "{m}");
|
||||
assert!(v.get("splitStroke").is_none(), "{v}");
|
||||
}
|
||||
|
||||
|
||||
@@ -221,4 +221,8 @@ pub enum Action {
|
||||
SwitchTool(String),
|
||||
/// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object).
|
||||
Notify(String),
|
||||
/// Show this English message in the status bar (e.g. why a Shape Builder gesture built
|
||||
/// nothing); an empty message clears the status bar. It changes nothing in the document and
|
||||
/// records no undo step.
|
||||
Status(String),
|
||||
}
|
||||
@@ -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<Item> {
|
||||
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;
|
||||
@@ -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<Vec<Blank>>, 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<PrintKey>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Cache {
|
||||
blanks: Option<Blanks>,
|
||||
/// The last fold, what it folds and how long it took (ms).
|
||||
folded: Option<(FoldKey, Arc<Folded>, f64)>,
|
||||
/// What the texture shows.
|
||||
drawn: Option<DrawKey>,
|
||||
/// Folds worked out and images rendered (tests count them).
|
||||
folds: u64,
|
||||
renders: u64,
|
||||
/// The print shown and what it shows.
|
||||
print: Option<(PrintKey, Arc<Print>)>,
|
||||
/// Renders the print off the UI thread (None: on this thread).
|
||||
worker: Option<ThumbWorker<(), PrintKey>>,
|
||||
worker_started: bool,
|
||||
pending: Option<PrintKey>,
|
||||
settle: Settle,
|
||||
tex: Option<egui::TextureHandle>,
|
||||
/// The last frame's image, for double-click picking, and the screen rect it filled.
|
||||
image: Option<(Image, Rect)>,
|
||||
frame: Option<Frame>,
|
||||
/// Prints rendered (tests count them).
|
||||
prints: u64,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static CACHE: crate::graphics::TexCache<Cache> = crate::graphics::TexCache::default();
|
||||
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = 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<DRect> {
|
||||
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<Vec<Blank>>, 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<Folded>, 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<vectorcraft_engine::doc::Document>, 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<Print>)> {
|
||||
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<Value, String> {
|
||||
let mut set = app.ui.fold_preview.clone();
|
||||
let number = |key: &str, lo: f64, hi: f64| -> Result<Option<f64>, 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::<Vec<_>>().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<Vec<f64>> = 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<String> = 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<String> {
|
||||
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<vectorcraft_engine::doc::Document>, 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<Image> {
|
||||
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<Rect> {
|
||||
CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -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<usize> =
|
||||
(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<Event>, 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}");
|
||||
}
|
||||
@@ -182,6 +182,8 @@ impl VectorcraftApp {
|
||||
automation_roots: None,
|
||||
synthetic_frame: false,
|
||||
pending_plugin_install: None,
|
||||
script_picked: Vec::new(),
|
||||
script_picked_left_out: false,
|
||||
pen_end: Default::default(),
|
||||
host_iteration: 0,
|
||||
#[cfg(test)]
|
||||
@@ -354,8 +356,13 @@ impl VectorcraftApp {
|
||||
// A panel's, a dialog's or the text input's commit journaled in the frame before.
|
||||
crate::panels::actions::after_journaled_edit(self);
|
||||
crate::scripts_menu::poll(self, ctx);
|
||||
if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() {
|
||||
// A script in `$.sleep` goes on when its time is up; until then the app can idle.
|
||||
if self.session.script_running()
|
||||
&& !self.session.script_waiting()
|
||||
&& self.session.script_dialog().is_none()
|
||||
&& self.session.script_picker().is_none()
|
||||
{
|
||||
// A script in `$.sleep` goes on when its time is up; until then the app can idle. A
|
||||
// script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that.
|
||||
match self.session.script_sleep_left() {
|
||||
Some(left) => ctx.request_repaint_after(left),
|
||||
None => ctx.request_repaint(),
|
||||
|
||||
@@ -64,7 +64,7 @@ pub use overlays::SharedPaths;
|
||||
#[cfg(test)]
|
||||
use overlays::selected_anchor;
|
||||
use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay};
|
||||
pub use panes::Panes;
|
||||
pub use panes::{Layout as TileLayout, Panes};
|
||||
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
|
||||
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
|
||||
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document
|
||||
//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its
|
||||
//! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the
|
||||
//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its
|
||||
//! document from a render of its own, with its artboards, guides and selected objects, and a press
|
||||
//! in it makes its document the current one. A Selection drag released in it drops the dragged
|
||||
//! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New
|
||||
@@ -39,6 +40,9 @@ pub struct Panes {
|
||||
pending: HashMap<Slot, CacheKey>,
|
||||
/// The panes the last frame drew, as (window, pane rect).
|
||||
pub(crate) last: Vec<(Win, egui::Rect)>,
|
||||
/// The slots of `last`'s windows, in the same order: which windows they were, as document
|
||||
/// indices shift when a document closes.
|
||||
last_slots: Vec<Option<Slot>>,
|
||||
/// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and
|
||||
/// center the fit gave.
|
||||
fits: HashMap<Slot, (egui::Vec2, f64, Point)>,
|
||||
@@ -50,6 +54,7 @@ impl Panes {
|
||||
self.shown.clear();
|
||||
self.pending.clear();
|
||||
self.last.clear();
|
||||
self.last_slots.clear();
|
||||
self.fits.clear();
|
||||
}
|
||||
|
||||
@@ -162,37 +167,123 @@ fn render_pane(
|
||||
img
|
||||
}
|
||||
|
||||
/// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n`
|
||||
/// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover
|
||||
/// `area`; the spare cells of the last row stay empty.
|
||||
pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec<egui::Rect> {
|
||||
if n == 0 {
|
||||
return vec![];
|
||||
/// How Tile lays out the panes (`window.arrange.tile`'s `layout`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Layout {
|
||||
/// A grid: as many columns as the square root of the number of panes rounded up.
|
||||
#[default]
|
||||
Grid,
|
||||
/// Side by side in one row, each pane as tall as the document area.
|
||||
Vertical,
|
||||
/// Stacked in one column, each pane as wide as the document area.
|
||||
Horizontal,
|
||||
/// At most this many panes (2, 3, 4 or 6); the other windows stay under their tabs.
|
||||
Up(usize),
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
/// Each layout with its name in `layout`, in the order the menus list them.
|
||||
pub(crate) const ALL: [(&'static str, Layout); 7] = [
|
||||
("grid", Layout::Grid),
|
||||
("vertical", Layout::Vertical),
|
||||
("horizontal", Layout::Horizontal),
|
||||
("2up", Layout::Up(2)),
|
||||
("3up", Layout::Up(3)),
|
||||
("4up", Layout::Up(4)),
|
||||
("6up", Layout::Up(6)),
|
||||
];
|
||||
|
||||
/// The layout's name in `layout`.
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
Self::ALL.iter().find(|(_, l)| *l == self).map_or("grid", |(n, _)| n)
|
||||
}
|
||||
|
||||
/// The layout `p`'s `layout` names, the grid without one. Any other value is an error.
|
||||
pub(crate) fn from_params(p: &serde_json::Value) -> Result<Layout, String> {
|
||||
let key = "layout";
|
||||
match p.get(key) {
|
||||
None => Ok(Layout::Grid),
|
||||
Some(v) => v
|
||||
.as_str()
|
||||
.and_then(|s| Self::ALL.iter().find(|(n, _)| *n == s))
|
||||
.map(|(_, l)| *l)
|
||||
.ok_or_else(|| format!("`{key}` must be one of {}", Self::ALL.map(|(n, _)| n).join(", "))),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of `n` windows the layout gives a pane.
|
||||
fn panes(self, n: usize) -> usize {
|
||||
match self {
|
||||
Layout::Up(k) => n.min(k),
|
||||
_ => n,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many columns the layout puts `n` panes in.
|
||||
fn columns(self, n: usize) -> usize {
|
||||
match self {
|
||||
Layout::Grid => grid_columns(n),
|
||||
Layout::Vertical => n,
|
||||
Layout::Horizontal => 1,
|
||||
Layout::Up(k) if k <= 3 => n,
|
||||
Layout::Up(k) => grid_columns(k).min(n),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The square root of `n` rounded up.
|
||||
fn grid_columns(n: usize) -> usize {
|
||||
let mut cols = 1;
|
||||
while cols * cols < n {
|
||||
cols += 1;
|
||||
}
|
||||
cols
|
||||
}
|
||||
|
||||
/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns
|
||||
/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to
|
||||
/// edge and cover `area`; the spare cells of the last row stay empty.
|
||||
pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec<egui::Rect> {
|
||||
if n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
let cols = layout.columns(n).clamp(1, n);
|
||||
let rows = n.div_ceil(cols);
|
||||
let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 };
|
||||
let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 };
|
||||
(0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect()
|
||||
}
|
||||
|
||||
/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own,
|
||||
/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it
|
||||
/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it.
|
||||
pub(crate) fn tile(app: &mut VectorcraftApp) -> Result<serde_json::Value, String> {
|
||||
/// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of
|
||||
/// the first ones as it shows, with the current window `active` in the last pane when it is not
|
||||
/// among them.
|
||||
pub(crate) fn shown_windows(layout: Layout, docked: &[Win], active: Option<Win>) -> Vec<Win> {
|
||||
let k = layout.panes(docked.len());
|
||||
let mut shown = docked[..k].to_vec();
|
||||
if let (Some(a), Some(last)) = (active.filter(|a| !shown.contains(a) && docked.contains(a)), shown.last_mut()) {
|
||||
*last = a;
|
||||
}
|
||||
shown
|
||||
}
|
||||
|
||||
/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own
|
||||
/// as `layout` places them (the grid without one), each fitted to its pane. With fewer than two
|
||||
/// windows open (when the menu item is grayed out) it leaves the view, `tiled` and the layout as
|
||||
/// they are. The windows floating come back under the tabs for it. A `layout` that is not one of
|
||||
/// [`Layout::ALL`]'s names is an error.
|
||||
pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
let layout = Layout::from_params(p)?;
|
||||
app.sync_views();
|
||||
let n = crate::doc_windows::windows(app).len();
|
||||
if n < 2 {
|
||||
return Ok(json!({"tiled": app.ui.tiled, "panes": n}));
|
||||
return Ok(json!({"tiled": app.ui.tiled, "panes": n, "layout": app.ui.tile_layout.name()}));
|
||||
}
|
||||
crate::doc_windows::dock_all(app);
|
||||
app.ui.tiled = true;
|
||||
app.ui.tile_layout = layout;
|
||||
app.ui.home = None;
|
||||
crate::doc_windows::unfit_all(app);
|
||||
Ok(json!({"tiled": app.ui.tiled, "panes": n}))
|
||||
Ok(json!({"tiled": app.ui.tiled, "panes": layout.panes(n), "layout": layout.name()}))
|
||||
}
|
||||
|
||||
/// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the
|
||||
@@ -220,27 +311,43 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
app.canvas.panes.clear();
|
||||
}
|
||||
app.canvas.panes.last.clear();
|
||||
app.canvas.panes.last_slots.clear();
|
||||
return false;
|
||||
}
|
||||
// The current window's pane is the canvas, unless it is a floating one.
|
||||
let active = crate::doc_windows::current(app).filter(|a| docked.contains(a));
|
||||
// The 2-up to 6-up layouts leave the windows past their panes under the tabs.
|
||||
let layout = app.ui.tile_layout;
|
||||
let shown = shown_windows(layout, &docked, active);
|
||||
app.sync_views();
|
||||
let live: Vec<Slot> = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect();
|
||||
// The renders of the panes and the floating windows stay; a window under its tab has none.
|
||||
let live: Vec<Slot> =
|
||||
crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect();
|
||||
app.canvas.panes.shown.retain(|s, _| live.contains(s));
|
||||
app.canvas.panes.pending.retain(|s, _| live.contains(s));
|
||||
app.canvas.panes.fits.retain(|s, _| live.contains(s));
|
||||
// A window opened, closed, floated or docked changes the grid, and so does coming back to the
|
||||
// panes from one window: each window fits its new pane.
|
||||
if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) {
|
||||
for w in &docked {
|
||||
if let Some(v) = crate::doc_windows::view_mut(app, *w) {
|
||||
v.fitted = false;
|
||||
}
|
||||
// A window that moved to another pane fits it, and so does a window whose pane changed place or
|
||||
// size because a window opened, closed, floated or docked, or because the panes came back from
|
||||
// one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its
|
||||
// window into the last pane of a 2-up to 6-up layout, or when 6-Up loses its sixth document.
|
||||
// Windows are compared by their slots, since a closed document shifts the indices of the
|
||||
// documents after it, and panes by their place in the layout.
|
||||
let before = std::mem::take(&mut app.canvas.panes.last_slots);
|
||||
let now: Vec<Option<Slot>> = shown.iter().map(|w| slot(app, *w)).collect();
|
||||
let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0));
|
||||
let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit));
|
||||
for (i, (w, s)) in shown.iter().zip(&now).enumerate() {
|
||||
if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) {
|
||||
continue;
|
||||
}
|
||||
if let Some(v) = crate::doc_windows::view_mut(app, *w) {
|
||||
v.fitted = false;
|
||||
}
|
||||
}
|
||||
app.canvas.panes.last_slots = now;
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect();
|
||||
let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect();
|
||||
let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect();
|
||||
let unfitted = refit_resized(app, &areas);
|
||||
let mut activate = None;
|
||||
|
||||
@@ -43,6 +43,11 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event {
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }
|
||||
}
|
||||
|
||||
/// Tile's grid of `n` panes in `area`.
|
||||
fn cells(n: usize, area: egui::Rect) -> Vec<egui::Rect> {
|
||||
layout_cells(Layout::Grid, n, area)
|
||||
}
|
||||
|
||||
/// The documents' indices in the panes the last frame drew, and the panes.
|
||||
fn panes(app: &VectorcraftApp) -> (Vec<usize>, Vec<egui::Rect>) {
|
||||
app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip()
|
||||
@@ -84,6 +89,336 @@ fn cells_tile_the_area_edge_to_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The distinct left and top edges of `c`: how many columns and rows its panes take.
|
||||
fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) {
|
||||
let lefts: BTreeSet<u32> = c.iter().map(|r| r.left().to_bits()).collect();
|
||||
let tops: BTreeSet<u32> = c.iter().map(|r| r.top().to_bits()).collect();
|
||||
(lefts.len(), tops.len())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_tile_layout_places_its_panes_edge_to_edge() {
|
||||
let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0));
|
||||
let cases = [
|
||||
(Layout::Vertical, 3, (3, 1)),
|
||||
(Layout::Vertical, 7, (7, 1)),
|
||||
(Layout::Horizontal, 3, (1, 3)),
|
||||
(Layout::Up(2), 2, (2, 1)),
|
||||
(Layout::Up(3), 3, (3, 1)),
|
||||
(Layout::Up(3), 2, (2, 1)),
|
||||
(Layout::Up(4), 4, (2, 2)),
|
||||
(Layout::Up(4), 3, (2, 2)),
|
||||
(Layout::Up(6), 6, (3, 2)),
|
||||
(Layout::Up(6), 4, (3, 2)),
|
||||
(Layout::Up(6), 2, (2, 1)),
|
||||
];
|
||||
for (layout, n, shape) in cases {
|
||||
let c = layout_cells(layout, n, area);
|
||||
assert_eq!(c.len(), n);
|
||||
assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows");
|
||||
assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner");
|
||||
let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max);
|
||||
let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max);
|
||||
assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges");
|
||||
for (i, r) in c.iter().enumerate() {
|
||||
assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}");
|
||||
for o in &c[i + 1..] {
|
||||
assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(layout_cells(Layout::Up(2), 0, area).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() {
|
||||
let mut app = app_with(3);
|
||||
let ctx = egui::Context::default();
|
||||
let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap();
|
||||
assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"}));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!(docs, [0, 1, 2]);
|
||||
assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}");
|
||||
let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap();
|
||||
assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"}));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!(docs, [0, 1, 2]);
|
||||
assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}");
|
||||
// Each document fits its new pane.
|
||||
let artboard = Rect::new(0.0, 0.0, 400.0, 300.0);
|
||||
let canvas = app.canvas_rect.unwrap();
|
||||
for (i, r) in docs.iter().zip(&rects) {
|
||||
let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 };
|
||||
let v = app.views[*i];
|
||||
assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}");
|
||||
}
|
||||
assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal"));
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() {
|
||||
let mut app = app_with(5);
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "2up"}));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(panes(&app).0, [0, 4], "the current document takes the last pane");
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order");
|
||||
let second = (app.session.documents()[1].uid, 1);
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane");
|
||||
app.run("document.activate", json!({"index": 3})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane");
|
||||
assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render");
|
||||
let artboard = Rect::new(0.0, 0.0, 400.0, 300.0);
|
||||
let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1;
|
||||
assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9);
|
||||
assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas");
|
||||
// A document brought into the last pane leaves the first pane's zoom as it is.
|
||||
app.views[0].zoom *= 2.0;
|
||||
let zoomed = app.views[0].zoom;
|
||||
app.run("document.activate", json!({"index": 2})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(panes(&app).0, [0, 2]);
|
||||
assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom");
|
||||
let last = app.canvas_rect.unwrap();
|
||||
assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane");
|
||||
assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3], (2, 2)));
|
||||
assert_eq!(app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap()["panes"], json!(5), "6-Up with five documents shows them all");
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2)));
|
||||
assert_eq!(app.run("window.arrange.tile", json!({"layout": "3up"})).unwrap()["panes"], json!(3));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2], (3, 1)));
|
||||
app.run("document.activate", json!({"index": 4})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(panes(&app).0, [0, 1, 4]);
|
||||
}
|
||||
|
||||
/// A document closed before the panes shifts the indices of the ones after it: the document that
|
||||
/// moves into another pane fits it.
|
||||
#[test]
|
||||
fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() {
|
||||
let mut app = app_with(4);
|
||||
let ctx = egui::Context::default();
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
app.run("document.activate", json!({"index": 3})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(panes(&app).0, [0, 3]);
|
||||
let moving = app.session.documents()[1].uid;
|
||||
// The second document's view, under its tab, is zoomed away from its fit.
|
||||
app.views[1].zoom *= 3.0;
|
||||
app.run("file.close", json!({"index": 0})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last");
|
||||
assert_eq!(app.session.documents()[0].uid, moving);
|
||||
let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1;
|
||||
let v = app.views[0];
|
||||
assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}");
|
||||
}
|
||||
|
||||
/// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the
|
||||
/// others in their panes with the zoom they had. Side by side, closing one widens every pane, and
|
||||
/// each document fits its new pane.
|
||||
#[test]
|
||||
fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() {
|
||||
let mut app = app_with(6);
|
||||
let ctx = egui::Context::default();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(panes(&app).0, [0, 1, 2, 3, 4, 5]);
|
||||
app.views[1].zoom *= 2.0;
|
||||
let zoomed = app.views[1].zoom;
|
||||
app.run("file.close", json!({"index": 5})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2)));
|
||||
assert_eq!(app.views[1].zoom, zoomed, "the document that kept its pane keeps its zoom");
|
||||
|
||||
let mut app = app_with(3);
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
app.views[1].zoom *= 2.0;
|
||||
app.run("file.close", json!({"index": 2})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!(docs, [0, 1]);
|
||||
let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1;
|
||||
let v = app.views[1];
|
||||
assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_refuses_a_layout_it_does_not_have() {
|
||||
let mut app = app_with(3);
|
||||
for bad in [json!("5up"), json!("Vertical"), json!(3), json!(null), json!({})] {
|
||||
let err = app.run("window.arrange.tile", json!({"layout": bad})).unwrap_err();
|
||||
assert_eq!(err, "`layout` must be one of grid, vertical, horizontal, 2up, 3up, 4up, 6up", "{bad}");
|
||||
assert!(!app.ui.tiled && app.ui.tile_layout == Layout::Grid, "{bad}: the view stays as it is");
|
||||
}
|
||||
app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap();
|
||||
assert!(app.run("window.arrange.tile", json!({"layout": "diagonal"})).is_err());
|
||||
assert_eq!(app.ui.tile_layout, Layout::Vertical, "a refused layout leaves the tiled one");
|
||||
// With one document the layout is still checked, and nothing changes.
|
||||
let mut one = app_with(1);
|
||||
assert!(one.run("window.arrange.tile", json!({"layout": "7up"})).is_err());
|
||||
assert_eq!(one.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tile_items_check_the_layout_the_panes_show() {
|
||||
let mut app = app_with(3);
|
||||
let checked = |app: &VectorcraftApp, layout: Option<&str>| {
|
||||
let p = layout.map_or(serde_json::Value::Null, |l| json!({"layout": l}));
|
||||
crate::menus::checked(app, "window.arrange.tile", &p)
|
||||
};
|
||||
assert_eq!(checked(&app, None), Some(false), "not tiled");
|
||||
app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap();
|
||||
assert_eq!(checked(&app, Some("4up")), Some(true));
|
||||
assert_eq!(checked(&app, None), Some(false));
|
||||
assert_eq!(checked(&app, Some("2up")), Some(false));
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
assert_eq!(checked(&app, None), Some(true), "Tile is the grid");
|
||||
app.run("window.arrange.consolidateAllWindows", json!({})).unwrap();
|
||||
assert_eq!(checked(&app, None), Some(false));
|
||||
// Window › Arrange lists every layout, after Cascade and before Float in Window.
|
||||
let window = crate::menus::menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, items)| items).unwrap();
|
||||
let arrange = window
|
||||
.into_iter()
|
||||
.find_map(|i| match i {
|
||||
crate::menus::Item::Sub("Arrange", items) => Some(items),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let labels: Vec<&str> = arrange
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
crate::menus::Item::Cmd(l, ..) => Some(*l),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
labels,
|
||||
[
|
||||
"Cascade",
|
||||
"Tile",
|
||||
"Tile All Vertically",
|
||||
"Tile All Horizontally",
|
||||
"2-Up Layout",
|
||||
"3-Up Layout",
|
||||
"4-Up Layout",
|
||||
"6-Up Layout",
|
||||
"Float in Window",
|
||||
"Float All in Windows",
|
||||
"Consolidate All Windows"
|
||||
]
|
||||
);
|
||||
// Each item's params run, as the menu sends them.
|
||||
for item in &arrange {
|
||||
if let crate::menus::Item::Cmd(_, "window.arrange.tile", p) = item {
|
||||
let p = if p.is_null() { json!({}) } else { p.clone() };
|
||||
assert!(app.run("window.arrange.tile", p.clone()).is_ok(), "{p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of the application bar with screen-reader nodes on → the nodes.
|
||||
fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<egui::accesskit::Node> {
|
||||
app_bar_frame_in(app, ctx, events, 1400.0)
|
||||
}
|
||||
|
||||
/// [`app_bar_frame`] on a window `width` points wide.
|
||||
fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>, width: f32) -> Vec<egui::accesskit::Node> {
|
||||
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0));
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui));
|
||||
out.textures_delta.clear();
|
||||
out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The center of the application bar's node whose label, without its leading spaces, is `name`
|
||||
/// (or starts with it and a shortcut in parentheses).
|
||||
fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option<Pos2> {
|
||||
let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('('));
|
||||
let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?;
|
||||
Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32))
|
||||
}
|
||||
|
||||
/// Click the application bar's node labeled `name`.
|
||||
fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) {
|
||||
let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn"));
|
||||
app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]);
|
||||
app_bar_frame(app, ctx, vec![button(at, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arrange_documents_button_tiles_and_consolidates() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let mut app = app_with(3);
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
app_bar_frame(&mut app, &ctx, vec![]);
|
||||
let nodes = app_bar_frame(&mut app, &ctx, vec![]);
|
||||
let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands"));
|
||||
let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search shows"));
|
||||
assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search: {arrange:?}, {search:?}");
|
||||
click_app_bar(&mut app, &ctx, "Arrange Documents");
|
||||
let menu = app_bar_frame(&mut app, &ctx, vec![]);
|
||||
for item in [
|
||||
"Consolidate All Windows",
|
||||
"Tile",
|
||||
"Tile All Vertically",
|
||||
"Tile All Horizontally",
|
||||
"2-Up Layout",
|
||||
"3-Up Layout",
|
||||
"4-Up Layout",
|
||||
"6-Up Layout",
|
||||
] {
|
||||
assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}");
|
||||
}
|
||||
click_app_bar(&mut app, &ctx, "Tile All Vertically");
|
||||
assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status);
|
||||
click_app_bar(&mut app, &ctx, "Arrange Documents");
|
||||
click_app_bar(&mut app, &ctx, "Consolidate All Windows");
|
||||
assert!(!app.ui.tiled);
|
||||
}
|
||||
|
||||
/// As the application bar narrows, Arrange Documents goes before the search.
|
||||
#[test]
|
||||
fn a_narrow_application_bar_keeps_search_before_arrange_documents() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let mut app = app_with(3);
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut search_alone = false;
|
||||
for width in (200..=1400).rev().step_by(4) {
|
||||
app_bar_frame_in(&mut app, &ctx, vec![], width as f32);
|
||||
let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32);
|
||||
let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands").is_some());
|
||||
assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search");
|
||||
search_alone |= search && !arrange;
|
||||
}
|
||||
assert!(search_alone, "some width shows the search without Arrange Documents");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_shows_a_pane_for_each_document_fitted_to_it() {
|
||||
let mut app = app_with(3);
|
||||
@@ -91,7 +426,7 @@ fn tile_shows_a_pane_for_each_document_fitted_to_it() {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(panes(&app).0.is_empty(), "documents open under their tabs");
|
||||
let tabbed = app.canvas_rect.unwrap();
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3}));
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"}));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let (docs, rects) = panes(&app);
|
||||
assert_eq!(docs, [0, 1, 2]);
|
||||
@@ -454,7 +789,7 @@ fn arrange_items_follow_the_open_documents() {
|
||||
fn tile_with_one_document_leaves_the_next_one_under_its_tab() {
|
||||
let mut app = app_with(1);
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1}));
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"}));
|
||||
assert!(!app.ui.tiled);
|
||||
assert!(!enabled(&app, "window.arrange.consolidateAllWindows"));
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
gap: ui.spacing().item_spacing.x,
|
||||
community: crate::community::discord_width(ui, false),
|
||||
});
|
||||
let (switcher, ws_w, learn, discord) = (fit.switcher, fit.switcher_w, fit.learn, fit.community);
|
||||
let (switcher, ws_w, arrange, learn, discord) = (fit.switcher, fit.switcher_w, fit.arrange, fit.learn, fit.community);
|
||||
let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
let ui = &mut rui;
|
||||
// Workspace switcher: shows the current workspace, opens Window → Workspace.
|
||||
@@ -129,6 +129,11 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
// Arrange Documents: Consolidate All Windows and the Tile layouts.
|
||||
if arrange {
|
||||
let resp = widgets::icon_button(ui, "layout-grid", tl!("Arrange Documents"), app.ui.tiled, BAR_ICON);
|
||||
egui::Popup::menu(&resp).show(|ui| arrange_documents_popup(app, ui));
|
||||
}
|
||||
// Search → command palette (its shortcut opens it too).
|
||||
let with_shortcut = |text: &str| match &field.shortcut {
|
||||
Some(sc) => format!("{text} ({sc})"),
|
||||
@@ -181,7 +186,34 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The side of the app bar's square icon buttons (the search icon, Explore tutorials).
|
||||
/// The Arrange Documents menu ([`menus::arrange_documents_items`]): each item as the Window menu
|
||||
/// shows it, grayed out while its command can't run, the Tile layout the panes show checked.
|
||||
fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.set_min_width(200.0);
|
||||
let mut clicked = None;
|
||||
for it in menus::arrange_documents_items() {
|
||||
match it {
|
||||
menus::Item::Sep => {
|
||||
ui.separator();
|
||||
}
|
||||
menus::Item::Cmd(label, id, p) => {
|
||||
let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue };
|
||||
let label = crate::i18n::t_id(id, label);
|
||||
let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") };
|
||||
if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() {
|
||||
clicked = Some((id, if p.is_null() { json!({}) } else { p }));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some((id, p)) = clicked {
|
||||
menus::invoke(app, id, p);
|
||||
}
|
||||
}
|
||||
|
||||
/// The side of the app bar's square icon buttons (the search icon, Arrange Documents, Explore tutorials).
|
||||
const BAR_ICON: f32 = 28.0;
|
||||
/// The narrowest the workspace switcher gets.
|
||||
const MIN_SWITCHER: f32 = 64.0;
|
||||
@@ -225,6 +257,8 @@ struct RightGroup {
|
||||
switcher_w: f32,
|
||||
/// How the search shows.
|
||||
search: Search,
|
||||
/// Whether Arrange Documents shows.
|
||||
arrange: bool,
|
||||
/// Whether Explore tutorials shows.
|
||||
learn: bool,
|
||||
/// Whether the community button shows.
|
||||
@@ -232,8 +266,8 @@ struct RightGroup {
|
||||
}
|
||||
|
||||
/// The right-hand group for the room it has. As the room runs short, the community button goes first
|
||||
/// (it is also under Help), then Explore tutorials (also Window › Learn), then the search field becomes the
|
||||
/// search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe
|
||||
/// (it is also under Help), then Explore tutorials (also Window › Learn), then Arrange Documents (also Window ›
|
||||
/// Arrange), then the search field becomes the search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe
|
||||
/// Mode the label's width is taken first, and the switcher (also under Window › Workspace) goes when
|
||||
/// a minimal one does not fit.
|
||||
fn fit_right_group(w: &RightWidths) -> RightGroup {
|
||||
@@ -254,10 +288,12 @@ fn fit_right_group(w: &RightWidths) -> RightGroup {
|
||||
Search::Hidden => 0.0,
|
||||
};
|
||||
let switcher_w = w.switcher.min(room - 8.0 - search_w).max(MIN_SWITCHER);
|
||||
let learn_end = switcher_w + 8.0 + search_w + w.gap + w.icon;
|
||||
let learn = field && room >= learn_end;
|
||||
let arrange_end = switcher_w + 8.0 + search_w + w.gap + w.icon;
|
||||
let arrange = field && room >= arrange_end;
|
||||
let learn_end = arrange_end + w.gap + w.icon;
|
||||
let learn = arrange && room >= learn_end;
|
||||
let community = learn && room >= learn_end + 10.0 + w.gap + w.community;
|
||||
RightGroup { switcher, switcher_w, search, learn, community }
|
||||
RightGroup { switcher, switcher_w, search, arrange, learn, community }
|
||||
}
|
||||
|
||||
/// The app bar's search field: a button drawn as a field. The command palette's popup holds the
|
||||
|
||||
@@ -172,11 +172,11 @@ fn right_stage(g: &super::RightGroup) -> String {
|
||||
w if w > super::MIN_SWITCHER => "narrower switcher",
|
||||
_ => "minimal switcher",
|
||||
};
|
||||
format!("community {}, learn {}, {:?}, {switcher}", g.community, g.learn, g.search)
|
||||
format!("community {}, learn {}, arrange {}, {:?}, {switcher}", g.community, g.learn, g.arrange, g.search)
|
||||
}
|
||||
|
||||
/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then the search
|
||||
/// field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes.
|
||||
/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then Arrange
|
||||
/// Documents, then the search field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes.
|
||||
/// Whatever shows fits in the room, down to the minimal switcher alone.
|
||||
#[test]
|
||||
fn the_app_bar_gives_up_its_right_hand_controls_in_order() {
|
||||
@@ -193,31 +193,33 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() {
|
||||
super::Search::Icon => w.gap + w.icon,
|
||||
super::Search::Hidden => 0.0,
|
||||
};
|
||||
let arrange = if g.arrange { w.gap + w.icon } else { 0.0 };
|
||||
let learn = if g.learn { w.gap + w.icon } else { 0.0 };
|
||||
let community = if g.community { 10.0 + w.gap + w.community } else { 0.0 };
|
||||
let used = g.switcher_w + 8.0 + search + learn + community;
|
||||
let used = g.switcher_w + 8.0 + search + arrange + learn + community;
|
||||
assert!(used <= room || g.switcher_w == super::MIN_SWITCHER && g.search == super::Search::Hidden, "{room}: {g:?} needs {used}");
|
||||
}
|
||||
assert_eq!(
|
||||
stages,
|
||||
[
|
||||
"community true, learn true, Field, full switcher",
|
||||
"community false, learn true, Field, full switcher",
|
||||
"community false, learn false, Field, full switcher",
|
||||
"community false, learn false, Icon, full switcher",
|
||||
"community false, learn false, Icon, narrower switcher",
|
||||
"community false, learn false, Icon, minimal switcher",
|
||||
"community true, learn true, arrange true, Field, full switcher",
|
||||
"community false, learn true, arrange true, Field, full switcher",
|
||||
"community false, learn false, arrange true, Field, full switcher",
|
||||
"community false, learn false, arrange false, Field, full switcher",
|
||||
"community false, learn false, arrange false, Icon, full switcher",
|
||||
"community false, learn false, arrange false, Icon, narrower switcher",
|
||||
"community false, learn false, arrange false, Icon, minimal switcher",
|
||||
// Once the icon has gone, the switcher takes the room it leaves.
|
||||
"community false, learn false, Hidden, narrower switcher",
|
||||
"community false, learn false, Hidden, minimal switcher",
|
||||
"community false, learn false, arrange false, Hidden, narrower switcher",
|
||||
"community false, learn false, arrange false, Hidden, minimal switcher",
|
||||
]
|
||||
);
|
||||
// In Safe Mode the label's width is taken first (not counted in `room`), and the switcher goes
|
||||
// when a minimal one does not fit.
|
||||
let safe = |room| right_stage(&super::fit_right_group(&right_widths(room, true)));
|
||||
assert_eq!(safe(700.0), "community true, learn true, Field, full switcher");
|
||||
assert_eq!(safe(72.0), "community false, learn false, Hidden, minimal switcher");
|
||||
assert_eq!(safe(71.0), "community false, learn false, Hidden, no switcher");
|
||||
assert_eq!(safe(700.0), "community true, learn true, arrange true, Field, full switcher");
|
||||
assert_eq!(safe(72.0), "community false, learn false, arrange false, Hidden, minimal switcher");
|
||||
assert_eq!(safe(71.0), "community false, learn false, arrange false, Hidden, no switcher");
|
||||
}
|
||||
|
||||
/// What screen readers call the app bar's search field, and the icon it becomes, before the shortcut.
|
||||
|
||||
@@ -275,11 +275,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
// The display profile the canvas is drawn through, or why none (Preferences ›
|
||||
// Performance › Use Monitor Profile for Canvas).
|
||||
"displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display),
|
||||
// Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew:
|
||||
// each one's document index, view number (Window › New Window) and rect. Canvas
|
||||
// coordinates map to the current window's pane, inside its rulers and scroll bars
|
||||
// Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the
|
||||
// last frame drew: each one's document index, view number (Window › New Window) and rect.
|
||||
// Canvas coordinates map to the current window's pane, inside its rulers and scroll bars
|
||||
// (`canvasRect`).
|
||||
"tiled": app.ui.tiled,
|
||||
"tileLayout": app.ui.tile_layout.name(),
|
||||
"panes": app.canvas.panes.last.iter().map(|(w, c)| json!({
|
||||
"document": w.0,
|
||||
"view": w.1,
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -440,6 +440,7 @@ registry! {
|
||||
ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC,
|
||||
ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC,
|
||||
ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC,
|
||||
ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC,
|
||||
VectorHalftone: [halftone::KIND] => halftone::SPEC,
|
||||
SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC,
|
||||
SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC,
|
||||
@@ -716,6 +717,9 @@ pub fn cancel(app: &mut VectorcraftApp) {
|
||||
if d.kind == script_run::NOTICE_KIND {
|
||||
script_run::notice_cancel(app, &d);
|
||||
}
|
||||
if d.kind == script_run::PICKER_KIND {
|
||||
script_run::picker_cancel(app, &d);
|
||||
}
|
||||
missing_links::cancelled(app, &d);
|
||||
// Find Font's next open starts with an empty replacement search.
|
||||
if d.kind == "findFont"
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
@@ -250,8 +250,14 @@ const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "des
|
||||
const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText"), ("Block", "block")];
|
||||
|
||||
/// Area Type Options › First Baseline.
|
||||
const FIRST_BASELINE: form::Choices =
|
||||
&[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")];
|
||||
const FIRST_BASELINE: form::Choices = &[
|
||||
("Ascent", "ascent"),
|
||||
("Cap Height", "capHeight"),
|
||||
("x Height", "xHeight"),
|
||||
("Leading", "leading"),
|
||||
("Em Box Height", "emBoxHeight"),
|
||||
("Fixed", "fixed"),
|
||||
];
|
||||
|
||||
/// Area Type Options › Align (vertical alignment of the lines in each row/column).
|
||||
const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")];
|
||||
@@ -313,6 +319,35 @@ mod tests {
|
||||
assert_eq!(t.area.vertical_align, VerticalAlign::Center);
|
||||
}
|
||||
|
||||
/// Area Type Options › First Baseline offers Em Box Height: OK sets it with its Min, and the
|
||||
/// dialog opens again with it chosen.
|
||||
#[test]
|
||||
fn area_type_options_dialog_sets_the_em_box_height_first_baseline() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
// The labels `i18n::tests::first_baseline_choices_are_in_complete_catalogs` checks.
|
||||
let labels: Vec<&str> = choices("text.areaOptions", "firstBaseline").unwrap().iter().map(|(l, _)| *l).collect();
|
||||
assert_eq!(labels, ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"]);
|
||||
crate::menus::invoke(&mut app, "text.areaOptions", json!({}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "ascent");
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let fields = &mut app.ui.dialog.as_mut().unwrap().fields;
|
||||
fields.insert("firstBaseline".into(), json!("emBoxHeight"));
|
||||
fields.insert("firstBaselineMin".into(), json!(4.0));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (vectorcraft_doc::FirstBaseline::EmBoxHeight, 4.0));
|
||||
crate::menus::invoke(&mut app, "text.areaOptions", json!({}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "emBoxHeight");
|
||||
}
|
||||
|
||||
/// Area Type Options shows the gutter between rows beside the gutter, and OK sets a gutter
|
||||
/// between rows of its own.
|
||||
#[test]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -85,7 +85,7 @@ mod tests {
|
||||
d.fields.insert("solidDashes".into(), json!(solid));
|
||||
super::super::confirm(app)
|
||||
};
|
||||
assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true}));
|
||||
assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true}));
|
||||
assert!(app.ui.dialog.is_none());
|
||||
app.run("ui.navigatorPanelOptions", json!({})).unwrap();
|
||||
set(&mut app, "#0000FF", true).unwrap();
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -167,7 +167,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
|
||||
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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -912,7 +912,7 @@ pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator<Item
|
||||
Value::String(s) => 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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -13,10 +13,22 @@
|
||||
//! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer.
|
||||
//! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert.
|
||||
//! Stop ends the run and puts back everything it did.
|
||||
//!
|
||||
//! A script's file dialog (kind `scriptFiles`: `File.openDialog`, `File.saveDialog`,
|
||||
//! `Folder.selectDialog` and the objects' `openDlg`, `saveDlg` and `selectDlg`) has the fields
|
||||
//! `kind` (open, save or folder), `prompt` and `canAlways`, and takes `answer`: `once`, `always`
|
||||
//! (only with `canAlways`), `deny` or `stop`. Only the person at the keyboard answers `once` or
|
||||
//! `always`: from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input they are refused, and the
|
||||
//! dialog stays open; `deny` and `stop` are taken from automation too. The paths it allows are the
|
||||
//! ones Choose… picked in the host's file dialog, at most 2,048; `ui.dialog.set` cannot set them,
|
||||
//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape,
|
||||
//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny.
|
||||
//! `selectDlg` opens the host's folder picker in its own folder.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs};
|
||||
use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text};
|
||||
use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker};
|
||||
use vectorcraft_engine::script::{DialogAnswer, ScriptDialog};
|
||||
|
||||
use super::{DialogAction, DialogSpec};
|
||||
@@ -32,6 +44,19 @@ pub const GROWTH_KIND: &str = "scriptGrowth";
|
||||
pub const CLOSE_KIND: &str = "scriptClose";
|
||||
/// The dialog kind of a script's `alert`, `confirm` and `prompt`.
|
||||
pub const NOTICE_KIND: &str = "scriptDialog";
|
||||
/// The dialog kind of a script's file dialogs.
|
||||
pub const PICKER_KIND: &str = "scriptFiles";
|
||||
|
||||
pub(super) const PICKER_SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Script File Access").into(),
|
||||
body_with_actions: Some(picker_body),
|
||||
confirm: picker_confirm,
|
||||
ok: None,
|
||||
inputs: |_| &["answer"],
|
||||
min_width: 420.0,
|
||||
max_width: Some(560.0),
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec {
|
||||
heading: notice_heading,
|
||||
@@ -171,7 +196,7 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result<Value, String>
|
||||
/// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which
|
||||
/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet.
|
||||
pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
|
||||
let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND);
|
||||
let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND);
|
||||
if app.ui.dialog.is_some() {
|
||||
return;
|
||||
}
|
||||
@@ -192,6 +217,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) {
|
||||
if !app.session.script_running() {
|
||||
app.ui.dialog = None;
|
||||
} else if app.session.script_dialog().is_none()
|
||||
&& app.session.script_picker().is_none()
|
||||
&& let Some(d) = app.ui.dialog.as_mut()
|
||||
{
|
||||
d.fields.remove(super::PARENT);
|
||||
@@ -327,6 +353,192 @@ fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result<Value, Str
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Shows the file dialog the running script waits at.
|
||||
pub(crate) fn open_picker(app: &mut VectorcraftApp, p: &ScriptPicker) {
|
||||
let fields = json!({
|
||||
"kind": p.kind.id(),
|
||||
"prompt": p.prompt,
|
||||
"multiple": p.multiple,
|
||||
"start": p.start,
|
||||
"filters": p.filters,
|
||||
"canAlways": p.can_always,
|
||||
});
|
||||
app.script_picked.clear();
|
||||
app.script_picked_left_out = false;
|
||||
app.ui.dialog = Some(Dialog::new(PICKER_KIND, fields));
|
||||
}
|
||||
|
||||
/// Shows the host's file dialog of the kind the running script asked for, starting at the script's
|
||||
/// file or folder, with the script's file types, and keeps what it picked in
|
||||
/// [`VectorcraftApp::script_picked`]: in place of the paths before, or after them when the script
|
||||
/// asked for several files. At most [`MAX_ENTRIES`] paths are kept, the number of files the script
|
||||
/// is given; the dialog tells the person when it left out more.
|
||||
pub(crate) fn choose(app: &mut VectorcraftApp, d: &mut Dialog) {
|
||||
let r = crate::picks::in_app_dialog(app, d, |app, _| {
|
||||
let Some(p) = app.session.script_picker() else { return Ok(()) };
|
||||
let start = p.start.as_deref().map(std::path::Path::new);
|
||||
let name = start.and_then(|s| s.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let folder = start.and_then(|s| s.parent()).map(|s| s.to_string_lossy().into_owned());
|
||||
let pick = FilePick { name, folder, filters: p.filters.clone() };
|
||||
let several = p.multiple && p.kind == PickerKind::Open;
|
||||
let chosen: Vec<String> = match p.kind {
|
||||
PickerKind::Open if several => crate::picks::open_files(app, &pick),
|
||||
PickerKind::Open => crate::picks::open(app, &pick).into_iter().collect(),
|
||||
PickerKind::Save => crate::picks::save(app, &pick).into_iter().collect(),
|
||||
// `selectDlg` starts in its folder; `Folder.selectDialog` gives none.
|
||||
PickerKind::Folder => match p.start.clone() {
|
||||
Some(start) => crate::picks::folder_at(app, &start).into_iter().collect(),
|
||||
None => crate::picks::folder(app).into_iter().collect(),
|
||||
},
|
||||
};
|
||||
if !chosen.is_empty() {
|
||||
let mut paths = if several { std::mem::take(&mut app.script_picked) } else { Vec::new() };
|
||||
let mut seen: std::collections::HashSet<String> = paths.iter().cloned().collect();
|
||||
for path in chosen {
|
||||
if seen.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
if paths.len() >= MAX_ENTRIES {
|
||||
app.script_picked_left_out = true;
|
||||
break;
|
||||
}
|
||||
seen.insert(path.clone());
|
||||
paths.push(path);
|
||||
}
|
||||
app.script_picked = paths;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
// Picking a path doesn't fail.
|
||||
let _ = r;
|
||||
}
|
||||
|
||||
/// The dialog's prompt and the access it describes come from the request the run waits at, not
|
||||
/// from the dialog's fields, so `ui.dialog.set` cannot change what the person reads.
|
||||
fn picker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Some((kind, prompt)) = app.session.script_picker().map(|p| (p.kind, shown_text(&p.prompt, true))) else { return DialogAction::None };
|
||||
if !prompt.is_empty() {
|
||||
egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| ui.label(&prompt));
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
ui.label(picker_request(kind));
|
||||
ui.add_space(8.0);
|
||||
let paths = app.script_picked.clone();
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::secondary_button(ui, tl!("Choose…")).clicked() {
|
||||
choose(app, d);
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
if let [path] = paths.as_slice() {
|
||||
ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong));
|
||||
}
|
||||
});
|
||||
if paths.len() > 1 {
|
||||
ui.add_space(4.0);
|
||||
egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, |ui| {
|
||||
for path in &paths {
|
||||
ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong));
|
||||
}
|
||||
});
|
||||
}
|
||||
if app.script_picked_left_out {
|
||||
ui.add_space(4.0);
|
||||
ui.colored_label(t.error, crate::i18n::msg(PICKED_LEFT_OUT));
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
let chosen = !app.script_picked.is_empty();
|
||||
let can_always = app.session.script_picker().is_some_and(|p| p.can_always);
|
||||
let mut answer = None;
|
||||
let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y);
|
||||
ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if widgets::primary_button_enabled(ui, tl!("Allow Once"), chosen).clicked() {
|
||||
answer = Some("once");
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
if can_always {
|
||||
if ui.add_enabled_ui(chosen, |ui| widgets::secondary_button(ui, tl!("Always Allow This Script"))).inner.clicked() {
|
||||
answer = Some("always");
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
if widgets::secondary_button(ui, tl!("Deny")).clicked() {
|
||||
answer = Some("deny");
|
||||
}
|
||||
// The row runs right to left: Stop goes at its left end.
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
if widgets::secondary_button(ui, tl!("Stop")).clicked() {
|
||||
answer = Some("stop");
|
||||
}
|
||||
});
|
||||
});
|
||||
// Enter gives the dialog's default answer, Deny, as `ui.dialog.confirm` without an answer does,
|
||||
// unless it goes to the button that has the keyboard focus (Choose…).
|
||||
let unfocused = ui.ctx().memory(|m| m.focused().is_none());
|
||||
if answer.is_none() && unfocused && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) {
|
||||
answer = Some("deny");
|
||||
}
|
||||
let Some(answer) = answer else { return DialogAction::None };
|
||||
d.fields.insert("answer".into(), json!(answer));
|
||||
DialogAction::Confirm
|
||||
}
|
||||
|
||||
/// What the file dialog of `kind` asks the person to allow.
|
||||
fn picker_request(kind: PickerKind) -> &'static str {
|
||||
match kind {
|
||||
PickerKind::Open => tl!("The script asks to read a file you choose."),
|
||||
PickerKind::Save => tl!("The script asks to read and write a file you choose."),
|
||||
PickerKind::Folder => tl!("The script asks to read and write a folder you choose, with everything in it."),
|
||||
}
|
||||
}
|
||||
|
||||
/// The note the file dialog shows when the person picked more files than a script is given.
|
||||
const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out";
|
||||
|
||||
/// Gives the running script the file dialog's `answer`, or Deny.
|
||||
fn picker_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or("deny");
|
||||
give_pick(app, answer)
|
||||
}
|
||||
|
||||
/// Escape or Cancel: Deny.
|
||||
pub(super) fn picker_cancel(app: &mut VectorcraftApp, _: &Dialog) {
|
||||
let _ = give_pick(app, "deny");
|
||||
}
|
||||
|
||||
/// Gives the running script `answer` with the paths Choose… picked. Only the person at the keyboard
|
||||
/// allows access: Allow Once and Always Allow are refused, and the dialog stays open, while
|
||||
/// automation sends the answer (a control or MCP request, or synthetic input) or opened the host's
|
||||
/// file dialog; Deny and Stop are taken from anyone.
|
||||
fn give_pick(app: &mut VectorcraftApp, answer: &str) -> Result<Value, String> {
|
||||
let paths = app.script_picked.clone();
|
||||
let can_always = app.session.script_picker().is_some_and(|p| p.can_always);
|
||||
let given = match answer {
|
||||
"stop" => None,
|
||||
"deny" => Some(PickAnswer::Deny),
|
||||
"once" | "always" if app.automation_asked() => return Err("Only the person at the keyboard can allow a script's file access".into()),
|
||||
"once" | "always" if paths.is_empty() => return Err("choose a file or folder first, or deny".into()),
|
||||
"always" if !can_always => return Err("this script's file access can be allowed only once".into()),
|
||||
"once" => Some(PickAnswer::Allow { paths, always: false }),
|
||||
"always" => Some(PickAnswer::Allow { paths, always: true }),
|
||||
_ => return Err("`answer` for a script's file dialog must be one of: once, always, deny, stop".into()),
|
||||
};
|
||||
app.script_picked.clear();
|
||||
app.script_picked_left_out = false;
|
||||
match given {
|
||||
None => {
|
||||
app.session.script_request_stop();
|
||||
}
|
||||
Some(a) => {
|
||||
app.session.script_pick(a);
|
||||
}
|
||||
}
|
||||
if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PICKER_KIND) {
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn answers_for(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"confirm" => "yes, no, stop",
|
||||
|
||||
@@ -98,7 +98,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
|
||||
let lines: Vec<String> = 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"));
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -259,7 +259,7 @@ fn tile_brings_floating_documents_back_into_the_grid() {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let docs: Vec<usize> = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect();
|
||||
assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it");
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3}));
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"}));
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let docs: Vec<usize> = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect();
|
||||
assert_eq!(docs, [0, 1, 2]);
|
||||
@@ -844,7 +844,7 @@ fn arrange_treats_each_view_as_a_window() {
|
||||
assert!(!enabled(&app, "window.arrange.tile") && !enabled(&app, "window.arrange.cascade"), "one window");
|
||||
app.run("window.newWindow", json!({})).unwrap();
|
||||
assert!(enabled(&app, "window.arrange.tile") && enabled(&app, "window.arrange.cascade"), "two views of one document");
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2}));
|
||||
assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "grid"}));
|
||||
app.run("window.arrange.cascade", json!({})).unwrap();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let uid = app.session.documents()[0].uid;
|
||||
|
||||
@@ -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.
|
||||
|
||||
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user