Merge main into feat/smudge-tool-mode

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
ljkxandClaude Fable 5.2 committed 2026-11-11 01:33:13 +01:00
commit cd81562c4e
55 files changed
+2795 -134

No files matched your search

+2 -1
View File
@@ -153,7 +153,7 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
.with_app_id(APP_ID)
.with_title("PhotoCraft")
.with_inner_size([1440.0, 900.0])
.with_min_inner_size([760.0, 480.0])
.with_min_inner_size(photocraft_ui_egui::MIN_WINDOW_SIZE)
.with_drag_and_drop(true)
.with_decorations(!custom_titlebar)
.with_fullsize_content_view(true)
@@ -682,6 +682,7 @@ fn main() -> eframe::Result {
tablet::spawn_x11(&app.stylus.feed, display);
app.services.right_button_down = tablet::right_button_service();
app.services.pen_end = tablet::pen_end_service();
app.services.pen_screen_px = tablet::pen_screen_service();
// Paths on the command line (Linux/Windows file associations, `photocraft a.psd`).
app.open_paths(&files);
if !unreadable_paths.is_empty() {
+11
View File
@@ -92,6 +92,17 @@ pub fn right_button_service() -> Option<photocraft_ui_egui::RightButtonDownFn> {
None
}
/// Where the pen is on the screen (Windows), for the title bar's pen moves (#7967).
#[cfg(target_os = "windows")]
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
Some(Box::new(|| photocraft_tablet::windows::pen_screen_px().map(|(x, y)| [x, y])))
}
#[cfg(not(target_os = "windows"))]
pub fn pen_screen_service() -> Option<photocraft_ui_egui::PenScreenFn> {
None
}
/// Which end of the pen is in use (Windows): flipping the pen to its eraser end selects the
/// Eraser (#2285). Elsewhere the end arrives with the samples in the stylus feed.
#[cfg(target_os = "windows")]
+2
View File
@@ -138,6 +138,8 @@ pub mod redeye_cmds;
pub mod render_cmds;
pub mod retouch_cmds;
pub mod sample_cmds;
#[cfg(test)]
mod sample_zoom_box_tests;
pub mod sampler_cmds;
pub mod select_extra_cmds;
pub mod selection_cmds;
+8 -2
View File
@@ -336,11 +336,17 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS
}
/// Pencil Auto Erase: a stroke that starts on a pixel of the foreground colour paints the
/// background colour instead (Photoshop).
/// background colour instead (Photoshop). The match is exact (#11966): the foreground as the
/// layer would store it (its mode and depth) against the pixel, its alpha aside, so one level
/// off paints the foreground.
fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&StrokePoint>, fg: [f32; 4], bg: [f32; 4]) {
let Some(p0) = start else { return };
let c = surf.rgba(p0.x.floor() as i32, p0.y.floor() as i32);
if c[3] > 0.0 && (0..3).all(|i| (c[i] - fg[i]).abs() < 1.5 / 255.0) {
let mut probe = Surface::new(surf.format());
probe.write_pixel(0, 0, &photocraft_raster::from_rgba(&surf.format(), [fg[0], fg[1], fg[2], 1.0]));
let stored = probe.rgba(0, 0);
// Far below one 8-bit level: only the float noise of the conversion.
if c[3] > 0.0 && (0..3).all(|i| (c[i] - stored[i]).abs() < 1e-5) {
brush.color = bg;
}
}
+6 -1
View File
@@ -287,7 +287,7 @@ pub fn apply_set(layer: &Layer, f: &Fill, canvas: Rect, p: &Value, fg: [f32; 4],
/// The Gradient Fill layer `gradient.fill.create` adds to `doc` for `p` (also the canvas's live
/// preview of a Gradient tool drag): laid out on the canvas, so the handles land exactly where
/// the drag was, and masked by the selection (Photoshop keeps the selection, as a mask).
/// the drag was, and masked by the selection (`create` then drops the selection, #12196).
pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result<Layer> {
const CMD: &str = CREATE;
let from = point(CMD, p, "from")?.ok_or_else(|| bad(CMD, "missing `from` [x, y]"))?;
@@ -322,6 +322,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
new_layer(s, &d.doc, p)?
};
let id = s.edit("New Gradient Fill Layer", |doc, active| {
doc.selection = None;
let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable);
*active = Some(id);
Ok(id)
@@ -596,3 +597,7 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "gradient_fill_selection_tests.rs"]
mod gradient_fill_selection_tests;
@@ -0,0 +1,86 @@
//! #12196: a live Gradient drag (`gradient.fill.create`) masks the new fill layer with the
//! selection and drops the selection in the same History step, while `new_layer` (used by the
//! canvas preview during the drag) masks the preview without mutating the document's selection.
use photocraft_geom::Rect;
use serde_json::json;
use super::{CREATE, LayerId, new_layer};
use crate::Session;
/// Creates an 800x600 white-background test session at the given bit depth.
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "depth": depth, "background": "white"})).unwrap();
s
}
/// Verifies that `new_layer` previews a selection-masked gradient without dropping the selection,
/// `gradient.fill.create` masks the new layer and drops the selection, and `edit.undo` restores it.
#[test]
fn create_masks_with_the_selection_drops_it_and_undo_restores_it() {
let bounds = Rect::new(200, 200, 600, 400);
let drag = json!({"from": [200, 200], "to": [600, 400], "stops": [[0, "#000000"], [1, "#000000"]]});
for depth in [8, 16, 32] {
let mut s = session(depth);
s.execute("select.rect", json!({"x": 200, "y": 200, "width": 400, "height": 200})).unwrap();
// The live drag preview calls `new_layer`: it is masked by the selection, renders only
// inside the selection, and leaves the document's selection intact while dragging.
let preview = new_layer(&s, &s.active().unwrap().doc, &drag).unwrap();
let preview_mask = preview.mask.as_ref().expect("preview is masked by the selection");
assert_eq!(preview_mask.surface.content_bounds(), bounds, "{depth}-bit preview mask bounds");
let mut preview_doc = (*s.active().unwrap().doc).clone();
preview_doc.layers.push(preview);
let flat = photocraft_compose::flatten(&preview_doc);
assert_eq!(flat.px[300 * 800 + 300], [0.0, 0.0, 0.0, 1.0], "{depth}-bit preview inside selection");
assert_eq!(flat.px[100 * 800 + 100], [1.0, 1.0, 1.0, 1.0], "{depth}-bit preview outside selection");
assert!(s.active().unwrap().doc.selection.is_some(), "{depth}-bit preview keeps selection");
let r = s.execute(CREATE, drag.clone()).unwrap();
let id = LayerId(r["layer"].as_u64().unwrap());
let d = s.active().unwrap();
let l = d.doc.layer(id).unwrap();
assert_eq!(l.name, "Gradient Fill 1", "{depth}-bit");
let mask = l.mask.as_ref().expect("selection becomes the fill layer's mask");
assert_eq!(mask.surface.content_bounds(), bounds, "{depth}-bit mask bounds");
assert_eq!(mask.value(300, 300), 1.0, "{depth}-bit inside selection");
assert_eq!(mask.value(100, 100), 0.0, "{depth}-bit outside selection");
assert!(d.doc.selection.is_none(), "{depth}-bit selection is dropped");
// One undo removes the layer and brings the selection back.
s.execute("edit.undo", json!({})).unwrap();
let d = s.active().unwrap();
assert!(d.doc.layer(id).is_none(), "{depth}-bit undo removes the layer");
let sel = d.doc.selection.as_ref().expect("undo brings the selection back");
assert_eq!(sel.content_bounds(), bounds, "{depth}-bit restored selection bounds");
// A soft/feathered selection's fractional coverage goes into the mask and survives undo.
s.execute("select.rect", json!({"x": 200, "y": 200, "width": 400, "height": 200, "feather": 5.0})).unwrap();
let canvas = s.active().unwrap().doc.bounds();
let before_sel = s.active().unwrap().doc.selection.as_ref().unwrap().read_region(canvas);
assert!(before_sel.iter().any(|&v| v > 0.0 && v < 1.0), "{depth}-bit has fractional coverage");
let r = s.execute(CREATE, drag.clone()).unwrap();
let feathered_id = LayerId(r["layer"].as_u64().unwrap());
let feathered_mask = s.active().unwrap().doc.layer(feathered_id).unwrap().mask.as_ref().unwrap();
assert_eq!(feathered_mask.surface.read_region(canvas), before_sel, "{depth}-bit mask carries fractional coverage");
assert!(s.active().unwrap().doc.selection.is_none(), "{depth}-bit feathered selection dropped");
s.execute("edit.undo", json!({})).unwrap();
let after_sel = s.active().unwrap().doc.selection.as_ref().unwrap().read_region(canvas);
assert_eq!(after_sel, before_sel, "{depth}-bit undo restores fractional selection coverage");
}
}
/// Verifies that `gradient.fill.create` without an active selection leaves the new layer unmasked.
#[test]
fn create_without_a_selection_adds_an_unmasked_fill_layer() {
for depth in [8, 16, 32] {
let mut s = session(depth);
let r = s.execute(CREATE, json!({"from": [100, 100], "to": [700, 500]})).unwrap();
let id = LayerId(r["layer"].as_u64().unwrap());
let d = s.active().unwrap();
let l = d.doc.layer(id).unwrap();
assert!(l.mask.is_none(), "{depth}-bit without selection has no mask");
assert!(d.doc.selection.is_none(), "{depth}-bit still has no selection");
}
}
+27 -8
View File
@@ -16,6 +16,9 @@ use crate::{EngineError, Result, Session};
const CMD: &str = "paint.redEye";
const MISS: &str = "no red-eye pixels near the click";
/// The reference's alert for a Red Eye click in a CMYK, Grayscale or Indexed Color document (#12575).
pub const MODE_REFUSAL: &str = "Could not use the red eye removal tool because it only works in full color modes.";
fn bad(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
}
@@ -226,7 +229,17 @@ fn enabled(s: &Session) -> std::result::Result<(), String> {
Ok(())
}
/// By the document's mode, not its pixel format: Indexed Color pixels are stored as RGB. Bitmap,
/// Duotone and Multichannel were not measured and keep running.
fn mode_refusal(s: &Session) -> Result<()> {
match s.active().map(|d| d.doc.mode) {
Some(ColorMode::Cmyk | ColorMode::Grayscale | ColorMode::Indexed) => Err(EngineError::Other(MODE_REFUSAL.into())),
_ => Ok(()),
}
}
fn red_eye(s: &mut Session, p: &Value) -> Result<Value> {
mode_refusal(s)?;
let pts = clicks(p)?;
let pupil_raw = num(p, "pupilSize", 50.0)?;
let darken = num(p, "darken", 50.0)?;
@@ -407,7 +420,7 @@ mod tests {
}
#[test]
fn cmyk_document_keeps_untouched_pixels_bit_exact() {
fn cmyk_document_is_refused_and_keeps_its_pixels_bit_exact() {
let mut s = session(64, 64, 8, "cmyk");
assert_eq!(s.active().unwrap().doc.pixel_format().mode, ColorMode::Cmyk);
// Rich black (all four inks) around the eye: a naive RGBA round trip regenerates K.
@@ -438,25 +451,31 @@ mod tests {
let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap();
surf.read_region(Rect::new(x, y, x + 1, y + 1))
};
let probes = [(32, 18), (2, 2), (50, 40)];
let probes = [(32, 26), (32, 18), (2, 2), (50, 40)];
let before: Vec<Vec<f32>> = probes.iter().map(|&(x, y)| raw(&s, x, y)).collect();
let r = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap();
assert!(r["pixels"].as_u64().unwrap() > 0, "{r}");
let past = s.active().unwrap().history.past_len();
let err = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap_err().to_string();
assert_eq!(err, MODE_REFUSAL);
for (&(x, y), b) in probes.iter().zip(&before) {
assert_eq!(&raw(&s, x, y), b, "untouched CMYK pixel ({x},{y}) inside the window changed");
assert_eq!(&raw(&s, x, y), b, "CMYK pixel ({x},{y}) changed");
}
assert!(rgba(&s, 32, 26)[0] < 0.7, "pupil corrected");
assert_eq!(s.active().unwrap().history.past_len(), past, "no history state");
}
#[test]
fn gray_document_misses() {
fn gray_document_is_refused() {
let mut s = session(24, 24, 16, "gray");
paint_layer(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]);
assert_eq!(s.active().unwrap().doc.pixel_format().mode, ColorMode::Grayscale);
assert!(s.execute("paint.redEye", json!({"x": 12, "y": 12})).is_err());
let err = s.execute("paint.redEye", json!({"x": 12, "y": 12})).unwrap_err().to_string();
assert_eq!(err, MODE_REFUSAL);
}
}
#[cfg(test)]
#[path = "redeye_history_state_tests.rs"]
mod redeye_history_state_tests;
#[cfg(test)]
#[path = "redeye_color_mode_tests.rs"]
mod redeye_color_mode_tests;
@@ -0,0 +1,93 @@
//! #12575: the Red Eye tool refuses CMYK, Grayscale and Indexed Color documents with the
//! reference's alert text and leaves the document and History unchanged. RGB (8, 16, 32 bit) and
//! Lab still correct the pupil; Bitmap, Duotone and Multichannel were not measured and keep
//! today's behaviour (no refusal).
use serde_json::{Value, json};
use super::*;
fn new_doc(mode: &str, depth: u64) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 64, "mode": mode, "depth": depth})).unwrap();
s
}
/// A red pupil on its own layer.
fn red_pupil(s: &mut Session) {
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("paint.pencil", json!({"points": [[32, 32]], "size": 14, "hardness": 100, "color": "#f21818"})).unwrap();
}
fn assert_refused(s: &mut Session, params: Value, case: &str) {
let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len());
let err = s.execute("paint.redEye", params).unwrap_err().to_string();
assert_eq!(err, MODE_REFUSAL, "{case}");
assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "{case}: document unchanged");
assert_eq!(s.active().unwrap().history.past_len(), steps, "{case}: no history state");
}
#[test]
fn the_refusal_is_the_reference_alert_text() {
assert_eq!(MODE_REFUSAL, "Could not use the red eye removal tool because it only works in full color modes.");
}
#[test]
fn cmyk_and_grayscale_documents_are_refused() {
for (mode, depths) in [("cmyk", &[8u64, 16][..]), ("gray", &[8, 16, 32][..])] {
for &depth in depths {
let mut s = new_doc(mode, depth);
red_pupil(&mut s);
assert_refused(&mut s, json!({"x": 32, "y": 32}), &format!("{mode} {depth} bit"));
}
}
}
#[test]
fn indexed_color_documents_are_refused() {
let mut s = new_doc("rgb", 8);
red_pupil(&mut s);
s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
assert_eq!(s.active().unwrap().doc.mode, ColorMode::Indexed);
assert_refused(&mut s, json!({"x": 32, "y": 32}), "indexed");
assert_refused(&mut s, json!({"points": [[32, 32], [10, 10]]}), "indexed, a points batch");
}
/// Converting to Indexed Color flattens the document, so a script's layer id is gone: the mode
/// is refused before the layer is looked up.
#[test]
fn the_refusal_comes_before_the_layer_lookup() {
let mut s = new_doc("rgb", 8);
red_pupil(&mut s);
let id = s.active().unwrap().active_layer.unwrap();
s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
assert_refused(&mut s, json!({"x": 32, "y": 32, "layer": id.0}), "a flattened layer id");
}
#[test]
fn rgb_and_lab_documents_still_correct_the_pupil() {
for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("lab", 8), ("lab", 16)] {
let mut s = new_doc(mode, depth);
red_pupil(&mut s);
let steps = s.active().unwrap().history.past_len();
let r = s.execute("paint.redEye", json!({"x": 32, "y": 32})).unwrap_or_else(|e| panic!("{mode} {depth}: {e}"));
assert!(r["pixels"].as_u64().unwrap() > 0, "{mode} {depth}: {r}");
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{mode} {depth}");
}
}
#[test]
fn unmeasured_modes_are_not_refused() {
let mut multi = new_doc("rgb", 8);
red_pupil(&mut multi);
multi.execute("image.mode.multichannel", json!({})).unwrap();
let mut bitmap = new_doc("gray", 8);
bitmap.execute("image.mode.bitmap", json!({})).unwrap();
let mut duotone = new_doc("gray", 8);
duotone.execute("image.mode.duotone", json!({"type": "monotone"})).unwrap();
for (mut s, mode) in [(multi, ColorMode::Multichannel), (bitmap, ColorMode::Bitmap), (duotone, ColorMode::Duotone)] {
assert_eq!(s.active().unwrap().doc.mode, mode);
let r = s.execute("paint.redEye", json!({"x": 32, "y": 32}));
assert!(r.as_ref().err().is_none_or(|e| e.to_string() != MODE_REFUSAL), "{mode:?}: {r:?}");
}
}
+50 -3
View File
@@ -76,6 +76,32 @@ pub fn sample_rect(x: f64, y: f64, size: u32, canvas: Rect) -> Option<Rect> {
Some(square.intersect(&canvas))
}
/// The widest box, in document pixels, a zoomed-out average reads (#11751): at 1 % zoom a
/// 101 by 101 Average would otherwise composite a 10 200-pixel square on every pointer move.
pub const MAX_ZOOM_BOX: u32 = 4096;
/// [`sample_rect`] for the Eyedropper at view `zoom` (screen pixels per document pixel, 1.0 is
/// 100 %), as in Photoshop (#11751). Above 100 % it is the centred `size` × `size` square. At 100 %
/// and below an N by N Average covers (N+1) × (N+1) *screen* pixels: at 100 % the document pixels
/// x−N/2 to x+N/2+1 (N/2 rounded down), at 50 % 3 by 3 covers 8 × 8 document pixels. Point
/// Sample is one pixel at every zoom; no zoom is today's centred square.
pub fn sample_rect_at(x: f64, y: f64, size: u32, zoom: Option<f64>, canvas: Rect) -> Option<Rect> {
let centred = sample_rect(x, y, size, canvas)?;
let Some(zoom) = zoom.filter(|z| z.is_finite() && *z > 0.0 && *z <= 1.0) else { return Some(centred) };
if size == 1 {
return Some(centred);
}
let (px, py) = (x.floor() as i32, y.floor() as i32);
// (N+1) screen pixels in document pixels, at least N+1.
let side = (f64::from(size + 1) / zoom).round().clamp(f64::from(size + 1), f64::from(MAX_ZOOM_BOX)) as i32;
// The pixel sits just left of the box's middle: x−N/2 … x+N/2+1 at 100 %.
let before = (side + 1) / 2 - 1;
let x0 = px.saturating_sub(before);
let y0 = py.saturating_sub(before);
let square = Rect::new(x0, y0, x0.saturating_add(side), y0.saturating_add(side));
Some(square.intersect(&canvas))
}
/// Round `v` to what a channel of `depth` can store (32 bit keeps the float).
fn quantize(v: f32, depth: SampleType) -> f32 {
let mut b = [0u8; 4];
@@ -166,7 +192,13 @@ fn sampled_document(doc: &Document, active: Option<LayerId>, which: SampleLayers
/// the canvas. Transparent black off the canvas, over transparency, or when `which` needs an
/// active layer and there is none.
pub fn sample_color(doc: &Document, active: Option<LayerId>, x: f64, y: f64, size: u32, which: SampleLayers) -> [f32; 4] {
let Some(rect) = sample_rect(x, y, size, doc.bounds()) else { return [0.0; 4] };
sample_color_at(doc, active, x, y, size, None, which)
}
/// [`sample_color`] over the box the Eyedropper reads at view `zoom` ([`sample_rect_at`]); `None`
/// is the centred square, as the Color Sampler always uses (#11751).
pub fn sample_color_at(doc: &Document, active: Option<LayerId>, x: f64, y: f64, size: u32, zoom: Option<f64>, which: SampleLayers) -> [f32; 4] {
let Some(rect) = sample_rect_at(x, y, size, zoom, doc.bounds()) else { return [0.0; 4] };
let Some(src) = sampled_document(doc, active, which) else { return [0.0; 4] };
let buf = photocraft_compose::render(&src, rect);
if size == 1 {
@@ -203,6 +235,20 @@ pub fn size_param(cmd: &str, p: &Value) -> Result<u32> {
}
}
/// The optional `zoom` param (#11751): the view zoom the Eyedropper samples at, screen pixels per
/// document pixel (1.0 = 100 %). Missing or null: the centred box. Anything but a finite positive
/// number is an error.
pub fn zoom_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
match p.get("zoom") {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_f64()
.filter(|z| z.is_finite() && *z > 0.0)
.map(Some)
.ok_or_else(|| bad(cmd, format!("`zoom` = {v} must be a positive number (screen pixels per document pixel, 1 = 100 %)"))),
}
}
/// The `sampleLayer` param (default `all`).
pub fn layers_param(cmd: &str, p: &Value) -> Result<SampleLayers> {
match p.get("sampleLayer") {
@@ -225,15 +271,16 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Sample Color",
menu: &[],
shortcut: None,
params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all"} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it, clipped to the canvas; transparent off the canvas)"##,
params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all","zoom":f64? (the view zoom, 1 = 100 %: at 100 % and below an N by N Average covers (N+1)×(N+1) screen pixels, as in Photoshop; missing: the centred square)} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it (without `zoom`; with it, the zoom-dependent box above), clipped to the canvas; transparent off the canvas)"##,
enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
run: |s: &mut Session, p: &Value| {
const CMD: &str = "document.sampleColor";
let (x, y) = (coord(CMD, p, "x")?, coord(CMD, p, "y")?);
let size = size_param(CMD, p)?;
let zoom = zoom_param(CMD, p)?;
let which = layers_param(CMD, p)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
Ok(json!(sample_color(&d.doc, d.active_layer, x, y, size, which)))
Ok(json!(sample_color_at(&d.doc, d.active_layer, x, y, size, zoom, which)))
},
journal: false,
}]
@@ -0,0 +1,162 @@
//! #11751: the Eyedropper's N by N Average box depends on the view zoom, as in Photoshop. Above
//! 100 % it is the centred N × N square of document pixels; at 100 % and below it covers
//! (N+1) × (N+1) screen pixels (at 100 % the document pixels x−N/2 … x+N/2+1). Without a zoom
//! `document.sampleColor` keeps the centred square.
use serde_json::{Value, json};
use crate::Session;
/// The issue's test document: 800 × 600 RGB/8 white; on a pixel layer a red (220,30,30) block at
/// 100,100–300,250, 2 px black / 2 px white stripes at 350,100–450,200 (black at x 350–351,
/// 354–355, …) and a grey ramp of ten 40 px blocks from x 100, values 100, 105, …, 145, at
/// y 350–450.
fn test_document() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap();
let fill = |s: &mut Session, x: i32, y: i32, w: i32, h: i32, grey_or_hex: String| {
s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": grey_or_hex})).unwrap();
};
fill(&mut s, 100, 100, 200, 150, "#dc1e1e".into());
fill(&mut s, 350, 100, 100, 100, "#ffffff".into());
for x in (350..450).step_by(4) {
fill(&mut s, x, 100, 2, 100, "#000000".into());
}
for i in 0..10 {
let v = 100 + 5 * i;
fill(&mut s, 100 + 40 * i, 350, 40, 100, format!("#{v:02x}{v:02x}{v:02x}"));
}
s.execute("select.deselect", json!({})).unwrap();
s
}
/// A black 400 × 400 document with one white pixel at 200,200 (the issue's probe).
fn probe() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 400, "background": "white"})).unwrap();
s.execute("select.all", json!({})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap();
s.execute("select.rect", json!({"x": 200, "y": 200, "width": 1, "height": 1})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#ffffff"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s
}
/// The 8-bit RGB read at document pixel (x, y).
fn read(s: &mut Session, x: i32, y: i32, size: u32, zoom: Option<f64>) -> [i64; 3] {
let mut p = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": size});
if let Some(z) = zoom {
p["zoom"] = json!(z);
}
let v = s.execute("document.sampleColor", p).unwrap();
let c = |i: usize| (v[i].as_f64().unwrap() * 255.0).round() as i64;
[c(0), c(1), c(2)]
}
fn grey(v: i64) -> [i64; 3] {
[v, v, v]
}
#[test]
fn at_100_percent_the_test_document_reads_the_measured_table() {
// Sample Size: stripes x 351, stripes x 352 (y 150), grey x 139 (y 400), red left edge x 100 (y 150).
// The reference application's table, except grey x 139 up to 51 by 51: that box is exactly
// half 100 and half 105, a mean of 102.5, which the reference reads 102 and PhotoCraft's shared
// `average` rounds to 103 (half up, as every Sample Size average does today). The box is right
// (101 by 101, whose mean is no tie, reads 122 in both).
const TIE: i64 = 103;
let measured: [(u32, [[i64; 3]; 4]); 6] = [
(3, [grey(128), grey(128), grey(TIE), [229, 86, 86]]),
(5, [grey(128), grey(85), grey(TIE), [232, 105, 105]]),
(11, [grey(170), grey(149), grey(TIE), [235, 124, 124]]),
(31, [grey(175), grey(175), grey(TIE), [236, 135, 135]]),
(51, [grey(186), grey(181), grey(TIE), [237, 138, 138]]),
(101, [grey(189), grey(186), grey(122), [237, 140, 140]]),
];
let mut s = test_document();
for (size, want) in measured {
let got = [
read(&mut s, 351, 150, size, Some(1.0)),
read(&mut s, 352, 150, size, Some(1.0)),
read(&mut s, 139, 400, size, Some(1.0)),
read(&mut s, 100, 150, size, Some(1.0)),
];
assert_eq!(got, want, "{size} by {size} at 100 %");
}
}
#[test]
fn without_a_zoom_the_box_stays_the_centred_square() {
// Today's values from the issue: 3 by 3 at stripes x 351 reads 85, red edge 232,105,105.
let mut s = test_document();
assert_eq!(read(&mut s, 351, 150, 3, None), grey(85));
assert_eq!(read(&mut s, 352, 150, 3, None), grey(170));
assert_eq!(read(&mut s, 100, 150, 3, None), [232, 105, 105]);
assert_eq!(read(&mut s, 351, 150, 11, None), grey(162));
}
#[test]
fn the_probe_at_100_percent_reads_16_for_3_by_3_and_7_for_5_by_5() {
let mut s = probe();
// 3 by 3 is 4 × 4 from x−1 to x+2: clicks at 198–201 (both axes) catch the white pixel.
for x in 197..=202 {
let want = if (198..=201).contains(&x) { 16 } else { 0 };
assert_eq!(read(&mut s, x, 200, 3, Some(1.0)), grey(want), "3 by 3, x {x}");
assert_eq!(read(&mut s, 200, x, 3, Some(1.0)), grey(want), "3 by 3, y {x}");
}
// 5 by 5 is 6 × 6 from x−2 to x+3.
for x in 196..=203 {
let want = if (197..=202).contains(&x) { 7 } else { 0 };
assert_eq!(read(&mut s, x, 200, 5, Some(1.0)), grey(want), "5 by 5, x {x}");
}
}
#[test]
fn at_50_percent_3_by_3_covers_8_by_8_document_pixels() {
let mut s = probe();
assert_eq!(read(&mut s, 200, 200, 3, Some(0.5)), grey(4), "255 / 64");
}
#[test]
fn above_100_percent_it_is_the_centred_square() {
let mut s = probe();
for zoom in [2.0, 3.125, 128.0] {
for x in 198..=202 {
let want = if (199..=201).contains(&x) { 28 } else { 0 };
assert_eq!(read(&mut s, x, 200, 3, Some(zoom)), grey(want), "{zoom}: x {x}");
}
}
}
#[test]
fn point_sample_is_one_pixel_at_every_zoom() {
let mut s = probe();
for zoom in [None, Some(0.05), Some(0.5), Some(1.0), Some(4.0)] {
assert_eq!(read(&mut s, 200, 200, 1, zoom), grey(255), "{zoom:?}");
assert_eq!(read(&mut s, 201, 200, 1, zoom), grey(0), "{zoom:?}");
}
}
#[test]
fn a_far_zoomed_out_box_is_capped_and_clipped_not_a_panic() {
let mut s = probe();
// At 1 % a 101 by 101 box would be 10 200 px wide: capped, and clipped to the canvas.
let v = read(&mut s, 0, 0, 101, Some(0.01));
assert!(v.iter().all(|c| (0..=1).contains(c)), "one white pixel in a canvas-wide average: {v:?}");
let rect = super::sample_cmds::sample_rect_at(200.5, 200.5, 101, Some(0.01), photocraft_geom::Rect::new(0, 0, 100_000, 100_000)).unwrap();
assert!(rect.width() <= super::sample_cmds::MAX_ZOOM_BOX && rect.height() <= super::sample_cmds::MAX_ZOOM_BOX, "{rect:?}");
}
#[test]
fn a_bad_zoom_is_an_error_not_a_panic() {
let mut s = probe();
for bad in [json!(0), json!(-1.0), json!("fast"), json!([1]), json!(-1e300)] {
let r = s.execute("document.sampleColor", json!({"x": 10, "y": 10, "size": 3, "zoom": bad}));
assert!(r.is_err(), "zoom {bad}: {r:?}");
}
// A huge zoom is above 100 %: the centred square.
let v: Value = s.execute("document.sampleColor", json!({"x": 200.5, "y": 200.5, "size": 3, "zoom": 1e300})).unwrap();
assert!((v[0].as_f64().unwrap() * 255.0 - 28.3).abs() < 1.0, "{v}");
}
+8 -2
View File
@@ -953,7 +953,8 @@ pub(crate) fn new_text_layer(s: &Session, p: &Value, cmd: &str) -> Result<TextLa
Ok(t)
}
/// The name of the history state a new type layer makes: what `type.create` records, and what the
/// The name of the history state a new horizontal type layer makes: what `type.create` records
/// (vertical text is "New Vertical Type Layer", #12058), and what the
/// Type tool's commit keeps in the modes [`commits_as_selection`] names (#12041).
pub const NEW_TYPE_LAYER_LABEL: &str = "New Type Layer";
@@ -1020,7 +1021,9 @@ pub fn specs() -> Vec<CommandSpec> {
let mut t = new_text_layer(s, p, "type.create")?;
let given = p.get("name").and_then(Value::as_str).map(str::to_string);
let name = given.clone().unwrap_or_else(|| layer_name(&t.text));
let id = s.edit(NEW_TYPE_LAYER_LABEL, |doc, active| {
// The reference application names new vertical text after its tool (#12058).
let label = if t.orientation == Orientation::Vertical { "New Vertical Type Layer" } else { NEW_TYPE_LAYER_LABEL };
let id = s.edit(label, |doc, active| {
refresh(doc, &mut t);
let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::AutoEditable);
*active = Some(id);
@@ -1306,3 +1309,6 @@ fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result<Va
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "type_vertical_history_name_tests.rs"]
mod vertical_history_name_tests;
+33 -37
View File
@@ -16,6 +16,8 @@ use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
const CMD: &str = "type.createSelection";
/// What an allocation failure names: the buffers are no longer bounded by the canvas.
const PURPOSE: &str = "the Type Mask selection";
fn bad(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
@@ -39,38 +41,27 @@ fn antialias(p: &Value) -> Result<Option<AntiAlias>> {
})
}
/// Glyph coverage of `t` (0..=1 per pixel) over its rendered bounds inside the canvas. The text
/// colour's own alpha doesn't thin the selection: every run renders opaque.
fn coverage(doc: &Document, t: &TextLayer) -> (Vec<f32>, Rect) {
/// Glyph coverage of `t` (0..=1 per pixel) over its rendered bounds, past the canvas edge too: the
/// reference application keeps a Type Mask's off-canvas part (#12074). The text colour's own alpha
/// doesn't thin the selection: every run renders opaque.
fn coverage(doc: &Document, t: &TextLayer) -> Result<(Vec<f32>, Rect)> {
let mut t = t.clone();
for r in &mut t.runs {
r.style.color.alpha = 1.0;
}
let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());
let surface = eng.render(&t, doc.resolution_dpi, doc.pixel_format()).1.surface;
let area = surface.content_bounds().intersect(&doc.bounds());
let area = surface.content_bounds();
if area.is_empty() {
return (Vec::new(), Rect::EMPTY);
return Ok((Vec::new(), Rect::EMPTY));
}
let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize];
// No longer bounded by the canvas: a very large text must fail as an error, not abort.
let len = (area.width() as usize).checked_mul(area.height() as usize).ok_or_else(|| crate::allocation::error(PURPOSE, "requested size overflowed"))?;
let mut px = crate::allocation::filled(len, [0.0f32; 4], PURPOSE)?;
surface.read_rgba_into(area, &mut px);
(px.iter().map(|p| p[3]).collect(), area)
}
/// Coverage of `area`'s mask spread over `to` (which contains `area`), zero elsewhere.
fn widen(m: &[f32], area: Rect, to: Rect) -> Vec<f32> {
if area == to {
return m.to_vec();
}
let (w, aw) = (to.width() as usize, area.width() as usize);
let mut out = vec![0.0; w * to.height() as usize];
for (y, row) in m.chunks_exact(aw.max(1)).enumerate() {
let start = (area.y0 - to.y0) as usize * w + y * w + (area.x0 - to.x0) as usize;
if let Some(dst) = out.get_mut(start..start + aw) {
dst.copy_from_slice(row);
}
}
out
let mut alpha = crate::allocation::capacity(len, PURPOSE)?;
alpha.extend(px.iter().map(|p| p[3]));
Ok((alpha, area))
}
fn create_selection(s: &mut Session, p: &Value) -> Result<Value> {
@@ -101,21 +92,22 @@ fn create_selection(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(aa) = aa {
t.antialias = aa;
}
let (mask, text_area) = coverage(&doc, &t);
let (mask, text_area) = coverage(&doc, &t)?;
// `combine_band` builds the new selection over the text's band where running out of memory
// aborts, and the band is no longer bounded by the canvas: check first that it fits, so a text
// too big for it is an error that changes nothing. Per pixel that is the new 8-bit grey tiles.
// With an unusual earlier selection (not 8-bit grey) that the mode reads, it keeps its format
// through more: the combined grey tiles and their float copy (1 + 4), the copy widened to every
// channel and its growth while collected (8 per channel), and its own new tiles.
let unusual = doc.selection.as_ref().filter(|o| mode != SelectionMode::Replace && o.format() != photocraft_color::PixelFormat::GRAY8);
let per_pixel = unusual.map_or(1, |old| 5 + 8 * old.channels() + old.format().bytes_per_pixel());
let bytes = (text_area.width() as usize).checked_mul(text_area.height() as usize).and_then(|n| n.checked_mul(per_pixel));
let bytes = bytes.ok_or_else(|| crate::allocation::error(PURPOSE, "requested size overflowed"))?;
drop(crate::allocation::capacity::<u8>(bytes, PURPOSE)?);
let selected = s.edit("Type Mask", |doc, active| {
let old = doc.selection.as_ref().map(|o| o.content_bounds().intersect(&doc.bounds())).unwrap_or(Rect::EMPTY);
// Replace and Intersect leave nothing outside the text; Add and Subtract keep the rest.
let area = match mode {
SelectionMode::Add | SelectionMode::Subtract if !old.is_empty() => {
if text_area.is_empty() {
old
} else {
old.union(&text_area)
}
}
_ => text_area,
};
doc.selection = if area.is_empty() { None } else { sel::combine(doc.selection.as_ref(), &widen(&mask, text_area, area), area, mode) };
// Replace and Intersect leave nothing outside the text; Add and Subtract keep the rest of
// the selection as it is, its part past the canvas too, without a buffer spanning both.
doc.selection = sel::combine_band(doc.selection.as_ref(), &mask, text_area, mode);
if let (true, Some(id)) = (remove, layer) {
let neighbours = crate::layer_multi_cmds::deletion_neighbours(doc, id);
doc.remove(id).ok_or(EngineError::NoLayer(id))?;
@@ -148,6 +140,10 @@ pub fn specs() -> Vec<CommandSpec> {
}]
}
#[cfg(test)]
#[path = "type_mask_off_canvas_tests.rs"]
mod off_canvas_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,233 @@
//! #12074: a Type Mask that runs past the canvas edge keeps the off-canvas part of its selection,
//! as the reference application does; masks fully on the canvas select exactly as before.
use photocraft_doc::{LayerContent, LayerId};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use serde_json::{Value, json};
use crate::Session;
fn session(width: u32, height: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": width, "height": height})).unwrap();
s
}
fn selection(s: &Session) -> Option<Surface> {
s.active().unwrap().doc.selection.clone()
}
fn bounds(s: &Session) -> Rect {
selection(s).map_or(Rect::EMPTY, |m| m.content_bounds())
}
fn mask(s: &mut Session, params: Value) -> Rect {
s.execute(super::CMD, params).unwrap();
bounds(s)
}
/// The rendered bounds of the same text as a type layer, which the canvas doesn't clip.
fn layer_bounds(width: u32, height: u32, params: Value) -> Rect {
let mut s = session(width, height);
let r = s.execute("type.create", params).unwrap();
let b: Vec<i32> = r["bounds"].as_array().unwrap().iter().map(|v| i32::try_from(v.as_i64().unwrap()).unwrap()).collect();
Rect::new(b[0], b[1], b[2], b[3])
}
#[test]
fn a_mask_started_on_the_pasteboard_selects_the_glyphs_left_of_the_canvas() {
let text = json!({"text": "MASK", "x": -129, "y": 300, "size": 48});
let mut s = session(600, 400);
let b = mask(&mut s, text.clone());
assert!(b.x0 < 0, "{b:?}");
assert!(b.x1 > 0, "the text reaches onto the canvas: {b:?}");
assert_eq!(b, layer_bounds(600, 400, text), "the whole outline, as the type layer renders it");
}
#[test]
fn a_vertical_mask_keeps_the_part_below_the_canvas() {
let text = json!({"text": "MASKMASKMASK", "x": 500, "y": 450, "size": 48, "orientation": "vertical"});
let mut s = session(800, 600);
let b = mask(&mut s, text.clone());
assert!(b.y0 < 600 && b.y1 > 600, "{b:?}");
assert_eq!(b, layer_bounds(800, 600, text));
// Moved up, the rows that were below the canvas are there: it equals the text masked there.
s.execute("select.transformSelection", json!({"dy": -300, "stepName": "Move Selection"})).unwrap();
let moved = selection(&s).unwrap();
let mut s = session(800, 600);
mask(&mut s, json!({"text": "MASKMASKMASK", "x": 500, "y": 150, "size": 48, "orientation": "vertical"}));
let there = selection(&s).unwrap();
let b = there.content_bounds();
assert_eq!(moved.content_bounds(), b);
assert_eq!(moved.read_region(b), there.read_region(b), "pixel for pixel");
}
/// Moving the selection onto the canvas shows the whole outline: it equals a mask of the same text
/// started there.
#[test]
fn moving_the_selection_onto_the_canvas_shows_the_whole_outline() {
let mut s = session(600, 400);
mask(&mut s, json!({"text": "MASK", "x": -129, "y": 300, "size": 48}));
s.execute("select.transformSelection", json!({"dx": 200, "stepName": "Move Selection"})).unwrap();
let moved = selection(&s).unwrap();
let mut s = session(600, 400);
mask(&mut s, json!({"text": "MASK", "x": 71, "y": 300, "size": 48}));
let there = selection(&s).unwrap();
assert_eq!(moved.content_bounds(), there.content_bounds());
let b = there.content_bounds();
assert!(b.x0 >= 0, "now fully on the canvas: {b:?}");
assert_eq!(moved.read_region(b), there.read_region(b), "pixel for pixel");
}
/// Adding a mask to, or subtracting it from, a selection that runs past the canvas keeps that part.
#[test]
fn add_and_subtract_keep_an_off_canvas_previous_selection() {
for operation in ["add", "subtract"] {
let mut s = session(600, 400);
// A rectangle dragged half off the left edge.
s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap();
s.execute("select.transformSelection", json!({"dx": -60, "stepName": "Move Selection"})).unwrap();
let first = bounds(&s);
assert_eq!(first, Rect::new(-50, 50, 50, 120), "precondition");
let off = Rect::new(-50, 50, 0, 120);
let before = selection(&s).unwrap().read_region(off);
mask(&mut s, json!({"text": "I", "x": 400, "y": 300, "size": 48, "operation": operation}));
assert_eq!(bounds(&s).x0, -50, "{operation}: the off-canvas part stays");
assert_eq!(selection(&s).unwrap().read_region(off), before, "{operation}: unchanged left of the canvas");
}
}
/// The glyph buffers are no longer bounded by the canvas, so running out of memory for either of
/// them is an error that changes nothing, not an abort.
#[test]
fn a_failed_coverage_allocation_is_an_error_that_changes_nothing() {
for skip in [0, 1] {
let mut s = session(600, 400);
s.execute("select.rect", json!({"x": 400, "y": 50, "width": 100, "height": 70})).unwrap();
let (before, steps) = (selection(&s), s.active().unwrap().history.entries().len());
crate::allocation::fail_after_for_test(skip);
let err = s.execute(super::CMD, json!({"text": "MASK", "x": -129, "y": 300, "size": 48})).unwrap_err().to_string();
assert!(err.contains("not enough memory for the Type Mask selection"), "allocation {skip}: {err}");
assert_eq!(selection(&s), before, "allocation {skip}");
assert_eq!(s.active().unwrap().history.entries().len(), steps, "allocation {skip}: no history step");
}
}
/// The expected selection at one pixel from the rectangle's and the glyphs' coverage.
type Combine = fn(f32, f32) -> f32;
/// A mask fully on the canvas selects what it did before: the glyphs' coverage, which is the alpha
/// of the same text rasterized, and new / add / subtract / intersect with a rectangle over part of
/// the text combine the two pixel by pixel.
#[test]
fn masks_on_the_canvas_select_as_before() {
let text = json!({"text": "MASK", "x": 100, "y": 200, "size": 48, "color": "#000000"});
let outline = layer_bounds(600, 400, text.clone());
assert!(outline.x0 >= 0 && outline.y0 >= 0 && outline.x1 <= 600 && outline.y1 <= 400, "{outline:?}");
let rect = Rect::new(outline.x0 + 20, outline.y0 - 10, outline.x0 + 80, outline.y1 + 10);
let area = outline.union(&rect);
let glyphs: Vec<f32> = {
let mut s = session(600, 400);
let id = s.execute("type.create", text.clone()).unwrap()["layer"].as_u64().unwrap();
s.execute("type.rasterize", json!({"layer": id})).unwrap();
match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content {
LayerContent::Raster(px) => px.read_region(area).as_chunks::<4>().0.iter().map(|p| p[3]).collect(),
other => panic!("{}", other.kind_name()),
}
};
assert!(glyphs.iter().any(|&a| a > 0.0 && a < 1.0), "anti-aliased edges are compared too");
let inside = |i: usize| {
let (x, y) = (area.x0 + (i % area.width() as usize) as i32, area.y0 + (i / area.width() as usize) as i32);
rect.contains(x, y)
};
let cases: [(&str, Combine); 4] = [("new", |_, g| g), ("add", |r, g| r.max(g)), ("subtract", |r, g| (r - g).max(0.0)), ("intersect", |r, g| r.min(g))];
for (operation, expected) in cases {
let mut s = session(600, 400);
s.execute("select.rect", json!({"x": rect.x0, "y": rect.y0, "width": rect.width(), "height": rect.height()})).unwrap();
let mut p = text.clone();
p["operation"] = json!(operation);
s.execute(super::CMD, p).unwrap();
let got = selection(&s).map_or_else(|| vec![0.0; glyphs.len()], |m| m.read_region(area));
for (i, (&v, &g)) in got.iter().zip(&glyphs).enumerate() {
let want = expected(if inside(i) { 1.0 } else { 0.0 }, g);
assert!((v - want).abs() <= 1.5 / 255.0, "{operation}: pixel {i} is {v}, expected {want}");
}
}
}
/// Text with no glyphs selects nothing: Add and Subtract leave an earlier selection as it is,
/// Replace and Intersect clear it, as before the combine step changed.
#[test]
fn a_mask_with_no_glyphs_keeps_or_clears_as_before() {
for operation in ["new", "add", "subtract", "intersect"] {
for earlier in [false, true] {
let mut s = session(600, 400);
if earlier {
s.execute("select.rect", json!({"x": 400, "y": 50, "width": 100, "height": 70})).unwrap();
}
let before = selection(&s);
let r = s.execute(super::CMD, json!({"text": " ", "x": 100, "y": 200, "size": 48, "operation": operation})).unwrap();
let kept = earlier && matches!(operation, "add" | "subtract");
assert_eq!(selection(&s), if kept { before } else { None }, "{operation}, earlier selection {earlier}");
assert_eq!(r["selected"], json!(kept), "{operation}, earlier selection {earlier}");
}
}
}
/// Replace and Intersect keep nothing of an earlier selection outside the text, its part past the
/// canvas included.
#[test]
fn replace_and_intersect_drop_an_off_canvas_previous_selection() {
// A new mask keeps nothing of the earlier rectangle (it ends at x 50, the text starts at 400);
// an intersection keeps only its on-canvas part under the text.
for (operation, x, left, right) in [("new", 400, 50, i32::MAX), ("intersect", 10, 0, 50)] {
let mut s = session(600, 400);
s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap();
s.execute("select.transformSelection", json!({"dx": -60, "stepName": "Move Selection"})).unwrap();
assert_eq!(bounds(&s), Rect::new(-50, 50, 50, 120), "precondition");
let b = mask(&mut s, json!({"text": "I", "x": x, "y": 110, "size": 48, "operation": operation}));
assert!(!b.is_empty() && b.x0 >= left && b.x1 <= right, "{operation}: only the text's part is left: {b:?}");
}
}
/// Adding to an unusual earlier selection (not 8-bit grey) keeps its format; when the buffers that
/// combining makes over the text can't be had, for any selection, that's an error that changes
/// nothing, not an abort.
#[test]
fn an_unusual_earlier_selection_keeps_its_format_or_fails_cleanly() {
use photocraft_color::{PixelFormat, SampleType};
let format = PixelFormat::GRAY8.with_sample(SampleType::F32);
let earlier = Rect::new(-50, 50, 50, 120);
let mut old = Surface::new(format);
old.write_region(earlier, &vec![1.0; (earlier.width() * earlier.height()) as usize]);
let mut s = session(600, 400);
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).selection = Some(old.clone());
let text = json!({"text": "I", "x": 400, "y": 300, "size": 48, "operation": "add"});
// The two glyph buffers are had; the third allocation is the room for combining.
crate::allocation::fail_after_for_test(2);
let steps = s.active().unwrap().history.entries().len();
let err = s.execute(super::CMD, text.clone()).unwrap_err().to_string();
assert!(err.contains("not enough memory for the Type Mask selection"), "{err}");
assert_eq!(selection(&s), Some(old.clone()), "unchanged");
assert_eq!(s.active().unwrap().history.entries().len(), steps, "no history step");
s.execute(super::CMD, text.clone()).unwrap();
let now = selection(&s).unwrap();
assert_eq!(now.format(), format);
assert_eq!(now.read_region(earlier), old.read_region(earlier), "the earlier part stays, past the canvas too");
// An 8-bit grey earlier selection, in every mode, gets the same check for its new tiles.
for operation in ["add", "subtract", "new", "intersect"] {
let mut s = session(600, 400);
s.execute("select.rect", json!({"x": 10, "y": 50, "width": 100, "height": 70})).unwrap();
let (before, steps) = (selection(&s), s.active().unwrap().history.entries().len());
crate::allocation::fail_after_for_test(2);
let err = s.execute(super::CMD, json!({"text": "I", "x": 400, "y": 300, "size": 48, "operation": operation})).unwrap_err().to_string();
assert!(err.contains("not enough memory for the Type Mask selection"), "{operation}: {err}");
assert_eq!(selection(&s), before, "{operation}: unchanged");
assert_eq!(s.active().unwrap().history.entries().len(), steps, "{operation}: no history step");
}
}
@@ -0,0 +1,71 @@
//! #12058: new vertical text is the history state "New Vertical Type Layer", point and paragraph
//! text alike; horizontal text stays "New Type Layer", and a committed Type Mask session, vertical
//! or not, still leaves one "Type Mask" state.
use serde_json::{Value, json};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 300, "height": 300})).unwrap();
s
}
fn entries(s: &Session) -> Vec<String> {
s.active().unwrap().history.entries()
}
/// The history states `type.create` adds with `params`, and the layer it makes.
fn create(params: Value) -> (Vec<String>, u64) {
let mut s = session();
let before = entries(&s).len();
let layer = s.execute("type.create", params).unwrap()["layer"].as_u64().unwrap();
(entries(&s)[before..].to_vec(), layer)
}
#[test]
fn vertical_text_is_a_new_vertical_type_layer() {
for (what, params) in [
("point", json!({"text": "AB", "x": 150, "y": 40, "orientation": "vertical"})),
("paragraph", json!({"text": "AB", "box": [100, 20, 60, 200], "orientation": "vertical"})),
] {
assert_eq!(create(params).0, ["New Vertical Type Layer"], "{what}");
}
}
#[test]
fn horizontal_text_is_still_a_new_type_layer() {
for (what, params) in [
("point", json!({"text": "AB", "x": 40, "y": 120})),
("point, horizontal", json!({"text": "AB", "x": 40, "y": 120, "orientation": "horizontal"})),
("paragraph", json!({"text": "AB", "box": [20, 20, 200, 60]})),
("paragraph, horizontal", json!({"text": "AB", "box": [20, 20, 200, 60], "orientation": "horizontal"})),
] {
assert_eq!(create(params).0, ["New Type Layer"], "{what}");
}
}
/// The Type Mask tools' commands: a hidden working layer from `type.create`, then
/// `type.createSelection` removing it, all coalesced into the session's one step.
#[test]
fn a_type_mask_session_is_still_one_type_mask_state() {
for orientation in ["horizontal", "vertical"] {
let mut s = session();
let before = entries(&s).len();
let key = json!("type-mask-session");
let created = json!({"text": "", "x": 150, "y": 40, "orientation": orientation, "coalesce": key});
let layer = s.execute("type.create", created).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setProps", json!({"layer": layer, "visible": false, "coalesce": key})).unwrap();
s.execute("type.edit", json!({"layer": layer, "text": "AB", "coalesce": key})).unwrap();
s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "coalesce": key})).unwrap();
assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}");
}
// Without a layer, `type.createSelection` makes its text itself: the same one state.
for orientation in ["horizontal", "vertical"] {
let mut s = session();
let before = entries(&s).len();
s.execute("type.createSelection", json!({"text": "AB", "x": 150, "y": 40, "size": 48, "orientation": orientation})).unwrap();
assert_eq!(entries(&s)[before..], ["Type Mask"], "{orientation}, no layer");
}
}
+2
View File
@@ -364,3 +364,5 @@ mod fx_mode_tests;
#[cfg(test)]
mod brush_clear_background_tests;
pub mod command_hints;
#[cfg(test)]
mod pencil_auto_erase_exact_tests;
@@ -0,0 +1,80 @@
//! #11966: Pencil Auto Erase paints the background colour only when the start pixel is exactly
//! the foreground colour (its alpha aside); one level off paints the foreground. The live preview
//! agrees, and at 16 and 32 bits a foreground equal to the pixel still counts.
use serde_json::{Value, json};
use crate::Session;
use crate::brush_cmds::LiveStroke;
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
/// A document of `depth` bits with a pixel layer filled with `fill`, the background colour white.
fn session(depth: u32, fill: [f32; 4]) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 24, "height": 24, "depth": depth, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": fill})).unwrap();
s.tools.background = WHITE;
s
}
fn pencil(fg: &str) -> Value {
json!({"points": [[12, 12]], "size": 3, "color": fg, "autoErase": true})
}
fn active_pixel(s: &Session) -> [f32; 4] {
let st = s.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(12, 12)
}
fn preview_pixel(s: &Session, p: &Value) -> [f32; 4] {
let preview = LiveStroke::begin_with(s, "paint.pencil", p).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
preview.doc.layer(id).unwrap().surface().unwrap().rgba(12, 12)
}
fn level(v: f32) -> u8 {
(v * 255.0).round() as u8
}
const RED: [f32; 4] = [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0];
#[test]
fn one_level_off_paints_the_foreground() {
let mut s = session(8, RED);
let p = pencil("#dd1e1e"); // 221, 30, 30
let preview = preview_pixel(&s, &p);
s.execute("paint.pencil", p).unwrap();
let px = active_pixel(&s);
assert_eq!([level(px[0]), level(px[1]), level(px[2]), level(px[3])], [221, 30, 30, 255]);
assert_eq!(preview, px, "the live preview agrees");
}
#[test]
fn the_exact_foreground_paints_the_background_colour() {
let mut s = session(8, RED);
let p = pencil("#dc1e1e"); // 220, 30, 30
assert_eq!(preview_pixel(&s, &p), WHITE);
s.execute("paint.pencil", p).unwrap();
assert_eq!(active_pixel(&s), WHITE);
}
#[test]
fn alpha_is_ignored_for_the_match() {
let mut s = session(8, [RED[0], RED[1], RED[2], 0.5]);
s.execute("paint.pencil", pencil("#dc1e1e")).unwrap();
assert_eq!(active_pixel(&s), WHITE, "opaque background colour");
}
#[test]
fn deeper_documents_still_match_an_equal_foreground() {
for depth in [16, 32] {
let mut s = session(depth, RED);
s.execute("paint.pencil", pencil("#dc1e1e")).unwrap();
assert_eq!(active_pixel(&s), WHITE, "{depth} bits");
let mut s = session(depth, RED);
s.execute("paint.pencil", pencil("#dd1e1e")).unwrap();
assert_ne!(active_pixel(&s), WHITE, "{depth} bits: one level off paints the foreground");
}
}
+2 -3
View File
@@ -135,9 +135,8 @@ fn mask_creation_preserves_selection_coverage_and_existing_masks() {
before.selection.as_ref().unwrap().read_region(before.bounds()),
"{depth}-bit coverage is unchanged"
);
// The selection went into the mask, except for the Gradient tool's fill layer.
let kept = if command == "gradient.fill.create" { before.selection.clone() } else { None };
assert_eq!(after.selection, kept, "{command}");
// The selection went into the mask, so it is dropped (#8801, #12196).
assert!(after.selection.is_none(), "{command}");
assert_eq!(after.layers[0].mask, before.layers[0].mask, "creating a mask does not requantize an existing mask");
}
}
+47
View File
@@ -0,0 +1,47 @@
//! #11886: with Airbrush on, a brush held still builds up at about ten dabs a second and a plain
//! click lays two dabs, as in Photoshop. Measured there with the default 13 px soft brush at Flow
//! 10 %, black on white: the dab centre reads 205 after a click and 26 after a 2 s hold, and 229
//! with Airbrush off however long the button is held.
use photocraft_color::PixelFormat;
use photocraft_raster::Surface;
use crate::{BrushSettings, StrokePoint, render_stroke};
fn brush(build_up: bool) -> BrushSettings {
BrushSettings { size: 13.0, hardness: 0.0, flow: 0.1, pressure_size: false, build_up, color: [0.0, 0.0, 0.0, 1.0], ..BrushSettings::default() }
}
/// The 0–255 value at the dab centre over white after holding the button still for `ms`.
fn centre_after_hold(b: &BrushSettings, ms: f64) -> f32 {
let a = StrokePoint { time: 0.0, ..StrokePoint::new(30.0, 30.0, 1.0) };
let z = StrokePoint { time: ms, ..a };
let mut s = Surface::new(PixelFormat::RGBA32F);
render_stroke(&mut s, b, &[a, z], None, false, 1.0);
255.0 * (1.0 - s.rgba(30, 30)[3])
}
#[test]
fn the_default_rate_is_ten_dabs_a_second() {
assert_eq!(BrushSettings::default().build_up_rate, 10.0);
}
#[test]
fn a_click_lays_two_dabs() {
let v = centre_after_hold(&brush(true), 0.0);
assert!((v - 205.0).abs() <= 5.0, "{v}");
}
#[test]
fn a_two_second_hold_builds_up_to_the_reference_value() {
let v = centre_after_hold(&brush(true), 2000.0);
assert!((v - 26.0).abs() <= 8.0, "{v}");
}
#[test]
fn airbrush_off_keeps_one_dab_however_long_it_is_held() {
for ms in [0.0, 500.0, 2000.0] {
let v = centre_after_hold(&brush(false), ms);
assert!((v - 229.0).abs() <= 3.0, "{ms} ms: {v}");
}
}
+2 -1
View File
@@ -656,7 +656,8 @@ impl Default for BrushSettings {
noise: false,
wet_edges: false,
build_up: false,
build_up_rate: 20.0,
// About ten dabs a second while held still, Photoshop's Airbrush rate (#11886).
build_up_rate: 10.0,
smoothing: Smoothing::default(),
protect_texture: false,
locks: SectionLocks::default(),
+5 -4
View File
@@ -609,7 +609,8 @@ fn build_up_accumulates_over_time() {
let (n0, a0) = hold(0.0);
let (n1, a1) = hold(500.0);
let (n2, a2) = hold(2000.0);
assert_eq!((n0, n1, n2), (1, 11, 41));
// A click lays two dabs with the airbrush on (#11886), then one per 50 ms at this rate.
assert_eq!((n0, n1, n2), (2, 12, 42));
assert!(a0 < a1 && a1 < a2, "{a0} {a1} {a2}");
// Without build-up, lingering adds nothing.
let nb = BrushSettings { build_up: false, ..b };
@@ -624,15 +625,15 @@ fn huge_airbrush_time_gap_emits_bounded_catch_up() {
let b = BrushSettings { build_up: true, build_up_rate: 1000.0, ..brush() };
let a = StrokePoint { time: 0.0, ..StrokePoint::new(20.0, 20.0, 1.0) };
let brief_pause = StrokePoint { time: 200.0, ..a };
assert_eq!(dabs_of(&b, &[a, brief_pause]).len(), 201, "a 200 ms pause should retain its airbrush build-up");
assert_eq!(dabs_of(&b, &[a, brief_pause]).len(), 202, "a 200 ms pause should retain its airbrush build-up (after the click's two dabs)");
let z = StrokePoint { time: f64::MAX, ..a };
let d = dabs_of(&b, &[a, z]);
assert!(d.len() <= 2, "a huge pause should resume with one dab, not replay its time backlog: {}", d.len());
assert!(d.len() <= 3, "a huge pause should resume with one dab, not replay its time backlog: {}", d.len());
assert_eq!(d.last().map(|dab| dab.center), Some(Point::new(20.0, 20.0)));
let infinite = StrokePoint { time: f64::INFINITY, ..a };
assert!(dabs_of(&b, &[a, infinite]).len() <= 1);
assert!(dabs_of(&b, &[a, infinite]).len() <= 2, "the click's two dabs, no backlog");
}
#[test]
+11 -2
View File
@@ -341,6 +341,15 @@ impl PathWalker {
self
}
/// The stroke's first point. With the airbrush on it lays two dabs, so a plain click builds
/// up as Photoshop's does (#11886).
fn emit_first(&mut self, point: StrokePoint, out: &mut impl FnMut(StepInput)) {
self.emit(point, out);
if self.interval.is_some() {
self.emit(point, out);
}
}
fn emit(&mut self, point: StrokePoint, out: &mut impl FnMut(StepInput)) {
if self.step >= MAX_STEPS_PER_STROKE {
return;
@@ -369,7 +378,7 @@ impl PathWalker {
}
}
if let Some(f) = self.pending_first.take() {
self.emit(f, out);
self.emit_first(f, out);
}
if len > 1e-9 {
// Speed spacing needs the segment's duration; without timestamps (a straight ⇧-click
@@ -432,7 +441,7 @@ impl PathWalker {
pub fn finish(&mut self, out: &mut impl FnMut(StepInput)) {
if let Some(f) = self.pending_first.take() {
self.emit(f, out);
self.emit_first(f, out);
}
}
}
+2
View File
@@ -406,6 +406,8 @@ mod tests {
}
}
#[cfg(test)]
mod airbrush_rate_tests;
#[cfg(test)]
mod brush_tests;
+41 -4
View File
@@ -11,7 +11,7 @@
#![allow(unsafe_code, clippy::upper_case_acronyms)]
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
static BARREL_DOWN: AtomicBool = AtomicBool::new(false);
@@ -25,6 +25,10 @@ static PEN_END: AtomicU8 = AtomicU8::new(0);
/// The pen end of the last contact [`take_pen_end`] has not read yet, as [`encode_end`] stores it.
static CONTACT_END: AtomicU8 = AtomicU8::new(0);
/// Where the pen was on the screen at its last pointer message (`ptPixelLocation`, physical
/// pixels), [`pack_px`]ed, or [`NO_PX`]. Read by [`pen_screen_px`].
static PEN_PX: AtomicU64 = AtomicU64::new(NO_PX);
const NO_PX: u64 = u64::MAX;
fn encode_end(end: Option<bool>) -> u8 {
match end {
@@ -213,15 +217,39 @@ pub fn handle_pointer_message(message: u32, w_param: usize, pen_flags: impl FnOn
PEN_END.store(encode_end(next.end), Ordering::Relaxed);
PEN_ID.store(next.pen_id.unwrap_or(NO_PEN), Ordering::Relaxed);
CONTACT_END.store(encode_end(next.contact), Ordering::Relaxed);
if next.pen_id.is_none() {
PEN_PX.store(NO_PX, Ordering::Relaxed);
}
}
/// `GetPointerPenInfo`'s pen flags for a pointer (`None`: not a pen). It also keeps where the pen
/// is on the screen ([`pen_screen_px`]).
fn read_pen_flags(pointer_id: u32) -> Option<u32> {
// SAFETY: `info` is a stack-allocated buffer initialized to zero that outlives the call, and
// `pointer_id` comes from a WM_POINTER message; an unknown id makes the call fail, not crash.
unsafe {
let info = unsafe {
let mut info: POINTER_PEN_INFO = std::mem::zeroed();
(GetPointerPenInfo(pointer_id, &mut info) != 0).then_some(info.pen_flags)
}
(GetPointerPenInfo(pointer_id, &mut info) != 0).then_some(info)
}?;
let at = &info.pointer_info.pt_pixel_location;
PEN_PX.store(pack_px(at.x, at.y), Ordering::Relaxed);
Some(info.pen_flags)
}
fn pack_px(x: i32, y: i32) -> u64 {
(u64::from(x as u32) << 32) | u64::from(y as u32)
}
fn unpack_px(v: u64) -> Option<(i32, i32)> {
(v != NO_PX).then_some(((v >> 32) as u32 as i32, v as u32 as i32))
}
/// Where the pen in range is on the screen, in physical pixels, as of its last pointer message;
/// `None` with no pen in range. Unlike a window-relative position it doesn't depend on where the
/// window is, so the title bar can move the window after the pen (#7967) while Windows is still
/// moving it (winit moves windows asynchronously). The system cursor doesn't follow every pen.
pub fn pen_screen_px() -> Option<(i32, i32)> {
PEN_ID.load(Ordering::Relaxed).ne(&NO_PEN).then(|| unpack_px(PEN_PX.load(Ordering::Relaxed))).flatten()
}
/// `WH_GETMESSAGE`: the posted pointer messages, as the UI thread takes them from its queue.
@@ -311,6 +339,7 @@ impl Drop for Monitor {
PEN_END.store(encode_end(None), Ordering::Relaxed);
PEN_ID.store(NO_PEN, Ordering::Relaxed);
CONTACT_END.store(encode_end(None), Ordering::Relaxed);
PEN_PX.store(NO_PX, Ordering::Relaxed);
}
}
@@ -339,6 +368,14 @@ mod tests {
const POINTER_FLAG_INCONTACT: u32 = 0x0004;
const POINTER_FLAG_FIRSTBUTTON: u32 = 0x0010;
#[test]
fn pen_screen_positions_round_trip_left_of_and_above_the_primary_monitor() {
for (x, y) in [(0, 0), (1140, 214), (-2400, -300), (i32::MAX, i32::MIN)] {
assert_eq!(unpack_px(pack_px(x, y)), Some((x, y)));
}
assert_eq!(unpack_px(NO_PX), None);
}
#[test]
fn plain_pen_contact_is_not_treated_as_barrel() {
// Plain tip touch on digitizer: INCONTACT is set, first button may be set, no barrel flag.
+2
View File
@@ -246,6 +246,8 @@ impl PhotocraftApp {
/// wait modal took the frame (its input, IME and window check already handled).
fn ui_body(&mut self, ui: &mut egui::Ui) -> bool {
let ctx = ui.ctx().clone();
// Where a pen dragging the window is on the screen, before the title bar reads it.
titlebar::note_os_pointer(self, &ctx);
// A text field's right-click menu, before any field is drawn (text_field_menu.rs).
text_field_menu::show(&ctx);
// The wheel goes to a focused value field before the canvas or a panel sees it (#5473).
@@ -9,7 +9,7 @@ use super::*;
use crate::canvas::{ToolEvent, tool_event};
/// A 64 × 64 document with a painted layer active, black foreground, `tool`.
fn app(tool: Tool) -> PhotocraftApp {
pub(super) fn app(tool: Tool) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
@@ -20,26 +20,26 @@ fn app(tool: Tool) -> PhotocraftApp {
app
}
fn active(app: &PhotocraftApp) -> u64 {
pub(super) fn active(app: &PhotocraftApp) -> u64 {
app.session.active().unwrap().active_layer.unwrap().0
}
fn steps(app: &PhotocraftApp) -> usize {
pub(super) fn steps(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.past_len()
}
/// A press, a short drag and the release with the active tool.
fn stroke(app: &mut PhotocraftApp) {
pub(super) fn stroke(app: &mut PhotocraftApp) {
tool_event(app, ToolEvent::Down { x: 20.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE);
tool_event(app, ToolEvent::Move { x: 44.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE);
tool_event(app, ToolEvent::Up { x: 44.0, y: 32.0 }, Modifiers::NONE);
}
fn alerts(app: &PhotocraftApp) -> Vec<String> {
pub(super) fn alerts(app: &PhotocraftApp) -> Vec<String> {
app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(Value::as_str).map(str::to_string)).collect()
}
fn refused(app: &mut PhotocraftApp, want: &str) {
pub(super) fn refused(app: &mut PhotocraftApp, want: &str) {
let before = steps(app);
stroke(app);
assert_eq!(alerts(app), [want], "the alert, once");
+7
View File
@@ -1901,6 +1901,13 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &
pipette_cursor(ui.ctx(), p)
}
}
// The Count tool (#11773): an arrow with "1+", "1" over a marker (the click's own hit
// test) or "1−" with ⌥ there. Precise Other Cursors keeps today's crosshair.
Tool::Count if !precise_other_cursor(app) => {
let alt = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)).alt;
let over = crate::analysis_ui::count_marker_at(app, xf.to_doc(p)).is_some();
crate::tool_cursor::count(ui.ctx(), p, crate::tool_cursor::CountCursor::pick(over, alt))
}
// The Color Sampler: a pipette, or the crosshair for precise Other Cursors.
Tool::ColorSampler => {
if precise_other_cursor(app) {
@@ -1261,6 +1261,7 @@ fn pen_dialog(app: &mut PhotocraftApp, command: &str, label: &str, name: &str) {
if command == "path.toSelection" {
// OK deselects and hides the path, as ⌘↩ does (#6079).
fields.insert("__deselectPath".into(), json!(true));
fields.insert(MAKE_SELECTION.into(), json!(true));
}
if command == "path.fill" {
let fg = app.session.tools.foreground;
@@ -1281,6 +1282,63 @@ fn pen_dialog(app: &mut PhotocraftApp, command: &str, label: &str, name: &str) {
spec_dialog(app, command, label, spec, fields);
}
/// Marks the Make Selection dialog [`pen_dialog`] opens. It keeps the schema dialog's fields, so OK
/// and Alt+Reset work as before; only the body is Photoshop's layout (#12917).
const MAKE_SELECTION: &str = "__makeSelection";
/// The Make Selection operations, in Photoshop's order: (`path.toSelection` mode, label).
const MAKE_SELECTION_OPERATIONS: [(&str, &str); 4] =
[("replace", "New Selection"), ("add", "Add to Selection"), ("subtract", "Subtract from Selection"), ("intersect", "Intersect with Selection")];
/// Is this dialog the Make Selection dialog?
pub(crate) fn owns_make_selection(fields: &serde_json::Map<String, Value>) -> bool {
fields.contains_key(MAKE_SELECTION)
}
/// Photoshop's Make Selection dialog: Rendering (Feather Radius, Anti-aliased) and Operation.
/// Without a selection there is nothing to combine with, so only New Selection is available.
pub(crate) fn make_selection_body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut serde_json::Map<String, Value>) {
let has_selection = app.session.active().is_some_and(|st| st.doc.selection.is_some());
ui.spacing_mut().item_spacing.y = 6.0;
crate::widgets::section_label(ui, tl!("Rendering"));
crate::widgets::hairline(ui);
ui.horizontal(|ui| {
ui.label(tl!("Feather Radius:"));
let mut feather = f.get("feather").and_then(Value::as_f64).unwrap_or(0.0) as f32;
crate::widgets::value_field(ui, &mut feather, 0.0..=250.0, "", 64.0).accessible_name(tl!("Feather Radius:"));
ui.label(tl!("pixels"));
// The schema dialog's rounding, so OK sends what it sent.
f.insert("feather".into(), json!((feather * 10.0).round() / 10.0));
});
let mut anti_alias = f.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);
crate::widgets::checkbox(ui, &mut anti_alias, tl!("Anti-aliased"));
f.insert("antiAlias".into(), json!(anti_alias));
ui.add_space(4.0);
crate::widgets::section_label(ui, tl!("Operation"));
crate::widgets::hairline(ui);
let mut mode = f.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string();
// A combining mode set from outside, or a selection gone while the dialog was open.
if !has_selection {
mode = "replace".into();
}
for (key, label) in MAKE_SELECTION_OPERATIONS {
ui.add_enabled_ui(key == "replace" || has_selection, |ui| ui.radio_value(&mut mode, key.to_string(), tl!(label)));
}
f.insert("mode".into(), json!(mode));
}
/// OK in the Make Selection dialog: a new selection is the History step Selection Change, as in
/// Photoshop (#12917). ⌘↩, the Paths panel and the combining operations keep the engine's Make
/// Selection (not measured). Only a step this run added is renamed: `revision` is from before it.
pub(crate) fn name_make_selection_step(app: &mut PhotocraftApp, fields: &serde_json::Map<String, Value>, params: &Value, revision: Option<u64>) {
if !owns_make_selection(fields) || params.get("mode").and_then(Value::as_str).is_some_and(|m| m != "replace") {
return;
}
if let Some(st) = app.session.active_mut().filter(|st| Some(st.revision) != revision) {
st.history.set_current_label("Selection Change");
}
}
/// The Pen options bar's Make Selection (Path mode, #5703): the canvas menu's Make Selection…
/// dialog for the path being drawn (committed first, as the menu does) or the active path.
pub(crate) fn make_selection(app: &mut PhotocraftApp) -> Result<(), String> {
@@ -1439,3 +1497,6 @@ mod hand_menu_entries_tests;
#[cfg(test)]
mod pen_free_transform_label_tests;
#[cfg(test)]
mod make_selection_dialog_tests;
@@ -0,0 +1,210 @@
//! #12917: Make Selection from a path is Photoshop's dialog: Rendering (Feather Radius in pixels,
//! Anti-aliased) and Operation (New / Add to / Subtract from / Intersect with Selection, the last
//! three greyed without a selection). OK with the defaults selects inside the path in one
//! Selection Change History step; each Operation runs `path.toSelection` with its mode. ⌘↩ and the
//! combining operations keep today's Make Selection step (not measured).
use egui::accesskit::{Role, Toggled};
use egui_kittest::kittest::{NodeT, Queryable};
use egui_kittest::{Harness, Node};
use serde_json::{Value, json};
use super::make_selection;
use super::tests::choose_open;
use crate::PhotocraftApp;
use crate::state::Tool;
const OPERATIONS: [&str; 4] = ["New Selection", "Add to Selection", "Subtract from Selection", "Intersect with Selection"];
const MODES: [&str; 4] = ["replace", "add", "subtract", "intersect"];
/// A document with the reference's closed triangle as the Work Path, with or without a selection
/// (a rectangle the triangle overlaps).
fn app(selection: bool) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 500})).unwrap();
let knots = json!([[100, 300], [300, 300], [200, 450]]);
app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": knots}]}})).unwrap();
if selection {
app.run("select.rect", json!({"x": 20, "y": 20, "width": 200, "height": 320})).unwrap();
}
app.ui.tool = Tool::Pen;
app
}
fn draw(ui: &mut egui::Ui, app: &mut PhotocraftApp) {
if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
crate::dialogs::show(app, ui.ctx());
}
}
/// The Pen canvas menu's Make Selection… dialog, drawn as the window shows it.
fn dialog(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {
choose_open(&mut app, "path.toSelection");
assert_eq!(app.ui.dialogs.len(), 1, "Make Selection… opened its dialog");
let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(draw, app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
h
}
fn click(h: &mut Harness<'_, PhotocraftApp>, label: &str) {
h.get_by_label(label).click();
h.run_steps(3);
}
fn steps(app: &PhotocraftApp) -> Vec<String> {
app.session.active().unwrap().history.entries().iter().map(|e| e.to_string()).collect()
}
fn last_step(app: &PhotocraftApp) -> Option<String> {
steps(app).last().cloned()
}
fn selection_bounds(app: &PhotocraftApp) -> Option<[i32; 4]> {
let r = app.session.active().unwrap().doc.selection.as_ref()?.content_bounds();
Some([r.x0, r.y0, r.x1, r.y1])
}
/// The params of the last command run.
fn last_params(app: &PhotocraftApp) -> Value {
let (id, params) = app.session.journal.last().cloned().unwrap();
assert_eq!(id, "path.toSelection");
params
}
fn enabled(h: &Harness<'_, PhotocraftApp>, label: &str) -> bool {
!h.get_by_label(label).accesskit_node().is_disabled()
}
fn feather_field<'h>(h: &'h Harness<'_, PhotocraftApp>) -> Node<'h> {
h.get_all_by_label("Feather Radius:").find(|n| n.accesskit_node().role() == Role::SpinButton).expect("the Feather Radius number field")
}
#[test]
fn the_dialog_shows_the_rendering_and_operation_groups() {
let h = dialog(app(false));
for label in ["Make Selection", "Rendering", "pixels", "Anti-aliased", "Operation", "OK", "Cancel"] {
assert!(h.query_by_label(label).is_some(), "{label} is shown");
}
for old in ["Feather", "Anti Alias", "Mode"] {
assert!(h.query_by_label(old).is_none(), "the schema dialog's {old} is gone");
}
assert_eq!(h.get_by_label("Anti-aliased").accesskit_node().toggled(), Some(Toggled::True), "Anti-aliased is on");
assert_eq!(h.get_by_label("New Selection").accesskit_node().toggled(), Some(Toggled::True), "New Selection is chosen");
assert_eq!(feather_field(&h).accesskit_node().numeric_value(), Some(0.0), "Feather Radius is 0");
let tops: Vec<f32> = OPERATIONS.iter().map(|label| h.get_by_label(label).rect().top()).collect();
assert!(tops.windows(2).all(|w| w[0] < w[1]), "the operations are listed in order: {tops:?}");
let rendering = h.get_by_label("Rendering").rect().top();
let operation = h.get_by_label("Operation").rect().top();
let feather = feather_field(&h).rect().top();
assert!(rendering < feather && feather < operation && operation < tops[0], "Rendering holds Feather Radius, Operation the radio buttons");
}
#[test]
fn the_options_bar_button_opens_the_same_dialog() {
let mut app = app(false);
make_selection(&mut app).unwrap();
let fields = &app.ui.dialogs.last().unwrap().fields;
assert!(super::owns_make_selection(fields));
assert_eq!(fields.get("__command"), Some(&json!("path.toSelection")));
assert!(fields.contains_key("__deselectPath"), "OK deselects the path, as from the canvas menu");
}
#[test]
fn without_a_selection_only_new_selection_is_available() {
let h = dialog(app(false));
assert!(enabled(&h, "New Selection"));
for label in &OPERATIONS[1..] {
assert!(!enabled(&h, label), "{label} is greyed out without a selection");
}
}
#[test]
fn with_a_selection_every_operation_is_available() {
let h = dialog(app(true));
for label in OPERATIONS {
assert!(enabled(&h, label), "{label} is available with a selection");
}
}
/// A combining mode the dialog was given (by automation, or before the selection went) falls
/// back to New Selection when there is nothing to combine with.
#[test]
fn without_a_selection_a_combining_mode_falls_back_to_new_selection() {
let mut h = dialog(app(false));
h.state_mut().ui.dialogs.last_mut().unwrap().fields.insert("mode".into(), json!("subtract"));
h.run_steps(2);
assert_eq!(h.get_by_label("New Selection").accesskit_node().toggled(), Some(Toggled::True));
click(&mut h, "OK");
assert_eq!(last_params(h.state()).get("mode"), Some(&json!("replace")));
assert_eq!(selection_bounds(h.state()), Some([100, 300, 300, 450]));
}
#[test]
fn ok_with_the_defaults_selects_the_triangle_in_one_selection_change_step() {
let mut h = dialog(app(false));
let before = steps(h.state());
click(&mut h, "OK");
assert!(h.state().ui.dialogs.is_empty(), "OK closed the dialog");
assert_eq!(selection_bounds(h.state()), Some([100, 300, 300, 450]));
let after = steps(h.state());
assert_eq!(after.len(), before.len() + 1, "one History step: {after:?}");
assert_eq!(after[..before.len()], before[..], "the earlier steps keep their names");
assert_eq!(after.last().map(String::as_str), Some("Selection Change"));
assert_eq!(h.state().ui.selected_path, None, "OK deselects the path, as ⌘↩ does");
}
#[test]
fn each_operation_runs_make_selection_with_its_mode() {
for (label, mode) in OPERATIONS.into_iter().zip(MODES) {
let mut h = dialog(app(true));
click(&mut h, label);
click(&mut h, "OK");
assert_eq!(last_params(h.state()).get("mode").and_then(Value::as_str), Some(mode), "{label}");
let want = if mode == "replace" { "Selection Change" } else { "Make Selection" };
assert_eq!(last_step(h.state()).as_deref(), Some(want), "{label}: the combining operations keep today's step name");
}
}
#[test]
fn a_typed_feather_radius_is_sent() {
let mut h = dialog(app(false));
feather_field(&h).click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("4".into()));
h.key_press(egui::Key::Tab);
h.run_steps(3);
click(&mut h, "OK");
assert_eq!(last_params(h.state()).get("feather").and_then(Value::as_f64), Some(4.0));
}
#[test]
fn cancel_changes_nothing() {
let mut h = dialog(app(true));
let (selection, before) = (selection_bounds(h.state()), steps(h.state()));
click(&mut h, "Intersect with Selection");
click(&mut h, "Cancel");
assert!(h.state().ui.dialogs.is_empty(), "Cancel closed the dialog");
assert_eq!(selection_bounds(h.state()), selection);
assert_eq!(steps(h.state()), before);
}
/// ⌘↩ runs the same command without the dialog: its step keeps today's name (not measured).
#[test]
fn cmd_enter_keeps_the_make_selection_step() {
let mut app = app(false);
crate::vector_ui::path_to_selection(&mut app, json!({})).unwrap();
assert_eq!(selection_bounds(&app), Some([100, 300, 300, 450]));
assert_eq!(last_step(&app).as_deref(), Some("Make Selection"));
}
/// OK that adds no step (the path went while the dialog was open) renames nothing.
#[test]
fn ok_that_fails_does_not_rename_the_previous_step() {
let mut h = dialog(app(true));
h.state_mut().run("path.delete", json!({"name": "work"})).unwrap();
let before = steps(h.state());
click(&mut h, "OK");
assert_eq!(steps(h.state()), before);
}
+3 -1
View File
@@ -274,7 +274,9 @@ fn sample_color(app: &mut PhotocraftApp, x: f64, y: f64, sample_layer: &str) ->
return None;
}
let size = app.ui.tool_options.eyedropper_size;
let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer})).ok()?;
// The box depends on the view zoom at 100 % and below, as in Photoshop (#11751).
let zoom = f64::from(app.current_zoom());
let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer, "zoom": zoom})).ok()?;
match serde_json::from_value::<Vec<f32>>(v).ok()?[..] {
[r, g, b, a] if a > 0.0 => Some([r, g, b]),
_ => None,
+49
View File
@@ -84,6 +84,52 @@ impl egui::plugin::Plugin for CursorLifecycle {
}
}
/// The Count tool's cursor (#11773): an arrow with "1+" (a click adds a marker), "1" (over a
/// marker: a click or drag moves it) or "1−" (⌥ over a marker: a click deletes it).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CountCursor {
Add,
Move,
Delete,
}
impl CountCursor {
/// The cursor for a pointer `over` a marker or not, with ⌥ held or not. Shift changes nothing,
/// and ⌥ off a marker is still "1+" (an ⌥-click there does nothing).
pub(crate) fn pick(over: bool, alt: bool) -> Self {
match (over, alt) {
(false, _) => Self::Add,
(true, false) => Self::Move,
(true, true) => Self::Delete,
}
}
/// The badge drawn below right of the arrow.
pub(crate) fn label(self) -> &'static str {
match self {
Self::Add => "1+",
Self::Move => "1",
Self::Delete => "1\u{2212}",
}
}
}
/// Draw the Count cursor `kind` at `at`: the OS arrow (hotspot at its tip) with its badge below right
/// of it, dark digits on a light halo so they read on any pixel. PhotoCraft's own artwork.
pub(crate) fn count(ctx: &egui::Context, at: Pos2, kind: CountCursor) -> CursorIcon {
let pos = at + vec2(12.0, 16.0);
// Painted straight onto a tooltip-order layer, above the canvas and its overlays: an Area
// would be invisible on the frame it first appears.
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-count-cursor")));
let font = egui::FontId::proportional(11.0);
// The halo: a white copy one point off on every side, diagonals too.
for (dx, dy) in [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)] {
painter.text(pos + vec2(dx, dy), egui::Align2::LEFT_TOP, kind.label(), font.clone(), egui::Color32::WHITE);
}
painter.text(pos, egui::Align2::LEFT_TOP, kind.label(), font, egui::Color32::BLACK);
CursorIcon::Default
}
/// The bucket artwork and its exact fill crosshair move as one native cursor or painted image.
pub(crate) fn bucket(painter: &Painter, at: Pos2) -> Result<CursorIcon, String> {
bucket::show(painter, at)
@@ -676,3 +722,6 @@ fn rasterize(shape: &Shape, scale: f32) -> Option<CustomCursorImage> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod count_tests;
@@ -0,0 +1,113 @@
//! #11773: the Count tool's cursors. An arrow with "1+" off a marker, "1" on one and "1−" with ⌥
//! on one; Shift changes nothing, Ctrl is the Move tool's cursor. "On a marker" is the click's own
//! hit test, so the cursor never promises what the click won't do.
use serde_json::json;
use super::{CountCursor, count};
use crate::PhotocraftApp;
use crate::canvas::ToolEvent;
use crate::state::Tool;
/// A 200 × 100 document with the Count tool and one marker at 50,40.
fn app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
app.run("count.add", json!({"x": 50, "y": 40})).unwrap();
app.ui.tool = Tool::Count;
app
}
fn markers(app: &PhotocraftApp) -> Vec<[f64; 2]> {
app.session.active().unwrap().doc.measurement.count_groups.iter().flat_map(|g| g.points.clone()).collect()
}
#[test]
fn the_cursor_kind_follows_the_marker_and_alt() {
assert_eq!(CountCursor::pick(false, false), CountCursor::Add, "empty canvas or pasteboard");
assert_eq!(CountCursor::pick(true, false), CountCursor::Move, "over a marker");
assert_eq!(CountCursor::pick(true, true), CountCursor::Delete, "⌥ over a marker");
assert_eq!(CountCursor::pick(false, true), CountCursor::Add, "⌥ off a marker: still 1+");
assert_eq!([CountCursor::Add, CountCursor::Move, CountCursor::Delete].map(CountCursor::label), ["1+", "1", "1\u{2212}"], "the badges (a real minus sign)");
}
#[test]
fn over_a_marker_is_the_clicks_own_hit_test() {
// Walk a click away from the marker: wherever the cursor says "1" the click grabs and moves the
// marker, and wherever it says "1+" the click adds a new one.
for dx in [0.0, 2.0, 4.0, 6.0, 6.9, 7.1, 8.0, 15.0] {
let mut app = app();
let at = [50.0 + dx, 40.0];
let kind = CountCursor::pick(crate::analysis_ui::count_marker_at(&app, at).is_some(), false);
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, egui::Modifiers::NONE);
crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 80.0, pressure: 1.0 }, egui::Modifiers::NONE);
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 150.0, y: 80.0 }, egui::Modifiers::NONE);
let m = markers(&app);
match kind {
CountCursor::Move => assert_eq!(m, vec![[150.0, 80.0]], "{dx} px off: \"1\" and the press moved the marker"),
CountCursor::Add => assert_eq!(m.len(), 2, "{dx} px off: \"1+\" and the click added a marker: {m:?}"),
CountCursor::Delete => assert_ne!(kind, CountCursor::Delete, "{dx} px off: no ⌥ is held"),
}
}
}
#[test]
fn ctrl_makes_the_count_tool_the_move_tool() {
// Holding Ctrl turns the Count tool into the temporary Move tool, so the canvas shows the Move
// tool's cursor instead of these.
assert!(crate::hold_keys::cmd_moves(Tool::Count));
}
#[test]
fn the_cursor_is_the_os_arrow_with_its_badge() {
// The OS arrow keeps its hotspot at the tip; the badge is drawn beside it.
let ctx = egui::Context::default();
let mut got = Vec::new();
let mut o = ctx.run_ui(egui::RawInput::default(), |ui| {
for kind in [CountCursor::Add, CountCursor::Move, CountCursor::Delete] {
got.push(count(ui.ctx(), egui::pos2(100.0, 60.0), kind));
}
});
o.textures_delta.clear();
assert_eq!(got, [egui::CursorIcon::Default; 3]);
let texts: Vec<String> = o
.shapes
.into_iter()
.filter_map(|c| match c.shape {
egui::Shape::Text(t) => Some(t.galley.text().to_owned()),
_ => None,
})
.collect();
for label in ["1+", "1", "1\u{2212}"] {
assert!(texts.iter().any(|t| t == label), "badge {label} drawn: {texts:?}");
}
}
#[test]
fn the_badge_halo_surrounds_the_digits_on_all_eight_sides() {
// White copies one point off in every direction, diagonals too, so the dark digits read on
// dark and busy pixels.
let ctx = egui::Context::default();
let mut o = ctx.run_ui(egui::RawInput::default(), |ui| {
count(ui.ctx(), egui::pos2(100.0, 60.0), CountCursor::Add);
});
o.textures_delta.clear();
let texts: Vec<(egui::Pos2, egui::Color32)> = o
.shapes
.into_iter()
.filter_map(|c| match c.shape {
egui::Shape::Text(t) => Some((t.pos, t.fallback_color)),
_ => None,
})
.collect();
let digits = texts.iter().find(|(_, c)| *c == egui::Color32::BLACK).expect("the dark digits").0;
for dx in [-1.0, 0.0, 1.0] {
for dy in [-1.0, 0.0, 1.0] {
if (dx, dy) == (0.0, 0.0) {
continue;
}
let want = digits + egui::vec2(dx, dy);
assert!(texts.iter().any(|&(p, c)| c == egui::Color32::WHITE && p == want), "a halo copy at {dx},{dy}: {texts:?}");
}
}
}
+47 -12
View File
@@ -425,6 +425,32 @@ fn mixer_press_failed(app: &mut PhotocraftApp, message: String) {
}
}
/// A Red Eye click. CMYK, Grayscale and Indexed Color documents get the reference's alert
/// (#12575), once even if more clicks arrive while it is open (`ui.pointer` can send them).
fn red_eye_click(app: &mut PhotocraftApp, x: f64, y: f64) {
use photocraft_engine::redeye_cmds::MODE_REFUSAL;
let o = app.ui.tool_options.clone();
let r = app.run(
"paint.redEye",
json!({
"x": x.floor(),
"y": y.floor(),
"pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0),
"darken": o.red_eye_darken.clamp(0.0, 100.0),
"target": paint_target(app),
}),
);
if r.is_err_and(|e| e == MODE_REFUSAL) {
app.ui.status.clear();
app.ui.status_error = false;
let message = tl!(MODE_REFUSAL);
let kind = crate::state::DialogKind::Error;
if !app.ui.dialogs.iter().any(|d| d.kind == kind && d.fields.get("message").and_then(|m| m.as_str()) == Some(message)) {
app.ui.open_dialog(kind, json!({ "message": message }).as_object().cloned().unwrap_or_default());
}
}
}
/// The Brush's chosen Clear paints as Normal on the Background, and its Mode then reads Normal
/// (#11897): at the press of a Brush stroke on the Background's own pixels, Clear (chosen in the
/// options bar, not a held `~`) is turned off, so the stroke is sent as Normal. A Background whose
@@ -566,6 +592,9 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods:
Tool::MagicWand => {
let o = app.ui.tool_options.clone();
let mode = selection_mode(app, mods);
if wand_pasteboard_click(app, x, y, mode) {
return;
}
let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.magic_wand, "mode": mode}));
return;
}
@@ -581,17 +610,7 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods:
return;
}
Tool::RedEye => {
let o = app.ui.tool_options.clone();
let _ = app.run(
"paint.redEye",
json!({
"x": x.floor(),
"y": y.floor(),
"pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0),
"darken": o.red_eye_darken.clamp(0.0, 100.0),
"target": paint_target(app),
}),
);
red_eye_click(app, x, y);
return;
}
Tool::PolygonLasso => {
@@ -802,6 +821,19 @@ fn covers(sel: &photocraft_raster::Surface, p: [f64; 2]) -> bool {
v[0] > 0.0
}
/// A New-mode Magic Wand click on the pasteboard deselects, as Photoshop's step "Deselect"
/// (#11782), instead of a "Magic Wand" step that selects nothing. True when it handled the click.
fn wand_pasteboard_click(app: &mut PhotocraftApp, x: f64, y: f64, mode: &str) -> bool {
let on_canvas = app.session.active().is_some_and(|st| st.doc.bounds().contains(x.floor() as i32, y.floor() as i32));
if mode != "replace" || on_canvas {
return false;
}
if app.session.is_enabled("select.deselect") {
let _ = app.run("select.deselect", json!({}));
}
true
}
/// Does a press with `tool` at `p` drag the selection rather than draw a new one? `Some(true)`
/// moves the floating piece (⌘ cuts one first, ⌘⌥ copies; the Polygonal Lasso and Magic Wand need
/// ⌘, as a plain press there places or samples), `Some(false)` just the outline (no ⇧ / ⌥ and the
@@ -840,7 +872,10 @@ pub fn selection_drag_kind(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: e
if cut {
return Some(true);
}
(!clicky && !mods.command && selection_mode(app, mods) == "replace").then_some(false)
// The Magic Wand in New mode drags the outline like a marquee: a click deselects, a drag
// moves the outline (#11782).
let outline = !clicky || tool == Tool::MagicWand;
(outline && !mods.command && selection_mode(app, mods) == "replace").then_some(false)
}
/// The tool a pointer event with `mods` goes to: ⌘ held is the Move tool (`hold_keys::cmd_moves`).
+9
View File
@@ -357,6 +357,9 @@ fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fie
_ if crate::smart_filter_dialog::owns(fields) => crate::smart_filter_dialog::body(app, ui, fields),
_ if crate::adjust_dialog::owns(fields) => crate::adjust_dialog::body(app, ui, fields),
_ if crate::blur_pins::owns(fields) => crate::blur_pins::body(ui, fields),
_ if crate::canvas_tool_menu::owns_make_selection(fields) => {
first_field_focused(ui, id, |ui| crate::canvas_tool_menu::make_selection_body(app, ui, fields))
}
_ if fields.contains_key("__filter") => filter_body(app, ui, d, fields, id),
_ if crate::new_guide_ui::owns(fields) => crate::new_guide_ui::body(ui, fields),
_ if crate::equalize_ui::owns(fields) => crate::equalize_ui::body(ui, fields),
@@ -1008,6 +1011,7 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value,
return Err(e);
}
};
let revision = app.session.active().map(|st| st.revision);
let result = crate::actions::run_step_dialog(app, &d.fields, &cmd, params.clone());
if let Ok(r) = &result {
report_file_errors(app, &d, r);
@@ -1020,6 +1024,9 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value,
Some(p) if result.is_ok() && running => p.committing = true,
_ => app.filter_preview = None,
}
if result.is_ok() && cmd == "path.toSelection" {
crate::canvas_tool_menu::name_make_selection_step(app, &d.fields, &params, revision);
}
if result.is_ok()
&& cmd == "path.toSelection"
&& d.fields.contains_key("__deselectPath")
@@ -1259,6 +1266,8 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str)
pub mod adjust_dialog;
pub mod adjust_editors;
pub mod adjust_preview;
#[cfg(test)]
mod arbitrary_ruler_prefill_tests;
pub(crate) mod bitmap_dialog;
pub mod blur_pins;
pub mod brush_preset_dialog;
@@ -0,0 +1,113 @@
//! #12035: Image Rotation › Arbitrary pre-fills the ruler's straightening angle at the
//! precision the reference application shows. A ruler from 100,100 to 400,300 (A -33.7° on
//! the Info panel) opens the Rotate Canvas dialog at 33.69°, Counter clockwise, and OK runs
//! `image.rotation.arbitrary` with that two-decimal angle, not the field's old one-decimal
//! round. The Angle range is -359.99..359.99, wide, so today's wide-range rounding to one
//! decimal decided the dialog's value; only this field now keeps hundredths.
use super::filter_dialog::{body, open, params_of};
use crate::PhotocraftApp;
use serde_json::{Map, Value, json};
/// Draw a dialog body once, as a live dialog does every frame: the drawn fields are what
/// the dialog shows and what OK sends.
fn drawn(f: &mut Map<String, Value>) {
egui::Context::default().run_ui(Default::default(), |ui| body(ui, f)).textures_delta.clear();
}
/// A 318 px square document (the size `ok_runs_the_two_decimal_angle` measures on), a ruler
/// from 100,100 to `end`, the opened Arbitrary dialog and its fields after one drawn frame.
fn ruler_dialog(end: [i32; 2]) -> (PhotocraftApp, u64, Map<String, Value>) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 318, "height": 318})).unwrap();
app.run("image.analysis.rulerTool", json!({"start": [100, 100], "end": end})).unwrap();
let id = open(&mut app, "image.rotation.arbitrary").unwrap();
let mut f = app.ui.dialog_mut(id).unwrap().fields.clone();
drawn(&mut f);
(app, id, f)
}
/// The measured case: the Rotate Canvas dialog opens at 33.69°, Counter clockwise — the
/// angle keeps two decimals where the wide-range rule used to round it to 33.7.
#[test]
fn ruler_prefill_keeps_the_measured_two_decimal_angle() {
let (_app, _id, f) = ruler_dialog([400, 300]);
let a = f["angle"].as_f64().unwrap();
assert!((a - 33.69).abs() < 1e-3, "the dialog opens at {a}, want the measured 33.69");
assert_eq!(crate::widgets::fmt_num2(a), "33.69", "the Angle field shows the measured string");
assert_eq!(f["direction"], json!("ccw"), "a ruler falling to the right straightens counter-clockwise");
}
/// A ruler that needs a clockwise turn pre-fills Clockwise, at the same two decimals;
/// with no ruler the dialog opens at today's default (0, Clockwise).
#[test]
fn clockwise_ruler_prefills_clockwise_and_no_ruler_keeps_the_default() {
// (100,100) → (400,50) rises to the right: a 9.46° clockwise turn.
let (_app, _id, f) = ruler_dialog([400, 50]);
let a = f["angle"].as_f64().unwrap();
assert_eq!(f["direction"], json!("cw"), "a rising ruler pre-fills Clockwise");
assert!((a - 9.46).abs() < 1e-3, "the clockwise pre-fill is {a}, want 9.46 to two decimals");
// No ruler: today's default, unchanged.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 318, "height": 318})).unwrap();
let id = open(&mut app, "image.rotation.arbitrary").unwrap();
let mut f = app.ui.dialog_mut(id).unwrap().fields.clone();
drawn(&mut f);
assert_eq!(f["angle"], json!(0.0), "without a ruler the dialog opens at today's 0");
assert_eq!(f["direction"], json!("cw"), "without a ruler the dialog opens Clockwise");
}
/// OK runs `image.rotation.arbitrary` with the two-decimal angle: a 318 px square rotated by
/// 33.69° measures 441 px across, by 33.7° 442 px — the dialog's rounding must not decide.
#[test]
fn ok_runs_the_two_decimal_angle() {
let (mut app, id, f) = ruler_dialog([400, 300]);
let params = params_of(&f);
assert!((params["angle"].as_f64().unwrap() - 33.69).abs() < 1e-3, "OK sends {params}");
app.ui.dialog_mut(id).unwrap().fields = f;
let r = crate::dialogs::confirm(&mut app, id).unwrap();
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(441), Some(441)), "442 would mean the 33.7 round ran");
}
/// The f32 double-rounding the review caught: a 43x27 ruler line (here 100,100 to 143,127)
/// is 32.1249984 degrees, and the f32 cast of that full-precision pre-fill lands exactly on
/// 32.125 - rounding the widened value half away from zero opened the dialog at 32.13. The
/// hundredths round in f64 before the field narrows, so it opens at 32.12, Counter clockwise.
#[test]
fn the_ruler_angle_rounds_at_full_precision_before_the_field_narrows() {
let (_app, _id, f) = ruler_dialog([143, 127]);
let a = f["angle"].as_f64().unwrap();
assert!((a - 32.12).abs() < 1e-3, "the 43x27 ruler opens at {a}, want 32.12");
assert_eq!(crate::widgets::fmt_num2(a), "32.12", "the Angle field shows 32.12, not the 32.13 the f32 round gives");
assert!((a - 32.13).abs() > 1e-3, "the f32 double-round must not reach the dialog: {a}");
assert_eq!(f["direction"], json!("ccw"));
}
/// The fix is per-field: unrelated number fields keep the precision they have today —
/// wide ranges round to one decimal (in another dialog, and under the same key name),
/// small ranges keep their two.
#[test]
fn other_number_fields_keep_their_precision() {
// A wide range in another dialog: Gaussian Blur's radius (0.1..1000) rounds to one decimal.
let mut f = Map::new();
f.insert("__command".into(), json!("filter.blur.gaussianBlur"));
f.insert("radius".into(), json!(7.26));
drawn(&mut f);
let r = f["radius"].as_f64().unwrap();
assert!((r - 7.3).abs() < 1e-5, "the Gaussian Blur radius {r} must stay at one decimal");
// The same key the fix touches, in another dialog: Twirl's angle (-999..999) rounds to one.
let mut f = Map::new();
f.insert("__command".into(), json!("filter.distort.twirl"));
f.insert("angle".into(), json!(33.69));
drawn(&mut f);
let a = f["angle"].as_f64().unwrap();
assert!((a - 33.7).abs() < 1e-5, "Twirl's angle {a} keeps the one-decimal round");
// A small range keeps its two decimals (Radial Blur spins, so the centre fields stay plain).
let mut f = Map::new();
f.insert("__command".into(), json!("filter.blur.radialBlur"));
f.insert("method".into(), json!("spin"));
f.insert("centerX".into(), json!(0.123));
drawn(&mut f);
let x = f["centerX"].as_f64().unwrap();
assert!((x - 0.12).abs() < 1e-5, "the Radial Blur centre {x} keeps its two decimals");
}
+39 -5
View File
@@ -806,6 +806,26 @@ fn uses_angle_dial(command: &str, key: &str) -> bool {
key == "angle" && ANGLE_DIAL.contains(&command)
}
/// Wide-range number fields that still show two decimals: the Rotate Canvas angle keeps
/// hundredths of a degree, so the ruler's straightening angle reaches the dialog as 33.69 and
/// not 33.7 (#12035). The arrow and drag step follow the shown precision, as elsewhere.
fn wide_field_decimals(command: &str, key: &str) -> Option<u32> {
match (command, key) {
("image.rotation.arbitrary", "angle") => Some(2),
_ => None,
}
}
/// The scale a drawn number field rounds to: two decimals for small ranges (0–1 thresholds and
/// centres) and for the wide fields that show them (#12035), one decimal for the other wide ones.
fn field_scale(command: &str, key: &str, min: f32, max: f32) -> f32 {
match wide_field_decimals(command, key) {
Some(d) => 10f32.powi(d.min(6) as i32),
None if max - min <= 10.0 => 100.0,
None => 10.0,
}
}
/// Replace Color (#4143): the dialog's "From" colour, sampled from the image with a canvas
/// eyedropper like Photoshop's. While armed, the next click on the image writes the merged
/// composite colour into the `color` field (the same sampler the Color Picker uses).
@@ -1031,7 +1051,10 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
}
match p.kind {
Kind::Range { min, max, default } => {
let mut v = f.get(&p.key).and_then(Value::as_f64).unwrap_or(default as f64) as f32;
let src = f.get(&p.key).and_then(Value::as_f64);
let mut v = src.unwrap_or(default as f64) as f32;
// A widget edit this frame makes the field's f32 value authoritative (#12035).
let mut edited = false;
if cmd == "image.mode.indexedColor" && p.key == "colors" {
let mut count = v.round().clamp(2.0, 256.0) as u32;
crate::widgets::color_count_row(ui, &label(&p.key), &mut count);
@@ -1074,12 +1097,23 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
} else {
// A double-click on the slider puts it back to the filter's default.
let gestures = crate::widgets::RowGestures { reset: Some(default), wheel_step: None, ..Default::default() };
crate::widgets::slider_row_with(ui, &label(&p.key), &mut v, min..=max, unit, None, gestures);
edited =
crate::widgets::slider_row_prec(ui, &label(&p.key), &mut v, min..=max, unit, None, gestures, wide_field_decimals(&cmd, &p.key))
.changed();
}
});
// Small ranges (0–1 thresholds and centres) keep the two decimals their field shows.
let scale = if max - min <= 10.0 { 100.0 } else { 10.0 };
f.insert(p.key, json!((v * scale).round() / scale));
// The field's shown precision: small ranges keep their two decimals, and so
// does the Arbitrary angle; the other wide fields round to one (#12035).
let scale = field_scale(&cmd, &p.key, min, max);
// A field showing two decimals rounds while the value is still f64: a 43x27
// ruler is 32.1249984°, whose f32 cast lands exactly on 32.125, and rounding
// that widened value half-away shows 32.13 where the pre-fill says 32.12.
// Values the user typed or dragged are f32 already, so they round as before.
let w = match (wide_field_decimals(&cmd, &p.key), src) {
(Some(_), Some(raw)) if !edited => ((raw * f64::from(scale)).round() / f64::from(scale)) as f32,
_ => (v * scale).round() / scale,
};
f.insert(p.key, json!(w));
}
Kind::Choice { options, default } => {
ui.horizontal(|ui| {
+8 -5
View File
@@ -57,7 +57,7 @@ pub mod screenshot;
pub mod state;
pub mod texel_guard;
pub mod theme;
pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn};
pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, MIN_WINDOW_SIZE, RenderIconFn};
pub(crate) mod tool_memory;
pub mod updates_ui;
pub mod widgets;
@@ -264,8 +264,8 @@ pub use services::{
AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn,
CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn,
ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox,
LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable,
RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PenScreenFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn,
Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
};
pub(crate) use services::{opaque_layer, saves_flat_in_place};
pub use text::bidi_text;
@@ -346,8 +346,8 @@ use widgets::tab_strip;
pub use widgets::text_field_menu;
pub use widgets::tone;
/// The Info panel's cached sample: pixel x, y, document revision and Eyedropper Sample Size.
type InfoSampleKey = (i32, i32, u64, u32);
/// The Info panel's cached sample: pixel x, y, document revision, Eyedropper Sample Size and the view zoom's bits.
type InfoSampleKey = (i32, i32, u64, u32, u32);
pub struct PhotocraftApp {
pub session: Session,
@@ -917,6 +917,9 @@ mod move_shift_click_tests;
#[cfg(test)]
mod move_target_default_tests;
#[cfg(test)]
mod wand_press_inside_selection_tests;
#[cfg(test)]
mod move_history_names_tests;
#[cfg(test)]
+8 -5
View File
@@ -7,19 +7,22 @@ pub(crate) fn hover_pixel(app: &PhotocraftApp) -> Option<(i32, i32)> {
}
/// The colour the Info panel reads at document pixel `(x, y)`, straight RGBA 0..1: averaged over
/// the Eyedropper's Sample Size, as in Photoshop (#1649), and cached per pixel and revision.
/// the Eyedropper's Sample Size over the box it reads at the view zoom, as in Photoshop (#1649,
/// #11751), and cached per pixel, revision, size and zoom.
pub(crate) fn pointer_sample(app: &mut PhotocraftApp, (x, y): (i32, i32)) -> Option<[f32; 4]> {
let rev = app.session.active()?.revision;
let sample_size = app.ui.tool_options.eyedropper_size;
if let Some(((cx, cy, cr, cs), v)) = app.info_sample
&& (cx, cy, cr, cs) == (x, y, rev, sample_size)
let zoom = app.current_zoom();
let key = (x, y, rev, sample_size, zoom.to_bits());
if let Some((k, v)) = app.info_sample
&& k == key
{
return Some(v);
}
let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size});
let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size, "zoom": f64::from(zoom)});
let v: Vec<f32> = serde_json::from_value(app.session.execute("document.sampleColor", params).ok()?).ok()?;
let v = [*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?];
app.info_sample = Some(((x, y, rev, sample_size), v));
app.info_sample = Some((key, v));
Some(v)
}
+1
View File
@@ -34,6 +34,7 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let gap = egui::Rect::from_x_y_ranges(gap_l.max(full.left())..=gap_r.min(full.right()).max(gap_l), full.y_range());
ui.ctx().data_mut(|d| d.insert_temp(crate::titlebar::modal_drag_area_id(), gap));
let drag = ui.interact(gap, ui.scope_id().with("titledrag"), Sense::click_and_drag());
crate::titlebar::follow_pen_drag(ui.ctx());
if drag.drag_started_by(egui::PointerButton::Primary) {
crate::titlebar::start_os_move(ui.ctx());
}
+195 -3
View File
@@ -10,7 +10,7 @@
//! Breeze's (KDE) or a plain round set elsewhere, with the set of buttons and their side taken
//! from the desktop's button layout. The shapes are drawn here, not read from the icon theme.
use egui::{Color32, CursorIcon, Id, LayerId, Order, PointerButton, Pos2, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2};
use egui::{Color32, CursorIcon, Id, LayerId, Order, PointerButton, Pos2, Rect, ResizeDirection, Sense, Stroke, Ui, Vec2, ViewportCommand, pos2, vec2};
use serde_json::json;
use crate::PhotocraftApp;
@@ -22,6 +22,9 @@ pub const BUTTON_WIDTH: f32 = 46.0;
/// (#1581); 8 pt is about a native resize border, and only trims the toolbar buttons' outer 3 pt.
const EDGE: f32 = 8.0;
const CORNER: f32 = 12.0;
/// The main window's minimum inner size (`apps/photocraft`'s viewport). A pen resize
/// ([`PenDrag`]) stops there, as the OS's own resize does.
pub const MIN_WINDOW_SIZE: Vec2 = vec2(760.0, 480.0);
const MODAL_DRAG_AREA: &str = "titlebar-modal-drag-area";
/// Breeze's Close button on hover and press (KDE's Breeze decoration colours).
const BREEZE_CLOSE_HOVER: Color32 = Color32::from_rgb(0xff, 0x98, 0xa2);
@@ -485,11 +488,198 @@ fn hand_off(ctx: &egui::Context) {
/// Move the window from this press. The window manager takes the press of an OS move as it does
/// that of a resize and keeps its release, so egui kept the drag: every other move failed, and a
/// resize right after one (#5725). The same hand-off ends it.
///
/// A pen or touch press moves the window itself instead ([`PenDrag`], #7967).
pub(crate) fn start_os_move(ctx: &egui::Context) {
if start_pen_drag(ctx, PenDragKind::Move) {
return;
}
ctx.send_viewport_cmd(ViewportCommand::StartDrag);
hand_off(ctx);
}
/// What a pen or touch press on the title bar or an edge does.
#[derive(Clone, Copy, Debug, PartialEq)]
enum PenDragKind {
Move,
Resize(ResizeDirection),
}
/// A window move or resize by a pen or a finger, done here rather than by the OS (#7967, #11840).
/// winit's `drag_window` / `drag_resize_window` post `WM_NCLBUTTONDOWN`, and Windows' move and
/// size loop follows the mouse button. winit takes pen and touch input as `WM_POINTER` messages
/// (`WindowEvent::Touch`) and Windows makes no mouse input from them, so the loop saw no button
/// down and never ran: the window stayed put. winit only clears its "dragging" flag when that loop
/// ends (`WM_EXITSIZEMOVE`), so after the first pen try it ignored every later `drag_window`,
/// the mouse's too, until restart. A pen press therefore never asks the OS: the window follows
/// the pen through `OuterPosition` / `InnerSize`, from where the pen is on the screen (the
/// window's inner rect plus the pointer), so moving the window under the pen changes nothing.
#[derive(Clone, Copy, Debug)]
struct PenDrag {
kind: PenDragKind,
/// The press in screen points, and the window's outer and inner rects then. `None` while a
/// maximized window restores before it moves.
start: Option<(Pos2, Rect, Rect)>,
/// Where the press was in the maximized window, as a fraction of its width and points from
/// its top: the restored window is placed so the pen holds it at the same spot.
grab: (f32, f32),
/// The last pass this was applied in, so the title bar and the edge zones can both call
/// [`follow_pen_drag`].
pass: u64,
/// The OS reports where the pen is on the screen ([`note_os_pointer`]): the drag follows that.
/// Otherwise it follows the window's inner rect plus the pointer, which can run ahead.
os: bool,
}
fn os_pointer_id() -> Id {
Id::unique("titlebar-os-pointer")
}
/// Read the pen's screen position from the OS for this pass while a pen or a finger is down. A
/// [`PenDrag`] follows that: winit moves the window asynchronously (`SWP_ASYNCWINDOWPOS`), so a
/// pointer position egui got before a move landed, added to the window position read after it,
/// counted the move twice, and the window ran away from the pen (an injected pen on Windows 11:
/// +687, +909 for a +200, +120 stroke). The pen's own pointer messages
/// (`Services::pen_screen_px`) say where it is; failing that the OS cursor
/// (`Services::cursor_pos`, relative to the window's inner rect, so the sum is the screen
/// position), which a pen doesn't always move. Call before the title bar and the edge zones.
pub(crate) fn note_os_pointer(app: &mut PhotocraftApp, ctx: &egui::Context) {
if !PEN_DRAG || !ctx.input(|i| i.any_touches()) {
return;
}
let pen = app.services.pen_screen_px.as_ref().and_then(|f| f()).map(|[x, y]| pos2(x as f32, y as f32) / ctx.pixels_per_point());
let cursor = || {
let inner = ctx.input(|i| i.viewport().inner_rect)?;
app.services.cursor_pos.as_mut().and_then(|f| f(ctx)).map(|at| inner.min + at.to_vec2())
};
let Some(at) = pen.or_else(cursor) else { return };
let pass = ctx.cumulative_pass_nr();
ctx.data_mut(|d| d.insert_temp(os_pointer_id(), (pass, at)));
}
/// The screen position [`note_os_pointer`] read this pass.
fn os_pointer(ctx: &egui::Context) -> Option<Pos2> {
let (pass, at) = ctx.data(|d| d.get_temp::<(u64, Pos2)>(os_pointer_id()))?;
(pass == ctx.cumulative_pass_nr()).then_some(at)
}
fn pen_drag_id() -> Id {
Id::unique("titlebar-pen-drag")
}
/// Only Windows needs it, and only Windows can place a window from the app everywhere (Wayland
/// lets no client place its window). Tests run it on every platform.
const PEN_DRAG: bool = cfg!(any(target_os = "windows", test));
/// Start a [`PenDrag`] if the press is a pen's or a finger's: true if it took the press.
fn start_pen_drag(ctx: &egui::Context, kind: PenDragKind) -> bool {
if !PEN_DRAG || !ctx.input(|i| i.any_touches()) {
return false;
}
let (inner, outer, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().outer_rect, i.viewport().maximized.unwrap_or(false)));
let (Some(inner), Some(outer), Some(press)) = (inner, outer, ctx.input(|i| i.pointer.press_origin().or(i.pointer.latest_pos()))) else {
return false;
};
let pass = ctx.cumulative_pass_nr();
// Trust the OS's position only if it is where the pointer is: a finger leaves the cursor
// behind.
let latest = ctx.input(|i| i.pointer.latest_pos()).unwrap_or(press);
let os_now = os_pointer(ctx).filter(|s| (*s - (inner.min + latest.to_vec2())).length() <= 8.0);
let os = os_now.is_some();
let drag = if maximized {
if kind != PenDragKind::Move {
return false;
}
ctx.send_viewport_cmd(ViewportCommand::Maximized(false));
PenDrag { kind, start: None, grab: (press.x / inner.width().max(1.0), press.y), pass, os }
} else {
let at = os_now.map_or(inner.min + press.to_vec2(), |s| s - (latest - press));
PenDrag { kind, start: Some((at, outer, inner)), grab: (0.0, 0.0), pass, os }
};
ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag));
true
}
/// Move or resize the window after the pen ([`PenDrag`]); ends with the press. Every pass, from
/// the title bar and the edge zones.
pub(crate) fn follow_pen_drag(ctx: &egui::Context) {
let Some(mut drag) = ctx.data(|d| d.get_temp::<PenDrag>(pen_drag_id())) else { return };
let pass = ctx.cumulative_pass_nr();
if drag.pass == pass {
return;
}
drag.pass = pass;
// The pen is down while egui has the press and a touch. egui's pointer can be gone meanwhile:
// the mouse cursor, parked where the window was, leaves the window as it moves away (winit's
// `CursorLeft`), which only matters when the drag goes by that pointer.
let (pos, down) = ctx.input(|i| (i.pointer.latest_pos(), i.pointer.primary_down() && i.any_touches()));
let (inner, outer, maximized) = ctx.input(|i| (i.viewport().inner_rect, i.viewport().outer_rect, i.viewport().maximized.unwrap_or(false)));
let end = |ctx: &egui::Context| ctx.data_mut(|d| d.remove::<PenDrag>(pen_drag_id()));
let (Some(inner), Some(outer), true) = (inner, outer, down) else { return end(ctx) };
let pen = if drag.os {
// No OS reading this pass (the service failed): wait for the next.
let Some(at) = os_pointer(ctx) else {
ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag));
return;
};
at
} else {
let Some(pos) = pos else { return end(ctx) };
inner.min + pos.to_vec2()
};
let Some((press, outer0, inner0)) = drag.start else {
// Restoring a maximized window: wait for its restored size, then put it under the pen.
if !maximized {
let at = pen - vec2(drag.grab.0 * inner.width(), drag.grab.1) - (inner.min - outer.min);
ctx.send_viewport_cmd(ViewportCommand::OuterPosition(at));
let shift = at - outer.min;
drag.start = Some((pen, outer.translate(shift), inner.translate(shift)));
}
ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag));
return;
};
let d = pen - press;
match drag.kind {
PenDragKind::Move => {
let at = outer0.min + d;
if at != outer.min {
ctx.send_viewport_cmd(ViewportCommand::OuterPosition(at));
}
}
PenDragKind::Resize(dir) => {
let r = resized(inner0, dir, d, MIN_WINDOW_SIZE);
if r.size() != inner.size() {
ctx.send_viewport_cmd(ViewportCommand::InnerSize(r.size()));
}
let at = outer0.min + (r.min - inner0.min);
if at != outer.min {
ctx.send_viewport_cmd(ViewportCommand::OuterPosition(at));
}
}
}
ctx.data_mut(|d| d.insert_temp(pen_drag_id(), drag));
}
/// `r` with the edges `dir` names moved by `d`, no smaller than `min`: a left or top edge stops
/// where the window would be too small rather than pushing it along.
fn resized(r: Rect, dir: ResizeDirection, d: Vec2, min: Vec2) -> Rect {
use ResizeDirection::*;
let mut r = r;
if matches!(dir, West | NorthWest | SouthWest) {
r.min.x = (r.min.x + d.x).min(r.max.x - min.x);
}
if matches!(dir, East | NorthEast | SouthEast) {
r.max.x = (r.max.x + d.x).max(r.min.x + min.x);
}
if matches!(dir, North | NorthWest | NorthEast) {
r.min.y = (r.min.y + d.y).min(r.max.y - min.y);
}
if matches!(dir, South | SouthWest | SouthEast) {
r.max.y = (r.max.y + d.y).max(r.min.y + min.y);
}
r
}
/// The compositor takes the button release of an OS resize or move (KDE Wayland, KWin on X11), so
/// egui kept the edge pressed: the zones stopped hovering until the next click, every other resize
/// (#1581, and #5725 for moves). End the press ourselves on the input after the hand-off, but only
@@ -525,9 +715,11 @@ fn reshow_cursor_after_os_resize(ctx: &egui::Context) {
}
/// Invisible resize zones along the window's edges, above everything else; a press in one starts
/// an OS resize in that direction. None while the window is maximized or full screen.
/// an OS resize in that direction (a pen's or a finger's: a [`PenDrag`]). None while the window
/// is maximized or full screen.
pub fn resize_zones(ui: &mut Ui) {
let ctx = ui.ctx().clone();
follow_pen_drag(&ctx);
if maximized(&ctx) || ctx.input(|i| i.viewport().fullscreen.unwrap_or(false)) {
reshow_cursor_after_os_resize(&ctx);
return;
@@ -537,7 +729,7 @@ pub fn resize_zones(ui: &mut Ui) {
let zui = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(w));
for (i, (r, dir, cursor)) in zones(w).into_iter().enumerate() {
let resp = zui.interact(r, Id::unique(("titlebar-resize", i)), Sense::drag()).on_hover_cursor(cursor);
if resp.drag_started_by(PointerButton::Primary) {
if resp.drag_started_by(PointerButton::Primary) && !start_pen_drag(&ctx, PenDragKind::Resize(dir)) {
ctx.send_viewport_cmd(ViewportCommand::BeginResize(dir));
hand_off(&ctx);
}
+219 -3
View File
@@ -1,5 +1,5 @@
use super::*;
use egui::{Event, Pos2, RawInput, ViewportId};
use egui::{Event, Pos2, RawInput, Vec2, ViewportId};
use photocraft_engine::Session;
/// #5826: the drag overlay under a dialog doesn't depend on the custom title bar. On macOS
@@ -24,8 +24,22 @@ struct Win {
ctx: egui::Context,
app: PhotocraftApp,
width: f32,
height: f32,
/// Where the window's content is on the screen, and its outer rect's offset from that.
at: Pos2,
frame_offset: Vec2,
time: f64,
maximized: bool,
/// Windows moves the window asynchronously: with `lag`, the pointer positions of a frame are
/// relative to where the window was before the previous frame's commands, while the viewport
/// already reports where it is now.
lag: bool,
before_move: Pos2,
/// The OS cursor on the screen, when it follows the pen (`Services::cursor_pos`).
cursor: std::rc::Rc<std::cell::Cell<Option<Pos2>>>,
cursor_follows: bool,
/// A pen frame, by its index in the path, where egui's pointer also leaves the window.
pointer_gone_at: Option<usize>,
}
impl Win {
@@ -34,7 +48,30 @@ impl Win {
PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);
let mut app = PhotocraftApp::new(Session::new(), crate::Services::default());
app.custom_titlebar = true;
Self { ctx, app, width, time: 0.0, maximized: false }
let at = pos2(200.0, 100.0);
Self {
ctx,
app,
width,
height: 600.0,
at,
frame_offset: vec2(-7.0, 0.0),
time: 0.0,
maximized: false,
lag: false,
before_move: at,
cursor: Default::default(),
cursor_follows: true,
pointer_gone_at: None,
}
}
/// The OS cursor follows the pen, as Windows Ink moves it: `Services::cursor_pos` reports it
/// relative to the window's client area.
fn with_os_cursor(mut self) -> Self {
let cursor = self.cursor.clone();
self.app.services.cursor_pos = Some(Box::new(move |ctx: &egui::Context| Some(cursor.get()? - ctx.input(|i| i.viewport().inner_rect)?.min.to_vec2())));
self
}
fn frame(&mut self, events: Vec<Event>) -> egui::FullOutput {
@@ -44,14 +81,19 @@ impl Win {
fn frame_with_modal(&mut self, events: Vec<Event>, modal: bool) -> egui::FullOutput {
self.time += 0.05;
let mut input =
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), time: Some(self.time), events, ..Default::default() };
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, self.height))), time: Some(self.time), events, ..Default::default() };
if let Some(v) = input.viewports.get_mut(&ViewportId::ROOT) {
v.maximized = Some(self.maximized);
let inner = Rect::from_min_size(self.at, vec2(self.width, self.height));
v.inner_rect = Some(inner);
v.outer_rect = Some(Rect::from_min_max(inner.min + self.frame_offset, inner.max - self.frame_offset));
}
// What `PhotocraftApp::raw_input_hook` does.
release_after_os_resize(&self.ctx, &mut input);
let app = &mut self.app;
let mut out = self.ctx.run_ui(input, |ui| {
// What `ui_body` does first.
note_os_pointer(app, ui.ctx());
crate::panels::title_bar(app, ui);
if modal {
egui::Modal::new(Id::unique("titlebar-drag-test-modal")).backdrop_color(Color32::TRANSPARENT).show(ui.ctx(), |ui| {
@@ -85,6 +127,57 @@ impl Win {
.collect()
}
/// A pen stroke along `path`, in screen points, as winit and egui-winit deliver it on Windows:
/// `Touch` events with an emulated pointer at the pen's spot in the window. The window obeys
/// the move, size and restore commands the frames send, as the OS would, so a window that
/// moves under the pen moves the pen's spot in it. The commands the frames sent.
fn pen(&mut self, path: &[Pos2]) -> Vec<ViewportCommand> {
let touch = |phase, pos| Event::Touch { device_id: egui::TouchDeviceId(7), id: egui::TouchId(1), phase, pos, force: Some(0.5) };
let mut all = vec![];
let last = path.len() - 1;
// The pen hovers first: winit reports that as touch moves, egui-winit as pointer moves.
let hover = path[0] - self.at.to_vec2();
all.extend(self.obey(vec![Event::PointerMoved(hover)]));
for (i, p) in path.iter().enumerate() {
if self.cursor_follows {
self.cursor.set(Some(*p));
}
let local = *p - if self.lag { self.before_move } else { self.at }.to_vec2();
let events = match i {
0 => vec![touch(egui::TouchPhase::Start, local), Event::PointerMoved(local), button(local, true, egui::PointerButton::Primary)],
_ => vec![touch(egui::TouchPhase::Move, local), Event::PointerMoved(local)],
};
let mut events = events;
if self.pointer_gone_at == Some(i) {
events.push(Event::PointerGone);
}
all.extend(self.obey(events));
if i == last {
let events = vec![touch(egui::TouchPhase::End, local), button(local, false, egui::PointerButton::Primary), Event::PointerGone];
all.extend(self.obey(events));
}
}
all
}
/// One frame; the window then moves, resizes and restores as its commands say.
fn obey(&mut self, events: Vec<Event>) -> Vec<ViewportCommand> {
let cmds = self.frame(events).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default();
self.before_move = self.at;
for c in &cmds {
match c {
ViewportCommand::OuterPosition(p) => self.at = *p - self.frame_offset,
ViewportCommand::InnerSize(s) => (self.width, self.height) = (s.x, s.y),
ViewportCommand::Maximized(false) => {
self.maximized = false;
(self.at, self.width, self.height) = (pos2(300.0, 200.0), 1000.0, 700.0);
}
_ => {}
}
}
cmds
}
fn click(&mut self, p: Pos2) -> Vec<ViewportCommand> {
self.gesture(&[p])
}
@@ -489,3 +582,126 @@ fn theme_icons_are_cached_and_fall_back() {
out.textures_delta.clear();
assert_eq!(calls.load(Ordering::Relaxed), 3, "each icon and size rendered once; absurd sizes never");
}
/// #7967, #11840: a pen on the title bar's gap moves the window itself. Windows' move loop follows
/// the mouse button, which a pen never presses (winit reads it as `WM_POINTER`), and winit's
/// unfinished `drag_window` then stopped the mouse moving the window too.
#[test]
fn a_pen_moves_the_window_and_the_mouse_still_can_after() {
let mut w = Win::new(1440.0);
w.frame(vec![]);
let empty = pos2(980.0, 16.0);
assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space");
let start = w.at;
let on_screen = start + empty.to_vec2();
let path: Vec<Pos2> = (0..=10).map(|i| on_screen + vec2(-30.0, 12.0) * i as f32).collect();
let cmds = w.pen(&path);
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag | ViewportCommand::BeginResize(_))), "no OS move for a pen: {cmds:?}");
assert_eq!(w.at, start + vec2(-300.0, 120.0), "the window followed the pen: {cmds:?}");
// Lifting the pen ends it: a move of the pointer moves nothing.
let cmds = w.obey(vec![Event::PointerMoved(pos2(500.0, 300.0))]);
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::OuterPosition(_))), "{cmds:?}");
// The mouse still hands the move to the OS.
let cmds = w.gesture(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]);
assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}");
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::OuterPosition(_))), "{cmds:?}");
}
/// A pen on an edge or a corner resizes the window itself, down to the minimum size, the left
/// and top edges without pushing the window along once it is that small.
#[test]
fn a_pen_resizes_the_window_from_its_edges() {
let mut w = Win::new(1000.0);
w.frame(vec![]);
let screen = |w: &Win, p: Pos2| w.at + p.to_vec2();
// South-east corner: 60 wider, 40 taller.
let p = screen(&w, pos2(998.0, 598.0));
let cmds = w.pen(&[p, p + vec2(30.0, 20.0), p + vec2(60.0, 40.0)]);
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}");
assert_eq!((w.width, w.height), (1060.0, 640.0));
let at = w.at;
// West edge, 100 in: the window narrows and its left edge follows the pen.
let p = screen(&w, pos2(2.0, 300.0));
w.pen(&[p, p + vec2(50.0, 0.0), p + vec2(100.0, 0.0)]);
assert_eq!((w.width, w.at), (960.0, at + vec2(100.0, 0.0)));
// North edge, far down: stops at the minimum height with the bottom edge kept.
let bottom = w.at.y + w.height;
let p = screen(&w, pos2(480.0, 1.0));
w.pen(&[p, p + vec2(0.0, 200.0), p + vec2(0.0, 900.0)]);
assert_eq!((w.height, w.at.y + w.height), (MIN_WINDOW_SIZE.y, bottom));
// The mouse still resizes through the OS.
let cmds = w.gesture(&[pos2(1.0, 300.0), pos2(8.0, 300.0)]);
assert_eq!(cmds, vec![ViewportCommand::BeginResize(ResizeDirection::West)]);
}
/// A pen dragging a maximized window's title bar restores it and carries it, held where the pen
/// took it, as Windows does for the mouse.
#[test]
fn a_pen_drags_a_maximized_window_out_restored() {
let mut w = Win::new(1920.0);
w.maximized = true;
w.at = Pos2::ZERO;
w.frame(vec![]);
let grab = pos2(1200.0, 16.0);
assert!(w.bar_widgets().iter().all(|r| !r.contains(grab)), "the probe point must be empty bar space");
let path: Vec<Pos2> = (0..=6).map(|i| grab + vec2(10.0, 20.0) * i as f32).collect();
let cmds = w.pen(&path);
assert!(cmds.contains(&ViewportCommand::Maximized(false)), "{cmds:?}");
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}");
let pen = *path.last().unwrap();
let held = pen - w.at;
assert!((held.x - 1000.0 * 1200.0 / 1920.0).abs() < 0.01 && (held.y - 16.0).abs() < 0.01, "held at {held:?}, window at {:?}", w.at);
}
/// Windows moves the window asynchronously, so a frame's pointer positions can be relative to
/// where the window was before the last move: added to where it is now they counted that move
/// twice, and the window ran away from the pen (seen with an injected pen on Windows 11: +477,
/// +783 for a +200, +120 stroke). With the OS cursor following the pen, the window follows the
/// cursor's screen position instead and lands exactly under the pen.
#[test]
fn a_pen_move_follows_the_os_cursor_when_the_window_moves_late() {
let stroke = |w: &mut Win| {
w.lag = true;
w.frame(vec![]);
let start = w.at;
let on_screen = start + pos2(980.0, 16.0).to_vec2();
let path: Vec<Pos2> = (0..=10).map(|i| on_screen + vec2(20.0, 12.0) * i as f32).collect();
w.pen(&path);
w.at - start
};
assert_eq!(stroke(&mut Win::new(1440.0).with_os_cursor()), vec2(200.0, 120.0));
// Without the cursor the window can only go by egui's positions: it overshoots.
let moved = stroke(&mut Win::new(1440.0));
assert!(moved.x > 200.0 && moved.y > 120.0, "{moved:?}");
}
/// A finger leaves the OS cursor behind: a cursor that isn't where the pointer is isn't followed.
#[test]
fn a_cursor_away_from_the_pen_is_not_followed() {
let mut w = Win::new(1440.0).with_os_cursor();
w.cursor_follows = false;
w.cursor.set(Some(pos2(5.0, 5.0)));
w.frame(vec![]);
let start = w.at;
let on_screen = start + pos2(980.0, 16.0).to_vec2();
let path: Vec<Pos2> = (0..=10).map(|i| on_screen + vec2(-30.0, 12.0) * i as f32).collect();
w.pen(&path);
assert_eq!(w.at, start + vec2(-300.0, 120.0));
}
/// The mouse cursor, parked where the pen took the window, can end up outside the window as it
/// moves away: winit reports the mouse leaving, and egui's pointer is gone for the rest of the
/// stroke. Seen on Windows 11 after a mouse move: the pen move stopped after 2 of 20 steps. The
/// drag follows the pen's own position, so it carries on.
#[test]
fn a_pen_move_survives_the_mouse_pointer_leaving_the_window() {
let mut w = Win::new(1440.0).with_os_cursor();
w.lag = true;
w.pointer_gone_at = Some(3);
w.frame(vec![]);
let start = w.at;
let on_screen = start + pos2(980.0, 16.0).to_vec2();
let path: Vec<Pos2> = (0..=10).map(|i| on_screen + vec2(20.0, 12.0) * i as f32).collect();
w.pen(&path);
assert_eq!(w.at - start, vec2(200.0, 120.0));
}
+6
View File
@@ -477,6 +477,9 @@ pub type CaptionStyleFn = Box<dyn Fn(&egui::Context) -> CaptionStyle>;
/// Physical right mouse button or stylus barrel button down (Windows; read for brush resize).
pub type RightButtonDownFn = Box<dyn Fn() -> bool + Send + Sync>;
/// Where the pen in range is on the screen, in physical pixels ([`Services::pen_screen_px`]).
pub type PenScreenFn = Box<dyn Fn() -> Option<[i32; 2]> + Send + Sync>;
/// Which end of the pen is in use, `Some(true)` = eraser, `None` = no pen ([`Services::pen_end`]).
pub type PenEndFn = Box<dyn Fn() -> Option<bool> + Send + Sync>;
@@ -616,6 +619,9 @@ pub struct Services {
/// Which end of the pen is in use, where the platform reports it outside the stylus feed
/// (Windows: the feed carries no pen samples there). Read for the eraser-end tool switch.
pub pen_end: Option<PenEndFn>,
/// Where the pen is on the screen, independent of where the window is (Windows: the pen's
/// pointer messages). A pen moving the window by its title bar follows it (`titlebar`).
pub pen_screen_px: Option<PenScreenFn>,
/// WinTab packet poll (Windows with Windows Ink disabled; see `photocraft_tablet::wintab`).
pub tablet_poll: Option<TabletPollFn>,
/// The persistent brush preset store, loading in the background (desktop; see
@@ -0,0 +1,95 @@
//! #12952: when the Sharpen tool can't work on the layer (hidden target layer, Lock All, Lock Image
//! Pixels, a group's pixels), a press opens the reference application's alert with OK and changes
//! nothing; Lock transparent pixels still sharpens. The Brush keeps its alerts, the Dodge tool its
//! colour-mode alert only.
use serde_json::json;
use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke};
use super::*;
use crate::control::{ControlRequest, Outcome, handle};
#[test]
fn a_hidden_target_layer() {
let mut app = app(Tool::Sharpen);
let id = active(&app);
app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
refused(&mut app, "Could not use the sharpen tool because the target layer is hidden.");
assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status);
}
#[test]
fn lock_all_and_lock_image_pixels() {
for lock in ["all", "pixels"] {
let mut app = app(Tool::Sharpen);
app.run("layer.lockLayers", json!({ lock: true })).unwrap();
refused(&mut app, "Could not use the sharpen tool because the layer is locked.");
}
}
#[test]
fn a_group_is_active() {
let mut app = app(Tool::Sharpen);
app.run("layer.new.group", json!({})).unwrap();
refused(&mut app, "Could not use the sharpen tool because the pixels in a group cannot be edited without merging the group.");
}
#[test]
fn the_alert_is_listed_and_confirmed_over_the_control_channel() {
let ctx = egui::Context::default();
let mut app = app(Tool::Sharpen);
app.run("layer.lockLayers", json!({"pixels": true})).unwrap();
stroke(&mut app);
let mut call = |method: &str, params: serde_json::Value| {
let (req, _rx) = ControlRequest::new(method, params);
match handle(&mut app, &ctx, &req) {
Outcome::Done(v) => v,
_ => panic!("{method}: expected an immediate reply"),
}
};
let inspect = call("ui.inspect", json!({}));
let dialog = &inspect["result"]["dialogs"][0];
assert_eq!(dialog["fields"]["message"], "Could not use the sharpen tool because the layer is locked.", "{inspect}");
assert_eq!(call("ui.dialog.confirm", json!({"dialog": dialog["id"]}))["ok"], true);
assert!(alerts(&app).is_empty());
}
#[test]
fn lock_transparent_pixels_still_sharpens() {
let mut app = app(Tool::Sharpen);
app.run("layer.lockLayers", json!({"transparency": true})).unwrap();
let before = steps(&app);
stroke(&mut app);
assert!(alerts(&app).is_empty());
assert_eq!(steps(&app), before + 1, "the stroke was applied");
}
#[test]
fn the_colour_mode_alert_comes_first() {
// A hidden layer in an Indexed Color document: the mode alert, as before this change.
let mut app = app(Tool::Sharpen);
app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
let id = active(&app);
app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
refused(&mut app, "Could not use the sharpen tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit).");
}
#[test]
fn the_brush_and_the_dodge_tool_keep_todays_behaviour() {
// The Brush: no alert for Lock Image Pixels.
let mut app = app(Tool::Brush);
app.run("layer.lockLayers", json!({"pixels": true})).unwrap();
stroke(&mut app);
assert!(alerts(&app).is_empty());
// The Dodge tool in an RGB document: no layer alerts, the status bar says a hidden target.
let mut app = self::app(Tool::Dodge);
let id = active(&app);
app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
stroke(&mut app);
assert!(alerts(&app).is_empty());
assert_eq!(app.ui.status, photocraft_engine::hidden_target::HIDDEN);
let mut app = self::app(Tool::Dodge);
app.run("layer.lockLayers", json!({"all": true})).unwrap();
assert_eq!(alert(&app, Tool::Dodge, false), None);
assert_eq!(tool_name(Tool::Dodge), None);
}
@@ -0,0 +1,190 @@
//! #12976: the Sponge options bar has a Flow field after Mode (default 50 %, whole numbers 1..100,
//! the reference's "Closest value inserted" alert for a value typed past the range, a slider
//! arrow), Reset Tool puts it back to 50 %, and a Sponge stroke passes it to `paint.sponge` as `flow`.
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::eraser_ui::TOLERANCE_RANGE_ALERT;
use crate::state::{DialogKind, Tool, ToolOptions};
fn bar() -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.ui.tool = Tool::Sponge;
let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
h
}
fn flow_field<'a>(h: &'a Harness<'static, PhotocraftApp>) -> egui_kittest::Node<'a> {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Flow:")).expect("the Flow field")
}
/// Types `text` into Flow, then Tabs out of it.
fn type_flow(h: &mut Harness<'static, PhotocraftApp>, text: &str) {
flow_field(h).click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(3);
}
fn flow(h: &Harness<'static, PhotocraftApp>) -> f32 {
h.state().ui.tool_options.sponge_flow
}
fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec<String> {
h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect()
}
fn click_at(h: &mut Harness<'static, PhotocraftApp>, p: egui::Pos2) {
h.hover_at(p);
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(3);
}
#[test]
fn the_sponge_bar_shows_flow_after_mode_at_50_percent() {
let h = bar();
assert_eq!(ToolOptions::default().sponge_flow, 50.0, "fresh settings");
let field = flow_field(&h);
assert_eq!(field.accesskit_node().numeric_value(), Some(50.0));
let mode = h.query_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some("Mode:")).expect("the Mode dropdown").rect();
let vibrance = h.get_by_role_and_label(Role::CheckBox, "Vibrance").rect();
let field = field.rect();
assert!(mode.right() <= field.left(), "Flow comes after Mode: {mode:?} {field:?}");
assert!(field.right() <= vibrance.left(), "and before Vibrance: {field:?} {vibrance:?}");
}
#[test]
fn settings_saved_before_the_field_load_with_flow_at_50() {
let mut saved = serde_json::to_value(ToolOptions::default()).unwrap();
saved.as_object_mut().unwrap().remove("sponge_flow").expect("the field is saved");
let loaded: ToolOptions = serde_json::from_value(saved).unwrap();
assert_eq!(loaded.sponge_flow, 50.0);
}
#[test]
fn reset_tool_puts_flow_back_to_50() {
let mut o = ToolOptions { sponge_flow: 12.0, ..Default::default() };
crate::tool_reset::reset_options(&mut o, Tool::Sponge);
assert_eq!(o.sponge_flow, 50.0);
assert!(crate::tool_reset::option_keys(Tool::Sponge).contains(&"sponge_flow"), "a Sponge preset stores it too");
}
#[test]
fn flow_typed_past_the_range_takes_the_closest_value_and_alerts() {
for (typed, want) in [("0", 1.0), ("150", 100.0)] {
let mut h = bar();
type_flow(&mut h, typed);
assert_eq!(flow(&h), want, "{typed}");
assert_eq!(alerts(&h), vec![TOLERANCE_RANGE_ALERT.to_string()], "{typed}: one alert");
let id = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).expect("an alert");
crate::dialogs::confirm(h.state_mut(), id).unwrap();
h.run_steps(3);
assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert");
assert_eq!(flow(&h), want, "{typed}: the closest value is kept");
}
}
#[test]
fn flow_in_range_is_stored_as_a_whole_number_without_an_alert() {
for (typed, want) in [("33.7", 34.0), ("1", 1.0), ("100", 100.0), ("72", 72.0)] {
let mut h = bar();
type_flow(&mut h, typed);
assert_eq!(flow(&h), want, "{typed}");
assert!(alerts(&h).is_empty(), "{typed} is in range");
}
}
#[test]
fn flow_that_is_no_number_keeps_the_value_without_an_alert() {
let mut h = bar();
type_flow(&mut h, "abc");
assert_eq!(flow(&h), 50.0, "the previous value stays");
assert!(alerts(&h).is_empty(), "no number, no alert");
}
#[test]
fn the_arrow_opens_a_slider_from_1_to_100() {
let mut h = bar();
assert!(h.query_all_by_role(Role::Slider).next().is_none(), "the slider stays closed");
h.get_by_role_and_label(Role::Button, "Flow").click();
h.run_steps(4);
let slider = h.get_by_role_and_label(Role::Slider, "Flow").rect();
click_at(&mut h, egui::pos2(slider.right() - 3.0, slider.center().y));
assert_eq!(flow(&h), 100.0, "the slider's far end");
click_at(&mut h, egui::pos2(slider.left() + 3.0, slider.center().y));
assert_eq!(flow(&h), 1.0, "the slider's near end");
click_at(&mut h, slider.center());
assert_eq!(flow(&h).fract(), 0.0, "the slider gives whole numbers");
assert!((2.0..=99.0).contains(&flow(&h)), "between the ends: {}", flow(&h));
assert!(alerts(&h).is_empty(), "the slider does not alert");
}
/// An 80 px document filled with red 200,40,40 and a 40 px hard tip.
fn red_app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.run("paint.pencil", json!({"points": [[40, 40]], "size": 400, "color": "#c82828"})).unwrap();
app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0}})).unwrap();
app
}
fn pixel(app: &PhotocraftApp) -> [f32; 4] {
let st = app.session.active().unwrap();
st.active_layer.and_then(|id| st.doc.layer(id)).unwrap().surface().unwrap().rgba(40, 40)
}
#[test]
fn a_sponge_click_uses_the_bar_flow() {
let untouched = pixel(&red_app());
let mut seen = Vec::new();
for f in [10.0, 50.0, 100.0] {
let mut clicked = red_app();
clicked.ui.tool = Tool::Sponge;
clicked.ui.tool_options.sponge_mode = "desaturate".into();
clicked.ui.tool_options.vibrance = true;
clicked.ui.tool_options.sponge_flow = f;
let m = egui::Modifiers::NONE;
tool_event(&mut clicked, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, m);
tool_event(&mut clicked, ToolEvent::Up { x: 40.0, y: 40.0 }, m);
assert!(!clicked.ui.status_error, "{f}: {}", clicked.ui.status);
let (cmd, params) = clicked.session.journal.last().unwrap().clone();
assert_eq!(cmd, "paint.sponge");
assert_eq!(params["flow"], json!(f), "the stroke records the bar's flow");
let mut command = red_app();
command
.run("paint.sponge", json!({"points": [[40.0, 40.0, 1.0]], "size": 40, "hardness": 100, "mode": "desaturate", "vibrance": true, "flow": f}))
.unwrap();
assert_eq!(pixel(&clicked), pixel(&command), "flow {f}: the click paints what paint.sponge does");
seen.push(pixel(&clicked));
}
// The flow reaches the stroke: without it every click painted at the command's default of 100 %.
assert_ne!(seen[2], untouched, "a click at 100 % desaturates");
assert_ne!(seen[0], seen[2], "10 % and 100 % give different pixels: {seen:?}");
}
#[test]
fn a_restored_fraction_paints_the_whole_number_the_bar_shows() {
let mut app = red_app();
app.ui.tool_options.sponge_flow = 33.7;
let (cmd, params) = crate::retouch_ui::dab_params(&app, Tool::Sponge).unwrap();
assert_eq!(cmd, "paint.sponge");
assert_eq!(params["flow"], json!(34.0));
app.ui.tool_options.sponge_flow = 0.0;
assert_eq!(crate::retouch_ui::dab_params(&app, Tool::Sponge).unwrap().1["flow"], json!(1.0));
}
+4
View File
@@ -84,6 +84,9 @@ pub struct ToolOptions {
pub protect_tones: bool,
/// Sponge: desaturate | saturate, vibrance.
pub sponge_mode: String,
/// Sponge: Flow %, whole numbers 1..100 (#12976). Settings saved before it load as 50.
#[serde(default = "fifty")]
pub sponge_flow: f32,
pub vibrance: bool,
/// Blur/Sharpen/Smudge strength %, Sharpen protect detail, Smudge finger painting.
pub strength: f32,
@@ -482,6 +485,7 @@ impl Default for ToolOptions {
exposure: 50.0,
protect_tones: true,
sponge_mode: "desaturate".into(),
sponge_flow: 50.0,
vibrance: true,
strength: 50.0,
protect_detail: true,
@@ -0,0 +1,71 @@
//! #11980: a plain click with the Ruler leaves the current ruler alone; a drag still replaces it.
use super::{PhotocraftApp, Ruler, Tool, ToolEvent, json};
/// A 600 × 400 document with the Ruler from 100,100 to 300,250 and the Ruler tool active.
fn ruler_app(protractor: Option<[f64; 2]>) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
app.run("image.analysis.rulerTool", json!({"start": [100, 100], "end": [300, 250], "protractor": protractor})).unwrap();
app.ui.tool = Tool::Ruler;
app
}
fn ruler(app: &PhotocraftApp) -> Option<Ruler> {
app.session.active().unwrap().doc.measurement.ruler
}
fn history(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.past_len()
}
/// A press at `from` and a release at `to`, moving between them when they differ.
fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) {
crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE);
if [x, y] != [end_x, end_y] {
crate::canvas::tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, egui::Modifiers::NONE);
}
crate::canvas::tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, egui::Modifiers::NONE);
}
#[test]
fn a_click_away_from_the_ruler_keeps_it() {
for protractor in [None, Some([150.0, 50.0])] {
let mut app = ruler_app(protractor);
let before = ruler(&app);
let steps = history(&app);
gesture(&mut app, [500.0, 350.0], [500.0, 350.0]);
assert_eq!(ruler(&app), before, "protractor {protractor:?}");
assert_eq!(history(&app), steps);
}
}
#[test]
fn a_click_on_an_end_point_keeps_the_ruler() {
let mut app = ruler_app(None);
let before = ruler(&app);
let steps = history(&app);
gesture(&mut app, [300.0, 250.0], [300.0, 250.0]);
gesture(&mut app, [100.0, 100.0], [100.0, 100.0]);
assert_eq!(ruler(&app), before);
assert_eq!(history(&app), steps);
}
#[test]
fn a_drag_away_from_the_ruler_replaces_it() {
let mut app = ruler_app(Some([150.0, 50.0]));
let steps = history(&app);
gesture(&mut app, [400.0, 300.0], [550.0, 320.0]);
assert_eq!(ruler(&app), Some(Ruler { start: [400.0, 300.0], end: [550.0, 320.0], protractor: None }));
assert_eq!(history(&app), steps);
}
/// Not measured, so as today: a click with no ruler yet leaves none.
#[test]
fn a_click_with_no_ruler_leaves_none() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
app.ui.tool = Tool::Ruler;
gesture(&mut app, [500.0, 350.0], [500.0, 350.0]);
assert_eq!(ruler(&app), None);
}
+26 -7
View File
@@ -25,8 +25,8 @@ use crate::theme::Tokens;
/// What a pointer drag is doing (not serialised).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Drag {
/// New ruler line from a point.
RulerNew,
/// New ruler line from a point; the ruler it replaces comes back if the press doesn't move (#11980).
RulerNew(Option<Ruler>),
/// Moving a ruler handle: 0 start, 1 end, 2 protractor end.
RulerHandle(u8),
/// Moving count marker (group, index) from where it was.
@@ -247,6 +247,10 @@ fn set_ruler(app: &mut PhotocraftApp, r: Ruler) {
let _ = app.run("image.analysis.rulerTool", json!({"start": r.start, "end": r.end, "protractor": r.protractor}));
}
#[cfg(test)]
#[path = "analysis_ruler_click_tests.rs"]
mod analysis_ruler_click_tests;
#[cfg(test)]
#[path = "note_show_on_new_tests.rs"]
mod note_show_on_new_tests;
@@ -300,14 +304,14 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) ->
Some(r) if near(r.start) => app.ui.analysis.drag = Some(Drag::RulerHandle(0)),
_ => {
set_ruler(app, Ruler { start: p, end: p, protractor: None });
app.ui.analysis.drag = Some(Drag::RulerNew);
app.ui.analysis.drag = Some(Drag::RulerNew(cur));
}
}
}
(Tool::Ruler, ToolEvent::Move { x, y, .. }) => {
let (Some(drag), Some(mut r)) = (app.ui.analysis.drag, doc.measurement.ruler) else { return true };
match drag {
Drag::RulerNew | Drag::RulerHandle(1) => r.end = constrain(r.start, [x, y], mods.shift),
Drag::RulerNew(_) | Drag::RulerHandle(1) => r.end = constrain(r.start, [x, y], mods.shift),
Drag::RulerHandle(0) => r.start = constrain(r.end, [x, y], mods.shift),
Drag::RulerHandle(_) => r.protractor = Some(constrain(r.start, [x, y], mods.shift)),
_ => return true,
@@ -316,8 +320,16 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) ->
}
(Tool::Ruler, ToolEvent::Up { .. }) => {
let drag = app.ui.analysis.drag.take();
if drag == Some(Drag::RulerNew) && doc.measurement.ruler.is_some_and(|r| dist(r.start, r.end) < 0.5) {
let _ = app.run("image.analysis.rulerTool", json!({"clear": true}));
if let Some(Drag::RulerNew(before)) = drag
&& doc.measurement.ruler.is_some_and(|r| dist(r.start, r.end) < 0.5)
{
// A click leaves the ruler that was there; with none, it leaves none.
match before {
Some(r) => set_ruler(app, r),
None => {
let _ = app.run("image.analysis.rulerTool", json!({"clear": true}));
}
}
}
}
(Tool::Count, ToolEvent::Down { x, y, .. }) => {
@@ -429,6 +441,13 @@ fn status_on_err(app: &mut PhotocraftApp, r: Result<Value, String>) {
}
}
/// The count marker a Count tool click at document point `at` would grab (the click's own hit
/// test, with its tolerance), or `None`. The cursor uses it too, so it never says "1" where a click
/// adds a marker (#11773).
pub(crate) fn count_marker_at(app: &PhotocraftApp, at: [f64; 2]) -> Option<(usize, usize)> {
nearest_marker(&app.session.active()?.doc, at, tolerance(app))
}
fn nearest_marker(d: &Document, at: [f64; 2], tol: f64) -> Option<(usize, usize)> {
let mut best: Option<(f64, usize, usize)> = None;
for (gi, g) in d.measurement.count_groups.iter().enumerate().filter(|(_, g)| g.visible) {
@@ -1183,7 +1202,7 @@ pub fn note_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
// Escape during a Ruler drag (a new ruler or an end) ends it and keeps the ruler where it is:
// no cancel, and the later moves and the release change nothing (#11986).
if app.ui.tool == Tool::Ruler
&& matches!(app.ui.analysis.drag, Some(Drag::RulerNew | Drag::RulerHandle(0 | 1)))
&& matches!(app.ui.analysis.drag, Some(Drag::RulerNew(_) | Drag::RulerHandle(0 | 1)))
&& ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
{
app.ui.analysis.drag = None;
@@ -92,9 +92,12 @@ fn ruler_drag_protractor_and_clear() {
up(&mut app, 60.0, 10.0);
let info = photocraft_engine::analysis_cmds::ruler_info(&ruler(&app).unwrap(), &Default::default());
assert!((info["angle"].as_f64().unwrap() - 90.0).abs() < 1e-6, "{info}");
// A click without a drag far away starts a new line and clears it.
// A click without a drag far away keeps the ruler (#11980); Clear removes it.
let before = ruler(&app);
down(&mut app, 150.0, 80.0, none);
up(&mut app, 150.0, 80.0);
assert_eq!(ruler(&app), before);
app.run("image.analysis.rulerTool", json!({"clear": true})).unwrap();
assert!(ruler(&app).is_none());
assert_eq!(app.session.active().unwrap().history.past_len(), 0, "the ruler adds no history");
}
+24 -11
View File
@@ -19,8 +19,8 @@ pub const INDEXED: &str = "Could not use the {tool} because it does not work wit
pub const BITMAP: &str = "Could not use the {tool} because it does not work with Bitmap images (convert image to Grayscale mode to edit).";
/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge
/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for these tools
/// yet (#12685, #12952).
/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for the Dodge
/// tool yet (#12685).
fn mode_tool_name(tool: Tool) -> Option<&'static str> {
match tool {
Tool::Dodge => Some(tl!("dodge tool")),
@@ -29,10 +29,12 @@ fn mode_tool_name(tool: Tool) -> Option<&'static str> {
}
}
/// The tool's name in the alerts, for the tools whose wording was measured: the Brush.
/// The tool's name in the alerts, for the tools whose wording was measured: the Brush and the
/// Sharpen tool (#12952).
pub fn tool_name(tool: Tool) -> Option<&'static str> {
match tool {
Tool::Brush => Some(tl!("brush tool")),
Tool::Sharpen => Some(tl!("sharpen tool")),
_ => None,
}
}
@@ -40,14 +42,15 @@ pub fn tool_name(tool: Tool) -> Option<&'static str> {
/// The alert a press with `tool` gets, if any. `hidden` is the press-time hidden-target refusal
/// (`canvas::tool_input`), which this only words; the lock and the group are checked here. Lock
/// transparent pixels is no refusal, and a group's targeted mask paints. A tool with a
/// [`mode_tool_name`] gets only its colour-mode alert, in an Indexed Color or Bitmap document.
/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document.
pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option<String> {
if let Some(name) = mode_tool_name(tool) {
let template = match app.session.active()?.doc.mode {
photocraft_doc::ColorMode::Indexed => INDEXED,
photocraft_doc::ColorMode::Bitmap => BITMAP,
_ => return None,
};
if let Some(name) = mode_tool_name(tool)
&& let Some(template) = match app.session.active()?.doc.mode {
photocraft_doc::ColorMode::Indexed => Some(INDEXED),
photocraft_doc::ColorMode::Bitmap => Some(BITMAP),
_ => None,
}
{
return Some(crate::i18n::fmt(tl!(template), &[("tool", name)]));
}
let name = tool_name(tool)?;
@@ -61,7 +64,7 @@ pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option<String> {
}
if layer.is_group() {
GROUP
} else if st.doc.effective_locks(layer.id).all {
} else if locked(st.doc.effective_locks(layer.id), tool) {
LOCKED
} else {
return None;
@@ -70,6 +73,12 @@ pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option<String> {
Some(crate::i18n::fmt(tl!(template), &[("tool", name)]))
}
/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen tool Lock Image Pixels as well
/// (measured for it; the Brush keeps today's behaviour there).
fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool {
locks.all || (tool == Tool::Sharpen && locks.pixels)
}
/// Opens the alert: ordinary dialog state, listed by `ui.inspect` and closed by `ui.dialog.confirm`.
pub fn prompt(app: &mut PhotocraftApp, message: &str) {
app.ui.open_dialog(DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default());
@@ -78,3 +87,7 @@ pub fn prompt(app: &mut PhotocraftApp, message: &str) {
#[cfg(test)]
#[path = "../brush_refusal_alert_tests.rs"]
mod brush_refusal_alert_tests;
#[cfg(test)]
#[path = "../sharpen_refusal_alert_tests.rs"]
mod sharpen_refusal_alert_tests;
+22 -1
View File
@@ -120,9 +120,26 @@ mod tests {
}
}
/// View the document at 200 %, where an N by N Average is the centred N × N square (#11751:
/// at 100 % and below it covers (N+1) × (N+1) screen pixels).
fn zoomed_in(app: &mut PhotocraftApp) {
app.sync_views();
for v in &mut app.ui.views {
v.zoom = 2.0;
}
}
#[test]
fn a_click_samples_the_average_of_the_sample_size() {
let mut app = app();
// At 100 % a 3 by 3 Average is the 4 × 4 box from (2, 2): one black pixel of sixteen (#11751).
app.sync_views();
app.ui.tool_options.eyedropper_size = 3;
click(&mut app, 3.5, 3.5, egui::Modifiers::NONE);
let want = (255.0f32 * 15.0 / 16.0).round() / 255.0;
assert_eq!(fg(&app), [want, want, want, 1.0], "3 by 3 at 100 %");
app.ui.tool_options.eyedropper_size = 1;
zoomed_in(&mut app);
// Point Sample at (3, 3): white.
click(&mut app, 3.5, 3.5, egui::Modifiers::NONE);
assert_eq!(fg(&app), [1.0; 4]);
@@ -200,7 +217,11 @@ mod tests {
}
crate::panels::options_bar(app, ui);
},
app(),
{
let mut a = app();
zoomed_in(&mut a);
a
},
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);
h.run_steps(4);
+14 -1
View File
@@ -115,7 +115,8 @@ pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static st
if tool == Tool::Dodge { "paint.dodge" } else { "paint.burn" },
json!({"range": o.tone_range, "exposure": o.exposure, "protectTones": o.protect_tones}),
),
Tool::Sponge => ("paint.sponge", json!({"mode": o.sponge_mode, "vibrance": o.vibrance})),
// Flow as the bar's field stores it (#12976), so a restored fraction paints what the bar shows.
Tool::Sponge => ("paint.sponge", json!({"mode": o.sponge_mode, "flow": crate::eraser_ui::stored_tolerance(o.sponge_flow), "vibrance": o.vibrance})),
_ => return None,
})
}
@@ -968,7 +969,15 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
opt(ui, tl!("Mode:"));
let opts = [("desaturate".to_string(), tl!("Desaturate")), ("saturate".to_string(), tl!("Saturate"))];
crate::widgets::dropdown(ui, "sponge-mode", tl!("Mode"), &mut o.sponge_mode, &opts, 110.0);
// Flow (#12976): whole numbers 1..100 with the "Closest value inserted" alert, and a slider arrow.
let label = tl!("Flow:");
opt(ui, label);
let (_, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut o.sponge_flow, 1.0..=100.0, "%", 58.0);
cam_amount_slider(ui, tl!("Flow"), &mut o.sponge_flow, 1.0, 100.0, "Flow");
crate::widgets::checkbox(ui, &mut o.vibrance, tl!("Vibrance"));
if out_of_range {
crate::eraser_ui::open_range_alert(app);
}
}
Tool::Blur | Tool::Sharpen | Tool::Smudge => {
if tool == Tool::Smudge {
@@ -1163,3 +1172,7 @@ mod burn_bar_tooltips_tests;
#[cfg(test)]
#[path = "../smudge_mode_bar_tests.rs"]
mod smudge_mode_bar_tests;
#[cfg(test)]
#[path = "../sponge_flow_field_tests.rs"]
mod sponge_flow_field_tests;
+1 -1
View File
@@ -239,7 +239,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] {
Tool::Blur | Tool::Sharpen => reset!(strength, protect_detail),
Tool::Smudge => reset!(strength, finger_painting, smudge_mode),
Tool::Dodge | Tool::Burn => reset!(tone_range, exposure, protect_tones),
Tool::Sponge => reset!(sponge_mode, vibrance),
Tool::Sponge => reset!(sponge_mode, sponge_flow, vibrance),
Tool::Slice => reset!(slice_style, slice_width, slice_height),
Tool::Pen => reset!(vector_mode, pen_path_op, pen_auto_add_delete),
Tool::CurvaturePen => reset!(vector_mode, pen_path_op),
@@ -883,7 +883,7 @@ fn split_tool_places_the_line_where_the_pointer_releases() {
assert!(us.len() == 3 && has(&us, 0.25), "{us:?}");
let vs = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap().vs.clone();
assert!(has(&vs, 1.0 / 3.0) && has(&vs, 2.0 / 3.0), "horizontal sections stay: {vs:?}");
assert!(app.transform_preview.as_ref().unwrap().split_tool.is_some(), "the tool stays armed");
assert!(app.transform_preview.as_ref().unwrap().split_tool.is_none(), "one split ends the mode");
// Option-click in the open places both lines, without a button armed.
app.transform_preview.as_mut().unwrap().split_tool = None;
let alt = egui::Modifiers::ALT;
@@ -67,6 +67,7 @@ pub(super) fn split_cursor(m: &BezierMesh, tool: SplitTool, (s, t): (f64, f64),
}
/// Armed split tool, or Option held: the guide tracks the pointer and the split lands on release.
/// A Split button is one-shot, as in the reference: the release that splits ends its mode (#12498).
/// Returns false when this event is an ordinary control-point drag.
fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {
let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool);
@@ -103,9 +104,12 @@ fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
} else {
None
};
if let Some(kind) = kind {
// On an existing line, or a click the drag path also delivers, this is a no-op.
let _ = split(app, kind.command(), Some([x, y]));
// Outside the grid or on an existing line this is a no-op, and the mode stays armed.
if let Some(kind) = kind
&& split(app, kind.command(), Some([x, y])).is_ok()
&& let Some(pv) = app.transform_preview.as_mut()
{
pv.split_tool = None;
}
true
}
@@ -189,3 +193,7 @@ pub fn split(app: &mut PhotocraftApp, id: &str, at: Option<[f64; 2]>) -> Result<
}
edit_session_warp(app, id, &p)
}
#[cfg(test)]
#[path = "warp_split_one_shot_tests.rs"]
mod warp_split_one_shot_tests;
@@ -0,0 +1,139 @@
//! #12498: an options-bar Split button places one split line, then its mode ends, as in the
//! reference. Quick splits and the menu / control-channel commands keep their behaviour.
use super::super::tests::app_with_square;
use super::*;
use egui::PointerButton;
use egui_kittest::kittest::Queryable;
type Harness = egui_kittest::Harness<'static, PhotocraftApp>;
/// A 400 × 300 layer in Warp with the Default grid.
fn warping() -> Harness {
let app = app_with_square(512, photocraft_geom::Rect::new(56, 56, 456, 356));
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
app
});
run(&mut h, "edit.transform.warp", json!({}));
h
}
/// A menu / control-channel command, then a few frames.
fn run(h: &mut Harness, id: &str, params: serde_json::Value) {
h.run_steps(3);
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, id, params).unwrap();
h.run_steps(3);
}
fn warp(h: &Harness) -> Option<Warp> {
h.state().ui.transform.as_ref().unwrap().warp.clone()
}
/// The grid's horizontal knots (`vs`): one more per horizontal split line.
fn rows(h: &Harness) -> usize {
warp(h).and_then(|w| w.mesh).map_or(2, |m| m.vs.len())
}
fn armed(h: &Harness) -> Option<SplitTool> {
h.state().transform_preview.as_ref().unwrap().split_tool
}
fn press_button(h: &mut Harness, tip: &str) {
h.get_by_label(tip).click();
h.run_steps(3);
}
/// A click on the canvas at document point `p`, through the real pointer path.
fn click_doc(h: &mut Harness, p: [f32; 2], m: egui::Modifiers) {
let at = ViewXform::active(h.state()).unwrap().to_screen(p[0], p[1]);
h.event(egui::Event::ModifiersChanged(m));
h.event(egui::Event::PointerMoved(at));
h.run_steps(1);
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: m });
h.run_steps(2);
}
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
h.run_steps(2);
}
#[test]
fn a_split_button_places_one_line_and_then_the_mode_ends() {
let mut h = warping();
press_button(&mut h, "Split Warp Horizontally");
assert!(armed(&h) == Some(SplitTool::Horizontal), "the button arms its mode");
let before = rows(&h);
click_doc(&mut h, [256.0, 156.0], egui::Modifiers::NONE);
assert_eq!(rows(&h), before + 1, "one split line at the click");
// The bar draws the button pressed only while `split_tool` names it.
assert!(armed(&h).is_none(), "the mode ends after one split");
let placed = rows(&h);
click_doc(&mut h, [256.0, 300.0], egui::Modifiers::NONE);
assert_eq!(rows(&h), placed, "the next click is an ordinary press, not another split");
assert!(armed(&h).is_none());
}
#[test]
fn every_split_button_is_one_shot() {
for tip in ["Split Warp Crosswise", "Split Warp Vertically", "Split Warp Horizontally"] {
let mut h = warping();
press_button(&mut h, tip);
assert!(armed(&h).is_some(), "{tip} arms its mode");
let before = warp(&h);
click_doc(&mut h, [200.0, 150.0], egui::Modifiers::NONE);
assert!(warp(&h) != before, "{tip} split the grid");
assert!(armed(&h).is_none(), "{tip} ends after one split");
}
}
#[test]
fn a_second_press_on_the_button_still_cancels_without_a_split() {
let mut h = warping();
let before = warp(&h);
press_button(&mut h, "Split Warp Vertically");
press_button(&mut h, "Split Warp Vertically");
assert!(armed(&h).is_none(), "the second press cancels the mode");
assert_eq!(warp(&h), before, "nothing was split");
}
/// Not measured: a release that places no line keeps the mode armed, as today.
#[test]
fn a_release_that_places_no_line_keeps_the_mode() {
let mut h = warping();
run(&mut h, "edit.transform.splitWarpHorizontally", json!({"at": [256.0, 156.0]}));
press_button(&mut h, "Split Warp Horizontally");
let before = rows(&h);
click_doc(&mut h, [256.0, 20.0], egui::Modifiers::NONE);
assert_eq!(rows(&h), before, "above the grid nothing is split");
assert!(armed(&h) == Some(SplitTool::Horizontal), "the mode stays after a miss above the grid");
click_doc(&mut h, [256.0, 156.0], egui::Modifiers::NONE);
assert_eq!(rows(&h), before, "the line is already there");
assert!(armed(&h) == Some(SplitTool::Horizontal), "the mode stays after a click on an existing line");
}
#[test]
fn quick_splits_still_place_one_split_per_click() {
let mut h = warping();
let before = rows(&h);
// On the Default grid a crosswise split also keeps both thirds, so it adds more than one row.
click_doc(&mut h, [256.0, 131.0], egui::Modifiers::ALT);
let first = rows(&h);
assert!(first > before, "the first Option-click splits");
click_doc(&mut h, [356.0, 281.0], egui::Modifiers::ALT);
assert_eq!(rows(&h), first + 1, "the second Option-click adds one more line");
click_doc(&mut h, [156.0, 206.0], egui::Modifiers::COMMAND);
assert_eq!(rows(&h), first + 2, "a Ctrl/Cmd-click splits the same way");
assert!(armed(&h).is_none(), "no mode is armed");
}
#[test]
fn menu_and_control_channel_splits_still_split_at_once() {
let mut h = warping();
let before = rows(&h);
run(&mut h, "edit.transform.splitWarpHorizontally", json!({}));
run(&mut h, "edit.transform.splitWarpHorizontally", json!({"at": [256.0, 300.0]}));
assert_eq!(rows(&h), before + 2, "at the box centre, then at `at`");
assert!(armed(&h).is_none(), "a command never arms the mode");
}
@@ -0,0 +1,113 @@
//! The Magic Wand pressed inside its selection (#11782), as measured in the reference
//! application: in New mode a click deselects and a drag moves the outline (the pixels stay),
//! the pointer shows the move-selection cursor, and a click on the pasteboard deselects. Add mode
//! and ⌘ drags keep today's behaviour.
use egui::Modifiers;
use photocraft_geom::Rect;
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{SelCursor, ToolEvent, selection_cursor, tool_event};
use crate::state::Tool;
/// A 500 x 400 document with an opaque red block at 100,100–300,250 on its own layer, selected
/// with the wand.
fn selected() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 500, "height": 400})).unwrap();
app.sync_views();
app.run("layer.new.layer", json!({})).unwrap();
app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap();
app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
app.run("select.deselect", json!({})).unwrap();
app.ui.tool = Tool::MagicWand;
app.ui.tool_options.anti_alias = false;
click(&mut app, [150.0, 150.0], Modifiers::NONE);
assert_eq!(selection(&app), Some(Rect::new(100, 100, 300, 250)), "the wand selected the block");
app
}
fn click(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) {
tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, mods);
}
fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) {
tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods);
}
fn selection(app: &PhotocraftApp) -> Option<Rect> {
let st = app.session.active()?;
st.doc.selection.as_ref().map(|s| s.content_bounds()).filter(|b| !b.is_empty())
}
fn last_step(app: &PhotocraftApp) -> Option<String> {
app.session.active()?.history.entries().last().map(ToString::to_string)
}
fn alpha_at(app: &PhotocraftApp, x: i32, y: i32) -> f32 {
let st = app.session.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3]
}
#[test]
fn a_new_mode_click_inside_the_selection_deselects() {
let mut app = selected();
click(&mut app, [200.0, 200.0], Modifiers::NONE);
assert_eq!(selection(&app), None, "nothing is selected");
assert_eq!(last_step(&app).as_deref(), Some("Deselect"));
}
#[test]
fn a_new_mode_drag_inside_the_selection_moves_the_outline_not_the_pixels() {
let mut app = selected();
drag(&mut app, [200.0, 200.0], [300.0, 250.0], Modifiers::NONE);
assert_eq!(selection(&app), Some(Rect::new(200, 150, 400, 300)), "the outline moved by +100,+50");
assert_eq!(last_step(&app).as_deref(), Some("Move Selection"));
assert_eq!(alpha_at(&app, 150, 150), 1.0, "the pixels stay where they are");
assert_eq!(alpha_at(&app, 350, 280), 0.0);
}
#[test]
fn the_pointer_over_the_selection_shows_the_move_selection_cursor_in_new_mode_only() {
let mut app = selected();
assert_eq!(selection_cursor(&app, Tool::MagicWand, [200.0, 200.0], Modifiers::NONE), Some(SelCursor::Outline));
assert_eq!(selection_cursor(&app, Tool::MagicWand, [400.0, 350.0], Modifiers::NONE), None, "outside: the wand");
assert_eq!(selection_cursor(&app, Tool::MagicWand, [200.0, 200.0], Modifiers::SHIFT), None, "Shift adds");
app.ui.selection_mode = 1;
assert_eq!(selection_cursor(&app, Tool::MagicWand, [200.0, 200.0], Modifiers::NONE), None, "Add mode");
}
#[test]
fn a_click_on_the_pasteboard_deselects() {
let mut app = selected();
click(&mut app, [-30.0, -30.0], Modifiers::NONE);
assert_eq!(selection(&app), None);
assert_eq!(last_step(&app).as_deref(), Some("Deselect"));
}
#[test]
fn add_mode_and_shift_keep_the_selection_and_move_nothing() {
for (bar, mods) in [(1, Modifiers::NONE), (0, Modifiers::SHIFT)] {
let mut app = selected();
app.ui.selection_mode = bar;
click(&mut app, [200.0, 200.0], mods);
assert_eq!(selection(&app), Some(Rect::new(100, 100, 300, 250)), "mode {bar}, {mods:?}: click");
drag(&mut app, [200.0, 200.0], [300.0, 250.0], mods);
assert_eq!(selection(&app), Some(Rect::new(100, 100, 300, 250)), "mode {bar}, {mods:?}: drag");
assert_eq!(alpha_at(&app, 150, 150), 1.0);
}
}
#[test]
fn a_new_mode_click_outside_the_selection_selects_that_region() {
let mut app = selected();
click(&mut app, [450.0, 350.0], Modifiers::NONE);
let b = selection(&app).expect("the transparent area is selected");
assert!(!b.contains(150, 150) || b.width() == 500, "a new selection of the clicked region: {b:?}");
assert_eq!(last_step(&app).as_deref(), Some("Magic Wand"));
}