mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/swatches-browser-selection-set
This commit is contained in:
commit
0848cfc2bb
48 files changed
+1488
-629
No files matched your search
@@ -33,37 +33,37 @@
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / cache warm (ubuntu-24.04)",
|
||||
"name": "gate / build (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 1/6 (ubuntu-24.04)",
|
||||
"name": "gate / lint (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 2/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 1/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 3/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 2/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 4/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 3/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 5/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 4/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 6/6 (ubuntu-24.04)",
|
||||
"name": "gate / test 5/5 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
|
||||
+27
-29
@@ -31,9 +31,9 @@ jobs:
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: 16bbfc3d451fad51971ca3f2a28c1e69e279b67c
|
||||
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
|
||||
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
|
||||
# those steps and the save it needs about two hours.
|
||||
# A cold build of every shard's tests (the nightly run, or any run after a toolchain or
|
||||
# lockfile change) took 90 minutes to reach its last three steps on 2026-11-27 and was
|
||||
# canceled there; with those steps and the save it needs about two hours.
|
||||
timeout-minutes: 150
|
||||
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
|
||||
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
|
||||
@@ -43,19 +43,24 @@ jobs:
|
||||
dev-strip: true
|
||||
# The workspace crates also build without line tables. A panic still names its file and line.
|
||||
dev-debug: "0"
|
||||
# Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run
|
||||
# half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6
|
||||
# runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)` passes only
|
||||
# when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and
|
||||
# saves the dependency cache.
|
||||
test-shards: 6
|
||||
# The `build (<os>)` job builds the tests once and writes one nextest archive per shard with
|
||||
# that shard's test binaries (`cargo xtask ci archive`), then runs the doctests. Five test
|
||||
# legs download their own archive and run it without building: shards 1 and 2 each run half
|
||||
# of vectorcraft-ui-egui's tests, and shards 3 to 5 the tests of their own crates
|
||||
# (xtask/src/shards.rs). The `lint (<os>)` leg runs the other `cargo xtask ci` steps beside
|
||||
# them, with a dependency cache of its own. `gate (<os>)` passes when the build and every
|
||||
# test leg that ran passed; `lint (<os>)` is a check of its own.
|
||||
test-shards: 5
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
archive-command: cargo xtask ci archive
|
||||
shard-archives: true
|
||||
after-archive-command: cargo xtask ci doctests
|
||||
lint-command: cargo xtask ci checks
|
||||
# A pull request runs only the test shards whose crates its changes reach: the crates that
|
||||
# own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every
|
||||
# crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the
|
||||
# shards left out and why; pushes to main, the nightly run and the `full-ci` label run all
|
||||
# six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does.
|
||||
# crate that depends on them. The `select legs` log lists the shards left out and why; pushes
|
||||
# to main, the nightly run and the `full-ci` label run all five. `shard-members` names each
|
||||
# shard's crates, as xtask/src/shards.rs › GROUPS does.
|
||||
select-tests: true
|
||||
shard-members: |
|
||||
vectorcraft-ui-egui
|
||||
@@ -63,14 +68,10 @@ jobs:
|
||||
vectorcraft-engine
|
||||
vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask
|
||||
(rest)
|
||||
(always)
|
||||
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
|
||||
# its shard builds), and `cache warm` puts their files into the one entry it saves.
|
||||
warm-split: true
|
||||
# The dependency cache also keeps the compiled workspace crates and their library and binary
|
||||
# test executables (not the integration tests' executables), so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
# test executables (not the integration tests' executables), so a pull request's build
|
||||
# rebuilds only the crates its changes reach. Each main run's `build` job saves a rolling
|
||||
# entry of its own, every build restores the newest one, and
|
||||
# cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores
|
||||
# nothing and builds everything from source.
|
||||
cache-workspace-crates: true
|
||||
@@ -83,15 +84,12 @@ jobs:
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
|
||||
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
|
||||
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
|
||||
# the script's start. A failed split leg fails this job too. The script then waits up to 160
|
||||
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
|
||||
# script's deadlines expire when split builds or runner waits take too long.
|
||||
# the old entries when the `build` job starts saving (scripts/ci-clear-rolling-cache.py). When
|
||||
# the job fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run build. The build starts after `gate / select legs`
|
||||
# and a free runner. The script allows 180 minutes from its start for the build to start, then
|
||||
# waits up to 160 minutes from the build's start. GitHub's 360-minute job limit can end this job
|
||||
# before the script's deadlines expire when runner waits take too long.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
|
||||
Generated
+1
@@ -8716,6 +8716,7 @@ dependencies = [
|
||||
name = "vectorcraft-cad"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"craft-dwg",
|
||||
"craft-dxf",
|
||||
"craft-image-codecs",
|
||||
|
||||
@@ -36,6 +36,9 @@ craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
# The DWG reader and writer craft-dwg uses, at the rev craft-libs pins (its Cargo.toml). Tests only: it writes the
|
||||
# R12, R13 and R14 DWG files that craft-dwg's writer, 2000 and later, does not.
|
||||
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
|
||||
@@ -29,3 +29,7 @@ serde_json = { workspace = true }
|
||||
# The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine)
|
||||
# and in fonts built in code (`vectorcraft_text::test_fonts`).
|
||||
vectorcraft-text = { workspace = true, features = ["bundled-fonts", "test-fonts"] }
|
||||
|
||||
# Writes the R12, R13 and R14 DWG files the import tests read. Left out where craft-dwg leaves it out.
|
||||
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
|
||||
acadrust = { workspace = true }
|
||||
+66
-4
@@ -1,9 +1,11 @@
|
||||
//! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result.
|
||||
//! Export writes a DWG the other way: the DXF writer's drawing, converted by `craft_dwg` ([`from_dxf`]).
|
||||
//!
|
||||
//! The conversion runs in a child process once the program has called [`use_own_worker`] (and
|
||||
//! Each conversion runs in a child process once the program has called [`use_own_worker`] (and
|
||||
//! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort
|
||||
//! ends that process, not VectorCraft. Without a worker the conversion is refused, unless
|
||||
//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there.
|
||||
//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read or written
|
||||
//! there.
|
||||
|
||||
use std::hash::BuildHasher;
|
||||
use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};
|
||||
@@ -11,7 +13,7 @@ use std::time::Duration;
|
||||
|
||||
use web_time::Instant;
|
||||
|
||||
pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker};
|
||||
pub use craft_dwg::{Unwritten, WORKER_ARG, allow_in_process, use_own_worker};
|
||||
|
||||
/// Whether this build decodes DWG drawings. Web builds and FreeBSD on 64-bit ARM have no DWG decoder.
|
||||
pub const DECODES: bool = !cfg!(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")));
|
||||
@@ -243,7 +245,48 @@ fn convert(bytes: &[u8]) -> Result<Converted, String> {
|
||||
Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() })
|
||||
}
|
||||
|
||||
/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one.
|
||||
/// Can a DWG file of `version` be written? craft-dwg writes 2000, 2004, 2007, 2010, 2013 and 2018.
|
||||
pub fn writes(version: crate::DxfVersion) -> bool {
|
||||
craft_dwg::VERSIONS.iter().any(|(code, _)| *code == version.acadver())
|
||||
}
|
||||
|
||||
/// A DWG file of `version` from `dxf`, an ASCII DXF of that version as [`crate::export_drawings`]
|
||||
/// writes it, and what the DWG writer left out: how many records of each DXF type. The conversion
|
||||
/// runs in the worker, as reading does.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When `version` is one a DWG can't be written as, or the conversion fails.
|
||||
pub fn from_dxf(dxf: &[u8], version: crate::DxfVersion) -> Result<(Vec<u8>, craft_dwg::Unwritten), String> {
|
||||
if !writes(version) {
|
||||
return Err(format!("DWG version `{}` can't be written: use {}", version.id(), written_versions()));
|
||||
}
|
||||
craft_dwg::encode_noted(dxf, version.acadver())
|
||||
}
|
||||
|
||||
/// The versions a DWG can be written as, as the `version` param names them ("2000, 2004 … or 2018").
|
||||
pub fn written_versions() -> String {
|
||||
let ids: Vec<&str> = crate::DxfVersion::ALL.iter().rev().filter(|v| writes(**v)).map(|v| v.id()).collect();
|
||||
match ids.split_last() {
|
||||
Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")),
|
||||
Some((last, _)) => (*last).to_string(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The warning for what the DWG writer left out of `files` files, by DXF type, else none.
|
||||
pub fn left_out_warning(left_out: &craft_dwg::Unwritten, files: usize) -> Option<String> {
|
||||
let total: usize = left_out.values().sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let kinds: Vec<String> = left_out.iter().map(|(kind, n)| format!("{kind} × {n}")).collect();
|
||||
let of = if files > 1 { format!("these {files} drawings") } else { "this drawing".to_string() };
|
||||
let records = if total == 1 { "record" } else { "records" };
|
||||
Some(format!("DWG: {total} {records} of {of} can't be written in this DWG version and were left out ({})", kinds.join(", ")))
|
||||
}
|
||||
|
||||
/// craft-dwg's message or note on reading a DWG, in VectorCraft's words.
|
||||
fn worded(message: &str) -> String {
|
||||
message
|
||||
.replace("accepted by this bridge", "VectorCraft opens")
|
||||
@@ -345,6 +388,25 @@ mod tests {
|
||||
assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_before_2000_is_refused_before_converting() {
|
||||
// No worker is configured here, so a conversion that ran would fail for that reason instead.
|
||||
let e = from_dxf(b" 0\nEOF\n", crate::DxfVersion::R14).unwrap_err();
|
||||
assert!(e.starts_with("DWG version `R14` can't be written: use 2000,") && e.ends_with("or 2018"), "{e}");
|
||||
assert!(writes(crate::DxfVersion::R2000) && !writes(crate::DxfVersion::R13) && !writes(crate::DxfVersion::R12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_the_dwg_writer_left_out_are_counted_by_type() {
|
||||
assert_eq!(left_out_warning(&craft_dwg::Unwritten::new(), 1), None);
|
||||
let one: craft_dwg::Unwritten = [("ACME_WIDGET".to_string(), 1)].into_iter().collect();
|
||||
let w = left_out_warning(&one, 1).unwrap();
|
||||
assert!(w.contains("1 record of this drawing") && w.contains("ACME_WIDGET × 1"), "{w}");
|
||||
let some: craft_dwg::Unwritten = [("ACME_WIDGET".to_string(), 2), ("ACME_OBJECT".to_string(), 1)].into_iter().collect();
|
||||
let w = left_out_warning(&some, 3).unwrap();
|
||||
assert!(w.contains("3 records of these 3 drawings") && w.contains("ACME_OBJECT × 1, ACME_WIDGET × 2"), "{w}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as() {
|
||||
let named = [
|
||||
|
||||
@@ -78,7 +78,8 @@ pub struct Imported {
|
||||
/// What a drawing holds, for the import options.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DxfInfo {
|
||||
/// The DXF version (`2018`, `R12`…; the `$ACADVER` code when it's none of the known ones).
|
||||
/// The drawing's version (`2018`, `R12`…; the `$ACADVER` code when it's none of the known ones). A DWG
|
||||
/// file's is the DWG's own, not that of the DXF it converts to.
|
||||
pub version: String,
|
||||
/// The drawing unit's name (`Millimeters`, `Unitless`…).
|
||||
pub units: String,
|
||||
@@ -194,7 +195,9 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
|
||||
}
|
||||
let h = &d.header;
|
||||
let (unit, scale) = default_ratio(h);
|
||||
let version = DxfVersion::ALL.into_iter().find(|v| v.acadver() == h.acadver).map_or_else(|| h.acadver.clone(), |v| v.id().to_string());
|
||||
// A DWG's own version: the DXF it converts to can be newer (an R12 DWG converts to an R13 DXF).
|
||||
let acadver = craft_dwg::version(bytes).unwrap_or_else(|| h.acadver.clone());
|
||||
let version = DxfVersion::ALL.into_iter().find(|v| v.acadver() == acadver).map_or(acadver, |v| v.id().to_string());
|
||||
Ok(DxfInfo {
|
||||
version,
|
||||
units: units_name(h.insunits).into(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF
|
||||
//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD
|
||||
//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer (2004 and 2018) or
|
||||
//! acadrust's (R12, R13 and R14), come in as the DXF does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD
|
||||
//! on aarch64.
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
@@ -12,6 +12,11 @@ use crate::{DxfOptions, DxfVersion};
|
||||
|
||||
/// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse.
|
||||
fn dxf() -> Vec<u8> {
|
||||
dxf_as(DxfVersion::R2000)
|
||||
}
|
||||
|
||||
/// [`dxf`] written as a DXF of `version`.
|
||||
fn dxf_as(version: DxfVersion) -> Vec<u8> {
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
let layer = d.add_layer(Some("Walls"));
|
||||
let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0);
|
||||
@@ -20,7 +25,7 @@ fn dxf() -> Vec<u8> {
|
||||
for n in [rect, oval] {
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() };
|
||||
let o = DxfOptions { version, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() };
|
||||
crate::export(&d, &o).unwrap().bytes
|
||||
}
|
||||
|
||||
@@ -55,19 +60,52 @@ fn art(doc: &Document) -> Vec<LayerArt> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `dxf` as an R12, R13 or R14 DWG file, the version the DXF declares, written by acadrust: the
|
||||
/// reader craft-dwg reads DWG with. craft-dwg's own writer starts at 2000.
|
||||
fn old_dwg(dxf: &[u8]) -> Vec<u8> {
|
||||
let doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(dxf.to_vec())).and_then(acadrust::DxfReader::read).unwrap();
|
||||
acadrust::DwgWriter::write_to_vec(&doc).unwrap()
|
||||
}
|
||||
|
||||
/// `dwg`, a DWG file of `version`, imports as the art `dxf` imports as, and its info names its
|
||||
/// version and layer.
|
||||
fn assert_comes_in_as(dxf: &[u8], dwg: &[u8], version: DxfVersion) {
|
||||
assert!(crate::is_dwg(dwg) && !crate::is_dwg(dxf));
|
||||
assert_eq!(craft_dwg::version(dwg).as_deref(), Some(version.acadver()));
|
||||
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
|
||||
let want = art(&import(dxf, &o).unwrap().document);
|
||||
assert_eq!(want.len(), 1, "{want:?}");
|
||||
// An R12 DXF writes layer names in capitals.
|
||||
assert!(want[0].0.as_deref().is_some_and(|n| n.eq_ignore_ascii_case("Walls")), "{want:?}");
|
||||
assert_eq!(want[0].1.len(), 2, "{want:?}");
|
||||
assert_eq!(art(&import(dwg, &o).unwrap().document), want, "{}", version.id());
|
||||
let i = info(dwg).unwrap();
|
||||
assert_eq!(i.version, version.id(), "{i:?}");
|
||||
assert!(i.layers.iter().any(|l| Some(l) == want[0].0.as_ref()), "{i:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_drawing_comes_in_as_its_dxf_does() {
|
||||
let (dxf, dwg) = (dxf(), dwg());
|
||||
assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf));
|
||||
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
|
||||
let want = art(&import(&dxf, &o).unwrap().document);
|
||||
assert_eq!(want.len(), 1, "{want:?}");
|
||||
assert_eq!(want[0].0.as_deref(), Some("Walls"));
|
||||
assert_eq!(want[0].1.len(), 2, "{want:?}");
|
||||
assert_eq!(art(&import(&dwg, &o).unwrap().document), want);
|
||||
assert_comes_in_as(&dxf, &dwg, DxfVersion::R2004);
|
||||
let i = info(&dwg).unwrap();
|
||||
assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model")));
|
||||
assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r12_r13_and_r14_dwg_drawings_come_in_as_their_dxf_does() {
|
||||
crate::dwg::allow_in_process();
|
||||
for version in [DxfVersion::R12, DxfVersion::R13, DxfVersion::R14] {
|
||||
let dxf = dxf_as(version);
|
||||
assert_comes_in_as(&dxf, &old_dwg(&dxf), version);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2018_dwg_drawing_comes_in_as_its_dxf_does() {
|
||||
crate::dwg::allow_in_process();
|
||||
let dxf = dxf_as(DxfVersion::R2018);
|
||||
assert_comes_in_as(&dxf, &craft_dwg::dxf_to_dwg_as(&dxf, "AC1032").unwrap(), DxfVersion::R2018);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+209
-8
@@ -6,8 +6,9 @@ use std::borrow::Cow;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use vectorcraft_geom::corners::{Corner, cut_corners, fitted_radii, path_corners};
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
use vectorcraft_geom::shapes::{self, CornerKind};
|
||||
use vectorcraft_geom::{Affine, PathData, Point, Rect};
|
||||
use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, SubPath};
|
||||
|
||||
use crate::node::{LiveShape, Node, NodeKind};
|
||||
use crate::selection::AnchorRef;
|
||||
@@ -198,6 +199,46 @@ impl<'a> LiveCorners<'a> {
|
||||
&self.sources
|
||||
}
|
||||
|
||||
/// Whether any corner has a radius stored, so the path as drawn has its corners cut (or
|
||||
/// cuts them again when an edit bends a straightened corner back).
|
||||
pub fn is_cut(&self) -> bool {
|
||||
self.radii.iter().any(|r| *r > 0.0)
|
||||
}
|
||||
|
||||
/// The anchors of `base` (subpath, anchor) that `anchors` of the path as drawn come from.
|
||||
pub fn outline_anchors(&self, anchors: &BTreeSet<AnchorRef>) -> BTreeSet<AnchorRef> {
|
||||
let ks: BTreeSet<usize> = anchors.iter().filter_map(|(si, ai)| self.sources.get(*si)?.get(*ai).copied()).collect();
|
||||
let mut out = BTreeSet::new();
|
||||
let mut first = 0;
|
||||
for (si, sp) in self.base.subpaths.iter().enumerate() {
|
||||
out.extend(ks.range(first..first + sp.anchors.len()).map(|k| (si, k - first)));
|
||||
first += sp.anchors.len();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The first anchor of the path as drawn that anchor `(si, ai)` of `base` gives.
|
||||
pub fn drawn_anchor(&self, (si, ai): AnchorRef) -> Option<AnchorRef> {
|
||||
let first: usize = self.base.subpaths.get(..si)?.iter().map(|sp| sp.anchors.len()).sum();
|
||||
let k = first + ai;
|
||||
self.sources.get(si)?.iter().position(|s| *s == k).map(|drawn| (si, drawn))
|
||||
}
|
||||
|
||||
/// [`LiveCorners::drawn_anchor`] of each of `anchors`, counting the subpaths' anchors once.
|
||||
pub fn drawn_anchors(&self, anchors: &BTreeSet<AnchorRef>) -> BTreeSet<AnchorRef> {
|
||||
let mut out = BTreeSet::new();
|
||||
let mut first = 0;
|
||||
for (si, sp) in self.base.subpaths.iter().enumerate() {
|
||||
let Some(sources) = self.sources.get(si) else { break };
|
||||
for &(_, ai) in anchors.range((si, 0)..(si + 1, 0)) {
|
||||
let k = first + ai;
|
||||
out.extend(sources.iter().position(|s| *s == k).map(|drawn| (si, drawn)));
|
||||
}
|
||||
first += sp.anchors.len();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The radius and kind `corners` share (each `None` when they differ, or for no corners).
|
||||
/// Radius is what was set ([`LiveCorners::radius`]: document lengths, or a fraction in 0..1
|
||||
/// when [`LiveCorners::radii_relative`]), not the fitted draw size ([`LiveCorners::drawn_radius`]).
|
||||
@@ -325,13 +366,8 @@ pub fn edit_corner_anchors(
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
edit: impl FnOnce(&mut PathData, &BTreeSet<AnchorRef>),
|
||||
) -> Option<()> {
|
||||
live.as_ref()?;
|
||||
if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let scale = (a * a + b * b).max(c * c + d * d).max(1e-12);
|
||||
if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale {
|
||||
return None;
|
||||
}
|
||||
if live.as_deref().is_none_or(uneven_rectangle) {
|
||||
return None;
|
||||
}
|
||||
let (mut base, moved, mut radii, kinds, relative) = {
|
||||
let lc = LiveCorners::new(path, live.as_deref())?;
|
||||
@@ -369,6 +405,156 @@ pub fn edit_corner_anchors(
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether `live` is a rectangle whose transform shears it or scales it unevenly.
|
||||
fn uneven_rectangle(live: &LiveShape) -> bool {
|
||||
let LiveShape::Rectangle { xf, .. } = live else { return false };
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let scale = (a * a + b * b).max(c * c + d * d).max(1e-12);
|
||||
((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale
|
||||
}
|
||||
|
||||
/// Change the anchors of the uncut outline of a path with cut Live Corners and cut the corners
|
||||
/// again. `edit` gets the outline in document space and returns, for each of its anchors after
|
||||
/// the change, the index of the anchor before the change it is (`None` for an anchor it added).
|
||||
/// Each corner keeps its radius and kind, and an added anchor has none; relative radii keep their
|
||||
/// document lengths. A live rectangle or polygon becomes a [`LiveShape::Path`] with that outline,
|
||||
/// and a path left with no radius and no corner kind other than round (or with no anchor) is a
|
||||
/// plain path. Returns `None`, leaving the path unchanged, as [`edit_corner_anchors`] does, or when
|
||||
/// `edit` returns `None` or does not list one entry per anchor.
|
||||
fn rebuild_corner_outline(
|
||||
path: &mut PathData,
|
||||
live: &mut Option<Box<LiveShape>>,
|
||||
edit: impl FnOnce(&mut PathData) -> Option<Vec<Option<usize>>>,
|
||||
) -> Option<()> {
|
||||
if live.as_deref().is_none_or(uneven_rectangle) {
|
||||
return None;
|
||||
}
|
||||
let (mut base, lengths, kinds, relative) = {
|
||||
let lc = LiveCorners::new(path, live.as_deref())?;
|
||||
if !lc.is_cut() {
|
||||
return None;
|
||||
}
|
||||
let base = lc.base.transformed(lc.xf);
|
||||
let mut radii = lc.radii.clone();
|
||||
radii.resize(base.anchor_count(), 0.0);
|
||||
let lengths = if lc.relative {
|
||||
let mut l = LiveShape::Path { base: base.clone(), radii, kinds: vec![], radii_relative: true };
|
||||
convert_radii_relative(&mut l, false);
|
||||
let LiveShape::Path { radii, .. } = l else { return None };
|
||||
radii
|
||||
} else {
|
||||
radii
|
||||
};
|
||||
(base, lengths, lc.kinds.clone(), lc.relative)
|
||||
};
|
||||
let from = edit(&mut base)?;
|
||||
if from.len() != base.anchor_count() {
|
||||
return None;
|
||||
}
|
||||
let radii: Vec<f64> = from.iter().map(|f| f.and_then(|i| lengths.get(i).copied()).unwrap_or(0.0)).collect();
|
||||
let kinds: Vec<CornerKind> = from.iter().map(|f| f.and_then(|i| kinds.get(i).copied()).unwrap_or_default()).collect();
|
||||
if radii.iter().all(|r| *r <= 0.0) && kinds.iter().all(|k| *k == CornerKind::Round) {
|
||||
*path = base;
|
||||
*live = None;
|
||||
return Some(());
|
||||
}
|
||||
let mut l = LiveShape::Path { base, radii, kinds, radii_relative: false };
|
||||
convert_radii_relative(&mut l, relative);
|
||||
*path = l.to_path();
|
||||
*live = Some(Box::new(l));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Add an anchor at `t` (0..1) on segment `seg` of subpath `si` of a path with cut Live Corners:
|
||||
/// it goes on the side of the uncut outline that the segment is part of, at the point of the
|
||||
/// segment at `t`, and the corners are cut again, keeping their radii and kinds
|
||||
/// ([`rebuild_corner_outline`]). Returns the new anchor's index in subpath `si` of the path as
|
||||
/// drawn, or `None`, leaving the path unchanged, for a segment that is a corner's cut, a segment
|
||||
/// that does not exist, or a path [`edit_corner_anchors`] leaves as it is.
|
||||
pub fn insert_corner_anchor(path: &mut PathData, live: &mut Option<Box<LiveShape>>, si: usize, seg: usize, t: f64) -> Option<usize> {
|
||||
let (target, first, local) = {
|
||||
let lc = LiveCorners::new(path, Some(live.as_deref()?))?;
|
||||
let sp = path.subpaths.get(si)?;
|
||||
let from = lc.sources.get(si)?;
|
||||
if seg >= sp.segment_count() || from.len() != sp.anchors.len() {
|
||||
return None;
|
||||
}
|
||||
let (ka, kb) = (*from.get(seg)?, *from.get((seg + 1) % from.len())?);
|
||||
// Both ends from one corner: the segment is that corner's cut.
|
||||
if ka == kb {
|
||||
return None;
|
||||
}
|
||||
let first: usize = lc.base.subpaths.get(..si)?.iter().map(|s| s.anchors.len()).sum();
|
||||
let outline = lc.base.subpaths.get(si)?;
|
||||
let local = ka.checked_sub(first).filter(|a| *a < outline.anchors.len())?;
|
||||
if !outline.has_segment(local, true) || kb != first + (local + 1) % outline.anchors.len() {
|
||||
return None;
|
||||
}
|
||||
(sp.segment(seg).eval(t.clamp(0.0, 1.0)), first, local)
|
||||
};
|
||||
let new_index = first + local + 1;
|
||||
let (mut p, mut l) = (path.clone(), live.clone());
|
||||
rebuild_corner_outline(&mut p, &mut l, |base| {
|
||||
let sp = base.subpaths.get_mut(si)?;
|
||||
// A straight side is a cubic with its handles on its ends too, so the parameter of the
|
||||
// point nearest `target` puts the new anchor there on either kind of side.
|
||||
let tb = sp.segment(local).nearest(target, 1e-9).t;
|
||||
sp.insert_anchor(local, tb.clamp(0.0, 1.0));
|
||||
Some((0..base.anchor_count()).map(|j| if j < new_index { Some(j) } else { (j > new_index).then(|| j - 1) }).collect())
|
||||
})?;
|
||||
let drawn = match LiveCorners::new(&p, l.as_deref()) {
|
||||
Some(lc) => lc.sources.get(si)?.iter().position(|k| *k == new_index)?,
|
||||
None => local + 1,
|
||||
};
|
||||
*path = p;
|
||||
*live = l;
|
||||
Some(drawn)
|
||||
}
|
||||
|
||||
/// Remove the anchors of the uncut outline that `anchors` (of the path as drawn) come from, so a
|
||||
/// cut corner goes when either of its anchors is removed, and cut the remaining corners again,
|
||||
/// keeping their radii and kinds ([`rebuild_corner_outline`]). `remove` takes the listed anchors
|
||||
/// (in ascending order) out of one subpath of the outline, refitting the curve round each; a
|
||||
/// subpath left with fewer than two anchors is removed, and a path left with none is an empty plain
|
||||
/// path. Returns `None`, leaving the path unchanged, when no anchor maps to the outline, when
|
||||
/// `remove` does not remove exactly the anchors listed, or for a path [`edit_corner_anchors`]
|
||||
/// leaves as it is.
|
||||
pub fn remove_corner_anchors(
|
||||
path: &mut PathData,
|
||||
live: &mut Option<Box<LiveShape>>,
|
||||
anchors: &BTreeSet<AnchorRef>,
|
||||
mut remove: impl FnMut(&mut SubPath, &[usize]),
|
||||
) -> Option<()> {
|
||||
let outline = LiveCorners::new(path, Some(live.as_deref()?))?.outline_anchors(anchors);
|
||||
if outline.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (mut p, mut l) = (path.clone(), live.clone());
|
||||
rebuild_corner_outline(&mut p, &mut l, |base| {
|
||||
let mut from = vec![];
|
||||
let mut first = 0;
|
||||
for (si, sp) in base.subpaths.iter_mut().enumerate() {
|
||||
let n = sp.anchors.len();
|
||||
let gone: Vec<usize> = outline.range((si, 0)..=(si, usize::MAX)).map(|&(_, ai)| ai).collect();
|
||||
if !gone.is_empty() {
|
||||
remove(sp, &gone);
|
||||
if sp.anchors.len() + gone.len() != n {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if sp.anchors.len() >= 2 {
|
||||
from.extend((0..n).filter(|ai| gone.binary_search(ai).is_err()).map(|ai| Some(first + ai)));
|
||||
}
|
||||
first += n;
|
||||
}
|
||||
base.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
Some(from)
|
||||
})?;
|
||||
*path = p;
|
||||
*live = l;
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -431,6 +617,21 @@ mod tests {
|
||||
assert_eq!((path, live), (star, None));
|
||||
}
|
||||
|
||||
/// Mapping a set of outline anchors gives the same anchors as drawn as mapping each one.
|
||||
#[test]
|
||||
fn drawn_anchors_match_drawn_anchor_across_subpaths() {
|
||||
let mut star = shapes::star(Point::new(100.0, 100.0), 50.0, 25.0, 5, 0.0);
|
||||
star.subpaths.extend(shapes::star(Point::new(300.0, 100.0), 50.0, 25.0, 4, 0.0).subpaths);
|
||||
let (mut path, mut live) = (star, None);
|
||||
set_corners(&mut path, &mut live, &set(&[0, 2, 10, 13]), Some(5.0), None);
|
||||
let c = LiveCorners::new(&path, live.as_deref()).unwrap();
|
||||
let refs: BTreeSet<AnchorRef> = (0..3).flat_map(|si| (0..12).map(move |ai| (si, ai))).collect();
|
||||
let one_by_one: BTreeSet<AnchorRef> = refs.iter().filter_map(|r| c.drawn_anchor(*r)).collect();
|
||||
assert_eq!(one_by_one.len(), 18, "ten and eight outline anchors");
|
||||
assert_eq!(c.drawn_anchors(&refs), one_by_one);
|
||||
assert_eq!(c.drawn_anchors(&BTreeSet::from([(1, 3)])), BTreeSet::from([(1, c.drawn_anchor((1, 3)).unwrap().1)]));
|
||||
}
|
||||
|
||||
/// A polygon's corners are cut in the document and survive a change of sides when shared.
|
||||
#[test]
|
||||
fn polygon_corners_follow_their_sides() {
|
||||
|
||||
@@ -103,7 +103,7 @@ pub use appearance::{
|
||||
};
|
||||
pub use assets::ExportAsset;
|
||||
pub use compound_shape::ShapeMode;
|
||||
pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii};
|
||||
pub use corners::{LiveCorners, edit_corner_anchors, insert_corner_anchor, rebase_relative_radii, remove_corner_anchors};
|
||||
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
|
||||
pub use graph::{
|
||||
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
|
||||
|
||||
@@ -31,7 +31,7 @@ mod freehand;
|
||||
mod quickpen;
|
||||
mod smooth;
|
||||
|
||||
pub(super) use anchors::{following_anchors, remove_anchors_of};
|
||||
pub(super) use anchors::remove_anchors_following;
|
||||
pub use commands::specs;
|
||||
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path};
|
||||
pub(super) use cut::{components, erase_outline};
|
||||
|
||||
@@ -129,7 +129,12 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.segments.remove(&id);
|
||||
return Ok(false);
|
||||
}
|
||||
let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let path = match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Path { path, .. }) => path,
|
||||
Some(_) => return Err(EngineError::Other(format!("object {id} is not a path"))),
|
||||
None => return Err(EngineError::NoNode(id)),
|
||||
};
|
||||
let sp = path.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if ai >= sp.anchors.len() {
|
||||
return Err(EngineError::Other("no such anchor".into()));
|
||||
}
|
||||
@@ -160,15 +165,14 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut gone = Vec::new();
|
||||
let mut emptied = Beside::replacing(d, &jobs.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
for (id, anchors) in jobs {
|
||||
let shape: Vec<(usize, bool)> =
|
||||
d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default();
|
||||
let next = following_anchors(&shape, &anchors);
|
||||
if remove_anchors_of(d, sel, &mut emptied, id, anchors, false)? {
|
||||
gone.push(id);
|
||||
} else if !next.is_empty() {
|
||||
match remove_anchors_following(d, sel, &mut emptied, id, anchors, false)? {
|
||||
None => gone.push(id),
|
||||
// The next anchor along is selected, so the next Remove Anchor Points goes on from
|
||||
// there without picking it first (#2241).
|
||||
sel.anchors.insert(id, next);
|
||||
Some(next) if !next.is_empty() => {
|
||||
sel.anchors.insert(id, next);
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
emptied.finish(d)?;
|
||||
@@ -225,12 +229,41 @@ pub(in crate::cmd) fn remove_anchors_of(
|
||||
sel: &mut Selection,
|
||||
emptied: &mut Beside,
|
||||
id: NodeId,
|
||||
mut anchors: Vec<(usize, usize)>,
|
||||
anchors: Vec<(usize, usize)>,
|
||||
curvature: bool,
|
||||
) -> Result<bool> {
|
||||
// The last first, so the indexes still to come stay valid.
|
||||
anchors.sort_unstable_by(|a, b| b.cmp(a));
|
||||
Ok(remove_anchors_following(d, sel, emptied, id, anchors, curvature)?.is_none())
|
||||
}
|
||||
|
||||
/// [`remove_anchors_of`], returning `None` when the path went, else the anchors that follow the
|
||||
/// removed ones in each subpath ([`following_anchors`]), numbered as the path is after the removal.
|
||||
/// A path with cut Live Corners keeps them ([`vectorcraft_doc::remove_corner_anchors`]): the anchors
|
||||
/// of its uncut outline that `anchors` come from are removed, so removing either anchor of a cut
|
||||
/// corner removes that corner, and the following anchors are those of the outline.
|
||||
pub(in crate::cmd) fn remove_anchors_following(
|
||||
d: &mut Document,
|
||||
sel: &mut Selection,
|
||||
emptied: &mut Beside,
|
||||
id: NodeId,
|
||||
mut anchors: Vec<(usize, usize)>,
|
||||
curvature: bool,
|
||||
) -> Result<Option<BTreeSet<(usize, usize)>>> {
|
||||
anchors.sort_unstable();
|
||||
anchors.dedup();
|
||||
if let Some(next) = remove_live_corner_anchors(d, id, &anchors, curvature) {
|
||||
if d.node(id).and_then(Node::path_data).is_none_or(PathData::is_empty) {
|
||||
emptied.put(d, id, vec![])?;
|
||||
return Ok(None);
|
||||
}
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
return Ok(Some(next));
|
||||
}
|
||||
let shape: Vec<(usize, bool)> =
|
||||
d.node(id).and_then(Node::path_data).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect()).unwrap_or_default();
|
||||
let next = following_anchors(&shape, &anchors);
|
||||
// The last first, so the indexes still to come stay valid.
|
||||
anchors.reverse();
|
||||
let path = path_mut(d, id)?;
|
||||
let mut rest = &anchors[..];
|
||||
while let Some(&(si, _)) = rest.first() {
|
||||
@@ -246,14 +279,41 @@ pub(in crate::cmd) fn remove_anchors_of(
|
||||
}
|
||||
}
|
||||
path.subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
let gone = path.is_empty();
|
||||
if gone {
|
||||
if path.is_empty() {
|
||||
emptied.put(d, id, vec![])?;
|
||||
} else {
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(gone)
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
Ok(Some(next))
|
||||
}
|
||||
|
||||
/// Remove `anchors` (ascending, no repeats) of path `id` when it has cut Live Corners, keeping
|
||||
/// them live ([`vectorcraft_doc::remove_corner_anchors`]), and return the anchors as drawn that
|
||||
/// follow the removed ones; `None`, changing nothing, when the corners can't stay live.
|
||||
fn remove_live_corner_anchors(d: &mut Document, id: NodeId, anchors: &[(usize, usize)], curvature: bool) -> Option<BTreeSet<(usize, usize)>> {
|
||||
let NodeKind::Path { path, live, .. } = &mut d.node_mut(id)?.kind else { return None };
|
||||
// A plain path has no corners to keep.
|
||||
live.as_ref()?;
|
||||
let set: BTreeSet<(usize, usize)> = anchors.iter().copied().collect();
|
||||
let lc = vectorcraft_doc::LiveCorners::new(path, live.as_deref())?;
|
||||
let shape: Vec<(usize, bool)> = lc.base.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect();
|
||||
let outline: Vec<(usize, usize)> = lc.outline_anchors(&set).into_iter().collect();
|
||||
drop(lc);
|
||||
vectorcraft_doc::remove_corner_anchors(path, live, &set, |sp, gone| {
|
||||
if curvature {
|
||||
for &ai in gone.iter().rev() {
|
||||
vectorcraft_tools::draw2::curvature_remove(sp, ai);
|
||||
}
|
||||
} else {
|
||||
po::remove_anchors(sp, gone);
|
||||
}
|
||||
})?;
|
||||
let next = following_anchors(&shape, &outline);
|
||||
Some(match vectorcraft_doc::LiveCorners::new(path, live.as_deref()) {
|
||||
Some(lc) => lc.drawn_anchors(&next),
|
||||
None => next,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least",
|
||||
"{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least; on a path with rounded Live Corners, the corner the anchor belongs to is removed and the other corners stay live",
|
||||
has_doc,
|
||||
remove_anchor
|
||||
),
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Anchor Points",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path → {removedObjects}",
|
||||
"{} remove the direct-selected anchors without opening their paths, refitting the curve round each; the anchor after each removed one is selected, so running it again goes on along the path; on a path with rounded Live Corners, the corners the anchors belong to are removed and the other corners stay live → {removedObjects}",
|
||||
has_anchors,
|
||||
remove_anchors
|
||||
),
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
//! per-format options (`file.formatOptions`); [`save_with`] is the one save path of every frontend.
|
||||
//! - `pdf`: PDF settings and presets for every PDF export, `document.exportPdf`.
|
||||
//! - `pdfimport`: the PDF pages, box and password `document.open` and Place read, `document.pdfInfo`.
|
||||
//! - `dxf`: DXF export options, `document.exportDxf`, and the formats that can't be written (DWG, PageMaker).
|
||||
//! - `dxf`: DXF and DWG export options, `document.exportDxf`, and the formats that can't be written (PageMaker).
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT and CGM open and place.
|
||||
|
||||
@@ -570,6 +570,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
| "tga"
|
||||
| "psd"
|
||||
| "dxf"
|
||||
| "dwg"
|
||||
| "emf"
|
||||
| "wmf"
|
||||
| "hpgl"
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! DXF export for every DXF path (`document.export {format: dxf}`, `document.exportDxf`, Export As
|
||||
//! → DXF Options): the options parsed from the params, one drawing per artboard with Use
|
||||
//! Artboards, and the formats that can't be written (DWG, which opens, and PageMaker) with what to
|
||||
//! use instead.
|
||||
//! DXF and DWG export for every path (`document.export {format: dxf|dwg}`, `document.exportDxf`,
|
||||
//! Export As → DXF Options and DWG Options): the options parsed from the params, one drawing per
|
||||
//! artboard with Use Artboards, and the formats that can't be written (PageMaker) with what to use
|
||||
//! instead. A DWG file is the DXF drawing converted by craft-dwg (`vectorcraft_cad::dwg::from_dxf`),
|
||||
//! from version 2000.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -22,14 +23,27 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export DXF",
|
||||
[],
|
||||
None,
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, groupBlocks?: false (Always Export Group as Block Reference: each group a block of its contents, nested groups blocks inside it, placed by an INSERT on the group's layer), selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
"{path?, format?: dxf (default)|dwg (a DWG file of the same drawing, version 2000 to 2018; records the DWG writer can't write in that version are left out with a warning), dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, groupBlocks?: false (Always Export Group as Block Reference: each group a block of its contents, nested groups blocks inside it, placed by an INSERT on the group's layer), selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf} (or dwg). A key DXF doesn't take is refused",
|
||||
has_doc,
|
||||
export_dxf
|
||||
)]
|
||||
}
|
||||
|
||||
/// The DXF options `document.formats` lists.
|
||||
pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
pub(crate) const OPTIONS: &[FormatOption] = &DXF_OPTIONS;
|
||||
|
||||
/// The DWG options `document.formats` lists: the DXF ones, with the versions a DWG is written as.
|
||||
pub(crate) const DWG_OPTIONS: &[FormatOption] = &{
|
||||
let mut o = DXF_OPTIONS;
|
||||
assert!(matches!(o[VERSION].name.as_bytes(), b"version"), "VERSION is the index of the version option");
|
||||
o[VERSION] = FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "2000, 2004, 2007, 2010, 2013 or 2018" };
|
||||
o
|
||||
};
|
||||
|
||||
/// Where the version option is in [`DXF_OPTIONS`].
|
||||
const VERSION: usize = 5;
|
||||
|
||||
const DXF_OPTIONS: [FormatOption; 18] = [
|
||||
super::ARTBOARD,
|
||||
super::ARTBOARDS,
|
||||
super::RANGE,
|
||||
@@ -119,16 +133,24 @@ pub fn unsupported(id_or_ext: &str) -> Option<&'static Unsupported> {
|
||||
UNSUPPORTED.iter().find(|u| u.id == k || u.extensions.contains(&k.as_str()))
|
||||
}
|
||||
|
||||
/// Formats VectorCraft opens but doesn't write (by id or extension), with what to export instead.
|
||||
/// Ids and extensions VectorCraft opens but doesn't write, with what to export instead: `.dws`
|
||||
/// drawing standards files and `.dwt` templates are DWG drawings, and only `.dwg` is written.
|
||||
const READ_ONLY_HINTS: &[(&[&str], &str)] =
|
||||
&[(&["dwg", "dws", "dwt"], "DWG files open but can't be written: export DXF instead, which CAD apps open")];
|
||||
&[(&["dws", "dwt"], ".dws and .dwt files open but can't be written: export DWG, or export DXF instead, which CAD apps open")];
|
||||
|
||||
/// The hint for an id or extension (any case, leading dot allowed) that names a read-only kind of
|
||||
/// file, even when its format is written under another extension (`.dws` is read as `dwg`).
|
||||
pub fn read_only_hint(id_or_ext: &str) -> Option<&'static str> {
|
||||
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
READ_ONLY_HINTS.iter().find(|(ids, _)| ids.contains(&k.as_str())).map(|(_, hint)| *hint)
|
||||
}
|
||||
|
||||
/// What to write instead of the format an id or extension (any case, leading dot allowed) names,
|
||||
/// when that format can't be written: an unsupported format's hint, or a read-only one's (DWG,
|
||||
/// also a `.dws` or `.dwt` file).
|
||||
/// when that format can't be written: an unsupported format's hint, or a read-only one's (a `.dws`
|
||||
/// or `.dwt` file).
|
||||
pub fn write_hint(id_or_ext: &str) -> Option<&'static str> {
|
||||
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
unsupported(&k).map(|u| u.hint).or_else(|| READ_ONLY_HINTS.iter().find(|(ids, _)| ids.contains(&k.as_str())).map(|(_, hint)| *hint))
|
||||
unsupported(&k).map(|u| u.hint).or_else(|| read_only_hint(&k))
|
||||
}
|
||||
|
||||
impl Unsupported {
|
||||
@@ -166,39 +188,42 @@ pub(crate) fn text(v: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `field` read by `read`, or an error listing what it may be.
|
||||
fn choice<T>(field: &str, v: Option<String>, read: impl Fn(&str) -> Option<T>, default: T, allowed: &str) -> Result<T> {
|
||||
/// `field` of a `kind` (DXF or DWG) export read by `read`, or an error listing what it may be.
|
||||
fn choice<T>(kind: &str, field: &str, v: Option<String>, read: impl Fn(&str) -> Option<T>, default: T, allowed: &str) -> Result<T> {
|
||||
match v {
|
||||
None => Ok(default),
|
||||
Some(s) => read(&s).ok_or_else(|| bad(C, format!("DXF {field} `{s}`: {allowed}"))),
|
||||
Some(s) => read(&s).ok_or_else(|| bad(C, format!("{kind} {field} `{s}`: {allowed}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice.
|
||||
fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("DXF options: {e}")))? } else { Params::default() };
|
||||
/// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice; with
|
||||
/// `dwg`, a version a DWG file is written as.
|
||||
fn parse(p: &Value, dwg: bool) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
let kind = if dwg { "DWG" } else { "DXF" };
|
||||
let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("{kind} options: {e}")))? } else { Params::default() };
|
||||
// The options a preset sets are the defaults of those `p` leaves out.
|
||||
let d = choice("dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options();
|
||||
let d = choice(kind, "dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options();
|
||||
let scale = q.scale.unwrap_or(d.scale);
|
||||
if !(scale.is_finite() && vectorcraft_cad::SCALE_RANGE.contains(&scale)) {
|
||||
return Err(bad(C, format!("DXF scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end())));
|
||||
return Err(bad(C, format!("{kind} scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end())));
|
||||
}
|
||||
let version = q.version.as_ref().map(text);
|
||||
let version = if dwg {
|
||||
let read = |s: &str| DxfVersion::from_id(s).filter(|v| vectorcraft_cad::dwg::writes(*v));
|
||||
choice(kind, "version", version, read, d.version, &vectorcraft_cad::dwg::written_versions())?
|
||||
} else {
|
||||
choice(kind, "version", version, DxfVersion::from_id, d.version, "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018")?
|
||||
};
|
||||
let opts = DxfOptions {
|
||||
version: choice(
|
||||
"version",
|
||||
q.version.as_ref().map(text),
|
||||
DxfVersion::from_id,
|
||||
d.version,
|
||||
"R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018",
|
||||
)?,
|
||||
unit: choice("unit", q.unit, Unit::named, d.unit, "a unit such as mm, cm, in or pt")?,
|
||||
version,
|
||||
unit: choice(kind, "unit", q.unit, Unit::named, d.unit, "a unit such as mm, cm, in or pt")?,
|
||||
scale,
|
||||
scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights),
|
||||
colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
|
||||
raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
|
||||
colors: choice(kind, "colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
|
||||
raster: choice(kind, "rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
|
||||
include_images: q.include_images.unwrap_or(d.include_images),
|
||||
include_hatches: q.include_hatches.unwrap_or(d.include_hatches),
|
||||
preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
|
||||
preserve: choice(kind, "preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
|
||||
alter_paths: q.alter_paths.unwrap_or(d.alter_paths),
|
||||
outline_text: q.outline_text.unwrap_or(d.outline_text),
|
||||
group_blocks: q.group_blocks.unwrap_or(d.group_blocks),
|
||||
@@ -207,21 +232,27 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
Ok((opts, q.boards))
|
||||
}
|
||||
|
||||
/// Check the DXF options in `p` without exporting (dialogs keep themselves open on an error).
|
||||
/// Is `p` a DWG export (`format: dwg`, or `.dwg` and the other names of the DWG format)?
|
||||
fn is_dwg(p: &Value) -> bool {
|
||||
p.get("format").and_then(Value::as_str).and_then(super::format).is_some_and(|f| f.id == "dwg")
|
||||
}
|
||||
|
||||
/// Check the DXF options in `p` without exporting (dialogs keep themselves open on an error);
|
||||
/// with `format: dwg`, as DWG options.
|
||||
pub fn check(p: &Value) -> std::result::Result<(), String> {
|
||||
parse(p).map(|_| ()).map_err(|e| e.to_string())
|
||||
parse(p, is_dwg(p)).map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The DXF options in `p` (the region and crop left at their defaults).
|
||||
pub fn options(p: &Value) -> std::result::Result<DxfOptions, String> {
|
||||
parse(p).map(|(o, _)| o).map_err(|e| e.to_string())
|
||||
parse(p, false).map(|(o, _)| o).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Encode `doc` as DXF: one drawing whose origin is the chosen artboard's bottom-left corner
|
||||
/// (default the first), or with `use_artboards` one drawing per chosen artboard (default all)
|
||||
/// holding the art over it.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let (opts, pick) = parse(p)?;
|
||||
/// Encode `doc` as DXF, or with `dwg` as DWG: one drawing whose origin is the chosen artboard's
|
||||
/// bottom-left corner (default the first), or with `use_artboards` one drawing per chosen artboard
|
||||
/// (default all) holding the art over it.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, dwg: bool) -> Result<Encoded> {
|
||||
let (opts, pick) = parse(p, dwg)?;
|
||||
let n = doc.artboards.len();
|
||||
let rect = |b: usize| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)));
|
||||
let drawings: Vec<(Option<usize>, Rect, bool)> = match use_artboards {
|
||||
@@ -234,7 +265,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
let b = match pick.resolve(n).map_err(|e| bad(C, e))?.as_deref() {
|
||||
None => 0,
|
||||
Some([b]) => *b,
|
||||
Some(_) => return Err(bad(C, "a DXF drawing has one origin: pass useArtboards: true for one drawing per artboard")),
|
||||
Some(_) => return Err(bad(C, "a DXF or DWG drawing has one origin: pass useArtboards: true for one drawing per artboard")),
|
||||
};
|
||||
vec![(Some(b), rect(b)?, false)]
|
||||
}
|
||||
@@ -242,9 +273,23 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect();
|
||||
let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
let mut left_out = vectorcraft_cad::dwg::Unwritten::new();
|
||||
for ((board, _, _), out) in drawings.into_iter().zip(outs) {
|
||||
enc.files.push((board, out.bytes));
|
||||
for w in out.warnings {
|
||||
let mut warnings = out.warnings;
|
||||
let bytes = if dwg {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
let (bytes, unwritten) = vectorcraft_cad::dwg::from_dxf(&out.bytes, opts.version).map_err(|e| bad(C, e))?;
|
||||
for (kind, n) in unwritten {
|
||||
*left_out.entry(kind).or_insert(0) += n;
|
||||
}
|
||||
// The DXF writer's version notes ("true colour needs DXF 2004 or later") hold for the DWG.
|
||||
warnings = warnings.into_iter().map(|w| w.replacen("needs DXF ", "needs DWG ", 1)).collect();
|
||||
bytes
|
||||
} else {
|
||||
out.bytes
|
||||
};
|
||||
enc.files.push((board, bytes));
|
||||
for w in warnings {
|
||||
if !enc.warnings.contains(&w) {
|
||||
enc.warnings.push(w);
|
||||
}
|
||||
@@ -259,11 +304,12 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
if enc.files.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
enc.warnings.extend(vectorcraft_cad::dwg::left_out_warning(&left_out, enc.files.len()));
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
fn export_dxf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut q = if p.is_object() { p.clone() } else { json!({}) };
|
||||
q["format"] = json!("dxf");
|
||||
q["format"] = json!(if is_dwg(p) { "dwg" } else { "dxf" });
|
||||
super::export::export(s, &q)
|
||||
}
|
||||
@@ -1135,7 +1135,8 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
let use_artboards =
|
||||
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -1175,7 +1176,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
"txt" => super::text::encode(doc, p)?,
|
||||
"svg" | "svgz" => return super::svg::encode(doc, p, f.id == "svgz").map_err(|e| bad(C, e)),
|
||||
"dxf" => return super::dxf::encode(doc, p, use_artboards),
|
||||
"dxf" | "dwg" => return super::dxf::encode(doc, p, use_artboards, f.id == "dwg"),
|
||||
// EPS reads its own `useArtboards` (the art's bounds unless asked).
|
||||
"eps" => return super::eps::encode(doc, p),
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
|
||||
@@ -586,8 +586,18 @@ pub const FORMATS: &[Format] = &[
|
||||
reader("pcraft", "PCRAFT", &["pcraft"], "application/x-pcraft", true),
|
||||
// DWG drawings, converted to DXF by craft-dwg (`vectorcraft_cad::dwg`) and read by the DXF
|
||||
// reader with the DXF import options; `.dws` drawing standards files are DWG drawings too.
|
||||
// Exports don't write them.
|
||||
reader("dwg", "DWG", &["dwg", "dws"], "image/vnd.dwg", false),
|
||||
// Exports write the DXF writer's drawing, converted by craft-dwg, as versions 2000 to 2018,
|
||||
// to `.dwg` only: exporting to `dws` answers with the read-only hint.
|
||||
Format {
|
||||
id: "dwg",
|
||||
label: "DWG",
|
||||
extensions: &["dwg", "dws"],
|
||||
mime: "image/vnd.dwg",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: dxf::DWG_OPTIONS,
|
||||
},
|
||||
// `.dwt` drawing templates, DWG drawings read as `dwg` is; a template opens as a new untitled
|
||||
// document. Exports don't write them.
|
||||
reader("dwt", "DWG Template", &["dwt"], "image/vnd.dwg", false),
|
||||
@@ -1180,6 +1190,12 @@ pub fn format_for_name(name: &str) -> Option<&'static Format> {
|
||||
pub fn writable_format(format_param: Option<&str>, path: Option<&str>) -> std::result::Result<&'static Format, String> {
|
||||
// Formats that can't be written say what to use instead.
|
||||
let unknown = |what: String, key: &str| unsupported(key).map_or(what, |u| u.hint.to_string());
|
||||
// A read-only kind of file read under a written format's id (`.dws` is read as `dwg`), named by
|
||||
// the format or by the path the file would be written to.
|
||||
let path_ext = path.map(extension).filter(|e| !e.is_empty());
|
||||
if let Some(hint) = format_param.into_iter().chain(path_ext.as_deref()).find_map(super::dxf::read_only_hint) {
|
||||
return Err(hint.to_string());
|
||||
}
|
||||
let f = match (format_param, path.map(extension).filter(|e| !e.is_empty())) {
|
||||
(Some(f), _) => format(f).ok_or_else(|| unknown(format!("unknown format `{f}` (see document.formats)"), f))?,
|
||||
(None, Some(e)) => format(&e).ok_or_else(|| unknown(format!("unknown extension `.{e}`: pass `format` (see document.formats)"), &e))?,
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 8] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
|
||||
@@ -533,7 +533,8 @@ fn export_extensions_name_every_writable_format() {
|
||||
"plt",
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx"
|
||||
"cmx",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
for e in exts {
|
||||
@@ -570,7 +571,8 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"hpgl",
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx"
|
||||
"cmx",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
@@ -657,7 +659,7 @@ fn export_without_path_returns_bytes_and_never_retargets() {
|
||||
let r = s.execute("document.export", &json!({"format": "jpg"})).unwrap();
|
||||
assert_eq!(&b64(&r)[..2], [0xFF, 0xD8]);
|
||||
assert!(r.get("path").is_none());
|
||||
assert!(s.execute("document.export", &json!({"path": dir.join("x.dwg").to_string_lossy()})).is_err(), "DWG can't be written");
|
||||
assert!(s.execute("document.export", &json!({"path": dir.join("x.pmd").to_string_lossy()})).is_err(), "PageMaker can't be written");
|
||||
// A never-saved document hands its native bytes back.
|
||||
let mut s = session(10.0, 10.0, 1);
|
||||
let r = s.execute("document.save", &json!({})).unwrap();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! DWG through the commands: `document.open`, `document.dxfInfo` and File → Place read a DWG
|
||||
//! drawing as the DXF it converts to, with the DXF options; DWG is in the format table as read
|
||||
//! only, and exporting one says to write DXF. craft-dwg reads and writes DWG everywhere but wasm32
|
||||
//! and FreeBSD on aarch64.
|
||||
//! drawing as the DXF it converts to, with the DXF options; `document.export` writes the DXF
|
||||
//! writer's drawing as a DWG of version 2000 or later. craft-dwg reads and writes DWG everywhere but
|
||||
//! wasm32 and FreeBSD on aarch64.
|
||||
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -102,12 +102,73 @@ fn a_dwg_opened_is_never_written_back_as_dwg() {
|
||||
s.execute("document.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let e = s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("not DWG"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": "dwg"})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), dwg, "the drawing is unchanged");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The bytes of the one file `document.export` handed back.
|
||||
fn exported(r: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "plan.dxf", &plan(), json!({})).unwrap();
|
||||
let dxf = exported(&s.execute("document.export", &json!({"format": "dxf", "version": "2000"})).unwrap());
|
||||
let r = s.execute("document.export", &json!({"format": "dwg", "version": "2000"})).unwrap();
|
||||
let dwg = exported(&r);
|
||||
assert_eq!(craft_dwg::version(&dwg).as_deref(), Some("AC1015"));
|
||||
assert!(r["warnings"].as_array().is_none_or(|w| w.iter().all(|w| !w.as_str().unwrap_or("").starts_with("DWG:"))), "{r}");
|
||||
open(&mut s, "again.dxf", &dxf, json!({})).unwrap();
|
||||
let (want_layers, want_leaves) = (layer_names(&s), leaves(&s).len());
|
||||
open(&mut s, "again.dwg", &dwg, json!({})).unwrap();
|
||||
assert_eq!(layer_names(&s), want_layers);
|
||||
assert_eq!(leaves(&s).len(), want_leaves);
|
||||
// The default version is 2018, and `.dwg` in the path picks the format.
|
||||
let dir = std::env::temp_dir().join(format!("vc-dwg-export-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("out.dwg");
|
||||
let r = s.execute("document.export", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["format"], "dwg");
|
||||
assert_eq!(craft_dwg::version(&std::fs::read(&path).unwrap()).as_deref(), Some("AC1032"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A canceled export stops before converting any drawing to DWG.
|
||||
#[test]
|
||||
fn a_canceled_dwg_export_converts_no_drawing() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let token = crate::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let r = crate::cancel::scope(&token, None, || super::dxf::encode(doc, &json!({}), Some(true), true));
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{:?}", r.map(|e| e.files.len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dwg_version_before_2000_is_refused_and_nothing_is_written() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let mut s = Session::new();
|
||||
open(&mut s, "plan.dxf", &plan(), json!({})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("vc-dwg-r14-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("old.dwg");
|
||||
for version in ["R12", "R13", "R14"] {
|
||||
let e = s.execute("document.export", &json!({"path": path.to_string_lossy(), "version": version})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("DWG version `{version}`")) && e.contains("2000") && e.contains("2018"), "{e}");
|
||||
}
|
||||
assert!(!path.exists());
|
||||
// The same versions are DXF versions.
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "version": "R14"})).unwrap();
|
||||
assert!(String::from_utf8_lossy(&exported(&r)).contains("AC1014"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxf_info_and_place_read_a_dwg() {
|
||||
let mut s = Session::new();
|
||||
@@ -129,15 +190,17 @@ fn dxf_info_and_place_read_a_dwg() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dwg_is_read_only_and_detected_by_content() {
|
||||
fn dwg_is_read_and_written_and_detected_by_content() {
|
||||
let f = format("dwg").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(f.read && f.write);
|
||||
let version = f.options.iter().find(|o| o.name == "version").unwrap();
|
||||
assert!(!version.description.contains("R14") && version.description.contains("2000"), "{}", version.description);
|
||||
assert!(OPEN_EXTS.contains(&"dwg") && PLACE_EXTS.contains(&"dwg") && UNASSOCIATED_EXTS.contains(&"dwg"));
|
||||
assert_eq!(detect("drawing.bin", &plan_dwg()).map(|f| f.id), Some("dwg"), "the content tells");
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.formats", &json!({})).unwrap();
|
||||
assert!(r["readable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(!r["writable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(r["writable"].as_array().unwrap().contains(&json!("dwg")));
|
||||
assert!(r["unsupported"].as_array().unwrap().iter().all(|u| u["id"] != "dwg"));
|
||||
}
|
||||
|
||||
@@ -204,5 +267,9 @@ fn dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf() {
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let e = s.execute("document.export", &json!({"format": ext})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "{ext}: {e}");
|
||||
let path = std::env::temp_dir().join(format!("vc-dwg-alias-{}.{ext}", std::process::id()));
|
||||
let e = s.execute("document.export", &json!({"format": "dwg", "path": path.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(e.contains("export DXF instead"), "format dwg to a .{ext} path: {e}");
|
||||
assert!(!path.exists(), "nothing is written to {}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! DXF export through the commands: options, artboards, selection, images, and the formats that
|
||||
//! can't be written (DWG, which opens, and PageMaker).
|
||||
//! can't be written (PICT, which opens, and PageMaker).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -320,12 +320,8 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dwg_and_pagemaker_say_what_to_use_instead() {
|
||||
fn pict_and_pagemaker_say_what_to_use_instead() {
|
||||
let mut s = two_boards();
|
||||
for p in [json!({"format": "dwg"}), json!({"path": "/tmp/plan.DWG"})] {
|
||||
let e = s.execute("document.export", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("DWG files open but can't be written") && e.contains("export DXF instead"), "{p}: {e}");
|
||||
}
|
||||
// PICT opens; it isn't written.
|
||||
let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PICT files can be opened but not written"), "{e}");
|
||||
|
||||
+151
-27
@@ -1,6 +1,6 @@
|
||||
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -149,7 +149,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection)",
|
||||
"{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection); on a path with rounded Live Corners, an anchor added on a side keeps the corners live (the selection follows its corners), and one added on a corner's arc makes the path plain and answers with a warning",
|
||||
has_doc,
|
||||
insert_anchor
|
||||
),
|
||||
@@ -2158,18 +2158,9 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
|
||||
if d.node(*id).is_none() {
|
||||
continue;
|
||||
}
|
||||
if keep_joined
|
||||
&& !set.is_empty()
|
||||
&& !segments.contains_key(id)
|
||||
&& let Some(path) = d.node(*id).and_then(|n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
{
|
||||
let shape: Vec<(usize, bool)> = path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect();
|
||||
if keep_joined && !set.is_empty() && !segments.contains_key(id) && d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })) {
|
||||
let anchors: Vec<(usize, usize)> = set.iter().copied().collect();
|
||||
let next = super::draw2::following_anchors(&shape, &anchors);
|
||||
if !super::draw2::remove_anchors_of(d, selection, &mut emptied, *id, anchors, false)? {
|
||||
if let Some(next) = super::draw2::remove_anchors_following(d, selection, &mut emptied, *id, anchors, false)? {
|
||||
survivors.push(*id);
|
||||
following.push((*id, next));
|
||||
}
|
||||
@@ -2470,6 +2461,87 @@ fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f
|
||||
/// the same points.
|
||||
/// A selected segment that the new anchor splits stays selected as its two halves, and the new
|
||||
/// anchor joins its ends in the anchors that move with it.
|
||||
/// After anchor `new` of the uncut outline of path `id` was added on its segment `split` as drawn,
|
||||
/// and the path's corners were cut again, select the segments as drawn that run between the same
|
||||
/// anchors of the outline as `segments` (the path's selected segments before), each listed in
|
||||
/// `before` and `after` as [`corner_sources`] gives them, `before` numbered as the outline is after
|
||||
/// the addition. A selected `split` gives both its halves, and the new anchor is selected with
|
||||
/// them, as [`renumber_after_insert`] selects them on a plain path. A segment whose two ends were
|
||||
/// in `held` (the selected anchors that end a selected segment, as drawn before) has the ends of
|
||||
/// its segments as drawn selected, and no other anchor of their corners.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn remap_corner_segments(
|
||||
sel: &mut Selection,
|
||||
id: NodeId,
|
||||
segments: &BTreeSet<SegmentRef>,
|
||||
held: &BTreeSet<AnchorRef>,
|
||||
before: &[Vec<usize>],
|
||||
after: &[Vec<usize>],
|
||||
split: SegmentRef,
|
||||
new: usize,
|
||||
) {
|
||||
let ends = |sources: &[Vec<usize>], (si, g): SegmentRef| {
|
||||
let v = sources.get(si)?;
|
||||
Some((*v.get(g)?, *v.get((g + 1) % v.len())?))
|
||||
};
|
||||
// Each subpath's segments as drawn by the corners at their ends, the first one for each pair.
|
||||
let index: Vec<HashMap<(usize, usize), usize>> = after
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(si, v)| {
|
||||
let mut m = HashMap::new();
|
||||
for g in 0..v.len() {
|
||||
if let Some(pair) = ends(after, (si, g)) {
|
||||
m.entry(pair).or_insert(g);
|
||||
}
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
let drawn = |si: usize, pair: (usize, usize)| index.get(si).and_then(|m| m.get(&pair)).map(|&g| (si, g));
|
||||
let mut out = BTreeSet::new();
|
||||
let mut picked = BTreeSet::new();
|
||||
for &r in segments {
|
||||
let Some((a, b)) = ends(before, r) else { continue };
|
||||
let found: Vec<SegmentRef> = if r == split {
|
||||
[drawn(r.0, (a, new)), drawn(r.0, (new, b))].into_iter().flatten().collect()
|
||||
} else {
|
||||
drawn(r.0, (a, b)).into_iter().collect()
|
||||
};
|
||||
let len = before.get(r.0).map_or(0, Vec::len);
|
||||
if len > 0 && held.contains(&r) && held.contains(&(r.0, (r.1 + 1) % len)) {
|
||||
let n = after.get(r.0).map_or(0, Vec::len);
|
||||
picked.extend(found.iter().flat_map(|&(si, g)| [(si, g), (si, (g + 1) % n.max(1))]));
|
||||
}
|
||||
if r == split
|
||||
&& let Some(ai) = after.get(r.0).and_then(|v| v.iter().position(|k| *k == new))
|
||||
{
|
||||
picked.insert((r.0, ai));
|
||||
}
|
||||
out.extend(found);
|
||||
}
|
||||
if !picked.is_empty() {
|
||||
sel.anchors.entry(id).or_default().extend(picked);
|
||||
}
|
||||
if sel.anchors.get(&id).is_some_and(BTreeSet::is_empty) {
|
||||
sel.anchors.remove(&id);
|
||||
}
|
||||
if !out.is_empty() {
|
||||
sel.segments.insert(id, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors as drawn that end the segments in `segments`, on subpaths of the lengths `sources`
|
||||
/// lists ([`corner_sources`]).
|
||||
fn segment_ends(segments: &BTreeSet<SegmentRef>, sources: &[Vec<usize>]) -> BTreeSet<AnchorRef> {
|
||||
let mut out = BTreeSet::new();
|
||||
for &(si, g) in segments {
|
||||
let Some(n) = sources.get(si).map(Vec::len).filter(|n| *n > 0 && g < *n) else { continue };
|
||||
out.extend([(si, g), (si, (g + 1) % n)]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usize) {
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
// A selected anchor index can name no anchor (`select.anchors` takes any index), so the
|
||||
@@ -2628,17 +2700,17 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let seg = index_opt(p, "segment", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing segment"))?;
|
||||
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
|
||||
let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?;
|
||||
let idx = s.edit("Add Anchor Point", |d, sel| {
|
||||
let idx = super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(sp.insert_anchor(seg, t))
|
||||
})?;
|
||||
// Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor`
|
||||
// leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only.
|
||||
let (idx, expanded) = s.edit("Add Anchor Point", |d, sel| {
|
||||
if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) {
|
||||
let idx = super::draw2::with_anchor_path(d, id, |path| {
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
Ok(sp.insert_anchor(seg, t))
|
||||
})?;
|
||||
// Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor`
|
||||
// leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only.
|
||||
if select_anchor || !sel.contains(id) {
|
||||
sel.clear();
|
||||
}
|
||||
@@ -2648,9 +2720,53 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.key_anchor = None;
|
||||
}
|
||||
sel.add(id);
|
||||
return Ok(idx);
|
||||
return Ok((idx, false));
|
||||
}
|
||||
renumber_after_insert(sel, id, si, idx);
|
||||
let (path, live) = match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Path { path, live, .. }) => (path, live),
|
||||
Some(_) => return Err(EngineError::Other(format!("object {id} is not a path"))),
|
||||
None => return Err(EngineError::NoNode(id)),
|
||||
};
|
||||
if seg >= path.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?.segment_count() {
|
||||
return Err(EngineError::Other("no such segment".into()));
|
||||
}
|
||||
// A plain path has no corners to keep, so it skips the Live Corners work.
|
||||
let (before, cut) = match live.as_deref().and_then(|l| vectorcraft_doc::LiveCorners::new(path, Some(l))) {
|
||||
Some(lc) => (Some(lc.sources().to_vec()), lc.is_cut()),
|
||||
None => (None, false),
|
||||
};
|
||||
let kept = match (&before, d.node_mut(id).map(|n| &mut n.kind)) {
|
||||
(Some(_), Some(NodeKind::Path { path, live, .. })) => vectorcraft_doc::insert_corner_anchor(path, live, si, seg, t),
|
||||
_ => None,
|
||||
};
|
||||
let after = if kept.is_some() { corner_sources(d, id) } else { None };
|
||||
let idx = match (kept, before, after) {
|
||||
// The corners stay live: the selection follows the corners its anchors come from, the
|
||||
// outline's anchors after the new one numbered one higher.
|
||||
(Some(idx), Some(before), Some(after)) => {
|
||||
let new = after.get(si).and_then(|v| v.get(idx)).copied().unwrap_or(usize::MAX);
|
||||
let before: Vec<Vec<usize>> = before.iter().map(|v| v.iter().map(|k| if *k >= new { k + 1 } else { *k }).collect()).collect();
|
||||
let segments = sel.segments.get(&id).cloned().unwrap_or_default();
|
||||
// The ends of selected segments follow the segments, not their whole corners.
|
||||
let ends = segment_ends(&segments, &before);
|
||||
let mut held = BTreeSet::new();
|
||||
if let Some(set) = sel.anchors.get_mut(&id) {
|
||||
held = set.intersection(&ends).copied().collect();
|
||||
set.retain(|r| !ends.contains(r));
|
||||
}
|
||||
remap_corner_anchors(sel, id, &before, &after);
|
||||
remap_corner_segments(sel, id, &segments, &held, &before, &after, (si, seg), new);
|
||||
idx
|
||||
}
|
||||
_ => {
|
||||
let path = path_mut(d, id)?;
|
||||
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
|
||||
let idx = sp.insert_anchor(seg, t);
|
||||
renumber_after_insert(sel, id, si, idx);
|
||||
idx
|
||||
}
|
||||
};
|
||||
let expanded = cut && kept.is_none();
|
||||
// A path that wasn't selected becomes the selection, its new anchor direct-selected, so
|
||||
// the point added shows and can be edited at once (#4237). `selectAnchor` does the same
|
||||
// for a path that is selected.
|
||||
@@ -2659,11 +2775,19 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
sel.add(id);
|
||||
sel.anchors.entry(id).or_default().insert((si, idx));
|
||||
}
|
||||
Ok(idx)
|
||||
Ok((idx, expanded))
|
||||
})?;
|
||||
Ok(json!({ "anchor": idx }))
|
||||
let mut out = json!({ "anchor": idx });
|
||||
if expanded {
|
||||
out["warning"] = json!(CORNERS_EXPANDED);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The status when adding an anchor point turned a path's Live Corners into plain anchor points.
|
||||
/// Anchors added on a straight or curved side keep them; one added on a corner's curve does not.
|
||||
const CORNERS_EXPANDED: &str = "Live Corners were expanded: the rounded corners are now plain anchor points";
|
||||
|
||||
fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const C: &str = "path.cutAtAnchors";
|
||||
let st = s.doc()?;
|
||||
|
||||
@@ -31,9 +31,10 @@
|
||||
//! when the name ends with `.svgz`.
|
||||
//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it,
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF
|
||||
//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not
|
||||
//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DWG
|
||||
//! (`.dwg`) with `AutoCADExportFileFormat.DWG`, the default, and DXF (`.dxf`) with
|
||||
//! `AutoCADExportFileFormat.DXF`. A DWG is written as version 2000 or later: `AutoCADRelease13`
|
||||
//! and `AutoCADRelease14` with DWG throw an error that names `AutoCADRelease15`. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
|
||||
//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to
|
||||
//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is
|
||||
//! one drawing unit. It is at least 0.0001 and at most 1000.
|
||||
@@ -720,11 +721,7 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result:
|
||||
p.insert("outlineText".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"exportFileFormat" => {
|
||||
if pick("AutoCADExportFileFormat")? == "DWG" {
|
||||
return Err(HostError::Error(
|
||||
"AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(),
|
||||
));
|
||||
}
|
||||
p.insert("_dwg".into(), json!(pick("AutoCADExportFileFormat")? == "DWG"));
|
||||
}
|
||||
"exportOption" => {
|
||||
let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" };
|
||||
@@ -1041,9 +1038,17 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
|
||||
},
|
||||
};
|
||||
// A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed
|
||||
// colors, and `AutoCADColors.TrueColors` with it throws.
|
||||
if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) {
|
||||
// `AutoCADExportFileFormat.DWG` writes the same drawing as a DWG file.
|
||||
let kind = match p.remove("_dwg") {
|
||||
Some(Value::Bool(true)) => ExportKind { format: "dwg", extensions: &["dwg"], options: kind.options },
|
||||
_ => kind,
|
||||
};
|
||||
if kind.format == "dwg" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14")) {
|
||||
return Err(HostError::Error("AutoCADExportFileFormat.DWG needs AutoCADRelease15 or a later version".into()));
|
||||
}
|
||||
// A DXF or DWG version before 2004 holds no true color: with `colors` left out it takes 256
|
||||
// indexed colors, and `AutoCADColors.TrueColors` with it throws.
|
||||
if matches!(kind.format, "dxf" | "dwg") && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) {
|
||||
match p.get("colors") {
|
||||
None => {
|
||||
p.insert("colors".into(), json!(256));
|
||||
@@ -1063,8 +1068,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into()));
|
||||
}
|
||||
// A raster file has one pixel per point at 100%, whatever the document's raster effects resolution.
|
||||
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100.
|
||||
if !matches!(kind.format, "svg" | "dxf") {
|
||||
// A DXF's or DWG's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100.
|
||||
if !matches!(kind.format, "svg" | "dxf" | "dwg") {
|
||||
p.insert("scale".into(), json!(hs / 100.0));
|
||||
}
|
||||
let format = if svgz { "svgz" } else { kind.format };
|
||||
|
||||
@@ -1004,9 +1004,10 @@ fn take_changed_paints(
|
||||
}
|
||||
|
||||
/// Whether command `id` acts on the drawing as a dialog's preview shows it (a copy, a save, a
|
||||
/// revert), so it runs inside that preview rather than as a step of its own.
|
||||
/// revert), so it runs inside that preview rather than as a step of its own. Place adds art, so
|
||||
/// it runs on the document without the preview, as other edits do.
|
||||
fn reads_preview(id: &str) -> bool {
|
||||
id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode")
|
||||
id == "edit.copy" || (id.starts_with("file.") && id != "file.documentColorMode" && id != "file.place")
|
||||
}
|
||||
|
||||
/// The selection on show in a dialog's preview `shown`, as a command from outside the dialog acts
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::collections::BTreeSet;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{AnchorRef, LiveCorners, LiveShape, NodeKind};
|
||||
use vectorcraft_geom::shapes::CornerKind;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
use vectorcraft_geom::{Affine, ParamCurve, Point};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -1582,3 +1582,174 @@ fn a_nudge_the_pixel_grid_takes_back_with_an_object_selected_whole_records_no_un
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().live_shape(), Some(LiveShape::Rectangle { .. })));
|
||||
assert_eq!(s.doc().unwrap().doc, doc);
|
||||
}
|
||||
|
||||
/// The segment of path `id` as drawn that runs from a cut of corner `a` of its uncut outline to
|
||||
/// a cut of corner `b` (the same corner twice: that corner's curve).
|
||||
fn segment_between(s: &Session, id: NodeId, a: usize, b: usize) -> usize {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
let from = &lc.sources()[0];
|
||||
(0..from.len()).find(|&i| from[i] == a && from[(i + 1) % from.len()] == b).unwrap_or_else(|| panic!("no segment {a} -> {b} in {from:?}"))
|
||||
}
|
||||
|
||||
/// The anchors of path `id` as drawn that come from `corners` of its uncut outline.
|
||||
fn corner_anchors(s: &Session, id: NodeId, corners: &[usize]) -> BTreeSet<AnchorRef> {
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
lc.anchors_of(&corners.iter().copied().collect())
|
||||
}
|
||||
|
||||
/// Adding an anchor point on a side of a rounded rectangle puts it on that side and keeps every
|
||||
/// corner live at its radius, in one undo step, with the direct-selected anchors still on their
|
||||
/// corner. Delete Anchor Point on it leaves the rectangle's outline with its corners still live.
|
||||
#[test]
|
||||
fn adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let before = node_path(&s, id).0;
|
||||
let picked: Vec<[usize; 2]> = corner_anchors(&s, id, &[2]).into_iter().map(|(si, ai)| [si, ai]).collect();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
let seg = segment_between(&s, id, 0, 1);
|
||||
let want = before.subpaths[0].segment(seg).eval(0.3);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.3})).unwrap();
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
let ai = usize::try_from(r["anchor"].as_u64().unwrap()).unwrap();
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert!(matches!(live, Some(LiveShape::Path { .. })), "{live:?}");
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
assert_eq!(path.anchor_count(), 9);
|
||||
assert!(path.subpaths[0].anchors[ai].p.distance(want) < 1e-9, "{:?} vs {want:?}", path.subpaths[0].anchors[ai].p);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
// The new anchor is the outline's anchor 1, so the corner that was 2 is 3 now.
|
||||
assert_eq!(selected_anchors(&s, id), Some(corner_anchors(&s, id, &[3])));
|
||||
|
||||
let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": ai})).unwrap();
|
||||
assert_eq!(r["removedObject"], false);
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 4]));
|
||||
let after = node_path(&s, id).0;
|
||||
assert_eq!(after.anchor_count(), 8);
|
||||
for (_, _, a) in before.anchors() {
|
||||
assert!(after.anchors().any(|(_, _, b)| b.p.distance(a.p) < 1e-9), "{:?} is still drawn", a.p);
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(corners(&s, id), ([10.0; 4], [CornerKind::Round; 4], 8));
|
||||
}
|
||||
|
||||
/// Selected segments of a rounded rectangle stay selected when an anchor point is added on a
|
||||
/// side: a selected side that is split gives both its halves and the new anchor, and the other
|
||||
/// selected segments stay on the same sides and curves.
|
||||
#[test]
|
||||
fn adding_an_anchor_keeps_the_selected_segments_on_their_sides() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (top, curve, bottom) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2), segment_between(&s, id, 2, 3));
|
||||
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, top], [0, curve], [0, bottom]], "mode": "set"})).unwrap();
|
||||
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": top, "t": 0.5})).unwrap();
|
||||
let ai = usize::try_from(r["anchor"].as_u64().unwrap()).unwrap();
|
||||
// The new anchor is the outline's anchor 1, so corners 1, 2 and 3 are 2, 3 and 4 now.
|
||||
let want: BTreeSet<_> =
|
||||
[segment_between(&s, id, 0, 1), segment_between(&s, id, 1, 2), segment_between(&s, id, 3, 3), segment_between(&s, id, 3, 4)]
|
||||
.map(|g| (0, g))
|
||||
.into();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.segments.get(&id), Some(&want));
|
||||
assert!(st.selection.anchors.get(&id).is_some_and(|a| a.contains(&(0, ai))), "{:?}", st.selection.anchors);
|
||||
}
|
||||
|
||||
/// The anchors selected as the ends of selected segments stay just those ends when an anchor
|
||||
/// point is added on another side: the far anchors of the corners at a selected side's ends are
|
||||
/// not selected, so an arrow-key nudge does not move them.
|
||||
#[test]
|
||||
fn adding_an_anchor_selects_only_the_ends_of_the_selected_segments() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (top, curve, bottom) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2), segment_between(&s, id, 2, 3));
|
||||
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, top], [0, curve]], "mode": "set"})).unwrap();
|
||||
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": bottom, "t": 0.5})).unwrap();
|
||||
let n = node_path(&s, id).0.subpaths[0].anchors.len();
|
||||
// The new anchor is the outline's anchor 3, after the corners at the selected segments' ends.
|
||||
let (top, curve) = (segment_between(&s, id, 0, 1), segment_between(&s, id, 2, 2));
|
||||
let want: BTreeSet<AnchorRef> = [top, (top + 1) % n, curve, (curve + 1) % n].map(|a| (0, a)).into();
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.anchors.get(&id), Some(&want));
|
||||
assert_eq!(st.selection.segments.get(&id), Some(&[(0, top), (0, curve)].into()));
|
||||
}
|
||||
|
||||
/// An anchor point added on a corner's curve turns the corners into plain anchor points, as
|
||||
/// before, and the status bar says so.
|
||||
#[test]
|
||||
fn adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let seg = segment_between(&s, id, 1, 1);
|
||||
let r = s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.5})).unwrap();
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("Live Corners")), "{r}");
|
||||
let (path, live) = node_path(&s, id);
|
||||
assert_eq!((path.anchor_count(), live), (9, None));
|
||||
}
|
||||
|
||||
/// Delete Anchor Point on either anchor of a cut corner removes that corner from the outline, and
|
||||
/// the other corners stay live at their radii.
|
||||
#[test]
|
||||
fn deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live() {
|
||||
for end in 0..2 {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let (_, ai) = corner_anchors(&s, id, &[1]).into_iter().nth(end).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": ai})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
assert_eq!(lc.base.anchor_count(), 3, "end {end}");
|
||||
assert!(lc.corners.iter().all(|c| c.at.distance(Point::new(110.0, 10.0)) > 1.0), "the top-right corner went");
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 3]), "end {end}");
|
||||
assert_eq!(node_path(&s, id).0.anchor_count(), 6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove Anchor Points on a cut corner of a rounded rectangle keeps the other corners live and
|
||||
/// selects an anchor of the next corner along, so the next Remove Anchor Points goes on there.
|
||||
#[test]
|
||||
fn remove_anchor_points_on_a_cut_corner_selects_the_next_corner() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let picked: Vec<[usize; 2]> = corner_anchors(&s, id, &[1]).into_iter().map(|(si, ai)| [si, ai]).collect();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
s.execute("path.removeAnchors", &json!({})).unwrap();
|
||||
assert_eq!(live_radii(&s, id), Some(vec![10.0; 3]));
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
// The bottom-right corner, which followed the removed one, is the outline's anchor 1 now.
|
||||
assert!(lc.base.subpaths[0].anchors[1].p.distance(Point::new(110.0, 70.0)) < 1e-9);
|
||||
assert_eq!(selected_anchors(&s, id), lc.drawn_anchor((0, 1)).map(|a| BTreeSet::from([a])));
|
||||
}
|
||||
|
||||
/// Remove Anchor Points with one anchor of every cut corner selected removes every corner, so the
|
||||
/// path goes, as a plain path with all its anchors removed does.
|
||||
#[test]
|
||||
fn removing_an_anchor_of_every_corner_removes_the_path() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"radius": 10}));
|
||||
let lc = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap();
|
||||
let picked: Vec<[usize; 2]> = (0..4).filter_map(|k| lc.drawn_anchor((0, k))).map(|(si, ai)| [si, ai]).collect();
|
||||
assert_eq!(picked.len(), 4);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
assert_eq!(s.execute("path.removeAnchors", &json!({})).unwrap()["removedObjects"], 1);
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
}
|
||||
|
||||
/// A relative radius keeps the length it is drawn at when an added anchor shortens the side its
|
||||
/// corner's largest radius depends on.
|
||||
#[test]
|
||||
fn an_added_anchor_keeps_a_relative_radius_at_its_length() {
|
||||
let (mut s, id) = session();
|
||||
run(&mut s, json!({"relativeRadii": true}));
|
||||
let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius();
|
||||
run(&mut s, json!({"radius": 0.25 * max}));
|
||||
let drawn = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().drawn_radius(0);
|
||||
let seg = segment_between(&s, id, 0, 1);
|
||||
s.execute("path.insertAnchor", &json!({"id": id.0, "segment": seg, "t": 0.5})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(matches!(n.live_shape(), Some(LiveShape::Path { radii_relative: true, .. })), "{:?}", n.live_shape());
|
||||
let lc = LiveCorners::of(n).unwrap();
|
||||
assert!((lc.drawn_radius(0) - drawn).abs() < 1e-9, "{} vs {drawn}", lc.drawn_radius(0));
|
||||
}
|
||||
@@ -904,10 +904,13 @@ fn dxf_xs(dxf: &str) -> Vec<f64> {
|
||||
xs
|
||||
}
|
||||
|
||||
/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and
|
||||
/// DWG, the help page's default format, throws without writing a file.
|
||||
/// `exportFile` with `ExportType.AutoCAD` writes a DWG, the help page's default format, or a DXF
|
||||
/// with the `ExportOptionsAutoCAD` options; a DWG of a release before 2000 throws without writing a
|
||||
/// file. craft-dwg writes DWG everywhere but wasm32 and FreeBSD on aarch64.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
fn an_autocad_export_writes_a_dwg_or_a_dxf_with_its_options() {
|
||||
vectorcraft_cad::dwg::allow_in_process();
|
||||
let base = folder("autocad");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
@@ -919,7 +922,9 @@ fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
|
||||
var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\
|
||||
try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\
|
||||
d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o);\n\
|
||||
o.version = AutoCADCompatibility.AutoCADRelease14;\n\
|
||||
try {{ d.exportFile(new File(dir + '/old'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\
|
||||
o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\
|
||||
o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\
|
||||
d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\
|
||||
@@ -930,8 +935,11 @@ fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true]));
|
||||
assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]);
|
||||
assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing");
|
||||
let w = std::fs::read(dir.join("w.dwg")).unwrap();
|
||||
assert_eq!(&w[..6], b"AC1024", "the default AutoCADRelease24 is the 2010 format");
|
||||
assert!(!dir.join("w.dxf").exists());
|
||||
assert!(out[1].as_str().is_some_and(|e| e.contains("DWG needs AutoCADRelease15")), "{}", out[1]);
|
||||
assert!(!dir.join("old.dwg").exists() && !dir.join("old").exists(), "a refused DWG writes nothing");
|
||||
let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap();
|
||||
let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap();
|
||||
assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it");
|
||||
@@ -1421,10 +1429,11 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
"from 0 to 100",
|
||||
),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"),
|
||||
(
|
||||
format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"),
|
||||
"DWG is not available",
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; o.version = AutoCADCompatibility.AutoCADRelease13; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"
|
||||
),
|
||||
"DWG needs AutoCADRelease15",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
|
||||
@@ -900,7 +900,7 @@ fn errors_are_tool_results_not_crashes() {
|
||||
("type_text", json!({"text": "hi"})),
|
||||
("screenshot", json!({"window": true})),
|
||||
("open_file", json!({"path": "/definitely/not/here.svg"})),
|
||||
("export", json!({"path": "/tmp/out.dwg"})),
|
||||
("export", json!({"path": "/tmp/out.pmd"})),
|
||||
("redo", json!({})),
|
||||
("press_key", json!({"key": "F13"})),
|
||||
];
|
||||
|
||||
@@ -81,7 +81,8 @@ fn export_tool_lists_engine_formats_and_options() {
|
||||
"hpgl",
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx"
|
||||
"cmx",
|
||||
"dwg"
|
||||
])
|
||||
);
|
||||
for k in ["artboard", "range", "options"] {
|
||||
|
||||
@@ -400,16 +400,16 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"export",
|
||||
"Export",
|
||||
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
|
||||
"Export the active document with the engine's document.export (the same bytes in the app and headless), in any format of the `format` enum: vectors (svg/svgz with the artboard as viewBox, eps, dxf, dwg (the DXF drawing as a DWG file, versions 2000 to 2018), emf, wmf, hpgl pen moves for plotters and cutters, cmx exchange files of fills and strokes), pdf and ai (one page per artboard: all, or `artboard` / `range`; ai is the PDF-compatible .ai file that Save writes, which carries the document when every artboard is written in order), rasters (one rendered artboard: png, jpg, webp, gif, png8 as an indexed .png, tiff, bmp, tga, psd with its layers), txt (the stories, back to front), vectorcraft or template (a native copy or template; the document keeps its path). run_command document.formats lists each format's options. For SVG/SVGZ, top-level `outlineText: true` writes text as paths; DXF and DWG take it too (its type is outlined anyway unless `preserve: editability`). PDF instead uses `options.advanced.outlineText: true`, default false (live text). `selection: true` exports only the selected objects, cropped to their bounds. Template layers are left out; live effects are kept (geometry baked, SVG filters for shadows/glows/blur). Without `path` the bytes come back as dataBase64.",
|
||||
obj(
|
||||
json!({
|
||||
"format": {"type": "string", "enum": FORMATS.iter().filter(|f| f.write).map(|f| f.id).collect::<Vec<_>>(), "description": "Default: from the path's extension"},
|
||||
"path": string("Destination file (omit to get dataBase64)"),
|
||||
"scale": num("Raster pixels per point (without scale or options.ppi, uses the document's raster effects resolution; options.ppi wins)"),
|
||||
"artboard": {"type": "integer", "minimum": 0, "description": "0-based artboard (default: the first; PDF and .ai default: all)"},
|
||||
"range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"),
|
||||
"range": string("1-based artboards such as \"1-3, 5\" (PDF and .ai: one page each; SVG and SVGZ: one file each; EPS: one file each, after a central file of the whole document when there are two or more and art shows; rasters, DXF, DWG, EMF, WMF and HP-GL: one, or one file each with options.useArtboards: true; CMX: one, or one page each in one file with options.useArtboards: true)"),
|
||||
"selection": {"type": "boolean", "description": "Export only the selection, cropped to it"},
|
||||
"outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF takes it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"},
|
||||
"outlineText": {"type": "boolean", "description": "SVG/SVGZ: true writes text as outlines (viewable without the fonts). DXF and DWG take it too (type outlined anyway unless preserve: editability). PDF uses options.advanced.outlineText instead (default false: live text)"},
|
||||
"options": {"type": "object", "description": "More format options, passed through (see run_command document.formats), e.g. {\"quality\": 80} for jpg or {\"advanced\": {\"outlineText\": true}} for PDF text as outlines (default false: live text)"},
|
||||
}),
|
||||
&[],
|
||||
|
||||
@@ -1774,7 +1774,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.dxfOptionsDialog",
|
||||
"DXF Options Dialog",
|
||||
"",
|
||||
"{path?, useArtboards?, range?, …document.exportDxf options} open DXF Options (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom); OK checks them, remembers them and writes path (else asks). Export As… → DXF opens it too",
|
||||
"{path?, format?: dxf (default)|dwg, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too",
|
||||
),
|
||||
(
|
||||
"links.editOriginal",
|
||||
|
||||
@@ -488,6 +488,30 @@ fn an_add_on_preview_keeps_an_edit_made_outside_the_dialog() {
|
||||
assert_eq!(undo_len(&app), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_preview_keeps_a_file_placed_outside_the_dialog() {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-addon-place-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("placed.vectorcraft");
|
||||
std::fs::write(&path, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(80.0, 40.0))).unwrap();
|
||||
let mut app = two_rects();
|
||||
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
|
||||
let id = dialog_id(&app);
|
||||
set(&app, id, "layout", json!("row"));
|
||||
set(&app, id, "preview", json!(true));
|
||||
frame(&mut app);
|
||||
assert_eq!(x0(&app, 1), 30.0, "previewed");
|
||||
let undo = undo_len(&app);
|
||||
app.run("file.place", json!({"path": path.to_string_lossy(), "at": [300, 300]})).unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(undo_len(&app), undo + 1, "the placed file is a step of its own");
|
||||
cancel(&app, id);
|
||||
frame(&mut app);
|
||||
assert!(!app.session.in_interaction());
|
||||
assert_eq!(count(&app), 3, "Cancel keeps the placed file");
|
||||
assert_eq!(x0(&app, 1), 100.0, "Cancel rolls the preview back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_on_preview_waits_for_its_opening_drawing() {
|
||||
let mut app = two_drawings();
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
//! art = N drawing units) and lineweights, number of colours, the format of placed images and
|
||||
//! Include Placed Images, Preserve Appearance or Maximize Editability, and Export Selected Art
|
||||
//! Only, Alter Paths for Appearance, Outline Text, Include Fill Hatches and Always Export Group as
|
||||
//! Block Reference (not set by a preset).
|
||||
//! Block Reference (not set by a preset). DWG Options (Export As → DWG) is the same dialog for a DWG
|
||||
//! file of the same drawing, offering the versions from 2000.
|
||||
//!
|
||||
//! Fields: `document.export` params (`format: dxf`, `path?`, the artboard choice) and the DXF
|
||||
//! options of `document.exportDxf`. OK remembers the options for next time and writes the file
|
||||
//! (asking where when there is no path); bad options keep the dialog open.
|
||||
//! Fields: `document.export` params (`format: dxf|dwg`, `path?`, the artboard choice) and the DXF
|
||||
//! options of `document.exportDxf`. OK remembers the options for next time (DXF and DWG share them)
|
||||
//! and writes the file (asking where when there is no path); bad options keep the dialog open.
|
||||
|
||||
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
@@ -71,7 +72,12 @@ fn dialog_fields(map: &Map<String, Value>) -> DialogFields {
|
||||
|
||||
/// The rows as far as their kinds go, for reading values to and from JSON.
|
||||
fn kinds() -> Vec<Param> {
|
||||
rows(false, false, false)
|
||||
rows(false, false, false, false)
|
||||
}
|
||||
|
||||
/// Is `format` (an id or extension) DWG?
|
||||
fn is_dwg(format: Option<&str>) -> bool {
|
||||
format.and_then(fileio::format).is_some_and(|f| f.id == "dwg")
|
||||
}
|
||||
|
||||
/// Gives the dialog the fields the current preset sets and the others have lost (a change of the preset row removes
|
||||
@@ -106,12 +112,14 @@ pub(super) fn check_param(key: &str, label: &'static str) -> Param {
|
||||
}
|
||||
|
||||
/// The rows. Export Selection leaves Export Selected Art Only out, as it writes the selected art alone;
|
||||
/// without a selection that row is off. `note` shows the true-colour note.
|
||||
fn rows(selection: bool, has_selection: bool, note: bool) -> Vec<Param> {
|
||||
/// without a selection that row is off. `note` shows the true-colour note; `dwg` offers the versions a
|
||||
/// DWG file is written as.
|
||||
fn rows(selection: bool, has_selection: bool, note: bool, dwg: bool) -> Vec<Param> {
|
||||
let keys: Vec<String> = preset_fields(DxfPreset::Custom).keys().cloned().collect();
|
||||
let versions = DxfVersion::ALL.iter().filter(|v| !dwg || vectorcraft_cad::dwg::writes(**v));
|
||||
let mut rows = vec![
|
||||
choice_param(PRESET, tl!("Preset:"), DxfPreset::ALL.iter().map(|p| (p.id(), p.label()))).resets(keys),
|
||||
choice_param("version", tl!("Version:"), DxfVersion::ALL.iter().map(|v| (v.id(), v.label()))),
|
||||
choice_param("version", tl!("Version:"), versions.map(|v| (v.id(), v.label()))),
|
||||
scale_param(None),
|
||||
check_param("scaleLineweights", tl!("Scale Lineweights")),
|
||||
choice_param("colors", tl!("Number of Colors:"), ColorDepth::ALL.iter().map(|c| (c.id(), c.label()))),
|
||||
@@ -182,17 +190,25 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) {
|
||||
|
||||
/// [`open`] for Export Selection when `selection` is set: the options then write the selected art alone.
|
||||
pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) {
|
||||
let dwg = is_dwg(params.get("format").and_then(Value::as_str));
|
||||
let mut fields = defaults();
|
||||
if let Some(o) = app.ui.dxf_options.as_object() {
|
||||
fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
}
|
||||
// DWG Options start on the default version when the version used last is one a DWG isn't
|
||||
// written as; a version `params` gives is kept, for OK to refuse.
|
||||
// `version` may be a number: 2018 and "2018" alike.
|
||||
let version = fields.get("version").and_then(|v| DxfVersion::from_id(&v.as_str().map_or_else(|| v.to_string(), str::to_string)));
|
||||
if dwg && !version.is_some_and(vectorcraft_cad::dwg::writes) {
|
||||
fields.insert("version".into(), json!(DxfVersion::default().id()));
|
||||
}
|
||||
if let Some(o) = params.as_object() {
|
||||
if let Some(p) = o.get(PRESET).and_then(Value::as_str).and_then(DxfPreset::from_id) {
|
||||
fields.extend(preset_fields(p));
|
||||
}
|
||||
fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
}
|
||||
fields.insert("format".into(), json!("dxf"));
|
||||
fields.insert("format".into(), json!(if dwg { "dwg" } else { "dxf" }));
|
||||
let mut values = dialog_fields(&fields);
|
||||
settle(&mut values);
|
||||
let has_selection = app.session.active().is_some_and(|st| !st.selection.is_empty());
|
||||
@@ -201,10 +217,9 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) {
|
||||
settle(fields);
|
||||
let note = fields.text("colors").and_then(ColorDepth::from_id) == Some(ColorDepth::True)
|
||||
&& fields.text("version").and_then(DxfVersion::from_id).unwrap_or_default() < DxfVersion::R2004;
|
||||
ParamDialog::new(KIND, tl!("DXF Options"), rows(selection, has_selection, note))
|
||||
.values(Bind::bound(fields))
|
||||
.ok_label(tl!("Export").into())
|
||||
.below(|ui, fields| {
|
||||
let heading = if dwg { tl!("DWG Options") } else { tl!("DXF Options") };
|
||||
ParamDialog::new(KIND, heading, rows(selection, has_selection, note, dwg)).values(Bind::bound(fields)).ok_label(tl!("Export").into()).below(
|
||||
|ui, fields| {
|
||||
Text::new(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() {
|
||||
Preserve::Appearance => tl!("Type becomes outlines, and strokes a CAD line can't draw become filled shapes."),
|
||||
Preserve::Editability => tl!("Type stays text, and every stroke is a line with its lineweight and dashes."),
|
||||
@@ -212,7 +227,8 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) {
|
||||
.role(TypeRole::Caption)
|
||||
.shade(Shade::Muted)
|
||||
.show(ui);
|
||||
})
|
||||
},
|
||||
)
|
||||
});
|
||||
export_host::open(app, Export::Dxf, selection, dialog);
|
||||
}
|
||||
@@ -223,7 +239,8 @@ pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFiel
|
||||
// drawing) counts as drawn.
|
||||
let mut fields = fields.clone();
|
||||
settle(&mut fields);
|
||||
let map = form::json_of(&rows(open.selection, true, false), &fields);
|
||||
let format = if is_dwg(fields.text("format")) { "dwg" } else { "dxf" };
|
||||
let map = form::json_of(&rows(open.selection, true, false, false), &fields);
|
||||
let params = Value::Object(map.clone());
|
||||
fileio::dxf::check(¶ms)?;
|
||||
// Nothing selected keeps the dialog open too.
|
||||
@@ -232,5 +249,5 @@ pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFiel
|
||||
}
|
||||
app.ui.dxf_options = Value::Object(map.into_iter().filter(|(k, _)| !PER_EXPORT.contains(&k.as_str())).collect());
|
||||
let path = fields.text("path").map(str::to_string);
|
||||
io::export(app, Some("dxf"), path, &super::export_as::exported(open.selection, params)).map(|_| None)
|
||||
io::export(app, Some(format), path, &super::export_as::exported(open.selection, params)).map(|_| None)
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
//! artboard, after a central file of the whole document for EPS with two or more when art shows,
|
||||
//! or one page each in a PDF); without artboards the export covers the visible art. OK
|
||||
//! picks the file, then the format's options dialog follows (PNG/JPEG/WebP/PNG-8/GIF Options, SVG
|
||||
//! Options, Text Export Options, DXF Options, EPS Options, HP-GL Options, and Save PDF),
|
||||
//! else the file is written. DWG is listed, greyed out, with what to use instead. The formats of
|
||||
//! Options, Text Export Options, DXF Options, DWG Options, EPS Options, HP-GL Options, and Save
|
||||
//! PDF), else the file is written. The formats of
|
||||
//! installed exporter plug-ins come after the built-in ones: they write the whole document (from
|
||||
//! Export Selection, the selection), and one with parameters asks for them before writing
|
||||
//! (`plugin::open_export`). Export Selection ([`export_selection`]) takes the same route after its
|
||||
@@ -29,8 +29,6 @@ pub(super) const KIND: &str = "exportAs";
|
||||
/// The built-in formats Export As writes (the native format and `.ai` are Save As's).
|
||||
static BUILT_IN: LazyLock<Vec<&'static Format>> =
|
||||
LazyLock::new(|| fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect());
|
||||
/// Formats listed after them that can't be written (`fileio::write_hint` ids), greyed out.
|
||||
const UNAVAILABLE: [(&str, &str); 1] = [("dwg", "DWG (use DXF)")];
|
||||
|
||||
/// The formats Export As writes: the built-in ones, then those of the installed exporter plug-ins.
|
||||
pub(super) fn formats() -> Vec<&'static Format> {
|
||||
@@ -42,13 +40,6 @@ fn from_plugin(f: &Format) -> bool {
|
||||
vectorcraft_plugins::export::by_format(f.id).is_some()
|
||||
}
|
||||
|
||||
/// What to use instead when the format field names a format that can't be written (DWG).
|
||||
fn unavailable(fields: &DialogFields) -> Option<(&'static str, &'static str)> {
|
||||
let id = fields.text("format")?;
|
||||
let (_, label) = UNAVAILABLE.iter().find(|u| u.0 == id)?;
|
||||
Some((label, fileio::write_hint(id)?))
|
||||
}
|
||||
|
||||
/// The chosen format (PNG when the field names none Export As writes).
|
||||
fn chosen(fields: &DialogFields) -> Option<&'static Format> {
|
||||
let all = formats();
|
||||
@@ -64,7 +55,7 @@ fn is_all(fields: &DialogFields) -> bool {
|
||||
/// The rows, from the formats installed now.
|
||||
fn params() -> Vec<Param> {
|
||||
let all = formats();
|
||||
let choices = all.iter().map(|f| (f.id, f.label)).chain(UNAVAILABLE);
|
||||
let choices = all.iter().map(|f| (f.id, f.label));
|
||||
// An exporter plug-in writes the whole document: Use Artboards is not its to apply.
|
||||
let whole: Vec<&str> = all.iter().filter(|f| !from_plugin(f)).map(|f| f.id).collect();
|
||||
vec![
|
||||
@@ -72,8 +63,7 @@ fn params() -> Vec<Param> {
|
||||
"format",
|
||||
tl!("Format:"),
|
||||
ParamKind::choice(choices.map(|(id, label)| (id.to_string(), Label::from(label))).collect(), Some("png".into())),
|
||||
)
|
||||
.disabled_options(UNAVAILABLE.map(|u| u.0)),
|
||||
),
|
||||
Param::new("useArtboards", tl!("Use Artboards"), ParamKind::bool(false)).enabled_when_in("format", whole),
|
||||
Param::new(
|
||||
"all",
|
||||
@@ -85,11 +75,8 @@ fn params() -> Vec<Param> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The line under the rows: what the export writes, or what to use instead of DWG.
|
||||
/// The line under the rows: what the export writes.
|
||||
fn summary(fields: &DialogFields) -> String {
|
||||
if let Some((_, hint)) = unavailable(fields) {
|
||||
return hint.to_string();
|
||||
}
|
||||
let Some(f) = chosen(fields) else { return String::new() };
|
||||
let whole = from_plugin(f);
|
||||
let use_artboards = fields.bool("useArtboards").unwrap_or(false) && !whole;
|
||||
@@ -114,11 +101,7 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res
|
||||
let source = app.session.active();
|
||||
let document = source.map(|source| (source.uid, source.reverts));
|
||||
let n = source.map_or(0, |source| source.doc.artboards.len());
|
||||
let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.'))));
|
||||
let format = match missing {
|
||||
Some((id, _)) => id,
|
||||
None => format.and_then(fileio::format).filter(|f| formats().iter().any(|g| g.id == f.id)).map_or("png", |f| f.id),
|
||||
};
|
||||
let format = format.and_then(fileio::format).filter(|f| formats().iter().any(|g| g.id == f.id)).map_or("png", |f| f.id);
|
||||
let range = p.get("range").and_then(Value::as_str);
|
||||
let initial = json!({
|
||||
"format": format,
|
||||
@@ -152,9 +135,6 @@ fn require_source(app: &VectorcraftApp, document: Option<(u64, u64)>) -> Result<
|
||||
/// the file follow once the dialog has closed.
|
||||
pub(super) fn confirm(app: &mut VectorcraftApp, document: Option<(u64, u64)>, fields: &DialogFields) -> Result<After, String> {
|
||||
require_source(app, document)?;
|
||||
if let Some((_, hint)) = unavailable(fields) {
|
||||
return Err(hint.into());
|
||||
}
|
||||
let f = chosen(fields).ok_or("no format to export to")?;
|
||||
let plugin = vectorcraft_plugins::export::by_format(f.id);
|
||||
let use_artboards = fields.bool("useArtboards").unwrap_or(false) && plugin.is_none();
|
||||
@@ -273,7 +253,7 @@ fn options_or_write(
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
match f.id {
|
||||
"dxf" => dxf_options::open(app, ¶ms),
|
||||
"dxf" | "dwg" => dxf_options::open(app, ¶ms),
|
||||
"eps" => eps_options::open(app, ¶ms),
|
||||
"hpgl" => hpgl_options::open(app, ¶ms),
|
||||
_ => return io::export(app, Some(f.id), Some(path), ¶ms),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Export As → DXF Options, and DWG listed as unavailable, drawn headlessly.
|
||||
//! Export As → DXF Options and DWG Options, drawn headlessly.
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
|
||||
use serde_json::json;
|
||||
@@ -198,17 +198,43 @@ fn bad_dxf_options_keep_the_dialog_open() {
|
||||
assert_eq!(names(&written), ["/out/a.dxf"]);
|
||||
}
|
||||
|
||||
/// craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on aarch64.
|
||||
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
|
||||
#[test]
|
||||
fn dwg_is_listed_but_points_to_dxf() {
|
||||
fn export_as_dwg_shows_dwg_options_then_writes_a_dwg() {
|
||||
vectorcraft_engine::dwg::allow_in_process();
|
||||
let (mut app, written) = app(1);
|
||||
// A version used last that a DWG isn't written as: DWG Options start on 2018, the other options carry over.
|
||||
app.ui.dxf_options = json!({"version": "R12", "unit": "Inches"});
|
||||
app.run("file.exportAs", json!({"format": "dwg"})).unwrap();
|
||||
assert_eq!(show(&fields(&app), "format"), "dwg");
|
||||
frame(&mut app);
|
||||
let e = try_confirm(&mut app).unwrap_err();
|
||||
assert!(e.contains("DWG") && e.contains("DXF"), "{e}");
|
||||
assert_eq!(kind(&app).as_deref(), Some("exportAs"), "the dialog stays open to pick DXF");
|
||||
set(&mut app, "format", json!("dxf"));
|
||||
confirm(&mut app);
|
||||
assert_eq!(kind(&app).as_deref(), Some("dxfOptions"), "DWG Options follow");
|
||||
let d = fields(&app);
|
||||
let shown = [show(&d, "format"), show(&d, "path"), show(&d, "version"), show(&d, "unit")];
|
||||
assert_eq!(shown, ["dwg", "/out/Untitled-1.dwg", "2018", "Inches"]);
|
||||
frame(&mut app);
|
||||
// The version row offers the versions from 2000.
|
||||
assert!(try_set(&mut app, "version", json!("R14")).is_err());
|
||||
set(&mut app, "version", json!("2000"));
|
||||
frame(&mut app);
|
||||
confirm(&mut app);
|
||||
assert!(kind(&app).is_none());
|
||||
assert_eq!(names(&written), ["/out/Untitled-1.dwg"]);
|
||||
assert_eq!(&written.borrow()[0].1[..6], b"AC1015");
|
||||
assert_eq!(app.ui.dxf_options["version"].as_str(), Some("2000"), "DXF and DWG share the options");
|
||||
// A version the command gives is kept, and OK refuses it.
|
||||
app.run("ui.dxfOptionsDialog", json!({"format": "dwg", "version": "R13", "path": "/out/b.dwg"})).unwrap();
|
||||
assert_eq!(show(&fields(&app), "version"), "R13");
|
||||
let e = try_confirm(&mut app).unwrap_err();
|
||||
assert!(e.contains("DWG version `R13`"), "{e}");
|
||||
assert_eq!(kind(&app).as_deref(), Some("dxfOptions"));
|
||||
assert!(written.borrow().is_empty());
|
||||
assert_eq!(written.borrow().len(), 1);
|
||||
// DXF Options still offer every DXF version.
|
||||
cancel(&mut app);
|
||||
app.run("ui.dxfOptionsDialog", json!({"path": "/out/c.dxf"})).unwrap();
|
||||
set(&mut app, "version", json!("R14"));
|
||||
confirm(&mut app);
|
||||
assert!(text(&written.borrow()[1].1).contains("AC1014"));
|
||||
}
|
||||
@@ -437,7 +437,7 @@ mod tests {
|
||||
assert!(vectorcraft_format::sniff(&w[1].1));
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/tmp/doc.vectorcraft"));
|
||||
drop(w);
|
||||
assert!(export(&mut app, None, Some("/tmp/x.dwg".into()), &Value::Null).is_err(), "DWG can't be written");
|
||||
assert!(export(&mut app, None, Some("/tmp/x.pmd".into()), &Value::Null).is_err(), "PageMaker can't be written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1775,7 +1775,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.dxfOptionsDialog",
|
||||
"DXF Options Dialog",
|
||||
"",
|
||||
"{path?, useArtboards?, range?, …document.exportDxf options} open DXF Options (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom); OK checks them, remembers them and writes path (else asks). Export As… → DXF opens it too",
|
||||
"{path?, format?: dxf (default)|dwg, useArtboards?, range?, …document.exportDxf options} open DXF Options, or DWG Options for format: dwg (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom; DWG offers the versions from 2000, and a version used last that DWG isn't written as starts on 2018); OK checks them, remembers them and writes path (else asks). Export As… → DXF or DWG opens it too",
|
||||
),
|
||||
(
|
||||
"links.editOriginal",
|
||||
|
||||
@@ -882,8 +882,10 @@ the artboard choice. Setting `dxfPreset` to
|
||||
`cnc` sets the fields it sets (see `document.exportDxf`), and `dxfPreset` reads `custom` again once one of them is
|
||||
changed; setting it to `custom` puts back the defaults. `ui.dialog.confirm` checks them (a bad value, or
|
||||
Export Selected Art Only with nothing selected, keeps the dialog open), remembers them for the next DXF Options and
|
||||
writes the file (asking for a path when there is none). Export As also lists DWG, greyed out: setting its `format` to
|
||||
`dwg` shows, and on confirm answers, the hint to export DXF instead.
|
||||
writes the file (asking for a path when there is none). Export As → DWG, and `ui.dxfOptionsDialog` with
|
||||
`format: "dwg"`, open the same dialog as DWG Options: its `version` offers `2000` to `2018`, a version remembered from
|
||||
DXF Options that a DWG isn't written as starts on `2018`, and OK writes a `.dwg` file. DXF and DWG Options share the
|
||||
remembered options.
|
||||
|
||||
DXF Import Options: opening a DXF drawing through the app (`app.open`, `file.open`, a drop) or placing one
|
||||
(`file.place` with a `.dxf` file and no `dxf` options, which answers `{"dialog": "dxfImport"}`) opens the `dxfImport`
|
||||
|
||||
@@ -63,7 +63,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a
|
||||
|---|---:|---:|---|
|
||||
| Formats opened or placed | ~30 | 37 | missing: FreeHand |
|
||||
| Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) |
|
||||
| Formats exported | ~16 | 20 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD |
|
||||
| Formats exported | ~16 | 21 | extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD |
|
||||
| **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting |
|
||||
|
||||
EPS editing-data follow-up (2026-10-16): both mesh-corner layouts (with and without opacity)
|
||||
@@ -373,7 +373,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
|
||||
| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) |
|
||||
| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. REGION entities open as filled paths of their faces' boundary loops (lines, circles, ellipses and spline edges), read from the text data of DXF R13 to 2010 and the binary data in the ACDSDATA section of DXF 2013 and later, DWG included; edges of other curve types come in straight, an outline that breaks off is closed with a straight line, and a spline edge whose endpoint lies on two parts of a self-crossing curve is trimmed at the nearer one, each with a warning ([REGION group codes](https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4), `crates/cad/src/import/tests_region.rs`). DXF and DWG import draw a pattern hatch as its pattern lines (groups 53, 43–46 and 49) clipped to its boundary and cut into their dashes and dots, and fill a gradient hatch (groups 450–470) with a linear or radial gradient in its colors at its angle; hatches follow their island style (normal, outer, ignore); the mapping of each named gradient to a linear or radial one is VectorCraft's own (`pattern_hatches_draw_their_lines_inside_the_boundary`, `gradient_hatches_keep_their_gradient`; [HATCH group codes](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-C6C71CED-CE0F-4184-82A5-07AD6241F15B.htm)) |
|
||||
| HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` |
|
||||
| DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build |
|
||||
| DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | yes (2000–2018, the drawing the DXF export writes, converted by craft-dwg in a child process on desktop; DWG Options; R12, R13 and R14 refused) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer; exported DWG files opened again), `crates/ui-egui/src/dialogs/tests_dxf.rs`; not in the web build |
|
||||
| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` |
|
||||
| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) |
|
||||
| PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | |
|
||||
|
||||
+32
-12
@@ -889,7 +889,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
|
||||
| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. The same holds for a step that is neither a number nor null, a `reflect` that is not a string, a `copy` that is not true or false, and an `origin` that is not two numbers. A null `rotate`, `scale`, `scaleX`, `scaleY`, `shear`, `reflect`, `copy` or `origin` is left out; a null `dx` or `dy` counts as 0, so it still runs the move. |
|
||||
| `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. |
|
||||
| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. |
|
||||
| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. A path whose selected anchors or segments the preview renumbered (Set Corners recut it) is left out of that selection, so Clear does not delete its points. A command that is refused leaves the dialog's selection as it was. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together afLine truncated
|
||||
| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. A path whose selected anchors or segments the preview renumbered (Set Corners recut it) is left out of that selection, so Clear does not delete its points. A command that is refused leaves the dialog's selection as it was. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together afLine truncated
|
||||
| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders the window enforces: those of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one), or `null` for both when a saved folder can't be used (a deleted folder, a file) and the window refuses every file (a window from before `agent.folders` was added answers with the saved folders, even one it can't use); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. |
|
||||
|
||||
For example, create editable Japanese area type with the engine's vertical writing mode:
|
||||
@@ -910,7 +910,7 @@ first frame's direction, frames taken out of a thread keep theirs, and a file wh
|
||||
with the first frame's direction in all of them. When every frame already has the direction, the command records no
|
||||
undo step.
|
||||
|
||||
For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF takes it too (its type is outlined anyway unless `preserve: editability`).
|
||||
For SVG/SVGZ, `export`'s top-level `outlineText: true` writes text as paths; DXF and DWG take it too (their type is outlined anyway unless `preserve: editability`).
|
||||
PDF instead uses `options: {"advanced": {"outlineText": true}}`; its default is false (live text).
|
||||
|
||||
With `mods.shift`, a marquee dragged with the Selection tool toggles the objects it reaches (the selected ones leave
|
||||
@@ -3578,8 +3578,9 @@ through `$`:
|
||||
`unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 100, VectorCraft's own values.
|
||||
`AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and
|
||||
`AutoCADColors.TrueColors` throws an error.
|
||||
`AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an
|
||||
AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`,
|
||||
`AutoCADExportFileFormat.DWG`, the help page's default, writes a `.dwg` file of the drawing the DXF export writes,
|
||||
and `AutoCADExportFileFormat.DXF` writes a `.dxf` file. A DWG is written as `AutoCADRelease15` (2000) or later:
|
||||
`AutoCADRelease13` and `14` with DWG throw an error that names `AutoCADRelease15`. The enumerations `AutoCADColors`,
|
||||
`AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit`
|
||||
hold the members the scripting constants page lists. `app.open`'s
|
||||
`options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with
|
||||
@@ -9572,6 +9573,17 @@ unevenly scaled, when an arrow-key nudge's selected curved segments bend or hold
|
||||
direct-selected anchors is other than a move. A nudge that changes nothing, including one that the pixel-grid snap of a
|
||||
pixel-aligned path takes back (objects selected whole beside the anchors included), records no undo step and leaves Live Corners as they are: a live rectangle stays a live
|
||||
rectangle. These fallbacks edit the drawn anchors rather than recutting the uncut outline.
|
||||
Adding and removing anchors keeps such corners live as well: `path.insertAnchor` on a straight or curved side puts the
|
||||
new anchor on that side of the uncut outline, at the point the drawn segment has at `t`, with no radius. `path.removeAnchor`,
|
||||
`path.removeAnchors` and the Delete key with `deleteKeepsPathsJoined` on remove the uncut corner each removed anchor
|
||||
belongs to, so removing either end of a corner's arc removes that corner. The other corners are cut again at their radii
|
||||
and kinds; a relative radius keeps the length it is drawn at, up to the corner's new largest radius. On `path.insertAnchor`
|
||||
the selected anchors follow their corners, the selected segments stay on their sides with only their own ends selected,
|
||||
and a selected segment that the new anchor splits stays selected as its two halves with the new anchor. Removing anchors
|
||||
clears the path's selected anchors and segments, and `path.removeAnchors` then selects the first anchor of the next
|
||||
anchor of the uncut outline along (a corner, or an anchor added on a side), or the anchor before the removed one at an open path's end. An anchor added on a corner's
|
||||
arc, or on a path the fallbacks above apply to, makes the shape a plain path, and when the path had rounded corners
|
||||
`path.insertAnchor` answers with a `warning`, which the status bar shows.
|
||||
`path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same
|
||||
length, and the anchor keeps its kind. At an open end, where no segment leaves the anchor on the other side,
|
||||
`symmetric` has no effect and the handle moves as it would without it. Both `symmetric` and `independent` default to false, and a call with both true is
|
||||
@@ -10661,8 +10673,9 @@ the corners holding a Direct-Selected anchor, or every corner of a path selected
|
||||
hold no corner is left out. The pop-up has the corner kind, the radius (blank while the picked corners differ) and the
|
||||
rounding, Relative or Absolute (`relativeRadii`, which applies to each path as a whole; neither is chosen while the
|
||||
paths differ). A path without Live Corners is Absolute: Relative leaves it, an ellipse or a line as it is, with no
|
||||
undo step. Moving a path's anchors with `path.moveAnchor`, `path.moveAnchors` or the arrow keys keeps Live Corners and
|
||||
the radius mode under the rules above. An anchor edit that makes the shape a plain path ends Live Corners and resets
|
||||
undo step. Moving a path's anchors with `path.moveAnchor`, `path.moveAnchors` or the arrow keys, and adding or removing
|
||||
anchors with `path.insertAnchor`, `path.removeAnchor` or `path.removeAnchors`, keeps Live Corners and the radius mode
|
||||
under the rules above. An anchor edit that makes the shape a plain path ends Live Corners and resets
|
||||
the radius mode to Absolute.
|
||||
With Relative rounding, a radius is
|
||||
compared as the fraction it stores (its share of the corner's maximum, at most all of it), so typing the radius
|
||||
@@ -13009,12 +13022,19 @@ blending, opacity masks, raster effects, clipping) comes back in `warnings`. In
|
||||
no linked file, and `warnings` carries "an image couldn't be decoded and is missing from the picture" once for all such
|
||||
images.
|
||||
|
||||
DWG drawings open and place (see DXF import) but can't be written: `document.formats` lists `dwg` and `dwt` as
|
||||
readable and not writable, and exporting to `dwg`, `dws` or `dwt` answers with the hint to export DXF. Web builds and
|
||||
FreeBSD on 64-bit ARM have no DWG decoder: there `document.formats` lists `dwg` and `dwt` as neither readable nor
|
||||
writable, File › Open, File › Place and `openExtensions` list `.dwg`, `.dws` and `.dwt` only for an installed importer
|
||||
plug-in that reads them, and a DWG drawing opens or places only through such a plug-in. PICT files open and place (see PICT
|
||||
import) but can't be written.
|
||||
`document.export` with `format: "dwg"` (or a `.dwg` path, or `document.exportDxf` with `format: "dwg"`) writes the
|
||||
drawing the DXF export writes, with the same options, as a DWG file: craft-dwg converts it, in the `--dwg-worker`
|
||||
copy of the program in the desktop app and `vectorcraft-cli` (see DXF import). `version` is `2000`, `2004`, `2007`,
|
||||
`2010`, `2013` or `2018` (default); `R12`, `R13` and `R14` are refused with an error that names these. Placed images
|
||||
are written next to the file as for DXF. Records the DWG writer can't write in the chosen version are left out, and
|
||||
`warnings` carries "DWG: n records of this drawing can't be written in this DWG version and were left out" with their
|
||||
DXF types. Export As → DWG opens DWG Options, the DXF Options dialog with the DWG versions. The web build answers an
|
||||
error that says to save as DXF. `.dws` drawing standards files and `.dwt` templates open and place as DWG drawings
|
||||
(see DXF import) but can't be written: `document.formats` lists `dwt` as readable and not writable, and exporting to
|
||||
`dws` or `dwt` answers with a hint to export DWG or DXF. Web builds and FreeBSD on 64-bit ARM have no DWG decoder:
|
||||
there `document.formats` lists `dwg` and `dwt` as not readable, File › Open, File › Place and `openExtensions` list
|
||||
`.dwg`, `.dws` and `.dwt` only for an installed importer plug-in that reads them, and a DWG drawing opens or places only
|
||||
through such a plug-in. PICT files open and place (see PICT import) but can't be written.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"document.exportDxf","params":{"path":"/tmp/plan.dxf","version":"2013","unit":"mm","scale":10,"preserve":"editability"}}}
|
||||
|
||||
@@ -81,9 +81,10 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer`
|
||||
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 9 jobs | Workflow list API; jobs that succeeded on recent main push runs |
|
||||
| `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits |
|
||||
|
||||
The signer reads the policy from `nightly-signer`, so a candidate whose CI ran six test shards
|
||||
(`test 1/6` to `test 6/6`) is admitted only after `nightly-signer` advances to a main commit with
|
||||
this policy. Candidates whose CI ran five shards should be signed before that advance.
|
||||
The signer reads the policy from `nightly-signer`, so a candidate whose CI built the tests once
|
||||
(`build`, `lint` and `test 1/5` to `test 5/5`) is admitted only after `nightly-signer` advances to
|
||||
a main commit with this policy. Candidates whose CI ran six shards (`cache warm` and `test 1/6` to
|
||||
`test 6/6`) should be signed before that advance.
|
||||
|
||||
## Ownership and interface
|
||||
|
||||
|
||||
+1
-1
@@ -199,7 +199,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 |
|
||||
| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 |
|
||||
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 |
|
||||
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | DWG import: DWG drawings open and place through the DXF reader (#10802; estimates unchanged); `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG export (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration reLine truncated
|
||||
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | DWG import: DWG drawings open and place through the DXF reader (#10802; estimates unchanged); DWG export: Export As → DWG writes the DXF export's drawing as DWG 2000 to 2018 (estimates unchanged); `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG export as R13 and R14, PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVGLine truncated
|
||||
| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 |
|
||||
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 |
|
||||
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders done (#1880); vertical type in progress (Type › Type Orientation, #5027) | 45–60 |
|
||||
|
||||
@@ -631,7 +631,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group, object and guide row), menus on blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
|
||||
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
|
||||
| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already; a marquee leaves locked or hidden guide paths out inside groups too, #8538) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units |
|
||||
| File formats | 6 | 85% | `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (#8087, follows #6983; scores and estimates unchanged); `.ai` and EPS import: an Art brush in Tints of a swatch's color comes in brushed (#8200; scores and estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group (#8128; scores and estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
|
||||
| File formats | 6 | 85% | `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (#8087, follows #6983; scores and estimates unchanged); `.ai` and EPS import: an Art brush in Tints of a swatch's color comes in brushed (#8200; scores and estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group (#8128; scores and estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; scores and estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not yet for type filled and stroked at less than full opacity, or a `TJ` whose kerning starts a new line part way through, which still come in as a filled object and a stroked one; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG in the web build and on FreeBSD for aarch64, R1.x and R2.x DWG drawings, and DWG export before version 2000 (the desktop app and `vectorcraft-cli` open and place other DWG drawings and export DWG 2000 to 2018 through the `--dwg-worker` copy of the app), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
|
||||
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
|
||||
| Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 |
|
||||
| Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 |
|
||||
@@ -869,6 +869,7 @@ since 2026-10-01.
|
||||
- **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of every selected path is selected (the paths selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. When another selected path has only some corners picked, a Shift-click on a widget of a path selected whole deselects that corner and keeps the other picks. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`.
|
||||
- **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks (while every corner of every selected path is picked, it picks that corner alone, and a double-click then opens Corners for that corner), a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `corners::tests::a_path_with_hidden_widgets_keeps_its_picks`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`.
|
||||
- **Anchor edits keep Live Corners (#10545):** moving an anchor of a path with rounded corners (Direct Selection drag, arrow keys, `path.moveAnchor`) moves its uncut corner by the drag delta and recuts it at its radius. A grabbed arc end can finish away from a snap target. A live rectangle or polygon becomes a path with live corners. When the anchor layout changes, the path's whole anchor selection is remapped and its segment selection is cleared. A corner that a move straightens keeps its radius and rounds again when a later move bends it. An anchor edit makes the shape a plain path when no anchor stores a radius above 0 (a straightened corner's stored radius keeps the path live), a live rectangle is sheared or unevenly scaled, an arrow-key nudge bends selected curved segments or holds their anchors, or direct-selected anchors receive a transform other than a move. A nudge that changes nothing, including one that the pixel-grid snap of pixel-aligned paths takes back (with objects selected whole too), records no undo step and leaves Live Corners as they are: a live rectangle stays a live rectangle. These are VectorCraft's own rules. Tests: `tests::livecorners::moving_an_anchor_keeps_the_corners_live`, `tests::livecorners::dragging_selected_anchors_keeps_the_corners_live`, `tests::livecorners::moving_an_anchor_of_a_distorted_rectangle_edits_the_drawn_path`, `tests::livecorners::a_recut_remaps_the_whole_anchor_selection`, `tests::livecorners::a_recut_clears_segments_even_when_selected_anchor_indices_stay_the_same`, `tests::livecorners::an_unchanged_corner_layout_keeps_the_selection`, `corners::tests::a_straightened_corner_rounds_again_when_it_bends_back`.
|
||||
- **Adding and removing anchors keeps Live Corners (#10545):** the Pen, Add Anchor Point and Delete Anchor Point tools, Object › Path › Remove Anchor Points and the Delete key with Delete Removes Anchor Points and Keeps Paths Joined on (`path.insertAnchor`, `path.removeAnchor`, `path.removeAnchors`) edit the uncut outline of a path with rounded corners and cut its corners again at their radii and kinds, so the corner widgets stay. An anchor added on a side has no radius; removing either end of a corner's arc removes that corner; a relative radius keeps its drawn length, up to the corner's new largest radius. When an anchor is added, selected anchors follow their corners and selected segments their sides, with only the segments' own ends selected; removing anchors clears the path's selected anchors and segments, and Remove Anchor Points then selects the first anchor of the next anchor of the uncut outline (a corner, or an anchor added on a side), or the anchor before the removed one at an open path's end. An anchor added on a corner's arc makes the path plain, and the status bar says the corners were expanded. These are VectorCraft's own rules. Tests: `tests::livecorners::adding_and_deleting_an_anchor_on_a_side_keeps_the_corners_live`, `tests::livecorners::adding_an_anchor_keeps_the_selected_segments_on_their_sides`, `tests::livecorners::adding_an_anchor_selects_only_the_ends_of_the_selected_segments`, `tests::livecorners::adding_an_anchor_on_a_corners_curve_expands_the_corners_and_warns`, `tests::livecorners::deleting_an_anchor_of_a_cut_corner_removes_the_corner_and_keeps_the_rest_live`, `tests::livecorners::remove_anchor_points_on_a_cut_corner_selects_the_next_corner`, `tests::livecorners::an_added_anchor_keeps_a_relative_radius_at_its_length`.
|
||||
- **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF.
|
||||
- **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`).
|
||||
- **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html).
|
||||
@@ -1139,7 +1140,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. In a Shaper group, new empty groups and compound paths and turning clipping on are refused, since the group keeps its source art at the bottom. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws unless the base settings hold a profile. `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DWG file (`AutoCADExportFileFormat.DWG`, the default; version 2000 or later; desktop app and `vectorcraft-cli` only, through the `--dwg-worker` copy of the program, so the web build throws an error) or a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
@@ -2577,7 +2578,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge.
|
||||
- DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`).
|
||||
- DXF Options' Always Export Group as Block Reference (`groupBlocks`, off by default and not set by a preset) writes each group with output as a block of its contents, placed by an INSERT on its layer, with groups inside it as blocks placed inside that block, in every version from R12 to 2018; a group whose contents write no entity (an empty group, or one whose objects are all hidden or left out) writes no block or INSERT; the drawing reads back with the same art bounds (`groups_are_blocks_placed_by_inserts_in_every_version`, `blocks_read_back_at_the_place_their_group_was`, `group_blocks_write_a_group_as_an_insert`). Behavior reference: [Export artwork, AutoCAD export options](https://helpx.adobe.com/illustrator/using/exporting-artwork.html).
|
||||
- DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build returns an error that says to save the drawing as DXF. A drawing of a DWG version the converter does not read (R1.0 to R9, an R10 drawing marked `AD1006`, a code the reader does not list such as `AC1010`, or a code newer than 2018's `AC1032`) returns an error that names its version and says to save it as DXF or as a DWG from R10 to 2018 (`a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as`). DWG is not written: Export As keeps it greyed out, exporting to it says to export DXF, and Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged).
|
||||
- DWG drawings open and place in the desktop build, and `document.dxfInfo` reads them: craft-dwg converts the drawing to DXF, in a copy of the app started with `--dwg-worker`, off the UI thread when the user opens or places it, and the DXF reader reads it with the DXF Import Options. The web build returns an error that says to save the drawing as DXF. A drawing of a DWG version the converter does not read (R1.0 to R9, an R10 drawing marked `AD1006`, a code the reader does not list such as `AC1010`, or a code newer than 2018's `AC1032`) returns an error that names its version and says to save it as DXF or as a DWG from R10 to 2018 (`a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as`). Save over the drawing is refused (`a_dwg_drawing_comes_in_as_its_dxf_does`, `document_open_reads_a_dwg_drawing_as_its_dxf`, `dxf_info_and_place_read_a_dwg`, `a_dwg_opened_is_never_written_back_as_dwg`; scores and estimates unchanged).
|
||||
- DWG export (https://helpx.adobe.com/illustrator/using/supported-file-formats.html, https://helpx.adobe.com/illustrator/using/exporting-artwork.html): Export As → DWG, `document.export {format: dwg}` and a script's `AutoCADExportFileFormat.DWG` write the drawing the DXF export writes as a DWG file of version 2000, 2004, 2007, 2010, 2013 or 2018, converted by craft-dwg in the `--dwg-worker` copy of the app, in the desktop app and `vectorcraft-cli`. The web build can't write DWG, and these paths return an error there. DWG Options is DXF Options with those versions; R12, R13 and R14 are refused with an error that names them. Records the DWG writer can't write in the chosen version are left out with a warning (`document_export_writes_a_dwg_that_opens_as_the_drawing_its_dxf_holds`, `a_dwg_version_before_2000_is_refused_and_nothing_is_written`, `export_as_dwg_shows_dwg_options_then_writes_a_dwg`, `an_autocad_export_writes_a_dwg_or_a_dxf_with_its_options`; scores and estimates unchanged).
|
||||
- `.dws` drawing standards files and `.dwt` drawing templates, which are DWG files, open and place as DWG drawings, are listed in the open and place dialogs, and go through the DXF Import Options; a `.dwt` opens as a new untitled document (`a_dwt_template_opens_untitled_and_a_dws_opens_as_its_drawing`, `a_dwt_or_dws_drawing_places_as_a_dwg_does`, `dwt_and_dws_are_read_only_and_exporting_them_says_to_write_dxf`; scores and estimates unchanged).
|
||||
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md).
|
||||
- `.cdr` drawings of versions 1 to 27 open and place, and `.cdt` templates open as new untitled documents. `craft-cdr` reads the `WL` files of versions 1 and 2 (one page and one layer of rectangles, whole ellipses and curves with uniform fills and outlines), the RIFF chunk tree of versions 3 on and its compressed lists, and the ZIP packages of versions 14 on with the data streams of versions 16 on, and the importer maps pages to artboards side by side, layers by name, the master page's guidelines to guides on every page, groups, clipping containers (as clipping groups), curves and paths, rectangles (live, with each corner's radius), ellipses (live), arcs and polygons, uniform fills in CMYK, CMY, RGB, gray and registration, and outlines with their width (0.25 pt for a width of 0), caps, joins and dashes (behind the fill, or scaled with the object's matrix, where the file says so), an object without a fill or outline of its own taking its style's, hidden and locked layers, groups and objects, the winding flag as the nonzero fill rule, and a uniform transparency of version 13 and later as the object's opacity and blend mode. A library color stored with its name and values (version 13 and later, in a fill or an outline) becomes a spot swatch with its tint; one stored only by its number opens as a black spot color named by its palette and number, with a warning. Text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills, arrowheads, lenses, other transparency and the envelopes of version 3 are left out with a warning, and encrypted, ZIP64 and split packages are refused with a message. Every record layout has a source in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`). Reading is bounded by limits on input size, inflated size, package members, nesting, chunks, objects, coordinates and dashes, where an outline's dashes count for every shape that uses it (`craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs`, `crates/engine/tests/import_fuzz.rs`).
|
||||
|
||||
@@ -18,7 +18,7 @@ _spec = importlib.util.spec_from_file_location("clear", Path(__file__).with_name
|
||||
clear = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(clear)
|
||||
|
||||
WARM = "gate / cache warm (ubuntu-24.04)"
|
||||
WARM = "gate / build (ubuntu-24.04)"
|
||||
ME = [{"name": "cold cache clear", "status": "in_progress"}]
|
||||
|
||||
|
||||
@@ -166,8 +166,10 @@ class Workflow(unittest.TestCase):
|
||||
|
||||
class Jobs(unittest.TestCase):
|
||||
def test_only_the_warm_leg_counts(self):
|
||||
jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}]
|
||||
self.assertEqual(clear.warm_job(jobs), jobs[2])
|
||||
jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"},
|
||||
{"name": "gate / cache warm (ubuntu-24.04)"}, {"name": WARM}]
|
||||
self.assertEqual(clear.warm_job(jobs), jobs[3])
|
||||
self.assertIsNone(clear.warm_job(jobs[:3]))
|
||||
|
||||
def test_a_rerun_of_failed_jobs_skips_a_leg_that_succeeded(self):
|
||||
grace = clear.RERUN_GRACE_SECONDS
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
The cold run (ci.yml, `cold-build`) never restores the rolling entry, so the old one only adds to
|
||||
the cache while the new one is saved: two entries of about 4.6 GB each, beside the others, go over
|
||||
the repository's 10 GB limit and GitHub evicts the corpus, SonarCloud and Windows ARM64 entries. The
|
||||
gate's `cache warm` leg saves in its `Post Setup` step; this deletes the old entries when that step
|
||||
gate's `build` leg saves in its `Post Setup` step; this deletes the old entries when that step
|
||||
starts, then waits for the step to finish. Pull requests and pushes that start in the minutes
|
||||
between restore nothing from the deleted entry and build cold once. Deleting is the only write; the
|
||||
entry the cold run saves does not exist yet when this runs. Only entries created before this run
|
||||
@@ -35,7 +35,9 @@ import sys
|
||||
import time
|
||||
|
||||
REF = 'refs/heads/main'
|
||||
WARM_JOB = re.compile(r'^gate / cache warm \(')
|
||||
# The leg that saves the rolling entry: the gate's `build` job (ci.yml's `archive-command`). While
|
||||
# the job is skipped, GitHub lists it as `gate / build (${{ matrix.os }})`.
|
||||
WARM_JOB = re.compile(r'^gate / build \((?!\$\{\{)')
|
||||
SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(')
|
||||
# The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of
|
||||
# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the
|
||||
@@ -64,8 +66,8 @@ START_SECONDS = 180 * 60
|
||||
STOPPED = ('failure', 'cancelled', 'timed_out')
|
||||
# Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml.
|
||||
TOLERATED_FAILURES = ('Trim the cache entry to this build',)
|
||||
NO_SAVE = 'the cache warm leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg'
|
||||
SAVE_LOST = 'the cache warm leg did not finish its save after the old rolling entries were deleted; the next run starts cold'
|
||||
NO_SAVE = 'the build leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg'
|
||||
SAVE_LOST = 'the build leg did not finish its save after the old rolling entries were deleted; the next run starts cold'
|
||||
|
||||
|
||||
def save_step(job):
|
||||
@@ -194,7 +196,7 @@ def main():
|
||||
job = warm_job(jobs.get('jobs', []))
|
||||
ready = start_wait_began(jobs.get('jobs', []), began)
|
||||
if started_late(job, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
print(f'::error::the build leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if job and saving(job):
|
||||
break
|
||||
@@ -206,7 +208,7 @@ def main():
|
||||
if warm_job(earlier_jobs[earlier]) is not None:
|
||||
break
|
||||
if not_in_attempt(jobs.get('jobs', []), earlier_jobs, (datetime.now(timezone.utc) - began).total_seconds()):
|
||||
print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted')
|
||||
print('the build leg is not part of this attempt (it succeeded in an earlier one); nothing deleted')
|
||||
return
|
||||
if legs_stopped(jobs.get('jobs', [])):
|
||||
print('::error::the gate stopped before its cache warm leg started; nothing deleted')
|
||||
@@ -216,14 +218,14 @@ def main():
|
||||
if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])):
|
||||
print(f'::error::{NO_SAVE}')
|
||||
return 1
|
||||
print('the cache warm leg finished without a save step; nothing deleted')
|
||||
print('the build leg finished without a save step; nothing deleted')
|
||||
return
|
||||
now = datetime.now(timezone.utc)
|
||||
if start_overdue(job, now, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
print(f'::error::the build leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if gave_up(job, now):
|
||||
print('::error::the cache warm leg never reached its save; nothing deleted')
|
||||
print('::error::the build leg never reached its save; nothing deleted')
|
||||
return 1
|
||||
time.sleep(POLL_SECONDS)
|
||||
if saves_nothing(job):
|
||||
@@ -249,7 +251,7 @@ def main():
|
||||
if saves_nothing(job):
|
||||
print(f'::error::{SAVE_LOST}')
|
||||
return 1
|
||||
print('the cache warm leg saved its entry')
|
||||
print('the build leg saved its entry')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! In a gate leg that saves the dependency cache, craft-common-actions' `rust-cache` action names a
|
||||
//! file in `CRAFT_CACHE_UNITS`, and its `cache-trim` action deletes every build unit of the target
|
||||
//! directory that the file does not name before the entry is saved. Cargo prints a JSON message for
|
||||
//! every unit a build compiled or found fresh. The builds of `cargo xtask ci warm` append those
|
||||
//! every unit a build compiled or found fresh. The builds of `cargo xtask ci archive` append those
|
||||
//! messages to the file, so the saved entry holds this build and no older builds of updated
|
||||
//! dependencies. Without `CRAFT_CACHE_UNITS` the commands run as they always have.
|
||||
|
||||
|
||||
+263
-174
@@ -50,11 +50,14 @@ commands:
|
||||
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker
|
||||
test the workspace tests (cargo nextest when installed, else cargo test), then the doctests
|
||||
ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, grant-sites, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure)
|
||||
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs
|
||||
the tests and doctests of its crates, the last shard the other steps
|
||||
ci warm build what every shard builds, without running it (fills the gate's cache); with
|
||||
GATE_SHARD of GATE_SHARDS set, only what that shard builds; with
|
||||
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file
|
||||
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci's tests (xtask/src/shards.rs): from the
|
||||
nextest archive in $NEXTEST_ARCHIVE_FILE when set, otherwise it builds them and
|
||||
also runs the doctests of its crates
|
||||
ci archive build every shard's tests once and write shard k's nextest archive to
|
||||
$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME for k from 1 to $GATE_SHARDS; with
|
||||
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for the build to that file
|
||||
ci doctests the doctests of each shard's crates, one cargo command per shard
|
||||
ci checks the ci steps other than the tests, the doctests and the i18n report
|
||||
shards list the crates each shard tests; fails when a member is in no shard or in two,
|
||||
or builds with other features in its shard than in the whole workspace
|
||||
corpus [--download | --affinity | --scripts]
|
||||
@@ -95,7 +98,9 @@ fn main() -> ExitCode {
|
||||
Some("wasm") => cmd_wasm(),
|
||||
Some("test") => cmd_test().and_then(|()| cmd_doctests()),
|
||||
Some("ci") if rest.first() == Some(&"shard") => cmd_ci_shard(),
|
||||
Some("ci") if rest.first() == Some(&"warm") => cmd_ci_warm(),
|
||||
Some("ci") if rest.first() == Some(&"archive") => cmd_ci_archive(),
|
||||
Some("ci") if rest.first() == Some(&"doctests") => cmd_ci_doctests(),
|
||||
Some("ci") if rest.first() == Some(&"checks") => cmd_ci_checks(),
|
||||
Some("ci") => cmd_ci(),
|
||||
Some("shards") => shards::run().map(drop),
|
||||
Some("corpus") => cmd_corpus_args(&rest),
|
||||
@@ -288,46 +293,62 @@ fn cmd_test() -> Result<(), String> {
|
||||
/// which needs nextest. A part runs its counted share, then its pinned tests, each with
|
||||
/// nextest's default thread count. Every run finishes before the first error is returned.
|
||||
fn test_packages(select: &[String], shown: &str, targets: shards::Targets, part: Option<shards::Part>) -> Result<(), String> {
|
||||
let (listed, targets) = (targets.shown(), targets.args());
|
||||
if let Some(part) = part {
|
||||
if !has_nextest() {
|
||||
return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest"));
|
||||
}
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(targets);
|
||||
let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("cargo nextest list {shown}: exited with {}", out.status));
|
||||
}
|
||||
let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?;
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)",
|
||||
missing.join(", ")
|
||||
));
|
||||
}
|
||||
let command = |args: Vec<String>| {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "run"]).args(select).args(targets).args(&args);
|
||||
let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" ");
|
||||
(c, format!("cargo nextest run {shown} {listed} {quoted}"))
|
||||
};
|
||||
let mut result = Ok(());
|
||||
for args in part.runs() {
|
||||
let (c, what) = command(args);
|
||||
result = result.and(run(c, &what));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
let mut c = cargo();
|
||||
if has_nextest() {
|
||||
c.args(["nextest", "run"]).args(select).args(targets);
|
||||
run(c, &format!("cargo nextest run {shown} {listed}"))
|
||||
} else {
|
||||
let (listed, args) = (targets.shown(), targets.args());
|
||||
if part.is_none() && !has_nextest() {
|
||||
eprintln!("note: cargo-nextest is not installed; running cargo test (cargo install cargo-nextest for faster runs)");
|
||||
c.arg("test").args(select).args(targets);
|
||||
run(c, &format!("cargo test {shown} {listed}"))
|
||||
let mut c = cargo();
|
||||
c.arg("test").args(select).args(args);
|
||||
return run(c, &format!("cargo test {shown} {listed}"));
|
||||
}
|
||||
let nextest = |sub: &str| {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", sub]).args(select).args(args);
|
||||
c
|
||||
};
|
||||
nextest_tests(&nextest, &format!("{shown} {listed}"), part)
|
||||
}
|
||||
|
||||
/// The tests of the nextest archive `file`, which `cargo xtask ci archive` wrote for one shard;
|
||||
/// with `part`, that part's share of them, as [`test_packages`] runs it.
|
||||
fn archive_tests(file: &Path, part: Option<shards::Part>) -> Result<(), String> {
|
||||
let nextest = |sub: &str| {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", sub, "--archive-file"]).arg(file).arg("--workspace-remap").arg(root());
|
||||
c
|
||||
};
|
||||
nextest_tests(&nextest, &format!("--archive-file {}", file.display()), part)
|
||||
}
|
||||
|
||||
/// The tests `nextest(sub)` selects for `cargo nextest <sub>`, shown after the subcommand as
|
||||
/// `shown`; with `part`, only that part's share of them (see [`test_packages`]).
|
||||
fn nextest_tests(nextest: &dyn Fn(&str) -> Command, shown: &str, part: Option<shards::Part>) -> Result<(), String> {
|
||||
if !has_nextest() {
|
||||
return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests, or runs an archive, needs cargo-nextest"));
|
||||
}
|
||||
let Some(part) = part else {
|
||||
return run(nextest("run"), &format!("cargo nextest run {shown}"));
|
||||
};
|
||||
let mut c = nextest("list");
|
||||
c.args(["--color", "never", "--message-format", "json"]);
|
||||
let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!("cargo nextest list {shown}: exited with {}", out.status));
|
||||
}
|
||||
let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?;
|
||||
if !missing.is_empty() {
|
||||
return Err(format!(
|
||||
"cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)",
|
||||
missing.join(", ")
|
||||
));
|
||||
}
|
||||
let mut result = Ok(());
|
||||
for args in part.runs() {
|
||||
let mut c = nextest("run");
|
||||
c.args(&args);
|
||||
let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::<Vec<_>>().join(" ");
|
||||
result = result.and(run(c, &format!("cargo nextest run {shown} {quoted}")));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The doctests, which nextest doesn't run.
|
||||
@@ -350,7 +371,8 @@ fn doctest_packages(crates: &[shards::Member]) -> Result<(), String> {
|
||||
/// One `cargo xtask ci` step: its name and what it runs.
|
||||
type Step = (&'static str, Box<dyn Fn() -> Result<(), String>>);
|
||||
|
||||
/// The `ci` steps that build and run tests of the whole workspace; `ci shard` runs them per shard.
|
||||
/// The `ci` steps that build and run tests of the whole workspace; `ci shard` runs them per shard,
|
||||
/// and `ci checks` runs the other steps.
|
||||
const TEST_STEPS: [&str; 3] = ["test", "doctests", "i18n-report"];
|
||||
|
||||
/// `cargo xtask ci`: each step in turn, stopping at the first that fails; the summary names the
|
||||
@@ -359,152 +381,180 @@ fn cmd_ci() -> Result<(), String> {
|
||||
run_steps(&ci_steps())
|
||||
}
|
||||
|
||||
/// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate
|
||||
/// workflow sets them). A test shard runs the shard checks, then the tests and doctests of its
|
||||
/// crates, and the i18n report where it tests vectorcraft-ui-egui; a part of a split runs its
|
||||
/// share of the tests, and only part 1 the doctests and the report. The checks shard runs every
|
||||
/// other `ci` step and the shard checks.
|
||||
fn cmd_ci_shard() -> Result<(), String> {
|
||||
let number = |key: &str| -> Result<usize, String> {
|
||||
let value = std::env::var(key).map_err(|_| format!("ci shard: {key} is not set (the gate workflow sets it)"))?;
|
||||
value.trim().parse().map_err(|_| format!("ci shard: {key} is `{value}`, not a number"))
|
||||
};
|
||||
let (shard, count) = (number("GATE_SHARD")?, number("GATE_SHARDS")?);
|
||||
/// `GATE_SHARDS`, the shard count the shared gate workflow sets, for `ci <what>`; it must equal
|
||||
/// the number of shards in xtask/src/shards.rs.
|
||||
fn gate_shards(what: &str) -> Result<usize, String> {
|
||||
let count = gate_number(what, "GATE_SHARDS")?;
|
||||
if count != shards::GROUPS.len() {
|
||||
return Err(format!(
|
||||
"ci shard: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
"ci {what}: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
shards::GROUPS.len()
|
||||
));
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The number in the environment variable `key`, which the shared gate workflow sets.
|
||||
fn gate_number(what: &str, key: &str) -> Result<usize, String> {
|
||||
let value = std::env::var(key).map_err(|_| format!("ci {what}: {key} is not set (the gate workflow sets it)"))?;
|
||||
value.trim().parse().map_err(|_| format!("ci {what}: {key} is `{value}`, not a number"))
|
||||
}
|
||||
|
||||
/// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate
|
||||
/// workflow sets them). A shard runs the tests of its crates, and the i18n report where it tests
|
||||
/// vectorcraft-ui-egui; a part of a split runs its share of the tests, and only part 1 the report.
|
||||
///
|
||||
/// With `NEXTEST_ARCHIVE_FILE` set (the gate's shard legs), it runs the tests of that archive,
|
||||
/// which `ci archive` built for this shard after the shard checks, and leaves the doctests to
|
||||
/// `ci doctests`. Otherwise it runs the shard checks, builds the tests, and runs the doctests of
|
||||
/// its crates on part 1 too.
|
||||
fn cmd_ci_shard() -> Result<(), String> {
|
||||
let count = gate_shards("shard")?;
|
||||
let shard = gate_number("shard", "GATE_SHARD")?;
|
||||
if !(1..=count).contains(&shard) {
|
||||
return Err(format!("ci shard: GATE_SHARD is {shard}, not 1 to {count}"));
|
||||
}
|
||||
let checked = shards::run()?;
|
||||
let archive = std::env::var_os("NEXTEST_ARCHIVE_FILE").filter(|f| !f.is_empty()).map(PathBuf::from);
|
||||
let shards::Shard { runs, part } = if archive.is_some() { shards::assigned()? } else { shards::run()? }.swap_remove(shard - 1);
|
||||
let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default();
|
||||
eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(&runs));
|
||||
let first = part.is_none_or(|p| p.is_first());
|
||||
let report =
|
||||
runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui")).filter(|_| first);
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
match &checked[shard - 1] {
|
||||
shards::Shard::Tests(runs, part) => {
|
||||
let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default();
|
||||
eprintln!("ci shard {shard}/{count}: the tests of {}{share}", shards::describe(runs));
|
||||
let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
|
||||
let part = *part;
|
||||
let tests: Vec<(Vec<String>, String, shards::Targets)> =
|
||||
runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect();
|
||||
// Each run finishes before the first error is returned.
|
||||
steps.push((
|
||||
"test",
|
||||
Box::new(move || {
|
||||
let mut result = Ok(());
|
||||
for (s, w, t) in &tests {
|
||||
result = result.and(test_packages(s, w, *t, part));
|
||||
}
|
||||
result
|
||||
}),
|
||||
));
|
||||
// The doctests and the i18n report run once, on a split's first part.
|
||||
let first = part.is_none_or(|p| p.is_first());
|
||||
if first {
|
||||
let c = shards::unit_crates(runs);
|
||||
steps.push(("doctests", Box::new(move || doctest_packages(&c))));
|
||||
}
|
||||
let all = runs.iter().find(|r| r.targets == shards::Targets::All && r.crates.iter().any(|m| m.name == "vectorcraft-ui-egui"));
|
||||
if let Some(r) = all.filter(|_| first) {
|
||||
let (select, shown) = (shards::select(&r.crates), shown(&r.crates));
|
||||
steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown))));
|
||||
}
|
||||
}
|
||||
shards::Shard::Checks => {
|
||||
eprintln!("ci shard {shard}/{count}: the ci steps other than the tests");
|
||||
steps.extend(ci_steps().into_iter().filter(|(name, _)| !TEST_STEPS.contains(name)));
|
||||
if let Some(file) = archive {
|
||||
let tests = file.clone();
|
||||
steps.push(("test", Box::new(move || archive_tests(&tests, part))));
|
||||
if report.is_some() {
|
||||
steps.push(("i18n-report", Box::new(move || i18n_report_archive(&file))));
|
||||
}
|
||||
return run_steps(&steps);
|
||||
}
|
||||
let shown = |crates: &[shards::Member]| crates.iter().map(|m| format!("-p {}", m.name)).collect::<Vec<_>>().join(" ");
|
||||
let report = report.map(|r| (shards::select(&r.crates), shown(&r.crates)));
|
||||
let tests: Vec<(Vec<String>, String, shards::Targets)> = runs.iter().map(|r| (shards::select(&r.crates), shown(&r.crates), r.targets)).collect();
|
||||
// Each run finishes before the first error is returned.
|
||||
steps.push((
|
||||
"test",
|
||||
Box::new(move || {
|
||||
let mut result = Ok(());
|
||||
for (s, w, t) in &tests {
|
||||
result = result.and(test_packages(s, w, *t, part));
|
||||
}
|
||||
result
|
||||
}),
|
||||
));
|
||||
// The doctests and the i18n report run once, on a split's first part.
|
||||
if first {
|
||||
let c = shards::unit_crates(&runs);
|
||||
steps.push(("doctests", Box::new(move || doctest_packages(&c))));
|
||||
}
|
||||
if let Some((select, shown)) = report {
|
||||
steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown))));
|
||||
}
|
||||
run_steps(&steps)
|
||||
}
|
||||
|
||||
/// `cargo xtask ci warm`: for each test shard, builds the library and binary tests of the crates
|
||||
/// it tests without running them, then builds what the checks shard builds, so one
|
||||
/// dependency-cache entry holds the dependencies of every shard with the features that shard builds
|
||||
/// them with (cargo resolves features over the packages each command selects). It does not build
|
||||
/// the integration tests ([`warm_runs`], [`warm_tests`]), which take the same dependencies and
|
||||
/// dev-dependencies as the library tests. Cargo warns `unused dependency vectorcraft-testkit` for
|
||||
/// vectorcraft-cli, whose integration tests are the only ones that use it.
|
||||
/// `cargo xtask ci archive`: the shared gate's `build` job (`archive-command` with
|
||||
/// `shard-archives`). After the shard checks it builds the tests of each shard's run, one cargo
|
||||
/// command per run ([`archive_builds`]), then writes the tests of shard k's run (1-based,
|
||||
/// [`archived_runs`]) to the nextest archive `$NEXTEST_ARCHIVE_DIR/<k>/$NEXTEST_ARCHIVE_NAME` for
|
||||
/// every k up to `GATE_SHARDS`, with the run's package and target selection, so the archive's own
|
||||
/// build finds them built. A split's later parts run the same binaries as part 1, so their archive
|
||||
/// is a copy of part 1's.
|
||||
///
|
||||
/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that
|
||||
/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build
|
||||
/// nothing in either case, since part 1 builds the same tests.
|
||||
///
|
||||
/// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS`
|
||||
/// (xtask/src/cache_units.rs), xtask's own build included.
|
||||
fn cmd_ci_warm() -> Result<(), String> {
|
||||
let var = |key: &str| match std::env::var(key) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")),
|
||||
/// In a leg that saves the cache, the library and binary tests' builds record their units in
|
||||
/// `CRAFT_CACHE_UNITS` (xtask/src/cache_units.rs), xtask's own build included, and the
|
||||
/// integration tests' builds do not, so the saved entry holds every dependency and
|
||||
/// dev-dependency the tests build with and none of the integration tests' executables.
|
||||
fn cmd_ci_archive() -> Result<(), String> {
|
||||
let var = |key: &str| {
|
||||
std::env::var(key).ok().filter(|v| !v.is_empty()).ok_or_else(|| format!("ci archive: {key} is not set (the gate workflow sets it)"))
|
||||
};
|
||||
let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?);
|
||||
let only = shards::warm_only(shard.as_deref(), count.as_deref())?;
|
||||
let (dir, name) = (PathBuf::from(var("NEXTEST_ARCHIVE_DIR")?), var("NEXTEST_ARCHIVE_NAME")?);
|
||||
gate_shards("archive")?;
|
||||
if !has_nextest() {
|
||||
return Err("ci archive: cargo-nextest is not installed".into());
|
||||
}
|
||||
cache_units::record_xtask()?;
|
||||
let checked = shards::run()?;
|
||||
let (tests, checks) = shards::warm_plan(&checked, only);
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
for i in tests {
|
||||
if let shards::Shard::Tests(runs, _) = checked[i].clone() {
|
||||
for r in warm_runs(runs) {
|
||||
steps.push((
|
||||
"build tests",
|
||||
Box::new(move || {
|
||||
let (c, what) = warm_tests(&r);
|
||||
cache_units::run(c, &what)
|
||||
}),
|
||||
));
|
||||
}
|
||||
let archived = archived_runs(&checked)?;
|
||||
for (units, r) in archive_builds(&checked) {
|
||||
let (c, what) = test_build(&r, units);
|
||||
if units { cache_units::run(c, &what)? } else { run(c, &what)? }
|
||||
}
|
||||
for (i, (shard, r)) in checked.iter().zip(archived).enumerate() {
|
||||
let file = dir.join((i + 1).to_string()).join(&name);
|
||||
let parent = file.parent().unwrap_or(&dir);
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("ci archive: {}: {e}", parent.display()))?;
|
||||
if let Some(p) = shard.part.filter(|p| !p.is_first()) {
|
||||
let first = dir.join((i + 2 - p.index).to_string()).join(&name);
|
||||
std::fs::hard_link(&first, &file)
|
||||
.or_else(|_| std::fs::copy(&first, &file).map(drop))
|
||||
.map_err(|e| format!("ci archive: copy {} to {}: {e}", first.display(), file.display()))?;
|
||||
eprintln!("ci archive: shard {} runs part {} of shard {}'s archive", i + 1, p.index, i + 2 - p.index);
|
||||
continue;
|
||||
}
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "archive"]).args(shards::select(&r.crates)).args(r.targets.args()).arg("--archive-file").arg(&file);
|
||||
let what = format!("cargo nextest archive {} ({}) --archive-file {}", r.targets.shown(), shards::names(&r.crates), file.display());
|
||||
run(c, &what)?;
|
||||
}
|
||||
if checks {
|
||||
push_warm_checks(&mut steps);
|
||||
}
|
||||
run_steps(&steps)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The builds of the checks shard that [`cmd_ci_warm`] runs.
|
||||
fn push_warm_checks(steps: &mut Vec<Step>) {
|
||||
steps.push((
|
||||
"clippy",
|
||||
Box::new(|| {
|
||||
let mut c = cargo();
|
||||
c.args(["clippy", "--workspace", "--all-targets", "--keep-going"]);
|
||||
cache_units::run(c, "cargo clippy --workspace --all-targets --keep-going")
|
||||
}),
|
||||
));
|
||||
steps.push((
|
||||
"no-bundled-fonts",
|
||||
Box::new(|| {
|
||||
let mut c = cargo();
|
||||
c.args(["test", "-p", "vectorcraft-text", "--no-default-features", "--test", "without_bundled_fonts", "--no-run"]);
|
||||
cache_units::run(c, "cargo test -p vectorcraft-text --no-default-features --test without_bundled_fonts --no-run")?;
|
||||
let mut c = cargo();
|
||||
c.args(["clippy", "-p", "vectorcraft-ui-egui", "--no-default-features", "--all-targets"]);
|
||||
cache_units::run(c, "cargo clippy -p vectorcraft-ui-egui --no-default-features --all-targets")?;
|
||||
let mut c = cargo();
|
||||
c.args(["test", "-p", "vectorcraft-ui-egui", "--no-default-features", "--test", "install_fonts", "--no-run"]);
|
||||
cache_units::run(c, "cargo test -p vectorcraft-ui-egui --no-default-features --test install_fonts --no-run")
|
||||
}),
|
||||
));
|
||||
steps.push(("wasm", Box::new(cmd_wasm)));
|
||||
/// The run of each shard, whose tests `ci archive` writes to the shard's archive with one cargo
|
||||
/// selection. A shard that makes more than one run is an error.
|
||||
fn archived_runs(shards: &[shards::Shard]) -> Result<Vec<&shards::Run>, String> {
|
||||
shards
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, s)| match s.runs.as_slice() {
|
||||
[r] => Ok(r),
|
||||
runs => Err(format!(
|
||||
"ci archive: shard {} makes {} runs, and its archive holds the tests of one (xtask/src/shards.rs › GROUPS)",
|
||||
i + 1,
|
||||
runs.len()
|
||||
)),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The runs of a test shard that `ci warm` builds: every run except an integration-test run, whose
|
||||
/// crate has its library tests in a run on another shard.
|
||||
fn warm_runs(runs: Vec<shards::Run>) -> impl Iterator<Item = shards::Run> {
|
||||
runs.into_iter().filter(|r| r.targets != shards::Targets::Integration)
|
||||
/// The builds `ci archive` runs before it writes the archives, in order: `(true, run)` builds the
|
||||
/// library and binary tests of a run of the first part of each shard (none for a run of
|
||||
/// integration tests alone, whose crate has its library tests in a run on another shard), then
|
||||
/// `(false, run)` builds each such run's integration tests.
|
||||
fn archive_builds(shards: &[shards::Shard]) -> Vec<(bool, shards::Run)> {
|
||||
let runs: Vec<&shards::Run> = shards.iter().filter(|s| s.part.is_none_or(|p| p.is_first())).flat_map(|s| &s.runs).collect();
|
||||
let units = runs.iter().filter(|r| r.targets != shards::Targets::Integration).map(|r| (true, (*r).clone()));
|
||||
let integration = runs.iter().filter(|r| r.targets != shards::Targets::Units).map(|r| (false, (*r).clone()));
|
||||
units.chain(integration).collect()
|
||||
}
|
||||
|
||||
/// The command `ci warm` builds the library and binary tests of one run of a test shard with, and
|
||||
/// its description.
|
||||
fn warm_tests(r: &shards::Run) -> (Command, String) {
|
||||
let units = shards::Targets::Units;
|
||||
/// The `cargo test --no-run` command that builds a run's library and binary tests (`units`) or its
|
||||
/// integration tests, and its description.
|
||||
fn test_build(r: &shards::Run, units: bool) -> (Command, String) {
|
||||
let targets = if units { shards::Targets::Units } else { shards::Targets::Integration };
|
||||
let mut c = cargo();
|
||||
c.arg("test").args(shards::select(&r.crates)).args(units.args()).arg("--no-run");
|
||||
(c, format!("cargo test {} --no-run ({})", units.shown(), shards::names(&r.crates)))
|
||||
c.arg("test").args(shards::select(&r.crates)).args(targets.args()).arg("--no-run");
|
||||
(c, format!("cargo test {} --no-run ({})", targets.shown(), shards::names(&r.crates)))
|
||||
}
|
||||
|
||||
/// `cargo xtask ci doctests`: the doctests of each shard's crates, one cargo command per shard
|
||||
/// with the crates `ci shard` runs them for, after `ci archive` (the shared gate's
|
||||
/// `after-archive-command`). Every command runs before the first error is returned.
|
||||
fn cmd_ci_doctests() -> Result<(), String> {
|
||||
let mut result = Ok(());
|
||||
for s in shards::assigned()?.iter().filter(|s| s.part.is_none_or(|p| p.is_first())) {
|
||||
result = result.and(doctest_packages(&shards::unit_crates(&s.runs)));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// `cargo xtask ci checks`: every `ci` step other than [`TEST_STEPS`], for the shared gate's
|
||||
/// `lint` leg.
|
||||
fn cmd_ci_checks() -> Result<(), String> {
|
||||
run_steps(&ci_steps().into_iter().filter(|(name, _)| !TEST_STEPS.contains(name)).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed
|
||||
@@ -651,22 +701,61 @@ fn i18n_report_packages(select: &[String], shown: &str) -> Result<(), String> {
|
||||
run(c, &format!("cargo test {shown} --lib --bins --tests -- i18n::tests::untranslated_report --exact --nocapture"))
|
||||
}
|
||||
|
||||
/// [`cmd_ci_i18n_report`] from the nextest archive `file` of a `ci shard` that tests
|
||||
/// vectorcraft-ui-egui.
|
||||
fn i18n_report_archive(file: &Path) -> Result<(), String> {
|
||||
let mut c = cargo();
|
||||
c.args(["nextest", "run", "--archive-file"]).arg(file).arg("--workspace-remap").arg(root());
|
||||
c.args(["--no-capture", "-E", "test(=i18n::tests::untranslated_report)"]);
|
||||
run(c, &format!("cargo nextest run --archive-file {} --no-capture -E 'test(=i18n::tests::untranslated_report)'", file.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shards::{Group, Split, Targets};
|
||||
|
||||
#[test]
|
||||
fn warm_builds_library_and_binary_tests_without_integration_tests() {
|
||||
fn the_archive_builds_each_run_once_library_tests_first() {
|
||||
let m =
|
||||
|name: &str| shards::Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true };
|
||||
let args = |r: &shards::Run| warm_tests(r).0.get_args().map(|a| a.to_string_lossy().into_owned()).collect::<Vec<String>>();
|
||||
let all = shards::Run::all(vec![m("a")]);
|
||||
assert_eq!(args(&all), ["test", "-p", "path+file:///w/a#0.1.0", "--lib", "--bins", "--no-run"]);
|
||||
assert_eq!(warm_tests(&all).1, "cargo test --lib --bins --no-run (a)");
|
||||
let units = shards::Run { targets: shards::Targets::Units, crates: vec![m("b")] };
|
||||
assert_eq!(args(&units), ["test", "-p", "path+file:///w/b#0.1.0", "--lib", "--bins", "--no-run"]);
|
||||
let integration = shards::Run { targets: shards::Targets::Integration, crates: vec![m("b")] };
|
||||
let built: Vec<shards::Run> = warm_runs(vec![all.clone(), integration, units.clone()]).collect();
|
||||
assert_eq!(built, [all, units]);
|
||||
static SPLIT: Split = Split { crates: &["a"], pinned: &[&[], &[]] };
|
||||
let groups = [
|
||||
Group::Part(&SPLIT, 1),
|
||||
Group::Part(&SPLIT, 2),
|
||||
Group::Targets(&[(Targets::Units, &["b"])]),
|
||||
Group::Targets(&[(Targets::All, &["c"]), (Targets::Integration, &["b"])]),
|
||||
Group::Rest,
|
||||
];
|
||||
let shards = shards::assign(&groups, &[m("a"), m("b"), m("c"), m("d")]).unwrap();
|
||||
let builds: Vec<(Vec<String>, String)> = archive_builds(&shards)
|
||||
.iter()
|
||||
.map(|(units, r)| {
|
||||
let (c, what) = test_build(r, *units);
|
||||
(c.get_args().map(|a| a.to_string_lossy().into_owned()).collect(), what)
|
||||
})
|
||||
.collect();
|
||||
let shown: Vec<&str> = builds.iter().map(|(_, what)| what.as_str()).collect();
|
||||
assert_eq!(
|
||||
shown,
|
||||
[
|
||||
"cargo test --lib --bins --no-run (a)",
|
||||
"cargo test --lib --bins --no-run (b)",
|
||||
"cargo test --lib --bins --no-run (c)",
|
||||
"cargo test --lib --bins --no-run (d)",
|
||||
"cargo test --test '*' --no-run (a)",
|
||||
"cargo test --test '*' --no-run (c)",
|
||||
"cargo test --test '*' --no-run (b)",
|
||||
"cargo test --test '*' --no-run (d)",
|
||||
]
|
||||
);
|
||||
assert_eq!(builds[1].0, ["test", "-p", "path+file:///w/b#0.1.0", "--lib", "--bins", "--no-run"]);
|
||||
assert_eq!(builds[6].0, ["test", "-p", "path+file:///w/b#0.1.0", "--test", "*", "--no-run"]);
|
||||
let two = archived_runs(&shards).unwrap_err();
|
||||
assert!(two.contains("shard 4 makes 2 runs"), "{two}");
|
||||
let real = shards::assigned().unwrap();
|
||||
let archived = archived_runs(&real).unwrap();
|
||||
assert_eq!(archived.len(), shards::GROUPS.len());
|
||||
assert!(archived.iter().zip(&real).all(|(r, s)| s.runs == [(*r).clone()]));
|
||||
}
|
||||
}
|
||||
+45
-161
@@ -2,10 +2,12 @@
|
||||
//! gate workflow): which workspace crates each shard tests, and the checks that keep the split
|
||||
//! complete.
|
||||
//!
|
||||
//! Each test shard builds and runs the tests of its own crates and what they depend on. The last
|
||||
//! shard runs the `cargo xtask ci` steps that are not tests. [`GROUPS`] names the crates of the
|
||||
//! first shards; every other workspace member goes to the [`Group::Rest`] shard, so a new crate is
|
||||
//! tested without a change here. [`check`] fails when a named crate is not a workspace member or
|
||||
//! In CI the gate's `build` job builds every shard's tests once and writes one nextest archive per
|
||||
//! shard (`cargo xtask ci archive`), and each shard runs its tests from its archive. Without an archive a shard builds and runs the tests of its own crates and what they
|
||||
//! depend on. The `cargo xtask ci` steps that are not tests run in the gate's `lint` leg
|
||||
//! (`cargo xtask ci checks`). [`GROUPS`] names the crates of the first shards; every other
|
||||
//! workspace member goes to the [`Group::Rest`] shard, so a new crate is tested without a change
|
||||
//! here. [`check`] fails when a named crate is not a workspace member or
|
||||
//! is named twice, when a group is empty, and when a crate's features in its shard differ from
|
||||
//! its features in `cargo test --workspace`. Cargo resolves features over the packages a command
|
||||
//! selects, so a feature that only another crate's dev-dependencies turn on is off in a shard
|
||||
@@ -37,8 +39,6 @@ pub enum Group {
|
||||
Targets(&'static [(Targets, &'static [&'static str])]),
|
||||
/// The tests of every workspace member no other group names.
|
||||
Rest,
|
||||
/// The `cargo xtask ci` steps that are not tests.
|
||||
Checks,
|
||||
}
|
||||
|
||||
/// The test targets a shard builds and runs for a crate.
|
||||
@@ -109,18 +109,14 @@ pub static UI_EGUI: Split = Split {
|
||||
};
|
||||
|
||||
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its
|
||||
/// `shard-members` names each shard's crates. vectorcraft-engine's integration tests run on
|
||||
/// shard 4, which already builds the engine library for the app crates.
|
||||
/// `shard-members` names each shard's crates. Each shard makes one run: `cargo xtask ci archive`
|
||||
/// writes a shard's archive with the run's package and target selection.
|
||||
pub const GROUPS: &[Group] = &[
|
||||
Group::Part(&UI_EGUI, 1),
|
||||
Group::Part(&UI_EGUI, 2),
|
||||
Group::Targets(&[(Targets::Units, &["vectorcraft-engine"])]),
|
||||
Group::Targets(&[
|
||||
(Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]),
|
||||
(Targets::Integration, &["vectorcraft-engine"]),
|
||||
]),
|
||||
Group::Targets(&[(Targets::All, &["vectorcraft-engine"])]),
|
||||
Group::Targets(&[(Targets::All, &["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"])]),
|
||||
Group::Rest,
|
||||
Group::Checks,
|
||||
];
|
||||
|
||||
/// A workspace member, as `cargo metadata` gives it.
|
||||
@@ -139,9 +135,9 @@ pub struct Member {
|
||||
|
||||
/// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Shard {
|
||||
Tests(Vec<Run>, Option<Part>),
|
||||
Checks,
|
||||
pub struct Shard {
|
||||
pub runs: Vec<Run>,
|
||||
pub part: Option<Part>,
|
||||
}
|
||||
|
||||
/// One test run of a shard: the given targets of these crates.
|
||||
@@ -286,7 +282,7 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String
|
||||
}
|
||||
vec![(Targets::All, split.crates)]
|
||||
}
|
||||
Group::Rest | Group::Checks => continue,
|
||||
Group::Rest => continue,
|
||||
};
|
||||
if lists.iter().all(|(_, names)| names.is_empty()) {
|
||||
return Err(format!("shard {} names no crates ({WHERE})", i + 1));
|
||||
@@ -326,25 +322,24 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result<Vec<Shard>, String
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, g)| match g {
|
||||
Group::Targets(lists) => Ok(Shard::Tests(
|
||||
lists
|
||||
Group::Targets(lists) => Ok(Shard {
|
||||
runs: lists
|
||||
.iter()
|
||||
.filter(|(_, names)| !names.is_empty())
|
||||
.map(|(targets, names)| Run { targets: *targets, crates: pick(&|m| names.contains(&m.name.as_str())) })
|
||||
.collect(),
|
||||
None,
|
||||
)),
|
||||
part: None,
|
||||
}),
|
||||
Group::Part(split, index) => {
|
||||
Ok(Shard::Tests(vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], Some(Part { split, index: *index })))
|
||||
Ok(Shard { runs: vec![Run::all(pick(&|m| split.crates.contains(&m.name.as_str())))], part: Some(Part { split, index: *index }) })
|
||||
}
|
||||
Group::Rest => {
|
||||
let rest = pick(&|m| !named.contains_key(m.name.as_str()));
|
||||
if rest.is_empty() {
|
||||
return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1));
|
||||
}
|
||||
Ok(Shard::Tests(vec![Run::all(rest)], None))
|
||||
Ok(Shard { runs: vec![Run::all(rest)], part: None })
|
||||
}
|
||||
Group::Checks => Ok(Shard::Checks),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -424,6 +419,13 @@ pub fn describe(runs: &[Run]) -> String {
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The shards of this workspace after the checks in [`assign`] alone. A shard that runs its tests
|
||||
/// from an archive uses it: the archive's build already ran [`check`], and `cargo tree` would
|
||||
/// first download every dependency.
|
||||
pub fn assigned() -> Result<Vec<Shard>, String> {
|
||||
assign(GROUPS, &members(&crate::metadata()?)?)
|
||||
}
|
||||
|
||||
/// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`].
|
||||
pub fn check() -> Result<Vec<Shard>, String> {
|
||||
// The shared gate runs only the shards that test a crate a pull request reaches, by these
|
||||
@@ -435,11 +437,9 @@ pub fn check() -> Result<Vec<Shard>, String> {
|
||||
let mut differences = Vec::new();
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
// Each run is its own cargo command, so cargo resolves features over that run's crates.
|
||||
if let Shard::Tests(runs, _) = shard {
|
||||
for r in runs {
|
||||
let alone = tree_features(&tree(&select(&r.crates))?, &members);
|
||||
differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone));
|
||||
}
|
||||
for r in &shard.runs {
|
||||
let alone = tree_features(&tree(&select(&r.crates))?, &members);
|
||||
differences.extend(feature_differences(i + 1, &r.crates, &workspace, &alone));
|
||||
}
|
||||
}
|
||||
if !differences.is_empty() {
|
||||
@@ -475,7 +475,6 @@ fn workflow_members(workflow: &str) -> Result<(), String> {
|
||||
lists.iter().filter(|(t, _)| *t != Targets::Integration).flat_map(|(_, c)| c.iter().copied()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
Group::Rest => "(rest)".to_owned(),
|
||||
Group::Checks => "(always)".to_owned(),
|
||||
})
|
||||
.collect();
|
||||
let found = shard_members(workflow);
|
||||
@@ -491,119 +490,17 @@ fn workflow_members(workflow: &str) -> Result<(), String> {
|
||||
pub fn run() -> Result<Vec<Shard>, String> {
|
||||
let shards = check()?;
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
match shard {
|
||||
Shard::Tests(runs, part) => {
|
||||
let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default();
|
||||
println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(runs))
|
||||
}
|
||||
Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()),
|
||||
}
|
||||
let share = shard.part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default();
|
||||
println!("shard {}/{}: tests of {}{share}", i + 1, shards.len(), describe(&shard.runs))
|
||||
}
|
||||
println!("OK: every workspace member is tested on one shard, with the features `cargo test --workspace` gives it.");
|
||||
Ok(shards)
|
||||
}
|
||||
|
||||
/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's
|
||||
/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one,
|
||||
/// a value that is not a number, a count other than the number of shards, or a shard out of range
|
||||
/// is an error.
|
||||
pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> {
|
||||
let (shard, count) = match (shard, count) {
|
||||
(None, None) => return Ok(None),
|
||||
(Some(shard), Some(count)) => (shard, count),
|
||||
_ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()),
|
||||
};
|
||||
let number =
|
||||
|key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) };
|
||||
let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?);
|
||||
if count != GROUPS.len() {
|
||||
return Err(format!(
|
||||
"ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
GROUPS.len()
|
||||
));
|
||||
}
|
||||
if !(1..=count).contains(&shard) {
|
||||
return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}"));
|
||||
}
|
||||
Ok(Some(shard - 1))
|
||||
}
|
||||
|
||||
/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it
|
||||
/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it
|
||||
/// builds that shard alone, and without it every shard. A split's later parts build nothing: they
|
||||
/// build the same tests as part 1, whose leg puts them in the cache.
|
||||
pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) {
|
||||
let mut tests = Vec::new();
|
||||
let mut checks = false;
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
if only.is_some_and(|k| k != i) {
|
||||
continue;
|
||||
}
|
||||
match shard {
|
||||
Shard::Checks => checks = true,
|
||||
Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {}
|
||||
Shard::Tests(..) => tests.push(i),
|
||||
}
|
||||
}
|
||||
(tests, checks)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warm_builds_every_shard_unless_the_gate_names_one() {
|
||||
let n = GROUPS.len().to_string();
|
||||
assert_eq!(warm_only(None, None), Ok(None));
|
||||
assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0)));
|
||||
assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1)));
|
||||
for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] {
|
||||
assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}");
|
||||
}
|
||||
let past = (GROUPS.len() + 1).to_string();
|
||||
assert!(warm_only(Some(&past), Some(&n)).is_err());
|
||||
assert!(warm_only(Some("1"), Some(&past)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_builds_each_shard_of_the_plan() {
|
||||
let ws = [m("a"), m("b")];
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(warm_plan(&shards, None), (vec![0, 2], true));
|
||||
assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false));
|
||||
assert_eq!(warm_plan(&shards, Some(1)), (vec![], false));
|
||||
assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false));
|
||||
assert_eq!(warm_plan(&shards, Some(3)), (vec![], true));
|
||||
// The real plan: every leg the gate names builds its own shard (a split's later part
|
||||
// builds nothing), and the legs together, like a full warm, build every crate's tests
|
||||
// once and the checks.
|
||||
let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap();
|
||||
let mut owned: Vec<&str> = real.iter().flat_map(owners).map(|(name, _)| name).collect();
|
||||
owned.sort_unstable();
|
||||
let (mut legs, mut leg_checks) = (Vec::new(), 0);
|
||||
for i in 0..GROUPS.len() {
|
||||
let n = GROUPS.len().to_string();
|
||||
let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap();
|
||||
let (tests, checks) = warm_plan(&real, only);
|
||||
let want = match &real[i] {
|
||||
Shard::Checks => (vec![], true),
|
||||
Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false),
|
||||
Shard::Tests(..) => (vec![i], false),
|
||||
};
|
||||
assert_eq!((tests.clone(), checks), want, "shard {}", i + 1);
|
||||
legs.extend(tests);
|
||||
leg_checks += usize::from(checks);
|
||||
}
|
||||
let (tests, checks) = warm_plan(&real, None);
|
||||
assert!(checks);
|
||||
assert_eq!(leg_checks, 1);
|
||||
assert_eq!(tests, legs);
|
||||
let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect();
|
||||
built.sort_unstable();
|
||||
assert_eq!(built, owned);
|
||||
}
|
||||
|
||||
fn m(name: &str) -> Member {
|
||||
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
|
||||
}
|
||||
@@ -626,20 +523,16 @@ mod tests {
|
||||
}
|
||||
|
||||
fn crates(shard: &Shard) -> Vec<&str> {
|
||||
match shard {
|
||||
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect(),
|
||||
Shard::Checks => Vec::new(),
|
||||
}
|
||||
shard.runs.iter().flat_map(|r| r.crates.iter().map(|m| m.name.as_str())).collect()
|
||||
}
|
||||
|
||||
/// Each crate a shard tests from the start, with the targets it runs: a part after the first
|
||||
/// runs a share of the same tests, so it is counted with part 1.
|
||||
fn owners(shard: &Shard) -> Vec<(&str, Targets)> {
|
||||
match shard {
|
||||
Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(),
|
||||
Shard::Tests(runs, _) => runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect(),
|
||||
Shard::Checks => Vec::new(),
|
||||
if shard.part.is_some_and(|p| !p.is_first()) {
|
||||
return Vec::new();
|
||||
}
|
||||
shard.runs.iter().flat_map(|r| r.crates.iter().map(|m| (m.name.as_str(), r.targets))).collect()
|
||||
}
|
||||
|
||||
/// The tests (binary ids and full names, in the order nextest lists them) that one `cargo nextest run` with
|
||||
@@ -685,9 +578,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_split_runs_on_its_parts_in_a_row() {
|
||||
let ws = [m("a"), m("b")];
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]);
|
||||
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("a")])], Some(Part { split: &SPLIT, index: 2 })));
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["a"], vec!["a"], vec!["b"]]);
|
||||
assert_eq!(shards[1], Shard { runs: vec![Run::all(vec![m("a")])], part: Some(Part { split: &SPLIT, index: 2 }) });
|
||||
let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err();
|
||||
assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}");
|
||||
let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err();
|
||||
@@ -755,9 +648,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_rest_shard_takes_every_crate_no_group_names() {
|
||||
let ws = [m("a"), m("b"), m("c"), m("d")];
|
||||
let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"], vec![]]);
|
||||
assert_eq!(shards[2], Shard::Checks);
|
||||
let shards = assign(&[Group::Targets(&[(Targets::All, &["c"])]), Group::Rest], &ws).unwrap();
|
||||
assert_eq!(shards.iter().map(crates).collect::<Vec<_>>(), [vec!["c"], vec!["a", "b", "d"]]);
|
||||
}
|
||||
|
||||
/// Every test target of `a`.
|
||||
@@ -768,18 +660,11 @@ mod tests {
|
||||
#[test]
|
||||
fn a_crate_s_units_and_integration_tests_run_on_two_shards() {
|
||||
let ws = [m("a"), m("b"), m("c")];
|
||||
let shards =
|
||||
assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(shards[0], Shard::Tests(vec![Run { targets: Targets::Units, crates: vec![m("a")] }], None));
|
||||
assert_eq!(shards[1], Shard::Tests(vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], None));
|
||||
let shards = assign(&[Group::Targets(&[UNITS]), Group::Targets(&[(Targets::All, &["b"]), INTEGRATION]), Group::Rest], &ws).unwrap();
|
||||
assert_eq!(shards[0], Shard { runs: vec![Run { targets: Targets::Units, crates: vec![m("a")] }], part: None });
|
||||
assert_eq!(shards[1], Shard { runs: vec![Run::all(vec![m("b")]), Run { targets: Targets::Integration, crates: vec![m("a")] }], part: None });
|
||||
assert_eq!(crates(&shards[2]), ["c"]);
|
||||
assert_eq!(
|
||||
unit_crates(match &shards[1] {
|
||||
Shard::Tests(r, _) => r,
|
||||
Shard::Checks => panic!("shard 2 is a test shard"),
|
||||
}),
|
||||
[m("b")]
|
||||
);
|
||||
assert_eq!(unit_crates(&shards[1].runs), [m("b")]);
|
||||
let half = assign(&[Group::Targets(&[UNITS]), Group::Rest], &ws).unwrap_err();
|
||||
assert!(half.contains("no shard runs its integration tests"), "{half}");
|
||||
let other_half = assign(&[Group::Targets(&[INTEGRATION]), Group::Rest], &ws).unwrap_err();
|
||||
@@ -833,7 +718,6 @@ mod tests {
|
||||
"`{name}` runs {targets:?}, not each test target once"
|
||||
);
|
||||
}
|
||||
assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user