Merge main into fix/transform-each-opening-document

This commit is contained in:
dotCooCoo committed 2026-11-26 17:00:15 -08:00
commit 5fb9748070
55 files changed
+2294 -302

No files matched your search

+1 -1
View File
@@ -284,7 +284,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Metadata Template…",
[],
None,
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
has_doc,
super::fileinfo::apply_template
),
+14 -9
View File
@@ -213,7 +213,7 @@ enum Merge {
Append,
}
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`.
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
let mode = match text_param(p, "mode", APPLY)? {
Some("replace") => Merge::Replace,
@@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes.
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?];
// At most one byte past the limit is read, so a huge file is never read whole.
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
let bytes = match given {
[Some(path), None, None] => read(path)?,
[None, Some(name), None] => {
[Some(path), None, None, None] => read(path)?,
[None, Some(name), None, None] => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
let mut path = template_path(dir, name, APPLY)?;
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
@@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
// The app's own folder: no root applies.
crate::file_access::unconfined(|| read(&path))?
}
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data)] => data.as_bytes().to_vec(),
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
[None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data), None] => data.as_bytes().to_vec(),
[None, None, None, Some(data)] => {
if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 {
return Err(too_big(APPLY));
}
vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))?
}
_ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")),
};
if bytes.len() > MAX_TEMPLATE_FILE {
return Err(too_big(APPLY));
+5
View File
@@ -708,12 +708,17 @@ fn metadata_template_errors() {
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
let encoded = "A".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES.div_ceil(3) * 4 + 1);
let e = s.execute("file.info.applyTemplate", &json!({"dataBase64": encoded, "mode": "keep"})).unwrap_err();
assert!(e.to_string().contains("larger than 8 MB"), "{e}");
for bad in [
json!({"data": xmp, "mode": "merge"}),
json!({"data": xmp}),
json!({"data": xmp, "mode": 3}),
json!({"mode": "keep"}),
json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"data": xmp, "dataBase64": "SGVsbG8=", "mode": "keep"}),
json!({"dataBase64": "!", "mode": "keep"}),
json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}),
json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}),
json!({"path": big.to_str().unwrap(), "mode": "keep"}),
+9
View File
@@ -94,6 +94,15 @@ impl crate::Renderer {
/// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and
/// nothing is held.
pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed {
// Trim View clips each draw when blending reaches the page and clips one composited
// layer otherwise. Changing modes can change unchanged art at an artboard edge.
if opts.trim && !old.artboards.is_empty() {
let before = crate::proof::prepare(old, opts, &mut self.proof_art);
let after = crate::proof::prepare(new, opts, &mut self.proof_art);
if self.children_blend(&before.layers) != self.children_blend(&after.layers) {
return Changed::Everything;
}
}
let renderer = (!crate::proof::overprints(opts)).then_some(self);
changed_with(old, new, renderer, opts)
}
+36
View File
@@ -99,6 +99,42 @@ fn area(c: Changed) -> Rect {
}
}
#[test]
fn removing_the_last_blend_in_trim_view_repaints_the_artboard_edges() {
use vectorcraft_color::BlendMode;
let mut before = Document::new(110.0, 80.0);
let layer = before.layers[0].id;
for color in [Color::BLACK, Color::WHITE] {
let shape = rect(&mut before, Rect::new(-10.0, 18.0, 25.0, 44.0), color);
before.insert(Some(layer), usize::MAX, shape).unwrap();
}
let mut blend = rect(&mut before, Rect::new(70.0, 35.0, 85.0, 50.0), Color::rgb(0.7, 0.4, 0.3));
blend.blend = BlendMode::Multiply;
let id = before.insert(Some(layer), usize::MAX, blend).unwrap();
let mut after = before.clone();
after.node_mut(id).unwrap().blend = BlendMode::Normal;
let opts = RenderOptions { trim: true, ..Default::default() };
let mut r = Renderer::new();
let first = r.render(&before, W, H, view(), &opts);
let change = r.changed(&before, &after, &opts);
let last = Renderer::new().render(&after, W, H, view(), &opts);
patched(&mut r, &first, &after, change, &last, &opts);
assert_eq!(change, Changed::Everything);
assert!(matches!(r.changed(&before, &after, &RenderOptions::default()), Changed::Area(_)));
// An overprinting fill gets its blend while preparing the proof.
let mut overprinting = after.clone();
overprinting.node_mut(id).unwrap().appearance.fill_mut().unwrap().overprint = true;
let proof = RenderOptions { overprint_preview: true, ..opts };
let first = r.render(&overprinting, W, H, view(), &proof);
let change = r.changed(&overprinting, &after, &proof);
let last = Renderer::new().render(&after, W, H, view(), &proof);
patched(&mut r, &first, &after, change, &last, &proof);
assert_eq!(change, Changed::Everything, "the proofed fill changes the clipping mode");
}
#[test]
fn moving_an_object_changes_where_it_was_and_is() {
let (old, [loose, ..]) = document();
+1
View File
@@ -242,6 +242,7 @@ impl VectorcraftApp {
three_d_dialog: None,
three_d: Default::default(),
export_dialogs: Default::default(),
package_document: None,
web_export: Default::default(),
flattener_preview: Default::default(),
flatten_dialog: Default::default(),
+36 -3
View File
@@ -163,12 +163,13 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value, Strin
/// `object_keys` are the option keys of Options of Selected Object, which the dialog then records
/// with the values it opened with. OK reaches [`ok`] once the dialog's own rows accept it.
fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Option<&[&str]>) -> Result<Value, String> {
let source = app.session.active().ok_or("no document open")?;
let document = source.uid;
let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default();
let object = object_keys.is_some();
let ctx = app.ui_ctx.clone().ok_or("no window")?;
// Modal: no edit changes the document while the dialog is open, so the previews read this snapshot.
let doc = app.session.active().map(|st| st.doc.clone());
let rows = rows(ty, object, doc, crate::canvas::rulers::unit_kind(app.session.general_unit()));
let rows = rows(ty, object, Some(source.doc.clone()), crate::canvas::rulers::unit_kind(app.session.general_unit()));
let title = Label::from(title(ty, object));
let mut initial = form::fields_of(&rows, f);
// The hidden values the rows read whole stay JSON: an untagged read makes an array a list of values.
@@ -192,7 +193,15 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
}
})
.held_ok();
app.ui.brush_options = Some(host::open_held(app, dialog, ok).ok_or("no window")?);
app.ui.brush_options = Some(
host::open_held(app, dialog, move |app, result: &ParamResult| {
if !object && app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to edit its brush").into());
}
ok(app, result)
})
.ok_or("no window")?,
);
Ok(Value::Null)
}
@@ -672,3 +681,27 @@ fn confirm(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod document_tests {
use super::*;
use crate::dialogs::tests_export;
#[test]
fn brush_options_does_not_rename_the_other_drawings_brush() {
let (mut app, _) = tests_export::app(1);
open(&mut app, Some("Diamonds")).unwrap();
tests_export::set(&mut app, "name", json!("Source diamonds"));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let previous = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let error = tests_export::try_confirm(&mut app).expect_err("Brush Options must refuse the other drawing");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap(), previous);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(tests_export::fields(&app)["name"], "Source diamonds");
app.run("document.activate", json!({"index": 0})).unwrap();
tests_export::try_confirm(&mut app).unwrap();
assert_eq!(app.run("brush.get", json!({"name": "Source diamonds"})).unwrap()["name"], "Source diamonds");
}
}
+112 -13
View File
@@ -51,6 +51,8 @@ const GLOBAL: &str = "global";
pub(crate) struct Open {
/// The dialog's id on the host.
pub id: DialogId,
/// The document whose art the dialog can adjust.
document: Option<u64>,
/// The preview the dialog's values run as one interaction.
pub preview: LivePreview,
}
@@ -85,22 +87,28 @@ impl Adjust {
fn try_open(self, app: &mut VectorcraftApp) -> Result<(), String> {
const NO_WINDOW: &str = "no window to open the dialog in";
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
if let Some(old) = (self.slot)(&mut app.color_dialogs).take() {
let document = app.session.active().map(|st| st.uid);
if let Some(old) = (self.slot)(&mut app.color_dialogs).take()
&& old.document == document
{
old.preview.cancel(app);
}
let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| {
ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true)
});
let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?;
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview: LivePreview::default() });
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() });
Ok(())
}
/// OK: keeps the preview as one undo step; an `Err` keeps the dialog open with the reason.
fn commit(self, app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> {
let live = (self.slot)(&mut app.color_dialogs).as_ref().map(|open| open.preview.clone()).unwrap_or_default();
// PLAN: assumed `LivePreview::commit(self, ..)` as the contract row says; the clone keeps the record when it fails.
live.commit(app, self.cmd, (self.params)(&answer.fields))?;
let document = app.session.active().map(|st| st.uid);
let open = (self.slot)(&mut app.color_dialogs)
.as_ref()
.filter(|open| open.document == document)
.ok_or(tl!("This adjustment can only apply to the document where it was opened."))?;
open.preview.clone().commit(app, self.cmd, (self.params)(&answer.fields))?;
*(self.slot)(&mut app.color_dialogs) = None;
Ok(())
}
@@ -108,17 +116,22 @@ impl Adjust {
/// Once per frame: previews the dialog's values while its Preview box is on, and rolls the preview back once the
/// dialog is gone without OK.
pub(super) fn pump(self, app: &mut VectorcraftApp) {
let Some(Open { id, mut preview }) = (self.slot)(&mut app.color_dialogs).take() else { return };
let Some(mut open) = (self.slot)(&mut app.color_dialogs).take() else { return };
let on_its_document = app.session.active().map(|st| st.uid) == open.document;
let shown = app.dialogs().and_then(|dialogs| {
dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields()))))
dialogs.with(|host| host.get_by_id::<HostedParamDialog>(open.id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields()))))
});
match shown {
Some((on, params)) => {
if let Some((on, params)) = shown {
if on_its_document {
// `run` reports a failed preview to the status line itself.
let _ = preview.run(app, on, self.label, self.cmd, &params);
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview });
let _ = open.preview.run(app, on, self.label, self.cmd, &params);
} else {
// Switching documents rolled back the original interaction.
open.preview = LivePreview::default();
}
None => preview.cancel(app),
*(self.slot)(&mut app.color_dialogs) = Some(open);
} else if on_its_document {
open.preview.cancel(app);
}
}
}
@@ -222,7 +235,7 @@ fn rows() -> Vec<Param> {
#[cfg(test)]
mod tests {
use craft::ui::dialog::dialog_id;
use craft::ui::dialog::{HeldOk, dialog_id};
use vectorcraft_engine::Session;
use super::*;
@@ -250,6 +263,92 @@ mod tests {
host::pump(app, ctx);
}
fn two_documents(color: &str) -> (VectorcraftApp, egui::Context, [u64; 2]) {
let (mut app, ctx) = app();
let ids = [0, 1].map(|_| {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"color": color})).unwrap();
id
});
app.run("document.activate", json!({"index": 0})).unwrap();
(app, ctx, ids)
}
#[test]
fn color_adjustment_stays_in_its_opening_document_with_preview_on() {
let (mut app, ctx, [source, destination]) = two_documents("#808080");
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
let source_undo = app.session.active().unwrap().history.undo.len();
open(&mut app);
set(&app, &ctx, "r", json!(20));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#b38080");
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#808080", "another document is not previewed");
assert!(!app.session.in_interaction());
confirm(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
confirm(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted)));
assert_eq!(fill_hex(&app, source), "#b38080");
assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1);
}
#[test]
fn color_adjustment_stays_in_its_opening_document_with_preview_off() {
let (mut app, ctx, [source, destination]) = two_documents("#cc6666");
let id = dialog_id(crate::dialogs::saturate::KIND);
let dialogs = app.dialogs().unwrap();
crate::dialogs::saturate::open(&mut app);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "intensity", json!(-100)).unwrap();
host.set_json_field(&ctx, id, "preview", json!(false)).unwrap();
});
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#cc6666");
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#cc6666", "another document is not adjusted");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted)));
assert_ne!(fill_hex(&app, source), "#cc6666");
}
#[test]
fn color_adjustment_cancel_leaves_the_new_documents_interaction_intact() {
let (mut app, ctx, [source, destination]) = two_documents("#808080");
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
open(&mut app);
set(&app, &ctx, "r", json!(20));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#b38080");
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Change fill").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
dialogs.with(|host| host.cancel_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#00ff00", "cancelling the old dialog leaves the new edit intact");
assert!(app.session.in_interaction());
}
#[test]
fn previews_live_and_commits_one_undo_step() {
let (mut app, ctx) = app();
+17 -7
View File
@@ -60,7 +60,7 @@ use vectorcraft_engine::cmd::compositefonts::{EXTS, file_bytes};
use vectorcraft_text::FontDb;
use crate::VectorcraftApp;
use crate::file_asks::{Owner, ask, open_params, save};
use crate::file_asks::{Owner, ask_while, open_params, save};
use crate::font_menu::{PickerHold, family_picker, family_sets};
mod sample;
@@ -156,6 +156,8 @@ pub struct CompositeFontsDialog {
held: HeldAnswer<Vec<CompositeFont>>,
/// The file dialog a Load…, Replace… or Save… asked for, which [`pump`] takes.
file: Option<PresetFileRequest>,
/// Identifies the draft that opened a Load or Replace picker.
file_owner: Arc<()>,
/// Why the last action on the fonts or sets was refused.
refusal: Option<String>,
/// The words of the file status line, kept from the last pass for [`pump`].
@@ -255,6 +257,7 @@ impl CompositeFontsDialog {
hold,
held: HeldAnswer::new(),
file: None,
file_owner: Arc::new(()),
refusal: None,
words: None,
}
@@ -848,25 +851,32 @@ impl StackDialog for CompositeFontsDialog {
/// Runs once per frame after the shell pass: answers OK's held fonts with the command's result, and takes the
/// file dialog a Load…, Replace… or Save… asked for.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some((held, request)) = with_dialog(app, |d| (d.held.take(), d.file.take())) else { return };
let Some((held, request)) = with_dialog(app, |d| {
let held = d.held.take();
let request = d.file.take().map(|request| (request, Arc::clone(&d.file_owner)));
(held, request)
}) else {
return;
};
if let Some(fonts) = held {
// A name two fonts share or a value out of range keeps the dialog open with the reason.
let answer = app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from);
with_dialog(app, |d| d.held.answer(answer));
}
if let Some(request) = request {
ask_file(app, request);
if let Some((request, owner)) = request {
ask_file(app, request, owner);
}
}
/// Asks for the file `request` names; the answer reaches the dialog by [`with_dialog`].
fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) {
/// Asks for the file `request` names. Open answers belong to the draft that requested them.
fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()>) {
// The pick's answer comes back through the continuation, so the immediate `{pending}` value says nothing more.
match request.clone() {
PresetFileRequest::Open { purpose, filter, extensions, replace, .. } => {
let exts: Vec<&str> = extensions.iter().map(String::as_str).collect();
let pick = PickRequest::open(purpose).filter(filter, &exts);
ask(app, pick, Owner::Free, move |app, picked| load_file(app, &request, replace, &picked));
let current = move |app: &VectorcraftApp| with_dialog(app, |draft| Arc::ptr_eq(&draft.file_owner, &owner)).unwrap_or(false);
ask_while(app, pick, Owner::Free, current, move |app, picked| load_file(app, &request, replace, &picked));
}
PresetFileRequest::Save { purpose, filter, extensions, file_name, bytes, .. } => {
let exts: Vec<&str> = extensions.iter().map(String::as_str).collect();
@@ -61,6 +61,42 @@ fn names(app: &VectorcraftApp) -> Vec<String> {
app.session.active().unwrap().doc.composite_fonts.iter().map(|f| f.name.clone()).collect()
}
#[test]
fn delayed_load_and_replace_leave_the_reopened_composite_fonts_draft_alone() {
let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["New draft", "From file"]), (PresetCommands::Replace, &["From file"])];
for (command, expected_live) in choices {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
let bytes = dialog(&mut app, |d| {
d.new_font("From file".into());
file_bytes(&d.fonts).unwrap()
});
let dir = vectorcraft_testkit::TempDir::new("composite-fonts-late-picker");
let file = dir.join("picked.vccomposite");
std::fs::write(&file, bytes).unwrap();
let path = file.to_str().unwrap();
request(&mut app, command, None);
assert_eq!(picker.requests().len(), 1);
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("New draft".into()));
picker.answer(&[path]);
poll(&mut app, &ctx);
let draft_names = |app: &mut VectorcraftApp| dialog(app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::<Vec<_>>());
assert_eq!(draft_names(&mut app), ["New draft"], "the stale picker leaves the new draft alone");
request(&mut app, command, None);
assert_eq!(picker.requests().len(), 2);
picker.answer(&[path]);
poll(&mut app, &ctx);
assert_eq!(draft_names(&mut app), expected_live, "a picker opened by the new draft still works");
assert!(names(&app).is_empty(), "a picker only edits the draft");
}
}
fn steps(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
+20 -4
View File
@@ -89,6 +89,8 @@ pub(crate) struct Question(StandardPrompt);
struct Asked {
command: String,
params: Value,
/// The document that must still be active for a document-specific confirmation.
document: Option<u64>,
/// The automation roots in force when asked: the command runs under them.
scope: ScopeHandle,
/// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation.
@@ -129,6 +131,17 @@ pub(crate) struct ReplaceFiles {
/// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command`
/// with `params`.
pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) {
ask_for(app, None, message, detail, command, params);
}
/// Ask about the active document. OK is valid only while that document is active.
pub(crate) fn ask_in_document(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) {
if let Some(document) = app.session.active().map(|st| st.uid) {
ask_for(app, Some(document), message, detail, command, params);
}
}
fn ask_for(app: &mut VectorcraftApp, document: Option<u64>, message: &str, detail: &str, command: &str, params: Value) {
let Some(dialogs) = app.dialogs() else {
app.status(format!("{message} (no window to ask in)"));
return;
@@ -137,7 +150,7 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str,
if !detail.is_empty() {
prompt = prompt.paragraph(detail.to_string());
}
let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() };
let asked = Asked { command: command.to_string(), params, document, scope: ScopeHandle::capture(), automated: app.automation_asked() };
let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked);
dialogs.with(|host| host.open(Question(prompt)));
}
@@ -263,10 +276,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
};
if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::<Question>())
&& answer.choice == PromptChoice::Proceed
&& let Some(Asked { command, params, scope, automated }) = answer.take_tag::<Asked>()
&& let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params)))
&& let Some(Asked { command, params, document, scope, automated }) = answer.take_tag::<Asked>()
{
app.status(e);
if document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
app.status(tl!("This dialog was opened in a different document."));
} else if let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) {
app.status(e);
}
}
// The host opens queued messages in `enqueue` order, so the one closed is the oldest.
while dialogs.with(|host| host.take::<Message>()).is_some() {
+42 -14
View File
@@ -41,6 +41,12 @@ fn state_id() -> egui::Id {
egui::Id::unique("custom-dictionary-words")
}
#[derive(Clone)]
struct Draft {
original: Vec<String>,
words: Vec<String>,
}
/// The custom dictionary's words.
fn dictionary(app: &mut VectorcraftApp) -> Result<Vec<String>, String> {
let words = app.run(COMMAND, json!({})).map_err(|e| e.to_string())?;
@@ -65,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
];
let dialog = HostedListManager::new(COMMAND, tl!("Edit Custom Dictionary"), tl!("Entry:"), actions).entries(entries(&words)).renames(WORD);
dialogs.with(|host| host.open(dialog));
ctx.data_mut(|data| data.insert_temp(state_id(), words));
ctx.data_mut(|data| data.insert_temp(state_id(), Draft { original: words.clone(), words }));
Ok(Value::Null)
}
@@ -79,7 +85,8 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi
if choice.action == DONE {
return save(app, ctx);
}
let Some(mut words) = ctx.data(|data| data.get_temp::<Vec<String>>(state_id())) else { return };
let Some(mut draft) = ctx.data(|data| data.get_temp::<Draft>(state_id())) else { return };
let words = &mut draft.words;
match (choice.action.as_str(), choice.entry.as_deref()) {
(ADD, _) => match custom_word(&choice.name) {
Some(word) => words.push(word),
@@ -100,24 +107,20 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| {
if let Some(list) = host.get_dyn_mut(id()).and_then(|d| d.downcast_mut::<HostedListManager>()) {
list.set_entries(entries(&words));
list.set_entries(entries(words));
}
});
}
ctx.data_mut(|data| data.insert_temp(state_id(), words));
ctx.data_mut(|data| data.insert_temp(state_id(), draft));
}
/// Done: deletes the words no longer in the list and adds the new ones in one
/// `text.spelling.editDictionary`, saved once. When it can't be saved, none of it is kept: the
/// dialog stays open with the error, its list as edited, and Cancel leaves the dictionary as it was.
fn save(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(words) = ctx.data(|data| data.get_temp::<Vec<String>>(state_id())) else { return };
let orig = match dictionary(app) {
Ok(orig) => orig,
Err(e) => return app.status(e),
};
let remove: Vec<&String> = orig.iter().filter(|w| !words.contains(w)).collect();
let add: Vec<&String> = words.iter().filter(|w| !orig.contains(w)).collect();
let Some(Draft { original, words }) = ctx.data(|data| data.get_temp::<Draft>(state_id())) else { return };
let remove: Vec<&String> = original.iter().filter(|w| words.binary_search(w).is_err()).collect();
let add: Vec<&String> = words.iter().filter(|w| original.binary_search(w).is_err()).collect();
match app.run(EDIT, json!({ "remove": remove, "add": add })) {
Ok(_) => {
if let Some(dialogs) = app.dialogs() {
@@ -136,8 +139,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
if let Some(choice) = dialogs.with(|host| host.get_mut_by_id::<HostedListManager>(id()).and_then(HostedListManager::take_choice)) {
apply(app, ctx, &choice);
}
if dialogs.with(|host| host.take_by_id::<HostedListManager>(id())).is_some() {
ctx.data_mut(|data| data.remove::<Vec<String>>(state_id()));
if dialogs.with(|host| host.take_by_id::<HostedListManager>(id()).is_some() && host.get_by_id::<HostedListManager>(id()).is_none()) {
ctx.data_mut(|data| data.remove::<Draft>(state_id()));
}
}
@@ -190,7 +193,7 @@ mod tests {
/// The dialog's list, of `mine` (other tests may have their words in the dictionary meanwhile).
fn words(app: &VectorcraftApp, mine: &[&str]) -> Vec<String> {
let ctx = app.ui_ctx.clone().expect("a window");
let all = ctx.data(|data| data.get_temp::<Vec<String>>(super::state_id())).unwrap_or_default();
let all = ctx.data(|data| data.get_temp::<super::Draft>(super::state_id())).map(|draft| draft.words).unwrap_or_default();
all.into_iter().filter(|w| mine.contains(&w.as_str())).collect()
}
@@ -235,6 +238,31 @@ mod tests {
forget(&mut app, &[A, B, C]);
}
#[test]
fn done_preserves_dictionary_changes_made_after_opening() {
let _dictionary = crate::testing::custom_dictionary();
const KEPT: &str = "zqvdictoutsideadd";
const REMOVED: &str = "zqvdictoutsideremove";
let mut app = app();
forget(&mut app, &[A, B, KEPT, REMOVED]);
for word in [A, REMOVED] {
app.run("text.spelling.addWord", json!({"word": word})).unwrap();
}
let mut p = Panel::new(app, draw);
super::open(&mut p.app()).unwrap();
p.app().run("text.spelling.addWord", json!({"word": KEPT})).unwrap();
p.app().run("text.spelling.removeWord", json!({"word": REMOVED})).unwrap();
p.click(A);
p.click("Delete");
enter(&mut p, B);
p.click("Add");
p.click("Done");
let mut app = p.app();
let final_words = [A, B, KEPT, REMOVED].map(|word| has(&mut app, word));
forget(&mut app, &[A, B, KEPT, REMOVED]);
assert_eq!(final_words, [false, true, true, false]);
}
/// Done that can't be saved keeps none of the edits: the dialog stays open and Cancel leaves the
/// dictionary as it was.
#[test]
+77 -10
View File
@@ -61,6 +61,8 @@ pub(crate) struct Open {
pub id: DialogId,
/// Which of the three dialogs it is.
pub kind: &'static str,
/// The drawing that supplied the selection and defaults at opening.
document: Option<u64>,
/// The envelope the dialog previews.
pub preview: LivePreview,
// PLAN: ef.C11's `Open` has no `generation`; the same kind reopened has the same id, so the id cannot tell the held Cancel of the replaced dialog from the new one's.
@@ -68,6 +70,18 @@ pub(crate) struct Open {
pub generation: u64,
}
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
app.session.active().map(|st| st.uid) == self.document
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app) {
self.preview.cancel(app);
}
}
}
/// The dialog's title.
fn heading(kind: &str, reset: bool) -> Label {
Label::from(
@@ -172,10 +186,12 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result<Value, String> {
/// Options dialog sets the defaults for new envelopes and has nothing to preview.
fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map<String, Value>, envelope: bool) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let document = app.session.active().map(|st| st.uid);
if let Some(previous) = app.effect_dialogs.envelope.take() {
previous.preview.cancel(app);
let id = previous.id;
previous.cancel_preview(app);
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.cancel_by_id(&ctx, previous.id));
dialogs.with(|host| host.cancel_by_id(&ctx, id));
}
}
let fields = fields_of(&params(kind, &DialogFields::new()), &values);
@@ -188,28 +204,32 @@ fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map<String,
if app.effect_dialogs.envelope.as_ref().is_some_and(|open| open.generation == generation)
&& let Some(open) = app.effect_dialogs.envelope.take()
{
open.preview.cancel(app);
open.cancel_preview(app);
}
});
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| accept(app, kind, result);
let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
let id = open_held_with(app, dialog, accept, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation });
Ok(Value::Null)
}
/// OK: keeps the preview as one undo step. A refused command keeps the dialog open.
fn accept(app: &mut VectorcraftApp, kind: &'static str, result: &ParamResult) -> Result<(), String> {
let (cmd, p, _) = command(kind, &json_of(&params(kind, &result.fields), &result.fields));
let Some(Open { id, generation, preview, .. }) = app.effect_dialogs.envelope.take() else {
fn accept(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let Some(open) = app.effect_dialogs.envelope.as_ref().filter(|open| open.id == result.id) else {
return Err("the envelope dialog is gone".into());
};
if !open.on_original_drawing(app) {
return Err(tl!("Return to the original drawing to apply the envelope").into());
}
let kind = open.kind;
let (cmd, p, _) = command(kind, &json_of(&params(kind, &result.fields), &result.fields));
let Open { id, document, preview, generation, .. } = app.effect_dialogs.envelope.take().ok_or("the envelope dialog is gone")?;
match preview.commit(app, cmd, p) {
Ok(_) => Ok(()),
Err(e) => {
// The attempt ended the preview; the next pass starts a new one over the same values. Nothing to undo
// when no interaction was open, so the answer is not needed.
let _ = app.session.cancel_interaction();
app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation });
Err(e)
}
}
@@ -252,6 +272,10 @@ fn command(kind: &str, f: &Map<String, Value>) -> (&'static str, Value, &'static
/// canvas shows them. The dialog's Cancel rolls the preview back through the held record's cancel.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.effect_dialogs.envelope.take() else { return };
if !open.on_original_drawing(app) {
app.effect_dialogs.envelope = Some(open);
return;
}
let shown = app
.dialogs()
.and_then(|dialogs| dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
@@ -465,6 +489,49 @@ mod tests {
);
}
#[test]
fn envelope_warp_refuses_preview_and_ok_in_the_other_drawing() {
let (mut app, _) = app_with_rect();
open(&mut app, MAKE_WARP).unwrap();
let id = dialog(&app);
set(&app, id, "bend", json!(23));
pump(&mut app);
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap();
app.run("select.all", json!({})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
set(&app, id, "bend", json!(31));
pump(&mut app);
assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "the other drawing keeps the rectangle");
let ctx = app.ui_ctx.clone().unwrap();
host(&app, |h| h.confirm_by_id(&ctx, id));
pump(&mut app);
assert!(
matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("original drawing"))
);
assert_eq!(json_fields(&app, id)["bend"], 31.0);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
accept(&mut app, id);
let (_, node) = envelope(&app);
assert!(matches!(node.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { bend: 31.0, .. })));
}
#[test]
fn cancelling_an_envelope_dialog_keeps_the_other_drawings_active_edit() {
let (mut app, _) = app_with_rect();
open(&mut app, MAKE_WARP).unwrap();
let id = dialog(&app);
pump(&mut app);
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap();
app.run("select.all", json!({})).unwrap();
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
dismiss(&mut app, id);
assert!(app.session.in_interaction(), "the other drawing's edit stays active");
}
#[test]
fn reset_items_take_the_make_items_place_while_an_envelope_is_selected() {
let labels = |app: &VectorcraftApp| -> Vec<String> {
+26 -1
View File
@@ -154,7 +154,14 @@ fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result<HostedParamDialog, S
/// Shows `dialog`; its OK expands.
fn show(app: &mut VectorcraftApp, dialog: HostedParamDialog) -> Result<Value, String> {
crate::dialogs::host::open_held(app, dialog, ok).ok_or("no window")?;
let document = app.session.active().ok_or("no document open")?.uid;
crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to expand the artwork").into());
}
ok(app, result)
})
.ok_or("no window")?;
Ok(Value::Null)
}
@@ -285,6 +292,24 @@ mod tests {
assert!(matches!(children[1].kind, NodeKind::Mesh(_)));
}
#[test]
fn expand_keeps_its_draft_when_another_drawing_is_active() {
let mut app = app();
gradient_rectangle(&mut app);
open(&mut app).unwrap();
set(&app, "gradient", json!("mesh")).unwrap();
gradient_rectangle(&mut app);
let undo = app.session.active().unwrap().history.undo.len();
let before = app.session.active().unwrap().doc.clone();
assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(reason)) if reason.as_str().contains("original drawing")));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before));
assert_eq!(fields(&app).text("gradient"), Some("mesh"));
app.run("document.activate", json!({"index": 0})).unwrap();
ok_and_close(&mut app);
assert!(expanded_to_a_mesh(&app));
}
#[test]
fn expand_gradient_to_is_disabled_for_a_pattern_fill_alone() {
let mut app = app();
+61 -1
View File
@@ -13,7 +13,7 @@
use std::path::PathBuf;
use craft::behavior::IconId;
use craft::host::{Host, PickId, PickKind, PickRequest};
use craft::host::{Host, PickId, PickKind, PickRequest, Picked};
use craft::theme::variant::Tone;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::{Radio, RadioGroup, Rating};
@@ -111,6 +111,8 @@ enum Request {
Folder,
/// Save the fields as a template at the path the save pick answered.
SaveTo(PathBuf),
/// A browser picker returned a template larger than the import limit.
TemplateTooLarge,
/// Merge the template `source` into the fields as `mode` says.
Import { source: Info, mode: &'static str },
}
@@ -151,6 +153,15 @@ impl Templates {
&& let Some(answer) = cx.take_pick_answer(id)
{
self.ticket = None;
if let (Pick::Open, Picked::Contents(files)) = (kind, &answer) {
let Some((_, bytes)) = files.first() else { return };
if bytes.len() > vectorcraft_pdf::MAX_TEMPLATE_BYTES {
self.requests.push(Request::TemplateTooLarge);
} else {
*import = Some(source("dataBase64", vectorcraft_format::base64_encode(bytes)));
}
return;
}
let Some(path) = answer.first_path() else { return };
match kind {
Pick::Open => *import = Some(source("path", path.to_string_lossy().into_owned())),
@@ -602,6 +613,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Some(fields) => save_template(app, path, fields),
None => Ok(()),
},
Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()),
Request::Import { source, mode } => {
dialogs.with(|host| host.get_mut_by_id::<FileInfoDialog>(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(()))
}
@@ -767,6 +779,54 @@ mod tests {
assert_eq!(st.history.undo.len(), 1);
}
#[test]
fn browser_picked_templates_enter_the_merge_choice_and_edit_only_the_draft() {
use std::sync::Arc;
use craft::host::{Files, PickRequest, Picked, ScriptedFiles};
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
description: Some("À l’affiche 版".into()),
rating: Some(3),
..Default::default()
});
let utf16 = std::iter::once(0xfeff).chain(template.encode_utf16()).flat_map(u16::to_le_bytes).collect::<Vec<_>>();
for bytes in [template.into_bytes(), utf16] {
let mut app = windowed();
let files = Arc::new(ScriptedFiles::held());
crate::tests::picks::install_files(&mut app, files.clone());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "author", json!("Ada")).unwrap();
let ticket = files.pick(PickRequest::open(super::PURPOSE));
with_dialog(&app, |d| d.templates.ticket = Some((ticket, super::Pick::Open))).unwrap();
assert!(files.answer(Picked::Contents(vec![("Studio.xmp".into(), bytes)])).is_some());
let ctx = app.ui_ctx.clone().unwrap();
for _ in 0..3 {
crate::tests::synthetic::key_frame(&mut app, &ctx, Vec::new());
}
with_dialog(&app, |d| {
assert!(d.templates.ticket.is_none(), "the File Info form consumed the picker answer");
assert!(d.import.is_some(), "a browser-selected template reaches the merge choice");
assert!(super::choose_mode(&mut d.import_mode, "append"));
super::ask_import(&mut d.templates, &d.import, d.import_mode);
})
.unwrap();
super::pump(&mut app, &ctx);
let fields = with_dialog(&app, |d| d.filed_fields()).unwrap();
assert_eq!(
(fields["author"].clone(), fields["description"].clone(), fields["rating"].clone()),
(json!("Ada"), json!("À l’affiche 版"), json!(3))
);
assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "the template updates the draft before OK");
assert!(press_ok(&mut app));
let st = app.session.active().unwrap();
assert_eq!(st.doc.metadata.description, "À l’affiche 版");
assert_eq!(st.history.undo.len(), 1);
}
}
#[test]
fn ok_waits_for_the_merge_choice_of_a_template_being_imported() {
let mut app = windowed();
+2 -1
View File
@@ -311,10 +311,11 @@ pub(super) fn from_missing_links(
folder: &str,
) -> Result<(), String> {
let mut find = dialog(app, missing.clone(), modified.clone(), true)?;
let document = find["document"].as_u64().ok_or("no document open")?;
find.insert("notes".into(), json!(notes));
start_search(app, &mut find, folder)?;
open(app, find)?;
app.link_asks = Some(LinkAsk { missing, modified, notes, back: true });
app.link_asks = Some(LinkAsk { document, missing, modified, notes, back: true });
Ok(())
}
+76 -11
View File
@@ -16,6 +16,8 @@
//! (`ObjectDialogs::flare`), not fields.
// PLAN: the `craft_ui` paths and `LivePreview`'s home (`form`) are assumed; `general_lengths` is cv.B5b's.
use std::sync::Arc;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamResult};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
@@ -39,6 +41,8 @@ pub const KIND: &str = "flareOptions";
pub(crate) struct Open {
/// The hosted dialog.
id: DialogId,
opening: Arc<()>,
document: Option<u64>,
/// Where a click opened it, to draw a flare there on OK.
click: Option<Point>,
/// The selected flares (ids) and the settings the dialog opened with, to change them on OK.
@@ -47,6 +51,27 @@ pub(crate) struct Open {
preview: Option<LivePreview>,
}
const PREVIEW_LABEL: &str = "Flare";
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
self.preview.is_none() || app.session.active().map(|st| st.uid) == self.document
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app)
&& !other_preview(app)
&& let Some(preview) = self.preview
{
preview.cancel(app);
}
}
}
fn other_preview(app: &VectorcraftApp) -> bool {
app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL)
}
/// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a
/// flare there on OK. Opened without a click while flares are selected, they show the first one's
/// settings, to change the selected flares on OK.
@@ -91,24 +116,25 @@ pub fn open(app: &mut VectorcraftApp, at: Option<Point>) -> Value {
return Value::Null;
};
// An open the host replaces leaves its preview behind unless it is rolled back here.
if let Some(old) = app.object_dialogs.flare.take()
&& let Some(preview) = old.preview
{
preview.cancel(app);
if let Some(old) = app.object_dialogs.flare.take() {
old.cancel_preview(app);
}
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.object_dialogs.flare.take()
&& let Some(preview) = open.preview
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(move |app| {
if app.object_dialogs.flare.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.flare.take()
{
preview.cancel(app);
open.cancel_preview(app);
}
});
let held = HeldOptions { parent: None, cancel: Some(cancel) };
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone())
});
let document = app.session.active().map(|st| st.uid);
match open_held_with(app, dialog, ok, held) {
Some(id) => app.object_dialogs.flare = Some(Open { id, click: at, edit, preview: previews.then(LivePreview::default) }),
Some(id) => app.object_dialogs.flare = Some(Open { id, opening, document, click: at, edit, preview: previews.then(LivePreview::default) }),
None => app.status("no window"),
}
json!({ "dialog": KIND })
@@ -242,15 +268,27 @@ fn option_values(fields: &Map<String, Value>) -> Map<String, Value> {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
// PLAN: registered in hub-w2's pump file (wg.A18), one line.
let Some(mut open) = app.object_dialogs.flare.take() else { return };
if !open.on_original_drawing(app) {
app.object_dialogs.flare = Some(open);
return;
}
if let Some(mut preview) = open.preview.take() {
let state = app
.dialogs()
.and_then(|host| host.with(|host| host.get_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
if let Some((previewing, fields)) = state {
let values = form::json_of(&params(general_lengths(app)), &fields);
if let Some((cmd, params)) = command(app, &open, &values) {
if previewing
&& other_preview(app)
&& let Err(e) = app.keep_typing()
{
app.status(e);
}
if !other_preview(app)
&& let Some((cmd, params)) = command(app, &open, &values)
{
// The preview reports its own failures on the status line.
let _ = preview.run(app, previewing, "Flare", &cmd, &params);
let _ = preview.run(app, previewing, PREVIEW_LABEL, &cmd, &params);
}
}
open.preview = Some(preview);
@@ -261,6 +299,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the
/// selected flares, draw them again with the settings changed, leaving the tool's options.
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let open = app.object_dialogs.flare.as_ref().ok_or("the Flare Tool Options dialog is gone")?;
if !open.on_original_drawing(app) {
return Err(tl!("Return to the original drawing to place or edit the flare").into());
}
if open.preview.is_some() && other_preview(app) {
app.keep_typing()?;
if other_preview(app) {
return Err(tl!("Finish the current edit before drawing the flare").into());
}
}
let fields = form::json_of(&params(general_lengths(app)), &result.fields);
let accepted = accept(app, &fields);
if accepted.is_ok() {
@@ -430,6 +478,23 @@ mod tests {
assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}");
}
#[test]
fn a_pending_flare_click_waits_for_its_original_drawing() {
let mut app = app();
open(&mut app, Some(Point::new(100.0, 110.0)));
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len();
pump(&mut app);
assert_eq!(count(&app), 0, "the other drawing never shows the flare preview");
press_ok(&mut app);
assert_eq!(count(&app), 0, "the other drawing never keeps the flare");
assert!(app.object_dialogs.flare.is_some());
app.run("document.activate", json!({"index": 0})).unwrap();
press_ok(&mut app);
assert_eq!(count(&app), 1);
assert!(!flare_parts(&app).is_empty());
}
/// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it
/// again with the settings changed, as one undo step, leaving the tool's options.
#[test]
+110 -20
View File
@@ -4,6 +4,8 @@
//!
//! Fields: `reduction`, `colors`, `dither`, `ditherAmount` and `preview`.
use std::sync::Arc;
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::UnitKind;
@@ -21,6 +23,28 @@ const CMD: &str = "edit.colors.toIndexed";
/// The undo step a preview and OK make.
const PREVIEW_LABEL: &str = "Convert to Indexed Color";
pub(crate) struct Open {
document: u64,
opening: Arc<()>,
preview: LivePreview,
}
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| st.uid == self.document)
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app) && !other_preview(app) {
self.preview.cancel(app);
}
}
}
fn other_preview(app: &VectorcraftApp) -> bool {
app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL)
}
/// The reductions besides those of a PNG-8 export, as (value, label).
const MORE_REDUCTIONS: [(&str, &str); 2] = [("uniform", "Uniform"), ("document", "Document Swatches")];
@@ -62,38 +86,71 @@ pub fn open(app: &mut VectorcraftApp) {
app.status("no window".to_string());
return;
};
let Some(document) = app.session.active().map(|st| st.uid) else {
app.status(tl!("Open a drawing to convert its images"));
return;
};
if let Some(old) = app.object_dialogs.indexed.take() {
old.cancel_preview(app);
}
let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build);
app.object_dialogs.indexed = Some(LivePreview::default());
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let ok = |app: &mut VectorcraftApp, r: &ParamResult| {
let preview = app.object_dialogs.indexed.take().unwrap_or_default();
let done = preview.commit(app, CMD, params(&r.fields)).map(|_| ());
let open = app.object_dialogs.indexed.as_ref().ok_or("the Indexed Color dialog is gone")?;
if !open.on_original_drawing(app) {
return Err(tl!("Return to the original drawing to convert its images").into());
}
if other_preview(app) {
app.keep_typing()?;
if other_preview(app) {
return Err(tl!("Finish the current edit before converting its images").into());
}
}
let open = app.object_dialogs.indexed.take().ok_or("the Indexed Color dialog is gone")?;
let done = open.preview.commit(app, CMD, params(&r.fields)).map(|_| ());
if done.is_err() {
// The dialog stays open and previews again.
app.object_dialogs.indexed = Some(LivePreview::default());
app.object_dialogs.indexed = Some(Open { preview: LivePreview::default(), ..open });
}
done
};
let cancel = Box::new(|app: &mut VectorcraftApp| {
if let Some(preview) = app.object_dialogs.indexed.take() {
preview.cancel(app);
let cancel = Box::new(move |app: &mut VectorcraftApp| {
if app.object_dialogs.indexed.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.indexed.take()
{
open.cancel_preview(app);
}
});
if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_none() {
app.object_dialogs.indexed = None;
if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_some() {
app.object_dialogs.indexed = Some(Open { document, opening, preview: LivePreview::default() });
} else {
app.status("no window".to_string());
}
}
/// Each frame: show the dialog's values on the canvas while its Preview box is on.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut preview) = app.object_dialogs.indexed.take() else { return };
let Some(mut open) = app.object_dialogs.indexed.take() else { return };
if !open.on_original_drawing(app) {
app.object_dialogs.indexed = Some(open);
return;
}
let shown = app
.dialogs()
.and_then(|h| h.with(|host| host.get_by_id::<HostedParamDialog>(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields())))));
if let Some((on, p)) = &shown {
let _ = preview.run(app, *on, PREVIEW_LABEL, CMD, p);
if *on
&& other_preview(app)
&& let Err(e) = app.keep_typing()
{
app.status(e);
}
if !other_preview(app) {
let _ = open.preview.run(app, *on, PREVIEW_LABEL, CMD, p);
}
}
app.object_dialogs.indexed = Some(preview);
app.object_dialogs.indexed = Some(open);
}
/// Whether reduction `r` takes a number of colors.
@@ -125,9 +182,7 @@ mod tests {
use super::*;
use vectorcraft_engine::Session;
#[test]
fn commits_the_chosen_palette_as_one_step() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
fn add_raster(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let img = craft_image_codecs::Image::from_raw(
2,
@@ -138,8 +193,7 @@ mod tests {
)
.unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let id = app
.session
app.session
.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
@@ -156,7 +210,19 @@ mod tests {
sel.set([id]);
Ok(id)
})
.unwrap();
.unwrap()
}
fn palette(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> &vectorcraft_doc::ImageBlob {
let st = app.session.doc().unwrap();
let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") };
&st.doc.images[&im.key]
}
#[test]
fn commits_the_chosen_palette_as_one_step() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let id = add_raster(&mut app);
let undo = app.session.doc().unwrap().history.undo.len();
app.run("ui.indexedColorDialog", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
@@ -170,9 +236,33 @@ mod tests {
crate::dialogs::host::pump(&mut app, &ctx);
let st = app.session.doc().unwrap();
assert_eq!(st.history.undo.len(), undo + 1);
let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") };
let blob = &st.doc.images[&im.key];
let blob = palette(&app, id);
assert!(blob.indexed_png());
assert_eq!(blob.rgba().unwrap().2, [0, 0, 0, 255, 0, 0, 0, 255], "black and white only");
}
#[test]
fn indexed_color_preview_and_ok_leave_the_other_drawings_pixels_unchanged() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let source = add_raster(&mut app);
open(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
let id = dialog_id(KIND);
host.with(|h| h.set_json_field(&ctx, id, "reduction", json!("blackWhite"))).unwrap();
let other = add_raster(&mut app);
host.with(|h| h.set_json_field(&ctx, id, "dither", json!("none"))).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!palette(&app, other).indexed_png(), "the other drawing does not show the preview");
host.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!palette(&app, other).indexed_png(), "the other drawing does not keep the preview");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
host.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(palette(&app, source).indexed_png());
}
}
+120 -18
View File
@@ -26,6 +26,7 @@ use crate::VectorcraftApp;
pub const KIND: &str = "livePaintGapOptions";
const CMD: &str = "livePaint.gapOptions";
const WRONG_DOCUMENT: &str = "Gap Options can only be applied in the document this dialog was opened for.";
/// The undo step the preview and OK make.
const PREVIEW_LABEL: &str = "Gap Options";
@@ -51,20 +52,31 @@ pub(super) static SPEC: OptionSpec = OptionSpec {
pub(crate) struct Open {
/// The dialog the preview belongs to.
pub id: DialogId,
/// The document that owns the preview interaction.
document: u64,
/// The preview the options run as.
pub preview: LivePreview,
}
impl Open {
fn cancel(self, app: &mut VectorcraftApp) {
if app.session.active().is_some_and(|active| active.uid == self.document) {
self.preview.cancel(app);
}
}
}
/// Open Gap Options on the selected Live Paint groups, filled in from the first one's options.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let groups: Vec<u64> = app
.session
.doc()
.map(|d| {
let doc = &d.doc;
d.selection.objects.iter().filter(|id| doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)).map(|id| id.0).collect()
})
.unwrap_or_default();
let active = app.session.active().ok_or("select a Live Paint group")?;
let document = active.uid;
let groups: Vec<u64> = active
.selection
.objects
.iter()
.filter(|id| active.doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint))
.map(|id| id.0)
.collect();
let Some(&first) = groups.first() else { return Err("select a Live Paint group".into()) };
let info = app.session.execute("livePaint.info", &json!({ "group": first })).map_err(|e| e.to_string())?;
let o = &info["gapOptions"];
@@ -75,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields =
[("detect", o["detect"].clone()), ("size", json!(size)), ("custom", custom), ("color", o["color"].clone()), ("closeGaps", json!(false))];
let values = Map::from_iter(fields.map(|(key, value)| (key.to_owned(), value)));
option_form::open(app, &SPEC, values, json!({ "ids": groups })).ok_or("no window")?;
option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document })).ok_or("no window")?;
Ok(Value::Null)
}
fn original_document(app: &VectorcraftApp, extra: &Value) -> Option<u64> {
let document = extra["document"].as_u64()?;
app.session.active().filter(|active| active.uid == document).map(|_| document)
}
/// `livePaint.gapOptions` parameters from the values and the groups in `extra`.
fn params(values: &Map<String, Value>, extra: &Value) -> Value {
let size = match values.get("size").and_then(Value::as_str) {
@@ -111,24 +128,43 @@ fn body(ui: &mut egui::Ui, rows: &mut Rows<'_>) {
/// OK: keep the previewed options as one undo step; with no preview running they run as one.
fn run(app: &mut VectorcraftApp, values: &Map<String, Value>, extra: &Value) -> Result<Value, String> {
let preview = app.object_dialogs.gaps.take().map_or_else(LivePreview::default, |open| open.preview);
let document = original_document(app, extra).ok_or_else(|| tl!(WRONG_DOCUMENT).to_owned())?;
let preview = app.object_dialogs.gaps.take().filter(|open| open.document == document).map_or_else(LivePreview::default, |open| open.preview);
preview.commit(app, CMD, params(values, extra))
}
/// The dialog closed without OK: roll the preview back.
fn cancelled(app: &mut VectorcraftApp) {
if let Some(open) = app.object_dialogs.gaps.take() {
open.preview.cancel(app);
open.cancel(app);
}
}
/// Runs the open Gap Options' preview as its options stand, once per frame after the shell pass: with Preview on the
/// options apply to the groups, off they are rolled back; the gaps a new preview finds are kept for [`overlays`].
/// Nothing runs while an OK waits for its answer, which keeps or refuses the preview that is running.
pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let shown = dialogs.with(|host| {
let form = host.get::<OptionForm>().filter(|form| form.is(KIND))?;
let form = host.get_mut::<OptionForm>().filter(|form| form.is(KIND))?;
let source = form.extra["document"].as_u64()?;
if !app.session.documents().iter().any(|doc| doc.uid == source) {
host.cancel::<OptionForm>(ctx);
return None;
}
let document = original_document(app, &form.extra);
let paused = document.is_none();
if form.preview_paused != paused {
form.preview_paused = paused;
if !paused && form.held.refusal().is_some_and(|(reason, _)| reason.as_str() == tl!(WRONG_DOCUMENT)) {
form.held.clear_refusal();
}
ctx.request_repaint();
}
let Some(document) = document else {
form.previewed = Value::Null;
return None;
};
if !form.held.state().is_none_or(|state| matches!(state, HeldOk::Refused(_))) {
return None;
}
@@ -137,17 +173,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
if form.values.get("color").and_then(Value::as_str).is_some_and(has_alpha) {
params["color"] = Value::Null;
}
Some((form.id(), params, form.preview))
Some((form.id(), document, params, form.preview))
});
let Some((id, params, on)) = shown else { return };
let Some((id, document, params, on)) = shown else { return };
// A preview of another dialog is rolled back before this one starts its own.
let mut open = match app.object_dialogs.gaps.take() {
Some(open) if open.id == id => open,
Some(open) if open.id == id && open.document == document => open,
stale => {
if let Some(stale) = stale {
stale.preview.cancel(app);
stale.cancel(app);
}
Open { id, preview: LivePreview::default() }
Open { id, document, preview: LivePreview::default() }
}
};
let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, &params);
@@ -177,6 +213,7 @@ pub(crate) fn overlays(app: &VectorcraftApp) -> Vec<Overlay> {
let Some(dialogs) = app.dialogs() else { return vec![] };
let shown = dialogs.with(|host| {
let form = host.get::<OptionForm>().filter(|form| form.is(KIND) && form.preview)?;
original_document(app, &form.extra)?;
Some((form.previewed.clone(), form.values.get("color").and_then(Value::as_str)?.to_owned()))
});
let Some((gaps, color)) = shown else { return vec![] };
@@ -236,6 +273,71 @@ mod tests {
app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap()
}
fn open_with_matching_groups(app: &mut VectorcraftApp) -> u64 {
let group = gapped_group(app);
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
assert_eq!(gapped_group(app), group, "the new document reuses the group ID");
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("ui.livePaintGapOptions", json!({})).unwrap();
set(app, "detect", json!(true)).unwrap();
group
}
#[test]
fn gap_confirmation_stays_with_its_document() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
assert!(!press_ok(&mut app), "the unrelated group cannot take the edit");
assert_eq!(options(&app, group), GapOptions::default());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
pump_all(&mut app);
assert!(held(&app).is_none(), "the stale refusal clears on the original tab");
assert!(press_ok(&mut app), "the original group's edit can be retried");
assert!(options(&app, group).detect);
}
#[test]
fn closing_the_original_document_dismisses_gap_options() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
assert!(app.session.close_document(0));
pump_all(&mut app);
assert!(!is_open(&app));
assert_eq!(options(&app, group), GapOptions::default());
}
#[test]
fn gap_preview_disappears_in_another_document_and_resumes_on_return() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
set(&app, "preview", json!(true)).unwrap();
pump_all(&mut app);
assert!(options(&app, group).detect);
assert!(!overlays(&app).is_empty());
app.run("document.activate", json!({"index": 1})).unwrap();
let unrelated_overlays = overlays(&app);
pump_all(&mut app);
let paused = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::<OptionForm>().unwrap().preview_paused);
assert!(paused(&app));
assert_eq!(fields(&app)["preview"], json!(true));
assert_eq!(options(&app, group), GapOptions::default());
assert!(!app.session.in_interaction());
assert!(unrelated_overlays.is_empty());
assert!(overlays(&app).is_empty());
app.run("document.activate", json!({"index": 0})).unwrap();
pump_all(&mut app);
assert!(!paused(&app));
assert!(options(&app, group).detect);
assert!(!overlays(&app).is_empty());
cancel(&mut app);
assert_eq!(options(&app, group), GapOptions::default());
}
#[test]
fn the_menu_item_opens_gap_options_which_preview_the_gaps_and_ok_keeps_them() {
let mut app = app();
+96 -5
View File
@@ -105,8 +105,10 @@ impl<W: Copy> Asked<W> {
/// What the questions about one open's linked files keep between their dialogs: the files still
/// asked about, the modified images to offer for update afterwards and the open's notes.
#[derive(Clone, Debug, Default, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LinkAsk {
/// The document that owns the linked-file IDs.
pub(crate) document: u64,
/// The missing files still asked about (`[{name, path, ids}]`), the next one first.
pub(crate) missing: Vec<Value>,
/// The ids of the images whose file was modified.
@@ -353,7 +355,11 @@ fn questions_for(app: &VectorcraftApp, r: &Value, web: bool) -> (Vec<String>, Ve
/// Opens the dialog about the first of `missing`, keeping what the questions after it need
/// ([`LinkAsk`]). A window that isn't up has nothing to show a question in.
fn open(app: &mut VectorcraftApp, missing: Vec<Value>, modified: Vec<Value>, notes: &[String]) {
let ask = LinkAsk { missing, modified, notes: notes.to_vec(), back: false };
let Some(document) = app.session.active().map(|st| st.uid) else { return };
open_ask(app, LinkAsk { document, missing, modified, notes: notes.to_vec(), back: false });
}
fn open_ask(app: &mut VectorcraftApp, ask: LinkAsk) {
let Some(dialogs) = app.dialogs() else { return };
let dialog = MissingLinksDialog::new(app, ask.clone());
app.link_asks = Some(ask);
@@ -436,9 +442,16 @@ pub(crate) fn changed_on_disk_status(n: usize) -> String {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some(result) = dialogs.with(|h| h.take::<MissingLinksDialog>()) else { return };
let ask = app.link_asks.take().unwrap_or_default();
let Some(ask) = app.link_asks.take() else { return };
let Some(answer) = result.ok() else { return show_notes_again(app, &ask) };
let LinkAsk { missing, modified, notes, .. } = ask;
if app.session.active().is_none_or(|st| st.uid != ask.document) {
app.status(tl!("This dialog was opened in a different document."));
if app.session.documents().iter().any(|st| st.uid == ask.document) {
open_ask(app, ask);
}
return;
}
let LinkAsk { document, missing, modified, notes, .. } = ask;
let done = match answer {
MissingLinksAnswer::FindInFolder(folder) => {
super::find_links::from_missing_links(app, missing.clone(), modified.clone(), notes.clone(), &folder).map(|()| None)
@@ -450,7 +463,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Ok(None) => {}
Err(e) => {
app.status(e);
open(app, missing, modified, &notes);
open_ask(app, LinkAsk { document, missing, modified, notes, back: false });
}
}
}
@@ -587,6 +600,84 @@ mod tests {
json!({ "name": format!("{n}.png"), "path": format!("/gone/{n}.png"), "ids": [n] })
}
fn check_replacing_a_missing_file_stays_in_the_opening_drawing(native_picker: bool) {
let name = if native_picker { "different-drawing-picker" } else { "different-drawing-path" };
let (mut app, dir, _) = opened_without_links(name);
let missing = drive::fields::<MissingLinksDialog>(&app)["missing"][0].clone();
let id = missing["ids"][0].as_u64().unwrap();
let picker = crate::tests::picks::scripted(&mut app);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let mut second_ids = Vec::new();
for name in ["second-one.png", "second-two.png"] {
let path = dir.join(name);
std::fs::write(&path, png([0, 200, 0])).unwrap();
let place = app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap();
second_ids.push(place["ids"][0].as_u64().unwrap());
}
assert!(second_ids.contains(&id), "the same ID refers to a different linked file");
let params = json!({"ids": [id]});
let original_path = app.run("links.check", params.clone()).unwrap()["links"][0]["path"].clone();
app.run("document.activate", json!({"index": 0})).unwrap();
if native_picker {
drive::answer::<MissingLinksDialog>(&mut app, &[], true);
assert_eq!(picker.requests().len(), 1);
}
app.run("document.activate", json!({"index": 1})).unwrap();
let replacement = dir.join("replacement.png");
std::fs::write(&replacement, png([0, 0, 200])).unwrap();
let replacement = replacement.to_string_lossy();
if native_picker {
picker.answer(&[&replacement]);
drive::frame(&mut app);
drive::pump(&mut app);
} else {
drive::answer::<MissingLinksDialog>(&mut app, &[("path", json!(replacement))], true);
}
assert_eq!(app.session.active_index(), Some(1));
let after = app.run("links.check", params).unwrap()["links"][0]["path"].clone();
assert_eq!(after, original_path, "the second drawing must keep its original link");
assert_eq!(app.ui.status, "This dialog was opened in a different document.");
assert_eq!(drive::fields::<MissingLinksDialog>(&app)["missing"][0], missing);
app.run("document.activate", json!({"index": 0})).unwrap();
drive::answer::<MissingLinksDialog>(&mut app, &[("path", json!(replacement))], true);
assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 1, "the opening drawing can still replace its file");
assert_eq!(asked_name(&app), "b.png", "the remaining missing file is still offered");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn typed_missing_file_replacement_keeps_the_other_drawing_untouched() {
check_replacing_a_missing_file_stays_in_the_opening_drawing(false);
}
#[test]
fn delayed_missing_file_picker_keeps_the_other_drawing_untouched() {
check_replacing_a_missing_file_stays_in_the_opening_drawing(true);
}
#[test]
fn a_missing_file_folder_search_starts_only_in_the_opening_drawing() {
use crate::dialogs::find_links::FindLinksDialog;
let (mut app, dir, _) = opened_without_links("different-drawing-search");
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let folder = [("searchFolder", json!(dir.to_string_lossy()))];
drive::answer::<MissingLinksDialog>(&mut app, &folder, true);
assert!(drive::is_open::<MissingLinksDialog>(&app));
assert!(!drive::is_open::<FindLinksDialog>(&app));
assert_eq!(app.session.active_index(), Some(1));
app.run("document.activate", json!({"index": 0})).unwrap();
drive::answer::<MissingLinksDialog>(&mut app, &folder, true);
assert!(drive::is_open::<FindLinksDialog>(&app));
assert_eq!(app.session.active_index(), Some(0));
drive::answer::<FindLinksDialog>(&mut app, &[], false);
let _ = std::fs::remove_dir_all(dir);
}
/// Replace relinks the first file and asks about the next; Ignore keeps its preview.
#[test]
fn opening_without_linked_files_asks_to_replace_or_ignore_each() {
+27 -1
View File
@@ -25,6 +25,7 @@ const TYPES: [&str; 5] = ["calligraphic", "scatter", "art", "bristle", "pattern"
/// It starts on Art when there is art, and it starts on Calligraphic otherwise.
pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let document = st.uid;
let art = match &ids {
Some(ids) => ids.as_array().is_some_and(|a| !a.is_empty()),
None => !st.selection.is_empty(),
@@ -36,7 +37,13 @@ pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> Result<Value, Strin
// PLAN: `HostedParamDialog::new` takes (ctx, key, fields, build); the sheet's (KIND, title, build) has no such form.
let dialog =
HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), rows.clone()).values(Bind::bound(f))).held_ok();
host::open_held(app, dialog, move |app, answer| confirm(app, &answer.fields, ids.clone())).ok_or("no window")?;
host::open_held(app, dialog, move |app, answer| {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to make the brush").into());
}
confirm(app, &answer.fields, ids.clone())
})
.ok_or("no window")?;
Ok(Value::Null)
}
@@ -156,6 +163,25 @@ mod tests {
assert_eq!((&def["type"], &def["size"]), (&json!("calligraphic"), &json!(9.0)));
}
#[test]
fn the_new_brush_type_chooser_waits_for_its_source_drawing() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
app.run("ui.newBrush", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let id = craft::ui::dialog::dialog_id(KIND);
app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "type", json!("scatter"))).unwrap();
app.run("file.new", json!({"width": 500, "height": 400})).unwrap();
app.run("shape.ellipse", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let error = super::super::tests_export::try_confirm(&mut app).expect_err("cannot take another drawing's artwork");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(open_fields(&app).text("type"), Some("scatter"));
app.run("document.activate", json!({"index": 0})).unwrap();
press_ok(&mut app, json!({}));
assert_eq!(open_fields(&app).text("__type"), Some("scatter"));
}
/// The new brush takes the art its Brush Options opened with: changing or clearing the
/// selection while the dialog is open does not change the art, and OK still makes the brush.
#[test]
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) struct ObjectDialogs {
/// The open Blend Options dialog's live preview.
pub blend: Option<LivePreview>,
/// The open Indexed Color dialog's live preview.
pub indexed: Option<LivePreview>,
pub indexed: Option<indexed_color::Open>,
/// The open Gap Options dialog's live preview.
pub gaps: Option<live_paint_gaps::Open>,
/// The Properties section's pending colour pick: dialog id, field key and target dimension.
+12 -2
View File
@@ -7,7 +7,7 @@ use std::ops::RangeInclusive;
use craft::theme::variant::Tone;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::Row;
@@ -175,6 +175,8 @@ pub(crate) struct OptionForm {
lengths: LengthUnits,
/// The Preview check box.
pub(super) preview: bool,
/// The current document does not own this dialog's preview.
pub(super) preview_paused: bool,
/// Whether the dialog's container is open.
open: bool,
/// The OK the dialog filed for [`pump`] to answer.
@@ -202,6 +204,7 @@ pub(super) fn open(app: &mut VectorcraftApp, spec: &'static OptionSpec, values:
extra,
lengths,
preview: false,
preview_paused: false,
open: true,
held: HeldAnswer::new(),
requests: HostRequests::new(),
@@ -249,8 +252,9 @@ impl StackDialog for OptionForm {
// The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing.
let finish = self.held.is_accepted() && !measuring;
let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
let OptionForm { spec, values, lengths, preview, open, held, requests, .. } = self;
let OptionForm { spec, values, lengths, preview, preview_paused, open, held, requests, .. } = self;
let (spec, lengths) = (*spec, *lengths);
let show_pause = *preview && *preview_paused;
let title = (spec.title)();
let refusal = held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone()));
let mut form = FormDialog::new(word(&title), Bind::bound(&mut *values))
@@ -274,6 +278,12 @@ impl StackDialog for OptionForm {
if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) {
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
}
if show_pause {
Notice::new(Tone::Info, tl!("Preview is paused. Return to the document this dialog was opened for.").to_owned())
.layout(NoticeLayout::Inline)
.announce(Politeness::Polite)
.show(ui);
}
if finish {
form.request_close_as(CloseReason::Activated);
}
+22 -4
View File
@@ -20,7 +20,7 @@ use craft::ui::runtime::requests::PathKind;
use serde_json::{Value, json};
use vectorcraft_engine::EngineError;
use super::confirm::ask;
use super::confirm::{ask, ask_in_document};
use crate::background::{self, Writer};
use crate::{VectorcraftApp, file_asks, io};
@@ -46,7 +46,7 @@ fn downloads(app: &VectorcraftApp) -> bool {
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let st = app.session.active().ok_or("no document")?;
let Some(path) = st.path.clone() else {
ask(
ask_in_document(
app,
tl!("Save the document first?"),
tl!("Package collects a saved document with its linked files and fonts."),
@@ -55,6 +55,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
);
return Ok(Value::Null);
};
let document = st.uid;
let p = std::path::Path::new(&path);
let stem = p.file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
@@ -73,6 +74,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.footer_note(Label::from(tl!("Fonts whose licence doesn't allow embedding are not copied.")))
});
crate::dialogs::host::open_held(app, dialog, |app, answer| confirm(app, &answer.fields).map(|_| ())).ok_or("no window")?;
app.package_document = Some(document);
Ok(Value::Null)
}
@@ -96,13 +98,27 @@ fn params(web: bool) -> Vec<Param> {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let id = dialog_id(KEY);
let Some(request) = dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).and_then(HostedParamDialog::pick_path)) else { return };
file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path);
let Some(request) = dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).map(HostedParamDialog::pick_path)) else {
app.package_document = None;
return;
};
if let Some(request) = request {
file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path);
}
}
fn require_package_document(app: &VectorcraftApp, document: u64) -> Result<(), String> {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Package can only save and collect the document where it was opened.").to_owned());
}
Ok(())
}
/// What OK does: save a dirty document, then write the package (on the worker with Background Export on) or
/// download it. `Err` refuses the OK and keeps the dialog open; the reply says whether the package is in the background.
pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
let document = app.package_document.ok_or("no Package dialog open")?;
require_package_document(app, document)?;
let text = |key: &str| fields.text(key).unwrap_or_default();
let mut params = json!({ "folder": text("folder"), "name": text("name") });
for (key, _) in OPTIONS {
@@ -144,6 +160,8 @@ pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result
return r;
}
}
// A completed background job may have changed the active document while Package waited.
require_package_document(app, document)?;
let package = app.session.prepare_package(&params).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?;
let label = format!("Packaging {}", text("name"));
let later = Rc::new(Cell::new(false));
@@ -609,7 +609,7 @@ fn tabs_buttons(unit: Unit) -> Param {
let (rows, _, _) = tab_rows(fields);
let can_add = new_tab_position(&rows, unit).is_some();
let (mut add, mut delete, mut clear) = (false, false, false);
let line = Row::new().show(ui, |ui, _| {
let line = Row::new().wrap(true).show(ui, |ui, _| {
add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui));
delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui));
clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui));
@@ -348,6 +348,42 @@ fn tab_rows(app: &VectorcraftApp) -> Vec<Value> {
fields(app)["tabs"].as_array().cloned().unwrap_or_default()
}
#[test]
fn clear_all_tabs_can_be_clicked_in_a_narrow_viewport() {
use egui::accesskit::Role;
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
for width in [800.0, 540.0] {
let mut app = app();
app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": [{"position": 36.0}, {"position": 72.0}]}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 500.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
};
frame(&mut app, vec![]);
open_tabs(&mut app, "Body");
for _ in 0..5 {
frame(&mut app, vec![]);
}
let out = frame(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let clear = nodes.iter().find(|(_, node)| node.role() == Role::Button && node.label() == Some("Clear All Tabs")).unwrap();
let bounds = clear.1.bounds().unwrap();
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
assert_eq!(tab_rows(&app).len(), 2);
frame(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(&mut app, vec![]);
assert!(tab_rows(&app).is_empty(), "Clear All Tabs at {bounds:?} was not reachable in a {width}-point viewport");
}
}
/// Tabs shows a style's stops in the General unit with their alignment, leader and Align On
/// character; a stop left as it was keeps its position exactly, a changed one is read in the unit,
/// and the stops are stored sorted by position. Add puts a left stop half an inch past the furthest
+180 -32
View File
@@ -3,6 +3,8 @@
//! Every dialog is a held parameter dialog: its OK is the closure given to `open_held`, a refusal keeps it open with
//! the reason, and [`pump`] only runs the live preview of the kinds that have one.
use std::sync::{Arc, Weak};
// PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and
// runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets).
use craft::behavior::ColumnWidth;
@@ -19,7 +21,7 @@ use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
use craft::ui::text::{NumberField, NumberOutput};
use craft::ui::value_drag::SliderScale;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{NodeId, NodeKind, Selection};
use vectorcraft_geom::PathData;
use super::form;
@@ -123,8 +125,55 @@ pub(crate) struct Open {
/// The open Split Into Grid dialog's live state.
pub(crate) struct SplitOpen {
id: DialogId,
document: u64,
preview: LivePreview,
last: Value,
/// An interaction allocates its own selection snapshot, even when the selected objects did not change.
preview_selection: Option<Weak<Selection>>,
}
impl SplitOpen {
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.preview_selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn update_preview(&mut self, app: &mut VectorcraftApp, on: bool, fields: &DialogFields) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return };
if !self.owns_preview(app) {
self.preview = LivePreview::default();
self.preview_selection = None;
if state.interaction.is_some() {
return;
}
}
let params = split_params(fields);
let ran = self.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, &params).is_some();
if !on {
self.preview_selection = None;
} else if ran {
self.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
}
}
fn confirm(&mut self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> {
if app.session.active().is_none_or(|state| state.uid != self.document) {
return Err(tl!("Split Into Grid can only change the document where it was opened.").to_owned());
}
if app.session.in_interaction() && !self.owns_preview(app) {
return Err(tl!("Finish the active edit before applying Split Into Grid.").to_owned());
}
self.preview_selection = None;
std::mem::take(&mut self.preview).commit(app, SPLIT_COMMAND, split_params(fields)).map(drop)
}
fn cancel(self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
self.preview.cancel(app);
}
}
}
/// The command the dialog runs and its parameters.
@@ -410,34 +459,25 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) {
app.status("There is no window to show the dialog in.");
return;
};
let (width, height) =
app.session.active().and_then(|st| st.doc.bounds_of(&st.selection.objects, false)).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let Some(state) = app.session.active() else {
app.status("Open a document before using Split Into Grid.");
return;
};
let document = state.uid;
let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let lengths = crate::canvas::general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| {
ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews(true)
});
let ok = |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| {
let params = split_params(&result.fields);
match app.object_dialogs.split.take() {
Some(record) => {
let id = record.id;
record.preview.commit(app, SPLIT_COMMAND, params).map(drop).inspect_err(|_| {
app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null });
})
}
None => app.run(SPLIT_COMMAND, params).map(drop),
}
let Some(mut record) = app.object_dialogs.split.take() else { return Err(tl!("The Split Into Grid dialog is closed.").to_owned()) };
record.confirm(app, &result.fields).inspect_err(|_| app.object_dialogs.split = Some(record))
};
if let Some(old) = app.object_dialogs.split.take() {
old.preview.cancel(app);
old.cancel(app);
}
let cancel = Box::new(|app: &mut VectorcraftApp| {
if let Some(record) = app.object_dialogs.split.take() {
record.preview.cancel(app);
}
});
match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) {
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null }),
match open_held(app, dialog, ok) {
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, preview: LivePreview::default(), preview_selection: None }),
None => app.status("There is no window to show the dialog in."),
}
}
@@ -456,17 +496,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
}
records.append(&mut app.object_dialogs.path);
app.object_dialogs.path = records;
if let Some(mut s) = app.object_dialogs.split.take() {
if let Some((on, fields)) = dialog_state(app, s.id) {
let params = split_params(&fields);
if !on {
s.last = Value::Null;
}
if s.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, &params).is_some() {
s.last = params;
}
if let Some(mut split) = app.object_dialogs.split.take() {
if let Some((on, fields)) = dialog_state(app, split.id) {
split.update_preview(app, on, &fields);
app.object_dialogs.split = Some(split);
} else {
split.cancel(app);
}
app.object_dialogs.split = Some(s);
}
}
@@ -516,3 +552,115 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> {
})
.collect()
}
#[cfg(test)]
mod split_tests {
use serde_json::json;
use super::*;
use crate::dialogs::tests::{app, cancel, confirm, frame, is_open, set};
fn selected_rectangle(app: &mut VectorcraftApp, width: u32, height: u32) {
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": width, "height": height})).unwrap();
app.run("select.all", json!({})).unwrap();
}
fn other_document(app: &mut VectorcraftApp) {
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
selected_rectangle(app, 150, 90);
}
#[test]
fn split_into_grid_skips_preview_in_the_other_drawing() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
let original = app.session.doc().unwrap().doc.clone();
open_split(&mut app);
set(&mut app, "columns", json!(3));
other_document(&mut app);
let other = app.session.doc().unwrap().doc.clone();
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by Preview");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app, vec![]);
assert_ne!(app.session.doc().unwrap().doc, original);
assert!(app.session.in_interaction());
assert!(confirm(&mut app));
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6);
assert!(!app.session.in_interaction());
}
#[test]
fn split_into_grid_keeps_the_draft_when_ok_is_in_another_drawing() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
open_split(&mut app);
set(&mut app, "columns", json!(3));
other_document(&mut app);
let other = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
let closed = confirm(&mut app);
assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by OK");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert!(!closed && is_open(&app), "the user can return to confirm");
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(confirm(&mut app));
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6);
}
#[test]
fn split_into_grid_cancel_preserves_the_other_drawings_edit() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
other_document(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
let opening = app.session.doc().unwrap().doc.clone();
open_split(&mut app);
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.in_interaction(), "the opening drawing is previewing");
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
assert!(cancel(&mut app));
assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit");
assert_eq!(app.session.doc().unwrap().doc, other);
app.session.commit_interaction().unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
}
#[test]
fn split_into_grid_does_not_adopt_a_new_edit_on_return() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
other_document(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
open_split(&mut app);
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.in_interaction());
for index in [1, 0] {
app.run("document.activate", json!({"index": index})).unwrap();
}
app.session.begin_interaction("New edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let editing = app.session.doc().unwrap().doc.clone();
frame(&mut app, vec![]);
assert!(!confirm(&mut app));
assert!(cancel(&mut app));
assert!(app.session.in_interaction());
assert_eq!(app.session.doc().unwrap().doc, editing);
}
}
@@ -19,6 +19,8 @@ use crate::canvas::general_lengths;
/// The dialog kind of the plane options.
pub const KIND: &str = "perspectivePlane";
const OPENING_DOCUMENT: &str = "__openingDocument";
/// What becomes of the objects on the plane: (`objects` value, label).
const OBJECTS: [(&str, &str); 3] = [("none", "Do Not Move"), ("move", "Move All Objects"), ("copy", "Copy All Objects")];
@@ -47,8 +49,9 @@ fn build<'a>(title: &str, lengths: LengthUnits, _fields: &'a mut DialogFields) -
/// Open the options of `plane` (`{plane}`; default the active plane), filled in with its location.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let doc = &app.session.active().ok_or("no document")?.doc;
let g = PerspectiveGrid::current(doc);
let state = app.session.active().ok_or("no document")?;
let document = state.uid;
let g = PerspectiveGrid::current(&state.doc);
let plane = match p.get("plane").and_then(Value::as_str) {
Some(s) => Plane::parse(s).ok_or("plane must be left, right or ground")?,
None => g.plane,
@@ -60,12 +63,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let lengths = general_lengths(app);
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let Value::Object(map) = json!({"plane": plane.id(), "location": offset, "objects": "none"}) else { return Err("no window".into()) };
let mut fields = form::fields_of(&params(lengths), &map);
// The held answer carries the drawing and plane from the same opening.
fields.set(OPENING_DOCUMENT, document.to_string());
let heading = title(plane);
let dialog = HostedParamDialog::new(&ctx, KIND, form::fields_of(&params(lengths), &map), move |f| build(&heading, lengths, f));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| build(&heading, lengths, f));
// A refusal keeps the dialog open with the reason under its rows.
let ok = move |app: &mut VectorcraftApp, r: &ParamResult| {
let ok = |app: &mut VectorcraftApp, r: &ParamResult| {
let document = r.fields.text(OPENING_DOCUMENT).and_then(|uid| uid.parse().ok());
if !app.session.active().is_some_and(|state| Some(state.uid) == document) {
return Err(tl!("Perspective Plane Options can only change the document where it was opened.").to_owned());
}
let plane = r.fields.text("plane").ok_or_else(|| tl!("The perspective plane is missing").to_owned())?;
let objects = r.fields.text("objects").unwrap_or("none");
let p = json!({"plane": plane.id(), "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects});
let p = json!({"plane": plane, "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects});
app.run("perspective.plane.move", p).map(|_| ())
};
open_held(app, dialog, ok).ok_or("no window")?;
@@ -100,15 +111,75 @@ mod tests {
host(app, |h| h.set_json_field(&ctx, id, field, value)).unwrap();
}
/// OK on the open dialog, then the frame's pump runs the held OK.
fn ok(app: &mut VectorcraftApp) {
fn pump_ok(app: &mut VectorcraftApp) {
let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), the_dialog(app));
// A held OK reports `false` and files its answer for the app; the dialog closes at its next pass.
assert!(host(app, |h| h.confirm_by_id(&ctx, id) || h.held_state(id) == Some(craft::ui::dialog::HeldOk::Waiting)), "OK is enabled");
crate::dialogs::host::pump(app, &ctx);
}
fn ok(app: &mut VectorcraftApp) {
pump_ok(app);
let ctx = app.ui_ctx.clone().unwrap();
crate::tests_synthetic::key_frame(app, &ctx, vec![]);
}
fn right_plane_with_art(app: &mut VectorcraftApp) {
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 450, "y": 380, "width": 60, "height": 60})).unwrap()["id"].clone();
app.run("perspective.attach", json!({"ids": [id], "plane": "right"})).unwrap();
}
#[test]
fn plane_options_keep_the_plane_and_copied_objects_in_the_opening_document() {
let mut app = app();
right_plane_with_art(&mut app);
let opening = app.session.doc().unwrap().doc.clone();
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
set(&app, "location", json!(40.0));
set(&app, "objects", json!("copy"));
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
right_plane_with_art(&mut app);
let other = app.session.doc().unwrap().doc.clone();
let history = app.session.doc().unwrap().history.undo.len();
let (id, _) = the_dialog(&app);
pump_ok(&mut app);
assert_eq!(app.session.doc().unwrap().doc, other, "foreign OK leaves the other drawing and its art unchanged");
assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
assert_eq!(the_dialog(&app).1["location"], 40.0);
assert_eq!(the_dialog(&app).1["objects"], "copy");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
ok(&mut app);
let doc = &app.session.doc().unwrap().doc;
assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0);
assert_eq!(doc.layers[0].children().unwrap().len(), 2, "one copy in the opening drawing");
}
#[test]
fn replacement_plane_options_use_the_replacement_drawing_and_plane() {
let mut app = app();
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
let opening = app.session.doc().unwrap().doc.clone();
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
app.run("ui.perspectivePlane", json!({"plane": "ground"})).unwrap();
set(&app, "location", json!(40.0));
ok(&mut app);
let grid = PerspectiveGrid::current(&app.session.doc().unwrap().doc);
assert_eq!(grid.offset(Plane::Ground), 40.0, "OK moves the replacement opening's plane");
assert_eq!(grid.offset(Plane::Right), 0.0);
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
}
#[test]
fn double_clicking_a_plane_widget_opens_its_options_and_ok_moves_it() {
let mut app = app();
@@ -298,8 +298,9 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul
Action::Import => {
let request = PickRequest::open(KIND).filter("Perspective grid presets", PRESET_EXTS);
file_asks::ask(app, request, Owner::Free, |app, picked| {
let path = picked.first_path().ok_or("cancelled")?;
let r = app.run("perspective.presets.import", json!({ "path": path }))?;
let mut params = file_asks::open_params(&picked).ok_or("cancelled")?;
params.remove("name");
let r = app.run("perspective.presets.import", Value::Object(params))?;
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
select(app, first);
}
@@ -43,6 +43,7 @@ fn params() -> Vec<Param> {
/// Open the dialog on the placement options of images `ids` (default: the selected ones).
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let source_document = app.session.active().map(|document| document.uid);
let ids = p.get("ids").cloned().unwrap_or(Value::Null);
let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?;
let placement = &r["placement"];
@@ -60,6 +61,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
})
.held_ok();
crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| {
if app.session.active().map(|document| document.uid) != source_document {
return Err(tl!("Placement Options can only change the document where it was opened.").to_owned());
}
let f = &result.fields;
let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]);
let params = json!({ "ids": ids, "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) });
@@ -68,3 +72,57 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
.ok_or("no window")?;
Ok(Value::Null)
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::{HeldOk, dialog_id};
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
use vectorcraft_engine::Session;
use super::*;
#[test]
fn held_placement_options_keep_the_link_and_undo_in_the_opening_document() {
let dir = vectorcraft_testkit::TempDir::new("placement-options-document");
let path = dir.join("linked.png");
let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap();
std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let link = |app: &mut VectorcraftApp| {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap()
};
let source_link = link(&mut app);
let other_link = link(&mut app);
assert_eq!(source_link, other_link, "different documents reuse this object ID");
let settings = |app: &mut VectorcraftApp| {
let placement = app.run(CMD, json!({"ids": [source_link]})).unwrap()["placement"].clone();
(placement, app.session.active().unwrap().history.undo.len())
};
let other = settings(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
let starting = settings(&mut app);
app.run("ui.placementOptionsDialog", json!({"ids": [source_link]})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let id = dialog_id(KEY);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "preserve", json!("fit")).unwrap();
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("document.activate", json!({"index": 1})).unwrap();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(settings(&mut app), other, "the other link and its undo history are preserved");
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(settings(&mut app), starting);
assert!(crate::dialogs::tests::confirm(&mut app));
let (placement, steps) = settings(&mut app);
assert_eq!(placement["preserve"], json!("fit"));
assert_eq!(steps, starting.1 + 1);
}
}
+30 -16
View File
@@ -100,6 +100,7 @@ pub(crate) struct PrintDialogs {
struct Open {
id: DialogId,
mode: PrintMode,
document: Option<u64>,
/// The preset the settings were loaded from last (the Print Preset row's selection).
preset: String,
/// The saved preset the editor edits (empty: a new one).
@@ -157,7 +158,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ).
let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()).to_string();
let fields = fields_of(&saved)?;
start(app, PrintMode::Print, fields, preset, Default::default())
let document = st.uid;
start(app, PrintMode::Print, Some(document), fields, preset, Default::default())
}
/// Open the preset editor on the saved preset `name`, or on a new preset starting from `preset`
@@ -173,7 +175,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
None => (s("preset").unwrap_or(DEFAULT_PRESET).to_string(), app.session.new_print_preset_name(), String::new()),
};
let set = app.session.print_preset_settings(&base).ok_or_else(|| format!("no print preset named `{base}`"))?;
start(app, PrintMode::PresetEditor, fields_of(&set)?, base, (editing, name))
start(app, PrintMode::PresetEditor, None, fields_of(&set)?, base, (editing, name))
}
/// Host the dialog over the settings `fields`; the preset editor edits the saved preset `editing` (empty: a new one)
@@ -181,6 +183,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
fn start(
app: &mut VectorcraftApp,
mode: PrintMode,
document: Option<u64>,
fields: DialogFields,
preset: String,
(editing, name): (String, String),
@@ -217,7 +220,7 @@ fn start(
hosted.set_json_field(&ctx, "name", json!(name))?;
}
let id = dialogs.with(|h| h.open(hosted));
app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None, driver });
app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver });
Ok(Value::Null)
}
@@ -366,6 +369,30 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
let _ = dialogs.with(|h| h.take_by_id::<HostedPrint>(open.id));
return false;
};
for event in std::mem::take(&mut d.events) {
apply_preset_event(app, dialogs, open, &mut d.settings, event);
}
if open.mode == PrintMode::Print {
let same = serde_json::from_value::<PrintSettings>(d.settings.clone())
.ok()
.is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s));
let held = same.then(|| open.preset.clone());
let rows: Vec<PresetRow<String>> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0))
.chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0)))
.collect();
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
}
if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
let message = tl!("Return to the original drawing to print it");
on(dialogs, |p| {
p.set_sheet(None);
p.set_message(Some(message.into()));
if d.ok.is_some() {
p.answer_ok(Err(message.into()));
}
});
return true;
}
// The row was drawn this frame with the controls of the printer before: the next frame shows the new ones.
if d.driver != open.driver {
open.driver = d.driver;
@@ -383,9 +410,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
{
app.status(e);
}
for event in std::mem::take(&mut d.events) {
apply_preset_event(app, dialogs, open, &mut d.settings, event);
}
let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision));
let stamp = (d.settings.to_string(), doc);
let changed = open.preview.as_ref().is_none_or(|(s, _)| *s != stamp);
@@ -425,16 +449,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
p.set_field("__inks", FieldValue::Json(inks));
});
}
if open.mode == PrintMode::Print {
let same = serde_json::from_value::<PrintSettings>(d.settings.clone())
.ok()
.is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s));
let held = same.then(|| open.preset.clone());
let rows: Vec<PresetRow<String>> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0))
.chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0)))
.collect();
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
}
if let Some(answer) = d.ok {
let result = accept(app, open, &answer, &d.name);
on(dialogs, |p| p.answer_ok(result.map_err(Into::into)));
+25 -1
View File
@@ -84,6 +84,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
fields.set("hasSlices", FieldValue::Bool(has_slices));
let summary = format!("{} × {} px · {} {}", info.width, info.height, crate::i18n::colon(tl!("Layers")), info.layers);
let placing = place.is_some();
let drawing = place.and_then(|params| crate::place::import_options_drawing(app, params));
let source = Source {
place: place.map(|p| other_place_params(p, &["layers", "hiddenLayers", "importSlices"])),
name: name.to_string(),
@@ -93,7 +94,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
};
let ctx = app.ui_ctx.clone().unwrap_or_default();
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| build(fields, placing, &summary)).held_ok();
open_held(app, dialog, move |app, result| confirm(app, &source, result)).is_some()
open_held(app, dialog, move |app, result| {
crate::place::check_import_options_drawing(app, drawing)?;
confirm(app, &source, result)
})
.is_some()
}
/// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`,
@@ -269,6 +274,25 @@ mod tests {
}
}
#[test]
fn normal_psd_place_options_wait_for_the_original_drawing() {
let mut app = host::app();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let encoded = vectorcraft_format::base64_encode(&layered());
let params = json!({"name": "poster.psd", "dataBase64": encoded, "at": [50, 50]});
assert_eq!(crate::place::run_for_user(&mut app, &params).unwrap()["dialog"], KIND);
set(&app, "convert", json!("flatten"));
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
let error = host::confirm(&mut app, KIND).expect_err("the other drawing must not receive the file");
assert!(error.contains("original drawing"), "{error}");
assert!(app.session.active().unwrap().history.undo.is_empty());
assert_eq!(host::fields(&app, KIND)["convert"], "flatten");
app.run("document.activate", json!({"index": 0})).unwrap();
host::confirm(&mut app, KIND).unwrap();
let st = app.session.active().unwrap();
assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([node]) if matches!(node.kind, NodeKind::Image(_))));
}
#[test]
fn placing_without_link_asks_and_places_the_layers_as_a_group() {
let b64 = vectorcraft_format::base64_encode(&layered());
+134 -45
View File
@@ -68,8 +68,7 @@ fn layout_glyph(l: ArtboardLayout, rtl: bool) -> (&'static str, &'static LayoutG
}
}
/// The settings the dialog edits, and for Rearrange the artboards it lays out (`indices`, sorted
/// and once each), which the dialog does not edit.
/// The settings the dialog edits.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RearrangeValues {
layout: ArtboardLayout,
@@ -78,26 +77,21 @@ pub(crate) struct RearrangeValues {
columns: f64,
spacing: f64,
move_artwork: bool,
indices: Option<Vec<usize>>,
}
impl Default for RearrangeValues {
fn default() -> Self {
RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true, indices: None }
RearrangeValues { layout: ArtboardLayout::GridByRow, rtl: false, columns: 2.0, spacing: 20.0, move_artwork: true }
}
}
impl RearrangeValues {
/// `artboard.rearrange` parameters.
fn params(&self) -> Value {
let mut p = json!({
json!({
"layout": self.layout.id(), "order": self.order(), "columns": self.columns,
"spacing": self.spacing, "moveArtwork": self.move_artwork,
});
if let Some(indices) = &self.indices {
p["indices"] = json!(indices);
}
p
})
}
fn order(&self) -> &'static str {
@@ -154,16 +148,19 @@ pub(crate) fn open_selected(app: &mut VectorcraftApp, indices: &[usize]) {
/// Opens the dialog for `indices` (Rearrange), or for every artboard (Rearrange All Artboards).
fn open_with(app: &mut VectorcraftApp, indices: Option<Vec<usize>>) -> Result<Value, String> {
let mut values = RearrangeValues::default();
if let Some(spacing) = app.ui.rearrange_artboards_spacing.as_f64() {
values.spacing = spacing;
}
let artboards = indices.as_ref().map_or_else(|| app.session.active().map_or(0, |doc| doc.doc.artboards.len()), Vec::len);
values.indices = indices;
let st = app.session.active().ok_or("no document")?;
let artboards = indices.as_ref().map_or(st.doc.artboards.len(), Vec::len);
let selected = indices
.map(|indices| {
indices.into_iter().map(|i| st.doc.artboards.get(i).map(|a| (i, a.id)).ok_or("no such artboard")).collect::<Result<Vec<_>, _>>()
})
.transpose()?;
let values = RearrangeValues { spacing: app.ui.rearrange_artboards_spacing.as_f64().unwrap_or(20.0), ..RearrangeValues::default() };
let document = st.uid;
let lengths = LengthUnits::new(UnitKind::Points, length_kind(app.session.general_unit()), 72.0);
let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points);
let dialogs = app.dialogs().ok_or("no window")?;
dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, artboards, lengths }));
dialogs.with(|host| host.open(RearrangeArtboardsDialog { id: dialog_id(CMD), open: true, values, document, selected, artboards, lengths }));
Ok(Value::Null)
}
@@ -181,6 +178,9 @@ pub(crate) struct RearrangeArtboardsDialog {
id: DialogId,
open: bool,
values: RearrangeValues,
document: u64,
/// Each selected artboard's opening row index and stable ID. None lays out the entire document.
selected: Option<Vec<(usize, u32)>>,
/// The artboards the dialog lays out (the document's, or the selected ones), which bounds Columns
/// and is the count it shows.
artboards: usize,
@@ -188,8 +188,20 @@ pub(crate) struct RearrangeArtboardsDialog {
lengths: LengthUnits,
}
pub(crate) struct RearrangeAnswer {
values: RearrangeValues,
document: u64,
selected: Option<Vec<(usize, u32)>>,
}
impl RearrangeArtboardsDialog {
fn answer(&self, values: RearrangeValues) -> RearrangeAnswer {
RearrangeAnswer { values, document: self.document, selected: self.selected.clone() }
}
}
/// The rows of the dialog for `artboards` artboards, Spacing shown in `unit`.
fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: LengthUnits) {
fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, selected: bool, lengths: LengthUnits) {
Field::new(tl!("Layout:")).id_salt("layout").show(ui, |ui, _| {
let entries: Vec<Entry<ArtboardLayout>> = ArtboardLayout::ALL
.into_iter()
@@ -231,12 +243,12 @@ fn body(ui: &mut egui::Ui, v: &mut RearrangeValues, artboards: usize, lengths: L
v.move_artwork = on;
}
});
let label = if v.indices.is_some() { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") };
let label = if selected { tl!("Selected Artboards: {n}") } else { tl!("Artboards: {n}") };
Text::new(crate::i18n::fmt(label, &[("n", &artboards.to_string())])).role(TypeRole::Caption).show(ui);
}
impl StackDialog for RearrangeArtboardsDialog {
type Result = RearrangeValues;
type Result = RearrangeAnswer;
fn id(&self) -> DialogId {
self.id
@@ -246,30 +258,31 @@ impl StackDialog for RearrangeArtboardsDialog {
Some(CMD)
}
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<RearrangeValues>> {
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<RearrangeAnswer>> {
let (artboards, lengths) = (self.artboards, self.lengths);
let title = if self.values.indices.is_some() { tl!("Rearrange") } else { tl!("Rearrange All Artboards") };
let selected = self.selected.is_some();
let title = if selected { tl!("Rearrange") } else { tl!("Rearrange All Artboards") };
let shown = FormDialog::new(title, Bind::bound(&mut self.values)).opened(Bind::bound(&mut self.open)).show(ui, |ui, _, v| {
body(ui, v, artboards, lengths);
body(ui, v, artboards, selected, lengths);
true
});
match (shown.accepted, shown.closed) {
(Some(value), _) => Some(DialogResult::Ok(value)),
(Some(value), _) => Some(DialogResult::Ok(self.answer(value))),
(None, Some(_)) => Some(DialogResult::Cancel),
(None, None) => None,
}
}
fn confirm(&mut self, _: &egui::Context) -> Option<RearrangeValues> {
Some(self.values.clone())
fn confirm(&mut self, _: &egui::Context) -> Option<RearrangeAnswer> {
Some(self.answer(self.values.clone()))
}
fn json_fields(&self) -> Option<Value> {
let v = &self.values;
let mut fields =
json!({"layout": v.layout.id(), "order": v.order(), "columns": v.columns, "spacing": v.spacing, "moveArtwork": v.move_artwork});
if let Some(indices) = &v.indices {
fields["indices"] = json!(indices);
if let Some(selected) = &self.selected {
fields["indices"] = json!(selected.iter().map(|(index, _)| index).collect::<Vec<_>>());
}
Some(fields)
}
@@ -311,28 +324,33 @@ impl StackDialog for RearrangeArtboardsDialog {
/// ([`place`]).
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some(DialogResult::Ok(values)) = dialogs.with(|host| host.take::<RearrangeArtboardsDialog>()) else { return };
match &values.indices {
None => match app.run(CMD, values.params()) {
Ok(_) => app.ui.rearrange_artboards_spacing = json!(values.spacing),
Err(e) => app.status(e),
},
Some(listed) => match wait_for_click(app, listed, values.params()) {
Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing),
Err(e) => app.status(e),
},
let Some(DialogResult::Ok(RearrangeAnswer { values, document, selected })) = dialogs.with(|host| host.take::<RearrangeArtboardsDialog>()) else {
return;
};
let applied = if app.session.active().is_none_or(|st| st.uid != document) {
Err(tl!("Rearrange Artboards can only change the document where it was opened.").to_owned())
} else if let Some(selected) = selected {
wait_for_click(app, &selected, values.params())
} else {
app.run(CMD, values.params()).map(drop)
};
match applied {
Ok(()) => app.ui.rearrange_artboards_spacing = json!(values.spacing),
Err(e) => app.status(e),
}
ctx.request_repaint();
}
/// Rearrange for artboards `listed` with `params`, confirmed: it waits for its click on the canvas,
/// for the active document and the tool in use.
fn wait_for_click(app: &mut VectorcraftApp, listed: &[usize], params: Value) -> Result<(), String> {
/// Rearrange the originally selected artboards in their current row order when the canvas is clicked.
fn wait_for_click(app: &mut VectorcraftApp, selected: &[(usize, u32)], mut params: Value) -> Result<(), String> {
let st = app.session.active().ok_or_else(|| "no document".to_string())?;
let ids: Vec<u32> = listed.iter().filter_map(|i| st.doc.artboards.get(*i)).map(|a| a.id).collect();
if ids.len() != listed.len() {
return Err("no such artboard".into());
let wanted: std::collections::HashSet<_> = selected.iter().map(|&(_, id)| id).collect();
let (indices, ids): (Vec<_>, Vec<_>) =
st.doc.artboards.iter().enumerate().filter_map(|(index, a)| wanted.contains(&a.id).then_some((index, a.id))).unzip();
if ids.len() != selected.len() {
return Err(tl!("An artboard selected when the dialog opened was removed.").to_owned());
}
params["indices"] = json!(indices);
let (doc, tool) = (st.uid, app.session.tool_id().to_string());
app.ui.rearrange_placement = Some(RearrangePlacement { doc, tool, params, ids, armed: false });
app.status(PLACE_HINT);
@@ -471,6 +489,77 @@ mod tests {
app.dialogs().unwrap().with(|host| host.open_dialogs().last().and_then(|d| d.fields.clone())).unwrap()
}
fn check_rearrange_stays_in_opening_document(selected: bool) {
let mut app = app(3);
app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap();
let destination = app.session.active().unwrap().uid;
app.run("document.activate", json!({"index": 0})).unwrap();
if selected {
app.select_tool("artboard");
open_selected(&mut app, &[0, 2]);
} else {
open_from_menu(&mut app);
}
set(&app, &[("layout", json!("row")), ("order", json!("rightToLeft")), ("spacing", json!(37))]).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
assert_eq!(app.session.active().unwrap().uid, destination);
let before = origins(&app);
let undo = app.session.active().unwrap().history.undo.len();
let spacing = app.ui.rearrange_artboards_spacing.clone();
ok(&mut app);
assert_eq!(origins(&app), before, "OK leaves the other tab's artboards in place");
assert!(app.ui.rearrange_placement.is_none(), "the other tab cannot start placement");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.rearrange_artboards_spacing, spacing);
}
#[test]
fn rearrange_opening_for_all_artboards_leaves_a_new_tab_untouched() {
check_rearrange_stays_in_opening_document(false);
}
#[test]
fn rearrange_opening_for_selected_artboards_cannot_place_in_a_new_tab() {
check_rearrange_stays_in_opening_document(true);
}
#[test]
fn rearrange_opening_keeps_the_intended_artboards_after_rows_move() {
let mut app = app(3);
app.select_tool("artboard");
let st = app.session.active().unwrap();
let source = [st.doc.artboards[0].id, st.doc.artboards[2].id];
open_selected(&mut app, &[0, 2]);
set(&app, &[("layout", json!("row")), ("spacing", json!(20))]).unwrap();
app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap();
let before = origins(&app);
let undo = app.session.active().unwrap().history.undo.len();
ok(&mut app);
let placement = app.ui.rearrange_placement.as_ref().expect("the original artboards wait for placement");
assert_eq!(placement.ids, source);
assert_eq!(placement.params["indices"], json!([1, 2]));
place(&mut app, Some(Point::new(700.0, 300.0)));
assert_eq!(origins(&app), [before[0], (700.0, 300.0), (820.0, 300.0)]);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn rearrange_opening_does_not_place_a_deleted_artboards_replacement() {
let mut app = app(3);
app.select_tool("artboard");
open_selected(&mut app, &[0]);
app.run("artboard.delete", json!({"index": 0})).unwrap();
let before = origins(&app);
let undo = app.session.active().unwrap().history.undo.len();
ok(&mut app);
assert!(app.ui.rearrange_placement.is_none(), "the replacement row is not a placement target");
assert_eq!(origins(&app), before);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
/// #681: the menu item opens the dialog; each setting reaches `artboard.rearrange`, as one undo step; a
/// setting the layout makes meaningless is refused.
#[test]
@@ -537,7 +626,7 @@ mod tests {
assert_eq!(shown["indices"], json!([0, 2]));
let (title, count) = app.dialogs().unwrap().with(|host| {
let d = host.get::<RearrangeArtboardsDialog>().unwrap();
(d.values.indices.is_some(), d.artboards)
(d.selected.is_some(), d.artboards)
});
assert_eq!((title, count), (true, 2), "Rearrange for the 2 selected artboards");
set(&app, &[("layout", json!("row"))]).unwrap();
+1 -1
View File
@@ -2126,7 +2126,7 @@ fn assign_tab(
let total: usize = rows.iter().map(|r| r["from"].as_array().map_or(0, Vec::len)).sum();
// Reduction and the preserve rules apply to art (a colour group alone has a row per colour).
if art {
Row::new().show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
let counts: Vec<Entry<usize>> = std::iter::once(Entry::new(0, Label::from(tl!("Auto"))))
.chain((1..=total).map(|n| Entry::new(n, Label::from(n.to_string()))))
.collect();
@@ -15,6 +15,50 @@ use serde_json::{Value, json};
use super::{Fields, GROUP_ACTION, KIND, RecolorDialog};
use crate::VectorcraftApp;
#[test]
fn preserve_grays_can_be_clicked_in_a_narrow_localized_dialog() {
use egui::accesskit::Role;
use egui::{RawInput, pos2, vec2};
for lang in ["de", "el"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
app.session.prefs.interface_language = lang.into();
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
app.run("select.all", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(540.0, 500.0));
let mut time = 0.0;
let mut draw = |app: &mut VectorcraftApp, events| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
};
draw(&mut app, vec![]);
app.run("ui.recolorDialog", json!({})).unwrap();
for _ in 0..5 {
draw(&mut app, vec![]);
}
let out = draw(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let label = crate::i18n::t("Grays");
let bounds = nodes
.iter()
.find(|(_, node)| node.role() == Role::CheckBox && node.label() == Some(label))
.and_then(|(_, node)| node.bounds())
.unwrap_or_else(|| panic!("{lang} has no Preserve Grays checkbox"));
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
draw(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
draw(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
draw(&mut app, vec![]);
let preserves_grays = app.dialogs().unwrap().with(|host| host.get::<RecolorDialog>().map(|d| d.fields.bool("preserveGrays")));
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(preserves_grays, Some(true), "the pointer click toggles Preserve Grays in {lang}");
}
}
/// Recolor Artwork over an app, in a window-sized fixture.
pub(crate) struct Recolor {
fixture: Fixture,
+65 -11
View File
@@ -37,10 +37,13 @@ use crate::{VectorcraftApp, io};
pub(super) mod color_table;
pub const KIND: &str = "saveForWeb";
const WRONG_DOCUMENT: &str = "Save for Web belongs to the document that opened the dialog.";
/// What the open dialog's pump keeps between frames: data keyed by its inputs, never UI state.
#[derive(Default)]
pub(crate) struct WebExport {
document: Option<u64>,
opening: Arc<()>,
/// The rendering of the art before optimisation, by [`render_key`].
render: Option<(String, Result<Arc<WebRender>, String>)>,
/// The Original pane's picture, `None` while the dialog has not been given the current rendering's.
@@ -183,11 +186,20 @@ fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: O
/// Open on the document's active artboard, keeping the other remembered settings.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
app.session.active().ok_or("no document")?;
let document = app.session.active().ok_or("no document")?.uid;
let host = app.dialogs().ok_or("no window")?;
let ctx = app.ui_ctx.clone().ok_or("no window")?;
// Settle a completed opening while its settings and source are still available.
if let Some(DialogResult::Ok(result)) = host.with(|dialog| dialog.take::<HostedSaveForWeb>()) {
finish(app, result);
}
let s = remembered(app);
app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() };
app.web_export = WebExport {
document: Some(document),
table: serde_json::to_value(&s.color_table).unwrap_or_default(),
kept: kept_of(&s),
..WebExport::default()
};
let (name, artboards, slices) = {
let st = app.session.active().ok_or("no document")?;
let slices: Vec<WebSlice> = st
@@ -449,6 +461,10 @@ fn on_dialog<R>(host: &craft::ui::shell::WindowDialogs, f: impl FnOnce(&mut Host
host.with(|h| h.get_mut::<HostedSaveForWeb>().map(f))
}
fn on_original_document(app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|active| app.web_export.document == Some(active.uid))
}
/// Answers the open dialog once per frame: its result when it closed, else its requests.
/// Colour requests (the matte, a palette cell) are routed by the host-wide colour picker routing;
/// a palette cell's pick is applied to the table by [`take_palette_pick`].
@@ -456,13 +472,32 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(host) = app.dialogs() else { return };
match host.with(|h| h.take::<HostedSaveForWeb>()) {
Some(DialogResult::Ok(result)) => return finish(app, result),
Some(_) => {
Some(_) if on_dialog(&host, |_| ()).is_none() => {
app.web_export = WebExport::default();
return;
}
None => {}
_ => {}
}
let Some(asked) = on_dialog(&host, Asked::take) else { return };
if !on_original_document(app) {
let restore = asked.tables.iter().any(|event| matches!(event.edit, ColorTableEdit::Restore));
if restore {
color_table::restore(&mut app.web_export.table);
let marks = color_table::marks(&app.web_export.table);
on_dialog(&host, |dialog| dialog.set_marks(marks));
}
let requested = asked.path.is_some()
|| asked.browser
|| asked.optimize_open
|| asked.optimize.is_some()
|| asked.tables.iter().any(|event| !matches!(event.edit, ColorTableEdit::Restore));
update_presets(app, &host, asked.presets, restore);
if requested {
on_dialog(&host, HostedSaveForWeb::cancel_requests);
app.status(tl!(WRONG_DOCUMENT).to_owned());
}
return;
}
// The framework keeps the result line while the settings are the ones it found; the art is the app's.
let art = art_key(app);
if app.web_export.optimized.is_some() && optimized_result(&app.web_export.optimized, &art).is_none() {
@@ -474,12 +509,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
let marks = color_table::marks(&app.web_export.table);
on_dialog(&host, |d| d.set_marks(marks));
let refresh_presets = !asked.tables.is_empty() || !asked.presets.is_empty();
store_presets(app, asked.presets);
if refresh_presets {
let presets = dialog_presets(app);
on_dialog(&host, |d| d.set_presets(presets));
}
update_presets(app, &host, asked.presets, !asked.tables.is_empty());
if asked.optimize_open {
let bytes = optimize_start(app, &asked.options);
on_dialog(&host, |d| d.answer_optimize_start(bytes));
@@ -565,6 +595,10 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key:
let Some(options) = host.with(|h| h.get_mut_by_id::<HostedSaveForWeb>(parent).map(|d| d.current().clone())) else {
return false;
};
if !on_original_document(app) {
app.status(tl!(WRONG_DOCUMENT).to_owned());
return true;
}
let rgb = |c: Srgba| {
let [r, g, b, _] = c.to_rgba().0;
[r, g, b]
@@ -578,7 +612,8 @@ pub(crate) fn take_palette_pick(app: &mut VectorcraftApp, parent: DialogId, key:
}
/// Runs what the preset list asked for and shows a failure in the status line.
fn store_presets(app: &mut VectorcraftApp, events: Vec<WebPresetEvent>) {
fn update_presets(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, events: Vec<WebPresetEvent>, table_changed: bool) {
let refresh = table_changed || !events.is_empty();
for event in events {
let r = match event {
WebPresetEvent::Saved(p) => {
@@ -595,6 +630,10 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec<WebPresetEvent>) {
app.status(e);
}
}
if refresh {
let presets = dialog_presets(app);
on_dialog(host, |d| d.set_presets(presets));
}
}
/// Saves the preset `from` under `to`, then deletes `from`.
@@ -692,7 +731,18 @@ fn ask_path(app: &mut VectorcraftApp, host: &craft::ui::shell::WindowDialogs, id
pick = pick.filter(f.name.clone(), &extensions);
}
// A cancelled panel has no path.
let opening = app.web_export.opening.clone();
file_asks::ask(app, pick, Owner::Free, move |app, picked| {
if !Arc::ptr_eq(&opening, &app.web_export.opening) {
return Ok(Value::Null);
}
if !on_original_document(app) {
if let Some(host) = app.dialogs() {
on_dialog(&host, HostedSaveForWeb::cancel_requests);
}
app.status(tl!(WRONG_DOCUMENT).to_owned());
return Ok(Value::Null);
}
match picked.first_path() {
Some(path) => answer_path(app, id, &key, path),
None => {
@@ -715,9 +765,13 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) {
/// The dialog closed with Save… or Done: the settings are remembered, and with a path the files are
/// written. Failures show in the status line; the dialog has closed.
fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) {
let wrong_document = result.path.is_some() && !on_original_document(app);
let table = std::mem::take(&mut app.web_export.table);
let kept = std::mem::take(&mut app.web_export.kept);
app.web_export = WebExport::default();
if wrong_document {
return app.status(tl!(WRONG_DOCUMENT).to_owned());
}
let params = settings_of(&result.options, &table, &kept, None);
if let Err(e) = app.run("webExport.settings", params.clone()) {
return app.status(e);
@@ -312,6 +312,49 @@ fn save_remembers_and_writes_and_done_only_remembers() {
assert!(!dir.join("Untitled-1.png").exists());
}
#[test]
fn save_for_web_download_waits_for_the_original_drawing() {
let dir = vectorcraft_testkit::temp_dir("sfw-original-download");
let (mut app, downloads) = app(&dir, true);
app.run("file.saveForWeb", json!({})).unwrap();
set(&mut app, "format", json!("png24"));
app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap();
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
confirm(&mut app);
assert!(downloads.borrow().is_empty(), "the other drawing is never downloaded");
assert!(is_open(&app));
assert_eq!(fields(&app)["format"], "png24");
app.run("document.activate", json!({"index": 0})).unwrap();
save(&mut app);
assert_eq!(downloads.borrow().len(), 1);
}
#[test]
fn save_for_web_does_not_write_another_drawing_when_the_picker_returns() {
let dir = vectorcraft_testkit::temp_dir("sfw-original-picker");
let (mut app, _) = app(&dir, false);
app.run("file.new", json!({"width": 26, "height": 20, "name": "Other drawing"})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 26, "height": 20})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("file.saveForWeb", json!({})).unwrap();
set(&mut app, "format", json!("png24"));
let ctx = app.ui_ctx.clone().unwrap();
let dialog = id(&app);
host(&app).with(|h| h.confirm_by_id(&ctx, dialog));
settle(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
answer_saves(&mut app);
settle(&mut app);
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
assert!(is_open(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
save(&mut app);
assert!(dir.join("Untitled-1.png").exists());
}
/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes
/// and stays remembered after Done.
#[test]
+52 -1
View File
@@ -36,6 +36,7 @@ fn document_name(app: &VectorcraftApp) -> Option<String> {
/// Open the dialog for `library`: `extra` rows sit under the Name row. `names` are the items selected in the
/// panel.
pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec<String>, extra: Vec<Param>) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let name = document_name(app).ok_or("no document open")?;
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let Library { key, title, cmd, only, ext, has_user_dir } = library;
@@ -64,7 +65,15 @@ pub(super) fn open(app: &mut VectorcraftApp, library: Library, names: Vec<String
let dialog =
HostedParamDialog::new(&ctx, key, fields, move |fields| ParamDialog::new(key, title.clone(), params.clone()).values(Bind::bound(fields)));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| save(app, cmd, ext, result);
let owner = egui::Id::unique((key, "opening-drawing"));
ctx.data_mut(|data| data.insert_temp(owner, document));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| {
let document = ctx.data(|data| data.get_temp::<u64>(owner));
if app.session.active().is_none_or(|st| Some(st.uid) != document) {
return Err(tl!("Return to the original drawing to save its library").into());
}
save(app, cmd, ext, result)
};
super::host::open_held(app, dialog, ok).ok_or("no window")?;
Ok(Value::Null)
}
@@ -105,3 +114,45 @@ fn save(app: &mut VectorcraftApp, cmd: &str, ext: fn(&DialogFields) -> String, r
Ok(_) => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::super::{save_symbol_library, tests_export};
use serde_json::json;
#[test]
fn save_library_waits_for_the_drawing_that_opened_it() {
let (mut app, written) = tests_export::app(1);
app.run("symbol.new", json!({"name": "Source Mark"})).unwrap();
save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap();
tests_export::set(&mut app, "saveTo", json!("file"));
tests_export::set(&mut app, "name", json!("Marks"));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
app.run("symbol.new", json!({"name": "Other Mark"})).unwrap();
let error = tests_export::try_confirm(&mut app).expect_err("Save Library must refuse the other drawing");
assert!(error.contains("original drawing"), "{error}");
assert!(written.borrow().is_empty());
assert_eq!(tests_export::fields(&app)["name"], "Marks");
app.run("document.activate", json!({"index": 0})).unwrap();
tests_export::try_confirm(&mut app).unwrap();
assert_eq!(written.borrow().len(), 1);
}
#[test]
fn reopening_save_library_uses_the_new_drawings_draft() {
let (mut app, written) = tests_export::app(1);
app.run("symbol.new", json!({"name": "Source Mark"})).unwrap();
save_symbol_library::open(&mut app, vec!["Source Mark".into()]).unwrap();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
app.run("symbol.new", json!({"name": "Other Mark"})).unwrap();
save_symbol_library::open(&mut app, vec!["Other Mark".into()]).unwrap();
tests_export::set(&mut app, "saveTo", json!("file"));
tests_export::set(&mut app, "name", json!("Other Marks"));
tests_export::try_confirm(&mut app).unwrap();
let output = written.borrow();
assert_eq!(output.len(), 1);
assert!(output[0].0.contains("Other Marks"));
}
}
@@ -48,7 +48,9 @@ fn params_of(result: &ParamResult) -> Value {
/// Report Results on, lists how many of each chosen replacement it made.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let selected = app.session.active().is_some_and(|d| !d.selection.is_empty());
let source = app.session.active().ok_or("no document")?;
let document = source.uid;
let selected = !source.selection.is_empty();
let mut params: Vec<Param> = options()
.into_iter()
.map(|(key, _, label)| Param::new(key, label, ParamKind::bool(matches!(key, "quotes" | "dashes" | "ellipsis"))))
@@ -66,7 +68,13 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if !selected {
dialog.set_field("scope", FieldValue::Text("document".into()));
}
let owner = egui::Id::unique((COMMAND, "opening-drawing"));
ctx.data_mut(|data| data.insert_temp(owner, document));
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| -> Result<(), String> {
let document = ctx.data(|data| data.get_temp::<u64>(owner));
if app.session.active().is_none_or(|st| Some(st.uid) != document) {
return Err(tl!("Return to the original drawing to replace its punctuation").into());
}
let r = app.run(COMMAND, params_of(result))?;
result.remember(&ctx);
if result.fields.bool("report") == Some(true) {
@@ -165,4 +173,39 @@ mod tests {
ok(&mut app);
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn smart_punctuation_waits_for_its_original_drawing() {
let (mut app, source) = app_with_text("a--b");
app.run("select.none", json!({})).unwrap();
open(&mut app).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
let error = super::super::tests_export::try_confirm(&mut app).expect_err("Smart Punctuation must refuse the other drawing");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(plain(&app, other), "c--d");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert_eq!(entry(&app, COMMAND).unwrap().fields.unwrap()["scope"], "document");
app.run("document.activate", json!({ "index": 0 })).unwrap();
ok(&mut app);
assert_eq!(plain(&app, source), "a–b");
}
#[test]
fn reopened_smart_punctuation_applies_in_its_new_drawing() {
let (mut app, source) = app_with_text("a--b");
app.run("select.none", json!({})).unwrap();
open(&mut app).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let other = app.run("text.create", json!({"x": 10, "y": 40, "text": "c--d", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
app.run("select.none", json!({})).unwrap();
open(&mut app).unwrap();
let (ctx, id) = (app.ui_ctx.clone().unwrap(), entry(&app, COMMAND).unwrap().id);
app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(plain(&app, other), "c–d");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(plain(&app, source), "a--b");
}
}
+133 -12
View File
@@ -40,12 +40,16 @@ pub const KIND: &str = "swatchOptions";
/// What a dialog says when the window has no dialog host to open it on.
pub(super) const NO_WINDOW: &str = "no window";
const PREVIEW_LABEL: &str = "Swatch Options";
/// The open Swatch Options dialog: the held dialog, the swatch it edits and the parameters its preview last ran with.
#[derive(Clone, Debug)]
pub(crate) struct Open {
/// The held dialog.
pub(crate) id: DialogId,
opening: Arc<()>,
document: u64,
preview_reset: u64,
/// The name of the swatch being edited.
swatch: String,
/// The `swatch.edit` parameters of the running preview; `None` while no preview runs.
@@ -287,24 +291,43 @@ fn stops_of(g: &GradientPaint) -> GradientStops {
/// Opens the held dialog over swatch `swatch`: OK is one `swatch.edit` undo step, Cancel rolls the preview back.
fn launch(app: &mut VectorcraftApp, swatch: &str, fields: DialogFields, rows: Vec<Param>) -> Result<Value, String> {
let document = app.session.active().ok_or("no drawing")?.uid;
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
let dialog = hosted(&ctx, KIND, tl!("Swatch Options"), fields, rows, true);
let edited = swatch.to_owned();
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
// The edit replaces the preview, so the preview is dropped first.
if owns_preview(app) {
let _ = app.session.cancel_interaction();
}
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let ok = |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let open = app.ui.swatch_options.as_ref().ok_or("the Swatch Options dialog is gone")?;
if app.session.active().is_none_or(|st| st.uid != open.document) {
return Err(tl!("Return to the original drawing to edit this swatch").into());
}
let edited = open.swatch.clone();
// The edit replaces the preview, so the preview is dropped first.
if owns_preview(app) {
let _ = app.session.cancel_interaction();
} else if app.session.in_interaction() {
app.keep_typing()?;
if app.session.in_interaction() {
return Err(tl!("Finish the current edit before changing this swatch").into());
}
}
app.run("swatch.edit", edit_params(&edited, &answer.fields))?;
app.ui.swatch_options = None;
Ok(())
};
let cancel = |app: &mut VectorcraftApp| {
if app.session.in_interaction() {
let _ = app.session.cancel_interaction();
let cancel = move |app: &mut VectorcraftApp| {
if app.ui.swatch_options.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled)) {
if owns_preview(app) {
let _ = app.session.cancel_interaction();
}
app.ui.swatch_options = None;
}
app.ui.swatch_options = None;
};
let id = open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(Box::new(cancel)) }).ok_or(NO_WINDOW)?;
app.ui.swatch_options = Some(Open { id, swatch: swatch.to_owned(), last: None });
app.ui.swatch_options = Some(Open { id, opening, document, preview_reset: app.session.tool_resets(), swatch: swatch.to_owned(), last: None });
Ok(Value::Null)
}
@@ -318,26 +341,49 @@ fn edit_params(swatch: &str, fields: &DialogFields) -> Value {
/// Shows the edit on the canvas while the Preview box is on and drops it when it goes off. It runs each pass; the
/// parameters it last previewed with are remembered, so a pass that changes nothing runs nothing.
fn owns_preview(app: &VectorcraftApp) -> bool {
app.ui.swatch_options.as_ref().is_some_and(|open| {
open.last.is_some()
&& open.preview_reset == app.session.tool_resets()
&& app
.session
.active()
.is_some_and(|st| st.uid == open.document && st.interaction.as_ref().is_some_and(|interaction| interaction.label == PREVIEW_LABEL))
})
}
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some((id, swatch, last)) = app.ui.swatch_options.as_ref().map(|o| (o.id, o.swatch.clone(), o.last.clone())) else { return };
let Some(open) = app.ui.swatch_options.as_ref().filter(|open| app.session.active().is_some_and(|st| st.uid == open.document)) else { return };
let (id, swatch, last) = (open.id, open.swatch.clone(), open.last.clone());
let owns_preview = owns_preview(app);
correct(app, id);
let Some((previewing, fields)) = with_dialog(app, id, |d| (d.is_previewing(), d.fields().clone())) else { return };
let want = previewing.then(|| edit_params(&swatch, &fields));
if let Some(params) = &want {
// A refused OK drops the interaction under an unchanged dialog: the preview starts again.
if want == last && app.session.in_interaction() {
if want == last && owns_preview {
return;
}
let begun = app.session.in_interaction() || app.begin_interaction("Swatch Options").map_err(|e| app.status(e)).is_ok();
if !owns_preview && app.session.in_interaction() {
if let Err(e) = app.keep_typing() {
app.status(e);
return;
}
if app.session.in_interaction() {
return;
}
}
let begun = owns_preview || app.begin_interaction(PREVIEW_LABEL).map_err(|e| app.status(e)).is_ok();
if begun && let Err(e) = app.session.preview("swatch.edit", params) {
app.status(e.to_string());
}
} else if last.is_some() {
} else if owns_preview {
// The Preview box went off: the document shows its own colour again. Nothing to report if none was open.
let _ = app.session.cancel_interaction();
}
if let Some(open) = app.ui.swatch_options.as_mut() {
open.last = want;
open.preview_reset = app.session.tool_resets();
}
}
@@ -530,6 +576,81 @@ mod tests {
(sw.paint.color(), sw.spot, sw.global)
}
#[test]
fn swatch_options_refuses_a_matching_name_in_another_drawing() {
let (ctx, mut app) = setup();
app.run("swatch.new", json!({"name": "Twin", "color": "#123456"})).unwrap();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.run("swatch.new", json!({"name": "Twin", "color": "#6789ab"})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap();
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let other = swatch(&app, "Twin");
activate(&mut app, 0);
open(&mut app, "Twin").unwrap();
set(&app, &ctx, &[("name", json!("Source paint")), ("preview", json!(false))]);
activate(&mut app, 1);
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
let dialogs = app.dialogs().unwrap();
let id = dialog_id(KIND);
dialogs.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.in_interaction(), "the other drawing's edit stays active");
assert_eq!(swatch(&app, "Twin"), other);
app.session.cancel_interaction().unwrap();
activate(&mut app, 0);
dialogs.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.active().unwrap().doc.swatch("Source paint").is_some());
}
#[test]
fn swatch_options_waits_for_another_preview_in_the_original_drawing() {
let (ctx, mut app) = setup();
app.run("swatch.new", json!({"name": "Editable", "color": "#123456"})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap();
open(&mut app, "Editable").unwrap();
set(&app, &ctx, &[("name", json!("Renamed")), ("preview", json!(false))]);
app.session.begin_interaction("An independent preview").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
let dialogs = app.dialogs().unwrap();
let id = dialog_id(KIND);
dialogs.with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.in_interaction());
assert!(app.session.active().unwrap().doc.swatch("Renamed").is_none());
app.session.cancel_interaction().unwrap();
let undo = app.session.active().unwrap().history.undo.len();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.active().unwrap().doc.swatch("Renamed").is_some());
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn reopening_swatch_options_rolls_back_the_replaced_preview() {
let (ctx, mut app) = setup();
for name in ["First color", "Second color"] {
app.run("swatch.new", json!({"name": name, "color": "#123456"})).unwrap();
}
open(&mut app, "First color").unwrap();
set(&app, &ctx, &[("name", json!("Temporary name")), ("preview", json!(true))]);
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.active().unwrap().doc.swatch("Temporary name").is_some());
open(&mut app, "Second color").unwrap();
assert!(app.session.active().unwrap().doc.swatch("First color").is_some());
assert!(app.session.active().unwrap().doc.swatch("Temporary name").is_none());
set(&app, &ctx, &[("name", json!("New name")), ("preview", json!(false))]);
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.confirm_by_id(&ctx, dialog_id(KIND)));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(app.session.active().unwrap().doc.swatch("New name").is_some());
assert!(app.session.active().unwrap().doc.swatch("First color").is_some());
}
#[test]
fn swatch_options_shows_and_corrects_both_warnings() {
assert_eq!(shown_warnings(ColorPanelMode::RgbSliders), (true, true), "RGB shows both");
@@ -224,6 +224,37 @@ fn package_dialog(app: &mut VectorcraftApp, out: &str) {
set(app, "folder", json!(out)).unwrap();
}
#[test]
fn package_opening_drawing_is_required_before_saving_or_packaging() {
let dir = Folder::new("opening-drawing");
let mut app = saved(&dir);
let source = app.session.active().unwrap().uid;
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let destination = app.session.active().unwrap().uid;
let destination_path = dir.path("destination.vectorcraft");
app.run("document.save", json!({"path": destination_path})).unwrap();
let saved_destination = std::fs::read(&destination_path).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.active().unwrap().uid, source);
let out = dir.path("out");
package_dialog(&mut app, &out);
app.run("document.activate", json!({"index": 1})).unwrap();
assert_eq!(app.session.active().unwrap().uid, destination);
let accepted = press_ok(&mut app);
assert!(app.session.active().unwrap().is_dirty(), "Package leaves the different drawing unsaved");
assert_eq!(std::fs::read(&destination_path).unwrap(), saved_destination);
let package = std::path::Path::new(&out).join("card Folder");
assert!(!package.exists());
assert!(!accepted && matches!(held_state(&app), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(press_ok(&mut app));
assert!(package.join("card.vectorcraft").is_file());
assert!(!package.join("destination.vectorcraft").exists());
}
#[test]
fn package_is_written_in_the_background_as_it_is_at_once() {
let dir = Folder::new("background");
@@ -609,3 +640,28 @@ fn package_without_a_location_says_so() {
assert!(matches!(held_state(&app), Some(HeldOk::Refused(_))), "OK is refused with its reason");
assert!(with_package(&app, |_| ()).is_some(), "stays open");
}
#[test]
fn package_save_first_does_not_save_a_different_drawing() {
let mut app = windowed();
let picker = crate::tests::picks::scripted(&mut app);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("ui.packageDialog", json!({})).unwrap();
assert_eq!(confirm::open_question(&app).unwrap().2, "file.saveAs");
app.run("document.activate", json!({"index": 1})).unwrap();
answer_question(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
crate::tests::picks::poll(&mut app, &ctx);
assert!(picker.requests().is_empty(), "Package in drawing A must never start Save As for drawing B");
assert_eq!(app.ui.status, "This dialog was opened in a different document.");
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("ui.packageDialog", json!({})).unwrap();
answer_question(&mut app);
crate::tests::picks::poll(&mut app, &ctx);
assert_eq!(picker.requests().len(), 1, "approval in the opening drawing starts Save As");
}
@@ -277,6 +277,40 @@ fn the_presets_manager_exports_to_a_file_named_after_the_preset() {
}
}
#[test]
fn the_presets_manager_imports_browser_contents_and_desktop_paths() {
use super::perspective_presets::{self, Action};
use vectorcraft_engine::cmd::perspgrid::PRESET_FORMAT;
let mut app = app();
let picker = crate::tests_picks::scripted(&mut app);
let ctx = window(&app);
let fixture = |name: &str| json!({"format": PRESET_FORMAT, "presets": [{"name": name}]}).to_string();
app.run("ui.perspectivePresetsDialog", json!({})).unwrap();
let default = "[1P-Normal View]";
perspective_presets::run(&mut app, Action::Import, default).unwrap();
picker.answer_contents(&[("Browser.vcperspective", fixture("Browser").as_bytes())]);
crate::tests_picks::poll(&mut app, &ctx);
assert!(app.session.perspective_preset("Browser").is_some(), "the selected browser file adds its preset");
assert_eq!(field(&app, "selected"), json!("Browser"));
let dir = vectorcraft_testkit::TempDir::new("perspective-presets-picker");
let file = dir.join("Desktop.vcperspective");
std::fs::write(&file, fixture("Desktop")).unwrap();
perspective_presets::run(&mut app, Action::Import, "Browser").unwrap();
picker.answer(&[file.to_str().unwrap()]);
crate::tests_picks::poll(&mut app, &ctx);
assert!(app.session.perspective_preset("Desktop").is_some(), "the selected desktop file adds its preset");
assert_eq!(field(&app, "selected"), json!("Desktop"));
perspective_presets::run(&mut app, Action::Import, "Desktop").unwrap();
picker.cancel();
crate::tests_picks::poll(&mut app, &ctx);
assert_eq!(app.session.prefs.perspective_presets.len(), 2);
assert_eq!(field(&app, "selected"), json!("Desktop"));
}
#[test]
fn perspective_preset_menus_list_the_views_of_each_type() {
let app = app();
+45
View File
@@ -206,6 +206,34 @@ fn done_keeps_the_settings_without_printing_and_bad_settings_keep_the_dialog() {
assert!(!crate::menus::enabled(&app, "print.printerSetup"), "the mock has no settings to open");
}
#[test]
fn print_does_not_send_or_update_the_other_drawing() {
let (mut app, jobs) = app();
app.run("file.new", json!({"width": 180, "height": 100, "name": "Other drawing"})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 50, "height": 30})).unwrap();
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);
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "copies", json!(2));
activate(&mut app, 1);
confirm(&mut app);
assert!(jobs.borrow().is_empty());
let other = app.session.active().unwrap();
assert!(other.doc.print_setup.is_none());
assert_eq!(other.history.undo.len(), undo);
assert!(is_open(&app));
assert_eq!(fields(&app)["copies"], 2);
activate(&mut app, 0);
confirm(&mut app);
assert_eq!(jobs.borrow().len(), 1);
assert_eq!(pages(&jobs.borrow()[0].2), 6);
assert!(!is_open(&app));
}
/// A print queue that puts each page on the paper as it is, as `lp` does.
struct UprightQueue(Jobs);
@@ -482,6 +510,23 @@ fn a_print_preset_keeps_the_scale_link() {
assert_eq!(fields(&app)["scale"], json!({"width": 30, "height": 70, "linked": false}));
}
#[test]
fn print_preset_changes_survive_a_paused_preview() {
let (mut app, jobs) = app();
app.run("print.presets.save", json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap();
app.run("file.print", json!({})).unwrap();
pump(&mut app);
app.run("file.new", json!({"width": 90, "height": 90})).unwrap();
set(&mut app, "preset", json!("Apart"));
let ctx = ctx(&app);
super::print::pump(&mut app, &ctx);
assert_eq!(scale(&app), (30.0, 90.0, false));
assert!(jobs.borrow().is_empty());
app.run("document.activate", json!({"index": 0})).unwrap();
super::print::pump(&mut app, &ctx);
assert_eq!(scale(&app), (30.0, 90.0, false));
}
#[test]
fn a_scale_set_through_the_dialog_keeps_the_percentage_it_changes() {
let (mut app, _) = app();
+22 -1
View File
@@ -97,8 +97,12 @@ fn starting_fields(app: &VectorcraftApp) -> DialogFields {
pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value {
let ctx = app.ui_ctx.clone().unwrap_or_default();
let dialog = HostedParamDialog::new(&ctx, KIND, starting_fields(app), build).held_ok();
let drawing = crate::place::import_options_drawing(app, params);
let params = params.clone();
open_held(app, dialog, move |app, result| confirm(app, &params, result));
open_held(app, dialog, move |app, result| {
crate::place::check_import_options_drawing(app, drawing)?;
confirm(app, &params, result)
});
json!({ "dialog": KIND })
}
@@ -244,6 +248,23 @@ mod tests {
assert_eq!(app.ui.text_import["removeLineReturns"], true, "remembered for the next file");
}
#[test]
fn normal_text_place_options_wait_for_the_original_drawing() {
let mut app = host::app();
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(b"one\r\ntwo")});
assert_eq!(app.run("file.place", file).unwrap()["dialog"], KIND);
host::set(&app, KIND, "removeLineReturns", json!(true));
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let error = host::confirm(&mut app, KIND).expect_err("the other drawing must not receive the file");
assert!(error.contains("original drawing"), "{error}");
assert!(placed_text(&app).is_none());
assert_eq!(host::fields(&app, KIND)["removeLineReturns"], true);
app.run("document.activate", json!({"index": 0})).unwrap();
host::confirm(&mut app, KIND).unwrap();
assert_eq!(placed_text(&app).as_deref(), Some("one two"));
}
/// Every character set is a choice: one confirmed last comes back on the next text file and
/// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options
/// off the remembered set is the one the file is placed with.
+59 -1
View File
@@ -30,9 +30,20 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
}
// Graph tool click: the graph's size.
"graph" => {
let Some(document) = app.session.active().map(|doc| doc.uid) else {
app.status("Open a document before drawing a graph");
return;
};
let at = click_of(&p).map_or(Point::new(0.0, 0.0), |c| c.at);
let graph_type = p.get("type").cloned().unwrap_or(json!("column"));
let params = [("type", graph_type), ("x", json!(at.x)), ("y", json!(at.y)), ("width", json!(200)), ("height", json!(150))];
let params = [
("type", graph_type),
("x", json!(at.x)),
("y", json!(at.y)),
("width", json!(200)),
("height", json!(150)),
("__doc", json!(document)),
];
let params = params.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
let r = command::open(app, "graph.create", "Graph", params);
reported(app, r);
@@ -99,3 +110,50 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
_ => {}
}
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::dialog_id;
use vectorcraft_engine::Session;
use super::*;
fn confirm_graph(app: &mut VectorcraftApp) {
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
for _ in 0..2 {
host.with(|h| h.confirm_by_id(&ctx, dialog_id("graph.create")));
super::super::host::pump(app, &ctx);
}
}
#[test]
fn graph_size_without_a_document_keeps_the_source_status() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
open_tool_dialog(&mut app, "graph", json!({"x": 40.0, "y": 30.0}));
assert_eq!(app.ui.status, "Open a document before drawing a graph");
assert!(!app.any_dialog_open());
}
#[test]
fn graph_size_does_not_draw_in_a_different_document() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let opening = app.session.doc().unwrap().doc.clone();
let click = json!({"x": 40.0, "y": 30.0, "type": "column"});
open_tool_dialog(&mut app, "graph", click.clone());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
confirm_graph(&mut app);
assert_eq!(app.session.doc().unwrap().doc, other, "confirmation leaves the other document unchanged");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
open_tool_dialog(&mut app, "graph", click);
confirm_graph(&mut app);
let doc = &app.session.doc().unwrap().doc;
assert_eq!(doc.layers[0].children().unwrap().len(), 1);
}
}
+66 -40
View File
@@ -89,6 +89,8 @@ pub(crate) struct Manager {
data: RowsData,
/// What a button asked for, taken by [`pump`].
action: Option<Action>,
/// Identifies this opening when an Import picker finishes later.
import_owner: Arc<()>,
}
impl StackDialog for Manager {
@@ -180,8 +182,13 @@ impl StackDialog for Manager {
/// Open the presets manager on `selected` (default: the first preset, Default).
pub(crate) fn open(app: &mut VectorcraftApp, selected: Option<&str>) {
let manager =
Manager { list: image_trace::presets(app), selected: selected.unwrap_or("Default").to_string(), data: RowsData::of(app), action: None };
let manager = Manager {
list: image_trace::presets(app),
selected: selected.unwrap_or("Default").to_string(),
data: RowsData::of(app),
action: None,
import_owner: Arc::new(()),
};
match app.dialogs() {
Some(dialogs) => {
dialogs.with(|host| host.open(manager));
@@ -251,10 +258,11 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin
select(app, next.as_deref().unwrap_or("Default"));
}
Action::Import => {
let Some(owner) = with_manager(app, |m| Arc::clone(&m.import_owner)) else { return Ok(()) };
let name = file_asks::filter_name(crate::i18n::current(), "Tracing presets");
let request = PickRequest::open("tracingPresets").filter(name, TRACE_PRESET_EXTS);
// The answer, or its failure, reaches the status bar from the continuation; nothing is pending here.
let _ = file_asks::ask(app, request, Owner::Free, picked);
let _ = file_asks::ask(app, request, Owner::Free, move |app, answer| picked(app, answer, ImportSource::Picker(owner)));
}
Action::Export => {
crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}), |_, _| Ok(Value::Null))?;
@@ -263,20 +271,37 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin
Ok(())
}
/// The file Import… picked: a path on the desktop, the file's bytes on the web.
fn picked(app: &mut VectorcraftApp, picked: Picked) -> Result<Value, String> {
match picked {
Picked::Paths(paths) => {
if let Some(path) = paths.first() {
open_path(app, &path.to_string_lossy())?;
}
enum ImportSource {
FileOpen,
Picker(Arc<()>),
}
impl ImportSource {
fn matches(&self, manager: &Manager) -> bool {
match self {
Self::FileOpen => true,
Self::Picker(owner) => Arc::ptr_eq(owner, &manager.import_owner),
}
Picked::Contents(files) => {
if let Some((_, bytes)) = files.first() {
open_file(app, bytes)?;
}
fn select(&self, app: &VectorcraftApp, name: &str) {
let _ = with_manager(app, |manager| {
if self.matches(manager) {
manager.selected = name.to_string();
}
}
_ => {}
});
}
}
/// The file Import… picked, a path on the desktop or the file's bytes on the web.
fn picked(app: &mut VectorcraftApp, picked: Picked, source: ImportSource) -> Result<Value, String> {
let file = match picked {
Picked::Paths(paths) => paths.first().map(|path| file_contents(app, json!({ "path": path.to_string_lossy() }))).transpose()?,
Picked::Contents(files) => files.first().map(|(_, bytes)| checked_contents(bytes)).transpose()?,
_ => None,
};
if let Some(file) = file {
open_import(app, file, source)?;
}
Ok(Value::Null)
}
@@ -294,6 +319,7 @@ fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec<Val
struct ReplaceFile {
file: Value,
first: Option<String>,
source: ImportSource,
}
/// The Replace question. Its own type, so the host keeps its answer apart from every other prompt's.
@@ -301,22 +327,23 @@ pub(crate) struct ReplacePresets(pub(crate) StandardPrompt);
crate::dialogs::confirm::wrapped_dialog!(ReplacePresets, StandardPrompt, REPLACE_KIND);
/// Asks whether the import of `file` replaces the saved presets `skipped` kept, over the manager
/// when it is open.
fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value) {
/// Asks whether the import of `file` replaces the saved presets `skipped` kept. It opens over the
/// manager if the import targets that opening.
fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value, source: ImportSource) {
let names: Vec<Label> = skipped.iter().filter_map(Value::as_str).map(|n| Label::from(n.to_string())).collect();
let first = skipped.first().and_then(Value::as_str).map(str::to_owned);
let prompt = StandardPrompt::custom(tl!("Replace the saved presets that have these names?"))
.lines(names)
.button(PromptChoice::Proceed, tl!("Replace"))
.button(PromptChoice::Cancel, tl!("Cancel"))
.tag(ReplaceFile { file, first });
.button(PromptChoice::Cancel, tl!("Cancel"));
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| {
if host.is_open::<Manager>() {
host.open_child(ReplacePresets(prompt), dialog_id(KIND));
let over_manager = host.get::<Manager>().is_some_and(|manager| source.matches(manager));
let prompt = ReplacePresets(prompt.tag(ReplaceFile { file, first, source }));
if over_manager {
host.open_child(prompt, dialog_id(KIND));
} else {
host.open(ReplacePresets(prompt));
host.open(prompt);
}
});
}
@@ -331,12 +358,12 @@ fn answer_replace(app: &mut VectorcraftApp) {
if answer.choice != PromptChoice::Proceed {
return;
}
let Some(ReplaceFile { mut file, first }) = answer.take_tag::<ReplaceFile>() else { return };
let Some(ReplaceFile { mut file, first, source }) = answer.take_tag::<ReplaceFile>() else { return };
file["replace"] = json!(true);
match app.run("imageTrace.presets.import", file) {
Ok(_) => {
if let Some(first) = first {
select(app, &first);
source.select(app, &first);
}
}
Err(e) => app.status(e),
@@ -363,37 +390,36 @@ fn file_contents(app: &VectorcraftApp, file: Value) -> Result<Value, String> {
(None, Some(read)) => read(path)?,
(None, None) => return Err("no file reader".into()),
};
checked_contents(&bytes)
}
fn checked_contents(bytes: &[u8]) -> Result<Value, String> {
if bytes.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(&bytes) }))
Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }))
}
/// A tracing presets file opened (File › Open, a drop, or the file Import… picked): it imports as
/// Import… does, over the manager when it is open (which selects the first preset it added), and
/// asks whether to replace saved presets of the file's names.
/// Imports a tracing presets file opened through File › Open or a drop. The open manager selects
/// the first newly imported preset and hosts the question about duplicates.
pub(crate) fn open_file(app: &mut VectorcraftApp, bytes: &[u8]) -> Result<(), String> {
if bytes.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
open_import(app, json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }))
open_import(app, checked_contents(bytes)?, ImportSource::FileOpen)
}
/// [`open_file`] for the tracing presets file at `path` (File › Open, a drop, Import…): the file is
/// read no further than one byte past the size limit.
/// [`open_file`] for the file at `path`. Reads at most one byte past the size limit.
pub(crate) fn open_path(app: &mut VectorcraftApp, path: &str) -> Result<(), String> {
let file = file_contents(app, json!({ "path": path }))?;
open_import(app, file)
open_import(app, file, ImportSource::FileOpen)
}
/// The import of a tracing presets file `file` (`{dataBase64}`), over the manager when it is open.
fn open_import(app: &mut VectorcraftApp, file: Value) -> Result<(), String> {
/// Imports the file into the saved presets and directs its dialog changes to the import's source.
fn open_import(app: &mut VectorcraftApp, file: Value, source: ImportSource) -> Result<(), String> {
let (imported, skipped) = import_file(app, &file)?;
if let Some(first) = imported.get(0).and_then(Value::as_str) {
select(app, first);
source.select(app, first);
}
if !skipped.is_empty() {
ask_replace(app, &skipped, file);
ask_replace(app, &skipped, file, source);
}
Ok(())
}
@@ -1,6 +1,7 @@
//! Edit → Tracing Presets: New… and Edit… through the preset editor, Delete, and the import with
//! the question about saved presets of the same names, all through the dialog host.
use craft::host::ScriptedFiles;
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{FieldValue, HostedParamDialog};
use serde_json::{Value, json};
@@ -297,6 +298,47 @@ fn import_asks_before_replacing_saved_presets() {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn delayed_import_keeps_the_reopened_tracing_preset_managers_selection() {
let (mut app, ctx) = windowed(Default::default());
let files = Arc::new(ScriptedFiles::held());
let host = app.host.with_files(files.clone());
host.clone().install(&ctx);
app.host = Arc::new(host);
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
press(&mut app, &ctx, Action::Import);
assert_eq!(files.open(), 1);
let dialogs = app.dialogs().unwrap();
assert!(dialogs.with(|host| host.cancel::<Manager>(&ctx)));
app.run("ui.tracingPresetsDialog", json!({"selected": "6 Colors"})).unwrap();
let contents =
br#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Poster", "params": {"noise": 40}}, {"name": "Ink", "params": {}}]}"#;
assert!(files.answer(Picked::Contents(vec![("picked.vctracepresets".into(), contents.to_vec())])).is_some());
crate::file_asks::poll(&mut app);
pass(&mut app, &ctx);
assert_eq!(saved_names(&app), ["Poster", "Ink"], "the requested import still adds new presets");
assert_eq!(selected(&app).as_deref(), Some("6 Colors"), "the reopened manager keeps its own selection");
let replace = dialog_id(REPLACE_KIND);
dialogs.with(|host| {
assert!(host.is_open::<ReplacePresets>());
assert_eq!(host.stack().parent(replace), None, "the duplicate question does not belong to the reopened manager");
host.set_json_field(&ctx, replace, "choice", json!("proceed")).unwrap();
assert!(host.confirm_by_id(&ctx, replace));
});
pass(&mut app, &ctx);
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40, "Replace still updates the saved preset");
assert_eq!(selected(&app).as_deref(), Some("6 Colors"), "Replace leaves the reopened manager's selection alone");
press(&mut app, &ctx, Action::Import);
let current_pick = br#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Graphite", "params": {}}]}"#;
assert!(files.answer(Picked::Contents(vec![("current.vctracepresets".into(), current_pick.to_vec())])).is_some());
crate::file_asks::poll(&mut app);
pass(&mut app, &ctx);
assert_eq!(selected(&app).as_deref(), Some("Graphite"), "the current manager selects the preset it imported");
}
#[test]
fn a_file_with_a_fault_changes_nothing() {
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-bad-{}", std::process::id()));
+7 -1
View File
@@ -689,7 +689,13 @@ pub fn ask_revert(app: &mut VectorcraftApp) -> Result<Value, String> {
(c.enabled)(&app.session)?;
let name = app.session.active().map(|d| d.title()).unwrap_or_default();
let message = crate::i18n::fmt(tl!("Revert to the saved version of “{name}”?"), &[("name", &name)]);
dialogs::confirm::ask(app, &message, tl!("Changes made since it was last saved will be lost."), "file.revert", json!({ "confirmed": true }));
dialogs::confirm::ask_in_document(
app,
&message,
tl!("Changes made since it was last saved will be lost."),
"file.revert",
json!({ "confirmed": true }),
);
Ok(json!({ "pending": dialogs::confirm::KIND }))
}
+2
View File
@@ -288,6 +288,8 @@ pub struct VectorcraftApp {
pub(crate) three_d: panels::three_d::Model,
/// The open export option dialogs and what runs after each.
pub(crate) export_dialogs: dialogs::export_host::ExportDialogs,
/// The drawing the open Package dialog saves and collects.
pub(crate) package_document: Option<u64>,
/// Save for Web's renders and colour table.
pub(crate) web_export: dialogs::save_for_web::WebExport,
/// The Flattener Preview panel's model.
@@ -14,6 +14,21 @@ fn app() -> VectorcraftApp {
app
}
#[test]
fn the_swatch_libraries_footer_button_uses_the_interface_language() {
use craft::ui::testing::Fixture;
for (locale, label) in [("en", "Swatch Libraries Menu"), ("de", "Menü „Farbfeldbibliotheken“"), ("ja", "スウォッチライブラリメニュー")]
{
let mut app = app();
app.session.prefs.interface_language = locale.into();
crate::i18n::set_current(app.ui_language());
let mut fixture = Fixture::new(move |ui| crate::panels::swatches::show(&mut app, ui));
fixture.settle();
assert!(fixture.by_label(label).is_some(), "missing {locale} Swatch Libraries button name: {label}");
}
}
/// A context whose frames report their accessibility tree, so rows are found by their names.
pub(crate) fn context() -> egui::Context {
let ctx = crate::testing::ui_context();
+2 -2
View File
@@ -27,7 +27,7 @@ use craft::host::{PickKind, PickRequest};
use craft::keymap::CommandRef;
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::display::{Shade, Text};
use craft::ui::display::{Elide, Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::list::{List, ListRow, ThumbSize};
@@ -958,7 +958,7 @@ fn link_info(ui: &mut Ui, app: &VectorcraftApp, info: Option<(u64, &Value)>, uni
if IconButton::new(IconId::new("folder-open")).label(tl!("Show in Folder")).enabled(can_reveal).show(ui).clicked() {
reveal = Some(id);
}
Text::new(l.to_string()).show(ui);
Text::new(l.to_string()).elide(Elide::Path).tooltip(l.to_string()).show(ui);
});
});
}
+1 -1
View File
@@ -777,7 +777,7 @@ fn footer(app: &mut VectorcraftApp, ui: &mut Ui) {
// Libraries, Show Swatch Kinds and the edit action sit at the start edge; Delete at the end edge, then New Swatch
// and New Color Group before it.
let actions = [
FooterAction::new(icon("library"), SwatchLibraries::MENU).pressed(library_panel::any_open::<SwatchLibraries>(&app.ui)),
FooterAction::new(icon("library"), tl!(SwatchLibraries::MENU)).pressed(library_panel::any_open::<SwatchLibraries>(&app.ui)),
FooterAction::new(icon("dc-swatch-kinds"), tl!("Show Swatch Kinds")).pressed(kind != Kind::All),
edit,
FooterAction::new(icon("trash-2"), tl!("Delete Swatch"))
+24
View File
@@ -420,6 +420,30 @@ fn edit_original_and_show_in_folder_hand_the_file_to_the_system() {
assert!(app.run("links.editOriginal", json!({"id": linked})).is_err());
}
#[test]
fn a_long_link_location_fits_the_minimum_width_float() {
use crate::panel_docking::PANEL_MIN_WIDTH;
use crate::tests::panel_harness::{Place, floated};
let folder = Folder::new("location-width");
let subfolder = folder.0.join("Überlagerung".repeat(5));
std::fs::create_dir_all(&subfolder).unwrap();
let path = subfolder.join("Éléments.png");
std::fs::write(&path, png(30, 20)).unwrap();
for locale in ["en", "fr", "de"] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let placed = app.run("file.place", json!({"path": path, "at": [100, 100]})).unwrap();
let info = app.run("links.info", json!({"id": placed["ids"][0]})).unwrap();
let location = info["location"].as_str().unwrap();
let names = ["Location", location, "Show in Folder"];
app.services.reveal = Some(Box::new(|_| Ok(())));
let panel = floated(app, "links", locale, Place::Floating(PANEL_MIN_WIDTH), &names);
let past = panel.past_named(&names);
assert!(past.is_empty(), "{locale} location row outside {:?}: {past:?}", panel.body);
}
}
/// The Location row of Link Info has a Show in Folder button that shows the file of the image Link
/// Info shows. An embedded image has no Location row; the button is off while the file is missing
/// and without a file manager (the web).
+12
View File
@@ -121,6 +121,18 @@ const ASKED: &str = "__placeCursorAsk";
/// document; hidden from the dialog's fields and removed before the file is placed.
const DROPPED: &str = "__dropTarget";
/// Normal Place import options wait for their opening drawing. Canvas drops already name their destination.
pub(crate) fn import_options_drawing(app: &VectorcraftApp, params: &Value) -> Option<u64> {
app.session.active().filter(|_| params.get(DROPPED).is_none()).map(|st| st.uid)
}
pub(crate) fn check_import_options_drawing(app: &VectorcraftApp, drawing: Option<u64>) -> Result<(), String> {
if drawing.is_some_and(|drawing| app.session.active().is_none_or(|st| st.uid != drawing)) {
return Err(tl!("Return to the original drawing to place the file").into());
}
Ok(())
}
/// The `file.place` param that holds the import options a Shift-click of the place cursor set
/// aside ([`set_aside_import_options`]): the file is placed with them when no import options dialog
/// opens for it. Removed before any dialog opens.
+21
View File
@@ -494,3 +494,24 @@ fn file_save_writes_opened_eps_back_without_another_save_as_dialog() {
assert_eq!(app.session.active().unwrap().path.as_deref(), Some(path.as_str()));
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn revert_confirmation_never_discards_another_drawings_changes() {
let d = dir("revert-drawing-switch");
let mut app = app();
for name in ["first.vectorcraft", "second.vectorcraft"] {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let path = d.join(name).to_string_lossy().to_string();
app.run("file.saveAs", json!({"path": path})).unwrap();
rect(&mut app);
}
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("file.revert", json!({})).unwrap();
assert!(confirm::open_question(&app).unwrap().0.contains("first"));
app.run("document.activate", json!({"index": 1})).unwrap();
let count = objects(&app);
answer_top(&mut app, true);
let result = (objects(&app), app.session.active().unwrap().is_dirty());
let _ = std::fs::remove_dir_all(d);
assert_eq!(result, (count, true), "the second drawing must retain its unsaved edits");
}