Dialogs n-z and addons: the 3D dialog sits at the window's right edge and passes the gizmo's presses through its modal layer, and an Escape puts the gizmo's fields back as they were; Map Art's Done is in the footer; the 3D preview leaves out light settings a classic effect doesn't take; Rasterize's dialog turns its resolution preset back into the effect's params; Zoom to Selection fits at once; Save PDF drops Custom flattener options when another flattener preset is chosen, checks them in the Summary, takes flattener.* fields from automation, refuses a taken preset name at OK and tells a failed Save Summary over the dialog; the Proof Setups folder stays until the pick's answer has written into it; a group's colours go first to the Recolor rows that hold them; Swatch Conflict lists the conflicts it asks about. Tests: the controls' real names, Preview ticked as command dialogs open with it off, a cell double-clicked to ask for its colour, the frame's paste settlement, pick answers taken with the frame input, renders counted by new images, numbers compared as numbers

This commit is contained in:
bflatastic
2026-11-23 09:36:02 +07:00
parent 91c76fb1e7
commit 1db6dc9df3
26 changed files with 403 additions and 93 deletions
+3 -2
View File
@@ -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<Value, String> {
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)
}
+1 -1
View File
@@ -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) = (
+2
View File
@@ -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");
@@ -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::<usize>()
.count()
};
let (fold, img) = (folded(&rig), image(&rig));
assert_eq!(uploads(&mut rig), 0, "nothing changed: no render");
+21 -1
View File
@@ -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<vectorcraft_geom::Rect>) {
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.
+1 -1
View File
@@ -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));
};
+6
View File
@@ -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, &params)
{
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 };
+17 -3
View File
@@ -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.
+16 -4
View File
@@ -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<String, Value> {
}
/// `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<String, Value>, fresh: bool) -> Map<String, Value> {
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<String, Value>, 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<String, Value> {
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<Value, String> {
let name = label(&open.cx.id);
@@ -244,7 +256,7 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>
}
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.
+1 -1
View File
@@ -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()
@@ -14,9 +14,11 @@ fn host<R>(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<D: StackDialog>(app: &VectorcraftApp) -> bool {
+5 -2
View File
@@ -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()]));
+21 -3
View File
@@ -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<Value>) {
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
+2 -1
View File
@@ -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);
}
}
+17
View File
@@ -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<String, Value>) {
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"),
+25 -2
View File
@@ -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::<DialogFields>(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));
}
}
@@ -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<egui::Event>) {
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::<Vec<_>>())
}
_ => 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"}));
}
@@ -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");
+95 -23
View File
@@ -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<Vec<String>, String>)>,
/// The flattener preset the dialog showed at the last pump: choosing another drops the Custom… options.
flattener_preset: Option<String>,
}
/// 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<Value, St
}
};
let settings = pdf::resolve("ui.savePdfDialog", &json!({ "preset": base }), &app.session.prefs.pdf_presets).map_err(|e| e.to_string())?;
// A name may not be taken by a built-in preset or by another saved one (case and spaces ignored).
let taken: Vec<String> = 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<String> {
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<PresetError> {
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<SavePdfJob>, editing: String) -> Result<Value, String> {
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::<Vec<_>>());
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.<option>`, on Save PDF: its settings keep only the flattener
/// preset's name, so the option goes to the job, over the options it flattens with now. `None` for another request.
// shortcut: one `field` without `action`; a `fields` list goes to the framework, which refuses these names.
pub(crate) fn dialog_set(app: &mut VectorcraftApp, params: &Value) -> Option<Result<Value, String>> {
let field = params.get("field")?.as_str()?;
let key = field.strip_prefix("flattener.")?;
if params.get("action").is_some() {
return None;
}
let dialogs = app.dialogs()?;
let saved = app.session.prefs.flattener_presets.clone();
let open = app.save_pdf.as_mut()?;
let id = open.id;
let (top, name) =
dialogs.with(|host| (host.open_dialogs().last().map(|d| d.id), host.get_by_id::<HostedPdfExport>(id).map(super::flatten::preset_name)));
let named = (params["dialog"] == "top" && top == Some(id)) || params["dialog"] == id.value().to_string();
let (true, Some(name), Some(job)) = (named, name, open.job.as_mut()) else { return None };
let custom = job.flattener.as_ref().and_then(|f| serde_json::to_value(f).ok());
let set = FlattenOptions::for_export(Some(&name), custom.as_ref(), &saved).and_then(|now| {
let mut options = serde_json::to_value(now).map_err(|e| e.to_string())?;
*options.get_mut(key).ok_or_else(|| format!("unknown field `{field}`"))? = params.get("value").cloned().unwrap_or(Value::Null);
FlattenOptions::for_export(None, Some(&options), &[]).map_err(|e| format!("{field}: {e}"))
});
Some(set.map(|options| {
job.flattener = Some(options);
let shown = dialogs.with(|host| craft::automation::dialogs::inspect(host));
shown.as_array().and_then(|list| list.iter().find(|d| d["id"] == id.value().to_string())).cloned().unwrap_or(Value::Null)
}))
}
/// The dialog's `settings` with the job's Custom… flattener options, as the export gets them.
fn with_custom(open: &SavePdfOpen, mut settings: Value) -> Value {
if let Some(options) = open.job.as_ref().and_then(|job| job.flattener.as_ref()).and_then(|f| serde_json::to_value(f).ok()) {
settings["flattener"] = options;
}
settings
}
/// Carry out a change the dialog made to the saved presets.
fn preset_event(app: &mut VectorcraftApp, event: PdfPresetEvent) -> Result<(), String> {
// PLAN: assumed `PdfPreset { name, description, settings }` and the params `name`/`newName` of `pdf.preset.rename`.
@@ -348,6 +409,12 @@ fn preset_event(app: &mut VectorcraftApp, event: PdfPresetEvent) -> Result<(), S
/// The preset editor's OK: `pdf.preset.save`, then back to Edit → PDF Presets on it.
fn save_preset(app: &mut VectorcraftApp, editing: &str, answer: &PdfExportAnswer) -> Result<Value, String> {
let draft = answer.draft.as_ref().ok_or("the preset editor gave no name")?;
// The editor's OK is off on such a name; an OK by automation is refused here.
match name_error(&taken_names(app, editing), &draft.name) {
Some(PresetError::NameTaken) => return Err("A preset with this name already exists.".into()),
Some(_) => return Err("This name can't be used.".into()),
None => {}
}
let mut p = settings_json(&answer.result.options);
p.insert("description".into(), json!(draft.description));
if editing.is_empty() {
@@ -472,7 +539,7 @@ pub(crate) fn save_summary(app: &mut VectorcraftApp, p: &Value) -> Result<Value,
if app.save_pdf.is_none() {
app.save_pdf = Some(open);
}
write_summary(app, path, &text?)
write_summary(app, None, path, &text?)
}
/// The Summary text of the open dialog `open`, after the document check.
@@ -482,6 +549,7 @@ fn summary_of(app: &mut VectorcraftApp, open: &mut SavePdfOpen) -> Result<String
let not_open = || NOT_OPEN.to_string();
let settings =
dialogs.with(|host| host.get_mut_by_id::<HostedPdfExport>(id).map(|d| Value::Object(settings_json(d.settings())))).ok_or_else(not_open)?;
let settings = with_custom(open, settings);
let checked = check(app, open, &settings);
if let Err(e) = checked {
return Err(e.clone());
@@ -499,15 +567,19 @@ fn summary_of(app: &mut VectorcraftApp, open: &mut SavePdfOpen) -> Result<String
}
/// Write the Summary's `text` (UTF-8) to `path`, else to a picked `<document> PDF Summary.txt`
/// next to the document → `{path, bytes}`.
fn write_summary(app: &mut VectorcraftApp, path: Option<String>, text: &str) -> Result<Value, String> {
/// next to the document → `{path, bytes}`; a failed write is told over the dialog `over`, the one it was asked from.
fn write_summary(app: &mut VectorcraftApp, over: Option<DialogId>, path: Option<String>, text: &str) -> Result<Value, String> {
let title = app.session.active().map(|d| d.title()).unwrap_or_default();
let stem = std::path::Path::new(&title).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
let bytes = text.len();
io::write_named(app, path, &format!("{stem} PDF Summary.txt"), text.as_bytes().to_vec(), move |app, path| {
let (name, bytes) = (format!("{stem} PDF Summary.txt"), text.len());
let saved = move |app: &mut VectorcraftApp, path: String| {
app.status(format!("Saved {path}"));
Ok(json!({ "path": path, "bytes": bytes }))
})
};
match over {
Some(parent) => io::write_named_over(app, parent, path, &name, text.as_bytes().to_vec(), saved),
None => io::write_named(app, path, &name, text.as_bytes().to_vec(), saved),
}
}
#[cfg(test)]
+23 -9
View File
@@ -78,6 +78,14 @@ fn set_field(app: &VectorcraftApp, name: &str, v: Value) {
set_at(app, pdf_id(app), name, v).unwrap();
}
/// Write a field through automation's `ui.dialog.set`, which also takes the Custom… flattener options the app keeps.
fn dialog_set(app: &mut VectorcraftApp, name: &str, v: Value) {
let ctx = app.ui_ctx.clone().expect("a UI context");
let (req, _) = craft::automation::ControlRequest::new("ui.dialog.set", json!({"field": name, "value": v}));
let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("ui.dialog.set {name} answered later") };
assert_eq!(r["ok"], true, "ui.dialog.set {name}: {r}");
}
fn with_pdf<R>(app: &VectorcraftApp, f: impl FnOnce(&mut HostedPdfExport) -> R) -> R {
let id = pdf_id(app);
host(app, |h, _| h.get_mut_by_id::<HostedPdfExport>(id).map(f)).expect("a Save PDF dialog")
@@ -123,10 +131,14 @@ fn press(app: &mut VectorcraftApp, name: &str) {
// The click finds the control in the accessibility tree of a frame drawn first, as a user presses what the window shows.
crate::testing::app_frame(app, &ctx, Default::default());
let (click, _reply) = craft::automation::ControlRequest::new("ui.click", json!({"control": {"name": name}}));
crate::control::handle(app, &ctx, &click);
// The click is queued as input: the window's frames after it take it and press the control.
for _ in 0..2 {
crate::testing::app_frame(app, &ctx, Default::default());
match crate::control::handle(app, &ctx, &click) {
craft::automation::Reply::Done(r) => assert_eq!(r["ok"], true, "ui.click {name}: {r}"),
// The click is queued as input: the window's frames after it take it and press the control.
_ => {
for _ in 0..2 {
crate::testing::app_frame(app, &ctx, Default::default());
}
}
}
pump(app);
}
@@ -350,6 +362,8 @@ fn the_save_summary_button_writes_the_summary() {
app.run("file.export.pdf", json!({})).unwrap();
let untouched = line_count(&summary(&app));
set_field(&app, "thumbnails", json!(true));
// The button is in the Summary section, which the user opens first.
set_field(&app, "section", json!("summary"));
press(&mut app, "Save Summary…");
let title = app.session.active().unwrap().title();
let stem = std::path::Path::new(&title).file_stem().unwrap().to_string_lossy().into_owned();
@@ -687,9 +701,9 @@ fn confirming_preserves_passwords_supplied_when_opening_the_dialog() {
)
.unwrap();
assert!(!summary(&app).contains("Password"), "summaries omit passwords");
// PLAN: assumed control names of the preset row: Save Preset…, then Create.
press(&mut app, "Save Preset…");
press(&mut app, "Create");
// The preset row's New… opens its name field; OK saves the preset under the suggested name.
press(&mut app, "New…");
press(&mut app, "OK");
let saved = &app.session.prefs.pdf_presets[0].settings.security;
assert!(saved.open_password.is_empty() && saved.permissions_password.is_empty(), "presets forget passwords");
@@ -783,8 +797,8 @@ fn summary_warnings_include_flattener_resolutions_when_flattening_transparency()
assert!(text.contains("1200") && text.contains("300"), "{text}");
// With a custom flattener override, the resolution in the warning reflects the options
set_field(&app, "flattener.lineArtPpi", json!(600));
set_field(&app, "flattener.gradientPpi", json!(200));
dialog_set(&mut app, "flattener.lineArtPpi", json!(600));
dialog_set(&mut app, "flattener.gradientPpi", json!(200));
pump(&mut app);
let text = summary(&app);
assert!(text.contains("600") && text.contains("200"), "{text}");
@@ -186,8 +186,9 @@ impl StackDialog for SwatchConflictDialog {
self.answer()
}
/// The choice, Apply to All when it takes input, and the conflicts asked about, which automation reads only.
fn json_fields(&self) -> Option<Value> {
let mut fields = json!({ "choice": self.choice.id() });
let mut fields = json!({ "choice": self.choice.id(), "conflicts": self.conflicts });
if self.offers_apply_to_all() {
fields["applyToAll"] = Value::Bool(self.apply_to_all);
}
@@ -217,7 +217,8 @@ fn light_rings_adjust_only_their_angle_and_snap_without_rotating_the_object() {
}
let other = if axis == 0 { "lightHeight" } else { "lightRotation" };
assert_eq!(value(&h, other), before.number(other).unwrap());
assert_eq!(stored(&h, key), json!(value(&h, key)));
// The effect may keep a whole number as an integer.
assert_eq!(stored(&h, key).as_f64(), Some(value(&h, key)));
}
}
+16 -3
View File
@@ -4,6 +4,7 @@
use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard};
use craft::ui::contract::Bind;
use craft::ui::contract::overlay::{FloatPlace, Place as OverlayPlace};
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog, ParamLayout, ParamResult};
use craft::ui::runtime::env::Label;
@@ -92,6 +93,7 @@ impl Session {
for key in super::three_d_classic::MAP_ROWS {
params.remove(key);
}
revolve::drop_untaken_light_keys(&self.effect, &mut params);
let (cmd, p) = self.command(&params);
(cmd, p, params)
}
@@ -115,15 +117,24 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String>
let footer_effect = effect.clone();
// The canvas of the current window: the gizmo and the droppers work there while the dialog is open.
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
// At the window's right edge from the canvas's top, where the 3D panel docks, so the dialog leaves the art the
// gizmo turns in view.
let beside = app.canvas_view().map(|v| egui::pos2(ctx.content_rect().right(), v.rect.top()));
let dialog = HostedParamDialog::new(&ctx, "effect.dialog", fields, move |f| {
let rows = revolve::params(&read(&build_data), f, Place::Dialog);
let reset = revolve::reset_all_button(&footer_effect, f);
let reset = revolve::reset_all_button(&footer_effect, f).or_else(|| super::three_d_classic::map_done_button(f));
let hint = hint_for(&footer_effect, f.bool("preview").unwrap_or(false), f);
let dialog = ParamDialog::new("effect.dialog", title.clone(), rows).values(Bind::bound(f)).previews(true).layout(ParamLayout::Stacked);
let dialog = match reset {
Some(reset) => dialog.extra_buttons(vec![reset]).footer_note(hint),
None => dialog,
};
let dialog = match beside {
Some(corner) => {
dialog.shaped(move |d| d.overlay(|o| o.place(OverlayPlace::Float(FloatPlace::corner_at(corner, egui::Align2::RIGHT_TOP)))))
}
None => dialog,
};
match canvas {
Some(canvas) => dialog.canvas(canvas),
None => dialog,
@@ -250,8 +261,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut s) = app.three_d_dialog.take() else { return };
// A dialog that closed is finished by the held drain (OK or Cancel), which owns the session's end.
let Some((fields, previewing)) = dialog_of(app, s.id, |d| {
if d.take_footer_action().as_deref() == Some(revolve::RESET_ALL) {
revolve::reset_all(d, &s.effect);
match d.take_footer_action().as_deref() {
Some(revolve::RESET_ALL) => revolve::reset_all(d, &s.effect),
Some(super::three_d_classic::MAP_DONE) => super::three_d_classic::map_done(d, &s.effect),
_ => {}
}
(d.fields().clone(), d.is_previewing())
}) else {
+21 -15
View File
@@ -15,10 +15,11 @@ use craft::ui::canvas_controls::SelectionOutline;
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::Picture;
use craft::ui::list::ThumbAspect;
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, Param, ParamKind};
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind};
use craft::ui::pickers::Select;
use craft::ui::primitives::ContentPainterCx;
use craft::ui::runtime::env::UnitKind;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::style::DataColor;
use craft::ui::text::NumberField;
use craft::ui::value_drag::SliderScale;
@@ -360,6 +361,19 @@ fn map_of_box(state: &BoxState, rect: Rect, base: &SurfaceMap) -> SurfaceMap {
}
}
/// The id of Map Art's Done, in the footer as Reset all is on the other pages.
pub(crate) const MAP_DONE: &str = "mapDone";
/// Map Art's Done, in the footer so it stays in view however long the page; none on the other pages.
pub(crate) fn map_done_button(fields: &DialogFields) -> Option<(String, FooterButton)> {
(fields.text(PAGE) == Some(MAP_PAGE)).then(|| (MAP_DONE.to_owned(), FooterButton::new(tl!("Done"), DialogRole::Other)))
}
/// Done's press: back to the effect's first page.
pub(crate) fn map_done(dialog: &mut HostedParamDialog, effect: &str) {
dialog.set_field(PAGE, FieldValue::from(if effect == CLASSIC_ROTATE { "rotation" } else { "object" }));
}
/// The surface laid out flat, as large as fits the row, in a light gray when the viewer sees it and a dark gray when
/// it is hidden, with the box of the mapped art on it: a free transform box that moves, scales and turns the art.
fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response {
@@ -431,29 +445,21 @@ fn map_actions(flat: Flat, has_map: bool, any_map: bool) -> Param {
.response
})
.full_width()
// The page's maps: automation sets them whole, as the rows above edit them one surface at a time.
.companions([MAP_ART])
}
/// Map Art: the surface (first, previous, its number, next, last, and whether the viewer sees it), the symbol mapped
/// onto it, the surface laid out flat with the art's box to move, scale and rotate, the same values as numbers, Scale
/// to Fit, Clear, Clear All, Shade Artwork and Invisible Geometry. The rows edit the effect's `mapArt`, `mapShade` and
/// `mapInvisible`, which the dialog previews and applies with its other settings; Done goes back to the effect's
/// first page. The number rows list only while the shown surface has a map.
/// `mapInvisible`, which the dialog previews and applies with its other settings; the footer's Done
/// ([`map_done_button`]) goes back to the effect's first page. The number rows list only while the shown surface has a
/// map.
pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) -> Vec<Param> {
if !vectorcraft_effects::takes_map_art(effect) {
return Vec::new();
}
let first_page = if effect == CLASSIC_ROTATE { "rotation" } else { "object" };
let mut rows = vec![
Param::custom("__mapDone", tl!("Map Art"), move |ui, fields, _| {
let done = Button::new(tl!("Done")).show(ui);
if done.clicked() {
fields.set(PAGE, first_page);
}
done.response
})
// The page's maps: automation sets them whole, as the rows below edit them one surface at a time.
.companions([MAP_ART]),
];
let mut rows = Vec::new();
let Some(listed) = data.surfaces.as_ref().filter(|s| !s.is_empty()) else { return rows };
let count = listed.len();
let current = shown_surface(fields, count);
+1 -1
View File
@@ -39,7 +39,7 @@ pub use save::{
SAVE_CANCELED, ask_format_options, ask_pdf_options, cancel_saves, hide_saves, remember_active_artboard, remember_view, save, save_pdf,
};
pub(crate) use save::{
clear_notes_left, export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to,
clear_notes_left, export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_named_over, write_reporting, write_to,
};
#[cfg(test)]
pub(crate) use save::{report_write_error, saved_status};
+37 -2
View File
@@ -330,12 +330,22 @@ pub fn hide_saves(app: &mut VectorcraftApp) -> Value {
/// must not look saved: it stays modified, and what was at `path` is as it was. Not for a request
/// an agent sent and waits on: the error is its reply.
pub(crate) fn report_write_error(app: &mut VectorcraftApp, export: bool, path: &str, e: &str) {
report_write_error_over(app, None, export, path, e);
}
/// [`report_write_error`] over the open dialog `over` when there is one, at once: the dialog the write was asked from
/// shows again when the message closes.
fn report_write_error_over(app: &mut VectorcraftApp, over: Option<DialogId>, export: bool, path: &str, e: &str) {
if app.ui.answering_control {
return;
}
let name = fileio::file_name(path);
let message = if export { tl!("Can't export “{name}”.") } else { tl!("Can't save “{name}”.") };
dialogs::confirm::tell(app, &crate::i18n::fmt(message, &[("name", &name)]), &crate::i18n::message(crate::i18n::current(), e));
let (message, detail) = (crate::i18n::fmt(message, &[("name", &name)]), crate::i18n::message(crate::i18n::current(), e));
match over {
Some(parent) => dialogs::confirm::tell_over(app, parent, &message, &detail),
None => dialogs::confirm::tell(app, &message, &detail),
}
}
/// [`write_to`], a failure reported ([`report_write_error`]).
@@ -373,6 +383,18 @@ pub(crate) fn write_named(
write_named_as(app, path, name, file_types(&fileio::extension(name)), bytes, then)
}
/// [`write_named`] asked from the open dialog `parent`: a failed write is told over it.
pub(crate) fn write_named_over(
app: &mut VectorcraftApp,
parent: DialogId,
path: Option<String>,
name: &str,
bytes: Vec<u8>,
then: impl FnOnce(&mut VectorcraftApp, String) -> Result<Value, String> + 'static,
) -> Result<Value, String> {
write_named_in(app, Some(parent), path, name, file_types(&fileio::extension(name)), bytes, then)
}
/// [`write_named`] with a save panel that shows `filters`, for a file whose extension names no one
/// type (`.json` holds shortcut sets as well as preferences).
pub(crate) fn write_named_as(
@@ -382,6 +404,19 @@ pub(crate) fn write_named_as(
filters: Vec<FileFilter>,
bytes: Vec<u8>,
then: impl FnOnce(&mut VectorcraftApp, String) -> Result<Value, String> + 'static,
) -> Result<Value, String> {
write_named_in(app, None, path, name, filters, bytes, then)
}
/// [`write_named_as`], a failed write told over the dialog `over` when there is one.
fn write_named_in(
app: &mut VectorcraftApp,
over: Option<DialogId>,
path: Option<String>,
name: &str,
filters: Vec<FileFilter>,
bytes: Vec<u8>,
then: impl FnOnce(&mut VectorcraftApp, String) -> Result<Value, String> + 'static,
) -> Result<Value, String> {
let ext = fileio::extension(name);
let (_, folder) = suggested(app, "");
@@ -394,7 +429,7 @@ pub(crate) fn write_named_as(
ext,
|_| false,
move |app, path| {
write_reporting(app, &path, &bytes)?;
write_to(&mut app.services, &path, &bytes).inspect_err(|e| report_write_error_over(app, over, false, &path, e))?;
then(app, path)
},
)