hub-w2: net change of 2 commits

- hub-w2: written from its sheet
- hub-w2: repair 1
This commit is contained in:
bflatastic
2026-11-21 23:22:03 +07:00
parent d4d0d51d7c
commit bc85d94a08
8 changed files with 426 additions and 1244 deletions
+27 -137
View File
@@ -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<usize, St
usize::try_from(n.max(1)).map_err(|_| format!("`{key}` is out of range"))
}
/// The fields one `ui.dialog.set` stores, in order: `{field, value?}`, or `{fields: [{field, value?}…]}`.
/// Every item is checked before any is stored, so a refused item leaves the dialog as it was.
fn dialog_fields(p: &Value) -> Result<Vec<(String, Value)>, 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<Option<DialogAnswer>, 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::<Vec<_>>(),
// 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<Item = (String, &mut serde_json::
/// Takes out of the params of a recorded step running `command` the paths the request may not read:
/// the folder preferences' values [`leave_out_unreadable_pref_steps`] takes out, and what
/// [`leave_out_unreadable_params`] takes out, each in one pass over the params.
fn leave_out_unreadable_step(command: &str, params: &mut serde_json::Map<String, Value>) {
pub(crate) fn leave_out_unreadable_step(command: &str, params: &mut serde_json::Map<String, Value>) {
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<String, Value>) {
/// 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<String, Value>) {
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<Str
{
leave_out_unreadable_folders(fields);
}
// The menu item picked in an open Insert Menu Item dialog, such as a saved proof setup's file.
if let Some(Value::Object(dialog)) = ui.get_mut("dialog")
&& dialog.get("kind").and_then(Value::as_str) == Some(crate::dialogs::action_insert_menu_item::KIND)
&& let Some(Value::Object(fields)) = dialog.get_mut("fields")
{
let command = fields.get("command").and_then(Value::as_str).unwrap_or_default().to_string();
if let Some(Value::Object(params)) = fields.get_mut("params") {
leave_out_unreadable_step(&command, params);
}
}
if let Some(Value::Object(dialog)) = ui.get_mut("dialog")
&& dialog.get("kind").and_then(Value::as_str) == Some(crate::dialogs::javascript_files::KIND)
&& let Some(Value::Object(fields)) = dialog.get_mut("fields")
&& let Some(Value::String(selected)) = fields.get_mut("selected")
&& let Some(st) = app.session.active()
{
*selected = vectorcraft_engine::cmd::links::shown_script(st, selected).into_owned();
}
}
/// Takes out of `prefs` the folder preferences
@@ -1296,7 +1228,6 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques
let outcome = match ran {
Ok(outcome) => 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, &params, &WindowHost, ViewportId) -> Result<Value, String>`
// and `WindowHost::of(ctx)` in craft_automation (widgets-02)
let host = craft_automation::WindowHost::of(ctx);
wrap(craft_automation::dialogs::dialog_method(&req.method, &params, &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)?))) {
File diff suppressed because it is too large Load Diff
+226
View File
@@ -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<WindowDialogs> {
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<DialogId>,
/// Runs when the dialog is cancelled (a live preview's rollback).
pub cancel: Option<Box<dyn FnOnce(&mut VectorcraftApp)>>,
}
/// Runs one held dialog's pass; `Some(cancelled)` once the dialog is gone.
type Drain = Box<dyn FnMut(&mut VectorcraftApp) -> Option<bool>>;
struct Record {
drain: Drain,
cancel: Option<Box<dyn FnOnce(&mut VectorcraftApp)>>,
}
/// The held dialogs of the app: one record each, served by [`pump`].
#[derive(Default)]
pub(crate) struct Held(Vec<Record>);
fn drain<D: HoldsOk>(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::<D>(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::<D>(id) {
d.answer_ok(verdict);
}
});
}
host.with(|h| h.take_by_id::<D>(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<D: HoldsOk>(
app: &mut VectorcraftApp,
dialog: D,
ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static,
) -> Option<DialogId> {
open_held_with(app, dialog, ok, HeldOptions::default())
}
/// [`open_held`] with a parent and a cancel hook.
pub(crate) fn open_held_with<D: HoldsOk>(
app: &mut VectorcraftApp,
dialog: D,
ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static,
options: HeldOptions,
) -> Option<DialogId> {
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::<D>(id, ok), cancel: options.cancel });
Some(id)
}
/// The dialog on top of the stack.
fn top_dialog(app: &VectorcraftApp) -> Option<DialogId> {
// `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<Value, String> {
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;
}
+22 -51
View File
@@ -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<Value, String>`.
pub(super) fn open_menu_dialog(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, String>> {
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"),
}
+6 -10
View File
@@ -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<Result
"ui.smoothAuto" => 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<Result
crate::canvas::apply_requests(app, r);
match s("command").as_deref() {
Some(c) if crate::dialogs::envelope::opens(c) => 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<Result
"ui.colorRgbPercent" => 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)
+5 -8
View File
@@ -90,7 +90,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option<bool> {
"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(),
+1 -7
View File
@@ -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",
+112 -95
View File
@@ -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<PanelRow>,
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<PanelRow> {
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<Value, Str
Ok(json!({ "panel": panel, "view": view }))
}
/// Whether the panel whose state is `key` has the keyboard for its rows (Delete and Backspace
/// remove its highlighted rows): it took it with a click on a row ([`set_row_keys`]) and kept it in
/// every frame since, so it lapses when the panel isn't drawn.
pub(crate) fn has_row_keys(ctx: &egui::Context, key: &str) -> bool {
pstate::<Option<u64>>(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;