diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 218312750d..363fe77ed7 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -16,12 +16,8 @@ //! - `ui.move {x, y}` / `ui.click {x, y, button?, count?, shift?…}` / `ui.drag {x, y, toX, toY, steps?}`: //! real egui pointer input in screen points (reaches every widget: panels, flyouts, dialogs) //! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}` -//! - `ui.dialog.set {field, value}` or `{fields: [{field, value}…]}` (all or none; setting a field -//! the dialog does not read is an error that lists its fields: [`crate::dialogs::accepts_field`]; -//! a `__` field other than the controls of the dialog's kind is an error too, so a request cannot -//! change the command, targets or file the dialog's OK acts on: [`crate::dialogs::protected_field`]; -//! `action: confirm | cancel` then confirms or cancels that dialog in the same request and replies -//! `{dialog, result}`) / `ui.dialog.confirm` / `ui.dialog.cancel` +//! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by +//! `craft_automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`) //! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, data?}` (`data: true`: the PNG //! comes back as `pngBase64` as well) //! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly @@ -68,45 +64,6 @@ fn input_count(p: &Value, key: &str, default: u64, max: u64) -> Result Result, String> { - let Some(list) = p.get("fields") else { - let f = p.get("field").and_then(Value::as_str).ok_or("missing `field`")?; - return Ok(vec![(f.to_string(), p.get("value").cloned().unwrap_or(Value::Null))]); - }; - if p.get("field").is_some() { - return Err("give `field` or `fields`, not both".into()); - } - let list = list.as_array().ok_or("`fields` must be a list of {field, value?}")?; - if list.len() > MAX_DIALOG_FIELDS { - return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", list.len())); - } - list.iter() - .enumerate() - .map(|(i, item)| { - let f = item.get("field").and_then(Value::as_str).ok_or_else(|| format!("fields {i}: missing string `field`"))?; - Ok((f.to_string(), item.get("value").cloned().unwrap_or(Value::Null))) - }) - .collect() -} - -/// What `ui.dialog.set {action}` does with the dialog once its fields are set. -enum DialogAnswer { - Confirm, - Cancel, -} - -/// The `action` of a `ui.dialog.set`: none, `confirm` or `cancel`. It is checked before any field is set. -fn dialog_action(p: &Value) -> Result, String> { - match p.get("action") { - None => Ok(None), - Some(v) if v == "confirm" => Ok(Some(DialogAnswer::Confirm)), - Some(v) if v == "cancel" => Ok(Some(DialogAnswer::Cancel)), - Some(_) => Err("`action` must be confirm or cancel".into()), - } -} - fn reserve_synthetic(app: &mut VectorcraftApp, additional: usize) -> Result<(), String> { if additional > MAX_SYNTHETIC_EVENTS.saturating_sub(app.synthetic.len()) { return Err(format!("synthetic input queue limit ({MAX_SYNTHETIC_EVENTS} events); retry after pending input drains")); @@ -253,7 +210,7 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // the layout. if let Some(fields) = ui.as_object_mut() { fields.remove("floating_panels"); - leave_out_unreadable_paths(app, fields); + leave_out_unreadable_paths(fields); } json!({ "scriptRunning": app.session.script_running(), @@ -263,20 +220,13 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "ui": ui, // Not saved with the UI state, so not in `ui`: 0 normal … 3 Presentation Mode. "screenMode": app.ui.screen_mode, - // The Contextual Task Bar: pinned (not saved either) and where it shows. - "taskBar": { - "pinned": app.ui.task_bar_place.pinned, - "rect": crate::canvas::task_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), - }, - // The Quick Pen toolbar: pinned (not saved either) and where it shows. - "quickPenToolbar": { - "pinned": app.ui.quick_pen_bar_place.pinned, - "rect": crate::canvas::quick_pen_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), - }, - // The Free Transform tool's widget, where it shows. - "freeTransformWidget": crate::free_transform::rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), + // The Contextual Task Bar: pinned (not saved either); `ui.locate` finds where it shows. + "taskBar": {"pinned": app.ui.task_bar_place.pinned}, + // The Quick Pen toolbar: pinned (not saved either); `ui.locate` finds where it shows. + "quickPenToolbar": {"pinned": app.ui.quick_pen_bar_place.pinned}, "view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()), - "canvasRect": app.canvas_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])), + // PLAN: assumed `CanvasView::rect: egui::Rect` from `app.canvas_view()` (canvas A1) + "canvasRect": app.canvas_view().map(|v| json!([v.rect.left(), v.rect.top(), v.rect.width(), v.rect.height()])), // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), @@ -316,10 +266,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "placing": app.placing.pending.iter().map(|p| p.name.as_str()).collect::>(), // The screen color sampler is shown, waiting for the person at the computer // (`ui.sampleScreenColor`). - "screenSampler": app.screen_sampler.is_some(), + // PLAN: assumed `ScreenPick::busy(&self) -> bool` on `app.screen_pick` (shell C2) + "screenSampler": app.screen_pick.busy(), // A native file dialog open off the UI thread (`open`, `place`, `save`, `folder`), waiting // for the person at the computer: what asked for it runs again when it answers. - "fileDialog": app.picks.waiting_kind(), + // PLAN: assumed `file_dialog_kind() -> Option<&'static str>` (files-01:77) + "fileDialog": app.file_dialog_kind(), }) } @@ -1072,7 +1024,7 @@ fn steps_mut(set: &mut Value) -> impl Iterator) { +pub(crate) fn leave_out_unreadable_step(command: &str, params: &mut serde_json::Map) { leave_out_unreadable_pref_steps(command, params); leave_out_unreadable_params(params, ParamsPlace::of(command)); } @@ -1151,10 +1103,8 @@ fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) { /// Takes out of `ui.inspect`'s copy of the UI state the paths the request may not read: recent files, /// a library panel's file, folder preferences (saved, and in an open Preferences dialog) and the paths -/// in recorded actions' steps and in the item an open Insert Menu Item dialog picked, outside the -/// read root. The file selected in an open JavaScript Files dialog is named as `svgInteractivity.info` -/// names the active document's linked files. The UI state itself is not changed. -fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map) { +/// in recorded actions' steps, outside the read root. The UI state itself is not changed. +fn leave_out_unreadable_paths(ui: &mut serde_json::Map) { if let Some(Value::Array(files)) = ui.get_mut("recent_files") { files.retain(|f| f.as_str().is_some_and(readable)); } @@ -1177,24 +1127,6 @@ fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map outcome, Err(msg) => { - app.picks.recover(); app.session.set_replaying(false); err(format!("internal error: {msg} (please report this bug)")) } @@ -1606,59 +1537,18 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) ok(Value::Null) } "ui.set" => set_ui(app, req), - "ui.dialog.set" => match app.ui.dialog.as_mut() { - Some(d) => { - let fields = match dialog_fields(p) { - Ok(fields) => fields, - Err(e) => return err(e), - }; - let action = match dialog_action(p) { - Ok(action) => action, - Err(e) => return err(e), - }; - // Every field is checked before any is set, so a request sets all of them or none. - if let Some((f, _)) = fields.iter().find(|(f, _)| !crate::dialogs::accepts_field(d, f)) { - if crate::dialogs::protected_field(d, f) { - return err(format!("the `{}` dialog cannot set protected field `{f}`", d.kind)); - } - let names = crate::dialogs::field_names(d).join(", "); - return err(format!("the `{}` dialog has no field `{f}`; its fields: {names}", d.kind)); - } - // Create Object Mosaic converts New Size against the selected image's size as it is now. - crate::dialogs::object_mosaic::refresh(app); - // In order: a field that sets others (an export preset) goes before the fields after it. - // A field that fails leaves the dialog as it was before the request. - let before = app.ui.dialog.clone(); - for (f, value) in fields { - let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(&f).cloned()); - if let Some(d) = app.ui.dialog.as_mut() { - crate::dialogs::set_field(d, f.clone(), value); - } - if let Err(e) = crate::dialogs::field_set(app, &f, old.as_ref()) { - app.ui.dialog = before; - return err(e); - } - } - let dialog = app.ui.dialog.as_ref().and_then(|d| serde_json::to_value(d).ok()).unwrap_or_default(); - // `action` answers the dialog the fields were just set in, within this request. - match action { - None => ok(dialog), - Some(DialogAnswer::Confirm) => match crate::dialogs::confirm(app) { - Ok(result) => ok(json!({"dialog": dialog, "result": result})), - Err(e) => err(e), - }, - Some(DialogAnswer::Cancel) => { - crate::dialogs::cancel(app); - ok(json!({"dialog": dialog, "result": null})) - } - } + "ui.dialog.set" | "ui.dialog.confirm" | "ui.dialog.cancel" => { + // Create Object Mosaic and Width Point convert against the selection as it is now. + crate::dialogs::host::sync(app); + // The dialog asked for is `dialog`, the top one when it is missing. + let mut params = if p.is_object() { p.clone() } else { json!({}) }; + if params.get("dialog").is_none_or(Value::is_null) { + params["dialog"] = json!("top"); } - None => err("no dialog open"), - }, - "ui.dialog.confirm" => wrap(crate::dialogs::confirm(app)), - "ui.dialog.cancel" => { - crate::dialogs::cancel(app); - ok(Value::Null) + // PLAN: assumed `dialog_method(method, ¶ms, &WindowHost, ViewportId) -> Result` + // and `WindowHost::of(ctx)` in craft_automation (widgets-02) + let host = craft_automation::WindowHost::of(ctx); + wrap(craft_automation::dialogs::dialog_method(&req.method, ¶ms, &host, egui::ViewportId::ROOT)) } "ui.resize" => { let (w, h) = match coord(p, "width", 1440.0).and_then(|w| Ok((w, coord(p, "height", 900.0)?))) { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..5406bb550f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1,12 +1,7 @@ -//! Modal dialogs. Fields live in `UiState::dialog` (string/number JSON) so agents can fill them -//! through `ui.dialog.set` and press OK with `ui.dialog.confirm`. -//! -//! Each dialog is a file here exporting a [`DialogSpec`] (heading, body, OK action, buttons) plus -//! a row in the `registry!` below that maps its `Dialog::kind` strings to it. Dialogs inside the -//! shared modal frame only supply a body and a confirm action; a few (Preferences, Keyboard -//! Shortcuts, Workspaces, Find Font) draw their own window. +//! Dialogs. Each dialog is a file here that the dialog host owns and shows; [`host`] opens held +//! dialogs, serves every module once per frame and reaches the open ones for automation. -mod about; +pub(crate) mod actions; pub mod action_batch; pub mod action_insert_menu_item; pub mod action_new; @@ -43,12 +38,16 @@ pub mod dxf_options; pub mod edit_selection; pub mod edit_views; mod effect; +pub(crate) mod effect_adjust; pub mod effect_gallery; +pub(crate) mod effect_params; +pub(crate) mod effect_rows; pub mod envelope; pub mod eps_options; pub mod expand; mod export_as; mod export_for_screens; +pub(crate) mod export_host; pub mod eyedropper; pub mod file_info; pub mod find_links; @@ -65,6 +64,7 @@ pub mod graph_design; pub mod graph_type; pub mod graphic_style_options; pub mod halftone; +pub(crate) mod host; pub mod hpgl_options; pub mod hyphenation; pub mod import_pdf; @@ -72,6 +72,7 @@ pub mod indexed_color; pub mod javascript_files; pub mod justification; pub mod kinsoku_sets; +pub(crate) mod layer_color; pub mod layer_options; pub mod layers_panel_options; pub mod liquify; @@ -80,7 +81,6 @@ pub mod live_paint_gaps; pub mod live_paint_selection; pub mod missing_fonts; pub mod missing_links; -pub(crate) mod modal; pub mod navigator_panel_options; pub mod new_brush; pub mod new_color_group; @@ -88,8 +88,10 @@ mod new_document; pub mod new_swatch; pub mod new_text_style; pub mod object_mosaic; +pub(crate) mod object_dialogs; pub mod objects_on_path_options; pub mod office_export; +pub(crate) mod option_form; pub mod package; pub mod para_style_options; pub(crate) mod path_ops; @@ -104,6 +106,9 @@ pub mod place; pub mod placement_options; pub mod plugin; mod png_options; +pub(crate) mod preset_manager; +pub(crate) mod preview; +pub(crate) mod preview_folders; pub mod print; pub mod print_presets; pub mod profile_mismatch; @@ -113,7 +118,6 @@ mod psd_options; pub mod raster_effects; pub mod rearrange_artboards; pub mod recolor; -mod recovery; pub mod relink; pub mod rename_artboards; pub(crate) mod revolve; @@ -122,13 +126,15 @@ pub(crate) mod revolve_lights; pub mod safe_mode; pub mod saturate; pub mod save_brush_library; -mod save_changes; pub mod save_for_web; +pub(crate) mod save_library; pub(crate) mod save_options; mod save_pdf; pub mod save_style_library; pub mod save_swatch_library; pub mod save_symbol_library; +pub(crate) mod saved_names; +pub(crate) mod screen_formats; pub mod script_check; pub mod script_run; pub mod shape_builder_options; @@ -149,30 +155,31 @@ pub mod symbolism_options; pub mod tate_chu_yoko; mod text_export; pub mod text_import; +pub(crate) mod three_d; mod three_d_classic; pub(crate) mod three_d_materials; pub mod three_point_arc_options; mod tiff_bmp_tga; pub mod tile_edge_color; +pub(crate) mod tool_options; mod tools; -pub mod trace_presets; +pub(crate) mod track_cube; pub mod tracing_presets; pub(crate) mod transform; pub mod transform_each; +pub(crate) mod variation; pub mod variables; pub mod warichu; mod warp_effect; pub mod width_point; -use serde_json::{Value, json}; - pub use color_picker::open as open_color_picker; pub use document_setup::open as open_document_setup; pub use effect::open as open_effect_dialog; pub(crate) use effect::{FILM_GRAIN_FIELDS, PAINT_DAUB_BRUSH_TYPE_LABELS, SHADES, shown_choices}; -pub use export_as::{export_selection, open as open_export_as}; pub(crate) use export_for_screens::drop_unread_screen_settings; pub use export_for_screens::open as open_export_for_screens; +// PLAN: these re-exports are kept as they were; export-w13 removes any whose item it deletes. pub(crate) use export_for_screens::{ KIND as EXPORT_FOR_SCREENS, PresetPick as ScreenPresetPick, artboard_name_editing as export_artboard_name_editing, export_preset as screen_export_preset, formats as screen_formats, import_presets as screen_import_presets, @@ -180,927 +187,12 @@ pub(crate) use export_for_screens::{ saved_rows as screen_saved_rows, settings_format as screen_settings_format, }; pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffix, read_number_list, unit_suffix}; -pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; +pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document}; pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name}; pub use png_options::open as open_raster_options; -pub(crate) use save_pdf::{SAVE_SUMMARY as SAVE_PDF_SUMMARY, save_summary as save_pdf_summary, summary_open as pdf_summary_open}; pub use save_pdf::{open as open_save_pdf, open_preset as open_pdf_preset}; pub use tools::open_tool_dialog; -use crate::state::Dialog; -use crate::{VectorcraftApp, widgets}; - -type DialogResult = Result; - -/// A dialog's Reset ([`DialogSpec::reset`]). -type ResetFn = fn(&VectorcraftApp, &mut Dialog) -> Result<(), String>; - -/// The shared dialog frame's inner margin, and the least room it leaves at the window's edges. -const MARGIN: i8 = 22; -const EDGE_GAP: f32 = 8.0; - -/// An action requested by a dialog that draws its buttons inside its body. -#[derive(Default)] -pub(crate) enum DialogAction { - #[default] - None, - Confirm, - Cancel, -} - -/// How a dialog draws and applies itself. Specs start from [`DialogSpec::FORM`] and override what -/// differs. -pub(crate) struct DialogSpec { - /// Draws its own window instead of the shared frame (the frame fields below are then unused). - pub window: Option, - /// The heading (and window title), in the UI language: the spec translates its own text and - /// leaves names in it (a document's, a plug-in's) as they are. - pub heading: fn(&Dialog) -> String, - /// Optional heading band inside the shared window; normal dialogs use `modal::heading`. - pub header: Option, - /// Draws the fields. Returns true to close the dialog as Cancel would. - pub body: fn(&mut VectorcraftApp, &mut egui::Ui, &mut Dialog) -> bool, - /// Optional body with inline buttons; replaces `body` and the shared footer. - pub body_with_actions: Option DialogAction>, - /// OK, Enter or `ui.dialog.confirm`: applies the dialog and closes it when done. - pub confirm: fn(&mut VectorcraftApp, &Dialog) -> DialogResult, - /// The OK button's label. None: no OK button, Enter does nothing and Cancel reads "Close". - pub ok: Option<&'static str>, - /// The Cancel button's label when it is not "Cancel" ("No"). Only with an `ok`. - pub cancel: Option<&'static str>, - /// An extra button left of Cancel that sets `discard: true` and confirms ("Don't Save"). - pub discard: Option<&'static str>, - /// A button left of Cancel, as (label, field), that sets `field: true` and confirms, as OK - /// does otherwise (Transform Each's Copy). - pub alternate: Option<(&'static str, &'static str)>, - /// Puts the fields back to their defaults. While Alt (Option on macOS) is held, the Cancel - /// button of a dialog with an `ok` reads Reset; Reset (or `ui.dialogReset`) runs this and the - /// dialog stays open. An error leaves the dialog as it was. - pub reset: Option, - pub min_width: f32, - pub max_width: Option, - /// The body runs a live preview interaction that Cancel rolls back. - pub preview: bool, - /// The fields that a dialog of a kind reads but may not hold yet, which `ui.dialog.set` also - /// takes (see [`accepts_field`]). - pub inputs: fn(&str) -> &'static [&'static str], - /// Whether the dialog passes a field it neither holds nor lists in `inputs` on to what it - /// runs (a parameter of the generic dialog's command), so `ui.dialog.set` takes it too. - pub passes: fn(&Dialog, &str) -> bool, - /// The OK button's label when it depends on the app (Export for Screens' "Download" on the - /// web); `ok` when none. Only with an `ok`. - pub ok_label: Option &'static str>, - /// Can OK (or Enter) apply the dialog as it is? None: always. The body says why not. - pub ok_enabled: Option bool>, - /// What a dialog draws at the left end of its button row, level with the buttons, instead of - /// in its body (Transform Each's Preview checkbox). - pub footer_left: Option, -} - -impl DialogSpec { - /// A text field per value; OK just closes. Also the fallback for unregistered kinds. - pub const FORM: Self = Self { - window: None, - heading: |_| tl!("Dialog").into(), - header: None, - body: |app, ui, d| { - form::grid(ui, d, app.session.general_unit()); - false - }, - body_with_actions: None, - confirm: |app, _| { - app.ui.dialog = None; - Ok(Value::Null) - }, - ok: Some("OK"), - cancel: None, - discard: None, - alternate: None, - reset: None, - min_width: 320.0, - max_width: None, - preview: false, - inputs: |_| &[], - passes: |_, _| false, - ok_label: None, - ok_enabled: None, - footer_left: None, - }; - - /// A dialog that draws its own window and confirms through its module. - const fn window(show: fn(&mut VectorcraftApp, &egui::Context), confirm: fn(&mut VectorcraftApp, &Dialog) -> DialogResult) -> Self { - Self { window: Some(show), confirm, ..Self::FORM } - } -} - -/// The dialog registry: one row per dialog with its [`DialogKind`] variant, the `Dialog::kind` -/// strings it handles and its [`DialogSpec`]. Adding a dialog is a new file plus one row. -macro_rules! registry { - ($($variant:ident: [$($kind:pat),+] => $spec:expr,)+) => { - /// Every registered dialog. - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - pub enum DialogKind { - $($variant,)+ - } - - impl DialogKind { - /// The dialog handling a `Dialog::kind` string. - pub fn of(kind: &str) -> Option { - match kind { - $($($kind)|+ => Some(Self::$variant),)+ - _ => None, - } - } - - /// Every variant, in registry order. - pub const ALL: &[DialogKind] = &[$(Self::$variant,)+]; - - fn spec(self) -> &'static DialogSpec { - match self { - $(Self::$variant => { - static SPEC: DialogSpec = $spec; - &SPEC - })+ - } - } - } - }; -} - -registry! { - DimensionOptions: [dimension::KIND] => dimension::SPEC, - NewDocument: [new_document::KIND] => new_document::SPEC, - Shape: ["rectangle", "roundedRectangle", "ellipse", "polygon", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid"] => shapes::SPEC, - Transform: ["move", "rotate", "scale", "reflect", "shear"] => transform::SPEC, - PathOp: ["average", "averageJoin", "offsetPath", "simplify", "splitIntoGrid"] => path_ops::SPEC, - DocumentSetup: ["documentSetup"] => document_setup::SPEC, - ArtboardOptions: [artboard_options::KIND] => artboard_options::SPEC, - ExportForScreens: ["exportForScreens"] => export_for_screens::SPEC, - Recolor: [recolor::KIND] => recolor::SPEC, - Command: ["command"] => command::SPEC, - Variables: [variables::KIND] => variables::SPEC, - Effect: ["effect"] => effect::SPEC, - SaveChanges: [crate::unsaved::KIND] => save_changes::SPEC, - Preferences: ["preferences"] => DialogSpec::window(crate::prefs_dialog::show, |app, _| crate::prefs_dialog::confirm(app)), - Shortcuts: ["shortcuts"] => DialogSpec::window(crate::shortcut_editor::show, |app, _| crate::shortcut_editor::confirm(app)), - Workspaces: ["newWorkspace", "manageWorkspaces"] => DialogSpec::window(crate::workspaces::show, |app, _| crate::workspaces::confirm(app)), - NewToolbar: [crate::custom_toolbars::KIND] => DialogSpec::window(crate::custom_toolbars::show_dialog, |app, _| crate::custom_toolbars::confirm(app)), - ManageToolbars: [crate::custom_toolbars::MANAGE] => DialogSpec::window(crate::custom_toolbars::show_manage, |app, _| crate::custom_toolbars::confirm_manage(app)), - FindFont: ["findFont"] => DialogSpec::window(crate::find_font::show, |app, _| crate::find_font::confirm(app)), - SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC, - Confirm: [confirm::KIND] => confirm::SPEC, - BrushDelete: [brush_delete::KIND] => brush_delete::SPEC, - BrushReplaceArt: [brush_replace_art::KIND] => brush_replace_art::SPEC, - Message: [confirm::MESSAGE] => confirm::MESSAGE_SPEC, - Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, - ReplaceFiles: [confirm::REPLACE_FILES] => confirm::REPLACE_FILES_SPEC, - ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC, - ResetActions: [confirm::RESET_ACTIONS] => confirm::RESET_ACTIONS_SPEC, - MissingFontEdit: [confirm::MISSING_FONT_EDIT] => confirm::MISSING_FONT_EDIT_SPEC, - NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, - NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, - ColorGroupOptions: [color_group_options::KIND] => color_group_options::SPEC, - GraphData: [graph_data::KIND] => graph_data::SPEC, - GraphDesign: [graph_design::DESIGN] => graph_design::DESIGN_SPEC, - GraphColumn: [graph_design::COLUMN] => graph_design::COLUMN_SPEC, - GraphMarker: [graph_design::MARKER] => graph_design::MARKER_SPEC, - GraphType: [graph_type::KIND] => graph_type::SPEC, - GradientStop: ["gradientStop"] => gradient_stop::SPEC, - ColorPicker: [color_picker::KIND] => color_picker::SPEC, - GraphicStyleOptions: [graphic_style_options::KIND] => graphic_style_options::SPEC, - CharStyleOptions: [char_style_options::KIND] => char_style_options::SPEC, - ParaStyleOptions: [para_style_options::KIND] => para_style_options::SPEC, - NewTextStyle: [new_text_style::KIND] => new_text_style::SPEC, - EffectExists: [effect::EXISTS] => effect::EXISTS_SPEC, - ColorGuideOptions: [color_guide_options::KIND] => color_guide_options::SPEC, - ColorBalance: [color_balance::KIND] => color_balance::SPEC, - Saturate: [saturate::KIND] => saturate::SPEC, - ProofSetup: [proof_setup::KIND] => proof_setup::SPEC, - IndexedColor: [indexed_color::KIND] => indexed_color::SPEC, - SaveSwatchLibrary: [save_swatch_library::KIND] => save_swatch_library::SPEC, - TileEdgeColor: [tile_edge_color::KIND] => tile_edge_color::SPEC, - EyedropperOptions: [eyedropper::KIND] => eyedropper::SPEC, - FlattenTransparency: [flatten::KIND] => flatten::SPEC, - FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC, - ImageTracePreset: [trace_presets::KIND] => trace_presets::SPEC, - TracingPresets: [tracing_presets::KIND] => tracing_presets::SPEC, - TracingPreset: [tracing_presets::PRESET_KIND] => tracing_presets::PRESET_SPEC, - TracingPresetsReplace: [tracing_presets::REPLACE_KIND] => tracing_presets::REPLACE_SPEC, - SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC, - SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC, - SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC, - Expand: [expand::KIND] => expand::SPEC, - SpotColors: [spot_colors::KIND] => spot_colors::SPEC, - TransformEach: [transform_each::KIND] => transform_each::SPEC, - WidthPoint: [width_point::KIND] => width_point::SPEC, - Corners: [corners::KIND] => corners::SPEC, - Hyphenation: [hyphenation::KIND] => hyphenation::SPEC, - Justification: [justification::KIND] => justification::SPEC, - BulletsAndNumbering: [bullets_numbering::KIND] => bullets_numbering::SPEC, - TateChuYokoSettings: [tate_chu_yoko::KIND] => tate_chu_yoko::SPEC, - WarichuSettings: [warichu::KIND] => warichu::SPEC, - CompositeFonts: [composite_fonts::KIND] => composite_fonts::SPEC, - KinsokuSets: [kinsoku_sets::KIND] => kinsoku_sets::SPEC, - SavePdf: [save_pdf::KIND] => save_pdf::SPEC, - SvgOptions: [svg_options::KIND] => svg_options::SPEC, - JavaScriptFiles: [javascript_files::KIND] => javascript_files::SPEC, - SvgFilter: [svg_filter::KIND] => svg_filter::SPEC, - NewDocumentMore: [new_document::MORE] => new_document::MORE_SPEC, - NewDocumentProfiles: [new_document::PROFILES] => new_document::MORE_SPEC, - Place: [place::KIND] => place::SPEC, - RasterOptions: ["pngOptions", "jpgOptions", "webpOptions", "gifOptions", "png8Options"] => png_options::SPEC, - ExportAs: ["exportAs"] => export_as::SPEC, - ImportPdf: [import_pdf::KIND] => import_pdf::SPEC, - SwatchConflict: [swatch_conflict::KIND] => swatch_conflict::SPEC, - ProfileMismatchOpen: [profile_mismatch::OPEN_KIND] => profile_mismatch::OPEN_SPEC, - ProfileMismatchPaste: [profile_mismatch::PASTE_KIND] => profile_mismatch::PASTE_SPEC, - FileInfo: [file_info::KIND] => file_info::SPEC, - RasterEffectsSettings: [raster_effects::KIND] => raster_effects::SPEC, - EffectGallery: [effect_gallery::KIND] => effect_gallery::SPEC, - MissingLinks: [missing_links::KIND] => missing_links::SPEC, - MissingFonts: [missing_fonts::KIND] => missing_fonts::SPEC, - FindLinks: [find_links::KIND] => find_links::SPEC, - FindReplace: [find_replace::KIND] => find_replace::SPEC, - TextImport: [text_import::KIND] => text_import::SPEC, - PdfPresets: [pdf_presets::KIND] => pdf_presets::SPEC, - PdfPreset: [save_pdf::PRESET_KIND] => save_pdf::PRESET_SPEC, - PdfFlattenerOptions: [save_pdf::CUSTOM_KIND] => save_pdf::CUSTOM_SPEC, - SaveOptions: [save_options::KIND] => save_options::SPEC, - TextExport: [text_export::KIND] => text_export::SPEC, - OfficeExport: [office_export::KIND] => office_export::SPEC, - DxfOptions: [dxf_options::KIND] => dxf_options::SPEC, - PlacementOptions: [placement_options::KIND] => placement_options::SPEC, - Relink: [relink::KIND] => relink::SPEC, - Package: [package::KIND] => package::SPEC, - ActionBatch: [action_batch::KIND] => action_batch::SPEC, - ActionSetOptions: [action_set_options::KIND] => action_set_options::SPEC, - ActionNew: [action_new::KIND] => action_new::SPEC, - ActionPlayback: [action_playback::KIND] => action_playback::SPEC, - ActionStopRecord: [action_stop::RECORD_KIND] => action_stop::RECORD_SPEC, - ActionStopMessage: [action_stop::MESSAGE_KIND] => action_stop::MESSAGE_SPEC, - ActionInsertMenuItem: [action_insert_menu_item::KIND] => action_insert_menu_item::SPEC, - ActionSelectObject: [action_select_object::KIND] => action_select_object::SPEC, - SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, - DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, - EpsOptions: [eps_options::KIND] => eps_options::SPEC, - EpsFlattenerOptions: [eps_options::CUSTOM_KIND] => eps_options::CUSTOM_SPEC, - HpglOptions: [hpgl_options::KIND] => hpgl_options::SPEC, - Recovery: [crate::recovery::KIND] => recovery::SPEC, - PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, - SafeMode: [safe_mode::KIND] => safe_mode::SPEC, - DxfImport: [dxf_import::KIND] => dxf_import::SPEC, - PsdImport: [psd_import::KIND] => psd_import::SPEC, - RasterFormatOptions: ["tiffOptions", "bmpOptions", "tgaOptions"] => png_options::SPEC, - SaveForWeb: [save_for_web::KIND] => save_for_web::SPEC, - PsdOptions: ["psdOptions"] => png_options::SPEC, - Print: [print::KIND] => print::SPEC, - PrintPreset: [print::PRESET_KIND] => print::PRESET_SPEC, - PrintPresets: [print_presets::KIND] => print_presets::SPEC, - Plugin: [plugin::KIND] => plugin::SPEC, - PluginExport: [plugin::EXPORT_KIND] => plugin::EXPORT_SPEC, - PluginImport: [plugin::IMPORT_KIND] => plugin::IMPORT_SPEC, - PluginInstall: [plugin::INSTALL_KIND] => plugin::INSTALL_SPEC, - ScriptCheck: [script_check::KIND] => script_check::SPEC, - ScriptRun: [script_run::KIND] => script_run::SPEC, - ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, - ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, - ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, - ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, - VectorHalftone: [halftone::KIND] => halftone::SPEC, - ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, - SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, - SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, - SmartPunctuation: [smart_punctuation::KIND] => smart_punctuation::SPEC, - PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC, - Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC, - LiquifyOptions: [liquify::KIND] => liquify::SPEC, - FreehandOptions: [freehand::KIND] => freehand::SPEC, - ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, - ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, - CircleOptions: [circle_options::KIND] => circle_options::SPEC, - ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, - FlareOptions: [flare_options::KIND] => flare_options::SPEC, - SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, - DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, - DeleteUsedSymbol: [symbol_delete::USED] => symbol_delete::USED_SPEC, - SymbolismOptions: [symbolism_options::KIND] => symbolism_options::SPEC, - PerspectiveGridPresets: [perspective_presets::KIND] => perspective_presets::SPEC, - PerspectiveGridOptions: [perspective_options::KIND] => perspective_options::SPEC, - BlendOptions: [blend_options::KIND] => blend_options::SPEC, - LivePaintGaps: [live_paint_gaps::KIND] => live_paint_gaps::SPEC, - LivePaintSelectionOptions: [live_paint_selection::KIND] => live_paint_selection::SPEC, - LivePaintBucketOptions: [live_paint_bucket::KIND] => live_paint_bucket::SPEC, - BrushOptions: [brush_options::KIND] => brush_options::SPEC, - NewBrush: [new_brush::KIND] => new_brush::SPEC, - EditSelection: [edit_selection::KIND] => edit_selection::SPEC, - EditViews: [edit_views::KIND] => edit_views::SPEC, - EditCustomDictionary: [custom_dictionary::KIND] => custom_dictionary::SPEC, - CheckSpelling: [check_spelling::KIND] => check_spelling::SPEC, - PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC, - LayerOptions: [layer_options::KIND] => layer_options::SPEC, - LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, - NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC, - AttributesPanelOptions: [attributes_panel_options::KIND] => attributes_panel_options::SPEC, - PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, - PixelSnapOptions: [pixel_snap_options::KIND] => pixel_snap_options::SPEC, - RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, - RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC, - PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, - DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, - SmoothBridge: [crate::addons::pathtools::bridge::KIND] => crate::addons::pathtools::bridge::SPEC, - TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC, - SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, - NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, - SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, - TextTweaker: [crate::addons::typetools::KIND] => crate::addons::typetools::SPEC, - SelectByArtboards: [crate::addons::select::KIND] => crate::addons::select::SPEC, - SelectByLinkStatus: [crate::addons::select::link_status::KIND] => crate::addons::select::link_status::SPEC, - ArrangeTools: [crate::addons::arrange::GRID, crate::addons::arrange::REPLACE, crate::addons::arrange::SIZE, crate::addons::arrange::OPACITY, crate::addons::arrange::SORT] => crate::addons::arrange::SPEC, - ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm), -} - -/// The button labels the shared dialog frame can show (OK, discard, the fixed Cancel/Close and -/// Reset), so the catalog tests can insist they are translated. -pub fn button_labels() -> Vec<&'static str> { - let mut v = vec!["Cancel", "Close"]; - for spec in std::iter::once(&DialogSpec::FORM).chain(DialogKind::ALL.iter().map(|k| k.spec())) { - v.extend(spec.ok); - v.extend(spec.cancel); - v.extend(spec.discard); - v.extend(spec.alternate.map(|(label, _)| label)); - v.extend(spec.reset.map(|_| "Reset")); - } - v.sort_unstable(); - v.dedup(); - v -} - -/// The spec for a `Dialog::kind` ([`DialogSpec::FORM`] when unregistered). -fn spec(kind: &str) -> &'static DialogSpec { - static FALLBACK: DialogSpec = DialogSpec::FORM; - DialogKind::of(kind).map_or(&FALLBACK, DialogKind::spec) -} - -/// The `__` fields that `ui.dialog.set` can set on `d`: controls of its kind that the dialog holds -/// under a `__` name, each set as the control sets it. Every other `__` field of a dialog holds -/// what its OK acts on (the command and its fixed params, the targets, a file, the preset being -/// edited) or state the dialog keeps for itself, and `ui.dialog.set` refuses it -/// ([`protected_field`]), so a request cannot change what OK does after a person opened the dialog. -/// Flags that a button sets together with other fields are refused too: the style dialogs' -/// `__reset*` (Reset Panel also clears the section's fields, so scripts run -/// `ui.charStyleOptions.resetPanel` or `ui.paraStyleOptions.resetPanel`) and Artboard Options' -/// `__fit`, `__sizeChoice`, `__refx` and `__refy` (set with the size and position they record), and -/// Scribble's `__scribbleSetting` (the menu sets the preset's parameters with it). -fn hidden_controls(d: &Dialog) -> &'static [&'static str] { - match DialogKind::of(&d.kind) { - // Duotone's tone row, and the 3D effects' tab, gizmo, light and Show axis. - Some(DialogKind::Effect) => &["__gizmo", "__light", "__showAxis", "__tab", "__tone"], - // The preset name being typed and the format whose settings the gear shows. - Some(DialogKind::ExportForScreens) => &["__savePreset", "__settings"], - // Keywords typed but not added yet. - Some(DialogKind::FileInfo) => &["__keyword"], - // The preset name being typed. - Some(DialogKind::FlattenTransparency) => &["__presetName"], - // The page shown. - Some(DialogKind::GraphType) => &[graph_type::PAGE], - // The Resolution menu's Other. - Some(DialogKind::RasterOptions | DialogKind::RasterFormatOptions | DialogKind::PsdOptions) => &["__otherPpi"], - // The category shown, the search text and the three settings kept outside the preferences. - Some(DialogKind::Preferences) => &["__category", "__search", "__smartGuides", "__snapToGrid", "__taskBar"], - // The section shown, the sheet the preview shows and the preset name being typed. - Some(DialogKind::Print | DialogKind::PrintPreset) => &["__savePresetAs", "__section", "__sheet"], - // The section shown, All or a range of artboards, the bleed link, the two password - // checkboxes and the preset name being typed. - Some(DialogKind::SavePdf | DialogKind::PdfPreset) => { - &["__allArtboards", "__bleedLinked", "__requireOpenPassword", "__restrictPermissions", "__savePresetAs", "__section"] - } - // The selected rows and Randomize's seed. - Some(DialogKind::Recolor) => &["__seed", "__sel"], - // The view, zoom, download speed, selected color table entries, the color table entry whose - // Color Picker opens and the preset name being typed. - Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__editColor", "__kbps", "__presetName", "__view", "__zoom"], - // The link that keeps width and height in proportion. - Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"], - // The attention filter, the Keys section, the search text and the key being recorded. - Some(DialogKind::ShortcutImport) => &["__attention", "__keysOpen", "__query", "__recording"], - // Set Size of Each's Width and Height checkboxes. - Some(DialogKind::ArrangeTools) if d.kind == crate::addons::arrange::SIZE => &["__height", "__width"], - // The search field. - Some(DialogKind::SelectByArtboards | DialogKind::SelectByLinkStatus) => &["__search"], - _ => &[], - } -} - -/// The controls of [`hidden_controls`] that a button adds to the dialog, which `ui.dialog.set` can -/// set only while the dialog holds them: Save PDF's and Print's `__savePresetAs`, whose presence -/// makes OK save a preset instead of writing the PDF or printing. -const ADDED_CONTROLS: &[&str] = &["__savePresetAs"]; - -/// Whether `field` is a control of `d` that `ui.dialog.set` can set: one of the controls of `d`'s -/// kind ([`hidden_controls`]), and for one that a button adds ([`ADDED_CONTROLS`]), one `d` holds. -fn settable_control(d: &Dialog, field: &str) -> bool { - hidden_controls(d).contains(&field) && (!ADDED_CONTROLS.contains(&field) || d.fields.contains_key(field)) -} - -/// Whether `field` is a `__` field of `d` that `ui.dialog.set` refuses: any `__` field, held or -/// not, except the controls of `d`'s kind ([`settable_control`]). -pub fn protected_field(d: &Dialog, field: &str) -> bool { - field.starts_with("__") && !settable_control(d, field) -} - -/// Whether `ui.dialog.set` can set `field` on `d`: a `__` field only when it is one of the controls -/// of `d`'s kind ([`protected_field`]); otherwise a field it holds, `discard` on a dialog with a -/// discard button, `preview` on one with a live preview, one of its spec's `inputs` for its kind, -/// or one it `passes` on. -pub fn accepts_field(d: &Dialog, field: &str) -> bool { - if field.starts_with("__") { - return !protected_field(d, field); - } - let spec = spec(&d.kind); - d.fields.contains_key(field) - || (field == "discard" && spec.discard.is_some()) - || (field == "preview" && spec.preview) - || (spec.inputs)(&d.kind).contains(&field) - || (spec.passes)(d, field) -} - -/// Set `field` of `d` to `value` for `ui.dialog.set`, as the dialog's own control for it does: a -/// Pattern Brush Options corner tile set this way is saved by OK, as one chosen from its menu is, -/// an Edit Data Set field set this way is no longer the row's empty text value, and a Layer -/// Options setting set this way for several rows is sent to every row (Template also sets Lock -/// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as -/// one picked from its menu does, and the preset it shows follows the DXF options set this way. -/// A Graph Data Column Width set this way sets every column, as Cell Style's does. A Width Point -/// Edit side width set this way for several points sets it on every point, as typing it does. An -/// Import PDF `allPages` set this way to the other pick sets Import PDF pages as links back to its -/// default. A Dimension Tool Options `arrowStyle` set this way clears `arrowHead`, and a built-in -/// `arrowHead` set this way sets both values of its Arrow Style entry, as that menu does. -/// A Pathfinder effect's precision set this way replaces a stored precision out of range, the -/// bound included. -pub fn set_field(d: &mut Dialog, field: String, value: Value) { - if d.kind == brush_options::KIND { - brush_art_options::note_set(d, &field); - } - if d.kind == variables::KIND { - variables::note_set(d, &field); - } - if d.kind == layer_options::KIND { - layer_options::note_set(d, &field, &value); - } - if d.kind == import_pdf::KIND { - import_pdf::note_set(d, &field, &value); - } - if d.kind == dimension::KIND && dimension::note_set(d, &field, &value) { - return; - } - if d.kind == "preferences" { - crate::prefs_dialog::note_set(d, &field, &value); - } - if d.kind == new_document::KIND || new_document::popup_open(d) { - new_document::note_set(d, &field); - } - // A Pathfinder effect's precision set this way replaces a stored one out of range, as one - // entered in its field does. - if d.kind == "effect" && field == "precision" { - d.fields.remove(effect::OPENED_PRECISION); - } - // Create Object Mosaic's Resize Using Percentages shows the new size the other way, as its checkbox does. - if d.kind == object_mosaic::KIND && field == "percentages" { - object_mosaic::set_percentages(d, &value); - return; - } - let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); - let mosaic = (d.kind == object_mosaic::KIND).then(|| field.clone()); - let graph = (d.kind == graph_data::KIND).then(|| field.clone()); - let width = (d.kind == width_point::KIND).then(|| field.clone()); - d.fields.insert(field, value); - if let Some(field) = dxf { - dxf_options::note_set(d, &field); - } - if let Some(field) = mosaic { - object_mosaic::note_set(d, &field); - } - if let Some(field) = graph { - graph_data::note_set(d, &field); - } - if let Some(field) = width { - width_point::note_set(d, &field); - } -} - -/// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the -/// `__` controls of its kind, `discard`, `preview` and the spec's `inputs` for its kind. -pub fn field_names(d: &Dialog) -> Vec { - let spec = spec(&d.kind); - let mut names: Vec = d.fields.keys().filter(|k| !k.starts_with("__")).cloned().collect(); - names.extend(hidden_controls(d).iter().filter(|f| settable_control(d, f)).map(|f| f.to_string())); - names.extend(spec.discard.map(|_| "discard".to_string())); - names.extend(spec.preview.then(|| "preview".to_string())); - names.extend((spec.inputs)(&d.kind).iter().map(|i| i.to_string())); - names.sort_unstable(); - names.dedup(); - names -} - -/// Run a command and close the dialog (whether or not the command succeeded). -fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogResult { - let r = app.run(id, params); - app.ui.dialog = None; - r -} - -/// Set a tool's options with `tool.setOption` (`params`) and close the dialog; when the tool -/// refuses one of them, nothing is set and the dialog stays open. -fn set_tool_options_and_close(app: &mut VectorcraftApp, params: Value) -> DialogResult { - let r = app.run("tool.setOption", params); - if r.is_ok() { - app.ui.dialog = None; - } - r -} - -/// The field of a dialog opened over another (Import Shortcut Set over Keyboard Shortcuts) that -/// holds the dialog under it, which Cancel and Escape show again. -pub(crate) const PARENT: &str = "__parent"; - -/// The dialog `d` was opened over, as it was. -pub(crate) fn parent(d: &Dialog) -> Option { - d.fields.get(PARENT).and_then(|v| serde::Deserialize::deserialize(v).ok()) -} - -/// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields -/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`, EPS Options' -/// and Save PDF's `flattenerPreset`, which drop the Custom… options), a change -/// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor -/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. Save -/// PDF's bleed link links the bleed as its button does. A value Composite Fonts' Show Sample or -/// Save PDF's bleed link can't take is refused. -pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { - if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { - transform_each::field_set(app, field, old); - return Ok(()); - } - if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) { - return recolor::field_set(app, field); - } - if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { - return composite_fonts::field_set(d, field); - } - if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == save_pdf::KIND || d.kind == save_pdf::PRESET_KIND) { - return save_pdf::field_set(d, field); - } - if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { - eps_options::field_set(d, field); - return Ok(()); - } - let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; - match field { - "exportPreset" => export_for_screens::preset_set(app), - "subfolders" | "subfolderBy" => { - if d.fields.get(field) != old { - d.fields.remove("__itemFolders"); - } - Ok(()) - } - _ => Ok(()), - } -} - -/// Close the open dialog as Cancel does, rolling back a live preview and showing the dialog it was -/// opened over (`ui.dialog.cancel`). -pub fn cancel(app: &mut VectorcraftApp) { - cancel_brush_key_color(app, true); - missing_fonts::requeue_replaced(app); - // More Settings' pop-up and Save Preset end on their own; New Document stays. - if app.ui.dialog.as_mut().is_some_and(new_document::close_popup) { - return; - } - if let Some(d) = app.ui.dialog.take() { - if d.kind == "preferences" { - crate::original_editor::cancel(app); - } - if d.kind == swatch_conflict::KIND { - crate::placing::cancel_swatch_paste(app); - } - if d.kind == profile_mismatch::OPEN_KIND { - profile_mismatch::cancel_open(app); - } - if d.kind == profile_mismatch::PASTE_KIND { - crate::placing::cancel_swatch_paste(app); - } - if d.kind == plugin::INSTALL_KIND { - app.pending_plugin_install = None; - } - if d.kind == safe_mode::STOPPED { - safe_mode::cancel_stopped(app); - } - if d.kind == confirm::MISSING_FONT_EDIT { - confirm::answer_missing_font_edit(app, &d, false); - } - // The growth question's Cancel button is its Stop button. - if d.kind == script_run::GROWTH_KIND { - app.session.script_request_stop(); - } - if d.kind == script_run::NOTICE_KIND { - script_run::notice_cancel(app, &d); - } - if d.kind == proof_setup::KIND { - proof_setup::cancel(app, &d); - } - if d.kind == script_run::PICKER_KIND { - script_run::picker_cancel(app, &d); - } - missing_links::cancelled(app, &d); - // Cancel discards Recolor Artwork's own history of color edits with them. - if d.kind == recolor::KIND { - app.ui.recolor_history = Default::default(); - } - // Find Font's next open starts with an empty replacement search. - if d.kind == "findFont" - && let Some(ctx) = app.ui_ctx.clone() - { - crate::find_font::clear_search(&ctx); - } - // Toolbar-only Flare options start no preview and must not cancel a gesture - // that was already active before opening them. The generic parameter dialog has a spec - // without a preview, yet previews some commands (Grid Repeat Options) when asked to. - let owns_preview = d.kind != flare_options::KIND || d.fields.contains_key(form::PREVIEWED); - if (spec(&d.kind).preview && owns_preview) || d.fields.contains_key(form::PREVIEWED) { - let _ = app.session.cancel_interaction(); - } - app.ui.dialog = parent(&d); - } - settle(app); -} - -/// Whether the open dialog has a Reset ([`DialogSpec::reset`]). -pub(crate) fn can_reset(app: &VectorcraftApp) -> bool { - app.ui.dialog.as_ref().is_some_and(|d| spec(&d.kind).reset.is_some()) -} - -/// Reset (`ui.dialogReset`, or Cancel while Alt or Option is held): the open dialog's fields go -/// back to their defaults and it stays open → the dialog; an error when no dialog is open, the -/// open one has no Reset, or its Reset fails (the dialog is then left as it was). -pub(crate) fn reset(app: &mut VectorcraftApp) -> DialogResult { - let Some(mut d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; - let Some(reset) = spec(&d.kind).reset else { return Err("the open dialog has no Reset".into()) }; - reset(app, &mut d)?; - let out = serde_json::to_value(&d).unwrap_or_default(); - app.ui.dialog = Some(d); - Ok(out) -} - -/// Apply the open dialog (OK). -pub fn confirm(app: &mut VectorcraftApp) -> DialogResult { - cancel_brush_key_color(app, true); - missing_fonts::requeue_replaced(app); - let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; - // A file dialog it shows off the UI thread confirms the dialog as it is again. - let r = crate::picks::as_entry(app, || crate::picks::Entry::Confirm(Box::new(d.clone())), |app| (spec(&d.kind).confirm)(app, &d)); - settle(app); - r -} - -/// After a dialog closes, and each frame: a Missing Fonts dialog that another dialog replaced waits -/// for its turn again, a Proof Setup preview that another dialog replaced is undone, the search a -/// Missing Fonts or Find Linked Files dialog started stops once that dialog is gone, and with no -/// dialog open the choice about a stopped plug-in that another -/// dialog replaced opens again, else the questions about the next restored document's linked files -/// ([`crate::recovery::ask_next`]), else the next document's Missing Fonts dialog (one dialog at a -/// time). -pub(crate) fn settle(app: &mut VectorcraftApp) { - crate::placing::settle_swatch_paste(app); - proof_setup::restore_replaced(app); - profile_mismatch::settle(app); - missing_fonts::requeue_replaced(app); - missing_fonts::stop_when_closed(app); - find_links::stop_when_closed(app); - safe_mode::reopen(app); - crate::recovery::ask_next(app); - missing_fonts::open_next(app); -} - -/// The field of a dialog that a save panel opened (its format's options): Enter doesn't confirm it -/// until Enter has been let go. -pub(crate) const AFTER_PANEL: &str = "__afterPanel"; - -/// Marks the open dialog, if any, as one a save panel opened ([`AFTER_PANEL`]): the Enter that -/// closed the panel, still held, doesn't confirm it. -pub(crate) fn opened_by_panel(app: &mut VectorcraftApp) { - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert(AFTER_PANEL.into(), json!(true)); - } -} - -/// Draws the active dialog and handles shared initial focus, keyboard shortcuts and actions. -/// Inline actions and footer buttons use the same confirmation and preview rollback paths. -pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { - refresh_brush_key_color(app); - crate::shortcuts::hold_back_keys(app, ctx); - about::show(app, ctx); - settle(app); - confirm::show_waiting(app); - // The kind of dialog shown last frame: a different one (or none) means this one just opened, and - // its first field is to take the keyboard focus (`focus_id`, until a field takes it). - let (shown_id, focus_id) = (egui::Id::unique("dialog-shown"), egui::Id::unique("dialog-focus-pending")); - let Some(mut d) = app.ui.dialog.clone() else { - revolve_gizmo::clear(ctx); - app.ui.dialog_file = None; - ctx.data_mut(|m| { - m.remove::(shown_id); - m.remove::(focus_id); - }); - return; - }; - if !revolve_gizmo::active(&d) { - revolve_gizmo::clear(ctx); - } - let focus_first = ctx.data_mut(|m| { - if m.get_temp::(shown_id).as_deref() != Some(d.kind.as_str()) { - m.insert_temp(shown_id, d.kind.clone()); - m.insert_temp(focus_id, true); - } - m.get_temp::(focus_id).unwrap_or(false) - }); - // Not in the frame of a click (the one on the menu item that opened it): egui takes the focus - // from a field the click missed, so the field takes it a frame later (#1367). - let clicked = ctx.input(|i| i.pointer.any_click()); - if focus_first && clicked { - ctx.request_repaint(); - } - let focus_first = focus_first && !clicked; - let spec = spec(&d.kind); - // Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to. - if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) { - modal::over_parent(ctx); - } - if let Some(window) = spec.window { - return window(app, ctx); - } - let mut ok = false; - let mut ok_clicked = false; - let mut ok_enabled = true; - let mut cancel = false; - let mut reset = false; - let mut discard = false; - let mut alternate = false; - // Opened as a save panel closed: the Enter that closed it isn't this dialog's, until it is let go. - let after_panel = d.bool(AFTER_PANEL); - if after_panel && !ctx.input(|i| i.key_down(egui::Key::Enter) || i.key_pressed(egui::Key::Enter)) { - d.fields.remove(AFTER_PANEL); - } - // A body can open another dialog in its place (EPS Options' Custom…): this frame's Enter - // doesn't confirm that one. - let opened = d.kind.clone(); - let heading = (spec.heading)(&d); - let revolves = revolve_gizmo::active(&d); - if revolves { - revolve_gizmo::show(app, ctx, &mut d); - three_d_classic::surface_outline(app, ctx, &d); - } - let initial = if revolves { egui::vec2((ctx.content_rect().width() / 2.0 - 226.0).max(0.0), -40.0) } else { egui::vec2(0.0, -40.0) }; - let id = egui::Id::unique(("dialog", d.kind.as_str())); - let id = if revolves { id.with("revolve") } else { id }; - let canvas_pick = brush_key_color_canvas(app, ctx); - modal::show_at(ctx, &heading, id, initial, MARGIN, canvas_pick, |ui| { - // Never wider than the window (a large UI scale in a small window): the text wraps. - let room = (ctx.content_rect().width() - 2.0 * (f32::from(MARGIN) + EDGE_GAP)).max(EDGE_GAP); - ui.set_min_width(spec.min_width.min(room)); - ui.set_max_width(spec.max_width.map_or(room, |w| w.min(room))); - if let Some(header) = spec.header { - header(ui, &heading); - } else { - modal::heading(ui, &heading); - } - ui.add_space(12.0); - // Just opened: its first enabled field takes the keyboard focus, as in the reference app - // (type a value, press Enter). Only the body's fields can take it. - if focus_first { - ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); - } - // When the dialog is taller than the window, its body scrolls, and the heading and the - // buttons stay in view. - if let Some(body) = spec.body_with_actions { - match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { - DialogAction::None => {} - DialogAction::Confirm => ok = true, - DialogAction::Cancel => cancel = true, - } - } else { - cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); - } - // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. - if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { - ui.data_mut(|m| m.remove::(focus_id)); - } - if spec.body_with_actions.is_some() { - return; - } - ui.add_space(16.0); - // The button row is as wide as the fields above it and as tall as the buttons: a - // right-to-left layout would otherwise take all the room left in the window, so the - // window could never shrink to its content. - let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); - ok_enabled = spec.ok_enabled.is_none_or(|f| f(app, &d)); - ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { - if let Some(label) = spec.ok.map(|ok| spec.ok_label.map_or(ok, |f| f(app))) - && widgets::primary_button_enabled(ui, label, ok_enabled).clicked() - { - ok_clicked = true; - } - ui.add_space(8.0); - // While Alt (Option) is held, Cancel reads Reset on a dialog that has one. - let resets = spec.ok.is_some() && spec.reset.is_some() && ui.input(|i| i.modifiers.alt); - let label = if resets { - "Reset" - } else if spec.ok.is_some() { - spec.cancel.unwrap_or("Cancel") - } else { - "Close" - }; - if widgets::secondary_button(ui, label).clicked() { - if resets { - reset = true; - } else { - cancel = true; - } - } - if let Some((label, _)) = spec.alternate { - ui.add_space(8.0); - alternate = widgets::secondary_button(ui, label).clicked() && ok_enabled; - } - if let Some(label) = spec.discard { - ui.add_space(28.0); - discard = widgets::secondary_button(ui, label).clicked(); - } - // The row runs right to left: a left-to-right layout in the room left of the buttons - // puts its control at the row's left end. - if let Some(left) = spec.footer_left { - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| left(ui, &mut d)); - } - }); - }); - let rejected = ctx.data_mut(|d| d.remove_temp::(widgets::dialog_reject_commit_flag())).unwrap_or(false); - // A field that refused its text when the press on OK took its focus keeps the dialog open, as - // Enter does. Only a pointer click has such a press; the keyboard and screen readers press OK - // in one frame. - let press = egui::Id::unique("dialog-press-pass"); - let (pressed, released) = ctx.input(|i| (i.pointer.any_pressed(), i.pointer.any_released())); - if pressed { - let pass = ctx.cumulative_pass_nr(); - ctx.data_mut(|m| m.insert_temp(press, pass)); - } - let (pressed_at, refused_at) = ctx.data(|m| (m.get_temp::(press), m.get_temp::(widgets::dialog_reject_pass()))); - let refused_during_click = released && matches!((refused_at, pressed_at), (Some(r), Some(p)) if r >= p); - if ok_clicked && !rejected && !refused_during_click { - ok = true; - } - if spec.ok.is_some() && ok_enabled && !after_panel && !rejected && d.kind == opened && crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) { - ok = true; - } - if discard { - d.fields.insert("discard".into(), json!(true)); - ok = true; - } - if alternate && let Some((_, field)) = spec.alternate { - d.fields.insert(field.into(), json!(true)); - ok = true; - } - app.ui.dialog = Some(d); - if cancel { - self::cancel(app); - } else if reset { - if let Err(e) = self::reset(app) { - app.status(e); - } - } else if ok && let Err(e) = confirm(app) { - app.status(e); - } -} - -/// What a dropdown shows for `names`, a list mixing built-in labels (`builtin(index)`: translated -/// into `lang`) with names the user saved or a file or the system supplied (shown as they are). -pub(crate) fn shown_names<'a>(lang: crate::i18n::Lang, names: &[&'a str], builtin: impl Fn(usize) -> bool) -> Vec<&'a str> { - names.iter().enumerate().map(|(k, n)| crate::i18n::label_or_name(lang, n, builtin(k))).collect() -} - -/// [`widgets::dropdown_names`] over such a mixed list ([`shown_names`] in the UI language), showing -/// `current` as its entry reads; a `current` that isn't among `names` is shown as given (a caller -/// translates its own [Custom]). Returns the index chosen in `names`. -pub(crate) fn mixed_dropdown( - ui: &mut egui::Ui, - id: impl std::hash::Hash + std::fmt::Debug, - current: &str, - names: &[&str], - width: f32, - builtin: impl Fn(usize) -> bool, -) -> Option { - let shown = shown_names(crate::i18n::current(), names, builtin); - let current = names.iter().position(|n| *n == current).and_then(|i| shown.get(i).copied()).unwrap_or(current); - widgets::dropdown_names(ui, id, current, &shown, width) -} - #[cfg(test)] mod tests; #[cfg(test)] @@ -1112,6 +204,8 @@ mod tests_export_selection; #[cfg(test)] mod tests_import_pdf; #[cfg(test)] +mod tests_messages; +#[cfg(test)] mod tests_package; #[cfg(test)] mod tests_plugin_export; @@ -1123,8 +217,6 @@ mod tests_plugin_import; mod tests_raster_formats; #[cfg(test)] mod tests_raster_supplied_options; -#[cfg(test)] -mod tests_svg_options_range; #[cfg(test)] mod tests_dxf; @@ -1147,6 +239,8 @@ mod tests_tiff_bmp_tga; #[cfg(test)] mod tests_save_for_web; +#[cfg(test)] +mod tests_save_for_web_table; #[cfg(test)] mod tests_psd; @@ -1169,9 +263,6 @@ mod tests_perspective; #[cfg(test)] mod tests_modal; -#[cfg(test)] -mod tests_scroll; - #[cfg(test)] mod tests_rectangular_grid; diff --git a/crates/ui-egui/src/dialogs/host.rs b/crates/ui-egui/src/dialogs/host.rs new file mode 100644 index 0000000000..d524d50dce --- /dev/null +++ b/crates/ui-egui/src/dialogs/host.rs @@ -0,0 +1,226 @@ +//! The app's access to its window's dialog host, and the once-per-frame pump that serves every dialog +//! module and every held dialog. + +use craft_ui::dialog::{DialogId, DialogResult, HoldsOk}; +use craft_ui::shell::{WindowDialogs, WindowKey}; +use serde_json::Value; + +use crate::VectorcraftApp; + +/// The most dialogs waiting for an answer at once. +pub(crate) const MAX_WAITING: usize = 16; + +/// What the app told the user for a dialog while it waited, as (dialog key, message) pairs, at most +/// [`MAX_WAITING`] of them. +#[derive(Default)] +pub(crate) struct Told(pub Vec<(String, String)>); + +/// The main window's dialog host. +pub(crate) fn window_dialogs(ctx: &egui::Context) -> WindowDialogs { + // PLAN: assumed `WindowKey::main()` names the main window's key + WindowDialogs::of(ctx, &WindowKey::main()) +} + +impl VectorcraftApp { + /// The dialog host of the window, `None` before the first frame gave the app its context. + pub(crate) fn dialogs(&self) -> Option { + self.ui_ctx.as_ref().map(window_dialogs) + } +} + +/// What a held dialog's open adds to [`open_held_with`]. +#[derive(Default)] +pub(crate) struct HeldOptions { + /// The dialog this one opens over; it closes with its parent. + pub parent: Option, + /// Runs when the dialog is cancelled (a live preview's rollback). + pub cancel: Option>, +} + +/// Runs one held dialog's pass; `Some(cancelled)` once the dialog is gone. +type Drain = Box Option>; + +struct Record { + drain: Drain, + cancel: Option>, +} + +/// The held dialogs of the app: one record each, served by [`pump`]. +#[derive(Default)] +pub(crate) struct Held(Vec); + +fn drain(id: DialogId, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain { + Box::new(move |app| { + // Without a window nothing can answer: the dialog counts as cancelled so its rollback runs. + let Some(host) = app.dialogs() else { return Some(true) }; + if let Some(answer) = host.with(|h| h.get_mut_by_id::(id).and_then(D::take_ok)) { + // The host's lock is released while `ok` runs: it may open dialogs. + let verdict = ok(app, &answer).map_err(Into::into); + host.with(|h| { + if let Some(d) = h.get_mut_by_id::(id) { + d.answer_ok(verdict); + } + }); + } + host.with(|h| h.take_by_id::(id)).map(|r| matches!(r, DialogResult::Cancel)) + }) +} + +/// Opens `dialog` holding its OK: OK runs `ok`, and an `Err` keeps the dialog open with the reason under its +/// rows. `None` without a window. +pub(crate) fn open_held( + app: &mut VectorcraftApp, + dialog: D, + ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static, +) -> Option { + open_held_with(app, dialog, ok, HeldOptions::default()) +} + +/// [`open_held`] with a parent and a cancel hook. +pub(crate) fn open_held_with( + app: &mut VectorcraftApp, + dialog: D, + ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static, + options: HeldOptions, +) -> Option { + let host = app.dialogs()?; + let dialog = dialog.held_ok(); + let id = host.with(|h| match options.parent { + Some(parent) => h.open_child(dialog, parent), + None => h.open(dialog), + }); + app.held.0.push(Record { drain: drain::(id, ok), cancel: options.cancel }); + Some(id) +} + +/// The dialog on top of the stack. +fn top_dialog(app: &VectorcraftApp) -> Option { + // `open_dialogs` lists in opening order, the top one last. + app.dialogs()?.with(|h| h.open_dialogs().last().map(|d| d.id)) +} + +/// Whether the top dialog has a Reset to run. +pub(crate) fn can_reset_top(app: &VectorcraftApp) -> bool { + let (Some(host), Some(top)) = (app.dialogs(), top_dialog(app)) else { return false }; + host.with(|h| h.can_reset_by_id(top)) +} + +/// `ui.dialogReset`: resets the top dialog. +pub(crate) fn reset_top(app: &mut VectorcraftApp) -> Result { + let (Some(host), Some(ctx), Some(top)) = (app.dialogs(), app.ui_ctx.clone(), top_dialog(app)) else { + return Err("no dialog open".into()); + }; + if host.with(|h| h.reset_by_id(&ctx, top)) { Ok(Value::Null) } else { Err("the dialog has no Reset".into()) } +} + +/// Pushes the app's facts into the dialogs that convert against them (Create Object Mosaic against the selected +/// image, Width Point Edit against the selected stroke). +pub(crate) fn sync(app: &mut VectorcraftApp) { + super::object_mosaic::sync(app); + super::width_point::sync(app); +} + +macro_rules! pumps { + ($app:ident, $ctx:ident; $($path:path),+ $(,)?) => { $( $path($app, $ctx); )+ }; +} + +/// Runs once per frame after the shell pass: every dialog module's pump, then the held dialogs. +// PLAN: every module pump below is assumed `pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context)`; +// `file_asks`' crate path and `missing_fonts::open_next` are assumed too. +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + sync(app); + pumps!(app, ctx; + crate::file_asks::pump, + crate::io::save::pump, + super::profile_mismatch::pump, + super::recovery::pump, + super::missing_links::pump, + super::find_links::pump, + super::missing_fonts::open_next, + super::text_import::pump, + super::psd_import::pump, + super::dxf_import::pump, + super::import_pdf::pump, + super::place::pump, + super::new_document::pump, + super::document_setup::pump, + super::package::pump, + super::graphic_style_options::pump, + super::layer_options::pump, + super::layers_panel_options::pump, + super::artboard_options::pump, + super::rearrange_artboards::pump, + super::rename_artboards::pump, + super::navigator_panel_options::pump, + super::variables::pump, + super::effect::pump, + super::halftone::pump, + super::raster_effects::pump, + super::envelope::pump, + super::effect_gallery::pump, + super::three_d::pump, + super::svg_filter::pump, + super::export_host::pump, + super::export_for_screens::pump, + super::save_for_web::pump, + super::save_pdf::pump, + super::flatten::pump, + super::preset_manager::pump, + super::print::pump, + super::tool_options::pump, + super::dimension::pump, + super::option_form::pump, + super::live_paint_gaps::pump, + super::graph_type::pump, + super::graph_data::pump, + super::graph_design::pump, + super::perspective_grid::pump, + super::perspective_presets::pump, + super::perspective_options::pump, + super::perspective_plane::pump, + super::slices::pump, + super::blend_options::pump, + super::corners::pump, + super::expand::pump, + super::saved_names::pump, + super::indexed_color::pump, + super::tracing_presets::pump, + super::plugin::pump, + crate::addons::dialogs::pump, + super::char_style_options::pump, + super::para_style_options::pump, + super::new_text_style::pump, + super::warichu::pump, + super::tate_chu_yoko::pump, + super::hyphenation::pump, + super::justification::pump, + super::smart_punctuation::pump, + super::kinsoku_sets::pump, + super::composite_fonts::pump, + super::bullets_numbering::pump, + super::find_replace::pump, + super::check_spelling::pump, + super::custom_dictionary::pump, + super::confirm::pump_missing_font, + super::actions::pump, + super::script_run::pump, + super::color_picker::pump, + super::proof_setup::pump, + super::command::pump, + ); + // A drain's `ok` may open held dialogs: those join the records that stay. + let mut kept = Vec::new(); + for mut record in std::mem::take(&mut app.held.0) { + match (record.drain)(app) { + None => kept.push(record), + Some(true) => { + if let Some(cancel) = record.cancel.take() { + cancel(app); + } + } + Some(false) => {} + } + } + kept.append(&mut app.held.0); + app.held.0 = kept; +} diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7186f0707d..8b846591cb 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -52,55 +52,24 @@ fn queried_dialog(id: &str) -> Option<(&'static str, &'static [&'static str])> { }) } -/// The dialog (kind, fields) the menu item of command `id` opens, as the reference app's does. -pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static str, Value)> { - if let Some(found) = crate::addons::arrange::dialog(app, id) { - return Some(found); +/// Opens the dialog the menu item of command `id` opens, as the reference app's does; `None` when `id`'s +/// item opens none. +// PLAN: assumed `object_dialogs::open_from_menu` and `addons::dialogs::open_from_menu` return whether they +// opened a dialog, and `halftone`, `rearrange_artboards`, `rename_artboards` and `smart_punctuation` each have +// `CMD` and `open(app) -> Result`. +pub(super) fn open_menu_dialog(app: &mut VectorcraftApp, id: &str) -> Option> { + if crate::dialogs::object_dialogs::open_from_menu(app, id) || crate::addons::dialogs::open_from_menu(app, id) { + return Some(Ok(Value::Null)); + } + if crate::dialogs::variables::opens(id) { + crate::dialogs::variables::open(app, id, None); + return Some(Ok(Value::Null)); } Some(match id { - // Move opens on the offset moved last and the checkboxes it was last confirmed with. - "object.move" => ("move", crate::dialogs::transform::move_fields(app)), - "object.rotate" => ("rotate", json!({"angle": 0})), - "object.scale" => ("scale", json!({"sx": 100, "sy": 100, "uniform": true})), - // Transform Each opens on the values it was last confirmed with (#1732). - "object.transformEach" => (crate::dialogs::transform_each::KIND, crate::dialogs::transform_each::open_fields(app)), - "object.reflect" => ("reflect", json!({"axis": "vertical", "angle": 90})), - "object.shear" => ("shear", json!({"angle": 0, "axis": "horizontal", "axisAngle": 0})), - "path.average" => ("average", json!({"axis": "both"})), - // Average & Join opens on the joined anchor chosen last (Corner the first time). - "path.averageJoin" if app.ui.average_join.is_object() => ("averageJoin", app.ui.average_join.clone()), - "path.averageJoin" => ("averageJoin", json!({"to": "corner"})), - // Offset Path opens on the values it was last confirmed with. - "object.path.offsetPath" if app.ui.offset_path.is_object() => ("offsetPath", app.ui.offset_path.clone()), - "object.path.offsetPath" => ("offsetPath", json!({"offset": "10 pt", "joins": "miter", "miterLimit": 4})), - // Simplify opens its slider, or the dialog on the fields it was last confirmed with when - // "Open this dialog with these settings next time" was ticked. - "object.path.simplify" if app.ui.simplify.is_object() => ("simplify", app.ui.simplify.clone()), - "object.path.simplify" => (crate::dialogs::simplify_slider::KIND, crate::dialogs::simplify_slider::fields(app)), - "object.path.smooth" => (crate::dialogs::smooth_slider::KIND, crate::dialogs::smooth_slider::fields()), - "object.path.splitIntoGrid" => { - // The grid starts at the size of the selection. - let size = - 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())); - ("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1)) - } - "object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()), - crate::addons::pathtools::set_corners::COMMAND => { - (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) - } - crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), - crate::addons::pathtools::bridge::COMMAND => (crate::addons::pathtools::bridge::KIND, crate::addons::pathtools::bridge::fields()), - crate::addons::pathtools::tangent_circle::COMMAND => { - (crate::addons::pathtools::tangent_circle::KIND, crate::addons::pathtools::tangent_circle::fields(app)) - } - crate::addons::color::nearest::COMMAND => (crate::addons::color::nearest::KIND, crate::addons::color::nearest::fields()), - crate::addons::color::legend::COMMAND => (crate::addons::color::legend::KIND, crate::addons::color::legend::fields()), - crate::addons::typetools::COMMAND => (crate::addons::typetools::KIND, crate::addons::typetools::fields(app)), - crate::addons::select::COMMAND => (crate::addons::select::KIND, crate::addons::select::fields(app)), - "artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::open_fields(app)), - "artboard.rename" => (crate::dialogs::rename_artboards::KIND, crate::dialogs::rename_artboards::open_fields(app)), - // Smart Punctuation opens on the fields it was last confirmed with. - "type.smartPunctuation" => (crate::dialogs::smart_punctuation::KIND, crate::dialogs::smart_punctuation::fields(app)), + crate::dialogs::halftone::CMD => crate::dialogs::halftone::open(app), + crate::dialogs::rearrange_artboards::CMD => crate::dialogs::rearrange_artboards::open(app), + crate::dialogs::rename_artboards::CMD => crate::dialogs::rename_artboards::open(app), + crate::dialogs::smart_punctuation::CMD => crate::dialogs::smart_punctuation::open(app), _ => return None, }) } @@ -139,7 +108,7 @@ pub fn invoke_from_system_menu(app: &mut VectorcraftApp, ctx: &egui::Context, id // in a frame whose keys are not this window's. app.drop_unwritten_formats(); } - None if id == "select.all" && crate::panels::artboards::selects_all(app, ctx) => crate::panels::artboards::select_all(app), + None if id == "select.all" && crate::panels::artboards::selects_all(app) => crate::panels::artboards::select_all(app), None => invoke(app, id, p), } } @@ -188,9 +157,11 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { } // Params first: some dialogs' fields take a look through the session (Move's last move). if p.as_object().is_none_or(|o| o.is_empty()) - && let Some((kind, fields)) = menu_dialog(app, id) + && let Some(opened) = open_menu_dialog(app, id) { - app.ui.dialog = Some(crate::state::Dialog::new(kind, fields)); + if let Err(e) = opened { + app.status(e); + } return; } // A plug-in command with parameters asks for them, from its menu item or its shortcut. @@ -371,7 +342,7 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { if id == "view.rotate" && p.as_object().is_none_or(|o| o.is_empty()) { match app.view_mut().map(|v| v.rotation) { Some(angle) => { - app.ui.dialog = Some(crate::state::Dialog::new("command", json!({"__command": id, "__label": "Rotate View", "angle": angle}))); + let _ = app.run("ui.paramDialog", json!({"command": id, "label": "Rotate View", "params": {"angle": angle}})); } None => app.status("no document"), } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 8c2767e20b..ea7592b358 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1,5 +1,5 @@ use super::bar::home_key; -use super::invoke::menu_dialog; +use super::invoke::open_menu_dialog; use super::slots::{recent_readable, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::state::{checked, selected_image}; use super::ui_commands::UI_COMMANDS; @@ -1057,7 +1057,7 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::smooth_slider::auto(app), "ui.recolorUndo" => crate::dialogs::recolor::step(app, true), "ui.recolorRedo" => crate::dialogs::recolor::step(app, false), - "ui.dialogReset" => crate::dialogs::reset(app), + "ui.dialogReset" => crate::dialogs::host::reset_top(app), "attributes.openUrl" => crate::panels::attributes::open_url(app, p), "ui.javascriptFilesDialog" => crate::panels::svg_interactivity::files_dialog(app, p), "ui.svgFilterDialog" => crate::dialogs::svg_filter::open(app, p), @@ -1069,13 +1069,9 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::envelope::open(app, c), - c => match c.and_then(|c| menu_dialog(app, c)) { - Some((kind, fields)) => { - app.ui.dialog = Some(crate::state::Dialog::new(kind, fields)); - Ok(Value::Null) - } - None => Err("`command` must be a command whose menu item opens a dialog (see ui.menuDialog)".into()), - }, + c => c + .and_then(|c| open_menu_dialog(app, c)) + .unwrap_or_else(|| Err("`command` must be a command whose menu item opens a dialog (see ui.menuDialog)".into())), } } "ui.widthPointEdit" => crate::dialogs::width_point::open(app, p), @@ -1089,7 +1085,7 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::color::rgb_percent_command(app, p), "ui.colorWheel" => crate::panels::color_wheel::command(app, p), "ui.savePdfDialog" => crate::dialogs::open_save_pdf(app, p), - crate::dialogs::SAVE_PDF_SUMMARY => crate::dialogs::save_pdf_summary(app, p), + "file.exportAs" if s("path").is_none() => { crate::dialogs::open_export_as(app, s("format").as_deref(), p); Ok(Value::Null) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 3fc578d754..c8a64684f9 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -90,7 +90,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "window.floatTools" => { let tool = p.get("tool").and_then(Value::as_str).unwrap_or(""); let toolbar = p.get("toolbar").and_then(Value::as_str); - crate::toolbar::strips(&app.ui, toolbar).iter().any(|f| f.tools.iter().any(|id| id == tool)) + crate::toolbar::strips(app, toolbar).iter().any(|strip| strip.contains(&tool)) } "window.taskBar" => app.ui.task_bar, "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, @@ -308,12 +308,9 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "file.export.pdf" | "ui.savePdfDialog" | "ui.fileInfoDialog" | "ui.rasterEffectsSettingsDialog" | "ui.svgFilterDialog" => { app.session.active().is_some() } - crate::dialogs::SAVE_PDF_SUMMARY => crate::dialogs::pdf_summary_open(app), - "ui.importSvgFilter" => { - app.session.active().is_some() && crate::picks::can(app, &crate::picks::PickRequest::Open(crate::dialogs::svg_filter::pick())) - } + "ui.importSvgFilter" => app.session.active().is_some(), "ui.missingFontsDialog" => !cfg!(target_arch = "wasm32") && app.session.active().is_some(), - "ui.findFontsInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), + "ui.findFontsInFolder" => app.session.active().is_some(), "ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" | "ui.colorGroupOptions" => app.session.active().is_some(), "ui.graphicStyleOptions" | "ui.charStyleOptions" | "ui.paraStyleOptions" | "ui.newCharStyle" | "ui.newParaStyle" => { app.session.active().is_some() @@ -355,13 +352,13 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.smoothAuto" => crate::dialogs::smooth_slider::showing(app), "ui.recolorUndo" => crate::dialogs::recolor::can_step(app, true), "ui.recolorRedo" => crate::dialogs::recolor::can_step(app, false), - "ui.dialogReset" => crate::dialogs::can_reset(app), + "ui.dialogReset" => crate::dialogs::host::can_reset_top(app), "ui.dxfOptionsDialog" => app.session.active().is_some(), "links.editOriginal" | "links.reveal" => selected_image(app, |im| im.link.is_some()) || selected_placed(app), "ui.placementOptionsDialog" => selected_image(app, |_| true) || selected_placed(app), "links.copyInfo" => !crate::panels::links::selected_rows_of_app(app).is_empty(), "ui.relinkDialog" => app.services.pick_open.is_some() && (selected_image(app, |_| true) || selected_placed(app)), - "ui.findLinksInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(), + "ui.findLinksInFolder" => app.session.active().is_some(), "ui.packageDialog" | "docInfo.save" => app.session.active().is_some(), "ui.batchDialog" => !app.ui.action_sets.is_empty() && app.ui.action_sets.iter().any(|s| !s.actions.is_empty()), "ui.epsOptionsDialog" | "ui.hpglOptionsDialog" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4602e12072..55de601e3d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1344,12 +1344,6 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{selected?: preset name} open the presets manager (dialog `flattenerPresets`, fields `selected`, then the selected preset's `name` and option keys: setting them on a saved preset saves it, a new `name` renames it; built-in presets don't change). New, Delete, Import… and Export… run flattener.presets.save / delete / import / export", ), - ( - "ui.imageTracePresetDialog", - "Save as New Preset…", - "", - "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", - ), ( "ui.tracingPresetsDialog", "Tracing Presets…", @@ -1557,7 +1551,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.dialogReset", "Reset", "", - "{} the open dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, dialog `flareOptions`; Save PDF, dialog `savePdf`): its fields go back to their defaults (Save PDF: the chosen preset's settings, with the path and artboards kept) and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open, the open one has no Reset, or Save PDF's chosen preset was deleted (the fields stay as they are)", + "{} the top dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, Save PDF): its fields go back to their defaults (Save PDF: the chosen preset's settings, with the path and artboards kept) and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open, the top one has no Reset, or Save PDF's chosen preset was deleted (the fields stay as they are)", ), ( "ui.justification", diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 6c4d7860e7..2e331019b5 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1,7 +1,7 @@ //! Panels. Each panel reads engine state and acts only through `app.run(...)` (slider drags //! preview through the session's interaction so one drag is one undo step). //! -//! Every icon panel has a body (`show_icon_panel`) and a panel (≡) menu (`panel_menu`). +//! Every icon panel has a body (`show_icon_panel`); its panel (≡) menu rows come from `panel_rows`. pub mod actions; pub mod align; @@ -64,7 +64,10 @@ use vectorcraft_engine::inspect::StrokeMixed; use vectorcraft_geom::shapes::CornerKind; use crate::theme::Tokens; -use crate::widgets::{Live, dim_label}; +use craft_ui::menu::PanelRow; +use craft_ui::runtime::commands::CommandStates; + +use crate::widgets::dim_label; use crate::{VectorcraftApp, icons}; /// The first selected node, as the `Arc` the document holds, if any. It does not change with later @@ -221,6 +224,21 @@ pub(crate) fn selection_len(app: &VectorcraftApp) -> usize { app.session.active().map(|d| d.selection.len()).unwrap_or(0) } +/// Whether the panel part `key` is hidden by its panel's menu. +// PLAN: assumed `UiState::hidden_parts` is a set of part keys (op.A3) +pub(crate) fn part_hidden(app: &VectorcraftApp, key: &str) -> bool { + app.ui.hidden_parts.contains(key) +} + +/// Hides or shows the panel part `key`. +pub(crate) fn set_part_hidden(app: &mut VectorcraftApp, key: &'static str, on: bool) { + if on { + app.ui.hidden_parts.insert(key.to_string()); + } else { + app.ui.hidden_parts.remove(key); + } +} + pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { match id { "swatches" => swatches::show(app, ui), @@ -284,58 +302,88 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { } } -/// Items of a panel's (≡) menu. Unimplemented Illustrator items are listed disabled. False for a -/// panel without items of its own. -pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool { - match id { - "swatches" => swatches::menu(app, ui), - "color" => color::menu(app, ui), - "colorGuide" => color_guide::menu(app, ui), - "stroke" => stroke::menu(app, ui), - "transparency" => transparency::menu(app, ui), - "appearance" => appearance::menu(app, ui), - "graphicStyles" => graphic_styles::menu(app, ui), - "align" => align::menu(app, ui), - "pathfinder" => pathfinder::menu(app, ui), - "transform" => transform::menu(app, ui), - "history" => history::menu(app, ui), - "info" => info::menu(app, ui), - "separations" => separations::menu(app, ui), - "artboards" => artboards::menu(app, ui), - "gradient" => gradient::menu(app, ui), - "character" => character::menu(app, ui), - "paragraph" => paragraph::menu(app, ui), - "glyphs" => glyphs::menu(app, ui), - "navigator" => navigator::menu(app, ui), - "brushes" => brushes::menu(app, ui), - "symbols" => symbols::menu(app, ui), - "patternOptions" => pattern_options::menu(app, ui), - "imageTrace" => image_trace::menu(app, ui), - "openType" => opentype::menu(app, ui), - "docInfo" => doc_info::menu(app, ui), - "charStyles" => text_styles::menu(app, ui, text_styles::Kind::Char), - "paraStyles" => text_styles::menu(app, ui, text_styles::Kind::Para), - "magicWand" => magic_wand::menu(app, ui), - "tabs" => tabs::menu(app, ui), - "libraries" => libraries::menu(app, ui), - flattener_preview::ID => flattener_preview::menu(app, ui), - "attributes" => attributes::menu(app, ui), - svg_interactivity::ID => svg_interactivity::menu(app, ui), - "colorThemes" => color_themes::menu(app, ui), - color_wheel::ID => color_wheel::menu(app, ui), - "layers" => layers::menu(app, ui), - links::ID => links::menu(app, ui), - asset_export::ID => asset_export::menu(app, ui), - css_properties::ID => css_properties::menu(app, ui), - variables::ID => variables::menu(app, ui), - script_console::ID => script_console::menu(app, ui), - retype::ID => retype::menu(app, ui), - "actions" => actions::menu(app, ui), - crate::addons::packaging::ID => crate::addons::packaging::panel_menu(app, ui), - id if library_panel::parse(id).is_some() => library_panel::menu(app, ui, id), - _ => return false, +/// A panel's menu: its rows and the states of its commands, both from the panel's module. +struct PanelMenu { + id: &'static str, + rows: fn(&VectorcraftApp) -> Vec, + states: fn(&VectorcraftApp, &mut CommandStates), +} + +/// Lists a panel's menu from its module's `menu_rows` and `menu_states`. +// PLAN: `text_styles` is assumed to take its `Kind`; the two style panels go through closures. +macro_rules! menu { + ($id:expr, $module:ident) => { + PanelMenu { id: $id, rows: $module::menu_rows, states: $module::menu_states } + }; + ($id:expr, $module:ident, $kind:expr) => { + PanelMenu { id: $id, rows: |app| $module::menu_rows(app, $kind), states: |app, states| $module::menu_states(app, states, $kind) } + }; +} + +/// Every panel with a menu of its own. +static PANEL_MENUS: &[PanelMenu] = &[ + menu!("swatches", swatches), + menu!("color", color), + menu!("colorGuide", color_guide), + menu!("stroke", stroke), + menu!("transparency", transparency), + menu!("appearance", appearance), + menu!("graphicStyles", graphic_styles), + menu!("align", align), + menu!("pathfinder", pathfinder), + menu!("transform", transform), + menu!("history", history), + menu!("info", info), + menu!("separations", separations), + menu!("artboards", artboards), + menu!("gradient", gradient), + menu!("character", character), + menu!("paragraph", paragraph), + menu!("glyphs", glyphs), + menu!("navigator", navigator), + menu!("brushes", brushes), + menu!("symbols", symbols), + menu!("patternOptions", pattern_options), + menu!("imageTrace", image_trace), + menu!("openType", opentype), + menu!("docInfo", doc_info), + menu!("charStyles", text_styles, text_styles::Kind::Char), + menu!("paraStyles", text_styles, text_styles::Kind::Para), + menu!("magicWand", magic_wand), + menu!("tabs", tabs), + menu!("libraries", libraries), + menu!(flattener_preview::ID, flattener_preview), + menu!("attributes", attributes), + menu!(svg_interactivity::ID, svg_interactivity), + menu!("colorThemes", color_themes), + menu!(color_wheel::ID, color_wheel), + menu!("layers", layers), + menu!(links::ID, links), + menu!(asset_export::ID, asset_export), + menu!(css_properties::ID, css_properties), + menu!(variables::ID, variables), + menu!(script_console::ID, script_console), + menu!(retype::ID, retype), + menu!("actions", actions), + menu!(crate::addons::packaging::ID, packaging_menu), +]; + +use crate::addons::packaging as packaging_menu; + +/// The rows of panel `id`'s (≡) menu; none for a panel without a menu of its own. +pub(crate) fn panel_rows(app: &VectorcraftApp, id: &str) -> Vec { + if library_panel::parse(id).is_some() { + return library_panel::menu_rows(app, id); } - true + PANEL_MENUS.iter().find(|m| m.id == id).map_or_else(Vec::new, |m| (m.rows)(app)) +} + +/// Sets the states of every panel menu's commands, and of the Contextual Task Bar's. +pub(crate) fn panel_menu_states(app: &VectorcraftApp, states: &mut CommandStates) { + for menu in PANEL_MENUS { + (menu.states)(app, states); + } + crate::canvas::task_bar::menu_states(app, states); } /// The ≡ button drawn into `rect` that opens a panel menu. @@ -347,29 +395,6 @@ pub(crate) fn menu_button(ui: &mut Ui, id: &str, rect: Rect) -> egui::Response { resp.on_hover_text(tl!("Panel menu")) } -/// The ≡ panel-menu button drawn into `rect` (the right end of a panel's title/tab strip). -pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, rect: Rect) { - let resp = menu_button(ui, id, rect); - egui::Popup::menu(&resp).show(|ui| { - crate::widgets::menu_scroll(ui, |ui| { - crate::widgets::menu_min_width(ui, 220.0); - if panel_menu_items(app, ui, id) { - ui.separator(); - } - // The panel floats out of the dock or goes back in, as dragging its tab does. - let (label, cmd) = if crate::panel_docking::floats(&app.ui, id) { - (tl!("Dock Panel"), "window.panel.dock") - } else { - (tl!("Float Panel"), "window.panel.float") - }; - if crate::widgets::menu_item(ui, label, true, false) - && let Err(e) = app.run(cmd, json!({ "panel": id })) - { - app.ui.status = e; - } - }); - }); -} pub fn libraries(app: &mut VectorcraftApp, ui: &mut Ui) { libraries::show(app, ui); @@ -577,6 +602,17 @@ fn paint_popover(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Where a live control's gesture stands this pass. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Live { + /// No gesture this pass. + Idle, + /// The value is being dragged. + Dragging, + /// The drag ended this pass. + Released, +} + /// Run `cmd` live: while dragging, preview on top of an interaction snapshot; on release, commit /// it as one undo step. Falls back to a plain run when no document is open. pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: Value, phase: Live) { @@ -645,25 +681,6 @@ pub(crate) fn set_view(app: &mut VectorcraftApp, p: &Value) -> Result bool { - pstate::>(ctx, key).is_some_and(|pass| pass + 1 >= ctx.cumulative_pass_nr()) -} - -/// Take (`on`) or give up the keyboard for the rows of the panel whose state is `key`, for this -/// frame and the next ([`has_row_keys`]). -pub(crate) fn set_row_keys(ctx: &egui::Context, key: &str, on: bool) { - set_pstate(ctx, key, on.then(|| ctx.cumulative_pass_nr())); -} - -/// Whether a plain Delete or Backspace belongs to a panel's rows this frame, the Layers or the -/// Appearance panel's after a click on one of them, so [`crate::shortcuts::handle`] leaves it to the -/// panel instead of running Edit › Clear on the selected art. -pub(crate) fn rows_take_delete(ctx: &egui::Context) -> bool { - has_row_keys(ctx, layers::ROW_KEYS) || has_row_keys(ctx, appearance::ROW_KEYS) -} /// How near a scrolled list's top or bottom edge a drag scrolls it ([`scroll_at_edges`]). const DRAG_SCROLL_EDGE: f32 = 28.0;