Merge main into feat/scripts-xmp-objects

This commit is contained in:
dotCooCoo committed 2026-11-26 19:04:59 -08:00
commit 520d9edd8b
149 files changed
+6463 -778

No files matched your search

+22
View File
@@ -196,6 +196,15 @@ impl Unit {
}
parse_measure(&times_as_asterisks(s), self).filter(|v| v.is_finite())
}
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
/// number that looks like a grouped integer, even when it is part of an expression.
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
return None;
}
self.parse(&decimal_point(text))
}
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
/// `feetInches`).
pub const fn key(self) -> &'static str {
@@ -397,6 +406,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
}
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
/// read a percentage's number without its percent sign.
fn thousands_operand(operand: &str) -> bool {
let operand = operand.trim();
if let Some((picas, points)) = operand.split_once('p')
&& !points.trim().is_empty()
&& points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b','))
{
return thousands(picas) || thousands(points);
}
thousands(operand.strip_suffix('%').unwrap_or(operand))
}
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
+5 -5
View File
@@ -1,6 +1,6 @@
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives
//! it in each unit of Preferences › Units › East Asian Type
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
@@ -10,7 +10,7 @@
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit};
use vectorcraft_render::effects;
use super::super::{CommandSpec, always, bad, cmd, has_selection};
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Units",
[],
None,
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
"{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
always,
convert
),
@@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(CONVERT, "missing `value`"));
};
let pt = match v {
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s),
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
_ => None,
};
+13 -3
View File
@@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() {
}
#[test]
fn values_read_as_number_fields_read_them() {
fn values_accept_units_arithmetic_and_decimal_commas() {
let mut s = session();
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
@@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() {
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
// Each number of a sum reads its own separator.
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25));
assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5));
assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5));
// A sum of 128 signs still reads.
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
// x, X and × multiply as * does, and each counts toward the 128 signs.
@@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() {
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
}
#[test]
fn a_thousands_comma_in_an_arithmetic_operand_is_refused() {
let mut s = session();
for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] {
let result = s.execute("addon.units.convert", &json!({"value": value}));
assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}");
}
}
#[test]
fn keys_the_commands_do_not_take_are_refused() {
let s = session();
+34 -13
View File
@@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec<u8> {
pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "view.proofSetup.save";
let (path, named) = file_path(s, p, C)?;
let mut setup = proof::view().setup;
setup_params(p, &mut setup, C)?;
check_device(&setup.target).map_err(|e| bad(C, e))?;
// A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
let bytes = encode(&setup);
if bytes.len() > MAX_FILE {
return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
}
let (setup, bytes) = encode_options(p, &path)?;
if named
&& let Some(dir) = std::path::Path::new(&path).parent()
&& !dir.is_dir()
@@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Object(r))
}
/// Serialize the Customize dialog's draft without committing it or writing a path.
pub fn draft_bytes(p: &Value) -> Result<Vec<u8>> {
encode_options(p, "Proof Setup").map(|(_, bytes)| bytes)
}
fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec<u8>)> {
const C: &str = "view.proofSetup.save";
let mut setup = proof::view().setup;
setup_params(p, &mut setup, C)?;
check_device(&setup.target).map_err(|e| bad(C, e))?;
let bytes = encode(&setup);
if bytes.len() > MAX_FILE {
return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes")));
}
Ok((setup, bytes))
}
/// The file `p` names for `cmd` and the usable proof setup in it.
fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
let (path, _) = file_path(s, p, cmd)?;
// One byte past the limit shows a file over it, which is not read further.
let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
if bytes.len() > MAX_FILE {
return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
}
let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let setup = checked_setup(&bytes, &path, cmd)?;
Ok((path, setup))
}
/// Read a picked proof setup's validated settings without applying them to the view.
pub fn draft_fields(bytes: &[u8], name: &str) -> Result<Value> {
let setup = checked_setup(bytes, name, "view.proofSetup.read")?;
Ok(Value::Object(setup_json(&setup)))
}
fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result<ProofSetup> {
if bytes.len() > MAX_FILE {
return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes")));
}
let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
Ok(setup)
}
pub(super) fn read(s: &mut Session, p: &Value) -> Result<Value> {
let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
let mut r = setup_json(&setup);
+1 -1
View File
@@ -284,7 +284,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Metadata Template…",
[],
None,
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
has_doc,
super::fileinfo::apply_template
),
+14 -9
View File
@@ -213,7 +213,7 @@ enum Merge {
Append,
}
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`.
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
let mode = match text_param(p, "mode", APPLY)? {
Some("replace") => Merge::Replace,
@@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes.
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?];
// At most one byte past the limit is read, so a huge file is never read whole.
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
let bytes = match given {
[Some(path), None, None] => read(path)?,
[None, Some(name), None] => {
[Some(path), None, None, None] => read(path)?,
[None, Some(name), None, None] => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
let mut path = template_path(dir, name, APPLY)?;
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
@@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
// The app's own folder: no root applies.
crate::file_access::unconfined(|| read(&path))?
}
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data)] => data.as_bytes().to_vec(),
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
[None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data), None] => data.as_bytes().to_vec(),
[None, None, None, Some(data)] => {
if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 {
return Err(too_big(APPLY));
}
vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))?
}
_ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")),
};
if bytes.len() > MAX_TEMPLATE_FILE {
return Err(too_big(APPLY));
+55 -14
View File
@@ -76,6 +76,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
relink
),
cmd!(
"links.replaceEmbedded",
"Replace Image",
[],
None,
"{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}",
has_doc,
replace_embedded
),
cmd!(
query "links.list",
"Links",
@@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
install(d, &[id], read, Some(Preserve::Bounds), None)
}
/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement.
fn replace_embedded(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.replaceEmbedded";
let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?;
let doc = &s.doc()?.doc;
let mut seen = BTreeSet::new();
for id in &ids {
if !seen.insert(*id) {
return Err(bad(C, format!("image {} is listed twice", id.0)));
}
if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) {
return Err(bad(C, format!("object {} is not an image", id.0)));
}
}
let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?;
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?;
let mut img = fileio::raster_image(&bytes)?;
img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?;
s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?;
Ok(json!({ "replaced": ids_json(&ids) }))
}
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the
/// transform still gives it its old size. Its Placement Options do not apply. The result is what
@@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it:
/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a
/// distort maps a path's.
fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo {
fn refill_distorted(
n: &mut Node,
old_clip: Option<&FileClip>,
link: Option<&LinkInfo>,
img: &RasterImage,
held: Option<(&PathData, FillRule)>,
) -> ClipTo {
let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule)));
if let NodeKind::Image(im) = &mut n.kind {
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
}
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned());
}
let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule)));
placed_clip_to(old.as_ref(), None, file, held)
@@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
/// show that content.
fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
install_with(d, ids, read, force, also, false)
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
install_with(d, ids, Some(&link), img, force, also, false)
}
/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it
@@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo {
}
}
/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`].
/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes
/// through [`unembed_clip`].
fn install_with(
d: &mut Document,
ids: &[NodeId],
(link, img): FileRead,
link: Option<&LinkInfo>,
img: RasterImage,
force: Option<Preserve>,
also: Option<(&str, &str)>,
unembed: bool,
@@ -1341,7 +1380,7 @@ fn install_with(
NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()),
_ => None,
};
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held);
return (n, keep(clip, held.is_some()));
}
if let NodeKind::Image(im) = &mut n.kind {
@@ -1353,7 +1392,7 @@ fn install_with(
};
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some());
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
}
(n, clip)
};
@@ -1367,7 +1406,7 @@ fn install_with(
};
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
if let Some(n) = d.node_mut(*id) {
let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
clips.push((*id, keep(clip, held.is_some())));
}
continue;
@@ -1384,12 +1423,12 @@ fn install_with(
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
}
}
// A DCS file's spot plates print on spot swatches of their inks.
super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates());
store_image(d, &img.key, img.blob, true);
store_image(d, &img.key, img.blob, link.is_some());
clips.into_iter().try_for_each(|(id, clip)| match clip {
ClipTo::Keep => Ok(()),
ClipTo::Path(path) => clip_image_to(d, id, path),
@@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
// Read before writing: pixels that can't be read leave no file behind.
let img = linked_image(&bytes, Some(&path))?;
write_file(&path, &bytes)?;
let read = (link_info(&path, &bytes), img);
let link = link_info(&path, &bytes);
drop(doc);
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?;
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?;
Ok(json!({ "id": id.0, "path": path }))
}
@@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
drop(doc);
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
let edited = s.edit("Unembed", |d, _| {
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))
editing_brush_art(d, |d| {
reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true))
})
});
if let Err(e) = edited {
remove_written(&written);
+7
View File
@@ -406,6 +406,13 @@ fn edit_blends(s: &mut Session, label: &str, f: impl Fn(&mut Vec<Arc<Node>>, &mu
ok()
}
impl Session {
/// Whether Blend Options would operate on selected artwork rather than new-blend defaults.
pub fn has_selected_blend(&self) -> bool {
super::common::any_selected_of(self, is_blend, |_| true)
}
}
/// The first selected blend: its id, spec and key ids.
fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
let b = *selected_of(s, is_blend).first()?;
+11 -5
View File
@@ -876,11 +876,17 @@ fn dataset_step(s: &mut Session, cmd: &str, forward: bool) -> Result<Value> {
/// result is that command's, with `format` set to `csv` or `xml`.
fn variable_import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "variable.import";
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let (name, input) = if let Some(path) = str_param(p, "path") {
(path, json!({"path": path}))
} else {
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `path` or `name` with `dataBase64`"))?;
let bytes = str_param(p, "dataBase64").ok_or_else(|| bad(C, "missing `dataBase64`"))?;
(name, json!({"dataBase64": bytes}))
};
let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let (format, mut out) = match ext.as_deref() {
Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &json!({"path": path}))?),
Some("xml") => ("xml", load_library(s, &json!({"path": path}))?),
Some("csv" | "tsv" | "txt") => ("csv", dataset_import(s, &input)?),
Some("xml") => ("xml", load_library(s, &input)?),
_ => return Err(bad(C, "Import reads a data source file ending in .csv, .tsv, .txt or .xml")),
};
out["format"] = json!(format);
@@ -1084,7 +1090,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import…",
["Window", "Variables"],
None,
"{path} import a data source file, chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`",
"{path | name | dataBase64 (a file's path, or its name with its bytes)} import a data source chosen by its extension (any case): a .csv, .tsv or .txt file is read as dataset.import reads it, and an .xml file as variable.loadLibrary reads it, with their refusals and undo steps; any other extension, or none, is refused before the file is read → the result of that command with `format`: `csv` or `xml`",
has_doc,
variable_import
),
+5
View File
@@ -708,12 +708,17 @@ fn metadata_template_errors() {
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
let encoded = "A".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES.div_ceil(3) * 4 + 1);
let e = s.execute("file.info.applyTemplate", &json!({"dataBase64": encoded, "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
for bad in [
json!({"data": xmp, "mode": "merge"}),
json!({"data": xmp}),
json!({"data": xmp, "mode": 3}),
json!({"mode": "keep"}),
json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"data": xmp, "dataBase64": "SGVsbG8=", "mode": "keep"}),
json!({"dataBase64": "!", "mode": "keep"}),
json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}),
json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": big.to_str().unwrap(), "mode": "keep"}),
+1 -1
View File
@@ -1096,7 +1096,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorPicker",
"Color Picker…",
"",
"{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard",
"{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard. Artboard preview and OK require the opening document to be active",
),
(
"ui.sampleScreenColor",
+9
View File
@@ -94,6 +94,15 @@ impl crate::Renderer {
/// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and
/// nothing is held.
pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed {
// Trim View clips each draw when blending reaches the page and clips one composited
// layer otherwise. Changing modes can change unchanged art at an artboard edge.
if opts.trim && !old.artboards.is_empty() {
let before = crate::proof::prepare(old, opts, &mut self.proof_art);
let after = crate::proof::prepare(new, opts, &mut self.proof_art);
if self.children_blend(&before.layers) != self.children_blend(&after.layers) {
return Changed::Everything;
}
}
let renderer = (!crate::proof::overprints(opts)).then_some(self);
changed_with(old, new, renderer, opts)
}
+38
View File
@@ -167,6 +167,8 @@ pub struct FrameStats {
/// group or an effect's raster. A part of the frame rendered on its own can draw that art with
/// other pixels than the whole frame does.
pub view_sized: usize,
bounded_view_sized: usize,
view_sized_bounds: Option<Rect>,
/// How many threads composed the frame from its two ink planes, in a CMYK document that shows
/// transparency; 0 for other frames.
pub ink_threads: usize,
@@ -183,10 +185,35 @@ pub struct FrameStats {
pub micros: u64,
}
impl FrameStats {
/// A conservative enclosure in the frame's output pixels, when every view-sized operation has
/// a known bound. `None` leaves the choice to render the whole frame.
pub fn view_sized_bounds(&self) -> Option<Rect> {
self.view_sized_bounds.filter(|_| self.bounded_view_sized == self.view_sized)
}
}
impl super::Renderer {
/// Records an operation bounded by its own output clip. A nested effect can affect more than
/// its own clip once an ancestor filters or composites it, so only bound direct RGB output.
pub(crate) fn note_view_sized_clip(&mut self, f: &Frame, clip: Rect) {
self.stats.view_sized += 1;
if self.nested == 0 && self.offscreen_live == 0 && f.view == f.output && f.doc.color_mode == vectorcraft_doc::ColorMode::Rgb {
let bound = f.output.transform_rect_bbox(clip).inflate(1.0, 1.0);
if bound.is_finite() {
self.stats.bounded_view_sized += 1;
self.stats.view_sized_bounds = vectorcraft_geom::union_opt(self.stats.view_sized_bounds, Some(bound));
}
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct Frame<'a> {
/// Drawing into a multithreaded context: vello filter layers must be rendered offscreen.
pub(crate) mt: bool,
/// Set the flag if the incomplete paint would need a full render.
pub(crate) patch: Option<&'a std::cell::Cell<bool>>,
pub(crate) doc: &'a Document,
/// `doc`'s symbol art boxes, which culling measures symbol instances by ([`SymbolBoxes::quick`]).
pub(crate) symbols: &'a SymbolBoxes<'a>,
@@ -208,6 +235,17 @@ pub(crate) struct Frame<'a> {
}
impl Frame<'_> {
pub(crate) fn reject_patch(&self) -> bool {
self.patch.is_some_and(|hit| {
hit.set(true);
true
})
}
pub(crate) fn patch_rejected(&self) -> bool {
self.patch.is_some_and(std::cell::Cell::get)
}
/// Text space → device pixels when type is snapped to the pixel grid (Type anti-aliasing).
pub(crate) fn text_snap(&self, t: &TextObject) -> Option<Affine> {
(self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf)
+18 -2
View File
@@ -11,6 +11,12 @@ use super::{
RasterFx, Rect, RenderContext, Renderer, Shape, blend_mode, effects, fill_rule, paint, peniko,
};
/// The content to filter. An inner glow's output has an enclosing clip, while a shadow can spread beyond its content.
pub(super) enum FilterReach {
Clipped(Rect),
Spreads(Rect),
}
/// A hash of the names of `doc`'s swatches and patterns, of the paints and spot flags of its global
/// swatches, and of the Spot Colors option those colors depend on.
pub(crate) fn paint_names(doc: &Document) -> u64 {
@@ -596,15 +602,25 @@ impl Renderer {
&mut self,
ctx: &mut RenderContext,
f: &Frame,
reach: Rect,
reach: FilterReach,
blur: f64,
composite: Option<(vectorcraft_doc::color::BlendMode, f32)>,
draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame, Option<(vectorcraft_doc::color::BlendMode, f32)>),
) {
// A filter layer's coarser grid starts where its context does: at the corner of a context
// drawn single-threaded, and at the frame's edge for a region cropped to the frame.
let (reach, clipped) = match reach {
FilterReach::Clipped(rect) => (rect, true),
FilterReach::Spreads(rect) => (rect, false),
};
let screen = Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
self.stats.view_sized += usize::from(!f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen);
if !f.mt || f.view.transform_rect_bbox(reach).union(screen) != screen {
if clipped {
self.note_view_sized_clip(f, reach);
} else {
self.stats.view_sized += 1;
}
}
if !f.mt {
return self.inside_layer(|r| draw(r, ctx, f, composite));
}
+12 -4
View File
@@ -1,5 +1,6 @@
use super::bounds::{cull_bounds, effected_path_carrying, node_bezpath, rasterize_stage};
use super::entries::{Content, Drawn, FX_RASTER_BUDGET, FxGeom, Inputs, ItemGeom, Kept, KeptImage, Made, Reads, Shadow, ShadowEntry};
use super::pixels::FilterReach;
use super::predicates::{evaluates_live, is_container, rasterize_bounds, reads_outside, shifted};
use super::raster::{
DRAG_PIXEL_BUDGET, MAX_RASTERIZE, PIXEL_BUDGET, ViewCrop, content_changing, doc_raster_ppi, image_size, linear_key, pan_margin, pcolor,
@@ -134,6 +135,9 @@ impl Renderer {
// During a drag, a larger shadow on a multithreaded context is filtered within the
// drag's budget (`with_filters`), and no raster is kept.
if f.opts.dragging && f.mt && w * h > DRAG_PIXEL_BUDGET {
// The fallback can differ from a still raster (a glow blurs soft alpha here).
// A patch over a still frame cannot splice these pictures together.
self.stats.view_sized += 1;
return None;
}
let (w, h) = (w as u16, h as u16);
@@ -258,7 +262,7 @@ impl Renderer {
let reach = reach + Vec2::new(dx, dy);
#[cfg(test)]
note_silhouette();
self.with_filters(ctx, f, reach, blur, Some((mode, opacity)), |r, c, fr, comp| {
self.with_filters(ctx, f, FilterReach::Spreads(reach), blur, Some((mode, opacity)), |r, c, fr, comp| {
c.set_transform(fr.view);
c.push_layer(None, comp.map(|m| blend_mode(m.0)), comp.map(|m| m.1), None, Some(filter));
let ink = darkness.map_or(fr.ink, |d| fr.ink.darkened(d));
@@ -470,7 +474,7 @@ impl Renderer {
let opacity = self.opacity_of(a);
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_doc::color::BlendMode::Normal || a.isolate) {
let blends = self.blends_through(a);
let bounds = if blends { self.bounds_of(f.symbols, a) } else { None };
let bounds = if blends { self.frame_bounds_of(f, a) } else { None };
let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() };
self.group(ctx, f, comp, &mut |r, c, fr| r.draw_object_fx_art(c, fr, a, cache));
} else {
@@ -816,6 +820,9 @@ impl Renderer {
rfx: &[RasterFx],
paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame),
) {
if !rfx.is_empty() && f.reject_patch() {
return;
}
// Only the last MAX_RASTERIZE Rasterize effects are drawn.
let count = rfx.iter().filter(|fx| matches!(fx, RasterFx::Rasterize(_))).count();
let capped: Vec<RasterFx>;
@@ -995,7 +1002,7 @@ impl Renderer {
let RasterFx::InnerGlow { mode, opacity, blur, color, center } = fx else { continue };
let filter = shadow_filter(0.0, 0.0, *blur, pcolor(f.ink, color));
if pixels {
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |r, c, fr, comp| {
self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |r, c, fr, comp| {
if let Some((m, o)) = comp {
c.set_transform(Affine::IDENTITY);
c.push_layer(None, Some(blend_mode(m)), Some(o), None, None);
@@ -1029,7 +1036,7 @@ impl Renderer {
});
continue;
}
self.with_filters(ctx, f, g.bounding_box(), *blur, Some((*mode, *opacity)), |_, c, fr, comp| {
self.with_filters(ctx, f, FilterReach::Clipped(g.bounding_box()), *blur, Some((*mode, *opacity)), |_, c, fr, comp| {
// The blend layer goes outside the clip: a clip layer is isolated, so a blend
// inside it would mix with nothing instead of the content below.
if let Some((m, o)) = comp {
@@ -1128,6 +1135,7 @@ mod tests {
let opts = RenderOptions::default();
let frame = Frame {
mt: false,
patch: None,
doc: &doc,
symbols: &symbols,
view: Affine::IDENTITY,
+97
View File
@@ -1530,6 +1530,78 @@ fn moved_objects_draw_their_effect_rasters_while_interacting() {
/// 1600 × 1000 view near its corner needs more than the drag's budget. The
/// frame after the drag, of the same document, is what a fresh renderer draws, as is a frame
/// rendered while interacting without a drag (a dialog's preview).
#[test]
fn a_plain_patch_stops_at_a_raster_effect() {
let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("texture.texturizer", json!({}))]);
let plain = Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(94.0, 3.0, 96.0, 6.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap();
let (width, height) = (2000, 1600);
let view = Affine::scale(20.0);
let still = RenderOptions::default();
let mut renderer = Renderer::new();
renderer.threads = 0;
renderer.render(&doc, width, height, view, &still);
let total_drawn = renderer.stats.drawn;
let mut scratch = Renderer::new();
scratch.threads = 0;
let patch_view = Affine::translate((-1850.0, -50.0)) * view;
assert!(scratch.render_plain_patch(&doc, 100, 100, patch_view, &still).is_some(), "the distant patch does not draw the effect");
assert!(scratch.render_plain_patch(&doc, width, height, view, &still).is_none(), "a patch that draws the effect needs the full render");
assert!(scratch.stats.drawn < total_drawn, "the rejected patch does not draw the artwork after the effect");
}
#[test]
fn a_plain_patch_does_not_build_unrelated_3d_art_to_cull_it() {
let mut doc = doc_with(Rect::new(20.0, 20.0, 80.0, 76.0), Color::BLACK, vec![("threeD.extrude", json!({"depth": 10}))]);
let plain = Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(290.0, 10.0, 300.0, 20.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(doc.layers[0].id), usize::MAX, plain).unwrap();
let opts = RenderOptions::default();
let mut whole = Renderer::new();
whole.threads = 0;
whole.render(&doc, 350, 150, Affine::IDENTITY, &opts);
assert!(whole.stats.three_d_built > 0, "the fixture generates 3D art");
let mut scratch = Renderer::new();
scratch.threads = 0;
let patch = Affine::translate((-280.0, 0.0));
let result = scratch.render_plain_patch(&doc, 40, 30, patch, &opts);
assert_eq!(scratch.stats.three_d_built, 0, "fall back before rebuilding 3D art");
assert!(result.is_none());
let layer = doc.layers[0].id;
let art = doc.layers[0].children().unwrap()[0].clone();
doc.remove(art.id).unwrap();
let mut group = Node::group(doc.alloc_id(), vec![art.clone()]);
group.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.innerGlow".into(), params: json!({"blur": 4}), visible: true });
assert!(super::has_object_fx(&group), "this group uses the alternate bounds path");
let group = doc.insert(Some(layer), 0, group).unwrap();
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "alternate group bounds also need the 3D child");
doc.remove(group).unwrap();
let mut template = Node::layer(doc.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(0));
if let vectorcraft_doc::NodeKind::Layer { template: flag, children, .. } = &mut template.kind {
*flag = true;
children.push(art.clone());
}
let template = doc.insert(Some(layer), 0, template).unwrap();
let hidden = RenderOptions { hide_templates: true, ..opts.clone() };
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &hidden).is_none(), "layer bounds conservatively include hidden templates");
assert_eq!(scratch.stats.three_d_built, 0);
doc.remove(template).unwrap();
doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Solid".into(), art });
let instance = Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Solid".into(), xf: Affine::IDENTITY });
doc.insert(Some(layer), 0, instance).unwrap();
assert!(scratch.render_plain_patch(&doc, 40, 30, patch, &opts).is_none(), "a symbol's definition also needs 3D bounds");
}
#[test]
fn a_drag_renders_raster_effects_within_the_drag_budget() {
let effects = vec![("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 7, "opacity": 80})), ("texture.texturizer", json!({}))];
@@ -1581,6 +1653,31 @@ fn a_drag_renders_raster_effects_within_the_drag_budget() {
assert!(after == threaded().render(&scaled, 1600, 1000, view, &still).pixels, "the frame after the drag");
}
#[test]
fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() {
let doc = doc_with(
Rect::new(20.0, 20.0, 40.0, 40.0),
Color::BLACK,
vec![
("stylize.outerGlow", json!({"blur": 1.3, "color": "#ff0000", "opacity": 100, "mode": "normal"})),
("stylize.outerGlow", json!({"blur": 1.0, "color": "#0000ff", "opacity": 100, "mode": "normal"})),
],
);
let view = Affine::translate((600.0, 600.0)) * Affine::scale(40.0) * Affine::translate((-30.0, -30.0));
let mut still = Renderer::new();
still.threads = 2;
let still_pixels = still.render(&doc, 1200, 1200, view, &RenderOptions::default()).pixels;
assert_eq!(still.stats.view_sized, 0, "the still frame draws both whole rasters");
let mut drag = Renderer::new();
drag.threads = 2;
let opts = RenderOptions { interacting: true, dragging: true, ..Default::default() };
let drag_pixels = drag.render(&doc, 1200, 1200, view, &opts).pixels;
assert_eq!(drag.stats.previewed, 0, "the fallback filter fits the drag budget without downsampling");
assert!(drag_pixels != still_pixels, "a glow over the first glow differs from the fallback filter");
assert!(drag.stats.view_sized > 0, "the fallback must replace the whole frame");
}
/// While interacting, a group holding a symbol instance whose art lies outside the 20 × 20
/// square around the origin draws its drop shadow from the raster of an earlier frame. The
/// shadow is made from the instance's art, which the renderer measures the group's content by.
+7 -1
View File
@@ -114,6 +114,9 @@ impl Renderer {
}
fn group_offscreen(&mut self, ctx: &mut RenderContext, f: &Frame, c: Composite, r: Region, draw: &mut Content) {
if f.reject_patch() {
return;
}
let Composite { clip, blend, opacity, mask, isolated, .. } = c;
// A group that blends with its backdrop is drawn twice (over the backdrop, and alone for
// its coverage), and so is everything in it, so such groups nested in each other cost 2ⁿ.
@@ -309,7 +312,10 @@ impl Renderer {
/// `c` over the backdrop and its shape are drawn offscreen over `c`'s bounds, and `c` is drawn
/// as in the other knockout passes (groups in it can't copy their backdrop).
pub(crate) fn knockout_over(&mut self, ctx: &mut RenderContext, f: &Frame, c: &Arc<Node>, backdrop: &Arc<Pixmap>) {
let bounds = self.bounds_of(f.symbols, c);
let bounds = self.frame_bounds_of(f, c);
if f.patch_rejected() {
return;
}
let Some(r) = region(ctx, f, bounds) else { return };
let view = Affine::translate((-(r.x as f64), -(r.y as f64))) * f.view;
let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, r.w as f64, r.h as f64));
+5 -1
View File
@@ -583,7 +583,7 @@ impl Renderer {
let enclosing = std::mem::replace(&mut self.knockout, knockout);
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) {
let blends = self.blends_through(a);
let bounds = if blends { self.bounds_of(f.symbols, a) } else { None };
let bounds = if blends { self.frame_bounds_of(f, a) } else { None };
let comp = crate::group::Composite { blend: a.blend, opacity, isolated: a.isolate, blends, bounds, ..Default::default() };
self.group(ctx, f, comp, &mut |r, c, fr| r.draw_live_body(c, fr, a, true));
} else {
@@ -636,6 +636,10 @@ impl Renderer {
if !m.is_valid() {
return;
}
// A cropped mesh may lose a covered neighbor that supplied a color at its fringe.
if f.reject_patch() {
return;
}
if f.opts.outline {
let bp = m.lines().to_bezpath();
self.hairline(ctx, f, &bp, [0, 0, 0, 255]);
+1
View File
@@ -198,6 +198,7 @@ fn rasterize(
let v = view * def.instance_xf(o);
let frame = Frame {
mt: false,
patch: None,
doc,
symbols: &symbols,
view: v,
+66 -11
View File
@@ -113,9 +113,32 @@ impl Renderer {
/// set in one of the document's composite fonts draws in the document's definition, also when
/// no session has registered it (a document that is not in front, or read from a file).
pub fn render(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Rendered {
self.render_document(doc, width, height, view, opts, None)
}
/// Render a plain RGB canvas patch using a separate renderer. Raster effects and offscreen
/// group compositing require the full render.
pub fn render_plain_patch(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
if doc.color_mode != vectorcraft_doc::ColorMode::Rgb || opts.mask_view.is_some() || opts.supersample {
return None;
}
let hit = std::cell::Cell::new(false);
let image = self.render_document(doc, width, height, view, opts, Some(&hit));
(!hit.get()).then_some(image)
}
fn render_document(
&mut self,
doc: &Document,
width: u32,
height: u32,
view: Affine,
opts: &RenderOptions,
patch: Option<&std::cell::Cell<bool>>,
) -> Rendered {
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
self.render_as(doc, width, height, view, opts, false, 1)
self.render_as(doc, width, height, view, opts, false, 1, patch)
}
/// [`Self::render`], or with `inks` the ink amounts in the working CMYK space instead of
@@ -123,14 +146,24 @@ impl Renderer {
/// pixel of the output in pixels of this render: the supersampling factor while an export
/// draws its art at several times its size, else 1 ([`Frame::output`]).
#[allow(clippy::too_many_arguments)]
fn render_as(&mut self, doc: &Document, width: u32, height: u32, view: Affine, opts: &RenderOptions, inks: bool, cell: u32) -> Rendered {
fn render_as(
&mut self,
doc: &Document,
width: u32,
height: u32,
view: Affine,
opts: &RenderOptions,
inks: bool,
cell: u32,
patch: Option<&std::cell::Cell<bool>>,
) -> Rendered {
let start = now();
if opts.supersample && opts.anti_alias == AntiAlias::Art && opts.mask_view.is_none() {
let (w, h) = (width.clamp(1, MAX_CONTEXT_SIDE), height.clamp(1, MAX_CONTEXT_SIDE));
if let Some(k) = supersample_factor(w, h) {
let hard = RenderOptions { anti_alias: AntiAlias::None, supersample: false, ..opts.clone() };
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k);
let big = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
self.hairline = hairline;
let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize);
self.stats.micros = now().saturating_sub(start);
@@ -164,7 +197,7 @@ impl Renderer {
let symbols = doc.symbol_boxes().quick();
let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view;
let plates = proof::plate_lut(opts, doc);
let frame = Frame { mt: threads > 0, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() };
let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() };
self.begin_frame();
// View Opacity Mask: the mask's coverage in greyscale instead of the artwork.
if let Some(m) = opts.mask_view.and_then(|id| doc.node(id)).and_then(|n| n.extras().mask.as_deref()) {
@@ -199,7 +232,7 @@ impl Renderer {
self.draw_frame(&frame, w, h)
};
self.end_frame();
if !inks {
if !inks && !pixels.is_empty() {
proof::post(&mut pixels, opts);
}
self.stats.symbol_art = symbols.art_measured();
@@ -218,9 +251,8 @@ impl Renderer {
self.placed_frame = None;
}
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
/// so the nodes they hold go with them).
fn end_frame(&mut self) {
/// Drop stale bounds and paths, including old versions of edited nodes.
fn sweep_node_geometry(&mut self) {
let g = self.stamp;
// Swept however few the entries: each keeps its node alive, and an object dragged or
// edited makes a new node (with its layer) in every frame. Kept until there were 1,024 of
@@ -230,6 +262,23 @@ impl Renderer {
// A kept path stays while its object is in `geom`, which keeps the objects still drawn.
let geom = &self.geom;
self.kept.retain(|_, e| g - e.stamp <= 3 || geom.get(&(Arc::as_ptr(&e.node) as usize)).is_some_and(|k| Arc::ptr_eq(&k.node, &e.node)));
}
/// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update.
/// Age the measurement caches and keep the previous draw's effect rasters available.
pub fn finish_measurement_only(&mut self) {
self.stamp += 1;
self.sweep_node_geometry();
let g = self.stamp;
self.blends.retain(|_, e| g - e.2 <= 3);
self.let_go_of_measured();
}
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
/// so the nodes they hold go with them).
fn end_frame(&mut self) {
let g = self.stamp;
self.sweep_node_geometry();
if self.strokes.len() > 1024 {
self.strokes.retain(|_, e| g - e.stamp <= 3);
let strokes = &self.strokes;
@@ -309,11 +358,17 @@ impl Renderer {
} else {
self.draw_page(&mut ctx, f);
}
let pm = self.finish(&mut ctx, self.raster);
let pm = if f.patch_rejected() {
self.picture = None;
None
} else {
Some(self.finish(&mut ctx, self.raster))
};
self.contexts.push((threads, ctx));
if self.contexts.len() > 2 {
self.contexts.remove(0);
}
let Some(pm) = pm else { return Vec::new() };
let mut pixels = pm.data_as_u8_slice().to_vec();
if let Some(bg) = opts.background {
over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg)));
@@ -370,7 +425,7 @@ impl Renderer {
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
let _frame = vectorcraft_text::KeptLayoutsFrame::begin();
self.render_as(doc, w, h, view, opts, true, 1).pixels
self.render_as(doc, w, h, view, opts, true, 1, None).pixels
}
/// Render a single node (thumbnails, previews) fitted into `size`×`size` pixels.
@@ -427,7 +482,7 @@ impl Renderer {
ctx.set_aliasing_threshold(opts.anti_alias.threshold());
let symbols = doc.symbol_boxes().quick();
let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view;
let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None };
let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None };
let raster = std::mem::replace(&mut self.raster, raster_settings(opts));
self.begin_frame();
(self.knockout, self.nested, self.backdrop, self.picture) = (false, 0, None, None);
+64 -8
View File
@@ -7,10 +7,33 @@ use super::{
use crate::kept_paths::{self, KeptPath};
use crate::node_checks::{holds_measured_three_d, measures_three_d};
fn needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool {
measures_three_d(node)
|| matches!(&node.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.symbol(symbol).is_some_and(
|s| holds_measured_three_d(&s.art) || holds_instance(&s.art) && symbols.has_effects(symbol)
))
}
fn subtree_needs_three_d_bounds(symbols: &SymbolBoxes, node: &Node) -> bool {
needs_three_d_bounds(symbols, node)
|| node.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child)))
}
impl Renderer {
/// Cached cull bounds of a node (containers union their cached children), symbol instances
/// measured by their art box from `symbols`.
pub(crate) fn bounds_of(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<Rect> {
self.bounds_with_patch(symbols, a, None)
}
pub(crate) fn frame_bounds_of(&mut self, f: &Frame, a: &Arc<Node>) -> Option<Rect> {
self.bounds_with_patch(f.symbols, a, f.patch.map(|_| f))
}
fn bounds_with_patch(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, patch: Option<&Frame<'_>>) -> Option<Rect> {
if patch.is_some_and(Frame::patch_rejected) {
return None;
}
let key = Arc::as_ptr(a) as usize;
if let Some(e) = self.geom.get_mut(&key)
&& Arc::ptr_eq(&e.node, a)
@@ -18,6 +41,11 @@ impl Renderer {
e.stamp = self.stamp;
return e.bounds;
}
// The full renderer can reuse its 3D art. A cold scratch renderer may otherwise
// build it while calculating cull bounds, including bounds of symbol definitions.
if patch.is_some_and(|f| needs_three_d_bounds(symbols, a) && f.reject_patch()) {
return None;
}
let b = match &a.kind {
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } if !fx::has_object_fx(a) => {
let mut acc: Option<Rect> = None;
@@ -25,7 +53,10 @@ impl Renderer {
let source = a.extras().trace.is_some().then(|| children.first()).flatten();
for c in children {
if c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)) {
acc = vectorcraft_geom::union_opt(acc, self.bounds_of(symbols, c));
acc = vectorcraft_geom::union_opt(acc, self.bounds_with_patch(symbols, c, patch));
if patch.is_some_and(Frame::patch_rejected) {
return None;
}
}
}
acc
@@ -48,6 +79,14 @@ impl Renderer {
let pad = brush_fx::pad(symbols, a);
b.map(|b| fx::with_own_raster_reach(symbols, a, b).inflate(pad, pad))
}
// The fallback measures the whole subtree without going through the cached
// child traversal above. Reject cold measurement before entering it.
_ if patch.is_some_and(|f| {
a.children().is_some_and(|children| children.iter().any(|child| subtree_needs_three_d_bounds(symbols, child))) && f.reject_patch()
}) =>
{
return None;
}
_ => self.kept_bounds(symbols, a).unwrap_or_else(|| brush_fx::cull_bounds(symbols, a)),
};
self.geom.insert(key, GeomEntry { node: a.clone(), bounds: b, path: None, stamp: self.stamp });
@@ -227,7 +266,11 @@ impl Renderer {
if crate::node_checks::left_out(f.opts, f.doc, a) {
return true;
}
match self.bounds_of(f.symbols, a) {
let bounds = self.frame_bounds_of(f, a);
if f.patch_rejected() {
return true;
}
match bounds {
Some(b) => {
let pad = f.px * 2.0;
// Level of detail: leaves smaller than a quarter pixel are invisible.
@@ -241,7 +284,7 @@ impl Renderer {
}
pub(crate) fn draw_arc(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>) {
if self.skipped(f, a) {
if f.patch_rejected() || self.skipped(f, a) {
return;
}
// An image masked by one white shape painted straight into the shape, as an image in a
@@ -272,7 +315,10 @@ impl Renderer {
let Some(m) = a.extras().mask.as_deref().filter(|m| !m.disabled && !f.opts.outline && !self.is_shape(a)) else { return false };
// A masked object is a non-isolated group of its own, drawn over its own pixels: the
// mask is rendered over those only.
let bounds = self.bounds_of(f.symbols, a);
let bounds = self.frame_bounds_of(f, a);
if f.patch_rejected() {
return true;
}
let Some((r, sub)) = group::area(ctx, f, bounds) else { return true };
let Some(mask) = self.mask_values(&sub, m, r.w, r.h) else { return true };
let blends = a.blend != vectorcraft_color::BlendMode::Normal || (!a.isolate && self.blends_through(a));
@@ -296,6 +342,9 @@ impl Renderer {
/// The coverage of opacity mask `m` per output pixel (row-major): its art rendered offscreen,
/// as luminance ([`mask_value`]).
pub(super) fn mask_values(&mut self, f: &Frame, m: &vectorcraft_doc::OpacityMask, w: u16, h: u16) -> Option<Vec<u8>> {
if f.reject_patch() {
return None;
}
let mut mctx = f.offscreen_context(w, h);
// Mask art is a picture of its own: it takes no part in a knockout group around the object,
// and its luminance is that of its screen colours.
@@ -393,7 +442,7 @@ impl Renderer {
return;
}
// A cancelled export stops drawing; whoever asked for the picture drops it (see `cancel`).
if vectorcraft_doc::cancel::is_cancelled() {
if f.patch_rejected() || f.patch.is_some() && measures_three_d(n) && f.reject_patch() || vectorcraft_doc::cancel::is_cancelled() {
return;
}
if force {
@@ -679,7 +728,7 @@ impl Renderer {
let inverse = im.xf.inverse();
let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h);
for c in shapes {
if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) {
if let Some(b) = self.frame_bounds_of(f, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) {
for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] {
let p = inverse * kurbo::Point::new(q.0, q.1);
if p.x.is_finite() && p.y.is_finite() {
@@ -742,7 +791,11 @@ impl Renderer {
if crate::node_checks::left_out(f.opts, f.doc, c) {
return;
}
match self.bounds_of(f.symbols, c) {
let bounds = self.frame_bounds_of(f, c);
if f.patch_rejected() {
return;
}
match bounds {
Some(b) => {
let pad = f.px * 2.0;
if !rects_overlap(b.inflate(pad, pad), f.visible) {
@@ -781,7 +834,7 @@ impl Renderer {
self.dimmed(ctx, f, &mut |r, c, fr| rest.iter().for_each(|n| r.draw_arc(c, fr, n)));
}
} else {
for c in children {
for c in children.iter().take_while(|_| !f.patch_rejected()) {
self.draw_arc(ctx, f, c);
}
}
@@ -804,6 +857,9 @@ impl Renderer {
/// over the elements below it (the art below the group when the group is non-isolated and
/// drawn over a copy of it, see [`Self::group`] and [`Self::knockout_over`]).
pub(crate) fn draw_knockout(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc<Node>]) {
if f.reject_patch() {
return;
}
let backdrop = self.backdrop.take();
for c in Node::knockout_elements(children) {
if self.skipped(f, c) {
+4
View File
@@ -327,6 +327,10 @@ impl Renderer {
/// characters'. It also returns false for type whose offscreen drawing would be more than
/// [`MAX_RASTER_SIDE`] pixels a side or more than [`fx::PIXEL_BUDGET`] pixels in all.
fn draw_type_edges(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject, g: &Arc<TextGeom>, geom_kept: bool) -> bool {
// A smaller frame can fit the offscreen type that a full frame draws as Sharp.
if f.reject_patch() {
return true;
}
if proof::overprints(f.opts) && t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke) {
return false;
}
+36
View File
@@ -99,6 +99,42 @@ fn area(c: Changed) -> Rect {
}
}
#[test]
fn removing_the_last_blend_in_trim_view_repaints_the_artboard_edges() {
use vectorcraft_color::BlendMode;
let mut before = Document::new(110.0, 80.0);
let layer = before.layers[0].id;
for color in [Color::BLACK, Color::WHITE] {
let shape = rect(&mut before, Rect::new(-10.0, 18.0, 25.0, 44.0), color);
before.insert(Some(layer), usize::MAX, shape).unwrap();
}
let mut blend = rect(&mut before, Rect::new(70.0, 35.0, 85.0, 50.0), Color::rgb(0.7, 0.4, 0.3));
blend.blend = BlendMode::Multiply;
let id = before.insert(Some(layer), usize::MAX, blend).unwrap();
let mut after = before.clone();
after.node_mut(id).unwrap().blend = BlendMode::Normal;
let opts = RenderOptions { trim: true, ..Default::default() };
let mut r = Renderer::new();
let first = r.render(&before, W, H, view(), &opts);
let change = r.changed(&before, &after, &opts);
let last = Renderer::new().render(&after, W, H, view(), &opts);
patched(&mut r, &first, &after, change, &last, &opts);
assert_eq!(change, Changed::Everything);
assert!(matches!(r.changed(&before, &after, &RenderOptions::default()), Changed::Area(_)));
// An overprinting fill gets its blend while preparing the proof.
let mut overprinting = after.clone();
overprinting.node_mut(id).unwrap().appearance.fill_mut().unwrap().overprint = true;
let proof = RenderOptions { overprint_preview: true, ..opts };
let first = r.render(&overprinting, W, H, view(), &proof);
let change = r.changed(&overprinting, &after, &proof);
let last = Renderer::new().render(&after, W, H, view(), &proof);
patched(&mut r, &first, &after, change, &last, &proof);
assert_eq!(change, Changed::Everything, "the proofed fill changes the clipping mode");
}
#[test]
fn moving_an_object_changes_where_it_was_and_is() {
let (old, [loose, ..]) = document();
+24
View File
@@ -10,6 +10,30 @@ use crate::blobs::blob_key;
use crate::tests_fontchange::fonts_steady;
use crate::*;
#[test]
fn geometry_from_measurement_only_frames_releases_old_node_versions() {
let mut doc = Document::new(100.0, 100.0);
let layer = doc.layers[0].id;
let id = doc.alloc_id();
let path = Node::path(
id,
vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)),
vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
doc.insert(Some(layer), 0, path).unwrap();
let oldest = Arc::downgrade(&doc.layers[0].children().unwrap()[0]);
let mut renderer = Renderer::new();
let opts = RenderOptions::default();
for _ in 0..12 {
let mut next = doc.clone();
next.node_mut(id).unwrap().transform(Affine::translate((1.0, 0.0)), false);
assert!(matches!(renderer.changed(&doc, &next, &opts), Changed::Area(_)));
renderer.finish_measurement_only();
doc = next;
}
assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw");
}
/// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by
/// the tests running alongside).
fn png(w: u32, h: u32, seed: u8) -> Vec<u8> {
+11
View File
@@ -43,6 +43,17 @@ fn partial(a: &[u8]) -> usize {
a.iter().filter(|v| **v > 0 && **v < 255).count()
}
#[test]
fn a_plain_patch_defers_frame_sensitive_type_edges() {
let mut renderer = Renderer::new();
renderer.threads = 0;
let opts = RenderOptions::default();
let sharp = page(TypeAntiAlias::Sharp, None);
let crisp = page(TypeAntiAlias::Crisp, None);
assert!(renderer.render_plain_patch(&sharp, W, H, Affine::IDENTITY, &opts).is_some());
assert!(renderer.render_plain_patch(&crisp, W, H, Affine::IDENTITY, &opts).is_none());
}
/// The first pixels of `drawn` (type drawn with `m`) that are not the share `edge_coverage` gives
/// the same pixel of `sharp` (the type drawn with Sharp), within a step of rounding: (pixel,
/// Sharp, drawn).
+4
View File
@@ -276,6 +276,10 @@ fn a_frame_counts_the_art_it_draws_by_its_size() {
let mut r = Renderer::new();
r.render(&mesh(100.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default());
assert_eq!(r.stats.view_sized, 0, "a mesh within the mesh buffer");
assert!(
r.render_plain_patch(&mesh(100.0), 60, 60, Affine::translate((-50.0, -50.0)), &RenderOptions::default()).is_none(),
"a patch through a mesh must fall back even when the full mesh fits"
);
r.render(&mesh(3000.0), 2100, 2100, Affine::IDENTITY, &RenderOptions::default());
assert!(r.stats.view_sized > 0, "a mesh past the mesh buffer");
}
+33 -8
View File
@@ -4,7 +4,7 @@
use std::mem;
use craft::ui::dialog::{DialogResult, StackDialog};
use craft::ui::dialog::{DialogId, DialogResult, StackDialog};
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog};
use egui::Context;
use serde_json::{Value, json};
@@ -32,13 +32,27 @@ pub(crate) struct Spec {
/// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document.
#[derive(Default)]
pub(crate) struct AddonDialogs {
open: Option<(craft::ui::dialog::DialogId, &'static Spec)>,
open: Option<Open>,
preview: LivePreview,
}
#[derive(Clone, Copy)]
struct Open {
id: DialogId,
spec: &'static Spec,
document: Option<u64>,
}
impl Open {
fn on_document(self, app: &VectorcraftApp) -> bool {
self.document == app.session.active().map(|state| state.uid)
}
}
/// Closes the open add-on dialog without an answer and rolls its preview back.
fn close_open(app: &mut VectorcraftApp) {
let Some((id, _)) = app.addon_dialogs.open.take() else { return };
let Some(open) = app.addon_dialogs.open.take() else { return };
let id = open.id;
if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) {
host.with(|h| {
h.cancel_by_id(&ctx, id);
@@ -46,7 +60,10 @@ fn close_open(app: &mut VectorcraftApp) {
let _ = h.take_by_id::<HostedParamDialog>(id);
});
}
mem::take(&mut app.addon_dialogs.preview).cancel(app);
let preview = mem::take(&mut app.addon_dialogs.preview);
if open.on_document(app) {
preview.cancel(app);
}
}
/// Opens the dialog `spec` describes over `fields`, built each pass by `build`.
@@ -62,7 +79,7 @@ pub(crate) fn open(
close_open(app);
let id = dialog.id();
host.with(|h| h.open(dialog));
app.addon_dialogs.open = Some((id, spec));
app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) });
Ok(json!({ "dialog": spec.command }))
}
@@ -94,10 +111,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
}
fn pump_commit(app: &mut VectorcraftApp) {
let Some((id, spec)) = app.addon_dialogs.open else { return };
let Some(open) = app.addon_dialogs.open else { return };
let Some(host) = app.dialogs() else { return };
let Open { id, spec, .. } = open;
let on_document = open.on_document(app);
if !on_document {
// Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing.
app.addon_dialogs.preview = LivePreview::default();
}
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), (spec.params)(d.fields()))));
if let Some((previewing, params)) = &live {
if on_document && let Some((previewing, params)) = &live {
let mut preview = mem::take(&mut app.addon_dialogs.preview);
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
let answer = preview.run(app, *previewing, label, spec.command, params);
@@ -115,7 +138,9 @@ fn pump_commit(app: &mut VectorcraftApp) {
app.addon_dialogs.open = None;
let preview = mem::take(&mut app.addon_dialogs.preview);
// The dialog is closed already, so a refusal can only go to the status line.
if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
if !on_document {
app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned());
} else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
app.status(error);
}
}
@@ -76,13 +76,29 @@ fn new_app() -> VectorcraftApp {
/// Two rectangles without a stroke, both selected.
fn two_rects() -> VectorcraftApp {
let mut app = new_app();
select_two_rects(&mut app);
app
}
fn select_two_rects(app: &mut VectorcraftApp) {
app.run("paint.setStroke", json!({"none": true})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap();
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
app.run("select.all", json!({})).unwrap();
}
fn two_drawings() -> VectorcraftApp {
let mut app = two_rects();
app.run("file.new", json!({"width": 700, "height": 500})).unwrap();
select_two_rects(&mut app);
activate(&mut app, 0);
app
}
fn activate(app: &mut VectorcraftApp, index: usize) {
app.run("document.activate", json!({"index": index})).unwrap();
}
fn two_circles() -> VectorcraftApp {
let mut app = new_app();
let ids: Vec<u64> = [100.0, 160.0]
@@ -280,3 +296,68 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview()
assert_eq!(app.dialogs().unwrap().with(|h| h.open_dialogs().len()), 1);
assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back");
}
#[test]
fn an_add_on_preview_waits_for_its_opening_drawing() {
let mut app = two_drawings();
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 in the opening drawing");
activate(&mut app, 1);
let undo = undo_len(&app);
frame(&mut app);
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, undo), "the other drawing never shows the preview");
assert!(!app.session.in_interaction());
activate(&mut app, 0);
assert_eq!(x0(&app, 1), 100.0, "the old preview rolled back when leaving the drawing");
frame(&mut app);
assert_eq!(x0(&app, 1), 30.0, "the retained settings preview again on the original drawing");
cancel(&app, id);
frame(&mut app);
assert_eq!(x0(&app, 1), 100.0);
}
#[test]
fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() {
let mut app = two_drawings();
let source_undo = undo_len(&app);
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!(false));
assert!(confirm(&app, id));
activate(&mut app, 1);
let target_undo = undo_len(&app);
frame(&mut app);
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, target_undo), "the other drawing is never rearranged or given an undo step");
assert_eq!(app.session.active_index(), Some(1));
activate(&mut app, 0);
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo));
}
#[test]
fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() {
let mut app = two_drawings();
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);
activate(&mut app, 1);
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let other = app.session.active().unwrap().doc.clone();
cancel(&app, id);
let context = ctx(&app);
super::pump(&mut app, &context);
let active = app.session.active().unwrap();
assert_eq!(active.interaction.as_ref().map(|edit| edit.label.as_str()), Some("Other drawing's edit"));
assert_eq!(active.doc, other);
}
+4 -1
View File
@@ -120,7 +120,9 @@ impl VectorcraftApp {
last_ms: 0.0,
moved: false,
from_worker: false,
worker_parts: false,
whole_frames: false,
view_sized_bounds: None,
web_patch_renderer: None,
reused: None,
waits_for_still: cfg!(target_arch = "wasm32"),
still: None,
@@ -242,6 +244,7 @@ impl VectorcraftApp {
three_d_dialog: None,
three_d: Default::default(),
export_dialogs: Default::default(),
package_document: None,
web_export: Default::default(),
flattener_preview: Default::default(),
flatten_dialog: Default::default(),
+10 -4
View File
@@ -25,10 +25,16 @@ pub struct CanvasCache {
/// The frame shown was rendered on the worker: an interaction's frames stay there
/// ([`canvas::show`]).
pub from_worker: bool,
/// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn
/// again on this thread would not have matched the frame around it: until the worker's next
/// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]).
pub worker_parts: bool,
/// The frame shown drew art in a way that depends on its size, or a part of it drawn again on
/// this thread would not have matched the frame around it. Edits that reach the affected area
/// render whole, on the worker when the frame is heavy ([`canvas::show`]).
pub whole_frames: bool,
/// The shown web frame can still be patched outside this enclosure in its own raster pixels.
/// Present only when all frame-size-dependent output has a known bound.
pub view_sized_bounds: Option<vectorcraft_geom::Rect>,
/// Draws for a patch against a web frame with bounded view-sensitive art.
/// The renderer of the whole frame keeps its raster and derived-art caches across these patches.
pub web_patch_renderer: Option<Box<vectorcraft_render::Renderer>>,
/// The frame shown holds pixels the worker copied from its last frame, and when it was shown
/// (seconds, egui's input time): it renders whole once it has been shown for
/// [`canvas::STILL_SECS`] with the view unmoved.
+7 -4
View File
@@ -173,7 +173,9 @@ impl Component for CanvasDrops<'_> {
let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone())));
let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone())));
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| Some(Payload::Symbol(d.grabbed.clone())));
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| Some(Payload::Brush(d.grabbed.clone())));
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| {
(d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone()))
});
let library = Target::new(rect, view, covered, |d: &ListDrag<LibraryKey>| Some(Payload::Library(d.grabbed.clone())));
let panel = cx.drop_target::<PanelDrag, _>(&panel);
let style = cx.drop_target::<StyleDrag, _>(&style);
@@ -336,7 +338,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => {
run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]}))
}
Payload::Brush(key) => match hit() {
Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() {
None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})),
None => Ok(()),
Some(hit) => {
@@ -344,13 +346,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
run(app, "brush.apply", json!({"name": key.name, "ids": [owner]}))
}
},
Payload::Brush(_) => Ok(()),
Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => {
let Some(hit) = hit() else { return Ok(()) };
let top = top_object(app, &hit)?;
run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy}))
}
Payload::Style(_) => Ok(()),
Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => {
Payload::Panel(drag @ PanelDrag::Paint { params, paint, .. }) if !params.is_null() => {
if let Some(color) = paint.color()
&& crate::panels::proxy_cmd(app, false) == "paint.setFill"
&& let Some((id, points)) = selected_mesh_drop(app, at, zoom)
@@ -359,7 +362,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
return run(app, "object.mesh.setPointColor", params);
}
let Some(hit) = hit() else { return Ok(()) };
let mut params = params.clone();
let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| st.uid)) else { return Ok(()) };
params["ids"] = json!([owner(app, &hit)?]);
params["focus"] = json!(false);
let cmd = crate::panels::proxy_cmd(app, false);
+102 -1
View File
@@ -10,7 +10,7 @@ use vectorcraft_engine::Session;
use vectorcraft_geom::Point;
use super::{CarriedArt, Dropped, Payload, apply_drop};
use crate::panel_drag::PanelDrag;
use crate::panel_drag::{PanelDrag, SwatchRows};
use crate::panels::brushes::{BrushKey, BrushLibraries};
use crate::panels::graphic_styles::StyleDrag;
use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _};
@@ -202,6 +202,32 @@ fn a_drop_runs_the_effect_of_its_payload() {
symbol_at(&app, empty);
}
#[test]
fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() {
let (mut app, ctx) = app_with_canvas();
let make_brush = |app: &mut VectorcraftApp, width| {
app.run("shape.rectangle", json!({"x": 15, "y": 15, "width": width, "height": 30})).unwrap();
app.run("brush.new", json!({"name": "Shared Brush", "type": "art"})).unwrap();
};
make_brush(&mut app, 30);
let document = app.session.active().unwrap().uid;
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
make_brush(&mut app, 60);
app.run("brush.setCurrent", json!({"name": null})).unwrap();
let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap());
frame(&mut app, &ctx, vec![]);
let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone());
let before = brush_of(&app);
assert!(before.is_none());
let history = undo_len(&app);
let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false });
drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap();
assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone");
drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap();
assert_eq!(undo_len(&app), history, "no artwork is placed on empty canvas either");
}
/// A symbol of another document is added here and placed in one undo step, the source is unchanged, and a symbol of
/// a closed document places nothing.
#[test]
@@ -230,6 +256,81 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() {
/// A colour dropped on a selected mesh recolors the point under the pointer, else the patch's four points; the same
/// colour again records no step.
#[test]
fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() {
let (mut app, ctx) = app_with_canvas();
let name = "Shared Swatch";
let at = Point::new(250.0, 70.0);
let add_target = |app: &mut VectorcraftApp| {
NodeId(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap())
};
let fill = |app: &VectorcraftApp, target| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint();
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
let source = app.session.active().unwrap();
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true };
let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None };
let local_target = add_target(&mut app);
app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap();
let edited = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
drop_at(&mut app, Payload::Panel(payload.clone()), at, DropOperation::Move).unwrap();
assert_eq!(fill(&app, local_target), edited, "a same-document drop still resolves the swatch by name");
assert_ne!(edited, paint);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap();
let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
let target = add_target(&mut app);
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
frame(&mut app, &ctx, vec![]);
drop_at(&mut app, Payload::Panel(payload), at, DropOperation::Move).unwrap();
assert_eq!(fill(&app, target), paint);
assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination);
}
#[test]
fn a_swatch_drag_keeps_its_color_after_next_document() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::runtime::drag;
use egui::{Key, Modifiers};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let name = "Shared Swatch";
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
let source = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap();
let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
let destination = app.session.active().unwrap().uid;
app.run("window.previousDocument", json!({})).unwrap();
let mut panel = Panel::new(app, |app, ui| {
app.sync_views();
ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| {
crate::panels::swatches::show(app, ui);
});
canvas::show(app, ui);
});
let label = "Shared Swatch, #ff0000";
let from = panel.rect(label).center();
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0));
panel.drag_hold_role(label, Role::LIST_ITEM, to - from);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the Swatches row starts a paint drag");
panel.key(Key::F6, Modifiers::COMMAND);
assert_eq!(panel.app().session.active().unwrap().uid, destination);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the drag stays held during Next Document");
panel.release();
let app = panel.app();
assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source);
}
#[test]
fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() {
use vectorcraft_doc::GradientMesh;
+76 -23
View File
@@ -55,12 +55,16 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo
/// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve)
/// shows in the frame it is made in, when the part's share of the frame's last whole render time
/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their
/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame
/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn
/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]):
/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What
/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to
/// draw the part again.
/// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame
/// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects,
/// and this thread's doesn't. A web frame with known view-sensitive output bounds can still be
/// patched outside them, accounting for the patch's rounding. Otherwise view-sensitive art or
/// an earlier rejected patch requires a whole render ([`crate::CanvasCache::whole_frames`]).
/// A frame that drew nothing from moved rasters or at a
/// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction
/// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change.
/// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what
/// it measures (a 3D effect's art) to draw the part again.
pub(super) fn changed_pixels(
app: &mut VectorcraftApp,
key: &CacheKey,
@@ -70,14 +74,20 @@ pub(super) fn changed_pixels(
w: u32,
h: u32,
) -> Option<Option<[u32; 4]>> {
let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| o == opts)?;
let shown_key = app.canvas.key.as_ref()?;
// The worker keeps its still rasters while the UI thread draws the first edit. Rendering only
// part of a UI-thread frame could evict its own still rasters before a drag needs them.
let starting = app.canvas.from_worker && !app.canvas.moved && key.interacting && !shown_key.interacting;
let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| {
o == opts || starting && vectorcraft_render::RenderOptions { interacting: opts.interacting, dragging: opts.dragging, ..o.clone() } == *opts
})?;
// A viewed opacity mask shows its coverage wherever its art reaches, past its object's bounds.
if opts.mask_view.is_some() {
return None;
}
let shown_key = app.canvas.key.as_ref()?;
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() };
let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some());
let (interacting, dragging) = if starting { (shown_key.interacting, shown_key.dragging) } else { (key.interacting, key.dragging) };
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, interacting, dragging, ..key.clone() };
let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.reused.is_some());
// A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]).
let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision);
if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way {
@@ -94,6 +104,14 @@ pub(super) fn changed_pixels(
None => Some(None),
Some([x0, y0, x1, y1]) => {
let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h));
let patch = Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1));
if app.canvas.whole_frames && app.canvas.view_sized_bounds.is_none_or(|bounds| !bounds.intersect(patch).is_zero_area()) {
return None;
}
// A full draw can use 3D art measured here. Do not rebuild it in the scratch renderer.
if app.canvas.view_sized_bounds.is_some() && app.canvas.renderer.measured_bytes() > 0 {
return None;
}
let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h));
(share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1]))
}
@@ -102,6 +120,14 @@ pub(super) fn changed_pixels(
}
}
fn web_patch_renderer(slot: &mut Option<Box<vectorcraft_render::Renderer>>) -> &mut vectorcraft_render::Renderer {
slot.get_or_insert_with(|| {
let mut renderer = vectorcraft_render::Renderer::new();
renderer.threads = 0;
Box::new(renderer)
})
}
/// `a..b` of `0..n`, grown to whole eighths of `n` and moved back into `0..n`: the parts of a
/// frame rendered again come in few sizes, which keep the contexts the renderer keeps.
fn in_steps(a: u32, b: u32, n: u32) -> (u32, u32) {
@@ -597,7 +623,9 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate:
app.canvas.reused = done.reused.then(|| frame::clock(ctx));
app.canvas.moved = done.moved > 0;
app.canvas.from_worker = true;
app.canvas.worker_parts = done.view_sized;
app.canvas.whole_frames = done.view_sized;
app.canvas.view_sized_bounds = None;
app.canvas.web_patch_renderer = None;
}
/// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas.
@@ -686,25 +714,38 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f
/// key: only the document changed since the frame shown, in that part of it
/// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's.
///
/// Over a frame the worker rendered, a part that drew raster effects from rasters made before
/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]),
/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]),
/// would not match the frame around it: it is not drawn, false is returned, and the edits after it
/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]).
/// A part that drew art in a way that depends on the frame's size
/// ([`vectorcraft_render::FrameStats::view_sized`]), draws effects at a drag's lower resolution
/// ([`vectorcraft_render::FrameStats::previewed`]), or uses this thread's moved rasters over a
/// worker frame, could differ from the frame around it. It is not drawn, false is returned,
/// and the edits after it render whole until the next whole frame is
/// shown ([`crate::CanvasCache::whole_frames`]).
fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool {
let Frame { key, doc, effects, view, opts, pixel, .. } = frame;
let t0 = monotonic_ms();
if region.is_none() {
// Nothing in view to draw again: what was made to measure the edit isn't drawn.
app.canvas.renderer.let_go_of_measured();
app.canvas.renderer.finish_measurement_only();
}
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) {
let renderer = &mut app.canvas.renderer;
let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view;
let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts));
if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) {
app.canvas.worker_parts = true;
let plain_patch = app.canvas.view_sized_bounds.is_some();
let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer };
let part = effects.view(|| {
if plain_patch {
renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts)
} else {
Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts))
}
});
let Some(mut part) = part else {
app.canvas.view_sized_bounds = None;
return false;
};
if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 {
app.canvas.whole_frames = true;
app.canvas.view_sized_bounds = None;
return false;
}
let width = part.width;
@@ -712,7 +753,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
let color = color_image(&part);
let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
tex.set_partial([x0 as usize, y0 as usize], color, options);
app.canvas.moved |= app.canvas.renderer.stats.moved > 0;
app.canvas.moved |= renderer.stats.moved > 0;
if plain_patch {
app.canvas.renderer.finish_measurement_only();
}
}
app.canvas.key = Some((*key).clone());
app.canvas.shown = Some(((*doc).clone(), opts.clone()));
@@ -768,6 +812,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
// thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a
// part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]).
let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc);
if !same_doc {
app.canvas.web_patch_renderer = None;
}
let settling = app.canvas.moved && !key.interacting;
let staying = key.interacting && app.canvas.from_worker;
// A document's first frame (opened, or its tab chosen) renders on the worker too: how long it
@@ -791,7 +838,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
(Some(worker), true, false) => {
// The worker draws the frame: what this thread's renderer made to measure the edit
// isn't drawn here.
app.canvas.renderer.let_go_of_measured();
app.canvas.renderer.finish_measurement_only();
let queued = worker.submit(crate::render_worker::Job {
key: key.clone(),
doc: doc.clone(),
@@ -824,6 +871,12 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
app.perf.render_ms = monotonic_ms() - t0;
app.canvas.last_ms = app.perf.render_ms;
app.canvas.moved = app.canvas.renderer.stats.moved > 0;
let stats = app.canvas.renderer.stats;
app.canvas.whole_frames = stats.view_sized > 0 || stats.previewed > 0;
app.canvas.view_sized_bounds = if app.canvas.waits_for_still && stats.previewed == 0 { stats.view_sized_bounds() } else { None };
if app.canvas.view_sized_bounds.is_none() {
app.canvas.web_patch_renderer = None;
}
app.canvas.from_worker = false;
app.canvas.reused = None;
}
+189 -19
View File
@@ -964,6 +964,144 @@ fn an_edit_renders_only_its_part_of_the_canvas() {
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "a new view renders all of it");
}
/// An edit over art that a part of the canvas would draw with other pixels than the whole canvas
/// does ([`vectorcraft_render::FrameStats::view_sized`]) renders all of it, on this thread too,
/// and shows what a fresh renderer draws: a blur cropped to the view, which the frame shown drew,
/// and an inner glow that fits the view but not the part the edit changed.
#[test]
fn an_edit_over_art_drawn_for_the_frames_size_renders_all_of_it() {
keeping_color_settings(an_edit_over_art_drawn_for_the_frames_size);
}
fn an_edit_over_art_drawn_for_the_frames_size() {
for cropped in [true, false] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.ui.task_bar = false;
app.ui.view.rulers = false;
app.canvas.worker_started = true; // every frame on this thread, however long it takes
app.canvas.renderer.threads = 2;
let (rect, effect) = if cropped {
(json!({"x": 0, "y": 0, "width": 400, "height": 300}), json!({"effect": "blur.gaussian", "params": {"radius": 8}}))
} else {
(json!({"x": 150, "y": 110, "width": 100, "height": 80}), json!({"effect": "stylize.innerGlow", "params": {"blur": 8}}))
};
let art = app.run("shape.rectangle", rect).unwrap()["id"].clone();
let mut effect = effect;
effect["ids"] = json!([art]);
app.run("effect.apply", effect).unwrap();
let id = app.run("shape.rectangle", json!({"x": 145, "y": 105, "width": 10, "height": 10})).unwrap()["id"].clone();
let outside = app.run("shape.rectangle", json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap()["id"].clone();
app.run("select.none", json!({})).unwrap();
let ctx = crate::testing::ui_context();
shapes(&mut app, &ctx);
// A new view: the next frame renders whole.
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = if cropped { (16.0, Point::new(150.0, 110.0)) } else { (1.5, Point::new(200.0, 150.0)) };
}
// Where the canvas texture changed in a frame, and its pixels there.
let canvas = |app: &VectorcraftApp, mut delta: egui::TexturesDelta| {
let tex = app.canvas.texture.as_ref().map(|t| t.id());
let set = delta.set.iter().find(|(t, _)| tex == Some(**t)).and_then(|(_, d)| d.last()).map(|d| {
let egui::ImageData::Color(img) = &d.image;
(d.pos, img.pixels.clone())
});
delta.clear();
set
};
let (_, delta) = frame_output(&mut app, &ctx);
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it");
assert_eq!(app.canvas.renderer.stats.view_sized > 0, cropped, "the frame shown drew art for its size: {cropped}");
assert_eq!(app.canvas.whole_frames, cropped, "the frame records whether its art depends on its size");
app.run("paint.setFill", json!({"color": "#00ff00", "ids": [outside]})).unwrap();
let (_, delta) = frame_output(&mut app, &ctx);
assert!(canvas(&app, delta).is_none(), "an edit outside the view does not upload a new canvas");
app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap();
let (_, delta) = frame_output(&mut app, &ctx);
let (pos, edited) = canvas(&app, delta).expect("the edit shows");
assert!(pos.is_none(), "the edit renders all of it, cropped: {cropped}");
assert_eq!(app.canvas.whole_frames, cropped, "the replacement records its own render stats");
app.canvas.renderer = vectorcraft_render::Renderer::new();
app.canvas.renderer.threads = 2;
app.canvas.key = None;
let (_, delta) = frame_output(&mut app, &ctx);
let fresh = canvas(&app, delta).map(|(_, px)| px);
assert!(fresh.as_ref() == Some(&edited), "what a fresh renderer draws, cropped {cropped}: {}", differing(&edited, fresh.as_deref()));
}
}
#[test]
fn web_partial_redraws_skip_unchanged_view_sensitive_art() {
keeping_color_settings(|| {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
app.ui.task_bar = false;
app.ui.view.rulers = false;
app.canvas.worker_started = true;
app.canvas.waits_for_still = true;
app.canvas.renderer.threads = 0;
let glow = app.run("shape.rectangle", json!({"x": 55, "y": 70, "width": 55, "height": 55})).unwrap()["id"].clone();
app.run("effect.apply", json!({"ids": [glow], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
let large = app.run("shape.rectangle", json!({"x": -980, "y": -700, "width": 965, "height": 1010})).unwrap()["id"].clone();
app.run("effect.apply", json!({"ids": [large], "effect": "texture.texturizer", "params": {}})).unwrap();
let far = app.run("shape.rectangle", json!({"x": 300, "y": 200, "width": 12, "height": 12})).unwrap()["id"].clone();
let near = app.run("shape.rectangle", json!({"x": 60, "y": 80, "width": 12, "height": 12})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
app.run("select.none", json!({})).unwrap();
let ctx = crate::testing::ui_context();
shapes(&mut app, &ctx);
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = (1.2, Point::new(200.0, 150.0));
}
// Start from a full raster at the chosen view rather than waiting for the reprojected view to settle.
app.canvas.key = None;
let read = |app: &mut VectorcraftApp| {
let (_, mut delta) = frame_output(app, &ctx);
let tex = app.canvas.texture.as_ref().unwrap().id();
delta.set.remove(&tex).and_then(|mut uploads| uploads.pop()).expect("the edit uploads canvas pixels")
};
let first = read(&mut app);
assert!(first.pos.is_none());
assert!(app.canvas.renderer.stats.view_sized > 0, "single-threaded filter layers depend on the frame size");
let egui::ImageData::Color(first) = first.image;
let mut composed = (*first).clone();
for color in ["#ff0000", "#00ff00"] {
app.run("paint.setFill", json!({"ids": [far], "color": color})).unwrap();
let delta = read(&mut app);
let [x, y] = delta.pos.expect("an edit away from the glow uploads only a patch");
let egui::ImageData::Color(patch) = delta.image;
for row in 0..patch.height() {
let start = (y + row) * composed.width() + x;
composed.pixels[start..start + patch.width()].copy_from_slice(&patch.pixels[row * patch.width()..(row + 1) * patch.width()]);
}
}
let key = app.canvas.key.as_ref().unwrap();
let view = app.canvas_view().unwrap();
let (w, h, view) = frame_view(key.pixel, (key.w, key.h), &view, key.ppp);
let (doc, still) = app.canvas.shown.as_ref().unwrap();
let drag = vectorcraft_render::RenderOptions { interacting: true, dragging: true, ..still.clone() };
let mut cold = vectorcraft_render::Renderer::new();
cold.threads = 0;
cold.render(doc, w, h, view, &drag);
assert!(cold.stats.previewed > 0, "a cold renderer draws the large effect at drag resolution");
app.canvas.renderer.render(doc, w, h, view, &drag);
assert_eq!(app.canvas.renderer.stats.previewed, 0, "distant canvas patches left the full-resolution effect available for the drag");
// The old glow's bounds survive successive partial renders, even though neither draws it.
app.run("paint.setFill", json!({"ids": [near], "color": "#0202ee"})).unwrap();
let overlap = read(&mut app);
assert!(overlap.pos.is_none(), "editing inside the old glow's bounds renders the whole frame");
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
let restored = read(&mut app);
assert!(restored.pos.is_none());
let egui::ImageData::Color(restored) = restored.image;
assert_eq!(restored.size, composed.size);
assert!(restored.pixels == composed.pixels, "partial updates equal a full redraw: {}", differing(&composed.pixels, Some(&restored.pixels)));
app.run("effect.apply", json!({"ids": [far], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
assert!(read(&mut app).pos.is_none(), "the new glow in the part also requires a whole frame");
});
}
/// A canvas more device pixels across than the largest texture side the display supports renders
/// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel
/// Preview's region of document pixels stays within it too.
@@ -1737,10 +1875,15 @@ fn dragging_with_raster_effects() {
/// without a drag, renders without `dragging` and draws the same.
#[test]
fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() {
keeping_color_settings(a_drag_at_a_lower_resolution);
keeping_color_settings(|| a_drag_at_a_lower_resolution(false));
}
fn a_drag_at_a_lower_resolution() {
#[test]
fn a_whole_drag_preview_keeps_the_next_canvas_render_whole() {
keeping_color_settings(|| a_drag_at_a_lower_resolution(true));
}
fn a_drag_at_a_lower_resolution(fits_frame: bool) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true; // render on this thread
@@ -1763,7 +1906,7 @@ fn a_drag_at_a_lower_resolution() {
};
run(&mut app, vec![]);
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = (32.0, Point::new(200.0, 155.0));
(vm.zoom, vm.center) = (if fits_frame { 6.4 } else { 32.0 }, Point::new(200.0, 155.0));
}
let still = run(&mut app, vec![]).expect("the zoomed view renders");
assert_eq!(app.canvas.renderer.stats.previewed, 0, "a still frame");
@@ -1771,10 +1914,19 @@ fn a_drag_at_a_lower_resolution() {
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(&mut app, vec![egui::Event::PointerMoved(at)]);
run(&mut app, vec![button(at, true)]);
if fits_frame {
// Force the first move to draw a whole frame without a previous effect raster.
app.canvas.renderer = vectorcraft_render::Renderer::new();
app.canvas.key = None;
}
for step in [1.0, 2.0] {
let drawn = run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]).expect("each frame of the drag renders");
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}");
assert_eq!(app.canvas.renderer.stats.previewed, 1, "the filtered content, step {step}");
if fits_frame {
assert_eq!(app.canvas.renderer.stats.view_sized, 0, "only the drag budget reduced the raster");
assert!(app.canvas.whole_frames, "a whole drag preview cannot accept a full-resolution patch");
}
assert!(app.canvas.moved);
assert!(drawn != still, "the rectangle moved, step {step}");
}
@@ -1788,9 +1940,15 @@ fn a_drag_at_a_lower_resolution() {
assert!(fresh.as_ref() == Some(&after), "the frame after the drag is what a fresh renderer draws: {}", differing(&after, fresh.as_deref()));
// A dialog's preview: an interaction, and no drag.
app.session.begin_interaction("Texturizer").unwrap();
assert!(run(&mut app, vec![]) == Some(after), "a dialog's preview draws the effect at full resolution");
app.session.preview("effect.setParams", &json!({"index": 0, "item": null, "ids": [id], "params": {"relief": 20}})).unwrap();
let preview = run(&mut app, vec![]).expect("the preview renders");
assert!(preview != after, "the preview changes the art");
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && !k.dragging));
assert_eq!(app.canvas.renderer.stats.previewed, 0);
app.canvas.renderer = vectorcraft_render::Renderer::new();
app.canvas.key = None;
let fresh = run(&mut app, vec![]);
assert!(fresh.as_ref() == Some(&preview), "a dialog's preview draws the effect at full resolution: {}", differing(&preview, fresh.as_deref()));
}
/// Where frame `b` differs from `a`: how many pixels, the first, and the largest channel difference.
@@ -1885,10 +2043,10 @@ fn a_drag_over_a_wide_blur() {
}
}
/// An interaction's frames stay on the worker once it drew the frame shown, however fast that
/// frame was: the worker's renderer keeps the effect rasters that made it fast, and this
/// thread's renderer, without them, would draw the next frame slowly. Without a frame from the
/// worker, a fast frame renders on this thread as before.
/// An interaction's whole frames (here after a new zoom) stay on the worker once it drew the frame
/// shown, however fast that frame was: the worker's renderer keeps the effect rasters that made it
/// fast, and this thread's renderer, without them, would draw the next frame slowly. Without a
/// frame from the worker, a fast frame renders on this thread as before.
#[test]
fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
@@ -1901,6 +2059,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone());
(app.canvas.from_worker, app.canvas.last_ms) = (from_worker, 1.0);
app.session.begin_interaction("Preview").unwrap();
if let Some(vm) = app.view_mut() {
vm.zoom *= 1.25;
}
shapes(&mut app, &ctx);
let pending = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| k.interacting);
assert_eq!(pending, from_worker, "sent to the worker: {from_worker}");
@@ -1913,9 +2074,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
}
}
/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the
/// frame of the move: once the press's frame arrives from the worker, every move shows the
/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters
/// A Pen drag over a frame the worker drew draws the press's anchor and each move's curve into
/// that frame, here, in the frame of the press or the move: each shows the document's revision and
/// queues nothing on the worker. When the frame shown drew effect rasters
/// from before their objects moved, when a part drawn here would have differed from it, or when
/// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker,
/// and the moves after the worker's frame are drawn here again. A frame of an older revision on
@@ -1936,6 +2097,14 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
let (worker, mut side) = WorkerSide::start();
app.canvas.worker = Some(worker);
app.canvas.last_ms = 50.0;
// A new zoom: the frame shown is the worker's.
if let Some(vm) = app.view_mut() {
vm.zoom *= 1.25;
}
frame(&mut app, &ctx, vec![]);
assert!(side.render());
frame(&mut app, &ctx, vec![]);
assert!(app.canvas.from_worker, "the worker drew the frame shown");
app.select_tool("pen");
let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision);
let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision);
@@ -1943,8 +2112,9 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0));
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
frame(&mut app, &ctx, vec![button(at, true)]);
assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker");
assert!(side.render());
assert_eq!(shown(&app), revision(&app), "the press's anchor, the first frame of the drag, is drawn in its own frame");
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting), "the press's frame is the interaction's");
assert!(side.jobs.try_recv().is_err(), "the press queues nothing on the worker");
let mut drag = |app: &mut VectorcraftApp| {
at += vec2(9.0, 5.0);
frame(app, &ctx, vec![egui::Event::PointerMoved(at)]);
@@ -1957,7 +2127,7 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
for case in ["moved", "differs", "slow"] {
match case {
"moved" => app.canvas.moved = true,
"differs" => app.canvas.worker_parts = true,
"differs" => app.canvas.whole_frames = true,
_ => app.canvas.last_ms = 10_000.0,
}
drag(&mut app);
@@ -1965,26 +2135,26 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
assert!(side.render(), "{case}: the move renders on the worker");
drag(&mut app);
assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here");
assert!(!app.canvas.worker_parts, "{case}");
assert!(!app.canvas.whole_frames, "{case}");
}
// A worker's frame that drew art in a way that depends on its size: the move after it renders
// on the worker too.
app.canvas.worker_parts = true;
app.canvas.whole_frames = true;
drag(&mut app);
let job = side.jobs.try_iter().last().expect("the move is on the worker");
let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job);
side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap();
drag(&mut app);
assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size");
assert!(app.canvas.whole_frames, "the frame shown drew art that depends on its size");
assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker");
drag(&mut app);
assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here");
// A frame on its way of an older revision: the next move is drawn here, and that frame is not
// shown when it arrives.
app.canvas.worker_parts = true;
app.canvas.whole_frames = true;
drag(&mut app);
assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way");
app.canvas.worker_parts = false;
app.canvas.whole_frames = false;
for late in [false, true] {
if late {
assert!(side.render());
@@ -6,8 +6,8 @@
//! Options also holds the action's function key and color (`key`, `cmd`, `shift`, `color`,
//! `automaticAlignTo`, see [`ActionOptions`]). OK adds the set and makes it the current one,
//! renames the set, or changes the action's name, function key and color (`ui.action.options`).
//! An invalid `set`, `action` or function key is an error, and so is a name the list refuses. OK
//! then changes no set or action, and the dialog stays open.
//! An invalid `set`, `action` or function key is an error, as are a name the list refuses and a
//! library change while editing an existing set or action. The dialog stays open with the error.
use craft::ui::contract::{Bind, Show as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id};
@@ -67,12 +67,14 @@ pub struct SetOptionsDialog {
pub set: Option<usize>,
/// The index of the action in its set; only for Action Options.
pub action: Option<usize>,
/// The action library revision these addresses described when Options opened.
revision: Option<u64>,
form: Form<SetOptionsFields>,
}
impl SetOptionsDialog {
fn new(kind: SetOptionsKind, set: Option<usize>, action: Option<usize>, fields: SetOptionsFields) -> Self {
SetOptionsDialog { id: dialog_id(KEY), kind, set, action, form: Form::new(fields, check) }
fn new(kind: SetOptionsKind, set: Option<usize>, action: Option<usize>, revision: Option<u64>, fields: SetOptionsFields) -> Self {
SetOptionsDialog { id: dialog_id(KEY), kind, set, action, revision, form: Form::new(fields, check) }
}
}
@@ -81,14 +83,15 @@ pub fn open_new(app: &mut VectorcraftApp) {
let sets = app.ui.actions.sets();
let n = (1..).find(|n| !sets.contains(&format!("Set {n}").as_str())).unwrap_or(1);
let fields = SetOptionsFields { name: format!("Set {n}"), ..SetOptionsFields::default() };
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, fields));
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, None, None, fields));
}
/// Open Set Options for the set at `set`, if there is one.
pub fn open(app: &mut VectorcraftApp, set: usize) {
if let Some(name) = model::set_name(&app.ui.actions, set) {
let fields = SetOptionsFields { name: name.to_owned(), ..SetOptionsFields::default() };
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, fields));
let revision = app.ui.actions.revision();
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, Some(revision), fields));
}
}
@@ -105,22 +108,26 @@ pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) {
automatic_align_to: model::automatic_align_to(a),
};
let fields = SetOptionsFields { name: a.name.clone(), options };
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), fields));
let revision = app.ui.actions.revision();
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), Some(revision), fields));
}
impl ActionDialog for SetOptionsDialog {
/// What OK files, with the kind and place the dialog had.
type Answer = (SetOptionsKind, Option<usize>, Option<usize>, SetOptionsFields);
/// What OK files, with the kind, place and library revision the dialog had.
type Answer = (SetOptionsKind, Option<usize>, Option<usize>, Option<u64>, SetOptionsFields);
fn take_ok(&mut self) -> Option<Self::Answer> {
self.form.take().map(|fields| (self.kind, self.set, self.action, fields))
self.form.take().map(|fields| (self.kind, self.set, self.action, self.revision, fields))
}
fn answer_ok(&mut self, answer: Result<(), Label>) {
self.form.answer(answer);
}
fn run(app: &mut VectorcraftApp, (kind, set, action, fields): Self::Answer) -> Result<(), String> {
fn run(app: &mut VectorcraftApp, (kind, set, action, revision, fields): Self::Answer) -> Result<(), String> {
if revision.is_some_and(|revision| app.ui.actions.revision() != revision) {
return Err("The action library changed. Reopen Options to edit it.".into());
}
match kind {
SetOptionsKind::NewSet => edits::new_set(app, &fields.name),
SetOptionsKind::Set => {
+40 -1
View File
@@ -154,6 +154,7 @@ struct Setup {
#[derive(Clone, Copy)]
struct Target {
document: u64,
reverts: u64,
/// The current artboard's ID, or no ID while creating a new artboard.
artboard: Option<u32>,
}
@@ -556,7 +557,7 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize {
fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option<u32>) -> Result<Value, String> {
let host = app.dialogs().ok_or("no window")?;
let st = app.session.active().ok_or("no document")?;
let target = Target { document: st.uid, artboard };
let target = Target { document: st.uid, reverts: st.reverts, artboard };
let artwork = vectorcraft_render::encode::art_bounds(&st.doc);
let [(_, fade), (_, update_while_dragging)] = global_fields(app);
(value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point);
@@ -652,6 +653,9 @@ fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -
.active()
.filter(|st| st.uid == target.document)
.ok_or(tl!("Artboard Options can only change the document where it was opened."))?;
if st.reverts != target.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
let globals = global_changes(app, v);
if v.new {
let r = confirm_new(app, v)?;
@@ -1063,4 +1067,39 @@ mod tests {
assert!(!is_open(&app));
assert_eq!(*app.session.doc().unwrap().doc, *before);
}
#[test]
fn artboard_options_refuses_a_stale_draft_after_confirmed_revert() {
let file = std::env::temp_dir().join(format!("vectorcraft-artboard-options-revert-{}.vectorcraft", std::process::id()));
let path = file.to_string_lossy();
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": path})).unwrap();
let original = app.session.active().unwrap();
let (uid, reverts, artboard) = (original.uid, original.reverts, original.doc.artboards[0].id);
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
open(&mut app).unwrap();
set(&app, &[("name", json!("Stale Draft"))]).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(&file);
let reverted = app.session.active().unwrap();
assert_eq!((reverted.uid, reverted.reverts, reverted.doc.artboards[0].id), (uid, reverts + 1, artboard));
let undo = undo_len(&app);
let answer = ok(&mut app);
assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1");
assert_eq!(undo_len(&app), undo);
assert_eq!(answer, Err("The document was reverted. Reopen this dialog to continue.".into()));
assert!(is_open(&app));
let host = app.dialogs().unwrap();
let ctx = app.ui_ctx.clone().unwrap();
assert_eq!(host.with(|h| h.get::<ArtboardOptionsDialog>().unwrap().value.name.clone()), "Stale Draft");
host.with(|h| h.cancel_by_id(&ctx, id()));
open(&mut app).unwrap();
set(&app, &[("name", json!("Fresh Draft"))]).unwrap();
ok(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Fresh Draft");
}
}
+70 -2
View File
@@ -130,7 +130,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let state = app
.dialogs()
.and_then(|d| d.with(|host| host.get_by_id::<HostedParamDialog>(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields())))));
if let Some((previewing, p)) = state {
if let Some((previewing, p)) = state
&& (!previewing || app.session.has_selected_blend())
{
// With no blend selected, the command sets application defaults instead of previewing artwork.
// The answer only reports the preview's status, which the preview itself shows.
let _ = preview.run(app, previewing, PREVIEW_LABEL, CMD, &p);
}
@@ -139,8 +142,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// OK: keeps the preview as one undo step on a blend; sets the defaults otherwise.
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let on_blend = result.fields.text("__target") == Some("blend");
if on_blend != app.session.has_selected_blend() {
let reason = if on_blend {
tl!("Select a blend before applying these options.")
} else {
tl!("Deselect any selected blends before applying the options for new blends.")
};
return Err(reason.to_owned());
}
let p = params(&result.fields);
if result.fields.text("__target") != Some("blend") {
if !on_blend {
return app.run(CMD, p).map(|_| ());
}
let preview = app.object_dialogs.blend.take().unwrap_or_default();
@@ -212,6 +224,62 @@ mod tests {
}
}
fn app_with_smooth_blend() -> (VectorcraftApp, u64) {
let mut app = app();
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
for x in [0, 200] {
app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap();
}
app.run("select.all", json!({})).unwrap();
let id = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap();
(app, id)
}
#[test]
fn opening_blend_defaults_does_not_edit_a_later_selected_blend() {
let (mut app, id) = app_with_smooth_blend();
app.run("select.none", json!({})).unwrap();
app.run("ui.blendOptions", json!({})).unwrap();
assert_eq!(fields(&app).text("__target"), Some("defaults"));
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
app.run("select.set", json!({"ids": [id]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
confirm(&mut app);
assert_eq!(spec(&app, id).spacing, BlendSpacing::SmoothColor, "a newly selected blend keeps its spacing");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(is_open(&app));
app.run("select.none", json!({})).unwrap();
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(app.session.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7));
}
#[test]
fn opening_blend_options_for_a_selection_does_not_write_defaults() {
let (mut app, id) = app_with_smooth_blend();
let defaults = app.session.prefs.blend_options;
app.run("ui.blendOptions", json!({})).unwrap();
assert_eq!(fields(&app).text("__target"), Some("blend"));
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
app.run("select.none", json!({})).unwrap();
frame(&mut app);
assert_eq!(app.session.prefs.blend_options, defaults, "the blend preview leaves new-blend defaults intact");
assert!(!app.session.in_interaction());
confirm(&mut app);
assert_eq!(app.session.prefs.blend_options, defaults);
assert!(is_open(&app));
app.run("select.set", json!({"ids": [id]})).unwrap();
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(spec(&app, id).spacing, BlendSpacing::Steps(7));
}
#[test]
fn opens_on_the_blend_previews_and_keeps_smooth_color() {
let mut app = app();
+17 -3
View File
@@ -21,7 +21,7 @@ super::confirm::wrapped_dialog!(BrushDeleteQuestion, StandardPrompt, KIND);
/// What the question is about: the document it was asked in, the `brush.delete` params and whether a
/// stroke uses one of the brushes.
struct BrushDeleteAsk {
doc: Option<u64>,
doc: Option<(u64, u64)>,
params: Value,
used: bool,
}
@@ -33,7 +33,7 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) {
return;
};
let (message, yes, no) = words(used);
let doc = app.session.active().map(|d| d.uid);
let doc = app.session.active().map(|d| (d.uid, d.reverts));
let prompt =
StandardPrompt::custom(message).button(PromptChoice::Proceed, yes).button(PromptChoice::Cancel, no).tag(BrushDeleteAsk { doc, params, used });
dialogs.with(|host| host.open(BrushDeleteQuestion(prompt)));
@@ -89,7 +89,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Yes on brushes that a stroke has started to use since the question opened asks again with Remove
/// Strokes and Cancel. When another document has become the active one, nothing is deleted.
fn confirm(app: &mut VectorcraftApp, question: BrushDeleteAsk) {
if question.doc != app.session.active().map(|doc| doc.uid) {
if !confirmation_is_current(app, question.doc) {
return;
}
if !question.used {
@@ -111,5 +111,19 @@ pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, bool)> {
Some((words(used).0.to_string(), used))
}
/// Whether the opening Brush confirmation still owns the active drawing's contents.
pub(super) fn confirmation_is_current(app: &mut VectorcraftApp, opening: Option<(u64, u64)>) -> bool {
let current = app.session.active().map(|st| (st.uid, st.reverts));
if opening == current {
return true;
}
if let (Some((document, _)), Some((active, _))) = (opening, current)
&& document == active
{
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
}
false
}
#[cfg(test)]
pub(super) mod tests;
@@ -10,6 +10,15 @@ pub(in crate::dialogs) fn app() -> VectorcraftApp {
crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()))
}
/// Writes a native file for the test to revert to.
pub(in crate::dialogs) fn save_for_revert(app: &mut VectorcraftApp, tag: &str) -> std::path::PathBuf {
let file = std::env::temp_dir().join(format!("vectorcraft-brush-{tag}-{}.vectorcraft", std::process::id()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap();
file
}
/// Answers the open question `D` the way its button does (`Some(choice)`: the button of that choice,
/// `None`: Cancel's close), then runs the module's `pump`.
pub(in crate::dialogs) fn answer<D: StackDialog>(app: &mut VectorcraftApp, choice: Option<&str>, pump: fn(&mut VectorcraftApp, &egui::Context)) {
@@ -84,3 +93,36 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() {
assert!(stroke.width > 0.0);
}
}
#[test]
fn stale_delete_approval_keeps_the_saved_brush_after_revert() {
let mut app = app();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let slim = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 8})).unwrap()["id"].as_u64().unwrap();
let tall = app.run("shape.rectangle", json!({"x": 10, "y": 30, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [slim]})).unwrap();
let file = save_for_revert(&mut app, "delete-revert");
let brush_height = |app: &mut VectorcraftApp| {
let brush = app.run("brush.get", json!({"name": "Bar"})).expect("the saved brush still exists");
let art: vectorcraft_doc::Node = serde_json::from_value(brush["art"].clone()).unwrap();
art.geometric_bounds().unwrap().height()
};
let saved = brush_height(&mut app);
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
assert!((brush_height(&mut app) - saved).abs() > 1e-6);
ask(&mut app, json!({"names": ["Bar"]}), false);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
let undo = app.session.active().unwrap().history.undo.len();
answer::<BrushDeleteQuestion>(&mut app, Some("proceed"), pump);
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
}
+36 -3
View File
@@ -163,12 +163,13 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value, Strin
/// `object_keys` are the option keys of Options of Selected Object, which the dialog then records
/// with the values it opened with. OK reaches [`ok`] once the dialog's own rows accept it.
fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Option<&[&str]>) -> Result<Value, String> {
let source = app.session.active().ok_or("no document open")?;
let document = source.uid;
let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default();
let object = object_keys.is_some();
let ctx = app.ui_ctx.clone().ok_or("no window")?;
// Modal: no edit changes the document while the dialog is open, so the previews read this snapshot.
let doc = app.session.active().map(|st| st.doc.clone());
let rows = rows(ty, object, doc, crate::canvas::rulers::unit_kind(app.session.general_unit()));
let rows = rows(ty, object, Some(source.doc.clone()), crate::canvas::rulers::unit_kind(app.session.general_unit()));
let title = Label::from(title(ty, object));
let mut initial = form::fields_of(&rows, f);
// The hidden values the rows read whole stay JSON: an untagged read makes an array a list of values.
@@ -192,7 +193,15 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
}
})
.held_ok();
app.ui.brush_options = Some(host::open_held(app, dialog, ok).ok_or("no window")?);
app.ui.brush_options = Some(
host::open_held(app, dialog, move |app, result: &ParamResult| {
if !object && app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to edit its brush").into());
}
ok(app, result)
})
.ok_or("no window")?,
);
Ok(Value::Null)
}
@@ -672,3 +681,27 @@ fn confirm(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod document_tests {
use super::*;
use crate::dialogs::tests_export;
#[test]
fn brush_options_does_not_rename_the_other_drawings_brush() {
let (mut app, _) = tests_export::app(1);
open(&mut app, Some("Diamonds")).unwrap();
tests_export::set(&mut app, "name", json!("Source diamonds"));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let previous = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let error = tests_export::try_confirm(&mut app).expect_err("Brush Options must refuse the other drawing");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap(), previous);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(tests_export::fields(&app)["name"], "Source diamonds");
app.run("document.activate", json!({"index": 0})).unwrap();
tests_export::try_confirm(&mut app).unwrap();
assert_eq!(app.run("brush.get", json!({"name": "Source diamonds"})).unwrap()["name"], "Source diamonds");
}
}
@@ -22,7 +22,7 @@ super::confirm::wrapped_dialog!(ReplaceArtQuestion, StandardPrompt, KIND);
/// What the question is about: the document it was asked in, the brush and the art.
struct ReplaceArtAsk {
doc: Option<u64>,
doc: Option<(u64, u64)>,
name: String,
ids: Vec<u64>,
}
@@ -59,7 +59,7 @@ pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) {
app.status("no window");
return;
};
let doc = app.session.active().map(|d| d.uid);
let doc = app.session.active().map(|d| (d.uid, d.reverts));
let prompt = StandardPrompt::custom(tl!(
"Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?"
))
@@ -86,7 +86,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Runs `brush.replaceArt`. When another document has become the active one, no brush changes.
fn confirm(app: &mut VectorcraftApp, question: ReplaceArtAsk, apply: bool) {
if question.doc != app.session.active().map(|doc| doc.uid) {
if !super::brush_delete::confirmation_is_current(app, question.doc) {
return;
}
let params = json!({"name": question.name, "ids": question.ids, "applyToStrokes": apply});
@@ -1,7 +1,7 @@
use serde_json::json;
use vectorcraft_doc::NodeId;
use super::super::brush_delete::tests::{answer, app};
use super::super::brush_delete::tests::{answer, app, save_for_revert};
use super::*;
fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 {
@@ -95,3 +95,30 @@ fn a_button_changes_no_brush_after_another_document_became_active() {
app.run("document.activate", json!({"index": 0})).unwrap();
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
}
#[test]
fn stale_replace_approval_keeps_the_saved_brush_art_after_revert() {
let mut app = app();
let (_, tall) = used_brush(&mut app);
let thick = rect(&mut app, 10.0, 65.0, 40.0, 30.0);
let file = save_for_revert(&mut app, "replace-revert");
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6);
replace(&mut app, "Bar", &[thick]);
assert!(asks(&app));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert!(st.doc.node(NodeId(thick)).is_some(), "the restored drawing shares the same local source ID");
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
let undo = app.session.active().unwrap().history.undo.len();
answer::<ReplaceArtQuestion>(&mut app, Some("proceed"), pump);
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "the stale answer leaves the restored brush intact");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
}
+241 -39
View File
@@ -25,18 +25,21 @@
//! <https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html>.
use std::borrow::Cow;
use std::sync::{Arc, Weak};
use craft::behavior::{Mixed, Selection, SelectionChange, keyed};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::display::Text;
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::ThumbAspect;
use craft::ui::pickers::Select;
use craft::ui::primitives::{HAlign, IconSpec, TextRun};
use craft::ui::runtime::env::{Env, LengthUnits};
use craft::ui::runtime::env::{Env, Label, LengthUnits};
use craft::ui::runtime::measure;
use craft::ui::runtime::overlay::CloseReason;
use craft::ui::runtime::words::CommonWords;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::tabs::{Tab, TabKind, TabStrip};
@@ -44,11 +47,14 @@ use craft::ui::text::NumberField;
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use egui::{Context, Ui};
use serde_json::{Map, Value, json};
use vectorcraft_doc::Selection as ArtworkSelection;
use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList};
use crate::VectorcraftApp;
use crate::panels::paragraph::BulletGlyph;
use super::preview::LivePreview;
/// The dialog kind of Bullets and Numbering.
pub const KIND: &str = "bulletsAndNumbering";
@@ -122,9 +128,70 @@ pub(crate) struct BulletsDialog {
hanging: bool,
/// The General unit the indent fields show; the pump keeps it current.
lengths: LengthUnits,
active_document: bool,
held: HeldAnswer<Map<String, Value>>,
open: bool,
}
/// The preview from the opening drawing and the interaction that owns its undo snapshot.
pub(crate) struct Preview {
document: u64,
live: LivePreview,
selection: Option<Weak<ArtworkSelection>>,
}
impl Preview {
fn owns_interaction(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn update(&mut self, app: &mut VectorcraftApp, fields: Map<String, Value>) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return };
if !self.owns_interaction(app) {
self.live = LivePreview::default();
self.selection = None;
if state.interaction.is_some() {
return;
}
}
let on = changes(&fields);
let ran = self.live.run(app, on, tl!("Bullets and Numbering"), CMD, &Value::Object(fields)).is_some();
if !on {
self.selection = None;
} else if ran {
self.selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
}
}
fn apply(&mut self, app: &mut VectorcraftApp, fields: Map<String, Value>) -> Result<(), String> {
if !changes(&fields) {
if self.owns_interaction(app) {
std::mem::take(&mut self.live).cancel(app);
self.selection = None;
}
return Ok(());
}
if app.session.active().is_none_or(|state| state.uid != self.document) {
return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned());
}
if app.session.in_interaction() && !self.owns_interaction(app) {
return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned());
}
self.selection = None;
std::mem::take(&mut self.live).commit(app, CMD, Value::Object(fields)).map(drop)
}
fn cancel(self, app: &mut VectorcraftApp) {
if self.owns_interaction(app) {
self.live.cancel(app);
}
}
}
/// The kind of list `list` is, as the `list` field names it.
fn kind(list: Option<ParaList>) -> &'static str {
match list {
@@ -144,8 +211,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?),
};
crate::panels::character::text_style(app).ok_or("select some type first")?;
let document = app.session.active().ok_or("no document")?.uid;
// A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own.
std::mem::take(&mut app.bullets_preview).cancel(app);
if let Some(old) = app.bullets_preview.take() {
old.cancel(app);
}
// While typing, the dialog acts on the paragraphs of the text being edited.
let mut targets = json!({});
if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? {
@@ -192,9 +262,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
targets,
hanging: false,
lengths: crate::canvas::general_lengths(app),
active_document: true,
held: HeldAnswer::default(),
open: true,
};
host.with(|h| h.open(dialog));
app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None });
Ok(Value::Null)
}
@@ -468,8 +541,7 @@ fn changes(p: &Map<String, Value>) -> bool {
}
impl StackDialog for BulletsDialog {
/// The `text.setFormat` parameters OK runs.
type Result = Value;
type Result = ();
fn id(&self) -> DialogId {
dialog_id(KIND)
@@ -479,20 +551,46 @@ impl StackDialog for BulletsDialog {
Some(KIND)
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Value>> {
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let common = Env::of(ui).words::<CommonWords>();
let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
let finish = self.held.is_accepted();
let refusal = self.held.refusal().map(|(reason, _)| reason.clone());
let buttons = [
FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(true).enabled(!self.held.is_waiting()),
FooterButton::new(common.cancel.clone(), DialogRole::Cancel),
];
let mut open = self.open;
let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open));
let shown = dialog.show(ui, |ui, _| self.body(ui));
let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone());
let shown = dialog.show(ui, |ui, cx| {
if finish && !measure::active(ui.ctx()) {
cx.request_close_as(CloseReason::Activated);
}
self.body(ui);
});
self.open = open;
let DialogOutput { closed, picked, .. } = shown.output;
closed?;
Some(if picked == Some(OK) { DialogResult::Ok(Value::Object(params(self))) } else { DialogResult::Cancel })
if picked == Some(OK) && !self.held.is_waiting() {
self.held.file(params(self));
}
match closed {
Some(CloseReason::Activated) if finish => self.held.finish().map(|_| DialogResult::Ok(())),
Some(_) => Some(DialogResult::Cancel),
None => None,
}
}
fn confirm(&mut self, _: &Context) -> Option<Value> {
Some(Value::Object(params(self)))
fn confirm(&mut self, _: &Context) -> Option<()> {
if self.held.is_accepted() {
return self.held.finish().map(drop);
}
if !self.held.is_waiting() {
self.held.file(params(self));
}
None
}
fn held_state(&self) -> Option<HeldOk> {
self.held.state()
}
fn json_fields(&self) -> Option<Value> {
@@ -515,38 +613,41 @@ impl StackDialog for BulletsDialog {
}
}
/// Runs once per frame: keeps the indent fields' unit current, shows the dialog's values on the type while they change
/// something, and answers a finished dialog: OK keeps the preview as one undo step, Cancel (Escape and the close box
/// too) and an OK that changes nothing put the type back.
/// Shows the draft on its opening drawing and answers OK before the dialog closes.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some(host) = app.dialogs() else { return };
if let Some(result) = host.with(|h| h.take::<BulletsDialog>()) {
let live = std::mem::take(&mut app.bullets_preview);
match result {
DialogResult::Ok(Value::Object(p)) if changes(&p) => {
if let Err(e) = live.commit(app, CMD, Value::Object(p)) {
app.status(e);
// The dialog is gone: a preview the refused OK left running goes with it. Nothing runs
// when the refusal came before the interaction began, which is the right outcome too.
let _ = app.session.cancel_interaction();
}
}
_ => live.cancel(app),
}
}
let Some(mut preview) = app.bullets_preview.take() else { return };
let active_document = app.session.active().is_some_and(|state| state.uid == preview.document);
let lengths = crate::canvas::general_lengths(app);
// The host's lock is released before the preview runs: a command never runs inside `with`.
let Some(p) = host.with(|h| {
let Some((fields, answer)) = host.with(|h| {
h.get_mut::<BulletsDialog>().map(|d| {
d.lengths = lengths;
params(d)
let fields = params(d);
if (active_document && !d.active_document) || d.held.refusal().is_some_and(|(_, at)| *at != fields) {
d.held.clear_refusal();
}
d.active_document = active_document;
(fields, d.held.take())
})
}) else {
preview.cancel(app);
return;
};
let mut live = std::mem::take(&mut app.bullets_preview);
let _ = live.run(app, changes(&p), tl!("Bullets and Numbering"), CMD, &Value::Object(p));
app.bullets_preview = live;
if let Some(answer) = answer {
let result = preview.apply(app, answer).map_err(Label::from);
let accepted = result.is_ok();
host.with(|h| {
if let Some(dialog) = h.get_mut::<BulletsDialog>() {
dialog.held.answer(result);
}
});
if accepted {
return;
}
} else {
preview.update(app, fields);
}
app.bullets_preview = Some(preview);
}
#[cfg(test)]
@@ -618,13 +719,23 @@ mod tests {
crate::dialogs::host::pump(app, &ctx);
}
/// OK on the open dialog, as automation answers it, then the frame's pump.
fn ok(app: &mut VectorcraftApp) {
fn press_ok(app: &mut VectorcraftApp) {
let (ctx, (id, _)) = (window(app), top(app));
assert!(app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)), "OK is enabled");
let host = app.dialogs().unwrap();
host.with(|h| {
assert!(!h.confirm_by_id(&ctx, id), "the app must accept the answer first");
assert_eq!(h.held_state(id), Some(HeldOk::Waiting));
});
frame(app);
}
/// Files OK and closes with the accepted answer, as the view or automation does.
fn ok(app: &mut VectorcraftApp) {
press_ok(app);
let (ctx, (id, _)) = (window(app), top(app));
assert!(app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)), "the app accepted OK");
}
/// Cancel on the open dialog, as Esc gives it, then the frame's pump.
fn cancel(app: &mut VectorcraftApp) {
let (ctx, (id, _)) = (window(app), top(app));
@@ -641,6 +752,97 @@ mod tests {
with_dialog(app, |d| params(d))
}
fn other_drawing(app: &mut VectorcraftApp) -> u64 {
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
let id = app.run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})).unwrap()["id"]
.as_u64()
.unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
id
}
#[test]
fn bullets_preview_pauses_in_another_drawing() {
let (mut app, id) = app();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
let other = other_drawing(&mut app);
let before = first(&app, other);
frame(&mut app);
assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by preview");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
ok(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
}
#[test]
fn bullets_ok_does_not_change_the_other_drawings_type() {
let (mut app, id) = app();
let opening = first(&app, id);
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "number", Some("arabic"));
let other = other_drawing(&mut app);
let before = first(&app, other);
let undo = app.session.doc().unwrap().history.undo.len();
press_ok(&mut app);
assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by OK");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert!(with_dialog(&app, |d| matches!(d.held.state(), Some(HeldOk::Refused(_)))));
assert_eq!(fields(&app)["number"], "arabic");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(first(&app, id), opening);
frame(&mut app);
assert!(with_dialog(&app, |d| d.held.state().is_none()));
ok(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic)));
}
#[test]
fn bullets_cancel_keeps_the_other_drawings_pending_edit() {
let (mut app, id) = app();
let opening = first(&app, id);
let other = other_drawing(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
frame(&mut app);
assert!(app.session.in_interaction());
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other paragraph edit").unwrap();
app.session.preview("text.setFormat", &json!({"ids": [other], "leftIndent": 41})).unwrap();
let editing = first(&app, other);
assert_eq!(editing.1, 41.0);
cancel(&mut app);
assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit");
assert_eq!(first(&app, other), editing);
app.session.commit_interaction().unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(first(&app, id), opening);
}
#[test]
fn accepted_bullets_close_on_the_next_view_pass() {
let (mut app, id) = app();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
press_ok(&mut app);
let ctx = window(&app);
crate::tests_synthetic::key_frame(&mut app, &ctx, vec![]);
assert!(!is_open(&app));
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
}
/// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the
/// indents show on the type at once, and OK keeps them as one `text.setFormat`, which one Undo
/// takes back.
+112 -13
View File
@@ -51,6 +51,8 @@ const GLOBAL: &str = "global";
pub(crate) struct Open {
/// The dialog's id on the host.
pub id: DialogId,
/// The document whose art the dialog can adjust.
document: Option<u64>,
/// The preview the dialog's values run as one interaction.
pub preview: LivePreview,
}
@@ -85,22 +87,28 @@ impl Adjust {
fn try_open(self, app: &mut VectorcraftApp) -> Result<(), String> {
const NO_WINDOW: &str = "no window to open the dialog in";
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
if let Some(old) = (self.slot)(&mut app.color_dialogs).take() {
let document = app.session.active().map(|st| st.uid);
if let Some(old) = (self.slot)(&mut app.color_dialogs).take()
&& old.document == document
{
old.preview.cancel(app);
}
let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| {
ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true)
});
let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?;
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview: LivePreview::default() });
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() });
Ok(())
}
/// OK: keeps the preview as one undo step; an `Err` keeps the dialog open with the reason.
fn commit(self, app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> {
let live = (self.slot)(&mut app.color_dialogs).as_ref().map(|open| open.preview.clone()).unwrap_or_default();
// PLAN: assumed `LivePreview::commit(self, ..)` as the contract row says; the clone keeps the record when it fails.
live.commit(app, self.cmd, (self.params)(&answer.fields))?;
let document = app.session.active().map(|st| st.uid);
let open = (self.slot)(&mut app.color_dialogs)
.as_ref()
.filter(|open| open.document == document)
.ok_or(tl!("This adjustment can only apply to the document where it was opened."))?;
open.preview.clone().commit(app, self.cmd, (self.params)(&answer.fields))?;
*(self.slot)(&mut app.color_dialogs) = None;
Ok(())
}
@@ -108,17 +116,22 @@ impl Adjust {
/// Once per frame: previews the dialog's values while its Preview box is on, and rolls the preview back once the
/// dialog is gone without OK.
pub(super) fn pump(self, app: &mut VectorcraftApp) {
let Some(Open { id, mut preview }) = (self.slot)(&mut app.color_dialogs).take() else { return };
let Some(mut open) = (self.slot)(&mut app.color_dialogs).take() else { return };
let on_its_document = app.session.active().map(|st| st.uid) == open.document;
let shown = app.dialogs().and_then(|dialogs| {
dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields()))))
dialogs.with(|host| host.get_by_id::<HostedParamDialog>(open.id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields()))))
});
match shown {
Some((on, params)) => {
if let Some((on, params)) = shown {
if on_its_document {
// `run` reports a failed preview to the status line itself.
let _ = preview.run(app, on, self.label, self.cmd, &params);
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview });
let _ = open.preview.run(app, on, self.label, self.cmd, &params);
} else {
// Switching documents rolled back the original interaction.
open.preview = LivePreview::default();
}
None => preview.cancel(app),
*(self.slot)(&mut app.color_dialogs) = Some(open);
} else if on_its_document {
open.preview.cancel(app);
}
}
}
@@ -222,7 +235,7 @@ fn rows() -> Vec<Param> {
#[cfg(test)]
mod tests {
use craft::ui::dialog::dialog_id;
use craft::ui::dialog::{HeldOk, dialog_id};
use vectorcraft_engine::Session;
use super::*;
@@ -250,6 +263,92 @@ mod tests {
host::pump(app, ctx);
}
fn two_documents(color: &str) -> (VectorcraftApp, egui::Context, [u64; 2]) {
let (mut app, ctx) = app();
let ids = [0, 1].map(|_| {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"color": color})).unwrap();
id
});
app.run("document.activate", json!({"index": 0})).unwrap();
(app, ctx, ids)
}
#[test]
fn color_adjustment_stays_in_its_opening_document_with_preview_on() {
let (mut app, ctx, [source, destination]) = two_documents("#808080");
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
let source_undo = app.session.active().unwrap().history.undo.len();
open(&mut app);
set(&app, &ctx, "r", json!(20));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#b38080");
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#808080", "another document is not previewed");
assert!(!app.session.in_interaction());
confirm(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
confirm(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted)));
assert_eq!(fill_hex(&app, source), "#b38080");
assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1);
}
#[test]
fn color_adjustment_stays_in_its_opening_document_with_preview_off() {
let (mut app, ctx, [source, destination]) = two_documents("#cc6666");
let id = dialog_id(crate::dialogs::saturate::KIND);
let dialogs = app.dialogs().unwrap();
crate::dialogs::saturate::open(&mut app);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "intensity", json!(-100)).unwrap();
host.set_json_field(&ctx, id, "preview", json!(false)).unwrap();
});
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#cc6666");
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#cc6666", "another document is not adjusted");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted)));
assert_ne!(fill_hex(&app, source), "#cc6666");
}
#[test]
fn color_adjustment_cancel_leaves_the_new_documents_interaction_intact() {
let (mut app, ctx, [source, destination]) = two_documents("#808080");
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
open(&mut app);
set(&app, &ctx, "r", json!(20));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#b38080");
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Change fill").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
dialogs.with(|host| host.cancel_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#00ff00", "cancelling the old dialog leaves the new edit intact");
assert!(app.session.in_interaction());
}
#[test]
fn previews_live_and_commits_one_undo_step() {
let (mut app, ctx) = app();
+32 -15
View File
@@ -3,7 +3,7 @@
//! as one undo step through `paint.setFill` / `paint.setStroke` and makes the colour the Color
//! Guide's base colour; Cancel puts the art back. Opened for an artboard (Properties › Artboards ›
//! Fill), it shows the colour on the artboard's paper and OK keeps it through
//! `artboard.setProps {index, color}`.
//! `artboard.setProps {index, color}`. Preview and OK require the opening document to be active.
//!
//! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog
//! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor
@@ -43,11 +43,18 @@ pub(crate) enum Target {
/// The stroke proxy.
Stroke,
/// The background colour of this artboard.
Artboard(usize),
Artboard { document: u64, index: usize },
/// A colour row `key` of the open dialog `parent`.
Answer { parent: DialogId, key: String },
}
impl Target {
fn in_active_document(&self, app: &VectorcraftApp) -> bool {
let Self::Artboard { document, .. } = self else { return true };
app.session.active().is_some_and(|st| st.uid == *document)
}
}
/// One open Color Picker: what the dialog itself does not know.
pub(crate) struct Open {
/// The dialog's id on the window's host.
@@ -150,14 +157,17 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
None | Some(Value::Null) => None,
Some(v) => {
let index = v.as_u64().and_then(|i| usize::try_from(i).ok());
let found = index.and_then(|i| Some((i, app.session.active()?.doc.artboards.get(i)?.color)));
let (i, color) = found.ok_or("no such artboard")?;
Some((i, color.unwrap_or(Color::WHITE)))
let found = index.and_then(|i| {
let st = app.session.active()?;
let color = st.doc.artboards.get(i)?.color.unwrap_or(Color::WHITE);
Some((st.uid, i, color))
});
Some(found.ok_or("no such artboard")?)
}
};
let color = match (p.get("color"), artboard) {
(Some(v), _) => color_value(v).ok_or_else(|| format!("bad color {v}"))?,
(None, Some((_, c))) => c,
(None, Some((_, _, c))) => c,
(None, None) => proxy_color(app, stroke),
};
let dialogs = app.dialogs().ok_or("no window")?;
@@ -184,9 +194,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
dialog = dialog.kept(model_values(&color));
}
// PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target.
if let Some((i, _)) = artboard {
dialog = dialog.instance(i);
// The host replaces a picker only for the same document and artboard.
if let Some((document, index, _)) = artboard {
dialog = dialog.instance((document, index));
}
let id = dialogs.with(|h| h.open(dialog));
// A picker the open replaced leaves its preview behind: end it.
@@ -196,7 +206,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let _ = app.session.cancel_interaction();
}
let target = match artboard {
Some((i, _)) => Target::Artboard(i),
Some((document, index, _)) => Target::Artboard { document, index },
None if stroke => Target::Stroke,
None => Target::Fill,
};
@@ -274,6 +284,13 @@ fn finish(
open: &mut Open,
result: Option<DialogResult<craft::color_ui::ui::ColorPickerResult>>,
) {
// Switching documents rolls back the source preview. Do not settle it against the new drawing.
if !open.target.in_active_document(app) {
if matches!(result, Some(DialogResult::Ok(_))) {
app.status("The active document changed while the Color Picker was open");
}
return;
}
let preview = std::mem::take(&mut open.preview);
match (result, &open.target) {
(Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => {
@@ -293,7 +310,7 @@ fn finish(
/// The command that applies colour `c` to the picker's target, and its params.
fn paint_command(target: &Target, c: Color) -> (&'static str, Value) {
match target {
Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })),
Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })),
Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })),
Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })),
}
@@ -314,18 +331,18 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color {
/// then only becomes the default paint, on OK). An artboard shows it with or without a selection.
fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) {
// A picker over a command dialog only fills a row; the dialog previews it.
if matches!(open.target, Target::Answer { .. }) {
if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) {
return;
}
let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked)));
let untouched = !app.session.in_interaction() && picked.color == open.start;
let artboard = matches!(open.target, Target::Artboard(_));
let artboard = matches!(open.target, Target::Artboard { .. });
let selected = artboard || app.session.active().is_some_and(|st| !st.selection.objects.is_empty());
if untouched || !selected {
return;
}
let label = match open.target {
Target::Artboard(_) => "Artboard Options",
Target::Artboard { .. } => "Artboard Options",
Target::Stroke => "Stroke Color",
_ => "Fill Color",
};
@@ -342,7 +359,7 @@ fn commit(app: &mut VectorcraftApp, open: &Open, preview: LivePreview, picked: &
let (cmd, params) = paint_command(&open.target, c);
preview.commit(app, cmd, params)?;
// A color picked for the fill or stroke also becomes the Color Guide's base color.
if !matches!(open.target, Target::Artboard(_)) {
if !matches!(open.target, Target::Artboard { .. }) {
crate::panels::color_guide::choose_base(app, c);
}
Ok(())
@@ -52,6 +52,15 @@ fn artboard_color(app: &VectorcraftApp) -> Option<Color> {
app.session.doc().unwrap().doc.artboards[1].color
}
fn two_documents_with_artboards() -> (VectorcraftApp, egui::Context) {
let (mut app, ctx) = app();
app.run("artboard.new", json!({})).unwrap();
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("artboard.new", json!({})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
(app, ctx)
}
/// The selected art takes each colour as it is picked; OK keeps the last as one undo step and
/// Cancel puts the art back.
#[test]
@@ -101,6 +110,71 @@ fn an_artboard_shows_its_background_color_live() {
assert!(app.run("ui.colorPicker", json!({"artboard": 9})).is_err());
}
#[test]
fn the_artboard_picker_previews_only_in_its_opening_document() {
let (mut app, ctx) = two_documents_with_artboards();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#ff0000");
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
app.run("document.activate", json!({"index": 1})).unwrap();
let before = undo_len(&app);
set_hex(&mut app, &ctx, "#00ff00");
assert_eq!(artboard_color(&app), None, "the other document never previews the color");
assert!(!app.session.in_interaction());
assert_eq!(undo_len(&app), before);
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(artboard_color(&app), None, "leaving the source rolled its preview back");
let before = undo_len(&app);
ok(&mut app, &ctx);
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#00ff00"));
assert_eq!(undo_len(&app), before + 1);
}
#[test]
fn confirming_an_artboard_picker_in_another_document_leaves_both_unchanged() {
let (mut app, ctx) = two_documents_with_artboards();
let source_undo = undo_len(&app);
app.run("ui.colorPicker", json!({"artboard": 1, "color": "#00ff00"})).unwrap();
frame(&mut app, &ctx);
app.run("document.activate", json!({"index": 1})).unwrap();
let destination_undo = undo_len(&app);
ok(&mut app, &ctx);
assert_eq!(app.ui.status, "The active document changed while the Color Picker was open");
assert_eq!(artboard_color(&app), None);
assert_eq!(undo_len(&app), destination_undo);
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(artboard_color(&app), None);
assert_eq!(undo_len(&app), source_undo);
}
#[test]
fn canceling_an_artboard_picker_preserves_the_other_documents_interaction() {
let (mut app, ctx) = two_documents_with_artboards();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#ff0000");
app.run("document.activate", json!({"index": 1})).unwrap();
app.begin_interaction("Other edit").unwrap();
app.session.preview("artboard.setProps", &json!({"index": 1, "color": "#445566"})).unwrap();
cancel(&mut app, &ctx);
assert!(app.session.in_interaction(), "the current document keeps its own interaction");
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#445566"));
}
#[test]
fn artboard_pickers_for_the_same_index_in_different_documents_have_separate_instances() {
let (mut app, _) = two_documents_with_artboards();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
let first = id(&app);
app.run("document.activate", json!({"index": 1})).unwrap();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
assert_ne!(id(&app), first);
assert_eq!(app.color_dialogs.pickers.len(), 2);
}
/// OK on an untouched picker for an artboard without a color leaves it without one and adds no
/// undo step; a white the opener passes as `color` is set.
#[test]
+38 -16
View File
@@ -26,6 +26,7 @@
use std::cell::RefCell;
use std::ops::RangeInclusive;
use std::path::Path;
use std::sync::Arc;
use craft::behavior::{ColumnKey, ColumnWidth, Selection, SelectionChange, keyed};
@@ -60,7 +61,7 @@ use vectorcraft_engine::cmd::compositefonts::{EXTS, file_bytes};
use vectorcraft_text::FontDb;
use crate::VectorcraftApp;
use crate::file_asks::{Owner, ask, open_params, save};
use crate::file_asks::{Owner, ask_while, open_params, save};
use crate::font_menu::{PickerHold, family_picker, family_sets};
mod sample;
@@ -135,6 +136,8 @@ enum PartEdit {
/// The Composite Fonts dialog on the dialog host. OK files the fonts for [`pump`], which runs
/// [`COMMAND`] and answers whether the dialog may close.
pub struct CompositeFontsDialog {
/// The document whose fonts the draft edits.
document: u64,
fonts: Vec<CompositeFont>,
/// The index of the font picked.
selected: usize,
@@ -156,6 +159,8 @@ pub struct CompositeFontsDialog {
held: HeldAnswer<Vec<CompositeFont>>,
/// The file dialog a Load…, Replace… or Save… asked for, which [`pump`] takes.
file: Option<PresetFileRequest>,
/// Identifies the draft that opened a Load or Replace picker.
file_owner: Arc<()>,
/// Why the last action on the fonts or sets was refused.
refusal: Option<String>,
/// The words of the file status line, kept from the last pass for [`pump`].
@@ -165,9 +170,9 @@ pub struct CompositeFontsDialog {
/// Open Composite Fonts on the active document's composite fonts, the first one picked, with the
/// custom character sets and the sample hidden and nothing typed.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec();
let document = app.session.active().ok_or("no document open")?;
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
let dialog = CompositeFontsDialog::new(fonts, crate::font_menu::hold(app));
let dialog = CompositeFontsDialog::new(document.uid, document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app));
dialogs.with(|host| host.open(dialog));
Ok(Value::Null)
}
@@ -239,10 +244,11 @@ fn part_mut(f: &mut CompositeFont, at: usize) -> Option<&mut CompositePart> {
impl CompositeFontsDialog {
/// The dialog over `fonts`, the first picked.
fn new(fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
fn new(document: u64, fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
let mut sample = Map::new();
sample::defaults(&mut sample);
CompositeFontsDialog {
document,
fonts,
selected: 0,
set: 0,
@@ -255,6 +261,7 @@ impl CompositeFontsDialog {
hold,
held: HeldAnswer::new(),
file: None,
file_owner: Arc::new(()),
refusal: None,
words: None,
}
@@ -848,25 +855,35 @@ impl StackDialog for CompositeFontsDialog {
/// Runs once per frame after the shell pass: answers OK's held fonts with the command's result, and takes the
/// file dialog a Load…, Replace… or Save… asked for.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some((held, request)) = with_dialog(app, |d| (d.held.take(), d.file.take())) else { return };
if let Some(fonts) = held {
// A name two fonts share or a value out of range keeps the dialog open with the reason.
let answer = app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from);
let Some((held, request)) = with_dialog(app, |d| {
let held = d.held.take().map(|fonts| (d.document, fonts));
let request = d.file.take().map(|request| (request, Arc::clone(&d.file_owner)));
(held, request)
}) else {
return;
};
if let Some((document, fonts)) = held {
let answer = if app.session.active().is_some_and(|active| active.uid == document) {
app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from)
} else {
Err(Label::from(tl!("Composite Fonts can only change the document where it was opened.").to_owned()))
};
with_dialog(app, |d| d.held.answer(answer));
}
if let Some(request) = request {
ask_file(app, request);
if let Some((request, owner)) = request {
ask_file(app, request, owner);
}
}
/// Asks for the file `request` names; the answer reaches the dialog by [`with_dialog`].
fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) {
/// Asks for the file `request` names. Open answers belong to the draft that requested them.
fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()>) {
// The pick's answer comes back through the continuation, so the immediate `{pending}` value says nothing more.
match request.clone() {
PresetFileRequest::Open { purpose, filter, extensions, replace, .. } => {
let exts: Vec<&str> = extensions.iter().map(String::as_str).collect();
let pick = PickRequest::open(purpose).filter(filter, &exts);
ask(app, pick, Owner::Free, move |app, picked| load_file(app, &request, replace, &picked));
let current = move |app: &VectorcraftApp| with_dialog(app, |draft| Arc::ptr_eq(&draft.file_owner, &owner)).unwrap_or(false);
ask_while(app, pick, Owner::Free, current, move |app, picked| load_file(app, &request, replace, &picked));
}
PresetFileRequest::Save { purpose, filter, extensions, file_name, bytes, .. } => {
let exts: Vec<&str> = extensions.iter().map(String::as_str).collect();
@@ -882,14 +899,19 @@ fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) {
/// Reads the fonts of the file picked and gives them to the dialog (Load… or Replace…).
fn load_file(app: &mut VectorcraftApp, request: &PresetFileRequest, replace: bool, picked: &Picked) -> Result<Value, String> {
// PLAN: assumed fl.A23 `file_asks::open_params(&Picked) -> Option<Map<String, Value>>`; `None` is a cancelled pick.
let Some(mut params) = open_params(picked) else { return Ok(Value::Null) };
let browser_name = params.remove("name");
let name = picked
.first_path()
.as_deref()
.or_else(|| browser_name.as_ref().and_then(Value::as_str).map(Path::new))
.and_then(Path::file_name)
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
params.insert("apply".into(), json!(false));
let read = app.run(IMPORT, Value::Object(params))?;
let fonts: Vec<CompositeFont> = serde_json::from_value(read["fonts"].clone()).map_err(|e| e.to_string())?;
with_dialog(app, |d| d.load(fonts, replace));
let name = picked.first_path().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default();
// Only the file's name goes into the status line.
if let Some(event) = request.loaded(name, Vec::new()) {
report(app, event);
}
@@ -61,6 +61,72 @@ fn names(app: &VectorcraftApp) -> Vec<String> {
app.session.active().unwrap().doc.composite_fonts.iter().map(|f| f.name.clone()).collect()
}
#[test]
fn delayed_load_and_replace_leave_the_reopened_composite_fonts_draft_alone() {
let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["New draft", "From file"]), (PresetCommands::Replace, &["From file"])];
for (command, expected_live) in choices {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
let bytes = dialog(&mut app, |d| {
d.new_font("From file".into());
file_bytes(&d.fonts).unwrap()
});
let dir = vectorcraft_testkit::TempDir::new("composite-fonts-late-picker");
let file = dir.join("picked.vccomposite");
std::fs::write(&file, bytes).unwrap();
let path = file.to_str().unwrap();
request(&mut app, command, None);
assert_eq!(picker.requests().len(), 1);
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("New draft".into()));
picker.answer(&[path]);
poll(&mut app, &ctx);
let draft_names = |app: &mut VectorcraftApp| dialog(app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::<Vec<_>>());
assert_eq!(draft_names(&mut app), ["New draft"], "the stale picker leaves the new draft alone");
request(&mut app, command, None);
assert_eq!(picker.requests().len(), 2);
picker.answer(&[path]);
poll(&mut app, &ctx);
assert_eq!(draft_names(&mut app), expected_live, "a picker opened by the new draft still works");
assert!(names(&app).is_empty(), "a picker only edits the draft");
}
}
#[test]
fn load_and_replace_accept_a_browser_picked_file() {
let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["Draft", "From Web"]), (PresetCommands::Replace, &["From Web"])];
for (command, expected) in choices {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
let bytes = dialog(&mut app, |d| {
d.new_font("From Web".into());
file_bytes(&d.fonts).unwrap()
});
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Draft".into()));
let dialogs = app.dialogs().unwrap();
ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear();
let step = steps(&app);
request(&mut app, command, None);
picker.answer_contents(&[("picked.vccomposite", &bytes)]);
poll(&mut app, &ctx);
let draft_names = dialog(&mut app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::<Vec<_>>());
assert_eq!(draft_names, expected, "{}", app.ui.status);
assert!(app.ui.status.contains("picked.vccomposite"), "{}", app.ui.status);
assert!(names(&app).is_empty(), "picking a file edits only the draft");
assert_eq!(steps(&app), step);
}
}
fn steps(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
@@ -133,6 +199,41 @@ fn composite_fonts_change_on_ok_as_one_undo_step() {
assert!(names(&app).is_empty());
}
#[test]
fn a_held_composite_fonts_ok_keeps_the_draft_with_its_opening_document() {
let mut app = app();
app.run("file.new", json!({"width": 440, "height": 440})).unwrap();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Destination only".into()));
ok(&mut app).unwrap();
let destination = (names(&app), steps(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
let source = (names(&app), steps(&app));
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("From the source".into()));
let ctx = ctx(&app);
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("document.activate", json!({"index": 1})).unwrap();
pump(&mut app, &ctx);
assert_eq!((names(&app), steps(&app)), destination, "the other document keeps its fonts and undo history");
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
assert!(is_open(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!((names(&app), steps(&app)), source);
ok(&mut app).unwrap();
assert_eq!(names(&app), ["From the source"]);
assert_eq!(steps(&app), source.1 + 1);
assert!(!is_open(&app));
}
/// New is based on the font picked and takes the next free name; a name two fonts share, or one
/// left empty, keeps the dialog open and changes nothing.
#[test]
+20 -4
View File
@@ -89,6 +89,8 @@ pub(crate) struct Question(StandardPrompt);
struct Asked {
command: String,
params: Value,
/// The document that must still be active for a document-specific confirmation.
document: Option<u64>,
/// The automation roots in force when asked: the command runs under them.
scope: ScopeHandle,
/// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation.
@@ -129,6 +131,17 @@ pub(crate) struct ReplaceFiles {
/// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command`
/// with `params`.
pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) {
ask_for(app, None, message, detail, command, params);
}
/// Ask about the active document. OK is valid only while that document is active.
pub(crate) fn ask_in_document(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) {
if let Some(document) = app.session.active().map(|st| st.uid) {
ask_for(app, Some(document), message, detail, command, params);
}
}
fn ask_for(app: &mut VectorcraftApp, document: Option<u64>, message: &str, detail: &str, command: &str, params: Value) {
let Some(dialogs) = app.dialogs() else {
app.status(format!("{message} (no window to ask in)"));
return;
@@ -137,7 +150,7 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str,
if !detail.is_empty() {
prompt = prompt.paragraph(detail.to_string());
}
let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() };
let asked = Asked { command: command.to_string(), params, document, scope: ScopeHandle::capture(), automated: app.automation_asked() };
let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked);
dialogs.with(|host| host.open(Question(prompt)));
}
@@ -263,10 +276,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
};
if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::<Question>())
&& answer.choice == PromptChoice::Proceed
&& let Some(Asked { command, params, scope, automated }) = answer.take_tag::<Asked>()
&& let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params)))
&& let Some(Asked { command, params, document, scope, automated }) = answer.take_tag::<Asked>()
{
app.status(e);
if document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
app.status(tl!("This dialog was opened in a different document."));
} else if let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) {
app.status(e);
}
}
// The host opens queued messages in `enqueue` order, so the one closed is the oldest.
while dialogs.with(|host| host.take::<Message>()).is_some() {
+42 -14
View File
@@ -41,6 +41,12 @@ fn state_id() -> egui::Id {
egui::Id::unique("custom-dictionary-words")
}
#[derive(Clone)]
struct Draft {
original: Vec<String>,
words: Vec<String>,
}
/// The custom dictionary's words.
fn dictionary(app: &mut VectorcraftApp) -> Result<Vec<String>, String> {
let words = app.run(COMMAND, json!({})).map_err(|e| e.to_string())?;
@@ -65,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
];
let dialog = HostedListManager::new(COMMAND, tl!("Edit Custom Dictionary"), tl!("Entry:"), actions).entries(entries(&words)).renames(WORD);
dialogs.with(|host| host.open(dialog));
ctx.data_mut(|data| data.insert_temp(state_id(), words));
ctx.data_mut(|data| data.insert_temp(state_id(), Draft { original: words.clone(), words }));
Ok(Value::Null)
}
@@ -79,7 +85,8 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi
if choice.action == DONE {
return save(app, ctx);
}
let Some(mut words) = ctx.data(|data| data.get_temp::<Vec<String>>(state_id())) else { return };
let Some(mut draft) = ctx.data(|data| data.get_temp::<Draft>(state_id())) else { return };
let words = &mut draft.words;
match (choice.action.as_str(), choice.entry.as_deref()) {
(ADD, _) => match custom_word(&choice.name) {
Some(word) => words.push(word),
@@ -100,24 +107,20 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| {
if let Some(list) = host.get_dyn_mut(id()).and_then(|d| d.downcast_mut::<HostedListManager>()) {
list.set_entries(entries(&words));
list.set_entries(entries(words));
}
});
}
ctx.data_mut(|data| data.insert_temp(state_id(), words));
ctx.data_mut(|data| data.insert_temp(state_id(), draft));
}
/// Done: deletes the words no longer in the list and adds the new ones in one
/// `text.spelling.editDictionary`, saved once. When it can't be saved, none of it is kept: the
/// dialog stays open with the error, its list as edited, and Cancel leaves the dictionary as it was.
fn save(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(words) = ctx.data(|data| data.get_temp::<Vec<String>>(state_id())) else { return };
let orig = match dictionary(app) {
Ok(orig) => orig,
Err(e) => return app.status(e),
};
let remove: Vec<&String> = orig.iter().filter(|w| !words.contains(w)).collect();
let add: Vec<&String> = words.iter().filter(|w| !orig.contains(w)).collect();
let Some(Draft { original, words }) = ctx.data(|data| data.get_temp::<Draft>(state_id())) else { return };
let remove: Vec<&String> = original.iter().filter(|w| words.binary_search(w).is_err()).collect();
let add: Vec<&String> = words.iter().filter(|w| original.binary_search(w).is_err()).collect();
match app.run(EDIT, json!({ "remove": remove, "add": add })) {
Ok(_) => {
if let Some(dialogs) = app.dialogs() {
@@ -136,8 +139,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
if let Some(choice) = dialogs.with(|host| host.get_mut_by_id::<HostedListManager>(id()).and_then(HostedListManager::take_choice)) {
apply(app, ctx, &choice);
}
if dialogs.with(|host| host.take_by_id::<HostedListManager>(id())).is_some() {
ctx.data_mut(|data| data.remove::<Vec<String>>(state_id()));
if dialogs.with(|host| host.take_by_id::<HostedListManager>(id()).is_some() && host.get_by_id::<HostedListManager>(id()).is_none()) {
ctx.data_mut(|data| data.remove::<Draft>(state_id()));
}
}
@@ -190,7 +193,7 @@ mod tests {
/// The dialog's list, of `mine` (other tests may have their words in the dictionary meanwhile).
fn words(app: &VectorcraftApp, mine: &[&str]) -> Vec<String> {
let ctx = app.ui_ctx.clone().expect("a window");
let all = ctx.data(|data| data.get_temp::<Vec<String>>(super::state_id())).unwrap_or_default();
let all = ctx.data(|data| data.get_temp::<super::Draft>(super::state_id())).map(|draft| draft.words).unwrap_or_default();
all.into_iter().filter(|w| mine.contains(&w.as_str())).collect()
}
@@ -235,6 +238,31 @@ mod tests {
forget(&mut app, &[A, B, C]);
}
#[test]
fn done_preserves_dictionary_changes_made_after_opening() {
let _dictionary = crate::testing::custom_dictionary();
const KEPT: &str = "zqvdictoutsideadd";
const REMOVED: &str = "zqvdictoutsideremove";
let mut app = app();
forget(&mut app, &[A, B, KEPT, REMOVED]);
for word in [A, REMOVED] {
app.run("text.spelling.addWord", json!({"word": word})).unwrap();
}
let mut p = Panel::new(app, draw);
super::open(&mut p.app()).unwrap();
p.app().run("text.spelling.addWord", json!({"word": KEPT})).unwrap();
p.app().run("text.spelling.removeWord", json!({"word": REMOVED})).unwrap();
p.click(A);
p.click("Delete");
enter(&mut p, B);
p.click("Add");
p.click("Done");
let mut app = p.app();
let final_words = [A, B, KEPT, REMOVED].map(|word| has(&mut app, word));
forget(&mut app, &[A, B, KEPT, REMOVED]);
assert_eq!(final_words, [false, true, true, false]);
}
/// Done that can't be saved keeps none of the edits: the dialog stays open and Cancel leaves the
/// dictionary as it was.
#[test]
+51 -4
View File
@@ -143,13 +143,15 @@ struct Edited {
pick: Option<ColorRequest>,
}
/// The Properties section's colour picker: the dialog it opened, the colour it answers for and the dimension it edits.
/// The Properties section's colour picker and the swatch, document and dimension it edits.
#[derive(Clone, Debug)]
pub(crate) struct Pick {
/// The open colour picker.
pub id: DialogId,
/// The key of the swatch that asked.
pub key: String,
/// The document that contains the dimension.
pub document: u64,
/// The dimension the colour goes to.
pub target: NodeId,
}
@@ -340,8 +342,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
let Some(pick) = app.object_dialogs.dimension.clone() else { return };
let Some(finished) = dialogs.with(|host| host.take_by_id::<ColorPickerDialog>(pick.id)) else { return };
app.object_dialogs.dimension = None;
if let Some(ColorPickerResult { picked, .. }) = finished.ok()
&& let Some(mut o) = options_of(app, pick.target)
let Some(ColorPickerResult { picked, .. }) = finished.ok() else { return };
if app.session.active().map(|st| st.uid) != Some(pick.document) {
app.status("The active document changed while the Color Picker was open");
return;
}
if let Some(mut o) = options_of(app, pick.target)
&& set_color(&mut o, &pick.key, picked.color)
{
update(app, pick.target.0, &o);
@@ -715,12 +721,13 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) {
});
}
if let Some(request) = edited.pick
&& let Some(document) = app.session.active().map(|st| st.uid)
&& let Some(dialogs) = app.dialogs()
{
let key = request.key.clone();
let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app));
let picker = dialogs.with(|host| host.open(picker));
app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) });
app.object_dialogs.dimension = Some(Pick { id: picker, key, document, target: NodeId(id) });
}
Row::new().show(ui, |ui, _| {
if Button::new(tl!("Apply to All")).show(ui).clicked()
@@ -775,6 +782,46 @@ mod tests {
serde_json::from_value(app.borrow().session.tool_options_of("dimension")["style"].clone()).unwrap()
}
#[test]
fn dimension_properties_picker_keeps_its_source_document() {
use crate::tests::panel_harness::Panel;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let mut add_dimension = |line_color: [u8; 3]| {
app.run("file.new", json!({"width":200,"height":200})).unwrap();
let created = app.run("dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"lineColor":line_color}})).unwrap();
let id = created["id"].as_u64().unwrap();
app.run("select.set", json!({"ids":[id]})).unwrap();
NodeId(id)
};
let source = add_dimension([17, 34, 51]);
let other = add_dimension([51, 34, 17]);
assert_eq!(source, other, "each drawing allocates its own object ids");
app.run("document.activate", json!({"index":0})).unwrap();
let mut panel = Panel::new(app, properties_section);
let ctx = panel.ctx().clone();
let host = WindowDialogs::of(&ctx, &WindowKey::main());
panel.click("Line Color");
let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id;
host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap();
panel.app().run("document.activate", json!({"index":1})).unwrap();
assert!(host.with(|h| h.confirm_by_id(&ctx, picker)));
pump(&mut panel.app(), &ctx);
assert_eq!(options_of(&panel.app(), other).unwrap().line_color, [51, 34, 17]);
panel.app().run("document.activate", json!({"index":0})).unwrap();
assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]);
panel.click("Line Color");
let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id;
host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap();
assert!(host.with(|h| h.confirm_by_id(&ctx, picker)));
pump(&mut panel.app(), &ctx);
assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [18, 52, 86]);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]);
}
/// The Arrow Style rule of `ui.dialog.set` and the saved style: a head clears with `arrowStyle`, a built-in head
/// sets its entry's two values, a name that is no built-in head is refused, and a draft that does not validate
/// cannot be saved.
+46 -2
View File
@@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into()));
fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into()));
fields["convertColors"] = json!(true);
let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone());
let (source, mode, setup) = ((st.uid, st.reverts), st.doc.color_mode, st.doc.setup.clone());
let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) };
let presets: Vec<String> = app.session.flattener_presets().into_iter().map(|p| p.name).collect();
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
@@ -186,8 +186,12 @@ fn color_commands(app: &VectorcraftApp, fields: &Map<String, Value>) -> Result<V
}
fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) {
let source = app.document_setup_source.and_then(|(uid, reverts)| app.session.active().filter(|st| st.uid == uid).map(|st| (st, reverts)));
let Some((doc, reverts)) = source else {
return Err(tl!("Document Setup can only change the document where it was opened.").to_owned());
};
if doc.reverts != reverts {
return Err(tl!("Reopen Document Setup after reverting the drawing.").to_owned());
}
let map = json_map(fields);
let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect());
@@ -700,6 +704,46 @@ mod tests {
check_source_document(true);
}
#[test]
fn a_revert_refuses_a_stale_document_setup_for_both_confirmation_paths() {
for edit_artboards in [false, true] {
let (mut app, ctx) = new_app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("document-setup-revert");
let path = dir.join("setup.vectorcraft");
app.run("document.setup", json!({"bleed": [2, 2, 2, 2]})).unwrap();
app.run("file.saveAs", json!({"path": path})).unwrap();
app.run("document.setup", json!({"bleed": [7, 7, 7, 7]})).unwrap();
app.run("file.documentSetup", json!({})).unwrap();
set(&app, &ctx, "bleed", json!([9, 9, 9, 9]));
let source = app.session.doc().unwrap();
let (uid, generation) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reverted = app.session.doc().unwrap();
assert_eq!(reverted.uid, uid);
assert_ne!(reverted.reverts, generation);
let undo = reverted.history.undo.len();
if edit_artboards {
set(&app, &ctx, "editArtboards", json!(true));
super::pump(&mut app, &ctx);
} else {
assert!(!press_ok(&mut app, &ctx));
}
assert!(is_open(&app));
assert_eq!(app.session.tool_id(), "selection");
let reverted = app.session.doc().unwrap();
assert_eq!(reverted.doc.setup.bleed, [2.0; 4]);
assert_eq!(reverted.history.undo.len(), undo);
app.run("file.documentSetup", json!({})).unwrap();
set(&app, &ctx, "bleed", json!([5, 5, 5, 5]));
assert!(press_ok(&mut app, &ctx));
assert_eq!(app.session.doc().unwrap().doc.setup.bleed, [5.0; 4]);
}
}
#[test]
fn edit_artboards_applies_settings_and_closes_the_dialog() {
let (mut app, ctx) = setup_open();
+77 -10
View File
@@ -61,6 +61,8 @@ pub(crate) struct Open {
pub id: DialogId,
/// Which of the three dialogs it is.
pub kind: &'static str,
/// The drawing that supplied the selection and defaults at opening.
document: Option<u64>,
/// The envelope the dialog previews.
pub preview: LivePreview,
// PLAN: ef.C11's `Open` has no `generation`; the same kind reopened has the same id, so the id cannot tell the held Cancel of the replaced dialog from the new one's.
@@ -68,6 +70,18 @@ pub(crate) struct Open {
pub generation: u64,
}
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
app.session.active().map(|st| st.uid) == self.document
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app) {
self.preview.cancel(app);
}
}
}
/// The dialog's title.
fn heading(kind: &str, reset: bool) -> Label {
Label::from(
@@ -172,10 +186,12 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result<Value, String> {
/// Options dialog sets the defaults for new envelopes and has nothing to preview.
fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map<String, Value>, envelope: bool) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let document = app.session.active().map(|st| st.uid);
if let Some(previous) = app.effect_dialogs.envelope.take() {
previous.preview.cancel(app);
let id = previous.id;
previous.cancel_preview(app);
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.cancel_by_id(&ctx, previous.id));
dialogs.with(|host| host.cancel_by_id(&ctx, id));
}
}
let fields = fields_of(&params(kind, &DialogFields::new()), &values);
@@ -188,28 +204,32 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map<String,
if app.effect_dialogs.envelope.as_ref().is_some_and(|open| open.generation == generation)
&& let Some(open) = app.effect_dialogs.envelope.take()
{
open.preview.cancel(app);
open.cancel_preview(app);
}
});
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| accept(app, kind, result);
let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
let id = open_held_with(app, dialog, accept, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation });
Ok(Value::Null)
}
/// OK: keeps the preview as one undo step. A refused command keeps the dialog open.
fn accept(app: &mut VectorcraftApp, kind: &'static str, result: &ParamResult) -> Result<(), String> {
let (cmd, p, _) = command(kind, &json_of(&params(kind, &result.fields), &result.fields));
let Some(Open { id, generation, preview, .. }) = app.effect_dialogs.envelope.take() else {
fn accept(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let Some(open) = app.effect_dialogs.envelope.as_ref().filter(|open| open.id == result.id) else {
return Err("the envelope dialog is gone".into());
};
if !open.on_original_drawing(app) {
return Err(tl!("Return to the original drawing to apply the envelope").into());
}
let kind = open.kind;
let (cmd, p, _) = command(kind, &json_of(&params(kind, &result.fields), &result.fields));
let Open { id, document, preview, generation, .. } = app.effect_dialogs.envelope.take().ok_or("the envelope dialog is gone")?;
match preview.commit(app, cmd, p) {
Ok(_) => Ok(()),
Err(e) => {
// The attempt ended the preview; the next pass starts a new one over the same values. Nothing to undo
// when no interaction was open, so the answer is not needed.
let _ = app.session.cancel_interaction();
app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation });
Err(e)
}
}
@@ -252,6 +272,10 @@ fn command(kind: &str, f: &Map<String, Value>) -> (&'static str, Value, &'static
/// canvas shows them. The dialog's Cancel rolls the preview back through the held record's cancel.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.effect_dialogs.envelope.take() else { return };
if !open.on_original_drawing(app) {
app.effect_dialogs.envelope = Some(open);
return;
}
let shown = app
.dialogs()
.and_then(|dialogs| dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
@@ -465,6 +489,49 @@ mod tests {
);
}
#[test]
fn envelope_warp_refuses_preview_and_ok_in_the_other_drawing() {
let (mut app, _) = app_with_rect();
open(&mut app, MAKE_WARP).unwrap();
let id = dialog(&app);
set(&app, id, "bend", json!(23));
pump(&mut app);
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap();
app.run("select.all", json!({})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
set(&app, id, "bend", json!(31));
pump(&mut app);
assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "the other drawing keeps the rectangle");
let ctx = app.ui_ctx.clone().unwrap();
host(&app, |h| h.confirm_by_id(&ctx, id));
pump(&mut app);
assert!(
matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("original drawing"))
);
assert_eq!(json_fields(&app, id)["bend"], 31.0);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
accept(&mut app, id);
let (_, node) = envelope(&app);
assert!(matches!(node.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { bend: 31.0, .. })));
}
#[test]
fn cancelling_an_envelope_dialog_keeps_the_other_drawings_active_edit() {
let (mut app, _) = app_with_rect();
open(&mut app, MAKE_WARP).unwrap();
let id = dialog(&app);
pump(&mut app);
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap();
app.run("select.all", json!({})).unwrap();
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
dismiss(&mut app, id);
assert!(app.session.in_interaction(), "the other drawing's edit stays active");
}
#[test]
fn reset_items_take_the_make_items_place_while_an_envelope_is_selected() {
let labels = |app: &VectorcraftApp| -> Vec<String> {
+26 -1
View File
@@ -154,7 +154,14 @@ fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result<HostedParamDialog, S
/// Shows `dialog`; its OK expands.
fn show(app: &mut VectorcraftApp, dialog: HostedParamDialog) -> Result<Value, String> {
crate::dialogs::host::open_held(app, dialog, ok).ok_or("no window")?;
let document = app.session.active().ok_or("no document open")?.uid;
crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to expand the artwork").into());
}
ok(app, result)
})
.ok_or("no window")?;
Ok(Value::Null)
}
@@ -285,6 +292,24 @@ mod tests {
assert!(matches!(children[1].kind, NodeKind::Mesh(_)));
}
#[test]
fn expand_keeps_its_draft_when_another_drawing_is_active() {
let mut app = app();
gradient_rectangle(&mut app);
open(&mut app).unwrap();
set(&app, "gradient", json!("mesh")).unwrap();
gradient_rectangle(&mut app);
let undo = app.session.active().unwrap().history.undo.len();
let before = app.session.active().unwrap().doc.clone();
assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(reason)) if reason.as_str().contains("original drawing")));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before));
assert_eq!(fields(&app).text("gradient"), Some("mesh"));
app.run("document.activate", json!({"index": 0})).unwrap();
ok_and_close(&mut app);
assert!(expanded_to_a_mesh(&app));
}
#[test]
fn expand_gradient_to_is_disabled_for_a_pattern_fill_alone() {
let mut app = app();
+19 -5
View File
@@ -19,7 +19,7 @@ use craft::ui::style::TypeRole;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format};
use super::export_host::{self, After, Export, Open};
use super::export_host::{self, After, Export};
use super::{dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export};
use crate::{VectorcraftApp, io};
@@ -111,7 +111,9 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) {
fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let n = app.session.active().map_or(0, |s| s.doc.artboards.len());
let source = app.session.active();
let document = source.map(|source| source.uid);
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,
@@ -133,12 +135,21 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res
})
.ok_label(Label::from("Export…"))
});
export_host::open(app, Export::As, false, dialog).map(|_| ()).ok_or_else(|| "no window".into())
export_host::open(app, Export::As { document }, false, dialog).map(|_| ()).ok_or_else(|| "no window".into())
}
fn require_source(app: &VectorcraftApp, document: Option<u64>) -> Result<(), String> {
let document = document.ok_or_else(|| tl!("Open Export As from the drawing you want to export").to_owned())?;
if app.session.active().is_none_or(|source| source.uid != document) {
return Err(tl!("Return to the original drawing to export it").into());
}
Ok(())
}
/// Check the artboard range and that there is something to export; the save panel and the format's options or
/// the file follow once the dialog has closed.
pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFields) -> Result<After, String> {
pub(super) fn confirm(app: &mut VectorcraftApp, document: Option<u64>, fields: &DialogFields) -> Result<After, String> {
require_source(app, document)?;
if let Some((_, hint)) = unavailable(fields) {
return Err(hint.into());
}
@@ -162,7 +173,10 @@ pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFie
}
let range = if all { "all".to_string() } else { range };
let pages = Pages { use_artboards, all, range, selection: false };
Ok(Some(Box::new(move |app| io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages)))))
Ok(Some(Box::new(move |app| {
require_source(app, document)?;
io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages))
})))
}
/// `params` of an options dialog for [`io::export`]: with [`io::EXPORT_SELECTION`] when
@@ -45,6 +45,7 @@ use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize, ToggleCell, ToggleS
use craft::ui::patterns::form_dialogs::{FormDialog, PathRow};
use craft::ui::primitives::{ContentPainterCx, fit_rect};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::focus::Initial;
use craft::ui::tabs::{Tab, TabKind, TabStrip};
use craft::ui::text::TextField;
use craft::ui::tile_grid::{Tile, TileGrid, TilePartEvent};
@@ -958,6 +959,10 @@ impl StackDialog for ExportForScreensDialog {
let mut held = std::mem::take(&mut self.held);
let mut dialog =
FormDialog::new(tl!("Export for Screens"), Bind::bound(&mut fields)).ok_label(ok).ok_enabled(chosen.is_none()).held(&mut held);
if self.web {
// Keep the first artboard visible when the web dialog opens in a short viewport.
dialog = dialog.shaped(|surface| surface.initial_focus(Initial::First));
}
if let Some(reason) = chosen {
dialog = dialog.ok_reason(reason);
}
+5 -2
View File
@@ -21,7 +21,10 @@ pub(crate) type After = Option<Box<dyn FnOnce(&mut VectorcraftApp) -> Result<Val
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Export {
/// Export As.
As,
As {
/// The drawing whose export the dialog configures, when one was open.
document: Option<u64>,
},
/// The options of the raster format `format`.
Raster {
/// The format's id.
@@ -126,7 +129,7 @@ fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String>
fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result<After, String> {
match &open.kind {
Export::As => export_as::confirm(app, open, fields),
Export::As { document } => export_as::confirm(app, *document, fields),
Export::Raster { .. } => png_options::confirm(app, open, fields),
Export::Svg { .. } => svg_options::confirm(app, open, fields),
Export::Eps => eps_options::confirm(app, open, fields),
+61 -1
View File
@@ -13,7 +13,7 @@
use std::path::PathBuf;
use craft::behavior::IconId;
use craft::host::{Host, PickId, PickKind, PickRequest};
use craft::host::{Host, PickId, PickKind, PickRequest, Picked};
use craft::theme::variant::Tone;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::{Radio, RadioGroup, Rating};
@@ -111,6 +111,8 @@ enum Request {
Folder,
/// Save the fields as a template at the path the save pick answered.
SaveTo(PathBuf),
/// A browser picker returned a template larger than the import limit.
TemplateTooLarge,
/// Merge the template `source` into the fields as `mode` says.
Import { source: Info, mode: &'static str },
}
@@ -151,6 +153,15 @@ impl Templates {
&& let Some(answer) = cx.take_pick_answer(id)
{
self.ticket = None;
if let (Pick::Open, Picked::Contents(files)) = (kind, &answer) {
let Some((_, bytes)) = files.first() else { return };
if bytes.len() > vectorcraft_pdf::MAX_TEMPLATE_BYTES {
self.requests.push(Request::TemplateTooLarge);
} else {
*import = Some(source("dataBase64", vectorcraft_format::base64_encode(bytes)));
}
return;
}
let Some(path) = answer.first_path() else { return };
match kind {
Pick::Open => *import = Some(source("path", path.to_string_lossy().into_owned())),
@@ -602,6 +613,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Some(fields) => save_template(app, path, fields),
None => Ok(()),
},
Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()),
Request::Import { source, mode } => {
dialogs.with(|host| host.get_mut_by_id::<FileInfoDialog>(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(()))
}
@@ -767,6 +779,54 @@ mod tests {
assert_eq!(st.history.undo.len(), 1);
}
#[test]
fn browser_picked_templates_enter_the_merge_choice_and_edit_only_the_draft() {
use std::sync::Arc;
use craft::host::{Files, PickRequest, Picked, ScriptedFiles};
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
description: Some("À l’affiche 版".into()),
rating: Some(3),
..Default::default()
});
let utf16 = std::iter::once(0xfeff).chain(template.encode_utf16()).flat_map(u16::to_le_bytes).collect::<Vec<_>>();
for bytes in [template.into_bytes(), utf16] {
let mut app = windowed();
let files = Arc::new(ScriptedFiles::held());
crate::tests::picks::install_files(&mut app, files.clone());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "author", json!("Ada")).unwrap();
let ticket = files.pick(PickRequest::open(super::PURPOSE));
with_dialog(&app, |d| d.templates.ticket = Some((ticket, super::Pick::Open))).unwrap();
assert!(files.answer(Picked::Contents(vec![("Studio.xmp".into(), bytes)])).is_some());
let ctx = app.ui_ctx.clone().unwrap();
for _ in 0..3 {
crate::tests::synthetic::key_frame(&mut app, &ctx, Vec::new());
}
with_dialog(&app, |d| {
assert!(d.templates.ticket.is_none(), "the File Info form consumed the picker answer");
assert!(d.import.is_some(), "a browser-selected template reaches the merge choice");
assert!(super::choose_mode(&mut d.import_mode, "append"));
super::ask_import(&mut d.templates, &d.import, d.import_mode);
})
.unwrap();
super::pump(&mut app, &ctx);
let fields = with_dialog(&app, |d| d.filed_fields()).unwrap();
assert_eq!(
(fields["author"].clone(), fields["description"].clone(), fields["rating"].clone()),
(json!("Ada"), json!("À l’affiche 版"), json!(3))
);
assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "the template updates the draft before OK");
assert!(press_ok(&mut app));
let st = app.session.active().unwrap();
assert_eq!(st.doc.metadata.description, "À l’affiche 版");
assert_eq!(st.history.undo.len(), 1);
}
}
#[test]
fn ok_waits_for_the_merge_choice_of_a_template_being_imported() {
let mut app = windowed();
+2 -1
View File
@@ -311,10 +311,11 @@ pub(super) fn from_missing_links(
folder: &str,
) -> Result<(), String> {
let mut find = dialog(app, missing.clone(), modified.clone(), true)?;
let document = find["document"].as_u64().ok_or("no document open")?;
find.insert("notes".into(), json!(notes));
start_search(app, &mut find, folder)?;
open(app, find)?;
app.link_asks = Some(LinkAsk { missing, modified, notes, back: true });
app.link_asks = Some(LinkAsk { document, missing, modified, notes, back: true });
Ok(())
}
+18 -2
View File
@@ -293,6 +293,22 @@ fn shown_match(app: &VectorcraftApp, at: &Value, found: &Value) -> Option<String
Some(format!("{} / {} {lead}{before}{hit}{after}{tail}", found["index"], found["count"]))
}
/// Refreshes the match line when a drawing or query change makes its match ineligible or current again.
fn refresh_match(app: &mut VectorcraftApp, query: &Value) -> (bool, Option<String>) {
let Some(last) = app.ui.last_find.as_ref() else { return (false, None) };
let Some(found) = last.get("found") else { return (false, None) };
let at = place(app, last, query);
let matched = at.is_some();
if found["visible"].as_bool().unwrap_or(true) == matched {
return (matched, None);
}
let message = at.and_then(|at| shown_match(app, at, found)).unwrap_or_default();
if let Some(found) = app.ui.last_find.as_mut().and_then(|last| last.get_mut("found")) {
found["visible"] = json!(matched);
}
(matched, Some(message))
}
/// Runs the request the dialog made this frame, then tells the dialog its message and whether a
/// match is current. The match is evaluated in every pump, so a changed Find text or switch
/// disables Replace and Replace & Find at once; a pass that has no request only refreshes it.
@@ -309,10 +325,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
};
Some(ran.unwrap_or_else(|e| said(&e)))
});
let matched = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some());
let (matched, match_message) = refresh_match(app, &form.query);
dialogs.with(|host| {
if let Some(d) = host.get_mut::<FindReplaceDialog>() {
if let Some(message) = message {
if let Some(message) = message.or(match_message) {
d.set_message(message);
}
d.set_matched(matched);
@@ -296,6 +296,37 @@ fn a_changed_search_starts_again() {
assert_eq!(matched(&p), Some((bottom, 4, 7)), "the same search goes on");
}
#[test]
fn the_match_line_follows_the_active_drawing_and_find_query() {
let (app, _) = app_with(&["source cat match"]);
let mut p = Panel::new(app, draw);
p.app().run("file.new", json!({"width": 800, "height": 600})).unwrap();
p.app().run("text.create", json!({"x": 50, "y": 50, "text": "destination dog match"})).unwrap();
p.app().run("document.activate", json!({"index": 0})).unwrap();
choose(&p);
set(&p, "find", json!("cat"));
p.click("Find Next");
assert!(message(&p).contains("source cat match"));
p.app().run("document.activate", json!({"index": 1})).unwrap();
pump(&p);
assert_eq!(matched(&p), None);
assert_eq!(message(&p), "", "the line must not describe a match from another drawing");
p.app().run("document.activate", json!({"index": 0})).unwrap();
pump(&p);
assert!(matched(&p).is_some());
assert!(message(&p).contains("source cat match"));
set(&p, "find", json!("dog"));
pump(&p);
assert_eq!(matched(&p), None);
assert_eq!(message(&p), "", "the line must not describe a match for the previous query");
p.click("Find Next");
pump(&p);
assert_eq!(message(&p), "No matches found", "refreshing the dialog leaves the search result visible");
}
/// The place a search reached belongs to its document: in another document, Edit › Find Next and
/// the dialog start at that document's first match, even where an object there has the same id.
/// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off
+76 -11
View File
@@ -16,6 +16,8 @@
//! (`ObjectDialogs::flare`), not fields.
// PLAN: the `craft_ui` paths and `LivePreview`'s home (`form`) are assumed; `general_lengths` is cv.B5b's.
use std::sync::Arc;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamResult};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
@@ -39,6 +41,8 @@ pub const KIND: &str = "flareOptions";
pub(crate) struct Open {
/// The hosted dialog.
id: DialogId,
opening: Arc<()>,
document: Option<u64>,
/// Where a click opened it, to draw a flare there on OK.
click: Option<Point>,
/// The selected flares (ids) and the settings the dialog opened with, to change them on OK.
@@ -47,6 +51,27 @@ pub(crate) struct Open {
preview: Option<LivePreview>,
}
const PREVIEW_LABEL: &str = "Flare";
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
self.preview.is_none() || app.session.active().map(|st| st.uid) == self.document
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app)
&& !other_preview(app)
&& let Some(preview) = self.preview
{
preview.cancel(app);
}
}
}
fn other_preview(app: &VectorcraftApp) -> bool {
app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL)
}
/// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a
/// flare there on OK. Opened without a click while flares are selected, they show the first one's
/// settings, to change the selected flares on OK.
@@ -91,24 +116,25 @@ pub fn open(app: &mut VectorcraftApp, at: Option<Point>) -> Value {
return Value::Null;
};
// An open the host replaces leaves its preview behind unless it is rolled back here.
if let Some(old) = app.object_dialogs.flare.take()
&& let Some(preview) = old.preview
{
preview.cancel(app);
if let Some(old) = app.object_dialogs.flare.take() {
old.cancel_preview(app);
}
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.object_dialogs.flare.take()
&& let Some(preview) = open.preview
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(move |app| {
if app.object_dialogs.flare.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.flare.take()
{
preview.cancel(app);
open.cancel_preview(app);
}
});
let held = HeldOptions { parent: None, cancel: Some(cancel) };
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone())
});
let document = app.session.active().map(|st| st.uid);
match open_held_with(app, dialog, ok, held) {
Some(id) => app.object_dialogs.flare = Some(Open { id, click: at, edit, preview: previews.then(LivePreview::default) }),
Some(id) => app.object_dialogs.flare = Some(Open { id, opening, document, click: at, edit, preview: previews.then(LivePreview::default) }),
None => app.status("no window"),
}
json!({ "dialog": KIND })
@@ -242,15 +268,27 @@ fn option_values(fields: &Map<String, Value>) -> Map<String, Value> {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
// PLAN: registered in hub-w2's pump file (wg.A18), one line.
let Some(mut open) = app.object_dialogs.flare.take() else { return };
if !open.on_original_drawing(app) {
app.object_dialogs.flare = Some(open);
return;
}
if let Some(mut preview) = open.preview.take() {
let state = app
.dialogs()
.and_then(|host| host.with(|host| host.get_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
if let Some((previewing, fields)) = state {
let values = form::json_of(&params(general_lengths(app)), &fields);
if let Some((cmd, params)) = command(app, &open, &values) {
if previewing
&& other_preview(app)
&& let Err(e) = app.keep_typing()
{
app.status(e);
}
if !other_preview(app)
&& let Some((cmd, params)) = command(app, &open, &values)
{
// The preview reports its own failures on the status line.
let _ = preview.run(app, previewing, "Flare", &cmd, &params);
let _ = preview.run(app, previewing, PREVIEW_LABEL, &cmd, &params);
}
}
open.preview = Some(preview);
@@ -261,6 +299,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the
/// selected flares, draw them again with the settings changed, leaving the tool's options.
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let open = app.object_dialogs.flare.as_ref().ok_or("the Flare Tool Options dialog is gone")?;
if !open.on_original_drawing(app) {
return Err(tl!("Return to the original drawing to place or edit the flare").into());
}
if open.preview.is_some() && other_preview(app) {
app.keep_typing()?;
if other_preview(app) {
return Err(tl!("Finish the current edit before drawing the flare").into());
}
}
let fields = form::json_of(&params(general_lengths(app)), &result.fields);
let accepted = accept(app, &fields);
if accepted.is_ok() {
@@ -430,6 +478,23 @@ mod tests {
assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}");
}
#[test]
fn a_pending_flare_click_waits_for_its_original_drawing() {
let mut app = app();
open(&mut app, Some(Point::new(100.0, 110.0)));
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len();
pump(&mut app);
assert_eq!(count(&app), 0, "the other drawing never shows the flare preview");
press_ok(&mut app);
assert_eq!(count(&app), 0, "the other drawing never keeps the flare");
assert!(app.object_dialogs.flare.is_some());
app.run("document.activate", json!({"index": 0})).unwrap();
press_ok(&mut app);
assert_eq!(count(&app), 1);
assert!(!flare_parts(&app).is_empty());
}
/// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it
/// again with the settings changed, as one undo step, leaving the tool's options.
#[test]
+111 -14
View File
@@ -25,14 +25,16 @@ use craft::host::{PickRequest, Picked};
use craft::table::ui::{
CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions,
};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, PaintUi, Props as _, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, PaintUi, Politeness, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{
DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field,
};
use craft::ui::display::Text;
use craft::ui::layout_components::Row;
use craft::ui::notices::{Notice, NoticeLayout};
use craft::ui::patterns::form_dialogs::FormDialog;
use craft::ui::primitives::TextRun;
use craft::ui::runtime::env::{Env, Label, Units};
@@ -48,6 +50,7 @@ use crate::file_asks::{self, Owner};
/// The dialog kind of Graph Data, the key of its dialog on the host.
pub const KIND: &str = "graphData";
const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet.";
/// The sheet's size: a row of labels over a graph's categories, a column of labels before its
/// series; the least rows it shows.
@@ -68,12 +71,13 @@ const ROW_H: f32 = 19.0;
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// The query fails without a graph selected, with the engine's own message.
let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?;
let document = app.session.active().ok_or("no document open")?.uid;
let graph = app.session.active().and_then(|st| st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)).map(|id| (st, id)));
let scatter = graph.is_some_and(|(st, id)| {
st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter)
});
let id = graph.map(|(_, id)| id.0);
let dialog = GraphDataDialog::new(grid_from_data(&v), id, scatter, can_import(app));
let dialog = GraphDataDialog::new(grid_from_data(&v), document, id, scatter, can_import(app));
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
dialogs.with(|host| host.open(dialog));
Ok(Value::Null)
@@ -391,9 +395,10 @@ fn graph_grid(app: &mut VectorcraftApp, graph: Option<u64>) -> Result<Grid, Stri
Ok(grid_from_data(&v))
}
/// Whether Import Data can ask for a file here: the host has a picker and the app can read files.
/// Browser picks carry their contents; native picks need a path reader.
fn can_import(app: &VectorcraftApp) -> bool {
file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some()
file_asks::can(app, craft::host::PickKind::Open)
&& (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some())
}
/// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it.
@@ -431,6 +436,7 @@ fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result<V
/// What the window asked of the app since the last [`pump`].
struct Asks {
document: u64,
graph: Option<u64>,
import_owner: Arc<()>,
apply: Option<Sheet>,
@@ -442,18 +448,28 @@ struct Asks {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let can = can_import(app);
let active = app.session.active().map(|doc| doc.uid);
let asked = dialogs.with(|host| {
host.get_mut::<GraphDataDialog>().map(|d| {
d.can_import = can;
if active == Some(d.document) {
d.held.clear_refusal();
}
d.take_asks()
})
});
let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return };
let Some(Asks { document, graph, import_owner, apply: filed, actions }) = asked else { return };
let same_document = active == Some(document);
if let Some(sheet) = filed {
if let Err(e) = apply(app, &sheet, graph) {
app.status(e);
}
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(GraphDataDialog::applied));
let answer = if same_document {
if let Err(e) = apply(app, &sheet, graph) {
app.status(e);
}
Ok(())
} else {
Err(Label::from(tl!(WRONG_DOCUMENT)))
};
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|dialog| dialog.applied(answer)));
}
for action in actions {
match action {
@@ -473,6 +489,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
move |app, picked| import(app, &owner, picked),
);
}
Action::Revert if !same_document => app.status(tl!(WRONG_DOCUMENT).to_owned()),
Action::Revert => match graph_grid(app, graph) {
Ok(grid) => {
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|d| d.replace(grid)));
@@ -657,6 +674,7 @@ pub(crate) struct GraphDataDialog {
sheet: Sheet,
state: GridState,
entry: Entry,
document: u64,
/// The graph the sheet opened on.
graph: Option<u64>,
scatter: bool,
@@ -669,7 +687,7 @@ pub(crate) struct GraphDataDialog {
impl GraphDataDialog {
/// The window over `grid`, the data of `graph`; Switch x/y is on for a `scatter` graph.
fn new(grid: Grid, graph: Option<u64>, scatter: bool, can_import: bool) -> Self {
fn new(grid: Grid, document: u64, graph: Option<u64>, scatter: bool, can_import: bool) -> Self {
let sheet = Sheet { grid, ..Sheet::default() };
let state = GridState::new(CellSelection::cell(CellAt::new(0, 1)), 1.0);
let mut entry = Entry { text: String::new(), at: (0, 1) };
@@ -680,6 +698,7 @@ impl GraphDataDialog {
sheet,
state,
entry,
document,
graph,
scatter,
can_import,
@@ -691,12 +710,18 @@ impl GraphDataDialog {
/// Everything the window asked since the last call, once.
fn take_asks(&mut self) -> Asks {
Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) }
Asks {
document: self.document,
graph: self.graph,
import_owner: self.import_owner.clone(),
apply: self.held.take(),
actions: std::mem::take(&mut self.actions),
}
}
/// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again.
fn applied(&mut self) {
self.held.answer(Ok(()));
fn applied(&mut self, answer: Result<(), Label>) {
self.held.answer(answer);
self.held.finish();
}
@@ -727,6 +752,7 @@ impl StackDialog for GraphDataDialog {
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let GraphDataDialog { sheet, state, entry, scatter, can_import, lines, actions, held, .. } = self;
let mut pane = Pane { state, entry, lines, actions, scatter: *scatter, can_import: *can_import };
let refusal = held.refusal().map(|(reason, _)| reason.clone());
let shown = FormDialog::new(tl!("Graph Data"), Bind::bound(&mut *sheet))
.ok_label(tl!("Apply"))
.ok_enabled(!held.is_waiting())
@@ -734,7 +760,12 @@ impl StackDialog for GraphDataDialog {
// The sheet owns the scroll; the controls above it stay in view.
.collection_body(true)
.shaped(|dialog| dialog.initial_focus(Initial::Default))
.show(ui, |ui, _, values| body(ui, values, &mut pane));
.show(ui, |ui, _, values| {
if let Some(reason) = refusal.clone() {
Notice::new(Tone::Bad, reason).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui);
}
body(ui, values, &mut pane)
});
// The pass reports a press only in the pass that took the input, so a second pass of the frame files nothing.
if shown.picked == Some(0) && !held.is_waiting() {
commit_text(sheet, pane.entry);
@@ -846,6 +877,51 @@ mod tests {
pump(app, &ctx);
}
fn sheet_with_matching_graphs() -> (VectorcraftApp, u64) {
let (mut app, id) = app_with("1,2\n3,4", "column");
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let other = app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "csv": "7,8\n9,10"})).unwrap();
assert_eq!(other["id"], id);
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
open(&mut app).unwrap();
set_field(&app, "grid", json!([[""], ["", "5", "6"]])).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
(app, id)
}
#[test]
fn graph_data_apply_cannot_change_the_other_drawings_graph() {
let (mut app, id) = sheet_with_matching_graphs();
let other = data(&mut app, id);
let undo = app.session.active().unwrap().history.undo.len();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id), other);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id)["rows"], json!([[5.0, 6.0]]));
}
#[test]
fn graph_data_revert_keeps_the_draft_in_the_other_drawing() {
let (mut app, id) = sheet_with_matching_graphs();
let draft = read(&app, |dialog| dialog.sheet.grid.clone());
let revert = |app: &mut VectorcraftApp| {
edit(app, |dialog| dialog.actions.push(Action::Revert));
pump(app, &crate::testing::ui_context());
};
revert(&mut app);
assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft);
app.run("document.activate", json!({"index": 0})).unwrap();
let expected = grid_from_data(&data(&mut app, id));
revert(&mut app);
assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), expected);
}
/// The app with the window drawn each frame as the shell draws it.
// PLAN: the shell's own frame (hub-w2) replaces `host.run` here, and runs `file_asks::poll` (files-w7) itself.
fn harness(app: VectorcraftApp) -> Harness {
@@ -978,6 +1054,27 @@ mod tests {
assert_eq!(at(&h, 0, 1), "c");
}
#[test]
fn browser_graph_data_import_reads_picked_bytes_without_a_path_reader() {
let (mut app, _) = app_with(",original\nQ1,1", "column");
app.services.read = None;
app.services.read_head = None;
let files = Arc::new(ScriptedFiles::held().in_browser());
app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap());
app.host = Arc::new(app.host.with_files(files.clone()));
open(&mut app).unwrap();
let mut h = harness(app);
h.run_steps(4);
h.get_by_label("Import Data…").click();
h.run_steps(3);
assert_eq!(files.open(), 1, "the browser can open the Import Data picker");
files.answer(Picked::Contents(vec![("data.txt".into(), b"\timported\nQ2\t8".to_vec())]));
h.run_steps(4);
assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)), "imported");
assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 0)), "Q2");
assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 1)), "8");
}
#[test]
fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() {
let (mut app, _) = app_with(",first\nQ1,1", "column");
+85 -10
View File
@@ -251,9 +251,12 @@ pub(crate) enum Answer {
impl Answer {
/// Runs the command; the refusal is its error.
fn run(&self, app: &mut VectorcraftApp) -> Result<(), Label> {
fn run(&self, app: &mut VectorcraftApp, target: &GraphTarget) -> Result<(), Label> {
if !target.in_active_document(app) {
return Err(Label::from(tl!("This graph design belongs to the document that opened the dialog.")));
}
let design = |d: &Option<DesignKey>| json!({ "design": d.as_ref().map(|d| d.name.as_str()), "library": library_of(d.as_ref()) });
let (command, params) = match self {
let (command, mut params) = match self {
Answer::Column { design: d, options } => {
let mut params = design(d);
params["columnType"] = json!(options.column_type.as_str());
@@ -263,10 +266,38 @@ impl Answer {
}
Answer::Marker { design: d } => ("graph.marker", design(d)),
};
// When selection still describes the opening target, let the command keep its selected series highlighted.
let selected = vectorcraft_engine::graph_type_subject(&app.session).ok();
if !selected.is_some_and(|selected| selected.id.0 == target.graph && selected.series == target.series) {
params["id"] = json!(target.graph);
if !target.series.is_empty() {
params["seriesIndexes"] = json!(target.series);
}
}
app.run(command, params).map(|_| ()).map_err(Label::from)
}
}
/// The graph and picked series the Column or Marker form opened for.
#[derive(Clone)]
struct GraphTarget {
document: u64,
graph: u64,
series: Vec<usize>,
}
impl GraphTarget {
fn selected(app: &VectorcraftApp) -> Result<Self, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let selected = vectorcraft_engine::graph_type_subject(&app.session).map_err(|error| error.to_string())?;
Ok(Self { document, graph: selected.id.0, series: selected.series })
}
fn in_active_document(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|active| active.uid == self.document)
}
}
/// A loaded library's document, for the thumbnails of its designs.
struct LibraryDoc {
id: String,
@@ -361,6 +392,7 @@ impl Lists {
pub(crate) struct GraphDesignDialog {
id: DialogId,
kind: Kind,
target: Option<GraphTarget>,
lists: Lists,
/// The selected rows: any number of designs in Graph Design; one design, or None, in Column and Marker.
selection: Selection<RowKey>,
@@ -376,14 +408,16 @@ pub(crate) struct GraphDesignDialog {
/// What [`pump`] takes from the open dialog to run.
struct Work {
actions: Vec<Action>,
answer: Option<Answer>,
answer: Option<(Answer, GraphTarget)>,
document: Option<u64>,
}
impl GraphDesignDialog {
fn new(kind: Kind, lists: Lists, chosen: Vec<DesignKey>, column: ColumnOptions) -> Self {
fn new(kind: Kind, lists: Lists, chosen: Vec<DesignKey>, column: ColumnOptions, target: Option<GraphTarget>) -> Self {
let mut dialog = GraphDesignDialog {
id: dialog_id(kind.key()),
kind,
target,
lists,
selection: Selection::new(Vec::new(), None, None),
name: String::new(),
@@ -432,7 +466,9 @@ impl GraphDesignDialog {
}
fn take_work(&mut self) -> Work {
Work { actions: std::mem::take(&mut self.actions), answer: self.held.take() }
let answer = self.held.take().and_then(|answer| self.target.clone().map(|target| (answer, target)));
let document = self.target.as_ref().map(|target| target.document);
Work { actions: std::mem::take(&mut self.actions), answer, document }
}
/// What OK files.
@@ -756,7 +792,7 @@ impl StackDialog for GraphDesignDialog {
pub fn open_design(app: &mut VectorcraftApp) -> Result<Value, String> {
let lists = Lists::read(app)?;
let first = lists.designs.first().map(|n| DesignKey::document(n));
open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default()))
open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default(), None))
}
/// Open Column for the selected graph series, on the design and options they draw their columns with (None for plain
@@ -769,14 +805,16 @@ pub fn open_column(app: &mut VectorcraftApp) -> Result<Value, String> {
fractions: v["fractions"].as_str().and_then(Fractions::parse).unwrap_or_default(),
};
let chosen = v["design"].as_str().map(DesignKey::document);
open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options))
let target = GraphTarget::selected(app)?;
open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options, Some(target)))
}
/// Open Marker for the selected graph series, on the design they draw with (None for the default).
pub fn open_marker(app: &mut VectorcraftApp) -> Result<Value, String> {
let v = app.session.execute("graph.marker", &json!({})).map_err(|e| e.to_string())?;
let chosen = v["design"].as_str().map(DesignKey::document);
open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default()))
let target = GraphTarget::selected(app)?;
open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default(), Some(target)))
}
fn open(app: &VectorcraftApp, dialog: GraphDesignDialog) -> Result<Value, String> {
@@ -815,8 +853,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
Err(e) => app.status(e),
}
}
let answered = work.answer.map(|answer| answer.run(app));
let lists = Lists::read(app).ok();
let answered = work.answer.map(|(answer, target)| answer.run(app, &target));
let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| active.uid == document));
let lists = if same_document { Lists::read(app).ok() } else { None };
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<GraphDesignDialog>() {
if let Some(lists) = lists {
@@ -881,6 +920,42 @@ mod tests {
assert!(!dialogs.with(|host| host.is_open::<GraphDesignDialog>()));
}
#[test]
fn graph_column_and_marker_keep_their_opening_graph() {
for (graph_kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
let (mut app, ctx) = app_with_design();
select_graph(&mut app, graph_kind);
let graph = app.session.active().unwrap().selection.objects[0].0;
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let r = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [r]})).unwrap();
app.run("graph.design", json!({"new": true})).unwrap();
select_graph(&mut app, graph_kind);
assert_eq!(app.session.active().unwrap().selection.objects[0].0, graph);
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let design = |app: &mut VectorcraftApp, id| app.session.execute(command, &json!({"id": id})).unwrap()["design"].clone();
activate(&mut app, 0);
crate::menus::invoke(&mut app, command, json!({}));
set(&app, &ctx, "selected", json!("New Design")).unwrap();
activate(&mut app, 1);
let undo = app.session.active().unwrap().history.undo.len();
app.dialogs().unwrap().with(|host| host.confirm::<GraphDesignDialog>(&ctx));
super::pump(&mut app, &ctx);
assert_eq!(design(&mut app, graph), Value::Null);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(fields(&app)["selected"], "New Design");
activate(&mut app, 0);
select_graph(&mut app, graph_kind);
let selected = app.session.active().unwrap().selection.objects[0].0;
assert_ne!(selected, graph);
ok(&mut app, &ctx);
assert_eq!(design(&mut app, graph), "New Design");
assert_eq!(design(&mut app, selected), Value::Null);
}
}
#[test]
fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() {
for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] {
@@ -40,13 +40,19 @@ impl Target {
/// Open the dialog with `name` in its field; OK runs `target`.
fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let params = vec![Param::new("name", tl!("Style Name:").to_string(), ParamKind::text(name.clone()))];
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::command(&ctx, KIND, DialogFields::from_pairs([("name", name)]), move |fields| {
ParamDialog::command(KIND, tl!("Graphic Style Options").to_string(), params.clone()).values(Bind::bound(fields))
});
// An `Err` (a name another style has) keeps the dialog open with the reason.
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ());
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
if !app.session.active().is_some_and(|active| active.uid == document) {
return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned());
}
target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ())
};
host::open_held(app, dialog, ok).ok_or("no window")?;
Ok(Value::Null)
}
@@ -132,4 +138,30 @@ mod tests {
assert_eq!(names(&app).last().unwrap(), "Halo");
assert!(app.run("ui.graphicStyleOptions", json!({"name": "nope"})).is_err());
}
#[test]
fn renaming_a_style_does_not_change_a_matching_name_in_another_drawing() {
let mut app = app();
app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap();
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap();
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let other = names(&app);
let undo = app.session.active().unwrap().history.undo.len();
activate(&mut app, 0);
open(&mut app, Some("Twin")).unwrap();
let id = options(&app);
set(&app, id, "name", json!("Source style"));
activate(&mut app, 1);
accept(&mut app, id);
assert_eq!(names(&app), other);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(options(&app), id);
activate(&mut app, 0);
accept(&mut app, id);
assert!(names(&app).iter().any(|name| name == "Source style"));
}
}
+110 -20
View File
@@ -4,6 +4,8 @@
//!
//! Fields: `reduction`, `colors`, `dither`, `ditherAmount` and `preview`.
use std::sync::Arc;
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::UnitKind;
@@ -21,6 +23,28 @@ const CMD: &str = "edit.colors.toIndexed";
/// The undo step a preview and OK make.
const PREVIEW_LABEL: &str = "Convert to Indexed Color";
pub(crate) struct Open {
document: u64,
opening: Arc<()>,
preview: LivePreview,
}
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.uid == self.document)
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app) && !other_preview(app) {
self.preview.cancel(app);
}
}
}
fn other_preview(app: &VectorcraftApp) -> bool {
app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL)
}
/// The reductions besides those of a PNG-8 export, as (value, label).
const MORE_REDUCTIONS: [(&str, &str); 2] = [("uniform", "Uniform"), ("document", "Document Swatches")];
@@ -62,38 +86,71 @@ pub fn open(app: &mut VectorcraftApp) {
app.status("no window".to_string());
return;
};
let Some(document) = app.session.active().map(|st| st.uid) else {
app.status(tl!("Open a drawing to convert its images"));
return;
};
if let Some(old) = app.object_dialogs.indexed.take() {
old.cancel_preview(app);
}
let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build);
app.object_dialogs.indexed = Some(LivePreview::default());
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let ok = |app: &mut VectorcraftApp, r: &ParamResult| {
let preview = app.object_dialogs.indexed.take().unwrap_or_default();
let done = preview.commit(app, CMD, params(&r.fields)).map(|_| ());
let open = app.object_dialogs.indexed.as_ref().ok_or("the Indexed Color dialog is gone")?;
if !open.on_original_drawing(app) {
return Err(tl!("Return to the original drawing to convert its images").into());
}
if other_preview(app) {
app.keep_typing()?;
if other_preview(app) {
return Err(tl!("Finish the current edit before converting its images").into());
}
}
let open = app.object_dialogs.indexed.take().ok_or("the Indexed Color dialog is gone")?;
let done = open.preview.commit(app, CMD, params(&r.fields)).map(|_| ());
if done.is_err() {
// The dialog stays open and previews again.
app.object_dialogs.indexed = Some(LivePreview::default());
app.object_dialogs.indexed = Some(Open { preview: LivePreview::default(), ..open });
}
done
};
let cancel = Box::new(|app: &mut VectorcraftApp| {
if let Some(preview) = app.object_dialogs.indexed.take() {
preview.cancel(app);
let cancel = Box::new(move |app: &mut VectorcraftApp| {
if app.object_dialogs.indexed.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.indexed.take()
{
open.cancel_preview(app);
}
});
if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_none() {
app.object_dialogs.indexed = None;
if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_some() {
app.object_dialogs.indexed = Some(Open { document, opening, preview: LivePreview::default() });
} else {
app.status("no window".to_string());
}
}
/// Each frame: show the dialog's values on the canvas while its Preview box is on.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut preview) = app.object_dialogs.indexed.take() else { return };
let Some(mut open) = app.object_dialogs.indexed.take() else { return };
if !open.on_original_drawing(app) {
app.object_dialogs.indexed = Some(open);
return;
}
let shown = app
.dialogs()
.and_then(|h| h.with(|host| host.get_by_id::<HostedParamDialog>(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields())))));
if let Some((on, p)) = &shown {
let _ = preview.run(app, *on, PREVIEW_LABEL, CMD, p);
if *on
&& other_preview(app)
&& let Err(e) = app.keep_typing()
{
app.status(e);
}
if !other_preview(app) {
let _ = open.preview.run(app, *on, PREVIEW_LABEL, CMD, p);
}
}
app.object_dialogs.indexed = Some(preview);
app.object_dialogs.indexed = Some(open);
}
/// Whether reduction `r` takes a number of colors.
@@ -125,9 +182,7 @@ mod tests {
use super::*;
use vectorcraft_engine::Session;
#[test]
fn commits_the_chosen_palette_as_one_step() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
fn add_raster(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let img = craft_image_codecs::Image::from_raw(
2,
@@ -138,8 +193,7 @@ mod tests {
)
.unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let id = app
.session
app.session
.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
@@ -156,7 +210,19 @@ mod tests {
sel.set([id]);
Ok(id)
})
.unwrap();
.unwrap()
}
fn palette(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> &vectorcraft_doc::ImageBlob {
let st = app.session.doc().unwrap();
let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") };
&st.doc.images[&im.key]
}
#[test]
fn commits_the_chosen_palette_as_one_step() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let id = add_raster(&mut app);
let undo = app.session.doc().unwrap().history.undo.len();
app.run("ui.indexedColorDialog", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
@@ -170,9 +236,33 @@ mod tests {
crate::dialogs::host::pump(&mut app, &ctx);
let st = app.session.doc().unwrap();
assert_eq!(st.history.undo.len(), undo + 1);
let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") };
let blob = &st.doc.images[&im.key];
let blob = palette(&app, id);
assert!(blob.indexed_png());
assert_eq!(blob.rgba().unwrap().2, [0, 0, 0, 255, 0, 0, 0, 255], "black and white only");
}
#[test]
fn indexed_color_preview_and_ok_leave_the_other_drawings_pixels_unchanged() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let source = add_raster(&mut app);
open(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
let id = dialog_id(KIND);
host.with(|h| h.set_json_field(&ctx, id, "reduction", json!("blackWhite"))).unwrap();
let other = add_raster(&mut app);
host.with(|h| h.set_json_field(&ctx, id, "dither", json!("none"))).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!palette(&app, other).indexed_png(), "the other drawing does not show the preview");
host.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!palette(&app, other).indexed_png(), "the other drawing does not keep the preview");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
host.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(palette(&app, source).indexed_png());
}
}
+40 -8
View File
@@ -14,7 +14,7 @@
//! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked.
use craft::behavior::{Selection, keyed};
use craft::host::PickRequest;
use craft::host::{PickId, PickRequest, Picked};
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
@@ -61,6 +61,8 @@ struct Form {
file: String,
/// The linked file selected in the list, as linked or as the list shows it.
selected: String,
/// The file chooser still waiting for its typed answer.
pick: Option<PickId>,
pending: Option<Pending>,
}
@@ -217,12 +219,25 @@ fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) {
if selection.items.first() != selected {
form.selected = selection.items.into_iter().next().unwrap_or_default();
}
Field::new(caption("File or URL:")).show(ui, |ui, _| {
let request = PickRequest::open("javascript").filter("JavaScript", &["js"]);
let out = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).pick(request).show(ui);
// The answer is a path; the dialog links a `file:///` URL ([`crate::io::file_url`]).
if let Some(path) = out.picked {
form.file = crate::io::file_url(&path);
Field::new(caption("File or URL:")).show(ui, |ui, cx| {
if let Some(ticket) = form.pick
&& let Some(answer) = cx.take_pick_answer(ticket)
{
form.pick = None;
// Browser picks supply the file's bytes and basename. Only a filesystem path can be linked.
if let Picked::Paths(paths) = answer
&& let Some(path) = paths.first()
{
form.file = crate::io::file_url(&path.to_string_lossy());
}
}
let row = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).show(ui);
if row.browse
&& form.pick.is_none()
&& let Some(host) = cx.env.host()
{
let request = PickRequest::open("javascript").filter("JavaScript", &["js"]);
form.pick = Some(host.files().pick(request));
}
});
let chosen = selected_row(files, &form.selected);
@@ -242,7 +257,7 @@ mod tests {
use std::rc::Rc;
use std::sync::Arc;
use craft::host::{AppInfo, Host, Picked, ScriptedFiles};
use craft::host::{AppInfo, Host, ScriptedFiles};
use craft::ui::testing::Fixture;
use egui::{Key, Modifiers};
use vectorcraft_engine::Session;
@@ -380,4 +395,21 @@ mod tests {
let file = form.borrow().file.clone();
assert!(file.starts_with("file:///") && file.ends_with("/my%20menu.js") && !file.contains('\\'), "{file}");
}
#[test]
fn a_browser_file_pick_does_not_invent_a_local_script_url() {
let files = Arc::new(ScriptedFiles::held());
let form = Rc::new(RefCell::new(Form { file: "https://example.test/menu.js".into(), ..Default::default() }));
let shown = Rc::clone(&form);
let mut fixture = Fixture::new(move |ui| body(ui, &[], &mut shown.borrow_mut()));
fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build()));
fixture.settle();
let choose = fixture.by_label(tl!("Choose…")).expect("the Choose button");
fixture.click(&choose);
fixture.settle();
let picked = Picked::Contents(vec![("menu.js".into(), b"// local script".to_vec())]);
assert!(files.answer(picked).is_some(), "Choose… filed a browser pick");
fixture.idle(3);
assert_eq!(form.borrow().file, "https://example.test/menu.js");
}
}
+82 -3
View File
@@ -36,6 +36,8 @@ const CMD: &str = "text.setFormat";
pub(crate) struct Open {
/// The dialog on the host.
pub id: DialogId,
/// The drawing that owns the text IDs and the preview.
document: u64,
/// The preview on the canvas.
pub preview: LivePreview,
/// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on.
@@ -47,6 +49,12 @@ pub(crate) struct Open {
initial: DialogFields,
}
impl Open {
fn in_opening_document(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.uid == self.document)
}
}
/// The three spacing rows: (`text.setFormat` key, field prefix, range).
const ROWS: [(&str, &str, (f64, f64)); 3] = [
("wordSpacing", "word", JustificationOptions::WORD_SPACING),
@@ -108,6 +116,7 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> {
/// Open Justification on the paragraph attributes the Paragraph panel shows.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
crate::panels::character::text_style(app).ok_or("select some type first")?;
let document = app.session.active().ok_or("no document open")?.uid;
// While typing, the dialog acts on the paragraphs of the text being edited.
let mut targets = json!({});
let mut story = None;
@@ -136,20 +145,24 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), |f| form(f)).preview_off();
let id = super::host::open_held(app, dialog, |app, result| {
let Some(open) = app.justification.take() else { return Ok(()) };
if !open.in_opening_document(app) {
app.justification = Some(open);
return Err(tl!("This dialog was opened in a different document.").to_owned());
}
let p = params(app, &result.fields, &open);
if !changes(&p) {
// Nothing to apply: end the preview as production's OK did.
open.preview.cancel(app);
return Ok(());
}
let Open { id, preview, targets, story, initial } = open;
let Open { id, document, preview, targets, story, initial } = open;
preview.commit(app, CMD, Value::Object(p)).map(|_| ()).inspect_err(|_| {
// The dialog stays open on the refusal, with a preview of its own again.
app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial });
app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial });
})
})
.ok_or("no window")?;
app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial: fields });
app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial: fields });
Ok(Value::Null)
}
@@ -200,6 +213,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.justification.take() else { return };
let shown =
app.dialogs().and_then(|d| d.with(|h| h.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
// A document switch ends that document's preview. The active drawing may have started a different one.
if !open.in_opening_document(app) {
if shown.is_some() {
open.preview = LivePreview::default();
app.justification = Some(open);
}
return;
}
// The host lock is released: a command never runs inside `DialogHost::with`.
let Some((on, fields)) = shown else {
open.preview.cancel(app);
@@ -433,4 +454,62 @@ mod tests {
app.run("edit.undo", json!({})).unwrap();
assert!(auto_leadings(&app, c).iter().all(|l| *l == 150.0), "undo restores the hidden frame");
}
fn two_drawings() -> (VectorcraftApp, u64) {
let (mut app, id) = app();
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap();
assert_eq!(id, second, "local text IDs may match between drawings");
app.run("document.activate", json!({"index": 0})).unwrap();
(app, id)
}
#[test]
fn justification_approval_leaves_text_in_the_other_drawing_unchanged() {
let (mut app, id) = two_drawings();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
app.run("document.activate", json!({"index": 1})).unwrap();
driver::ok(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
assert!(driver::is_open(&app));
assert_eq!(driver::fields(&app).number("autoLeading"), Some(180.0));
app.run("document.activate", json!({"index": 0})).unwrap();
driver::ok(&mut app);
assert!(!driver::is_open(&app));
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
}
#[test]
fn justification_preview_leaves_text_in_the_other_drawing_unchanged() {
let (mut app, id) = two_drawings();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
app.run("document.activate", json!({"index": 1})).unwrap();
driver::set(&mut app, "preview", json!(true));
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
driver::cancel(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
}
#[test]
fn cancelling_justification_keeps_the_other_drawings_new_interaction() {
let (mut app, id) = two_drawings();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
driver::set(&mut app, "preview", json!(true));
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
app.run("document.activate", json!({"index": 1})).unwrap();
app.begin_interaction("New text edit").unwrap();
app.session.preview("text.setFormat", &json!({"ids": [id], "autoLeading": 190})).unwrap();
driver::cancel(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 190.0);
assert!(app.session.in_interaction());
}
}
+58 -6
View File
@@ -249,9 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue {
/// Opens the dialog on `value`.
fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let st = app.session.active().ok_or("no document open")?;
let dialogs = app.dialogs().ok_or("no window")?;
dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value)));
dialogs.with(|host| host.open(LayerOptionsDialog::new(st.uid, st.reverts, value)));
Ok(Value::Null)
}
@@ -412,6 +412,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) {
pub(crate) struct LayerOptionsDialog {
id: DialogId,
document: u64,
reverts: u64,
open: bool,
value: LayerOptionsValue,
held: HeldAnswer<LayerOptionsValue>,
@@ -423,8 +424,17 @@ pub(crate) struct LayerOptionsDialog {
impl LayerOptionsDialog {
/// The dialog over `value`.
fn new(document: u64, value: LayerOptionsValue) -> Self {
LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None }
fn new(document: u64, reverts: u64, value: LayerOptionsValue) -> Self {
LayerOptionsDialog {
id: dialog_id(KEY),
document,
reverts,
open: true,
value,
held: HeldAnswer::new(),
refused_at: None,
color_request: None,
}
}
/// The OK filed by the user, once.
@@ -573,9 +583,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
// The closed dialog's answer was run when OK was filed.
let _ = dialogs.with(|host| host.take::<LayerOptionsDialog>());
let Some((document, value)) = dialogs.with(|host| {
let Some((document, reverts, value)) = dialogs.with(|host| {
let dialog = host.get_mut::<LayerOptionsDialog>()?;
Some((dialog.document, dialog.take_filed()?))
Some((dialog.document, dialog.reverts, dialog.take_filed()?))
}) else {
return;
};
@@ -588,6 +598,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
// Isolation mode can start while the dialog is open.
let answer = match app.session.active().filter(|st| st.uid == document) {
None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))),
Some(st) if st.reverts != reverts => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))),
Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => {
Err(Label::from("exit isolation mode first"))
}
@@ -935,4 +946,45 @@ mod tests {
let n = app.session.doc().unwrap().doc.node(NodeId(rect)).unwrap().clone();
assert_eq!((n.display_name(), n.locked), ("Box".to_string(), true));
}
#[test]
fn layer_options_refuses_a_stale_draft_after_confirmed_revert() {
let file = std::env::temp_dir().join(format!("vectorcraft-layer-options-revert-{}.vectorcraft", std::process::id()));
let path = file.to_string_lossy();
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": path})).unwrap();
let original = app.session.active().unwrap();
let (uid, reverts, layer) = (original.uid, original.reverts, original.doc.layers[0].id);
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("ui.layerOptions", json!({"id": layer.0})).unwrap();
set(&mut app, "name", json!("Stale Draft"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(&file);
let reverted = app.session.active().unwrap();
assert_eq!((reverted.uid, reverted.reverts, reverted.doc.layers[0].id), (uid, reverts + 1, layer));
let undo = reverted.history.undo.len();
let ctx = app.ui_ctx.clone().unwrap();
let id = open_id(&app);
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
let reverted = app.session.active().unwrap();
assert_eq!(reverted.doc.node(layer).unwrap().display_name(), "Layer 1");
assert_eq!(reverted.history.undo.len(), undo);
assert!(app.any_dialog_open(), "the refused draft stays available to inspect or cancel");
assert_eq!(fields(&app)["name"], "Stale Draft");
assert_eq!(
dialogs.with(|host| host.held_state(id)),
Some(HeldOk::Refused("The document was reverted. Reopen this dialog to continue.".into()))
);
dialogs.with(|host| host.cancel_by_id(&ctx, id));
app.run("ui.layerOptions", json!({"id": layer.0})).unwrap();
set(&mut app, "name", json!("Fresh Draft"));
ok(&mut app);
assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft");
}
}
+120 -18
View File
@@ -26,6 +26,7 @@ use crate::VectorcraftApp;
pub const KIND: &str = "livePaintGapOptions";
const CMD: &str = "livePaint.gapOptions";
const WRONG_DOCUMENT: &str = "Gap Options can only be applied in the document this dialog was opened for.";
/// The undo step the preview and OK make.
const PREVIEW_LABEL: &str = "Gap Options";
@@ -51,20 +52,31 @@ pub(super) static SPEC: OptionSpec = OptionSpec {
pub(crate) struct Open {
/// The dialog the preview belongs to.
pub id: DialogId,
/// The document that owns the preview interaction.
document: u64,
/// The preview the options run as.
pub preview: LivePreview,
}
impl Open {
fn cancel(self, app: &mut VectorcraftApp) {
if app.session.active().is_some_and(|active| active.uid == self.document) {
self.preview.cancel(app);
}
}
}
/// Open Gap Options on the selected Live Paint groups, filled in from the first one's options.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let groups: Vec<u64> = app
.session
.doc()
.map(|d| {
let doc = &d.doc;
d.selection.objects.iter().filter(|id| doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)).map(|id| id.0).collect()
})
.unwrap_or_default();
let active = app.session.active().ok_or("select a Live Paint group")?;
let document = active.uid;
let groups: Vec<u64> = active
.selection
.objects
.iter()
.filter(|id| active.doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint))
.map(|id| id.0)
.collect();
let Some(&first) = groups.first() else { return Err("select a Live Paint group".into()) };
let info = app.session.execute("livePaint.info", &json!({ "group": first })).map_err(|e| e.to_string())?;
let o = &info["gapOptions"];
@@ -75,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields =
[("detect", o["detect"].clone()), ("size", json!(size)), ("custom", custom), ("color", o["color"].clone()), ("closeGaps", json!(false))];
let values = Map::from_iter(fields.map(|(key, value)| (key.to_owned(), value)));
option_form::open(app, &SPEC, values, json!({ "ids": groups })).ok_or("no window")?;
option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document })).ok_or("no window")?;
Ok(Value::Null)
}
fn original_document(app: &VectorcraftApp, extra: &Value) -> Option<u64> {
let document = extra["document"].as_u64()?;
app.session.active().filter(|active| active.uid == document).map(|_| document)
}
/// `livePaint.gapOptions` parameters from the values and the groups in `extra`.
fn params(values: &Map<String, Value>, extra: &Value) -> Value {
let size = match values.get("size").and_then(Value::as_str) {
@@ -111,24 +128,43 @@ fn body(ui: &mut egui::Ui, rows: &mut Rows<'_>) {
/// OK: keep the previewed options as one undo step; with no preview running they run as one.
fn run(app: &mut VectorcraftApp, values: &Map<String, Value>, extra: &Value) -> Result<Value, String> {
let preview = app.object_dialogs.gaps.take().map_or_else(LivePreview::default, |open| open.preview);
let document = original_document(app, extra).ok_or_else(|| tl!(WRONG_DOCUMENT).to_owned())?;
let preview = app.object_dialogs.gaps.take().filter(|open| open.document == document).map_or_else(LivePreview::default, |open| open.preview);
preview.commit(app, CMD, params(values, extra))
}
/// The dialog closed without OK: roll the preview back.
fn cancelled(app: &mut VectorcraftApp) {
if let Some(open) = app.object_dialogs.gaps.take() {
open.preview.cancel(app);
open.cancel(app);
}
}
/// Runs the open Gap Options' preview as its options stand, once per frame after the shell pass: with Preview on the
/// options apply to the groups, off they are rolled back; the gaps a new preview finds are kept for [`overlays`].
/// Nothing runs while an OK waits for its answer, which keeps or refuses the preview that is running.
pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let shown = dialogs.with(|host| {
let form = host.get::<OptionForm>().filter(|form| form.is(KIND))?;
let form = host.get_mut::<OptionForm>().filter(|form| form.is(KIND))?;
let source = form.extra["document"].as_u64()?;
if !app.session.documents().iter().any(|doc| doc.uid == source) {
host.cancel::<OptionForm>(ctx);
return None;
}
let document = original_document(app, &form.extra);
let paused = document.is_none();
if form.preview_paused != paused {
form.preview_paused = paused;
if !paused && form.held.refusal().is_some_and(|(reason, _)| reason.as_str() == tl!(WRONG_DOCUMENT)) {
form.held.clear_refusal();
}
ctx.request_repaint();
}
let Some(document) = document else {
form.previewed = Value::Null;
return None;
};
if !form.held.state().is_none_or(|state| matches!(state, HeldOk::Refused(_))) {
return None;
}
@@ -137,17 +173,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
if form.values.get("color").and_then(Value::as_str).is_some_and(has_alpha) {
params["color"] = Value::Null;
}
Some((form.id(), params, form.preview))
Some((form.id(), document, params, form.preview))
});
let Some((id, params, on)) = shown else { return };
let Some((id, document, params, on)) = shown else { return };
// A preview of another dialog is rolled back before this one starts its own.
let mut open = match app.object_dialogs.gaps.take() {
Some(open) if open.id == id => open,
Some(open) if open.id == id && open.document == document => open,
stale => {
if let Some(stale) = stale {
stale.preview.cancel(app);
stale.cancel(app);
}
Open { id, preview: LivePreview::default() }
Open { id, document, preview: LivePreview::default() }
}
};
let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, &params);
@@ -177,6 +213,7 @@ pub(crate) fn overlays(app: &VectorcraftApp) -> Vec<Overlay> {
let Some(dialogs) = app.dialogs() else { return vec![] };
let shown = dialogs.with(|host| {
let form = host.get::<OptionForm>().filter(|form| form.is(KIND) && form.preview)?;
original_document(app, &form.extra)?;
Some((form.previewed.clone(), form.values.get("color").and_then(Value::as_str)?.to_owned()))
});
let Some((gaps, color)) = shown else { return vec![] };
@@ -236,6 +273,71 @@ mod tests {
app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap()
}
fn open_with_matching_groups(app: &mut VectorcraftApp) -> u64 {
let group = gapped_group(app);
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
assert_eq!(gapped_group(app), group, "the new document reuses the group ID");
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("ui.livePaintGapOptions", json!({})).unwrap();
set(app, "detect", json!(true)).unwrap();
group
}
#[test]
fn gap_confirmation_stays_with_its_document() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
assert!(!press_ok(&mut app), "the unrelated group cannot take the edit");
assert_eq!(options(&app, group), GapOptions::default());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
pump_all(&mut app);
assert!(held(&app).is_none(), "the stale refusal clears on the original tab");
assert!(press_ok(&mut app), "the original group's edit can be retried");
assert!(options(&app, group).detect);
}
#[test]
fn closing_the_original_document_dismisses_gap_options() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
assert!(app.session.close_document(0));
pump_all(&mut app);
assert!(!is_open(&app));
assert_eq!(options(&app, group), GapOptions::default());
}
#[test]
fn gap_preview_disappears_in_another_document_and_resumes_on_return() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
set(&app, "preview", json!(true)).unwrap();
pump_all(&mut app);
assert!(options(&app, group).detect);
assert!(!overlays(&app).is_empty());
app.run("document.activate", json!({"index": 1})).unwrap();
let unrelated_overlays = overlays(&app);
pump_all(&mut app);
let paused = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::<OptionForm>().unwrap().preview_paused);
assert!(paused(&app));
assert_eq!(fields(&app)["preview"], json!(true));
assert_eq!(options(&app, group), GapOptions::default());
assert!(!app.session.in_interaction());
assert!(unrelated_overlays.is_empty());
assert!(overlays(&app).is_empty());
app.run("document.activate", json!({"index": 0})).unwrap();
pump_all(&mut app);
assert!(!paused(&app));
assert!(options(&app, group).detect);
assert!(!overlays(&app).is_empty());
cancel(&mut app);
assert_eq!(options(&app, group), GapOptions::default());
}
#[test]
fn the_menu_item_opens_gap_options_which_preview_the_gaps_and_ok_keeps_them() {
let mut app = app();
+145 -6
View File
@@ -105,8 +105,10 @@ impl<W: Copy> Asked<W> {
/// What the questions about one open's linked files keep between their dialogs: the files still
/// asked about, the modified images to offer for update afterwards and the open's notes.
#[derive(Clone, Debug, Default, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LinkAsk {
/// The document that owns the linked-file IDs.
pub(crate) document: u64,
/// The missing files still asked about (`[{name, path, ids}]`), the next one first.
pub(crate) missing: Vec<Value>,
/// The ids of the images whose file was modified.
@@ -353,7 +355,11 @@ fn questions_for(app: &VectorcraftApp, r: &Value, web: bool) -> (Vec<String>, Ve
/// Opens the dialog about the first of `missing`, keeping what the questions after it need
/// ([`LinkAsk`]). A window that isn't up has nothing to show a question in.
fn open(app: &mut VectorcraftApp, missing: Vec<Value>, modified: Vec<Value>, notes: &[String]) {
let ask = LinkAsk { missing, modified, notes: notes.to_vec(), back: false };
let Some(document) = app.session.active().map(|st| st.uid) else { return };
open_ask(app, LinkAsk { document, missing, modified, notes: notes.to_vec(), back: false });
}
fn open_ask(app: &mut VectorcraftApp, ask: LinkAsk) {
let Some(dialogs) = app.dialogs() else { return };
let dialog = MissingLinksDialog::new(app, ask.clone());
app.link_asks = Some(ask);
@@ -415,7 +421,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec<Value>, one: &str, other: &str) -> Opt
return Some(changed_on_disk_status(ids.len()));
}
let detail = crate::i18n::tn(ids.len() as u64, one, other);
super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids }));
super::confirm::ask_in_document(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids }));
None
}
@@ -436,9 +442,16 @@ pub(crate) fn changed_on_disk_status(n: usize) -> String {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some(result) = dialogs.with(|h| h.take::<MissingLinksDialog>()) else { return };
let ask = app.link_asks.take().unwrap_or_default();
let Some(ask) = app.link_asks.take() else { return };
let Some(answer) = result.ok() else { return show_notes_again(app, &ask) };
let LinkAsk { missing, modified, notes, .. } = ask;
if app.session.active().is_none_or(|st| st.uid != ask.document) {
app.status(tl!("This dialog was opened in a different document."));
if app.session.documents().iter().any(|st| st.uid == ask.document) {
open_ask(app, ask);
}
return;
}
let LinkAsk { document, missing, modified, notes, .. } = ask;
let done = match answer {
MissingLinksAnswer::FindInFolder(folder) => {
super::find_links::from_missing_links(app, missing.clone(), modified.clone(), notes.clone(), &folder).map(|()| None)
@@ -450,7 +463,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Ok(None) => {}
Err(e) => {
app.status(e);
open(app, missing, modified, &notes);
open_ask(app, LinkAsk { document, missing, modified, notes, back: false });
}
}
}
@@ -587,6 +600,84 @@ mod tests {
json!({ "name": format!("{n}.png"), "path": format!("/gone/{n}.png"), "ids": [n] })
}
fn check_replacing_a_missing_file_stays_in_the_opening_drawing(native_picker: bool) {
let name = if native_picker { "different-drawing-picker" } else { "different-drawing-path" };
let (mut app, dir, _) = opened_without_links(name);
let missing = drive::fields::<MissingLinksDialog>(&app)["missing"][0].clone();
let id = missing["ids"][0].as_u64().unwrap();
let picker = crate::tests::picks::scripted(&mut app);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let mut second_ids = Vec::new();
for name in ["second-one.png", "second-two.png"] {
let path = dir.join(name);
std::fs::write(&path, png([0, 200, 0])).unwrap();
let place = app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap();
second_ids.push(place["ids"][0].as_u64().unwrap());
}
assert!(second_ids.contains(&id), "the same ID refers to a different linked file");
let params = json!({"ids": [id]});
let original_path = app.run("links.check", params.clone()).unwrap()["links"][0]["path"].clone();
app.run("document.activate", json!({"index": 0})).unwrap();
if native_picker {
drive::answer::<MissingLinksDialog>(&mut app, &[], true);
assert_eq!(picker.requests().len(), 1);
}
app.run("document.activate", json!({"index": 1})).unwrap();
let replacement = dir.join("replacement.png");
std::fs::write(&replacement, png([0, 0, 200])).unwrap();
let replacement = replacement.to_string_lossy();
if native_picker {
picker.answer(&[&replacement]);
drive::frame(&mut app);
drive::pump(&mut app);
} else {
drive::answer::<MissingLinksDialog>(&mut app, &[("path", json!(replacement))], true);
}
assert_eq!(app.session.active_index(), Some(1));
let after = app.run("links.check", params).unwrap()["links"][0]["path"].clone();
assert_eq!(after, original_path, "the second drawing must keep its original link");
assert_eq!(app.ui.status, "This dialog was opened in a different document.");
assert_eq!(drive::fields::<MissingLinksDialog>(&app)["missing"][0], missing);
app.run("document.activate", json!({"index": 0})).unwrap();
drive::answer::<MissingLinksDialog>(&mut app, &[("path", json!(replacement))], true);
assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 1, "the opening drawing can still replace its file");
assert_eq!(asked_name(&app), "b.png", "the remaining missing file is still offered");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn typed_missing_file_replacement_keeps_the_other_drawing_untouched() {
check_replacing_a_missing_file_stays_in_the_opening_drawing(false);
}
#[test]
fn delayed_missing_file_picker_keeps_the_other_drawing_untouched() {
check_replacing_a_missing_file_stays_in_the_opening_drawing(true);
}
#[test]
fn a_missing_file_folder_search_starts_only_in_the_opening_drawing() {
use crate::dialogs::find_links::FindLinksDialog;
let (mut app, dir, _) = opened_without_links("different-drawing-search");
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let folder = [("searchFolder", json!(dir.to_string_lossy()))];
drive::answer::<MissingLinksDialog>(&mut app, &folder, true);
assert!(drive::is_open::<MissingLinksDialog>(&app));
assert!(!drive::is_open::<FindLinksDialog>(&app));
assert_eq!(app.session.active_index(), Some(1));
app.run("document.activate", json!({"index": 0})).unwrap();
drive::answer::<MissingLinksDialog>(&mut app, &folder, true);
assert!(drive::is_open::<FindLinksDialog>(&app));
assert_eq!(app.session.active_index(), Some(0));
drive::answer::<FindLinksDialog>(&mut app, &[], false);
let _ = std::fs::remove_dir_all(dir);
}
/// Replace relinks the first file and asks about the next; Ignore keeps its preview.
#[test]
fn opening_without_linked_files_asks_to_replace_or_ignore_each() {
@@ -893,4 +984,52 @@ mod tests {
assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn accepting_a_modified_link_offer_does_not_update_another_drawing() {
let dir = std::env::temp_dir().join(format!("vectorcraft-modified-switch-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut app = drive::app();
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
app.session.prefs.update_links = "askWhenModified".into();
let mut ids = vec![];
for name in ["first.png", "second.png"] {
let path = dir.join(name);
std::fs::write(&path, png([200, 0, 0])).unwrap();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap();
let links = app.run("links.list", json!({})).unwrap();
ids.push(links["links"][0]["id"].as_u64().unwrap());
let stamp = std::fs::metadata(&path).unwrap().modified().unwrap();
std::fs::write(&path, png([0, 0, 200])).unwrap();
std::fs::OpenOptions::new()
.write(true)
.open(&path)
.unwrap()
.set_times(std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2)))
.unwrap();
}
assert_eq!(ids[0], ids[1], "the same ID refers to different files");
let answer = |app: &mut VectorcraftApp| {
let question = crate::tests::picks::open_dialogs(app).pop().unwrap().id;
crate::tests::picks::answer_dialog(app, question, &[], true);
};
app.run("document.activate", json!({"index": 0})).unwrap();
ask_update_changed(&mut app, vec![json!(ids[0])]);
app.run("document.activate", json!({"index": 1})).unwrap();
assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1);
answer(&mut app);
let foreign_modified = app.run("links.check", json!({})).unwrap()["modified"].clone();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1);
ask_update_changed(&mut app, vec![json!(ids[0])]);
answer(&mut app);
let original_modified = app.run("links.check", json!({})).unwrap()["modified"].clone();
let _ = std::fs::remove_dir_all(dir);
assert_eq!(foreign_modified, 1, "the second drawing's link still needs approval");
assert_eq!(original_modified, 0, "approval updates the first drawing's link");
}
}
+27 -1
View File
@@ -25,6 +25,7 @@ const TYPES: [&str; 5] = ["calligraphic", "scatter", "art", "bristle", "pattern"
/// It starts on Art when there is art, and it starts on Calligraphic otherwise.
pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let document = st.uid;
let art = match &ids {
Some(ids) => ids.as_array().is_some_and(|a| !a.is_empty()),
None => !st.selection.is_empty(),
@@ -36,7 +37,13 @@ pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> Result<Value, Strin
// PLAN: `HostedParamDialog::new` takes (ctx, key, fields, build); the sheet's (KIND, title, build) has no such form.
let dialog =
HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), rows.clone()).values(Bind::bound(f))).held_ok();
host::open_held(app, dialog, move |app, answer| confirm(app, &answer.fields, ids.clone())).ok_or("no window")?;
host::open_held(app, dialog, move |app, answer| {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to make the brush").into());
}
confirm(app, &answer.fields, ids.clone())
})
.ok_or("no window")?;
Ok(Value::Null)
}
@@ -156,6 +163,25 @@ mod tests {
assert_eq!((&def["type"], &def["size"]), (&json!("calligraphic"), &json!(9.0)));
}
#[test]
fn the_new_brush_type_chooser_waits_for_its_source_drawing() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
app.run("ui.newBrush", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let id = craft::ui::dialog::dialog_id(KIND);
app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "type", json!("scatter"))).unwrap();
app.run("file.new", json!({"width": 500, "height": 400})).unwrap();
app.run("shape.ellipse", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let error = super::super::tests_export::try_confirm(&mut app).expect_err("cannot take another drawing's artwork");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(open_fields(&app).text("type"), Some("scatter"));
app.run("document.activate", json!({"index": 0})).unwrap();
press_ok(&mut app, json!({}));
assert_eq!(open_fields(&app).text("__type"), Some("scatter"));
}
/// The new brush takes the art its Brush Options opened with: changing or clearing the
/// selection while the dialog is open does not change the art, and OK still makes the brush.
#[test]
@@ -18,6 +18,7 @@ pub const KIND: &str = "newColorGroup";
/// art is selected and no swatches are.
pub fn open(app: &mut VectorcraftApp, swatches: Vec<String>) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let document = st.uid;
let art = !st.selection.is_empty();
let mut fields = DialogFields::new();
fields.set("name", st.doc.free_swatch_name("Color Group"));
@@ -37,6 +38,9 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec<String>) -> Result<Value, St
];
let dialog = hosted(&ctx, KIND, tl!("New Color Group"), fields, rows, false);
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
if !app.session.active().is_some_and(|active| active.uid == document) {
return Err(tl!("Create this color group in the document that opened the dialog.").to_owned());
}
app.run("swatch.newGroup", params(&answer.fields, &swatches)).map(|_| ())
};
super::host::open_held(app, dialog, ok).ok_or(NO_WINDOW)?;
@@ -53,3 +57,45 @@ fn params(fields: &DialogFields, swatches: &[String]) -> Value {
json!({"name": name, "swatches": swatches})
}
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::dialog_id;
use vectorcraft_engine::Session;
use super::*;
#[test]
fn color_group_does_not_convert_the_other_drawings_artwork() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
for color in ["#123456", "#446688"] {
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 25, "height": 25})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
}
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let other = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
activate(&mut app, 0);
open(&mut app, Vec::new()).unwrap();
activate(&mut app, 1);
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let id = dialog_id(KIND);
let confirm = |app: &mut VectorcraftApp| {
dialogs.with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(app, &ctx);
crate::testing::app_frame(app, &ctx, Default::default());
};
confirm(&mut app);
let current = app.session.active().unwrap();
assert_eq!(current.doc, other, "the other drawing keeps its swatches and process fills");
assert_eq!(current.history.undo.len(), undo);
activate(&mut app, 0);
confirm(&mut app);
assert!(app.session.active().unwrap().doc.swatch_groups.iter().any(|group| group.name == "Color Group"));
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) struct ObjectDialogs {
/// The open Blend Options dialog's live preview.
pub blend: Option<LivePreview>,
/// The open Indexed Color dialog's live preview.
pub indexed: Option<LivePreview>,
pub indexed: Option<indexed_color::Open>,
/// The open Gap Options dialog's live preview.
pub gaps: Option<live_paint_gaps::Open>,
/// The Properties section's pending colour pick: dialog id, field key and target dimension.
+12 -2
View File
@@ -7,7 +7,7 @@ use std::ops::RangeInclusive;
use craft::theme::variant::Tone;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::Row;
@@ -175,6 +175,8 @@ pub(crate) struct OptionForm {
lengths: LengthUnits,
/// The Preview check box.
pub(super) preview: bool,
/// The current document does not own this dialog's preview.
pub(super) preview_paused: bool,
/// Whether the dialog's container is open.
open: bool,
/// The OK the dialog filed for [`pump`] to answer.
@@ -202,6 +204,7 @@ pub(super) fn open(app: &mut VectorcraftApp, spec: &'static OptionSpec, values:
extra,
lengths,
preview: false,
preview_paused: false,
open: true,
held: HeldAnswer::new(),
requests: HostRequests::new(),
@@ -249,8 +252,9 @@ impl StackDialog for OptionForm {
// The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing.
let finish = self.held.is_accepted() && !measuring;
let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
let OptionForm { spec, values, lengths, preview, open, held, requests, .. } = self;
let OptionForm { spec, values, lengths, preview, preview_paused, open, held, requests, .. } = self;
let (spec, lengths) = (*spec, *lengths);
let show_pause = *preview && *preview_paused;
let title = (spec.title)();
let refusal = held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone()));
let mut form = FormDialog::new(word(&title), Bind::bound(&mut *values))
@@ -274,6 +278,12 @@ impl StackDialog for OptionForm {
if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) {
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
}
if show_pause {
Notice::new(Tone::Info, tl!("Preview is paused. Return to the document this dialog was opened for.").to_owned())
.layout(NoticeLayout::Inline)
.announce(Politeness::Polite)
.show(ui);
}
if finish {
form.request_close_as(CloseReason::Activated);
}
+22 -4
View File
@@ -20,7 +20,7 @@ use craft::ui::runtime::requests::PathKind;
use serde_json::{Value, json};
use vectorcraft_engine::EngineError;
use super::confirm::ask;
use super::confirm::{ask, ask_in_document};
use crate::background::{self, Writer};
use crate::{VectorcraftApp, file_asks, io};
@@ -46,7 +46,7 @@ fn downloads(app: &VectorcraftApp) -> bool {
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let st = app.session.active().ok_or("no document")?;
let Some(path) = st.path.clone() else {
ask(
ask_in_document(
app,
tl!("Save the document first?"),
tl!("Package collects a saved document with its linked files and fonts."),
@@ -55,6 +55,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
);
return Ok(Value::Null);
};
let document = st.uid;
let p = std::path::Path::new(&path);
let stem = p.file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
@@ -73,6 +74,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.footer_note(Label::from(tl!("Fonts whose licence doesn't allow embedding are not copied.")))
});
crate::dialogs::host::open_held(app, dialog, |app, answer| confirm(app, &answer.fields).map(|_| ())).ok_or("no window")?;
app.package_document = Some(document);
Ok(Value::Null)
}
@@ -96,13 +98,27 @@ fn params(web: bool) -> Vec<Param> {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let id = dialog_id(KEY);
let Some(request) = dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).and_then(HostedParamDialog::pick_path)) else { return };
file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path);
let Some(request) = dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).map(HostedParamDialog::pick_path)) else {
app.package_document = None;
return;
};
if let Some(request) = request {
file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path);
}
}
fn require_package_document(app: &VectorcraftApp, document: u64) -> Result<(), String> {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Package can only save and collect the document where it was opened.").to_owned());
}
Ok(())
}
/// What OK does: save a dirty document, then write the package (on the worker with Background Export on) or
/// download it. `Err` refuses the OK and keeps the dialog open; the reply says whether the package is in the background.
pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
let document = app.package_document.ok_or("no Package dialog open")?;
require_package_document(app, document)?;
let text = |key: &str| fields.text(key).unwrap_or_default();
let mut params = json!({ "folder": text("folder"), "name": text("name") });
for (key, _) in OPTIONS {
@@ -144,6 +160,8 @@ pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result
return r;
}
}
// A completed background job may have changed the active document while Package waited.
require_package_document(app, document)?;
let package = app.session.prepare_package(&params).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?;
let label = format!("Packaging {}", text("name"));
let later = Rc::new(Cell::new(false));
@@ -609,7 +609,7 @@ fn tabs_buttons(unit: Unit) -> Param {
let (rows, _, _) = tab_rows(fields);
let can_add = new_tab_position(&rows, unit).is_some();
let (mut add, mut delete, mut clear) = (false, false, false);
let line = Row::new().show(ui, |ui, _| {
let line = Row::new().wrap(true).show(ui, |ui, _| {
add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui));
delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui));
clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui));
@@ -348,6 +348,42 @@ fn tab_rows(app: &VectorcraftApp) -> Vec<Value> {
fields(app)["tabs"].as_array().cloned().unwrap_or_default()
}
#[test]
fn clear_all_tabs_can_be_clicked_in_a_narrow_viewport() {
use egui::accesskit::Role;
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
for width in [800.0, 540.0] {
let mut app = app();
app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": [{"position": 36.0}, {"position": 72.0}]}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 500.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
};
frame(&mut app, vec![]);
open_tabs(&mut app, "Body");
for _ in 0..5 {
frame(&mut app, vec![]);
}
let out = frame(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let clear = nodes.iter().find(|(_, node)| node.role() == Role::Button && node.label() == Some("Clear All Tabs")).unwrap();
let bounds = clear.1.bounds().unwrap();
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
assert_eq!(tab_rows(&app).len(), 2);
frame(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(&mut app, vec![]);
assert!(tab_rows(&app).is_empty(), "Clear All Tabs at {bounds:?} was not reachable in a {width}-point viewport");
}
}
/// Tabs shows a style's stops in the General unit with their alignment, leader and Align On
/// character; a stop left as it was keeps its position exactly, a changed one is read in the unit,
/// and the stops are stored sorted by position. Add puts a left stop half an inch past the furthest
+180 -32
View File
@@ -3,6 +3,8 @@
//! Every dialog is a held parameter dialog: its OK is the closure given to `open_held`, a refusal keeps it open with
//! the reason, and [`pump`] only runs the live preview of the kinds that have one.
use std::sync::{Arc, Weak};
// PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and
// runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets).
use craft::behavior::ColumnWidth;
@@ -19,7 +21,7 @@ use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
use craft::ui::text::{NumberField, NumberOutput};
use craft::ui::value_drag::SliderScale;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{NodeId, NodeKind, Selection};
use vectorcraft_geom::PathData;
use super::form;
@@ -123,8 +125,55 @@ pub(crate) struct Open {
/// The open Split Into Grid dialog's live state.
pub(crate) struct SplitOpen {
id: DialogId,
document: u64,
preview: LivePreview,
last: Value,
/// An interaction allocates its own selection snapshot, even when the selected objects did not change.
preview_selection: Option<Weak<Selection>>,
}
impl SplitOpen {
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.preview_selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn update_preview(&mut self, app: &mut VectorcraftApp, on: bool, fields: &DialogFields) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return };
if !self.owns_preview(app) {
self.preview = LivePreview::default();
self.preview_selection = None;
if state.interaction.is_some() {
return;
}
}
let params = split_params(fields);
let ran = self.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, &params).is_some();
if !on {
self.preview_selection = None;
} else if ran {
self.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
}
}
fn confirm(&mut self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> {
if app.session.active().is_none_or(|state| state.uid != self.document) {
return Err(tl!("Split Into Grid can only change the document where it was opened.").to_owned());
}
if app.session.in_interaction() && !self.owns_preview(app) {
return Err(tl!("Finish the active edit before applying Split Into Grid.").to_owned());
}
self.preview_selection = None;
std::mem::take(&mut self.preview).commit(app, SPLIT_COMMAND, split_params(fields)).map(drop)
}
fn cancel(self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
self.preview.cancel(app);
}
}
}
/// The command the dialog runs and its parameters.
@@ -410,34 +459,25 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) {
app.status("There is no window to show the dialog in.");
return;
};
let (width, height) =
app.session.active().and_then(|st| st.doc.bounds_of(&st.selection.objects, false)).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let Some(state) = app.session.active() else {
app.status("Open a document before using Split Into Grid.");
return;
};
let document = state.uid;
let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let lengths = crate::canvas::general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| {
ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews(true)
});
let ok = |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| {
let params = split_params(&result.fields);
match app.object_dialogs.split.take() {
Some(record) => {
let id = record.id;
record.preview.commit(app, SPLIT_COMMAND, params).map(drop).inspect_err(|_| {
app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null });
})
}
None => app.run(SPLIT_COMMAND, params).map(drop),
}
let Some(mut record) = app.object_dialogs.split.take() else { return Err(tl!("The Split Into Grid dialog is closed.").to_owned()) };
record.confirm(app, &result.fields).inspect_err(|_| app.object_dialogs.split = Some(record))
};
if let Some(old) = app.object_dialogs.split.take() {
old.preview.cancel(app);
old.cancel(app);
}
let cancel = Box::new(|app: &mut VectorcraftApp| {
if let Some(record) = app.object_dialogs.split.take() {
record.preview.cancel(app);
}
});
match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) {
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null }),
match open_held(app, dialog, ok) {
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, preview: LivePreview::default(), preview_selection: None }),
None => app.status("There is no window to show the dialog in."),
}
}
@@ -456,17 +496,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
}
records.append(&mut app.object_dialogs.path);
app.object_dialogs.path = records;
if let Some(mut s) = app.object_dialogs.split.take() {
if let Some((on, fields)) = dialog_state(app, s.id) {
let params = split_params(&fields);
if !on {
s.last = Value::Null;
}
if s.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, &params).is_some() {
s.last = params;
}
if let Some(mut split) = app.object_dialogs.split.take() {
if let Some((on, fields)) = dialog_state(app, split.id) {
split.update_preview(app, on, &fields);
app.object_dialogs.split = Some(split);
} else {
split.cancel(app);
}
app.object_dialogs.split = Some(s);
}
}
@@ -516,3 +552,115 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> {
})
.collect()
}
#[cfg(test)]
mod split_tests {
use serde_json::json;
use super::*;
use crate::dialogs::tests::{app, cancel, confirm, frame, is_open, set};
fn selected_rectangle(app: &mut VectorcraftApp, width: u32, height: u32) {
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": width, "height": height})).unwrap();
app.run("select.all", json!({})).unwrap();
}
fn other_document(app: &mut VectorcraftApp) {
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
selected_rectangle(app, 150, 90);
}
#[test]
fn split_into_grid_skips_preview_in_the_other_drawing() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
let original = app.session.doc().unwrap().doc.clone();
open_split(&mut app);
set(&mut app, "columns", json!(3));
other_document(&mut app);
let other = app.session.doc().unwrap().doc.clone();
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by Preview");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app, vec![]);
assert_ne!(app.session.doc().unwrap().doc, original);
assert!(app.session.in_interaction());
assert!(confirm(&mut app));
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6);
assert!(!app.session.in_interaction());
}
#[test]
fn split_into_grid_keeps_the_draft_when_ok_is_in_another_drawing() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
open_split(&mut app);
set(&mut app, "columns", json!(3));
other_document(&mut app);
let other = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
let closed = confirm(&mut app);
assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by OK");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert!(!closed && is_open(&app), "the user can return to confirm");
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(confirm(&mut app));
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6);
}
#[test]
fn split_into_grid_cancel_preserves_the_other_drawings_edit() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
other_document(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
let opening = app.session.doc().unwrap().doc.clone();
open_split(&mut app);
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.in_interaction(), "the opening drawing is previewing");
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
assert!(cancel(&mut app));
assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit");
assert_eq!(app.session.doc().unwrap().doc, other);
app.session.commit_interaction().unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
}
#[test]
fn split_into_grid_does_not_adopt_a_new_edit_on_return() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
other_document(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
open_split(&mut app);
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.in_interaction());
for index in [1, 0] {
app.run("document.activate", json!({"index": index})).unwrap();
}
app.session.begin_interaction("New edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let editing = app.session.doc().unwrap().doc.clone();
frame(&mut app, vec![]);
assert!(!confirm(&mut app));
assert!(cancel(&mut app));
assert!(app.session.in_interaction());
assert_eq!(app.session.doc().unwrap().doc, editing);
}
}
@@ -19,6 +19,8 @@ use crate::canvas::general_lengths;
/// The dialog kind of the plane options.
pub const KIND: &str = "perspectivePlane";
const OPENING_DOCUMENT: &str = "__openingDocument";
/// What becomes of the objects on the plane: (`objects` value, label).
const OBJECTS: [(&str, &str); 3] = [("none", "Do Not Move"), ("move", "Move All Objects"), ("copy", "Copy All Objects")];
@@ -47,8 +49,9 @@ fn build<'a>(title: &str, lengths: LengthUnits, _fields: &'a mut DialogFields) -
/// Open the options of `plane` (`{plane}`; default the active plane), filled in with its location.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let doc = &app.session.active().ok_or("no document")?.doc;
let g = PerspectiveGrid::current(doc);
let state = app.session.active().ok_or("no document")?;
let document = state.uid;
let g = PerspectiveGrid::current(&state.doc);
let plane = match p.get("plane").and_then(Value::as_str) {
Some(s) => Plane::parse(s).ok_or("plane must be left, right or ground")?,
None => g.plane,
@@ -60,12 +63,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let lengths = general_lengths(app);
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let Value::Object(map) = json!({"plane": plane.id(), "location": offset, "objects": "none"}) else { return Err("no window".into()) };
let mut fields = form::fields_of(&params(lengths), &map);
// The held answer carries the drawing and plane from the same opening.
fields.set(OPENING_DOCUMENT, document.to_string());
let heading = title(plane);
let dialog = HostedParamDialog::new(&ctx, KIND, form::fields_of(&params(lengths), &map), move |f| build(&heading, lengths, f));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| build(&heading, lengths, f));
// A refusal keeps the dialog open with the reason under its rows.
let ok = move |app: &mut VectorcraftApp, r: &ParamResult| {
let ok = |app: &mut VectorcraftApp, r: &ParamResult| {
let document = r.fields.text(OPENING_DOCUMENT).and_then(|uid| uid.parse().ok());
if !app.session.active().is_some_and(|state| Some(state.uid) == document) {
return Err(tl!("Perspective Plane Options can only change the document where it was opened.").to_owned());
}
let plane = r.fields.text("plane").ok_or_else(|| tl!("The perspective plane is missing").to_owned())?;
let objects = r.fields.text("objects").unwrap_or("none");
let p = json!({"plane": plane.id(), "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects});
let p = json!({"plane": plane, "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects});
app.run("perspective.plane.move", p).map(|_| ())
};
open_held(app, dialog, ok).ok_or("no window")?;
@@ -100,15 +111,75 @@ mod tests {
host(app, |h| h.set_json_field(&ctx, id, field, value)).unwrap();
}
/// OK on the open dialog, then the frame's pump runs the held OK.
fn ok(app: &mut VectorcraftApp) {
fn pump_ok(app: &mut VectorcraftApp) {
let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), the_dialog(app));
// A held OK reports `false` and files its answer for the app; the dialog closes at its next pass.
assert!(host(app, |h| h.confirm_by_id(&ctx, id) || h.held_state(id) == Some(craft::ui::dialog::HeldOk::Waiting)), "OK is enabled");
crate::dialogs::host::pump(app, &ctx);
}
fn ok(app: &mut VectorcraftApp) {
pump_ok(app);
let ctx = app.ui_ctx.clone().unwrap();
crate::tests_synthetic::key_frame(app, &ctx, vec![]);
}
fn right_plane_with_art(app: &mut VectorcraftApp) {
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 450, "y": 380, "width": 60, "height": 60})).unwrap()["id"].clone();
app.run("perspective.attach", json!({"ids": [id], "plane": "right"})).unwrap();
}
#[test]
fn plane_options_keep_the_plane_and_copied_objects_in_the_opening_document() {
let mut app = app();
right_plane_with_art(&mut app);
let opening = app.session.doc().unwrap().doc.clone();
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
set(&app, "location", json!(40.0));
set(&app, "objects", json!("copy"));
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
right_plane_with_art(&mut app);
let other = app.session.doc().unwrap().doc.clone();
let history = app.session.doc().unwrap().history.undo.len();
let (id, _) = the_dialog(&app);
pump_ok(&mut app);
assert_eq!(app.session.doc().unwrap().doc, other, "foreign OK leaves the other drawing and its art unchanged");
assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
assert_eq!(the_dialog(&app).1["location"], 40.0);
assert_eq!(the_dialog(&app).1["objects"], "copy");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
ok(&mut app);
let doc = &app.session.doc().unwrap().doc;
assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0);
assert_eq!(doc.layers[0].children().unwrap().len(), 2, "one copy in the opening drawing");
}
#[test]
fn replacement_plane_options_use_the_replacement_drawing_and_plane() {
let mut app = app();
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
let opening = app.session.doc().unwrap().doc.clone();
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
app.run("ui.perspectivePlane", json!({"plane": "ground"})).unwrap();
set(&app, "location", json!(40.0));
ok(&mut app);
let grid = PerspectiveGrid::current(&app.session.doc().unwrap().doc);
assert_eq!(grid.offset(Plane::Ground), 40.0, "OK moves the replacement opening's plane");
assert_eq!(grid.offset(Plane::Right), 0.0);
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
}
#[test]
fn double_clicking_a_plane_widget_opens_its_options_and_ok_moves_it() {
let mut app = app();
@@ -9,6 +9,8 @@
//!
//! Field: `selected` (a preset's name).
use std::sync::Arc;
use craft::behavior::{DisplayOrder, ItemSource, Selection};
use craft::host::PickRequest;
use craft::ui::buttons::Button;
@@ -117,13 +119,22 @@ pub(super) struct PresetsDialog {
names: Vec<String>,
/// The button pressed in the last pass, for [`pump`] to run outside the host's lock.
action: Option<Action>,
/// Identifies the manager that opened an Import picker.
import_owner: Arc<()>,
open: bool,
}
impl PresetsDialog {
fn new(selected: &str, presets: Vec<GridDefinition>) -> Self {
let mut dialog =
PresetsDialog { id: dialog_id(KIND), selected: selected.to_owned(), presets: Vec::new(), names: Vec::new(), action: None, open: true };
let mut dialog = PresetsDialog {
id: dialog_id(KIND),
selected: selected.to_owned(),
presets: Vec::new(),
names: Vec::new(),
action: None,
import_owner: Arc::new(()),
open: true,
};
dialog.set_presets(presets);
dialog
}
@@ -296,12 +307,18 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul
select(app, &next);
}
Action::Import => {
let Some(owner) = with_dialog(app, |manager| Arc::clone(&manager.import_owner)) else { return Ok(()) };
let request = PickRequest::open(KIND).filter("Perspective grid presets", PRESET_EXTS);
file_asks::ask(app, request, Owner::Free, |app, picked| {
let path = picked.first_path().ok_or("cancelled")?;
let r = app.run("perspective.presets.import", json!({ "path": path }))?;
file_asks::ask(app, request, Owner::Free, move |app, picked| {
let mut params = file_asks::open_params(&picked).ok_or("cancelled")?;
params.remove("name");
let r = app.run("perspective.presets.import", Value::Object(params))?;
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
select(app, first);
with_dialog(app, |manager| {
if Arc::ptr_eq(&manager.import_owner, &owner) {
manager.selected = first.to_owned();
}
});
}
Ok(r)
});
@@ -43,6 +43,7 @@ fn params() -> Vec<Param> {
/// Open the dialog on the placement options of images `ids` (default: the selected ones).
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let source_document = app.session.active().map(|document| document.uid);
let ids = p.get("ids").cloned().unwrap_or(Value::Null);
let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?;
let placement = &r["placement"];
@@ -60,6 +61,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
})
.held_ok();
crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| {
if app.session.active().map(|document| document.uid) != source_document {
return Err(tl!("Placement Options can only change the document where it was opened.").to_owned());
}
let f = &result.fields;
let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]);
let params = json!({ "ids": ids, "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) });
@@ -68,3 +72,57 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
.ok_or("no window")?;
Ok(Value::Null)
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::{HeldOk, dialog_id};
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
use vectorcraft_engine::Session;
use super::*;
#[test]
fn held_placement_options_keep_the_link_and_undo_in_the_opening_document() {
let dir = vectorcraft_testkit::TempDir::new("placement-options-document");
let path = dir.join("linked.png");
let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap();
std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let link = |app: &mut VectorcraftApp| {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap()
};
let source_link = link(&mut app);
let other_link = link(&mut app);
assert_eq!(source_link, other_link, "different documents reuse this object ID");
let settings = |app: &mut VectorcraftApp| {
let placement = app.run(CMD, json!({"ids": [source_link]})).unwrap()["placement"].clone();
(placement, app.session.active().unwrap().history.undo.len())
};
let other = settings(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
let starting = settings(&mut app);
app.run("ui.placementOptionsDialog", json!({"ids": [source_link]})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let id = dialog_id(KEY);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "preserve", json!("fit")).unwrap();
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("document.activate", json!({"index": 1})).unwrap();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(settings(&mut app), other, "the other link and its undo history are preserved");
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(settings(&mut app), starting);
assert!(crate::dialogs::tests::confirm(&mut app));
let (placement, steps) = settings(&mut app);
assert_eq!(placement["preserve"], json!("fit"));
assert_eq!(steps, starting.1 + 1);
}
}
+30 -16
View File
@@ -100,6 +100,7 @@ pub(crate) struct PrintDialogs {
struct Open {
id: DialogId,
mode: PrintMode,
document: Option<u64>,
/// The preset the settings were loaded from last (the Print Preset row's selection).
preset: String,
/// The saved preset the editor edits (empty: a new one).
@@ -157,7 +158,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ).
let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()).to_string();
let fields = fields_of(&saved)?;
start(app, PrintMode::Print, fields, preset, Default::default())
let document = st.uid;
start(app, PrintMode::Print, Some(document), fields, preset, Default::default())
}
/// Open the preset editor on the saved preset `name`, or on a new preset starting from `preset`
@@ -173,7 +175,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
None => (s("preset").unwrap_or(DEFAULT_PRESET).to_string(), app.session.new_print_preset_name(), String::new()),
};
let set = app.session.print_preset_settings(&base).ok_or_else(|| format!("no print preset named `{base}`"))?;
start(app, PrintMode::PresetEditor, fields_of(&set)?, base, (editing, name))
start(app, PrintMode::PresetEditor, None, fields_of(&set)?, base, (editing, name))
}
/// Host the dialog over the settings `fields`; the preset editor edits the saved preset `editing` (empty: a new one)
@@ -181,6 +183,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
fn start(
app: &mut VectorcraftApp,
mode: PrintMode,
document: Option<u64>,
fields: DialogFields,
preset: String,
(editing, name): (String, String),
@@ -217,7 +220,7 @@ fn start(
hosted.set_json_field(&ctx, "name", json!(name))?;
}
let id = dialogs.with(|h| h.open(hosted));
app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None, driver });
app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver });
Ok(Value::Null)
}
@@ -366,6 +369,30 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
let _ = dialogs.with(|h| h.take_by_id::<HostedPrint>(open.id));
return false;
};
for event in std::mem::take(&mut d.events) {
apply_preset_event(app, dialogs, open, &mut d.settings, event);
}
if open.mode == PrintMode::Print {
let same = serde_json::from_value::<PrintSettings>(d.settings.clone())
.ok()
.is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s));
let held = same.then(|| open.preset.clone());
let rows: Vec<PresetRow<String>> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0))
.chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0)))
.collect();
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
}
if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
let message = tl!("Return to the original drawing to print it");
on(dialogs, |p| {
p.set_sheet(None);
p.set_message(Some(message.into()));
if d.ok.is_some() {
p.answer_ok(Err(message.into()));
}
});
return true;
}
// The row was drawn this frame with the controls of the printer before: the next frame shows the new ones.
if d.driver != open.driver {
open.driver = d.driver;
@@ -383,9 +410,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
{
app.status(e);
}
for event in std::mem::take(&mut d.events) {
apply_preset_event(app, dialogs, open, &mut d.settings, event);
}
let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision));
let stamp = (d.settings.to_string(), doc);
let changed = open.preview.as_ref().is_none_or(|(s, _)| *s != stamp);
@@ -425,16 +449,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
p.set_field("__inks", FieldValue::Json(inks));
});
}
if open.mode == PrintMode::Print {
let same = serde_json::from_value::<PrintSettings>(d.settings.clone())
.ok()
.is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s));
let held = same.then(|| open.preset.clone());
let rows: Vec<PresetRow<String>> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0))
.chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0)))
.collect();
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
}
if let Some(answer) = d.ok {
let result = accept(app, open, &answer, &d.name);
on(dialogs, |p| p.answer_ok(result.map_err(Into::into)));
+85 -19
View File
@@ -4,8 +4,8 @@
//! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and
//! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save…
//! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one
//! into the dialog (`view.proofSetup.read`). Both are desktop only. Their pickers start in the
//! Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below
//! into the dialog (`view.proofSetup.read`). The browser reads picked bytes and downloads a copy
//! when saving. Desktop pickers start in the Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below
//! Customize… ([`saved_items`]): Save… makes the folder when it may be written, and Load…'s picker
//! starts in its own default folder until the folder exists.
//!
@@ -116,15 +116,10 @@ fn rgb_device(device: &str) -> bool {
/// The dialog over the host's values, made again every pass.
fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
// The web has no folder to keep setups in.
let footer = if cfg!(target_arch = "wasm32") {
Vec::new()
} else {
vec![
(SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)),
(LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)),
]
};
let footer = vec![
(SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)),
(LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)),
];
ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer)
}
@@ -297,6 +292,29 @@ fn act(app: &mut VectorcraftApp, id: DialogId, fields: &DialogFields, action: &s
/// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again.
fn save(app: &mut VectorcraftApp, fields: &DialogFields) {
let mut request =
PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT);
let mut p = params(fields);
if let Some(o) = p.as_object_mut() {
o.remove("proof");
}
if app.host.files().browser_saves() {
match proof_file::draft_bytes(&p) {
Ok(bytes) => {
crate::file_asks::save(app, request, bytes, Owner::Free, |app, picked| {
match picked {
Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())),
Picked::Downloaded(name) => app.status(format!("Saved {name}")),
Picked::Failed(error) => return Err(error),
_ => {}
}
Ok(Value::Null)
});
}
Err(e) => app.status(e.to_string()),
}
return;
}
// The picker opens in the folder, made for it when it may be written. [`list_saved`] removes
// it again when the picker closes without a file in it.
let dir = app.session.proof_setup_dir().map(Path::to_path_buf);
@@ -307,15 +325,9 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) {
if made.is_some() {
saved().made = made;
}
let mut request =
PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT);
if let Some(dir) = dir {
request = request.directory(dir);
}
let mut p = params(fields);
if let Some(o) = p.as_object_mut() {
o.remove("proof");
}
ask(app, request, Owner::Free, move |app, picked| {
let Picked::Saved { path, .. } = picked else { return Ok(Value::Null) };
let path = path.to_string_lossy().into_owned();
@@ -343,8 +355,16 @@ fn load(app: &mut VectorcraftApp, id: DialogId) {
&& app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
};
ask_while(app, request, Owner::Free, is_live, move |app, picked| {
let Some(path) = picked.first_path() else { return Ok(Value::Null) };
let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?;
let r = match picked {
Picked::Contents(files) => {
let Some((name, bytes)) = files.into_iter().next() else { return Ok(Value::Null) };
proof_file::draft_fields(&bytes, &name).map_err(|e| e.to_string())?
}
other => {
let Some(path) = other.first_path() else { return Ok(Value::Null) };
app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?
}
};
let fields = [
("device", "target"),
("intent", "intent"),
@@ -817,6 +837,52 @@ mod tests {
assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation));
}
#[test]
fn a_browser_pick_loads_a_proof_setup_into_the_draft() {
let _view = DefaultProofView::new();
let (mut app, ctx) = app();
let files = scripted(&mut app, ScriptedFiles::held().in_browser());
app.run("ui.proofSetupDialog", json!({})).unwrap();
set(&mut app, &ctx, "preview", json!(false));
let before = proof::view();
let mut source = before.setup.clone();
source.intent = Intent::Saturation;
press(&mut app, &ctx, LOAD_BUTTON);
files.answer(Picked::Contents(vec![("browser.vcproof".into(), proof_file::encode(&source))]));
crate::file_asks::poll(&mut app);
assert_eq!(values(&app)["intent"], "saturation");
assert_eq!(proof::view(), before);
press(&mut app, &ctx, LOAD_BUTTON);
files.answer(Picked::Contents(vec![("oversized.vcproof".into(), vec![b' '; proof_file::MAX_FILE + 1])]));
crate::file_asks::poll(&mut app);
assert!(app.ui.status.contains("larger than"));
assert_eq!(values(&app)["intent"], "saturation");
assert_eq!(proof::view(), before);
}
#[test]
fn saving_a_browser_proof_setup_gives_the_file_service_the_draft_bytes() {
let _view = DefaultProofView::new();
let (mut app, ctx) = app();
let files = scripted(&mut app, ScriptedFiles::held().in_browser());
app.run("ui.proofSetupDialog", json!({})).unwrap();
for (k, v) in [("intent", json!("saturation")), ("preview", json!(false))] {
set(&mut app, &ctx, k, v);
}
let before = proof::view();
let dir = vectorcraft_testkit::TempDir::new("proof-setup-browser-save");
let path = dir.join("draft.vcproof");
press(&mut app, &ctx, SAVE);
files.answer(Picked::Saved { path: path.clone(), file_type: None });
crate::file_asks::poll(&mut app);
let bytes = files.file(&path).expect("the browser file service receives the draft bytes");
assert_eq!(proof_file::parse(&bytes).unwrap().intent, Intent::Saturation);
assert_eq!(proof::view(), before);
assert_eq!(values(&app)["intent"], "saturation");
assert!(!path.exists(), "the browser save does not write through the native path");
}
#[test]
fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() {
let _view = DefaultProofView::new();
+25 -1
View File
@@ -84,6 +84,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
fields.set("hasSlices", FieldValue::Bool(has_slices));
let summary = format!("{} × {} px · {} {}", info.width, info.height, crate::i18n::colon(tl!("Layers")), info.layers);
let placing = place.is_some();
let drawing = place.and_then(|params| crate::place::import_options_drawing(app, params));
let source = Source {
place: place.map(|p| other_place_params(p, &["layers", "hiddenLayers", "importSlices"])),
name: name.to_string(),
@@ -93,7 +94,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
};
let ctx = app.ui_ctx.clone().unwrap_or_default();
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| build(fields, placing, &summary)).held_ok();
open_held(app, dialog, move |app, result| confirm(app, &source, result)).is_some()
open_held(app, dialog, move |app, result| {
crate::place::check_import_options_drawing(app, drawing)?;
confirm(app, &source, result)
})
.is_some()
}
/// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`,
@@ -269,6 +274,25 @@ mod tests {
}
}
#[test]
fn normal_psd_place_options_wait_for_the_original_drawing() {
let mut app = host::app();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let encoded = vectorcraft_format::base64_encode(&layered());
let params = json!({"name": "poster.psd", "dataBase64": encoded, "at": [50, 50]});
assert_eq!(crate::place::run_for_user(&mut app, &params).unwrap()["dialog"], KIND);
set(&app, "convert", json!("flatten"));
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
let error = host::confirm(&mut app, KIND).expect_err("the other drawing must not receive the file");
assert!(error.contains("original drawing"), "{error}");
assert!(app.session.active().unwrap().history.undo.is_empty());
assert_eq!(host::fields(&app, KIND)["convert"], "flatten");
app.run("document.activate", json!({"index": 0})).unwrap();
host::confirm(&mut app, KIND).unwrap();
let st = app.session.active().unwrap();
assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([node]) if matches!(node.kind, NodeKind::Image(_))));
}
#[test]
fn placing_without_link_asks_and_places_the_layers_as_a_group() {
let b64 = vectorcraft_format::base64_encode(&layered());
+134 -45
View File
@@ -68,8 +68,7 @@ fn layout_glyph(l: ArtboardLayout, rtl: bool) -> (&'static str, &'static LayoutG
}
}
/// The settings the dialog edits, and for Rearrange the artboards it lays out (`indices`, sorted
/// and once each), which the dialog does not edit.
/// The settings the dialog edits.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RearrangeValues {
layout: ArtboardLayout,
@@ -78,26 +77,21 @@ pub(crate) struct RearrangeValues {
columns: f64,
spacing: f64,
move_artwork: bool,
indices: Option<Vec<usize>>,
}
impl Default for RearrangeValues {
fn default() -> Self {
RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true, indices: None }
RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true }
}
}
impl RearrangeValues {
/// `artboard.rearrange` parameters.
fn params(&self) -> Value {
let mut p = json!({
json!({
"layout": self.layout.id(), "order": self.order(), "columns": self.columns,
"spacing": self.spacing, "moveArtwork": self.move_artwork,
});
if let Some(indices) = &self.indices {
p["indices"] = json!(indices);
}
p
})
}
fn order(&self) -> &'static str {
@@ -154,16 +148,19 @@ pub(crate) fn open_selected(app: &mut VectorcraftApp, indices: &[usize]) {
/// Opens the dialog for `indices` (Rearrange), or for every artboard (Rearrange All Artboards).
fn open_with(app: &mut VectorcraftApp, indices: Option<Vec<usize>>) -> Result<Value, String> {
let mut values = RearrangeValues::default();
if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() {
values.spacing = spacing;
}
let artboards = indices.as_ref().map_or_else(|| app.session.active().map_or(0, |doc| doc.doc.artboards.len()), Vec::len);
values.indices = indices;
let st = app.session.active().ok_or("no document")?;
let artboards = indices.as_ref().map_or(st.doc.artboards.len(), Vec::len);
let selected = indices
.map(|indices| {
indices.into_iter().map(|i| st.doc.artboards.get(i).map(|a| (i, a.id)).ok_or("no such artboard")).collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let values = RearrangeValues { spacing: app.ui.rearrange_artboards_spacing.as_f64().unwrap_or(20.0), ..RearrangeValues::default() };
let document = st.uid;
let lengths = LengthUnits::new(UnitKind::Points, length_kind(app.session.general_unit()), 72.0);
let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points);
let dialogs = app.dialogs().ok_or("no window")?;
dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, artboards, lengths }));
dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, document, selected, artboards, lengths }));
Ok(Value::Null)
}
@@ -181,6 +178,9 @@ pub(crate) struct RearrangeArtboardsDialog {
id: DialogId,
open: bool,
values: RearrangeValues,
document: u64,
/// Each selected artboard's opening row index and stable ID. None lays out the entire document.
selected: Option<Vec<(usize, u32)>>,
/// The artboards the dialog lays out (the document's, or the selected ones), which bounds Columns
/// and is the count it shows.
artboards: usize,
@@ -188,8 +188,20 @@ pub(crate) struct RearrangeArtboardsDialog {
lengths: LengthUnits,
}
pub(crate) struct RearrangeAnswer {
values: RearrangeValues,
document: u64,
selected: Option<Vec<(usize, u32)>>,
}
impl RearrangeArtboardsDialog {
fn answer(&self, values: RearrangeValues) -> RearrangeAnswer {
RearrangeAnswer { values, document: self.document, selected: self.selected.clone() }
}
}
/// The rows of the dialog for `artboards` artboards, Spacing shown in `unit`.
fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: LengthUnits) {
fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, selected: bool, lengths: LengthUnits) {
Field::new(tl!("Layout:")).id_salt("layout").show(ui, |ui, _| {
let entries: Vec<Entry<ArtboardLayout>> = ArtboardLayout::ALL
.into_iter()
@@ -231,12 +243,12 @@ fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: L
v.move_artwork = on;
}
});
let label = if v.indices.is_some() { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") };
let label = if selected { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") };
Text::new(crate::i18n::fmt(label, &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui);
}
impl StackDialog for RearrangeArtboardsDialog {
type Result = RearrangeValues;
type Result = RearrangeAnswer;
fn id(&self) -> DialogId {
self.id
@@ -246,30 +258,31 @@ impl StackDialog for RearrangeArtboardsDialog {
Some(CMD)
}
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<RearrangeValues>> {
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<RearrangeAnswer>> {
let (artboards, lengths) = (self.artboards, self.lengths);
let title = if self.values.indices.is_some() { tl!("Rearrange") } else { tl!("Rearrange All Artboards") };
let selected = self.selected.is_some();
let title = if selected { tl!("Rearrange") } else { tl!("Rearrange All Artboards") };
let shown = FormDialog::new(title, Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show(ui, |ui, _, v| {
body(ui, v, artboards, lengths);
body(ui, v, artboards, selected, lengths);
true
});
match (shown.accepted, shown.closed) {
(Some(value), _) => Some(DialogResult::Ok(value)),
(Some(value), _) => Some(DialogResult::Ok(self.answer(value))),
(None, Some(_)) => Some(DialogResult::Cancel),
(None, None) => None,
}
}
fn confirm(&mut self, _: &egui::Context) -> Option<RearrangeValues> {
Some(self.values.clone())
fn confirm(&mut self, _: &egui::Context) -> Option<RearrangeAnswer> {
Some(self.answer(self.values.clone()))
}
fn json_fields(&self) -> Option<Value> {
let v = &self.values;
let mut fields =
json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork});
if let Some(indices) = &v.indices {
fields["indices"] = json!(indices);
if let Some(selected) = &self.selected {
fields["indices"] = json!(selected.iter().map(|(index, _)| index).collect::<Vec<_>>());
}
Some(fields)
}
@@ -311,28 +324,33 @@ impl StackDialog for RearrangeArtboardsDialog {
/// ([`place`]).
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some(DialogResult::Ok(values)) = dialogs.with(|host| host.take::<RearrangeArtboardsDialog>()) else { return };
match &values.indices {
None => match app.run(CMD, values.params()) {
Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing),
Err(e) => app.status(e),
},
Some(listed) => match wait_for_click(app, listed, values.params()) {
Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing),
Err(e) => app.status(e),
},
let Some(DialogResult::Ok(RearrangeAnswer { values, document, selected })) = dialogs.with(|host| host.take::<RearrangeArtboardsDialog>()) else {
return;
};
let applied = if app.session.active().is_none_or(|st| st.uid != document) {
Err(tl!("Rearrange Artboards can only change the document where it was opened.").to_owned())
} else if let Some(selected) = selected {
wait_for_click(app, &selected, values.params())
} else {
app.run(CMD, values.params()).map(drop)
};
match applied {
Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing),
Err(e) => app.status(e),
}
ctx.request_repaint();
}
/// Rearrange for artboards `listed` with `params`, confirmed: it waits for its click on the canvas,
/// for the active document and the tool in use.
fn wait_for_click(app: &mut VectorcraftApp, listed: &[usize], params: Value) -> Result<(), String> {
/// Rearrange the originally selected artboards in their current row order when the canvas is clicked.
fn wait_for_click(app: &mut VectorcraftApp, selected: &[(usize, u32)], mut params: Value) -> Result<(), String> {
let st = app.session.active().ok_or_else(|| "no document".to_string())?;
let ids: Vec<u32> = listed.iter().filter_map(|i| st.doc.artboards.get(*i)).map(|a| a.id).collect();
if ids.len() != listed.len() {
return Err("no such artboard".into());
let wanted: std::collections::HashSet<_> = selected.iter().map(|&(_, id)| id).collect();
let (indices, ids): (Vec<_>, Vec<_>) =
st.doc.artboards.iter().enumerate().filter_map(|(index, a)| wanted.contains(&a.id).then_some((index, a.id))).unzip();
if ids.len() != selected.len() {
return Err(tl!("An artboard selected when the dialog opened was removed.").to_owned());
}
params["indices"] = json!(indices);
let (doc, tool) = (st.uid, app.session.tool_id().to_string());
app.ui.rearrange_placement = Some(RearrangePlacement { doc, tool, params, ids, armed: false });
app.status(PLACE_HINT);
@@ -471,6 +489,77 @@ mod tests {
app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap()
}
fn check_rearrange_stays_in_opening_document(selected: bool) {
let mut app = app(3);
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
let destination = app.session.active().unwrap().uid;
app.run("document.activate", json!({"index": 0})).unwrap();
if selected {
app.select_tool("artboard");
open_selected(&mut app, &[0, 2]);
} else {
open_from_menu(&mut app);
}
set(&app, &[("layout", json!("row")), ("order", json!("rightToLeft")), ("spacing", json!(37))]).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
assert_eq!(app.session.active().unwrap().uid, destination);
let before = origins(&app);
let undo = app.session.active().unwrap().history.undo.len();
let spacing = app.ui.rearrange_artboards_spacing.clone();
ok(&mut app);
assert_eq!(origins(&app), before, "OK leaves the other tab's artboards in place");
assert!(app.ui.rearrange_placement.is_none(), "the other tab cannot start placement");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.rearrange_artboards_spacing, spacing);
}
#[test]
fn rearrange_opening_for_all_artboards_leaves_a_new_tab_untouched() {
check_rearrange_stays_in_opening_document(false);
}
#[test]
fn rearrange_opening_for_selected_artboards_cannot_place_in_a_new_tab() {
check_rearrange_stays_in_opening_document(true);
}
#[test]
fn rearrange_opening_keeps_the_intended_artboards_after_rows_move() {
let mut app = app(3);
app.select_tool("artboard");
let st = app.session.active().unwrap();
let source = [st.doc.artboards[0].id, st.doc.artboards[2].id];
open_selected(&mut app, &[0, 2]);
set(&app, &[("layout", json!("row")), ("spacing", json!(20))]).unwrap();
app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap();
let before = origins(&app);
let undo = app.session.active().unwrap().history.undo.len();
ok(&mut app);
let placement = app.ui.rearrange_placement.as_ref().expect("the original artboards wait for placement");
assert_eq!(placement.ids, source);
assert_eq!(placement.params["indices"], json!([1, 2]));
place(&mut app, Some(Point::new(700.0, 300.0)));
assert_eq!(origins(&app), [before[0], (700.0, 300.0), (820.0, 300.0)]);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn rearrange_opening_does_not_place_a_deleted_artboards_replacement() {
let mut app = app(3);
app.select_tool("artboard");
open_selected(&mut app, &[0]);
app.run("artboard.delete", json!({"index": 0})).unwrap();
let before = origins(&app);
let undo = app.session.active().unwrap().history.undo.len();
ok(&mut app);
assert!(app.ui.rearrange_placement.is_none(), "the replacement row is not a placement target");
assert_eq!(origins(&app), before);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
/// #681: the menu item opens the dialog; each setting reaches `artboard.rearrange`, as one undo step; a
/// setting the layout makes meaningless is refused.
#[test]
@@ -537,7 +626,7 @@ mod tests {
assert_eq!(shown["indices"], json!([0, 2]));
let (title, count) = app.dialogs().unwrap().with(|host| {
let d = host.get::<RearrangeArtboardsDialog>().unwrap();
(d.values.indices.is_some(), d.artboards)
(d.selected.is_some(), d.artboards)
});
assert_eq!((title, count), (true, 2), "Rearrange for the 2 selected artboards");
set(&app, &[("layout", json!("row"))]).unwrap();
+182 -19
View File
@@ -118,7 +118,7 @@ mod prominent;
use std::borrow::Cow;
use std::cell::RefCell;
use std::sync::Arc;
use std::sync::{Arc, Weak};
use craft::behavior::edit_history::{EditHistory, Step};
use craft::behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed};
@@ -152,6 +152,7 @@ use serde_json::{Value, json};
use vectorcraft_color::harmony::{self, Harmony, move_on_wheel};
use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method};
use vectorcraft_color::{Color, keep_model};
use vectorcraft_doc::Selection as ArtworkSelection;
use vectorcraft_engine::cmd::color_value;
use vectorcraft_engine::cmd::fileio::builtin_open_filters;
use vectorcraft_engine::cmd::swatchlib;
@@ -258,8 +259,44 @@ impl Fields {
pub(crate) struct Open {
/// The dialog on the window's host.
pub id: DialogId,
document: u64,
/// The preview the pump runs and OK commits.
pub preview: LivePreview,
/// The selection snapshot identifies the interaction that ran the preview.
preview_selection: Option<Weak<ArtworkSelection>>,
}
impl Open {
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.preview_selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn problem(&self, app: &VectorcraftApp) -> Option<&'static str> {
if app.session.active().is_none_or(|state| state.uid != self.document) {
Some("Return to the document where Recolor Artwork opened.")
} else if app.session.in_interaction() && !self.owns_preview(app) {
Some("Finish the active edit before applying Recolor Artwork.")
} else {
None
}
}
fn take_preview(&mut self) -> LivePreview {
self.preview_selection = None;
std::mem::take(&mut self.preview)
}
fn cancel(&mut self, app: &mut VectorcraftApp) {
let owns_preview = self.owns_preview(app);
let preview = self.take_preview();
if owns_preview {
preview.cancel(app);
}
}
}
/// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?, preset?}`) on the selected
@@ -284,7 +321,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
// The group is looked for in the document without the preview of a Recolor Artwork this one
// replaces (which can rename the group), as that dialog's rollback below leaves it.
let unpreviewed = match &st.interaction {
Some(it) if app.color_dialogs.recolor.is_some() => &it.doc,
Some(it) if app.color_dialogs.recolor.as_ref().is_some_and(|open| open.owns_preview(app)) => &it.doc,
_ => &st.doc,
};
if let Some(g) = group
@@ -301,6 +338,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
// A Recolor Artwork still open is replaced: its preview goes before the group's colours are read.
cancel_open(app);
let st = app.session.active().ok_or("no document open")?;
let document = st.uid;
let group_colors: Option<Vec<Color>> = match group {
Some(g) => {
let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?;
@@ -339,7 +377,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let dialog = RecolorDialog::new(app, d);
let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() };
let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?;
app.color_dialogs.recolor = Some(Open { id, preview: LivePreview::default() });
app.color_dialogs.recolor = Some(Open { id, document, preview: LivePreview::default(), preview_selection: None });
Ok(Value::Null)
}
@@ -349,8 +387,8 @@ fn cancelled(app: &mut VectorcraftApp) {
if app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.is_open::<RecolorDialog>())) {
return;
}
if let Some(open) = app.color_dialogs.recolor.take() {
open.preview.cancel(app);
if let Some(mut open) = app.color_dialogs.recolor.take() {
open.cancel(app);
}
}
@@ -363,9 +401,9 @@ const NEW_GROUP: &str = "Color Group";
/// Ends an open Recolor Artwork as Cancel ends it: its preview is rolled back and it closes.
pub(super) fn cancel_open(app: &mut VectorcraftApp) {
let Some(old) = app.color_dialogs.recolor.take() else { return };
let Some(mut old) = app.color_dialogs.recolor.take() else { return };
let id = old.id;
old.preview.cancel(app);
old.cancel(app);
if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) {
dialogs.with(|host| {
host.cancel_by_id(&ctx, id);
@@ -476,8 +514,9 @@ const SAVE_GROUP: &str = "__saveGroup";
/// Cancel the preview, so commands read the art's own colors; the pump runs it again afterwards.
fn cancel_preview(app: &mut VectorcraftApp) {
if let Some(preview) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) {
preview.cancel(app);
if let Some(mut open) = app.color_dialogs.recolor.take() {
open.cancel(app);
app.color_dialogs.recolor = Some(open);
}
}
@@ -1630,12 +1669,20 @@ pub(super) fn limit_to(dialogs: &craft::ui::shell::WindowDialogs, parent: Dialog
/// Runs the open dialog's live preview with `(on, command, params)`.
fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) {
let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return };
// `run` reports a preview that fails on the status line itself.
let _ = live.run(app, on, TITLE, cmd, &params);
if let Some(open) = app.color_dialogs.recolor.as_mut() {
open.preview = live;
let Some(mut open) = app.color_dialogs.recolor.take() else { return };
if open.problem(app).is_none() {
if !open.owns_preview(app) {
open.take_preview();
}
// `run` reports a preview that fails on the status line itself.
let ran = open.preview.run(app, on, TITLE, cmd, &params).is_some();
if !on {
open.preview_selection = None;
} else if ran {
open.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
}
}
app.color_dialogs.recolor = Some(open);
}
/// Feeds the open Recolor Artwork what it shows of the app, runs what its passes asked for, asks for
@@ -1643,8 +1690,27 @@ fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str,
/// previews its recolour: once a frame, after the window's dialog host ran.
// PLAN: hub-w2 adds the line `recolor::pump(app, ctx)` to `dialogs::host::pump` (co.A6 names this pump).
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(id) = app.color_dialogs.recolor.as_ref().map(|open| open.id) else { return };
let Some(open) = app.color_dialogs.recolor.as_ref() else { return };
let id = open.id;
let Some(dialogs) = app.dialogs() else { return };
if let Some(reason) = open.problem(app) {
let requests = dialogs.with(|host| {
let d = host.get_mut_by_id::<RecolorDialog>(id)?;
let group_action = d.fields.fields.remove(GROUP_ACTION).is_some();
let save_group = d.fields.fields.remove(SAVE_GROUP).is_some();
let library = std::mem::take(&mut d.filed.library).then(|| Arc::clone(&d.opening));
Some((library, group_action || save_group))
});
if let Some((library, action_refused)) = requests {
if let Some(opening) = library {
pick_library(app, opening);
}
if action_refused {
app.status(reason);
}
}
return;
}
// The colour the picker answered for a row reaches the row here, where the app can snap it to Limit to Library.
dialogs.with(|host| {
if let Some(d) = host.get_mut_by_id::<RecolorDialog>(id)
@@ -1681,7 +1747,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Artwork dialog → {changed, canUndo, canRedo}.
pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result<Value, String> {
const NOT_OPEN: &str = "Recolor Artwork is not open";
let id = app.color_dialogs.recolor.as_ref().map(|open| open.id).ok_or(NOT_OPEN)?;
let open = app.color_dialogs.recolor.as_ref().ok_or(NOT_OPEN)?;
if let Some(reason) = open.problem(app) {
return Err(crate::i18n::msg(reason));
}
let id = open.id;
let dialogs = app.dialogs().ok_or(NOT_OPEN)?;
let mut work = dialogs.with(|host| host.get_mut_by_id::<RecolorDialog>(id).map(RecolorDialog::take_work)).ok_or(NOT_OPEN)?;
// Fields set since the last frame take effect first, as the next frame would give them.
@@ -1706,7 +1776,8 @@ pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result<Value, String
/// Whether Undo Changes (`back`) or Redo Changes can run: Recolor Artwork is open with a step to go to.
pub(crate) fn can_step(app: &VectorcraftApp, back: bool) -> bool {
app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::<RecolorDialog>().is_some_and(|d| d.steps.can(&d.fields, back))))
app.color_dialogs.recolor.as_ref().is_some_and(|open| open.problem(app).is_none())
&& app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::<RecolorDialog>().is_some_and(|d| d.steps.can(&d.fields, back))))
}
/// Row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library.
@@ -1725,6 +1796,10 @@ pub(super) fn with_new_color(app: &VectorcraftApp, d: &mut RecolorDialog, i: usi
/// save colours opened alone as a new colour group). The dialog closes once this answers `Ok`; an
/// `Err` keeps it open with the reason.
fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> {
let open = app.color_dialogs.recolor.as_ref().ok_or("Recolor Artwork is not open")?;
if let Some(reason) = open.problem(app) {
return Err(crate::i18n::msg(reason));
}
let mut d = fields.clone();
select_group(app, &mut d)?;
sync(app, &mut d);
@@ -1743,7 +1818,7 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> {
}
r?;
}
let preview = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)).unwrap_or_default();
let preview = app.color_dialogs.recolor.as_mut().map(Open::take_preview).unwrap_or_default();
let committed = if d.bool("__newGroup") {
let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r) && to_color(r).is_some()));
preview.commit(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}))
@@ -2126,7 +2201,7 @@ fn assign_tab(
let total: usize = rows.iter().map(|r| r["from"].as_array().map_or(0, Vec::len)).sum();
// Reduction and the preserve rules apply to art (a colour group alone has a row per colour).
if art {
Row::new().show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
let counts: Vec<Entry<usize>> = std::iter::once(Entry::new(0, Label::from(tl!("Auto"))))
.chain((1..=total).map(|n| Entry::new(n, Label::from(n.to_string()))))
.collect();
@@ -3118,6 +3193,94 @@ mod tests {
rc
}
fn two_red_drawings() -> (Recolor, u64, u64) {
let mut app = app(120);
let opening = square(&mut app, 10.0, "#ff0000");
app.run("select.set", json!({"ids": [opening]})).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let other = square(&mut app, 60.0, "#ff0000");
app.run("select.set", json!({"ids": [other]})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
let mut rc = opened(app, json!({}));
rc.set("method", json!(Method::Exact.id())).unwrap();
rc.frame();
rc.set("rows", json!([{"from": ["rgb 255 0 0"], "to": "rgb 0 255 0"}])).unwrap();
(rc, opening, other)
}
#[test]
fn recolor_preview_does_not_change_the_other_drawings_art() {
let (mut rc, opening, other) = two_red_drawings();
rc.app().run("document.activate", json!({"index": 1})).unwrap();
rc.frame();
assert_eq!(fill_hex(&rc, other), "#ff0000", "preview leaves the other drawing's fill alone");
assert!(!rc.app().session.in_interaction());
rc.app().run("document.activate", json!({"index": 0})).unwrap();
rc.frame();
assert_eq!(fill_hex(&rc, opening), "#00ff00");
rc.confirm().unwrap();
}
#[test]
fn recolor_ok_keeps_the_draft_on_the_opening_drawing() {
let (mut rc, opening, other) = two_red_drawings();
rc.set("preview", json!(false)).unwrap();
rc.app().run("document.activate", json!({"index": 1})).unwrap();
let undo = undo_len(&rc.app());
let confirmed = rc.confirm();
assert_eq!(fill_hex(&rc, other), "#ff0000", "OK leaves the other drawing's fill alone");
assert_eq!(undo_len(&rc.app()), undo);
assert!(confirmed.is_err() && rc.is_open());
rc.app().run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(fill_hex(&rc, opening), "#ff0000");
rc.confirm().unwrap();
assert_eq!(fill_hex(&rc, opening), "#00ff00");
}
#[test]
fn recolor_cancel_leaves_the_other_drawings_pending_edit() {
let (mut rc, opening, other) = two_red_drawings();
rc.frame();
assert_eq!(fill_hex(&rc, opening), "#00ff00");
{
let mut app = rc.app();
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other edit").unwrap();
app.session.preview("paint.setFill", &json!({"ids": [other], "color": "#0000ff"})).unwrap();
}
rc.cancel();
assert!(rc.app().session.in_interaction(), "Cancel preserves the other drawing's pending edit");
assert_eq!(fill_hex(&rc, other), "#0000ff");
rc.app().session.commit_interaction().unwrap();
rc.app().run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(fill_hex(&rc, opening), "#ff0000");
}
#[test]
fn recolor_delete_leaves_the_other_drawings_same_named_group() {
let mut app = app(120);
app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#00ff00"]})).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.run("swatch.newGroup", json!({"name": "Shared", "colors": ["#ff0000"]})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
let mut rc = opened(app, json!({"group": "Shared"}));
rc.frame();
rc.app().run("document.activate", json!({"index": 1})).unwrap();
let other = group_hex(&rc.app(), "Shared");
rc.act("delete").unwrap();
assert_eq!(group_hex(&rc.app(), "Shared"), other, "Delete leaves the other drawing's group alone");
rc.app().run("document.activate", json!({"index": 0})).unwrap();
rc.frame();
assert!(group_hex(&rc.app(), "Shared").is_some(), "a refused action does not run after returning");
rc.act("delete").unwrap();
assert!(group_hex(&rc.app(), "Shared").is_none());
}
#[test]
fn recolor_dialog_keeps_the_default_model_without_an_extra_dropdown() {
let rc = opened(app(100), json!({"colors": ["#ff8000"]}));
@@ -15,6 +15,50 @@ use serde_json::{Value, json};
use super::{Fields, GROUP_ACTION, KIND, RecolorDialog};
use crate::VectorcraftApp;
#[test]
fn preserve_grays_can_be_clicked_in_a_narrow_localized_dialog() {
use egui::accesskit::Role;
use egui::{RawInput, pos2, vec2};
for lang in ["de", "el"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
app.session.prefs.interface_language = lang.into();
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
app.run("select.all", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(540.0, 500.0));
let mut time = 0.0;
let mut draw = |app: &mut VectorcraftApp, events| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
};
draw(&mut app, vec![]);
app.run("ui.recolorDialog", json!({})).unwrap();
for _ in 0..5 {
draw(&mut app, vec![]);
}
let out = draw(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let label = crate::i18n::t("Grays");
let bounds = nodes
.iter()
.find(|(_, node)| node.role() == Role::CheckBox && node.label() == Some(label))
.and_then(|(_, node)| node.bounds())
.unwrap_or_else(|| panic!("{lang} has no Preserve Grays checkbox"));
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
draw(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
draw(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
draw(&mut app, vec![]);
let preserves_grays = app.dialogs().unwrap().with(|host| host.get::<RecolorDialog>().map(|d| d.fields.bool("preserveGrays")));
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(preserves_grays, Some(true), "the pointer click toggles Preserve Grays in {lang}");
}
}
/// Recolor Artwork over an app, in a window-sized fixture.
pub(crate) struct Recolor {
fixture: Fixture,
@@ -24,6 +24,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if st.selection.is_empty() {
return Err("select artwork to recolor".into());
}
let document = st.uid;
if p.get("group").is_some_and(|g| !g.is_null()) {
return Err("`group` does not apply to a preset".into());
}
@@ -39,6 +40,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false);
// Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays.
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
if !app.session.active().is_some_and(|active| active.uid == document) {
return Err(tl!("Open the original drawing to continue with Recolor with Preset.").to_owned());
}
let mut p = serde_json::Map::new();
if let Some(n) = colors {
p.insert("colors".into(), json!(n));
@@ -59,3 +63,42 @@ fn count(v: Option<&Value>) -> Result<Option<u64>, String> {
Some(n) => n.as_u64().filter(|n| *n >= 1).map(Some).ok_or_else(|| "`colors` must be a count of at least 1".into()),
}
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::{HeldOk, dialog_id};
use vectorcraft_engine::Session;
use super::*;
#[test]
fn recolor_preset_does_not_open_artwork_in_another_drawing() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
for color in ["#ff0000", "#0000ff"] {
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"ids": [shape], "color": color})).unwrap();
app.run("select.set", json!({"ids": [shape]})).unwrap();
}
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("ui.recolorDialog", json!({"preset": true, "colors": 1})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
let id = dialog_id(KIND);
host.with(|h| h.set_json_field(&ctx, id, "limitTo", json!("document"))).unwrap();
assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the preset waits for the app");
app.run("document.activate", json!({"index": 1})).unwrap();
let target_undo = app.session.active().unwrap().history.undo.len();
super::super::host::pump(&mut app, &ctx);
assert!(app.color_dialogs.recolor.is_none(), "the held answer must not open Recolor Artwork on the other drawing");
assert_eq!(app.session.active().unwrap().history.undo.len(), target_undo);
assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(super::super::tests::confirm(&mut app), "the original preset draft can open Recolor Artwork");
assert!(app.color_dialogs.recolor.is_some());
let limit = super::super::recolor::limit_to(&host, dialog_id(super::super::recolor::KIND));
assert_eq!(limit.as_deref(), Some("document"));
}
}
+71 -7
View File
@@ -6,7 +6,7 @@
//! dialog opened on are held by its OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use serde_json::{Value, json};
use super::host::open_held;
@@ -15,12 +15,13 @@ use crate::VectorcraftApp;
/// The command Rename answers for; the key of its dialog.
pub(crate) const CMD: &str = "artboard.rename";
const TARGET: &str = "__target";
/// `artboard.rename` for the selected artboards: opens the dialog on the one artboard's name, or on an empty name
/// for several.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?;
let document = st.uid;
let selected: Vec<_> =
crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect();
let name = match selected.as_slice() {
@@ -30,21 +31,34 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let artboards: Vec<_> = selected.iter().map(|board| board.id).collect();
let mut fields = DialogFields::new();
fields.set("name", name);
// The held answer carries the target of the draft being confirmed, including after reopening.
fields.set(TARGET, FieldValue::Json(json!({"document": st.uid, "reverts": st.reverts, "artboards": artboards})));
let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| {
let rows = vec![Param::new("name", tl!("Name:"), ParamKind::text(""))];
ParamDialog::command(CMD, tl!("Rename"), rows).values(Bind::bound(fields))
});
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
let name = result.fields.text("name").unwrap_or_default();
// An empty name keeps the names as they are, as the Artboards panel's name field does.
if name.trim().is_empty() {
return Ok(());
}
let st =
app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?;
let indices = artboards
let Some(FieldValue::Json(target)) = result.fields.get(TARGET) else {
return Err(tl!("The artboards being renamed could not be found.").to_owned());
};
let st = app
.session
.active()
.filter(|st| Some(st.uid) == target["document"].as_u64())
.ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?;
if Some(st.reverts) != target["reverts"].as_u64() {
return Err(tl!("The document was reverted. Reopen the dialog to rename artboards.").to_owned());
}
let indices = target["artboards"]
.as_array()
.ok_or_else(|| tl!("The artboards being renamed could not be found.").to_owned())?
.iter()
.map(|id| st.doc.artboards.iter().position(|board| board.id == *id))
.map(|id| st.doc.artboards.iter().position(|board| Some(u64::from(board.id)) == id.as_u64()))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?;
if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) {
@@ -61,6 +75,14 @@ mod tests {
use super::*;
use vectorcraft_engine::Session;
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
@@ -143,6 +165,48 @@ mod tests {
assert!(!app.any_dialog_open());
}
#[test]
fn rename_cannot_use_a_draft_opened_before_file_revert() {
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-rename-artboards-revert-{}.vectorcraft", std::process::id())));
let services = crate::Services {
read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))),
write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))),
..Default::default()
};
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
app.select_tool("artboard");
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
let active = app.session.active().unwrap();
let (document, reverts, artboard) = (active.uid, active.reverts, active.doc.artboards[0].id);
app.run(CMD, json!({"indices": [0], "name": "Temporary"})).unwrap();
open(&mut app).unwrap();
let (id, fields) = open_rename(&app);
assert_eq!(fields["name"], "Temporary");
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
host.set_json_field(&ctx, id, "name", json!("Stale")).unwrap();
assert!(!host.confirm_by_id(&ctx, id));
});
app.run("file.revert", json!({"confirmed": true})).unwrap();
let active = app.session.active().unwrap();
assert_eq!((active.uid, active.reverts, active.doc.artboards[0].id), (document, reverts + 1, artboard));
let undo = active.history.undo.len();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"], "an older draft cannot rename the reloaded board");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
app.session.set_tool_option("selected", &json!([0, 2]));
open(&mut app).unwrap();
rename(&mut app, "Page");
assert_eq!(names(&app), ["Page-1", "Artboard 2", "Page-2"]);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() {
let mut app = app();
+65 -11
View File
@@ -37,10 +37,13 @@ use crate::{VectorcraftApp, io};
pub(super) mod color_table;
pub const KIND: &str = "saveForWeb";
const WRONG_DOCUMENT: &str = "Save for Web belongs to the document that opened the dialog.";
/// What the open dialog's pump keeps between frames: data keyed by its inputs, never UI state.
#[derive(Default)]
pub(crate) struct WebExport {
document: Option<u64>,
opening: Arc<()>,
/// The rendering of the art before optimisation, by [`render_key`].
render: Option<(String, Result<Arc<WebRender>, String>)>,
/// The Original pane's picture, `None` while the dialog has not been given the current rendering's.
@@ -183,11 +186,20 @@ fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: O
/// Open on the document's active artboard, keeping the other remembered settings.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
app.session.active().ok_or("no document")?;
let document = app.session.active().ok_or("no document")?.uid;
let host = app.dialogs().ok_or("no window")?;
let ctx = app.ui_ctx.clone().ok_or("no window")?;
// Settle a completed opening while its settings and source are still available.
if let Some(DialogResult::Ok(result)) = host.with(|dialog| dialog.take::<HostedSaveForWeb>()) {
finish(app, result);
}
let s = remembered(app);
app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() };
app.web_export = WebExport {
document: Some(document),
table: serde_json::to_value(&s.color_table).unwrap_or_default(),
kept: kept_of(&s),
..WebExport::default()
};
let (name, artboards, slices) = {
let st = app.session.active().ok_or("no document")?;
let slices: Vec<WebSlice> = st
@@ -449,6 +461,10 @@ fn on_dialog<R>(host: &craft::ui::shell::WindowDialogs, f: impl FnOnce(&mut Host
host.with(|h| h.get_mut::<HostedSaveForWeb>().map(f))
}
fn on_original_document(app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|active| app.web_export.document == Some(active.uid))
}
/// Answers the open dialog once per frame: its result when it closed, else its requests.
/// Colour requests (the matte, a palette cell) are routed by the host-wide colour picker routing;
/// a palette cell's pick is applied to the table by [`take_palette_pick`].
@@ -456,13 +472,32 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(host) = app.dialogs() else { return };
match host.with(|h| h.take::<HostedSaveForWeb>()) {
Some(DialogResult::Ok(result)) => return finish(app, result),
Some(_) => {
Some(_) if on_dialog(&host, |_| ()).is_none() => {
app.web_export = WebExport::default();
return;
}
None => {}
_ => {}
}
let Some(asked) = on_dialog(&host, Asked::take) else { return };
if !on_original_document(app) {
let restore = asked.tables.iter().any(|event| matches!(event.edit, ColorTableEdit::Restore));
if restore {
color_table::restore(&mut app.web_export.table);
let marks = color_table::marks(&app.web_export.table);
on_dialog(&host, |dialog| dialog.set_marks(marks));
}
let requested = asked.path.is_some()
|| asked.browser
|| asked.optimize_open
|| asked.optimize.is_some()
|| asked.tables.iter().any(|event| !matches!(event.edit, ColorTableEdit::Restore));
update_presets(app, &host, asked.presets, restore);
if requested {
on_dialog(&host, HostedSaveForWeb::cancel_requests);
app.status(tl!(WRONG_DOCUMENT).to_owned());
}
return;
}
// The framework keeps the result line while the settings are the ones it found; the art is the app's.
let art = art_key(app);
if app.web_export.optimized.is_some() && optimized_result(&app.web_export.optimized, &art).is_none() {
@@ -474,12 +509,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
let marks = color_table::marks(&app.web_export.table);
on_dialog(&host, |d| d.set_marks(marks));
let refresh_presets = !asked.tables.is_empty() || !asked.presets.is_empty();
store_presets(app, asked.presets);
if refresh_presets {
let presets = dialog_presets(app);
on_dialog(&host, |d| d.set_presets(presets));
}
update_presets(app, &host, asked.presets, !asked.tables.is_empty());
if asked.optimize_open {
let bytes = optimize_start(app, &asked.options);
on_dialog(&host, |d| d.answer_optimize_start(bytes));
@@ -565,6 +595,10 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key:
let Some(options) = host.with(|h| h.get_mut_by_id::<HostedSaveForWeb>(parent).map(|d| d.current().clone())) else {
return false;
};
if !on_original_document(app) {
app.status(tl!(WRONG_DOCUMENT).to_owned());
return true;
}
let rgb = |c: Srgba| {
let [r, g, b, _] = c.to_rgba().0;
[r, g, b]
@@ -578,7 +612,8 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key:
}
/// Runs what the preset list asked for and shows a failure in the status line.
fn store_presets(app: &mut VectorcraftApp, events: Vec<WebPresetEvent>) {
fn update_presets(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, events: Vec<WebPresetEvent>, table_changed: bool) {
let refresh = table_changed || !events.is_empty();
for event in events {
let r = match event {
WebPresetEvent::Saved(p) => {
@@ -595,6 +630,10 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec<WebPresetEvent>) {
app.status(e);
}
}
if refresh {
let presets = dialog_presets(app);
on_dialog(host, |d| d.set_presets(presets));
}
}
/// Saves the preset `from` under `to`, then deletes `from`.
@@ -692,7 +731,18 @@ fn ask_path(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, id
pick = pick.filter(f.name.clone(), &extensions);
}
// A cancelled panel has no path.
let opening = app.web_export.opening.clone();
file_asks::ask(app, pick, Owner::Free, move |app, picked| {
if !Arc::ptr_eq(&opening, &app.web_export.opening) {
return Ok(Value::Null);
}
if !on_original_document(app) {
if let Some(host) = app.dialogs() {
on_dialog(&host, HostedSaveForWeb::cancel_requests);
}
app.status(tl!(WRONG_DOCUMENT).to_owned());
return Ok(Value::Null);
}
match picked.first_path() {
Some(path) => answer_path(app, id, &key, path),
None => {
@@ -715,9 +765,13 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) {
/// The dialog closed with Save… or Done: the settings are remembered, and with a path the files are
/// written. Failures show in the status line; the dialog has closed.
fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) {
let wrong_document = result.path.is_some() && !on_original_document(app);
let table = std::mem::take(&mut app.web_export.table);
let kept = std::mem::take(&mut app.web_export.kept);
app.web_export = WebExport::default();
if wrong_document {
return app.status(tl!(WRONG_DOCUMENT).to_owned());
}
let params = settings_of(&result.options, &table, &kept, None);
if let Err(e) = app.run("webExport.settings", params.clone()) {
return app.status(e);
@@ -312,6 +312,49 @@ fn save_remembers_and_writes_and_done_only_remembers() {
assert!(!dir.join("Untitled-1.png").exists());
}
#[test]
fn save_for_web_download_waits_for_the_original_drawing() {
let dir = vectorcraft_testkit::temp_dir("sfw-original-download");
let (mut app, downloads) = app(&dir, true);
app.run("file.saveForWeb", json!({})).unwrap();
set(&mut app, "format", json!("png24"));
app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap();
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
confirm(&mut app);
assert!(downloads.borrow().is_empty(), "the other drawing is never downloaded");
assert!(is_open(&app));
assert_eq!(fields(&app)["format"], "png24");
app.run("document.activate", json!({"index": 0})).unwrap();
save(&mut app);
assert_eq!(downloads.borrow().len(), 1);
}
#[test]
fn save_for_web_does_not_write_another_drawing_when_the_picker_returns() {
let dir = vectorcraft_testkit::temp_dir("sfw-original-picker");
let (mut app, _) = app(&dir, false);
app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("file.saveForWeb", json!({})).unwrap();
set(&mut app, "format", json!("png24"));
let ctx = app.ui_ctx.clone().unwrap();
let dialog = id(&app);
host(&app).with(|h| h.confirm_by_id(&ctx, dialog));
settle(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
answer_saves(&mut app);
settle(&mut app);
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
assert!(is_open(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
save(&mut app);
assert!(dir.join("Untitled-1.png").exists());
}
/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes
/// and stays remembered after Done.
#[test]
+52 -1
View File
@@ -36,6 +36,7 @@ fn document_name(app: &VectorcraftApp) -> Option<String> {
/// Open the dialog for `library`: `extra` rows sit under the Name row. `names` are the items selected in the
/// panel.
pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec<String>, extra: Vec<Param>) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let name = document_name(app).ok_or("no document open")?;
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let Library { key, title, cmd, only, ext, has_user_dir } = library;
@@ -64,7 +65,15 @@ pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec<String
let dialog =
HostedParamDialog::new(&ctx, key, fields, move |fields| ParamDialog::new(key, title.clone(), params.clone()).values(Bind::bound(fields)));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| save(app, cmd, ext, result);
let owner = egui::Id::unique((key, "opening-drawing"));
ctx.data_mut(|data| data.insert_temp(owner, document));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
let document = ctx.data(|data| data.get_temp::<u64>(owner));
if app.session.active().is_none_or(|st| Some(st.uid) != document) {
return Err(tl!("Return to the original drawing to save its library").into());
}
save(app, cmd, ext, result)
};
super::host::open_held(app, dialog, ok).ok_or("no window")?;
Ok(Value::Null)
}
@@ -105,3 +114,45 @@ fn save(app: &mut VectorcraftApp, cmd: &str, ext: fn(&DialogFields) -> String, r
Ok(_) => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::super::{save_symbol_library, tests_export};
use serde_json::json;
#[test]
fn save_library_waits_for_the_drawing_that_opened_it() {
let (mut app, written) = tests_export::app(1);
app.run("symbol.new", json!({"name": "Source Mark"})).unwrap();
save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap();
tests_export::set(&mut app, "saveTo", json!("file"));
tests_export::set(&mut app, "name", json!("Marks"));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
app.run("symbol.new", json!({"name": "Other Mark"})).unwrap();
let error = tests_export::try_confirm(&mut app).expect_err("Save Library must refuse the other drawing");
assert!(error.contains("original drawing"), "{error}");
assert!(written.borrow().is_empty());
assert_eq!(tests_export::fields(&app)["name"], "Marks");
app.run("document.activate", json!({"index": 0})).unwrap();
tests_export::try_confirm(&mut app).unwrap();
assert_eq!(written.borrow().len(), 1);
}
#[test]
fn reopening_save_library_uses_the_new_drawings_draft() {
let (mut app, written) = tests_export::app(1);
app.run("symbol.new", json!({"name": "Source Mark"})).unwrap();
save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
app.run("symbol.new", json!({"name": "Other Mark"})).unwrap();
save_symbol_library::open(&mut app, vec!["Other Mark".into()]).unwrap();
tests_export::set(&mut app, "saveTo", json!("file"));
tests_export::set(&mut app, "name", json!("Other Marks"));
tests_export::try_confirm(&mut app).unwrap();
let output = written.borrow();
assert_eq!(output.len(), 1);
assert!(output[0].0.contains("Other Marks"));
}
}
+101 -10
View File
@@ -138,6 +138,7 @@ impl ItemSource<usize> for Shown<'_> {}
pub(crate) struct SavedNamesDialog {
id: DialogId,
document: u64,
reverts: u64,
names: SavedNames,
draft: NamesDraft,
/// The picked row, by its index in the draft; one at most.
@@ -148,10 +149,10 @@ pub(crate) struct SavedNamesDialog {
impl SavedNamesDialog {
/// The dialog over `list`, with the first name picked.
fn new(document: u64, names: SavedNames, list: Vec<String>) -> Self {
fn new(document: u64, reverts: u64, names: SavedNames, list: Vec<String>) -> Self {
let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) };
let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect();
SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() }
SavedNamesDialog { id: id_of(names.kind), document, reverts, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() }
}
/// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for
@@ -327,9 +328,10 @@ impl StackDialog for SavedNamesDialog {
/// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them).
pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec<String>) -> Result<(), String> {
list.truncate(names.max);
let document = app.session.active().ok_or("no document open")?.uid;
let active = app.session.active().ok_or("no document open")?;
let (document, reverts) = (active.uid, active.reverts);
let dialogs = app.dialogs().ok_or("no window")?;
dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list)));
dialogs.with(|host| host.open(SavedNamesDialog::new(document, reverts, names, list)));
Ok(())
}
@@ -343,15 +345,15 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
.filter_map(|open| {
let dialog = host.get_mut_by_id::<SavedNamesDialog>(open.id)?;
let edits = dialog.held.take()?;
Some((open.id, dialog.document, dialog.names.command, edits))
Some((open.id, dialog.document, dialog.reverts, dialog.names.command, edits))
})
.collect()
});
for (id, document, command, edits) in filed {
let outcome = if app.session.active().is_some_and(|active| active.uid == document) {
app.run(command, json!({ "edits": edits }))
} else {
Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned())
for (id, document, reverts, command, edits) in filed {
let outcome = match app.session.active().filter(|active| active.uid == document) {
Some(active) if active.reverts != reverts => Err(tl!("The document was reverted. Reopen the dialog to edit saved names.").to_owned()),
Some(_) => app.run(command, json!({ "edits": edits })),
None => Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()),
};
if let Err(reason) = &outcome {
app.status(reason.clone());
@@ -368,6 +370,95 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
mod tests {
use super::*;
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn saved_selection_draft_does_not_edit_a_reverted_drawing() {
exercise_reverted_draft(false);
}
#[test]
fn saved_views_draft_does_not_edit_a_reverted_drawing() {
exercise_reverted_draft(true);
}
fn exercise_reverted_draft(is_view: bool) {
let path = SavedFile(std::env::temp_dir().join(format!("vc-saved-names-revert-{}-{is_view}.vectorcraft", std::process::id())));
let services = crate::Services {
read: Some(Box::new(|path: &str| std::fs::read(path).map_err(|e| e.to_string()))),
write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))),
..Default::default()
};
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services));
let add_shape = |app: &mut VectorcraftApp, x| {
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap();
};
let names = |app: &mut VectorcraftApp| {
if is_view {
let views = &app.session.active().unwrap().doc.views;
json!(views.iter().map(|view| &view.name).collect::<Vec<_>>())
} else {
app.run("select.savedList", json!({})).unwrap()
}
};
let open = |app: &mut VectorcraftApp| {
if is_view {
crate::dialogs::edit_views::open(app).unwrap();
crate::dialogs::edit_views::KIND
} else {
crate::dialogs::edit_selection::open(app).unwrap();
crate::dialogs::edit_selection::KIND
}
};
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
add_shape(&mut app, 10);
for name in ["Shared", "Spare"] {
app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap();
}
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
add_shape(&mut app, 40);
let old = app.session.active().unwrap();
let (document, reverts) = (old.uid, old.reverts);
let kind = open(&mut app);
let id = id_of(kind);
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
host.set_json_field(&ctx, id, "name0", json!("Stale")).unwrap();
host.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap();
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("file.revert", json!({"confirmed": true})).unwrap();
let active = app.session.active().unwrap();
assert_eq!((active.uid, active.reverts), (document, reverts + 1), "Revert preserves the tab's UID");
assert_eq!(names(&mut app), json!(["Shared", "Spare"]));
let undo = app.session.active().unwrap().history.undo.len();
pump(&mut app, &ctx);
assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "{kind} cannot apply its old draft to the reloaded drawing");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
assert!(dialogs.with(|host| host.cancel_by_id(&ctx, id)));
assert_eq!(open(&mut app), kind);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap();
host.confirm_by_id(&ctx, id);
});
pump(&mut app, &ctx);
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Accepted)));
assert_eq!(names(&mut app), json!(["Revised", "Spare"]));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn saved_names_edits_stay_with_their_document() {
for is_view in [false, true] {
+43 -18
View File
@@ -14,7 +14,7 @@ use std::sync::LazyLock;
use craft::behavior::{ColumnWidth, IconId};
use craft::egui::{Response, Ui};
use craft::host::{PickRequest, Picked};
use craft::host::PickRequest;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::overlay::Trigger;
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
@@ -178,26 +178,16 @@ pub(crate) fn save_preset_row(ui: &mut Ui, fields: &mut Map<String, Value>) -> O
}
/// Import Preset…: the presets of a picked file are added to the saved ones; `then` gets the names
/// added, or the error (`cancelled` when no file was picked). On the web the picked file arrives
/// with its bytes and imports through `io::open_bytes`, which reports no names.
/// added, or the error (`cancelled` when no file was picked). Browser picks use the file's contents.
pub(crate) fn import_presets(app: &mut VectorcraftApp, then: impl FnOnce(&mut VectorcraftApp, Result<Vec<String>, String>) + 'static) {
let request = PickRequest::open("export-presets").filter("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS);
// `then` reports its own result, so the continuation never fails (a failure would reach the status line twice).
let _ = file_asks::ask(app, request, Owner::Free, move |app, picked| {
let result: Result<Vec<String>, String> = match picked {
Picked::Contents(files) => match files.first() {
Some((name, bytes)) => io::open_bytes(app, name, bytes, None).map(|_| Vec::new()),
None => Err("cancelled".into()),
},
other => match other.first_path() {
Some(path) => {
let path = path.to_string_lossy().into_owned();
io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, json!({ "path": path }))
.map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect())
}
None => Err("cancelled".into()),
},
};
let result = file_asks::open_params(&picked).ok_or_else(|| "cancelled".to_owned()).and_then(|mut params| {
params.remove("name");
io::import_presets(app, "document.exportPresets.import", io::EXPORT_PRESETS, Value::Object(params))
.map(|r| r["imported"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect())
});
then(app, result);
Ok(Value::Null)
});
@@ -488,7 +478,6 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map<String, Value>, mut menu: Optio
}
shown.output
}
/// The format Format Settings opens on for format rows `rows`: the first row's format when it has
/// settings of its own, else PNG. Row spellings (`jpeg`, `tif`) give the canonical id.
pub(crate) fn settings_format(rows: &[Value]) -> &'static str {
@@ -561,3 +550,39 @@ pub(crate) fn settings(ui: &mut Ui, fields: &mut Map<String, Value>, presets: &[
}
shown.output
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_browser_preset_picker_routes_by_content_without_opening_drawings() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.services.download = Some(Box::new(|_, _| Ok(())));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("document.exportPresets.save", json!({"name": "Fleet", "settings": {"formats": [{"format": "png"}]}})).unwrap();
let export = app.run("document.exportPresets.export", json!({"names": ["Fleet"]})).unwrap();
let bytes = export["data"].as_str().unwrap().as_bytes();
app.run("document.exportPresets.delete", json!({"name": "Fleet"})).unwrap();
let document = app.session.active().unwrap().uid;
let picker = crate::tests::picks::scripted(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let picked = |app: &mut VectorcraftApp, name: &str, bytes: &[u8]| {
let answer = Rc::new(Cell::new(None));
let report = Rc::clone(&answer);
import_presets(app, move |_, result| report.set(Some(result)));
picker.answer_contents(&[(name, bytes)]);
crate::tests::picks::poll(app, &ctx);
answer.take().unwrap()
};
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="30" height="20"><rect width="10" height="10"/></svg>"#;
let error = picked(&mut app, "drawing.svg", svg);
assert_eq!(app.session.documents().len(), 1, "Import Preset must not open a drawing");
assert!(error.unwrap_err().contains("not an export presets file"));
assert_eq!(picked(&mut app, "different-extension.svg", bytes), Ok(vec!["Fleet".to_string()]));
assert_eq!(app.ui.status, "Imported export presets: Fleet");
assert_eq!(app.session.active().unwrap().uid, document);
}
}
+12 -2
View File
@@ -29,6 +29,7 @@
//! are not the dialog's default. `selectDlg` opens the host's folder picker in its own folder.
use std::path::Path;
use std::sync::Arc;
use craft::host::{PickRequest, Picked};
use craft::theme::variant::Tone;
@@ -276,6 +277,7 @@ impl StackDialog for ScriptNotice {
/// The dialog of a script's file dialog call: what the run asked for, read from the run's own
/// request when the dialog opens, so no field of the dialog changes what the person reads.
pub(crate) struct ScriptFiles {
opening: Arc<()>,
kind: PickerKind,
prompt: String,
can_always: bool,
@@ -290,6 +292,7 @@ pub(crate) struct ScriptFiles {
impl ScriptFiles {
fn new(p: ScriptPicker) -> Self {
Self {
opening: Arc::new(()),
kind: p.kind,
prompt: p.prompt,
can_always: p.can_always,
@@ -719,8 +722,11 @@ pub(crate) fn settle_files(app: &mut VectorcraftApp, result: DialogResult<FilesA
}
/// Asks for the files of the kind the running script asked for, starting at the script's file or
/// folder, with the script's file types; the answer goes to the open file dialog.
/// folder, with the script's file types; the answer goes to the dialog that opened the picker.
fn choose(app: &mut VectorcraftApp) {
let Some(opening) = with_host(app, |host, _| host.get::<ScriptFiles>().map(|dialog| Arc::clone(&dialog.opening))).flatten() else {
return;
};
let Some(p) = app.session.script_picker() else { return };
let several = p.multiple && p.kind == PickerKind::Open;
let mut request = match p.kind {
@@ -750,7 +756,11 @@ fn choose(app: &mut VectorcraftApp) {
file_asks::ask(app, request, Owner::Free, move |app, picked| {
let chosen = picked.paths().iter().map(|path| path.to_string_lossy().into_owned()).collect();
let automated = app.file_asks.automated();
with_host(app, |host, _| host.get_mut::<ScriptFiles>().map(|dialog| dialog.add(chosen, several, automated)));
with_host(app, |host, _| {
if let Some(dialog) = host.get_mut::<ScriptFiles>().filter(|dialog| Arc::ptr_eq(&dialog.opening, &opening)) {
dialog.add(chosen, several, automated);
}
});
Ok(Value::Null)
});
}
+80 -7
View File
@@ -35,6 +35,9 @@ pub(crate) const OPTION_TOOLS: [&str; 4] = ["rectangularGrid", "polarGrid", "arc
/// link as the Transform panel's, and the next of these dialogs opens with it as this one left it.
const SIZE_KINDS: [&str; 3] = ["rectangle", "roundedRectangle", "ellipse"];
const CLICK_DOCUMENT: &str = "__clickDocument";
const CLICK_ALT: &str = "__clickAlt";
/// Where a shape tool was clicked: the dialog's shape is drawn there, and with `alt` held a box shape
/// is centred on it.
#[derive(Clone, Copy, Debug)]
@@ -87,10 +90,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option<Click>) {
if SIZE_KINDS.contains(&kind) {
values.insert("constrain".into(), json!(app.object_dialogs.shape_link));
}
// The click is among the fields (no row shows it), where OK reads it.
// Keep the placement with the draft whose fields OK receives.
if let Some(click) = click {
let Some(document) = app.session.active().map(|doc| doc.uid) else {
app.status(tl!("Open a document before drawing a shape").to_string());
return;
};
values.insert("x".into(), json!(click.at.x));
values.insert("y".into(), json!(click.at.y));
values.insert(CLICK_DOCUMENT.into(), json!(document.to_string()));
values.insert(CLICK_ALT.into(), json!(click.alt));
}
let ink = (kind == "arc" && click.is_none()).then(|| ArcInk::of(&app.session));
let params = shape_params(kind, &values, lengths, ink);
@@ -100,7 +109,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: &str, click: Option<Click>) {
ParamDialog::new(key.clone(), title, params.clone()).values(Bind::bound(fields))
});
let kind_owned = kind.to_owned();
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, click, &result.fields);
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| confirm(app, &kind_owned, &result.fields);
if open_held(app, dialog, ok).is_none() {
app.status(format!("no window to show the {kind} dialog"));
}
@@ -470,18 +479,28 @@ fn option_values(kind: &str, fields: &DialogFields) -> Option<Map<String, Value>
/// OK of the `kind` dialog: Tool Options set the tool's options and draw nothing; a click dialog draws at the
/// click, then keeps the options and General › Corner Radius. Every refusal comes before the draw, so a refused OK
/// draws nothing and the dialog stays open for a second OK.
fn confirm(app: &mut VectorcraftApp, kind: &str, click: Option<Click>, fields: &DialogFields) -> Result<(), String> {
fn confirm(app: &mut VectorcraftApp, kind: &str, fields: &DialogFields) -> Result<(), String> {
let options = option_values(kind, fields);
let Some(click) = click else {
let Some(document) = fields.text(CLICK_DOCUMENT) else {
return match options {
Some(options) if OPTION_TOOLS.contains(&kind) => set_options(app, kind, options),
_ => Err(format!("the {kind} tool has no options")),
};
};
let document = document.parse::<u64>().map_err(|_| tl!("The shape click document is missing").to_string())?;
if app.session.active().is_none_or(|doc| doc.uid != document) {
let reason = if app.session.documents().iter().any(|doc| doc.uid == document) {
tl!("Switch back to the document where you clicked to draw the shape")
} else {
tl!("The document where you clicked to draw the shape has closed")
};
return Err(reason.into());
}
let (Some(x), Some(y)) = (fields.number("x"), fields.number("y")) else {
return Err(tl!("The shape click position is missing").into());
};
let click = Click { at: Point::new(x, y), alt: fields.bool(CLICK_ALT).unwrap_or(false) };
let corner_radius = if kind == "roundedRectangle" { Some(rounded_radius(app, fields)?) } else { None };
let at = |key, clicked| fields.number(key).unwrap_or(clicked);
let click = Click { at: Point::new(at("x", click.at.x), at("y", click.at.y)), ..click };
let (x, y) = (click.at.x, click.at.y);
let (width, height) = (length_of(fields, "width", 100.0), length_of(fields, "height", 100.0));
let (bx, by) = box_origin(click, width, height);
let (id, params) = match kind {
@@ -658,6 +677,60 @@ mod tests {
app.session.doc().unwrap().doc.layers[0].children().unwrap().len()
}
#[test]
fn rectangle_click_waits_for_its_opening_document() {
let (mut app, mut fx) = shown();
let opening = app.session.doc().unwrap().uid;
super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0}));
set(&app, &fx, "rectangle", "width", json!(32.0)).unwrap();
app.run("file.new", json!({"width": 350, "height": 200})).unwrap();
assert_ne!(app.session.doc().unwrap().uid, opening);
press_ok(&mut app, &mut fx, "rectangle");
assert_eq!(drawn(&app), 0, "OK must leave the other document unchanged");
assert!(is_open(&app, "rectangle"));
app.run("document.activate", json!({"index": 0})).unwrap();
press_ok(&mut app, &mut fx, "rectangle");
assert!(!is_open(&app, "rectangle"));
let doc = &app.session.doc().unwrap().doc;
let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap();
assert!((bounds.x0 - 40.0).abs() < 1e-6 && (bounds.y0 - 60.0).abs() < 1e-6);
assert!((bounds.width() - 32.0).abs() < 1e-6);
}
#[test]
fn a_reopened_rectangle_uses_the_replacement_click_and_modifier() {
let (mut app, mut fx) = shown();
super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 40.0, "y": 60.0}));
app.run("file.new", json!({"width": 350, "height": 200})).unwrap();
super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 120.0, "y": 130.0, "alt": true}));
set(&app, &fx, "rectangle", "width", json!(20.0)).unwrap();
set(&app, &fx, "rectangle", "height", json!(30.0)).unwrap();
press_ok(&mut app, &mut fx, "rectangle");
assert!(!is_open(&app, "rectangle"));
assert_eq!(drawn(&app), 1);
let doc = &app.session.doc().unwrap().doc;
let bounds = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap();
assert!((bounds.center().x - 120.0).abs() < 1e-6 && (bounds.center().y - 130.0).abs() < 1e-6);
}
#[test]
fn tool_options_can_be_confirmed_after_switching_documents() {
let (mut app, mut fx) = shown();
open_options(&mut app, "lineSegment").unwrap();
set(&app, &fx, "lineSegment", "length", json!(72.0)).unwrap();
app.run("file.new", json!({"width": 350, "height": 200})).unwrap();
press_ok(&mut app, &mut fx, "lineSegment");
assert!(!is_open(&app, "lineSegment"));
assert_eq!(drawn(&app), 0);
assert_eq!(app.session.tool_options_of("lineSegment")["length"], json!(72.0));
}
#[test]
fn spiral_click_dialog_uses_and_updates_tool_options() {
let (mut app, mut fx) = shown();
+35 -5
View File
@@ -85,6 +85,8 @@ impl StripKind {
pub(crate) struct Strip {
/// Which command the strip previews.
pub kind: StripKind,
/// The drawing whose selection and preview the strip uses.
document: Option<u64>,
/// The slider's value, 0 to 100.
pub level: f64,
/// The selection's document bounds when the strip opened, so the strip stays put while the
@@ -99,6 +101,18 @@ pub(crate) struct Strip {
}
impl Strip {
fn in_source(&self, app: &VectorcraftApp) -> bool {
self.document == app.session.active().map(|doc| doc.uid)
}
fn cancel(self, app: &mut VectorcraftApp) {
if self.in_source(app)
&& app.session.active().and_then(|doc| doc.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == self.kind.cmd())
{
self.preview.cancel(app);
}
}
/// The slider's level, a whole number from 0 to 100.
fn level(&self) -> f64 {
if self.level.is_finite() { self.level.round().clamp(0.0, 100.0) } else { self.kind.default_level() }
@@ -124,10 +138,17 @@ pub(crate) fn opening_level(app: &VectorcraftApp, kind: StripKind) -> f64 {
/// Opens the strip of `kind`, replacing (and cancelling the preview of) one that is open.
pub(crate) fn open(app: &mut VectorcraftApp, kind: StripKind) {
if let Some(old) = app.object_dialogs.strip.take() {
old.preview.cancel(app);
old.cancel(app);
}
let strip =
Strip { kind, level: opening_level(app, kind), bounds: app.selection_bounds(), open: true, auto: None, preview: LivePreview::default() };
let strip = Strip {
kind,
document: app.session.active().map(|doc| doc.uid),
level: opening_level(app, kind),
bounds: app.selection_bounds(),
open: true,
auto: None,
preview: LivePreview::default(),
};
app.object_dialogs.strip = Some(strip);
}
@@ -158,6 +179,9 @@ pub(super) fn auto_of(app: &mut VectorcraftApp, kind: StripKind) -> Result<Value
return Err(not_open(kind));
}
let Some(mut strip) = app.object_dialogs.strip.take() else { return Err(not_open(kind)) };
if !strip.in_source(app) {
return Err(not_open(kind));
}
let answer = strip.preview.run(app, true, kind.label(), kind.cmd(), &json!({ "auto": true }));
let result = answer.unwrap_or_else(|| Ok(json!({ "level": strip.level() })));
if let Ok(v) = &result {
@@ -176,8 +200,11 @@ pub(crate) fn more_options(app: &mut VectorcraftApp) -> Result<Value, String> {
return Err(not_open(StripKind::Simplify));
}
let Some(strip) = app.object_dialogs.strip.take() else { return Err(not_open(StripKind::Simplify)) };
if !strip.in_source(app) {
return Err(not_open(StripKind::Simplify));
}
let tolerance = simplify_level_tolerance(strip.level());
strip.preview.cancel(app);
strip.cancel(app);
// PLAN: assumed `path_ops::open_simplify(app: &mut VectorcraftApp, tolerance: f64)` returning `()`.
super::path_ops::open_simplify(app, tolerance);
Ok(json!({ "tolerance": tolerance }))
@@ -202,6 +229,9 @@ fn anchor_rect(view: &CanvasView, bounds: Option<Rect>) -> ScreenRect {
/// the canvas body.
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasView) {
let Some(mut strip) = app.object_dialogs.strip.take() else { return };
if !strip.in_source(app) {
return;
}
let kind = strip.kind;
let anchor = anchor_rect(view, strip.bounds);
let (mut level, mut open) = (strip.level, strip.open);
@@ -226,7 +256,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, view: &CanvasVie
strip.open = open;
let result = match shown.output.closed {
Some(CloseReason::Escape) => {
strip.preview.cancel(app);
strip.cancel(app);
return;
}
Some(_) => {
@@ -48,7 +48,9 @@ fn params_of(result: &ParamResult) -> Value {
/// Report Results on, lists how many of each chosen replacement it made.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let selected = app.session.active().is_some_and(|d| !d.selection.is_empty());
let source = app.session.active().ok_or("no document")?;
let document = source.uid;
let selected = !source.selection.is_empty();
let mut params: Vec<Param> = options()
.into_iter()
.map(|(key, _, label)| Param::new(key, label, ParamKind::bool(matches!(key, "quotes" | "dashes" | "ellipsis"))))
@@ -66,7 +68,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if !selected {
dialog.set_field("scope", FieldValue::Text("document".into()));
}
let owner = egui::Id::unique((COMMAND, "opening-drawing"));
ctx.data_mut(|data| data.insert_temp(owner, document));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> {
let document = ctx.data(|data| data.get_temp::<u64>(owner));
if app.session.active().is_none_or(|st| Some(st.uid) != document) {
return Err(tl!("Return to the original drawing to replace its punctuation").into());
}
let r = app.run(COMMAND, params_of(result))?;
result.remember(&ctx);
if result.fields.bool("report") == Some(true) {
@@ -165,4 +173,39 @@ mod tests {
ok(&mut app);
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn smart_punctuation_waits_for_its_original_drawing() {
let (mut app, source) = app_with_text("a--b");
app.run("select.none", json!({})).unwrap();
open(&mut app).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
let error = super::super::tests_export::try_confirm(&mut app).expect_err("Smart Punctuation must refuse the other drawing");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(plain(&app, other), "c--d");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "document");
app.run("document.activate", json!({ "index": 0 })).unwrap();
ok(&mut app);
assert_eq!(plain(&app, source), "a–b");
}
#[test]
fn reopened_smart_punctuation_applies_in_its_new_drawing() {
let (mut app, source) = app_with_text("a--b");
app.run("select.none", json!({})).unwrap();
open(&mut app).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
app.run("select.none", json!({})).unwrap();
open(&mut app).unwrap();
let (ctx, id) = (app.ui_ctx.clone().unwrap(), entry(&app, COMMAND).unwrap().id);
app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(plain(&app, other), "c–d");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(plain(&app, source), "a--b");
}
}
+146 -23
View File
@@ -16,6 +16,8 @@
//! `__list` (the filters listed, pushed by [`pump`]), and with an applied effect `__index`,
//! `__item` and `missing` (the name of a deleted filter the effect names).
use std::sync::Arc;
use craft::behavior::{DisplayOrder, ItemSource, Selection};
use craft::host::{PickRequest, Picked};
use craft::ui::buttons::Button;
@@ -47,6 +49,32 @@ const LISTING: &str = "__list";
/// The rows the filter list shows before it scrolls.
const LIST_ROWS: u16 = 7;
struct Opening {
document: u64,
reverts: u64,
}
impl Opening {
fn check(&self, app: &VectorcraftApp) -> Result<(), String> {
let Some(doc) = app.session.active().filter(|doc| doc.uid == self.document) else {
return Err(tl!("Return to the original drawing to edit its SVG filters").into());
};
if doc.reverts != self.reverts {
return Err(tl!("Reopen Apply SVG Filter after reverting the drawing").into());
}
Ok(())
}
}
fn opening_id() -> egui::Id {
egui::Id::unique((KIND, "opening"))
}
fn opening(app: &VectorcraftApp) -> Option<Arc<Opening>> {
with_dialog(app, |_| ())?;
app.ui_ctx.as_ref()?.data(|d| d.get_temp(opening_id()))
}
/// The dialog's heading.
fn heading() -> String {
tl!("Apply SVG Filter…").trim_end_matches('…').to_string()
@@ -252,9 +280,8 @@ fn code_row(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut craft::ui::p
/// the default's code or with nothing; when neither has its name, the name shown above the list if
/// the filter was deleted, or else its code open as a new filter.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if app.session.active().is_none() {
return Err("no document open".into());
}
let doc = app.session.active().ok_or("no document open")?;
let source = Arc::new(Opening { document: doc.uid, reverts: doc.reverts });
let mut fields = json!({ "selected": "", "code": "", "editing": "", "__action": "" });
if let Some(k) = p.get("index").and_then(Value::as_u64) {
let mut q = json!({});
@@ -289,7 +316,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let pairs = fields.as_object().into_iter().flatten().map(|(k, v)| (k.clone(), field_value(v.clone())));
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::from_pairs(pairs), build);
crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields)).ok_or("no window")?;
crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| {
let source = opening(app).ok_or("the SVG Filter dialog is gone")?;
source.check(app)?;
confirm(app, &result.fields)
})
.ok_or("no window")?;
ctx.data_mut(|d| d.insert_temp(opening_id(), source));
Ok(Value::Null)
}
@@ -337,6 +370,15 @@ fn set(app: &mut VectorcraftApp, fields: &[(&str, Value)]) {
/// Each frame: pushes the listed filters into the dialog (the build closure has no app) and runs the
/// button pressed, once.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(source) = opening(app) else { return };
if let Err(error) = source.check(app) {
let has_action = with_dialog(app, |d| !text(d.fields(), ACTION).is_empty()).unwrap_or_default();
if has_action {
set(app, &[(ACTION, json!(""))]);
app.status(error);
}
return;
}
let listing = listing(app);
let taken = with_dialog(app, |d| {
if json_field(d.fields(), LISTING).as_ref() != Some(&listing) {
@@ -374,7 +416,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Ok(())
}
"import" => {
ask_import(app);
ask_import(app, Some(source));
Ok(())
}
_ => Ok(()),
@@ -407,7 +449,7 @@ pub(crate) fn menu_items(names: &[String]) -> Vec<Node> {
/// `ui.importSvgFilter {}`: add the filters of an SVG file the user picks to the active document.
/// The answer is `{pending: "fileDialog"}`; the continuation runs the import.
pub fn import_file(app: &mut VectorcraftApp) -> Result<Value, String> {
Ok(ask_import(app))
Ok(ask_import(app, None))
}
/// The extensions of the SVG files Import… reads.
@@ -420,24 +462,33 @@ pub(crate) fn pick() -> PickRequest {
/// Asks for an SVG file; once picked, its filters are added to the document and the first one
/// added is selected in the dialog when it is open.
fn ask_import(app: &mut VectorcraftApp) -> Value {
file_asks::ask(app, pick(), Owner::Document, |app, picked| {
let params = match picked {
// The browser answers with the file's contents, not a path.
Picked::Contents(files) => {
let (_, bytes) = files.first().ok_or("cancelled")?;
json!({ "svg": String::from_utf8_lossy(bytes) })
fn ask_import(app: &mut VectorcraftApp, source: Option<Arc<Opening>>) -> Value {
let dialog = source.clone().or_else(|| opening(app).filter(|opening| opening.check(app).is_ok()));
file_asks::ask_while(
app,
pick(),
Owner::Document,
move |app| source.is_none_or(|source| source.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(&current, &source))),
move |app, picked| {
let params = match picked {
// The browser answers with the file's contents, not a path.
Picked::Contents(files) => {
let (_, bytes) = files.first().ok_or("cancelled")?;
json!({ "svg": String::from_utf8_lossy(bytes) })
}
other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }),
};
let r = app.run("svgFilter.import", params)?;
let added = r["added"].as_array().map_or(0, Vec::len);
app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[]));
if let Some(first) = r["added"].get(0)
&& dialog.is_some_and(|dialog| dialog.check(app).is_ok() && opening(app).is_some_and(|current| Arc::ptr_eq(&current, &dialog)))
{
set(app, &[(SELECTED, first.clone())]);
}
other => json!({ "path": other.first_path().ok_or("cancelled")?.to_string_lossy() }),
};
let r = app.run("svgFilter.import", params)?;
let added = r["added"].as_array().map_or(0, Vec::len);
app.status(crate::i18n::msg_n(added as u64, "Imported {n} SVG filter", "Imported {n} SVG filters", &[]));
if let Some(first) = r["added"].get(0) {
set(app, &[(SELECTED, first.clone())]);
}
Ok(r)
})
Ok(r)
},
)
}
#[cfg(test)]
@@ -493,6 +544,78 @@ mod tests {
assert!(open_dialogs(&app).is_empty());
}
#[test]
fn svg_filter_ok_leaves_the_other_drawings_artwork_alone() {
let mut app = self::app();
app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap();
let id = rect(&mut app);
app.run("file.new", json!({"width": 120, "height": 120})).unwrap();
app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap();
assert_eq!(rect(&mut app), id);
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
activate(&mut app, 0);
open(&mut app, &json!({})).unwrap();
activate(&mut app, 1);
let dialog = dialog_id(KIND);
answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true);
assert!(effects(&app, id).is_empty());
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(fields(&app)[SELECTED], "Shift");
activate(&mut app, 0);
answer_dialog(&mut app, dialog, &[], true);
assert_eq!(effects(&app, id)[0].params["name"], "Shift");
}
#[test]
fn reopened_svg_filter_uses_the_replacement_openings_drawing() {
let mut app = self::app();
app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap();
let first = rect(&mut app);
open(&mut app, &json!({})).unwrap();
app.run("file.new", json!({"width": 120, "height": 120})).unwrap();
app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap();
let second = rect(&mut app);
open(&mut app, &json!({})).unwrap();
answer_dialog(&mut app, dialog_id(KIND), &[(SELECTED, json!("Shift"))], true);
assert_eq!(effects(&app, second).first().map(|f| f.params["name"].clone()), Some(json!("Shift")));
assert!(open_dialogs(&app).is_empty());
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(effects(&app, first).is_empty());
}
#[test]
fn an_svg_filter_draft_cannot_apply_after_reverting_its_drawing() {
let mut app = self::app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("svg-filter-drawing-revert");
let path = dir.join("drawing.vectorcraft");
app.run("svgFilter.define", json!({"xml": SHIFT})).unwrap();
let object = rect(&mut app);
app.run("file.saveAs", json!({"path": path})).unwrap();
rect(&mut app);
app.run("select.set", json!({"ids": [object]})).unwrap();
let original = app.session.doc().unwrap();
let (uid, generation) = (original.uid, original.reverts);
open(&mut app, &json!({})).unwrap();
let dialog = dialog_id(KIND);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reverted = app.session.doc().unwrap();
assert_eq!(reverted.uid, uid);
assert_ne!(reverted.reverts, generation);
app.run("select.set", json!({"ids": [object]})).unwrap();
answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true);
assert!(effects(&app, object).is_empty());
open(&mut app, &json!({})).unwrap();
answer_dialog(&mut app, dialog, &[(SELECTED, json!("Shift"))], true);
assert_eq!(effects(&app, object).first().map(|effect| effect.params["name"].clone()), Some(json!("Shift")));
}
#[test]
fn the_dialog_draws_its_filters_and_buttons() {
let mut app = app();
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more