PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix: resolve edge-case crashes, unbounded allocations, and UI sync defects (#1010)
buivanvu94a41800c466d0
diff --git a/crates/algo/src/fxutil.rs b/crates/algo/src/fxutil.rsindex 21e3b809a..fc8b509e3 100644--- a/crates/algo/src/fxutil.rs+++ b/crates/algo/src/fxutil.rs@@ -221,6 +221,9 @@ pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {/// average many samples; unpremultiply the sum once at the end.#[inline]pub(crate) fn add_sample_premul(src: &Image, x: f32, y: f32, clip: Rect, alpha: bool, acc: &mut [f32]) {+ if !x.is_finite() || !y.is_finite() || clip.is_empty() {+ return;+ }let n = src.ch;let fx = (x - 0.5).clamp(clip.x0 as f32, (clip.x1 - 1) as f32);let fy = (y - 0.5).clamp(clip.y0 as f32, (clip.y1 - 1) as f32);diff --git a/crates/algo/src/gallery.rs b/crates/algo/src/gallery.rsindex 1ccaa6e06..3e719b94d 100644--- a/crates/algo/src/gallery.rs+++ b/crates/algo/src/gallery.rs@@ -114,12 +114,13 @@ pub(crate) fn tilt_shift(src: &Image, out: Rect, ctx: &Ctx, blur: f32, centre: (fn pin_distance(x: f32, y: f32, b: Rect, px: f32, py: f32, rx: f32, ry: f32, angle: f32, m: f32) -> (f32, f32, f32) {let ss = short_side(b);let (cx, cy) = (b.x0 as f32 + px * b.width() as f32, b.y0 as f32 + py * b.height() as f32);- let (s, c) = angle.to_radians().sin_cos();+ let angle_deg = if angle.is_finite() { angle } else { 0.0 };+ let (s, c) = angle_deg.to_radians().sin_cos();let (dx, dy) = (x - cx, y - cy);let (u, v) = (dx * c + dy * s, -dx * s + dy * c);let (u, v) = (u / (rx.max(1e-3) * ss), v / (ry.max(1e-3) * ss));let e = if (m - 2.0).abs() < 1e-3 { (u * u + v * v).sqrt() } else { (u.abs().powf(m) + v.abs().powf(m)).powf(1.0 / m) };- (e, u, v)+ if !e.is_finite() { (f32::INFINITY, 0.0, 0.0) } else { (e, u, v) }}/// Iris Blur: everything outside each pin's ellipse is blurred; the sharp@@ -178,15 +179,16 @@ pub(crate) fn spin(src: &Image, out: Rect, ctx: &Ctx, pins: &[SpinPin]) -> Vec<flet (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);for p in pins {let (e, u, v) = pin_distance(fx, fy, b, p.x, p.y, p.radius_x, p.radius_y, p.angle, 2.0);- if e >= 1.0 {+ if !e.is_finite() || e >= 1.0 {continue;}let theta = p.blur_angle.clamp(0.0, 360.0).to_radians();- let rpx = e * p.radius_x.max(p.radius_y) * ss;+ let rpx = (e * p.radius_x.max(p.radius_y) * ss).max(0.0);// ~2 px between samples along the arc is smooth enough for a blur and halves the cost.- let m = ((theta * rpx / 2.0).ceil() as usize).clamp(2, 64);+ let m = if rpx.is_finite() && theta.is_finite() { ((theta * rpx / 2.0).ceil() as usize).clamp(2, 64) } else { 2 };let (cx, cy) = (b.x0 as f32 + p.x * b.width() as f32, b.y0 as f32 + p.y * b.height() as f32);- let (sa, ca) = p.angle.to_radians().sin_cos();+ let angle_deg = if p.angle.is_finite() { p.angle } else { 0.0 };+ let (sa, ca) = angle_deg.to_radians().sin_cos();acc[..n].fill(0.0);for j in 0..m {let phi = theta * (j as f32 / (m - 1) as f32 - 0.5);diff --git a/crates/algo/src/image.rs b/crates/algo/src/image.rsindex 8f2fc1f2d..6a17e08b0 100644--- a/crates/algo/src/image.rs+++ b/crates/algo/src/image.rs@@ -91,6 +91,9 @@ impl Image {/// Sample with an edge policy relative to `area`.#[inline]pub fn get_edge(&self, x: i32, y: i32, c: usize, edge: Edge, area: Rect) -> f32 {+ if area.is_empty() {+ return 0.0;+ }if area.contains(x, y) {return self.get(x, y, c);}diff --git a/crates/algo/src/render2.rs b/crates/algo/src/render2.rsindex a99aec50f..ed6567ca5 100644--- a/crates/algo/src/render2.rs+++ b/crates/algo/src/render2.rs@@ -629,12 +629,17 @@ pub fn flame(spec: &FlameSpec, paths: &[Vec<(f32, f32)>]) -> Vec<Prim> {(a.0 - b.0).abs() < 1.0 && (a.1 - b.1).abs() < 1.0};let count = if spec.adjust_interval_for_loops && closed {- (total / interval).round().max(1.0) as usize+ let c = (total / interval).round();+ if c.is_finite() && c > 1.0 { (c as usize).min(2048) } else { 1 }} else {- (total / interval).floor() as usize + 1+ let c = (total / interval).floor();+ if c.is_finite() && c >= 0.0 { (c as usize).saturating_add(1).min(2048) } else { 1 }};let step = if spec.adjust_interval_for_loops && closed { total / count as f32 } else { interval };for k in 0..count {+ if out.len() >= 65536 {+ break;+ }let s = k as f32 * step;let ((x, y), (dx, dy)) = spine.at(s);let dir = match spec.flame_type {diff --git a/crates/algo/src/stylize2.rs b/crates/algo/src/stylize2.rsindex f783e99d5..f955d51ff 100644--- a/crates/algo/src/stylize2.rs+++ b/crates/algo/src/stylize2.rs@@ -326,9 +326,11 @@ pub(crate) fn trace_contour(src: &Image, out: Rect, ctx: &Ctx, level: f32, upperlet n = src.ch;let cc = ncol(ctx, n);let sub = subtractive(ctx);+ let bounds = ctx.bounds.intersect(&src.rect);+ let area = if bounds.is_empty() { src.rect } else { bounds };let t = level.clamp(0.0, 255.0) / 255.0;let bright = |x: i32, y: i32, c: usize| {- let v = src.get_edge(x, y, c, crate::image::Edge::Repeat, ctx.bounds.intersect(&src.rect));+ let v = src.get_edge(x, y, c, crate::image::Edge::Repeat, area);if sub { 1.0 - v } else { v }};let mut res = src.crop(out);diff --git a/crates/algo/src/tests_ext.rs b/crates/algo/src/tests_ext.rsindex 14d9d70fe..864c5bebf 100644--- a/crates/algo/src/tests_ext.rs+++ b/crates/algo/src/tests_ext.rs@@ -367,6 +367,13 @@ fn trace_contour_draws_line_at_level_crossing() {assert_eq!(lo.pixel(19, 10)[0], 0.0, "line on the dark side");}+#[test]+fn trace_contour_off_canvas_does_not_panic() {+ let s = flat(SampleType::F32, Rect::new(100, 100, 120, 120), [0.8, 0.8, 0.8, 1.0]);+ let p = FilterParams::TraceContour { level: 128.0, upper: true };+ let _ = apply_tiled(&s, &p, s.content_bounds(), R, None, 64, None);+}+#[test]fn tiles_leave_gaps_with_fill() {let s = flat(SampleType::F32, R, [0.0, 0.0, 1.0, 1.0]);diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rsindex 1f25aff52..97386c086 100644--- a/crates/engine/src/filters_ext.rs+++ b/crates/engine/src/filters_ext.rs@@ -329,16 +329,25 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {pins: list::<FieldPin>(p, "pins").unwrap_or_else(|| vec![FieldPin { x: f(p, "centerX", 0.5), y: f(p, "centerY", 0.5), blur: blur(15.0) }]),},"filter.blurGallery.spinBlur" => FilterParams::SpinBlur {- pins: list::<SpinPin>(p, "pins").unwrap_or_else(|| {- vec![SpinPin {- x: f(p, "centerX", 0.5),- y: f(p, "centerY", 0.5),- radius_x: f(p, "radiusX", 0.3).max(0.001),- radius_y: f(p, "radiusY", 0.3).max(0.001),- angle: f(p, "angle", 0.0),- blur_angle: f(p, "blurAngle", 15.0).clamp(0.0, 360.0),- }]- }),+ pins: list::<SpinPin>(p, "pins")+ .map(|mut v| {+ for pin in &mut v {+ pin.angle = if pin.angle.is_finite() { pin.angle.clamp(-360.0, 360.0) } else { 0.0 };+ pin.blur_angle = if pin.blur_angle.is_finite() { pin.blur_angle.clamp(0.0, 360.0) } else { 0.0 };+ }+ v+ })+ .unwrap_or_else(|| {+ let a = f(p, "angle", 0.0);+ vec![SpinPin {+ x: f(p, "centerX", 0.5),+ y: f(p, "centerY", 0.5),+ radius_x: f(p, "radiusX", 0.3).max(0.001),+ radius_y: f(p, "radiusY", 0.3).max(0.001),+ angle: if a.is_finite() { a.clamp(-360.0, 360.0) } else { 0.0 },+ blur_angle: f(p, "blurAngle", 15.0).clamp(0.0, 360.0),+ }]+ }),},"filter.blurGallery.pathBlur" => FilterParams::PathBlur {paths: list::<BlurPath>(p, "paths")diff --git a/crates/engine/src/gallery_cmds.rs b/crates/engine/src/gallery_cmds.rsindex a13995697..848400d37 100644--- a/crates/engine/src/gallery_cmds.rs+++ b/crates/engine/src/gallery_cmds.rs@@ -63,6 +63,9 @@ pub fn effect_from_json(filter: GalleryFilter, p: &Value, fallback: &Value) -> G/// `filter`); hidden entries are skipped.pub fn effects_from_json(p: &Value) -> std::result::Result<Vec<GalleryEffect>, String> {let Some(list) = p.get("effects").and_then(Value::as_array) else { return Ok(Vec::new()) };+ if list.len() > 32 {+ return Err("too many effects in filterGallery stack (max 32)".into());+ }let mut out = Vec::new();for (k, item) in list.iter().enumerate() {if item.get("visible").and_then(Value::as_bool) == Some(false) {diff --git a/crates/engine/src/gallery_cmds/tests.rs b/crates/engine/src/gallery_cmds/tests.rsindex 21e6b2973..93d848701 100644--- a/crates/engine/src/gallery_cmds/tests.rs+++ b/crates/engine/src/gallery_cmds/tests.rs@@ -103,6 +103,8 @@ fn gallery_validates_and_lists() {let mut s = session(8, "rgb");assert!(s.execute("filter.filterGallery", json!({})).is_err());assert!(s.execute("filter.filterGallery", json!({"effects": [{"filter": "nope"}]})).is_err());+ let too_many: Vec<_> = (0..33).map(|_| json!({"filter": "coloredPencil"})).collect();+ assert!(s.execute("filter.filterGallery", json!({"effects": too_many})).is_err());let list = s.execute("filter.filterGallery", json!({"list": true})).unwrap();assert_eq!(list["filters"].as_array().unwrap().len(), 47);assert_eq!(list["categories"].as_array().unwrap().len(), 6);diff --git a/crates/ui-egui/src/artboard_ui.rs b/crates/ui-egui/src/artboard_ui.rsindex 68a228a94..b12e2a7ee 100644--- a/crates/ui-egui/src/artboard_ui.rs+++ b/crates/ui-egui/src/artboard_ui.rs@@ -116,7 +116,18 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {let mut bg = a.background.name().to_string();let opts = [("white".to_string(), tl!("White")), ("black".to_string(), tl!("Black")), ("transparent".to_string(), tl!("Transparent")), ("custom".to_string(), tl!("Other…"))];if crate::widgets::dropdown(ui, &key("bg"), &mut bg, &opts, 120.0) {- edit = Some(json!({"layer": layer.id.0, "background": bg}));+ let mut params = json!({"layer": layer.id.0, "background": bg});+ if bg == "custom" {+ let hex = match a.background {+ ArtboardBackground::Custom(c) => {+ let [r8, g8, b8, _] = c.to_rgba8();+ format!("#{:02x}{:02x}{:02x}", r8, g8, b8)+ }+ _ => "#ffffff".to_string(),+ };+ params["color"] = json!(hex);+ }+ edit = Some(params);}if let ArtboardBackground::Custom(c) = a.background {let [r8, g8, b8, _] = c.to_rgba8();diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rsindex bb690bd15..3d2f622dc 100644--- a/crates/ui-egui/src/prefs_ui.rs+++ b/crates/ui-egui/src/prefs_ui.rs@@ -1374,13 +1374,24 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,// commands included, which the engine doesn't know).let mut ov: BTreeMap<String, String> = serde_json::from_value(overrides).unwrap_or_default();let items = shortcut_items(app);- let changed: Vec<(String, String)> = ov.iter().filter(|(_, s)| !s.is_empty()).map(|(k, s)| (k.clone(), s.clone())).collect();- for (id, sc) in changed {+ // Newly assigned shortcuts are checked first and take theirs from any holder, custom+ // overrides included; unchanged overrides only take theirs from defaults.+ let before = &app.session.prefs().shortcuts;+ let mut todo: Vec<(String, String, bool)> =+ ov.iter().filter(|(_, s)| !s.is_empty()).map(|(k, s)| (k.clone(), s.clone(), before.get(k) != Some(s))).collect();+ todo.sort_by_key(|(_, _, new)| !new);+ for (id, sc, new) in todo {+ if ov.get(&id).is_some_and(String::is_empty) {+ continue; // taken by a newer assignment+ }+ let norm = prefs::normalize_shortcut(&sc);for (other, _, _, def) in &items {- if *other != id- && !ov.contains_key(other)- && def.as_deref().and_then(prefs::normalize_shortcut).as_deref() == prefs::normalize_shortcut(&sc).as_deref()- {+ let held = match ov.get(other) {+ Some(s) if new => Some(s.as_str()),+ Some(_) => None,+ None => def.as_deref(),+ };+ if *other != id && held.and_then(prefs::normalize_shortcut) == norm {ov.insert(other.clone(), String::new());}}@@ -1980,6 +1991,33 @@ mod tests {assert!(items.iter().any(|i| i.id == "layer.new.layer" && i.shortcut.as_deref() == Some("Cmd+O")));assert!(items.iter().any(|i| i.id == "file.open" && i.shortcut.is_none()));assert_eq!(shortcut_text(egui::Key::K, egui::Modifiers { command: true, shift: true, ..Default::default() }).as_deref(), Some("Cmd+Shift+K"));++ // Re-assigning a shortcut already held by a custom override takes it from the override.+ let id2 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap();+ let mut cur_overrides = app.session.prefs().shortcuts.clone();+ cur_overrides.insert("layer.new.group".into(), "Cmd+O".into());+ app.ui.dialog_mut(id2).unwrap().fields.insert("overrides".into(), json!(cur_overrides));+ crate::dialogs::confirm(&mut app, id2).unwrap();+ assert_eq!(effective_shortcut(&app, "layer.new.group", None).as_deref(), Some("Cmd+O"));+ assert_eq!(effective_shortcut(&app, "layer.new.layer", None), None, "taken from layer.new.layer override");++ // OK with nothing changed keeps every shortcut where it is.+ let id3 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap();+ let unchanged = app.session.prefs().shortcuts.clone();+ app.ui.dialog_mut(id3).unwrap().fields.insert("overrides".into(), json!(unchanged));+ crate::dialogs::confirm(&mut app, id3).unwrap();+ assert_eq!(app.session.prefs().shortcuts, unchanged);++ // Giving the shortcut back to Layer › New › Layer takes it from the group override; a+ // cleared override (empty) holds nothing and is left alone.+ let id4 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap();+ let mut ov = app.session.prefs().shortcuts.clone();+ ov.insert("layer.new.layer".into(), "Cmd+O".into());+ app.ui.dialog_mut(id4).unwrap().fields.insert("overrides".into(), json!(ov));+ crate::dialogs::confirm(&mut app, id4).unwrap();+ assert_eq!(effective_shortcut(&app, "layer.new.layer", None).as_deref(), Some("Cmd+O"));+ assert_eq!(effective_shortcut(&app, "layer.new.group", None), None, "taken back from the group");+ assert_eq!(effective_shortcut(&app, "file.open", Some("Cmd+O")), None, "File › Open stays cleared");}#[test]