Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Window menu: list the open documents, the active one checked (#2991) (#3147)

Brennan Stehling16bdcbd54e5d
diff --git a/apps/photocraft/src/mac_menu.rs b/apps/photocraft/src/mac_menu.rs
index 648595ad4..f8a7c8c68 100644
--- a/apps/photocraft/src/mac_menu.rs
+++ b/apps/photocraft/src/mac_menu.rs
@@ -5,13 +5,15 @@
//! - Item ids are command ids; a command in two menus (Keyboard Shortcuts is in Edit and Window)
//! gets `id#2` for its second copy, as muda ids must be unique.
//! - A structure change (a new Open Recent file, a language switch) rebuilds the menu; anything
-//! else (labels, enabled, checked) is updated in place.
+//! else (labels, enabled, checked) is updated in place. Opening or closing a document rebuilds
+//! only the Window menu, whose list of documents changed: AppKit adds its own items to that
+//! menu (window tiling, the window list), so muda can't insert rows there by position.
//! - A chosen item is a click or a key equivalent: AppKit's current event says which. Key
//! equivalents go back to egui as the key press that was made (the event's modifiers, not the
//! item's: AppKit may match ⌘R to a ⇧⌘R item), so PhotoCraft's key rules still apply.
//! - Hide is a custom item calling `NSApplication hide:`, as the predefined one always takes ⌘H.
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::mpsc::{Receiver, channel};
use muda::accelerator::{Accelerator, Code, Modifiers};
@@ -49,6 +51,8 @@ pub struct MacMenu {
entries: HashMap<String, Entry>,
rx: Receiver<Chosen>,
structure: u64,
+ /// The Window menu, the muda ids of its items, and its [`native_menu::window_key`].
+ window: Option<(Submenu, Vec<String>, u64)>,
}
impl MacMenu {
@@ -67,7 +71,7 @@ impl MacMenu {
// Wake egui, so the item runs now rather than on the next mouse move.
repaint.request_repaint();
}));
- MacMenu { menu: None, entries: HashMap::new(), rx, structure: 0 }
+ MacMenu { menu: None, entries: HashMap::new(), rx, structure: 0, window: None }
}
fn build(&mut self, bar: &MenuBar) {
@@ -75,12 +79,15 @@ impl MacMenu {
old.remove_for_nsapp();
}
self.entries.clear();
+ self.window = None;
let menu = Menu::new();
let mut special = Vec::new();
for m in &bar.menus {
- let sub = Submenu::new(escape(&m.title), true);
- self.append(&sub, &m.children);
+ let (sub, ids) = self.submenu(m);
let _ = menu.append(&sub);
+ if m.role == MenuRole::Window {
+ self.window = Some((sub.clone(), ids, native_menu::window_key(bar)));
+ }
if matches!(m.role, MenuRole::Window | MenuRole::Help) {
special.push((m.role, sub));
}
@@ -97,6 +104,33 @@ impl MacMenu {
self.structure = native_menu::structure_key(bar);
}
+ /// A top-level menu, and the muda ids of the items it added.
+ fn submenu(&mut self, m: &native_menu::Menu) -> (Submenu, Vec<String>) {
+ let before: HashSet<String> = self.entries.keys().cloned().collect();
+ let sub = Submenu::new(escape(&m.title), true);
+ self.append(&sub, &m.children);
+ let ids = self.entries.keys().filter(|id| !before.contains(*id)).cloned().collect();
+ (sub, ids)
+ }
+
+ /// Replace the Window menu (a document opened or closed), leaving the other menus as they are.
+ fn rebuild_window(&mut self, bar: &MenuBar) {
+ let (Some(menu), Some((old, ids, _))) = (self.menu.clone(), self.window.take()) else { return self.build(bar) };
+ let Some((at, spec)) = bar.menus.iter().enumerate().find(|(_, m)| m.role == MenuRole::Window) else { return self.build(bar) };
+ if menu.remove(&old).is_err() {
+ return self.build(bar);
+ }
+ for id in ids {
+ self.entries.remove(&id);
+ }
+ let (sub, ids) = self.submenu(spec);
+ if menu.insert(&sub, at).is_err() {
+ return self.build(bar);
+ }
+ sub.set_as_windows_menu_for_nsapp();
+ self.window = Some((sub, ids, native_menu::window_key(bar)));
+ }
+
fn append(&mut self, sub: &Submenu, nodes: &[Node]) {
for n in nodes {
match n {
@@ -160,6 +194,9 @@ impl Backend for MacMenu {
self.build(bar);
return;
}
+ if self.window.as_ref().map(|w| w.2) != Some(native_menu::window_key(bar)) {
+ self.rebuild_window(bar);
+ }
let items: HashMap<&str, &native_menu::Item> = bar.items().into_iter().map(|it| (it.id.as_str(), it)).collect();
for e in self.entries.values_mut() {
let Some(it) = items.get(e.command.as_str()) else { continue };
diff --git a/apps/photocraft/tests/mac_menu_appkit.rs b/apps/photocraft/tests/mac_menu_appkit.rs
index 401cc7c0e..feacb4bd3 100644
--- a/apps/photocraft/tests/mac_menu_appkit.rs
+++ b/apps/photocraft/tests/mac_menu_appkit.rs
@@ -165,6 +165,31 @@ fn main() {
frame(&mut app, raw);
assert_eq!(app.ui.extras.rulers, !rulers, "↩ on Rulers toggled it");
+ // Window ends with the open documents (#2991). Opening one rebuilds only the Window menu,
+ // which AppKit still knows as its Window menu; choosing a row brings that document forward.
+ app.run("file.new", json!({"width": 32, "height": 32})).expect("a second document");
+ frame(&mut app, egui::RawInput::default());
+ assert!(Retained::as_ptr(&bar) == Retained::as_ptr(&main_menu()), "a new document rebuilt only the Window menu");
+ let window = submenu(&main_menu(), "Window");
+ assert!(nsapp.windowsMenu().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)), "AppKit knows the new Window menu");
+ let names: Vec<String> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
+ // The last rows (both documents are "Untitled").
+ let rows = [window.numberOfItems() - 2, window.numberOfItems() - 1];
+ let shown: Vec<String> = rows.iter().filter_map(|&i| window.itemAtIndex(i)).map(|it| it.title().to_string()).collect();
+ assert_eq!(shown, names, "in tab order, after Bring All to Front: {:?}", titles(&window));
+ let checked = |menu: &NSMenu, at: isize| menu.itemAtIndex(at).is_some_and(|it| it.state() == 1);
+ assert!(!checked(&window, rows[0]) && checked(&window, rows[1]), "the active document is checked");
+ dequeue(&other());
+ window.performActionForItemAtIndex(rows[0]);
+ let mut raw = egui::RawInput::default();
+ if let Some(m) = app.services.native_menu.as_mut() {
+ m.raw_input(&mut raw);
+ }
+ frame(&mut app, raw);
+ assert_eq!(app.session.active_index(), Some(0), "choosing the first row brought it forward");
+ let window = submenu(&main_menu(), "Window");
+ assert!(checked(&window, rows[0]) && !checked(&window, rows[1]), "the check moved in place");
+
println!("mac_menu_appkit: ok");
}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index d5e55afae..2c79bb6e4 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -100,6 +100,10 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
("help.about", "About PhotoCraft", &["Help"], None),
];
+/// Window › <document>: the open documents, listed at the end of the Window menu as in Photoshop.
+/// The id ends in the document's index, which is its tab's position.
+pub(crate) const DOCUMENT_ITEM: &str = "window.document.";
+
/// Photoshop's Window › <panel> ids for the panels the shell already has, as `window.toggle.*`.
pub(crate) fn panel_alias(id: &str) -> Option<&'static str> {
Some(match id.strip_prefix("window.panel.")? {
@@ -588,6 +592,13 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
app.jobs.focus = None;
Ok(json!({"document": to}))
}
+ id if let Some(index) = id.strip_prefix(DOCUMENT_ITEM) => {
+ let n = app.session.documents().len();
+ let to = index.parse::<usize>().ok().filter(|i| *i < n).ok_or("no such document")?;
+ app.session.set_active(to);
+ app.jobs.focus = None;
+ Ok(json!({"document": to}))
+ }
t if t.starts_with("window.toggle.") => {
// A shown but collapsed dock group is expanded rather than hidden (#129).
if let Some(g) = crate::dock::Group::from_key(&t["window.toggle.".len()..]).filter(|g| g.shown(&app.ui.panels) && app.ui.dock.is_collapsed(*g)) {
@@ -667,6 +678,7 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
"window.panel.group" | "window.panel.move" | "window.panel.float" | "window.panel.dock" | "window.panel.close" => !app.session.prefs().workspace_locked,
"file.open" | "file.exit" | "file.clearRecent" | "file.removeRecent" | "help.about" | "help.systemInfo" | "edit.search" => true,
i if i.starts_with("file.openRecent.") => true,
+ i if i.starts_with(DOCUMENT_ITEM) => true,
i if crate::links::url_for(i).is_some() => true,
i if i.starts_with("window.theme.") => true,
"file.save" | "file.saveAs" | "file.export.exportAs" | "file.export.quickExportAsPng" => {
@@ -820,6 +832,10 @@ pub(crate) fn reveal_label() -> &'static str {
/// Translate the fixed command label and substitute the currently configured export format.
/// Reuse the existing translated PNG sentence, so dynamic formats work in every UI language.
fn translated_menu_label(lang: crate::i18n::Lang, item: &MenuItem) -> String {
+ // A document's name is shown as it is.
+ if item.id.starts_with(DOCUMENT_ITEM) {
+ return item.label.clone();
+ }
if item.id == "file.export.quickExportAsPng"
&& let Some(fmt) = item.label.strip_prefix("Quick Export as ")
{
@@ -988,6 +1004,25 @@ pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
MenuItem { id: "---".into(), label: "---".into(), path: vec!["Help".into()], shortcut: None, enabled: false, checked: None, color: None },
);
}
+ // Window: the open documents in tab order, after a separator, the active one checked.
+ if let Some(last) = items.iter().rposition(|i| i.path.first().map(String::as_str) == Some("Window")) {
+ let window = || vec!["Window".to_string()];
+ let active = app.session.active_index();
+ let docs = app.session.documents().iter().enumerate().map(|(i, st)| MenuItem {
+ id: format!("{DOCUMENT_ITEM}{i}"),
+ label: st.doc.name.clone(),
+ path: window(),
+ shortcut: None,
+ enabled: true,
+ checked: Some(active == Some(i)),
+ color: None,
+ });
+ let separator = MenuItem { id: "---".into(), label: "---".into(), path: window(), shortcut: None, enabled: false, checked: None, color: None };
+ let rows: Vec<MenuItem> = std::iter::once(separator).chain(docs).collect();
+ if rows.len() > 1 {
+ items.splice(last + 1..last + 1, rows);
+ }
+ }
// Edit › Keyboard Shortcuts overrides, Edit › Menus hidden items and colours.
let prefs = app.session.prefs();
if !prefs.shortcuts.is_empty() {
@@ -2022,3 +2057,88 @@ mod reveal_label_tests {
assert!(crate::menu_catalog::CATALOG.iter().any(|(_, label, _, i)| *i == id && *label == "Reveal in Finder"));
}
}
+
+#[cfg(test)]
+mod window_documents_tests {
+ use super::*;
+ use serde_json::json;
+
+ fn app(docs: usize) -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ for _ in 0..docs {
+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
+ }
+ app.sync_views();
+ app
+ }
+
+ /// The rows after Window's last own item: a separator and the documents.
+ fn listed(app: &PhotocraftApp) -> Vec<(String, String, Option<bool>)> {
+ let items = menu_items(app);
+ let window: Vec<&MenuItem> = items.iter().filter(|i| i.path == ["Window"]).collect();
+ let at = window.iter().position(|i| i.id.starts_with(DOCUMENT_ITEM)).unwrap_or(window.len());
+ if at > 0 && at < window.len() {
+ assert_eq!(window[at - 1].label, "---", "a separator comes before the documents");
+ }
+ window[at..].iter().map(|i| (i.id.clone(), i.label.clone(), i.checked)).collect()
+ }
+
+ /// #2991: Window ends with the open documents in tab order, the active one checked, as in
+ /// Photoshop; choosing one brings it to the front.
+ #[test]
+ fn the_window_menu_lists_the_open_documents_and_switches_between_them() {
+ assert!(listed(&app(0)).is_empty(), "no documents, no list (and no separator)");
+
+ let mut app = app(3);
+ let ctx = egui::Context::default();
+ let names: Vec<String> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
+ let row = |i: usize, active: bool| (format!("window.document.{i}"), names[i].clone(), Some(active));
+ assert_eq!(listed(&app), [row(0, false), row(1, false), row(2, true)]);
+ // It stays last in Window, after the panels.
+ let items = menu_items(&app);
+ let last = items.iter().rposition(|i| i.path.first().map(String::as_str) == Some("Window")).unwrap();
+ assert_eq!(items[last].id, "window.document.2");
+
+ assert_eq!(invoke(&mut app, &ctx, "window.document.0", json!({})).unwrap(), json!({"document": 0}));
+ assert_eq!(app.session.active_index(), Some(0));
+ assert_eq!(listed(&app), [row(0, true), row(1, false), row(2, false)]);
+
+ // A stale or malformed id (a document closed since the menu was built) is an error.
+ for id in ["window.document.3", "window.document.", "window.document.x", "window.document.-1"] {
+ assert!(is_enabled(&app, id), "{id}: rows are always enabled");
+ assert!(invoke(&mut app, &ctx, id, json!({})).is_err(), "{id}");
+ }
+ assert_eq!(app.session.active_index(), Some(0));
+ }
+
+ /// The rows show the document's name as it is, never a translation of it, and follow a
+ /// rename (Save As).
+ #[test]
+ fn document_names_are_shown_as_they_are_and_follow_a_rename() {
+ let mut app = app(1);
+ let before = crate::native_menu::state_hash(&app, None);
+ if let Some(d) = app.session.active_mut() {
+ d.saved_to("/tmp/Layers".into());
+ }
+ assert_ne!(crate::native_menu::state_hash(&app, None), before, "a rename updates the native menu");
+ let de = crate::i18n::Lang::from_code("de").unwrap();
+ let items = menu_items(&app);
+ let row = items.iter().find(|i| i.id == "window.document.0").unwrap();
+ assert_eq!(translated_menu_label(de, row), "Layers");
+ let bar = crate::native_menu::photocraft_layout(&items, de, "de").bar;
+ assert_eq!(bar.find("window.document.0").map(|i| i.label.as_str()), Some("Layers"));
+ let panel = items.iter().find(|i| i.path == ["Window"] && i.label == "Layers").unwrap();
+ assert_eq!(bar.find(&panel.id).map(|i| i.label.as_str()), Some("Ebenen"), "Window › Layers is still translated");
+ }
+
+ /// The rows go through the control channel's `ui.menu.invoke`, like a click.
+ #[test]
+ fn control_can_choose_a_document_from_the_window_menu() {
+ let mut app = app(2);
+ let ctx = egui::Context::default();
+ let (req, _rx) = crate::control::ControlRequest::new("ui.menu.invoke", json!({"id": "window.document.0"}));
+ let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("expected an immediate reply") };
+ assert_eq!(r["ok"], true, "{r}");
+ assert_eq!(app.session.active_index(), Some(0));
+ }
+}
diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs
index 6ee60bf3f..e76c20eec 100644
--- a/crates/ui-egui/src/native_menu.rs
+++ b/crates/ui-egui/src/native_menu.rs
@@ -7,7 +7,8 @@
//! Appearance (Window › Theme), Services, Hide, Hide Others, Show All and Quit (File › Exit,
//! still the app's own `file.exit` so the unsaved-changes prompt runs). The other Craft apps
//! use the same app menu;
-//! - **Window** gets Minimize, Zoom and Bring All to Front, and **Help** the system search field;
+//! - **Window** gets Minimize, Zoom and Bring All to Front, with the open documents after it
+//! (where a Mac app lists its windows), and **Help** the system search field;
//! - **clashes** with the system's keys (⌘H, ⌘M, ⌘W, ⌘,) are resolved in PhotoCraft's favour, and
//! reported; Hide and Minimize move to ⌃⌘H and ⌃⌘M, as Photoshop does.
//!
@@ -237,30 +238,55 @@ fn tidy(nodes: Vec<Node>) -> Vec<Node> {
/// A hash of everything a native menu can only change by rebuilding: menus, roles, item ids,
/// kinds (plain or check), shortcuts and submenu labels. Labels, enabled and checked are updated
-/// in place.
+/// in place. Window's list of open documents is left out: opening or closing a document rebuilds
+/// only the Window menu ([`window_key`]).
pub fn structure_key(bar: &MenuBar) -> u64 {
- fn walk(nodes: &[Node], h: &mut DefaultHasher) {
- for n in nodes {
- match n {
- Node::Item(it) => ('i', &it.id, it.checked.is_some(), &it.shortcut, it.role).hash(h),
- Node::Separator => '-'.hash(h),
- Node::Submenu { label, children, role } => {
- ('[', label, role).hash(h);
- walk(children, h);
- ']'.hash(h);
- }
- Node::Standard(s) => ('s', s).hash(h),
+ let mut h = DefaultHasher::new();
+ for m in &bar.menus {
+ (&m.title, m.role).hash(&mut h);
+ if m.role == MenuRole::Window {
+ let mut rest: Vec<Node> = m.children.iter().filter(|n| !is_document(n)).cloned().collect();
+ while matches!(rest.last(), Some(Node::Separator)) {
+ rest.pop();
}
+ hash_nodes(&rest, &mut h);
+ } else {
+ hash_nodes(&m.children, &mut h);
}
}
+ h.finish()
+}
+
+/// The Window menu's structure, its open documents included: when it changes and nothing else
+/// did, a native menu rebuilds just the Window menu.
+pub fn window_key(bar: &MenuBar) -> u64 {
let mut h = DefaultHasher::new();
- for m in &bar.menus {
- (&m.title, m.role).hash(&mut h);
- walk(&m.children, &mut h);
+ if let Some(m) = bar.menu(MenuRole::Window) {
+ hash_nodes(&m.children, &mut h);
}
h.finish()
}
+/// Window › <document> (see [`crate::menus::DOCUMENT_ITEM`]).
+fn is_document(n: &Node) -> bool {
+ matches!(n, Node::Item(it) if it.id.starts_with(crate::menus::DOCUMENT_ITEM))
+}
+
+fn hash_nodes(nodes: &[Node], h: &mut DefaultHasher) {
+ for n in nodes {
+ match n {
+ Node::Item(it) => ('i', &it.id, it.checked.is_some(), &it.shortcut, it.role).hash(h),
+ Node::Separator => '-'.hash(h),
+ Node::Submenu { label, children, role } => {
+ ('[', label, role).hash(h);
+ hash_nodes(children, h);
+ ']'.hash(h);
+ }
+ Node::Standard(s) => ('s', s).hash(h),
+ }
+ }
+}
+
// ----------------------------------------------------------------------------- shortcuts
/// A shortcut as PhotoCraft writes it (`Cmd+Shift+Z`). `Cmd` is ⌘ and `Ctrl` the Control key,
@@ -447,9 +473,11 @@ pub fn mac_layout(bar: &MenuBar, lang: Lang) -> Layout {
None => Node::Standard(Standard::Minimize),
};
if let Some(window) = bar.menus.iter_mut().find(|m| m.role == MenuRole::Window) {
+ let (docs, rest): (Vec<Node>, Vec<Node>) = std::mem::take(&mut window.children).into_iter().partition(is_document);
let mut children = vec![minimize, Node::Standard(Standard::Zoom), Node::Separator];
- children.append(&mut window.children);
- children.extend([Node::Separator, Node::Standard(Standard::BringAllToFront)]);
+ children.extend(rest);
+ children.extend([Node::Separator, Node::Standard(Standard::BringAllToFront), Node::Separator]);
+ children.extend(docs);
window.children = children;
}
@@ -549,7 +577,8 @@ fn translate(bar: &mut MenuBar, lang: Lang) {
fn walk(nodes: &mut [Node], lang: Lang) {
for n in nodes {
match n {
- Node::Item(it) if it.role.is_none() => it.label = tr_id(lang, &it.id, &it.label).to_string(),
+ // A document's name is shown as it is.
+ Node::Item(it) if it.role.is_none() && !it.id.starts_with(crate::menus::DOCUMENT_ITEM) => it.label = tr_id(lang, &it.id, &it.label).to_string(),
Node::Submenu { label, children, role } => {
if role.is_none() {
*label = tr(lang, label).to_string();
@@ -710,7 +739,8 @@ pub(crate) fn had_input(ctx: &egui::Context) -> bool {
ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. } | egui::Event::PointerButton { pressed: false, .. })))
}
-/// What the menus' rows depend on, cheaply: commands run, the documents and their revisions,
+/// What the menus' rows depend on, cheaply: commands run, the documents (their names, in tab
+/// order, for the Window menu) and the active one's revision,
/// selection, recent files, panels and view state, the language. `input` forces a change on
/// frames with a click or key press, which covers state the hash doesn't list.
pub(crate) fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
@@ -719,6 +749,9 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
let s = &app.session;
s.journal.len().hash(&mut h);
s.active_index().hash(&mut h);
+ for d in s.documents() {
+ (d.doc.id.0, &d.doc.name).hash(&mut h);
+ }
s.clipboard.is_some().hash(&mut h);
// A running job greys the commands that would change its document.
s.has_jobs().hash(&mut h);
@@ -815,7 +848,7 @@ mod tests {
assert_eq!(l.bar.find(MINIMIZE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+M"));
let window = l.bar.menu(MenuRole::Window).unwrap();
assert_eq!(ids(&window.children)[..3], [MINIMIZE.to_string(), "<Zoom>".into(), "---".into()]);
- assert_eq!(ids(&window.children).last().unwrap(), "<BringAllToFront>");
+ assert!(ids(&window.children).ends_with(&["<BringAllToFront>".into(), "---".into(), "window.document.0".into()]));
let file = l.bar.menus.iter().find(|m| m.title == "File").unwrap();
assert!(!file.children.contains(&Node::Standard(Standard::CloseWindow)), "⌘W stays File › Close");
}
@@ -894,7 +927,8 @@ mod tests {
}
/// A native menu can't turn a plain item into a check item in place: opening the first
- /// document must not change any item's kind, or the whole menu is rebuilt.
+ /// document must not change any item's kind, or the whole menu is rebuilt. Window's list of
+ /// documents gains a row, which rebuilds only the Window menu.
#[test]
fn opening_a_document_changes_state_not_structure() {
let (a, b) = (crate::menus::menu_items(&app(false)), crate::menus::menu_items(&app(true)));
@@ -902,7 +936,31 @@ mod tests {
let (ka, kb) = (kind(&a), kind(&b));
let flips: Vec<&String> = ka.iter().filter(|(id, k)| kb.get(*id).is_some_and(|o| o != *k)).map(|(id, _)| id).collect();
assert!(flips.is_empty(), "items that change kind: {flips:?}");
- assert_eq!(structure_key(&layout(false).bar), structure_key(&layout(true).bar));
+ let (no_doc, one_doc) = (layout(false).bar, layout(true).bar);
+ assert_eq!(structure_key(&no_doc), structure_key(&one_doc));
+ assert_ne!(window_key(&no_doc), window_key(&one_doc), "the Window menu is rebuilt for its new row");
+ }
+
+ /// #2991: the open documents follow Bring All to Front, where a Mac app lists its windows,
+ /// the active one checked. Switching documents moves the check without a rebuild.
+ #[test]
+ fn the_documents_follow_bring_all_to_front() {
+ let none = ids(&layout(false).bar.menu(MenuRole::Window).unwrap().children);
+ assert_eq!(none.last().map(String::as_str), Some("<BringAllToFront>"));
+
+ let mut a = app(true);
+ a.run("file.new", json!({"width": 32, "height": 32})).unwrap();
+ a.sync_views();
+ let bar = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto").bar;
+ let window = ids(&bar.menu(MenuRole::Window).unwrap().children);
+ assert_eq!(window[window.len() - 4..], ["<BringAllToFront>", "---", "window.document.0", "window.document.1"]);
+ assert_eq!(bar.find("window.document.1").and_then(|i| i.checked), Some(true));
+ assert_eq!(bar.find("window.document.0").and_then(|i| i.checked), Some(false));
+
+ a.session.set_active(0);
+ let switched = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto").bar;
+ assert_eq!(switched.find("window.document.0").and_then(|i| i.checked), Some(true));
+ assert_eq!((structure_key(&switched), window_key(&switched)), (structure_key(&bar), window_key(&bar)), "a check moves in place");
}
#[test]
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 4fd1c41ac..929b69b42 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -47,7 +47,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size). The menu tree is not included; use `ui.menu.list`. `brushPicker` is `null` while closed and `{pos: [x, y], size: [w, h]?, list: {collapsed, filter, renaming, showName, showStroke, showTip, scale}}` while the Brush Preset picker is open (coordinates in screen points; `size` is the picker's content size once its corner grip was dragged, `null` before that, and the drag remembers both dimensions; the three `show*` flags pick the parts of each preset's card — at least one is always on; `scale` is the footer slider, 0.15–2 with 1 the standard, multiplying the cards' width and height — the heights stop at half size and the name and tip-size text hold their 1.0 size — and dropping the tips' size numbers at 0.40 and below; the parts and the scale are remembered across restarts, while the search, collapsed groups and a rename in progress are not). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options. `perf.timings.gpuInfo` holds the graphics adapter, backend, driver, the backend chosen at launch and why, the canvas renderer (`gpu`/`cpu`) and, after a device loss, `lost` (`help.systemInfo` returns the same as `info`)
- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerName?, brushPickerStroke?, brushPickerTip?, brushPickerScale?, gradientBlendMode?, gradientClassic?, shapeStroke?}`: change UI state; any other field is an error, checked before anything changes (`zoom` is the canvas zoom where 1 = 100%, one document pixel per physical display pixel, so a scaled display doesn't magnify the image; `theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` is `list` or `grid` for the Brushes panel; `brushPickerName`, `brushPickerStroke` and `brushPickerTip` are the Brush Preset picker's card parts (booleans, at least one on), and `brushPickerScale` its footer card-scale slider (0.15 to 2, 1 the standard); `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"], tabOrder: {"layers": ["Paths", "Layers", "Channels"]}}`, the right-dock groups top to bottom, their heights in points, the groups collapsed to their tab strip and each group's tab order left to right by panel name (a group left out keeps its default order, unknown names are ignored and tabs not listed follow in their default order; `dockTabs` keeps indexing tabs in their default order); `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour; `maskTarget` targets the active layer's mask, which, like Photoshop, swaps in the foreground/background pair kept for masks (white/black until one is picked) and swaps the pixels' pair back when the pixels are targeted again)
- `typeTransform` is `null` outside a temporary Ctrl/Cmd Type-tool drag. During a drag it reports its source document/revision, original affine, oriented `frame` (layer, local bounds, document-space corners and pivot), and captured `gesture`. Drive it with `ui.pointer` and `command: true` at `down`; `move`/`up` may release the modifier. The document/history remain unchanged during preview, and `up` applies one `type.edit` within `textEdit`'s session. Pressing Escape during the drag cancels only the preview. This pointer state is never restored from saved UI state.
-- `ui.menu.invoke {id, params?, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once
+- `ui.menu.invoke {id, params?, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once. Window ends with the open documents as `window.document.<index>` (tab order, the active one checked, #2991); invoking one brings that document to the front and replies `{document: index}`
- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.
- Each painting tool keeps its own brush, as in Photoshop: `tools.setBrush` and `ui.set {brushSize}` change the active tool's brush, and switching tools swaps in that tool's own (size, hardness, mode, opacity, flow, dynamics, smoothing). A tool used for the first time starts from the brush in hand. The colours, the erase flag and the stroke seed stay shared. So `ui.set {tool: "eraser", brushSize: 12}` sets the Eraser's size, and `ui.set {tool: "brush"}` afterwards brings the Brush's own size back.
- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks.