PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Format: check pattern sizes on load (#3478) (#3484)
Valentin Kleinfd21e734111e
diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rsindex a55c2c8ab..a2c5c52fb 100644--- a/crates/compose/src/pattern.rs+++ b/crates/compose/src/pattern.rs@@ -45,7 +45,7 @@ impl<'a> PreparedPatterns<'a> {pub(crate) fn get(&self, id: &str, name: &str) -> Option<Arc<Tile>> {let p = photocraft_doc::pattern::find(self.patterns, id, name)?;- if p.is_empty() {+ if !p.is_paintable() {return None;}let bytes = usize::try_from(p.width)@@ -87,9 +87,13 @@ impl<'a> PreparedPatterns<'a> {/// colour mode `mode`. A pattern keeps its own colours (an RGB pattern stays RGB, in the/// library and in the document), but in a Grayscale or CMYK document it paints that mode's/// colours: what Edit › Fill writes into the document's pixels, and what Photoshop shows (the-/// pattern in colour in its picker, filled in grey).+/// pattern in colour in its picker, filled in grey). Empty for a pattern that isn't+/// [paintable](Pattern::is_paintable).pub fn pattern_rgba(p: &Pattern, mode: ColorMode) -> Vec<[f32; 4]> {- let mut px = vec![[0.0f32; 4]; (p.width as usize).saturating_mul(p.height as usize)];+ let Some(n) = p.is_paintable().then(|| usize::try_from(p.pixel_count()).ok()).flatten() else {+ return Vec::new();+ };+ let mut px = vec![[0.0f32; 4]; n];p.surface.read_rgba_into(p.rect(), &mut px);let paints_in = matches!(mode, ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone | ColorMode::Cmyk);if paints_in && p.surface.format().mode != mode {@@ -117,8 +121,9 @@ impl Tile {}/// The tile of `p` painted into a document of colour mode `mode` (see [`pattern_rgba`]).+ /// `None` when the pattern isn't [paintable](Pattern::is_paintable).pub fn new_in(p: &Pattern, mode: ColorMode) -> Option<Tile> {- if p.is_empty() {+ if !p.is_paintable() {return None;}let (w, h) = (p.width as usize, p.height as usize);@@ -255,6 +260,17 @@ mod tests {assert_eq!(px[8], [0.0, 0.0, 1.0, 1.0]); // x = 4}+ #[test]+ fn patterns_too_large_to_paint_are_skipped_without_allocating() {+ // Only the size is declared (no tiles): a hostile file can claim any size.+ let p = Pattern { id: "big".into(), name: "Big".into(), width: 9000, height: 8000, surface: Surface::new(PixelFormat::RGBA8) };+ assert!(!p.is_paintable());+ assert!(Tile::new(&p).is_none());+ assert!(pattern_rgba(&p, ColorMode::Rgb).is_empty());+ let list = [p];+ assert!(PreparedPatterns::new(&list, 0).get("big", "").is_none());+ }+#[test]fn link_phase_scale_and_angle_move_the_origin() {let t = Tile::new(&checker()).unwrap();diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rsindex 47279e2c8..9a43c0a46 100644--- a/crates/doc/src/pattern.rs+++ b/crates/doc/src/pattern.rs@@ -5,6 +5,13 @@use photocraft_geom::Rect;use photocraft_raster::Surface;+/// Largest pattern edge a file may declare (the PSD reader's limit; Define Pattern stops at 4000).+pub const MAX_EDGE: u32 = 30_000;++/// Most pixels a pattern may have to be painted. Renderers expand a pattern into a 16-byte-per-pixel+/// working copy, so this keeps that copy at 1 GiB; larger patterns paint nothing.+pub const MAX_PAINT_PIXELS: u64 = 1 << 26;+/// One pattern tile. Pixels cover `0..width × 0..height` of `surface`, in any pixel format/// (depth and colour model are the pattern's own, as in Photoshop).#[derive(Clone, Debug, PartialEq)]@@ -57,6 +64,16 @@ impl Pattern {pub fn is_empty(&self) -> bool {self.width == 0 || self.height == 0}++ /// Pixels in the tile (`width × height`, never overflowing).+ pub fn pixel_count(&self) -> u64 {+ u64::from(self.width) * u64::from(self.height)+ }++ /// Whether the tile has pixels and is small enough to paint (see [`MAX_PAINT_PIXELS`]).+ pub fn is_paintable(&self) -> bool {+ !self.is_empty() && self.pixel_count() <= MAX_PAINT_PIXELS+ }}/// Display form of a stored pattern name (see [`Pattern::display_name`]).diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rsindex a7350dafc..130977ce2 100644--- a/crates/engine/src/fill_cmds.rs+++ b/crates/engine/src/fill_cmds.rs@@ -106,7 +106,7 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {"pattern" => {let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?;let (scale, angle, _, phase) = crate::pattern_cmds::placement(p);- let tile = photocraft_compose::pattern::Tile::new(&pat).ok_or_else(|| bad("the pattern is empty"))?;+ let tile = photocraft_compose::pattern::Tile::new(&pat).ok_or_else(|| bad("the pattern is empty or too large to paint"))?;// Photoshop's Fill uses the canvas origin.let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, phase, scale, angle);out["pattern"] = json!(pat.id);diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rsindex 7366758e9..ad16cd85d 100644--- a/crates/engine/src/paint_cmds.rs+++ b/crates/engine/src/paint_cmds.rs@@ -55,7 +55,7 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {let pattern = if source == "pattern" {let pat = crate::pattern_cmds::resolve_param(s, "paint.bucket", p)?;let tile = photocraft_compose::pattern::Tile::new(&pat)- .ok_or_else(|| EngineError::BadParams { cmd: "paint.bucket".into(), msg: "the pattern is empty".into() })?;+ .ok_or_else(|| EngineError::BadParams { cmd: "paint.bucket".into(), msg: "the pattern is empty or too large to paint".into() })?;let (scale, angle, _, phase) = crate::pattern_cmds::placement(p);Some((tile, scale, angle, phase))} else {diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rsindex 21bee1283..d58fd9e82 100644--- a/crates/engine/src/pattern_cmds.rs+++ b/crates/engine/src/pattern_cmds.rs@@ -326,8 +326,12 @@ fn new_fill_layer(s: &mut Session, p: &Value) -> Result<Value> {fn brush_texture(s: &mut Session, p: &Value) -> Result<Value> {let pat = resolve_param(s, "brush.texturePattern", p)?;+ let n = pat.is_paintable().then(|| usize::try_from(pat.pixel_count()).ok()).flatten();+ let Some(n) = n else {+ return Err(bad("brush.texturePattern", "the pattern is empty or too large to paint"));+ };// Brush textures are grey: luminance of the composite over white.- let mut px = vec![[0.0f32; 4]; (pat.width * pat.height) as usize];+ let mut px = vec![[0.0f32; 4]; n];pat.surface.read_rgba_into(pat.rect(), &mut px);let lum: Vec<f32> = px.iter()@@ -348,8 +352,11 @@ fn brush_texture(s: &mut Session, p: &Value) -> Result<Value> {/// A swatch colour for UIs (average of the tile), straight RGB.pub fn average_color(p: &Pattern) -> Color {- let mut px = vec![[0.0f32; 4]; (p.width * p.height) as usize];- p.surface.read_rgba_into(p.rect(), &mut px);+ // A pattern too large to paint is averaged over its paintable top-left corner.+ let side = photocraft_doc::pattern::MAX_PAINT_PIXELS.isqrt() as u32;+ let (w, h) = (p.width.min(side), p.height.min(side));+ let mut px = vec![[0.0f32; 4]; w as usize * h as usize];+ p.surface.read_rgba_into(Rect::new(0, 0, w as i32, h as i32), &mut px);let n = px.len().max(1) as f32;let s = px.iter().fold([0.0f32; 3], |a, q| [a[0] + q[0], a[1] + q[1], a[2] + q[2]]);Color::rgb(s[0] / n, s[1] / n, s[2] / n)@@ -560,4 +567,14 @@ mod tests {assert!(s.tools.brush.texture.enabled);assert!(matches!(s.tools.brush.texture.pattern, photocraft_paint::Pattern::Tile(_)));}++ #[test]+ fn a_pattern_too_large_to_paint_is_refused_not_allocated() {+ // width × height overflows u32: this panicked (debug) or wrapped (release).+ let mut s = session(8);+ let huge = Pattern { id: "huge".into(), name: "Huge".into(), width: 65_536, height: 65_536, surface: Surface::new(PixelFormat::RGBA8) };+ s.patterns.items.push(huge);+ let e = s.execute("brush.texturePattern", json!({"pattern": "huge"})).unwrap_err();+ assert!(e.to_string().contains("too large"), "{e}");+ }}diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/retouch_cmds/pattern_stamp.rsindex cb9e0adfe..0dc9f102a 100644--- a/crates/engine/src/retouch_cmds/pattern_stamp.rs+++ b/crates/engine/src/retouch_cmds/pattern_stamp.rs@@ -45,7 +45,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(CMD, "`points` is empty"));};let phase = stamp_phase(p, CMD, aligned, first)?;- let tile = Tile::new(&pat).ok_or_else(|| bad(CMD, "the pattern is empty"))?;+ let tile = Tile::new(&pat).ok_or_else(|| bad(CMD, "the pattern is empty or too large to paint"))?;reject_huge_stroke(CMD, &stroke)?;let seed = p.get("seed").and_then(Value::as_u64).unwrap_or_else(|| {diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rsindex 4dbbb6aa3..47ea5383d 100644--- a/crates/format/src/convert.rs+++ b/crates/format/src/convert.rs@@ -592,6 +592,15 @@ impl Loader<'_> {}let mut patterns = Vec::with_capacity(m.patterns.len());for p in &m.patterns {+ // Sizes come from the file: a pattern with no tiles can claim any size, and renderers+ // allocate per pixel.+ let max = photocraft_doc::pattern::MAX_EDGE;+ if p.width == 0 || p.height == 0 {+ return Err(FormatError::corrupt(format!("pattern `{}` is {}×{} px", p.name, p.width, p.height)));+ }+ if p.width > max || p.height > max {+ return Err(FormatError::LimitExceeded(format!("pattern `{}` is {}×{} px (max {max} per side)", p.name, p.width, p.height)));+ }patterns.push(Pattern { id: p.id.clone(), name: p.name.clone(), width: p.width, height: p.height, surface: self.surface(&p.surface)? });}let layer_comps = m.layer_comps.iter().map(|c| self.comp(c)).collect::<Result<Vec<_>>>()?;diff --git a/crates/format/tests/corruption.rs b/crates/format/tests/corruption.rsindex 2f47203b3..2ef07bcd4 100644--- a/crates/format/tests/corruption.rs+++ b/crates/format/tests/corruption.rs@@ -419,6 +419,31 @@ fn tile_coordinates_outside_the_i32_pixel_range_are_rejected() {}}+/// Rewrites the first pattern's declared size (its tiles stay as saved).+fn with_pattern_size(w: u64, h: u64) -> Vec<u8> {+ rebuild(sample_cached(), |n, d| {+ if n != "manifest.json" {+ return Some(d);+ }+ let mut v: serde_json::Value = serde_json::from_slice(&d).unwrap();+ let p = &mut v["document"]["patterns"][0];+ assert!(p.is_object(), "the sample has a pattern");+ p["width"] = w.into();+ p["height"] = h.into();+ Some(serde_json::to_vec(&v).unwrap())+ })+}++#[test]+fn pattern_sizes_from_the_file_are_checked() {+ // A pattern can claim any size without tiles; painting it allocated per pixel (abort).+ let huge = load_from_bytes(&with_pattern_size(65_535, 65_535));+ assert!(matches!(huge, Err(FormatError::LimitExceeded(_))), "{huge:?}");+ let empty = load_from_bytes(&with_pattern_size(0, 24));+ assert!(matches!(empty, Err(FormatError::Corrupt(_))), "{empty:?}");+ assert!(load_from_bytes(&with_pattern_size(32, 24)).is_ok());+}+/// A canvas is a few bytes of manifest JSON; one past the budget is refused before any work (#2935)./// The default budget is the largest canvas the app creates (300000 × 300000, as `file.new`,/// Canvas Size and PSB import allow), so everything a user can save reopens.diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rsindex 9eba5888b..cc396d8ba 100644--- a/crates/gpu/src/fx.rs+++ b/crates/gpu/src/fx.rs@@ -389,7 +389,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool,h = b.push(st);}if let Some(t) = &bv.texture- && let Some(pat) = photocraft_doc::pattern::find(patterns, &t.id, &t.name).filter(|p| !p.is_empty())+ && let Some(pat) = photocraft_doc::pattern::find(patterns, &t.id, &t.name).filter(|p| p.is_paintable()){// Texture element (`effects::bevel_height`): luminance × depth / unit added.let unit = if bv.depth.abs() > 1e-6 { (g.depth / bv.depth).abs().max(1e-3) } else { g.width.max(1.0) };diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rsindex f5a3b573e..fb135dc13 100644--- a/crates/gpu/src/plan.rs+++ b/crates/gpu/src/plan.rs@@ -803,7 +803,7 @@ impl<'a> Planner<'a> {// compose::render_fill: the pattern tiled from the layer's frame (transparent// when missing), then the layer's masks.let empty = self.clear();- let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| !p.is_empty()) else { return Ok(empty) };+ let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) else { return Ok(empty) };let frame = photocraft_compose::fill_frame(layer, self.cx.canvas);let anchor = if frame.is_empty() { (0.0, 0.0) } else { (f64::from(frame.x0), f64::from(frame.y0)) };let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle));@@ -1097,7 +1097,7 @@ impl<'a> Planner<'a> {};for &(_, e) in &rev {if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e- && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| !p.is_empty())+ && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()){let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle));l = self.paint(l, content, Cov::One, &paint, common.blend, common.opacity, F_GATE, clip, sb);@@ -1312,7 +1312,7 @@ impl<'a> Planner<'a> {match p {FxPaint::Color(c) => Paint::Color(c.to_rgb()),FxPaint::Gradient(g) => Paint::Gradient(g),- FxPaint::Pattern { name, id, scale } => match photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| !p.is_empty()) {+ FxPaint::Pattern { name, id, scale } => match photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) {Some(pat) => Paint::Pattern(pat, placement(anchor, true, (0.0, 0.0), *scale, 0.0)),None => Paint::None,},