Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Menus from the command list

Indicode BVd34937e0454e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a1a0c89..13084b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,8 @@ The first builds, and klad's licences.
- In-betweens blend colours evenly (in OKLab), so light can follow a turning limb when the second key is coloured for it.
- `klad arcs` follows the part of a foot on the ground: a heel-to-toe roll is no longer reported as a slide.
- "Report a problem" copies what an issue needs.
-- Bones: a layer or group gets a skeleton (`klad bone`, the bone tool J), weights from the bones or painted (`klad weights`), and poses that bend the drawing (`klad pose`, pose mode); in-betweens of two poses turn the bones.
+- Bones: a layer or group gets a skeleton (`klad bone`, the bone tool J), weights from the bones or painted (`klad weights`), and poses that bend the drawing (`klad pose`, pose mode); in-betweens of two poses turn the bones. The bone tool lists the skeleton, picks a bone in every mode, and moves ends, joints and whole bones with their children (`klad bone --move` with `--by`).
+- Menus: a menu bar (the Mac's own, an in-window one on Windows and Linux) holds every command, with its keys, ticks for what is on and greyed items for what cannot run now; File has close (cmd W) and recent drawings.
- Keys: layers, groups and shapes move, turn, scale and fade between frames with eases (`klad key`, the keys section of the inspector).
- Godot: `--godot-rig` exports a Skeleton2D with Polygon2D parts and the poses as animations; `--godot-scene` a parallax scene with a Parallax2D per depth plane.
- `klad paintover` (and "paint over" in the layers panel): brushwork from any picture, strokes that follow its forms and stop at its colour edges, big to small, detail where the picture has it; `--like` and `--frames` carry it through an animation without boiling.
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml
index 1cc560b..91c6bfc 100644
--- a/crates/app/Cargo.toml
+++ b/crates/app/Cargo.toml
@@ -27,7 +27,7 @@ zstd = "0.14.3"
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6"
objc2 = "0.6"
-objc2-app-kit = { version = "0.3", features = ["NSEvent", "NSResponder", "NSGraphics", "NSApplication", "NSWindow", "NSPanel", "NSSavePanel", "NSOpenPanel"] }
+objc2-app-kit = { version = "0.3", features = ["NSEvent", "NSResponder", "NSGraphics", "NSApplication", "NSWindow", "NSPanel", "NSSavePanel", "NSOpenPanel", "NSMenu", "NSMenuItem", "NSCell"] }
objc2-foundation = "0.3"
[target.'cfg(not(target_os = "macos"))'.dependencies]
diff --git a/crates/app/src/commands.rs b/crates/app/src/commands.rs
index bd6e23f..1fa979f 100644
--- a/crates/app/src/commands.rs
+++ b/crates/app/src/commands.rs
@@ -160,6 +160,8 @@ pub enum Cmd {
ShowGaps,
ShowParts,
ShowArcs,
+ CloseDocument,
+ Quit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -474,7 +476,7 @@ use Repeat as R;
use Trigger as T;
impl Cmd {
- pub const ALL: [Cmd; 156] = [
+ pub const ALL: [Cmd; 158] = [
Cmd::Brush,
Cmd::Eraser,
Cmd::Fill,
@@ -616,6 +618,8 @@ impl Cmd {
Cmd::PasteCellsLinked,
Cmd::ClipSettings,
Cmd::NewDocument,
+ Cmd::CloseDocument,
+ Cmd::Quit,
Cmd::OpenDocument,
Cmd::OpenRecent,
Cmd::CopyPath,
@@ -1886,6 +1890,24 @@ impl Cmd {
R::No,
"name, loop, own fps, first and last frame, delete, export to Godot",
),
+ Cmd::CloseDocument => spec(
+ "file.close",
+ "close the drawing",
+ icon::CLOSE,
+ G::File,
+ T::Press(const { &[cmd(Key::W)] }),
+ R::No,
+ "back to the start window; everything is saved as you go",
+ ),
+ Cmd::Quit => spec(
+ "file.quit",
+ "quit klad",
+ icon::CLOSE,
+ G::File,
+ T::Press(const { &[cmd(Key::Q)] }),
+ R::No,
+ "close the window and quit; everything is saved as you go",
+ ),
Cmd::NewDocument => spec(
"file.new",
"new drawing",
@@ -2047,6 +2069,294 @@ impl Cmd {
}
}
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Item {
+ Run(Cmd),
+ Line,
+ Sub(&'static str, &'static [Item]),
+ Recent,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Menu {
+ pub title: &'static str,
+ pub items: &'static [Item],
+}
+
+use Item::{Line, Run, Sub};
+
+pub const MENUS: [Menu; 7] = [
+ Menu {
+ title: "File",
+ items: &[
+ Run(Cmd::NewDocument),
+ Run(Cmd::OpenDocument),
+ Item::Recent,
+ Run(Cmd::CloseDocument),
+ Line,
+ Run(Cmd::Export),
+ Run(Cmd::ExportGodot),
+ Line,
+ Run(Cmd::ImportPicture),
+ Run(Cmd::AddFont),
+ Line,
+ Run(Cmd::CopyPath),
+ Run(Cmd::InstallCommand),
+ Line,
+ Run(Cmd::Quit),
+ ],
+ },
+ Menu {
+ title: "Edit",
+ items: &[
+ Run(Cmd::Undo),
+ Run(Cmd::Redo),
+ Line,
+ Run(Cmd::Copy),
+ Run(Cmd::Paste),
+ Run(Cmd::DuplicateInPlace),
+ Run(Cmd::Delete),
+ Line,
+ Run(Cmd::SelectAll),
+ Run(Cmd::Deselect),
+ Run(Cmd::CutLasso),
+ Line,
+ Sub(
+ "Selection",
+ &[
+ Run(Cmd::Recolour),
+ Run(Cmd::Thinner),
+ Run(Cmd::Thicker),
+ Line,
+ Run(Cmd::FlipH),
+ Run(Cmd::FlipV),
+ Run(Cmd::TurnLeft90),
+ Run(Cmd::TurnRight90),
+ Line,
+ Run(Cmd::NudgeLeft),
+ Run(Cmd::NudgeRight),
+ Run(Cmd::NudgeUp),
+ Run(Cmd::NudgeDown),
+ ],
+ ),
+ Sub(
+ "Points",
+ &[
+ Run(Cmd::Corner),
+ Run(Cmd::Smooth),
+ Run(Cmd::Simplify),
+ Run(Cmd::MakePath),
+ ],
+ ),
+ Line,
+ Run(Cmd::Settings),
+ ],
+ },
+ Menu {
+ title: "Draw",
+ items: &[
+ Run(Cmd::Brush),
+ Run(Cmd::Eraser),
+ Run(Cmd::Fill),
+ Run(Cmd::Shapes),
+ Run(Cmd::Strokes),
+ Run(Cmd::Points),
+ Run(Cmd::Pen),
+ Run(Cmd::ShapeTool),
+ Run(Cmd::TextTool),
+ Run(Cmd::BoneTool),
+ Run(Cmd::Note),
+ Line,
+ Run(Cmd::Smaller),
+ Run(Cmd::Bigger),
+ Run(Cmd::Symmetry),
+ Run(Cmd::BrushWindow),
+ Line,
+ Run(Cmd::SwapColours),
+ Run(Cmd::AddSwatch),
+ Line,
+ Run(Cmd::Refill),
+ Run(Cmd::FillLike),
+ Run(Cmd::ShowGaps),
+ ],
+ },
+ Menu {
+ title: "View",
+ items: &[
+ Run(Cmd::Fit),
+ Run(Cmd::ActualSize),
+ Run(Cmd::TurnRight),
+ Run(Cmd::TurnLeft),
+ Run(Cmd::ResetRotation),
+ Run(Cmd::FlipView),
+ Line,
+ Run(Cmd::Onion),
+ Run(Cmd::OnionSettings),
+ Run(Cmd::ShowParts),
+ Run(Cmd::ShowArcs),
+ Run(Cmd::CompareReference),
+ Line,
+ Run(Cmd::HideAll),
+ Run(Cmd::HideDock),
+ Run(Cmd::LayersPane),
+ Run(Cmd::ToolPane),
+ Run(Cmd::InspectorPane),
+ Run(Cmd::NotesPane),
+ Run(Cmd::HistoryPane),
+ Run(Cmd::Timeline),
+ Line,
+ Run(Cmd::MessageLog),
+ Sub("Numbers", &[Run(Cmd::Numbers), Run(Cmd::ResetNumbers), Run(Cmd::Spin)]),
+ ],
+ },
+ Menu {
+ title: "Layer",
+ items: &[
+ Run(Cmd::NewPaintLayer),
+ Run(Cmd::NewVectorLayer),
+ Run(Cmd::NewAdjustLayer),
+ Run(Cmd::NewGroupLayer),
+ Line,
+ Run(Cmd::DuplicateLayer),
+ Run(Cmd::RenameLayer),
+ Run(Cmd::GroupLayer),
+ Run(Cmd::DeleteLayer),
+ Line,
+ Run(Cmd::ToggleVisible),
+ Run(Cmd::ToggleLocked),
+ Run(Cmd::ToggleClip),
+ Run(Cmd::ToggleLockAlpha),
+ Run(Cmd::OnionLayer),
+ Line,
+ Sub(
+ "Mask",
+ &[
+ Run(Cmd::AddMask),
+ Run(Cmd::AddMaskHiding),
+ Run(Cmd::PaintMask),
+ Run(Cmd::BackToLayer),
+ Run(Cmd::ToggleMask),
+ Run(Cmd::TintMask),
+ Run(Cmd::RemoveMask),
+ ],
+ ),
+ Sub(
+ "Shapes",
+ &[
+ Run(Cmd::MakeRepeat),
+ Run(Cmd::MakeScatter),
+ Run(Cmd::MakeMirror),
+ Run(Cmd::Unwrap),
+ ],
+ ),
+ Run(Cmd::PaintOver),
+ ],
+ },
+ Menu {
+ title: "Frame",
+ items: &[
+ Run(Cmd::NextFrame),
+ Run(Cmd::PrevFrame),
+ Run(Cmd::NextDrawing),
+ Run(Cmd::PrevDrawing),
+ Run(Cmd::FirstFrame),
+ Run(Cmd::LastFrame),
+ Line,
+ Run(Cmd::NewDrawing),
+ Run(Cmd::NewDrawingAfter),
+ Sub(
+ "New drawings on",
+ &[Run(Cmd::ExposeOnes), Run(Cmd::ExposeTwos), Run(Cmd::ExposeThrees)],
+ ),
+ Run(Cmd::Duplicate),
+ Run(Cmd::Link),
+ Run(Cmd::Unlink),
+ Run(Cmd::DeleteDrawing),
+ Line,
+ Run(Cmd::HoldLonger),
+ Run(Cmd::HoldShorter),
+ Run(Cmd::MoveEarlier),
+ Run(Cmd::MoveLater),
+ Run(Cmd::InsertFrame),
+ Run(Cmd::InsertFrameAll),
+ Run(Cmd::RemoveFrame),
+ Run(Cmd::RemoveFrameAll),
+ Line,
+ Run(Cmd::Play),
+ Run(Cmd::LoopRange),
+ Run(Cmd::Prepare),
+ Line,
+ Sub(
+ "Selected frames",
+ &[
+ Run(Cmd::OnOnes),
+ Run(Cmd::OnTwos),
+ Run(Cmd::OnThrees),
+ Run(Cmd::FitFrames),
+ Run(Cmd::Reverse),
+ Run(Cmd::Pingpong),
+ Run(Cmd::EveryLayer),
+ Line,
+ Run(Cmd::Inbetween),
+ Run(Cmd::RedoInbetweens),
+ Line,
+ Run(Cmd::CopyCells),
+ Run(Cmd::PasteCells),
+ Run(Cmd::PasteCellsLinked),
+ ],
+ ),
+ Sub(
+ "Clip",
+ &[
+ Run(Cmd::NewClip),
+ Run(Cmd::ClipSettings),
+ Run(Cmd::ClipLoops),
+ Run(Cmd::ClipOwnFps),
+ Run(Cmd::DeleteClip),
+ ],
+ ),
+ ],
+ },
+ Menu {
+ title: "Help",
+ items: &[
+ Run(Cmd::Palette),
+ Run(Cmd::Keys),
+ Line,
+ Run(Cmd::ReportProblem),
+ Run(Cmd::About),
+ ],
+ },
+];
+
+#[cfg(any(target_os = "macos", test))]
+pub const IN_APP_MENU: [Cmd; 3] = [Cmd::About, Cmd::Settings, Cmd::Quit];
+
+pub fn menu_label(cmd: Cmd) -> String {
+ let name = cmd.spec().name;
+ let mut chars = name.chars();
+ chars
+ .next()
+ .map_or_else(String::new, |c| c.to_uppercase().chain(chars).collect())
+}
+
+pub fn menu_hint(menu: &Menu) -> String {
+ let names: Vec<&str> = in_menus(menu.items).iter().take(4).map(|c| c.spec().name).collect();
+ format!("{}: {}, ...", menu.title, names.join(", "))
+}
+
+pub fn in_menus(items: &[Item]) -> Vec<Cmd> {
+ items
+ .iter()
+ .flat_map(|i| match i {
+ Item::Run(c) => vec![*c],
+ Item::Sub(_, inner) => in_menus(inner),
+ Item::Recent => vec![Cmd::OpenRecent],
+ Item::Line => Vec::new(),
+ })
+ .collect()
+}
+
fn squash(text: &str) -> String {
text.to_lowercase().chars().filter(|c| *c != '-').collect()
}
@@ -2204,6 +2514,29 @@ mod tests {
("reset numbers (M0)", "numbers.reset"),
];
+ #[test]
+ fn every_command_is_in_a_menu_once_but_the_holds() {
+ let listed: Vec<Cmd> = MENUS.iter().flat_map(|m| in_menus(m.items)).collect();
+ let twice: Vec<&Cmd> = listed
+ .iter()
+ .enumerate()
+ .filter(|(i, c)| listed[..*i].contains(c))
+ .map(|(_, c)| c)
+ .collect();
+ assert!(twice.is_empty(), "in two places: {twice:?}");
+ let missing: Vec<Cmd> = Cmd::ALL
+ .into_iter()
+ .filter(|c| !listed.contains(c) && !c.spec().is_hold())
+ .collect();
+ assert!(missing.is_empty(), "not in any menu: {missing:?}");
+ assert!(
+ listed.iter().all(|c| !c.spec().is_hold()),
+ "holds are gestures, not menu items"
+ );
+ assert!(IN_APP_MENU.iter().all(|c| listed.contains(c)));
+ assert_eq!(menu_label(Cmd::NewDocument), "New drawing");
+ }
+
#[test]
fn every_editor_action_of_m1_to_m3_is_a_named_command() {
let missing: Vec<&str> = INVENTORY
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 664107d..a87e93b 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -523,11 +523,13 @@ struct PaletteState {
opened: bool,
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Want {
New,
Open,
Recent,
+ Close,
+ Path(std::path::PathBuf),
}
pub(crate) struct Editor {
diff --git a/crates/app/src/editor/commands.rs b/crates/app/src/editor/commands.rs
index fd76bd3..b0f6e6f 100644
--- a/crates/app/src/editor/commands.rs
+++ b/crates/app/src/editor/commands.rs
@@ -68,6 +68,9 @@ impl Editor {
let editing = self.busy().then(|| "finish the stroke or drag first".to_string());
match cmd {
Cmd::Undo | Cmd::Redo => editing,
+ Cmd::CloseDocument => (!self.jobs.is_empty())
+ .then(|| "wait for the running jobs, or cancel them in the status line".to_string())
+ .or(editing),
Cmd::Delete => match self.tool {
Tool::Note => self
.note_open
@@ -294,6 +297,18 @@ impl Editor {
self.jobs.busy(crate::jobs::Tag::Inbetween)
}
+ pub(crate) fn menu_state(&self) -> crate::menus::Shown {
+ crate::menus::Shown {
+ off: Cmd::ALL.into_iter().filter(|c| self.can_run(*c).is_some()).collect(),
+ on: Cmd::ALL.into_iter().filter(|c| self.is_on(*c) == Some(true)).collect(),
+ }
+ }
+
+ pub(crate) fn run_later(&mut self, cmd: Cmd) {
+ self.queued.push(cmd);
+ self.ctx.request_repaint();
+ }
+
pub(super) fn is_on(&self, cmd: Cmd) -> Option<bool> {
let layer = self.scene.active_layer();
let layout = &self.settings.layout;
@@ -585,6 +600,8 @@ impl Editor {
Cmd::PasteCellsLinked => self.paste_cells(true)?,
Cmd::ClipSettings => self.windows.clip = !self.windows.clip,
Cmd::NewDocument => self.wants = Some(super::Want::New),
+ Cmd::CloseDocument => self.wants = Some(super::Want::Close),
+ Cmd::Quit => self.ctx.send_viewport_cmd(egui::ViewportCommand::Close),
Cmd::OpenDocument => self.wants = Some(super::Want::Open),
Cmd::OpenRecent => self.wants = Some(super::Want::Recent),
Cmd::About => self.windows.about = !self.windows.about,
diff --git a/crates/app/src/editor/panels.rs b/crates/app/src/editor/panels.rs
index 589f107..759419f 100644
--- a/crates/app/src/editor/panels.rs
+++ b/crates/app/src/editor/panels.rs
@@ -79,6 +79,11 @@ impl Editor {
let window = ctx.content_rect().size();
self.settings.layout.clamp(window);
let pressing = ui.input(|i| i.pointer.any_down());
+ if !crate::menus::native() && !self.settings.layout.hidden {
+ egui::Panel::top("menus")
+ .resizable(false)
+ .show(ui, |ui| egui::MenuBar::new().ui(ui, |ui| self.menu_bar(ui)));
+ }
egui::Panel::bottom("status")
.exact_size(layout::STATUS)
.resizable(false)
@@ -245,6 +250,65 @@ impl Editor {
});
}
+ fn menu_bar(&mut self, ui: &mut egui::Ui) {
+ commands::MENUS.iter().for_each(|m| {
+ ui.menu_button(m.title, |ui| self.menu_items(ui, m.items))
+ .response
+ .hint(commands::menu_hint(m));
+ });
+ }
+
+ fn menu_items(&mut self, ui: &mut egui::Ui, items: &[commands::Item]) {
+ items.iter().for_each(|item| match *item {
+ commands::Item::Line => {
+ ui.separator();
+ }
+ commands::Item::Run(cmd) => self.menu_entry(ui, cmd),
+ commands::Item::Sub(title, inner) => {
+ ui.menu_button(title, |ui| self.menu_items(ui, inner));
+ }
+ commands::Item::Recent => {
+ ui.menu_button("Open recent", |ui| {
+ let paths: Vec<std::path::PathBuf> = self
+ .settings
+ .documents
+ .iter()
+ .take(crate::menus::RECENT)
+ .map(std::path::PathBuf::from)
+ .collect();
+ paths.iter().for_each(|path| {
+ if ui
+ .button(crate::menus::recent_label(path))
+ .hint(path.display().to_string())
+ .clicked()
+ {
+ self.wants = Some(super::Want::Path(path.clone()));
+ ui.close();
+ }
+ });
+ if !paths.is_empty() {
+ ui.separator();
+ }
+ self.menu_entry(ui, Cmd::OpenRecent);
+ });
+ }
+ });
+ }
+
+ fn menu_entry(&mut self, ui: &mut egui::Ui, cmd: Cmd) {
+ let label = commands::menu_label(cmd);
+ let can = self.can_run(cmd).is_none();
+ let response = match self.is_on(cmd) {
+ Some(mut on) => ui.add_enabled(can, egui::Checkbox::new(&mut on, label)),
+ None => ui.add_enabled(can, egui::Button::new(label).shortcut_text(self.bindings.label(cmd))),
+ }
+ .hint(self.command_hint(cmd));
+ if response.clicked() {
+ self.queued.push(cmd);
+ ui.close();
+ }
+ }
+
fn document_menu(&mut self, ui: &mut egui::Ui) {
let button = egui::Button::new(RichText::new(icon::FILE).size(18.0)).min_size(vec2(36.0, 32.0));
let name = self
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index fd5645a..b2eb562 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -725,7 +725,7 @@ fn palette_swatches_move_by_dragging_and_go_from_their_corner() {
)
.unwrap();
}
- let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ let mut h = harness(editor(&path), vec2(1440.0, 1060.0));
let order = |h: &Harness<'static, Editor>| -> Vec<String> {
h.state()
.scene
@@ -2529,6 +2529,47 @@ fn text_is_typed_on_the_canvas_and_edited_in_place() {
assert!(path.join("fonts/Cinzel.ttf").is_file(), "picking a font copies it in");
}
+#[test]
+fn the_menu_bar_reaches_commands_shows_their_state_and_greys_what_cannot_run() {
+ let path = sample("menus");
+ let mut h = harness(editor(&path), vec2(1440.0, 1000.0));
+ let item = |h: &Harness<'static, Editor>, name: &str| {
+ h.query_all_by_label_contains(name)
+ .find(|n| n.accesskit_node().role() != Role::Window)
+ .unwrap_or_else(|| panic!("no menu item {name}"))
+ .rect()
+ };
+ h.get_by_label("File").click();
+ h.run_steps(2);
+ assert!(h.query_by_label_contains("Close the drawing").is_some());
+ h.get_by_label("Export").click();
+ h.run_steps(3);
+ assert!(h.state().windows.export, "File > Export opens the export window");
+ assert!(h.state().settings.layout.timeline);
+ h.get_by_label("View").click();
+ h.run_steps(2);
+ h.get_by_label("Timeline").click();
+ h.run_steps(3);
+ assert!(!h.state().settings.layout.timeline, "View > Timeline hides it");
+ h.get_by_label("Edit").click();
+ h.run_steps(2);
+ h.hover_at(item(&h, "Selection").center());
+ h.run_steps(3);
+ let recolour = h
+ .query_all_by_label_contains("Recolour the selected strokes")
+ .next()
+ .expect("the selection submenu opens");
+ assert!(recolour.accesskit_node().is_disabled(), "nothing selected greys it out");
+ h.key_press(Key::Escape);
+ h.run_steps(2);
+ h.get_by_label("File").click();
+ h.run_steps(2);
+ h.get_by_label_contains("Close the drawing").click();
+ h.run_steps(2);
+ assert_eq!(h.state().wants, Some(super::Want::Close));
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn bones_are_drawn_weighted_and_posed_on_the_canvas() {
let path = sample("bones");
diff --git a/crates/app/src/home.rs b/crates/app/src/home.rs
index 10aa217..c76cf04 100644
--- a/crates/app/src/home.rs
+++ b/crates/app/src/home.rs
@@ -1,5 +1,7 @@
+use crate::commands::{Bindings, Cmd};
use crate::editor::{Editor, Want};
use crate::gpu::CanvasGpu;
+use crate::menus::{self, Picked};
use crate::messages::Tone;
use crate::picker;
use crate::settings::{self, Settings};
@@ -46,6 +48,9 @@ pub(crate) struct Home {
themed: bool,
pub(crate) update: Option<crate::updates::Release>,
checking: Option<std::sync::mpsc::Receiver<updates::Checked>>,
+ native_menus: bool,
+ menus_built: Option<u64>,
+ menus_shown: Option<std::time::Instant>,
}
impl Home {
@@ -57,6 +62,7 @@ impl Home {
let settings_path = settings::default_path();
let settings = settings_path.as_deref().map(Settings::load).unwrap_or_default();
let mut home = Self::with(settings, settings_path, Some(gpu));
+ home.native_menus = true;
if updates::due(
home.settings.check_updates,
home.settings.updates_checked,
@@ -82,6 +88,9 @@ impl Home {
themed: false,
update: None,
checking: None,
+ native_menus: false,
+ menus_built: None,
+ menus_shown: None,
}
}
@@ -148,8 +157,83 @@ impl Home {
}
}
+ fn tend_menus(&mut self, ctx: &egui::Context) {
+ if !self.native_menus {
+ return;
+ }
+ let settings = self.editor.as_ref().map_or(&self.settings, |e| &e.settings);
+ let built = menus::signature(&settings.keys, &settings.documents);
+ if self.menus_built != Some(built) {
+ menus::install(ctx, &Bindings::from_settings(&settings.keys), &settings.documents);
+ self.menus_built = Some(built);
+ }
+ if self
+ .menus_shown
+ .is_none_or(|t| t.elapsed() > std::time::Duration::from_millis(400))
+ {
+ menus::show(
+ self.editor
+ .as_ref()
+ .map_or_else(menus::outside_a_drawing, |e| e.menu_state()),
+ );
+ self.menus_shown = Some(std::time::Instant::now());
+ }
+ }
+
+ fn picked(&mut self, ctx: &egui::Context) -> Option<PathBuf> {
+ menus::take()
+ .into_iter()
+ .fold(None, |path, picked| match (picked, self.editor.as_mut()) {
+ (Picked::Open(p), _) => Some(p),
+ (Picked::Run(cmd), Some(editor)) => {
+ editor.run_later(cmd);
+ path
+ }
+ (Picked::Run(Cmd::NewDocument), None) => {
+ self.start = Some(Start::new(&self.settings, Section::New));
+ path
+ }
+ (Picked::Run(Cmd::OpenRecent), None) => {
+ self.start = Some(Start::new(&self.settings, Section::Recent));
+ path
+ }
+ (Picked::Run(Cmd::OpenDocument), None) if picker::NATIVE => {
+ let folder = self.settings.drawings_folder();
+ picker::choose_folder(Some(&folder), "Open").or(path)
+ }
+ (Picked::Run(Cmd::OpenDocument), None) => {
+ self.start = Some(Start::new(&self.settings, Section::Open));
+ path
+ }
+ (Picked::Run(Cmd::Quit), None) => {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ path
+ }
+ (Picked::Run(_), None) => path,
+ })
+ }
+
+ fn close(&mut self, ctx: &egui::Context) {
+ let Some(editor) = self.editor.take() else {
+ return;
+ };
+ self.settings = editor.settings.clone();
+ if let Some(path) = &self.settings_path
+ && let Err(e) = self.settings.save(path)
+ {
+ let mut start = Start::new(&self.settings, Section::Recent);
+ start.error = Some(format!("saving your settings: {e:#}"));
+ self.start = Some(start);
+ } else {
+ self.start = Some(Start::new(&self.settings, Section::Recent));
+ }
+ ctx.send_viewport_cmd(egui::ViewportCommand::Title(start::title(None)));
+ }
+
pub(crate) fn frame(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
+ self.tend_menus(&ctx);
+ let from_menu = self.picked(&ctx);
self.checked();
if self.checking.is_some() {
ctx.request_repaint_after(std::time::Duration::from_millis(200));
@@ -160,10 +244,13 @@ impl Home {
editor.update.clone_from(&self.update);
}
let mut chosen = None;
+ let mut closing = false;
match self.editor.as_mut() {
Some(editor) => {
editor.frame(ui);
match editor.wants.take() {
+ Some(Want::Close) => closing = true,
+ Some(Want::Path(path)) => chosen = Some(path),
Some(Want::New) => self.start = Some(Start::new(&editor.settings, Section::New)),
Some(Want::Recent) => self.start = Some(Start::new(&editor.settings, Section::Recent)),
Some(Want::Open) if picker::NATIVE => {
@@ -245,7 +332,10 @@ impl Home {
}
}
}
- if let Some(path) = chosen.or_else(crate::opened::take)
+ if closing {
+ self.close(&ctx);
+ }
+ if let Some(path) = chosen.or(from_menu).or_else(crate::opened::take)
&& let Err(e) = self.open(&ctx, &path)
{
let message = format!("opening {}: {e:#}", path.display());
@@ -390,6 +480,35 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn menu_picks_open_a_drawing_run_its_commands_and_close_it() {
+ let dir = folder("menus");
+ let made = dir.join("ledge.klad");
+ Bundle::blank(&made, &small(), "cli").unwrap();
+ let mut first = home(&dir, &[]);
+ first.begin(&egui::Context::default(), None);
+ let mut h = harness(first);
+ menus::push(Picked::Run(Cmd::Undo));
+ menus::push(Picked::Run(Cmd::OpenRecent));
+ h.run_steps(2);
+ assert!(
+ h.state().editor.is_none(),
+ "outside a drawing only the file commands run"
+ );
+ menus::push(Picked::Open(made.clone()));
+ h.run_steps(3);
+ assert_eq!(opened(&h), made);
+ let state = h.state().editor.as_ref().unwrap().menu_state();
+ assert!(state.off.contains(&Cmd::Unlink) && !state.off.contains(&Cmd::Export));
+ assert!(state.on.contains(&Cmd::Brush), "the tool in use is ticked");
+ menus::push(Picked::Run(Cmd::CloseDocument));
+ h.run_steps(3);
+ assert!(h.state().editor.is_none(), "close goes back to the start window");
+ assert!(h.state().start.is_some());
+ assert_eq!(h.state().settings.documents, [made.display().to_string()]);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn a_new_version_shows_in_the_start_window_with_what_changed() {
let dir = folder("update");
diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs
index 2009215..9405fa3 100644
--- a/crates/app/src/lib.rs
+++ b/crates/app/src/lib.rs
@@ -8,6 +8,7 @@ mod home;
mod jobs;
mod layout;
mod lift;
+mod menus;
mod messages;
mod opened;
mod pen;
diff --git a/crates/app/src/menus.rs b/crates/app/src/menus.rs
new file mode 100644
index 0000000..ed62c82
--- /dev/null
+++ b/crates/app/src/menus.rs
@@ -0,0 +1,432 @@
+use crate::commands::Cmd;
+#[cfg(any(target_os = "macos", test))]
+use crate::commands::Item;
+use std::cell::RefCell;
+use std::collections::BTreeSet;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+pub enum Picked {
+ Run(Cmd),
+ Open(PathBuf),
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Shown {
+ pub off: BTreeSet<Cmd>,
+ pub on: BTreeSet<Cmd>,
+}
+
+thread_local! {
+ static QUEUE: RefCell<Vec<Picked>> = const { RefCell::new(Vec::new()) };
+ static SHOWN: RefCell<Shown> = const {
+ RefCell::new(Shown {
+ off: BTreeSet::new(),
+ on: BTreeSet::new(),
+ })
+ };
+}
+
+static NATIVE: AtomicBool = AtomicBool::new(false);
+
+pub const RECENT: usize = 10;
+pub const OUTSIDE_A_DRAWING: [Cmd; 4] = [Cmd::NewDocument, Cmd::OpenDocument, Cmd::OpenRecent, Cmd::Quit];
+
+pub fn native() -> bool {
+ NATIVE.load(Ordering::Relaxed)
+}
+
+#[cfg(any(target_os = "macos", test))]
+pub fn push(picked: Picked) {
+ QUEUE.with(|q| q.borrow_mut().push(picked));
+}
+
+pub fn take() -> Vec<Picked> {
+ QUEUE.with(|q| std::mem::take(&mut *q.borrow_mut()))
+}
+
+pub fn show(shown: Shown) {
+ SHOWN.with(|s| *s.borrow_mut() = shown);
+}
+
+#[cfg(any(target_os = "macos", test))]
+fn shown() -> Shown {
+ SHOWN.with(|s| s.borrow().clone())
+}
+
+pub fn outside_a_drawing() -> Shown {
+ Shown {
+ off: Cmd::ALL
+ .into_iter()
+ .filter(|c| !OUTSIDE_A_DRAWING.contains(c))
+ .collect(),
+ on: BTreeSet::new(),
+ }
+}
+
+pub fn recent_label(path: &Path) -> String {
+ let name = path
+ .file_stem()
+ .map_or_else(|| path.display().to_string(), |s| s.to_string_lossy().to_string());
+ match path.parent().and_then(Path::file_name) {
+ Some(folder) => format!("{name} ({})", folder.to_string_lossy()),
+ None => name,
+ }
+}
+
+#[cfg(any(target_os = "macos", test))]
+pub fn tidy(items: &[Item], keep: impl Fn(&Item) -> bool) -> Vec<Item> {
+ let kept: Vec<Item> = items.iter().copied().filter(|i| keep(i)).collect();
+ kept.iter()
+ .enumerate()
+ .filter(|(i, item)| **item != Item::Line || (*i > 0 && *i + 1 < kept.len() && kept[i - 1] != Item::Line))
+ .map(|(_, item)| *item)
+ .collect()
+}
+
+pub fn signature(keys: &std::collections::BTreeMap<String, Vec<String>>, recent: &[String]) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ keys.hash(&mut hasher);
+ recent.iter().take(RECENT).for_each(|r| r.hash(&mut hasher));
+ hasher.finish()
+}
+
+#[cfg(target_os = "macos")]
+pub use mac::install;
+
+#[cfg(not(target_os = "macos"))]
+pub fn install(_ctx: &egui::Context, _bindings: &crate::commands::Bindings, _recent: &[String]) {}
+
+#[cfg(target_os = "macos")]
+mod mac {
+ use super::{Picked, RECENT, push, recent_label, shown, tidy};
+ use crate::commands::{Bindings, Cmd, IN_APP_MENU, Item, Keys, MENUS, menu_label};
+ use egui::Key;
+ use objc2::rc::Retained;
+ use objc2::runtime::{ProtocolObject, Sel};
+ use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
+ use objc2_app_kit::{
+ NSApplication, NSControlStateValueOff, NSControlStateValueOn, NSEvent, NSEventModifierFlags, NSMenu,
+ NSMenuDelegate, NSMenuItem,
+ };
+ use objc2_foundation::{NSObject, NSObjectProtocol, NSString};
+ use std::cell::RefCell;
+ use std::ffi::c_void;
+ use std::path::PathBuf;
+ use std::sync::OnceLock;
+ use std::sync::atomic::Ordering;
+
+ static CTX: OnceLock<egui::Context> = OnceLock::new();
+ const RECENT_TAG: isize = 100_000;
+
+ thread_local! {
+ static TARGET: RefCell<Option<Retained<Target>>> = const { RefCell::new(None) };
+ static PATHS: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
+ }
+
+ define_class!(
+ #[unsafe(super(NSObject))]
+ #[thread_kind = MainThreadOnly]
+ #[name = "KladMenuTarget"]
+ struct Target;
+
+ impl Target {
+ #[unsafe(method(kladRun:))]
+ fn run(&self, item: &NSMenuItem) {
+ let tag = item.tag();
+ let picked = match tag {
+ t if t >= RECENT_TAG => PATHS.with(|p| p.borrow().get((t - RECENT_TAG) as usize).cloned().map(Picked::Open)),
+ t => Cmd::ALL.get(t as usize).copied().map(Picked::Run),
+ };
+ if let Some(picked) = picked {
+ push(picked);
+ }
+ if let Some(ctx) = CTX.get() {
+ ctx.request_repaint();
+ }
+ }
+
+ #[unsafe(method(validateMenuItem:))]
+ fn validate(&self, item: &NSMenuItem) -> bool {
+ let cmd = usize::try_from(item.tag()).ok().and_then(|t| Cmd::ALL.get(t));
+ let now = shown();
+ if let Some(cmd) = cmd {
+ item.setState(match now.on.contains(cmd) {
+ true => NSControlStateValueOn,
+ false => NSControlStateValueOff,
+ });
+ }
+ cmd.is_none_or(|c| !now.off.contains(c))
+ }
+
+ #[unsafe(method(menuHasKeyEquivalent:forEvent:target:action:))]
+ fn has_key(&self, _menu: &NSMenu, _event: &NSEvent, _target: *mut c_void, _action: *mut c_void) -> bool {
+ false
+ }
+ }
+
+ unsafe impl NSObjectProtocol for Target {}
+
+ unsafe impl NSMenuDelegate for Target {}
+ );
+
+ impl Target {
+ fn new(mtm: MainThreadMarker) -> Retained<Self> {
+ let this = Self::alloc(mtm).set_ivars(());
+ unsafe { msg_send![super(this), init] }
+ }
+ }
+
+ fn key_text(key: Key) -> Option<String> {
+ let special = match key {
+ Key::Period => ".",
+ Key::Comma => ",",
+ Key::OpenBracket => "[",
+ Key::CloseBracket => "]",
+ Key::Equals => "=",
+ Key::Plus => "+",
+ Key::Minus => "-",
+ Key::Questionmark => "?",
+ Key::Num1 => "1",
+ Key::Enter => "\r",
+ Key::Escape => "\u{1b}",
+ Key::Tab => "\t",
+ Key::Backspace => "\u{8}",
+ Key::Delete => "\u{F728}",
+ Key::ArrowUp => "\u{F700}",
+ Key::ArrowDown => "\u{F701}",
+ Key::ArrowLeft => "\u{F702}",
+ Key::ArrowRight => "\u{F703}",
+ Key::Home => "\u{F729}",
+ Key::End => "\u{F72B}",
+ Key::F5 => "\u{F708}",
+ other => {
+ let name = other.name();
+ return (name.chars().count() == 1).then(|| name.to_lowercase());
+ }
+ };
+ Some(special.to_string())
+ }
+
+ fn equivalent(keys: &[Keys]) -> (String, NSEventModifierFlags) {
+ keys.iter()
+ .find(|k| k.key == Key::Backspace)
+ .or(keys.first())
+ .and_then(|k| {
+ let text = key_text(k.key)?;
+ let mut mask = NSEventModifierFlags::empty();
+ [
+ (k.command, NSEventModifierFlags::Command),
+ (k.shift, NSEventModifierFlags::Shift),
+ (k.alt, NSEventModifierFlags::Option),
+ ]
+ .into_iter()
+ .filter(|(on, _)| *on)
+ .for_each(|(_, flag)| mask |= flag);
+ Some((text, mask))
+ })
+ .unwrap_or_else(|| (String::new(), NSEventModifierFlags::empty()))
+ }
+
+ fn item(
+ mtm: MainThreadMarker,
+ title: &str,
+ action: Option<Sel>,
+ key: &str,
+ mask: NSEventModifierFlags,
+ ) -> Retained<NSMenuItem> {
+ let item = unsafe {
+ NSMenuItem::initWithTitle_action_keyEquivalent(
+ NSMenuItem::alloc(mtm),
+ &NSString::from_str(title),
+ action,
+ &NSString::from_str(key),
+ )
+ };
+ item.setKeyEquivalentModifierMask(mask);
+ item
+ }
+
+ fn command(mtm: MainThreadMarker, target: &Target, cmd: Cmd, bindings: &Bindings) -> Retained<NSMenuItem> {
+ let (key, mask) = equivalent(&bindings.keys(cmd));
+ let entry = item(mtm, &menu_label(cmd), Some(sel!(kladRun:)), &key, mask);
+ unsafe { entry.setTarget(Some(target)) };
+ entry.setTag(Cmd::ALL.iter().position(|c| *c == cmd).unwrap_or_default() as isize);
+ entry
+ }
+
+ fn menu(mtm: MainThreadMarker, title: &str, target: Option<&Target>) -> Retained<NSMenu> {
+ let menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title));
+ if let Some(target) = target {
+ menu.setDelegate(Some(ProtocolObject::from_ref(target)));
+ }
+ menu
+ }
+
+ fn holding(mtm: MainThreadMarker, sub: &NSMenu) -> Retained<NSMenuItem> {
+ let holder = item(mtm, &sub.title().to_string(), None, "", NSEventModifierFlags::empty());
+ holder.setSubmenu(Some(sub));
+ holder
+ }
+
+ fn fill(
+ mtm: MainThreadMarker,
+ into: &NSMenu,
+ items: &[Item],
+ target: &Target,
+ bindings: &Bindings,
+ recent: &[String],
+ ) {
+ tidy(items, |i| !matches!(i, Item::Run(c) if IN_APP_MENU.contains(c)))
+ .into_iter()
+ .for_each(|entry| match entry {
+ Item::Line => into.addItem(&NSMenuItem::separatorItem(mtm)),
+ Item::Run(cmd) => into.addItem(&command(mtm, target, cmd, bindings)),
+ Item::Sub(title, inner) => {
+ let sub = menu(mtm, title, Some(target));
+ fill(mtm, &sub, inner, target, bindings, recent);
+ into.addItem(&holding(mtm, &sub));
+ }
+ Item::Recent => {
+ let sub = menu(mtm, "Open recent", Some(target));
+ let paths: Vec<PathBuf> = recent.iter().take(RECENT).map(PathBuf::from).collect();
+ paths.iter().enumerate().for_each(|(i, path)| {
+ let entry = item(
+ mtm,
+ &recent_label(path),
+ Some(sel!(kladRun:)),
+ "",
+ NSEventModifierFlags::empty(),
+ );
+ unsafe { entry.setTarget(Some(target)) };
+ entry.setTag(RECENT_TAG + i as isize);
+ sub.addItem(&entry);
+ });
+ if !paths.is_empty() {
+ sub.addItem(&NSMenuItem::separatorItem(mtm));
+ }
+ sub.addItem(&command(mtm, target, Cmd::OpenRecent, bindings));
+ PATHS.with(|p| *p.borrow_mut() = paths);
+ into.addItem(&holding(mtm, &sub));
+ }
+ });
+ }
+
+ fn system(
+ mtm: MainThreadMarker,
+ title: &str,
+ action: Sel,
+ key: &str,
+ mask: NSEventModifierFlags,
+ ) -> Retained<NSMenuItem> {
+ item(mtm, title, Some(action), key, mask)
+ }
+
+ pub fn install(ctx: &egui::Context, bindings: &Bindings, recent: &[String]) {
+ let Some(mtm) = MainThreadMarker::new() else {
+ return;
+ };
+ let _ = CTX.set(ctx.clone());
+ let target = TARGET.with(|t| t.borrow_mut().get_or_insert_with(|| Target::new(mtm)).clone());
+ let app = NSApplication::sharedApplication(mtm);
+ let bar = menu(mtm, "", None);
+ let klad = menu(mtm, "klad", None);
+ let services = menu(mtm, "Services", None);
+ let command = NSEventModifierFlags::Command;
+ klad.addItem(&self::command(mtm, &target, Cmd::About, bindings));
+ klad.addItem(&NSMenuItem::separatorItem(mtm));
+ klad.addItem(&self::command(mtm, &target, Cmd::Settings, bindings));
+ klad.addItem(&NSMenuItem::separatorItem(mtm));
+ klad.addItem(&holding(mtm, &services));
+ klad.addItem(&NSMenuItem::separatorItem(mtm));
+ klad.addItem(&system(mtm, "Hide klad", sel!(hide:), "h", command));
+ klad.addItem(&system(
+ mtm,
+ "Hide others",
+ sel!(hideOtherApplications:),
+ "h",
+ command | NSEventModifierFlags::Option,
+ ));
+ klad.addItem(&system(
+ mtm,
+ "Show all",
+ sel!(unhideAllApplications:),
+ "",
+ NSEventModifierFlags::empty(),
+ ));
+ klad.addItem(&NSMenuItem::separatorItem(mtm));
+ klad.addItem(&self::command(mtm, &target, Cmd::Quit, bindings));
+ bar.addItem(&holding(mtm, &klad));
+ let window = menu(mtm, "Window", None);
+ window.addItem(&system(mtm, "Minimize", sel!(performMiniaturize:), "m", command));
+ window.addItem(&system(
+ mtm,
+ "Zoom",
+ sel!(performZoom:),
+ "",
+ NSEventModifierFlags::empty(),
+ ));
+ window.addItem(&NSMenuItem::separatorItem(mtm));
+ window.addItem(&system(
+ mtm,
+ "Bring all to front",
+ sel!(arrangeInFront:),
+ "",
+ NSEventModifierFlags::empty(),
+ ));
+ MENUS.iter().for_each(|m| {
+ if m.title == "Help" {
+ bar.addItem(&holding(mtm, &window));
+ }
+ let built = menu(mtm, m.title, Some(&target));
+ fill(mtm, &built, m.items, &target, bindings, recent);
+ bar.addItem(&holding(mtm, &built));
+ if m.title == "Help" {
+ app.setHelpMenu(Some(&built));
+ }
+ });
+ app.setMainMenu(Some(&bar));
+ app.setServicesMenu(Some(&services));
+ app.setWindowsMenu(Some(&window));
+ super::NATIVE.store(true, Ordering::Relaxed);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::commands::{IN_APP_MENU, MENUS, in_menus};
+
+ #[test]
+ fn tidy_drops_separators_at_the_ends_and_twice_in_a_row() {
+ let file = MENUS[0].items;
+ let mac = tidy(file, |i| !matches!(i, Item::Run(c) if IN_APP_MENU.contains(c)));
+ assert_ne!(
+ mac.last(),
+ Some(&Item::Line),
+ "quit moved out leaves no line at the end"
+ );
+ assert!(mac.windows(2).all(|w| w != [Item::Line, Item::Line]));
+ assert_eq!(tidy(file, |_| true).len(), file.len());
+ assert!(!in_menus(&mac).contains(&Cmd::Quit));
+ }
+
+ #[test]
+ fn picks_queue_up_until_taken_and_outside_a_drawing_only_files_run() {
+ push(Picked::Run(Cmd::Export));
+ push(Picked::Open(PathBuf::from("/w/a.klad")));
+ assert_eq!(
+ take(),
+ [Picked::Run(Cmd::Export), Picked::Open(PathBuf::from("/w/a.klad"))]
+ );
+ assert!(take().is_empty());
+ let outside = outside_a_drawing();
+ assert!(outside.off.contains(&Cmd::Undo) && !outside.off.contains(&Cmd::NewDocument));
+ show(outside.clone());
+ assert_eq!(shown(), outside);
+ assert_eq!(recent_label(Path::new("/w/rocks/ledge.klad")), "ledge (rocks)");
+ }
+}
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
index 89c9b5b..9aca5ba 100644
--- a/docs/DESIGN.md
+++ b/docs/DESIGN.md
@@ -1,4 +1,4 @@
-_Last updated: 2026-11-06 16:56_
+_Last updated: 2026-11-06 17:17_
# klad: design
@@ -434,6 +434,7 @@ Scripts are any language that prints edit ops as JSON lines into `klad apply`. G
- Layout (M4 batch 1): a tool strip on the left (the tools with their key letter, undo and redo, and at its foot settings, numbers and the command palette); a dock on the right holding panes (colour and brush, layers, inspector, notes for the agent, history), each with a title row that folds it, closes it and, dragged at its top edge, resizes the pane above; the timeline along the bottom, resizable and foldable to its toolbar; a status line under everything. Panes share the dock's height: they keep the sizes the user gave them, the last open one takes what is left, and when they do not fit they shrink towards their minimums and scroll inside (`layout::Layout::bodies`). Tab hides every panel but the status line, shift Tab the dock. Which panels are open, the dock's width, the timeline's height and each pane's size are kept in the user's settings (`layout`) and restored, clamped to the window. Pen calibration lives in the settings window (cmd ,); the performance numbers in a numbers window that can stay open over the canvas.
- Commands (M4 batch 1): every editor action is a `Cmd` in one list (`commands.rs`): an id (`tool.brush`, `drawing.new`, kept in settings), a name in plain words, a Phosphor icon, a group, its keys or the hold that triggers it, whether a held key repeats it, and a line on what it does. Keys, the strip, panel buttons, the timeline's buttons and context menu, and the palette all run commands through `Editor::invoke`, which first asks `can_run` (a reason when it cannot, shown as a refusal) and remembers the last twelve run. A key matches only with exactly its modifiers (shift K is not K); key repeats run commands that repeat (`=`, `[`, cmd Z) and frame steps only once the frame on screen caught up. cmd K opens the palette: type to filter (name start, then a key, a word, a substring, the letters in order, the group; hyphens ignored, so "inb" finds in-between), arrows and Return run, rows grey out with the reason, recent commands first; `?` opens it too. Every control has a hover hint after 0.35 s (from its command where there is one) and is at least 24 pt high; a test walks every control of every panel and window to keep it so.
- Tool options and selections (M4 batch 2): a bar over the canvas holds the active tool's settings (brush: picker, size, opacity, flow, and a "more" menu for hardness, lightest size, curve, taper, stabiliser and smoothing; fill: reference, gap, tolerance, grow, opacity; strokes: cut at the lasso edge, select all; points: corner, smooth, simplify, make it a path). The strip shows the eraser while the eraser brush or the pen's eraser end is on, and two colours (the current one over the second; X or a click swaps them; picking a colour from a swatch, the hex field or the eyedropper makes the old one the second). cmd alt drag sideways on the canvas sizes the brush (doubling every 120 pt), the circle staying where the drag began. H flips the view left-right (the view's mappings and the GPU matrix mirror; the document does not change); the status line's zoom takes a click for 100% and a double-click to fit, its rotation a click to turn upright. A selection bar sits under (or over) the selection's box: for strokes flips, quarter turns, recolour, thinner, thicker, opacity, copy, paste, duplicate in place, delete, deselect; for a shape flips (sx or sy negated and its rotation mirrored), quarter turns, duplicate in place (an `add` of the node without ids, above it), delete, deselect; for points corner, smooth, nudges, delete. Arrows nudge strokes, a shape or points by 1 px, 10 px with shift. Strokes select across layers (M5 batch 2 round 1): cmd or shift click on rows in the layers panel adds paint layers to the active one (marked with a blue edge); S then lassos, clicks and selects all on all of them, and the selection (one part per layer) moves, turns, scales, flips, recolours, cuts at the lasso edge, copies and deletes as one edit, each layer's marks staying on their layer. A selection on several layers drags as its outline (no GPU lift) and lands on release; copies of several layers paste back into their own layers, a copy of one layer into the active one. The strip's panels button lists the five panels and the timeline with a tick each, so a closed panel always has a way back. U draws rectangles and ellipses on a vector layer (shift for a square or circle, alt from the centre, rounded corners for rectangles; fill, outline and width shared with the pen, the fill in the first colour and the outline in the second, as for the pen's paths) as `rect` and `ellipse` nodes. Mirror painting (the brush bar's "mirror" and its axis) paints every stroke's mirror image as it is drawn, in a second stroke buffer landed after the first, and commits both as plain marks in one history step. Handles are drawn at 12 pt and hit within 12 pt (`grab`); shapes whose rotation is a quarter turn get edge handles too (`lift::stretched` scales their own axis). Pen events that arrive while a shape move or point edit is being written are held and replayed in order after it. The colour and brush pane shows the palette (swatches drag to reorder; the x in a hovered swatch's corner, or a right-click, removes it), recent colours, size presets and the brushes as tiles, each with a sample stroke drawn by `klad-brush` once per brush definition.
+- Menus (S8.6, `commands::MENUS`, `menus.rs`): one list of menus (File, Edit, Draw, View, Layer, Frame, Help) holds every command but the holds (pan, zoom, the eyedropper, flipping, rolling, the parallax preview and sizing on the canvas, which are gestures), so the menus, the palette and the keys stay one list; a test fails when a command is in no menu or in two. Items are the commands' names with their first letter capitalised and their keys; toggles show a tick; a command that cannot run now is greyed out (its reason is the palette's). On macOS the list becomes the system menu bar (`menus::install`, rebuilt when the keys or the recent drawings change): an app menu with About, Settings, Services, hide and Quit, then the list, Window and Help. Items target one Objective-C object (`KladMenuTarget`, `define_class!`) whose `kladRun:` queues the command for the next frame (the editor runs it through `Editor::invoke` as any key would) and whose `validateMenuItem:` reads a snapshot of what is off and on that the app refreshes every 0.4 s. The item keys are shown but not claimed: the object is each menu's delegate and answers no to `menuHasKeyEquivalent:forEvent:target:action:`, so a key still reaches the editor's own dispatch (which knows holds, repeats and text fields) and nothing runs twice; only the app menu's own keys (cmd , cmd Q cmd H) and Window's cmd M are AppKit's. On Windows and Linux (and in tests) the same list is an egui menu bar over the window, hidden with the panels (Tab). File > Open recent lists the last ten drawings; File > Close the drawing (cmd W, refused while a job runs) goes back to the start window, where only new, open, recent and quit run. Settings, About and Quit sit in the app menu on macOS and in Edit, Help and File elsewhere.
- Messages and jobs (M4 batch 1): every result, refusal and error goes through `Editor::say` with a tone (info, done, refused, error). Done and refused messages show for 3.5 and 6 s as a toast next to the pointer where the user acted (jobs' messages at the bottom right), errors until dismissed, info only in the status line; the status line shows the latest message (a click opens the message log, the last 200 with times), the frame, where the next stroke goes ("draws into c12 on lines, frames 4 to 7"), running jobs with a cancel button, slow internal work (preparing a selection, drawing an edited path, loading a frame), zoom and rotation. Times that used to be status text (stroke, fill, edit, undo, sync, frame step, last play, last job) are kept by name for the numbers window. Background jobs (in-betweens, Godot export) run the same `klad` binary through one job list (`jobs.rs`); when the CLI exits with code 75 (the document changed while it computed) the job runs again, up to three times, so an edit made in the editor meanwhile is never overwritten.
- Tools: brush, eraser, smudge, fill (inside lines, gap closing), lasso select and transform, move/rotate/scale handles, path point editing, eyedropper.
- Stroke select (S, M2): click picks the topmost stroke or fill on the active paint layer under the pointer, a dragged loop picks every stroke whose samples are all inside it and every fill whose pixels are, shift adds or toggles. With "a lasso cuts strokes at its edge" (on by default) the loop also takes the parts of strokes and fills crossing it: the selection shows the dashed lasso and the parts that will move, and the first edit (move, recolour, delete, ...) writes one `lasso` op that splits them, after which the selection is the moved marks. The selection shows as thin lines and a box with corner handles (uniform scale), edge handles (stretch one axis; dragging past the other edge flips) and a rotate knob; dragging moves it on the GPU (the selected marks drawn alone, over the cel replayed without them) and release writes one `transform` or `lasso` op. The inspector recolours (the current colour), makes thinner or thicker, sets opacity, flips left-right or up-down and deletes, each as one history step. The selection is shared with the agent as addresses.