mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge current main for Free Transform Windows validation
This commit is contained in:
commit
18d431c2ea
31 files changed
+1431
-56
No files matched your search
@@ -288,6 +288,21 @@ pub fn scaled_rect(r: Rect, sx: f64, sy: f64) -> Rect {
|
||||
Rect::new((r.x0 as f64 * sx).floor() as i32, (r.y0 as f64 * sy).floor() as i32, (r.x1 as f64 * sx).ceil() as i32, (r.y1 as f64 * sy).ceil() as i32)
|
||||
}
|
||||
|
||||
/// The largest rectangle a resize of content at `r` by `(sx, sy)` with `filter` stores: the
|
||||
/// result, or the image between the passes of a two-pass bicubic. That one keeps an axis at its
|
||||
/// old size, so when both axes shrink it is larger than the result (#9212).
|
||||
pub fn largest_resize_rect(r: Rect, sx: f64, sy: f64, filter: Resample) -> Rect {
|
||||
let area = |r: Rect| u64::from(r.width()) * u64::from(r.height());
|
||||
let (mut cur, mut largest) = (r, Rect::EMPTY);
|
||||
for p in plan(filter, sx, sy) {
|
||||
cur = scaled_rect(cur, p.sx, p.sy);
|
||||
if area(cur) > area(largest) {
|
||||
largest = cur;
|
||||
}
|
||||
}
|
||||
largest
|
||||
}
|
||||
|
||||
/// Resizes a surface by `(sx, sy)` about the document origin. The surface's
|
||||
/// default pixel is kept (masks keep their "reveal all" background).
|
||||
pub fn resize_surface(s: &Surface, sx: f64, sy: f64, filter: Resample) -> Surface {
|
||||
@@ -346,7 +361,8 @@ fn resize(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>)
|
||||
|
||||
/// Runs `filter`'s passes. Between two passes the image is stored in its own format, which
|
||||
/// clips it (and rounds it at 8 and 16 bits) as Photoshop does; the smaller scale goes first, so
|
||||
/// the intermediate image is never larger than the result.
|
||||
/// the intermediate image is never larger than the result when an axis grows, but is when both
|
||||
/// shrink ([`largest_resize_rect`]).
|
||||
fn resize_with_budget(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>, budget: usize) -> Surface {
|
||||
resize_controlled(s, sx, sy, filter, canvas, budget, &photocraft_raster::Interrupt::NONE)
|
||||
}
|
||||
|
||||
@@ -401,6 +401,25 @@ fn nearest_neighbor_reduction_does_not_average() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9212: a bicubic shrink of both axes stores the image between its passes with one axis at the
|
||||
/// old size, larger than the result; single-pass filters and growing axes store nothing larger.
|
||||
#[test]
|
||||
fn largest_resize_rect_counts_the_image_between_the_passes() {
|
||||
let r = Rect::new(0, 0, 100, 80);
|
||||
for f in [Resample::Bicubic, Resample::BicubicSharper, Resample::BicubicAutomatic, Resample::PreserveDetails] {
|
||||
assert_eq!(largest_resize_rect(r, 0.5, 0.5, f), Rect::new(0, 0, 50, 80), "{f:?}");
|
||||
}
|
||||
// The axis with the smaller scale goes first.
|
||||
assert_eq!(largest_resize_rect(r, 0.5, 0.25, Resample::Bicubic), Rect::new(0, 0, 100, 20));
|
||||
for f in [Resample::Bilinear, Resample::Nearest, Resample::Lanczos] {
|
||||
assert_eq!(largest_resize_rect(r, 0.5, 0.5, f), Rect::new(0, 0, 50, 40), "{f:?}");
|
||||
}
|
||||
for f in [Resample::Bicubic, Resample::BicubicAutomatic] {
|
||||
assert_eq!(largest_resize_rect(r, 2.0, 3.0, f), Rect::new(0, 0, 200, 240), "{f:?} grows");
|
||||
assert_eq!(largest_resize_rect(r, 0.5, 2.0, f), Rect::new(0, 0, 50, 160), "{f:?} shrinks x, grows y");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_resize_matches_pixels_and_discards_cancelled_work() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
|
||||
@@ -188,6 +188,8 @@ pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
|
||||
// Color Sampler points are view state a step may move (crop, rotation): roll them back too, so
|
||||
// a failed second step can't leave them pinned to pixels the restored document no longer has.
|
||||
let samplers = st.color_samplers.clone();
|
||||
// So is the painting symmetry, which a rotation moves with the pixels.
|
||||
let symmetry = st.symmetry.clone();
|
||||
let r = f(s);
|
||||
if r.is_err() {
|
||||
s.journal.truncate(journal);
|
||||
@@ -212,6 +214,7 @@ pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
|
||||
st.channel_view = channel_view;
|
||||
st.coalesce = coalesce;
|
||||
st.color_samplers = samplers;
|
||||
st.symmetry = symmetry;
|
||||
st.revision += 1;
|
||||
// A failed compound does not make an otherwise untouched document dirty.
|
||||
if was_clean {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! Image menu: Image Size, Canvas Size, Crop, Trim, Mode (colour model and
|
||||
//! bit depth) conversions, Duplicate.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::convert::Infallible;
|
||||
|
||||
use photocraft_algo::resample::{Resample, crop_surface, resize_surface_in_canvas, translate_surface};
|
||||
use photocraft_algo::resample::{Resample, crop_surface, largest_resize_rect, resize_surface_in_canvas, scaled_rect, translate_surface};
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Effect, Effects, FxPaint, Layer, LayerContent, LayerId, Size};
|
||||
use photocraft_geom::Rect;
|
||||
@@ -11,6 +12,7 @@ use photocraft_raster::Surface;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::CommandSpec;
|
||||
use crate::document_preset_cmds::MAX_RESOLUTION;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
fn has_doc(s: &Session) -> std::result::Result<(), String> {
|
||||
@@ -235,15 +237,27 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pw = pw.or(Some(ow as f64 * pc / 100.0));
|
||||
ph = ph.or(Some(oh as f64 * pc / 100.0));
|
||||
}
|
||||
// The document range File › New and the dialog's field allow; outside it, refuse rather than
|
||||
// clamp (#9260: 1e39 became inf as f32, then silently 10000 ppi). The document's own
|
||||
// resolution always passes: an imported file may have one outside the range, and the dialog
|
||||
// sends it back unchanged (exactly: a value that only rounds to it as f32 is refused).
|
||||
let own_dpi = f64::from(d.doc.resolution_dpi);
|
||||
let dpi = match p.get("resolution") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let r = v.as_f64().filter(|&r| r.is_finite() && ((1.0..=MAX_RESOLUTION).contains(&r) || r == own_dpi));
|
||||
Some(r.ok_or_else(|| bad("image.imageSize", format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_RESOLUTION}")))?)
|
||||
}
|
||||
};
|
||||
// `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size
|
||||
// with Resample on, as an action records it).
|
||||
// with Resample on, as an action records it). An unchanged resolution keeps the pixels.
|
||||
if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true)
|
||||
&& pw.is_none()
|
||||
&& ph.is_none()
|
||||
&& let Some(r) = p.get("resolution").and_then(Value::as_f64)
|
||||
&& let Some(r) = dpi
|
||||
&& r != own_dpi
|
||||
{
|
||||
let r = r.clamp(1.0, 10_000.0);
|
||||
let old = f64::from(d.doc.resolution_dpi).max(1.0);
|
||||
let old = own_dpi.max(1.0);
|
||||
pw = Some(ow as f64 * r / old);
|
||||
ph = Some(oh as f64 * r / old);
|
||||
}
|
||||
@@ -260,7 +274,6 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) {
|
||||
check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?;
|
||||
}
|
||||
let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32);
|
||||
let scale_styles = p.get("scaleStyles").and_then(Value::as_bool).unwrap_or(true);
|
||||
if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) {
|
||||
// Before the sampler map or the document change: a resize that doesn't fit would trap on the web (#10024).
|
||||
@@ -272,7 +285,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit("Image Size", |doc, _| {
|
||||
if let Some(r) = dpi {
|
||||
// Type keeps its pixel size; resampling below then scales it with the pixels.
|
||||
crate::canvas_geom::set_resolution(doc, r.clamp(1.0, 10_000.0));
|
||||
crate::canvas_geom::set_resolution(doc, r as f32);
|
||||
}
|
||||
let filter = match resample {
|
||||
Method::None => return Ok(()),
|
||||
@@ -280,8 +293,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails,
|
||||
Method::Automatic => Resample::BicubicSharper,
|
||||
};
|
||||
resample_doc_with_styles(doc, nw, nh, filter, scale_styles);
|
||||
Ok(())
|
||||
resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles)
|
||||
})?;
|
||||
// The size the document has now: without resampling `width`/`height` are ignored (#1815).
|
||||
let size = s.active().ok_or(EngineError::NoDocument)?.doc.size;
|
||||
@@ -316,18 +328,20 @@ pub(crate) fn check_working_budget(cmd: &str, doc: &Document, nw: u32, nh: u32,
|
||||
|
||||
/// Resamples the whole document (pixels, masks, channels, selection, effects, vectors, guides) to
|
||||
/// `nw` x `nh` px with `filter`: the body of Image Size, shared by the Crop tool's W x H x Resolution
|
||||
/// mode. Callers check [`check_resample_budget`] first.
|
||||
pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) {
|
||||
resample_doc_with_styles(doc, nw, nh, filter, true);
|
||||
/// mode. Callers check [`check_resample_budget`] for the new canvas first; the pixels outside the
|
||||
/// canvas are scaled too, so a surface they would grow past the budget is refused here (#9212).
|
||||
pub(crate) fn resample_doc(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filter: Resample) -> Result<()> {
|
||||
resample_doc_with_styles(doc, cmd, nw, nh, filter, true)
|
||||
}
|
||||
|
||||
/// Resize document content while optionally retaining layer-effect sizes in pixels.
|
||||
fn resample_doc_with_styles(doc: &mut Document, nw: u32, nh: u32, filter: Resample, scale_styles: bool) {
|
||||
fn resample_doc_with_styles(doc: &mut Document, cmd: &str, nw: u32, nh: u32, filter: Resample, scale_styles: bool) -> Result<()> {
|
||||
let (ow, oh) = (doc.size.width, doc.size.height);
|
||||
let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64);
|
||||
if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
check_hidden_resample_budget(cmd, doc, sx, sy, filter)?;
|
||||
// Content that reaches the canvas edge keeps it: a Background stays opaque to the border.
|
||||
let canvas = Rect::from_xywh(0, 0, ow, oh);
|
||||
let taken = crate::smart_cmds::take_caches(&mut doc.layers);
|
||||
@@ -358,6 +372,76 @@ fn resample_doc_with_styles(doc: &mut Document, nw: u32, nh: u32, filter: Resamp
|
||||
doc.size = Size::new(nw, nh);
|
||||
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All);
|
||||
let Ok(()) = crate::smart_cmds::restore_unrendered(doc, taken, |c| Ok::<_, Infallible>(resize_surface_in_canvas(c, sx, sy, filter, canvas)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_resample_budget`] for the largest surface [`resample_doc`] stores while scaling by
|
||||
/// `sx` x `sy` with `filter` (masks, channels and the selection with Bilinear): each keeps its
|
||||
/// pixels outside the canvas (a crop that didn't delete them, a layer moved off the canvas), and
|
||||
/// those grow with the scale like the rest. A bicubic shrink also stores the image between its
|
||||
/// two passes, one axis still at its old size ([`largest_resize_rect`]). The refusal suggests
|
||||
/// Delete Cropped Pixels only when the surfaces over the budget are all ones it clips
|
||||
/// ([`delete_cropped_pixels`]).
|
||||
fn check_hidden_resample_budget(cmd: &str, doc: &mut Document, sx: f64, sy: f64, filter: Resample) -> Result<()> {
|
||||
let new_canvas = scaled_rect(doc.bounds(), sx, sy);
|
||||
// The surfaces Delete Cropped Pixels clips; masks, channels, the selection, type, shapes and
|
||||
// smart objects keep their pixels outside the crop.
|
||||
let mut clipped: HashSet<*const Surface> = HashSet::new();
|
||||
for_each_layer(&mut doc.layers, &mut |l| {
|
||||
clipped.extend(l.fill_cache.as_ref().map(|fc| std::ptr::from_ref(&fc.surface)));
|
||||
if let Some(v) = &l.video {
|
||||
clipped.extend(v.frames.iter().chain(v.original_frames.iter().flatten()).map(std::ptr::from_ref));
|
||||
}
|
||||
if let LayerContent::Raster(s) = &l.content {
|
||||
clipped.insert(std::ptr::from_ref(s));
|
||||
}
|
||||
});
|
||||
let bytes = |(w, h, bpp): (u32, u32, u64)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp);
|
||||
// The largest surface by bytes, and the largest one Delete Cropped Pixels doesn't clip: its
|
||||
// width, height and bytes per pixel (a mask has one channel, the layers the document's).
|
||||
let (mut largest, mut largest_kept) = ((0u32, 0u32, 1u64), (0u32, 0u32, 1u64));
|
||||
let mut visit = |surf: &Surface, filter: Resample| {
|
||||
let r = largest_resize_rect(surf.content_bounds(), sx, sy, filter);
|
||||
// What stays within the new canvas is already budgeted.
|
||||
if r.is_empty() || new_canvas.union(&r) == new_canvas {
|
||||
return;
|
||||
}
|
||||
let this = (r.width(), r.height(), surf.format().bytes_per_pixel().max(1) as u64);
|
||||
if bytes(this) > bytes(largest) {
|
||||
largest = this;
|
||||
}
|
||||
if !clipped.contains(&std::ptr::from_ref(surf)) && bytes(this) > bytes(largest_kept) {
|
||||
largest_kept = this;
|
||||
}
|
||||
};
|
||||
// The surfaces `resample_doc` scales, smart object caches included.
|
||||
for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| visit(surf, if is_mask { Resample::Bilinear } else { filter }));
|
||||
for ch in doc.channels.iter().chain(doc.quick_mask.as_ref()) {
|
||||
visit(&ch.surface, Resample::Bilinear);
|
||||
}
|
||||
if let Some(sel) = &doc.selection {
|
||||
visit(sel, Resample::Bilinear);
|
||||
}
|
||||
let (kept, (w, h, bpp)) = if bytes(largest_kept) > MAX_RESAMPLE_BYTES {
|
||||
(true, largest_kept)
|
||||
} else if bytes(largest) > MAX_RESAMPLE_BYTES {
|
||||
(false, largest)
|
||||
} else {
|
||||
return Ok(());
|
||||
};
|
||||
let hint = if kept {
|
||||
"choose a smaller size (layer masks, channels, the quick mask, the selection, type, shapes and smart objects keep theirs through Crop with Delete Cropped Pixels)"
|
||||
} else {
|
||||
"choose a smaller size, or delete them first (Crop with Delete Cropped Pixels)"
|
||||
};
|
||||
let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000;
|
||||
Err(bad(
|
||||
cmd,
|
||||
format!(
|
||||
"{w} x {h} px is {} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. The pixels outside the canvas are resampled too: {hint}",
|
||||
u64::from(w).saturating_mul(u64::from(h)) / 1_000_000
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
@@ -728,8 +812,7 @@ fn crop_with(s: &mut Session, p: &Value, keep_background: bool) -> Result<Value>
|
||||
crate::crop_fill::fill_uncovered(doc, *active, &crate::crop_fill::Coverage::crop(r, original.width, original.height))?;
|
||||
}
|
||||
doc.selection = None;
|
||||
target.apply(doc);
|
||||
Ok(())
|
||||
target.apply(doc)
|
||||
})?;
|
||||
Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() })))
|
||||
}
|
||||
@@ -744,15 +827,16 @@ struct CropTarget {
|
||||
|
||||
impl CropTarget {
|
||||
/// Applies the target to a document that has just been cropped (inside the crop's history step).
|
||||
fn apply(&self, doc: &mut Document) {
|
||||
fn apply(&self, doc: &mut Document) -> Result<()> {
|
||||
if let Some((w, h)) = self.size {
|
||||
// As for Image Size: an Indexed Color document holds only its colour table's colours (#6019).
|
||||
let filter = if doc.mode == ColorMode::Indexed { Resample::Nearest } else { self.filter };
|
||||
resample_doc(doc, w, h, filter);
|
||||
resample_doc(doc, "image.crop", w, h, filter)?;
|
||||
}
|
||||
if let Some(r) = self.resolution {
|
||||
doc.resolution_dpi = r;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where Color Sampler points go: shifted by the crop's origin, then scaled with the pixels
|
||||
@@ -937,8 +1021,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar
|
||||
crate::crop_fill::fill_uncovered(doc, *active, &coverage)?;
|
||||
}
|
||||
doc.selection = None;
|
||||
crop_target.apply(doc);
|
||||
Ok(())
|
||||
crop_target.apply(doc)
|
||||
})
|
||||
})?;
|
||||
Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle })))
|
||||
|
||||
@@ -234,6 +234,48 @@ fn resolution_only_change() {
|
||||
assert_eq!(r, json!({"width": 40, "height": 20}));
|
||||
}
|
||||
|
||||
/// #9260: a resolution outside the document range (1..=30000 ppi, as File › New and the
|
||||
/// dialog's field) is refused and leaves the document as it was, instead of being clamped;
|
||||
/// one inside it, also above 10000, is set as given.
|
||||
#[test]
|
||||
fn image_size_refuses_a_resolution_out_of_range() {
|
||||
for extra in [json!({"resample": "none"}), json!({"resample": "bicubic"}), json!({"resample": "bicubic", "keepPrintSize": true})] {
|
||||
for r in [json!(1e39), json!(-5), json!(0), json!(0.5), json!(30_001), json!("300")] {
|
||||
let mut s = session();
|
||||
let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len());
|
||||
let mut p = extra.clone();
|
||||
p["resolution"] = r;
|
||||
assert!(s.execute("image.imageSize", p.clone()).is_err(), "{p}");
|
||||
assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed");
|
||||
}
|
||||
}
|
||||
let mut s = session();
|
||||
s.execute("image.imageSize", json!({"resolution": 20_000, "resample": "none"})).unwrap();
|
||||
assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 20_000.0));
|
||||
s.execute("image.imageSize", json!({"resolution": null, "resample": "none"})).unwrap();
|
||||
assert_eq!(doc(&s).resolution_dpi, 20_000.0, "null leaves the resolution as it is");
|
||||
// An imported document's own resolution outside the range (a PNG pHYs of 1 px/m is
|
||||
// 0.0254 ppi) still resizes: the Image Size dialog sends it back unchanged on OK.
|
||||
for own in [0.0254_f32, 40_000.0] {
|
||||
let mut s = session();
|
||||
s.edit("ppi", |doc, _| {
|
||||
doc.resolution_dpi = own;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("image.imageSize", json!({"width": 80, "height": 40, "resolution": f64::from(own), "resample": "bicubic"})).unwrap();
|
||||
assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}");
|
||||
assert!(s.execute("image.imageSize", json!({"resolution": 0.03, "resample": "none"})).is_err(), "{own}: another value is still checked");
|
||||
// Only the exact value: one that merely rounds to it as f32 is refused.
|
||||
let near = if own < 1.0 { f64::from(own) * (1.0 + 1e-9) } else { f64::from(own) + 0.001 };
|
||||
assert_eq!(near as f32, own);
|
||||
assert!(s.execute("image.imageSize", json!({"resolution": near, "resample": "none"})).is_err(), "{own}: {near}");
|
||||
// keepPrintSize with the unchanged resolution keeps the pixels.
|
||||
s.execute("image.imageSize", json!({"resolution": f64::from(own), "resample": "bicubic", "keepPrintSize": true})).unwrap();
|
||||
assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), own), "{own}: keepPrintSize");
|
||||
}
|
||||
}
|
||||
|
||||
/// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is
|
||||
/// twice as tall (not 4x), with Resample off it stays, and a later re-render doesn't jump.
|
||||
#[test]
|
||||
@@ -825,6 +867,79 @@ fn crop_target_accepts_whole_number_floats() {
|
||||
assert_eq!(doc(&s).size, Size::new(40, 20));
|
||||
}
|
||||
|
||||
/// #9212: a non-deleting crop keeps the pixels outside the frame, and W x H resamples them
|
||||
/// too. A 20 px frame of a 2000 px Background resampled to 2000 px scales its hidden pixels
|
||||
/// x100, to 200000 px a side (160 GB at 8 bits, past the 8 GiB budget): refused before
|
||||
/// allocating, like a target size past the budget.
|
||||
#[test]
|
||||
fn crop_target_budgets_the_hidden_pixels_it_resamples() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 2000, "height": 2000})).unwrap();
|
||||
s.execute("paint.setSymmetry", json!({"mode": "vertical", "center": [500, 700]})).unwrap();
|
||||
let symmetry = s.active().unwrap().symmetry.clone();
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
let mut p = json!({"x": 0, "y": 0, "width": 20, "height": 20, "deleteCroppedPixels": false, "targetWidth": 2000, "targetHeight": 2000});
|
||||
for angle in [None, Some(90)] {
|
||||
let mut p = p.clone();
|
||||
if let Some(a) = angle {
|
||||
p["angle"] = json!(a);
|
||||
}
|
||||
let err = s.execute("image.crop", p).unwrap_err().to_string();
|
||||
// Since the crop turns the Background into Layer 0 (#10867), the turned layer's
|
||||
// bounds are 2001 px a side, resampled x100 to 200100.
|
||||
let want = if angle.is_some() { "200100 x 200100 px is 40040 megapixels" } else { "200000 x 200000 px is 40000 megapixels" };
|
||||
assert!(err.contains(want) && err.contains("Delete Cropped Pixels"), "{angle:?}: {err}");
|
||||
assert_eq!(doc(&s).size, Size::new(2000, 2000), "{angle:?}: the document is unchanged");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past, "{angle:?}: no history step");
|
||||
// The turned crop rotates first: the painting symmetry turns back with the document.
|
||||
assert_eq!(s.active().unwrap().symmetry, symmetry, "{angle:?}: the painting symmetry stays");
|
||||
}
|
||||
// Deleting the cropped pixels leaves only the frame to resample.
|
||||
p["deleteCroppedPixels"] = json!(true);
|
||||
s.execute("image.crop", p).unwrap();
|
||||
assert_eq!(doc(&s).size, Size::new(2000, 2000));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), past + 1);
|
||||
}
|
||||
|
||||
/// #9212: Image Size resamples the pixels outside the canvas as well. After a non-deleting
|
||||
/// crop to 10 px, 20000 px (400 MP, within the budget) scales the hidden 100 px Background x2000.
|
||||
#[test]
|
||||
fn image_size_budgets_the_hidden_pixels_it_resamples() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": false})).unwrap();
|
||||
let past = s.active().unwrap().history.past_len();
|
||||
let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string();
|
||||
assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}");
|
||||
// The hidden pixels are a pixel layer's: Delete Cropped Pixels would clear them.
|
||||
assert!(err.contains("or delete them first (Crop with Delete Cropped Pixels)"), "{err}");
|
||||
assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (Size::new(10, 10), past));
|
||||
// Without resampling only the resolution changes.
|
||||
s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap();
|
||||
assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(10, 10), 300.0));
|
||||
}
|
||||
|
||||
/// Delete Cropped Pixels clips pixel layers only: an alpha channel keeps its pixels outside the
|
||||
/// crop, so the refusal doesn't send the user to an option that can't clear it.
|
||||
#[test]
|
||||
fn hidden_resample_budget_names_what_delete_cropped_pixels_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
s.edit("channel", |doc, _| {
|
||||
let fmt = photocraft_color::PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false);
|
||||
let mut ch = Surface::new(fmt);
|
||||
ch.write_region(Rect::new(0, 0, 100, 100), &[1.0; 100 * 100]);
|
||||
doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": true})).unwrap();
|
||||
let err = s.execute("image.imageSize", json!({"width": 20000, "height": 20000})).unwrap_err().to_string();
|
||||
assert!(err.contains("200000 x 200000 px is 40000 megapixels"), "{err}");
|
||||
assert!(err.contains("channels") && !err.contains("delete them first"), "{err}");
|
||||
assert_eq!(doc(&s).size, Size::new(10, 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_target_rejects_bad_params_without_changing_the_document() {
|
||||
let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10});
|
||||
@@ -973,6 +1088,24 @@ fn duplicate_document() {
|
||||
assert!(doc(&s).name.ends_with("copy"));
|
||||
}
|
||||
|
||||
/// #9212: a bicubic shrink stores the image between its two passes with one axis at its old
|
||||
/// size. A Background whose kept pixels reach (69999, 69999), halved from 200 to 100 px, ends at
|
||||
/// about 35000 x 35000 px (4.9 GB, within the 8 GiB budget) but passes through about
|
||||
/// 35000 x 70000 px (9.8 GB): refused before allocating. Bilinear has one pass and fits. The
|
||||
/// check alone runs, so nothing that large is allocated either way.
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
#[test]
|
||||
fn hidden_resample_budget_counts_the_image_between_bicubic_passes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let mut d = doc(&s).clone();
|
||||
let bg = d.background_mut().unwrap().surface_mut().unwrap();
|
||||
bg.fill_rect(Rect::new(69_999, 69_999, 70_000, 70_000), &[1.0, 0.0, 0.0, 1.0]);
|
||||
let err = check_hidden_resample_budget("image.imageSize", &mut d, 0.5, 0.5, Resample::Bicubic).unwrap_err().to_string();
|
||||
assert!(err.contains(" x 70000 px is "), "{err}");
|
||||
check_hidden_resample_budget("image.imageSize", &mut d, 0.5, 0.5, Resample::Bilinear).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_and_duplicate_merged_on_too_large_document_fail_gracefully_without_panic() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -566,7 +566,7 @@ fn bitmap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.edit("Bitmap", |doc, active| {
|
||||
if (nw, nh) != (doc.size.width, doc.size.height) {
|
||||
crate::image_cmds::resample_doc(doc, nw, nh, photocraft_algo::resample::Resample::Bicubic);
|
||||
crate::image_cmds::resample_doc(doc, CMD, nw, nh, photocraft_algo::resample::Resample::Bicubic)?;
|
||||
}
|
||||
doc.resolution_dpi = dpi;
|
||||
let w = doc.size.width as usize;
|
||||
|
||||
@@ -452,6 +452,18 @@ fn bitmap_output_resolution_resamples_and_sets_the_resolution() {
|
||||
assert_eq!(first_white(doc(&s), 0, 1, 0), Some(128));
|
||||
}
|
||||
|
||||
/// #9212: the Output resolution resamples the pixels outside the canvas too. A 10 px crop that
|
||||
/// kept a 1000 px document's pixels, converted from 1 to 100 ppi, would grow them to 100000 px a
|
||||
/// side (20 GB of gray and alpha at 8 bits, past the 8 GiB budget): refused before allocating.
|
||||
#[test]
|
||||
fn bitmap_output_resolution_budgets_the_hidden_pixels() {
|
||||
let mut s = ramp(1000, 1000, 8, 1.0);
|
||||
s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": false})).unwrap();
|
||||
let err = s.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 100})).unwrap_err().to_string();
|
||||
assert!(err.contains("100000 x 100000 px is 10000 megapixels"), "{err}");
|
||||
assert_eq!((doc(&s).size.width, doc(&s).mode), (10, ColorMode::Grayscale));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmap_halftone_screen_is_laid_out_at_the_output_resolution() {
|
||||
// The same 10 lines/inch screen has twice the cell (in pixels) at twice the resolution: the
|
||||
|
||||
@@ -63,6 +63,35 @@ fn re_placing_at_another_scale_re_renders_the_vector_source() {
|
||||
assert!(red(&surf, 150, 81) < 0.02 && red(&surf, 150, 75) > 0.98 && red(&surf, 150, 87) > 0.98);
|
||||
}
|
||||
|
||||
/// A `.pcraft` opens from its cached pixels and parses an embedded SVG source only on a later
|
||||
/// edit. A source whose DTD entity hides 20 000 nested groups from the depth check used to open
|
||||
/// clean and then overflow the stack on Image Size or a PSD save; both are an error or a fallback
|
||||
/// now. Run on a 2 MB stack, as the app's import and command threads are.
|
||||
#[test]
|
||||
fn a_pcraft_smart_object_with_a_hostile_svg_does_not_abort_a_later_edit() {
|
||||
let deep = format!("{}{}", "<g>".repeat(20_000), "</g>".repeat(20_000));
|
||||
let hostile = format!("<!DOCTYPE svg [<!ENTITY a \"{deep}\">]><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"10\">&a;</svg>");
|
||||
std::thread::Builder::new()
|
||||
.stack_size(2 * 1024 * 1024)
|
||||
.spawn(move || {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap();
|
||||
photocraft_engine::file_cmds::place_bytes(&mut s, "logo.svg", SVG.as_bytes().to_vec(), None, &json!({"scale": 100})).unwrap();
|
||||
let mut doc = (*s.active().unwrap().doc).clone();
|
||||
let LayerContent::Smart(sm) = &mut doc.layers.last_mut().unwrap().content else { panic!("smart object") };
|
||||
sm.source = photocraft_doc::SmartSource::Embedded { file_name: "logo.svg".into(), bytes: std::sync::Arc::new(hostile.into_bytes()) };
|
||||
let carrier = photocraft_format::save_to_bytes(&doc, &photocraft_format::SaveOptions::default()).unwrap();
|
||||
|
||||
photocraft_engine::file_cmds::open_bytes_as(&mut s, "carrier.pcraft", &carrier, None, None).unwrap();
|
||||
let _ = s.execute("image.imageSize", json!({"width": 50, "height": 50}));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let _ = s.execute("file.saveACopy", json!({"path": dir.path().join("copy.psd").to_string_lossy()}));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Placed through a background job, an SVG is rendered at its placement scale on the worker and
|
||||
/// lands exactly as the inline place does: still sharp, not a resampled raster.
|
||||
#[test]
|
||||
|
||||
@@ -49,6 +49,8 @@ imagesize = "0.13"
|
||||
# already in the tree through the UI's icon loader; text shaping needs the fonts feature set.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] }
|
||||
# The SVG fallback font search keeps each font file's character map (already in the tree through usvg).
|
||||
ttf-parser = { version = "0.25", default-features = false }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] }
|
||||
|
||||
+114
-9
@@ -281,15 +281,78 @@ fn in_memory(id: usvg::fontdb::ID, db: &mut Arc<usvg::fontdb::Database>) -> usvg
|
||||
loaded.into_iter().find(|&n| db.face_source(n).is_some_and(|(_, i)| i == index)).unwrap_or(id)
|
||||
}
|
||||
|
||||
/// Most `cmap` table bytes [`has_char`] keeps; past it a face is asked on disk (slow, still right).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const MAX_CACHED_CMAP_BYTES: usize = 64 << 20;
|
||||
|
||||
/// Whether face `face` maps `c` to a glyph, as usvg's own check decides it. usvg reads a font
|
||||
/// file's whole font for every face it asks, so one character no font has re-read every
|
||||
/// installed font once per text element (430 ms each with 273 faces). A file face's `cmap` table
|
||||
/// is kept instead, read once per process; a file that doesn't load isn't remembered.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn has_char(db: &usvg::fontdb::Database, face: &usvg::fontdb::FaceInfo, c: char) -> bool {
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use ttf_parser::{Face, Tag, cmap};
|
||||
type Cmaps = (HashMap<(PathBuf, u32), Arc<Vec<u8>>>, usize);
|
||||
static CMAPS: OnceLock<Mutex<Cmaps>> = OnceLock::new();
|
||||
let maps = || CMAPS.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let in_cmap =
|
||||
|table: &[u8]| cmap::Table::parse(table).is_some_and(|t| t.subtables.into_iter().any(|s| s.is_unicode() && s.glyph_index(u32::from(c)).is_some()));
|
||||
let usvg_check = |data: &[u8], index| Face::parse(data, index).is_ok_and(|f| f.glyph_index(c).is_some());
|
||||
let usvg::fontdb::Source::File(path) = &face.source else {
|
||||
return db.with_face_data(face.id, usvg_check).unwrap_or(false);
|
||||
};
|
||||
let key = (path.clone(), face.index);
|
||||
if let Some(table) = maps().0.get(&key).cloned() {
|
||||
return in_cmap(&table);
|
||||
}
|
||||
// usvg's check parses the whole face first: one that doesn't parse has no characters. Its
|
||||
// `cmap` is the last such table record (a linear walk, unsorted directories included).
|
||||
let cmap_of = |data: &[u8], index| {
|
||||
let face = Face::parse(data, index).ok()?;
|
||||
let raw = face.raw_face();
|
||||
let record = raw.table_records.into_iter().filter(|r| r.tag == Tag::from_bytes(b"cmap")).last();
|
||||
let table = record.and_then(|r| {
|
||||
let start = usize::try_from(r.offset).ok()?;
|
||||
raw.data.get(start..start.checked_add(usize::try_from(r.length).ok()?)?)
|
||||
});
|
||||
Some(table.unwrap_or_default().to_vec())
|
||||
};
|
||||
let Some(table) = db.with_face_data(face.id, cmap_of).flatten() else {
|
||||
return false;
|
||||
};
|
||||
let found = in_cmap(&table);
|
||||
let mut maps = maps();
|
||||
// An import that missed at the same time may have kept it already.
|
||||
if !maps.0.contains_key(&key) && maps.1.saturating_add(table.len()) <= MAX_CACHED_CMAP_BYTES {
|
||||
maps.1 = maps.1.saturating_add(table.len());
|
||||
maps.0.insert(key, Arc::new(table));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// usvg's fallback choice (the first face, in database order, not used yet, sharing the base
|
||||
/// face's style, weight or stretch and having `c`), asked through [`has_char`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn fallback_face(c: char, used: &[usvg::fontdb::ID], db: &usvg::fontdb::Database) -> Option<usvg::fontdb::ID> {
|
||||
let base = db.face(*used.first()?)?;
|
||||
db.faces()
|
||||
.filter(|f| !used.contains(&f.id))
|
||||
.filter(|f| base.style == f.style || base.weight == f.weight || base.stretch == f.stretch)
|
||||
.find(|f| has_char(db, f, c))
|
||||
.map(|f| f.id)
|
||||
}
|
||||
|
||||
/// usvg's font choice, with the chosen faces read from memory ([`in_memory`]).
|
||||
fn font_resolver() -> usvg::FontResolver<'static> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let select = usvg::FontResolver::default_font_selector();
|
||||
let fallback = usvg::FontResolver::default_fallback_selector();
|
||||
usvg::FontResolver {
|
||||
select_font: Box::new(move |font, db| select(font, db).map(|id| in_memory(id, db))),
|
||||
select_fallback: Box::new(move |c, used, db| fallback(c, used, db).map(|id| in_memory(id, db))),
|
||||
select_fallback: Box::new(|c, used, db| fallback_face(c, used, db).map(|id| in_memory(id, db))),
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -329,7 +392,7 @@ fn options(fontdb: Arc<usvg::fontdb::Database>, depth_left: usize) -> usvg::Opti
|
||||
Ok(std::borrow::Cow::Owned(xml)) if !xml.starts_with(&[0x1f, 0x8b]) => ("image/svg+xml", Arc::new(xml)),
|
||||
_ => return None,
|
||||
};
|
||||
if nesting_depth(&xml, depth_left) > depth_left {
|
||||
if !nesting_depth(&xml, depth_left).is_ok_and(|depth| depth <= depth_left) {
|
||||
return None;
|
||||
}
|
||||
return default_resolver(mime, xml, opts);
|
||||
@@ -366,7 +429,7 @@ fn parse(bytes: &[u8]) -> Result<Parsed, IoError> {
|
||||
/// [`parse`] with the font database `fonts` supplies (the tests hand in an empty one).
|
||||
fn parse_with(bytes: &[u8], fonts: fn() -> Arc<usvg::fontdb::Database>) -> Result<Parsed, IoError> {
|
||||
let xml = inflate(bytes)?;
|
||||
let depth = nesting_depth(&xml, MAX_XML_DEPTH);
|
||||
let depth = nesting_depth(&xml, MAX_XML_DEPTH)?;
|
||||
if depth > MAX_XML_DEPTH {
|
||||
return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep")));
|
||||
}
|
||||
@@ -627,7 +690,7 @@ fn parse_image_bounded_with(
|
||||
if left.is_none() {
|
||||
return Err(overrun(IoError::Svg("embedded SVG XML exceeds the decoded byte budget".into())));
|
||||
}
|
||||
let nesting = nesting_depth(&xml, xml_left);
|
||||
let nesting = nesting_depth(&xml, xml_left)?;
|
||||
if nesting > xml_left {
|
||||
return Err(IoError::Svg(format!("elements are nested more than {xml_left} levels deep")));
|
||||
}
|
||||
@@ -806,8 +869,10 @@ fn inflate_with_limit(bytes: &[u8], limit: u64) -> Result<std::borrow::Cow<'_, [
|
||||
/// The deepest element nesting in `xml`, stopping as soon as it passes `limit` (the result is
|
||||
/// then `limit + 1`). Comments, CDATA sections, processing instructions and the DOCTYPE add
|
||||
/// nothing; quoted attribute values may hold `>` or `/>`. Malformed markup is only counted
|
||||
/// loosely: the parser rejects it afterwards.
|
||||
pub(crate) fn nesting_depth(xml: &[u8], limit: usize) -> usize {
|
||||
/// loosely: the parser rejects it afterwards. The parser expands the DTD's entities after this
|
||||
/// count, so an entity holding markup (a `<`) is an error: it could nest deeper than anything
|
||||
/// counted here. A `<` there stays text.
|
||||
pub(crate) fn nesting_depth(xml: &[u8], limit: usize) -> Result<usize, IoError> {
|
||||
let after = |from: usize, pat: &[u8]| -> usize {
|
||||
xml.get(from..).and_then(|s| s.windows(pat.len()).position(|w| w == pat)).map_or(xml.len(), |p| from.saturating_add(p).saturating_add(pat.len()))
|
||||
};
|
||||
@@ -829,6 +894,44 @@ pub(crate) fn nesting_depth(xml: &[u8], limit: usize) -> usize {
|
||||
}
|
||||
(xml.len(), false)
|
||||
};
|
||||
// The byte after the DOCTYPE starting at `from`: its internal subset `[...]` is walked
|
||||
// declaration by declaration, so a quote in a comment there can't hide the markup after it.
|
||||
let doctype_end = |from: usize| -> Result<usize, IoError> {
|
||||
let (mut quote, mut j) = (None, from);
|
||||
loop {
|
||||
let Some(&b) = xml.get(j) else { return Ok(xml.len()) };
|
||||
j = j.saturating_add(1);
|
||||
match quote {
|
||||
Some(q) if b == q => quote = None,
|
||||
Some(_) => {}
|
||||
None if b == b'"' || b == b'\'' => quote = Some(b),
|
||||
None if b == b'>' => return Ok(j),
|
||||
None if b == b'[' => break,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
while let Some(rest) = xml.get(j..).filter(|r| !r.is_empty()) {
|
||||
j = if rest.starts_with(b"<!--") {
|
||||
after(j.saturating_add(4), b"-->")
|
||||
} else if rest.starts_with(b"<?") {
|
||||
after(j.saturating_add(2), b"?>")
|
||||
} else if rest.starts_with(b"<!ENTITY") {
|
||||
let end = tag_end(j.saturating_add(2)).0;
|
||||
if xml.get(j.saturating_add(2)..end).is_some_and(|decl| decl.contains(&b'<')) {
|
||||
return Err(IoError::Svg("the SVG's DTD declares an entity holding markup, which isn't supported".into()));
|
||||
}
|
||||
end
|
||||
} else if rest.starts_with(b"<!") {
|
||||
// The parser ends ELEMENT, ATTLIST and NOTATION at the first `>`, quotes or not.
|
||||
after(j.saturating_add(2), b">")
|
||||
} else if rest.starts_with(b"]") {
|
||||
return Ok(tag_end(j.saturating_add(1)).0);
|
||||
} else {
|
||||
j.saturating_add(1)
|
||||
};
|
||||
}
|
||||
Ok(xml.len())
|
||||
};
|
||||
let (mut depth, mut deepest, mut i) = (0usize, 0usize, 0usize);
|
||||
while let Some(p) = xml.get(i..).and_then(|s| s.iter().position(|&b| b == b'<')) {
|
||||
let at = i.saturating_add(p);
|
||||
@@ -839,6 +942,8 @@ pub(crate) fn nesting_depth(xml: &[u8], limit: usize) -> usize {
|
||||
after(at.saturating_add(9), b"]]>")
|
||||
} else if rest.starts_with(b"<?") {
|
||||
after(at.saturating_add(2), b"?>")
|
||||
} else if rest.starts_with(b"<!DOCTYPE") {
|
||||
doctype_end(at.saturating_add(9))?
|
||||
} else if rest.starts_with(b"<!") {
|
||||
tag_end(at.saturating_add(2)).0
|
||||
} else if rest.starts_with(b"</") {
|
||||
@@ -850,13 +955,13 @@ pub(crate) fn nesting_depth(xml: &[u8], limit: usize) -> usize {
|
||||
depth = depth.saturating_add(1);
|
||||
deepest = deepest.max(depth);
|
||||
if deepest > limit {
|
||||
return deepest;
|
||||
return Ok(deepest);
|
||||
}
|
||||
}
|
||||
end
|
||||
};
|
||||
}
|
||||
deepest
|
||||
Ok(deepest)
|
||||
}
|
||||
|
||||
/// The document canvas for a drawing: its size in px, scaled down to [`MAX_SIDE`] when needed.
|
||||
|
||||
@@ -487,6 +487,79 @@ fn imports_missing_the_same_font_at_once_share_one_read() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #9671: the fallback search for a character the text's font lacks reads each font file's
|
||||
/// character map once per process, not the whole file on every text element (430 ms an
|
||||
/// element with 273 installed faces). A second import still finds the fallback face after
|
||||
/// its file stopped being readable, so it didn't go back to the disk.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn the_fallback_search_reads_each_font_file_once() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
static GONE: AtomicBool = AtomicBool::new(false);
|
||||
fn path() -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("photocraft-svg-test-fallback-{}.ttf", std::process::id()))
|
||||
}
|
||||
fn inter_and_mono_on_disk() -> Arc<usvg::fontdb::Database> {
|
||||
std::fs::write(path(), include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf")).unwrap();
|
||||
let mut db = usvg::fontdb::Database::new();
|
||||
db.load_font_data(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec());
|
||||
db.load_font_file(path()).unwrap();
|
||||
if GONE.load(Ordering::SeqCst) {
|
||||
std::fs::write(path(), b"not a font any more").unwrap();
|
||||
}
|
||||
Arc::new(db)
|
||||
}
|
||||
// Inter has no box-drawing characters; JetBrains Mono has.
|
||||
let svg = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"60\"><text x=\"5\" y=\"45\" font-size=\"48\" font-family=\"Inter\">I\u{2500}I</text></svg>";
|
||||
let outlines = |parsed: Parsed| {
|
||||
let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH, None, false).unwrap().document.layers;
|
||||
let groups = layers.into_iter().filter_map(|l| if let LayerContent::Group(g) = l.content { Some(g) } else { None });
|
||||
groups.flat_map(|g| g.children).filter_map(|l| if let LayerContent::Shape(s) = l.content { Some(s.path) } else { None }).collect::<Vec<_>>()
|
||||
};
|
||||
let first = parse_with(svg.as_bytes(), inter_and_mono_on_disk).unwrap();
|
||||
let mono =
|
||||
first.tree.fontdb().faces().any(|f| f.families.iter().any(|(n, _)| n == "JetBrains Mono") && matches!(f.source, usvg::fontdb::Source::Binary(_)));
|
||||
assert!(mono, "the box-drawing character falls back to JetBrains Mono");
|
||||
let first = outlines(first);
|
||||
GONE.store(true, Ordering::SeqCst);
|
||||
let second = outlines(parse_with(svg.as_bytes(), inter_and_mono_on_disk).unwrap());
|
||||
let _ = std::fs::remove_file(path());
|
||||
assert!(first.iter().any(|p| !p.subpaths.is_empty()), "the text has outlines");
|
||||
assert!(second == first, "the second import set the character in the same fallback face");
|
||||
}
|
||||
|
||||
/// #9671: the kept `cmap` is the one usvg reads (the last such record of a linear walk), also
|
||||
/// in a font whose table directory isn't sorted by tag, where a binary search misses it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn the_fallback_search_reads_the_cmap_of_an_unsorted_font() {
|
||||
fn inter_and_unsorted_mono_on_disk() -> Arc<usvg::fontdb::Database> {
|
||||
let mut font = include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec();
|
||||
let count = usize::from(u16::from_be_bytes([font[4], font[5]]));
|
||||
// The `cmap` record moves to the end of the directory.
|
||||
let mut records: Vec<Vec<u8>> = font[12..12 + count * 16].chunks(16).map(<[u8]>::to_vec).collect();
|
||||
let at = records.iter().position(|r| r.starts_with(b"cmap")).unwrap();
|
||||
let cmap = records.remove(at);
|
||||
records.push(cmap);
|
||||
font.splice(12..12 + count * 16, records.concat());
|
||||
let raw = ttf_parser::RawFace::parse(&font, 0).unwrap();
|
||||
assert!(raw.table(ttf_parser::Tag::from_bytes(b"cmap")).is_none(), "a binary search misses the cmap");
|
||||
assert!(raw.table(ttf_parser::Tag::from_bytes(b"name")).is_some(), "fontdb still finds the name");
|
||||
let path = std::env::temp_dir().join(format!("photocraft-svg-test-unsorted-{}.ttf", std::process::id()));
|
||||
std::fs::write(&path, font).unwrap();
|
||||
let mut db = usvg::fontdb::Database::new();
|
||||
db.load_font_data(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec());
|
||||
db.load_font_file(&path).unwrap();
|
||||
Arc::new(db)
|
||||
}
|
||||
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"60\"><text x=\"5\" y=\"45\" font-family=\"Inter\">I\xE2\x94\x80I</text></svg>";
|
||||
let parsed = parse_with(svg, inter_and_unsorted_mono_on_disk).unwrap();
|
||||
let _ = std::fs::remove_file(std::env::temp_dir().join(format!("photocraft-svg-test-unsorted-{}.ttf", std::process::id())));
|
||||
let mono =
|
||||
parsed.tree.fontdb().faces().any(|f| f.families.iter().any(|(n, _)| n == "JetBrains Mono") && matches!(f.source, usvg::fontdb::Source::Binary(_)));
|
||||
assert!(mono, "the box-drawing character falls back to JetBrains Mono");
|
||||
}
|
||||
|
||||
/// #9406: moving a font collection into memory keeps its faces in their order, so the
|
||||
/// fallback search for a later text still finds the face it found on disk first.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -15,7 +15,7 @@ pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result<Document<'i>
|
||||
if opts.allow_dtd && internal_subset(text.as_bytes()) {
|
||||
return Err("internal DTD subsets aren't supported".into());
|
||||
}
|
||||
if crate::svg::nesting_depth(text.as_bytes(), MAX_DEPTH) > MAX_DEPTH {
|
||||
if crate::svg::nesting_depth(text.as_bytes(), MAX_DEPTH).map_err(|e| e.to_string())? > MAX_DEPTH {
|
||||
return Err(format!("elements are nested more than {MAX_DEPTH} levels deep"));
|
||||
}
|
||||
Document::parse_with_options(text, opts).map_err(|e| e.to_string())
|
||||
|
||||
@@ -411,6 +411,53 @@ fn deeply_nested_markup_is_an_error_not_a_stack_overflow() {
|
||||
assert_eq!(r.document.layers.len(), 1);
|
||||
}
|
||||
|
||||
/// The parser expands a DTD's internal entities after the depth check: an entity holding
|
||||
/// markup, or a quote in a DTD comment or declaration that made the check skip ahead, hid 20 000 nested groups
|
||||
/// from it and overflowed the stack again. Both are errors now; same small stack as above.
|
||||
#[test]
|
||||
fn a_dtd_cannot_hide_nesting_from_the_depth_check() {
|
||||
let deep = |open: &str, close: &str| format!("{}{}", open.repeat(20_000), close.repeat(20_000));
|
||||
let with_dtd = |subset: &str, body: &str| format!("<!DOCTYPE svg [{subset}]><svg {NS} width=\"8\" height=\"8\">{body}</svg>");
|
||||
let cases = [
|
||||
("entity", with_dtd(&format!("<!ENTITY a \"{}\">", deep("<g>", "</g>")), "&a;")),
|
||||
("single-quoted entity", with_dtd(&format!("<!ENTITY a '{}'>", deep("<g>", "</g>")), "&a;")),
|
||||
("quote in a comment", with_dtd("<!-- ' -->", &format!("{}<desc>'</desc>", deep("<g>", "</g>")))),
|
||||
("quote in an element declaration", with_dtd("<!ELEMENT x '>", &format!("{}<desc>'</desc>", deep("<g>", "</g>")))),
|
||||
(
|
||||
"entity between quoted attribute lists",
|
||||
with_dtd(&format!("<!ATTLIST svg x CDATA '><!ENTITY a \"{}\"><!ATTLIST svg y CDATA '>", deep("<g>", "</g>")), "&a;"),
|
||||
),
|
||||
("entity between quoted notations", with_dtd(&format!("<!NOTATION n SYSTEM '><!ENTITY a \"{}\"><!NOTATION m SYSTEM '>", deep("<g>", "</g>")), "&a;")),
|
||||
];
|
||||
std::thread::Builder::new()
|
||||
.stack_size(512 * 1024)
|
||||
.spawn(move || {
|
||||
for (name, svg) in &cases {
|
||||
let gz = gzip(svg.as_bytes());
|
||||
for bytes in [svg.as_bytes(), gz.as_slice()] {
|
||||
let e = import("deep.svg", bytes).err().unwrap_or_else(|| panic!("{name} opened"));
|
||||
assert!(matches!(&e, IoError::Svg(_)), "{name}: {e}");
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Text-only entities, as Illustrator declares its namespaces, still open, `<` included:
|
||||
/// the parser keeps a character reference in an entity as text.
|
||||
#[test]
|
||||
fn text_entities_in_a_dtd_still_open() {
|
||||
let r = open(
|
||||
"<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\" [\
|
||||
<!ENTITY ns_svg \"http://www.w3.org/2000/svg\"> <!-- a ' and a <g> --> <?pi > ?> <!ATTLIST svg data-x CDATA '<'> <!ENTITY red '#ff0000'> <!ENTITY c \"© <g>\"> ]>\
|
||||
<svg xmlns=\"&ns_svg;\" width=\"8\" height=\"8\"><title>&c;</title><rect width=\"8\" height=\"8\" fill=\"&red;\"/></svg>",
|
||||
);
|
||||
assert_eq!(r.document.layers.len(), 1);
|
||||
assert!(close(px(&r.document, 4, 4), [1.0, 0.0, 0.0, 1.0]));
|
||||
}
|
||||
|
||||
/// The depth check reads the markup, not the parser's tree: it must not count `<` in comments,
|
||||
/// CDATA, processing instructions or the DOCTYPE, nor end a tag at a `>` inside quotes.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! #5532: the Layers panel's Blend Mode list draws a line between Photoshop's six groups of modes:
|
||||
//! Normal, Dissolve | Darken … Darker Color | Lighten … Lighter Color | Overlay … Hard Mix |
|
||||
//! Difference … Divide | Hue … Luminosity.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui::{Pos2, Rect, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use photocraft_doc::BlendMode;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
/// The app at 1440×900 with a new document and a pixel layer above the Background, active.
|
||||
fn harness() -> Harness<'static, PhotocraftApp> {
|
||||
let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(8);
|
||||
h
|
||||
}
|
||||
|
||||
/// The Layers panel's dropdown: the lowest one (the options bar and the title bar have some too).
|
||||
fn dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect {
|
||||
h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).unwrap()
|
||||
}
|
||||
|
||||
/// The open list's rect (the one foreground area: no other popup is open).
|
||||
fn open_list(h: &Harness<'_, PhotocraftApp>) -> Option<Rect> {
|
||||
h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id)))
|
||||
}
|
||||
|
||||
fn blend(h: &Harness<'_, PhotocraftApp>) -> BlendMode {
|
||||
let st = h.state().session.active().unwrap();
|
||||
st.doc.layer(st.active_layer.unwrap()).unwrap().blend
|
||||
}
|
||||
|
||||
fn steps(h: &Harness<'_, PhotocraftApp>) -> usize {
|
||||
h.state().session.active().unwrap().history.past_len()
|
||||
}
|
||||
|
||||
/// Presses at `at`, holds for `held` frames and releases there.
|
||||
fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, held: usize) {
|
||||
h.hover_at(at);
|
||||
h.run_steps(1);
|
||||
for (pressed, frames) in [(true, held), (false, 4)] {
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
|
||||
h.run_steps(frames);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_layers_blend_mode_list_has_a_line_between_each_group() {
|
||||
let mut h = harness();
|
||||
let at = dropdown(&h).center();
|
||||
click(&mut h, at, 1);
|
||||
assert!(open_list(&h).is_some(), "the list is open");
|
||||
// Each mode's row in the open list: its label's last node (the box shows the chosen one's
|
||||
// first). Rows scrolled out of the list keep their place in it, so the gaps hold for all.
|
||||
let rows: Vec<Rect> = BlendMode::LAYER_MODES
|
||||
.iter()
|
||||
.map(|m| h.get_all_by_label(m.label()).map(|n| n.rect()).next_back().unwrap_or_else(|| panic!("{m:?} is in the list")))
|
||||
.collect();
|
||||
let gaps: Vec<f32> = rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect();
|
||||
let row_gap = gaps.iter().copied().fold(f32::INFINITY, f32::min);
|
||||
let lines: Vec<(BlendMode, BlendMode)> =
|
||||
gaps.iter().enumerate().filter(|(_, g)| **g > row_gap + 2.0).map(|(i, _)| (BlendMode::LAYER_MODES[i], BlendMode::LAYER_MODES[i + 1])).collect();
|
||||
assert_eq!(
|
||||
lines,
|
||||
[
|
||||
(BlendMode::Dissolve, BlendMode::Darken),
|
||||
(BlendMode::DarkerColor, BlendMode::Lighten),
|
||||
(BlendMode::LighterColor, BlendMode::Overlay),
|
||||
(BlendMode::HardMix, BlendMode::Difference),
|
||||
(BlendMode::Divide, BlendMode::Hue),
|
||||
],
|
||||
"row gaps {gaps:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A plain click on the Layers panel's Blend Mode box at 1440×900, released where it was pressed
|
||||
/// (after one frame, or after a few as a person's click takes), opens the list beside the box and
|
||||
/// chooses nothing: the list doesn't open over the box, where the release would pick a row
|
||||
/// (#5495 review of a taller list).
|
||||
#[test]
|
||||
fn a_click_on_the_blend_mode_box_opens_the_list_and_changes_nothing() {
|
||||
for held in [6, 1] {
|
||||
let mut h = harness();
|
||||
let undo = steps(&h);
|
||||
let button = dropdown(&h);
|
||||
click(&mut h, button.center(), held);
|
||||
assert_eq!((blend(&h), steps(&h)), (BlendMode::Normal, undo), "held {held}: the click chose nothing");
|
||||
let Some(list) = open_list(&h) else { panic!("held {held}: the list is open") };
|
||||
assert!(!list.intersects(button.shrink(1.0)), "held {held}: the list {list:?} leaves the box {button:?} free");
|
||||
assert!(list.top() >= 0.0 && list.bottom() <= 900.0, "held {held}: the list {list:?} is in the window");
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ pub(crate) fn choices() -> Vec<((Option<BlendMode>, bool), &'static str)> {
|
||||
fn blend_items(behind: bool, clear: bool) -> Vec<Item> {
|
||||
let mut out = Vec::new();
|
||||
for m in BlendMode::LAYER_MODES {
|
||||
if matches!(m, BlendMode::Darken | BlendMode::Lighten | BlendMode::Overlay | BlendMode::Difference | BlendMode::Hue) {
|
||||
if crate::panels::starts_blend_group(m) {
|
||||
out.push(Item::Separator);
|
||||
}
|
||||
out.push(Item::Blend(m));
|
||||
|
||||
@@ -1699,9 +1699,14 @@ fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut Vie
|
||||
painter.set(layer_edges, egui::Shape::rect_stroke(xf.doc_rect(b), 0, Stroke::new(1.0, LAYER_EDGES), egui::StrokeKind::Outside));
|
||||
}
|
||||
// A tool drag held past the canvas edge scrolls the view toward the pointer (#4183); the
|
||||
// drag's next move then extends into what scrolled in.
|
||||
// drag's next move then extends into what scrolled in. The crop tools keep their own drags:
|
||||
// they scroll only while the press is the canvas's own (not a panel slider or a scrollbar held
|
||||
// while a stale crop drag lingers) and the crop tool has it (not a temporary Zoom, which
|
||||
// freezes the drag).
|
||||
let crop_drag =
|
||||
response.is_pointer_button_down_on() && tool == app.ui.tool && (crate::crop_ui::autoscrolls(app) || crate::perspective_crop_ui::dragging(app));
|
||||
if primary
|
||||
&& app.drag.is_some()
|
||||
&& (app.drag.is_some() || crop_drag)
|
||||
&& tool != Tool::Hand
|
||||
&& !middle
|
||||
&& let Some(p) = ui.input(|i| i.pointer.primary_down().then(|| i.pointer.latest_pos()).flatten())
|
||||
@@ -1962,6 +1967,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
crate::crop_straighten::set_held(app, !ctx.text_edit_focused() && ui.input(|i| i.modifiers.command));
|
||||
// A tab switched this frame drops the other document's pending crop (#1918).
|
||||
crate::crop_ui::cancel_stale(app);
|
||||
// A tool picked mid-drag ends the crop gesture before the frame sees the switch, which would
|
||||
// otherwise drop the untouched default frame under the box being drawn (#9223). The Hand and
|
||||
// Zoom never reach `tool_event`, so this is the one place that sees every tool.
|
||||
crate::crop_ui::end_drag_on_leave(app);
|
||||
crate::crop_ui::ensure_frame(app);
|
||||
let mut drawing = crate::crop_ui::active(app);
|
||||
if let Some(pen) = app.ui.pen.as_mut().filter(|pen| pen.dragging && !pen.curvature) {
|
||||
|
||||
@@ -61,6 +61,12 @@ fn preflight_tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modi
|
||||
{
|
||||
crate::guide_select::clear(app);
|
||||
}
|
||||
// A tool key pressed mid-drag ends the crop gesture here: a later handler can take every event
|
||||
// of the new tool, and a drag left set keeps the frame from committing on leave. It ends as a
|
||||
// release would, so a box drawn over the untouched default frame is committed, not dropped (#9223).
|
||||
if app.ui.tool != Tool::Crop {
|
||||
crate::crop_ui::end_drag(app);
|
||||
}
|
||||
if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -50,6 +50,30 @@ fn dialog_maps_to_engine_command() {
|
||||
assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50));
|
||||
}
|
||||
|
||||
/// #9260: OK with a new Width resizes a document whose own resolution is outside the range
|
||||
/// the command accepts (an imported PNG's pHYs of 1 px/m is 0.0254 ppi); the dialog sends that
|
||||
/// resolution back unchanged.
|
||||
#[test]
|
||||
fn ok_resizes_a_document_with_an_imported_resolution_out_of_range() {
|
||||
for own in [0.0254_f32, 40_000.0] {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.session.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap();
|
||||
app.session
|
||||
.edit("ppi", |doc, _| {
|
||||
doc.resolution_dpi = own;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let id = open(&mut app, "image.imageSize").unwrap();
|
||||
let d = app.ui.dialog_mut(id).unwrap();
|
||||
d.fields.insert("width".into(), json!(100));
|
||||
d.fields.insert("height".into(), json!(50));
|
||||
crate::dialogs::confirm(&mut app, id).unwrap();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
assert_eq!((doc.size, doc.resolution_dpi), (photocraft_doc::Size::new(100, 50), own), "{own}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_reset_restores_open_dimensions() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
|
||||
@@ -820,8 +820,12 @@ fn handle_registry_and_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f
|
||||
return true;
|
||||
}
|
||||
// In a full screen mode, the Crop tool's untouched default frame (Straighten off) has nothing to cancel: cancelling only
|
||||
// makes the next one, so Esc goes on to leave full screen (#7315).
|
||||
let untouched = app.ui.view.screen_mode != "standard" && app.ui.polygon.is_empty() && app.crop.default_frame && !crate::crop_straighten::mode(app);
|
||||
// makes the next one, so Esc goes on to leave full screen (#7315). A gesture on it is still cancelled (#9275).
|
||||
let untouched = app.ui.view.screen_mode != "standard"
|
||||
&& app.ui.polygon.is_empty()
|
||||
&& app.crop.default_frame
|
||||
&& app.crop.drag.is_none()
|
||||
&& !crate::crop_straighten::mode(app);
|
||||
if !untouched && pressed(Key::Escape) {
|
||||
app.ui.polygon.clear();
|
||||
app.ui.polygon_mode.clear();
|
||||
|
||||
@@ -881,6 +881,9 @@ mod blend_dropdown_wheel_tests;
|
||||
#[cfg(test)]
|
||||
mod paths_scroll_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod blend_dropdown_groups_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod options_bar_mode_wheel_tests;
|
||||
|
||||
|
||||
@@ -764,6 +764,29 @@ fn esc_leaves_full_screen_with_the_crop_tool_showing_its_default_frame() {
|
||||
assert_eq!(app.ui.view.screen_mode, "standard");
|
||||
}
|
||||
|
||||
/// #9275: a gesture on the default frame is something to cancel, so Esc in full screen cancels it
|
||||
/// (as in Standard Screen Mode) and full screen stays.
|
||||
#[test]
|
||||
fn esc_in_full_screen_cancels_a_crop_drag_on_the_default_frame() {
|
||||
use crate::canvas::{ToolEvent, tool_event};
|
||||
let none = egui::Modifiers::NONE;
|
||||
// Inside draws a new box, on the corner handle resizes, outside turns.
|
||||
for (what, from) in [("draw", [20.0, 20.0]), ("resize", [100.0, 80.0]), ("turn", [130.0, 110.0])] {
|
||||
let (mut app, ctx) = app_with(1);
|
||||
app.ui.tool = crate::Tool::Crop;
|
||||
crate::crop_ui::ensure_frame(&mut app);
|
||||
menu(&mut app, &ctx, "view.screenMode.fullScreen", json!({})).unwrap();
|
||||
tool_event(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, none);
|
||||
tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 50.0, pressure: 1.0 }, none);
|
||||
assert!(app.crop.drag.is_some() && app.crop.default_frame, "{what}: mid-gesture on the default frame");
|
||||
press_esc(&mut app, &ctx);
|
||||
assert_eq!(app.ui.view.screen_mode, "fullScreen", "{what}: Esc cancels the gesture, full screen stays");
|
||||
assert!(app.crop.drag.is_none(), "{what}: the gesture is cancelled");
|
||||
tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 50.0 }, none);
|
||||
assert!(!crate::crop_ui::pending(&app), "{what}: the release leaves no pending crop");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn esc_leaves_full_screen_modes_unless_something_else_owns_it() {
|
||||
let (mut app, ctx) = app_with(1);
|
||||
|
||||
@@ -262,6 +262,13 @@ mod title_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether blend mode `m` starts one of the groups Photoshop's blend mode lists draw a line above:
|
||||
/// Normal, Dissolve (and Pass Through, Clear) | darken | lighten | contrast | difference | colour
|
||||
/// (#5532). The first mode of a list never gets a line.
|
||||
pub(crate) fn starts_blend_group(m: BlendMode) -> bool {
|
||||
matches!(m, BlendMode::Darken | BlendMode::Lighten | BlendMode::Overlay | BlendMode::Difference | BlendMode::Hue)
|
||||
}
|
||||
|
||||
fn label(ui: &mut egui::Ui, s: &str) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.label(RichText::new(s).color(t.text_dim));
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, StrokeKind, Tokens, c32, icons, json, pos2, vec2, widgets};
|
||||
use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, StrokeKind, Tokens, c32, icons, json, pos2, starts_blend_group, vec2, widgets};
|
||||
|
||||
/// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the
|
||||
/// mode. Returns the mode picked this frame.
|
||||
/// mode. Returns the mode picked this frame. A list of every blend mode draws the Layers panel's
|
||||
/// group lines (#5532; Clear starts none); a short one (the Healing Brush's) draws none.
|
||||
pub(super) fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option<BlendMode>], current: Option<BlendMode>) -> Option<Option<BlendMode>> {
|
||||
let opts: Vec<(Option<BlendMode>, &str)> = modes.iter().map(|m| (*m, m.map_or("Clear", BlendMode::label))).collect();
|
||||
let grouped = BlendMode::LAYER_MODES.iter().all(|m| modes.contains(&Some(*m)));
|
||||
let mut mode = current;
|
||||
let chosen = widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0;
|
||||
let chosen = widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| grouped && m.is_some_and(starts_blend_group)).0;
|
||||
chosen.last().copied()
|
||||
}
|
||||
|
||||
@@ -21,7 +23,7 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf
|
||||
} else {
|
||||
(Some(b.mode), false)
|
||||
};
|
||||
if !widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0.is_empty() {
|
||||
if !widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| m.0.is_some_and(starts_blend_group)).0.is_empty() {
|
||||
*clear = mode == (None, false);
|
||||
b.behind = mode.1;
|
||||
if mode.1 {
|
||||
|
||||
@@ -4,7 +4,9 @@ use super::layer_drag::{
|
||||
};
|
||||
use super::layer_row::{RowSel, layer_row};
|
||||
use super::options_bar::{LAYER_PCT_W, body_text_width, pct_action, scrub_pct_label};
|
||||
use super::{BlendMode, Layer, LayerId, MaskKind, PhotocraftApp, Rect, Sense, Tokens, Value, empty, icons, json, label, pos2, theme, vec2, widgets};
|
||||
use super::{
|
||||
BlendMode, Layer, LayerId, MaskKind, PhotocraftApp, Rect, Sense, Tokens, Value, empty, icons, json, label, pos2, starts_blend_group, theme, vec2, widgets,
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------- layers
|
||||
|
||||
@@ -58,7 +60,7 @@ fn inactive_blend_rows(ui: &mut egui::Ui, pro: bool) {
|
||||
let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x);
|
||||
let mut m = BlendMode::Normal;
|
||||
let options = blend_options(false, m);
|
||||
widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width);
|
||||
widgets::dropdown_wheel_grouped(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width, |m| starts_blend_group(*m));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let mut o = 100.0;
|
||||
widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W);
|
||||
@@ -154,7 +156,9 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let (blend_width, show_opacity_label) =
|
||||
opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x);
|
||||
let (chosen, hovered) =
|
||||
widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &blend_options(all_groups, l.blend), blend_width);
|
||||
widgets::dropdown_wheel_grouped(ui, "blend", tl!("Blend Mode"), &mut m, &blend_options(all_groups, l.blend), blend_width, |m| {
|
||||
starts_blend_group(*m)
|
||||
});
|
||||
// One step per choice: a click, an arrow key or each wheel notch (#1747).
|
||||
for m in &chosen {
|
||||
let mut p = targets.clone();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::brush_controls::{brush_preset_chip, mixer_load_swatch, paint_mode_dropdown, smoothing_field, smoothing_options, tool_mode_dropdown};
|
||||
use super::properties::{select_and_mask_button, selection_mode_buttons};
|
||||
use super::{BlendMode, Color32, PhotocraftApp, RichText, Sense, Tokens, Tool, Value, icons, json, vec2, widgets};
|
||||
use super::{BlendMode, Color32, PhotocraftApp, RichText, Sense, Tokens, Tool, Value, icons, json, starts_blend_group, vec2, widgets};
|
||||
use photocraft_paint::BrushSettings;
|
||||
|
||||
// Custom controls also need to bring keyboard focus into a scroll viewport.
|
||||
@@ -449,7 +449,9 @@ fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool:
|
||||
opt_label(ui, tl!("Mode"));
|
||||
let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect();
|
||||
// The wheel over it steps the mode, as over the Layers panel's (#2061).
|
||||
widgets::dropdown_wheel_hovered(ui, "gradient-blend-mode", tl!("Blend Mode"), &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0);
|
||||
widgets::dropdown_wheel_grouped(ui, "gradient-blend-mode", tl!("Blend Mode"), &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0, |m| {
|
||||
starts_blend_group(*m)
|
||||
});
|
||||
opt_label(ui, tl!("Opacity"));
|
||||
let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);
|
||||
// Live while scrubbed, one undo step per scrub (#5012).
|
||||
|
||||
@@ -499,6 +499,29 @@ pub fn active(app: &PhotocraftApp) -> bool {
|
||||
app.ui.tool == Tool::Crop && app.crop.drag.is_some()
|
||||
}
|
||||
|
||||
/// A drag that sizes or moves the frame over the image, which scrolls the view when held past the
|
||||
/// canvas edge (#4183). Not the turns, nor the default mode's image moves and live-centred resizes:
|
||||
/// those drive the camera themselves. A new frame's drag that hasn't left the size of a click (a
|
||||
/// long press that slipped past the edge) doesn't either: scrolling would draw a frame under the
|
||||
/// still pointer.
|
||||
pub fn autoscrolls(app: &PhotocraftApp) -> bool {
|
||||
app.ui.tool == Tool::Crop
|
||||
&& match app.crop.drag {
|
||||
Some(CropDrag::Draw { anchor, cur, .. }) => !is_click(app, anchor, cur),
|
||||
Some(CropDrag::Move { .. } | CropDrag::Resize { view: None, .. }) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A new-frame drag shorter than this (screen points) on both axes is still a click.
|
||||
const CLICK_PX: f64 = 3.0;
|
||||
|
||||
/// Document points `a` and `b` lie within [`CLICK_PX`] screen points of each other on both axes.
|
||||
fn is_click(app: &PhotocraftApp, a: [f64; 2], b: [f64; 2]) -> bool {
|
||||
let click = CLICK_PX / (app.point_zoom() as f64).max(0.01);
|
||||
(b[0] - a[0]).abs() <= click && (b[1] - a[1]).abs() <= click
|
||||
}
|
||||
|
||||
/// Cancel the pending crop: the frame, any gesture on it and the default-frame state. With the
|
||||
/// Crop tool still picked, [`ensure_frame`] then makes the active document a new default frame.
|
||||
pub fn cancel(app: &mut PhotocraftApp) {
|
||||
@@ -952,7 +975,7 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
/// Pointer input for the Crop tool. Returns true when the event was its.
|
||||
pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool {
|
||||
if app.ui.tool != Tool::Crop {
|
||||
app.crop.drag = None;
|
||||
end_drag(app);
|
||||
return false;
|
||||
}
|
||||
let p = match ev {
|
||||
@@ -1060,7 +1083,9 @@ fn release(app: &mut PhotocraftApp, drag: CropDrag) {
|
||||
let ok = app.ui.crop_rect.is_some_and(size_ok);
|
||||
// A click outside the untouched default frame (no turn) leaves it the default.
|
||||
let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app))
|
||||
&& !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect));
|
||||
&& !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect))
|
||||
// A press that never moved draws nothing: the frame shown is still the previous one.
|
||||
&& !matches!(drag, CropDrag::Draw { anchor, cur, .. } if anchor == cur);
|
||||
if ok && changed {
|
||||
app.crop.default_frame = false;
|
||||
}
|
||||
@@ -1072,6 +1097,25 @@ fn release(app: &mut PhotocraftApp, drag: CropDrag) {
|
||||
push_press_step(app);
|
||||
}
|
||||
|
||||
/// Another tool was picked while a drag on the frame is held (a tool key, #9223): the gesture ends
|
||||
/// where the pointer last moved it, as a release there would, so a box drawn over the untouched
|
||||
/// default frame counts as drawn and leaving the tool commits it.
|
||||
pub fn end_drag(app: &mut PhotocraftApp) {
|
||||
let Some(drag) = app.crop.drag.take() else { return };
|
||||
let tool = std::mem::replace(&mut app.ui.tool, Tool::Crop);
|
||||
release(app, drag);
|
||||
crate::crop_mode::sync_frame(app);
|
||||
app.ui.tool = tool;
|
||||
}
|
||||
|
||||
/// [`end_drag`] once another tool is current, except while the pen's eraser end stands in for the
|
||||
/// Crop tool (`stylus`): the gesture goes on when the tip comes back.
|
||||
pub fn end_drag_on_leave(app: &mut PhotocraftApp) {
|
||||
if app.ui.tool != Tool::Crop && app.stylus.tool_before_eraser != Some(Tool::Crop) {
|
||||
end_drag(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// On release: the frame state at the press becomes a box Undo step when the gesture changed it.
|
||||
fn push_press_step(app: &mut PhotocraftApp) {
|
||||
if let Some(before) = app.crop.press_step.take()
|
||||
|
||||
@@ -665,6 +665,226 @@ fn space_on_the_canvas_moves_the_frame_not_the_view() {
|
||||
assert!(st.crop.drag.is_none());
|
||||
}
|
||||
|
||||
/// Real egui input: a handle dragged past the canvas edge and held there scrolls the view, as a
|
||||
/// marquee drag does (#4183), so the frame can reach the part of the image that was off screen.
|
||||
#[test]
|
||||
fn a_handle_held_past_the_canvas_edge_scrolls_the_view() {
|
||||
use egui::{Event, PointerButton, pos2};
|
||||
let mut a = app(SampleType::U8);
|
||||
// 200x100 at 400% in a 600x400 canvas: document x 25..175 shows.
|
||||
a.ui.views = vec![crate::state::View {
|
||||
zoom: 4.0,
|
||||
center: [100.0, 50.0],
|
||||
fit_pending: false,
|
||||
fill_pending: false,
|
||||
doc_size: [200, 100],
|
||||
rotation: 0.0,
|
||||
zoom_animating: false,
|
||||
zoom_anchor: None,
|
||||
display_camera: None,
|
||||
zoom_transition: None,
|
||||
}];
|
||||
a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]);
|
||||
a.crop.default_frame = false;
|
||||
a.ui.extras.rulers = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
// The right edge's middle handle: document (100, 25).
|
||||
let p0 = h.state().ui.views[0].center;
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
|
||||
let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: p0, flip: false, rotation: 0.0, aspect: 1.0 };
|
||||
let grab = xf.to_screen(100.0, 25.0);
|
||||
h.event(Event::PointerMoved(grab));
|
||||
h.event(button(grab, true));
|
||||
h.step();
|
||||
let out = pos2(650.0, grab.y);
|
||||
for p in [pos2(grab.x + 40.0, grab.y), out] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
let before = h.state().ui.views[0].center;
|
||||
h.run_steps(10);
|
||||
let st = h.state();
|
||||
assert!(matches!(st.crop.drag, Some(CropDrag::Resize { .. })), "{:?}", st.crop.drag);
|
||||
assert!(st.ui.views[0].center[0] > before[0], "the view scrolled right: {:?} -> {:?}", before, st.ui.views[0].center);
|
||||
assert!(st.ui.crop_rect.is_some_and(|r| r[2] > 175.0), "the frame reached past what showed: {:?}", st.ui.crop_rect);
|
||||
h.event(button(out, false));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// A press that started off the canvas (a panel slider beside it) doesn't scroll the view,
|
||||
/// even with a crop drag still recorded: only a drag on the canvas auto-scrolls.
|
||||
#[test]
|
||||
fn a_press_beside_the_canvas_does_not_scroll_it_for_a_crop_drag() {
|
||||
use egui::{Event, PointerButton, pos2};
|
||||
let mut a = app(SampleType::U8);
|
||||
a.ui.views = vec![crate::state::View {
|
||||
zoom: 4.0,
|
||||
center: [100.0, 50.0],
|
||||
fit_pending: false,
|
||||
fill_pending: false,
|
||||
doc_size: [200, 100],
|
||||
rotation: 0.0,
|
||||
zoom_animating: false,
|
||||
zoom_anchor: None,
|
||||
display_camera: None,
|
||||
zoom_transition: None,
|
||||
}];
|
||||
a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]);
|
||||
a.crop.default_frame = false;
|
||||
a.ui.extras.rulers = false;
|
||||
// Left over from a drag a tool switch didn't end.
|
||||
a.crop.drag = Some(CropDrag::Resize { hx: 1, hy: 0, start: [100.0, 25.0], rect: [40.0, 10.0, 100.0, 40.0], view: None });
|
||||
// The canvas takes the left 400 points; the rest stands in for a panel.
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 400.0));
|
||||
crate::canvas::canvas_view(app, ui, 0, rect, v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
let p = pos2(500.0, 100.0);
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.event(button(p, true));
|
||||
h.step();
|
||||
h.event(Event::PointerMoved(pos2(550.0, 100.0)));
|
||||
h.run_steps(10);
|
||||
assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "the view stayed put");
|
||||
h.event(button(pos2(550.0, 100.0), false));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// The 200x100 test document at 400% (document x 25..175 shows in a 600-point canvas).
|
||||
fn zoomed_view(height: u32) -> crate::state::View {
|
||||
crate::state::View {
|
||||
zoom: 4.0,
|
||||
center: [100.0, height as f32 / 2.0],
|
||||
fit_pending: false,
|
||||
fill_pending: false,
|
||||
doc_size: [200, height],
|
||||
rotation: 0.0,
|
||||
zoom_animating: false,
|
||||
zoom_anchor: None,
|
||||
display_camera: None,
|
||||
zoom_transition: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A press held just inside the canvas edge (past egui's click time, so egui starts a drag) that
|
||||
/// slips a point past it is still a click: it draws no frame and doesn't scroll the view, which
|
||||
/// would grow a frame under the still pointer. A new frame dragged past the edge does scroll.
|
||||
#[test]
|
||||
fn a_held_click_at_the_canvas_edge_draws_no_frame_and_does_not_scroll() {
|
||||
use egui::{Event, PointerButton, pos2};
|
||||
let mut a = app(SampleType::U8);
|
||||
a.ui.views = vec![zoomed_view(100)];
|
||||
a.ui.extras.rulers = false;
|
||||
// The canvas starts 100 points from the window's left, so its left edge (no scrollbar there)
|
||||
// has room past it.
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(100.0, 0.0), egui::vec2(600.0, 400.0));
|
||||
crate::canvas::canvas_view(app, ui, 0, rect, v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
let frame = h.state().ui.crop_rect;
|
||||
assert!(h.state().crop.default_frame, "{frame:?}");
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
let press = pos2(101.0, 200.0);
|
||||
let slip = pos2(99.0, 200.0);
|
||||
h.event(Event::PointerMoved(press));
|
||||
h.event(button(press, true));
|
||||
h.step();
|
||||
for p in [slip, pos2(98.5, 200.0), slip] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.run_steps(4);
|
||||
}
|
||||
assert!(matches!(h.state().crop.drag, Some(CropDrag::Draw { .. })), "egui started a drag: {:?}", h.state().crop.drag);
|
||||
assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "a click doesn't scroll the view");
|
||||
h.event(button(slip, false));
|
||||
h.step();
|
||||
let st = h.state();
|
||||
assert_eq!(st.ui.crop_rect, frame, "the click drew no frame");
|
||||
assert!(st.crop.default_frame);
|
||||
// A new frame dragged from inside the canvas past its edge does scroll.
|
||||
let start = pos2(300.0, 200.0);
|
||||
h.event(Event::PointerMoved(start));
|
||||
h.event(button(start, true));
|
||||
h.step();
|
||||
for p in [pos2(240.0, 220.0), pos2(50.0, 220.0)] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
let before = h.state().ui.views[0].center;
|
||||
h.run_steps(10);
|
||||
let st = h.state();
|
||||
assert!(matches!(st.crop.drag, Some(CropDrag::Draw { .. })), "{:?}", st.crop.drag);
|
||||
assert!(st.ui.views[0].center[0] < before[0], "the frame drag scrolled left: {:?} -> {:?}", before, st.ui.views[0].center);
|
||||
assert!(st.ui.crop_rect.is_some_and(|r| r[0] < 25.0), "the frame reached past what showed: {:?}", st.ui.crop_rect);
|
||||
h.event(button(pos2(50.0, 220.0), false));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// A scrollbar drag is the scrollbar's, even with a crop drag still recorded (left over from a
|
||||
/// drag a tool switch didn't end): dragged out past the canvas edge, it doesn't auto-scroll the
|
||||
/// view as a crop drag would.
|
||||
#[test]
|
||||
fn a_scrollbar_drag_past_the_canvas_edge_does_not_scroll_for_a_crop_drag() {
|
||||
use egui::{Event, PointerButton, pos2};
|
||||
let doc = Document::with_background("crop", Size::new(200, 200), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.add_document(doc, None);
|
||||
let mut a = PhotocraftApp::new(s, crate::Services::default());
|
||||
a.ui.tool = Tool::Crop;
|
||||
a.ui.tool_options.crop_shield.classic_mode = true;
|
||||
a.ui.extras.snap = false;
|
||||
a.ui.extras.rulers = false;
|
||||
// 200x200 at 400% in a 600x400 canvas: both scrollbars show.
|
||||
a.ui.views = vec![zoomed_view(200)];
|
||||
a.ui.crop_rect = Some([40.0, 10.0, 100.0, 40.0]);
|
||||
a.crop.default_frame = false;
|
||||
a.crop.drag = Some(CropDrag::Resize { hx: 1, hy: 0, start: [100.0, 25.0], rect: [40.0, 10.0, 100.0, 40.0], view: None });
|
||||
// The window is taller than the canvas, so the pointer can leave it below the bottom bar.
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 500.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
|
||||
crate::canvas::canvas_view(app, ui, 0, rect, v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.view.shows_scrollbars());
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
// The horizontal bar's thumb (the view is centred, so is the thumb), dragged straight down
|
||||
// out of the canvas: the bar keeps x, and nothing else may move the view.
|
||||
let thumb = pos2(294.0, 400.0 - crate::canvas::scrollbars::THICKNESS / 2.0);
|
||||
h.event(Event::PointerMoved(thumb));
|
||||
h.event(button(thumb, true));
|
||||
h.step();
|
||||
for p in [pos2(294.0, 420.0), pos2(294.0, 480.0)] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
h.run_steps(10);
|
||||
assert_eq!(h.state().ui.views[0].center, [100.0, 100.0], "the view stayed put");
|
||||
h.event(button(pos2(294.0, 480.0), false));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file
|
||||
/// or switching tabs cancels it; it never shows on, or crops, another document.
|
||||
/// A turned pending frame is dropped with its angle when another document becomes active, and
|
||||
@@ -984,6 +1204,126 @@ fn the_stylus_eraser_and_a_gesture_in_progress_keep_the_frame_pending() {
|
||||
assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100));
|
||||
}
|
||||
|
||||
/// A tool key pressed while a drag on the frame is held (⇧C to Perspective Crop): the next
|
||||
/// tool's events end the gesture, even a tool that takes every event before the Crop tool's
|
||||
/// handler, and leaving then commits the frame as it does for any other tool (#3368).
|
||||
#[test]
|
||||
fn a_tool_switch_during_a_drag_ends_it_and_commits_the_frame() {
|
||||
for tool in [Tool::PerspectiveCrop, Tool::Ruler, Tool::Slice, Tool::Frame, Tool::Artboard, Tool::Brush] {
|
||||
let mut app = app(SampleType::U8);
|
||||
ensure_frame(&mut app);
|
||||
drag(&mut app, &[[20.0, 20.0], [120.0, 80.0]], NONE);
|
||||
tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 50.0, pressure: 1.0 }, NONE);
|
||||
assert!(app.crop.drag.is_some());
|
||||
app.ui.tool = tool;
|
||||
tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE);
|
||||
tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 50.0 }, NONE);
|
||||
assert!(app.crop.drag.is_none(), "{tool:?}");
|
||||
ensure_frame(&mut app);
|
||||
assert_eq!(app.ui.crop_rect, None, "{tool:?}");
|
||||
assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 60), "{tool:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The same mid-drag tool switch on the untouched default frame: a box drawn over it, or the
|
||||
/// frame resized by a handle, is an edit and commits on leave; a box too small to keep goes back
|
||||
/// to the default frame, which leaving drops (#9223).
|
||||
#[test]
|
||||
fn a_tool_switch_during_a_drag_on_the_default_frame_keeps_the_edit() {
|
||||
let cases: [(&[[f64; 2]], Size); 3] = [
|
||||
(&[[20.0, 20.0], [120.0, 80.0]], Size::new(100, 60)),
|
||||
(&[[200.0, 100.0], [150.0, 80.0]], Size::new(150, 80)),
|
||||
(&[[20.0, 20.0], [20.0, 20.0]], Size::new(200, 100)),
|
||||
];
|
||||
for (path, size) in cases {
|
||||
for tool in [Tool::PerspectiveCrop, Tool::Brush] {
|
||||
let mut app = app(SampleType::U8);
|
||||
ensure_frame(&mut app);
|
||||
assert!(app.crop.default_frame);
|
||||
tool_event(&mut app, ToolEvent::Down { x: path[0][0], y: path[0][1], pressure: 1.0 }, NONE);
|
||||
tool_event(&mut app, ToolEvent::Move { x: path[1][0], y: path[1][1], pressure: 1.0 }, NONE);
|
||||
assert!(app.crop.drag.is_some());
|
||||
app.ui.tool = tool;
|
||||
tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE);
|
||||
tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 50.0 }, NONE);
|
||||
assert!(app.crop.drag.is_none(), "{tool:?} {path:?}");
|
||||
ensure_frame(&mut app);
|
||||
assert_eq!(app.ui.crop_rect, None, "{tool:?} {path:?}");
|
||||
assert_eq!(app.session.active().unwrap().doc.size, size, "{tool:?} {path:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Real egui input: a tool picked while a box is being drawn over the untouched default frame
|
||||
/// (a tool key mid-drag) commits that box on leaving, whichever tool it is; the canvas ends the
|
||||
/// gesture before the frame sees the switch, also for the Hand, whose events never reach
|
||||
/// `tool_event` (#9223).
|
||||
#[test]
|
||||
fn a_tool_switch_during_a_real_drag_commits_the_drawn_box() {
|
||||
use egui::{Event, PointerButton, pos2};
|
||||
for tool in [Tool::Brush, Tool::PerspectiveCrop, Tool::Hand] {
|
||||
let mut a = app(SampleType::U8);
|
||||
a.sync_views();
|
||||
let v = &mut a.ui.views[0];
|
||||
(v.zoom, v.center, v.fit_pending, v.doc_size, v.rotation) = (2.0, [100.0, 50.0], false, [200, 100], 0.0);
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().crop.default_frame, "{tool:?}");
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
let p0 = pos2(200.0, 150.0);
|
||||
h.event(Event::PointerMoved(p0));
|
||||
h.event(button(p0, true));
|
||||
h.step();
|
||||
for p in [pos2(220.0, 170.0), pos2(260.0, 190.0)] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
assert!(h.state().crop.drag.is_some(), "{tool:?}");
|
||||
h.state_mut().ui.tool = tool;
|
||||
h.event(Event::PointerMoved(pos2(270.0, 195.0)));
|
||||
h.step();
|
||||
h.event(button(pos2(270.0, 195.0), false));
|
||||
h.run_steps(2);
|
||||
let st = h.state();
|
||||
assert!(st.crop.drag.is_none(), "{tool:?}");
|
||||
assert_eq!(st.ui.crop_rect, None, "{tool:?}");
|
||||
assert_eq!(st.session.active().unwrap().doc.size, Size::new(30, 20), "{tool:?}: the drawn 60x40 screen px at 200%");
|
||||
}
|
||||
}
|
||||
|
||||
/// A press inside the untouched default frame that never moves draws nothing, so the frame
|
||||
/// stays the default one and leaving drops it: no crop to the selection's bounds, released or
|
||||
/// cut short by a tool switch (#9223).
|
||||
#[test]
|
||||
fn a_press_that_never_moves_leaves_the_default_frame_untouched() {
|
||||
for switch in [false, true] {
|
||||
let mut app = app(SampleType::U8);
|
||||
app.run("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
ensure_frame(&mut app);
|
||||
assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 40.0, 60.0]));
|
||||
let steps = app.session.active().unwrap().history.past_len();
|
||||
tool_event(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, NONE);
|
||||
if switch {
|
||||
app.ui.tool = Tool::Brush;
|
||||
end_drag_on_leave(&mut app);
|
||||
} else {
|
||||
tool_event(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }, NONE);
|
||||
assert!(app.crop.default_frame, "a click is no edit");
|
||||
app.ui.tool = Tool::Brush;
|
||||
}
|
||||
ensure_frame(&mut app);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps), "switch: {switch}");
|
||||
assert_eq!(app.ui.crop_rect, None, "switch: {switch}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps).
|
||||
#[test]
|
||||
fn image_crop_menu_commits_a_pending_crop() {
|
||||
|
||||
@@ -53,6 +53,24 @@ pub fn pending(app: &PhotocraftApp) -> bool {
|
||||
app.ui.perspective_crop.is_some() || !app.pcrop.clicks.is_empty() || app.pcrop.drag.is_some()
|
||||
}
|
||||
|
||||
/// A box, corner or quad drag in progress: held past the canvas edge, it scrolls the view (#4183).
|
||||
/// A press that hasn't moved further than a click doesn't: scrolling would turn a corner-placing
|
||||
/// click near the edge into a box.
|
||||
pub fn dragging(app: &PhotocraftApp) -> bool {
|
||||
app.ui.tool == Tool::PerspectiveCrop
|
||||
&& match app.pcrop.drag {
|
||||
Some(Drag::New { start, cur }) => !is_click(app, start, cur),
|
||||
Some(_) => true,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A new-box press released within [`CLICK_PX`] screen points of where it began places a corner.
|
||||
fn is_click(app: &PhotocraftApp, start: [f64; 2], cur: [f64; 2]) -> bool {
|
||||
let click = crate::distort_ui::tolerance(app) * CLICK_PX / 8.0;
|
||||
(cur[0] - start[0]).abs() <= click && (cur[1] - start[1]).abs() <= click
|
||||
}
|
||||
|
||||
pub fn cancel(app: &mut PhotocraftApp) {
|
||||
app.ui.perspective_crop = None;
|
||||
app.pcrop.drag = None;
|
||||
@@ -121,8 +139,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) -> bool {
|
||||
ToolEvent::Up { .. } => {
|
||||
drag_to(app, p);
|
||||
if let Some(Drag::New { start, cur }) = app.pcrop.drag {
|
||||
let click = tol * CLICK_PX / 8.0;
|
||||
if (cur[0] - start[0]).abs() <= click && (cur[1] - start[1]).abs() <= click {
|
||||
if is_click(app, start, cur) {
|
||||
app.pcrop.clicks.push(start);
|
||||
if let [a, b, c, d] = app.pcrop.clicks[..] {
|
||||
app.ui.perspective_crop = Some(ordered([a, b, c, d]));
|
||||
@@ -327,6 +344,202 @@ mod tests {
|
||||
assert_eq!(app.ui.perspective_crop, None);
|
||||
}
|
||||
|
||||
/// Real egui input: a corner dragged past the canvas edge and held there scrolls the view, as a
|
||||
/// marquee drag does (#4183), so the corner can reach the part of the image that was off screen.
|
||||
#[test]
|
||||
fn a_corner_held_past_the_canvas_edge_scrolls_the_view() {
|
||||
use egui::{Event, Modifiers, PointerButton, pos2};
|
||||
let doc = Document::with_background("p", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.add_document(doc, None);
|
||||
let mut a = PhotocraftApp::new(s, crate::Services::default());
|
||||
a.ui.tool = Tool::PerspectiveCrop;
|
||||
a.ui.extras.snap = false;
|
||||
a.ui.extras.rulers = false;
|
||||
// 200x100 at 400% in a 600x400 canvas: document x 25..175 shows.
|
||||
a.ui.views = vec![crate::state::View {
|
||||
zoom: 4.0,
|
||||
center: [100.0, 50.0],
|
||||
fit_pending: false,
|
||||
fill_pending: false,
|
||||
doc_size: [200, 100],
|
||||
rotation: 0.0,
|
||||
zoom_animating: false,
|
||||
zoom_anchor: None,
|
||||
display_camera: None,
|
||||
zoom_transition: None,
|
||||
}];
|
||||
a.ui.perspective_crop = Some([[40.0, 10.0], [100.0, 10.0], [100.0, 40.0], [40.0, 40.0]]);
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
|
||||
let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 };
|
||||
// The top-right corner: document (100, 10).
|
||||
let grab = xf.to_screen(100.0, 10.0);
|
||||
h.event(Event::PointerMoved(grab));
|
||||
h.event(button(grab, true));
|
||||
h.step();
|
||||
let out = pos2(650.0, grab.y);
|
||||
for p in [pos2(grab.x + 40.0, grab.y), out] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
let before = h.state().ui.views[0].center;
|
||||
h.run_steps(10);
|
||||
let st = h.state();
|
||||
assert!(matches!(st.pcrop.drag, Some(Drag::Corner { index: 1, .. })), "{:?}", st.pcrop.drag);
|
||||
assert!(st.ui.views[0].center[0] > before[0], "the view scrolled right: {:?} -> {:?}", before, st.ui.views[0].center);
|
||||
assert!(st.ui.perspective_crop.is_some_and(|q| q[1][0] > 175.0), "the corner reached past what showed: {:?}", st.ui.perspective_crop);
|
||||
h.event(button(out, false));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// ⌘Space (Ctrl+Space off the Mac) pressed during a corner drag held past the canvas edge
|
||||
/// selects the temporary Zoom, which takes the pointer from the drag: the view no longer
|
||||
/// scrolls for the corner the Zoom froze.
|
||||
#[test]
|
||||
fn a_temporary_zoom_during_a_corner_drag_stops_the_scrolling() {
|
||||
use egui::{Event, Key, Modifiers, PointerButton, pos2};
|
||||
let doc = Document::with_background("p", Size::new(800, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.add_document(doc, None);
|
||||
let mut a = PhotocraftApp::new(s, crate::Services::default());
|
||||
a.ui.tool = Tool::PerspectiveCrop;
|
||||
a.ui.extras.snap = false;
|
||||
a.ui.extras.rulers = false;
|
||||
// 800x100 at 400% in a 600x400 canvas: document x 25..175 shows, with room to scroll right.
|
||||
a.ui.views = vec![crate::state::View {
|
||||
zoom: 4.0,
|
||||
center: [100.0, 50.0],
|
||||
fit_pending: false,
|
||||
fill_pending: false,
|
||||
doc_size: [800, 100],
|
||||
rotation: 0.0,
|
||||
zoom_animating: false,
|
||||
zoom_anchor: None,
|
||||
display_camera: None,
|
||||
zoom_transition: None,
|
||||
}];
|
||||
a.ui.perspective_crop = Some([[40.0, 10.0], [100.0, 10.0], [100.0, 40.0], [40.0, 40.0]]);
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
let button = |pos, pressed, modifiers| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers };
|
||||
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
|
||||
let xf = crate::canvas::ViewXform { rect, zoom: 4.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 };
|
||||
let grab = xf.to_screen(100.0, 10.0);
|
||||
h.event(Event::PointerMoved(grab));
|
||||
h.event(button(grab, true, Modifiers::NONE));
|
||||
h.step();
|
||||
let out = pos2(650.0, grab.y);
|
||||
for p in [pos2(grab.x + 40.0, grab.y), out] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
// Scrolling while the crop tool has the pointer.
|
||||
let before = h.state().ui.views[0].center;
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.views[0].center[0] > before[0], "the corner drag scrolls: {:?} -> {:?}", before, h.state().ui.views[0].center);
|
||||
let zoom = Modifiers::COMMAND;
|
||||
let zoom = if cfg!(target_os = "macos") { Modifiers { mac_cmd: true, ..zoom } } else { Modifiers { ctrl: true, ..zoom } };
|
||||
h.event(Event::ModifiersChanged(zoom));
|
||||
h.event(Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: zoom });
|
||||
h.step();
|
||||
assert_eq!(crate::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::hold_keys::Temporary::ZoomIn));
|
||||
assert!(h.state().pcrop.drag.is_some(), "the corner drag is still recorded");
|
||||
let before = h.state().ui.views[0].center;
|
||||
h.run_steps(10);
|
||||
assert_eq!(h.state().ui.views[0].center, before, "the temporary Zoom's press doesn't scroll for the corner");
|
||||
h.event(button(out, false, zoom));
|
||||
h.event(Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: zoom });
|
||||
h.event(Event::ModifiersChanged(Modifiers::NONE));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// A corner-placing click pressed just inside the canvas edge that slips a point past it doesn't
|
||||
/// scroll the view (scrolling would turn it into a box); a new box dragged past the edge does.
|
||||
#[test]
|
||||
fn a_click_at_the_canvas_edge_places_a_corner_without_scrolling() {
|
||||
use egui::{Event, Modifiers, PointerButton, pos2};
|
||||
let doc = Document::with_background("p", Size::new(200, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.add_document(doc, None);
|
||||
let mut a = PhotocraftApp::new(s, crate::Services::default());
|
||||
a.ui.tool = Tool::PerspectiveCrop;
|
||||
a.ui.extras.snap = false;
|
||||
a.ui.extras.rulers = false;
|
||||
// 200x100 at 400% in a 600x400 canvas 100 points from the window's left: document x 25..175
|
||||
// shows.
|
||||
a.ui.views = vec![crate::state::View {
|
||||
zoom: 4.0,
|
||||
center: [100.0, 50.0],
|
||||
fit_pending: false,
|
||||
fill_pending: false,
|
||||
doc_size: [200, 100],
|
||||
rotation: 0.0,
|
||||
zoom_animating: false,
|
||||
zoom_anchor: None,
|
||||
display_camera: None,
|
||||
zoom_transition: None,
|
||||
}];
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let v = app.ui.views[0].clone();
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(100.0, 0.0), egui::vec2(600.0, 400.0));
|
||||
crate::canvas::canvas_view(app, ui, 0, rect, v, true);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
|
||||
// Pressed a point inside the left edge (the scrollbars sit right and bottom), slipping two
|
||||
// points past it: still a click.
|
||||
let press = pos2(101.0, 200.0);
|
||||
let slip = pos2(99.0, 200.0);
|
||||
h.event(Event::PointerMoved(press));
|
||||
h.event(button(press, true));
|
||||
h.step();
|
||||
// Held past egui's click time, the press becomes a drag that hasn't left the click size.
|
||||
for p in [slip, pos2(98.5, 200.0), slip] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.run_steps(4);
|
||||
}
|
||||
assert_eq!(h.state().ui.views[0].center, [100.0, 50.0], "a click doesn't scroll the view");
|
||||
h.event(button(slip, false));
|
||||
h.step();
|
||||
let st = h.state();
|
||||
assert_eq!(st.pcrop.clicks.len(), 1, "the click placed a corner: {:?}", st.pcrop.clicks);
|
||||
assert_eq!(st.ui.perspective_crop, None);
|
||||
// A new box dragged from inside the canvas past its edge does scroll.
|
||||
let start = pos2(200.0, 200.0);
|
||||
h.event(Event::PointerMoved(start));
|
||||
h.event(button(start, true));
|
||||
h.step();
|
||||
for p in [pos2(140.0, 220.0), pos2(50.0, 220.0)] {
|
||||
h.event(Event::PointerMoved(p));
|
||||
h.step();
|
||||
}
|
||||
let before = h.state().ui.views[0].center;
|
||||
h.run_steps(10);
|
||||
let st = h.state();
|
||||
assert!(matches!(st.pcrop.drag, Some(Drag::New { .. })), "{:?}", st.pcrop.drag);
|
||||
assert!(st.ui.views[0].center[0] < before[0], "the box drag scrolled left: {:?} -> {:?}", before, st.ui.views[0].center);
|
||||
h.event(button(pos2(50.0, 220.0), false));
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// A box drag makes the quad, corners drag alone, and ↵'s commit crops the document to the
|
||||
/// quad's size; four clicks in any order make a quad in TL, TR, BR, BL order.
|
||||
#[test]
|
||||
|
||||
@@ -42,7 +42,9 @@ pub use color::{
|
||||
};
|
||||
#[cfg(test)]
|
||||
use color::{checker_tile_id, checker_uv};
|
||||
pub use dropdown::{dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup};
|
||||
pub use dropdown::{
|
||||
dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup,
|
||||
};
|
||||
pub(crate) use fields::compact_wrapping_value_field;
|
||||
#[cfg(test)]
|
||||
use fields::{FieldOpts, NUMERIC_INPUT_LIMIT, value_field_in};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::panel::chevron_icon;
|
||||
use super::scrub::take_label_scrub_name;
|
||||
use super::slider::wheel_notches_of;
|
||||
use super::{Pos2, Rect, Response, Ui, Vec2, type_ahead};
|
||||
use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, type_ahead, vec2};
|
||||
|
||||
/// A compact labelled dropdown in the studio style.
|
||||
pub fn dropdown<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool {
|
||||
@@ -11,13 +11,13 @@ pub fn dropdown<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current
|
||||
/// [`dropdown`] whose option labels are shown exactly as given: names the user typed (a channel
|
||||
/// or layer name) must not be translated, unlike the built-in labels [`dropdown`] translates (#5335).
|
||||
pub fn dropdown_literal<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool {
|
||||
let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false);
|
||||
let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false, &|_| false);
|
||||
!chosen.is_empty()
|
||||
}
|
||||
|
||||
/// [`dropdown`], also returning the option under the pointer in its open list (live previews).
|
||||
pub fn dropdown_hovered<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option<T>) {
|
||||
let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true);
|
||||
let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true, &|_| false);
|
||||
(!chosen.is_empty(), hovered)
|
||||
}
|
||||
|
||||
@@ -35,7 +35,22 @@ pub fn dropdown_wheel_hovered<T: PartialEq + Clone>(
|
||||
options: &[(T, &str)],
|
||||
width: f32,
|
||||
) -> (Vec<T>, Option<T>) {
|
||||
dropdown_with(ui, id, name, current, options, width, true, true)
|
||||
dropdown_with(ui, id, name, current, options, width, true, true, &|_| false)
|
||||
}
|
||||
|
||||
/// [`dropdown_wheel_hovered`] whose open list draws a line above each option (but the first) that
|
||||
/// `starts_group`: Photoshop's blend mode lists group their modes (#5532). The lines are only
|
||||
/// drawn: the options, their order and how the wheel, the keys and the pointer pick them stay.
|
||||
pub fn dropdown_wheel_grouped<T: PartialEq + Clone>(
|
||||
ui: &mut Ui,
|
||||
id: &str,
|
||||
name: &str,
|
||||
current: &mut T,
|
||||
options: &[(T, &str)],
|
||||
width: f32,
|
||||
starts_group: impl Fn(&T) -> bool,
|
||||
) -> (Vec<T>, Option<T>) {
|
||||
dropdown_with(ui, id, name, current, options, width, true, true, &starts_group)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -48,6 +63,7 @@ fn dropdown_with<T: PartialEq + Clone>(
|
||||
width: f32,
|
||||
wheel: bool,
|
||||
translate: bool,
|
||||
starts_group: &dyn Fn(&T) -> bool,
|
||||
) -> (Vec<T>, Option<T>) {
|
||||
let shown = |l: &str| if translate { tl!(l).to_string() } else { l.to_string() };
|
||||
let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| shown(l)).unwrap_or_else(|| "—".into());
|
||||
@@ -86,7 +102,10 @@ fn dropdown_with<T: PartialEq + Clone>(
|
||||
// The row nearest the pointer, by its distance to each row.
|
||||
let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect()));
|
||||
let mut nearest: Option<(f32, &T)> = None;
|
||||
for ((v, _), text) in options.iter().zip(texts.iter()) {
|
||||
for (i, ((v, _), text)) in options.iter().zip(texts.iter()).enumerate() {
|
||||
if i > 0 && starts_group(v) {
|
||||
list_separator(ui);
|
||||
}
|
||||
let item = ui.selectable_label(v == current, text.as_str());
|
||||
if reveal && v == current {
|
||||
item.scroll_to_me(None);
|
||||
@@ -135,6 +154,15 @@ fn dropdown_with<T: PartialEq + Clone>(
|
||||
(chosen, hovered)
|
||||
}
|
||||
|
||||
/// A line between two groups of an open dropdown list's options, as wide as the list. Like egui's
|
||||
/// separator it takes no width while egui sizes the list, so it never widens it.
|
||||
fn list_separator(ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let width = if ui.is_sizing_pass() { 0.0 } else { ui.available_width() };
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, 1.0), Sense::hover());
|
||||
ui.painter().hline(rect.x_range(), rect.center().y, Stroke::new(1.0, t.separator));
|
||||
}
|
||||
|
||||
/// Makes an open dropdown list as wide as its widest option is when hovered, from the start. egui
|
||||
/// takes a plain row's frame stroke off its padding but draws a hovered row with the stroke, so a
|
||||
/// row grows by two stroke widths under the pointer, and the list never shrinks back: scrolling
|
||||
|
||||
@@ -1442,3 +1442,44 @@ fn the_wheel_leaves_a_plain_dropdown_alone() {
|
||||
wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::NONE);
|
||||
assert_eq!(*h.state(), 0);
|
||||
}
|
||||
|
||||
/// [`MODES`] in a wheel dropdown whose list draws a line above each option `starts_group` picks,
|
||||
/// opened: the open list's rect and each option's row in it.
|
||||
fn open_grouped_modes(starts_group: fn(&usize) -> bool) -> (egui::Rect, Vec<egui::Rect>) {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(300.0, 300.0)).build_ui_state(
|
||||
move |ui, selected: &mut usize| {
|
||||
super::dropdown_wheel_grouped(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0, starts_group);
|
||||
},
|
||||
0,
|
||||
);
|
||||
crate::theme::apply(&h.ctx, crate::theme::ThemeKind::ProMedium);
|
||||
h.run();
|
||||
h.get_by_role(egui::accesskit::Role::ComboBox).click();
|
||||
h.run_steps(4);
|
||||
let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id)));
|
||||
let Some(list) = list else { panic!("the list is open") };
|
||||
let rows = MODES.iter().map(|(_, l)| h.get_all_by_label(l).map(|n| n.rect()).rfind(|r| list.contains_rect(*r)).unwrap_or(egui::Rect::NOTHING)).collect();
|
||||
(list, rows)
|
||||
}
|
||||
|
||||
/// The gaps between consecutive rows of an open list.
|
||||
fn row_gaps(rows: &[egui::Rect]) -> Vec<f32> {
|
||||
rows.windows(2).map(|w| w[1].top() - w[0].bottom()).collect()
|
||||
}
|
||||
|
||||
/// A grouped dropdown draws a line above each option starting a group, never above the first one,
|
||||
/// and the lines take no width: the list is as wide as without them (#5532).
|
||||
#[test]
|
||||
fn a_grouped_dropdown_list_draws_a_line_above_each_group_and_keeps_its_width() {
|
||||
let (plain_list, plain) = open_grouped_modes(|_| false);
|
||||
let plain_gaps = row_gaps(&plain);
|
||||
let (lo, hi) = plain_gaps.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), g| (lo.min(*g), hi.max(*g)));
|
||||
assert!(hi - lo < 1.0, "no groups, even row gaps: {plain_gaps:?}");
|
||||
// Darken (index 2) starts a group; so does Normal, the first option, which never gets a line.
|
||||
let (list, rows) = open_grouped_modes(|i| matches!(*i, 0 | 2));
|
||||
let gaps = row_gaps(&rows);
|
||||
assert!((gaps[0] - lo).abs() < 0.5 && (gaps[2] - lo).abs() < 0.5, "only Dissolve/Darken is wider: {gaps:?}");
|
||||
assert!(gaps[1] > lo + 2.0, "a line between Dissolve and Darken: {gaps:?}");
|
||||
assert!((rows[0].top() - plain[0].top()).abs() < 0.5, "no line above the first row: {rows:?} vs {plain:?}");
|
||||
assert_eq!(list.width(), plain_list.width(), "the line doesn't widen the list");
|
||||
}
|
||||
Reference in new issue
Block a user