mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
Merge main into fix/character-style-options-opening-document
This commit is contained in:
commit
14133dd458
66 files changed
+2697
-305
No files matched your search
@@ -196,6 +196,15 @@ impl Unit {
|
||||
}
|
||||
parse_measure(×_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
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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()?;
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 => {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -421,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
|
||||
}
|
||||
|
||||
@@ -984,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");
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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, ¶ms);
|
||||
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, ¶ms).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}))
|
||||
@@ -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"]}));
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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(_) => {
|
||||
|
||||
@@ -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(¤t, &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(¤t, &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();
|
||||
|
||||
@@ -100,10 +100,14 @@ fn rows(name: &str) -> Vec<Param> {
|
||||
/// edited), applies the fields to it; `keep_art` leaves the selection as ordinary art for a new one;
|
||||
/// `opened` are the guides the dialog opened with.
|
||||
fn open_dialog(app: &mut VectorcraftApp, fields: DialogFields, edit: Option<String>, keep_art: bool, opened: [f64; 4]) -> Result<Value, String> {
|
||||
let document = app.session.active().ok_or("no document open")?.uid;
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
let name = fields.text("name").unwrap_or_default().to_string();
|
||||
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Symbol Options"), rows(&name)));
|
||||
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> {
|
||||
if !app.session.active().is_some_and(|active| active.uid == document) {
|
||||
return Err(tl!("This symbol belongs to the document that opened the dialog.").to_owned());
|
||||
}
|
||||
let f = &result.fields;
|
||||
let name = f.text("name").unwrap_or_default().trim().to_string();
|
||||
if name.is_empty() {
|
||||
@@ -187,3 +191,38 @@ fn merge(into: &mut Value, extra: Value) {
|
||||
a.extend(b);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod document_tests {
|
||||
use craft::ui::dialog::dialog_id;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::super::tests_warp::{accept, set, windowed};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn editing_symbol_options_does_not_rename_another_drawings_symbol() {
|
||||
let mut app = windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
for side in [30, 50] {
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": side, "height": side})).unwrap();
|
||||
app.run("symbol.new", json!({"name": "Badge"})).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_edit(&mut app, Some("Badge")).unwrap();
|
||||
let id = dialog_id(KIND);
|
||||
set(&app, id, "name", json!("Source badge"));
|
||||
activate(&mut app, 1);
|
||||
accept(&mut app, id);
|
||||
assert_eq!(app.session.active().unwrap().doc, other);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
|
||||
activate(&mut app, 0);
|
||||
accept(&mut app, id);
|
||||
assert!(app.session.active().unwrap().doc.symbols.iter().any(|symbol| symbol.name == "Source badge"));
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ fn rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
/// Open Tate-chu-yoko Settings on the characters the Character panel acts on.
|
||||
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")?.uid;
|
||||
let (up, right) = crate::panels::character::shared_tcy_offsets(app);
|
||||
let mut fields = DialogFields::new();
|
||||
for (key, v) in KEYS.into_iter().zip([up, right]) {
|
||||
@@ -52,6 +53,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
if p.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if !app.session.active().is_some_and(|active| active.uid == document) {
|
||||
return Err(tl!("Tate-chu-yoko Settings can only change the document where it was opened.").to_owned());
|
||||
}
|
||||
crate::panels::character::run_format(app, Value::Object(p)).map(|_| ())
|
||||
})
|
||||
.ok_or("no window")?;
|
||||
@@ -133,6 +137,42 @@ mod tests {
|
||||
assert_eq!(offsets(&app, id), [(0.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tate_chu_yoko_settings_refuses_confirmation_in_another_drawing() {
|
||||
use craft::ui::dialog::{HeldOk, dialog_id};
|
||||
|
||||
let (mut app, source_id) = app();
|
||||
let source_before = offsets(&app, source_id);
|
||||
let source_undo = app.session.active().unwrap().history.undo.len();
|
||||
app.run("ui.tateChuYokoSettings", json!({})).unwrap();
|
||||
driver::set(&mut app, "tcyUpDown", json!(7));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let host = app.dialogs().unwrap();
|
||||
let id = dialog_id(KIND);
|
||||
assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the edit waits for the app");
|
||||
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
let target_id = app.run("text.create", json!({"x": 10, "y": 50, "text": "other"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [target_id]})).unwrap();
|
||||
let target_before = offsets(&app, target_id);
|
||||
let target_undo = app.session.active().unwrap().history.undo.len();
|
||||
driver::pump(&mut app);
|
||||
assert_eq!(
|
||||
(offsets(&app, target_id), app.session.active().unwrap().history.undo.len()),
|
||||
(target_before, target_undo),
|
||||
"the other drawing's text and undo history stay untouched"
|
||||
);
|
||||
assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
|
||||
assert_eq!(driver::fields(&app).number("tcyUpDown"), Some(7.0));
|
||||
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("select.set", json!({"ids": [source_id]})).unwrap();
|
||||
assert_eq!(offsets(&app, source_id), source_before);
|
||||
assert!(crate::dialogs::tests::confirm(&mut app), "confirm the retained edit on its original drawing");
|
||||
assert_eq!(offsets(&app, source_id), [(7.0, 0.0)]);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1);
|
||||
}
|
||||
|
||||
/// While the Type tool edits text, OK sets the selected characters.
|
||||
#[test]
|
||||
fn tate_chu_yoko_settings_dialog_sets_the_range_the_type_tool_selects() {
|
||||
|
||||
@@ -344,6 +344,40 @@ fn a_bad_range_keeps_export_as_open() {
|
||||
assert!(written.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_as_opened_without_a_drawing_does_not_take_a_later_drawing() {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()));
|
||||
save_panel(&mut app, |_| Some("/out/untitled.png".into()));
|
||||
app.run("file.exportAs", json!({"format": "png"})).unwrap();
|
||||
assert_eq!(kind(&app).as_deref(), Some("exportAs"));
|
||||
assert_eq!(fields(&app)["format"], "png");
|
||||
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
|
||||
let error = try_confirm(&mut app).expect_err("the old Export As draft has no source drawing");
|
||||
assert!(error.contains("Open Export As from the drawing"), "{error}");
|
||||
assert_eq!(kind(&app).as_deref(), Some("exportAs"));
|
||||
PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_as_waits_for_the_drawing_that_opened_it() {
|
||||
let (mut app, written) = app(2);
|
||||
app.run("file.exportAs", json!({"format": "png", "useArtboards": true, "range": "1"})).unwrap();
|
||||
app.run("file.new", json!({ "width": 200, "height": 100 })).unwrap();
|
||||
let error = try_confirm(&mut app).expect_err("Export As must refuse the other drawing");
|
||||
assert!(error.contains("original drawing"), "{error}");
|
||||
assert_eq!(kind(&app).as_deref(), Some("exportAs"));
|
||||
assert_eq!(fields(&app)["range"], "1");
|
||||
PANEL.with_borrow(|panel| assert!(panel.as_ref().unwrap().picker.requests().is_empty()));
|
||||
app.run("document.activate", json!({ "index": 0 })).unwrap();
|
||||
confirm(&mut app);
|
||||
assert_eq!(kind(&app).as_deref(), Some("pngOptions"));
|
||||
confirm(&mut app);
|
||||
assert_eq!(written.borrow().len(), 1);
|
||||
assert_eq!(&written.borrow()[0].1[16..20], 60u32.to_be_bytes());
|
||||
}
|
||||
|
||||
/// Each format's Export As continues in its options dialog, writes nothing before that dialog's OK, and then
|
||||
/// writes its files: (case, artboards, Export As params, the options' key, the files, the pages of a PDF, the
|
||||
/// page size of a PDF of the art's bounds).
|
||||
|
||||
@@ -179,6 +179,34 @@ fn simplify_slider_escape_puts_the_paths_back() {
|
||||
assert_eq!(anchor_count(&app), 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_sliders_close_on_a_drawing_switch() {
|
||||
for (kind, command) in
|
||||
[(simplify_slider::StripKind::Simplify, "object.path.simplify"), (simplify_slider::StripKind::Smooth, "object.path.smooth")]
|
||||
{
|
||||
let mut app = app_with_dense_path();
|
||||
let original = app.session.doc().unwrap().doc.clone();
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": 120.0 + (i % 2) as f64 * 0.2})).collect();
|
||||
let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.anchors", json!({"id": id, "anchors": [[0, 19]]})).unwrap();
|
||||
let second = app.session.doc().unwrap().doc.clone();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
crate::menus::invoke(&mut app, command, json!({}));
|
||||
settle(&mut app);
|
||||
assert!(simplify_slider::showing_of(&app, kind));
|
||||
assert!(app.session.in_interaction());
|
||||
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
assert!(simplify_slider::auto_of(&mut app, kind).is_err(), "Auto must not use the second drawing");
|
||||
frame(&mut app, vec![]);
|
||||
assert!(!simplify_slider::showing_of(&app, kind));
|
||||
assert!(!app.session.in_interaction());
|
||||
assert_eq!(app.session.doc().unwrap().doc, second);
|
||||
assert_eq!(app.session.documents()[0].doc, original);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Simplify slider stays where it opened, under the paths as they were, while the preview changes their bounds, so a
|
||||
/// drag doesn't move the rail under the pointer.
|
||||
#[test]
|
||||
|
||||
@@ -61,6 +61,51 @@ fn open(app: &mut VectorcraftApp) {
|
||||
assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_artboard_is_clickable_on_open_in_a_short_web_viewport() {
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
|
||||
|
||||
for view in ["grid", "list"] {
|
||||
let (mut app, log) = app(2, true);
|
||||
app.run("artboard.rename", json!({"indices": [0], "name": "First audit board"})).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 500.0));
|
||||
let mut time = 0.0;
|
||||
let mut draw = |app: &mut VectorcraftApp, events| {
|
||||
time += 0.2;
|
||||
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
|
||||
};
|
||||
draw(&mut app, vec![]);
|
||||
open(&mut app);
|
||||
set(&mut app, "view", json!(view));
|
||||
for _ in 0..5 {
|
||||
draw(&mut app, vec![]);
|
||||
}
|
||||
let out = draw(&mut app, vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
let bounds = nodes
|
||||
.iter()
|
||||
.find_map(|(_, node)| {
|
||||
if node.role() == Role::CheckBox && node.label().is_some_and(|label| label.contains("First audit board")) {
|
||||
node.bounds()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.expect("the first artboard has a checkbox");
|
||||
let pos = pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32);
|
||||
|
||||
assert_eq!(field(&app, "boards"), json!([true, true]));
|
||||
draw(&mut app, vec![Event::PointerMoved(pos)]);
|
||||
for pressed in [true, false] {
|
||||
draw(&mut app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
|
||||
}
|
||||
draw(&mut app, vec![]);
|
||||
assert_eq!(field(&app, "boards"), json!([false, true]), "the first {view} checkbox should be clickable without scrolling");
|
||||
assert!(log.borrow().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Presses OK, which the dialog refuses or does not offer: it stays open.
|
||||
fn stays_open(app: &mut VectorcraftApp) {
|
||||
let _ = try_confirm(app);
|
||||
|
||||
@@ -66,6 +66,7 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool
|
||||
app.status(tl!("no document").to_string());
|
||||
return true;
|
||||
};
|
||||
let document = st.uid;
|
||||
let vars = st.doc.variables.clone();
|
||||
let mut fields = DialogFields::new();
|
||||
match id {
|
||||
@@ -128,18 +129,19 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool
|
||||
let rows = params(&vars, &build_id, fields);
|
||||
ParamDialog::command(KEY, Label::from(title.clone()), rows)
|
||||
});
|
||||
crate::dialogs::host::open_held(app, dialog, move |app, result| ok(app, &command, result));
|
||||
crate::dialogs::host::open_held(app, dialog, move |app, result| ok(app, document, &command, result));
|
||||
true
|
||||
}
|
||||
|
||||
/// Runs `command` with what the confirmed `result` says. A data set dialog answers the error, which
|
||||
/// keeps it open with what was typed (a taken or empty name); any other command's error goes to the
|
||||
/// status line and the dialog closes.
|
||||
fn ok(app: &mut VectorcraftApp, command: &str, result: &ParamResult) -> Result<(), String> {
|
||||
let Some(vars) = app.session.active().map(|st| st.doc.variables.clone()) else {
|
||||
return Err(tl!("no document").to_string());
|
||||
fn ok(app: &mut VectorcraftApp, document: u64, command: &str, result: &ParamResult) -> Result<(), String> {
|
||||
let Some(st) = app.session.active().filter(|st| st.uid == document) else {
|
||||
return Err(tl!("These changes belong to the document this dialog was opened for.").to_owned());
|
||||
};
|
||||
let Err(e) = app.run(command, params_of(command, result, &vars)) else { return Ok(()) };
|
||||
let params = params_of(command, result, &st.doc.variables);
|
||||
let Err(e) = app.run(command, params) else { return Ok(()) };
|
||||
if matches!(command, "dataset.new" | "dataset.set") {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -440,6 +442,37 @@ mod tests {
|
||||
assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_data_set_edit_stays_with_the_drawing_that_opened_it() {
|
||||
let mut app = app_with_variables();
|
||||
app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Source"}})).unwrap();
|
||||
app.run("file.new", json!({"width": 240, "height": 220})).unwrap();
|
||||
app.run("variable.define", json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Other"}})).unwrap();
|
||||
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
|
||||
let other = app.run("dataset.list", json!({})).unwrap();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
|
||||
activate(&mut app, 0);
|
||||
assert!(open(&mut app, "dataset.set", None));
|
||||
set(&mut app, "name", json!("Revised"));
|
||||
set(&mut app, &value_key("Title"), json!("New value"));
|
||||
activate(&mut app, 1);
|
||||
ok(&mut app);
|
||||
|
||||
assert_eq!(app.run("dataset.list", json!({})).unwrap(), other);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
assert!(is_open(&app));
|
||||
assert_eq!(fields(&app)[value_key("Title")], "New value");
|
||||
|
||||
activate(&mut app, 0);
|
||||
ok(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
let source = app.run("dataset.list", json!({})).unwrap();
|
||||
assert_eq!(source["datasets"][0]["name"], "Revised");
|
||||
assert_eq!(source["datasets"][0]["values"]["Title"], json!({"text": "New value"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_data_sets_name_field_renames_the_row_it_edits() {
|
||||
let mut app = app_with_variables();
|
||||
|
||||
@@ -68,6 +68,7 @@ fn rows(lengths: LengthUnits) -> Vec<Param> {
|
||||
/// Open Warichu Settings on the characters the Character panel acts on.
|
||||
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")?.uid;
|
||||
let shared = crate::panels::character::shared_warichu(app);
|
||||
let mut fields = DialogFields::new();
|
||||
set_shared(&mut fields, KEYS[0], shared.lines.map(i64::from));
|
||||
@@ -83,6 +84,9 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
if p.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if !app.session.active().is_some_and(|active| active.uid == document) {
|
||||
return Err(tl!("Warichu Settings can only change the document where it was opened.").to_owned());
|
||||
}
|
||||
crate::panels::character::run_format(app, Value::Object(p)).map(|_| ())
|
||||
})
|
||||
.ok_or("no window")?;
|
||||
@@ -260,6 +264,42 @@ mod tests {
|
||||
assert_eq!(params(&fields, &initial).get("warichuGap"), Some(&json!(MAX_WARICHU_GAP)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warichu_settings_refuses_confirmation_in_another_drawing() {
|
||||
use craft::ui::dialog::{HeldOk, dialog_id};
|
||||
|
||||
let (mut app, source_id) = app();
|
||||
let source_before = settings(&app, source_id);
|
||||
let source_undo = app.session.active().unwrap().history.undo.len();
|
||||
app.run("ui.warichuSettings", json!({})).unwrap();
|
||||
driver::set(&mut app, "warichuLines", json!(4));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let host = app.dialogs().unwrap();
|
||||
let id = dialog_id(KIND);
|
||||
assert!(!host.with(|h| h.confirm_by_id(&ctx, id)), "the edit waits for the app");
|
||||
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
let target_id = app.run("text.create", json!({"x": 10, "y": 50, "text": "other"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [target_id]})).unwrap();
|
||||
let target_before = settings(&app, target_id);
|
||||
let target_undo = app.session.active().unwrap().history.undo.len();
|
||||
driver::pump(&mut app);
|
||||
assert_eq!(
|
||||
(settings(&app, target_id), app.session.active().unwrap().history.undo.len()),
|
||||
(target_before, target_undo),
|
||||
"the other drawing's text and undo history stay untouched"
|
||||
);
|
||||
assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
|
||||
assert_eq!(driver::fields(&app).number("warichuLines"), Some(4.0));
|
||||
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("select.set", json!({"ids": [source_id]})).unwrap();
|
||||
assert_eq!(settings(&app, source_id), source_before);
|
||||
assert!(crate::dialogs::tests::confirm(&mut app), "confirm the retained edit on its original drawing");
|
||||
assert_eq!(settings(&app, source_id), [(false, 4, 0.0, 50.0, WarichuAlign::Auto)]);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1);
|
||||
}
|
||||
|
||||
/// While the Type tool edits text, OK sets the selected characters.
|
||||
#[test]
|
||||
fn warichu_settings_dialog_sets_the_range_the_type_tool_selects() {
|
||||
|
||||
@@ -877,7 +877,7 @@ pub(super) fn ask_before_losing(app: &mut VectorcraftApp, path: &str, command: &
|
||||
if command != "file.save" {
|
||||
params["path"] = json!(path);
|
||||
}
|
||||
dialogs::confirm::ask(app, &message, &detail, command, params);
|
||||
dialogs::confirm::ask_in_document(app, &message, &detail, command, params);
|
||||
Some(json!({ "pending": dialogs::confirm::KIND }))
|
||||
}
|
||||
|
||||
|
||||
@@ -274,7 +274,7 @@ pub struct VectorcraftApp {
|
||||
/// The hosted dialogs whose OK the app answers, one record each.
|
||||
pub(crate) held: dialogs::host::Held,
|
||||
/// The document whose settings the open Document Setup dialog edits.
|
||||
pub(crate) document_setup_source: Option<u64>,
|
||||
pub(crate) document_setup_source: Option<(u64, u64)>,
|
||||
/// The undo step each value gesture in progress edits under: a scrub or a slider drag is one
|
||||
/// step however many values it sets.
|
||||
pub(crate) edit_scopes: HashMap<GestureId, UndoScope>,
|
||||
@@ -319,7 +319,7 @@ pub struct VectorcraftApp {
|
||||
/// The Justification dialog, while it is open.
|
||||
pub(crate) justification: Option<dialogs::justification::Open>,
|
||||
/// The Bullets and Numbering dialog's live preview.
|
||||
pub(crate) bullets_preview: dialogs::preview::LivePreview,
|
||||
pub(crate) bullets_preview: Option<dialogs::bullets_numbering::Preview>,
|
||||
/// The paste that waits for the answer to its colour profile question.
|
||||
pub(crate) pending_paste: Option<dialogs::profile_mismatch::PasteAsk>,
|
||||
/// The missing links' questions, while they are asked.
|
||||
|
||||
@@ -1097,7 +1097,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",
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
//! `actionSet.read`), a Set Selection step as a Select Object step.
|
||||
|
||||
use craft::automation::actions::{Action, ActionColor, ActionStep, ActionsFile};
|
||||
use craft::host::{PickKind, PickRequest}; // PLAN: assumed path of the host's picker types in the app's `craft` facade
|
||||
use craft::host::{PickKind, PickRequest, Picked}; // PLAN: assumed path of the host's picker types in the app's `craft` facade
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -577,15 +577,20 @@ fn read_path(app: &mut VectorcraftApp, path: &str) -> Result<FileRead, String> {
|
||||
(None, Some(read)) => read(path)?,
|
||||
(None, None) => return Err("no file reader".into()),
|
||||
};
|
||||
read_bytes(app, path, &bytes)
|
||||
}
|
||||
|
||||
/// A desktop or browser file's contents, with its name used only as the unnamed set's fallback.
|
||||
fn read_bytes(app: &mut VectorcraftApp, name: &str, bytes: &[u8]) -> Result<FileRead, String> {
|
||||
if bytes.len() > MAX_SET_FILE {
|
||||
return Err("the action set file is larger than 8 MiB".into());
|
||||
}
|
||||
if is_aia(&bytes) {
|
||||
return read_aia(app, json!({ "name": path, "dataBase64": vectorcraft_format::base64_encode(&bytes) }));
|
||||
if is_aia(bytes) {
|
||||
return read_aia(app, json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }));
|
||||
}
|
||||
let stem = std::path::Path::new(path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let text = String::from_utf8(bytes).map_err(|_| "not an action set file")?;
|
||||
let (name, actions) = read_set(&text, if stem.is_empty() { "Actions" } else { &stem })?;
|
||||
let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| "not an action set file")?;
|
||||
let (name, actions) = read_set(text, if stem.is_empty() { "Actions" } else { &stem })?;
|
||||
Ok(FileRead { name, actions, aia: None })
|
||||
}
|
||||
|
||||
@@ -613,8 +618,16 @@ fn read_file(
|
||||
let exts = [&[ACTIONS_EXT], vectorcraft_engine::cmd::actionset::EXTS].concat();
|
||||
let request = PickRequest::open("actions").filter("Action sets", &exts);
|
||||
Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| {
|
||||
let path = picked.first_path().ok_or("cancelled")?;
|
||||
let read = read_path(app, &path.to_string_lossy())?;
|
||||
let read = match picked {
|
||||
Picked::Contents(files) => {
|
||||
let (name, bytes) = files.into_iter().next().ok_or("cancelled")?;
|
||||
read_bytes(app, &name, &bytes)?
|
||||
}
|
||||
other => {
|
||||
let path = other.first_path().ok_or("cancelled")?;
|
||||
read_path(app, &path.to_string_lossy())?
|
||||
}
|
||||
};
|
||||
then(app, read)
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -203,6 +203,29 @@ fn options_with_a_field_that_is_not_an_index_change_nothing() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_action_options_do_not_rename_the_copy_that_took_its_index() {
|
||||
let mut app = app_with_sets();
|
||||
crate::dialogs::action_set_options::open_action(&mut app, 1, 1);
|
||||
set_dialog::<SetOptionsDialog>(&mut app, "name", json!("Wrong target"));
|
||||
assert_eq!(app.run(DUPLICATE, json!({"set": 1, "action": 0})).unwrap(), json!({"set": 1, "action": 1}));
|
||||
let before = action_names(&app, 1);
|
||||
assert!(confirm_dialog::<SetOptionsDialog>(&mut app).is_err(), "an index taken by a copy must refuse OK");
|
||||
assert!(is_open::<SetOptionsDialog>(&app));
|
||||
assert_eq!(action_names(&app, 1), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_set_options_do_not_rename_the_set_that_took_its_index() {
|
||||
let mut app = app_with_sets();
|
||||
crate::dialogs::action_set_options::open(&mut app, 1);
|
||||
set_dialog::<SetOptionsDialog>(&mut app, "name", json!("Wrong target"));
|
||||
app.ui.actions.delete_set("Mine").unwrap();
|
||||
assert!(confirm_dialog::<SetOptionsDialog>(&mut app).is_err(), "an index taken by the next set must refuse OK");
|
||||
assert!(is_open::<SetOptionsDialog>(&app));
|
||||
assert_eq!(set_names(&app), ["Default Actions", "Other"]);
|
||||
}
|
||||
|
||||
/// `ui.actionSet.delete` moves the panel's selected action down with its set, and clears it
|
||||
/// when its set is deleted.
|
||||
#[test]
|
||||
|
||||
@@ -7,6 +7,52 @@ use super::tests_support::*;
|
||||
use super::*;
|
||||
use crate::dialogs::action_batch::BatchDialog;
|
||||
|
||||
#[test]
|
||||
fn browser_picks_load_and_replace_action_sets_without_a_file_reader() {
|
||||
let native = json!({
|
||||
"format": "vcactions", "version": 1, "name": "Browser",
|
||||
"actions": [{"name": "Group", "steps": [{"command": "object.group", "params": {}}]}]
|
||||
})
|
||||
.to_string();
|
||||
let mut aia = aia_text("", &[("Group", &[("group", true)])]).into_bytes();
|
||||
// AIA's text encoding is not required to be UTF-8.
|
||||
aia.extend(b"/note (\xFF)\n");
|
||||
for command in [LOAD_SET, REPLACE_SET] {
|
||||
for (name, bytes) in [("Browser.vcactions", native.as_bytes()), ("Browser.aia", aia.as_slice())] {
|
||||
let mut app = app_with_sets();
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
let picker = crate::tests::picks::scripted(&mut app);
|
||||
app.services.read = None;
|
||||
app.services.read_head = None;
|
||||
let before = saved_sets(&app);
|
||||
let undo = undo_steps(&app);
|
||||
app.run(command, json!({})).unwrap();
|
||||
picker.cancel();
|
||||
crate::file_asks::poll(&mut app);
|
||||
assert_eq!(saved_sets(&app), before, "cancel keeps the sets");
|
||||
for invalid in [vec![0xff], vec![b' '; files::MAX_SET_FILE + 1]] {
|
||||
app.run(command, json!({})).unwrap();
|
||||
picker.answer_contents(&[(name, &invalid)]);
|
||||
crate::file_asks::poll(&mut app);
|
||||
assert_eq!(saved_sets(&app), before, "invalid picked bytes keep the sets");
|
||||
assert!(!app.ui.status.is_empty(), "a rejected file reports why");
|
||||
}
|
||||
app.run(command, json!({})).unwrap();
|
||||
picker.answer_contents(&[(name, bytes)]);
|
||||
crate::file_asks::poll(&mut app);
|
||||
let names = set_names(&app);
|
||||
assert_eq!(names.last().map(String::as_str), Some("Browser"));
|
||||
if command == REPLACE_SET {
|
||||
assert_eq!(names, ["Browser"]);
|
||||
} else {
|
||||
assert!(names.len() > 1, "Load keeps existing sets");
|
||||
}
|
||||
assert_eq!(set_actions(&app, names.len() - 1)[0].steps, [ActionStep::new("object.group", json!({}))]);
|
||||
assert_eq!(undo_steps(&app), undo, "loading actions does not edit the drawing");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_are_valid_commands() {
|
||||
for a in default_sets().actions {
|
||||
|
||||
@@ -944,7 +944,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result<Va
|
||||
/// dialog.
|
||||
pub(crate) fn other_library(app: &mut VectorcraftApp, path: Option<String>) -> Result<Value, String> {
|
||||
let filters = library_panel::library_pick_filters(BrushLibraries::KIND);
|
||||
library_panel::pick_library_file(app, path, filters, |app, path| load_library(app, json!({ "path": path })))
|
||||
library_panel::pick_library_file(app, path, filters, load_library)
|
||||
}
|
||||
|
||||
/// The id prefix of the Window → Brush Libraries → User Defined slots.
|
||||
|
||||
@@ -1041,7 +1041,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result<Va
|
||||
/// Other Library…: load the library (or document) at `path`, else one picked in an open dialog.
|
||||
pub(crate) fn other_library(app: &mut VectorcraftApp, path: Option<String>) -> Result<Value, String> {
|
||||
let filters = library_panel::library_pick_filters(GraphicStyleLibraries::KIND);
|
||||
library_panel::pick_library_file(app, path, filters, |app, path| load_library(app, json!({ "path": path })))
|
||||
library_panel::pick_library_file(app, path, filters, load_library)
|
||||
}
|
||||
|
||||
/// The id prefix of the Window → Graphic Style Libraries → User Defined slots.
|
||||
|
||||
@@ -90,8 +90,10 @@ fn mono(ui: &mut Ui, s: &str) {
|
||||
Text::new(s.to_string()).role(TypeRole::Mono).show(ui);
|
||||
}
|
||||
|
||||
/// One paint's row: its tile, its values and its note. A mixed paint keeps the tile's room empty.
|
||||
/// One paint's tile and readout. A solid tint's name sits below its channel values.
|
||||
/// A mixed paint keeps the tile's room empty.
|
||||
fn paint_block(ui: &mut Ui, p: &PaintLines) {
|
||||
let (inline_note, tint_name) = if p.values.is_empty() { (p.note.as_ref(), None) } else { (None, p.note.as_ref()) };
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Picture::painter("", ThumbAspect::SQUARE, |cx, rect| {
|
||||
if !p.mixed {
|
||||
@@ -102,10 +104,13 @@ fn paint_block(ui: &mut Ui, p: &PaintLines) {
|
||||
for v in &p.values {
|
||||
mono(ui, v);
|
||||
}
|
||||
if let Some(note) = &p.note {
|
||||
if let Some(note) = inline_note {
|
||||
Text::new(note.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
});
|
||||
if let Some(name) = tint_name {
|
||||
Text::new(name.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the panel reads from the document and the tool for its rows of numbers ([`Rows::of`]).
|
||||
@@ -408,4 +413,29 @@ mod tests {
|
||||
g.swatch = Some("Sunset".into());
|
||||
assert_eq!(paint_name(&Paint::Gradient(Box::new(g))), Some("Sunset".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_solid_tint_and_its_channels_fit_in_the_narrowest_info_panel() {
|
||||
use crate::panel_docking::PANEL_MIN_WIDTH;
|
||||
use crate::tests::panel_harness::{Place, floated};
|
||||
|
||||
const SWATCH: &str = "Signal Red Coated";
|
||||
const TINT: &str = "Signal Red Coated 40%";
|
||||
let mut app = app_with_rect();
|
||||
let color = json!({"model": "cmyk", "c": 0.1, "m": 0.8, "y": 0.6, "k": 0.2});
|
||||
run(&mut app, "swatch.new", json!({"name": SWATCH, "color": color, "spot": true}));
|
||||
run(&mut app, "paint.setFill", json!({"swatch": SWATCH, "tint": 40}));
|
||||
let paint = lines(&mut app, &crate::testing::ui_context()).fill;
|
||||
assert_eq!(paint.note.as_deref(), Some(TINT));
|
||||
assert_eq!(paint.values.len(), 4, "the fixture has four CMYK channels");
|
||||
let names: Vec<_> = paint.values.iter().map(String::as_str).chain([TINT]).collect();
|
||||
let panel = floated(app, "info", "en", Place::Floating(PANEL_MIN_WIDTH), &names);
|
||||
assert!((panel.body.width() - PANEL_MIN_WIDTH).abs() < 1.0, "the Info panel is at its minimum width");
|
||||
let past = panel.past_named(&names);
|
||||
assert!(past.is_empty(), "the readout extends past the Info panel: {past:?}");
|
||||
let tint = panel.rects(TINT)[0];
|
||||
for name in &paint.values {
|
||||
assert!(panel.rects(name)[0].center().y < tint.top(), "the tint follows the color channels on its own line");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use craft::behavior::{IconId, Selection, SelectionModel};
|
||||
use craft::host::{PickRequest, Picked};
|
||||
use craft::host::PickRequest;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::contract::{Bind, MemoKey, MemoProps, SelectMode, Show as _, ShowContainer as _, Trigger};
|
||||
use craft::ui::menu::{Menu, MenuItem, PanelRow};
|
||||
@@ -113,7 +113,7 @@ pub(crate) trait LibraryKind {
|
||||
const OPEN: &'static str;
|
||||
/// The engine command listing the libraries, for error messages.
|
||||
const LIST: &'static str;
|
||||
/// The engine command loading a library from a file (`{path}` → `{library}`).
|
||||
/// The engine command loading a library by path or by file name and contents (`{library}`).
|
||||
const LOAD: &'static str;
|
||||
/// The libraries menu's tooltip ("Swatch Libraries Menu").
|
||||
const MENU: &'static str;
|
||||
@@ -502,13 +502,13 @@ pub(crate) fn locate(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Strin
|
||||
}
|
||||
let path = p.get("path").and_then(Value::as_str).map(str::to_string);
|
||||
let panel = given.to_string();
|
||||
pick_library_file(app, path, library_pick_filters(k.kind), move |app, path| located(app, &panel, &path))
|
||||
pick_library_file(app, path, library_pick_filters(k.kind), move |app, params| located(app, &panel, params))
|
||||
}
|
||||
|
||||
/// Locate Library… answered with the file at `path` for missing library panel `given`.
|
||||
fn located(app: &mut VectorcraftApp, given: &str, path: &str) -> Result<Value, String> {
|
||||
/// Locate Library… answered with the chosen file for missing library panel `given`.
|
||||
fn located(app: &mut VectorcraftApp, given: &str, params: Value) -> Result<Value, String> {
|
||||
let (k, id) = parse(given).ok_or_else(|| format!("`{given}` isn't a library panel (see window.swatchLibrary)"))?;
|
||||
let r = app.run(k.load, json!({ "path": path }))?;
|
||||
let r = app.run(k.load, params)?;
|
||||
let next = r["library"].as_str().unwrap_or_default().to_string();
|
||||
let to = panel_id(k.kind, &next);
|
||||
if to != given && is_open(&app.ui, &to) {
|
||||
@@ -543,25 +543,21 @@ pub(crate) fn library_pick_filters(kind: &str) -> Vec<(&'static str, &'static [&
|
||||
}
|
||||
}
|
||||
|
||||
/// Other Library… and Locate Library…: `then` loads the library file at `path`, else one picked in
|
||||
/// an open dialog. The pick is asked of the app (`file_asks`) and answers on a later pass, which
|
||||
/// runs `then` with the picked file; until then this returns what `file_asks::ask` returns.
|
||||
/// Other Library… and Locate Library…: `then` gets the load command parameters for the file at
|
||||
/// `path`, or for the picked file. A browser pick supplies the name and contents.
|
||||
pub(crate) fn pick_library_file(
|
||||
app: &mut VectorcraftApp,
|
||||
path: Option<String>,
|
||||
filters: Vec<(&'static str, &'static [&'static str])>,
|
||||
then: impl FnOnce(&mut VectorcraftApp, String) -> Result<Value, String> + 'static,
|
||||
then: impl FnOnce(&mut VectorcraftApp, Value) -> Result<Value, String> + 'static,
|
||||
) -> Result<Value, String> {
|
||||
if let Some(path) = path {
|
||||
return then(app, path);
|
||||
return then(app, json!({ "path": path }));
|
||||
}
|
||||
let request = filters.into_iter().fold(PickRequest::open("library"), |r, (name, exts)| r.filter(name, exts));
|
||||
Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| match picked {
|
||||
Picked::Paths(paths) => match paths.into_iter().next() {
|
||||
Some(path) => then(app, path.to_string_lossy().into_owned()),
|
||||
None => Ok(Value::Null),
|
||||
},
|
||||
_ => Ok(Value::Null),
|
||||
Ok(file_asks::ask(app, request, Owner::Free, move |app, picked| match file_asks::open_params(&picked) {
|
||||
Some(params) => then(app, Value::Object(params)),
|
||||
None => Ok(Value::Null),
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -262,6 +262,45 @@ fn saving_to_a_file_and_opening_a_palette_file() {
|
||||
assert!(!builtin_library(&open.id) && builtin_library(vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES));
|
||||
}
|
||||
|
||||
fn browser_library<K: LibraryKind>(filename: &str, bytes: &[u8], entry: &str) -> Option<String> {
|
||||
let mut app = app();
|
||||
app.services.download = Some(Box::new(|_, _| Ok(())));
|
||||
let picker = scripted(&mut app);
|
||||
let undo = undo_len(&app);
|
||||
crate::tests::picks::asks(&mut app, &format!("{}.other", K::OPEN));
|
||||
picker.answer_contents(&[(filename, bytes)]);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
crate::tests::picks::poll(&mut app, &ctx);
|
||||
assert_eq!((app.session.documents().len(), undo_len(&app)), (1, undo), "loading a library does not change the drawing");
|
||||
let open = last_open(&app.ui)?;
|
||||
assert_eq!(open.kind, K::KIND);
|
||||
assert!(is_open(&app.ui, &open.panel()));
|
||||
let (name, library) = K::get(&app, &open.id)?;
|
||||
assert!(K::rows(&library, &open.id).iter().any(|row| row.name == entry && row.item.is_some()), "{entry} is in the {name} library");
|
||||
Some(name)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_library_opens_browser_pick_contents_for_each_panel_kind() {
|
||||
use crate::panels::{brushes::BrushLibraries, graphic_styles::GraphicStyleLibraries, symbols::SymbolLibraries};
|
||||
|
||||
let mut source = app();
|
||||
source.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
source.run("graphicStyle.new", json!({"name": "Studio Style"})).unwrap();
|
||||
source.run("symbol.new", json!({"name": "Studio Symbol"})).unwrap();
|
||||
source.run("brush.new", json!({"type": "bristle", "name": "Studio Brush"})).unwrap();
|
||||
let encoded = source.run("document.serialize", json!({})).unwrap();
|
||||
let document = vectorcraft_format::base64_decode(encoded["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let palette = b"GIMP Palette\nName: Browser Palette\n#\n255 0 0\tBrowser Red\n";
|
||||
let loaded = [
|
||||
browser_library::<SwatchLibraries>("Browser Palette.gpl", palette, "Browser Red"),
|
||||
browser_library::<BrushLibraries>("Browser Studio.vectorcraft", &document, "Studio Brush"),
|
||||
browser_library::<SymbolLibraries>("Browser Studio.vectorcraft", &document, "Studio Symbol"),
|
||||
browser_library::<GraphicStyleLibraries>("Browser Studio.vectorcraft", &document, "Studio Style"),
|
||||
];
|
||||
assert_eq!(loaded.map(|name| name.unwrap_or_default()), ["Browser Palette", "Browser Studio", "Browser Studio", "Browser Studio"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_dialog_writes_swatch_exchange_files() {
|
||||
let written = std::rc::Rc::new(std::cell::RefCell::new(vec![]));
|
||||
@@ -503,6 +542,32 @@ fn a_persistent_panel_whose_file_is_gone_is_listed_as_missing_until_located() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locate_library_loads_browser_contents_into_the_missing_panel() {
|
||||
let path = std::env::temp_dir().join(format!("vc-browser-locate-{}.gpl", std::process::id()));
|
||||
let palette = b"GIMP Palette\nName: Replacement\n#\n255 0 0\tNew Red\n";
|
||||
std::fs::write(&path, palette).unwrap();
|
||||
let mut app = app();
|
||||
let missing = panel_of(app.run("window.swatchLibrary.other", json!({"path": path})).unwrap());
|
||||
app.run("ui.libraryPanel", json!({"panel": missing, "persistent": true, "view": "smallList"})).unwrap();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
|
||||
let mut app = restarted(&app);
|
||||
tidy(&mut app);
|
||||
app.services.download = Some(Box::new(|_, _| Ok(())));
|
||||
let picker = scripted(&mut app);
|
||||
assert_eq!(app.run("ui.libraryPanel.locate", json!({"panel": missing})), Ok(json!({"pending": "fileDialog"})));
|
||||
picker.answer_contents(&[("Replacement.gpl", palette)]);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
crate::tests::picks::poll(&mut app, &ctx);
|
||||
|
||||
assert!(!is_open(&app.ui, &missing), "the missing panel has been recovered");
|
||||
let panel = last_open(&app.ui).unwrap();
|
||||
assert!(is_open(&app.ui, &panel.panel()));
|
||||
assert_eq!((panel.persistent, panel.view), (true, Some(View::SmallList)));
|
||||
assert!(SwatchLibraries::get(&app, &panel.id).is_some_and(|(_, lib)| lib.swatch("New Red").is_some()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locating_a_library_open_in_its_own_panel_brings_that_panel_forward() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-locate-open-library-{}", std::process::id()));
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::{IconId, Selection, keyed};
|
||||
use craft::host::{PickKind, PickRequest};
|
||||
use craft::host::{PickKind, PickRequest, Picked};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
@@ -364,12 +364,26 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest, then: impl FnOnce(&mut Ve
|
||||
/// say.
|
||||
pub(crate) fn replace(app: &mut VectorcraftApp, ids: Vec<u64>) {
|
||||
let request = vectorcraft_engine::cmd::fileio::place_filters().fold(PickRequest::open("links"), |r, (name, exts)| r.filter(name, exts));
|
||||
ask(app, request, move |app, path| {
|
||||
let r = app.run("links.relink", json!({ "ids": ids, "path": path, "preserve": "fit" }));
|
||||
report(app, r, |v| crate::i18n::msg_n(v["relinked"].as_array().map_or(0, Vec::len) as u64, "Replaced {n} image", "Replaced {n} images", &[]));
|
||||
file_asks::ask(app, request, Owner::Document, move |app, picked| {
|
||||
if let Picked::Contents(files) = picked {
|
||||
if let Some((name, bytes)) = files.into_iter().next() {
|
||||
let result = app
|
||||
.run("links.replaceEmbedded", json!({ "ids": ids, "dataBase64": vectorcraft_format::base64_encode(&bytes) }))
|
||||
.map_err(|err| format!("{name}: {err}"));
|
||||
report(app, result, |v| replaced_status(v["replaced"].as_array().map_or(0, Vec::len)));
|
||||
}
|
||||
} else if let Some(path) = picked.first_path() {
|
||||
let r = app.run("links.relink", json!({ "ids": ids, "path": path.to_string_lossy(), "preserve": "fit" }));
|
||||
report(app, r, |v| replaced_status(v["relinked"].as_array().map_or(0, Vec::len)));
|
||||
}
|
||||
Ok(Value::Null)
|
||||
});
|
||||
}
|
||||
|
||||
fn replaced_status(n: usize) -> String {
|
||||
crate::i18n::msg_n(n as u64, "Replaced {n} image", "Replaced {n} images", &[])
|
||||
}
|
||||
|
||||
/// Relink images `ids` (none: every missing one) to the files of their names in a picked folder.
|
||||
fn relink_to_folder(app: &mut VectorcraftApp, ids: Vec<u64>) {
|
||||
ask(app, PickRequest::folder("links"), move |app, folder| {
|
||||
|
||||
@@ -270,6 +270,7 @@ fn load_profile(app: &mut VectorcraftApp) {
|
||||
Some(path) => app.run("color.loadProfile", json!({ "path": path })),
|
||||
None => Ok(Value::Null),
|
||||
},
|
||||
Picked::Contents(files) if !files.is_empty() => Err("loading profiles from disk isn't available in the browser".into()),
|
||||
_ => Ok(Value::Null),
|
||||
});
|
||||
}
|
||||
@@ -457,6 +458,24 @@ mod tests {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
#[test]
|
||||
fn browser_profile_pick_reports_why_it_cannot_load() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let picker = crate::tests::picks::scripted(&mut app);
|
||||
app.status("Previous status");
|
||||
|
||||
load_profile(&mut app);
|
||||
picker.cancel();
|
||||
crate::file_asks::poll(&mut app);
|
||||
assert_eq!(app.ui.status, "Previous status");
|
||||
|
||||
load_profile(&mut app);
|
||||
assert_eq!(picker.requests().len(), 2);
|
||||
picker.answer_contents(&[("proof.icc", b"test profile")]);
|
||||
crate::file_asks::poll(&mut app);
|
||||
assert_eq!(app.ui.status, "loading profiles from disk isn't available in the browser");
|
||||
}
|
||||
|
||||
/// The panel's Proof Setup list offers the targets of View › Proof Setup, in the same order and
|
||||
/// with the same labels, and each one is a target `view.proofSetup` accepts.
|
||||
#[test]
|
||||
|
||||
@@ -200,12 +200,9 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result<Va
|
||||
open_library(app, &json!({ "library": r["library"] }))
|
||||
}
|
||||
|
||||
/// Other Library…: load the library (or document) at `path`, else one picked in an open dialog
|
||||
/// (on the web the picked file arrives later and opens through [`crate::io::open_bytes`]).
|
||||
/// Other Library…: load the library (or document) at `path`, else one picked in an open dialog.
|
||||
pub(crate) fn other_library(app: &mut VectorcraftApp, path: Option<String>) -> Result<Value, String> {
|
||||
library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SwatchLibraries::KIND), |app, path| {
|
||||
load_library(app, json!({ "path": path }))
|
||||
})
|
||||
library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SwatchLibraries::KIND), load_library)
|
||||
}
|
||||
|
||||
/// The id prefix of the Window → Swatch Libraries → User Defined slots.
|
||||
|
||||
@@ -1037,9 +1037,7 @@ pub(crate) fn load_library(app: &mut VectorcraftApp, params: Value) -> Result<Va
|
||||
/// Other Library…: load the symbols of the document at `path`, else of one picked in an open
|
||||
/// dialog.
|
||||
pub(crate) fn other_library(app: &mut VectorcraftApp, path: Option<String>) -> Result<Value, String> {
|
||||
library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SymbolLibraries::KIND), |app, path| {
|
||||
load_library(app, json!({ "path": path }))
|
||||
})
|
||||
library_panel::pick_library_file(app, path, library_panel::library_pick_filters(SymbolLibraries::KIND), load_library)
|
||||
}
|
||||
|
||||
/// The id prefix of the Window → Symbol Libraries → User Defined slots.
|
||||
|
||||
@@ -653,6 +653,61 @@ fn properties_shows_the_selected_image_and_its_link_actions() {
|
||||
assert!(text.contains("Linked File") && text.contains("Edit Original") && text.contains("Embed"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step() {
|
||||
use crate::tests::picks::{poll, scripted};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
let dir = Folder::new("replace-browser-bytes");
|
||||
let (mut app, linked, _) = app(&dir);
|
||||
let before = app.session.doc().unwrap().doc.clone();
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
let journal = app.session.journal.len();
|
||||
let picker = scripted(&mut app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let bytes = png(10, 20);
|
||||
|
||||
super::links::replace(&mut app, vec![linked]);
|
||||
assert_eq!(picker.requests().len(), 1);
|
||||
picker.answer_contents(&[("replacement.png", &bytes)]);
|
||||
poll(&mut app, &ctx);
|
||||
|
||||
let state = app.session.doc().unwrap();
|
||||
let NodeKind::Image(image) = &state.doc.node(NodeId(linked)).unwrap().kind else { panic!("replacement must keep the image's id") };
|
||||
assert_eq!((image.width, image.height), (10, 20));
|
||||
assert!(image.link.is_none(), "browser file contents are embedded");
|
||||
assert_eq!(state.doc.images[&image.key].bytes.as_slice(), bytes);
|
||||
let bounds = image.xf.transform_rect_bbox(Rect::new(0.0, 0.0, 10.0, 20.0));
|
||||
assert_eq!((bounds.width(), bounds.height()), (100.0, 200.0), "fit in the old 300 by 200 bounds");
|
||||
assert_eq!(state.history.undo.len(), undo + 1);
|
||||
assert_eq!(app.session.journal.get(journal).map(|(command, _)| command.as_str()), Some("links.replaceEmbedded"));
|
||||
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_image_with_a_desktop_path_remains_linked() {
|
||||
use crate::tests::picks::{poll, scripted};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
let dir = Folder::new("replace-desktop-path");
|
||||
let (mut app, _, embedded) = app(&dir);
|
||||
let path = dir.file("replacement.png", &png(10, 20));
|
||||
let picker = scripted(&mut app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
|
||||
super::links::replace(&mut app, vec![embedded]);
|
||||
picker.answer(&[&path]);
|
||||
poll(&mut app, &ctx);
|
||||
|
||||
let state = app.session.doc().unwrap();
|
||||
let NodeKind::Image(image) = &state.doc.node(NodeId(embedded)).unwrap().kind else { panic!("replacement must keep the image's id") };
|
||||
assert_eq!((image.width, image.height), (10, 20));
|
||||
assert_eq!(image.link.as_ref().unwrap().path, path);
|
||||
}
|
||||
|
||||
/// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for
|
||||
/// each image there and links each one to its file; with no folder picked, nothing changes.
|
||||
#[test]
|
||||
|
||||
@@ -695,7 +695,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option
|
||||
fn ask_open(app: &mut VectorcraftApp, filters: &[(&str, &[&str])], command: &'static str) -> Value {
|
||||
let request = filters.iter().fold(PickRequest::open("variables"), |r, (name, exts)| r.filter(*name, exts));
|
||||
file_asks::ask(app, request, Owner::Document, move |app, picked| match file_asks::open_params(&picked) {
|
||||
Some(params) => app.run(command, Value::Object(params)),
|
||||
Some(mut params) => {
|
||||
// The combined importer uses the file name to choose a reader. The dedicated readers already know the format.
|
||||
if command != "variable.import" {
|
||||
params.remove("name");
|
||||
}
|
||||
app.run(command, Value::Object(params))
|
||||
}
|
||||
None => Ok(Value::Null),
|
||||
})
|
||||
}
|
||||
@@ -739,6 +745,48 @@ fn save_library(app: &mut VectorcraftApp) -> Value {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pick_variable_source(command: fn(&mut VectorcraftApp) -> Value, name: &str, bytes: &[u8]) -> VectorcraftApp {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let picker = crate::tests::picks::scripted(&mut app);
|
||||
assert_eq!(command(&mut app), json!({"pending": "fileDialog"}));
|
||||
picker.answer_contents(&[(name, bytes)]);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
crate::tests::picks::poll(&mut app, &ctx);
|
||||
app
|
||||
}
|
||||
|
||||
fn browser_xml() -> String {
|
||||
let mut source = vectorcraft_engine::Session::new();
|
||||
source.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
source.execute("variable.define", &json!({"name": "Caption", "kind": "text"})).unwrap();
|
||||
source.execute("variable.saveLibrary", &json!({})).unwrap()["xml"].as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_variable_import_reads_csv_and_tsv_from_the_file_name() {
|
||||
for (name, bytes) in [("rows.CSV", &b"Caption,Other\nHello,World\n"[..]), ("rows.tsv", &b"Caption\tOther\nHello\tWorld\n"[..])] {
|
||||
let app = pick_variable_source(import_data_source, name, bytes);
|
||||
let data = &app.session.active().unwrap().doc.variables;
|
||||
assert_eq!(data.datasets.len(), 1, "{name}");
|
||||
assert!(data.variables.iter().any(|v| v.name == "Caption"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_variable_import_reads_xml_from_the_file_name() {
|
||||
let app = pick_variable_source(import_data_source, "variables.XML", browser_xml().as_bytes());
|
||||
assert!(app.session.active().unwrap().doc.variables.variables.iter().any(|v| v.name == "Caption"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_dedicated_variable_importers_accept_file_bytes() {
|
||||
let csv = pick_variable_source(import_datasets, "rows.csv", b"Caption\nHello\n");
|
||||
assert_eq!(csv.session.active().unwrap().doc.variables.datasets.len(), 1);
|
||||
let xml = pick_variable_source(load_library, "variables.xml", browser_xml().as_bytes());
|
||||
assert!(xml.session.active().unwrap().doc.variables.variables.iter().any(|v| v.name == "Caption"));
|
||||
}
|
||||
use crate::i18n::LangExt;
|
||||
|
||||
fn app_with_data() -> VectorcraftApp {
|
||||
|
||||
@@ -308,9 +308,23 @@ fn export_preferences(app: &mut VectorcraftApp) {
|
||||
fn import_preferences(app: &mut VectorcraftApp) {
|
||||
let request = PickRequest::open("preferences").filter("Preferences", &["json"]);
|
||||
file_asks::ask(app, request, Owner::Free, |app, picked| {
|
||||
let Picked::Paths(paths) = picked else { return Ok(Value::Null) };
|
||||
let Some(path) = paths.first() else { return Ok(Value::Null) };
|
||||
match app.run("prefs.import", json!({ "path": path.to_string_lossy() })) {
|
||||
let params = match picked {
|
||||
Picked::Paths(paths) => {
|
||||
let Some(path) = paths.first() else { return Ok(Value::Null) };
|
||||
json!({ "path": path.to_string_lossy() })
|
||||
}
|
||||
Picked::Contents(files) => {
|
||||
let Some((_, bytes)) = files.into_iter().next() else { return Ok(Value::Null) };
|
||||
// Match prefs.import's file cap before allocating its JSON text parameter.
|
||||
if bytes.len() > 1 << 20 {
|
||||
return Err("The preferences file is larger than 1 MB".into());
|
||||
}
|
||||
let data = String::from_utf8(bytes).map_err(|_| "The preferences file is not valid UTF-8")?;
|
||||
json!({ "data": data })
|
||||
}
|
||||
_ => return Ok(Value::Null),
|
||||
};
|
||||
match app.run("prefs.import", params) {
|
||||
Ok(_) => app.status("Preferences imported."),
|
||||
Err(e) => app.status(e),
|
||||
}
|
||||
|
||||
@@ -797,6 +797,41 @@ fn prefs_import_refreshes_an_open_preferences_dialog() {
|
||||
assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(7.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_import_applies_picked_preferences_and_refreshes_the_draft() {
|
||||
let mut a = app();
|
||||
open(&mut a, Some("General"));
|
||||
set_field(&mut a, "keyboardIncrement", json!(9)).unwrap();
|
||||
let picker = crate::tests::picks::scripted(&mut a);
|
||||
a.services.read = None;
|
||||
let data = json!({"format": "vectorcraft-preferences", "version": 1, "prefs": {"keyboardIncrement": 7}}).to_string();
|
||||
import_preferences(&mut a);
|
||||
picker.answer_contents(&[("preferences.json", data.as_bytes())]);
|
||||
file_asks::poll(&mut a);
|
||||
assert!(same(&field(&a, "keyboardIncrement"), &json!(7.0)));
|
||||
assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(7.0));
|
||||
assert_eq!(a.ui.status, "Preferences imported.");
|
||||
assert!(is_open(&a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_import_refuses_bad_contents_without_losing_draft_edits() {
|
||||
for bytes in [vec![0xff], vec![b' '; (1 << 20) + 1], b"not JSON".to_vec()] {
|
||||
let mut a = app();
|
||||
open(&mut a, Some("General"));
|
||||
set_field(&mut a, "keyboardIncrement", json!(9)).unwrap();
|
||||
let before = a.session.prefs.to_json();
|
||||
let picker = crate::tests::picks::scripted(&mut a);
|
||||
import_preferences(&mut a);
|
||||
picker.answer_contents(&[("preferences.json", &bytes)]);
|
||||
file_asks::poll(&mut a);
|
||||
assert_eq!(a.session.prefs.to_json(), before);
|
||||
assert!(same(&field(&a, "keyboardIncrement"), &json!(9)));
|
||||
assert!(!a.ui.status.is_empty(), "the invalid picked file reports an error");
|
||||
assert_ne!(a.ui.status, "Preferences imported.");
|
||||
}
|
||||
}
|
||||
|
||||
/// An import that turns Enable Touch Workspace on or off switches the workspace on a touch screen,
|
||||
/// as OK in Preferences does.
|
||||
#[test]
|
||||
|
||||
@@ -515,3 +515,36 @@ fn revert_confirmation_never_discards_another_drawings_changes() {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert_eq!(result, (count, true), "the second drawing must retain its unsaved edits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acknowledging_import_loss_does_not_overwrite_the_source_with_another_drawing() {
|
||||
let d = dir("lossy-drawing-switch");
|
||||
let path = d.join("source.vectorcraft").to_string_lossy().to_string();
|
||||
let mut app = app();
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run("file.saveAs", json!({"path": path})).unwrap();
|
||||
let saved = std::fs::read(&path).unwrap();
|
||||
let st = app.session.doc_mut().unwrap();
|
||||
st.imported_from = Some(path.clone());
|
||||
st.import_losses = vec!["hidden type".into()];
|
||||
rect(&mut app);
|
||||
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
rect(&mut app);
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
let params = json!({"path": path, "options": {"compress": true}});
|
||||
assert_eq!(app.run("file.saveAs", params.clone()).unwrap()["pending"], confirm::KIND);
|
||||
app.run("document.activate", json!({"index": 1})).unwrap();
|
||||
answer_top(&mut app, true);
|
||||
crate::background::wait_all(&mut app);
|
||||
let after_switch = std::fs::read(&path).unwrap();
|
||||
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("file.saveAs", params).unwrap();
|
||||
answer_top(&mut app, true);
|
||||
crate::background::wait_all(&mut app);
|
||||
let after_original = std::fs::read(&path).unwrap();
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(after_switch == saved, "drawing B must never overwrite A's file");
|
||||
assert!(after_original != saved, "approval in drawing A must still save A");
|
||||
}
|
||||
+7
-3
@@ -10194,6 +10194,7 @@ layer of its own below the others; files that carry the editing data (Preserve E
|
||||
Export for Screens) keep it as the artboard's color, not as art. `includeArtboardFill: false` on `document.export`,
|
||||
`document.serialize`, `document.exportForScreens` (Include Artboard Fill) or `file.print` leaves it out. `inspect_document`
|
||||
lists it as the artboard's `color` (`#rrggbb`), and `ui.colorPicker {artboard: index}` opens the Color Picker for it.
|
||||
The artboard preview and confirmation require the opening document to be active.
|
||||
|
||||
Artboard Options' Show Center Mark and Show Cross Hairs: `artboard.setProps {index, showCenterMark?: bool,
|
||||
showCrossHairs?: bool}` (or each entry of `artboards`) turns them on or off for that artboard in one undo step, and
|
||||
@@ -10689,6 +10690,8 @@ listed in `warnings`. ASCII and binary DXF files are read; DWG files answer an e
|
||||
|
||||
## Links panel
|
||||
|
||||
`links.replaceEmbedded {ids, dataBase64}` uses raster file bytes to replace existing canvas images. It embeds the new pixels and keeps the image ids. The new aspect ratio fits inside the old bounds, and a distorted image keeps its corners. The command records one undo step and returns `{replaced: [ids]}`. The browser's Replace Image uses this operation with the file picker result.
|
||||
|
||||
`links.list {show?: all|missing|modified|embedded, sort?: name|kind|status|size}` lists every image in the layers, top
|
||||
first, as the Links panel does (`sort: "size"`, the panel menu's Sort by Size, puts the smallest file first by the
|
||||
size Link Info shows; rows without one, embedded images and missing files whose size is not kept, come last, and equal
|
||||
@@ -16888,10 +16891,11 @@ Unit Converter is a built-in add-on that shows one length in every unit at once
|
||||
`addon.units.convert` and `addon.units.selectionSize`, and in the desktop app it lives in Object › Plug-ins › Unit
|
||||
Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither command changes the document.
|
||||
|
||||
`addon.units.convert {value, unit?}` reads `value` as a number field reads it: a number, or text with a unit suffix and
|
||||
`addon.units.convert {value, unit?}` accepts a number, or text with a unit suffix and
|
||||
`+ - * /` arithmetic, where `x`, `X` and `×` multiply as `*` does (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`,
|
||||
`"3cm*50%"`, `"2x3 mm"`, `"13q"`), a decimal comma read as a point (`"0,5 mm"`) and a single number with a thousands
|
||||
comma (`"1,000 mm"`) refused, in at most 1024 bytes with at most 128 `+ - * /` signs (each multiplication sign counts).
|
||||
`"3cm*50%"`, `"2x3 mm"`, `"13q"`). The command reads an unambiguous decimal comma as a point (`"0,5 mm"`).
|
||||
It refuses numbers that look like grouped integers, whether alone (`"1,000 mm"`) or in arithmetic (`"1,500+2"`).
|
||||
Text may contain at most 1024 bytes and 128 `+ - * /` signs (each multiplication sign counts).
|
||||
A number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`,
|
||||
`centimeters`, `pixels`, `feetInches`, `meters`, `yards`, `feet`, `q`, `ha`; default `points`); a suffix in the text
|
||||
takes precedence over `unit`. It works without an open document. The command fails when `value` is missing, does not
|
||||
|
||||
@@ -970,7 +970,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (<https://www.adobe.com/learn/illustrator/web/crop-using-masks>: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`.
|
||||
- **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`.
|
||||
- **Edit Artboards in Properties:** a Transform section comes first (#5219): the reference point the Transform panel and Control bar share, the active artboard's X and Y (of that point) and W and H with the Constrain Width and Height Proportions link, its preset and orientation, and Move and Scale Artwork with Artboard. The Artboards section follows, with the name field, Artboard Options and Fill. The active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html).
|
||||
- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html).
|
||||
- **Artboard background colors:** each artboard can have a background color (`artboard.setProps {index, color}`, `color: null` removes it). With the Artboard tool, Properties has a Fill row: its list sets None, White or Black, and its chip and its Color Picker… item open the Color Picker for the artboard. Artboard preview and confirmation require its opening document to be active. Artboard Options has a Background Color row with a list that sets None, White or Black, and a color button. The canvas draws the artboard's paper in the color, multiplied with the paper color while Simulate Colored Paper is on, and the transparency grid still covers it. The native format saves the color, and a document without colors saves as before. Exports draw it behind each exported artboard's art, inside the artboard and in the color's own model: raster formats (on a transparent background too), PDF, SVG and EPS pages, `.ai` files' PDF pages, Export for Screens and print, whose preview shows it; files with editing data keep it as the artboard's color, not as art. Export for Screens has Include Artboard Fill beside Include Bleed (on by default and remembered; `includeArtboardFill: false`, which `document.export` and `file.print` take too, leaves it out) (#4937). Not done: `.ai` files the reference app reads keep it only in VectorCraft's editing data, and `.ai`/PDF import doesn't read a background color from the reference app's own data. Engine, canvas, Properties, Color Picker, Artboard Options, export (`fileio::tests_artboard_fill`) and Export for Screens dialog tests cover it. Public reference: [Apply colors to artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/add-background-color-to-artboards.html).
|
||||
- **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`), and a Fill chosen in Properties colors each of them (#5698); a Shift- or Ctrl/Cmd-click on an Artboards panel row with another tool in use switches to the Artboard tool and selects as it does; with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019).
|
||||
- **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`.
|
||||
- **Escape in the distort tools:** Escape during a Puppet Warp pin drag or turn, a Perspective Grid tool handle or plane widget drag, a Perspective Selection move, resize or plane widget drag, or a Liquify stroke cancels it: the art goes back to how the press found it, no undo step is added, and the tool stays chosen. Puppet Warp also selects again the pins selected before the press, and Escape during a Liquify Alt-drag puts the brush size back. Regression tests: `escape_cancels_*` in `crates/tools/src/distort/puppet.rs`, `perspective.rs` and `liquify.rs`, and `escape_cancels_a_puppet_warp_perspective_or_liquify_drag` in `tests/distortkeys.rs`.
|
||||
@@ -2538,6 +2538,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing.
|
||||
- On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed.
|
||||
- In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one.
|
||||
- Replace Image in the browser embeds the picked raster in the existing image and fits it within the old bounds in one undo step. The desktop picker continues to link to the chosen file. Evidence includes `replace_image_uses_browser_picker_bytes_and_fits_them_in_one_undo_step` and `replace_image_with_a_desktop_path_remains_linked`.
|
||||
- The Links panel menu's Sort by Size ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) lists the links by file size, smallest first (`links.list {sort: "size"}`). VectorCraft's own rules: a file's size is the one Link Info shows, rows without one (embedded images, a missing file whose size the document does not keep) come last, and equal sizes go by name.
|
||||
- When a document opens with notes and with linked files that changed on disk (Update Links: Manually) or, on the web, can't be read, the status bar shows the line about the linked files, then counts the notes and names the first, and hovering it lists the notes. The same holds when the line about modified files follows the Linked File Not Found dialog, and File › New from Template… shows the notes of the file it opens as File › Open does (`an_open_with_modified_links_keeps_link_notice_and_import_notes_reachable`, `new_from_template_preserves_open_warnings`, `an_open_with_unreadable_links_keeps_import_notes_reachable`, `modified_links_after_the_missing_ones_keep_the_open_notes`, `combined_open_and_link_status_lists_notes_on_hover_and_for_accessibility`).
|
||||
- On the web, when a document opens with linked files that can't be read and linked files that changed on disk (Update Links: Manually), the status bar shows the line about the unreadable files, and the line about the changed files is the first of the notes its hover lists, ahead of the open's notes. With Ask When Modified the update question opens and the line about the unreadable files stays (`a_web_open_with_unreadable_and_modified_links_keeps_both_lines`).
|
||||
@@ -3077,6 +3078,9 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo
|
||||
|
||||
A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`.
|
||||
|
||||
The `addon.units.convert` command rejects numbers that look like grouped integers even in expressions such as
|
||||
`1,500+2`. The panel treats separators according to the input locale.
|
||||
|
||||
## Cutting Tools add-on: Stencil Bridges (2026-11-12)
|
||||
|
||||
A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges.
|
||||
|
||||
Reference in new issue
Block a user