Merge main into #5345

# Conflicts:
#	crates/ui-egui/src/i18n/fr.tsv
#	crates/ui-egui/src/i18n/id.tsv
#	crates/ui-egui/src/i18n/ru.tsv
#	crates/ui-egui/src/i18n/zh-hans.tsv
#	crates/ui-egui/src/i18n/zh-hant.tsv
This commit is contained in:
Brandon Thomas committed 2026-10-15 00:23:25 -04:00
commit c38e8cb2f2
51 files changed
+1835 -155

No files matched your search

+35
View File
@@ -26,6 +26,25 @@ pub fn window_icon() -> egui::IconData {
}
}
/// Whether the window gets [`window_icon`] at runtime: everywhere except inside a macOS app
/// bundle. There the Dock shows the bundle's `PhotoCraft.icns` (`CFBundleIconFile`), which macOS
/// renders in its own style (Liquid Glass and its tinted and dark variants); a runtime PNG
/// replaced it with a flat picture (#5849). `exe` is the running executable.
pub fn sets_runtime_icon(exe: Option<&std::path::Path>) -> bool {
!(cfg!(target_os = "macos") && exe.is_some_and(in_app_bundle))
}
/// Whether `exe` is an app bundle's executable: `…/Name.app/Contents/MacOS/binary`.
fn in_app_bundle(exe: &std::path::Path) -> bool {
let name = |p: Option<&std::path::Path>| p.and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned());
let macos = exe.parent();
let contents = macos.and_then(std::path::Path::parent);
let bundle = contents.and_then(std::path::Path::parent);
name(macos).as_deref() == Some("MacOS")
&& name(contents).as_deref() == Some("Contents")
&& name(bundle).is_some_and(|n| n.len() > 4 && n.to_ascii_lowercase().ends_with(".app"))
}
#[cfg(target_os = "macos")]
const PNG: &[u8] = include_bytes!("../../../assets/app-icon/photocraft-1024.png");
#[cfg(not(target_os = "macos"))]
@@ -45,6 +64,22 @@ mod tests {
u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as usize
}
/// #5849: a macOS app bundle keeps its .icns in the Dock; unbundled runs (cargo run, the
/// Linux and Windows builds) still set the runtime icon.
#[test]
fn only_a_macos_app_bundle_skips_the_runtime_icon() {
use std::path::Path;
assert!(in_app_bundle(Path::new("/Applications/PhotoCraft.app/Contents/MacOS/photocraft")));
assert!(in_app_bundle(Path::new("/Users/a/Downloads/PhotoCraft Beta.APP/Contents/MacOS/photocraft")));
assert!(!in_app_bundle(Path::new("/Users/a/src/photocraft/target/release/photocraft")));
assert!(!in_app_bundle(Path::new("/opt/Contents/MacOS/photocraft")), "not inside a .app");
assert!(!in_app_bundle(Path::new("/.app/Contents/MacOS/photocraft")), "a bare `.app` is no bundle name");
assert!(!in_app_bundle(Path::new("photocraft")));
assert!(sets_runtime_icon(None));
assert!(sets_runtime_icon(Some(Path::new("/usr/bin/photocraft"))));
assert_eq!(sets_runtime_icon(Some(Path::new("/Applications/PhotoCraft.app/Contents/MacOS/photocraft"))), !cfg!(target_os = "macos"));
}
#[test]
fn window_icon_decodes() {
let icon = window_icon();
+4 -2
View File
@@ -78,9 +78,11 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool {
/// different offset every launch (#419). A later launch restores the saved position instead
/// (`main` turns `centered` off, #4826). Wayland compositors place windows themselves.
fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
let viewport = egui::ViewportBuilder::default();
// Not inside a macOS app bundle: its Dock icon is the bundle's .icns (`app_icon`, #5849).
let viewport = if app_icon::sets_runtime_icon(std::env::current_exe().ok().as_deref()) { viewport.with_icon(app_icon::window_icon()) } else { viewport };
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_icon(app_icon::window_icon())
viewport: viewport
.with_app_id(APP_ID)
.with_title("PhotoCraft")
.with_inner_size([1440.0, 900.0])
+68 -4
View File
@@ -4,8 +4,10 @@
//! The source rectangle is subdivided into a fine grid whose vertices are mapped forward; each
//! cell's two triangles are rasterized in destination space with the source position
//! interpolated barycentrically, then the source is sampled there (premultiplied, nearest /
//! bilinear / Photoshop's Keys bicubic, like Free Transform). Cells are a few source pixels across, so
//! the piecewise-affine inverse is within a small fraction of a pixel of the true one; affine
//! bilinear / Photoshop's Keys bicubic, like Free Transform). Cells are a few pixels across in
//! both the source and the destination (a thin layer stretched far gets as many cells as its
//! warped size needs), so the piecewise-affine inverse is within a small fraction of a pixel of
//! the true one; affine
//! maps (the identity included) are reproduced exactly. Where the warp shrinks the source, each
//! pixel instead averages a grid of bilinear subsamples over its source footprint (about one per
//! source pixel), so thin lines don't alias. Where the warp folds over itself the
@@ -77,8 +79,11 @@ pub fn warp_mesh_surface(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) ->
return Surface::new(PixelFormat::new(fmt.mode, fmt.sample, true));
}
let (sw, sh) = (f64::from(src_rect.width()), f64::from(src_rect.height()));
let nx = ((sw / CELL).ceil() as usize).clamp(1, MAX_CELLS);
let ny = ((sh / CELL).ceil() as usize).clamp(1, MAX_CELLS);
// Cells are a few pixels across on both sides of the map: a thin source stretched far (a
// 3 px column scaled into a wide band, then bent) needs many cells, or it comes out straight.
let (lu, lv) = mapped_lengths(src_rect, f);
let cells = |s: f64, d: f64| ((s.max(d) / CELL).ceil() as usize).clamp(1, MAX_CELLS);
let (nx, ny) = (cells(sw, lu), cells(sh, lv));
// Forward-mapped vertices (and their source positions).
let mut verts = Vec::with_capacity((nx + 1) * (ny + 1));
for j in 0..=ny {
@@ -101,6 +106,43 @@ pub fn warp_mesh_surface(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) ->
warp_triangles(src, src_rect, &verts, &tris, interp)
}
/// Probe lines per axis [`mapped_lengths`] follows through the map.
const PROBE: usize = 16;
/// The longest destination length of a source row and of a source column under `f`, measured
/// along polylines through a [`PROBE`]-step grid. Non-finite steps count as zero.
fn mapped_lengths(src_rect: Rect, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync)) -> (f64, f64) {
let (x0, y0) = (f64::from(src_rect.x0), f64::from(src_rect.y0));
let (sw, sh) = (f64::from(src_rect.width()), f64::from(src_rect.height()));
let n = PROBE + 1;
let mut pts = Vec::with_capacity(n * n);
for j in 0..n {
for i in 0..n {
let (dx, dy) = f(x0 + sw * i as f64 / PROBE as f64, y0 + sh * j as f64 / PROBE as f64);
pts.push([dx, dy]);
}
}
let step = |a: [f64; 2], b: [f64; 2]| {
let d = (b[0] - a[0]).hypot(b[1] - a[1]);
if d.is_finite() { d } else { 0.0 }
};
let (mut lu, mut lv) = (0.0f64, 0.0f64);
for k in 0..n {
let (mut row, mut col) = (0.0, 0.0);
for m in 1..n {
if let (Some(&a), Some(&b)) = (pts.get(k * n + m - 1), pts.get(k * n + m)) {
row += step(a, b);
}
if let (Some(&a), Some(&b)) = (pts.get((m - 1) * n + k), pts.get(m * n + k)) {
col += step(a, b);
}
}
lu = lu.max(row);
lv = lv.max(col);
}
(lu, lv)
}
/// Rasterizes textured triangles: each vertex is `(destination, source)` in document pixels and
/// each triangle samples `src` (restricted to `src_rect`) through the barycentric
/// interpolation of its source positions. Later triangles in `tris` draw over earlier ones (the
@@ -399,6 +441,28 @@ mod tests {
surf
}
#[test]
fn a_thin_layer_stretched_into_a_curve_keeps_the_curve() {
// #5793: a 3 px wide column stretched 100x and bent into an arch. The grid was sized in
// source pixels (one cell across), so the arch came out as a straight band.
let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
src.fill_rect(Rect::new(0, 0, 3, 40), &[1.0, 0.0, 0.0, 1.0]);
let arch = |x: f64, y: f64| {
let dx = x * 100.0;
let t = (dx - 150.0) / 150.0;
(dx, y + 40.0 * (1.0 - t * t))
};
let out = warp_mesh_surface(&src, Rect::new(0, 0, 3, 40), &arch, Interp::Bilinear);
let alpha = |x: i32, y: i32| {
let mut p = [0.0f32; 4];
out.read_pixel(x, y, &mut p);
p[3]
};
// The band follows the arch: 40 px lower in the middle, about 36 px a third of the way in.
assert!(alpha(150, 60) > 0.99 && alpha(150, 20) < 0.01, "mid {} {}", alpha(150, 60), alpha(150, 20));
assert!(alpha(100, 55) > 0.99 && alpha(100, 20) < 0.01, "third {} {}", alpha(100, 55), alpha(100, 20));
}
#[test]
fn a_mesh_warp_far_off_canvas_writes_only_the_two_regions() {
// #995: the old and warped regions were cleared as one dense `src ∪ warped` buffer, about
+22
View File
@@ -24,6 +24,22 @@ fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
/// Photoshop ExtendScript / UXP script suffixes — not PhotoCraft JSON or command lists.
fn extendscript_ext(path: &str) -> Option<&str> {
let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
let dot = name.rfind('.')?;
let ext = &name[dot + 1..];
let lower = ext.to_ascii_lowercase();
matches!(lower.as_str(), "js" | "jsx" | "jsxbin" | "psjs" | "ccjs").then_some(ext)
}
fn reject_extendscript(cmd: &str, path: &str) -> Result<()> {
match extendscript_ext(path) {
Some(_) => Err(bad(cmd, "PhotoCraft scripts are JSON or command lists (one command.id {json} per line), not Photoshop ExtendScript (.js/.jsx)")),
None => Ok(()),
}
}
/// Session state of the File-menu commands (not saved, not history).
#[derive(Clone, Debug, Default)]
pub struct FileMenuState {
@@ -127,6 +143,12 @@ fn run_steps(s: &mut Session, steps: &[(String, Value)]) -> Vec<Value> {
/// File › Scripts › Browse…: run a script file on the session.
fn browse(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.scripts.browse";
if let Some(path) = p.get("path").and_then(Value::as_str) {
reject_extendscript(cmd, path)?;
}
if let Some(name) = p.get("name").and_then(Value::as_str) {
reject_extendscript(cmd, name)?;
}
let steps = match (p.get("path").and_then(Value::as_str), p.get("script").and_then(Value::as_str), p.get("steps")) {
(Some(path), _, _) => parse_script(&String::from_utf8_lossy(&read_file(path)?))?,
(_, Some(text), _) => parse_script(text)?,
+21
View File
@@ -54,6 +54,27 @@ fn browse_runs_a_script_file() {
assert_eq!(r["results"].as_array().unwrap().len(), 1);
}
#[test]
fn browse_rejects_photoshop_extendscript() {
let dir = tmp("jsx");
let jsx = format!("{dir}/hello.jsx");
std::fs::write(&jsx, "alert('hi');\n").unwrap();
let mut s = Session::new();
let err = s.execute("file.scripts.browse", json!({"path": jsx})).unwrap_err().to_string();
assert!(err.contains("not Photoshop ExtendScript"), "{err}");
assert!(err.contains("JSON"), "{err}");
let js = format!("{dir}/hello.js");
std::fs::write(&js, "alert('hi');\n").unwrap();
assert!(s.execute("file.scripts.browse", json!({"path": js})).is_err());
let err = s.execute("file.scripts.browse", json!({"name": "Resize.jsx", "script": "alert(1);"})).unwrap_err().to_string();
assert!(err.contains(".js/.jsx"), "{err}");
// A JSON script still runs even if the file name is not a Photoshop suffix.
let json = format!("{dir}/rotate.json");
std::fs::write(&json, r#"[["file.new", {"width": 8, "height": 8}]]"#).unwrap();
let r = s.execute("file.scripts.browse", json!({"path": json})).unwrap();
assert_eq!(r["ok"], true);
}
#[test]
fn recording_browse_script_captures_each_effect_once() {
let mut s = Session::new();
+9
View File
@@ -885,6 +885,15 @@ pub fn preset_list(ui: &mut egui::Ui, presets: &[BrushPreset], current: Option<&
let show = (st.show_name, st.show_stroke, st.show_tip);
let collapsed = &st.collapsed;
egui::ScrollArea::vertical().id_salt(layout.id).max_height(layout.max_height).auto_shrink([false, true]).show(ui, |ui| {
// A preset, group or folder dragged to the list's top or bottom edge (or past it) scrolls
// the list, as the Layers panel's rows do, so it can be dropped on rows out of view (#5741).
let dragging = egui::DragAndDrop::has_payload_of_type::<BrushDrag>(ui.ctx()) && ui.input(|i| i.pointer.primary_down());
let pointer = ui.ctx().pointer_interact_pos();
let delta = crate::panels::layer_drag_edge_scroll(pointer, ui.clip_rect(), dragging, ui.input(|i| i.stable_dt));
if delta != 0.0 {
ui.scroll_with_delta(vec2(0.0, delta));
ui.ctx().request_repaint();
}
ui.spacing_mut().item_spacing.y = 1.0;
for (label, items) in grouped_presets(presets) {
let items: Vec<&BrushPreset> =
+37
View File
@@ -51,6 +51,43 @@ fn dragging_a_brush_shows_its_tip_preview() {
}
}
/// #5741: a brush dragged to the list's bottom edge (or below it) scrolls the list, so it can be
/// dropped on rows out of view; the list used to stay put, and the drag stopped at the last
/// visible row.
#[test]
fn dragging_a_brush_to_the_list_edge_scrolls_the_list() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.ui.panels.brush_settings = true;
app.ui.brush_tab = 1;
app.ui.brushes_panel.view = BrushesView::List;
app.ui.brushes_panel.collapsed.clear();
let name = app.session.tools.presets[0].name.clone();
let (w, h_px) = (1200.0, 520.0);
let mut h = Harness::builder().with_size(vec2(w, h_px)).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]);
app
});
h.run_steps(4);
let start = h.get_by_role_and_label(Role::Button, &name).rect();
h.hover_at(start.center());
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: start.center(), button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
h.run_steps(1);
h.event(egui::Event::PointerMoved(start.center() + vec2(0.0, 12.0)));
h.run_steps(2);
assert!(egui::DragAndDrop::has_payload_of_type::<BrushDrag>(&h.ctx), "the brush is being dragged");
// Held at the bottom of the window, below the list's last visible row.
let bottom = egui::pos2(start.center().x, h_px - 2.0);
for _ in 0..12 {
h.event(egui::Event::PointerMoved(bottom));
h.run_steps(1);
}
let moved = h.query_by_role_and_label(Role::Button, &name).map(|n| n.rect());
assert!(moved.is_none_or(|r| r.top() < start.top() - 1.0), "the list scrolled down: {start:?} → {moved:?}");
h.event(egui::Event::PointerButton { pos: bottom, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(2);
}
#[test]
fn grid_columns_centre_whole_columns_past_the_indent() {
// 6 × 44 + 5 × 3 = 279 of the 290 past a 4 pt indent: 5 spare on each side (rounded down).
+101 -18
View File
@@ -1924,14 +1924,22 @@ fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option
/// If a live adjustment preview is active on a large document, composite it on the proxy and upload
/// it under its own GPU key. Returns (factor, gpu key, dimensions) when the proxy should be drawn.
fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64, [u32; 2])> {
/// `zoom` is the view's (physical screen pixels per document pixel).
fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> {
let (layer, params) = app.live_adjust.clone()?;
let (doc_id, revision, doc) = {
let st = app.session.documents().get(idx)?;
(st.doc.id, st.revision, st.doc.clone())
};
// Low-resolution previews off: k is 1 and the canvas shows `display_doc` (full size).
let k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app));
let mut k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app));
// Zoomed in, a proxy coarser than the screen showed the drag in k-pixel blocks (#5764): when
// the wgpu compositor draws the full-size document, use a proxy only as coarse as the screen
// (none at 50 % and closer). Otherwise the full size would be a CPU composite per change.
let fine = crate::proxy::view_factor(k, zoom);
if fine < k && app.gpu.as_ref().is_some_and(|g| g.supports(&doc)) {
k = fine;
}
if k <= 1 {
return None;
}
@@ -2962,7 +2970,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if app.gpu.is_some()
&& gpu_ok
&& let Some((k, key, preview_size)) =
ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx))
ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx, view.zoom))
{
on_gpu = true;
app.navigator_gpu.remove(&doc.id);
@@ -3195,12 +3203,14 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let bars_id = egui::Id::new(("pc-canvas-bars-hover", idx));
let over_bars = ctx.data(|d| d.get_temp::<bool>(bars_id)).unwrap_or(false);
let nav_hovered = response.hovered() || free_hover || over_bars;
let wheel = crate::wheel_nav::read(
// Interface › Enable Animations off: the wheel moves the canvas without a glide (#5721).
let wheel = crate::wheel_nav::read_with(
&ctx,
app.session.prefs().general.zoom_with_scroll_wheel,
app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch,
response.id.with("wheel"),
nav_hovered,
app.session.prefs().interface.enable_animations,
);
if nav_hovered {
let pointer = ui.input(|i| i.pointer.hover_pos());
@@ -3302,7 +3312,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
primary && app.ui.dialogs.last().is_some_and(|d| crate::select_mask_view::owns(&d.fields) && crate::select_mask_view::brush_on(&d.fields));
// Field Blur's pins are placed and dragged on the image (`blur_pins`).
let pinning = primary && app.ui.dialogs.last().is_some_and(|d| crate::blur_pins::owns(&d.fields));
let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning;
// Layer Style on a Drop or Inner Shadow page: a drag on the image moves the shadow (#5701).
let shadow_drag =
!picking && app.ui.dialogs.last().is_some_and(|d| d.kind == crate::state::DialogKind::LayerStyle && crate::layer_style::drags_shadow(&d.fields));
let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning && !shadow_drag;
if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) {
let d = xf.unmap_vec(d) / (view.zoom / ppp);
view.center[0] -= d.x;
@@ -3310,6 +3323,15 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, true));
} else if free_hover && (space_pan || hand) {
ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, false));
} else if shadow_drag && !middle && crate::dialogs::free_pointer_over(&ctx, rect).is_some() {
ctx.set_cursor_icon(egui::CursorIcon::Move);
if let Some(p) = crate::dialogs::free_press(&ctx, rect) {
let (start, origin) = ctx.input(|i| (i.pointer.primary_pressed(), i.pointer.press_origin().unwrap_or(p)));
let total = xf.unmap_vec(p - origin) / (view.zoom / ppp);
if let Some(d) = app.ui.dialogs.last_mut() {
crate::layer_style::drag_shadow(&mut d.fields, start, [f64::from(total.x), f64::from(total.y)]);
}
}
} else if picking && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect) {
if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise {
ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
@@ -3820,8 +3842,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// corner badge, as Photoshop's corner radius cursor.
ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
crate::icons::cursor_badge(&ctx, "scan", p);
} else if let Some((r, p, c)) =
response.hover_pos().and_then(|p| transform_controls_rect(app, &xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c))))
} else if let Some((r, p, c)) = response
.hover_pos()
.filter(|_| !transform_controls_several(app))
.and_then(|p| transform_controls_rect(app, &xf).and_then(|r| transform_controls_cursor(r, p).map(|c| (r, p, c))))
{
// The Move tool draws handles without opening a Free Transform session.
// Give them their resize/rotate cursors before the first pointer press (#2871).
@@ -3991,7 +4015,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
{
egui::CursorIcon::Crosshair
}
Tool::Move => egui::CursorIcon::Move,
// Photoshop's Move tool keeps the standard arrow pointer (#5646): the movable
// layer under it is marked by the hover outline, not by a different cursor.
Tool::Move => egui::CursorIcon::Default,
// Dragging is handled with the pan itself, above.
Tool::Hand => crate::tool_cursor::hand(ui.ctx(), false),
Tool::RotateView => crate::rotate_view::cursor(response.dragged()),
@@ -4653,23 +4679,36 @@ pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option<photoc
Some(b.translate(dx, dy))
}
/// Move tool › Show Transform Controls: the box Free Transform would open on the active layer.
fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option<Rect> {
// A corner radius drag hides the box, as in Photoshop.
/// The layers Move › Show Transform Controls frames: every selected layer but the Background.
/// A corner radius drag hides the box, as in Photoshop.
fn transform_controls_layers(app: &PhotocraftApp) -> Vec<&photocraft_doc::Layer> {
if app.ui.tool != Tool::Move
|| !app.ui.tool_options.move_show_transform
|| app.ui.transform.is_some()
|| app.drag.is_some()
|| app.ui.corner_radius.is_some()
{
return None;
return Vec::new();
}
let Some(st) = app.session.active() else { return Vec::new() };
st.selected_layers().into_iter().filter_map(|id| st.doc.layer(id)).filter(|l| !crate::doc_props_ui::is_background(&st.doc, l)).collect()
}
/// Several layers are selected: Show Transform Controls frames them all, as Photoshop does, but
/// Free Transform works on one layer, so the frame has no handles to scale or rotate them.
fn transform_controls_several(app: &PhotocraftApp) -> bool {
transform_controls_layers(app).len() > 1
}
/// Move tool › Show Transform Controls: the boxes Free Transform would open on the selected
/// layers, joined into one.
fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option<Rect> {
let st = app.session.active()?;
let l = st.active_layer.and_then(|id| st.doc.layer(id))?;
if crate::doc_props_ui::is_background(&st.doc, l) {
return None;
}
let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, l);
let b = transform_controls_layers(app)
.into_iter()
.map(|l| photocraft_engine::transform_cmds::transform_frame(&st.doc, l))
.filter(|b| !b.is_empty())
.reduce(|a, b| a.union(&b))?;
let (dx, dy) = crate::move_ui::floating_offset(app).unwrap_or((0, 0));
let b = b.translate(dx, dy);
if b.is_empty() {
@@ -4726,6 +4765,9 @@ fn transform_controls_hit(r: Rect, p: Pos2) -> bool {
/// Enter the existing Free Transform session when a Move-tool transform control is pressed.
fn begin_transform_controls_at(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, p: Pos2) -> bool {
if transform_controls_several(app) {
return false;
}
let Some(r) = transform_controls_rect(app, xf) else { return false };
if !transform_controls_hit(r, p) {
return false;
@@ -4739,11 +4781,21 @@ fn begin_transform_controls_at(app: &mut PhotocraftApp, ctx: &egui::Context, xf:
}
}
/// Move tool › Show Transform Controls: the active layer's bounding box with its eight handles.
/// Move tool › Show Transform Controls: the selected layers' bounding box, with its eight handles
/// for one layer, and the outline of every selected shape layer, as in Photoshop.
fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
let Some(r) = transform_controls_rect(app, xf) else { return };
let accent = crate::theme::Tokens::get(painter.ctx()).accent;
let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32);
for l in transform_controls_layers(app) {
if let LayerContent::Shape(sh) = &l.content {
crate::vector_ui::draw_outline(painter, &sh.path, &to_scr, accent);
}
}
painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Middle);
if transform_controls_several(app) {
return;
}
for p in [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] {
let h = Rect::from_center_size(p, vec2(7.0, 7.0));
painter.rect_filled(h, 0.0, Color32::WHITE);
@@ -8085,6 +8137,37 @@ mod transform_controls_tests {
use super::*;
use serde_json::json;
#[test]
fn several_selected_layers_share_one_frame_without_handles() {
// As in Photoshop: Show Transform Controls frames every selected layer. Free Transform
// works on one layer, so the shared frame doesn't start it.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();
app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 40, 40], "fill": "#ff0000"})).unwrap();
let a = app.session.active().unwrap().active_layer.unwrap();
app.session.execute("shape.create", json!({"kind": "rect", "rect": [100, 120, 50, 30], "fill": "#ff0000"})).unwrap();
app.sync_views();
app.ui.tool = Tool::Move;
app.ui.tool_options.move_show_transform = true;
let xf =
ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 };
let one = transform_controls_rect(&app, &xf).unwrap();
assert!(!transform_controls_several(&app));
app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap();
assert!(transform_controls_several(&app));
let both = transform_controls_rect(&app, &xf).unwrap();
assert!(both.contains_rect(one) && both.width() > one.width() && both.height() > one.height(), "{both:?} frames both");
let (lt, rb) = (xf.to_doc(both.left_top()), xf.to_doc(both.right_bottom()));
assert!((lt[0] - 20.0).abs() < 1e-3 && (lt[1] - 30.0).abs() < 1e-3 && (rb[0] - 150.0).abs() < 1e-3 && (rb[1] - 150.0).abs() < 1e-3, "{lt:?} {rb:?}");
let ctx = egui::Context::default();
assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, both.right_bottom()));
assert!(app.ui.transform.is_none());
// The Background never joins the frame.
let bg = app.session.active().unwrap().doc.layers[0].id;
app.session.execute("layer.select", json!({"layer": bg.0, "mode": "add"})).unwrap();
assert_eq!(transform_controls_layers(&app).len(), 2);
}
#[test]
fn move_transform_controls_start_free_transform_for_vector_shapes() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+67 -1
View File
@@ -330,7 +330,11 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
let load = icons::button(ui, "circle-dashed", 26.0, false, tl!("Load channel as selection"));
if load.clicked() {
actions.push(("select.loadSelection".into(), json!({ "channel": target_ref })));
// The selected mask row can coexist with a Composite engine target while mask
// painting is active. The footer follows the row the user sees as targeted.
let params =
if mask_targeted { json!({ "channel": "mask", "layer": masked.as_ref().map(|layer| layer.id.0) }) } else { json!({ "channel": target_ref }) };
actions.push(("select.loadSelection".into(), params));
}
actions.extend(drop(ui, &load, Footer::Load));
});
@@ -615,6 +619,68 @@ mod tests {
assert!(h.state().session.active().unwrap().doc.selection.is_some(), "the white channel selects everything");
}
/// The footer follows the targeted row shown by the panel when mask painting is active,
/// even though the engine's channel-view target remains Composite. Other channel targets
/// continue to load their own values, and each load remains one undoable selection change.
#[test]
fn footer_loads_the_selected_layer_mask_and_preserves_color_alpha_targets() {
let (mut h, _) = channels_harness();
h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap();
h.state_mut().run("layer.layerMask.hideAll", json!({})).unwrap();
h.state_mut().run("layer.layerMask.revealSelection", json!({})).unwrap();
h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap();
h.state_mut().ui.mask_target = true;
h.run_steps(2);
let click_load = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| {
use egui::{Modifiers, PointerButton};
let p = at(h, "Load channel as selection");
h.hover_at(p);
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
};
let sample =
|h: &egui_kittest::Harness<'_, PhotocraftApp>, x, y| h.state().session.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(x, y, 0);
assert_eq!(h.state().session.active().unwrap().channel_view.target, ChannelTarget::Composite);
click_load(&mut h);
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "mask row selection wins over the Composite engine target");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert!(h.state().session.active().unwrap().doc.selection.is_none());
h.state_mut().run("edit.redo", json!({})).unwrap();
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0));
h.state_mut().ui.mask_target = false;
h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap();
click_load(&mut h);
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "composite luminosity remains available");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0));
h.state_mut().run("edit.redo", json!({})).unwrap();
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0));
h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap();
h.state_mut().run("channel.new", json!({"fill": "selection"})).unwrap();
h.state_mut().run("select.deselect", json!({})).unwrap();
h.state_mut().run("channel.target", json!({"channel": "red"})).unwrap();
click_load(&mut h);
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "color channel still loads its own plane");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.state_mut().run("edit.redo", json!({})).unwrap();
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0));
h.state_mut().run("channel.target", json!({"channel": 1})).unwrap();
click_load(&mut h);
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "alpha channel still loads its own plane");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0));
h.state_mut().run("edit.redo", json!({})).unwrap();
assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0));
}
/// A plain click on a row still targets it, and a drag released elsewhere does nothing.
#[test]
fn clicks_still_target_and_a_drop_elsewhere_does_nothing() {
+111 -4
View File
@@ -135,6 +135,26 @@ fn show_modal<T>(
})
}
/// Whether dialogs have a close box (×) in their title bar (#5496). Photoshop's modal dialogs have
/// one on Windows, where clicking it is Cancel, and none on macOS; Linux and the web follow Windows.
pub(crate) const CLOSE_BOX: bool = !cfg!(target_os = "macos");
/// The side of the close box's square, in points.
const CLOSE_BOX_SIZE: f32 = 20.0;
/// The close box's square: flush with the title band's right end `right`, centred on the title
/// row at height `centre_y`.
fn close_box_rect(right: f32, centre_y: f32) -> egui::Rect {
egui::Rect::from_min_size(egui::pos2(right - CLOSE_BOX_SIZE, centre_y - CLOSE_BOX_SIZE / 2.0), egui::vec2(CLOSE_BOX_SIZE, CLOSE_BOX_SIZE))
}
/// Draws a title bar's close box in `rect`, the same × icon button the floating panels close with,
/// and says whether it was clicked. Its own child `Ui`, so the title row's layout is unchanged.
pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::right_to_left(egui::Align::Center)));
crate::icons::button(&mut child, "x", CLOSE_BOX_SIZE, false, tl!("Close")).clicked()
}
pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
crate::layer_style::color_picker::prune(app);
crate::type_panels_ui::color_picker::prune(app);
@@ -163,6 +183,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let place = place_id(&d);
let start = pinned.or_else(|| ctx.data_mut(|m| m.get_persisted::<egui::Vec2>(place))).or_else(|| crate::blur_pins::first_place(&d.fields, ctx));
let mut drag = egui::Vec2::ZERO;
let mut close_clicked = false;
let mut sizing = false;
let area = match start {
Some(offset) => egui::Modal::default_area(id).anchor(egui::Align2::LEFT_TOP, offset),
@@ -242,8 +263,15 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let t = if crate::color_picker_ui::owns(&fields) { ui.add_sized(egui::vec2(ui.available_width(), 22.0), label).rect } else { ui.add(label).rect };
// The whole title band drags (#1921): the full width plus a little of the popup's
// padding around it and the gap above the hairline, but none of the controls below.
let bar = egui::Rect::from_min_max(t.min - egui::vec2(7.0, 7.0), egui::pos2(ui.max_rect().right() + 7.0, t.bottom() + 4.0));
// The close box (#5496) sits at the band's right end and is left out of the drag area:
// egui would let a drag that starts on a button move the dialog.
let close_rect = CLOSE_BOX.then(|| close_box_rect(ui.max_rect().right(), t.center().y));
let bar_right = close_rect.map_or(ui.max_rect().right() + 7.0, |r| r.left());
let bar = egui::Rect::from_min_max(t.min - egui::vec2(7.0, 7.0), egui::pos2(bar_right, t.bottom() + 4.0));
drag = ui.interact(bar, id.with("title"), egui::Sense::drag()).drag_delta();
if let Some(r) = close_rect {
close_clicked = close_box(ui, r);
}
ui.add_space(4.0);
crate::widgets::hairline(ui);
ui.add_space(8.0);
@@ -458,11 +486,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
ctx.data_mut(|m| m.insert_persisted(place, offset));
}
}
// Esc cancels (topmost dialog, no popup open). A click outside does nothing: Photoshop keeps
// the dialog, and the pointer may be panning or zooming the canvas under it.
// Esc and the title bar's close box cancel (topmost dialog, no popup open for Esc). A click
// outside does nothing: Photoshop keeps the dialog, and the pointer may be panning or
// zooming the canvas under it.
if interactive
&& outcome.is_none()
&& (modal.response.should_close()
&& (close_clicked
|| modal.response.should_close()
|| (modal.is_top_modal && !modal.any_popup_open && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))))
{
outcome = Some(false);
@@ -735,6 +765,83 @@ mod tests {
assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), None);
}
/// #5496: a pointer click on the title bar's close box does what Cancel does: the dialog
/// closes, the live preview goes and nothing reaches the document or the journal. On macOS
/// dialogs have no close box.
#[test]
fn the_title_bar_close_box_cancels_like_cancel() {
use egui_kittest::kittest::Queryable;
let close = |button: &str| {
let (mut app, _) = filter_dialog_with_preview(false);
let revision = app.session.active().unwrap().revision;
let journal = app.session.journal.len();
// The fonts are set up after the harness's first frame: the dialog appears after it.
let dialogs = std::mem::take(&mut app.ui.dialogs);
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.state_mut().ui.dialogs = dialogs;
h.run_steps(4);
assert!(h.state().filter_preview.is_some(), "the preview is on screen");
if !CLOSE_BOX {
assert_eq!(h.query_all_by_label("Close").count(), 0, "no close box on macOS");
}
let target = h.query_by_label(button).map(|n| n.rect().center())?;
h.hover_at(target);
h.drag_at(target);
h.drop_at(target);
h.run_steps(3);
let app = h.state();
Some((
app.ui.dialogs.is_empty(),
app.filter_preview.is_none(),
app.session.active().unwrap().revision == revision,
app.session.journal.len() == journal,
))
};
let cancel = close("Cancel");
assert_eq!(cancel, Some((true, true, true, true)), "Cancel closes, drops the preview and changes nothing");
if CLOSE_BOX {
assert_eq!(close("Close"), cancel, "the × is Cancel");
}
}
/// #5496: the close box sits at the title band's right end, and the band stays a drag handle
/// around it: a drag that starts on the × neither moves nor closes the dialog, and the band
/// just left of the × still moves it.
#[test]
fn the_close_box_and_the_title_drag_keep_apart() {
use egui_kittest::kittest::Queryable;
if !CLOSE_BOX {
return;
}
let mut h = dialog_harness(egui::vec2(1280.0, 800.0), "filter.blur.gaussianBlur");
let title = h.get_by_label("Gaussian Blur").rect();
let x = h.get_by_label("Close").rect();
let frame = rects(&h.ctx)[0];
assert!((x.center().y - title.center().y).abs() < 2.0 && x.left() > title.right(), "the × is on the title row: {x:?}, {title:?}");
assert!(frame.right() - x.right() < 16.0, "at its right end: {x:?} in {frame:?}");
let drag = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2| {
h.hover_at(from);
h.drag_at(from);
h.run_steps(2);
for i in 1..=8 {
h.hover_at(from + (to - from) * (i as f32 / 8.0));
h.run_steps(1);
}
h.drop_at(to);
h.run_steps(3);
};
drag(&mut h, x.center(), x.center() + egui::vec2(-80.0, 60.0));
assert_eq!(h.state().ui.dialogs.len(), 1, "a drag from the × doesn't close the dialog");
assert!((h.get_by_label("Gaussian Blur").rect().min - title.min).length() < 1.0, "nor move it");
let x = h.get_by_label("Close").rect();
let beside = x.left_center() - egui::vec2(4.0, 0.0);
drag(&mut h, beside, beside + egui::vec2(-120.0, 40.0));
assert_eq!(h.state().ui.dialogs.len(), 1, "a title drag doesn't close the dialog");
let moved = h.get_by_label("Gaussian Blur").rect().min - title.min;
assert!((moved - egui::vec2(-120.0, 40.0)).length() < 2.0, "the band beside the × moved the dialog: {moved:?}");
}
#[test]
fn color_picker_has_inset_content_and_actions_at_the_right_edge() {
use egui_kittest::{Harness, kittest::Queryable};
+8 -2
View File
@@ -94,6 +94,11 @@ pub enum Edit {
}
impl Edit {
/// The drag's end with ⇧ held: moving anchors locks to multiples of 45°, as in Photoshop (#5475).
fn constrain(&self, start: [f64; 2], p: [f64; 2], shift: bool) -> [f64; 2] {
if shift && matches!(self, Edit::Anchors(_)) { crate::stroke_constraint::snap45(start, p) } else { p }
}
/// The edit for a drag from `start` to `end`, as a command and its params (without target).
fn command(&self, start: [f64; 2], end: [f64; 2]) -> (&'static str, Value) {
let d = [end[0] - start[0], end[1] - start[1]];
@@ -238,7 +243,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool
let ds = &mut app.ui.direct_selection;
match &mut ds.drag {
Some(Drag::Edit { base, edit, start, end, preview, .. }) => {
*end = [x, y];
*end = edit.constrain(*start, [x, y], mods.shift);
*preview = edit.preview(base, *start, *end);
}
Some(Drag::Marquee { end, .. }) => *end = [x, y],
@@ -248,7 +253,8 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool
}
ToolEvent::Up { x, y } => match app.ui.direct_selection.drag.take() {
Some(Drag::Edit { target, base, edit, start, .. }) => {
release(app, target, &base, &edit, start, [x, y]);
let end = edit.constrain(start, [x, y], mods.shift);
release(app, target, &base, &edit, start, end);
app.ui.direct_selection.coalesce = None;
true
}
+22
View File
@@ -326,6 +326,28 @@ fn arrow_keys_nudge_the_selected_anchors() {
assert_eq!(work(&app), before);
}
/// #5475: ⇧ during an anchor drag locks it to 45°, whether it's held from the press or added later.
#[test]
fn shift_locks_an_anchor_drag_to_45_degrees() {
let mut app = app(Tool::DirectSelection);
with_path(&mut app);
tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE);
tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 44.0, pressure: 1.0 }, Modifiers::SHIFT);
let Some(Drag::Edit { preview: Some(p), .. }) = &app.ui.direct_selection.drag else { panic!("dragging") };
assert_eq!(p.subpaths[0].knots[0].anchor, Point::new(70.0, 40.0), "the preview is locked too");
tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 47.0 }, Modifiers::SHIFT);
assert_eq!(anchor(&app, 0), Point::new(100.0, 40.0));
// Diagonal, and without ⇧ the drag stays free.
// (⇧ at the press would deselect the anchor, so it comes once the drag is under way.)
tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE);
tool_event(&mut app, ToolEvent::Up { x: 131.0, y: 69.0 }, Modifiers::SHIFT);
let a = anchor(&app, 0);
assert!((a.x - 130.0).abs() < 1e-9 && (a.y - 70.0).abs() < 1e-9, "{a:?}");
drag(&mut app, [130.0, 70.0], [140.0, 73.0], Modifiers::NONE);
assert_eq!(anchor(&app, 0), Point::new(140.0, 73.0));
}
#[test]
fn the_curvature_pen_drags_an_anchor_of_the_active_path_without_a_modifier() {
// As in Photoshop: with no path being drawn, pressing an anchor and dragging moves it.
+38 -12
View File
@@ -265,7 +265,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
vec![(ButtonRole::Default, "Yes", Some(Key::Y), 84.0, Answer::Save), (ButtonRole::Alternate, "No", Some(Key::N), 84.0, Answer::Discard), cancel]
};
let mut answer = ctx.input_mut(|i| buttons.iter().find(|b| b.2.is_some_and(|k| i.consume_key(egui::Modifiers::NONE, k))).map(|b| b.4));
let labels: Vec<String> = buttons.iter().map(|b| button_label(mac, b.1, b.2)).collect();
let labels = button_labels(mac, &buttons.iter().map(|b| (b.1, b.2)).collect::<Vec<_>>());
let row: Vec<DialogButton> = buttons.iter().zip(&labels).map(|(b, label)| DialogButton::new(b.0, label, b.3)).collect();
let modal = egui::Modal::new(egui::Id::new("discard-prompt")).show(ctx, |ui| {
ui.set_max_width(420.0);
@@ -361,17 +361,30 @@ enum Answer {
}
/// macOS keeps the plain button wording even though the keyboard shortcuts still work.
#[cfg(test)]
fn button_label(mac: bool, label: &str, key: Option<Key>) -> String {
if mac { tl!(label).to_string() } else { key.map_or_else(|| tl!(label).to_string(), |k| mnemonic(label, k)) }
button_labels(mac, &[(label, key)]).into_iter().next().unwrap_or_default()
}
/// "(S)ave": the key in parentheses, or appended ("Guardar (S)") when the translation doesn't start with it.
fn mnemonic(label: &str, key: Key) -> String {
let (label, k) = (tl!(label), key.name());
match label.split_at_checked(1) {
Some((first, rest)) if first.eq_ignore_ascii_case(k) => format!("({first}){rest}"),
_ => format!("{label} ({k})"),
}
/// The labels of one dialog's buttons, each with its key in the same style: "(Y)es" when every
/// translation starts with its key, otherwise appended to all ("Ja (Y)", "Nein (N)") (#5564).
fn button_labels(mac: bool, buttons: &[(&str, Option<Key>)]) -> Vec<String> {
let starts_with_key = |label: &str, k: Key| label.split_at_checked(1).is_some_and(|(first, _)| first.eq_ignore_ascii_case(k.name()));
let inline = buttons.iter().all(|&(label, key)| key.is_none_or(|k| starts_with_key(tl!(label), k)));
buttons
.iter()
.map(|&(label, key)| {
let text = tl!(label);
match key {
None => text.to_string(),
Some(_) if mac => text.to_string(),
Some(k) => match text.split_at_checked(1) {
Some((first, rest)) if inline => format!("({first}){rest}"),
_ => format!("{text} ({})", k.name()),
},
}
})
.collect()
}
#[cfg(test)]
@@ -529,9 +542,9 @@ mod tests {
#[test]
fn mnemonic_labels_bracket_the_key() {
assert_eq!(mnemonic("Don't Save", Key::D), "(D)on't Save");
assert_eq!(mnemonic("Guardar", Key::S), "Guardar (S)");
assert_eq!(mnemonic("保存", Key::S), "保存 (S)");
assert_eq!(button_label(false, "Don't Save", Some(Key::D)), "(D)on't Save");
assert_eq!(button_label(false, "Guardar", Some(Key::S)), "Guardar (S)");
assert_eq!(button_label(false, "保存", Some(Key::S)), "保存 (S)");
}
type Prompted = egui_kittest::Harness<'static, PhotocraftApp>;
@@ -668,6 +681,19 @@ mod tests {
assert_eq!(button_label(false, "Cancel", Some(Key::C)), "(C)ancel");
}
/// German "Ja" doesn't start with Y, so every button appends its key rather than mixing
/// "Ja (Y)" with "(N)ein" (#5564).
#[test]
fn one_dialog_shows_every_key_in_the_same_style() {
let buttons = [("Yes", Some(Key::Y)), ("No", Some(Key::N)), ("Cancel", Some(Key::C))];
assert_eq!(button_labels(false, &buttons), ["(Y)es", "(N)o", "(C)ancel"]);
let german = crate::i18n::Lang::from_code("de").unwrap();
crate::i18n::with_language(german, || {
assert_eq!(button_labels(false, &buttons), ["Ja (Y)", "Nein (N)", "Abbrechen (C)"]);
assert_eq!(button_labels(true, &buttons), ["Ja", "Nein", "Abbrechen"]);
});
}
#[test]
fn macos_asks_dont_save_cancel_save_with_the_default_last() {
let mut h = prompt_on(egui::os::OperatingSystem::Mac);
+14 -1
View File
@@ -329,10 +329,23 @@ fn scripts_browse_lists_only_script_files() {
assert!(matches!(
open.borrow().first().map(|(r, _)| r),
Some(FileDialogRequest::Open { multiple: false, extensions: Some(exts), .. })
if exts.iter().map(String::as_str).collect::<Vec<_>>() == ["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt"]
if exts.iter().map(String::as_str).collect::<Vec<_>>() == ["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt", "pcdroplet"]
));
}
#[test]
fn scripts_browse_extendscript_picks_report_the_error() {
// Photoshop scripts stay in the picker (matching its filter) and choosing one shows why it won't run.
let (mut app, open, _) = app();
let ctx = egui::Context::default();
menus::invoke(&mut app, &ctx, "file.scripts.browse", json!({})).unwrap();
app.poll_file_dialog(&ctx, None);
answer(&open, Some(FileDialogAnswer::Contents("resize.jsx".into(), b"alert('hi');".to_vec())));
app.poll_file_dialog(&ctx, None);
assert!(app.ui.status_error);
assert!(app.ui.status.contains("not Photoshop ExtendScript"), "{}", app.ui.status);
}
#[test]
fn last_used_dir_takes_the_most_recent_parent() {
assert_eq!(last_used_dir(&[]), None);
+23
View File
@@ -572,6 +572,29 @@ fn a_drop_slot_counts_documents_not_the_tabs_shown() {
assert_eq!(crate::canvas::TabStrip { rect: strip.rect, tabs: vec![] }.slot(10.0), 0);
}
/// #5687: files dropped from another app's window bring PhotoCraft to the front (a focus request
/// in the frame that takes the drop), so the source window ends up behind it.
#[test]
fn a_drop_brings_the_window_to_the_front() {
let dir = std::env::temp_dir().join(format!("photocraft-drop-focus-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("photo.png");
std::fs::write(&file, png_bytes(8, 8)).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).with_max_steps(8).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
PhotocraftApp::new(photocraft_engine::Session::new(), Services::default())
});
h.run_steps(2);
let focus = |h: &egui_kittest::Harness<'_, PhotocraftApp>| {
h.output().viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.commands.contains(&egui::ViewportCommand::Focus))
};
assert!(!focus(&h), "no focus request without a drop");
h.input_mut().dropped_files.push(dropped(file, Err("read from the path".into())));
h.step();
assert!(focus(&h), "the drop brings the window forward");
let _ = std::fs::remove_dir_all(&dir);
}
/// The whole app (eframe harness, real layout): over the tab strip, the pointer read from the OS
/// service picks a slot; files dropped there open (in the background) at it; dropped on the canvas they're placed in Free Transform, and Esc takes the place back.
#[test]
+5 -3
View File
@@ -55,8 +55,10 @@ fn form(app: &mut PhotocraftApp, command: &str, label: &str, fields: Value, choi
json!({"dialog": app.ui.open_dialog(DialogKind::Command, f)})
}
/// File › Scripts › Browse… lists these script files (plus the JSON/text the engine parses).
const SCRIPT_EXTENSIONS: &[&str] = &["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt"];
/// File › Scripts › Browse… lists Photoshop's script types (matching its filter, #2452) plus the
/// JSON/text/droplet files the engine parses; selecting a Photoshop script gets the engine's
/// "not Photoshop ExtendScript" error instead of hiding those files from the picker.
const SCRIPT_EXTENSIONS: &[&str] = &["psjs", "ccjs", "jsx", "js", "jsxbin", "json", "txt", "pcdroplet"];
/// Menu items fronted here (dialogs before the engine command). `None` when not ours.
pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
@@ -104,7 +106,7 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V
"file.scripts.statistics" => json!({"dialog": crate::stack_dialog::open_statistics(app)}),
"file.scripts.browse" => {
return Some(app.pick_file_bytes_filtered(SCRIPT_EXTENSIONS, |app, name, bytes| {
let r = app.run("file.scripts.browse", json!({"script": String::from_utf8_lossy(&bytes)}));
let r = app.run("file.scripts.browse", json!({"name": name, "script": String::from_utf8_lossy(&bytes)}));
if r.is_ok() {
let template = "Ran script {name}";
app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]);
+36
View File
@@ -822,6 +822,11 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
ui.horizontal(|ui| {
ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim));
crate::widgets::value_field(ui, &mut v, -30000.0..=30000.0, "", 80.0);
// A seed gets a fresh random value in one click (#5710): Clouds, Add Noise,
// Fibers… then render a new pattern, as each run of Photoshop's does.
if p.key == "seed" && ui.button(tl!("Random")).clicked() {
v = random_seed(ui.input(|i| i.time).to_bits(), v as i64) as f32;
}
});
f.insert(p.key, json!(v.round() as i64));
}
@@ -839,6 +844,15 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
}
}
/// A new seed for a dialog's Random button: 0..=30000 (what the field takes), never `current`.
/// `entropy` varies per click (the input time); the process's random hasher keys mix it.
fn random_seed(entropy: u64, current: i64) -> i64 {
use std::hash::BuildHasher;
let h = std::collections::hash_map::RandomState::new().hash_one(entropy);
let seed = (h % 30_001) as i64;
if seed == current { (seed + 1) % 30_001 } else { seed }
}
/// User-facing params (strip the dialog's private `__` keys).
pub fn params_of(f: &Map<String, Value>) -> Value {
// A document picker left at "None" (-1) means "not given".
@@ -1005,6 +1019,28 @@ impl FilterPreviewKey {
mod tests {
use super::*;
/// #5710: the seed field's Random button always gives a different seed the field can hold.
#[test]
fn random_seeds_stay_in_range_and_change() {
let mut seen = std::collections::HashSet::new();
for i in 0..200u64 {
let s = random_seed(i, 7);
assert!((0..=30_000).contains(&s), "{s}");
assert_ne!(s, 7, "a click always changes the seed");
seen.insert(s);
}
assert!(seen.len() > 100, "seeds spread out: {}", seen.len());
assert_ne!(random_seed(1, 30_000), 30_000);
// Every seed dialog shows the button: Clouds, Add Noise and the like carry a `seed` param.
let specs = photocraft_engine::command_specs();
assert!(
specs
.iter()
.filter(|c| c.id.starts_with("filter."))
.any(|c| parse_spec(c.params).iter().any(|p| p.key == "seed" && matches!(p.kind, Kind::Int { .. })))
);
}
/// Preset names such as "iPhone 14 Pro Max" (the artboard dialog's choices) are text, not
/// camelCase keys: they used to read "I Phone 14 Pro Max".
#[test]
+1
View File
@@ -3193,3 +3193,4 @@ curves Smooth Lisser
There are too many sets: delete one first. Il y a trop de jeux : supprimez-en un d’abord.
set name nom du jeu
{set} (modified) {set} (modifié)
Random Aléatoire
Can't render this file because it contains an unexpected character in line 6 and column 47.
+6 -6
View File
@@ -1194,7 +1194,7 @@
Capture Brush Size in Preset Ecsetméret rögzítése az előbeállításban
Include Tool Settings Eszközbeállítások belefoglalása
Include Color Szín belefoglalása
Enter a name for the brush preset Adjon nevet az ecset-előbeállításnak
Enter a name for the brush preset Adj nevet az ecset-előbeállításnak
A brush preset with this name already exists Már van ilyen nevű ecset-előbeállítás
New Crop Preset… Új körbevágási előbeállítás…
New Tool Preset Új eszköz-előbeállítás
@@ -2490,8 +2490,8 @@ navigator Zoom Nagyítás mértéke
Camera Raw Filter ({layer}) Camera Raw szűrő ({layer})
Camera Raw isn't open A Camera Raw nincs megnyitva
Cancelled opening {name} Megnyitás megszakítva: {name}
The document “{name}” does not have an embedded {mode} profile. A(z) „{name}” dokumentumnak nincs beágyazott {mode}-profilja.
The document “{name}” has an embedded color profile that does not match the current {mode} working space. A(z) „{name}” dokumentum beágyazott színprofilja nem egyezik az aktuális {mode}-munkaszíntérrel.
The document “{name}” does not have an embedded {mode} profile. Nincs beágyazott profil ({mode}) ebben a dokumentumban: „{name}”
The document “{name}” has an embedded color profile that does not match the current {mode} working space. A dokumentum beágyazott színprofilja nem egyezik az aktuális munkaszíntérrel ({mode}): „{name}”
Working: {working} Munkaszíntér: {working}
Cancelled {label} Megszakítva: {label}
Clarity Tisztaság
@@ -4018,7 +4018,7 @@ cameraRaw Yellow Sárga
The layer or its mask changed. Drag the mask onto the Trash again. A réteg vagy a maszkja megváltozott. Húzd újra a maszkot a Kukába.
Transform On Drop Átalakítás elengedéskor
Vanishing Point is not active Az Enyészpont nem aktív
Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattintson a négy sarokra
Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattints a négy sarokra
Response curve Válaszgörbe
Show home recent files Legutóbbi fájlok megjelenítése a kezdőképernyőn
Clear Brush Controls Ecsetvezérlők törlése
@@ -4051,7 +4051,7 @@ cameraRaw Yellow Sárga
Drag to pan · Scroll to zoom · Double-click to fit Húzás: mozgatás · Görgetés: nagyítás · Dupla kattintás: igazítás
Gradient Preset Options Színátmenet-előbeállítás beállításai
Import .GRD .GRD importálása
Choose a gradient file (.grd). Válasszon színátmenetfájlt (.grd).
Choose a gradient file (.grd). Válassz színátmenetfájlt (.grd).
Save Settings… Beállítások mentése…
Load Settings… Beállítások betöltése…
Save these settings as a Camera Raw .xmp file A beállítások mentése Camera Raw .xmp-fájlként
@@ -4078,7 +4078,7 @@ cameraRaw Yellow Sárga
Use the embedded profile ({profile}) A beágyazott profil használata ({profile})
Convert to the working space ({profile}) Átalakítás a munkaszíntérbe ({profile})
Remember this choice for future images A választás megjegyzése a későbbi képekhez
Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. A kérdés a Szerkesztés › Színbeállítások Ask On Mismatch beállításával kapcsolható vissza.
Turn the prompt back on with Ask On Mismatch in Edit › Color Settings. A kérdést a Szerkesztés › Színbeállítások „Profileltérés: rákérdezés megnyitáskor” beállításával kapcsolhatod vissza.
Button Mode Gomb mód
Button Mode On Gomb mód be
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -3180,3 +3180,4 @@ curves Smooth Haluskan
There are too many sets: delete one first. Terlalu banyak set: hapus satu terlebih dahulu.
set name nama set
{set} (modified) {set} (diubah)
Random Acak
Can't render this file because it contains an unexpected character in line 4 and column 47.
+1
View File
@@ -3158,3 +3158,4 @@ curves Smooth Сгладить
There are too many sets: delete one first. Слишком много наборов: сначала удалите один.
set name имя набора
{set} (modified) {set} (изменён)
Random Случайно
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -2804,3 +2804,4 @@ curves Smooth 平滑
There are too many sets: delete one first. 组太多:请先删除一个。
set name 组名称
{set} (modified) {set}(已修改)
Random 随机
Can't render this file because it contains an unexpected character in line 2600 and column 53.
+1
View File
@@ -2789,3 +2789,4 @@ curves Smooth 平滑
There are too many sets: delete one first. 組合太多:請先刪除一個。
set name 組合名稱
{set} (modified) {set}(已修改)
Random 隨機
Can't render this file because it contains an unexpected character in line 6 and column 47.
+29
View File
@@ -132,3 +132,32 @@ fn reveal_survives_odd_documents() {
h.state_mut().sync_views();
h.run_steps(3);
}
#[test]
fn layers_scroll_position_survives_document_switches() {
for theme in [ThemeKind::ProMedium, ThemeKind::Studio] {
let (app, inner, _, _, _) = tall_doc();
let mut h = harness(app, theme);
h.state_mut().run("layer.select", json!({"layer": inner.0})).unwrap();
h.run_steps(4);
let before = row(&h, "Deep inside").unwrap();
assert!(in_view(&h, before));
// A short second document clamps its own scroll offset to zero. That must
// not erase the first document's position or trigger a selection change.
h.state_mut().run("file.new", json!({"width": 20, "height": 20})).unwrap();
h.state_mut().sync_views();
h.run_steps(4);
for _ in 0..3 {
h.state_mut().session.set_active(0);
h.state_mut().sync_views();
h.run_steps(4);
assert_eq!(h.state().session.active().unwrap().active_layer, Some(inner));
let restored = row(&h, "Deep inside").unwrap();
assert!(in_view(&h, restored), "{theme:?}: restored bottom row: {restored:?}");
assert!((restored.top() - before.top()).abs() < 0.5, "{theme:?}: restored exact scroll position");
h.state_mut().session.set_active(1);
h.state_mut().sync_views();
h.run_steps(4);
}
}
}
@@ -174,7 +174,7 @@ fn edit_type_command_rejects_missing_or_non_type_layers_without_changes() {
}
#[test]
fn reentering_type_edit_keeps_the_session_and_cancel_restores_cached_pixels() {
fn layer_reselection_commits_type_edit_and_cancel_preserves_committed_text() {
let mut s = session();
let id = s.execute("type.create", json!({"text": "Hello", "size": 48, "x": 100, "y": 180})).unwrap()["layer"].as_u64().unwrap();
// Stand-in for a PSD's retained Photoshop rendering, displaced from our glyph layout.
@@ -197,10 +197,13 @@ fn reentering_type_edit_keeps_the_session_and_cancel_restores_cached_pixels() {
let key = h.state().ui.text_edit.as_ref().expect("inline text editor").session.clone();
h.event(Event::Text("Changed".into()));
h.run_steps(2);
// The first row click commits the edit; the second opens a new session (#5584).
double_click(&mut h, at);
assert_eq!(h.state().ui.text_edit.as_ref().unwrap().session, key);
assert_ne!(h.state().ui.text_edit.as_ref().unwrap().session, key);
assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 1);
crate::type_tool::cancel(h.state_mut());
assert_eq!(text(&h, id), "Changed");
assert!(h.state_mut().session.undo());
assert_eq!(text(&h, id), "Hello");
let st = h.state().session.active().unwrap();
let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("text") };
+65
View File
@@ -461,6 +461,39 @@ fn remove_instance(f: &mut Map<String, Value>, id: &str) {
/// the layer's order), the blending options and the selected page. `select`
/// names a kind to open: its first instance is selected (and enabled), or one
/// is created. `light` is the document's global light angle.
/// Whether the selected page is a Drop Shadow or Inner Shadow, which a drag on the image moves
/// while the dialog is open, as in Photoshop (#5701; [`drag_shadow`]).
pub fn drags_shadow(f: &Map<String, Value>) -> bool {
let selected = f.get("selected").and_then(Value::as_str).unwrap_or_default();
entry(f, selected).and_then(|e| e.get("kind")).and_then(Value::as_str).is_some_and(|k| matches!(k, "dropShadow" | "innerShadow"))
}
/// A drag on the image with a shadow page selected: `start` is true on the press (it records the
/// shadow's angle and distance then), `total` the pointer's movement since in document pixels.
/// The shadow's offset follows the pointer, kept as Photoshop's whole-degree angle and whole-pixel
/// distance (offset = (−cos angle, sin angle) × distance, the light opposite the shadow); with
/// Use Global Light the shared angle moves too ([`set_param`]).
pub fn drag_shadow(f: &mut Map<String, Value>, start: bool, total: [f64; 2]) {
const KEY: &str = "__shadowDrag";
let Some(id) = f.get("selected").and_then(Value::as_str).map(str::to_string).filter(|_| drags_shadow(f)) else { return };
let Some(p) = entry(f, &id).and_then(|e| e.get("params")) else { return };
if start || f.get(KEY).is_none() {
let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(120.0);
let distance = p.get("distance").and_then(Value::as_f64).unwrap_or(0.0);
f.insert(KEY.into(), json!([angle, distance]));
}
let Some([angle, distance]) = f.get(KEY).and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])) else { return };
let a = angle.to_radians();
let (ox, oy) = (-a.cos() * distance + total[0], a.sin() * distance + total[1]);
let d = ox.hypot(oy);
if !d.is_finite() {
return;
}
let new_angle = if d >= 0.5 { oy.atan2(-ox).to_degrees().round() } else { angle };
set_param(f, &id, "angle", json!(new_angle));
set_param(f, &id, "distance", json!(d.round().clamp(0.0, 30000.0)));
}
pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map<String, Value> {
let mut f = Map::new();
f.insert("layer".into(), json!(layer.id.0));
@@ -1346,6 +1379,38 @@ mod tests {
use super::*;
use photocraft_doc::StrokeFx;
/// #5701: with a shadow page selected, a drag on the image moves the shadow: its offset
/// follows the pointer, as whole degrees and pixels, the global light angle with it.
#[test]
fn dragging_on_the_image_moves_the_selected_shadow() {
let shadow = |id: &str, kind: &str, global: bool| json!({"id": id, "kind": kind, "on": true, "params": {"angle": 120.0, "distance": 10.0, "useGlobalLight": global}});
let mut f = Map::new();
f.insert("selected".into(), json!("fx1"));
f.insert("globalLight".into(), json!(120.0));
f.insert("effects".into(), json!([shadow("fx1", "dropShadow", true), shadow("fx2", "innerShadow", true), shadow("fx3", "dropShadow", false)]));
assert!(drags_shadow(&f));
let params = |f: &Map<String, Value>, id: &str| {
let p = &entry(f, id).unwrap()["params"];
(p["angle"].as_f64().unwrap(), p["distance"].as_f64().unwrap())
};
// The press keeps the shadow where it is: (5, 8.66) px.
drag_shadow(&mut f, true, [0.0, 0.0]);
assert_eq!(params(&f, "fx1"), (120.0, 10.0));
// Dragged to (15, 0): straight right of the layer, the light from the left (180°).
drag_shadow(&mut f, false, [10.0, -8.660_254]);
assert_eq!(params(&f, "fx1"), (180.0, 15.0));
assert_eq!(params(&f, "fx2").0, 180.0, "the global light angle is shared");
assert_eq!(params(&f, "fx3"), (120.0, 10.0), "an instance with its own angle is left alone");
// Back onto the layer: no offset, and the angle the drag started with.
drag_shadow(&mut f, false, [-5.0, -8.660_254]);
assert_eq!(params(&f, "fx1"), (120.0, 0.0));
// Not on a shadow page: nothing moves.
f.insert("selected".into(), json!(BLENDING));
assert!(!drags_shadow(&f));
drag_shadow(&mut f, true, [50.0, 50.0]);
assert_eq!(params(&f, "fx1"), (120.0, 0.0));
}
fn session() -> photocraft_engine::Session {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
+17 -1
View File
@@ -1086,6 +1086,10 @@ impl PhotocraftApp {
id,
"layer.vectorMask.add" | "layer.vectorMask.fromPath" | "layer.vectorMask.revealAll" | "layer.vectorMask.hideAll" | "layer.vectorMask.currentPath"
) && on_active_layer;
// A draft Pen path belongs to the current document, not the one about to be created.
if id == "file.new" && self.ui.pen.is_some() {
vector_ui::pen_commit(self, false);
}
let r = if id == "actions.play" {
actions::play(self, &params)
} else if photocraft_engine::actions_cmds::shell_view_command(id) {
@@ -1767,6 +1771,7 @@ impl eframe::App for PhotocraftApp {
// Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvas
// cursor block needs it before the frame renders. `None` (Wayland/web) keeps `false`.
self.caps_lock = self.services.caps_lock.as_mut().is_some_and(|f| f());
tool_cursor::set_wayland(ctx, self.services.is_wayland);
if !self.styled {
Self::setup_context(ctx, self.ui.theme);
self.styled = true;
@@ -1835,6 +1840,9 @@ impl eframe::App for PhotocraftApp {
if !dropped.is_empty() {
let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx));
self.open_dropped(ctx, dropped, at);
// Files dragged in from another app's window: PhotoCraft comes to the front and takes
// the keyboard, as Photoshop does, instead of staying behind the source (#5687).
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
self.place_next_dropped(ctx);
// The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a
@@ -1963,7 +1971,7 @@ impl eframe::App for PhotocraftApp {
notices::show(self, &ctx);
gpu_status::show_fallback(self, &ctx);
kys_import::show_offer(self, &ctx);
if chrome && self.ui.panels.menu_bar && self.custom_titlebar && !self.ui.dialogs.is_empty() {
if self.titlebar_modal_drag(chrome) {
titlebar::modal_drag_overlay(&ctx);
}
if self.custom_titlebar {
@@ -2034,6 +2042,14 @@ fn read_dropped(_f: &dyn egui::DroppedFile) -> Result<Vec<u8>, String> {
}
impl PhotocraftApp {
/// Whether the title bar's free gap gets the drag overlay this frame: the app draws its title
/// strip (`chrome`: not hidden by the screen mode) and a dialog's modal layer covers it. Not
/// only with the custom title bar: on macOS the strip under the traffic lights is the window's
/// title bar too, and an open dialog (Embedded Profile Mismatch…) left it undraggable (#5826).
pub(crate) fn titlebar_modal_drag(&self, chrome: bool) -> bool {
chrome && self.ui.panels.menu_bar && !self.ui.dialogs.is_empty()
}
/// `params` aimed at the active layer's mask (`"target":"mask"`) when the Layers panel targets
/// it and command `id` edits the target (adjustments, filters, fills) without naming one:
/// ⌘I then inverts the mask, as in Photoshop (#780). A targeted alpha channel or Quick Mask
+9
View File
@@ -546,6 +546,15 @@ fn mouse_drag_inside_the_selection_moves_it() {
assert_eq!(selection(&h), Rect::new(120, 90, 220, 170), "moved by (20, 10)");
}
/// #5646: the Move tool keeps Photoshop's arrow pointer instead of the 4-way move cursor (the
/// hover outline still marks the layer under the pointer).
#[test]
fn the_move_tool_keeps_the_arrow_pointer() {
let mut h = harness(Tool::Move);
move_to(&mut h, 200.0, 150.0);
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default);
}
/// #1428: hovering inside the ants with a marquee shows the move cursor (a press there drags the
/// outline); outside it is the marquee's own cursor.
#[test]
@@ -152,6 +152,32 @@ fn every_theme_shows_the_auto_select_toggle() {
}
}
#[test]
fn every_theme_shows_the_transform_controls_toggle() {
// #5740: outside the Pro themes the Move tool's options bar had no Show Transform Controls, so
// a click on a layer never showed its box and handles there.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
for theme in crate::theme::ThemeKind::ALL {
let (app, _, _) = app();
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 60.0)).build_ui_state(
|ui, app: &mut PhotocraftApp| {
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
crate::panels::options_bar(app, ui);
},
app,
);
PhotocraftApp::setup_context(&h.ctx, theme);
h.run_steps(4);
let before = h.state().ui.tool_options.move_show_transform;
h.get_by_label("Show Transform Controls").click();
h.run_steps(2);
assert_ne!(h.state().ui.tool_options.move_show_transform, before, "{theme:?}: the toggle flips Show Transform Controls");
}
}
#[test]
fn every_theme_shows_the_type_options() {
// #1387: outside the Pro themes the Type tool's options bar was only the hint "Click to add
@@ -210,3 +236,24 @@ fn every_theme_shows_the_gradient_options() {
assert!(combos.iter().any(|c| c.contains("Normal")), "{theme:?}: the blend mode picker shows; combo boxes: {combos:?}");
}
}
#[test]
fn shift_click_adds_shape_layers_one_after_another() {
// Shapes, as in Photoshop: a click selects one, each ⇧-click adds the one under it.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();
for rect in [[10, 10, 40, 40], [80, 10, 40, 40], [10, 100, 40, 40]] {
app.session.execute("shape.create", json!({"kind": "rect", "rect": rect, "fill": "#ff0000"})).unwrap();
}
app.sync_views();
app.ui.tool = Tool::Move;
app.ui.extras.snap = false;
app.ui.view.show.smart_guides = false;
let ids: Vec<LayerId> = app.session.active().unwrap().doc.layers.iter().skip(1).map(|l| l.id).collect();
drag(&mut app, [30.0, 30.0], [0.0, 0.0], egui::Modifiers::NONE);
drag(&mut app, [100.0, 30.0], [0.0, 0.0], egui::Modifiers::SHIFT);
drag(&mut app, [30.0, 120.0], [0.0, 0.0], egui::Modifiers::SHIFT);
let mut selected = app.session.active().unwrap().selected_layers();
selected.sort_by_key(|l| l.0);
assert_eq!(selected, ids);
}
+196 -6
View File
@@ -546,10 +546,18 @@ fn color_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, two_columns: bool) {
}
s.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Swap colours (X)")));
if s.on_hover_text(tl!("Swap colours (X)")).clicked() {
let _ = app.run("tools.swapColors", json!({}));
chip_command(app, "tools.swapColors");
}
if d.is_some_and(|d| d.on_hover_text(tl!("Default colours (D)")).clicked()) {
let _ = app.run("tools.defaultColors", json!({}));
chip_command(app, "tools.defaultColors");
}
}
/// Run Switch Colors or Default Colors from the chips. As in Photoshop, characters highlighted
/// in the type layer being edited take the new foreground colour, like picking one (#5690).
fn chip_command(app: &mut PhotocraftApp, id: &str) {
if app.run(id, json!({})).is_ok() {
crate::type_tool::foreground_changed(app);
}
}
@@ -1391,6 +1399,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
Tool::Move => {
// The Studio themes keep Photoshop's Auto-Select toggle too (#1275).
widgets::checkbox(ui, &mut app.ui.tool_options.move_auto_select, tl!("Auto-Select:"));
// And Show Transform Controls (#5740): without it the box could not be
// turned on outside the Pro themes.
widgets::checkbox(ui, &mut app.ui.tool_options.move_show_transform, tl!("Show Transform Controls"));
hint(ui, tl!("Drag to move the active layer"));
}
Tool::Eyedropper => crate::eyedropper_ui::options(app, ui),
@@ -1786,6 +1797,13 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
.hover_doc
.map(|p| (p[0].floor() as i32, p[1].floor() as i32))
.filter(|(x, y)| *x >= 0 && *y >= 0 && *x < size.width as i32 && *y < size.height as i32);
// While a guide is dragged (#5728), the Info panel shows its position in one axis only, even
// when the pointer is outside the canvas (ruler drags do not update `hover_doc` there).
let (guide_x, guide_y) = match app.guide_drag {
Some(d) if d.vertical => (Some(d.pos), None),
Some(d) => (None, Some(d.pos)),
None => (None, None),
};
// The readout averages the Eyedropper's Sample Size, as in Photoshop (#1649).
let sample_size = app.ui.tool_options.eyedropper_size;
let rgba = pos.and_then(|(x, y)| {
@@ -1824,8 +1842,8 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.columns(2, |cols| {
let dash = || "—".to_string();
// Measured from the rulers' zero point (#2955).
row(&mut cols[0], "X:", pos.map_or_else(dash, |p| fx(p.0 as f64 - origin[0])));
row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| fy(p.1 as f64 - origin[1])));
row(&mut cols[0], "X:", guide_x.map(|p| fx(p - origin[0])).or_else(|| pos.map(|p| fx(p.0 as f64 - origin[0]))).unwrap_or_else(dash));
row(&mut cols[0], "Y:", guide_y.map(|p| fy(p - origin[1])).or_else(|| pos.map(|p| fy(p.1 as f64 - origin[1]))).unwrap_or_else(dash));
row(&mut cols[1], "W:", sel.map_or_else(dash, |r| fx(r.width() as f64)));
row(&mut cols[1], "H:", sel.map_or_else(dash, |r| fy(r.height() as f64)));
});
@@ -2163,7 +2181,7 @@ fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static s
/// list downward (reveals rows above) and negative upward (reveals rows below).
/// The speed ramps with proximity to the edge and clamps to the maximum speed when
/// dragged outside, using elapsed time instead of assuming a particular refresh rate.
fn layer_drag_edge_scroll(pointer: Option<Pos2>, viewport: Rect, dragging: bool, dt: f32) -> f32 {
pub(crate) fn layer_drag_edge_scroll(pointer: Option<Pos2>, viewport: Rect, dragging: bool, dt: f32) -> f32 {
if !dragging || viewport.width() <= 0.0 || viewport.height() <= 0.0 || dt.is_nan() || dt <= 0.0 {
return 0.0;
}
@@ -2309,7 +2327,8 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let fill = ui.available_height() > footer + 60.0;
let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY };
egui::ScrollArea::vertical()
.id_salt("layer-rows")
// Keep each document's position independent, even when tab indices change (#5522).
.id_salt(("layer-rows", doc.id.0))
.max_height(rows_h)
.min_scrolled_height(if fill { rows_h } else { 0.0 })
.auto_shrink([false, !fill])
@@ -2539,6 +2558,11 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
});
for (id, p) in actions {
// A row click commits even when it selects the layer already being edited (#5584).
// Finish before selection changes so the existing type session keeps its own target.
if id == "layer.select" && app.ui.text_edit.is_some() {
crate::type_tool::commit(app);
}
if id == "ui.maskTarget" {
app.ui.mask_target = p.as_bool().unwrap_or(false);
app.ui.vector_mask_target = false;
@@ -4304,6 +4328,64 @@ mod color_tests {
}
}
/// While characters are highlighted in a type layer being edited, the Switch Colors and
/// Default Colors buttons recolour them with the new foreground (#5690); without a selection
/// they only change the tool colours, as before.
#[test]
fn swap_and_default_colors_recolour_selected_type() {
use egui_kittest::kittest::Queryable;
use photocraft_doc::LayerId;
let rgb = |app: &PhotocraftApp, id: LayerId, ci: usize| {
let doc = &app.session.active().unwrap().doc;
let photocraft_doc::LayerContent::Text(t) = &doc.layer(id).unwrap().content else { panic!("not a type layer") };
let b = t.text.char_indices().nth(ci).map_or(t.text.len(), |(b, _)| b);
let mut at = 0;
for r in t.char_runs() {
if b < at + r.len {
return r.style.color.to_rgba8();
}
at += r.len;
}
[0; 4]
};
for selected in [true, false] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let made = app.run("type.create", json!({"text": "Hello world", "size": 40, "x": 50, "y": 150, "color": "#000000"})).unwrap();
let id = LayerId(made["layer"].as_u64().unwrap());
app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap();
let anchor = if selected { 6 } else { 11 };
app.ui.text_edit = Some(crate::state::TextEdit {
layer: id.0,
caret: 11,
anchor,
session: "s".into(),
created: false,
mask: false,
dragging: false,
resize: None,
preedit: None,
});
let mut h =
egui_kittest::Harness::builder().with_size(vec2(80.0, 120.0)).build_ui_state(|ui, app: &mut PhotocraftApp| color_chips(app, ui, false), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);
h.run_steps(2);
h.get_by_label("Swap colours (X)").click();
h.run_steps(2);
assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0]);
assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0]);
let blue = if selected { [0, 0, 255, 255] } else { [0, 0, 0, 255] };
assert_eq!(rgb(h.state(), id, 0), [0, 0, 0, 255], "unselected characters keep their colour");
assert_eq!((rgb(h.state(), id, 6), rgb(h.state(), id, 10)), (blue, blue), "selected: {selected}");
// Default Colors: the selection takes black, the new foreground.
h.state_mut().run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap();
h.get_by_label("Default colours (D)").click();
h.run_steps(2);
assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0]);
assert_eq!(rgb(h.state(), id, 6), [0, 0, 0, 255], "selected: {selected}");
}
}
/// The Studio layout (chips stacked, icons below) fits the height the toolbar reserves for
/// the chips, so the two-column check does not change with the theme.
#[test]
@@ -6241,6 +6323,114 @@ mod properties_target_regressions {
#[cfg(test)]
#[path = "history_panel_select_tests.rs"]
mod history_panel_select_tests;
#[cfg(test)]
mod layer_click_type_commit_tests {
use super::*;
use egui_kittest::{Harness, kittest::Queryable};
fn harness(kind: theme::ThemeKind) -> (Harness<'static, PhotocraftApp>, LayerId, LayerId) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let text = LayerId(app.run("type.create", json!({"text": "Before", "size": 24, "x": 20, "y": 80})).unwrap()["layer"].as_u64().unwrap());
app.run("layer.setProps", json!({"layer": text.0, "name": "Edited type"})).unwrap();
let other = LayerId(app.run("layer.new.layer", json!({"name": "Other pixels"})).unwrap()["layer"].as_u64().unwrap());
app.run("layer.select", json!({"layer": text.0})).unwrap();
crate::type_tool::edit_active(&mut app).unwrap();
let session = app.ui.text_edit.as_ref().unwrap().session.clone();
app.run("type.edit", json!({"layer": text.0, "text": "Preserved edit", "coalesce": session})).unwrap();
let mut ready = false;
let mut h = Harness::builder().with_size(vec2(360.0, 650.0)).with_step_dt(1.0 / 60.0).build_ui_state(
move |ui, app: &mut PhotocraftApp| {
if !ready {
PhotocraftApp::setup_context(ui.ctx(), kind);
ready = true;
return;
}
layers(app, ui);
},
app,
);
h.run_steps(4);
(h, text, other)
}
fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, modifiers: egui::Modifiers) {
h.event(egui::Event::ModifiersChanged(modifiers));
h.hover_at(at);
h.run_steps(1);
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers });
h.run_steps(1);
}
}
fn preserved(app: &PhotocraftApp, id: LayerId) {
let layer = app.session.active().unwrap().doc.layer(id).unwrap();
let LayerContent::Text(text) = &layer.content else { panic!("type must remain editable") };
assert_eq!(text.text, "Preserved edit");
}
#[test]
fn layer_name_and_thumbnail_clicks_commit_same_or_other_type_selection() {
for kind in theme::ThemeKind::ALL {
for same in [true, false] {
for thumbnail in [true, false] {
let (mut h, text, other) = harness(kind);
let label = if same { "Edited type" } else { "Other pixels" };
let row = h.get_by_label(label).rect();
let at = pos2(row.left() + if thumbnail { 43.0 } else { 120.0 }, row.center().y);
click(&mut h, at, egui::Modifiers::NONE);
assert!(h.state().ui.text_edit.is_none(), "{kind:?}, same={same}, thumbnail={thumbnail}");
assert_eq!(h.state().session.active().unwrap().active_layer, Some(if same { text } else { other }));
preserved(h.state(), text);
}
}
}
}
#[test]
fn layer_click_commits_without_breaking_modifier_selection_or_double_click_editing() {
for kind in theme::ThemeKind::ALL {
let (mut h, text, other) = harness(kind);
let row = h.get_by_label("Other pixels").rect();
click(&mut h, pos2(row.left() + 120.0, row.center().y), egui::Modifiers { command: true, ..Default::default() });
assert!(h.state().ui.text_edit.is_none());
let selected = h.state().session.active().unwrap().selected_layers();
assert!(selected.contains(&text) && selected.contains(&other));
preserved(h.state(), text);
let (mut h, text, _) = harness(kind);
let row = h.get_by_label("Edited type").rect();
let thumb = pos2(row.left() + 43.0, row.center().y);
click(&mut h, thumb, egui::Modifiers::NONE);
assert!(h.state().ui.text_edit.is_none());
click(&mut h, thumb, egui::Modifiers::NONE);
assert_eq!(h.state().ui.text_edit.as_ref().map(|ed| ed.layer), Some(text.0));
preserved(h.state(), text);
}
}
#[test]
#[ignore = "offscreen visual evidence for #5584"]
fn layer_click_synthetic_visual_evidence() {
let (h, text, _) = harness(theme::ThemeKind::ProMedium);
let mut app = h.into_state();
app.ui.tool = Tool::Type;
let mut h = Harness::builder().with_size(vec2(1280.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).wgpu().build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, theme::ThemeKind::ProMedium);
app
});
h.run_steps(4);
assert!(h.state().ui.text_edit.is_some());
h.render().unwrap().save("5584-before.png").unwrap();
let row = h.get_by_label("Other pixels").rect();
click(&mut h, pos2(row.left() + 120.0, row.center().y), egui::Modifiers::NONE);
assert!(h.state().ui.text_edit.is_none());
preserved(h.state(), text);
h.run_steps(4);
h.render().unwrap().save("5584-after.png").unwrap();
}
}
#[cfg(test)]
mod sampler_readout_tests {
+65
View File
@@ -122,6 +122,23 @@ fn alt_breaks_the_handle_being_dragged_and_grabs_the_last_outgoing_handle() {
assert!(near([k.out_ctrl.x, k.out_ctrl.y], [140.0, 20.0]));
}
#[test]
fn opening_a_new_document_finishes_the_previous_pen_path() {
let mut h = harness();
click(&mut h, [20.0, 20.0]);
click(&mut h, [120.0, 20.0]);
assert_eq!(h.state().ui.pen.as_ref().map(|p| p.knots.len()), Some(2));
let original = h.state().session.active().unwrap().doc.id;
h.state_mut().run("file.new", json!({"width": 300, "height": 200})).unwrap();
assert!(h.state().ui.pen.is_none(), "the Pen draft must not overlay the new document");
let docs = h.state().session.documents();
assert_eq!(docs.len(), 2);
assert_eq!(docs[0].doc.id, original);
assert_eq!(docs[0].doc.work_path.as_ref().unwrap().subpaths[0].knots.len(), 2);
assert!(docs[1].doc.work_path.is_none(), "the new document starts with no path");
}
#[test]
fn dragging_on_the_first_anchor_closes_with_its_handles_in_one_step() {
let mut h = harness();
@@ -154,3 +171,51 @@ fn dragging_on_the_first_anchor_closes_with_its_handles_in_one_step() {
assert!(sp.closed && sp.knots.len() == 3);
assert!(near([k.in_ctrl.x, k.in_ctrl.y], [0.0, 20.0]) && near([k.out_ctrl.x, k.out_ctrl.y], [40.0, 20.0]), "{k:?}");
}
/// #5702: a finished work path showed again whenever the Pen came back, and ⌫ / Delete reached
/// Edit › Clear (the pixels under it) instead, so the path looked impossible to delete. With the
/// Pen the key deletes the path, in one undoable step, and leaves the pixels; other tools keep
/// Edit › Clear.
#[test]
fn delete_with_the_pen_deletes_the_finished_work_path_not_the_pixels() {
let mut h = harness();
h.state_mut().run("layer.new.layer", json!({})).unwrap();
h.state_mut()
.session
.edit("paint", |doc, a| {
doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 200, 150), &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
for p in [[20.0, 20.0], [120.0, 20.0], [120.0, 100.0]] {
click(&mut h, p);
}
h.key_press(Key::Enter);
h.run_steps(2);
let work = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().doc.work_path.is_some();
let red = |h: &Harness<'static, PhotocraftApp>| {
let st = h.state().session.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 60) == [1.0, 0.0, 0.0, 1.0]
};
assert!(work(&h) && h.state().ui.pen.is_none(), "a finished work path");
let steps = h.state().session.active().unwrap().history.past_len();
h.key_press(Key::Delete);
h.run_steps(2);
assert!(!work(&h), "Delete deletes the work path");
assert!(red(&h), "and leaves the pixels under it");
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one History step");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert!(work(&h), "Undo brings it back");
h.state_mut().ui.tool = Tool::PathSelection;
h.key_press(Key::Backspace);
h.run_steps(2);
assert!(!work(&h), "Backspace with Path Selection deletes it too");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.state_mut().ui.tool = Tool::Brush;
h.key_press(Key::Delete);
h.run_steps(2);
assert!(work(&h), "another tool's Delete is Edit › Clear, not Delete Path");
}
+24
View File
@@ -27,6 +27,13 @@ pub fn preview_factor(doc: &Document, reduced: bool) -> u32 {
if reduced { factor(doc) } else { 1 }
}
/// A live preview's factor `k` capped for a view at `zoom` (physical screen pixels per document
/// pixel): never coarser than the screen ([`crate::adjust_preview::proxy_factor`]), so a view at
/// 100 % shows full resolution instead of k-pixel blocks while a control moves (#5764).
pub fn view_factor(k: u32, zoom: f32) -> u32 {
k.min(crate::adjust_preview::proxy_factor(zoom)).max(1)
}
pub use photocraft_compose::proxy::{downsample, proxy_document};
#[cfg(test)]
@@ -48,6 +55,23 @@ mod tests {
assert_eq!(preview_factor(&small, true), 1);
}
/// #5764: dragging a Curves point on a large document showed the canvas in k-pixel blocks at
/// any zoom. The proxy may only be as coarse as the screen.
#[test]
fn view_factor_never_coarser_than_the_screen() {
let big = Document::new("b", Size::new(6016, 6016), ColorMode::Rgb, SampleType::U8);
let k = preview_factor(&big, true);
assert!(k > 2, "{k}");
assert_eq!(view_factor(k, 1.0), 1, "100 %: full resolution");
assert_eq!(view_factor(k, 2.0), 1, "zoomed in: full resolution");
assert_eq!(view_factor(k, 0.6), 1);
assert_eq!(view_factor(k, 0.5), 2);
assert_eq!(view_factor(k, 0.1), k, "far out: the document's proxy");
assert_eq!(view_factor(1, 0.1), 1, "small documents stay full size");
assert_eq!(view_factor(k, f32::NAN), 1);
assert_eq!(view_factor(0, 0.1), 1);
}
#[test]
fn proxy_keeps_structure_and_ids() {
let doc = Document::with_background("d", Size::new(4000, 3000), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+52
View File
@@ -431,6 +431,9 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
}
if let Some(pos) = resp.interact_pointer_pos().filter(|_| salt != "ruler-corner" && (resp.dragged() || resp.drag_started())) {
// ⌥/Alt turns the guide the other way, as in Photoshop: a vertical guide out of the top
// ruler, a horizontal one out of the left (#5698), switching as Alt goes up and down.
let vertical = vertical != ui.input(|i| i.modifiers.alt);
let d = xf.to_doc(pos);
let along = if vertical { d[0] } else { d[1] };
let pos = if ui.input(|i| i.modifiers.shift) { snap_to_tick(app, xf, vertical, along) } else { crate::snap_ui::snap_guide(app, vertical, along) };
@@ -665,6 +668,24 @@ mod tests {
assert!(h.query_by_label("50").is_none(), "not the raw image x");
}
/// #5728: dragging a guide shows its coordinate in the Info panel on one axis only.
#[test]
fn info_panel_shows_guide_drag_position_outside_canvas() {
use egui_kittest::kittest::Queryable;
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.hover_doc = None;
app.guide_drag = Some(GuideDrag { vertical: true, index: None, pos: 42.0, press: 42.0 });
let mut h = egui_kittest::Harness::builder()
.with_size(vec2(260.0, 240.0))
.build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app);
h.run_steps(2);
assert!(h.query_by_label("42").is_some(), "vertical guide: X readout");
h.state_mut().guide_drag = Some(GuideDrag { vertical: false, index: None, pos: 17.0, press: 17.0 });
h.run_steps(2);
assert!(h.query_by_label("17").is_some(), "horizontal guide: Y readout");
}
#[test]
fn percentage_grid_spacing_uses_both_canvas_dimensions() {
let mut g = GuidesGridAndSlices { grid_unit: Unit::Percent, gridline_every: 20.0, subdivisions: 2, ..Default::default() };
@@ -951,6 +972,35 @@ mod tests {
}
}
/// #5698: as in Photoshop, an Alt-drag out of the top ruler makes a vertical guide and one out
/// of the left ruler a horizontal guide; without Alt each ruler makes its own kind.
#[test]
fn alt_drags_a_guide_of_the_other_orientation_out_of_a_ruler() {
let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0));
let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max);
let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 };
let drag = |from: Pos2, modifiers: egui::Modifiers| {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 256, "height": 128})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app);
let to = xf.to_screen(37.0, 90.0);
h.event_modifiers(egui::Event::PointerMoved(from), modifiers);
h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers);
h.run_steps(1);
h.event_modifiers(egui::Event::PointerMoved(to), modifiers);
h.run_steps(1);
h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers);
h.run_steps(2);
let g = &h.state().session.active().unwrap().doc.guides;
(g.vertical.clone(), g.horizontal.clone())
};
let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0));
assert_eq!(drag(top, egui::Modifiers::NONE), (vec![], vec![90.0]), "top ruler: horizontal");
assert_eq!(drag(left, egui::Modifiers::NONE), (vec![37.0], vec![]), "left ruler: vertical");
assert_eq!(drag(top, egui::Modifiers::ALT), (vec![37.0], vec![]), "Alt from the top ruler: vertical");
assert_eq!(drag(left, egui::Modifiers::ALT), (vec![], vec![90.0]), "Alt from the left ruler: horizontal");
}
/// #3770: a guide Shift-dragged out of a ruler lands on the nearest tick the ruler draws
/// (tenths of the labelled step, in the ruler unit); without Shift it lands where it's dropped.
#[test]
@@ -978,6 +1028,8 @@ mod tests {
h.state().session.active().unwrap().doc.guides.vertical.clone()
};
assert_eq!(drag_guide(egui::Modifiers::NONE), vec![37.0]);
// #5698: Alt turns it into a horizontal guide (at the drop's y, the document's centre).
assert_eq!(drag_guide(egui::Modifiers::ALT), Vec::<f64>::new(), "no vertical guide with Alt");
// Pixels at 100%: labels every 100 px, ticks every 10 px.
assert_eq!(drag_guide(egui::Modifiers::SHIFT), vec![40.0]);
+13
View File
@@ -477,6 +477,19 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
crate::vector_ui::pen_commit(app, false);
return;
}
// A finished work path shown by the Pen or Path Selection: ⌫/Delete deletes it, as in
// Photoshop (#5702), never Edit › Clear on the pixels under it.
if focus != Focus::DeletingWidget && crate::vector_ui::delete_key_deletes_work_path(app) {
let mods = ctx.input(|i| i.modifiers);
if !mods.command && !mods.ctrl && !mods.shift && !mods.alt && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete))
{
if let Err(e) = app.run("path.delete", json!({"name": "work"})) {
app.ui.status = e;
app.ui.status_error = true;
}
return;
}
}
// Magnetic Lasso: ↩ closes, Esc cancels, ⌫ removes a fastening point (not Edit › Clear),
// [ ] change the detection width (not the brush size).
if crate::magnetic_lasso_ui::keys(app, ctx) {
+73 -16
View File
@@ -71,6 +71,7 @@ pub fn reset(f: &mut Map<String, Value>) {
pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
let unit = pref_unit(app.session.prefs().units_and_rulers.rulers);
let resample = pref_resample(app.session.prefs().general.image_interpolation);
let pt_per_in = app.session.prefs().units_and_rulers.point_size.per_inch();
let d = &app.session.active()?.doc;
let (w, h, res) = (d.size.width as f64, d.size.height as f64, d.resolution_dpi as f64);
let label = photocraft_engine::commands::find(command).map(|c| c.label).unwrap_or("Image Size…");
@@ -82,6 +83,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
f.insert("__origH".into(), json!(h));
f.insert("__origRes".into(), json!(res));
f.insert("__unit".into(), json!(unit));
f.insert("__ptPerIn".into(), json!(pt_per_in));
f.insert("__bytesPerPixel".into(), json!(d.layers.first().and_then(|l| l.surface()).map_or(4, |s| s.format().bytes_per_pixel())));
f.insert("width".into(), json!(w));
f.insert("height".into(), json!(h));
@@ -102,27 +104,33 @@ fn num(f: &Map<String, Value>, k: &str) -> f64 {
f.get(k).and_then(Value::as_f64).unwrap_or(0.0)
}
/// Pixels → display unit.
fn to_unit(px: f64, unit: &str, orig: f64, res: f64) -> f64 {
/// Points per inch from Preferences › Units & Rulers › Point/Pica Size, stored when the dialog
/// opens: 72 (PostScript) when missing or not a positive finite number.
fn pt_per_in(f: &Map<String, Value>) -> f64 {
f.get("__ptPerIn").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(72.0)
}
/// Pixels → display unit; `ppi` is points per inch (a pica is 12 points).
fn to_unit(px: f64, unit: &str, orig: f64, res: f64, ppi: f64) -> f64 {
match unit {
"percent" => px / orig.max(1.0) * 100.0,
"in" => px / res.max(1.0),
"cm" => px / res.max(1.0) * 2.54,
"mm" => px / res.max(1.0) * 25.4,
"pt" => px / res.max(1.0) * 72.0,
"pica" => px / res.max(1.0) * 6.0,
"pt" => px / res.max(1.0) * ppi,
"pica" => px / res.max(1.0) * ppi / 12.0,
_ => px,
}
}
fn from_unit(v: f64, unit: &str, orig: f64, res: f64) -> f64 {
fn from_unit(v: f64, unit: &str, orig: f64, res: f64, ppi: f64) -> f64 {
match unit {
"percent" => v * orig / 100.0,
"in" => v * res,
"cm" => v / 2.54 * res,
"mm" => v / 25.4 * res,
"pt" => v / 72.0 * res,
"pica" => v / 6.0 * res,
"pt" => v / ppi * res,
"pica" => v / ppi * 12.0 * res,
_ => v,
}
}
@@ -165,18 +173,19 @@ fn dim_field(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, orig_key:
let res = f.get("resolution").and_then(Value::as_f64).unwrap_or(num(f, "__origRes"));
let orig = num(f, orig_key);
let px = num(f, key);
let mut v = to_unit(px, &unit, orig, res) as f32;
let ppi = pt_per_in(f);
let mut v = to_unit(px, &unit, orig, res, ppi) as f32;
// The engine's 300000 px limit in this unit (never below 30000), so a large document's size
// isn't clamped when the field is drawn: egui clamps the shown value to the range, and the
// field reports that as an edit (#4162).
let lim = if unit == "px" { 300000.0 } else { to_unit(300000.0, &unit, orig, res).max(30000.0) as f32 };
let lim = if unit == "px" { 300000.0 } else { to_unit(300000.0, &unit, orig, res, ppi).max(30000.0) as f32 };
let range = -lim..=lim;
// Each unit keeps its own precision: whole pixels, 3 places for inches, 2 for cm/mm/picas (#2434).
// A typed unit (`2in` while in pixels) converts at the dialog's resolution.
let units = crate::widgets::FieldUnits { unit: crate::widgets::unit_of_key(&unit), dpi: res, ppi: 72.0 };
let units = crate::widgets::FieldUnits { unit: crate::widgets::unit_of_key(&unit), dpi: res, ppi };
let changed = crate::widgets::value_field_units(ui, &mut v, range, 90.0, crate::widgets::unit_decimals(&unit), units).changed();
if changed {
let px = from_unit(v as f64, &unit, orig, res);
let px = from_unit(v as f64, &unit, orig, res, ppi);
f.insert(key.into(), json!(if unit == "px" { px.round() } else { px }));
}
let _ = id;
@@ -442,15 +451,36 @@ mod tests {
#[test]
fn unit_conversions_round_trip() {
for unit in ["px", "percent", "in", "cm", "mm", "pt", "pica"] {
let v = to_unit(1500.0, unit, 3000.0, 300.0);
assert!((from_unit(v, unit, 3000.0, 300.0) - 1500.0).abs() < 1e-9, "{unit}");
for ppi in [72.0, 72.27] {
for unit in ["px", "percent", "in", "cm", "mm", "pt", "pica"] {
let v = to_unit(1500.0, unit, 3000.0, 300.0, ppi);
assert!((from_unit(v, unit, 3000.0, 300.0, ppi) - 1500.0).abs() < 1e-9, "{unit} at {ppi} pt/in");
}
}
assert_eq!(to_unit(1500.0, "percent", 3000.0, 300.0), 50.0);
assert_eq!(to_unit(600.0, "in", 3000.0, 300.0), 2.0);
assert_eq!(to_unit(1500.0, "percent", 3000.0, 300.0, 72.0), 50.0);
assert_eq!(to_unit(600.0, "in", 3000.0, 300.0, 72.0), 2.0);
assert_eq!(human_bytes(6016.0 * 6016.0 * 4.0), "138.1M");
}
/// #5756: points and picas use the Point/Pica Size preference (Traditional is 72.27 pt/in),
/// and a dialog without the field (or with a bad one) falls back to PostScript's 72.
#[test]
fn points_and_picas_use_the_points_per_inch() {
assert!((to_unit(72.0, "pt", 72.0, 72.0, 72.27) - 72.27).abs() < 1e-9);
assert!((to_unit(72.0, "pica", 72.0, 72.0, 72.27) - 72.27 / 12.0).abs() < 1e-9);
assert_eq!(to_unit(72.0, "pt", 72.0, 72.0, 72.0), 72.0);
assert_eq!(to_unit(72.0, "pica", 72.0, 72.0, 72.0), 6.0);
assert!((from_unit(72.27, "pt", 72.0, 72.0, 72.27) - 72.0).abs() < 1e-9);
let mut f = Map::new();
assert_eq!(pt_per_in(&f), 72.0);
for bad in [json!(0.0), json!(-3.0), json!("x")] {
f.insert("__ptPerIn".into(), bad);
assert_eq!(pt_per_in(&f), 72.0);
}
f.insert("__ptPerIn".into(), json!(72.27));
assert_eq!(pt_per_in(&f), 72.27);
}
#[test]
fn dialog_maps_to_engine_command() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
@@ -547,6 +577,33 @@ mod tests {
(h, id)
}
/// #5756: points and picas follow Preferences › Units & Rulers › Point/Pica Size. With
/// Traditional (72.27 pt/in) and Resample off, 100 px typed as 72.27 pt wide is 100 ppi.
#[test]
fn traditional_point_size_drives_points_and_picas() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 100, "height": 50, "resolution": 72})).unwrap();
app.session.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap();
for command in ["image.imageSize", "image.canvasSize"] {
let id = open(&mut app, command).unwrap();
assert_eq!(app.ui.dialog_mut(id).unwrap().fields.get("__ptPerIn"), Some(&json!(72.27)), "{command}");
app.ui.close_dialog(id);
}
let mut h = egui_kittest::Harness::builder()
.with_size(egui::vec2(1400.0, 900.0))
.build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
let id = open(h.state_mut(), "image.imageSize").unwrap();
let d = h.state_mut().ui.dialog_mut(id).unwrap();
d.fields.insert("resample".into(), json!("none"));
d.fields.insert("__unit".into(), json!("pt"));
h.run_steps(3);
type_width(&mut h, "72.27");
let f = fields(&h);
assert_eq!((num(&f, "width"), num(&f, "height")), (100.0, 50.0), "{f:?}");
assert!((num(&f, "resolution") - 100.0).abs() < 1e-2, "{f:?}");
}
/// Types `text` into the Width field and leaves it with Tab.
fn type_width(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, text: &str) {
use egui::accesskit::Role;
+48 -1
View File
@@ -295,15 +295,29 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm:
}
return;
}
// An adjustment recorded on the smart object (Brightness/Contrast, Levels…) re-opens its own
// Image › Adjustments editor, like the filters above.
if crate::adjust_dialog::has_dialog(&f.command) {
if let Some(id) = crate::adjust_dialog::open(app, &f.command) {
edit_filter(app, id, layer, index, &f.params);
}
return;
}
if !crate::filter_dialog::has_dialog(&f.command) {
return;
}
let Some(id) = crate::filter_dialog::open(app, &f.command) else { return };
edit_filter(app, id, layer, index, &f.params);
}
/// Hands the open dialog `id` the smart filter's recorded `params` and makes OK update that
/// filter (`layer.smartFilter.setParams`, see [`confirm_command`]) instead of adding another.
fn edit_filter(app: &mut PhotocraftApp, id: u64, layer: u64, index: usize, params: &Value) {
if let Some(d) = app.ui.dialog_mut(id) {
// The live preview would stack a second copy of the filter on the smart object.
d.fields.remove("__preview");
d.fields.insert("__smartFilter".into(), json!({"layer": layer, "index": index}));
if let Value::Object(p) = &f.params {
if let Value::Object(p) = params {
for (k, v) in p {
if d.fields.contains_key(k) {
d.fields.insert(k.clone(), v.clone());
@@ -405,4 +419,37 @@ mod tests {
assert!(drawn.contains(&(frame, t.field)));
assert!(drawn.iter().all(|(_, c)| *c != t.icon));
}
/// #5689: an Image › Adjustments recorded on a smart object (Brightness/Contrast…) opens its
/// own editor from the Smart Filters row, with the recorded settings, and OK updates that
/// filter instead of stacking another.
#[test]
fn an_adjustment_smart_filter_opens_its_editor_and_updates_it() {
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"contents": "black"})).unwrap();
let id = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap();
s.execute("image.adjustments.brightnessContrast", json!({"brightness": 40, "contrast": -10})).unwrap();
let mut app = PhotocraftApp::new(s, crate::Services::default());
let sm = match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content {
LayerContent::Smart(sm) => sm.clone(),
other => panic!("expected a smart object, got {other:?}"),
};
assert_eq!(sm.smart_filters.len(), 1);
open_editor(&mut app, &egui::Context::default(), id, &sm, 0);
let d = app.ui.dialogs.last().expect("the adjustment editor opened");
assert_eq!(d.fields.get("__adjust").and_then(Value::as_str), Some("brightnessContrast"));
assert_eq!(d.fields.get("brightness").and_then(Value::as_f64), Some(40.0), "the recorded settings");
assert_eq!(d.fields.get("contrast").and_then(Value::as_f64), Some(-10.0));
let dialog = d.id;
// OK updates the recorded filter (one history step), it does not add a second filter.
crate::dialogs::confirm(&mut app, dialog).unwrap();
let LayerContent::Smart(sm) = &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content else {
panic!("the layer stays a smart object");
};
assert_eq!(sm.smart_filters.len(), 1, "no filter was stacked");
assert_eq!(sm.smart_filters[0].params.get("brightness").and_then(Value::as_f64), Some(40.0));
assert_eq!(sm.smart_filters[0].params.get("contrast").and_then(Value::as_f64), Some(-10.0));
}
}
+117 -1
View File
@@ -31,6 +31,9 @@ pub enum Gesture {
/// A selection outline (or its floating piece) dragged with a selection tool: its bounds at
/// the start of the drag.
SelectionMove { rect: [f64; 4] },
/// A marquee, Object Selection box or shape being drawn, repositioned with Space held
/// (`hold_keys`): its bounds when Space went down.
DrawMove { rect: [f64; 4] },
/// A guide being moved with the Move tool.
Guide,
}
@@ -292,7 +295,7 @@ fn apply(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> [f64; 2
}
Gesture::TransformCorner { .. } => snap.targets.snap_point(p, tol),
Gesture::Guide => snap.targets.snap_point(p, tol),
Gesture::Move { rect } | Gesture::TransformMove { rect } | Gesture::SelectionMove { rect } => {
Gesture::Move { rect } | Gesture::TransformMove { rect } | Gesture::SelectionMove { rect } | Gesture::DrawMove { rect } => {
let d = [p[0] - snap.start[0], p[1] - snap.start[1]];
let moved = [rect[0] + d[0], rect[1] + d[1], rect[2] + d[0], rect[3] + d[1]];
let set = if snap.targets.is_empty() { &snap.smart } else { &snap.targets };
@@ -388,6 +391,40 @@ fn crop_handle(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers, targets:
Some((view.map_or(q, |view| crate::crop_mode::from_press(app, view, q)), lines))
}
/// The bounds `[x0, y0, x1, y1]` of what drag `d` draws so far, for the tools whose drag Space
/// repositions and that snap (`None` for the rest, or a shape still too small to draw).
fn drawn_rect(app: &PhotocraftApp, d: &crate::canvas::Drag) -> Option<[f64; 4]> {
let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]);
let (a, b) = match d.tool {
Tool::RectMarquee | Tool::EllipseMarquee => crate::canvas::marquee_corners(&app.ui.tool_options, d, last),
Tool::ObjectSelection => (d.start, last),
t if crate::vector_ui::is_shape_tool(t) => return crate::vector_ui::shape_bounds(&app.ui.tool_options, t, d.start, last, d.live),
_ => return None,
};
Some([a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])])
}
/// Space held while a marquee, Object Selection box or shape is drawn moves the whole of it
/// (`hold_keys`): its edges and centre snap, as a moved selection's do, not just the corner under
/// the pointer. Releasing Space goes back to snapping that corner.
fn follow_reposition(app: &mut PhotocraftApp) {
let Some(d) = app.drag.as_ref() else { return };
let Some(snap) = app.prefs_rt.snap.as_ref() else { return };
let gesture = match (&snap.gesture, d.reposition) {
(Gesture::Point, true) => match drawn_rect(app, d) {
Some(rect) => Gesture::DrawMove { rect },
None => return,
},
(Gesture::DrawMove { .. }, false) => Gesture::Point,
_ => return,
};
let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]);
if let Some(snap) = app.prefs_rt.snap.as_mut() {
snap.gesture = gesture;
snap.start = last;
}
}
/// Snap a tool event's coordinates (called by `canvas::tool_event` before the tools see it).
pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent {
match ev {
@@ -415,6 +452,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier
if app.prefs_rt.snap.is_none() {
return ev;
}
follow_reposition(app);
let disabled = override_for_gesture(app, mods);
if let Some(s) = app.prefs_rt.snap.as_mut() {
s.disabled = disabled;
@@ -427,6 +465,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier
if app.prefs_rt.snap.is_none() {
return ev;
}
follow_reposition(app);
let disabled = override_for_gesture(app, mods);
if let Some(s) = app.prefs_rt.snap.as_mut() {
s.disabled = disabled;
@@ -661,6 +700,37 @@ mod tests {
assert_eq!(sel.x1, 116);
}
/// Space while drawing a marquee, Object Selection box or shape moves it: its edges snap, not
/// only the corner under the pointer; with Space released the corner snaps again.
#[test]
fn drawing_repositioned_with_space_snaps_its_edges() {
for tool in [Tool::RectMarquee, Tool::EllipseMarquee, Tool::ObjectSelection, Tool::Rectangle, Tool::Line] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.sync_views();
app.ui.views[0].zoom = 1.0;
app.ui.views[0].fit_pending = false;
app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap();
app.ui.tool = tool;
let m = egui::Modifiers::NONE;
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m);
crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 140.0, pressure: 1.0 }, m);
// Space down: the 50 × 40 box moves so its left edge lands 4 px short of the guide;
// the pointer corner (x = 266) is near nothing.
app.drag.as_mut().unwrap().reposition = true;
crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 266.0, y: 140.0, pressure: 1.0 }, m);
assert_eq!(app.drag.as_ref().unwrap().start, [220.0, 100.0], "{tool:?}");
if tool != Tool::RectMarquee {
continue;
}
// Space up: sizing resumes and the corner snaps to the document's right edge.
app.drag.as_mut().unwrap().reposition = false;
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 397.0, y: 140.0 }, m);
let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds();
assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (220, 100, 400, 140));
}
}
/// Dragging inside a selection with a marquee or lasso moves the outline (⌘ cuts the pixels
/// into a floating piece): its bounds snap, not the pointer.
#[test]
@@ -1019,6 +1089,52 @@ mod tests {
assert_eq!(mover_bounds(&app).x0, 300);
}
/// #5751: a Rectangle drawn on a 1080 px canvas, then resized with Free Transform under the
/// Move tool. With Snap Vector Tools and Transforms to Pixel Grid on (the default) the box's
/// edges stay on whole pixels: the grab offset and a proportional scale used to leave them at
/// 20.6 and 1040.4. Off, the box follows the pointer exactly.
#[test]
fn free_transform_of_a_shape_keeps_whole_pixels() {
for grid in [true, false] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 1080, "height": 1080, "resolution": 72})).unwrap();
app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": grid})).unwrap();
app.sync_views();
app.ui.views[0].zoom = 0.6;
app.ui.views[0].fit_pending = false;
app.ui.tool = Tool::Rectangle;
let m = egui::Modifiers::NONE;
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 31.0, pressure: 1.0 }, m);
crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 300.0, y: 700.0, pressure: 1.0 }, m);
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 481.0, y: 1000.0 }, m);
app.ui.tool = Tool::Move;
crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap();
let whole = |q: [[f64; 2]; 4]| q.iter().flatten().all(|v| v.fract() == 0.0);
// The left edge handle, grabbed 1.3 px inside, dropped away from any snap target.
let q = app.ui.transform.as_ref().unwrap().quad;
let mid_y = (q[0][1] + q[3][1]) / 2.0;
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[0][0] + 1.3, y: mid_y, pressure: 1.0 }, m);
crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 60.0, y: mid_y, pressure: 1.0 }, m);
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 80.6, y: mid_y }, m);
let q = app.ui.transform.as_ref().unwrap().quad;
assert_eq!(whole(q), grid, "grid {grid}: left edge {q:?}");
// The bottom-right corner scaled proportionally (the default), off any snap target.
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[2][0], y: q[2][1], pressure: 1.0 }, m);
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 450.4, y: 900.1 }, m);
let q = app.ui.transform.as_ref().unwrap().quad;
assert_eq!(whole(q), grid, "grid {grid}: corner {q:?}");
crate::transform_tool::commit(&mut app);
let st = app.session.active().unwrap();
let photocraft_doc::LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") };
let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap();
if grid {
for v in [x0, y0, x1, y1] {
assert!((v - v.round()).abs() < 1e-6, "committed shape {:?}", (x0, y0, x1, y1));
}
}
}
}
#[test]
fn guides_snap_to_layer_edges() {
let mut app = app_with_box();
+4
View File
@@ -1073,6 +1073,9 @@ pub struct UiState {
/// Inline type editing session, if any.
#[serde(default)]
pub text_edit: Option<TextEdit>,
/// Tool to restore when an inline type edit session commits or cancels (e.g. Move tool, #1132).
#[serde(skip)]
pub text_edit_return_tool: Option<Tool>,
/// Ctrl/Cmd Type-tool gesture, exposed to automation but never restored as a held pointer.
#[serde(default, skip_deserializing)]
pub type_transform: Option<TypeTransform>,
@@ -1304,6 +1307,7 @@ impl Default for UiState {
spring: None,
recent_files: Vec::new(),
text_edit: None,
text_edit_return_tool: None,
type_transform: None,
type_transform_pivot: None,
cam_transform: None,
+17
View File
@@ -538,6 +538,23 @@ mod tests {
use egui::{Event, Pos2, RawInput, ViewportId};
use photocraft_engine::Session;
/// #5826: the drag overlay under a dialog doesn't depend on the custom title bar. On macOS
/// (OS traffic lights over the app's own title strip) a dialog left the window undraggable.
#[test]
fn a_dialog_keeps_the_title_strip_draggable_with_either_title_bar() {
for custom in [false, true] {
let mut app = PhotocraftApp::new(Session::new(), crate::Services::default());
app.custom_titlebar = custom;
app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap();
assert!(!app.titlebar_modal_drag(true), "no dialog, no overlay");
crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap();
assert!(app.titlebar_modal_drag(true), "custom title bar: {custom}");
assert!(!app.titlebar_modal_drag(false), "chrome hidden (full screen): no title strip");
app.ui.panels.menu_bar = false;
assert!(!app.titlebar_modal_drag(true), "no menu bar, no title strip");
}
}
/// A headless window `width` pt wide showing the title bar and the resize zones.
struct Win {
ctx: egui::Context,
+18 -2
View File
@@ -93,9 +93,25 @@ fn close_ring() -> Vec<Vec2> {
}
/// Can this pass show an OS cursor bitmap? eframe's immediate viewports and its web integration
/// don't upload cursor images; every desktop root viewport does (winit custom cursors).
/// don't upload cursor images; every desktop root viewport does (winit custom cursors). Wayland at
/// any scale but 1 doesn't either: winit sizes the bitmap there with a `wp_viewport` destination
/// that some compositors ignore on cursor surfaces (Hyprland 0.56; Mutter before GNOME 48). They
/// show it one bitmap pixel per logical pixel, so at 1.25 a brush outline was 1.25× too large and
/// its centre sat 0.2 × its half-width right of and below the pointer, which is where the brush
/// painted. Nothing tells the app which compositor does what, so the outline is painted instead.
fn native(ctx: &egui::Context) -> bool {
cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() == egui::ViewportId::ROOT
cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() == egui::ViewportId::ROOT && !scaled_wayland(ctx)
}
/// Mark this window as a Wayland surface (or not), for [`native`]; the shell calls it every pass.
pub(crate) fn set_wayland(ctx: &egui::Context, wayland: bool) {
ctx.data_mut(|d| d.insert_temp(egui::Id::new("photocraft-cursor-wayland"), wayland));
}
/// A Wayland window whose scale is not 1, where winit's cursor bitmaps are unreliable.
fn scaled_wayland(ctx: &egui::Context) -> bool {
let wayland = cfg!(target_os = "linux") && ctx.data(|d| d.get_temp::<bool>(egui::Id::new("photocraft-cursor-wayland"))).unwrap_or(false);
wayland && ctx.native_pixels_per_point().unwrap_or_else(|| ctx.pixels_per_point() / ctx.zoom_factor()) != 1.0
}
/// Bitmap pixels per egui point. winit takes an `NSCursor` image's dimensions as logical points on
+34
View File
@@ -272,6 +272,40 @@ fn ordinary_brush_cursor_is_not_part_of_the_canvas_draw_list() {
assert!(output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Circle(_))), "the full tip is not silently shrunk");
}
#[test]
#[cfg(target_os = "linux")]
fn scaled_wayland_paints_the_brush_outline_instead_of_an_os_bitmap() {
// Hyprland ignores the viewport winit sizes cursor bitmaps with: at 1.25 the outline was
// 1.25× too large and its centre 0.2 × its half-width right of and below where the brush
// painted. Off scale 1 on Wayland the outline is painted at the pointer, at its true size.
let run = |ctx: &egui::Context, native_ppp: f32| {
let mut input = egui::RawInput::default();
input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(native_ppp);
let mut output = ctx.run_ui(input, |ui| {
let icon = circle(ui.painter(), pos2(100.0, 100.0), 20.0, false);
ui.ctx().set_cursor_icon(icon);
});
output.textures_delta.clear();
let circles: Vec<_> =
output.shapes.iter().filter_map(|s| if let egui::Shape::Circle(c) = &s.shape { Some((c.center, c.radius)) } else { None }).collect();
(output.platform_output.cursor_image.is_some(), output.platform_output.cursor_icon, circles)
};
let ctx = egui::Context::default();
ctx.add_plugin(CursorLifecycle);
set_wayland(&ctx, true);
for ppp in [1.25, 1.5, 2.0] {
let (bitmap, icon, circles) = run(&ctx, ppp);
assert!(!bitmap, "{ppp}: no OS bitmap");
assert_eq!(icon, CursorIcon::None, "{ppp}: the painted outline is the pointer");
assert!(!circles.is_empty() && circles.iter().all(|&(c, r)| c == pos2(100.0, 100.0) && r == 20.0), "{ppp}: {circles:?}");
}
let (bitmap, _, circles) = run(&ctx, 1.0);
assert!(bitmap && circles.is_empty(), "Wayland at scale 1 keeps the low-latency bitmap");
set_wayland(&ctx, false);
let (bitmap, _, circles) = run(&ctx, 1.25);
assert!(bitmap && circles.is_empty(), "X11 at 1.25 keeps the bitmap");
}
/// Run explicitly for visual QA: native cursors are absent from GPU screenshots.
#[test]
#[ignore = "writes target/tool-cursor-preview.png for visual inspection"]
+112 -58
View File
@@ -1435,6 +1435,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) ->
} else {
apply_mode_drag(s, g, [x, y], mode, type_layer, mods);
}
round_to_pixel_grid(app);
}
}
}
@@ -1442,6 +1443,40 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) ->
true
}
/// Preferences › Tools › Snap Vector Tools and Transforms to Pixel Grid (#5751): while a shape
/// layer or a path is moved or scaled (the box still an upright rectangle), its edges stay on
/// whole pixels, whatever the tool. Rounding the pointer alone left the edges off by the grab
/// offset, and a proportional scale off by its ratio: a shape dragged to 540 px came out 539.6.
/// Rotated, skewed and distorted boxes are left as dragged.
fn round_to_pixel_grid(app: &mut PhotocraftApp) {
if !app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid {
return;
}
let Some(t) = app.ui.transform.as_ref() else { return };
if t.selection || t.warp.is_some() || t.content_aware.is_some() || t.target.is_some() {
return;
}
let vector =
t.path.is_some() || app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Shape(_)));
if !vector || !upright(&t.quad) {
return;
}
let q = t.quad.map(|p| p.map(f64::round));
// A box narrower than a pixel keeps its size rather than collapsing.
if (q[1][0] - q[0][0]).abs() < 1.0 || (q[3][1] - q[0][1]).abs() < 1.0 || q.iter().flatten().any(|v| !v.is_finite()) {
return;
}
if let Some(s) = app.ui.transform.as_mut() {
s.quad = q;
}
}
/// Whether corners clockwise from top-left form an axis-aligned rectangle (flips included).
fn upright(q: &[[f64; 2]; 4]) -> bool {
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
near(q[0][1], q[1][1]) && near(q[2][1], q[3][1]) && near(q[0][0], q[3][0]) && near(q[1][0], q[2][0])
}
/// The same effective modifiers drive the geometry and decide whether Ctrl is a distortion
/// gesture rather than the ordinary snap override. Keep type and Content-Aware Scale refusals.
fn drag_mods(app: &PhotocraftApp, t: &TransformSession, hit: Hit, mods: egui::Modifiers) -> (TransformMode, egui::Modifiers) {
@@ -1717,8 +1752,7 @@ pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods
let Some(inv) = h.inverse() else { return };
let (u, v) = inv.apply(p[0], p[1]);
let (pu, pv) = inv.apply(g.pivot0[0], g.pivot0[1]);
// Moving edges/corner in unit space: [u0, v0, u1, v1] starting as [0, 0, 1, 1].
let mut r = [0.0f64, 0.0, 1.0, 1.0];
// Which sides of the unit box move: (u = 0, u = 1) and (v = 0, v = 1).
let (mu, mv) = match g.hit {
Hit::Corner(0) => ((true, false), (true, false)),
Hit::Corner(1) => ((false, true), (true, false)),
@@ -1729,33 +1763,21 @@ pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods
Hit::Edge(2) => ((false, false), (false, true)),
_ => ((true, false), (false, false)),
};
if mu.0 {
r[0] = u;
}
if mu.1 {
r[2] = u;
}
if mv.0 {
r[1] = v;
}
if mv.1 {
r[3] = v;
}
// ⌥: symmetric about the reference point.
if mods.alt {
if mu.0 {
r[2] = 2.0 * pu - r[0];
// Each axis scales by a factor `k` about an anchor: the opposite side, or with ⌥ the
// reference point, wherever it was set (#1329). The dragged handle follows the cursor.
let axis = |moving: (bool, bool), at: f64, pivot: f64| -> (f64, f64) {
if !moving.0 && !moving.1 {
return (0.5, 1.0);
}
if mu.1 {
r[0] = 2.0 * pu - r[2];
}
if mv.0 {
r[3] = 2.0 * pv - r[1];
}
if mv.1 {
r[1] = 2.0 * pv - r[3];
}
}
let handle = if moving.0 { 0.0 } else { 1.0 };
let anchor = if mods.alt { pivot } else { 1.0 - handle };
let d = handle - anchor;
// A reference point on the dragged side leaves nothing to scale against.
let k = if d.abs() > 1e-9 { (at - anchor) / d } else { 1.0 };
(anchor, if k.is_finite() { k } else { 1.0 })
};
let (mut au, mut ku) = axis(mu, u, pu);
let (mut av, mut kv) = axis(mv, v, pv);
// Corners and edges scale proportionally by default; ⇧ frees them (the legacy
// preference swaps the two for corners and always stretches edges, `legacy_mods`).
let corner = matches!(g.hit, Hit::Corner(_));
@@ -1765,41 +1787,16 @@ pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods
// corners), so the opposite edge's handle stays put. Past the opposite edge only
// the dragged axis flips.
if mu.0 || mu.1 {
let k = (r[2] - r[0]).abs();
let c = if mods.alt { pv } else { 0.5 };
r[1] = c - k / 2.0;
r[3] = c + k / 2.0;
(av, kv) = (if mods.alt { pv } else { 0.5 }, ku.abs());
} else {
let k = (r[3] - r[1]).abs();
let c = if mods.alt { pu } else { 0.5 };
r[0] = c - k / 2.0;
r[2] = c + k / 2.0;
(au, ku) = (if mods.alt { pu } else { 0.5 }, kv.abs());
}
}
if corner && !mods.shift {
let (sx, sy) = (r[2] - r[0], r[3] - r[1]);
let k = if sx.abs() > sy.abs() { sx.abs() } else { sy.abs() };
let (nx, ny) = (k * sx.signum(), k * sy.signum());
let (ax, ay) = if mods.alt { (pu, pv) } else { (if mu.0 { r[2] } else { r[0] }, if mv.0 { r[3] } else { r[1] }) };
let fx = if mods.alt {
0.5
} else if mu.0 {
1.0
} else {
0.0
};
let fy = if mods.alt {
0.5
} else if mv.0 {
1.0
} else {
0.0
};
r[0] = ax - nx * fx;
r[2] = r[0] + nx;
r[1] = ay - ny * fy;
r[3] = r[1] + ny;
let k = ku.abs().max(kv.abs());
(ku, kv) = (k * ku.signum(), k * kv.signum());
}
let r = [au - au * ku, av - av * kv, au + (1.0 - au) * ku, av + (1.0 - av) * kv];
let map = |a: f64, b: f64| {
let (x, y) = h.apply(a, b);
[x, y]
@@ -3755,6 +3752,37 @@ mod tests {
assert!(close(s.quad, corners([-50.0, 0.0, 150.0, 50.0])), "{:?}", s.quad);
}
/// A reference point moved off the centre (⌥-click) is the centre of ⌥-scaling too, not just
/// of rotation: it stays put and the box scales away from it.
#[test]
fn alt_scales_about_a_moved_reference_point() {
let alt = egui::Modifiers::ALT;
// Reference point on the top-left corner: the bottom-right corner to (200, 100) doubles
// the box, top-left fixed (not centred on the reference point).
let mut s = session();
s.pivot = [0.0, 0.0];
drag(&mut s, [100.0, 50.0], [200.0, 100.0], alt);
assert!(close(s.quad, corners([0.0, 0.0, 200.0, 100.0])), "{:?}", s.quad);
assert!(near(s.pivot, [0.0, 0.0]), "{:?}", s.pivot);
// Reference point at (25, 25): the right edge to x = 175 is 2× about x = 25, and
// proportionally 2× about y = 25 too.
let mut s = session();
s.pivot = [25.0, 25.0];
drag(&mut s, [100.0, 25.0], [175.0, 25.0], alt);
assert!(close(s.quad, corners([-25.0, -25.0, 175.0, 75.0])), "{:?}", s.quad);
// ⌥⇧: that edge's axis only.
let mut s = session();
s.pivot = [25.0, 25.0];
drag(&mut s, [100.0, 25.0], [175.0, 25.0], egui::Modifiers { alt: true, shift: true, ..Default::default() });
assert!(close(s.quad, corners([-25.0, 0.0, 175.0, 50.0])), "{:?}", s.quad);
// Reference point in line with the dragged corner horizontally: that axis has nothing to
// scale against and stays, the other doubles about it.
let mut s = session();
s.pivot = [100.0, 50.0];
drag(&mut s, [100.0, 0.0], [150.0, -50.0], egui::Modifiers { alt: true, shift: true, ..Default::default() });
assert!(close(s.quad, corners([0.0, -50.0, 100.0, 50.0])), "{:?}", s.quad);
}
fn near(a: [f64; 2], b: [f64; 2]) -> bool {
(a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6
}
@@ -4924,6 +4952,32 @@ mod tests {
assert!(app.ui.transform.as_ref().unwrap().warp.is_none());
}
#[test]
fn a_thin_layer_scaled_then_warped_commits_the_curve() {
// #5793: a 3 px column stretched wide, switched to Warp and pulled down in the middle.
// The commit came out straight: the warp's grid was one cell across the 3 source pixels.
let mut app = app_with_square(128, photocraft_geom::Rect::new(40, 20, 43, 60));
let ctx = egui::Context::default();
begin(&mut app, &ctx).unwrap();
scale_about_pivot(&mut app, 30.0, 1.0);
enter_warp(&mut app, &ctx);
warp_pointer(&mut app, ToolEvent::Down { x: 41.5, y: 40.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);
warp_pointer(&mut app, ToolEvent::Move { x: 41.5, y: 70.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE);
warp_pointer(&mut app, ToolEvent::Up { x: 41.5, y: 70.0 }, 2.0, egui::Modifiers::NONE);
commit(&mut app);
assert!(app.ui.transform.is_none(), "{}", app.ui.status);
let st = app.session.active().unwrap();
let s = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
let alpha = |x: i32, y: i32| {
let mut p = [0.0f32; 4];
s.read_pixel(x, y, &mut p);
p[3]
};
// The middle sags below the band's old bottom edge (y 60); the ends stay put.
assert!(alpha(41, 70) > 0.99, "middle {}", alpha(41, 70));
assert!(alpha(15, 70) < 0.01 && alpha(15, 40) > 0.99, "end {} {}", alpha(15, 70), alpha(15, 40));
}
fn warping_square() -> PhotocraftApp {
let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32));
begin_warp(&mut app, &egui::Context::default()).unwrap();
+40 -1
View File
@@ -768,7 +768,17 @@ fn spelling_window(app: &mut PhotocraftApp, ctx: &egui::Context) {
.anchor(Align2::CENTER_CENTER, vec2(0.0, -40.0))
.show(ctx, |ui| {
ui.set_width(380.0);
ui.label(RichText::new(tl!("Check Spelling")).color(t.text).size(13.0).strong());
ui.horizontal(|ui| {
ui.label(RichText::new(tl!("Check Spelling")).color(t.text).size(13.0).strong());
// The close box (#5496) is Done, as in Photoshop: every change is already made.
if crate::dialogs::CLOSE_BOX {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if crate::icons::button(ui, "x", 20.0, false, tl!("Close")).clicked() {
act = Some("done");
}
});
}
});
ui.add_space(6.0);
ui.horizontal_top(|ui| {
ui.vertical(|ui| {
@@ -930,4 +940,33 @@ mod tests {
// Headless calls with an action go to the engine.
assert!(menu(&mut app, "edit.checkSpelling", &json!({"action": "list"})).is_none());
}
/// #5496: Check Spelling's close box is Done, as in Photoshop on Windows: the window closes
/// and the text keeps what it had. None on macOS.
#[test]
fn check_spellings_close_box_is_done() {
use egui_kittest::kittest::Queryable;
let mut app = app_with_text("Teh cat");
menu(&mut app, "edit.checkSpelling", &json!({})).unwrap().unwrap();
let revision = app.session.active().unwrap().revision;
// The fonts are set up after the harness's first frame: the window appears after it.
let spell = app.ui.type_panels.spell.take();
let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state(|ui, app| windows(app, ui.ctx()), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.state_mut().ui.type_panels.spell = spell;
h.run_steps(3);
if !crate::dialogs::CLOSE_BOX {
assert_eq!(h.query_all_by_label("Close").count(), 0, "no close box on macOS");
return;
}
let x = h.get_by_label("Close").rect();
let done = h.get_by_label("Done").rect();
assert!(x.bottom() <= done.top() && x.right() >= done.right(), "the × ends the title row: {x:?} over {done:?}");
h.hover_at(x.center());
h.drag_at(x.center());
h.drop_at(x.center());
h.run_steps(2);
assert!(h.state().ui.type_panels.spell.is_none(), "the × closed Check Spelling");
assert_eq!(h.state().session.active().unwrap().revision, revision, "and changed nothing");
}
}
+65 -10
View File
@@ -121,6 +121,7 @@ pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> {
ed.caret = n;
}
let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical);
app.ui.text_edit_return_tool = None;
app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type };
app.ui.mask_target = false;
app.ui.vector_mask_target = false;
@@ -132,6 +133,7 @@ pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> {
/// type is there.
pub fn edit_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool {
let Some(id) = hit_layer(app, x, y) else { return false };
let previous_tool = app.ui.tool;
commit(app);
if app.session.select_layer(id).is_err() {
return false;
@@ -144,6 +146,9 @@ pub fn edit_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool {
app.ui.text_edit =
Some(TextEdit { layer: id.0, caret: off, anchor: off, session: key, created: false, mask: false, dragging: false, resize: None, preedit: None });
let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical);
if !previous_tool.is_type() {
app.ui.text_edit_return_tool = Some(previous_tool);
}
app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type };
app.ui.mask_target = false;
app.ui.vector_mask_target = false;
@@ -271,6 +276,7 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifie
let off = hit_offset(app, id, x, y);
app.ui.text_edit =
Some(TextEdit { layer: id.0, caret: off, anchor: off, session: key, created: false, mask: false, dragging: true, resize: None, preedit: None });
app.ui.text_edit_return_tool = None;
return true;
}
false
@@ -335,6 +341,7 @@ pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {
// Like Photoshop: the placeholder is selected, so typing replaces it.
let n = text.chars().count();
app.ui.text_edit = Some(TextEdit { layer: id, caret: n, anchor: 0, session: key, created: true, mask, dragging: false, resize: None, preedit: None });
app.ui.text_edit_return_tool = None;
}
}
@@ -773,6 +780,7 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
let id = LayerId(ed.layer);
let Some(text) = current_text(app, id) else {
app.ui.text_edit = None;
app.ui.text_edit_return_tool = None;
return false;
};
// Undo/redo can shorten the text under us.
@@ -960,6 +968,11 @@ pub fn commit_with(app: &mut PhotocraftApp, mods: egui::Modifiers) {
}
crate::type_transform::reset(app);
let Some(ed) = app.ui.text_edit.take() else { return };
if let Some(tool) = app.ui.text_edit_return_tool.take()
&& app.ui.tool.is_type()
{
app.ui.tool = tool;
}
let Some(text) = current_text(app, LayerId(ed.layer)) else { return };
if ed.mask {
// Type Mask: the text's glyphs become (or combine with) the selection and the working
@@ -1014,20 +1027,20 @@ pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewX
}
// Frame: paragraph text shows its box with handles; point text an underline per line.
let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers));
if crate::type_transform::draw(app, painter, xf, mods) {
return;
}
let has_transform = crate::type_transform::draw(app, painter, xf, mods);
let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone()));
let frame = Stroke::new(1.0, t.accent);
match shape {
Some(photocraft_doc::text::TextShape::Box { x, y, width, height }) => {
let c = [scr_t(x, y), scr_t(x + width, y), scr_t(x + width, y + height), scr_t(x, y + height)];
painter.add(egui::Shape::closed_line(c.to_vec(), frame));
let mids = [c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5), c[3].lerp(c[0], 0.5)];
for p in c.iter().chain(mids.iter()) {
let r = egui::Rect::from_center_size(*p, egui::vec2(7.0, 7.0));
painter.rect_filled(r, 0.0, Color32::WHITE);
painter.rect_stroke(r, 0.0, frame, egui::StrokeKind::Inside);
if !has_transform {
let c = [scr_t(x, y), scr_t(x + width, y), scr_t(x + width, y + height), scr_t(x, y + height)];
painter.add(egui::Shape::closed_line(c.to_vec(), frame));
let mids = [c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5), c[3].lerp(c[0], 0.5)];
for p in c.iter().chain(mids.iter()) {
let r = egui::Rect::from_center_size(*p, egui::vec2(7.0, 7.0));
painter.rect_filled(r, 0.0, Color32::WHITE);
painter.rect_stroke(r, 0.0, frame, egui::StrokeKind::Inside);
}
}
}
_ => {
@@ -2392,6 +2405,11 @@ fn type_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
pub fn cancel(app: &mut PhotocraftApp) {
crate::type_transform::reset(app);
let Some(ed) = app.ui.text_edit.take() else { return };
if let Some(tool) = app.ui.text_edit_return_tool.take()
&& app.ui.tool.is_type()
{
app.ui.tool = tool;
}
undo_session(app, &ed);
}
@@ -2682,4 +2700,41 @@ mod tests {
assert_eq!(word_boundary("hello big world", 7, false), 6);
assert_eq!(word_boundary("hello big world", 15, false), 10);
}
#[test]
fn double_click_from_move_tool_restores_move_tool_on_commit_and_cancel() {
let (mut app, _) = variants();
app.ui.tool = crate::state::Tool::Move;
assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1));
assert_eq!(app.ui.tool, crate::state::Tool::Type);
assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move));
commit(&mut app);
assert_eq!(app.ui.tool, crate::state::Tool::Move, "commit restores the Move tool");
assert_eq!(app.ui.text_edit_return_tool, None);
// Also test cancel
app.ui.tool = crate::state::Tool::Move;
assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1));
assert_eq!(app.ui.tool, crate::state::Tool::Type);
cancel(&mut app);
assert_eq!(app.ui.tool, crate::state::Tool::Move, "cancel restores the Move tool");
assert_eq!(app.ui.text_edit_return_tool, None);
// Switching tools mid-edit commits without overriding the newly chosen tool
app.ui.tool = crate::state::Tool::Move;
assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1));
assert_eq!(app.ui.tool, crate::state::Tool::Type);
assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move));
app.ui.tool = crate::state::Tool::Brush;
commit(&mut app);
assert_eq!(app.ui.tool, crate::state::Tool::Brush, "switching tools keeps the chosen tool");
assert_eq!(app.ui.text_edit_return_tool, None);
// Layers-thumbnail edit stays on Type tool (matches Photoshop)
app.ui.tool = crate::state::Tool::Move;
edit_active(&mut app).unwrap();
assert_eq!(app.ui.tool, crate::state::Tool::Type);
assert_eq!(app.ui.text_edit_return_tool, None);
commit(&mut app);
assert_eq!(app.ui.tool, crate::state::Tool::Type, "Layers-thumbnail edit stays on Type tool");
}
}
+37
View File
@@ -779,6 +779,23 @@ fn temporary_type_transform_visibility_and_cursors() {
assert!(crate::type_transform::visible(h.state(), sticky));
}
#[test]
fn type_selection_highlight_visible_with_command_held() {
let (app, _id) = transform_app(false, false, Affine::IDENTITY);
let mut h = harness(1.0, app);
if let Some(ed) = h.state_mut().ui.text_edit.as_mut() {
ed.anchor = 0;
ed.caret = 5;
}
hold(&mut h, type_command());
h.run();
let accent = crate::theme::Tokens::get(&h.ctx).accent;
let expected_fill = egui::Color32::from_rgba_unmultiplied(accent.r(), accent.g(), accent.b(), 110);
let has_selection_highlight =
h.output().shapes.iter().any(|clipped| if let egui::Shape::Path(path) = &clipped.shape { path.fill == expected_fill && path.closed } else { false });
assert!(has_selection_highlight, "selection highlight must remain visible while Ctrl/Cmd is held");
}
/// Real canvas input: layer-local scaling stays correct across orientation, zoom, HiDPI and flip.
#[test]
fn temporary_type_transform_scales_without_reflow_or_leaving_type() {
@@ -1528,6 +1545,26 @@ mod multi_layer_formatting {
assert_eq!(text(h.state(), ids[1]).char_runs(), peer);
}
/// #5717: a layer scaled so its shown size or leading is past a field's range (2400 pt, or
/// 0.08 pt) keeps it while the Character panel and the options bar only show it.
#[test]
fn showing_a_scaled_layer_past_the_size_range_does_not_change_it() {
for (layer, scale) in [(0, 200.0), (1, 0.005)] {
for properties in [true, false] {
let (mut app, ids) = fixture();
let id = ids[layer];
app.run("type.edit", json!({"layer": id.0, "transform": [scale, 0.0, 0.0, scale, 0.0, 0.0]})).unwrap();
selected(&mut app, &[id]);
let before = text(&app, id).char_runs();
let steps = app.session.active().unwrap().history.entries().len();
let mut h = controls(app, properties);
h.run_steps(3);
assert_eq!(text(h.state(), id).char_runs(), before, "scale {scale}, properties {properties}");
assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "no history step");
}
}
}
#[test]
fn formatting_menus_isolate_the_edit_layer_and_range_but_honor_explicit_targets() {
let (mut app, ids) = fixture();
+1
View File
@@ -52,6 +52,7 @@ pub(crate) fn cancel_stale(app: &mut PhotocraftApp) {
cancel_drag(app);
if lost_layer {
app.ui.text_edit = None;
app.ui.text_edit_return_tool = None;
}
}
}
+26
View File
@@ -104,6 +104,19 @@ fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], m
})
}
/// The box `[x0, y0, x1, y1]` a Shape-tool drag draws (a line's: its ends'), which snaps while
/// Space repositions it (`snap_ui`). None when too small to draw.
pub fn shape_bounds(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option<[f64; 4]> {
let g = shape_geometry(o, tool, start, end, mods)?;
if tool == Tool::Line {
let a: [f64; 2] = serde_json::from_value(g["from"].clone()).ok()?;
let b: [f64; 2] = serde_json::from_value(g["to"].clone()).ok()?;
return Some([a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]);
}
let [x, y, w, h]: [f64; 4] = serde_json::from_value(g["rect"].clone()).ok()?;
Some([x, y, x + w, y + h])
}
/// Finish a Shape-tool drag: ⇧ constrains proportions, ⌥ draws from the centre.
pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) {
let Some(mut p) = shape_geometry(&app.ui.tool_options, tool, start, end, mods) else { return };
@@ -725,6 +738,19 @@ pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> {
}
}
/// Does ⌫ / Delete delete the work path? With the Pen, Freeform Pen or Path Selection tool, no
/// path being drawn and the work path the one these tools show and edit (no shape layer or
/// targeted vector mask in front of it), as in Photoshop (#5702). It was drawn whenever one of
/// these tools was active, but the key reached Edit › Clear, so it looked impossible to delete.
/// Direct Selection and the Curvature Pen delete selected anchors in Photoshop, not the path.
pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool {
matches!(app.ui.tool, Tool::Pen | Tool::FreeformPen | Tool::PathSelection)
&& app.ui.pen.is_none()
&& app.ui.transform.is_none()
&& app.ui.view.shows(app.ui.view.show.target_path)
&& matches!(target_path(app), Some((PathTarget::Work, _)))
}
/// The path Path Selection edits: the targeted vector mask, the active shape layer's path, else
/// the work path.
fn target_path(app: &PhotocraftApp) -> Option<(PathTarget, Path)> {
+45
View File
@@ -198,6 +198,13 @@ const SNAP_IDLE_TIMEOUT: f64 = 0.5;
/// accumulator per viewport. `hovered` gates accumulation: only the viewport receiving
/// navigation may add raw input to the snap residual.
pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool) -> Option<Wheel> {
read_with(ctx, zoom_with_wheel, pinch_zooms, owner, hovered, true)
}
/// [`read`], choosing how a plain wheel scroll pans: `smooth` glides it over a few frames (egui's
/// smoothed delta); off, as with Interface › Enable Animations off, the view moves the whole notch
/// in the frame the wheel turns and stops there (#5721), as scroll areas already do.
pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool, smooth: bool) -> Option<Wheel> {
let notch = ctx.options(|o| o.input_options.line_scroll_speed);
// --- Modifier tracking (always runs for all callers) ---
@@ -316,6 +323,8 @@ pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id,
d.remove::<f64>(snap_time_id(owner));
});
}
// Unsmoothed, a plain scroll pans by this frame's own wheel events (none: no tail).
let scroll = if smooth || alt || shift { scroll } else { raw };
classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, notch })
}
}
@@ -370,6 +379,42 @@ mod tests {
(a - b).length() < 0.01
}
/// #5721: with smoothing off a wheel notch pans the whole notch in the frame it arrives and
/// nothing after; smoothed (the default) it glides, reaching the same total over later frames.
#[test]
fn unsmoothed_wheel_pans_at_once_without_a_glide() {
let pans = |smooth: bool| -> Vec<Vec2> {
let owner = Id::new("test-unsmoothed");
let ctx = Context::default();
configure(&ctx);
(0..30)
.map(|n| {
let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)] } else { Vec::new() };
let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() };
let mut pan = Vec2::ZERO;
let mut out = ctx.run_ui(raw, |ui| {
if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, owner, true, smooth) {
pan = d;
}
});
out.textures_delta.clear();
pan
})
.collect()
};
let notch = {
let ctx = Context::default();
configure(&ctx);
ctx.options(|o| o.input_options.line_scroll_speed)
};
let direct = pans(false);
assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]);
assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it");
let smooth = pans(true);
assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]);
assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows");
}
#[test]
fn plain_scroll_pans() {
assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0))));
+40 -3
View File
@@ -759,14 +759,20 @@ pub fn text_field_ex(ui: &mut Ui, id: egui::Id, text: &mut String, hint: &str, w
ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
}
let font = if mono { theme::mono(12.0) } else { egui::FontId::proportional(12.5) };
let mut edit = egui::TextEdit::singleline(text).id(id).hint_text(hint).frame(egui::Frame::NONE).font(font);
let inner = rect.shrink2(TEXT_FIELD_PAD);
// TextEdit draws its text at the top of its rect; fill the box and centre the line in it, so
// the text sits on the field's middle like a dropdown's or value field's.
let mut edit =
egui::TextEdit::singleline(text).id(id).hint_text(hint).frame(egui::Frame::NONE).font(font).min_size(inner.size()).vertical_align(egui::Align::Center);
if let Some(limit) = char_limit {
edit = edit.char_limit(limit);
}
// A child Ui keeps the field's selection colour local: `Visuals::selection` also fills selected
// list rows and slider trails, which must keep the theme's.
let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(TEXT_FIELD_PAD)).layout(layout));
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(layout));
// The theme's 24 pt interact height would make the edit taller than the box's inside.
child.spacing_mut().interact_size.y = inner.height();
child.style_mut().visuals.selection.bg_fill = t.field_selection();
child.add(edit)
}
@@ -818,6 +824,9 @@ fn number_edit(
let mut resp = ui.add(
egui::DragValue::new(value)
.range(range.clone())
// Only edits are clamped (below): showing a value past the range, such as a type layer
// scaled to 2400 pt in a 1296 pt field, must not change it (#5717).
.clamp_existing_to_range(false)
// A warp is an absolute-position jump. The scoped scrub below removes that jump.
.speed(if wrapped_drag { 0.0 } else { speed })
.custom_formatter(move |v, _| match decimals {
@@ -838,7 +847,12 @@ fn number_edit(
}),
);
if wrap_drag {
crate::scrub_wrap::update(ui, &resp, value, before, range, speed, wrapping);
crate::scrub_wrap::update(ui, &resp, value, before, range.clone(), speed, wrapping);
}
let (lo, hi) = (*range.start(), *range.end());
// `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts.
if *value != before && lo <= hi {
*value = value.clamp(lo, hi);
}
resp.flags.set(egui::response::Flags::CHANGED, *value != before);
resp
@@ -2274,6 +2288,29 @@ mod tests {
assert_eq!(*h.state(), (25.0, 3));
}
/// #5717: a value past the range shows as it is without reporting a change; an edit is clamped.
#[test]
fn value_field_keeps_a_shown_value_past_its_range_and_clamps_edits() {
use egui_kittest::{Harness, kittest::Queryable};
let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state(
|ui, (v, changes): &mut (f32, u32)| {
if super::value_field(ui, v, 0.1..=1296.0, "pt", 90.0).changed() {
*changes += 1;
}
},
(2400.0, 0),
);
h.run_steps(3);
assert_eq!(*h.state(), (2400.0, 0), "showing it changes nothing");
h.get_by_role(egui::accesskit::Role::SpinButton).click();
h.run();
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("5000".into()));
h.key_press(egui::Key::Enter);
h.run();
assert_eq!(h.state().0, 1296.0, "a typed value is clamped");
}
#[test]
fn value_field_applies_typed_arithmetic() {
use egui::Key::{Enter, Tab};
+1
View File
@@ -58,6 +58,7 @@ curl -sfL -o assets/icons/<name>.svg https://raw.githubusercontent.com/lucide-ic
| Quick layer pick | `quick_pick.rs` | macOS: ⌘⌥⌃-click with any tool selects the topmost visible layer with pixels under the pointer (`layer.pickAt`) without switching tools; the drag and release are swallowed. Windows/Linux have no third modifier distinct from the ⌃⌥ brush resize, so the gesture is a no-op there (use the Move tool's Auto-Select). A failed pick is a status-bar error. |
| Layers rows | `panels.rs` | Double-click: on the name renames in place; on the Background makes it a normal layer; on an adjustment or fill thumbnail opens its Properties; on a Smart Object thumbnail opens its contents (Edit Contents); anywhere else on the row opens Layer Style. |
| Layer masks | `panels.rs` | Clicking the mask thumbnail targets the mask (corner-bracket frame; the tab reads "Layer, Layer Mask/8"). Brush, eraser (paints background colour), gradient, bucket and moving the selected pixels (⌘-drag, `select.float`; the hole takes the background colour) then send `"target": "mask"`. Adjustment and fill layers target their mask automatically. |
| Channels selection | `channels_panel.rs` | Load channel as selection in the footer follows the highlighted channel row. When the active layer mask is targeted for painting while the underlying channel view remains Composite, it loads that layer mask; otherwise it loads the selected composite, color, alpha or vector mask channel. |
| Path thumbnails | `vector_ui.rs` | Ctrl/Cmd-click the thumbnail of a Work Path, saved path or layer path to load it as a selection; Shift adds, Alt subtracts, Shift+Alt intersects. Clicking the row name only selects the path. |
| Levels / Curves | `tone.rs` | Histogram of the image *below* the adjustment. Curves: click to add a point, drag out to delete. Every change is a coalesced `layer.setAdjustment`, so one drag = one undo step and the canvas updates at full resolution on the GPU. |
| Shape Stroke Options | `shape_stroke_ui.rs`, `vector_ui.rs` | Direct editing: valid changes apply immediately, with one numeric drag per undo step in Properties. Escape/outside click closes the popup and retains changes; a child dropdown keeps the parent open. The options bar sets new-shape defaults; Properties edits the selected shape. |
+3 -1
View File
@@ -1,6 +1,6 @@
# UI parity: tools, handles, modifiers and feel
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026
How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the
handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,
@@ -96,6 +96,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| ⌥-drag duplicates, ⇧ constrains to 45° | done | `move_mods.rs` |
| Auto-Select with hover outline, box-select layers, double-click fit | missing | TOOL-214-4 |
| Auto-Select bounding box and snapping follow the picked layer | partial | follow the previous layer (#2666) |
| Several layers selected (⇧-click adds, box-select): Show Transform Controls frames them all, with every selected shape's outline | partial: the shared frame has no handles, since Free Transform works on one layer (`canvas.rs` `transform_controls_layers`, `several_selected_layers_share_one_frame_without_handles`; `move_auto_select_tests.rs`) | |
| ⌘-drag temporary Move shows the box and snaps | partial | #2681 |
| ⌘-right-click layer list under the pointer | done | `layer_pick_ui.rs` |
| Double-click type to edit it (caret at the pointer, Type tool) | done | #1132, `type_tool::edit_at` |
@@ -254,3 +255,4 @@ Paragraph; the rest open as in-app floating windows.
| 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) |
| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit |
| 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) |
| 2026-10-14 | minor | Move › Show Transform Controls frames every selected layer and outlines the selected shapes |