PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Brushes: import an image file as a brush tip (#3279) (#3292)
Valentin Klein973e86817360
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rsindex cde3a3a70..23b64ae30 100644--- a/crates/automation/src/workspace.rs+++ b/crates/automation/src/workspace.rs@@ -363,7 +363,7 @@ fn preference_uses_ambient_filesystem(path: &str) -> bool {fn command_uses_ambient_path(id: &str, params: &Value) -> bool {match id {- "actions.load" | "brush.presets.importAbr" | "gradient.presets.importGrd" | "plugin.install" | "swatches.import" => {+ "actions.load" | "brush.presets.importAbr" | "brush.presets.importImage" | "gradient.presets.importGrd" | "plugin.install" | "swatches.import" => {// `data` wins over `path` in these commands; any `path` without it reads the filesystem.params.get("data").is_none() && params.get("path").is_some()}@@ -758,6 +758,7 @@ mod tests {fn automation_rejects_ambient_path_commands_and_preferences() {for (id, params) in [("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})),+ ("brush.presets.importImage", serde_json::json!({"path": "/outside/tip.png"})),("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})),("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})),("plugin.reload", serde_json::json!({"path": "/outside/plugins"})),@@ -772,6 +773,7 @@ mod tests {}for (id, params) in [("brush.presets.importAbr", serde_json::json!({"data": "QUJD"})),+ ("brush.presets.importImage", serde_json::json!({"data": "QUJD"})),("gradient.presets.importGrd", serde_json::json!({"data": "QUJD"})),("plugin.install", serde_json::json!({"data": "QUJD"})),("swatches.import", serde_json::json!({"data": "QUJD"})),diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rsindex 5c1942441..b76f8c836 100644--- a/crates/engine/src/brush_cmds.rs+++ b/crates/engine/src/brush_cmds.rs@@ -873,11 +873,24 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result<Value> {v[y * w + x] = ((1.0 - l) * c[3] * sv[(y * w + x) * sc]).clamp(0.0, 1.0);}}+ let (brush, tw, th) = sampled_brush(cmd, &v, w, h)?;+ upsert(s, BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, group: String::new(), folder: Vec::new(), captures: Default::default() });+ s.tools.brush = brush;+ s.tools.current_preset = Some(name.clone());+ s.tools.brush_changed();+ Ok(json!({ "name": name, "width": tw, "height": th }))+}++/// A sampled-tip brush from a paint-amount map (`w`×`h`, row-major, 0 = no paint, 1 = full):+/// cropped to the painted extent, at most [`MAX_TIP`] px a side. Shared by Define Brush Preset+/// and importing an image file as a brush (`brush.presets.importImage`).+pub(crate) fn sampled_brush(cmd: &str, v: &[f32], w: usize, h: usize) -> Result<(BrushSettings, u32, u32)> {+ let at = |x: usize, y: usize| v.get(y * w + x).copied().unwrap_or(0.0);// Crop to the painted extent.let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);for y in 0..h {for x in 0..w {- if v[y * w + x] > 1e-4 {+ if at(x, y) > 1e-4 {x0 = x0.min(x);y0 = y0.min(y);x1 = x1.max(x + 1);@@ -886,23 +899,19 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result<Value> {}}if x1 <= x0 || y1 <= y0 {- return Err(bad(cmd, "the selected pixels contain no paint (all white or transparent)"));+ return Err(bad(cmd, "the pixels contain no paint (all white or transparent)"));}let (tw, th) = ((x1 - x0) as u32, (y1 - y0) as u32);if tw.max(th) > MAX_TIP {- return Err(bad(cmd, format!("selection too large for a brush tip ({tw}×{th}; max {MAX_TIP} px)")));+ return Err(bad(cmd, format!("too large for a brush tip ({tw}×{th}; max {MAX_TIP} px)")));}let mut data = Vec::with_capacity((tw * th) as usize);for y in y0..y1 {- data.extend_from_slice(&v[y * w + x0..y * w + x1]);+ data.extend((x0..x1).map(|x| at(x, y)));}let tip = GrayTile::from_f32(tw, th, &data);let brush = BrushSettings { tip: TipShape::Sampled(tip), size: tw.max(th) as f32, spacing: 0.25, pressure_size: false, ..BrushSettings::default() };- upsert(s, BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, group: String::new(), folder: Vec::new(), captures: Default::default() });- s.tools.brush = brush;- s.tools.current_preset = Some(name.clone());- s.tools.brush_changed();- Ok(json!({ "name": name, "width": tw, "height": th }))+ Ok((brush, tw, th))}pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result<Value> {diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/preset_import_cmds.rsindex e6bff8eb6..8da6cee8a 100644--- a/crates/engine/src/preset_import_cmds.rs+++ b/crates/engine/src/preset_import_cmds.rs@@ -4,6 +4,9 @@//! library as one group named after the file, with the file's own folders nested inside it//! as Photoshop does (Brushes panel › Import Brushes…, Preset Manager). Parsing lives in//! `photocraft-psd` (`abr`), the mapping onto [`BrushSettings`] in `photocraft-io` (`abr_map`).+//! - `brush.presets.importImage` turns an image file (anything File › Open reads: PNG, JPEG,+//! TIFF, PSD…) into a sampled-tip brush preset, as Edit › Define Brush Preset does with a+//! selection: dark pixels paint, white and transparent ones don't (TOOL-213-12).//! - `gradient.presets.importGrd` adds the gradients of a `.grd` file (version 5) to the//! Gradients panel as one group.//!@@ -115,6 +118,87 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_ioOk(json!({ "group": group, "imported": names, "count": names.len(), "folders": folders, "version": imp.version, "warnings": imp.warnings }))}+/// The image's paint amount (darkness × alpha of its composite, as Define Brush Preset reads a+/// selection), cropped to the painted extent. The composite is rendered in bands twice: once to+/// find the painted bounds, then only those, so a large mostly-white image never needs a+/// full-size buffer.+fn image_paint(doc: &photocraft_doc::Document, cmd: &str) -> Result<(Vec<f32>, usize, usize)> {+ let paint = |c: [f32; 4]| ((1.0 - photocraft_color::blend::lum([c[0], c[1], c[2]])) * c[3]).clamp(0.0, 1.0);+ let mut bounds: Option<photocraft_geom::Rect> = None;+ let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> std::result::Result<(), ()> {+ let w = band.rect.width() as usize;+ for (i, c) in band.px.iter().enumerate() {+ if paint(*c) > 1e-4 {+ let (x, y) = (band.rect.x0 + (i % w.max(1)) as i32, band.rect.y0 + (i / w.max(1)) as i32);+ let px = photocraft_geom::Rect::new(x, y, x.saturating_add(1), y.saturating_add(1));+ bounds = Some(bounds.map_or(px, |b| b.union(&px)));+ }+ }+ Ok(())+ });+ let area = bounds.ok_or_else(|| bad(cmd, "the image contains no paint (all white or transparent)"))?;+ let max = crate::brush_cmds::MAX_TIP;+ if area.width().max(area.height()) > max {+ return Err(bad(cmd, format!("the painted part of the image is too large for a brush tip ({}×{}; max {max} px)", area.width(), area.height())));+ }+ let (w, h) = (area.width() as usize, area.height() as usize);+ let mut v = vec![0.0f32; w * h];+ let _ = photocraft_compose::render_bands(doc, area, 0, |band| -> std::result::Result<(), ()> {+ let bw = band.rect.width() as usize;+ for (i, c) in band.px.iter().enumerate() {+ let (x, y) = ((band.rect.x0 - area.x0) as usize + i % bw.max(1), (band.rect.y0 - area.y0) as usize + i / bw.max(1));+ if let Some(out) = v.get_mut(y * w + x) {+ *out = paint(*c);+ }+ }+ Ok(())+ });+ Ok((v, w, h))+}++/// Brushes panel › Import Brushes… with an image file: a new sampled-tip preset named after the+/// file (never overwriting one), made the current brush unless `select` is false.+fn import_image(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "brush.presets.importImage";+ let (bytes, stem) = file_bytes(p, cmd, "image file")?;+ let file_name = match p.get("fileName") {+ None => None,+ Some(v) => Some(v.as_str().map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`fileName` must be a non-empty string"))?),+ };+ // The decoder picks the format by content, falling back to the name's extension.+ let decode_name = p.get("path").and_then(Value::as_str).or(file_name).unwrap_or("image");+ let stem = if stem.is_empty() {+ file_name.and_then(|n| std::path::Path::new(n).file_stem()).map(|s| s.to_string_lossy().trim().to_string()).unwrap_or_default()+ } else {+ stem+ };+ let name = match p.get("name") {+ None if stem.is_empty() => "Imported Brush".to_string(),+ None => stem,+ Some(v) => v.as_str().map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` must be a non-empty string"))?.to_string(),+ };+ let doc = crate::file_cmds::import(decode_name, &bytes)?;+ let (v, w, h) = image_paint(&doc, cmd)?;+ let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?;+ let taken: Vec<String> = s.tools.presets.iter().map(|x| x.name.clone()).collect();+ let name = unique(&name, &taken);+ s.tools.presets.push(photocraft_paint::BrushPreset {+ name: name.clone(),+ brush: brush.clone(),+ builtin: false,+ group: String::new(),+ folder: Vec::new(),+ captures: Default::default(),+ });+ s.brush_presets_changed();+ if p.get("select").and_then(Value::as_bool).unwrap_or(true) {+ s.tools.brush = brush;+ s.tools.current_preset = Some(name.clone());+ s.tools.brush_changed();+ }+ Ok(json!({ "name": name, "width": tw, "height": th }))+}+/// Brush-file import command specs.pub fn specs() -> Vec<CommandSpec> {vec![@@ -128,6 +212,16 @@ pub fn specs() -> Vec<CommandSpec> {run: import_abr,journal: true,},+ CommandSpec {+ id: "brush.presets.importImage",+ label: "Import Brush from Image…",+ menu: &[],+ shortcut: None,+ params: r##"{"path":"image file (PNG, JPEG, TIFF, PSD…)"?,"data":base64 bytes?,"fileName":string? (with data: the file's name, for its format and the default preset name),"name":string?=file name,"select":bool=true (make it the current brush)} → {name, width, height}"##,+ enabled: always,+ run: import_image,+ journal: true,+ },CommandSpec {id: "gradient.presets.importGrd",label: "Import Gradients…",@@ -362,6 +456,76 @@ mod tests {assert!(k.iter().all(|v| *v < 0.01), "{k:?}");}+ /// A 40×30 16-bit RGBA PNG: transparent, a white opaque band (no paint) and a black 10×6 block+ /// at (5, 8) (full paint).+ fn stamp_png16() -> Vec<u8> {+ let mut px = vec![0u16; 40 * 30 * 4];+ for y in 0..30 {+ for x in 0..40 {+ let i = (y * 40 + x) * 4;+ if (5..15).contains(&x) && (8..14).contains(&y) {+ px[i + 3] = u16::MAX;+ } else if y >= 20 {+ px[i..i + 4].copy_from_slice(&[u16::MAX; 4]);+ }+ }+ }+ let img = photocraft_codecs::Image::from_u16(40, 30, photocraft_codecs::ChannelLayout::Rgba, &px).unwrap();+ photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()+ }++ #[test]+ fn imports_an_image_as_a_brush_tip() {+ use photocraft_paint::TipShape;+ let mut s = Session::new();+ let data = photocraft_paint::tile::b64_encode(&stamp_png16());+ let r = s.execute("brush.presets.importImage", json!({"data": data, "fileName": "Stamp.png"})).unwrap();+ assert_eq!(r, json!({"name": "Stamp", "width": 10, "height": 6}), "cropped to the dark block");+ let pr = s.tools.presets.iter().find(|p| p.name == "Stamp").unwrap();+ let TipShape::Sampled(tip) = &pr.brush.tip else { panic!("sampled tip expected") };+ assert_eq!((tip.width, tip.height), (10, 6));+ assert!((pr.brush.size - 10.0).abs() < 1e-6);+ assert_eq!(s.tools.current_preset.as_deref(), Some("Stamp"), "the imported brush is current");+ assert!(matches!(s.tools.brush.tip, TipShape::Sampled(_)));+ // A second import keeps the first: a new name, and `select: false` leaves the brush alone.+ let r = s.execute("brush.presets.importImage", json!({"data": data, "fileName": "Stamp.png", "select": false})).unwrap();+ assert_eq!(r["name"], "Stamp 2");+ assert_eq!(s.tools.current_preset.as_deref(), Some("Stamp"));++ // An 8-bit grayscale JPEG from disk: named after the file.+ let px: Vec<u8> = (0..24 * 24).map(|i| if (8..16).contains(&(i % 24)) && (4..20).contains(&(i / 24)) { 0 } else { 255 }).collect();+ let img = photocraft_codecs::Image::from_u8(24, 24, photocraft_codecs::ChannelLayout::Gray, px).unwrap();+ let jpeg = photocraft_codecs::encode(&img, photocraft_codecs::Format::Jpeg, &Default::default()).unwrap();+ let path = std::env::temp_dir().join(format!("pc-brush-tip-{}.jpg", std::process::id()));+ std::fs::write(&path, jpeg).unwrap();+ let r = s.execute("brush.presets.importImage", json!({"path": path.to_string_lossy()}));+ let _ = std::fs::remove_file(&path);+ let r = r.unwrap();+ assert!(r["name"].as_str().unwrap().starts_with("pc-brush-tip-"), "{r}");+ let (w, h) = (r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap());+ assert!((8..=10).contains(&w) && (16..=18).contains(&h), "JPEG ringing aside, the bar: {r}");+ }++ #[test]+ fn image_brush_import_fails_cleanly() {+ let mut s = Session::new();+ let white = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Gray, vec![255; 16]).unwrap();+ let white = photocraft_paint::tile::b64_encode(&photocraft_codecs::encode(&white, photocraft_codecs::Format::Png, &Default::default()).unwrap());+ let n = s.tools.presets.len();+ for p in [+ json!({}),+ json!({"data": white}),+ json!({"data": "@@"}),+ json!({"data": photocraft_paint::tile::b64_encode(b"not an image")}),+ json!({"data": white, "name": 3}),+ json!({"data": white, "fileName": ""}),+ json!({"path": "/nope/brush.png"}),+ ] {+ assert!(s.execute("brush.presets.importImage", p.clone()).is_err(), "{p}");+ }+ assert_eq!(s.tools.presets.len(), n, "a failed import adds nothing");+ }+#[test]fn unique_names() {let taken = vec!["A".to_string(), "a 2".to_string()];diff --git a/crates/ui-egui/src/brush_picker.rs b/crates/ui-egui/src/brush_picker.rsindex 8ac5bb8c2..9bef83a64 100644--- a/crates/ui-egui/src/brush_picker.rs+++ b/crates/ui-egui/src/brush_picker.rs@@ -166,7 +166,7 @@ pub fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, picks: Vec<Pick>) {crate::brush_preset_dialog::open(app, None);}Pick::Import => {- let _ = app.open_dialog_file();+ let _ = crate::preset_files_ui::import_brushes(app);}}}diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rsindex fefb3aa4d..a31b06a0d 100644--- a/crates/ui-egui/src/brushes_tab.rs+++ b/crates/ui-egui/src/brushes_tab.rs@@ -1009,8 +1009,8 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if crate::brush_picker::named(new, "Create new brush from the current settings").clicked() {crate::brush_preset_dialog::open(app, None);}- if icons::button(ui, "folder-open", 24.0, false, "Import Brushes… (.abr)").clicked() {- let _ = app.open_dialog_file();+ if icons::button(ui, "folder-open", 24.0, false, "Import Brushes… (.abr or image)").clicked() {+ let _ = crate::preset_files_ui::import_brushes(app);}});});diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 46bf70cf6..5dd6aa7e9 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2097,7 +2097,8 @@Expand group ({key}-click: all groups) Rozbalit skupinu ({key}+kliknutí: všechny skupiny)Fade steps Kroky zeslabeníHide the layer's effects ({key}-click: all layers) Skrýt efekty vrstvy ({key}+kliknutí: všechny vrstvy)- Import Brushes… (.abr) Importovat štětce… (.abr)+ Import Brushes… (.abr or image) Importovat štětce… (.abr nebo obrázek)+ Import Brush from Image… Importovat štětec z obrázku…Move Group Down Posunout skupinu dolůMove Group Up Posunout skupinu nahoruReset the brush to the defaults Obnovit výchozí nastavení štětcediff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 5a86f996c..4c9402c2d 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2069,7 +2069,8 @@Expand group ({key}-click: all groups) Gruppe ausklappen ({key}-Klick: alle Gruppen)Fade steps Verblassen-SchritteHide the layer's effects ({key}-click: all layers) Effekte der Ebene ausblenden ({key}-Klick: alle Ebenen)- Import Brushes… (.abr) Pinsel importieren… (.abr)+ Import Brushes… (.abr or image) Pinsel importieren… (.abr oder Bild)+ Import Brush from Image… Pinsel aus Bild importieren…Move Group Down Gruppe nach untenMove Group Up Gruppe nach obenReset the brush to the defaults Pinsel auf Standardwerte zurücksetzendiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 335d09ff2..98c9d5d58 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -2529,7 +2529,8 @@Image Size: Μέγεθος εικόνας:Image interpolation Παρεμβολή εικόναςImage previews Προεπισκοπήσεις εικόνων- Import Brushes… (.abr) Εισαγωγή πινέλων… (.abr)+ Import Brushes… (.abr or image) Εισαγωγή πινέλων… (.abr ή εικόνα)+ Import Brush from Image… Εισαγωγή πινέλου από εικόνα…Import Presets Εισαγωγή προεπιλογώνImported ΕισήχθηIn Είσοδοςdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex f28462b8d..c495cef81 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2084,7 +2084,8 @@Expand group ({key}-click: all groups) Expandir grupo ({key}-clic: todos los grupos)Fade steps Pasos de desvanecimientoHide the layer's effects ({key}-click: all layers) Ocultar los efectos de la capa ({key}-clic: todas las capas)- Import Brushes… (.abr) Importar pinceles… (.abr)+ Import Brushes… (.abr or image) Importar pinceles… (.abr o imagen)+ Import Brush from Image… Importar pincel desde imagen…Move Group Down Mover grupo abajoMove Group Up Mover grupo arribaReset the brush to the defaults Restablecer el pincel a los valores predeterminadosdiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 1ca36c6e1..130a8fbef 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2049,7 +2049,8 @@Expand group ({key}-click: all groups) Développer le groupe ({key}-clic : tous les groupes)Fade steps Étapes d'estompageHide the layer's effects ({key}-click: all layers) Masquer les effets du calque ({key}-clic : tous les calques)- Import Brushes… (.abr) Importer des pinceaux… (.abr)+ Import Brushes… (.abr or image) Importer des pinceaux… (.abr ou image)+ Import Brush from Image… Importer un pinceau depuis une image…Move Group Down Descendre le groupeMove Group Up Monter le groupeReset the brush to the defaults Réinitialiser le pinceau aux valeurs par défautdiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 56f5a3d0d..381a0e374 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2043,7 +2043,8 @@Expand group ({key}-click: all groups) Bentangkan grup ({key}-klik: semua grup)Fade steps Langkah pudarHide the layer's effects ({key}-click: all layers) Sembunyikan efek layer ({key}-klik: semua layer)- Import Brushes… (.abr) Impor Kuas… (.abr)+ Import Brushes… (.abr or image) Impor Kuas… (.abr atau gambar)+ Import Brush from Image… Impor Kuas dari Gambar…Move Group Down Pindah Grup ke BawahMove Group Up Pindah Grup ke AtasReset the brush to the defaults Reset kuas ke defaultdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 29b08b500..21fc6e5a4 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2080,6 +2080,8 @@Fade steps Passi dissolvenzaHide the layer's effects ({key}-click: all layers) Nascondi effetti livello ({key}-clic: tutti i livelli)Import Brushes… (.abr) Importa pennelli… (.abr)+ Import Brushes… (.abr or image) Importa pennelli… (.abr o immagine)+ Import Brush from Image… Importa pennello da immagine…Move Group Down Sposta gruppo giùMove Group Up Sposta gruppo suReset the brush to the defaults Reimposta pennello ai predefinitidiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 7a4e3da8e..2152313c5 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2082,6 +2082,8 @@Fade steps フェードのステップ数Hide the layer's effects ({key}-click: all layers) レイヤーの効果を隠す ({key}+クリック: すべてのレイヤー)Import Brushes… (.abr) ブラシを読み込み…(.abr)+ Import Brushes… (.abr or image) ブラシを読み込み…(.abr または画像)+ Import Brush from Image… 画像からブラシを読み込み…Move Group Down グループを下へ移動Move Group Up グループを上へ移動Reset the brush to the defaults ブラシを既定に戻すdiff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex b6baf821e..9a5db74f5 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2043,7 +2043,8 @@Expand group ({key}-click: all groups) 그룹 펼치기 ({key} 키를 누른 채 클릭: 모든 그룹)Fade steps 약화 단계Hide the layer's effects ({key}-click: all layers) 레이어 효과 숨기기 ({key} 키를 누른 채 클릭: 모든 레이어)- Import Brushes… (.abr) 브러시 가져오기… (.abr)+ Import Brushes… (.abr or image) 브러시 가져오기… (.abr 또는 이미지)+ Import Brush from Image… 이미지에서 브러시 가져오기…Move Group Down 그룹 아래로 이동Move Group Up 그룹 위로 이동Reset the brush to the defaults 브러시를 기본값으로 초기화diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex f21a7b93e..04ab080f4 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -2049,7 +2049,8 @@Expand group ({key}-click: all groups) Groep uitvouwen ({key}-klik: alle groepen)Fade steps AfzwakstappenHide the layer's effects ({key}-click: all layers) De effecten van de laag verbergen ({key}-klik: alle lagen)- Import Brushes… (.abr) Penselen importeren… (.abr)+ Import Brushes… (.abr or image) Penselen importeren… (.abr of afbeelding)+ Import Brush from Image… Penseel uit afbeelding importeren…Move Group Down Groep omlaagMove Group Up Groep omhoogReset the brush to the defaults Het penseel terugzetten naar de standaardwaardendiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 4e59677fb..d41b3abea 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -2073,7 +2073,8 @@Expand group ({key}-click: all groups) Rozwiń grupę (kliknięcie z {key}: wszystkie grupy)Fade steps Kroki zanikaniaHide the layer's effects ({key}-click: all layers) Ukryj efekty warstwy (kliknięcie z {key}: wszystkie warstwy)- Import Brushes… (.abr) Importuj pędzle… (.abr)+ Import Brushes… (.abr or image) Importuj pędzle… (.abr lub obraz)+ Import Brush from Image… Importuj pędzel z obrazu…Move Group Down Przesuń grupę w dółMove Group Up Przesuń grupę w góręReset the brush to the defaults Przywróć domyślne ustawienia pędzladiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 048dc176d..9d28ba1da 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2044,7 +2044,8 @@Expand group ({key}-click: all groups) Expandir grupo ({key}-clique: todos os grupos)Fade steps Etapas de atenuaçãoHide the layer's effects ({key}-click: all layers) Ocultar os efeitos da camada ({key}-clique: todas as camadas)- Import Brushes… (.abr) Importar pincéis… (.abr)+ Import Brushes… (.abr or image) Importar pincéis… (.abr ou imagem)+ Import Brush from Image… Importar pincel de imagem…Move Group Down Mover grupo para baixoMove Group Up Mover grupo para cimaReset the brush to the defaults Redefinir o pincel para os padrõesdiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 61e8a105c..7608aa5e2 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -1036,6 +1036,8 @@Rename Brush… Переименовать кисть…Delete Brush Удалить кистьImport Brushes… Импортировать кисти…+ Import Brushes… (.abr or image) Импортировать кисти… (.abr или изображение)+ Import Brush from Image… Импортировать кисть из изображения…Gradient Preset Options Параметры наборов градиентовImport .GRD Импортировать .GRDChoose a gradient file (.grd). Выберите файл градиентов (.grd).diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 95f117718..c60140e01 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -2900,7 +2900,8 @@ fontWeight Italic КурсивнийFrame {current} / {total} Кадр {current} / {total}Create new brush from the current settings Створити новий пензель із поточних параметрівDelete brush Видалити пензель- Import Brushes… (.abr) Імпортувати пензлі… (.abr)+ Import Brushes… (.abr or image) Імпортувати пензлі… (.abr або зображення)+ Import Brush from Image… Імпортувати пензель із зображення…System Info Інформація про системуClick to sample the foreground colour · {key}-click for background Клацання бере зразок переднього плану · {key}+клацання для фонуCreate Warped Text Створити деформований текстdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 262d68064..aa81d4fa9 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2092,7 +2092,8 @@Expand group (⌥-click: all groups) 展开组 (⌥-单击:所有组)Fade steps 渐隐步数Hide the layer's effects (⌥-click: all layers) 隐藏图层效果 (⌥-单击:所有图层)- Import Brushes… (.abr) 导入画笔… (.abr)+ Import Brushes… (.abr or image) 导入画笔… (.abr 或图像)+ Import Brush from Image… 从图像导入画笔…Move Group Down 向下移动组Move Group Up 向上移动组Reset the brush to the defaults 将画笔重置为默认值diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex d004168fd..e1db19320 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2085,7 +2085,8 @@Expand group ({key}-click: all groups) 展開群組 ({key}+按一下:全部群組)Fade steps 淡出步數Hide the layer's effects ({key}-click: all layers) 隱藏圖層效果 ({key}+按一下:所有圖層)- Import Brushes… (.abr) 匯入筆刷… (.abr)+ Import Brushes… (.abr or image) 匯入筆刷… (.abr 或影像)+ Import Brush from Image… 從影像匯入筆刷…Move Group Down 下移群組Move Group Up 上移群組Reset the brush to the defaults 將筆刷重設為預設值diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rsindex 6138c0884..1ea072583 100644--- a/crates/ui-egui/src/preset_files_ui.rs+++ b/crates/ui-egui/src/preset_files_ui.rs@@ -4,7 +4,8 @@//! `gradient.presets.importGrd`, swatches (`.aco`, `.ase`) to the Swatches panel through//! `swatches.import`, patterns (`.pat`) to the Patterns panel through `pattern.import`, keyboard//! shortcut sets (`.kys`) to Edit › Keyboard Shortcuts through-//! [`crate::kys_import`], instead of opening as documents.+//! [`crate::kys_import`], instead of opening as documents. Import Brushes… also takes an image+//! file, which becomes a brush tip through `brush.presets.importImage` (TOOL-213-12).use serde_json::{Value, json};@@ -25,6 +26,36 @@ pub fn is_preset_file(name: &str) -> bool {PRESET_EXTS.contains(&ext(name).as_str())}+/// Image files Import Brushes… offers besides `.abr`: each becomes a sampled brush tip.+pub const BRUSH_IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "psd", "psb", "bmp", "gif", "webp", "tga"];++/// Brushes panel / brush preset picker › Import Brushes…: an `.abr` joins the brush library as a+/// group (as File › Open does), an image file becomes a new brush preset with that image as its tip.+pub fn import_brushes(app: &mut PhotocraftApp) -> Result<Value, String> {+ let exts: Vec<&str> = std::iter::once("abr").chain(BRUSH_IMAGE_EXTS.iter().copied()).collect();+ app.pick_file_bytes_filtered(&exts, |app, name, bytes| match open(app, &name, &bytes) {+ Some(r) => r.map(|()| Value::Null),+ None => import_brush_image(app, &name, &bytes),+ })+}++/// An image file as a brush tip: a new preset named after the file, made the current brush.+pub fn import_brush_image(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result<Value, String> {+ let file = std::path::Path::new(name).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| name.to_string());+ let mut p = source(name, bytes);+ if p.get("data").is_some() {+ p["fileName"] = json!(file);+ }+ let r = app.run("brush.presets.importImage", p)?;+ let preset = r.get("name").and_then(Value::as_str).unwrap_or_default();+ app.ui.status_error = false;+ app.ui.status = format!("Imported brush {preset} from {file}");+ // Show it: Brush Settings › Brushes tab.+ app.ui.panels.brush_settings = true;+ app.ui.brush_tab = 1;+ Ok(r)+}+/// Import from a gradient picker through the same preset command as File › Open.pub(crate) fn import_gradients_dialog(app: &mut PhotocraftApp) {let result = app.pick_file_bytes_filtered(&["grd"], |app, name, bytes| {@@ -114,4 +145,33 @@ mod tests {assert!(!is_preset_file("photo.psd"));assert!(!is_preset_file("abr"));}++ /// Import Brushes… with a PNG: the image becomes the current brush's tip (TOOL-213-12).+ #[test]+ fn import_brushes_turns_an_image_into_a_brush_tip() {+ use photocraft_engine::paint::TipShape;+ let mut px = vec![255u8; 16 * 16];+ for y in 4..12 {+ for x in 6..9 {+ px[y * 16 + x] = 0;+ }+ }+ let img = photocraft_codecs::Image::from_u8(16, 16, photocraft_codecs::ChannelLayout::Gray, px).unwrap();+ let png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();+ let (show, asked) = crate::file_dialog::fake(vec![Some(crate::file_dialog::FileDialogAnswer::Contents("Leaf.png".into(), png))]);+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(show), ..Default::default() });+ import_brushes(&mut app).unwrap();+ app.poll_file_dialog(&egui::Context::default(), None);+ match asked.borrow().first() {+ Some(crate::file_dialog::FileDialogRequest::Open { extensions: Some(e), .. }) => {+ assert!(e.iter().any(|x| x == "abr") && e.iter().any(|x| x == "png"), "{e:?}")+ }+ other => panic!("expected a filtered open dialog, got {other:?}"),+ }+ assert!(!app.ui.status_error, "{}", app.ui.status);+ assert_eq!(app.session.tools.current_preset.as_deref(), Some("Leaf"));+ let TipShape::Sampled(tip) = &app.session.tools.brush.tip else { panic!("sampled tip expected") };+ assert_eq!((tip.width, tip.height), (3, 8));+ assert!(app.ui.panels.brush_settings && app.ui.brush_tab == 1, "the Brushes tab shows the new brush");+ }}diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 9068b4048..25004ce49 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js|---|---:|---:|---:|---|| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) || [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 241/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 149/256, round trip ≥ 258/256 |-| [Tools](#tools) | 29 | 13 | 1 | |+| [Tools](#tools) | 30 | 13 | 0 | || [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 160 (target 0) || [Type](#type) | 4 | 3 | 2 | || [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) |@@ -141,7 +141,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| TOOL-213-9 | Eyedropper comparison ring (new colour above, current below) while sampling | done | [#213](https://github.com/storytold/photocraft/issues/213) | eyedropper_ring (canvas.rs): the sampled colour on the upper arc, the foreground below, drawn for the Eyedropper and Alt-sampling while the button is held; the Precise-cursor preference keeps the crosshair || TOOL-213-10 | Ctrl+Alt drag resizes brush size/hardness with an on-canvas readout | done | [#213](https://github.com/storytold/photocraft/issues/213) | brush_resize.rs (#297, #370): Alt+right-drag, or Control+Option-drag on macOS (Control+Alt everywhere), sets diameter horizontally and hardness vertically, circle plus Diameter/Hardness readout, one coalesced tools.setBrush, no paint or history; 9 tests there || TOOL-213-11 | Editable pressure curve, global and per control | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Global: Preferences › Tools › Pressure Curve (prefs tools.pressureCurve; monotone cubic, engine prefs::PressureCurve; applied to every pen sample in ui-egui stylus.rs before any brush; editor pressure_curve_ui.rs with Linear/Soft/Hard presets). Missing: per-control curves (each brush dynamic's own response to pressure, tilt, rotation) |-| TOOL-213-12 | Import an image file as a brush tip | missing | [#213](https://github.com/storytold/photocraft/issues/213) | Only brush.defineFromSelection and brush.presets.importAbr |+| TOOL-213-12 | Import an image file as a brush tip | done | [#213](https://github.com/storytold/photocraft/issues/213) | brush.presets.importImage (path or data); Brushes panel and preset picker Import Brushes… take .abr or an image (#3279) || TOOL-213-13 | Brush regression tests: no seams, hard edge, zero-scatter defaults, ABR never black | done | [#213](https://github.com/storytold/photocraft/issues/213) | Seam, hard-edge and zero-scatter tests in brush_tests.rs; ABR tip colour test in abr_map/tests.rs || TOOL-213-14 | Tablet: no OS arrow cursor over the canvas on macOS, Windows and Linux | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Brush tools set CursorIcon::None (canvas.rs:1259-1275); not verified per OS || TOOL-213-18 | Pattern Stamp tool: sibling of Clone Stamp in the S flyout | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::PatternStamp in the S group; paint.patternStamp stamps the Patterns-panel tile with Aligned and Impressionist (an approximation: it jitters each dab's tile phase, not Photoshop's smeared impressionist look); engine tests cover depths, seams, hostile input |diff --git a/scorecard/tools.toml b/scorecard/tools.tomlindex 1123c6aab..36deb272e 100644--- a/scorecard/tools.toml+++ b/scorecard/tools.toml@@ -85,9 +85,9 @@ note = "Global: Preferences › Tools › Pressure Curve (prefs tools.pressureCu[[item]]id = "TOOL-213-12"target = "Import an image file as a brush tip"-status = "missing"+status = "done"issue = 213-note = "Only brush.defineFromSelection and brush.presets.importAbr"+note = "brush.presets.importImage (path or data); Brushes panel and preset picker Import Brushes… take .abr or an image (#3279)"[[item]]id = "TOOL-213-13"