Merge pull request #9119 from dotCooCoo/feat/toolbar-command-buttons

Toolbars: a toolbar made with New Toolbar holds menu command buttons
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-28 00:45:29 -08:00
commit ed86cbf5ab
11 files changed
+669 -31

No files matched your search

+13 -1
View File
@@ -612,6 +612,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots",
),
(
"toolbar.addCommand",
"Toolbar: Add Command",
"",
"{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:<id>`, `effect:<id>` or `panel:<id>`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands",
),
(
"toolbar.removeCommand",
"Toolbar: Remove Command",
"",
"{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands",
),
(
"toolbar.reset",
"Toolbar: Reset",
@@ -670,7 +682,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.toolbar.list",
"List Toolbars",
"",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
),
("window.taskBar", "Contextual Task Bar", "", "{}"),
(
+203 -19
View File
@@ -8,9 +8,12 @@
//! The ••• button at a toolbar's foot opens the All Tools drawer beside it, and tools dragged from the
//! drawer fill it (`edit_toolbar`, with the `toolbar` param of its commands). The + button above it
//! opens Add Tool…, a menu of every tool where a click adds the tool at the end, and whose Remove Tool
//! items take tools out: VectorCraft's own way to fill a toolbar without a drag. Each toolbar is listed
//! under Window › Toolbars, where its item shows or hides it. Window › Toolbars › Manage Toolbars (also
//! in the drawer's menu) renames, copies and deletes them.
//! items take tools out: VectorCraft's own way to fill a toolbar without a drag. The same menu's Add
//! Command submenu searches the Command Palette's results and adds a command button after the tools,
//! which runs what the command's menu item runs (`toolbar.addCommand`, `toolbar.removeCommand`);
//! command buttons are VectorCraft's own. Each toolbar is listed under Window › Toolbars, where its
//! item shows or hides it. Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames,
//! copies and deletes them.
//!
//! Behavior from the public documentation:
//! <https://helpx.adobe.com/illustrator/using/tools.html> (Create and manage toolbars: New Toolbar
@@ -24,10 +27,10 @@ use std::collections::BTreeSet;
use craft::behavior::IconId;
use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target};
use craft::ui::buttons::IconButton;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::dialog::DialogResult;
use craft::ui::display::Divider;
use craft::ui::display::{Divider, Shade, Text};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::patterns::form_dialogs::{
DialogFields, FieldValue, HostedListManager, HostedParamDialog, ListManagerAction, ListManagerChoice, ListManagerEntry, ListManagerWords, Param,
@@ -35,6 +38,7 @@ use craft::ui::patterns::form_dialogs::{
};
use craft::ui::rails::RailFooter;
use craft::ui::runtime::commands::CommandRef;
use craft::ui::text::TextField;
use egui::pos2;
use serde_json::{Value, json};
use vectorcraft_tools::tool_info;
@@ -47,6 +51,8 @@ use crate::{VectorcraftApp, panel_docking};
pub(crate) const MAX: usize = 64;
/// The most characters a toolbar's name has.
const MAX_NAME: usize = 200;
/// The most command buttons a toolbar holds.
const MAX_COMMANDS: usize = 200;
/// Where the first toolbar made floats, right of the Tools panel; the next ones go lower.
const NEW_AT: [f32; 2] = [96.0, 120.0];
/// The kind every Manage Toolbars entry has: all of them rename in place.
@@ -179,6 +185,7 @@ fn blank(id: u32, name: String) -> CustomToolbar {
slot_tool: Default::default(),
double: false,
floating: Vec::new(),
commands: Vec::new(),
}
}
@@ -274,8 +281,10 @@ pub(crate) fn delete(app: &mut VectorcraftApp, name: &str) -> Result<(), String>
/// Keep named toolbars, each name once whatever its case and at most [`MAX_NAME`] characters, of
/// known tools, each once in its toolbar, each group's tool chosen last only when the group holds it,
/// and each with an id of its own: one saved without an id or repeating an earlier toolbar's gets
/// the lowest id nobody holds (a hand-edited preferences file or workspace).
/// at most [`MAX_COMMANDS`] command buttons, each command once and none for a tool, and each with an
/// id of its own: one saved without an id or repeating an earlier toolbar's gets the lowest id nobody
/// holds (a hand-edited preferences file or workspace). A command that is not known now stays: it may
/// be an uninstalled plug-in's.
pub(crate) fn sanitize(bars: &mut Vec<CustomToolbar>) {
let mut names = BTreeSet::new();
bars.retain_mut(|b| {
@@ -285,6 +294,9 @@ pub(crate) fn sanitize(bars: &mut Vec<CustomToolbar>) {
s.retain(|id| tool_info(id).is_some() && seen.insert(id.clone()));
}
b.slots.retain(|s| !s.is_empty());
let mut commands = BTreeSet::new();
b.commands.retain(|id| !id.trim().is_empty() && !id.starts_with("tool:") && commands.insert(id.clone()));
b.commands.truncate(MAX_COMMANDS);
let old = std::mem::take(&mut b.last_used);
for (first, slot) in b.slots.iter().filter_map(|s| Some((s.first()?, s))) {
let at = crate::toolbar::slot_id(first);
@@ -559,6 +571,41 @@ fn run_choice(app: &mut VectorcraftApp, choice: &ListManagerChoice) {
}
}
/// The toolbar the `toolbar` param of `toolbar.addCommand` and `toolbar.removeCommand` names,
/// which must be one made with New Toolbar: the Tools panel's toolbar holds tools only.
fn command_target(ui: &UiState, p: &Value) -> Result<usize, String> {
let name = target(ui, p)?.ok_or("toolbar (a toolbar's name) is required: only toolbars made with New Toolbar hold commands")?;
index(ui, &name)
}
/// Put the command button for the Command Palette result `id` in `bar`, moving it if it is there
/// already: at place `at` among its command buttons (0 = the first; none: at the end). A command
/// that is gone (an uninstalled plug-in's) can still move, but not be added. A tool, and a UI
/// command that fails without params, can't be added.
pub(crate) fn add_command(bar: &mut CustomToolbar, id: &str, at: Option<usize>) -> Result<(), String> {
if id.starts_with("tool:") {
return Err(format!("`{id}` is a tool: toolbar.addTool adds tools"));
}
if crate::shortcut_editor::ui_command_needs_params(id) {
return Err(format!("`{id}` needs params, which a click on a button does not give"));
}
if !bar.commands.iter().any(|c| c == id) && !crate::palette::is_command(id) {
return Err(format!("unknown command `{id}`"));
}
let mut list: Vec<String> = bar.commands.iter().filter(|c| *c != id).cloned().collect();
if list.len() >= MAX_COMMANDS {
return Err(format!("a toolbar holds at most {MAX_COMMANDS} commands"));
}
let at = match at {
None => list.len(),
Some(n) if n <= list.len() => n,
Some(n) => return Err(format!("`at` must be a whole number from 0 to {} (got {n})", list.len())),
};
list.insert(at, id.to_string());
bar.commands = list;
Ok(())
}
/// The commands of the toolbars made with New Toolbar; `None` for other ids.
pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
Some(match id {
@@ -591,6 +638,25 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?;
delete(app, name).map(|_| Value::Null)
})(),
"toolbar.addCommand" => (|| {
let k = command_target(&app.ui, p)?;
let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?;
let at = match p.get("at") {
None | Some(Value::Null) => None,
Some(v) => Some(
v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| format!("`at` must be 0 or a larger whole number (got {v})"))?,
),
};
let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?;
add_command(bar, id, at).map(|_| json!(bar.commands))
})(),
"toolbar.removeCommand" => (|| {
let k = command_target(&app.ui, p)?;
let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?;
let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?;
bar.commands.retain(|c| c != id);
Ok(json!(bar.commands))
})(),
"window.toolbar.dock" => dock(app, p),
"window.toolbar.float" => float(app, p),
"window.toolbar.list" => {
@@ -609,6 +675,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
"shown": panel_docking::visible(app, &panel),
"double": double,
"slots": b.slots,
"commands": b.commands,
"floating": docked.is_none(),
"side": side_name(last_edge(&app.ui, &panel)),
"order": docked.map(|(_, n)| *n),
@@ -651,19 +718,100 @@ pub(crate) fn shown_tool(bar: &CustomToolbar, active: &'static str, tools: &[&'s
Some(bar.last_used.get(crate::toolbar::slot_id(first)).and_then(|id| tools.iter().copied().find(|t| *t == id.as_str())).unwrap_or(first))
}
/// Add Tool…, in the footer of the toolbar with id `id`: the + button opens a menu where, under Remove
/// Tool, a click takes one of the toolbar's tools out; then every tool under the All Tools drawer's
/// headings, where a click adds one at the end (dimmed: in the toolbar already). `measured`: the rail
/// measures its footer, which draws the button alone.
pub(crate) fn add_menu(app: &VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer: RailFooter, measured: bool) {
let Some(bar) = app.ui.custom_toolbars.iter().find(|b| b.id == id) else { return };
let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect();
let plus = IconButton::new(IconId::new("plus")).label(tl!("Add Tool…")).popup(PopupKind::Menu).show(ui).response;
// The rail measures its footer too: the menu opens from the button the rail shows.
if measured || craft::ui::runtime::measure::active(ui.ctx()) {
/// What a command button shows, worked out before its toolbar's footer is drawn.
#[derive(Clone, Debug)]
struct CommandLook {
/// The Command Palette result it runs.
id: String,
/// Its label, name and command; none while the palette lists no result with its id (an
/// uninstalled plug-in's command).
text: Option<crate::palette::ButtonText>,
}
impl CommandLook {
/// The label the button shows: the command's, or its id while the command is gone.
fn label(&self) -> &str {
self.text.as_ref().map_or(self.id.as_str(), |t| t.label.as_str())
}
/// Its full name, with the menu path that tells it apart from a command of the same label, or
/// its id while the command is gone.
fn name(&self) -> &str {
self.text.as_ref().map_or(self.id.as_str(), |t| t.name.as_str())
}
}
/// How each command button of the toolbar with id `id` looks now.
fn command_looks(app: &mut VectorcraftApp, ui: &egui::Ui, id: u32) -> Vec<CommandLook> {
let commands = app.ui.custom_toolbars.iter().find(|b| b.id == id).map(|b| b.commands.clone()).unwrap_or_default();
let texts = crate::palette::button_texts(app, ui, &commands);
commands.into_iter().zip(texts).map(|(id, text)| CommandLook { id, text }).collect()
}
/// A command button on the toolbar named `bar`: the command's label, cut short with … when it is
/// longer than the toolbar is wide, and its full name and shortcut in its tooltip. A click runs what a
/// pick of the command in the Command Palette runs, and while the command's menu item is dimmed the
/// button is dimmed too. A command that is gone shows its id, dimmed. Its context menu moves it up or
/// down among the toolbar's command buttons (`place`: its place and how many there are) and takes it
/// out; `measuring`: the rail measures its footer, which draws the button alone.
fn command_button(app: &VectorcraftApp, ui: &mut egui::Ui, bar: &str, look: &CommandLook, place: (usize, usize), measuring: bool) {
let shortcut = crate::menus::shortcut_of(app, &look.id).map(|c| c.display(crate::keymap::platform()));
let tip = match (&look.text, shortcut) {
(None, _) => format!("{}\n{}", look.id, crate::i18n::msg(&format!("command `{}` is not available right now", look.id))),
(Some(t), Some(keys)) => format!("{} {keys}", t.name),
(Some(t), None) => t.name.clone(),
};
let button = match &look.text {
Some(t) => Button::command(t.command.clone()).label(look.label().to_string()),
None => Button::new(look.label().to_string()).enabled(false),
};
let response = button.tooltip(tip).show(ui).response;
if measuring {
return;
}
let command = |verb: &str, tool: &str| CommandRef::with_params(verb, json!({ "tool": tool, "toolbar": bar.name }));
let (i, n) = place;
let moved = |at: usize| CommandRef::with_params("toolbar.addCommand", json!({ "command": look.id, "toolbar": bar, "at": at }));
let removed = CommandRef::with_params("toolbar.removeCommand", json!({ "command": look.id, "toolbar": bar }));
Menu::context(look.name().to_string(), &response).show(ui, |ui, _| {
MenuItem::command(moved(i.saturating_sub(1))).label(tl!("Move Up")).enabled(i > 0).show(ui);
MenuItem::command(moved(i + 1)).label(tl!("Move Down")).enabled(i + 1 < n).show(ui);
MenuItem::command(removed.clone()).label(tl!("Remove from Toolbar")).show(ui);
});
}
/// The most commands the Add Command submenu lists for a search.
const COMMAND_RESULTS: usize = 30;
/// Where the Add Command submenu of the toolbar with id `id` keeps the text of its search field.
pub(crate) fn command_query_id(id: u32) -> egui::Id {
egui::Id::unique(("custom-toolbar-command-query", id))
}
/// Add Tool…, in the footer of the toolbar with id `id`, after the toolbar's command buttons
/// ([`command_button`]): the + button opens a menu where, under Remove Tool, a click takes one of the
/// toolbar's tools out; then every tool under the All Tools drawer's headings, where a click adds one
/// at the end (dimmed: in the toolbar already); then, under Remove Command, the toolbar's command
/// buttons by their full names, which a click takes out, and the Add Command submenu: a search field
/// over the Command Palette's results other than tools, whose first [`COMMAND_RESULTS`] matches a
/// click adds at the end (dimmed: on the toolbar already). `measured`: the rail measures its footer,
/// which draws the buttons alone.
pub(crate) fn add_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer: RailFooter, measured: bool) {
let Some(bar) = app.ui.custom_toolbars.iter().find(|b| b.id == id) else { return };
let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect();
let name = bar.name.clone();
let measuring = measured || craft::ui::runtime::measure::active(ui.ctx());
let looks = command_looks(app, ui, id);
for (i, look) in looks.iter().enumerate() {
command_button(app, ui, &name, look, (i, looks.len()), measuring);
}
let plus = IconButton::new(IconId::new("plus")).label(tl!("Add Tool…")).popup(PopupKind::Menu).show(ui).response;
// The rail measures its footer too: the menu opens from the button the rail shows.
if measuring {
return;
}
let command = |verb: &str, tool: &str| CommandRef::with_params(verb, json!({ "tool": tool, "toolbar": name }));
let query_id = command_query_id(id);
let mut query: String = ui.data(|d| d.get_temp(query_id)).unwrap_or_default();
Menu::new(tl!("Add Tool…")).opened_by(&plus, Trigger::Click).show(ui, |ui, _| {
if !held.is_empty() {
MenuItem::heading(crate::i18n::colon(tl!("Remove Tool"))).show(ui);
@@ -678,7 +826,35 @@ pub(crate) fn add_menu(app: &VectorcraftApp, ui: &mut egui::Ui, id: u32, _footer
MenuItem::command(command("toolbar.addTool", tool.id)).label(tool.label).enabled(!held.contains(&tool.id)).show(ui);
}
}
Divider::horizontal().show(ui);
if !looks.is_empty() {
MenuItem::heading(crate::i18n::colon(tl!("Remove Command"))).show(ui);
for look in &looks {
let removed = CommandRef::with_params("toolbar.removeCommand", json!({ "command": look.id, "toolbar": name }));
MenuItem::command(removed).label(look.name().to_string()).show(ui);
}
Divider::horizontal().show(ui);
}
Menu::submenu_row(ui, tl!("Add Command"), |ui, cx| {
// The field drives the submenu: Up and Down move its active row and Enter runs it, while
// typing stays in the field.
TextField::search(tl!("Search Commands"), Bind::bound(&mut query)).placeholder(tl!("Search Commands")).drives(cx.resolved.id).show(ui);
if query.trim().is_empty() {
Text::new(tl!("Type to find a command")).shade(Shade::Muted).show(ui);
return;
}
let found = crate::palette::command_matches(app, ui, &query, COMMAND_RESULTS);
if found.is_empty() {
Text::new(tl!("No matching commands")).shade(Shade::Muted).show(ui);
}
for (command, shown) in found {
let on = !looks.iter().any(|l| l.id == command);
let added = CommandRef::with_params("toolbar.addCommand", json!({ "command": command, "toolbar": name }));
MenuItem::command(added).label(shown).enabled(on).show(ui);
}
});
});
ui.data_mut(|d| d.insert_temp(query_id, query));
}
#[cfg(test)]
@@ -832,7 +1008,7 @@ mod tests {
let names: Vec<String> = toolbars_menu(&app).into_iter().filter(|(_, id, _)| *id == "window.toolbar.custom").map(|(l, ..)| l).collect();
assert_eq!(names, ["Mine", "Toolbar 1"]);
let list = app.run("window.toolbar.list", json!({})).unwrap();
let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "floating": true, "side": "left", "order": null});
let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "commands": [], "floating": true, "side": "left", "order": null});
assert_eq!(list, json!([blank("Mine"), blank("Toolbar 1")]));
}
@@ -876,7 +1052,10 @@ mod tests {
assert!(app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Nope"})).is_err());
let r = app.run("toolbar.removeTool", json!({"tool": "artboard", "toolbar": "Mine"})).unwrap();
assert_eq!(r, json!([["pen", "curvature"]]));
// Its command buttons go with it.
app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
let mine = find(&app.ui, "Mine").cloned().unwrap();
assert_eq!(mine.commands, ["object.group"]);
// Another workspace has its own toolbars (none); coming back brings Mine back.
app.run("window.workspace", json!({"name": "Essentials"})).unwrap();
assert!(app.ui.custom_toolbars.is_empty());
@@ -1148,7 +1327,12 @@ mod tests {
bars[0].last_used.set(slot("rectangle"), "pen".into());
bars[4].last_used.set(slot("pen"), "curvature".into());
bars[5].last_used.set(slot("pen"), "curvature".into());
// Command buttons: each once, none for a tool or a blank id; one not known now stays.
bars[4].commands = ["object.group", "tool:pen", " ", "object.group", "plugin:gone"].map(String::from).to_vec();
bars[5].commands = (0..MAX_COMMANDS + 5).map(|i| format!("plugin:p{i}")).collect();
sanitize(&mut bars);
assert_eq!(bars[1].commands, ["object.group", "plugin:gone"]);
assert_eq!(bars[2].commands.len(), MAX_COMMANDS);
assert_eq!(bars.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["A", "B", "C"], "a name past {MAX_NAME} characters goes too");
assert_eq!(bars.iter().map(|b| b.id).collect::<Vec<_>>(), [1, 3, 2], "the first has none, the third repeats the second's");
assert_eq!(bars[0].last_used.get(slot("pen")), Some(&"curvature".to_string()));
+5 -1
View File
@@ -297,7 +297,11 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
})(),
"toolbar.reset" => (|| {
if let Some(name) = crate::custom_toolbars::target(&app.ui, p)? {
// A toolbar made with New Toolbar goes back to blank, as it was made.
// A toolbar made with New Toolbar goes back to blank, as it was made, without its
// command buttons too.
if let Some(bar) = crate::custom_toolbars::find_mut(&mut app.ui, &name) {
bar.commands.clear();
}
return edit_custom(app, &name, |cats| {
cats.clear();
Ok(())
+251 -2
View File
@@ -3,8 +3,8 @@ use vectorcraft_engine::Session;
use super::*;
/// Tall enough for the whole Basic toolbar and the whole drawer.
const SCREEN: egui::Vec2 = vec2(1000.0, 4000.0);
/// Tall enough for the whole Basic toolbar, the whole drawer and the whole Add Tool… menu.
const SCREEN: egui::Vec2 = vec2(1000.0, 5000.0);
/// The rail's Edit Toolbar button, by its access name.
const EDIT: &str = "Edit Toolbar"; // PLAN: assumed `RailWords::edit_toolbar` in English
/// The + button of a toolbar made with New Toolbar.
@@ -566,3 +566,252 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
assert!(slot_of(&app, tool).is_some(), "{tool}");
}
}
/// The command buttons of the toolbar made with New Toolbar called Mine.
fn mine_commands(app: &VectorcraftApp) -> Vec<String> {
crate::custom_toolbars::find(&app.ui, "Mine").unwrap().commands.clone()
}
/// `f` run with `app` and a `Ui` of one frame of `ctx` as the hosts run it ([`crate::testing::part_frame`]).
fn in_pass<T>(app: &mut VectorcraftApp, ctx: &egui::Context, f: impl FnOnce(&mut VectorcraftApp, &egui::Ui) -> T) -> T {
let mut f = Some(f);
let mut got = None;
let _ = crate::testing::part_frame(app, ctx, RawInput::default(), |app, ui| {
if let Some(f) = f.take() {
got = Some(f(app, ui));
}
});
got.expect("the frame ran")
}
/// `toolbar.addCommand` puts command buttons on a toolbar made with New Toolbar and moves them,
/// `toolbar.removeCommand` takes them off, and a bad call changes nothing. Manage Toolbars' copy
/// keeps them, and `toolbar.reset` takes them off with the tools.
#[test]
fn command_buttons_are_added_moved_and_removed_by_their_commands() {
let mut app = app();
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
let added = app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
assert_eq!(added, json!(["object.group"]));
app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine"})).unwrap();
app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine", "at": 0})).unwrap();
assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "moved, not added twice");
for (p, why) in [
(json!({"command": "no.such", "toolbar": "Mine"}), "an unknown command"),
(json!({"command": "tool:pen", "toolbar": "Mine"}), "a tool"),
(json!({"command": "object.group", "toolbar": "Mine", "at": 2}), "a place past the end"),
(json!({"command": "object.group", "toolbar": "Mine", "at": -1}), "a negative place"),
(json!({"command": "toolbar.addTool", "toolbar": "Mine"}), "a command that needs params"),
(json!({"command": "object.group"}), "no toolbar"),
(json!({"toolbar": "Mine"}), "no command"),
] {
assert!(app.run("toolbar.addCommand", p.clone()).is_err(), "{why}: {p}");
assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "{why} changes nothing");
}
assert!(app.run("toolbar.removeCommand", json!({"command": "object.group"})).is_err(), "no toolbar");
let list = app.run("window.toolbar.list", json!({})).unwrap();
assert_eq!(list[0]["commands"], json!(["object.path.cleanUp", "object.group"]));
let copy = app.run("window.toolbar.duplicate", json!({"name": "Mine"})).unwrap();
let copy = copy["toolbar"].as_str().unwrap().to_string();
assert_eq!(crate::custom_toolbars::find(&app.ui, &copy).unwrap().commands, mine_commands(&app), "the copy has them");
let left = app.run("toolbar.removeCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
assert_eq!(left, json!(["object.path.cleanUp"]));
app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap();
app.run("toolbar.reset", json!({"toolbar": "Mine"})).unwrap();
assert!(mine_commands(&app).is_empty(), "Reset makes the toolbar blank");
assert_eq!(crate::custom_toolbars::find(&app.ui, &copy).unwrap().commands.len(), 2, "the copy keeps its own");
}
/// What a frame drew inside the toolbar called Mine, by access name: (name, bounds, dimmed).
fn on_mine(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64) -> Vec<(String, Rect, bool)> {
frame(app, ctx, time, vec![]);
let input = RawInput { time: Some(time + 0.05), screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SCREEN)), ..Default::default() };
let out = crate::testing::app_frame(app, ctx, input);
let nodes: Vec<(String, Rect, bool)> = out
.platform_output
.accesskit_update
.map(|u| u.nodes)
.unwrap_or_default()
.into_iter()
.filter_map(|(_, n)| {
let b = n.bounds()?;
let rect = Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32));
Some((n.label()?.to_string(), rect, n.is_disabled()))
})
.collect();
let bar = nodes.iter().filter(|(n, ..)| n == "Mine").map(|(_, r, _)| *r).max_by(|a, b| a.area().total_cmp(&b.area()));
let Some(bar) = bar else { return vec![] };
nodes.into_iter().filter(|(n, r, _)| n != "Mine" && bar.contains(r.center())).collect()
}
/// The button inside the toolbar called Mine whose name is `name`: its bounds and whether it is dimmed.
fn mine_button(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, name: &str) -> Option<(Rect, bool)> {
on_mine(app, ctx, time).into_iter().find(|(n, ..)| n.trim() == name).map(|(_, r, off)| (r, off))
}
/// A command button shows its command's label, without the ellipsis, and a click runs what the
/// command's menu item runs. While that item would be dimmed, the button is dimmed too and a click
/// runs nothing.
#[test]
fn a_command_button_runs_its_command_and_is_dimmed_while_it_cannot() {
let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default());
let ctx = ctx();
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
for c in ["object.group", "object.path.cleanUp"] {
app.run("toolbar.addCommand", json!({"command": c, "toolbar": "Mine"})).unwrap();
}
let undo = |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.history.undo.len());
app.run("select.set", json!({"ids": []})).unwrap();
let (at, off) = mine_button(&mut app, &ctx, 0.0, "Group").expect("the button shows Group");
assert!(off, "dimmed with nothing selected");
let before = undo(&app);
click(&mut app, &ctx, 1.0, at.center());
assert_eq!(undo(&app), before, "a dimmed button runs nothing");
app.run("select.all", json!({})).unwrap();
let (at, off) = mine_button(&mut app, &ctx, 2.0, "Group").expect("the button shows Group");
assert!(!off, "not dimmed with objects selected");
click(&mut app, &ctx, 3.0, at.center());
assert!(undo(&app) > before, "Group ran");
assert!(mine_button(&mut app, &ctx, 4.0, "Clean Up").is_some(), "the button shows Clean Up");
assert!(mine_button(&mut app, &ctx, 4.5, "Clean Up…").is_none(), "without the ellipsis");
}
/// Command buttons are kept with the preferences, and a toolbar saved before toolbars held commands
/// loads with none. A command that is gone, such as an uninstalled plug-in's, stays: its button is
/// dimmed and shows its id, and Remove Command takes it off.
#[test]
fn a_missing_command_stays_dimmed_until_it_is_removed() {
let mut app = app();
let ctx = ctx();
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push("plugin:x".into());
let kept = app.ui.custom_toolbars.clone();
let prefs: crate::state::UiState = serde_json::from_slice(&serde_json::to_vec(&app.ui).unwrap()).unwrap();
assert_eq!(prefs.sanitized().custom_toolbars, kept, "kept with the preferences, the missing command too");
let mut old = serde_json::to_value(&kept[0]).unwrap();
old.as_object_mut().unwrap().remove("commands");
let old: crate::state::CustomToolbar = serde_json::from_value(old).unwrap();
assert!(old.commands.is_empty(), "an older toolbar loads without commands");
let (_, off) = mine_button(&mut app, &ctx, 0.0, "plugin:x").expect("the button shows the command's id");
assert!(off, "dimmed while it is gone");
let left = app.run("toolbar.removeCommand", json!({"command": "plugin:x", "toolbar": "Mine"})).unwrap();
assert_eq!(left, json!(["object.group"]));
}
/// The footer looks up all its command buttons in one call: each id gets what a lookup of it alone
/// gives, in order, and none for a tool, a command that needs params or a command that is gone.
#[test]
fn command_buttons_are_looked_up_together() {
let mut app = app();
let ctx = ctx();
let ids: Vec<String> =
["object.group", "tool:pen", "plugin:x", "toolbar.addTool", "object.path.cleanUp"].into_iter().map(str::to_string).collect();
let together = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_texts(app, ui, &ids));
let alone: Vec<_> = ids
.iter()
.map(|id| crate::palette::is_command(id).then(|| in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, id))).flatten())
.collect();
assert_eq!(together, alone);
assert!(together[0].is_some() && together[4].is_some(), "Group and Clean Up are found: {together:?}");
assert!(together[1..4].iter().all(Option::is_none), "a tool, a missing command and one that needs params: {together:?}");
assert!(in_pass(&mut app, &ctx, |app, ui| crate::palette::button_texts(app, ui, &[])).is_empty());
}
/// Add Tool…'s menu lists a toolbar's command buttons under Remove Command, where a click takes one
/// off, and its Add Command submenu searches the Command Palette's results other than tools: a click
/// on a match adds its button at the end of the toolbar.
#[test]
fn the_add_tool_menu_adds_and_removes_commands() {
let mut app = app();
let ctx = ctx();
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap();
let id = crate::custom_toolbars::find(&app.ui, "Mine").unwrap().id;
// The menu's items called `name`, top first: inside the menu, the Add Tool… node larger than the + button.
let items = |nodes: &Nodes, name: &str| -> Vec<Rect> {
let menu = named(nodes, ADD).into_iter().max_by(|a, b| a.area().total_cmp(&b.area())).expect("the menu is open");
named(nodes, name).into_iter().filter(|r| menu.contains(r.center())).collect()
};
let open = |app: &mut VectorcraftApp, time: f64| -> Nodes {
let nodes = settle(app, &ctx, time);
if !named(&nodes, "Select:").is_empty() {
return nodes;
}
let plus = inside(&nodes, ADD, one(&nodes, "Mine"));
click(app, &ctx, time + 0.2, plus.center());
settle(app, &ctx, time + 0.5)
};
let nodes = open(&mut app, 0.0);
assert_eq!(named(&nodes, "Remove Command:").len(), 1, "a heading over the toolbar's commands");
// The submenu lists the matches of its search; a click on one adds it at the end.
ctx.data_mut(|d| d.insert_temp(crate::custom_toolbars::command_query_id(id), "clean up".to_string()));
let row = items(&nodes, "Add Command");
assert_eq!(row.len(), 1, "the Add Command row");
let nodes = click(&mut app, &ctx, 1.0, row[0].center());
let name = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, "object.path.cleanUp")).expect("Clean Up's result").name;
let at = named(&nodes, &name).first().copied().unwrap_or_else(|| panic!("{name} is listed"));
click(&mut app, &ctx, 2.0, at.center());
assert_eq!(mine_commands(&app), ["object.group", "object.path.cleanUp"], "added at the end");
let pen = in_pass(&mut app, &ctx, |app, ui| crate::palette::command_matches(app, ui, "pen", 30));
assert!(!pen.is_empty() && pen.iter().all(|(id, _)| !id.starts_with("tool:")), "tools are not listed among the commands: {pen:?}");
let twice = |name: &str| {
let parts: Vec<&str> = name.split(" › ").collect();
(1..=parts.len() / 2).any(|k| parts[..k] == parts[k..2 * k])
};
assert!(pen.iter().all(|(_, name)| !twice(name)), "a label that carries its menu path is not given it twice: {pen:?}");
let toolbar = in_pass(&mut app, &ctx, |app, ui| crate::palette::command_matches(app, ui, "toolbar add", 30));
assert!(toolbar.iter().all(|(id, _)| id != "toolbar.addTool" && id != "toolbar.addCommand"), "commands that need params: {toolbar:?}");
// Under Remove Command, Group is listed by its full name, and a click takes it off.
let name = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, "object.group")).expect("Group's result").name;
let nodes = open(&mut app, 10.0);
let group = items(&nodes, &name);
assert!(!group.is_empty(), "{name} under Remove Command");
click(&mut app, &ctx, 11.0, group[0].center());
assert_eq!(mine_commands(&app), ["object.path.cleanUp"]);
}
/// A button for a panel shows the panel, as the panel's Command Palette result does.
#[test]
fn a_panel_button_shows_its_panel() {
let mut app = app();
let ctx = ctx();
let panel = crate::state::all_panels()
.map(|(id, _)| id)
.find(|id| !crate::panel_docking::visible(&app, id) && crate::palette::is_command(&format!("panel:{id}")))
.expect("a hidden panel");
let id = format!("panel:{panel}");
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap();
let label = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, &id)).expect("the panel's result").label;
let (at, _) = mine_button(&mut app, &ctx, 0.0, &label).unwrap_or_else(|| panic!("the button shows {label}"));
click(&mut app, &ctx, 1.0, at.center());
assert!(crate::panel_docking::visible(&app, panel), "{panel} is shown");
}
/// A button for a plug-in's command that is not installed is dimmed and shows the command's id;
/// once the plug-in is installed it shows the plug-in's name and can run, and when the plug-in is
/// removed again it is dimmed again.
#[test]
fn a_plugin_command_button_works_again_when_the_plugin_returns() {
use vectorcraft_plugins::wat as tpl;
let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default());
let ctx = ctx();
// A name no other test gives a plug-in.
let filter = "test.UI.toolbar_command-probe";
let id = format!("plugin:{filter}");
app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push(id.clone());
app.run("select.all", json!({})).unwrap();
let gone = mine_button(&mut app, &ctx, 0.0, &id).map(|(_, off)| off);
let manifest = format!(r#"{{"id":"{filter}","name":"Toolbar Probe","version":"1","kind":"filter","params":{{}}}}"#);
vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
let back = mine_button(&mut app, &ctx, 1.0, "Toolbar Probe").map(|(_, off)| off);
let added = app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine", "at": 0}));
vectorcraft_plugins::registry::remove(filter);
let gone_again = mine_button(&mut app, &ctx, 2.0, &id).map(|(_, off)| off);
assert_eq!(gone, Some(true), "dimmed, with its id, while it is not installed");
assert_eq!(back, Some(false), "its name, and it can run, once it is installed");
assert!(added.is_ok(), "an installed plug-in's command can be added: {added:?}");
assert_eq!(gone_again, Some(true), "dimmed again once it is removed");
}
+13 -1
View File
@@ -613,6 +613,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots",
),
(
"toolbar.addCommand",
"Toolbar: Add Command",
"",
"{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:<id>`, `effect:<id>` or `panel:<id>`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands",
),
(
"toolbar.removeCommand",
"Toolbar: Remove Command",
"",
"{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands",
),
(
"toolbar.reset",
"Toolbar: Reset",
@@ -671,7 +683,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.toolbar.list",
"List Toolbars",
"",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)",
),
("window.taskBar", "Contextual Task Bar", "", "{}"),
(
+111 -1
View File
@@ -576,6 +576,8 @@ pub(crate) struct Built {
// PLAN: an `Arc`, not the `SearchIndex` the decision names: `SearchIndex` is not `Clone`, and re-homing a tool entry goes through `Arc::make_mut` on `Built`
index: Arc<SearchIndex>,
tool_homes: Vec<String>,
/// Where each result id is in `entries`.
by_id: Arc<HashMap<String, usize>>,
}
/// The entries in the UI language and their index, which `ui`'s words fold and expand.
@@ -584,7 +586,115 @@ fn build(app: &VectorcraftApp, ui: &egui::Ui) -> Built {
let env = Env::of(ui);
let view = env.view();
let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::<SearchWords>()));
Built { entries, index: Arc::new(index), tool_homes: tool_homes(app) }
let by_id = entries.iter().enumerate().filter_map(|(i, e)| Some((e.ids().first()?.clone(), i))).collect();
Built { entries, index: Arc::new(index), tool_homes: tool_homes(app), by_id: Arc::new(by_id) }
}
/// What a command button on a toolbar made with New Toolbar shows for the result `id`
/// ([`button_text`]).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ButtonText {
/// The result's label in the interface language, without the menu path in front of it and
/// without a closing ellipsis.
pub label: String,
/// The result's full name in the interface language: its menu path and its label.
pub name: String,
/// What a click runs: what a pick of the result in the palette runs.
pub command: CommandRef,
}
/// The label, name and command of the palette result `id` in the interface language, from the
/// entries built once per catalog generation; none when the palette lists no result with that id
/// now (an uninstalled plug-in's command).
#[cfg(test)]
pub(crate) fn button_text(app: &mut VectorcraftApp, ui: &egui::Ui, id: &str) -> Option<ButtonText> {
let built = kept_build(app, ui);
let e = built.by_id.get(id).and_then(|&i| built.entries.get(i))?;
Some(button_text_of(e))
}
/// The [`ButtonText`] of each result id in `ids`, in order, from one kept build: none for an id
/// that [`is_command`] does not allow or that the palette lists no longer (an uninstalled plug-in's
/// command). A toolbar's footer draws all its command buttons from one call.
pub(crate) fn button_texts(app: &mut VectorcraftApp, ui: &egui::Ui, ids: &[String]) -> Vec<Option<ButtonText>> {
if ids.is_empty() {
return Vec::new();
}
let built = kept_commands(app, ui);
ids.iter().map(|id| if is_command(id) { built.by_id.get(id).and_then(|&i| built.entries.get(i)).map(button_text_of) } else { None }).collect()
}
/// [`ButtonText`] of the entry `e`.
fn button_text_of(e: &HelpEntry) -> ButtonText {
let label = e.label().as_str().trim_end();
let label = label.rsplit(" › ").next().unwrap_or(label);
let label = label.strip_suffix('…').or_else(|| label.strip_suffix("...")).unwrap_or(label).trim_end();
let path: Vec<&str> = e.path().iter().map(|p| p.as_str()).collect();
// A label that already starts with its menu path (a plug-in command's) is the full name.
let joined = path.join(" › ");
let full = e.label().as_str();
let name = if path.is_empty() || full.starts_with(&format!("{joined} › ")) { full.to_string() } else { format!("{joined} › {full}") };
ButtonText { label: label.to_string(), name, command: e.command().clone() }
}
/// The results a toolbar made with New Toolbar can hold as command buttons that the query `q`
/// matches, best first, at most `most`: the results [`is_command`] allows. Each is its id and its
/// name in the interface language ([`ButtonText::name`]).
pub(crate) fn command_matches(app: &mut VectorcraftApp, ui: &egui::Ui, q: &str, most: usize) -> Vec<(String, String)> {
if q.trim().is_empty() {
return Vec::new();
}
let built = kept_build(app, ui);
let mut seen = std::collections::HashSet::new();
craft::ui::menu::rank(&built.index, q, &[], &|_| 0)
.into_iter()
.filter_map(|at| built.entries.get(at))
.filter_map(|e| Some((e.ids().first()?.clone(), e)))
.filter(|(id, _)| is_command(id) && seen.insert(id.clone()))
.take(most)
.map(|(id, e)| (id, button_text_of(e).name))
.collect()
}
/// Can a toolbar made with New Toolbar hold the result `id` as a command button now: is it a
/// palette result other than a tool, and not a UI command that fails without params a click does
/// not give ([`crate::shortcut_editor::ui_command_needs_params`]: `toolbar.addTool` needs a
/// `tool`)? The ids are listed again when the plug-ins change, not on every call.
pub(crate) fn is_command(id: &str) -> bool {
type Ids = (u64, Arc<std::collections::HashSet<String>>);
static IDS: std::sync::Mutex<Option<Ids>> = std::sync::Mutex::new(None);
if id.starts_with("tool:") {
return false;
}
let key = menus::plugin_revision();
let kept = IDS.lock().ok().and_then(|ids| ids.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v.clone()));
let ids = kept.unwrap_or_else(|| {
let filters: Vec<String> = crate::shortcut_editor::filter_items().iter().map(|f| format!("plugin:{}", f.id)).collect();
let ids = drafts()
.into_iter()
.map(|d| d.id)
.filter(|id| !id.starts_with("tool:") && id != menus::TODO && !crate::shortcut_editor::ui_command_needs_params(id));
let ids: Arc<std::collections::HashSet<String>> = Arc::new(ids.chain(filters).collect());
if let Ok(mut kept) = IDS.lock() {
*kept = Some((key, ids.clone()));
}
ids
});
ids.contains(id)
}
/// The kept build for the current [`BuildKey`] as it is, without re-homing its tool entries, for
/// looking up results other than tools, whose entries a toolbar's change leaves as they are: a
/// toolbar's footer looks its command buttons up on every pass. Without a build for the key, it is
/// [`kept_build`].
fn kept_commands(app: &mut VectorcraftApp, ui: &egui::Ui) -> Arc<Built> {
let key = BuildKey { catalog: app.menus.catalog_generation(), native: app.services.native_menu.is_some() };
if let Some((kept, built)) = &app.canvas.palette
&& *kept == key
{
return built.clone();
}
kept_build(app, ui)
}
/// The built entries for the current [`BuildKey`]: built again when the key moves (the index is
+31 -4
View File
@@ -488,7 +488,6 @@ const GROUPS: &[(&str, &str)] = &[
("ui.newLayer", "Window › Layers"),
("ui.newParaStyle", "Window › Paragraph Styles"),
("ui.newSwatch", "Window › Swatches"),
("ui.pdfSummary.", "File"),
("ui.perspectivePlane", "View › Perspective Grid"),
("ui.perspectiveUserPreset1.", "View › Perspective Grid › One Point Perspective"),
("ui.perspectiveUserPreset2.", "View › Perspective Grid › Two Point Perspective"),
@@ -500,7 +499,6 @@ const GROUPS: &[(&str, &str)] = &[
("ui.relinkDialog", "Window › Links"),
("ui.rename", "Window › Layers"),
("ui.retype", "Window › Properties"),
("ui.runInstalledScript", "File › Scripts"),
("ui.sampleScreenColor", "Color"),
("ui.savePdfDialog", "File"),
("ui.shortcutImportDialog", "Shortcuts"),
@@ -828,6 +826,16 @@ fn a_menu_bar_item_runs(id: &str, params: &str) -> bool {
|| menu_target(id).is_some_and(|(target, _)| target != id || !names_a_required_field(params))
}
/// Is `id` a UI command that fails when it runs with no params: its params doc names a field a call
/// must give, no item of the menu bar runs it ([`a_menu_bar_item_runs`]), and a key press does not
/// run it on its own ([`ui_listed_on_its_own`])? `toolbar.addTool` needs a `tool`.
pub(crate) fn ui_command_needs_params(id: &str) -> bool {
crate::menus::UI_COMMANDS
.iter()
.find(|c| c.0 == id)
.is_some_and(|c| names_a_required_field(c.3) && !a_menu_bar_item_runs(c.0, c.3) && !ui_listed_on_its_own(c.0, c.2, c.3))
}
/// Is engine command `c` listed in Edit › Keyboard Shortcuts whether or not an item of the menu bar
/// runs it? A command with a menu path of its own is. One without (a panel menu item) is when a key
/// alone can run it: it has a default key, or it is an undoable command, not an alias, whose params
@@ -838,9 +846,11 @@ fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool {
/// Is UI command `id` (default key `sc`, params doc `params`) listed in Edit › Keyboard Shortcuts
/// whether or not an item of the menu bar runs it? It is when it has a default key or a params doc
/// of `{}` or `{path…}`, or is one of [`KEY_ONLY_UI`].
/// of `{}` or `{path?…}`, where a call with no path picks a file, or is one of [`KEY_ONLY_UI`]. A
/// params doc of `{path}` or `{path: …}` (Save Summary…, a Scripts folder script) needs a path, so a
/// key press alone can't run it.
fn ui_listed_on_its_own(id: &str, sc: &str, params: &str) -> bool {
!sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || KEY_ONLY_UI.contains(&id)
!sc.is_empty() || params.starts_with("{}") || params.starts_with("{path?") || KEY_ONLY_UI.contains(&id)
}
/// Does a menu bar item run the command with no params, so that it does what its label says and opens
@@ -2450,6 +2460,23 @@ mod tests {
assert!(failures.is_empty(), "{failures:#?}");
}
/// A UI command whose params doc starts `{path}` or `{path: …}` needs a path, so it is neither
/// listed on its own nor offered as a button; one that starts `{path?` picks a file without one.
#[test]
fn a_ui_command_that_needs_a_path_is_not_run_without_one() {
for id in ["ui.pdfSummary.save", crate::scripts_menu::COMMAND] {
let (_, _, sc, params) = menus::UI_COMMANDS.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{id} is a UI command"));
assert!(!ui_listed_on_its_own(id, sc, params), "{id} is not listed on its own");
assert!(ui_command_needs_params(id), "{id} needs a path");
assert!(!crate::palette::is_command(id), "{id} is not offered as a toolbar button");
}
for id in ["shortcuts.export", "file.open"] {
let (_, _, sc, params) = menus::UI_COMMANDS.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{id} is a UI command"));
assert!(ui_listed_on_its_own(id, sc, params) || a_menu_bar_item_runs(id, params), "{id} runs without a path");
assert!(!ui_command_needs_params(id), "{id} picks a file without a path");
}
}
/// #2991: Enter Isolation Mode has no default key but runs on the selection, so it belongs in
/// Edit › Keyboard Shortcuts.
#[test]
+5
View File
@@ -1248,6 +1248,11 @@ pub struct CustomToolbar {
/// Older files: the groups torn off it. Read by the conversion, never written.
#[serde(default, skip_serializing)]
pub floating: Vec<FloatingFlyout>,
/// Its command buttons, after its tools: Command Palette result ids (a command's id, or
/// `plugin:`, `effect:` or `panel:` and an id). A command that is gone, such as an uninstalled
/// plug-in's, is kept and shows as unavailable until it comes back.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub commands: Vec<String>,
}
/// A category of an edited toolbar: its name (one of the Basic toolbar's; none in the Advanced
+14 -2
View File
@@ -491,8 +491,20 @@ toolbars Tab hid are turned off. A toolbar's ••• button
button (Add Tool…) opens a menu of every tool under the drawer's headings: a click on a tool runs `toolbar.addTool
{tool, toolbar}`, which puts it at the end, and the tools under its Remove Tool heading run `toolbar.removeTool
{tool, toolbar}`; the tools already in the toolbar are dimmed under their headings. The drawer has no Show section
there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with
it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag,
there. The same menu's Add Command submenu searches the Command Palette's results other than tools, and a pick runs
`toolbar.addCommand {command, toolbar}`, which puts a command button at the end of the toolbar, after its tools;
`toolbar.addCommand {command, toolbar, at}` moves one to place `at` among the command buttons (Move Up and Move Down
in the button's context menu), and `toolbar.removeCommand {command, toolbar}` takes one off (Remove Command in the
menu, Remove from Toolbar in the context menu). `command` is a palette result's id: a command's id, or
`plugin:<id>`, `effect:<id>` or `panel:<id>`. A click on the button runs what the command's menu item runs, and the
button is dimmed while that item is. A missing `toolbar` is an error for both and changes nothing. For
`toolbar.addCommand`, an unknown command, a tool, a command that needs params a click does not give
(`toolbar.addTool`) or a place past the end is also an error and changes nothing. `toolbar.removeCommand` with a
command the toolbar has no button for, a tool's id included, is not an error: it answers with the toolbar's command
buttons unchanged. A command that is no longer installed keeps its button, dimmed, and `toolbar.removeCommand` still
takes it off.
`window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it.
`window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, commands, shown flag,
two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked).
`window.toolbar.dock {name, side?, order?}` docks a toolbar as a column of the dock along the window's left or right
edge, and `window.toolbar.float {name, x?, y?}` floats it again; dragging its title bar does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in:
+22
View File
@@ -4202,6 +4202,28 @@ workspace. These are VectorCraft's own layout rules.
{"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}}
```
## Command buttons on toolbars made with New Toolbar
A toolbar made with New Toolbar holds command buttons after its tools. `toolbar.addCommand {command, toolbar, at?}`
(Add Command in the toolbar's Add Tool… menu, remote mode, `invoke_menu`) puts a button for `command` on the toolbar
named `toolbar`, or moves the button when the toolbar has it already: at place `at` among its command buttons, 0 for
the first, or at the end without `at`. `command` is a Command Palette result's id: a command's id, or
`plugin:<id>`, `effect:<id>` or `panel:<id>`. `toolbar.removeCommand {command, toolbar}` takes a button off. Both
answer with the toolbar's command buttons, and `window.toolbar.list` reports `commands` for each toolbar. A missing
`toolbar` is an error for both and changes nothing. For `toolbar.addCommand`, an unknown command, a tool, a command
that needs params a click does not give (`toolbar.addTool`) or an `at` past the end is also an error and changes
nothing. `toolbar.removeCommand` with a command the toolbar has no button for, a tool's id included, is not an error:
it answers with the toolbar's command buttons unchanged. A click on a button runs what the command's menu item runs, so a
command whose item ends in … opens its dialog, and the button is dimmed while that item is. A command that is no
longer installed, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it is
installed again or removed. `toolbar.reset {toolbar}` takes the buttons off with the tools. The buttons are kept with
the workspace, and toolbars saved before command buttons existed load without any. Command buttons are VectorCraft's
own.
```json
{"name":"invoke_menu","arguments":{"command":"toolbar.addCommand","params":{"command":"object.group","toolbar":"Toolbar 1"}}}
```
## Help search
Help › VectorCraft Help… and F1 show the Help panel. `help.discover {query?}` opens it without
+1
View File
@@ -1219,6 +1219,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done.
- Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`).
- A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`).
- A toolbar made with New Toolbar also holds command buttons, after its tools. The Add Command submenu at the end of its Add Tool… menu searches every Command Palette result other than a tool (menu commands, plug-in commands, effects and panels), and a pick adds a button at the end; Remove Command in the same menu lists the buttons and takes one off. A button shows its command's label without the ellipsis, on up to two lines, and its full name and shortcut on hover. A click runs what the command's menu item runs, so a command whose item ends in … opens its dialog. While that item is dimmed the button is dimmed and runs nothing. The button's context menu has Move Up, Move Down and Remove from Toolbar. The buttons are kept with the toolbar in the workspace, Manage Toolbars' copy keeps them, and a toolbar saved without them loads unchanged. A command that is gone, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it comes back or is removed. Not done: dragging a menu item or a Command Palette result onto a toolbar, an Add to Toolbar item in the palette, dragging command buttons to reorder or remove them, and command icons (a button shows its label). Command buttons are VectorCraft's own (`toolbar.addCommand`, `toolbar.removeCommand`; `command_buttons_are_added_moved_and_removed_by_their_commands`, `a_command_button_runs_its_command_and_is_dimmed_while_it_cannot`, `a_missing_command_stays_dimmed_until_it_is_removed`, `a_plugin_command_button_works_again_when_the_plugin_returns`, `a_panel_button_shows_its_panel`, `command_buttons_ask_whether_they_can_run_a_few_at_a_time`, `the_add_tool_menu_adds_and_removes_commands`).
- Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`).
- In the All Tools drawer a tool the toolbar holds is drawn throughout — name, shortcut and icon — in the dim text colour, one step dimmer than a tool not in it, so it still reads as in the toolbar while its name stays readable against the panel; the disabled colour it was drawn in before was about 2.6:1 on the panel, unreadable at the drawer's 12.5 px (#8294; `tools_in_the_toolbar_are_dimmed_in_the_drawer` in `crates/ui-egui/src/edit_toolbar/tests.rs`, which asserts the painted colour's contrast). The dimming is VectorCraft's own (#1018).
- A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`).