Skip to content

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

Control channel: menu/dialog requests wait for their job; right-click menus at the point; MCP ui_pointer button (#510, #511, #512, #514) (#548)

BFlat8f0f95959dae
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index 6c9952336..2a7017d38 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -145,13 +145,20 @@ pub struct BatchParams {
pub stop_on_error: Option<bool>,
}
+/// Strict: an argument the tool doesn't forward is an error, not silently dropped.
#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
pub struct PointerParams {
/// Events in document coordinates: `[{"kind":"down|move|up","x":..,"y":..,"pressure":..}]`.
pub events: Vec<Value>,
- /// Modifier keys, e.g. `{"shift":true}`.
+ /// Modifier keys, e.g. `{"shift":true}` (also `alt`, `command`, `ctrl`, `space`).
#[serde(default)]
pub modifiers: Option<Value>,
+ /// Mouse button: `left` (default), or `right` / `secondary`: with the Move tool or
+ /// `{"command":true}` it opens the canvas layer menu, with a painting tool the Brush Preset
+ /// picker.
+ #[serde(default)]
+ pub button: Option<String>,
}
#[derive(Debug, Deserialize, JsonSchema)]
@@ -547,7 +554,9 @@ impl PhotocraftMcp {
// ----- live-GUI tools (bridge mode) -----
- #[tool(description = "Bridge mode: full UI state of the live app (tool, panels, views, dialogs, menu tree).")]
+ #[tool(
+ description = "Bridge mode: full UI state of the live app (tool, panels, views, dialogs, windows). For the menu tree, call `control_call` with method `ui.menu.list`."
+ )]
async fn ui_inspect(&self) -> Result<CallToolResult, McpError> {
match self.bridge_client() {
Some(b) => to_result(b.call("ui.inspect", json!({})).await),
@@ -571,6 +580,9 @@ impl PhotocraftMcp {
if let Some(m) = p.modifiers {
params["modifiers"] = m;
}
+ if let Some(button) = p.button {
+ params["button"] = button.into();
+ }
to_result(b.call("ui.pointer", params).await)
}
None => bridge_only("ui_pointer"),
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index 7915cf3e6..313f23f7d 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -406,6 +406,7 @@ async fn fake_app() -> (String, tokio::task::JoinHandle<Vec<Value>>) {
"engine.commands" => {
json!({"id": id, "ok": true, "result": [{"id": "file.new", "label": "New…", "enabled": true}]})
}
+ "ui.pointer" => json!({"id": id, "ok": true, "result": req["params"]}),
"ui.screenshot" => {
let img = photocraft_codecs::Image::from_u8(40, 20, photocraft_codecs::ChannelLayout::Rgba, vec![9; 3200]).unwrap();
let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
@@ -547,6 +548,30 @@ async fn bridge_command_batch_forwards_each_steps_wait() {
app.abort();
}
+/// #514: `ui_pointer` forwards `button` (a right-click opens the layer menu or the Brush Preset
+/// picker) and rejects arguments it doesn't forward instead of dropping them.
+#[tokio::test(flavor = "multi_thread")]
+async fn bridge_ui_pointer_forwards_the_button_and_rejects_unknown_arguments() {
+ let (addr, app) = fake_app().await;
+ let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await;
+ let events = json!([{"kind": "down", "x": 5, "y": 6}, {"kind": "up", "x": 5, "y": 6}]);
+ let sent = json_of(&call(&client, "ui_pointer", json!({"events": events, "button": "right", "modifiers": {"command": true}})).await);
+ assert_eq!(sent, json!({"events": events, "button": "right", "modifiers": {"command": true}}));
+ let sent = json_of(&call(&client, "ui_pointer", json!({"events": events})).await);
+ assert_eq!(sent, json!({"events": events}), "unset fields are not sent");
+ for bad in [json!({"events": events, "buton": "right"}), json!({"events": events, "space": true})] {
+ let Value::Object(args) = bad.clone() else { unreachable!() };
+ let r = client.call_tool(CallToolRequestParams::new("ui_pointer").with_arguments(args)).await;
+ assert!(!r.as_ref().is_ok_and(|r| r.is_error != Some(true)), "{bad} accepted: {r:?}");
+ }
+ let tools = client.list_all_tools().await.unwrap();
+ let schema = &tools.iter().find(|t| t.name == "ui_pointer").unwrap().input_schema;
+ assert_eq!(schema.get("additionalProperties"), Some(&json!(false)), "{schema:?}");
+ assert!(schema.get("properties").and_then(|p| p.get("button")).is_some(), "{schema:?}");
+ client.cancel().await.unwrap();
+ app.abort();
+}
+
/// #368: agents can open the clipboard as a document of its own.
#[tokio::test(flavor = "multi_thread")]
async fn new_from_clipboard_opens_the_copy_as_a_document() {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 1734bd895..b6398e2af 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -321,6 +321,11 @@ pub struct ViewXform {
}
impl ViewXform {
+ /// The main canvas's mapping for the active document as last laid out (inside the rulers).
+ pub fn active(app: &PhotocraftApp) -> Option<Self> {
+ let v = app.ui.views.get(app.session.active_index()?)?;
+ Some(Self { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal })
+ }
pub fn to_screen(&self, x: f32, y: f32) -> Pos2 {
let sx = if self.flip { -1.0 } else { 1.0 };
self.rect.center() + vec2((x - self.center[0]) * self.zoom * sx, (y - self.center[1]) * self.zoom)
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 60640b8f8..b3fc3c024 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -6,11 +6,12 @@
//! Methods:
//! - `engine.execute {command, params}`: run any engine or UI command by id
//! - `engine.commands`: list commands with enablement
-//! - `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size)
+//! - `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size); the menu
+//! tree is `ui.menu.list`
//! - `ui.set {tool?, panels?, dock?, dockTabs?, dockWidth?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSection?, brushTab?, brushesView?, brushSize?}`:
//! change UI state; any other field is an error ([`UI_SET_FIELDS`])
-//! - `ui.menu.invoke {id}` / `ui.menu.list`: activate a menu item by id; list the menu tree
-//! - `ui.dialog.open {kind, fields?}` (kinds: newDocument, about, layerStyle {effect?}, colorPicker {target: foreground|background}, command {command}) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`
+//! - `ui.menu.invoke {id, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree
+//! - `ui.dialog.open {kind, fields?}` (kinds: newDocument, about, layerStyle {effect?}, colorPicker {target: foreground|background}, command {command}) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`
//! - `ui.dialog.apply {dialog}`: commit Preferences changes without closing the dialog
//! - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
//! - `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], modifiers?, button?}`: drive the active tool in document coordinates (`button: "secondary"` = the right button: opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase)
@@ -26,8 +27,8 @@
//! - `app.open {path}` / `app.save {path}`: relative file I/O under the automation roots; reply with `warnings`
//! - `app.quit`
//! - `jobs.list` / `jobs.cancel {job?}`: background jobs (#210) with progress; cancel one (or all).
-//! `engine.execute` waits for a command that runs as a job unless `wait: false` (then the reply
-//! is `{job, pending: true}`)
+//! `engine.execute`, `ui.menu.invoke` and `ui.dialog.confirm` wait for a command that runs as a
+//! job unless `wait: false` (then the reply is `{job, pending: true}`)
use std::sync::mpsc::Sender;
@@ -101,10 +102,40 @@ fn wrap(r: Result<Value, String>) -> Outcome {
}
}
+/// Run a command the way automation does (script events off). Long commands may run as
+/// background jobs: by default the reply waits for the job's result (backward compatible); with
+/// `wait` false it is `{job, pending: true}` at once.
+fn run_waiting(app: &mut PhotocraftApp, wait: bool, run: impl FnOnce(&mut PhotocraftApp) -> Result<Value, String>) -> Outcome {
+ let events_enabled = app.session.prefs().script_events.enabled;
+ if events_enabled {
+ app.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
+ }
+ app.jobs.last_started = None;
+ let result = run(app);
+ if events_enabled {
+ app.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
+ }
+ match (result, app.jobs.last_started.take()) {
+ (Ok(_), Some(job)) if wait => Outcome::AfterJob(job),
+ (result, _) => wrap(result),
+ }
+}
+
+/// Screen position of document point (x, y) on the main canvas, where a `ui.pointer` right-click
+/// opens its menu (the mouse's opens at the pointer); the canvas centre when it can't be mapped.
+fn screen_point(app: &PhotocraftApp, x: f64, y: f64) -> [f32; 2] {
+ let p = crate::canvas::ViewXform::active(app)
+ .map(|xf| xf.to_screen(x as f32, y as f32))
+ .filter(|p| p.is_finite())
+ .unwrap_or_else(|| app.last_canvas_rect.center());
+ [p.x, p.y]
+}
+
pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
let p = &req.params;
let s = |k: &str| p.get(k).and_then(Value::as_str);
let u = |k: &str| p.get(k).and_then(Value::as_u64);
+ let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true);
match req.method.as_str() {
"engine.execute" | "ui.menu.invoke" => {
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
@@ -118,27 +149,9 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
// params and never open a dialog (an agent would otherwise get a modal instead of a
// result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog.
if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() {
- // Long commands may run as background jobs: by default the reply waits for the
- // result (backward compatible); with `"wait": false` it is `{job, pending}`.
- let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true);
- app.jobs.last_started = None;
- let r = app.run_automation(id, params);
- if let (Ok(_), Some(job)) = (&r, app.jobs.last_started.take())
- && wait
- {
- return Outcome::AfterJob(job);
- }
- return wrap(r);
+ return run_waiting(app, wait, |app| app.run(id, params));
}
- let events_enabled = app.session.prefs().script_events.enabled;
- if events_enabled {
- app.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
- }
- let result = crate::menus::invoke(app, ctx, id, params);
- if events_enabled {
- app.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
- }
- wrap(result)
+ run_waiting(app, wait, |app| crate::menus::invoke(app, ctx, id, params))
}
"engine.commands" => wrap(app.run("command.list", json!({}))),
// Background jobs (#210): running ones with progress, then the last few that ended.
@@ -314,15 +327,8 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
{
return err(error);
}
- let events_enabled = app.session.prefs().script_events.enabled;
- if events_enabled {
- app.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
- }
- let result = if req.method == "ui.dialog.apply" { crate::prefs_ui::apply(app, id) } else { crate::dialogs::confirm(app, id) };
- if events_enabled {
- app.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
- }
- wrap(result)
+ let apply = req.method == "ui.dialog.apply";
+ run_waiting(app, wait, |app| if apply { crate::prefs_ui::apply(app, id) } else { crate::dialogs::confirm(app, id) })
}
None => err("missing `dialog`"),
},
@@ -370,17 +376,18 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
"up" => ToolEvent::Up { x, y },
_ => ToolEvent::Move { x, y, pressure: pr },
};
- // Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there.
- if matches!(s("button"), Some("secondary" | "right")) && crate::layer_pick_ui::is_gesture(app.ui.tool, mods) {
- if matches!(ev, ToolEvent::Down { .. }) {
- let at = app.last_canvas_rect.center();
- crate::layer_pick_ui::open(app, [at.x, at.y], x, y);
+ if matches!(s("button"), Some("secondary" | "right")) {
+ let down = matches!(ev, ToolEvent::Down { .. });
+ // Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there.
+ if crate::layer_pick_ui::is_gesture(app.ui.tool, mods) {
+ if down {
+ crate::layer_pick_ui::open(app, screen_point(app, x, y), x, y);
+ }
+ continue;
+ }
+ if !crate::paint_mouse::pointer_secondary(app, down, mods, screen_point(app, x, y)) {
+ continue;
}
- continue;
- }
- if matches!(s("button"), Some("secondary" | "right")) && !crate::paint_mouse::pointer_secondary(app, matches!(ev, ToolEvent::Down { .. }), mods)
- {
- continue;
}
// A simulated pen: tilt/rotation reach the stroke like a real stylus's (see `stylus`).
let tilt = |k: &str| e.get(k).and_then(Value::as_f64).map(|v| v as f32);
diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rs
index f7dd3226f..25735cdb6 100644
--- a/crates/ui-egui/src/jobs_ui_tests.rs
+++ b/crates/ui-egui/src/jobs_ui_tests.rs
@@ -154,16 +154,7 @@ fn control_requests_wait_for_jobs_unless_asked_not_to() {
let (req, rx) = crate::ControlRequest::new("engine.execute", json!({"command": "jobs.list"}));
let _ = crate::control::handle(h.state_mut(), &ctx, &req);
drop(rx);
- let (tx, rx) = std::sync::mpsc::channel();
- h.state_mut().jobs.waiters.push((job, tx));
- let t = Instant::now();
- let reply: Value = loop {
- h.step();
- if let Ok(v) = rx.try_recv() {
- break v;
- }
- assert!(t.elapsed() < Duration::from_secs(30));
- };
+ let reply = job_reply(&mut h, job);
assert_eq!(reply["ok"], true, "{reply}");
assert!(reply["result"]["filter"].is_object(), "{reply}");
@@ -179,6 +170,58 @@ fn control_requests_wait_for_jobs_unless_asked_not_to() {
assert_eq!(v["ok"], false);
}
+/// The control reply for `job`, once the app's frame loop has applied it.
+fn job_reply(h: &mut Harness<'static, PhotocraftApp>, job: JobId) -> Value {
+ let (tx, rx) = std::sync::mpsc::channel();
+ h.state_mut().jobs.waiters.push((job, tx));
+ let t = Instant::now();
+ loop {
+ h.step();
+ if let Ok(v) = rx.try_recv() {
+ return v;
+ }
+ assert!(t.elapsed() < Duration::from_secs(30));
+ }
+}
+
+/// #511: a filter started by a menu item (Blur More has no dialog) or by a filter dialog's OK
+/// replies with its result once applied, like `engine.execute`; `wait: false` replies at once.
+#[test]
+fn menu_and_dialog_requests_wait_for_jobs_unless_asked_not_to() {
+ let mut h = app_harness();
+ let ctx = h.ctx.clone();
+ let control = |h: &mut Harness<'static, PhotocraftApp>, method: &str, params: Value| {
+ let (req, _rx) = crate::ControlRequest::new(method, params);
+ crate::control::handle(h.state_mut(), &ctx, &req)
+ };
+ // The job a request started: deferred while waiting, `{job, pending}` at once otherwise.
+ // Lets it land and checks the filter's result.
+ let land = |h: &mut Harness<'static, PhotocraftApp>, what: &str, outcome: crate::control::Outcome, wait: bool| {
+ let job = match (outcome, wait) {
+ (crate::control::Outcome::AfterJob(job), true) => job,
+ (crate::control::Outcome::Done(v), false) => {
+ assert_eq!(v["result"]["pending"], true, "{what}: {v}");
+ JobId(v["result"]["job"].as_u64().unwrap())
+ }
+ _ => panic!("{what}, wait {wait}: wrong reply kind"),
+ };
+ let reply = job_reply(h, job);
+ assert!(reply["result"]["filter"].is_object(), "{what}: {reply}");
+ };
+ let steps = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().history.past_len();
+ for wait in [true, false] {
+ let before = steps(&h);
+ let outcome = control(&mut h, "ui.menu.invoke", json!({"id": "filter.blur.blurMore", "wait": wait}));
+ land(&mut h, "Blur More", outcome, wait);
+ let crate::control::Outcome::Done(v) = control(&mut h, "ui.menu.invoke", json!({"id": "filter.blur.gaussianBlur"})) else { panic!("dialog") };
+ let dialog = v["result"]["dialog"].as_u64().expect("Gaussian Blur opens its dialog");
+ control(&mut h, "ui.dialog.set", json!({"dialog": dialog, "field": "radius", "value": 3}));
+ let outcome = control(&mut h, "ui.dialog.confirm", json!({"dialog": dialog, "wait": wait}));
+ land(&mut h, "Gaussian Blur", outcome, wait);
+ assert_eq!(steps(&h), before + 2, "both filters applied");
+ }
+}
+
fn psd_bytes() -> Vec<u8> {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
diff --git a/crates/ui-egui/src/layer_pick_ui.rs b/crates/ui-egui/src/layer_pick_ui.rs
index 40bca1d4e..70b7f39b9 100644
--- a/crates/ui-egui/src/layer_pick_ui.rs
+++ b/crates/ui-egui/src/layer_pick_ui.rs
@@ -255,4 +255,38 @@ mod tests {
let crate::control::Outcome::Done(v) = crate::control::handle(&mut a, &ctx, &req) else { panic!("inspect") };
assert_eq!(v["result"]["layerMenu"]["layers"][0][1], "Red");
}
+
+ /// #512: a `ui.pointer` right-click opens the layer menu (and, with a painting tool, the Brush
+ /// Preset picker) at its document point on screen, where a mouse right-click there opens it.
+ #[test]
+ fn agents_open_it_at_the_pointed_point() {
+ let (mut a, _, _, _) = app();
+ a.ui.tool = Tool::Move;
+ let mut h = harness(a);
+ let ctx = h.ctx.clone();
+ let pointer = |h: &mut Harness<'static, PhotocraftApp>, tool: &str, x: f64, y: f64| {
+ let events = json!([{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}]);
+ let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"tool": tool, "button": "right", "events": events}));
+ let _ = crate::control::handle(h.state_mut(), &ctx, &req);
+ crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(x as f32, y as f32)
+ };
+ let near = |a: Option<[f32; 2]>, b: Pos2| a.is_some_and(|a| (a[0] - b.x).abs() < 0.5 && (a[1] - b.y).abs() < 0.5);
+ let mut opened = Vec::new();
+ for (x, y, listed) in [(100.0, 100.0, vec!["Red", "Background"]), (20.0, 170.0, vec!["Background"])] {
+ let at = pointer(&mut h, "move", x, y);
+ let pos = h.state().ui.layer_menu.as_ref().map(|m| m.pos);
+ assert!(near(pos, at), "({x}, {y}): menu at {pos:?}, point on screen {at:?}");
+ assert_eq!(names(h.state()), listed);
+ h.state_mut().ui.layer_menu = None;
+ right_click(&mut h, at, Modifiers::NONE);
+ assert!(near(h.state().ui.layer_menu.as_ref().map(|m| m.pos), at), "the mouse opens it there too");
+ assert_eq!(names(h.state()), listed);
+ h.key_press(egui::Key::Escape);
+ h.run_steps(2);
+ opened.push(at);
+ }
+ assert!(opened[0].distance(opened[1]) > 50.0, "{opened:?}");
+ let at = pointer(&mut h, "brush", 20.0, 170.0);
+ assert!(near(h.state().ui.brush_picker, at), "picker at {:?}, point on screen {at:?}", h.state().ui.brush_picker);
+ }
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 644741663..4fe6bf7a6 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -666,21 +666,6 @@ impl PhotocraftApp {
Ok(warnings)
}
- /// Run one engine command on behalf of automation while suppressing
- /// user-configured script-event file reads. Interactive commands retain
- /// their normal event behavior.
- pub fn run_automation(&mut self, id: &str, params: Value) -> Result<Value, String> {
- let events_enabled = self.session.prefs().script_events.enabled;
- if events_enabled {
- self.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
- }
- let result = self.run(id, params);
- if events_enabled {
- self.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
- }
- result
- }
-
/// File › Open: the platform dialog returns the chosen file's path (native; the web delivers
/// picks through the inbox instead).
pub fn open_dialog_file(&mut self) {
diff --git a/crates/ui-egui/src/paint_mouse.rs b/crates/ui-egui/src/paint_mouse.rs
index bfb07666d..84647c8ae 100644
--- a/crates/ui-egui/src/paint_mouse.rs
+++ b/crates/ui-egui/src/paint_mouse.rs
@@ -100,8 +100,8 @@ pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool)
/// `ui.pointer` with `"button": "secondary"`: true when its events should reach the tool (an
/// Alt+right-drag brush resize, `brush_resize_armed` for its `Down`; or an erasing right stroke,
/// `secondary_erase` armed for its `Down`). Otherwise a right-click with a painting tool opens
-/// the Brush Preset picker over the canvas, and nothing paints.
-pub fn pointer_secondary(app: &mut PhotocraftApp, down: bool, mods: egui::Modifiers) -> bool {
+/// the Brush Preset picker at screen point `at`, and nothing paints.
+pub fn pointer_secondary(app: &mut PhotocraftApp, down: bool, mods: egui::Modifiers, at: [f32; 2]) -> bool {
let tool = app.ui.tool;
if crate::brush_resize::applies(tool) && (crate::brush_resize::is_right_gesture(mods) || app.brush_resize.is_some_and(|r| r.secondary)) {
app.brush_resize_armed = down && app.drag.is_none();
@@ -112,8 +112,7 @@ pub fn pointer_secondary(app: &mut PhotocraftApp, down: bool, mods: egui::Modifi
return true;
}
if down && has_brush_picker(tool) {
- let c = app.last_canvas_rect.center();
- app.ui.brush_picker = Some([c.x, c.y]);
+ app.ui.brush_picker = Some(at);
}
false
}
@@ -301,7 +300,7 @@ mod tests {
app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap();
app.ui.tool = Tool::Brush;
let m = Modifiers::NONE;
- assert!(pointer_secondary(&mut app, true, egui::Modifiers::NONE));
+ assert!(pointer_secondary(&mut app, true, egui::Modifiers::NONE, [0.0, 0.0]));
tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 0.4 }, m);
assert!(!app.secondary_erase, "armed for one stroke only");
tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 0.8 }, m);
@@ -314,7 +313,7 @@ mod tests {
assert_eq!(st.doc.layers[0].surface().unwrap().rgba(50, 40), [1.0, 1.0, 1.0, 1.0]);
// With the default preference the right button opens the picker and nothing paints.
app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "brushPicker"})).unwrap();
- assert!(!pointer_secondary(&mut app, true, egui::Modifiers::NONE));
+ assert!(!pointer_secondary(&mut app, true, egui::Modifiers::NONE, [0.0, 0.0]));
assert!(app.ui.brush_picker.is_some() && !app.secondary_erase);
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 8499455d1..1b4c9a878 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -34,15 +34,15 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `engine.execute {command, params}`: run any engine or UI command by id. Engine commands run directly with their default params and never open a dialog. Use `ui.menu.invoke` for menu-click behaviour, which opens a command's dialog when no params are given
- `engine.commands`: list commands with enablement
-- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size). `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.inspect`: full UI state (tool, panels, views, dialogs, windows, window size). The menu tree is not included; use `ui.menu.list`. `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?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?}`: change UI state; any other field is an error, checked before anything changes (`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; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520)
-- `ui.menu.invoke {id}` / `ui.menu.list`: activate a menu item by id; list the menu tree
-- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`
+- `ui.menu.invoke {id, 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.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog, wait?}` / `ui.dialog.cancel {dialog}`. Like `ui.menu.invoke`, `ui.dialog.confirm` waits for a background job its command starts (a filter dialog's OK) and replies with the result; `"wait": false` replies `{job, pending: true}` at once
- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) edits the sections in its `values` field. `ui.dialog.apply {dialog}` saves those values through `prefs.set` and keeps the same dialog and section open. `ui.dialog.confirm` saves and closes; `ui.dialog.cancel` discards only edits made since the last successful Apply. Invalid values return an error without closing the Apply dialog or changing the saved preferences. Settings marked for the next launch still require a restart.
- Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`).
- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.
- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
-- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], modifiers?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen); `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing); `button: "right"` with the Move tool (or `command: true` with any tool) opens the canvas layer menu at that point instead (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`)
+- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu instead (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. Both menus open at the screen position of the pressed document point, like a mouse right-click's
- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`
- `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing)
- `ui.resize {width, height}`: resize the main window
@@ -76,7 +76,7 @@ UI-level commands (`file.open`, `file.save`, `view.zoomIn`, `window.theme.pro`,
### Background jobs (#210)
-Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`) and file opens run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute` still waits for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.
+Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`) and file opens run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke` and `ui.dialog.confirm` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.
## Preferences
@@ -157,7 +157,7 @@ How each MCP tool maps onto control methods in bridge mode:
| `doc_render_preview {max_side?}` | `ui.screenshot`, returned directly as PNG image content |
| `session_list`, `ui_inspect` | `ui.inspect` |
| `ui_screenshot {max_side?}` | `ui.screenshot`, returned as PNG image content |
-| `ui_pointer {events, modifiers?}` | `ui.pointer` |
+| `ui_pointer {events, modifiers?, button?}` | `ui.pointer` (other arguments are an error) |
| `ui_menu_invoke {id}` | `ui.menu.invoke` |
| `ui_set {fields}` | `ui.set` |
| `control_call {method, params}` | any method, passed through unchanged |