Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Merge remote-tracking branch 'origin/main' into integration-batch-7

David Mann2b0deddec2fa
diff --cc crates/io/src/smart_map.rs
index b62e836c4,2322ec7bf..fcc9eec3f
--- a/crates/io/src/smart_map.rs
+++ b/crates/io/src/smart_map.rs
@@@ -1820,20 -1731,15 +1820,27 @@@ mod tests
sf("image.adjustments.levels", json!({"inBlack": 20, "inWhite": 220, "gamma": 1.4, "red": {"inBlack": 0, "inWhite": 255, "gamma": 0.8}})),
sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [64.0, 40.0], [255.0, 255.0]], "blue": [[0.0, 20.0], [255.0, 235.0]]})),
sf("image.adjustments.shadowsHighlights", json!({})),
+ sf("filter.sharpen.sharpen", json!({})),
+ // Photoshop stores Dust & Scratches' radius in whole pixels (a `long`).
+ sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 12})),
+ sf(
+ "image.adjustments.hueSaturation",
+ json!({"colorize": false, "hue": 10, "saturation": -20, "lightness": 5, "reds": {"hue": 5, "saturation": 0, "lightness": -3, "range": [315, 345, 15, 45]}}),
+ ),
// A pencil-drawn curve: 256 output levels (`Mpng`).
sf("image.adjustments.curves", json!({"pencil": true, "points": (0..256).rev().collect::<Vec<i32>>()})),
+ sf("filter.distort.pinch", json!({"amount": -28})),
+ sf("filter.distort.polarCoordinates", json!({"mode": "rectangularToPolar"})),
+ sf("filter.distort.ripple", json!({"amount": 250, "size": "small"})),
+ sf("filter.distort.spherize", json!({"amount": 60, "mode": "verticalOnly"})),
+ sf("filter.distort.twirl", json!({"angle": -355})),
+ sf(
+ "filter.distort.wave",
+ json!({"type": "square", "generators": 3, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30,
+ "undefinedAreas": "repeat", "seed": 4_000_000_000u32}),
+ ),
+ sf("filter.distort.zigZag", json!({"amount": 30, "ridges": 7, "style": "aroundCenter"})),
+ sf("image.adjustments.invert", json!({})),
];
for mut f in filters.into_iter().chain(wind_extrude_tiles_settings()) {
f.blend = BlendMode::Overlay;
@@@ -2723,160 -2587,68 +2730,222 @@@
assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER);
}
+ /// Distort smart filters from a Photoshop file open as their PhotoCraft filters, and the ones
+ /// PhotoCraft writes carry the same settings, keys and order as Photoshop's.
+ #[test]
+ fn photoshop_distort_filters_read_and_write_like_photoshop() {
+ for (command, params, hex) in PHOTOSHOP_FLTR {
+ let ps = Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap();
+ let f = filter_from_item(&photoshop_fltr_item(ps.clone()));
+ let want: J = serde_json::from_str(params).unwrap();
+ assert_eq!((f.command.as_str(), &f.params), (command, &want), "{command}");
+ let ours = match item_for_filter(&f).unwrap().get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("{command}: no Fltr ({other:?})"),
+ };
+ assert_eq!((&ours.class_id, &ours.items), (&ps.class_id, &ps.items), "{command}: same keys, values and order");
+ }
+ // A scaled wave can't be modelled, so it stays Photoshop's, unchanged.
+ let wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap();
+ let item = photoshop_fltr_item(wave);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER);
+ assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"));
+ // Unscaled, but with 332 generators (the renderer draws 64 at most), it stays Photoshop's too.
+ let mut unscaled = match item.get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("wave: no Fltr ({other:?})"),
+ };
+ set(&mut unscaled, "SclV", Value::Integer(100));
+ let item = photoshop_fltr_item(unscaled);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER);
+ assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"));
+
+ // An extra or repeated setting PhotoCraft doesn't model keeps the filter Photoshop's, unchanged.
+ let mut fltrs: Vec<Descriptor> = PHOTOSHOP_FLTR.iter().map(|(_, _, hex)| Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap()).collect();
+ let mut wave = unscaled_wave();
+ set(&mut wave, "NmbG", Value::Integer(5));
+ assert_eq!(filter_from_item(&photoshop_fltr_item(wave.clone())).command, "filter.distort.wave", "the plain wave maps");
+ fltrs.push(wave);
+ for ps in fltrs {
+ let name = String::from_utf8_lossy(ps.class_id.as_bytes()).into_owned();
+ let mut repeated = ps.clone();
+ repeated.items.push(ps.items[0].clone());
+ for odd in [ps.clone().with("Xtra", Value::Integer(7)), repeated] {
+ let item = photoshop_fltr_item(odd);
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{name}");
+ assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{name}: written back unchanged");
+ }
+ }
+ }
+
+ /// Photoshop's Wave ([`PHOTOSHOP_WAVE`]) at 100% scale both ways.
+ fn unscaled_wave() -> Descriptor {
+ let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap();
+ set(&mut wave, "SclV", Value::Integer(100));
+ wave
+ }
+
+ /// An unscaled Wave opens as PhotoCraft's Wave (Triangle, the other settings as stored) up to
+ /// the generators the renderer models; one more and it stays Photoshop's, unchanged.
+ #[test]
+ fn wave_maps_up_to_the_generators_the_renderer_models() {
+ let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap();
+ assert_eq!(max, 64);
+ let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap();
+ set(&mut wave, "SclV", Value::Integer(100));
+ for (generators, mapped) in [(1, true), (max, true), (max + 1, false), (999, false), (0, false), (-1, false)] {
+ set(&mut wave, "NmbG", Value::Integer(generators));
+ let item = photoshop_fltr_item(wave.clone());
+ let f = filter_from_item(&item);
+ if mapped {
+ assert_eq!(
+ (f.command.as_str(), &f.params),
+ (
+ "filter.distort.wave",
+ &json!({"type": "triangle", "generators": generators, "wavelengthMin": 213, "wavelengthMax": 214, "amplitudeMin": 240,
+ "amplitudeMax": 241, "undefinedAreas": "wrap", "seed": 1270346})
+ ),
+ "{generators} generators"
+ );
+ match item_for_filter(&f).unwrap().get("Fltr") {
+ Some(Value::Descriptor(ours)) => assert_eq!((&ours.class_id, &ours.items), (&wave.class_id, &wave.items), "{generators} generators"),
+ other => panic!("wave: no Fltr ({other:?})"),
+ }
+ } else {
+ assert_eq!(f.command, UNSUPPORTED_FILTER, "{generators} generators");
+ assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{generators} generators");
+ }
+ }
+ }
+
+ /// PhotoCraft draws at most `MAX_WAVE_GENERATORS` generators, so a Wave edited past that exports
+ /// the 64 it rendered, and a count below 1 exports 1, instead of Photoshop drawing more.
+ #[test]
+ fn wave_export_writes_only_the_generators_the_renderer_draws() {
+ let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap();
+ for (stored, written) in [(100, max), (999, max), (max + 1, max), (max, max), (5, 5), (1, 1), (0, 1), (-3, 1)] {
+ let wave = sf(
+ "filter.distort.wave",
+ json!({"type": "sine", "generators": stored, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30}),
+ );
+ let fltr = match item_for_filter(&wave).unwrap().get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("wave: no Fltr ({other:?})"),
+ };
+ assert_eq!(int(&fltr, "NmbG"), Some(written), "{stored} generators");
+ }
+ }
+
+ /// `RndS` is the seed the renderer draws with, also for a legacy signed or fractional seed
+ /// (stored as is by `layer.smartFilter.setParams`), not 0.
+ #[test]
+ fn wave_export_writes_the_seed_the_renderer_draws() {
+ for (stored, written) in [
+ (json!(77), 77),
+ (json!(4_000_000_000u32), -294_967_296),
+ (json!(-1), -1),
+ (json!(7.4), 7),
+ (json!(-2.6), -3),
+ (json!(1e12), i32::MAX),
+ (json!("x"), 0),
+ ] {
+ let wave = sf("filter.distort.wave", json!({"generators": 3, "seed": stored}));
+ let fltr = match item_for_filter(&wave).unwrap().get("Fltr") {
+ Some(Value::Descriptor(d)) => d.clone(),
+ other => panic!("wave: no Fltr ({other:?})"),
+ };
+ assert_eq!(int(&fltr, "RndS"), Some(written), "seed {stored}");
+ // And it reads back as that bit pattern.
+ assert_eq!(known_params("Wave", Some(&fltr), &Descriptor::new("filterFX")).unwrap().1["seed"], json!(written as u32), "seed {stored}");
+ }
+ }
+
+ /// Invert on a smart object: Photoshop stores no `Fltr`, `hasoptions` false and its filter id.
+ #[test]
+ fn invert_smart_filter_reads_and_writes_like_photoshop() {
+ let item = Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul("Invert")))
+ .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))))
+ .with("enab", Value::Boolean(true))
+ .with("hasoptions", Value::Boolean(false))
+ .with("FrgC", rgbc(255.0))
+ .with("BckC", rgbc(0.0))
+ .with("filterID", Value::Integer(code(b"Invr")));
+ let f = filter_from_item(&item);
+ assert_eq!((f.command.as_str(), &f.params), ("image.adjustments.invert", &json!({})));
+ let back = item_for_filter(&f).unwrap();
+ assert_eq!(back.get("Fltr"), None);
+ assert_eq!(back.get("hasoptions"), Some(&Value::Boolean(false)));
+ assert_eq!(back.get("filterID"), Some(&Value::Integer(code(b"Invr"))));
+ assert_eq!(back.get("Nm "), Some(&Value::Text(UnicodeString::new_nul("Invert"))));
+ }
+
+ /// A filter PhotoCraft doesn't model, or a known one with settings it doesn't, is kept verbatim; only its visibility and blend change.
+ #[test]
+ fn photoshop_sharpen_without_fltr_imports_as_sharpen() {
+ // #6267: Photoshop's Sharpen item holds only its name, blending and `filterID`.
+ let item = Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul("Sharpen")))
+ .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))))
+ .with("enab", Value::Boolean(true))
+ .with("hasoptions", Value::Boolean(false))
+ .with("filterID", Value::Integer(1_399_353_968));
+ let f = filter_from_item(&item);
+ assert_eq!((f.command.as_str(), &f.params), ("filter.sharpen.sharpen", &json!({})));
+ // Hue/Saturation with an unnumbered range and Dust & Scratches with a missing setting fail
+ // cleanly instead of panicking.
+ let bad = SmartFilter {
+ command: "image.adjustments.hueSaturation".into(),
+ params: json!({"reds": {"range": [1, "x", 3, 4]}}),
+ blend: BlendMode::Normal,
+ opacity: 1.0,
+ visible: true,
+ };
+ assert!(item_for_filter(&bad).is_err());
+ let dust = Descriptor::new("filterFX")
+ .with("Fltr", Value::Descriptor(Descriptor::new("DstS").with("Rds ", Value::Integer(3))))
+ .with("filterID", Value::Integer(code(b"DstS")));
+ assert_eq!(filter_from_item(&dust).command, UNSUPPORTED_FILTER);
+ }
+
+ #[test]
+ fn hue_saturation_ranges_are_not_lost() {
+ let hue_sat = |params: J| item_for_filter(&sf("image.adjustments.hueSaturation", params));
+ // A range that is not an object is an error, not a silently dropped setting.
+ assert!(hue_sat(json!({"reds": 5})).is_err());
+ assert!(hue_sat(json!({"reds": null})).is_ok());
+ // Colorize's 25% default is the master saturation's only: a range's stays 0.
+ let d = hue_sat(json!({"colorize": true, "reds": {"hue": 5}})).unwrap();
+ let adjs = adjustment_list(get_desc(&d, "Fltr").unwrap()).unwrap();
+ let saturations: Vec<_> = adjs.iter().map(|a| int(a, "Strt")).collect();
+ assert_eq!(saturations, [Some(25), Some(0)]);
+ // A repeated range (or master) would overwrite the first: the filter is kept verbatim.
+ let entry = |range: Option<i32>| {
+ let e = Descriptor::new("Hst2").with("H ", Value::Integer(0)).with("Strt", Value::Integer(0)).with("Lght", Value::Integer(0));
+ let Some(r) = range else { return Value::Descriptor(e) };
+ let e = ["BgnR", "BgnS", "EndS", "EndR"].iter().fold(e.with("LclR", Value::Integer(r)), |e, k| e.with(k, Value::Integer(10)));
+ Value::Descriptor(e)
+ };
+ for adjs in [vec![entry(None), entry(Some(1)), entry(Some(1))], vec![entry(None), entry(None)]] {
+ let fltr = Descriptor::new("HStr").with("Clrz", Value::Boolean(false)).with("Adjs", Value::List(adjs));
+ let item = Descriptor::new("filterFX")
+ .with("Nm ", Value::Text(UnicodeString::new_nul("Hue/Saturation...")))
+ .with(
+ "blendOptions",
+ Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))),
+ )
+ .with("enab", Value::Boolean(true))
+ .with("Fltr", Value::Descriptor(fltr))
+ .with("filterID", Value::Integer(code(b"HStr")));
+ let f = filter_from_item(&item);
+ assert_eq!(f.command, UNSUPPORTED_FILTER);
+ assert_eq!(item_for_filter(&f).unwrap(), item);
+ }
+ }
+
#[test]
fn unknown_filters_keep_their_descriptor() {
let item = Descriptor::new("filterFX")
diff --cc crates/ui-egui/src/panels.rs
index 2d8dc5a8c,162cf0911..b6bd34d9d
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@@ -4167,58 -4321,69 +4167,57 @@@ pub(crate) fn color_field(app: &mut Pho
ui.spacing_mut().item_spacing.x = 8.0;
let (chips, _) = ui.allocate_exact_size(vec2(38.0, h), Sense::hover());
field_chips(app, ui, chips);
- // SV field.
+ // Hue Cube: saturation across and brightness up, hue on the strip. Brightness Cube (the
+ // Color Picker's B mode): hue across and saturation up, brightness on the strip.
+ let brightness = app.ui.color_panel.mode == crate::state::ColorPanelMode::BrightnessCube;
let field_w = w - 38.0 - strip_w - 16.0;
let (field, fresp) = ui.allocate_exact_size(vec2(field_w, h), Sense::click_and_drag());
- let mut mesh = egui::Mesh::default();
- let n = 16;
- for j in 0..=n {
- for i in 0..=n {
- let (sx, vy) = (i as f32 / n as f32, j as f32 / n as f32);
- let c = hsva_color32(egui::ecolor::Hsva::new(hsva.h, sx, 1.0 - vy, 1.0));
- mesh.colored_vertex(pos2(field.left() + sx * field.width(), field.top() + vy * field.height()), c);
- }
- }
- for j in 0..n {
- for i in 0..n {
- let a = (j * (n + 1) + i) as u32;
- let b = a + 1;
- let c = a + (n + 1) as u32;
- let d = c + 1;
- mesh.add_triangle(a, b, d);
- mesh.add_triangle(a, d, c);
- }
- }
- ui.painter().add(mesh);
+ let at = |x: f32, y: f32| {
+ if brightness { egui::ecolor::Hsva::new(x.min(0.9999), 1.0 - y, hsva.v, 1.0) } else { egui::ecolor::Hsva::new(hsva.h, x, 1.0 - y, 1.0) }
+ };
+ ui.painter().add(color_grid(field, 16, |x, y| hsva_color32(at(x, y))));
ui.painter().rect_stroke(field, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside);
- if (fresp.dragged() || fresp.clicked())
- && let Some(p) = fresp.interact_pointer_pos()
- {
+ let field_pick = widgets::pick_pos(&fresp);
+ if let Some(p) = field_pick {
- hsva.s = ((p.x - field.left()) / field.width()).clamp(0.0, 1.0);
- hsva.v = 1.0 - ((p.y - field.top()) / field.height()).clamp(0.0, 1.0);
+ let x = ((p.x - field.left()) / field.width()).clamp(0.0, 1.0);
+ let y = ((p.y - field.top()) / field.height()).clamp(0.0, 1.0);
+ if brightness {
+ hsva.h = x.min(0.9999);
+ hsva.s = 1.0 - y;
+ } else {
+ hsva.s = x;
+ hsva.v = 1.0 - y;
+ }
}
- let knob = pos2(field.left() + hsva.s * field.width(), field.top() + (1.0 - hsva.v) * field.height());
+ let (kx, ky) = if brightness { (hsva.h, 1.0 - hsva.s) } else { (hsva.s, 1.0 - hsva.v) };
+ let knob = pos2(field.left() + kx * field.width(), field.top() + ky * field.height());
ui.painter().circle_stroke(knob, 5.0, Stroke::new(1.5, Color32::WHITE));
ui.painter().circle_stroke(knob, 6.5, Stroke::new(1.0, Color32::from_black_alpha(160)));
- // Hue strip.
+ // The strip: hue (red at both ends, as Photoshop's) or brightness (the colour down to black).
let (strip, sresp) = ui.allocate_exact_size(vec2(strip_w, h), Sense::click_and_drag());
- let mut m2 = egui::Mesh::default();
- let steps = 24;
- for k in 0..=steps {
- let f = k as f32 / steps as f32;
- let c = hsva_color32(egui::ecolor::Hsva::new(1.0 - f, 1.0, 1.0, 1.0));
- m2.colored_vertex(pos2(strip.left(), strip.top() + f * strip.height()), c);
- m2.colored_vertex(pos2(strip.right(), strip.top() + f * strip.height()), c);
- }
- for k in 0..steps {
- let a = (k * 2) as u32;
- m2.add_triangle(a, a + 1, a + 3);
- m2.add_triangle(a, a + 3, a + 2);
- }
- ui.painter().add(m2);
+ let strip_at = |f: f32| {
+ if brightness { egui::ecolor::Hsva::new(hsva.h, hsva.s, 1.0 - f, 1.0) } else { egui::ecolor::Hsva::new(1.0 - f, 1.0, 1.0, 1.0) }
+ };
+ ui.painter().add(color_grid(strip, 24, |_, y| hsva_color32(strip_at(y))));
- if (sresp.dragged() || sresp.clicked())
- && let Some(p) = sresp.interact_pointer_pos()
- {
+ let strip_pick = widgets::pick_pos(&sresp);
+ if let Some(p) = strip_pick {
- hsva.h = 1.0 - ((p.y - strip.top()) / strip.height()).clamp(0.0, 0.9999);
+ let f = ((p.y - strip.top()) / strip.height()).clamp(0.0, 1.0);
+ if brightness {
+ hsva.v = 1.0 - f;
+ } else {
+ hsva.h = 1.0 - f.min(0.9999);
+ }
}
- let y = strip.top() + (1.0 - hsva.h) * strip.height();
+ let y = strip.top() + (1.0 - if brightness { hsva.v } else { hsva.h }) * strip.height();
let tri = vec![pos2(strip.right() + 1.0, y), pos2(strip.right() + 6.0, y - 4.0), pos2(strip.right() + 6.0, y + 4.0)];
ui.painter().add(egui::Shape::convex_polygon(tri, t.text, Stroke::NONE));
- if fresp.dragged() || fresp.clicked() || sresp.dragged() || sresp.clicked() {
+ if field_pick.is_some() || strip_pick.is_some() {
if bg_active {
app.session.tools.background = hsva_srgb(hsva);
- } else {
+ } else if app.session.tools.foreground != hsva_srgb(hsva) {
+ // A held, unmoved press repeats the pick: restyle selected type only on a change.
app.session.tools.foreground = hsva_srgb(hsva);
- crate::type_tool::foreground_changed(app);
- crate::shape_fill_ui::foreground_changed(app, crate::shape_fill_ui::gesture(ui));
+ crate::apply_color::foreground_changed(app, crate::apply_color::gesture(ui.ctx()));
}
ui.data_mut(|d| d.insert_temp(key, (hsva.h, hsva.s)));
}