mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 23:31:18 +00:00
Merge remote-tracking branch 'upstream/main' into fix-8538-locked-guides
# Conflicts: # docs/roadmap.md # docs/target-app-parity.md # docs/ui-parity.md
This commit is contained in:
@@ -74,6 +74,7 @@ pub mod perspgrid;
|
||||
pub mod place;
|
||||
pub mod plugin;
|
||||
pub(crate) mod plugin_call;
|
||||
mod preflight;
|
||||
pub mod prefscmds;
|
||||
pub mod print;
|
||||
pub(crate) mod printadvanced;
|
||||
@@ -382,6 +383,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(package::specs());
|
||||
v.extend(slices::specs());
|
||||
v.extend(print::specs());
|
||||
v.extend(preflight::specs());
|
||||
v.extend(recovery::specs());
|
||||
v.extend(fileio::dxfimport::specs());
|
||||
v.extend(webexport::specs());
|
||||
|
||||
@@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
|
||||
super::typecmd::export_overflow_warning(&overflow)
|
||||
}
|
||||
|
||||
/// The objects behind production findings. Resource art points to its first visible owner on
|
||||
/// the canvas, so a finding can be located without selecting an id outside the layer tree.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PreflightType {
|
||||
pub fonts: BTreeMap<UsedFont, BTreeSet<NodeId>>,
|
||||
pub overflow: BTreeSet<NodeId>,
|
||||
pub images: BTreeMap<NodeId, NodeId>,
|
||||
}
|
||||
|
||||
pub(super) fn preflight_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> PreflightType {
|
||||
let mut walk = Printed::new(d);
|
||||
walk.preflight = Some(PreflightType::default());
|
||||
for l in layers {
|
||||
walk.node(l, Some(areas));
|
||||
}
|
||||
walk.preflight.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The walk of [`printed_type`].
|
||||
struct Printed<'a> {
|
||||
d: &'a Document,
|
||||
@@ -546,13 +564,25 @@ struct Printed<'a> {
|
||||
/// The symbols and patterns whose art was walked.
|
||||
symbols: BTreeSet<String>,
|
||||
patterns: BTreeSet<String>,
|
||||
preflight: Option<PreflightType>,
|
||||
owner: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl<'a> Printed<'a> {
|
||||
/// A walk of `d` among its own objects, nothing found yet.
|
||||
fn new(d: &'a Document) -> Self {
|
||||
let boxes = d.symbol_boxes();
|
||||
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
|
||||
Self {
|
||||
d,
|
||||
boxes,
|
||||
own: true,
|
||||
fonts: BTreeSet::new(),
|
||||
overflow: BTreeSet::new(),
|
||||
symbols: BTreeSet::new(),
|
||||
patterns: BTreeSet::new(),
|
||||
preflight: None,
|
||||
owner: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
|
||||
@@ -560,6 +590,15 @@ impl<'a> Printed<'a> {
|
||||
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
|
||||
/// object) all of them but those outside the clipping path of a clip group.
|
||||
fn node(&mut self, n: &Node, areas: Option<&[Rect]>) {
|
||||
let previous = self.owner;
|
||||
if self.own {
|
||||
self.owner = Some(n.id);
|
||||
}
|
||||
self.node_contents(n, areas);
|
||||
self.owner = previous;
|
||||
}
|
||||
|
||||
fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) {
|
||||
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return;
|
||||
}
|
||||
@@ -571,6 +610,14 @@ impl<'a> Printed<'a> {
|
||||
&& !open
|
||||
&& !self.meets(n, a)
|
||||
{
|
||||
// An entirely overset frame paints nothing, but is still a delivery problem. Keep
|
||||
// the export walk unchanged; only preflight checks the frame itself in this case.
|
||||
if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind)
|
||||
&& n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b)))
|
||||
&& vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow
|
||||
{
|
||||
p.overflow.insert(owner);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The art that its opacity mask, pattern paints and brushed strokes draw.
|
||||
@@ -616,16 +663,33 @@ impl<'a> Printed<'a> {
|
||||
if overflows && self.own {
|
||||
self.overflow.insert(n.id);
|
||||
}
|
||||
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
p.overflow.insert(owner);
|
||||
}
|
||||
for r in runs {
|
||||
self.fonts.extend(run_fonts(r));
|
||||
let fonts = run_fonts(r);
|
||||
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
for font in &fonts {
|
||||
p.fonts.entry(font.clone()).or_default().insert(owner);
|
||||
}
|
||||
}
|
||||
self.fonts.extend(fonts);
|
||||
// Inline graphics draw their symbols' art.
|
||||
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
|
||||
self.symbol(&art.symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeKind::Image(_) => {
|
||||
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
p.images.entry(n.id).or_insert(owner);
|
||||
}
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol),
|
||||
NodeKind::PlacedDocument(p) => {
|
||||
if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
report.images.entry(n.id).or_insert(owner);
|
||||
}
|
||||
for art in p.art(n) {
|
||||
self.art(&art);
|
||||
}
|
||||
|
||||
@@ -1152,6 +1152,13 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Resolution at a placed image's transform: 72 points per inch over each pixel axis.
|
||||
pub(super) fn effective_ppi(xf: Affine) -> [f64; 2] {
|
||||
let [a, b, c, d, ..] = xf.as_coeffs();
|
||||
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
|
||||
[ppi(a, b), ppi(c, d)]
|
||||
}
|
||||
|
||||
pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "image.info";
|
||||
let st = s.doc()?;
|
||||
@@ -1165,9 +1172,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
|
||||
let [a, b, c, d, ..] = im.xf.as_coeffs();
|
||||
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
|
||||
let doc_path = super::links::LinkBase::of(st).doc;
|
||||
@@ -1179,7 +1183,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
|
||||
"pixelWidth": im.width,
|
||||
"pixelHeight": im.height,
|
||||
"ppi": [ppi(a, b), ppi(c, d)],
|
||||
"ppi": effective_ppi(im.xf),
|
||||
"width": size.width(),
|
||||
"height": size.height(),
|
||||
}))
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Production preflight: the existing output-aware type walk, linked-file probes and image
|
||||
//! resolution calculation, returned as findings that the interface can locate and recheck.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param};
|
||||
|
||||
const COMMAND: &str = "document.preflight";
|
||||
const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "document.preflight",
|
||||
"Production Preflight",
|
||||
[],
|
||||
None,
|
||||
"{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file",
|
||||
has_doc,
|
||||
check
|
||||
)]
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf");
|
||||
if !matches!(output, "pdf" | "print" | "screen") {
|
||||
return Err(bad(COMMAND, "output must be pdf, print or screen"));
|
||||
}
|
||||
let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?;
|
||||
if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) {
|
||||
return Err(bad(COMMAND, "minPpi must be from 1 to 9600"));
|
||||
}
|
||||
let indices = match p.get("artboards").filter(|v| !v.is_null()) {
|
||||
Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?,
|
||||
None => (0..s.doc()?.doc.artboards.len()).collect(),
|
||||
};
|
||||
let context = if output == "print" {
|
||||
super::print::preflight_context(s, &indices)?
|
||||
} else {
|
||||
let doc = &s.doc()?.doc;
|
||||
let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect();
|
||||
super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] }
|
||||
};
|
||||
let areas = context.pages.iter().map(|(r, _)| *r).collect::<Vec<_>>();
|
||||
let st = s.doc()?;
|
||||
let doc = st.doc.with_placed_art();
|
||||
let mut layers = doc.layers.clone();
|
||||
vectorcraft_pdf::keep_layers(&mut layers, context.layers);
|
||||
let typed = super::fonts::preflight_type(&doc, &layers, &areas);
|
||||
let statuses = super::links::statuses(st);
|
||||
let mut findings = vec![];
|
||||
let db = FontDb::global();
|
||||
for (font, ids) in typed.fonts {
|
||||
let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) {
|
||||
None | Some(FontMatch::Missing) => "missingFont",
|
||||
Some(FontMatch::Style) => "substitutedFont",
|
||||
_ => continue,
|
||||
};
|
||||
findings.push(
|
||||
json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "name": super::fonts::font_label(&font) }),
|
||||
);
|
||||
}
|
||||
for id in typed.overflow {
|
||||
findings.push(finding("text", "overflow", id, &doc));
|
||||
}
|
||||
let mut resolution_unchecked = 0usize;
|
||||
for (source, owner) in typed.images {
|
||||
if let Some((status, _, _)) = statuses.get(&source) {
|
||||
let code = match status.as_str() {
|
||||
"missing" => Some("missingLink"),
|
||||
"modified" => Some("modifiedLink"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(code) = code {
|
||||
let mut f = finding("links", code, owner, &doc);
|
||||
f["sourceId"] = json!(source.0);
|
||||
findings.push(f);
|
||||
}
|
||||
}
|
||||
// A vector placed document has no single bitmap resolution. Its embedded artwork, and
|
||||
// resources with their own coordinate systems, must never be certified at a local scale.
|
||||
if doc.node(source).is_none() || source != owner {
|
||||
resolution_unchecked += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else {
|
||||
resolution_unchecked += 1;
|
||||
continue;
|
||||
};
|
||||
let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n));
|
||||
let ppi = context
|
||||
.pages
|
||||
.iter()
|
||||
.filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0))
|
||||
.map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf))
|
||||
.reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]);
|
||||
let Some(ppi) = ppi else {
|
||||
resolution_unchecked += 1;
|
||||
continue;
|
||||
};
|
||||
// Inverting the placed-size transform can round an exact threshold slightly down.
|
||||
if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) {
|
||||
resolution_unchecked += 1;
|
||||
} else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) {
|
||||
let mut f = finding("resolution", "lowResolution", owner, &doc);
|
||||
f["effectivePpi"] = json!(ppi);
|
||||
f["threshold"] = json!(min_ppi);
|
||||
findings.push(f);
|
||||
}
|
||||
}
|
||||
let checks = KINDS.map(|kind| {
|
||||
let count = findings.iter().filter(|f| f["kind"] == kind).count();
|
||||
let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 };
|
||||
let status = if count > 0 {
|
||||
"failed"
|
||||
} else if not_checked > 0 {
|
||||
"notChecked"
|
||||
} else {
|
||||
"passed"
|
||||
};
|
||||
json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked })
|
||||
});
|
||||
Ok(json!({
|
||||
"output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks,
|
||||
"findings": findings, "outputWarnings": context.warnings,
|
||||
"limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."]
|
||||
}))
|
||||
}
|
||||
|
||||
fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value {
|
||||
json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) })
|
||||
}
|
||||
@@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Reuse the Print dialog's saved settings and page geometry for production preflight, without
|
||||
/// printing, writing a file or duplicating its type warnings.
|
||||
pub(super) struct PreflightContext {
|
||||
pub layers: PrintLayers,
|
||||
pub pages: Vec<(Rect, Affine)>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result<PreflightContext> {
|
||||
let settings =
|
||||
json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::<Vec<_>>().join(",") } });
|
||||
let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?;
|
||||
super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?;
|
||||
let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?;
|
||||
let pages = pv
|
||||
.sheets
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let to_page = Affine::new(p.transform);
|
||||
on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page))
|
||||
})
|
||||
.collect();
|
||||
pv.warnings.extend(pv.setting_notes);
|
||||
Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings })
|
||||
}
|
||||
|
||||
/// The parts of the document (document space) that the pages of `pv` print.
|
||||
fn areas(pv: &PrintPreview) -> Vec<Rect> {
|
||||
pv.sheets
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
//! Production preflight must find actual delivery problems and clear them after repairs.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn new() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({ "width": 500, "height": 400 })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn check(s: &mut Session) -> Value {
|
||||
s.execute("document.preflight", &json!({})).unwrap()
|
||||
}
|
||||
|
||||
fn codes(report: &Value) -> Vec<&str> {
|
||||
report["findings"].as_array().unwrap().iter().map(|f| f["code"].as_str().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_finds_four_problems_and_repairs_clear_each_one() {
|
||||
let dir = Folder::new("preflight-four");
|
||||
let path = dir.file("picture.png");
|
||||
let bytes = png(40, 40, [200, 50, 10]);
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
let mut s = new();
|
||||
let text = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight Missing Family 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone();
|
||||
let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200], "link": true })).unwrap()["ids"][0].clone();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let before_doc = s.doc().unwrap().doc.clone();
|
||||
let before_sel = s.doc().unwrap().selection.clone();
|
||||
let revision = s.doc().unwrap().revision;
|
||||
let report = check(&mut s);
|
||||
for code in ["missingFont", "overflow", "missingLink", "lowResolution"] {
|
||||
assert!(codes(&report).contains(&code), "{code}: {report}");
|
||||
}
|
||||
assert_eq!(*before_doc, *s.doc().unwrap().doc);
|
||||
assert_eq!(before_sel, s.doc().unwrap().selection);
|
||||
assert_eq!(revision, s.doc().unwrap().revision, "checking doesn't edit the document");
|
||||
for f in report["findings"].as_array().unwrap() {
|
||||
assert!(f["ids"].as_array().unwrap().iter().all(|id| id == &text || id == &image), "{f}");
|
||||
}
|
||||
s.execute("text.areaOptions", &json!({ "ids": [text], "height": 150 })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"overflow"));
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
s.execute("links.update", &json!({ "ids": [image] })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"missingLink"));
|
||||
s.execute("select.set", &json!({ "ids": [image] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 7.2, "height": 7.2 })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"lowResolution"));
|
||||
// Deleting the missing-font object fixes the final delivery issue on any machine, including
|
||||
// builds with no optional craft-fonts checkout or installed fonts.
|
||||
s.execute("select.set", &json!({ "ids": [text] })).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let clean = check(&mut s);
|
||||
assert!(codes(&clean).is_empty(), "{clean}");
|
||||
assert!(clean["checks"].as_array().unwrap().iter().all(|c| c["status"] == "passed"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(codes(&check(&mut s)).contains(&"missingFont"), "undo is checked too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_reuses_link_probes_for_external_changes_without_an_edit() {
|
||||
let dir = Folder::new("preflight-modified");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200] })).unwrap()["ids"][0].clone();
|
||||
let rev = s.doc().unwrap().revision;
|
||||
std::fs::write(&path, png(41, 45, [10, 50, 200])).unwrap();
|
||||
assert!(codes(&check(&mut s)).contains(&"modifiedLink"));
|
||||
assert_eq!(rev, s.doc().unwrap().revision);
|
||||
s.execute("links.update", &json!({ "ids": [image] })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"modifiedLink"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_scopes_artboards_and_respects_hidden_and_nonprinting_layers() {
|
||||
let mut s = new();
|
||||
let id = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Scope 917" })).unwrap()["id"].clone();
|
||||
s.execute("artboard.new", &json!({ "x": 600, "y": 0, "width": 500, "height": 400 })).unwrap();
|
||||
let other = s.execute("document.preflight", &json!({ "artboards": [1] })).unwrap();
|
||||
assert!(codes(&other).is_empty(), "{other}");
|
||||
assert!(codes(&check(&mut s)).contains(&"missingFont"));
|
||||
s.execute("object.setProps", &json!({ "ids": [id], "visible": false })).unwrap();
|
||||
assert!(codes(&check(&mut s)).is_empty());
|
||||
s.execute("object.setProps", &json!({ "ids": [id], "visible": true, "locked": true })).unwrap();
|
||||
assert!(codes(&check(&mut s)).contains(&"missingFont"), "locked artwork still exports");
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.setProps", &json!({ "id": layer.0, "printable": false })).unwrap();
|
||||
let print = s.execute("document.preflight", &json!({ "output": "print" })).unwrap();
|
||||
assert!(codes(&print).is_empty(), "{print}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_follows_placed_size_and_both_axes() {
|
||||
let dir = Folder::new("preflight-resolution");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone();
|
||||
s.execute("select.set", &json!({ "ids": [id] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 24, "height": 72 })).unwrap();
|
||||
let r = check(&mut s);
|
||||
let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap();
|
||||
assert_eq!(f["effectivePpi"], json!([300.0, 100.0]));
|
||||
let screen = s.execute("document.preflight", &json!({ "output": "screen" })).unwrap();
|
||||
assert_eq!(screen["minPpi"], 96.0);
|
||||
assert!(codes(&screen).is_empty(), "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() {
|
||||
let dir = Folder::new("preflight-resolution-boundary");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap();
|
||||
for threshold in [31.0, 59.0, 300.0, 600.0, 9600.0] {
|
||||
let size = 40.0 * 72.0 / threshold;
|
||||
s.execute("object.setBounds", &json!({ "width": size, "height": size })).unwrap();
|
||||
let exact = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap();
|
||||
assert!(!codes(&exact).contains(&"lowResolution"), "exactly {threshold} ppi: {exact}");
|
||||
s.execute("object.setBounds", &json!({ "width": size * 1.000001, "height": size })).unwrap();
|
||||
let below = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap();
|
||||
let f = below["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap();
|
||||
assert_eq!(f["threshold"], threshold);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_includes_the_print_jobs_scale() {
|
||||
let dir = Folder::new("preflight-print-scale");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
s.execute("file.place", &json!({ "path": path, "link": false, "at": [250, 200] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap();
|
||||
let doc = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap();
|
||||
assert!(codes(&doc).is_empty(), "{doc}");
|
||||
s.execute("print.setup", &json!({ "settings": { "scaling": "custom", "scale": { "width": 200, "height": 200 } } })).unwrap();
|
||||
let print = s.execute("document.preflight", &json!({ "output": "print", "minPpi": 200 })).unwrap();
|
||||
let f = print["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap();
|
||||
assert_eq!(f["effectivePpi"], json!([150.0, 150.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_reports_a_frame_that_cannot_show_even_its_first_line() {
|
||||
let mut s = new();
|
||||
let id = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Abc", "size": 30, "area": { "width": 100, "height": 1 } })).unwrap()["id"]
|
||||
.clone();
|
||||
let r = check(&mut s);
|
||||
assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_reports_type_that_cannot_place_a_glyph_on_a_horizontal_path() {
|
||||
let mut s = new();
|
||||
let path = s.execute("path.create", &json!({ "d": "M10 20 L11 20" })).unwrap()["id"].clone();
|
||||
let id = s.execute("text.createInPath", &json!({ "path": path, "mode": "onPath", "text": "Longer than the path" })).unwrap()["id"].clone();
|
||||
let r = check(&mut s);
|
||||
assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_bad_options_leave_document_and_selection_unchanged() {
|
||||
let mut s = new();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [
|
||||
json!({ "output": "unknown" }),
|
||||
json!({ "output": 1 }),
|
||||
json!({ "minPpi": 0 }),
|
||||
json!({ "minPpi": "300" }),
|
||||
json!({ "artboards": [] }),
|
||||
json!({ "artboards": [0.5] }),
|
||||
json!({ "artboards": [999] }),
|
||||
] {
|
||||
assert!(s.execute("document.preflight", &p).is_err(), "{p}");
|
||||
assert_eq!(*doc, *s.doc().unwrap().doc);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resource_font_finding_locates_its_instance() {
|
||||
let mut s = new();
|
||||
let text = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Symbol 917" })).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({ "ids": [text] })).unwrap();
|
||||
s.execute("symbol.new", &json!({ "name": "Label" })).unwrap();
|
||||
let r = check(&mut s);
|
||||
let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap();
|
||||
assert!(f["ids"].as_array().unwrap().iter().all(|id| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some()), "{r}");
|
||||
}
|
||||
|
||||
struct Folder(std::path::PathBuf);
|
||||
impl Folder {
|
||||
fn new(name: &str) -> Self {
|
||||
Self(vectorcraft_testkit::temp_dir(name))
|
||||
}
|
||||
fn file(&self, name: &str) -> String {
|
||||
self.0.join(name).to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
impl Drop for Folder {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
|
||||
let pixels = (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect();
|
||||
let image =
|
||||
craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap();
|
||||
craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).unwrap()
|
||||
}
|
||||
@@ -707,6 +707,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> {
|
||||
panel("Pathfinder", "pathfinder"),
|
||||
panel("Pattern Options", "patternOptions"),
|
||||
panel("Properties", "properties"),
|
||||
panel("Production Preflight", crate::panels::preflight::ID),
|
||||
panel("Script Console", crate::panels::script_console::ID),
|
||||
panel("Separations Preview", "separations"),
|
||||
panel("Stroke", "stroke"),
|
||||
|
||||
@@ -38,6 +38,7 @@ pub mod opentype;
|
||||
pub mod paragraph;
|
||||
pub mod pathfinder;
|
||||
pub mod pattern_options;
|
||||
pub mod preflight;
|
||||
pub mod properties;
|
||||
pub mod script_console;
|
||||
pub mod separations;
|
||||
@@ -188,6 +189,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
|
||||
"colorThemes" => color_themes::show(app, ui),
|
||||
color_wheel::ID => color_wheel::show(app, ui),
|
||||
links::ID => links::show(app, ui),
|
||||
preflight::ID => preflight::show(app, ui),
|
||||
asset_export::ID => asset_export::show(app, ui),
|
||||
css_properties::ID => css_properties::show(app, ui),
|
||||
three_d::ID => three_d::show(app, ui),
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Window › Production Preflight. Results follow the active document/revision and chosen output;
|
||||
//! file and font changes outside the document are rechecked periodically while the panel is open.
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{empty_state, pstate, set_pstate};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{self, dim_label};
|
||||
|
||||
pub const ID: &str = "preflight";
|
||||
const OPTIONS: &str = "production-preflight-options";
|
||||
const CACHE: &str = "production-preflight-cache";
|
||||
const RECHECK: f64 = 2.0;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Options {
|
||||
output: usize,
|
||||
active_only: bool,
|
||||
min_ppi: f64,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self { output: 0, active_only: false, min_ppi: 300.0 }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Cache {
|
||||
/// Document identity, revision, output, artboard scope and resolution threshold.
|
||||
key: Option<(u64, u64, usize, Option<usize>, u64)>,
|
||||
at: f64,
|
||||
report: Value,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
fn cached(app: &mut VectorcraftApp, ui: &Ui, o: &Options, force: bool) -> Cache {
|
||||
let Some(st) = app.session.active() else { return Cache::default() };
|
||||
let board = o.active_only.then(|| app.view().map_or(0, |v| v.artboard));
|
||||
let key = Some((st.uid, st.revision, o.output, board, o.min_ppi.to_bits()));
|
||||
let now = ui.input(|i| i.time);
|
||||
let mut c: Cache = pstate(ui.ctx(), CACHE);
|
||||
if force || c.key != key || now - c.at >= RECHECK {
|
||||
let output = ["pdf", "print", "screen"].get(o.output).copied().unwrap_or("pdf");
|
||||
let mut params = json!({ "output": output, "minPpi": o.min_ppi });
|
||||
if let Some(i) = board {
|
||||
params["artboards"] = json!([i]);
|
||||
}
|
||||
match app.session.execute("document.preflight", ¶ms) {
|
||||
Ok(v) => {
|
||||
c.report = v;
|
||||
c.error = None;
|
||||
}
|
||||
Err(e) => {
|
||||
c.report = Value::Null;
|
||||
c.error = Some(e.to_string());
|
||||
}
|
||||
}
|
||||
(c.key, c.at) = (key, now);
|
||||
set_pstate(ui.ctx(), CACHE, c.clone());
|
||||
}
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(RECHECK));
|
||||
c
|
||||
}
|
||||
|
||||
fn kind_label(kind: &str) -> &str {
|
||||
match kind {
|
||||
"fonts" => tl!("Fonts"),
|
||||
"text" => tl!("Text Overflow"),
|
||||
"links" => tl!("Linked Files"),
|
||||
_ => tl!("Image Resolution"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reason(code: &str) -> &str {
|
||||
match code {
|
||||
"missingFont" => tl!("Missing font; fallback will be used"),
|
||||
"substitutedFont" => tl!("Missing font style; closest style will be used"),
|
||||
"overflow" => tl!("Text past the frame will be left out"),
|
||||
"missingLink" => tl!("Linked file is missing"),
|
||||
"modifiedLink" => tl!("Linked file changed; update it before delivery"),
|
||||
_ => tl!("Image resolution is below the minimum"),
|
||||
}
|
||||
}
|
||||
|
||||
/// All locating actions go through commands. Resource findings name a visible canvas owner.
|
||||
fn locate(app: &mut VectorcraftApp, finding: &Value) {
|
||||
let ids = finding["ids"].as_array().cloned().unwrap_or_default();
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let selected = match app.run("select.set", json!({ "ids": ids })) {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
app.ui.status = error;
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Selection can succeed while dropping artwork protected by a locked artboard.
|
||||
let selected: std::collections::HashSet<_> = selected["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();
|
||||
let found = ids.iter().filter_map(Value::as_u64).filter(|id| selected.contains(id)).count();
|
||||
if found > 0
|
||||
&& let Err(error) = app.run(crate::addons::arrange::ZOOM, json!({}))
|
||||
{
|
||||
app.ui.status = error;
|
||||
return;
|
||||
}
|
||||
let warning = tl!("Some affected artwork could not be selected. Unlock it or its artboard, or leave isolation mode, then try again.");
|
||||
if found < ids.len() {
|
||||
app.ui.status = warning.to_string();
|
||||
} else if app.ui.status == warning {
|
||||
app.ui.status.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if app.session.active().is_none() {
|
||||
empty_state(ui, "dc-list-view", "Production Preflight", "Open a document to check it before delivery.");
|
||||
return;
|
||||
}
|
||||
let mut options: Options = pstate(ui.ctx(), OPTIONS);
|
||||
let labels = [tl!("PDF"), tl!("Print"), tl!("Screen")];
|
||||
widgets::label_row(ui, tl!("Output:"), 74.0, |ui| {
|
||||
let shown = labels.get(options.output).copied().unwrap_or(labels[0]);
|
||||
if let Some(i) = widgets::dropdown(ui, "preflight-output", shown, &labels, ui.available_width().max(90.0)) {
|
||||
options.output = i;
|
||||
options.min_ppi = if i == 2 { 96.0 } else { 300.0 };
|
||||
}
|
||||
});
|
||||
widgets::label_row(ui, tl!("Minimum PPI:"), 90.0, |ui| {
|
||||
if let Some(ppi) = widgets::range_field(ui, "preflight-ppi", options.min_ppi, 1.0..=9600.0, "", 0, 80.0) {
|
||||
options.min_ppi = ppi;
|
||||
}
|
||||
});
|
||||
ui.checkbox(&mut options.active_only, tl!("Active Artboard Only"));
|
||||
let force = ui.button(tl!("Recheck")).clicked();
|
||||
set_pstate(ui.ctx(), OPTIONS, options.clone());
|
||||
ui.separator();
|
||||
if app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy() {
|
||||
dim_label(ui, tl!("Preflight updates when the edit finishes."));
|
||||
return;
|
||||
}
|
||||
let cache = cached(app, ui, &options, force);
|
||||
if let Some(error) = cache.error {
|
||||
ui.colored_label(Tokens::get(ui.ctx()).error, tl!("Preflight could not complete"));
|
||||
ui.label(crate::i18n::msg(&error));
|
||||
return;
|
||||
}
|
||||
let report = &cache.report;
|
||||
let height = ui.available_height().clamp(100.0, 600.0);
|
||||
widgets::panel_scroll(ui, egui::ScrollArea::vertical().id_salt("preflight-findings").max_height(height).auto_shrink([false, true]), |ui| {
|
||||
results(app, ui, report);
|
||||
});
|
||||
}
|
||||
|
||||
fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) {
|
||||
let findings = report["findings"].as_array().map_or(&[][..], Vec::as_slice);
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
for check in report["checks"].as_array().into_iter().flatten() {
|
||||
let kind = check["kind"].as_str().unwrap_or_default();
|
||||
let count = check["count"].as_u64().unwrap_or(0);
|
||||
let (status, color) = match check["status"].as_str() {
|
||||
Some("passed") => (tl!("Passed"), tokens.text),
|
||||
Some("failed") => (tl!("Needs attention"), tokens.warning),
|
||||
_ => (tl!("Not checked"), tokens.text_dim),
|
||||
};
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(kind_label(kind));
|
||||
ui.colored_label(color, status);
|
||||
if count > 0 {
|
||||
ui.label(count.to_string());
|
||||
}
|
||||
});
|
||||
for (index, finding) in findings.iter().enumerate().filter(|(_, f)| f["kind"] == kind) {
|
||||
let name = finding["name"].as_str().unwrap_or_default();
|
||||
let code = finding["code"].as_str().unwrap_or_default();
|
||||
let text = format!("{name}\n{}", reason(code));
|
||||
ui.push_id(index, |ui| {
|
||||
if ui
|
||||
.add(egui::Button::new(text).wrap().min_size(egui::vec2(ui.available_width(), 0.0)))
|
||||
.on_hover_text(tl!("Select and zoom to affected artwork"))
|
||||
.clicked()
|
||||
{
|
||||
locate(app, finding);
|
||||
}
|
||||
if let Some(ppi) = finding["effectivePpi"].as_array() {
|
||||
let values = ppi.iter().filter_map(Value::as_f64).map(|n| format!("{n:.0}")).collect::<Vec<_>>();
|
||||
dim_label(ui, &format!("{}: {} ppi", tl!("Effective PPI"), values.join(" × ")));
|
||||
}
|
||||
let source = finding["sourceId"].as_u64();
|
||||
if code == "missingLink"
|
||||
&& ui.small_button(tl!("Relink…")).clicked()
|
||||
&& let Some(id) = source
|
||||
{
|
||||
app.run("ui.relinkDialog", json!({"ids": [id]})).ok();
|
||||
}
|
||||
if code == "modifiedLink"
|
||||
&& ui.small_button(tl!("Update Link")).clicked()
|
||||
&& let Some(id) = source
|
||||
{
|
||||
app.run("links.update", json!({"ids": [id]})).ok();
|
||||
}
|
||||
});
|
||||
}
|
||||
if kind == "fonts" && count > 0 && ui.small_button(tl!("Find Font…")).clicked() {
|
||||
app.run("type.findFont", json!({})).ok();
|
||||
}
|
||||
if check["notChecked"].as_u64().unwrap_or(0) > 0 {
|
||||
dim_label(ui, tl!("Resolution inside resource art or placed documents is not checked."));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
for warning in report["outputWarnings"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
ui.colored_label(tokens.warning, crate::i18n::msg(warning));
|
||||
}
|
||||
ui.separator();
|
||||
dim_label(ui, tl!("Checks update after edits. Linked files are rechecked every two seconds."));
|
||||
dim_label(ui, tl!("These checks do not certify an exported file."));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,179 @@
|
||||
use super::*;
|
||||
use crate::panels::tests_appearance::{frame_raw, text_rect};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn app() -> (VectorcraftApp, Value) {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({ "width": 500, "height": 400 })).unwrap();
|
||||
let id = app.run("text.create", json!({ "x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight UI Missing 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone();
|
||||
app.run("object.setProps", json!({ "ids": [id], "name": "Delivery headline" })).unwrap();
|
||||
(app, id)
|
||||
}
|
||||
|
||||
fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, time: f64, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
|
||||
frame_raw(
|
||||
ctx,
|
||||
app,
|
||||
egui::RawInput {
|
||||
time: Some(time),
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(360.0, 1000.0))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
show,
|
||||
)
|
||||
}
|
||||
|
||||
fn text(rows: &[(String, egui::Rect)]) -> String {
|
||||
rows.iter().map(|(s, _)| s.as_str()).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_panel_rechecks_edits_undo_and_document_switches() {
|
||||
let (mut app, id) = app();
|
||||
let ctx = egui::Context::default();
|
||||
let first = text(&frame(&ctx, &mut app, 1.0, vec![]));
|
||||
assert!(first.contains("Preflight UI Missing 917") && first.contains("Text past the frame"), "{first}");
|
||||
app.run("text.areaOptions", json!({ "ids": [id], "height": 150 })).unwrap();
|
||||
let fixed = text(&frame(&ctx, &mut app, 1.1, vec![]));
|
||||
assert!(!fixed.contains("Text past the frame"), "revision rechecks before the timer: {fixed}");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert!(text(&frame(&ctx, &mut app, 1.2, vec![])).contains("Text past the frame"));
|
||||
app.run("file.new", json!({ "width": 500, "height": 400 })).unwrap();
|
||||
let clean = text(&frame(&ctx, &mut app, 1.3, vec![]));
|
||||
assert!(!clean.contains("Preflight UI Missing 917") && !clean.contains("Needs attention"), "{clean}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_preflight_finding_selects_and_zooms_to_its_artwork() {
|
||||
let (mut app, id) = app();
|
||||
app.run("select.set", json!({ "ids": [] })).unwrap();
|
||||
app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)));
|
||||
let ctx = egui::Context::default();
|
||||
let rows = frame(&ctx, &mut app, 1.0, vec![]);
|
||||
let at = text_rect(&rows, "Delivery headline\nText past the frame will be left out").center();
|
||||
let event = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
frame(&ctx, &mut app, 1.1, vec![egui::Event::PointerMoved(at), event(true)]);
|
||||
frame(&ctx, &mut app, 1.2, vec![event(false)]);
|
||||
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id.as_u64().unwrap())]);
|
||||
assert!(app.view().unwrap().fitted);
|
||||
assert!(app.view().unwrap().zoom > 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_preflight_finding_on_a_locked_artboard_reports_the_problem() {
|
||||
let (mut app, id) = app();
|
||||
app.run("select.set", json!({ "ids": [] })).unwrap();
|
||||
app.run("artboard.setProps", json!({ "index": 0, "locked": true })).unwrap();
|
||||
app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)));
|
||||
let before_view = *app.view().unwrap();
|
||||
let before_doc = app.session.active().unwrap().doc.clone();
|
||||
app.ui.status.clear();
|
||||
let ctx = egui::Context::default();
|
||||
let rows = frame(&ctx, &mut app, 1.0, vec![]);
|
||||
let at = text_rect(&rows, "Delivery headline\nText past the frame will be left out").center();
|
||||
let event = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
frame(&ctx, &mut app, 1.1, vec![egui::Event::PointerMoved(at), event(true)]);
|
||||
frame(&ctx, &mut app, 1.2, vec![event(false)]);
|
||||
assert!(app.ui.status.contains("could not be selected"), "{}", app.ui.status);
|
||||
assert!(app.session.active().unwrap().selection.objects.is_empty());
|
||||
assert_eq!(app.view().unwrap().zoom, before_view.zoom);
|
||||
assert_eq!(*app.session.active().unwrap().doc, *before_doc);
|
||||
app.run("artboard.setProps", json!({ "index": 0, "locked": false })).unwrap();
|
||||
locate(&mut app, &json!({ "ids": [id] }));
|
||||
assert!(app.ui.status.is_empty(), "successful navigation clears its previous warning: {}", app.ui.status);
|
||||
assert!(app.view().unwrap().fitted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_navigation_reports_partial_selection_and_zooms_to_selectable_artwork() {
|
||||
let (mut app, locked) = app();
|
||||
app.run("artboard.new", json!({ "x": 600, "y": 0, "width": 500, "height": 400 })).unwrap();
|
||||
let free = app.run("text.create", json!({ "x": 610, "y": 30, "text": "Free", "font": "Preflight UI Missing 917" })).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({ "ids": [] })).unwrap();
|
||||
app.run("artboard.setProps", json!({ "index": 0, "locked": true })).unwrap();
|
||||
app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)));
|
||||
let report = app.session.execute("document.preflight", &json!({})).unwrap();
|
||||
let finding = report["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap();
|
||||
assert!(finding["ids"].as_array().unwrap().contains(&locked));
|
||||
locate(&mut app, finding);
|
||||
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(free.as_u64().unwrap())]);
|
||||
assert!(app.view().unwrap().fitted);
|
||||
assert!(app.view().unwrap().zoom > 1.0);
|
||||
assert!(app.ui.status.contains("could not be selected"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_panel_does_not_present_stale_results_during_a_drag() {
|
||||
let (mut app, _) = app();
|
||||
let ctx = egui::Context::default();
|
||||
frame(&ctx, &mut app, 1.0, vec![]);
|
||||
app.session.begin_interaction("Preflight test").unwrap();
|
||||
let shown = text(&frame(&ctx, &mut app, 1.1, vec![]));
|
||||
assert!(shown.contains("Preflight updates when the edit finishes."), "{shown}");
|
||||
assert!(!shown.contains("Passed") && !shown.contains("Needs attention"), "{shown}");
|
||||
app.session.cancel_interaction().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_window_menu_and_empty_state_are_available() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("window.panel", json!({ "panel": ID })).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let shown = text(&frame(&ctx, &mut app, 1.0, vec![]));
|
||||
assert!(shown.contains("Open a document to check it before delivery."), "{shown}");
|
||||
assert!(crate::state::all_panels().any(|(id, name)| id == ID && name == "Production Preflight"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_panel_rechecks_missing_files_on_its_timer_and_on_request() {
|
||||
let dir = vectorcraft_testkit::temp_dir("ui-preflight-timer");
|
||||
let path = dir.join("picture.png");
|
||||
let image = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, vec![255; 16])
|
||||
.unwrap();
|
||||
let bytes = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).unwrap();
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({ "width": 500, "height": 400 })).unwrap();
|
||||
app.run("file.place", json!({ "path": path.to_string_lossy(), "at": [100, 100] })).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
frame(&ctx, &mut app, 1.0, vec![]);
|
||||
let rev = app.session.active().unwrap().revision;
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert!(!text(&frame(&ctx, &mut app, 1.1, vec![])).contains("Linked file is missing"));
|
||||
assert!(text(&frame(&ctx, &mut app, 3.1, vec![])).contains("Linked file is missing"));
|
||||
assert_eq!(rev, app.session.active().unwrap().revision);
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
let rows = frame(&ctx, &mut app, 3.2, vec![]);
|
||||
let at = text_rect(&rows, "Recheck").center();
|
||||
let event = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
frame(&ctx, &mut app, 3.3, vec![egui::Event::PointerMoved(at), event(true)]);
|
||||
let after = text(&frame(&ctx, &mut app, 3.4, vec![event(false)]));
|
||||
assert!(!after.contains("Linked file is missing"), "{after}");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
|
||||
/// An optional visual QA artifact, never a checked-in snapshot or an asset shipped by the app.
|
||||
#[test]
|
||||
#[ignore = "set PREFLIGHT_PREVIEW_PATH to write an offscreen GPU render for visual review"]
|
||||
fn preflight_panel_preview() {
|
||||
let (app, _) = app();
|
||||
let mut harness = egui_kittest::Harness::builder()
|
||||
.with_size(egui::vec2(340.0, 480.0))
|
||||
.with_accessibility_check(false)
|
||||
.with_context_setup(|ctx| {
|
||||
crate::theme::install_fonts(ctx);
|
||||
crate::theme::apply(ctx, crate::theme::Brightness::Dark);
|
||||
})
|
||||
.build_ui_state(
|
||||
|ui, app| {
|
||||
ui.heading("Production Preflight");
|
||||
ui.separator();
|
||||
show(app, ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
harness.run_steps(3);
|
||||
let path = std::env::var("PREFLIGHT_PREVIEW_PATH").expect("PREFLIGHT_PREVIEW_PATH");
|
||||
harness.render().unwrap().save(path).unwrap();
|
||||
}
|
||||
@@ -219,6 +219,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[
|
||||
("colorThemes", "Color Themes", "sun"),
|
||||
(crate::panels::color_wheel::ID, "Color Wheel", "circle"),
|
||||
(crate::panels::links::ID, "Links", "link"),
|
||||
(crate::panels::preflight::ID, "Production Preflight", "dc-list-view"),
|
||||
(crate::panels::asset_export::ID, "Asset Export", "share-2"),
|
||||
(crate::panels::css_properties::ID, "CSS Properties", "globe"),
|
||||
(crate::panels::three_d::ID, "3D and Materials", "dc-cube"),
|
||||
|
||||
@@ -520,7 +520,9 @@ fn a_slow_first_read_says_so_until_its_listing_comes() {
|
||||
scripts_menu::check_slow(started + scripts_menu::SLOW_SECS / 2.0);
|
||||
assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING));
|
||||
assert_eq!(scripts_menu::revision(), before);
|
||||
scripts_menu::check_slow(started + scripts_menu::SLOW_SECS);
|
||||
// Past the threshold rather than at it: `(started + SLOW_SECS) - started` can round below
|
||||
// SLOW_SECS, which made this test fail for some start times.
|
||||
scripts_menu::check_slow(started + 1.5 * scripts_menu::SLOW_SECS);
|
||||
assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::SLOW));
|
||||
assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::SLOW));
|
||||
assert_eq!(scripts_menu::revision(), before + 1);
|
||||
|
||||
+4
-1
File diff suppressed because one or more lines are too long
+17
-1
@@ -1,6 +1,6 @@
|
||||
# VectorCraft MCP server
|
||||
|
||||
> **Last updated:** 2026-11-14 · **Change:** `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained.
|
||||
> **Last updated:** 2026-11-18 · **Change:** Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained.
|
||||
>
|
||||
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
|
||||
|
||||
@@ -9222,6 +9222,21 @@ Screens doesn't write EPS.
|
||||
{"name":"export","arguments":{"path":"/tmp/art.eps","options":{"useArtboards":true,"cmykPostScript":false}}}
|
||||
```
|
||||
|
||||
## Production Preflight
|
||||
|
||||
`document.preflight {output?: "pdf"|"print"|"screen", minPpi?: 1..9600, artboards?: [index, …]}`
|
||||
checks the active document without editing it or writing an export. Defaults: PDF, 300 ppi
|
||||
(96 ppi for Screen), all artboards. Indices are zero based. Print uses the saved Print settings
|
||||
with the requested artboards, including page scaling; PDF and Screen check visible art on them.
|
||||
|
||||
The result contains `checks` for `fonts`, `text`, `links` and `resolution`, each with `status`
|
||||
(`passed`, `failed`, `notChecked`), finding `count` and `notChecked` count. `findings` give a
|
||||
`code`, canvas `ids` and `name`; link findings also carry `sourceId`, and resolution findings
|
||||
carry `effectivePpi` and `threshold`. `outputWarnings` carries the Print preview's output/settings
|
||||
warnings. Resource findings point to their first visible canvas owner. Resolution inside resource
|
||||
art or placed documents is explicitly not checked; a pass is not certification of an exported file.
|
||||
See [Production Preflight](production-preflight.md) for the panel and coverage limits.
|
||||
|
||||
## Print
|
||||
|
||||
File → Print lays the job out as a print-ready PDF, in which each page is a sheet of the chosen paper. The desktop app
|
||||
@@ -14359,6 +14374,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n
|
||||
|
||||
| Date | Change |
|
||||
|---|---|
|
||||
| 2026-11-18 | Production Preflight: output and artboard scope, four check summaries, clickable canvas ids, effective PPI and explicit unchecked resolution coverage. |
|
||||
| 2026-11-14 | Built-in Tech Circuit brush library (id `tech-circuit`): Circuit Trace, Bus Lines and Terminal Nodes; ten built-in libraries. |
|
||||
| 2026-11-13 | The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides; Snap to Grid and Snap to Pixel still move its ends (#7252). |
|
||||
| 2026-11-13 | `path.freehand`: `closed`, when given, decides whether a stroke that continues a path (`extend`) closes it; the Pencil and the Paintbrush send it by Close Paths When Ends Are Within. |
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# Production Preflight
|
||||
|
||||
Open **Window > Production Preflight** before delivering artwork. Choose **PDF**, **Print** or
|
||||
**Screen**, set the minimum image resolution, and optionally check only the active artboard.
|
||||
The default minimum is 300 ppi for PDF/Print and 96 ppi for Screen. These are editable workflow
|
||||
defaults, not a guarantee of suitability for a particular printer or display.
|
||||
|
||||
The panel checks:
|
||||
|
||||
- **Fonts:** unavailable font families and styles that will use a fallback or a substitute.
|
||||
- **Text Overflow:** area type or type on a path whose text extends beyond its frame.
|
||||
- **Linked Files:** missing files and files that changed since they were read.
|
||||
- **Image Resolution:** effective resolution along both pixel axes at the image's placed size.
|
||||
Print includes the job's page transform, so enlarging the print can lower effective resolution.
|
||||
|
||||
Click a finding to select and zoom to the affected artwork. A font finding can select several
|
||||
objects. A finding inside a symbol, pattern, brush or opacity mask locates its first visible
|
||||
canvas owner. If some artwork cannot be selected, the status bar reports it; any selectable
|
||||
objects are still located without unlocking artwork or artboards. **Find Font…**, **Relink…** and
|
||||
**Update Link** open the existing repair workflows;
|
||||
they do not apply an automatic font substitution or change artwork just by checking it.
|
||||
|
||||
Results refresh after document edits, Undo/Redo, document switches and changes to the panel's
|
||||
options. During an interaction the panel waits for the edit to finish. External files are
|
||||
checked again every two seconds while the panel is visible; **Recheck** runs immediately.
|
||||
|
||||
PDF and Screen inspect visible artwork intersecting the chosen artboards. Print reuses the saved
|
||||
Print settings with the chosen artboards, including which layers print and what fits on the
|
||||
sheet; it also shows the existing print-preview geometry/settings warnings. Locked artwork is
|
||||
still checked because locking it does not prevent output. Hidden artwork is checked only if the
|
||||
Print settings include hidden layers.
|
||||
|
||||
## Coverage limits
|
||||
|
||||
This is a check of the document and selected output context, not validation or certification of
|
||||
an exported file. PDF export presets, colour conversion, ink coverage, bleed adequacy and
|
||||
accessibility compliance are not checked by this first version.
|
||||
|
||||
Resolution inside symbols, patterns, brushes, opacity masks and placed documents is reported as
|
||||
**Not checked**, because the resource's local transform alone does not establish its final output
|
||||
resolution. A resolution check with both findings and unchecked art shows **Needs attention**
|
||||
and also states that some art was not checked. A vector placed document has no single bitmap PPI.
|
||||
|
||||
The font and text checks share the existing output-aware walk, including its bounds/clipping
|
||||
approximations for generated art and container effects. Resource findings identify a representative
|
||||
visible owner, not an exhaustive list of every instance. A passed check means only that no problem
|
||||
of that kind was found within the stated coverage.
|
||||
|
||||
The same read-only report is available through `document.preflight`; see [MCP](mcp.md#production-preflight).
|
||||
|
||||
## Validation (2026-11-18)
|
||||
|
||||
Checked on Windows with Rust 1.99.1, based on `main` at `36b5a5920c`:
|
||||
|
||||
- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test preflight`).
|
||||
- Panel tests: 5 passed (`cargo test -p vectorcraft-ui-egui --lib preflight`), including pointer
|
||||
selection/zoom, edits and Undo, document switching, external-file polling and explicit Recheck.
|
||||
- Both test commands used `--offline --target-dir target --config profile.test.opt-level=0`.
|
||||
- Existing Print Preview and Links panel engine regressions: 16 + 16 passed, run from the native
|
||||
engine test binary with filters `tests::printpreview` and `tests::linkspanel`.
|
||||
- The ignored `preflight_panel_preview` test was run explicitly, rendered through the offscreen GPU
|
||||
harness and visually inspected. Its output remains under the ignored `target/` directory.
|
||||
- Native Clippy for the engine and UI, all targets, passed with `-D warnings` (explicit
|
||||
`--target x86_64-pc-windows-msvc`, using `target/wasm-check` for the validation artifacts).
|
||||
- Engine/UI WebAssembly typecheck passed. Formatting, asset attribution, branding, dependency
|
||||
layering and PDF dependency checks passed.
|
||||
- Windows desktop build passed (`cargo build -p vectorcraft --offline --target-dir target
|
||||
--config profile.dev.opt-level=0`). The running panel was visually inspected with a sample
|
||||
exercising all four findings, and the contributor tried it in the desktop app.
|
||||
|
||||
`cargo xtask ci` was attempted with `CARGO_BUILD_TARGET=x86_64-pc-windows-msvc`: formatting and
|
||||
workspace Clippy (all targets, `-D warnings`) passed. It was stopped during workspace-test
|
||||
compilation after the separate `ui-commands --check` confirmed pre-existing drift between the
|
||||
unchanged `menus/ui_commands.rs` and generated `mcp/src/ui_catalog.rs`. The complete workspace
|
||||
test suite and remaining CI stages were not completed. An additional
|
||||
WebAssembly Clippy run also encounters existing target-specific lints in unchanged `cmd/plugin.rs`
|
||||
(`drop_non_drop`) and `font_menu.rs` (`unnecessary_lazy_evaluations`); the WebAssembly typecheck and
|
||||
the native Clippy run above pass without source changes for those findings.
|
||||
|
||||
### Review follow-up on `main` at `ee60c51fd`
|
||||
|
||||
The exact-threshold and locked-artboard regressions were first run against the original
|
||||
implementation and failed. After the fixes and merge-conflict resolution:
|
||||
|
||||
- All 10 engine preflight tests and 7 panel tests passed. The optional GPU preview also passed
|
||||
and was visually inspected.
|
||||
- The boundary regression checks several exact PPI thresholds and a real shortfall on one axis.
|
||||
- Navigation regressions cover a locked artboard, retry after unlocking, and partial selection
|
||||
that still zooms to the selectable artwork. Finding navigation never unlocks artwork.
|
||||
- Formatting, native workspace Clippy with warnings denied, engine/UI WebAssembly typecheck,
|
||||
layering and PDF dependency checks passed. The complete workspace CI suite remains incomplete; the unchanged UI command catalog
|
||||
still fails its separate drift check.
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change |
|
||||
|---|---|
|
||||
| 2026-11-18 | Review follow-up: tolerate PPI rounding at the minimum, report incomplete finding selection, and retain main's symbol lookup improvements when resolving merge conflicts. |
|
||||
| 2026-11-18 | Initial Production Preflight panel and command. |
|
||||
+3
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user