diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 735821d998..093d91695a 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -6,7 +6,7 @@ use std::borrow::Cow; use craft::menu::Node; -use craft::ui::canvas::{ViewCommands, ViewRequest}; +use craft::ui::canvas::ViewCommands; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Value, json}; @@ -243,7 +243,8 @@ pub(crate) fn zoom(app: &mut VectorcraftApp) -> Result { return Err("nothing selected".into()); }; let bounds = st.doc.bounds_of(&st.selection.objects, true); - app.request_view(ViewRequest::Command(ViewCommands::FitLayers), bounds); + // At once, as production fitted: a dialog's OK that selects and zooms shows the fit without another frame. + app.view_now(ViewCommands::FitLayers, bounds); Ok(Value::Null) } diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 06c803114e..ad24ac5a37 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -68,8 +68,8 @@ fn zoom_to_selection_fits_the_selection_in_the_view() { app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(560.0, 460.0)); app.run("select.set", json!({"ids": [b.0]})).unwrap(); assert!(menus::enabled(&app, ZOOM)); + // The view fits at once, in the canvas it was laid out in. app.run(ZOOM, json!({})).unwrap(); - host::frame(&mut app); let (canvas, view) = (app.view().unwrap().rect, app.canvas_view().unwrap()); let selected = bounds(&app, b); let (min, max) = ( diff --git a/crates/ui-egui/src/addons/image/tests.rs b/crates/ui-egui/src/addons/image/tests.rs index 8ebbe5b2ca..154972dec7 100644 --- a/crates/ui-egui/src/addons/image/tests.rs +++ b/crates/ui-egui/src/addons/image/tests.rs @@ -190,6 +190,8 @@ fn color_mask_previews_keeps_its_settings_and_comes_off() { let fields = dialog_fields(&app); assert_eq!((fields["background"].as_str(), fields["tolerance"].as_f64()), (Some("edges"), Some(10.0))); assert!(fields.get("masked").is_none()); + // The Preview box starts off (#5360). + set(&app, "preview", json!(true)); set(&app, "tolerance", json!(20)); pump(&mut app); assert_eq!(masked_alphas(&app), [0, 0, 255], "the preview hides the white and the ring"); diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 34fbc1041b..42d8bf13a1 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -10,7 +10,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::Session; use vectorcraft_three_d::fold::raster::{Image, MAX_PIXELS, MAX_SIDE}; -use super::{PrintKey, Settings, Shown, View, inside_color, show, status, store}; +use super::{PrintKey, Settings, Shown, View, inside_color, show, status}; use crate::VectorcraftApp; /// How long a test waits for the print to render. @@ -473,14 +473,16 @@ fn the_view_is_folded_and_drawn_again_only_when_something_changes() { let mut rig = Rig::front(); let folded = |rig: &Rig| rig.app.borrow().addon_panels.fold_view.folded.as_ref().map(|f| Arc::clone(&f.1)).expect("a fold"); let image = |rig: &Rig| rig.app.borrow().addon_panels.fold_view.shown.as_ref().map(|s| Arc::clone(&s.image)).expect("an image"); - // Frames one at a time, as the store counts the uploads of one frame. + // Frames one at a time, each counted when it shows a newly drawn image: the store's upload count is of the frame + // running, so it reads none between frames. let uploads = |rig: &mut Rig| { (0..5) - .map(|_| { + .filter(|_| { + let before = image(rig); rig.fx.frame(vec![]); - store(rig.fx.ctx()).statistics(rig.fx.ctx()).uploads + !Arc::ptr_eq(&before, &image(rig)) }) - .sum::() + .count() }; let (fold, img) = (folded(&rig), image(&rig)); assert_eq!(uploads(&mut rig), 0, "nothing changed: no render"); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index aa25651ae1..e18e57e161 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -1,5 +1,5 @@ use craft::behavior::{CanvasView, ZoomScheme}; -use craft::ui::canvas::{NavigationOptions, ViewRequest}; +use craft::ui::canvas::{NavigationOptions, ViewCommands, ViewRequest}; use serde_json::Value; use vectorcraft_engine::Prefs; @@ -169,6 +169,26 @@ impl VectorcraftApp { } } + /// Runs `command` on the active view at once, in the canvas its last pass laid out, and eases the canvas there; + /// `bounds` are the layers' bounds for Fit Layers. Without a window, or before the canvas was laid out, the canvas + /// runs it in its next pass. + pub(crate) fn view_now(&mut self, command: ViewCommands, bounds: Option) { + let (Some(ctx), Some(win), Some(_)) = (self.ui_ctx.clone(), crate::doc_windows::current(self), self.canvas_view()) else { + return self.request_view(ViewRequest::Command(command), bounds); + }; + let target = crate::canvas::view_target(self, win); + let (scaling, ppp) = (self.ui_scaling(), ctx.pixels_per_point()); + let scheme = zoom_scheme(&self.session.prefs, ppp / ctx.zoom_factor()); + let Some(v) = self.view_mut() else { return }; + let before = *v; + let mut cv = v.canvas(scaling, v.rect); + let layers = move || bounds; + if command.apply(&mut cv, &target, Some(&layers), ppp, &scheme) { + v.set_canvas(&cv, scaling); + self.ease_view(before); + } + } + pub fn view_info(&self) -> ViewInfo { ViewInfo { // The tools measure their tolerances and widgets in the interface's points. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a37ec2bc21..56f242b7e4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -306,7 +306,7 @@ fn scroll_bars(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Op /// The size of the art and the artboards together, and the artboard Fit Artboard shows (the view's, /// the first when it has gone). -fn view_target(app: &VectorcraftApp, win: Win) -> ViewTarget { +pub(crate) fn view_target(app: &VectorcraftApp, win: Win) -> ViewTarget { let (Some(st), Some(view)) = (app.session.documents().get(win.0), doc_windows::view(app, win)) else { return ViewTarget::new(Size::new(1.0, 1.0)); }; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index e8891acf11..d7840e9ad1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1444,6 +1444,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val if params.get("dialog").is_none_or(Value::is_null) { params["dialog"] = json!("top"); } + // Save PDF's Custom… options are the app's, not the dialog's settings. + if method == "ui.dialog.set" + && let Some(r) = crate::dialogs::save_pdf::dialog_set(app, ¶ms) + { + return wrap(r); + } // `ui.dialog.set {action}` answers the dialog after setting its fields: the app's own key, which the // framework's method does not take. let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None }; diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index ff49c7b998..9584166098 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -4,7 +4,7 @@ //! ([`ask_missing_font_edit`]). Both texts are shown as given: callers translate their template //! before filling in a name, so the name is never translated. -use craft::ui::dialog::{Alert, DialogHost, DialogResult, HostedAlert, PromptChoice, StackDialog, StandardPrompt, StartupStage}; +use craft::ui::dialog::{Alert, DialogHost, DialogId, DialogResult, HostedAlert, PromptChoice, StackDialog, StandardPrompt, StartupStage}; use egui::Context; use serde_json::{Value, json}; @@ -141,8 +141,22 @@ pub fn tell(app: &mut VectorcraftApp, message: &str, detail: &str) { return; } told.push((message.to_string(), detail.to_string())); - let alert = HostedAlert::new(Alert::new(message.to_string(), detail.to_string()).ok_label(tl!("Close"))); - dialogs.with(|host| open_or_wait(host, Message(alert))); + dialogs.with(|host| open_or_wait(host, message_dialog(message, detail))); +} + +/// [`tell`] over the open dialog `parent`, at once: the message shows above it, and `parent` shows again when the +/// message closes. +pub(crate) fn tell_over(app: &mut VectorcraftApp, parent: DialogId, message: &str, detail: &str) { + let Some(dialogs) = app.dialogs() else { + return; + }; + // Shown before the messages waiting their turn, so it is the first the host closes. + app.told.0.insert(0, (message.to_string(), detail.to_string())); + dialogs.with(|host| host.open_child(message_dialog(message, detail), parent)); +} + +fn message_dialog(message: &str, detail: &str) -> Message { + Message(HostedAlert::new(Alert::new(message.to_string(), detail.to_string()).ok_label(tl!("Close")))) } /// Opens `dialog` at once when no other dialog is open or waiting, else queues it to open after them. diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index f6bc39cd94..9a01842160 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -14,7 +14,7 @@ use std::path::PathBuf; use craft::host::{PickRequest, Picked}; use craft::ui::contract::Bind; use craft::ui::dialog::{DialogId, PromptChoice, StandardPrompt}; -use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, ParamDialog, ParamResult}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamResult}; use craft::ui::runtime::memory::{Lifetime, SaveKey}; use serde_json::{Map, Value, json}; @@ -189,7 +189,8 @@ fn defaults_of(id: &str) -> Map { } /// `values` as the dialog's rows show them: in the effect's current form, a Pathfinder effect's -/// options filled in, Duotone's tones padded and Radial Blur's centre within its bounds. +/// options filled in, Duotone's tones padded, Radial Blur's centre within its bounds and Rasterize's +/// resolution as its preset. fn normalized(app: &VectorcraftApp, id: &str, values: Map, fresh: bool) -> Map { let mut values = match vectorcraft_effects::upgrade_params(id, &Value::Object(values)) { Value::Object(m) => m, @@ -200,10 +201,21 @@ fn normalized(app: &VectorcraftApp, id: &str, values: Map, fresh: super::duotone::pad_tones(&mut values); } else if id == super::effect_params::RADIAL_BLUR { super::effect_rows::clamp_blur_center(&mut values); + } else if id == vectorcraft_effects::RASTERIZE { + super::raster_effects::preset_of(&mut values); } values } +/// The params `rows` show for `fields`, as the effect `id` takes them: Rasterize's preset back to its resolution. +fn params_of_rows(id: &str, rows: &[Param], fields: &DialogFields) -> Map { + let mut params = form::json_of(rows, fields); + if id == vectorcraft_effects::RASTERIZE { + super::raster_effects::resolution_of(&mut params); + } + params +} + /// Asks whether to edit the applied effect or add another one; [`pump`] reads the answer. fn ask(app: &mut VectorcraftApp, mut open: Open) -> Result { let name = label(&open.cx.id); @@ -244,7 +256,7 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map } let (baseline, shown) = (normalized(app, &id, baseline, fresh), normalized(app, &id, shown, fresh)); let rows = effect_params(&open.cx, &DialogFields::new()); - open.opened = form::json_of(&rows, &form::fields_of(&rows, &baseline)); + open.opened = params_of_rows(&id, &rows, &form::fields_of(&rows, &baseline)); let fields = form::fields_of(&rows, &shown); let (cx, title) = (open.cx.clone(), heading(&open.cx)); @@ -308,7 +320,7 @@ fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) - /// effect, with the rows whose value differs from the opening values. fn command(open: &Open, fields: &DialogFields) -> (&'static str, Value) { let rows = effect_params(&open.cx, fields); - let mut params = form::json_of(&rows, fields); + let mut params = params_of_rows(&open.cx.id, &rows, fields); params.retain(|k, v| open.opened.get(k) != Some(v)); // The Style row's companion says the user chose a style: the other targets keep their own // Warp ids otherwise. diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index e468f1ac43..15eb1c5db4 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -151,7 +151,7 @@ pub(crate) fn as_written(o: &mut FlattenOptions, overprint: Overprint) { } /// The name of the flattener preset Save PDF `parent` flattens with, as the list names it. -fn preset_name(parent: &HostedPdfExport) -> String { +pub(super) fn preset_name(parent: &HostedPdfExport) -> String { let name = parent.settings().flattener_preset.trim(); let name = if name.is_empty() { pdf::DEFAULT_FLATTENER } else { name }; FlattenOptions::preset_label(&name.to_ascii_lowercase()).unwrap_or(name).to_string() diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index fd6156d8d2..a84a748dea 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -14,9 +14,11 @@ fn host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost) -> R) -> R { app.dialogs().expect("a window host").with(f) } +/// The frame's dialog pumps, then the paste waiting on a question that was answered, as the frame's tick runs it. fn pump(app: &mut VectorcraftApp) { let ctx = app.ui_ctx.clone().expect("a window context"); crate::dialogs::host::pump(app, &ctx); + crate::placing::settle_swatch_paste(app); } fn is_open(app: &VectorcraftApp) -> bool { diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index 7646199f98..4ff53c7cba 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -455,7 +455,7 @@ pub(crate) fn wait() { /// List the folder on the first frame, after `view.proofSetup.save` wrote a setup (from the dialog, /// a control client or the command palette), and when the window becomes the active one, so a setup /// copied into the folder is listed without a restart; take in the listings that ended. Once no -/// picker is open, the folder Save… made is removed if it is still empty. +/// picker is open and its answer was carried out, the folder Save… made is removed if it is still empty. fn list_saved(app: &mut VectorcraftApp, ctx: &egui::Context) { // A pass applies only its own input: the focus event is in the frame's first pass, so a second // pass of the frame does not list again. @@ -463,7 +463,9 @@ fn list_saved(app: &mut VectorcraftApp, ctx: &egui::Context) { let saves = app.session.proof_setup_saves(); let start = { let mut saved = saved(); + // An answered pick waits for `file_asks::poll` to write into the folder. if !app.file_dialog_open() + && !app.file_asks.asking() && let Some(dir) = saved.made.take() { // A folder that a setup was saved in is not empty, and stays. @@ -809,7 +811,8 @@ mod tests { refresh_saved(&app); wait(); // Load… puts the file's settings back in the dialog. - for (k, v) in [("device", json!(WORKING)), ("intent", json!("perceptual")), ("preserveNumbers", json!(false))] { + // Preserve Numbers off first: the intent takes no input while it is on. + for (k, v) in [("device", json!(WORKING)), ("preserveNumbers", json!(false)), ("intent", json!("perceptual"))] { set(&mut app, &ctx, k, v); } files.queue(Picked::Paths(vec![file.clone()])); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index cae9945831..b4a02dcc87 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -377,9 +377,7 @@ fn sync(app: &mut VectorcraftApp, d: &mut Fields) { Ok(r) => { let mut rows = r["map"].as_array().cloned().unwrap_or_default(); let assign = d.fields.get("__assign").and_then(Value::as_array).cloned().unwrap_or_default(); - for (row, to) in rows.iter_mut().zip(assign) { - row["to"] = to; - } + assign_colors(&mut rows, assign); number_slots(&mut rows); snap(app, d, &mut rows); d.fields.insert("rows".into(), Value::Array(rows)); @@ -399,6 +397,26 @@ fn sync(app: &mut VectorcraftApp, d: &mut Fields) { d.fields.remove(WEIGHED); } +/// Gives `rows` the new colors `assign`: a row that lists one of them takes it, so art in the group's own colors (art +/// linked to its swatches) keeps them; the others go to the other rows in order. +fn assign_colors(rows: &mut [Value], assign: Vec) { + let mut given = vec![false; rows.len()]; + let mut rest = Vec::new(); + for to in assign { + let own = row_listing(rows, &to).and_then(|r| rows.iter().position(|x| std::ptr::eq(x, r))).filter(|&i| !given[i]); + match own { + Some(i) => { + rows[i]["to"] = to; + given[i] = true; + } + None => rest.push(to), + } + } + for (row, to) in rows.iter_mut().zip(given).filter_map(|(row, given)| (!given).then_some(row)).zip(rest) { + row["to"] = to; + } +} + /// The fields of Prominent Colors: the weights the rows are to take (`recolor.weigh`'s `weights`, /// one per row; a new list moves the rows' current colors), the weights they last took, each row's /// share of the art's uses (`recolor.weigh`'s `shares`) and the rows' current colors, exclusions diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index 93f279f003..6497550e1b 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -372,7 +372,8 @@ mod tests { let ctx = ctx(app); let dialogs = app.dialogs().expect("a window"); for _ in 0..2 { - ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear(); + // With the app's frame input, as the hosts give it: the dialog takes its pick's answer from the host there. + crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |_, ui| dialogs.with(|host| host.run(ui))); crate::dialogs::host::pump(app, &ctx); } } diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 14feb4b2c1..9b59bd5208 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -577,6 +577,23 @@ pub(crate) fn reset_all(dialog: &mut HostedParamDialog, effect: &str) { } } +/// Drops from `params` the light settings `effect` doesn't take: the light editor lists all six, and the classic effects +/// take neither a colour nor a softness. +pub(super) fn drop_untaken_light_keys(effect: &str, params: &mut serde_json::Map) { + for (_, key) in LIGHT_KEYS { + if let Some(value) = params.get(key) + && vectorcraft_engine::cmd::params::check_effect_params( + "effect.apply", + effect, + &Value::Object([(key.to_owned(), value.clone())].into_iter().collect()), + ) + .is_err() + { + params.remove(key); + } + } +} + const LIGHT_KEYS: [(&str, &str); 6] = [ ("color", "lightColor"), ("intensity", "lightIntensity"), diff --git a/crates/ui-egui/src/dialogs/revolve_gizmo.rs b/crates/ui-egui/src/dialogs/revolve_gizmo.rs index ff83838e25..3ef06cecef 100644 --- a/crates/ui-egui/src/dialogs/revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/revolve_gizmo.rs @@ -760,6 +760,18 @@ fn write(dialog: &mut HostedParamDialog, before: GizmoValues, landed: GizmoValue } } +/// Puts the keys the gizmo writes back as `start` held them, value for value: Escape restores the fields as they were, +/// not only their numbers. +fn restore(dialog: &mut HostedParamDialog, start: &DialogFields) { + for key in KEYS.iter().copied().chain(["lights", "lightRotation", "lightHeight"]) { + match start.get(key) { + Some(value) if dialog.fields().get(key) != Some(value) => dialog.set_field(key, value.clone()), + Some(_) => {} + None => dialog.clear_field(key), + } + } +} + /// The gizmo over the canvas while the 3D effect's dialog shows it, then the Map Art outline: each event's values go /// to the dialog's fields, which its preview applies. pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { @@ -768,12 +780,23 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) { && let Some(fields) = three_d::with_fields(app, |dialog| dialog.fields().clone()) && shown(&fields) { + // The dialog is modal and keeps the canvas's view open: the gizmo's presses pass its layer as a canvas tool's do. + if let Some(canvas) = crate::doc_windows::current(app).map(crate::canvas::canvas_id) { + craft::ui::runtime::sampler::pass_tool_gesture(ui.ctx(), canvas, craft::ui::contract::CanvasGesture::PRIMARY); + } let before = GizmoValues::of(&fields); let label = if lighting(&fields) { tl!("Lighting") } else { tl!("Rotation") }; let subject = Subject { fields, bounds }; let output = RevolveGizmo::new(label, Bind::given(before), &subject).show_at(ui, space.view.rect); - // The last value of the pass's events, a cancel's included: Escape writes the values back. - if let Some(landed) = output.edit.events.landed().copied() { + // The fields as the gesture found them, for its cancel. + let start = egui::Id::unique("revolve-gizmo-start"); + if output.edit.events.began() { + ui.data_mut(|d| d.insert_temp(start, subject.fields.clone())); + } + let cancelled = output.edit.events.cancel_reason().is_some().then(|| ui.data_mut(|d| d.remove_temp::(start))).flatten(); + if let Some(start) = cancelled { + three_d::with_fields(app, |dialog| restore(dialog, &start)); + } else if let Some(landed) = output.edit.events.landed().copied() { three_d::with_fields(app, |dialog| write(dialog, before, landed)); } } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs index a3c3b0859a..424912c78d 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs @@ -3,10 +3,11 @@ use serde_json::{Value, json}; use vectorcraft_engine::cmd::webexport; -use craft::ui::patterns::form_dialogs::{ColorTableEdit, PALETTE_COLOR_KEY, TableOrder}; +use craft::ui::patterns::form_dialogs::{ColorTableEdit, TableOrder}; use super::color_table::{apply, marks, restore, shift}; -use super::tests::{app, frame, host, save, set}; +use super::tests::{app, frame, host, id, save, set}; +use crate::VectorcraftApp; const A: [u8; 3] = [0x00, 0x00, 0x00]; const B: [u8; 3] = [0x11, 0x11, 0x11]; @@ -109,8 +110,48 @@ fn an_edit_skips_selected_colors_the_table_does_not_show() { assert_eq!((&t["customPalette"], &t["deleted"]), (&json!(["#000000", "#111111"]), &json!(["#111111"]))); } -/// The dialog's colour request, answered by the Color Picker's OK, shifts the colour; no answer -/// shifts nothing. +/// One app frame with `events`, a moment after the last. +fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let time = ctx.input(|i| i.time) + 0.05; + crate::testing::app_frame(app, ctx, egui::RawInput { time: Some(time), focused: true, events, ..Default::default() }); +} + +/// Double-clicks the Color Table's cell of `hex` in drawn frames, as a user opens it, and gives the Color Picker the +/// app opens over the dialog for it. +fn open_cell(app: &mut VectorcraftApp, ctx: &egui::Context, hex: &str) -> craft::ui::dialog::DialogId { + let parent = id(app); + app_frame(app, ctx, vec![]); + // The cells are named by their index and colour. + let find = |app: &mut VectorcraftApp, name: &str| { + let (find, _) = craft::automation::ControlRequest::new("ui.find", json!({"name": name})); + match crate::control::handle(app, ctx, &find) { + craft::automation::Reply::Done(r) if r["ok"] == true => { + r["result"]["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::>()) + } + _ => None, + } + }; + let rect = (0..256).find_map(|i| find(app, &format!("{i} {hex}"))).unwrap_or_else(|| panic!("the table shows {hex}")); + let at = egui::pos2((rect[0] + rect[2] / 2.0) as f32, (rect[1] + rect[3] / 2.0) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + for events in [ + vec![egui::Event::PointerMoved(at)], + vec![button(true)], + vec![button(false)], + vec![button(true)], + vec![button(false)], + vec![], + vec![], + vec![], + ] { + app_frame(app, ctx, events); + } + let top = host(app).with(|h| h.open_dialogs().pop()).expect("a dialog is open"); + assert_eq!(top.parent, Some(parent), "the Color Picker opens over the dialog: {top:?}"); + top.id +} + +/// Opening a colour of the table asks the Color Picker for it: its OK shifts the colour, its Cancel shifts nothing. #[test] fn a_picked_color_becomes_a_shift_and_cancel_shifts_nothing() { let dir = vectorcraft_testkit::temp_dir("sfw-shift-color"); @@ -123,14 +164,18 @@ fn a_picked_color_becomes_a_shift_and_cancel_shifts_nothing() { } let ctx = app.ui_ctx.clone().expect("the app has a window"); crate::dialogs::host::pump(&mut app, &ctx); - let (id, request) = host(&app).with(|h| h.take_color_request()).expect("the table asks for a colour"); - assert_eq!(request.key, PALETTE_COLOR_KEY); - // Cancel: nothing is answered, nothing shifts. - crate::dialogs::host::pump(&mut app, &ctx); + let picker = open_cell(&mut app, &ctx, "#0000ff"); + host(&app).with(|h| h.cancel_by_id(&ctx, picker)); + for _ in 0..3 { + app_frame(&mut app, &ctx, vec![]); + } assert_eq!(app.web_export.table.get("shifted").cloned().unwrap_or(json!({})), json!({})); - // OK: the answer arrives as a Shift event for the selected colour. - host(&app).with(|h| h.answer_color(id, PALETTE_COLOR_KEY, craft::theme::Srgba::rgb(0.0, 1.0, 0.0))); - crate::dialogs::host::pump(&mut app, &ctx); + let picker = open_cell(&mut app, &ctx, "#0000ff"); + host(&app).with(|h| h.set_json_field(&ctx, picker, "color", json!("#00ff00"))).unwrap(); + host(&app).with(|h| h.confirm_by_id(&ctx, picker)); + for _ in 0..3 { + app_frame(&mut app, &ctx, vec![]); + } assert_eq!(app.web_export.table["shifted"], json!({"#0000ff": "#00ff00"})); } diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index a15e23a536..a0e5dbbd56 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -330,7 +330,9 @@ fn web_save_as_names_the_file_and_picks_the_format() { // OK goes on to the Save PDF dialog, whose OK saves. assert!(ok(&mut app)); assert!(written.borrow().is_empty()); - assert_eq!(dialog(&mut app).text("path"), Some("Untitled-1.pdf")); + assert_eq!(host(&app, |h| h.open_dialogs().last().and_then(|d| d.key.clone())).as_deref(), Some("pdf-export")); + let job = app.save_pdf.as_ref().and_then(|o| o.job.as_ref()).and_then(|j| j.path.clone()); + assert_eq!(job.as_deref(), Some("Untitled-1.pdf"), "Save PDF writes under the name Save As gave"); assert!(ok(&mut app)); let (name, bytes) = written.borrow()[0].clone(); assert_eq!(name, "Untitled-1.pdf"); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 42ffd6bbcf..dd90597699 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -57,6 +57,8 @@ pub(crate) struct SavePdfOpen { editing: String, /// The document check, with the key of everything it was computed from. checked: Option<(egui::Id, Result, String>)>, + /// The flattener preset the dialog showed at the last pump: choosing another drops the Custom… options. + flattener_preset: Option, } /// Open the dialog with `params` (`document.exportPdf` options and `path?`) applied over their @@ -132,24 +134,31 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result = vectorcraft_pdf::builtin_presets(APP) + let taken = taken_names(app, &editing); + let dialog = base_dialog(app, settings).preset(base).mode(PdfExportMode::PresetEditor).draft(draft).check_name(move |n| name_error(&taken, n)); + open_dialog(app, dialog, None, editing) +} + +/// The names a preset other than `editing` (empty: a new one) has: a built-in preset's or another saved one's. +fn taken_names(app: &VectorcraftApp, editing: &str) -> Vec { + vectorcraft_pdf::builtin_presets(APP) .into_iter() .map(|p| p.name) .chain(app.session.prefs.pdf_presets.iter().map(|p| p.name.clone())) .filter(|n| editing.is_empty() || !n.eq_ignore_ascii_case(editing.trim())) - .collect(); - let dialog = base_dialog(app, settings).preset(base).mode(PdfExportMode::PresetEditor).draft(draft).check_name(move |n| { - let n = n.trim(); - if n.is_empty() { - Some(PresetError::EmptyName) - } else if taken.iter().any(|t| t.eq_ignore_ascii_case(n)) { - Some(PresetError::NameTaken) - } else { - None - } - }); - open_dialog(app, dialog, None, editing) + .collect() +} + +/// Why the preset name `n` can't be used: empty, or one of `taken` (case and spaces ignored). +fn name_error(taken: &[String], n: &str) -> Option { + let n = n.trim(); + if n.is_empty() { + Some(PresetError::EmptyName) + } else if taken.iter().any(|t| t.eq_ignore_ascii_case(n)) { + Some(PresetError::NameTaken) + } else { + None + } } /// The dialog for `settings` with what the document and the app tell it. @@ -192,7 +201,7 @@ fn unit_kind(unit: Unit) -> UnitKind { fn open_dialog(app: &mut VectorcraftApp, dialog: HostedPdfExport, job: Option, editing: String) -> Result { let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; let id = dialogs.with(|host| host.open(dialog)); - app.save_pdf = Some(SavePdfOpen { id, job, editing, checked: None }); + app.save_pdf = Some(SavePdfOpen { id, job, editing, checked: None, flattener_preset: None }); Ok(Value::Null) } @@ -269,13 +278,23 @@ fn drive(app: &mut VectorcraftApp, ctx: &egui::Context, open: &mut SavePdfOpen) open_held_with(app, child, custom_ok, HeldOptions { parent: Some(id), ..HeldOptions::default() }); } } + // A failed write is told over the dialog, which shows again when the message closes. if let Some(text) = filed.summary - && let Err(e) = write_summary(app, None, &text) + && let Err(e) = write_summary(app, Some(id), None, &text) && e != "cancelled" { app.status(e); } - let warnings = worded(check(app, open, &filed.settings)); + let preset = filed.settings.get("flattenerPreset").and_then(Value::as_str).map(str::to_owned); + if open.flattener_preset.is_some() + && open.flattener_preset != preset + && let Some(job) = open.job.as_mut() + { + job.flattener = None; + } + open.flattener_preset = preset; + let settings = with_custom(open, filed.settings); + let warnings = worded(check(app, open, &settings)); let prefs = &app.session.prefs; let (presets, names) = (prefs.pdf_presets.clone(), prefs.flattener_presets.iter().map(|p| p.name.clone()).collect::>()); let custom = open.job.as_ref().is_some_and(|j| j.flattener.is_some()); @@ -324,10 +343,52 @@ fn custom_ok(app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), Strin if applied? { let ctx = app.ui_ctx.clone().ok_or(NOT_OPEN)?; dialogs.with(|host| host.set_json_field(&ctx, id, "flattenerPreset", json!("")))?; + // The blanked name is no preset choice: the options just set stay. + if let Some(open) = app.save_pdf.as_mut() { + open.flattener_preset = Some(String::new()); + } } Ok(()) } +/// `ui.dialog.set` of a Custom… option, `flattener.