Merge main into the integration batch

This commit is contained in:
Federico Olivares committed 2026-10-24 20:16:55 -03:00
commit 2475b10143
9 files changed
+352 -97

No files matched your search

+56 -29
View File
@@ -199,6 +199,10 @@ pub(crate) struct CommandsArgs {
}
/// Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`)
///
/// Headless: each automation root grants that direction of file access; an omitted root denies it.
/// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop
/// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT).
#[derive(Args)]
pub(crate) struct McpArgs {
/// Bridge to the PhotoCraft app listening here instead of a headless engine; a bare port means
@@ -219,7 +223,8 @@ pub(crate) struct McpArgs {
/// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute,
/// jobs.list/cancel, engine.commands,
/// doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close,
/// session.list, batch, methods (docs/control-protocol.md#headless-server).
/// session.list, batch, methods (docs/control-protocol.md#headless-server). The token flags require
/// --port (or PHOTOCRAFT_CONTROL_PORT); stdio needs no control token.
#[derive(Args)]
pub(crate) struct ServeArgs {
/// Listen on 127.0.0.1:<PORT> instead of stdio
@@ -252,6 +257,34 @@ enum ValueError {
Bridge,
}
/// Why `parse` refuses `mcp` or `serve` options clap accepted: clap prints it as a usage error
/// (exit 2).
#[derive(Debug, thiserror::Error)]
enum ServerOptionError {
/// PHOTOCRAFT_CONTROL_PORT holds a port, as for the desktop app's --control: only the flag
/// takes host:port.
#[error("invalid value '{0}' for 'PHOTOCRAFT_CONTROL_PORT': {bridge}", bridge = ValueError::Bridge)]
BridgeVar(String),
/// With --bridge the roots are the desktop process's to set: accepting them here promises
/// authority the bridge can't give (#8035).
#[error("configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode")]
BridgeRoots,
/// A token flag without the bridge or port that reads it would be ignored (#8035).
#[error("{flag} requires {transport}")]
NeedsTransport { flag: &'static str, transport: &'static str },
}
impl ServerOptionError {
fn into_clap(self, cmd: &mut clap::Command) -> clap::Error {
let kind = match self {
Self::BridgeVar(_) => ErrorKind::ValueValidation,
Self::BridgeRoots => ErrorKind::ArgumentConflict,
Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument,
};
cmd.error(kind, self)
}
}
fn tga_bits(s: &str) -> Result<TgaBits, ValueError> {
s.parse().ok().and_then(TgaBits::from_bits).ok_or(ValueError::TgaBits)
}
@@ -326,16 +359,16 @@ fn steps(m: &ArgMatches) -> Vec<Step> {
/// Parse the arguments (without the binary name). clap reads them as `OsString`s: a path need not
/// be valid Unicode (#1108), text must. A flag left out falls back to its environment variable,
/// unless that is empty, and a bad value from one is a usage error naming the variable (#2491).
/// unless that is empty, and a bad value from one is a usage error naming the variable (#2491). A
/// bare `--help` or `-h` is help even after a mistake on the same line (`--out --help`, `mcp
/// stray.psd --help`): clap reports the mistake first.
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset));
let argv = std::iter::once(OsString::from("photocraft-cli")).chain(args.iter().cloned());
let matches = match cmd.try_get_matches_from_mut(argv) {
// Help where a flag's value should be (`--out --help`) is still help: clap reports the
// missing value first.
Err(e) if e.kind() == ErrorKind::InvalidValue && args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => {
Err(e) if args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => {
let help = [OsString::from("photocraft-cli"), args.first().cloned().unwrap_or_default(), OsString::from("--help")];
return Err(Cli::command().try_get_matches_from(help).err().unwrap_or(e));
return Err(cmd.try_get_matches_from_mut(help).err().unwrap_or(e));
}
matches => matches.map_err(|e| name_env_vars(e, &cmd, args))?,
};
@@ -345,12 +378,10 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
(Command::Run(r), Some((_, m))) => r.steps = steps(m),
(Command::Mcp(a), Some((name, m))) => {
a.bridge_from_env = from_env(m, "bridge");
// The variable holds a port, as for the desktop app's --control: only the flag takes
// host:port, which `bridge` lets through.
if a.bridge_from_env
&& let Some(Bridge::Addr(v)) = &a.bridge
{
return Err(cmd.error(ErrorKind::ValueValidation, format!("invalid value '{v}' for 'PHOTOCRAFT_CONTROL_PORT': {}", ValueError::Bridge)));
return Err(ServerOptionError::BridgeVar(v.clone()).into_clap(&mut cmd));
}
if let Some(sub) = cmd.find_subcommand_mut(name) {
// Only the bridge reads a token, so a stale exported pair doesn't stop a headless
@@ -359,43 +390,39 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
conflict(sub, m, "control_token", "control_token_file")?;
}
// The roots are the headless engine's: the variable switching to the bridge would
// drop them.
// drop them, and the error names it.
if a.bridge_from_env {
conflict(sub, m, "automation_read_root", "bridge")?;
conflict(sub, m, "automation_write_root", "bridge")?;
}
if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) {
return Err(ServerOptionError::BridgeRoots.into_clap(sub));
}
check_server(sub, m, a.bridge.is_some(), "--bridge")?;
}
check_server(cmd.find_subcommand_mut(name), m, "bridge")?;
}
(Command::Serve(a), Some((name, m))) => {
a.port_from_env = from_env(m, "port");
// Only the TCP server reads a token, so a stale exported pair doesn't stop stdio.
if a.port.is_some()
&& let Some(sub) = cmd.find_subcommand_mut(name)
{
conflict(sub, m, "control_token", "control_token_file")?;
if let Some(sub) = cmd.find_subcommand_mut(name) {
// Only the TCP server reads a token, so a stale exported pair doesn't stop stdio.
if a.port.is_some() {
conflict(sub, m, "control_token", "control_token_file")?;
}
check_server(sub, m, a.port.is_some(), "--port")?;
}
check_server(cmd.find_subcommand_mut(name), m, "port")?;
}
_ => {}
}
Ok(cli)
}
/// Refuse `mcp` and `serve` launch options that would otherwise be silently ignored (#8035): a
/// token flag without the bridge or port that reads it (flag or variable; a token variable alone
/// may be a stale export), and bridge roots, which belong to the desktop process: accepting them
/// here promises authority the bridge cannot set.
fn check_server(sub: Option<&mut clap::Command>, m: &ArgMatches, transport: &str) -> Result<(), clap::Error> {
let Some(sub) = sub else { return Ok(()) };
/// Refuse a token flag without the bridge or port that reads it (as a flag or its variable). A
/// token variable alone may be a stale export, so it isn't refused.
fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, transport: &'static str) -> Result<(), clap::Error> {
for (id, flag) in [("control_token", "--control-token"), ("control_token_file", "--control-token-file")] {
if m.value_source(id) == Some(ValueSource::CommandLine) && !m.contains_id(transport) {
return Err(sub.error(ErrorKind::MissingRequiredArgument, format!("{flag} requires --{transport}")));
if m.value_source(id) == Some(ValueSource::CommandLine) && !has_transport {
return Err(ServerOptionError::NeedsTransport { flag, transport }.into_clap(sub));
}
}
if transport == "bridge" && m.contains_id(transport) && (m.contains_id("automation_read_root") || m.contains_id("automation_write_root")) {
let message = "configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode";
return Err(sub.error(ErrorKind::ArgumentConflict, message));
}
Ok(())
}
+11 -3
View File
@@ -74,7 +74,15 @@ fn every_subcommand_answers_help() {
}
}
// Help where a flag's value should be is still help, not a missing value or a file named `-h`.
for args in [&["run", "x.png", "--out", "--help"][..], &["commands", "--filter", "-h"], &["mcp", "--bridge", "-h"], &["serve", "--port", "--help"]] {
// So is help after another mistake.
for args in [
&["run", "x.png", "--out", "--help"][..],
&["commands", "--filter", "-h"],
&["mcp", "--bridge", "-h"],
&["serve", "--port", "--help"],
&["mcp", "stray.psd", "--help"],
&["serve", "--port", "abc", "--port", "1", "-h"],
] {
let o = bin().current_dir(&d).args(args).stdin(Stdio::null()).output().unwrap();
assert_eq!(o.status.code(), Some(0), "{args:?}: {}", String::from_utf8_lossy(&o.stderr));
assert!(String::from_utf8_lossy(&o.stdout).contains(&format!("photocraft-cli {}", args[0])), "{args:?}");
@@ -161,14 +169,14 @@ fn server_modes_reject_ignored_or_conflicting_options() {
}
for flag in ["--automation-read-root", "--automation-write-root"] {
server_usage_error(&[sub, flag, ".", flag, "."], "cannot be used multiple times");
server_usage_error(&[sub, &format!("{flag}=")], &format!("'{flag} "));
server_usage_error(&[sub, &format!("{flag}=")], &format!("a value is required for '{flag} "));
server_usage_error(&[sub, flag, "--automation-write-root", "."], &format!("a value is required for '{flag} "));
}
let transport = if sub == "mcp" { "--bridge" } else { "--port" };
for flag in [transport, "--control-token", "--control-token-file"] {
// Valid values, so the repeat is what is refused (a transport value is parsed first).
server_usage_error(&[sub, flag, "7878", &format!("{flag}=7879")], "cannot be used multiple times");
server_usage_error(&[sub, flag, ""], &format!("'{flag} "));
server_usage_error(&[sub, flag, ""], &format!("for '{flag} "));
}
server_usage_error(&[sub, transport, "7878", "--control-token", "unused", "--control-token-file", "unused"], "cannot be used with");
}
+3 -2
View File
@@ -23,8 +23,9 @@ photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file /private/path/co
Use absolute root paths in MCP client configurations, since a relative root is resolved from the
client's launch directory. In bridge mode the roots are configured on the desktop app, and root
flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and
`--control-token-file` flags require `--bridge` and are mutually exclusive; bridge credentials can
also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`. Each launch option
`--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually
exclusive; bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or
`PHOTOCRAFT_CONTROL_TOKEN_FILE`. Each launch option
except `--help`/`-h` takes one non-empty value and cannot be repeated. Stray positional arguments,
missing values and options for the wrong mode are usage errors (exit 2) reported on stderr before
the server starts.
+37 -15
View File
@@ -524,23 +524,24 @@ fn components4(mask: &[bool], w: usize, h: usize) -> (Vec<u32>, Vec<usize>) {
/// rule as the magic wand's anti-aliasing).
pub fn antialias_u8(mask: &mut [u8], w: usize, h: usize) {
let src = mask.to_vec();
let at = |x: i32, y: i32, v: u8| if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 { v } else { src[y as usize * w + x as usize] };
// A span whose 3×3 neighbourhood holds one value has no edge pixel, so it is only compared:
// most of a full-resolution mask is far from its boundary. 64 pixels keep the three row
// compares cheap per pixel, and a span that does reach the boundary costs few extra pixels.
const SPAN: usize = 64;
let uniform = |y: usize, x0: usize, x1: usize| {
let (a, b, v) = (x0.saturating_sub(1), (x1 + 1).min(w), src[y * w + x0]);
(y.saturating_sub(1)..(y + 2).min(h)).all(|ny| src[ny * w + a..ny * w + b].iter().all(|n| *n == v))
};
let row = |y: usize, out: &mut [u8]| {
for (x, o) in out.iter_mut().enumerate() {
let v = src[y * w + x];
let mut sum = 0u32;
let mut edge = false;
for dy in -1..=1 {
for dx in -1..=1 {
let n = at(x as i32 + dx, y as i32 + dy, v);
edge |= n != v;
sum += n as u32;
}
for (c, span) in out.chunks_mut(SPAN).enumerate() {
let x0 = c * SPAN;
if uniform(y, x0, x0 + span.len()) {
continue;
}
if edge {
let avg = sum as f32 / (9.0 * 255.0);
let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg };
*o = (f * 255.0).round() as u8;
for (i, o) in span.iter_mut().enumerate() {
if let Some(v) = edge_value(&src, w, h, x0 + i, y) {
*o = v;
}
}
}
};
@@ -553,6 +554,27 @@ pub fn antialias_u8(mask: &mut [u8], w: usize, h: usize) {
mask.chunks_mut(w).enumerate().for_each(|(y, r)| row(y, r));
}
/// The anti-aliased value of pixel `(x, y)` of `src` (`w` × `h`), or `None` when every neighbour
/// in its 3×3 neighbourhood has its value (neighbours outside the mask count as the pixel itself).
fn edge_value(src: &[u8], w: usize, h: usize, x: usize, y: usize) -> Option<u8> {
let v = src[y * w + x];
let mut sum = 0u32;
let mut edge = false;
for dy in -1..=1 {
for dx in -1..=1 {
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
let n = if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 { v } else { src[ny as usize * w + nx as usize] };
edge |= n != v;
sum += n as u32;
}
}
edge.then(|| {
let avg = sum as f32 / (9.0 * 255.0);
let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg };
(f * 255.0).round() as u8
})
}
/// Shrinks a region's box to its non-zero pixels (`None` if empty).
pub fn trim_region(r: Region) -> Option<Region> {
let w = r.bbox.width() as usize;
+44
View File
@@ -903,6 +903,50 @@ fn select_subject_leaves_a_background_coloured_gap_open() {
assert!(v > 0.9, "IoU {v}");
}
#[test]
fn antialias_blends_edge_pixels_with_their_neighbourhood() {
// A lone selected pixel keeps most of its coverage and its neighbours get half of a ninth;
// neighbours outside the mask count as the pixel itself.
let mut m = vec![0, 0, 0, 0, 255, 0, 0, 0, 0];
antialias_u8(&mut m, 3, 3);
assert_eq!(m, [14, 14, 14, 14, 142, 14, 14, 14, 14]);
}
#[test]
fn antialias_skips_only_spans_without_edge_pixels() {
// Every pixel through the per-pixel rule, no span skipped.
let every_pixel = |mask: &mut [u8], w: usize, h: usize| {
let src = mask.to_vec();
for y in 0..h {
for x in 0..w {
if let Some(v) = edge_value(&src, w, h, x, y) {
mask[y * w + x] = v;
}
}
}
};
let mut rng = Rng::new(11);
// Widths around the 64-pixel span, single rows and columns, discs, noise and stripes.
for (w, h) in [(1usize, 1usize), (1, 9), (9, 1), (63, 4), (64, 3), (65, 5), (127, 2), (129, 70), (300, 200)] {
let (cx, cy, r) = (w as f32 * 0.6, h as f32 * 0.4, w.min(h) as f32 / 3.0);
let masks: Vec<Vec<u8>> = vec![
vec![255; w * h],
vec![0; w * h],
(0..w * h).map(|i| if ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r { 255 } else { 0 }).collect(),
(0..w * h).map(|_| if rng.f32() < 0.02 { 255 } else { 0 }).collect(),
(0..w * h).map(|_| if rng.f32() < 0.5 { 255 } else { 0 }).collect(),
(0..w * h).map(|i| if (i % w) / 64 % 2 == 0 { 255 } else { 0 }).collect(),
(0..w * h).map(|i| if i % w == w - 1 || i / w == h / 2 { 255 } else { 0 }).collect(),
];
for (k, m) in masks.into_iter().enumerate() {
let (mut fast, mut slow) = (m.clone(), m);
antialias_u8(&mut fast, w, h);
every_pixel(&mut slow, w, h);
assert!(fast == slow, "{w}×{h} mask {k}");
}
}
}
/// Timing on a 6 MP figure, for before/after numbers (`cargo test --release -- --ignored select_subject_timing --nocapture`).
#[test]
#[ignore = "timing only"]
+161 -43
View File
@@ -289,6 +289,10 @@ pub struct DetailTexture {
pub(crate) struct CpuTextures {
pub texture: egui::TextureId,
pub scale: f32,
/// The document area the texture covers: the document's bounds, or for a filter preview that
/// changes the canvas's dimensions (Image › Rotation) its result centred on the document, as
/// the GPU canvas draws it.
pub bounds: DRect,
/// The detail texture and the document area it covers (x0, y0, x1, y1 in document pixels).
pub detail: Option<(egui::TextureId, [f32; 4])>,
}
@@ -1746,11 +1750,25 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize,
ensure_texture_in_view(app, ctx, idx, display, None).map(|t| (t.texture, t.scale))
}
/// Whether a filter preview of `preview` size shows a `doc` sized document reduced by `k` (its
/// proxy factor), so the CPU canvas can draw it over the document's bounds unstretched.
fn preview_fits(doc: photocraft_geom::Size, preview: photocraft_geom::Size, k: u32) -> bool {
/// The document area a filter preview of `preview` size covers, for a `doc` sized document
/// previewed at proxy factor `k`: the document's bounds when it is the document's size (reduced by
/// `k`), else its own size (times `k`) centred on the document's centre, as the GPU canvas centres
/// a size-changing preview (Image › Rotation).
fn preview_bounds(doc: photocraft_geom::Size, preview: photocraft_geom::Size, k: u32) -> DRect {
let k = k.max(1);
doc.width.div_ceil(k) == preview.width && doc.height.div_ceil(k) == preview.height
let full = DRect::from_size(doc);
if doc.width.div_ceil(k) == preview.width && doc.height.div_ceil(k) == preview.height {
return full;
}
let side = |p: u32, d: u32| {
let covered = i64::from(p) * i64::from(k);
let x0 = (i64::from(d) - covered).div_euclid(2);
let clamp = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32;
(clamp(x0), clamp(x0 + covered))
};
let (x0, x1) = side(preview.width, doc.width);
let (y0, y1) = side(preview.height, doc.height);
DRect::new(x0, y0, x1, y1)
}
/// [`ensure_texture`], and for a canvas showing `view` of a document too large for one
@@ -1772,15 +1790,18 @@ pub(crate) fn ensure_texture_in_view(
// canvas (no usable GPU, a flipped or pixel-aspect-corrected view, a GPU fallback) showed the
// document unfiltered. Its result is drawn here instead, as the channel views draw it.
// A preview reduced for a zoomed-out view (a proxy, factor `k`) covers the whole document at
// its own size. One whose dimensions change otherwise (Image › Rotation) would be stretched
// over the document's bounds here, so the CPU canvas keeps the document for it, as before.
// its own size. One whose dimensions change otherwise (Image › Rotation) covers its own area,
// centred on the document's, as the GPU canvas draws it (`preview_bounds`).
let committed = app.session.documents().get(idx).map(|st| st.doc.bounds()).unwrap_or(doc.bounds());
let mut bounds = committed;
let mut reduced = false;
if let Some((preview, key)) = filter_channel_preview(app, idx, ctx) {
let k = app.filter_preview.as_ref().map_or(1, |p| p.key.k.max(1));
if app.session.documents().get(idx).is_some_and(|st| preview_fits(st.doc.size, preview.size, k)) {
(doc, preview_key, reduced) = (preview, key, k > 1);
}
bounds = preview_bounds(committed.size(), preview.size, k);
(doc, preview_key, reduced) = (preview, key, k > 1);
}
// Detail textures and partial redraws work in the document's own pixels.
let reduced = reduced || bounds != committed;
let view = view.filter(|_| !reduced);
// A flipped view draws a GPU machine's canvas through here: an adjustment dialog's preview of
// a large document (taken by the GPU path) would cost a full-size CPU composite per change.
@@ -1855,10 +1876,10 @@ pub(crate) fn ensure_texture_in_view(
let texture = cache.texture.as_ref()?.id();
let scale = cache.scale;
// Without a view (the Navigator's call) the views' detail textures stay as they are.
let Some(view) = view else { return Some(CpuTextures { texture, scale, detail: None }) };
let Some(view) = view else { return Some(CpuTextures { texture, scale, bounds, detail: None }) };
let old = cache.detail.iter().position(|(k, _)| *k == view.key).map(|i| cache.detail.remove(i).1);
let Some(plan) = detail_plan([doc.size.width, doc.size.height], texture_side(ctx), view.zoom, view.visible) else {
return Some(CpuTextures { texture, scale, detail: None });
return Some(CpuTextures { texture, scale, bounds, detail: None });
};
let t0 = crate::gpu_canvas::now_ms();
let name = format!("canvas-detail-{}-{}", id.0, cache_key(id, output).1);
@@ -1866,7 +1887,7 @@ pub(crate) fn ensure_texture_in_view(
if detail.as_ref().is_some_and(|d| d.rendered) {
app.perf.span("canvas detail", crate::gpu_canvas::now_ms() - t0);
}
let Some(mut detail) = detail else { return Some(CpuTextures { texture, scale, detail: None }) };
let Some(mut detail) = detail else { return Some(CpuTextures { texture, scale, bounds, detail: None }) };
detail.rendered = false;
// Where its texels lie in the document: reduced texel t covers [t·W/w, (t+1)·W/w).
let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1));
@@ -1878,7 +1899,7 @@ pub(crate) fn ensure_texture_in_view(
if cache.detail.len() > MAX_DETAIL_VIEWS {
cache.detail.remove(0);
}
Some(CpuTextures { texture, scale, detail: Some(shown) })
Some(CpuTextures { texture, scale, bounds, detail: Some(shown) })
}
/// Most CPU canvas views of one document on one display that keep a detail texture.
@@ -3660,6 +3681,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow;
// Drop shadow, checkerboard, document image.
let img_rect = xf.doc_rect(doc.bounds());
// The canvas edge the Line border outlines: a size-changing preview's own (CPU canvas).
let mut edge_rect = img_rect;
// The document area the image is drawn over: a size-changing preview's own on the CPU
// canvas (Image › Rotation). Overlays drawn from the same preview follow it.
let mut shown_area = doc.bounds();
// Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas
// (whose edge blends into them) and without its shadow.
let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output);
@@ -3738,42 +3764,60 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
paint_gpu_view(&painter, rect, params, &pattern);
} else {
app.navigator_gpu.remove(&doc.id);
if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow {
painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0));
}
let rotated = view.rotation.abs() > 0.05;
let checkerboard = app.session.prefs().transparency_and_gamut.square().map(|square| (checker(app, &ctx), square));
// A document too large for one full-resolution texture also gets the part in view at
// the screen's resolution, drawn over the reduced whole (#7568).
let in_view =
InView { visible: visible_doc_rect(&xf), zoom: view.zoom, key: egui::Id::new(("pc-canvas-detail", ctx.viewport_id(), idx, primary)).value() };
let textures = ensure_texture_in_view(app, &ctx, idx, output, Some(in_view));
let tex = textures.as_ref().map(|t| t.texture);
// The area the image covers: a size-changing preview's own (Image › Rotation).
let area = textures.as_ref().map_or(doc.bounds(), |t| t.bounds);
shown_area = area;
if area != doc.bounds() {
edge_rect = xf.doc_rect(area);
}
if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow {
let shadow_rect = edge_rect;
painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(shadow_rect, 0));
}
let rotated = view.rotation.abs() > 0.05;
let checkerboard = app.session.prefs().transparency_and_gamut.square().map(|square| (checker(app, &ctx), square));
// Repeated-quad coverage is not proven identical on all Pattern Preview adapters.
// Retain its legacy checker submissions, including the central document's.
let opaque = !app.ui.view.pattern_preview && app.canvases.get(&cache_key(doc.id, output)).is_some_and(|c| c.texture_opaque) && tex.is_some();
paint_cpu_document(&painter, &xf, doc.bounds(), rotated, checkerboard, tex, opaque);
paint_cpu_document(&painter, &xf, area, rotated, checkerboard, tex, opaque);
if let Some((detail, area)) = textures.and_then(|t| t.detail) {
paint_cpu_detail(&painter, &xf, doc.bounds(), rotated, checkerboard, detail, area);
}
for &c in &pattern {
paint_cpu_document(&painter, &pattern_xf(&xf, c, size), doc.bounds(), rotated, checkerboard, tex, opaque);
// Pattern Preview tiles what is shown: a size-changing preview's area, from its origin.
let (tile, copies) = if area == doc.bounds() || !app.ui.view.pattern_preview {
(size, pattern.clone())
} else {
let tile = [area.width(), area.height()];
let v = visible_doc_rect(&xf).translate(-area.x0, -area.y0);
(tile, crate::pattern_preview::copies([v.x0, v.y0, v.x1, v.y1].map(f64::from), tile))
};
for &c in &copies {
paint_cpu_document(&painter, &pattern_xf(&xf, c, tile), area, rotated, checkerboard, tex, opaque);
}
}
// Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs).
if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) {
// Rendered from the live preview, so over the area the preview is shown in.
let a = shown_area;
if view.rotation.abs() > 0.05 {
paint_mapped_image(
paint_mapped_image_at(
&painter,
&xf,
tex,
Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)),
[doc.size.width as f32, doc.size.height as f32],
[a.x0 as f32, a.y0 as f32],
[a.width() as f32, a.height() as f32],
Color32::WHITE,
);
} else {
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
painter.image(tex, img_rect, uv, Color32::WHITE);
painter.image(tex, xf.doc_rect(a), uv, Color32::WHITE);
}
}
crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip);
@@ -3922,7 +3966,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
}
(img_rect, beyond, layer_edges)
(beyond, layer_edges, edge_rect)
};
let painted = if crop_camera { None } else { Some(paint_canvas(app, ui, &display_view, xf)) };
let img_rect = xf.doc_rect(doc.bounds());
@@ -4584,7 +4628,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
} else {
xf
};
let (img_rect, beyond, layer_edges) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf));
let (beyond, layer_edges, edge_rect) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf));
// A Hand drag (the tool, Space or the middle button) keeps every overlay on screen, as in
// Photoshop: the Pen path being drawn, paths, guides, grid, transform box (#6592). Only the
// tool cursors below give way to the fist.
@@ -4631,7 +4675,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// The canvas edge isn't outlined while the pixels past it show (Photoshop's crop preview),
// nor while the Crop tool hides everything outside its box (Show Cropped Area off).
if border == photocraft_engine::prefs::CanvasBorder::Line && !beyond && !crate::crop_shield::hides_outside(app) {
painter.rect_stroke(img_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside);
painter.rect_stroke(edge_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside);
}
crate::type_tool::draw_overlay(app, &painter, &xf);
crate::transform_tool::draw_overlay(app, &painter, &xf);
@@ -4999,10 +5043,10 @@ fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32, center_on
view.center = [before[0] as f32 - u.x, before[1] as f32 - u.y];
}
/// Textured document quad whose corners follow [`ViewXform`] (rotation + flip).
fn paint_mapped_image(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, size: [f32; 2], tint: Color32) {
let [w, h] = size;
let pts = [xf.to_screen(0.0, 0.0), xf.to_screen(w, 0.0), xf.to_screen(w, h), xf.to_screen(0.0, h)];
/// A texture mapped over the `size` document area starting at `origin` (follows a rotated view).
fn paint_mapped_image_at(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, origin: [f32; 2], size: [f32; 2], tint: Color32) {
let ([x, y], [w, h]) = (origin, size);
let pts = [xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)];
let uvs = [uv.min, pos2(uv.max.x, uv.min.y), uv.max, pos2(uv.min.x, uv.max.y)];
let mut mesh = Mesh::with_texture(tex);
for i in 0..4 {
@@ -5048,12 +5092,13 @@ fn paint_cpu_document(
opaque: bool,
) {
let size = [bounds.width() as f32, bounds.height() as f32];
let origin = [bounds.x0 as f32, bounds.y0 as f32];
let img_rect = xf.doc_rect(bounds);
match checker {
Some((checker_id, square)) if !opaque || tex.is_none() => {
if rotated {
let tiles = vec2(size[0], size[1]) / (2.0 * square);
paint_mapped_image(painter, xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), size, Color32::WHITE);
paint_mapped_image_at(painter, xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), origin, size, Color32::WHITE);
} else {
let tiles = img_rect.size() / (2.0 * square);
painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE);
@@ -5064,7 +5109,7 @@ fn paint_cpu_document(
Some(_) => {}
None => {
if rotated {
paint_mapped_quad(painter, xf, size, Color32::WHITE);
paint_mapped_quad(painter, xf, origin, size, Color32::WHITE);
} else {
painter.rect_filled(img_rect, 0.0, Color32::WHITE);
}
@@ -5072,7 +5117,7 @@ fn paint_cpu_document(
}
if let Some(tex) = tex {
if rotated {
paint_mapped_image(painter, xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), size, Color32::WHITE);
paint_mapped_image_at(painter, xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), origin, size, Color32::WHITE);
} else {
let uv = if xf.flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
painter.image(tex, img_rect, uv, Color32::WHITE);
@@ -5122,9 +5167,9 @@ fn paint_cpu_detail(
quad(tex, [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]);
}
fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, size: [f32; 2], color: Color32) {
let [w, h] = size;
let pts = vec![xf.to_screen(0.0, 0.0), xf.to_screen(w, 0.0), xf.to_screen(w, h), xf.to_screen(0.0, h)];
fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, origin: [f32; 2], size: [f32; 2], color: Color32) {
let ([x, y], [w, h]) = (origin, size);
let pts = vec![xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)];
painter.add(egui::Shape::convex_polygon(pts, color, Stroke::NONE));
}
@@ -7018,13 +7063,86 @@ mod tests {
assert_eq!(shown, expected.pixels, "{size:?}: the canvas shows the preview");
assert_ne!(shown.first(), plain.first(), "{size:?}: not the unfiltered document");
}
// A preview that changes the canvas's dimensions (a 90° rotation) isn't stretched over the
// document's bounds: only one the document's size (reduced by its factor) is drawn.
// A preview that changes the canvas's dimensions covers its own area, centred on the
// document's (as the GPU canvas centres it), rather than being stretched over it.
let size = |w, h| photocraft_geom::Size::new(w, h);
assert!(preview_fits(size(64, 32), size(64, 32), 1));
assert!(preview_fits(size(2401, 2200), size(1201, 1100), 2), "a proxy");
assert!(!preview_fits(size(64, 32), size(32, 64), 1), "rotated");
assert!(!preview_fits(size(64, 32), size(80, 40), 1), "canvas grown");
assert_eq!(preview_bounds(size(64, 32), size(64, 32), 1), DRect::new(0, 0, 64, 32));
assert_eq!(preview_bounds(size(2401, 2200), size(1201, 1100), 2), DRect::new(0, 0, 2401, 2200), "a proxy");
assert_eq!(preview_bounds(size(64, 32), size(32, 64), 1), DRect::new(16, -16, 48, 48), "rotated");
assert_eq!(preview_bounds(size(64, 32), size(80, 40), 1), DRect::new(-8, -4, 72, 36), "canvas grown");
assert_eq!(preview_bounds(size(4000, 2000), size(1000, 2000), 2), DRect::new(1000, -1000, 3000, 3000), "a rotated proxy");
// Image › Image Rotation › Arbitrary 90° on a 64×32 document: its 32×64 preview is drawn over
// the centred 32×64 area.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.background_jobs = false;
app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap();
let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap();
let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap();
d.fields.insert("angle".into(), json!(90.0));
d.fields.insert("__preview".into(), json!(true));
let ctx = egui::Context::default();
let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap();
let (size, _) = pixels(&ctx, t.texture);
assert_eq!(size, [32, 64], "the rotated preview's texture");
assert_eq!(t.bounds, DRect::new(16, -16, 48, 48), "centred on the document");
let centre = |r: DRect| (r.x0 + r.x1, r.y0 + r.y1);
assert_eq!(centre(t.bounds), centre(app.session.active().unwrap().doc.bounds()), "the same centre, so the view's pan holds");
// Preview off, then Cancel: the document again, unchanged.
let revision = app.session.active().unwrap().revision;
app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap().fields.insert("__preview".into(), json!(false));
let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap();
assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "Preview off");
crate::dialogs::cancel(&mut app, id).unwrap();
let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap();
assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "after Cancel");
assert_eq!(app.session.active().unwrap().revision, revision, "the document untouched");
assert_eq!(app.session.active().unwrap().doc.size, photocraft_geom::Size::new(64, 32));
}
/// A channel overlay drawn from a size-changing preview covers the preview's own area, as the
/// image does, not the document's: a 90° rotation of a 64×32 document shows a 32×64 overlay.
#[test]
fn a_channel_overlay_follows_a_size_changing_preview() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.background_jobs = false;
app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap();
app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap();
let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap();
let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap();
d.fields.insert("angle".into(), json!(90.0));
d.fields.insert("__preview".into(), json!(true));
let ctx = egui::Context::default();
for rotation in [0.0f32, 30.0] {
let view = View { zoom: 4.0, center: [32.0, 16.0], rotation, ..app.ui.views[0].clone() };
let mut output = ctx.run_ui(Default::default(), |ui| {
canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), view.clone(), true);
});
output.textures_delta.clear();
let overlay = crate::channel_view::ensure(&mut app, &ctx, 0).expect("the channel overlay");
let mesh = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Mesh(m) if m.texture_id == overlay => Some(m.clone()),
_ => None,
})
.expect("the overlay is painted");
// The quad's sides, in screen points: the two shortest distances from a corner (the
// third is the diagonal; a rotated view turns the quad, not its side lengths).
let v: Vec<Pos2> = mesh.vertices.iter().map(|v| v.pos).collect();
let mut d: Vec<f32> = v[1..4].iter().map(|p| v[0].distance(*p)).collect();
d.sort_by(f32::total_cmp);
let (short, long) = (d[0], d[1]);
// Which side is the width: the one along the view's x axis turned by the rotation.
let along = |p: Pos2| {
let r = rotation.to_radians();
((p - v[0]).x * r.cos() + (p - v[0]).y * r.sin()).abs()
};
let width = v[1..4].iter().map(|p| along(*p)).fold(0.0f32, f32::max);
assert!((long / short - 2.0).abs() < 0.01, "rotation {rotation}: sides {short}×{long}, the preview's 1:2");
assert!((width - short).abs() < 0.5, "rotation {rotation}: the short side ({short}) runs across the view (width {width})");
}
}
#[test]
+5 -1
View File
@@ -246,7 +246,11 @@ impl Nav {
fn after_row(&mut self, level: usize, i: usize, lit: bool, r: &egui::Response) {
let moved = r.ctx.input(|inp| inp.pointer.delta() != egui::Vec2::ZERO);
let follow = self.follow == Some(level);
if (moved || follow) && r.hovered() && !lit {
// `hovered` is false while the primary button is held (egui attributes the pointer to
// the pressed widget), so a press-drag through the items never highlighted anything
// (#8887). `contains_pointer` keeps answering while a button is down.
let over = r.contains_pointer();
if (moved || follow) && over && !lit {
if follow {
self.follow = None;
}
+31
View File
@@ -727,6 +727,37 @@ fn press_drag_release_reaches_other_menus_and_submenus() {
assert!(Nav::current(&h.ctx).rows.first().is_none_or(|r| r.is_empty()), "and closed the menus");
}
/// Press-and-hold a menu title and drag through the items: the highlight follows the
/// pointer the whole way, down and back up, without lagging or dropping (#8887).
#[test]
fn press_drag_highlight_follows_the_pointer() {
use egui::{Modifiers, PointerButton};
let mut h = harness((1280.0, 720.0, 1.0));
let title = h.get_by_label("View").rect().center();
h.event(egui::Event::PointerMoved(title));
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: title, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(2);
let rows = Nav::current(&h.ctx).rows.first().cloned().unwrap_or_default();
assert!(rows.len() > 4, "the View menu has rows to drag through");
// Drag down through the first rows, one at a time, still holding the button.
for i in 1..=4 {
let row = rows.get(i).expect("row exists");
h.event(egui::Event::PointerMoved(row.rect.center()));
h.run_steps(1);
assert_eq!(Nav::current(&h.ctx).highlighted(0), Some(i), "holding and dragging onto row {i} highlights it");
}
// Back up the way a user overshooting and correcting does.
for i in (1..=3).rev() {
let row = rows.get(i).unwrap();
h.event(egui::Event::PointerMoved(row.rect.center()));
h.run_steps(1);
assert_eq!(Nav::current(&h.ctx).highlighted(0), Some(i), "dragging back up to row {i} highlights it");
}
h.event(egui::Event::PointerButton { pos: rows.get(1).unwrap().rect.center(), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// A menu bar whose frames are `dt` seconds apart, as with a real pointer sending moves.
fn harness_dt(dt: f32) -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1280.0, 720.0)).with_step_dt(dt).build_ui_state(
+4 -4
View File
@@ -60,14 +60,14 @@ described in [development.md](development.md). UI tools require a running deskto
Use absolute root paths in MCP client configurations, since a relative root is resolved from
the client's launch directory. In bridge mode, configure roots on the **desktop app**; root
flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and
`--control-token-file` flags require `--bridge` and are mutually exclusive. Bridge credentials
can also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`.
`--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually
exclusive. Bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`.
MCP and `serve` launch options (all but `--help`/`-h`) take one non-empty value each and cannot
be repeated. Missing values, stray positional arguments and options for the wrong mode are
usage errors (exit 2), reported on stderr before the server starts; stdout stays available for
protocol messages. For `serve`, explicit credential flags require `--port`; stdio needs no
control token.
protocol messages. For `serve`, explicit credential flags require `--port` (or
`PHOTOCRAFT_CONTROL_PORT`); stdio needs no control token.
## Tools and resources