Skip to content

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

Persist brush presets in a size-aware preset store (#78) (#82)

Brandon Thomasff53be714db5
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index a25a83cec..5624663c0 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -98,6 +98,8 @@ fn main() -> eframe::Result {
// Read the main display's ICC profile while the window opens (colour-managed canvas).
let monitor = monitor_profile::detect_async();
+ // Brush presets load in the background; the app attaches them when they arrive.
+ let presets = services::presets_dir().map(photocraft_engine::preset_store::open_dir_async);
let mut options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_icon(app_icon())
@@ -118,7 +120,9 @@ fn main() -> eframe::Result {
options,
Box::new(move |cc| {
let automation = control.as_ref().map(|(_, _, workspace)| workspace.clone());
- let mut app = PhotocraftApp::new(Session::new(), services::native(automation));
+ let mut services = services::native(automation);
+ services.preset_store = presets;
+ let mut app = PhotocraftApp::new(Session::new(), services);
app.integrated_titlebar = cfg!(target_os = "macos");
if let Ok(Some(icc)) = monitor.recv_timeout(std::time::Duration::from_secs(2)) {
app.session.color.monitor_profile = Some(std::sync::Arc::new(icc));
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 9157f1ddb..d745d791b 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -57,6 +57,12 @@ fn prefs_file() -> Option<PathBuf> {
config_dir().map(|d| d.join("preferences.json"))
}
+/// The brush preset store (one file per preset group plus tip bitmaps; see
+/// `photocraft_engine::preset_store`).
+pub fn presets_dir() -> Option<PathBuf> {
+ config_dir().map(|d| d.join("Presets"))
+}
+
fn recovery_dir() -> Option<PathBuf> {
config_dir().map(|d| d.join("Recovery"))
}
@@ -168,6 +174,8 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
})),
// Set by main once the Apple-event handlers are connected (macOS).
os_events: None,
+ // Set by main, which starts loading the store before the window opens.
+ preset_store: None,
}
}
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
index 39629f1d7..b0f5be8db 100644
--- a/crates/engine/src/brush_cmds.rs
+++ b/crates/engine/src/brush_cmds.rs
@@ -375,6 +375,7 @@ fn upsert(s: &mut Session, preset: BrushPreset) {
Some(x) => *x = preset,
None => s.tools.presets.push(preset),
}
+ s.brush_presets_changed();
}
fn presets_save(s: &mut Session, p: &Value) -> Result<Value> {
@@ -396,6 +397,7 @@ fn presets_delete(s: &mut Session, p: &Value) -> Result<Value> {
if s.tools.presets.len() == before {
return Err(bad(cmd, format!("no brush preset named `{name}`")));
}
+ s.brush_presets_changed();
Ok(json!({ "count": s.tools.presets.len() }))
}
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs
index 91093273d..c3724bc32 100644
--- a/crates/engine/src/edit_menu_cmds.rs
+++ b/crates/engine/src/edit_menu_cmds.rs
@@ -759,7 +759,12 @@ fn preset_manager(s: &mut Session, p: &Value) -> Result<Value> {
let new =
p.get("newName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `newName`"))?.to_string();
match kind.as_str() {
- "brushes" => s.tools.presets[i].name = new,
+ "brushes" => {
+ // A renamed built-in is the user's preset now (and persists as one).
+ let b = &mut s.tools.presets[i];
+ b.name = new;
+ b.builtin = false;
+ }
"patterns" => s.patterns.items[i].name = new,
_ => s.edit_state.custom_shapes[i].name = new,
}
@@ -779,6 +784,9 @@ fn preset_manager(s: &mut Session, p: &Value) -> Result<Value> {
}
other => return Err(bad(cmd, format!("unknown action `{other}` (list|rename|delete|move)"))),
}
+ if kind == "brushes" {
+ s.brush_presets_changed();
+ }
Ok(json!({kind.clone(): preset_names(s, &kind)}))
}
@@ -835,6 +843,7 @@ fn export_import(s: &mut Session, p: &Value) -> Result<Value> {
}
nb += 1;
}
+ s.brush_presets_changed();
}
if want("customShapes") {
for c in file.custom_shapes {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 87a514245..5c9b45eb3 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -49,6 +49,7 @@ mod pixels;
pub mod plugin_cmds;
pub mod prefs;
pub mod preset_import_cmds;
+pub mod preset_store;
pub mod presets;
pub mod print_cmds;
pub mod proof_sim;
@@ -186,6 +187,9 @@ pub struct ToolState {
pub brush: photocraft_paint::BrushSettings,
/// Brush presets (built-ins plus user presets; see `brush.presets.*`).
pub presets: Vec<photocraft_paint::BrushPreset>,
+ /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store
+ /// syncs when it moves.
+ pub presets_rev: u64,
/// Mixer Brush paint carried between strokes.
pub mixer: photocraft_paint::mixer::MixerState,
}
@@ -197,6 +201,7 @@ impl Default for ToolState {
background: [1.0, 1.0, 1.0, 1.0],
brush: Default::default(),
presets: photocraft_paint::presets::builtin(),
+ presets_rev: 0,
mixer: Default::default(),
}
}
@@ -238,6 +243,9 @@ pub struct Session {
/// File menu state: Lock Slices, Image Assets, last Print / Save for Web settings, script
/// event log (see `automate_cmds`).
pub file_menu: automate_cmds::FileMenuState,
+ /// Persistent brush preset store (desktop only; `None` keeps presets session-only, as in
+ /// headless and test sessions). See `preset_store`.
+ pub preset_store: Option<preset_store::PresetStore>,
}
impl Session {
@@ -311,6 +319,7 @@ impl Session {
let r = r?;
edit_menu_cmds::after_command(self, id);
automate_cmds::after_command(self, id);
+ self.sync_preset_store();
if spec.journal {
self.journal.push((id.to_string(), params));
}
diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/preset_import_cmds.rs
index 8a8b2f92d..e65b310dc 100644
--- a/crates/engine/src/preset_import_cmds.rs
+++ b/crates/engine/src/preset_import_cmds.rs
@@ -75,6 +75,7 @@ fn import_abr(s: &mut Session, p: &Value) -> Result<Value> {
names.push(preset.name.clone());
s.tools.presets.push(preset);
}
+ s.brush_presets_changed();
if p.get("select").and_then(Value::as_bool).unwrap_or(false)
&& let Some(first) = names.first()
&& let Some(pr) = photocraft_paint::presets::find(&s.tools.presets, first)
diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs
new file mode 100644
index 000000000..2b6bdfbc9
--- /dev/null
+++ b/crates/engine/src/preset_store.rs
@@ -0,0 +1,728 @@
+//! Persistent brush preset store: user and imported (`.abr`) brush presets survive a restart.
+//!
+//! Sampled tips would bloat the preferences document, so brush presets live in their own store,
+//! a directory next to the preferences (desktop: `<config dir>/Presets`):
+//!
+//! - `<group>-<hash>.pcbrushes`: one JSON file per preset group (folder) holding the presets'
+//! settings with every bitmap (sampled tip, Dual Brush tip, texture tile) replaced by a
+//! reference to a tip file;
+//! - `tips/<hash>.pctip`: content-addressed bitmaps, deflated, stored at 8 bits per sample when
+//! the tip came from 8-bit data and 16 bits otherwise. Renaming or re-grouping a preset only
+//! rewrites a small JSON file; a tip no group references any more is deleted;
+//! - `index.json`: group order and the built-in presets the user deleted.
+//!
+//! Built-in presets are never written (they are regenerated on start). The store syncs after
+//! every command that changes the brush presets ([`Session::brush_presets_changed`]); only groups
+//! whose content changed are rewritten. Every write is atomic (temp file + rename) and bounded
+//! ([`MAX_GROUP_BYTES`], [`MAX_TIP_BYTES`], [`MAX_STORE_BYTES`]); corrupt or oversized files are
+//! skipped with a warning and left on disk, never a panic.
+//!
+//! A [`Session`] has no store by default, so headless CLI/MCP sessions and tests never write.
+//! The desktop app opens the store on a background thread ([`open`]) and attaches it with
+//! [`Session::attach_preset_store`] once loaded, so the first frame never waits for it. The web
+//! app has no store (localStorage is too small for sampled tips): its brush presets are
+//! session-only. Gradient presets, including imported `.grd` groups, are small and persist with
+//! the preferences document (`presets.gradients`).
+
+use std::collections::{HashMap, HashSet};
+use std::io::Read;
+
+use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Pattern, TipShape};
+use serde::{Deserialize, Serialize};
+
+use crate::Session;
+
+/// Group file extension.
+pub const GROUP_EXT: &str = "pcbrushes";
+/// Tip file extension (inside [`TIPS_DIR`]).
+pub const TIP_EXT: &str = "pctip";
+/// Subdirectory holding the tip bitmaps.
+pub const TIPS_DIR: &str = "tips";
+/// Group order and deleted built-ins.
+pub const INDEX_FILE: &str = "index.json";
+/// Largest group file read or written.
+pub const MAX_GROUP_BYTES: u64 = 16 << 20;
+/// Largest tip file read or written.
+pub const MAX_TIP_BYTES: u64 = 64 << 20;
+/// Largest index file read.
+pub const MAX_INDEX_BYTES: u64 = 4 << 20;
+/// The whole store never grows beyond this; further groups are skipped with a warning.
+pub const MAX_STORE_BYTES: u64 = 2 << 30;
+/// Largest tip side accepted from disk.
+pub const MAX_TIP_SIDE: u32 = 16384;
+/// Largest tip sample count accepted from disk (64 Mi samples).
+pub const MAX_TIP_SAMPLES: u64 = 1 << 26;
+/// Most group files loaded.
+pub const MAX_GROUPS: usize = 4096;
+/// Most presets loaded from one group file.
+pub const MAX_PRESETS_PER_GROUP: usize = 50_000;
+
+const GROUP_FORMAT: &str = "photocraft-brush-group";
+const TIP_MAGIC: &[u8; 6] = b"PCTIP1";
+const TIP_HEADER: usize = 6 + 1 + 4 + 4;
+
+/// Where the store's files live. File names are relative (`name.pcbrushes`, `tips/x.pctip`).
+pub trait PresetBackend: Send {
+ /// Every file in the store with its size in bytes (the top level plus [`TIPS_DIR`]).
+ /// A missing store is empty, not an error.
+ fn list(&self) -> Result<Vec<(String, u64)>, String>;
+ /// Read a file, failing when it is larger than `max` bytes.
+ fn read(&self, name: &str, max: u64) -> Result<Vec<u8>, String>;
+ /// Replace a file atomically (a crash leaves the old or the new file, never half of one).
+ fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String>;
+ /// Delete a file; deleting a missing file succeeds.
+ fn remove(&self, name: &str) -> Result<(), String>;
+}
+
+/// Store file names are generated (`[A-Za-z0-9 _.-]`, optionally under `tips/`); anything else
+/// (path separators, `..`) is refused so a backend never leaves its directory.
+fn valid_name(name: &str) -> bool {
+ let leaf = name.strip_prefix("tips/").unwrap_or(name);
+ !leaf.is_empty() && leaf.len() <= 128 && !leaf.starts_with('.') && leaf.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '_' | '-' | '.'))
+}
+
+/// An in-memory store (tests, and frontends without a file system). Clones share the files.
+#[derive(Clone, Default)]
+pub struct MemBackend {
+ pub files: std::sync::Arc<std::sync::Mutex<std::collections::BTreeMap<String, Vec<u8>>>>,
+}
+
+impl MemBackend {
+ fn lock(&self) -> Result<std::sync::MutexGuard<'_, std::collections::BTreeMap<String, Vec<u8>>>, String> {
+ self.files.lock().map_err(|_| "preset store lock poisoned".to_string())
+ }
+}
+
+impl PresetBackend for MemBackend {
+ fn list(&self) -> Result<Vec<(String, u64)>, String> {
+ Ok(self.lock()?.iter().map(|(k, v)| (k.clone(), v.len() as u64)).collect())
+ }
+ fn read(&self, name: &str, max: u64) -> Result<Vec<u8>, String> {
+ let files = self.lock()?;
+ let b = files.get(name).ok_or_else(|| format!("{name}: not found"))?;
+ if b.len() as u64 > max {
+ return Err(format!("{name}: too large ({} bytes)", b.len()));
+ }
+ Ok(b.clone())
+ }
+ fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
+ if !valid_name(name) {
+ return Err(format!("invalid store file name `{name}`"));
+ }
+ self.lock()?.insert(name.to_string(), bytes.to_vec());
+ Ok(())
+ }
+ fn remove(&self, name: &str) -> Result<(), String> {
+ self.lock()?.remove(name);
+ Ok(())
+ }
+}
+
+/// A store directory on disk (desktop).
+#[cfg(not(target_arch = "wasm32"))]
+pub struct DirBackend {
+ root: std::path::PathBuf,
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+impl DirBackend {
+ pub fn new(root: impl Into<std::path::PathBuf>) -> Self {
+ DirBackend { root: root.into() }
+ }
+ pub fn root(&self) -> &std::path::Path {
+ &self.root
+ }
+ fn path(&self, name: &str) -> Result<std::path::PathBuf, String> {
+ if !valid_name(name) {
+ return Err(format!("invalid store file name `{name}`"));
+ }
+ Ok(self.root.join(name))
+ }
+ fn list_dir(&self, sub: &str, out: &mut Vec<(String, u64)>) -> Result<(), String> {
+ let dir = if sub.is_empty() { self.root.clone() } else { self.root.join(sub) };
+ let rd = match std::fs::read_dir(&dir) {
+ Ok(rd) => rd,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(e) => return Err(format!("{}: {e}", dir.display())),
+ };
+ for entry in rd.flatten() {
+ let Ok(meta) = entry.metadata() else { continue };
+ if !meta.is_file() {
+ continue;
+ }
+ let Some(leaf) = entry.file_name().to_str().map(str::to_string) else { continue };
+ let name = if sub.is_empty() { leaf } else { format!("{sub}/{leaf}") };
+ if valid_name(&name) {
+ out.push((name, meta.len()));
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+impl PresetBackend for DirBackend {
+ fn list(&self) -> Result<Vec<(String, u64)>, String> {
+ let mut out = Vec::new();
+ self.list_dir("", &mut out)?;
+ self.list_dir(TIPS_DIR, &mut out)?;
+ Ok(out)
+ }
+ fn read(&self, name: &str, max: u64) -> Result<Vec<u8>, String> {
+ let path = self.path(name)?;
+ let f = std::fs::File::open(&path).map_err(|e| format!("{name}: {e}"))?;
+ let mut out = Vec::new();
+ f.take(max.saturating_add(1)).read_to_end(&mut out).map_err(|e| format!("{name}: {e}"))?;
+ if out.len() as u64 > max {
+ return Err(format!("{name}: larger than {max} bytes"));
+ }
+ Ok(out)
+ }
+ fn write(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
+ let path = self.path(name)?;
+ let dir = path.parent().ok_or_else(|| format!("{name}: no parent directory"))?;
+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ let leaf = path.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();
+ let tmp = dir.join(format!(".{leaf}.tmp"));
+ std::fs::write(&tmp, bytes).map_err(|e| format!("{name}: {e}"))?;
+ std::fs::rename(&tmp, &path).map_err(|e| {
+ let _ = std::fs::remove_file(&tmp);
+ format!("{name}: {e}")
+ })
+ }
+ fn remove(&self, name: &str) -> Result<(), String> {
+ match std::fs::remove_file(self.path(name)?) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(format!("{name}: {e}")),
+ }
+ }
+}
+
+// ------------------------------------------------------------------ tips
+
+/// Content hash of a tip (32 hex digits); the tip file's name.
+fn tip_hash(t: &GrayTile) -> String {
+ let mut h = blake3::Hasher::new();
+ h.update(&t.width.to_le_bytes());
+ h.update(&t.height.to_le_bytes());
+ let mut buf = Vec::with_capacity(8192);
+ for chunk in t.data.chunks(4096) {
+ buf.clear();
+ for v in chunk {
+ buf.extend_from_slice(&v.to_le_bytes());
+ }
+ h.update(&buf);
+ }
+ h.finalize().to_hex()[..32].to_string()
+}
+
+/// `PCTIP1`, bits (8|16), width, height (u32 LE), then the zlib-deflated samples.
+pub fn encode_tip(t: &GrayTile) -> Vec<u8> {
+ use std::io::Write;
+ let eight = t.data.iter().all(|v| v % 257 == 0);
+ let mut out = Vec::with_capacity(TIP_HEADER + t.data.len() / 4);
+ out.extend_from_slice(TIP_MAGIC);
+ out.push(if eight { 8 } else { 16 });
+ out.extend_from_slice(&t.width.to_le_bytes());
+ out.extend_from_slice(&t.height.to_le_bytes());
+ let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::fast());
+ let mut buf = Vec::with_capacity(8192);
+ let mut ok = true;
+ for chunk in t.data.chunks(4096) {
+ buf.clear();
+ if eight {
+ buf.extend(chunk.iter().map(|v| (v / 257) as u8));
+ } else {
+ for v in chunk {
+ buf.extend_from_slice(&v.to_le_bytes());
+ }
+ }
+ ok &= z.write_all(&buf).is_ok();
+ }
+ match z.finish() {
+ Ok(v) if ok => v,
+ _ => Vec::new(),
+ }
+}
+
+/// Inverse of [`encode_tip`]; any malformed, truncated or oversized input is an error.
+pub fn decode_tip(bytes: &[u8]) -> Result<GrayTile, String> {
+ let head = bytes.get(..TIP_HEADER).ok_or("truncated tip header")?;
+ if &head[..6] != TIP_MAGIC {
+ return Err("not a PhotoCraft tip".into());
+ }
+ let bits = head[6];
+ let u32_at = |i: usize| u32::from_le_bytes([head[i], head[i + 1], head[i + 2], head[i + 3]]);
+ let (w, h) = (u32_at(7), u32_at(11));
+ if w == 0 || h == 0 || w > MAX_TIP_SIDE || h > MAX_TIP_SIDE {
+ return Err(format!("bad tip size {w}×{h}"));
+ }
+ let n = u64::from(w) * u64::from(h);
+ if n > MAX_TIP_SAMPLES {
+ return Err(format!("tip too large ({w}×{h})"));
+ }
+ let bytes_per = match bits {
+ 8 => 1u64,
+ 16 => 2,
+ b => return Err(format!("unsupported tip depth {b}")),
+ };
+ let want = n * bytes_per;
+ let mut raw = Vec::with_capacity(want as usize);
+ flate2::read::ZlibDecoder::new(&bytes[TIP_HEADER..]).take(want + 1).read_to_end(&mut raw).map_err(|e| format!("tip data: {e}"))?;
+ if raw.len() as u64 != want {
+ return Err(format!("tip data has {} bytes, expected {want}", raw.len()));
+ }
+ let data: Vec<u16> =
+ if bits == 8 { raw.iter().map(|&v| u16::from(v) * 257).collect() } else { raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect() };
+ Ok(GrayTile { width: w, height: h, data })
+}
+
+// ------------------------------------------------------------------ group files
+
+/// References from a stored preset to its tip files.
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+struct TipRefs {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ tip: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ dual_tip: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ texture: Option<String>,
+}
+
+impl TipRefs {
+ fn hashes(&self) -> impl Iterator<Item = &String> {
+ [&self.tip, &self.dual_tip, &self.texture].into_iter().flatten()
+ }
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct StoredPreset {
+ name: String,
+ brush: BrushSettings,
+ #[serde(default)]
+ tips: TipRefs,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct GroupFile {
+ format: String,
+ version: u32,
+ group: String,
+ presets: Vec<StoredPreset>,
+}
+
+#[derive(Default, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+struct IndexFile {
+ version: u32,
+ /// Group files in display order.
+ groups: Vec<String>,
+ /// Built-in presets the user deleted (by name).
+ hidden_builtins: Vec<String>,
+}
+
+/// The group's file name: a readable, sanitised prefix plus a hash of the exact name, so
+/// different names never share a file.
+pub fn group_file_name(group: &str) -> String {
+ let mut stem: String = group.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, ' ' | '_' | '-') { c } else { '_' }).take(48).collect();
+ stem = stem.trim().to_string();
+ if stem.is_empty() {
+ stem = "Ungrouped".into();
+ }
+ let h = blake3::hash(group.as_bytes()).to_hex();
+ format!("{stem}-{}.{GROUP_EXT}", &h[..8])
+}
+
+/// Take the bitmaps out of a preset's settings (they are stored as tip files).
+fn split_tips(mut b: BrushSettings) -> (BrushSettings, [Option<GrayTile>; 3]) {
+ let tip = match std::mem::take(&mut b.tip) {
+ TipShape::Sampled(t) => Some(t),
+ TipShape::Round => None,
+ };
+ let dual = match std::mem::take(&mut b.dual_brush.tip) {
+ TipShape::Sampled(t) => Some(t),
+ TipShape::Round => None,
+ };
+ let texture = match std::mem::take(&mut b.texture.pattern) {
+ Pattern::Tile(t) => Some(t),
+ other => {
+ b.texture.pattern = other;
+ None
+ }
+ };
+ (b, [tip, dual, texture])
+}
+
+/// The opposite of [`split_tips`]: `None` when a referenced tip is missing.
+fn join_tips(mut b: BrushSettings, refs: &TipRefs, tips: &HashMap<String, GrayTile>) -> Option<BrushSettings> {
+ if let Some(h) = &refs.tip {
+ b.tip = TipShape::Sampled(tips.get(h)?.clone());
+ }
+ if let Some(h) = &refs.dual_tip {
+ b.dual_brush.tip = TipShape::Sampled(tips.get(h)?.clone());
+ }
+ if let Some(h) = &refs.texture {
+ b.texture.pattern = Pattern::Tile(tips.get(h)?.clone());
+ }
+ Some(b)
+}
+
+fn tip_file(hash: &str) -> String {
+ format!("{TIPS_DIR}/{hash}.{TIP_EXT}")
+}
+
+/// What a group looked like when it was last written (or loaded).
+struct Synced {
+ presets: Vec<BrushPreset>,
+ tips: Vec<String>,
+ bytes: u64,
+}
+
+/// The persistent brush preset store attached to a session (see the module docs).
+pub struct PresetStore {
+ backend: Box<dyn PresetBackend>,
+ /// `tools.presets_rev` at the last sync.
+ synced_rev: Option<u64>,
+ /// Group file name → its last written content.
+ groups: HashMap<String, Synced>,
+ /// Tip hash → file size, for every tip file the store owns.
+ tips: HashMap<String, u64>,
+ index: Option<IndexFile>,
+ warnings: Vec<String>,
+}
+
+/// A loaded store: the presets on disk plus what the session should hide.
+pub struct Opened {
+ pub store: PresetStore,
+ /// User and imported presets, in group order.
+ pub presets: Vec<BrushPreset>,
+ /// Built-in presets the user deleted.
+ pub hidden_builtins: Vec<String>,
+ /// Files that were skipped (corrupt, oversized, missing tips).
+ pub warnings: Vec<String>,
+}
+
+/// Load a store (any thread; the desktop app does this in the background at start).
+pub fn open(backend: Box<dyn PresetBackend>) -> Opened {
+ let mut warnings = Vec::new();
+ let files = backend.list().unwrap_or_else(|e| {
+ warnings.push(format!("brush presets: {e}"));
+ Vec::new()
+ });
+ let index: Option<IndexFile> = if files.iter().any(|(n, _)| n == INDEX_FILE) {
+ match backend.read(INDEX_FILE, MAX_INDEX_BYTES).and_then(|b| serde_json::from_slice(&b).map_err(|e| e.to_string())) {
+ Ok(i) => Some(i),
+ Err(e) => {
+ warnings.push(format!("brush presets: {INDEX_FILE} skipped: {e}"));
+ None
+ }
+ }
+ } else {
+ None
+ };
+ // Group files in index order, then the rest by name.
+ let mut group_files: Vec<(String, u64)> = files.iter().filter(|(n, _)| !n.contains('/') && n.ends_with(&format!(".{GROUP_EXT}"))).cloned().collect();
+ group_files.sort_by(|a, b| a.0.cmp(&b.0));
+ if let Some(ix) = &index {
+ let pos = |n: &str| ix.groups.iter().position(|g| g == n).unwrap_or(usize::MAX);
+ group_files.sort_by_key(|(n, _)| pos(n));
+ }
+ if group_files.len() > MAX_GROUPS {
+ warnings.push(format!("brush presets: only the first {MAX_GROUPS} of {} groups were loaded", group_files.len()));
+ group_files.truncate(MAX_GROUPS);
+ }
+ let tip_sizes: HashMap<String, u64> =
+ files.iter().filter_map(|(n, sz)| Some((n.strip_prefix(&format!("{TIPS_DIR}/"))?.strip_suffix(&format!(".{TIP_EXT}"))?.to_string(), *sz))).collect();
+
+ // Parse the group files.
+ let mut parsed: Vec<(String, u64, GroupFile)> = Vec::new();
+ let mut failed = false;
+ for (name, size) in group_files {
+ let r = backend.read(&name, MAX_GROUP_BYTES).and_then(|b| serde_json::from_slice::<GroupFile>(&b).map_err(|e| e.to_string())).and_then(|g| {
+ if g.format != GROUP_FORMAT {
+ Err(format!("unknown format `{}`", g.format))
+ } else if g.version != 1 {
+ Err(format!("unsupported version {}", g.version))
+ } else if g.presets.len() > MAX_PRESETS_PER_GROUP {
+ Err(format!("{} presets (limit {MAX_PRESETS_PER_GROUP})", g.presets.len()))
+ } else {
+ Ok(g)
+ }
+ });
+ match r {
+ Ok(g) => parsed.push((name, size, g)),
+ Err(e) => {
+ failed = true;
+ warnings.push(format!("brush presets: {name} skipped: {e}"));
+ }
+ }
+ }
+ // Decode every referenced tip once.
+ let wanted: Vec<String> = {
+ let mut seen = HashSet::new();
+ parsed.iter().flat_map(|(_, _, g)| g.presets.iter().flat_map(|p| p.tips.hashes())).filter(|h| seen.insert(h.as_str())).cloned().collect()
+ };
+ let decoded = decode_tips(backend.as_ref(), &wanted, &tip_sizes);
+ let mut tips: HashMap<String, GrayTile> = HashMap::with_capacity(decoded.len());
+ for (h, r) in wanted.iter().zip(decoded) {
+ match r {
+ Ok(t) => {
+ tips.insert(h.clone(), t);
+ }
+ Err(e) => warnings.push(format!("brush presets: tip {h} skipped: {e}")),
+ }
+ }
+
+ let mut store = PresetStore { backend, synced_rev: None, groups: HashMap::new(), tips: HashMap::new(), index: None, warnings: Vec::new() };
+ let mut presets = Vec::new();
+ for (file, size, g) in parsed {
+ let mut items = Vec::with_capacity(g.presets.len());
+ let mut hashes = Vec::new();
+ let mut missing = 0;
+ for sp in g.presets {
+ match join_tips(sp.brush, &sp.tips, &tips) {
+ Some(brush) => {
+ hashes.extend(sp.tips.hashes().cloned());
+ items.push(BrushPreset { name: sp.name, brush, builtin: false, group: g.group.clone() });
+ }
+ None => missing += 1,
+ }
+ }
+ if missing > 0 {
+ // Left on disk untouched (a sync never deletes a file it did not load).
+ failed = true;
+ warnings.push(format!("brush presets: {file} skipped: {missing} preset(s) have missing or unreadable tips"));
+ continue;
+ }
+ for h in &hashes {
+ if let Some(sz) = tip_sizes.get(h) {
+ store.tips.insert(h.clone(), *sz);
+ }
+ }
+ presets.extend(items.iter().cloned());
+ store.groups.insert(file, Synced { presets: items, tips: hashes, bytes: size });
+ }
+ // Tip files nothing references are garbage (e.g. left by a crash), unless a group failed to
+ // load: its tips must survive so a fixed file still works.
+ if !failed {
+ for (h, sz) in &tip_sizes {
+ store.tips.entry(h.clone()).or_insert(*sz);
+ }
+ }
+ let hidden_builtins = index.as_ref().map(|i| i.hidden_builtins.clone()).unwrap_or_default();
+ store.index = index;
+ Opened { store, presets, hidden_builtins, warnings }
+}
+
+/// Read and decode tips, in parallel on native targets.
+fn decode_tips(backend: &dyn PresetBackend, hashes: &[String], sizes: &HashMap<String, u64>) -> Vec<Result<GrayTile, String>> {
+ let read = |h: &String| -> Result<Vec<u8>, String> {
+ if !sizes.contains_key(h) {
+ return Err("file missing".into());
+ }
+ backend.read(&tip_file(h), MAX_TIP_BYTES)
+ };
+ // Reads stay sequential (the backend need not be Sync); decoding is the expensive part.
+ let raw: Vec<Result<Vec<u8>, String>> = hashes.iter().map(read).collect();
+ let dec = |r: &Result<Vec<u8>, String>| r.as_ref().map_err(Clone::clone).and_then(|b| decode_tip(b));
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ raw.par_iter().map(dec).collect()
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ raw.iter().map(dec).collect()
+ }
+}
+
+/// Open a store directory (desktop). Never fails: problems become warnings.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn open_dir(root: impl Into<std::path::PathBuf>) -> Opened {
+ open(Box::new(DirBackend::new(root)))
+}
+
+/// Open a store directory on a background thread; the receiver yields it once loaded.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn open_dir_async(root: std::path::PathBuf) -> std::sync::mpsc::Receiver<Opened> {
+ let (tx, rx) = std::sync::mpsc::channel();
+ let spawned = std::thread::Builder::new().name("brush-presets".into()).spawn(move || {
+ let _ = tx.send(open_dir(root));
+ });
+ if let Err(e) = spawned {
+ // No thread: the caller simply never gets a store (presets stay session-only).
+ eprintln!("brush presets: {e}");
+ }
+ rx
+}
+
+impl PresetStore {
+ /// Warnings from writes since the last call (the shell shows them in the status bar).
+ pub fn take_warnings(&mut self) -> Vec<String> {
+ std::mem::take(&mut self.warnings)
+ }
+
+ /// Total bytes of the files the store owns.
+ pub fn bytes(&self) -> u64 {
+ self.groups.values().map(|g| g.bytes).sum::<u64>() + self.tips.values().sum::<u64>()
+ }
+
+ /// Bring the files in line with `presets` (built-ins skipped): write changed groups, delete
+ /// removed ones and their unreferenced tips, update the index.
+ pub fn sync(&mut self, presets: &[BrushPreset]) {
+ // User presets by group, in first-appearance order.
+ let mut order: Vec<(String, Vec<&BrushPreset>)> = Vec::new();
+ for p in presets.iter().filter(|p| !p.builtin) {
+ match order.iter_mut().find(|(g, _)| *g == p.group) {
+ Some((_, v)) => v.push(p),
+ None => order.push((p.group.clone(), vec![p])),
+ }
+ }
+ let mut files = Vec::with_capacity(order.len());
+ for (group, items) in &order {
+ let file = group_file_name(group);
+ files.push(file.clone());
+ let unchanged = self.groups.get(&file).is_some_and(|s| s.presets.len() == items.len() && s.presets.iter().zip(items).all(|(a, b)| a == *b));
+ if unchanged {
+ continue;
+ }
+ if let Err(e) = self.write_group(&file, group, items) {
+ self.warnings.push(format!("Couldn't save brush presets `{}`: {e}", if group.is_empty() { "(ungrouped)" } else { group }));
+ }
+ }
+ // Groups that are gone.
+ let gone: Vec<String> = self.groups.keys().filter(|f| !files.contains(f)).cloned().collect();
+ for f in gone {
+ match self.backend.remove(&f) {
+ Ok(()) => drop(self.groups.remove(&f)),
+ Err(e) => self.warnings.push(format!("Couldn't delete brush presets file: {e}")),
+ }
+ }
+ // Tips nothing references any more.
+ let used: HashSet<&String> = self.groups.values().flat_map(|g| g.tips.iter()).collect();
+ let unused: Vec<String> = self.tips.keys().filter(|h| !used.contains(h)).cloned().collect();
+ for h in unused {
+ match self.backend.remove(&tip_file(&h)) {
+ Ok(()) => drop(self.tips.remove(&h)),
+ Err(e) => self.warnings.push(format!("Couldn't delete brush tip: {e}")),
+ }
+ }
+ // Index: group order and deleted built-ins.
+ let hidden: Vec<String> = builtin_names().iter().filter(|n| !presets.iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(|n| n.to_string()).collect();
+ let groups: Vec<String> = files.into_iter().filter(|f| self.groups.contains_key(f)).collect();
+ let want = IndexFile { version: 1, groups, hidden_builtins: hidden };
+ let same = self.index.as_ref().is_some_and(|i| i.groups == want.groups && i.hidden_builtins == want.hidden_builtins);
+ if !same {
+ let empty = want.groups.is_empty() && want.hidden_builtins.is_empty();
+ let r = if empty && self.index.is_none() {
+ Ok(())
+ } else {
+ serde_json::to_vec_pretty(&want).map_err(|e| e.to_string()).and_then(|b| self.backend.write(INDEX_FILE, &b))
+ };
+ match r {
+ Ok(()) => self.index = Some(want),
+ Err(e) => self.warnings.push(format!("Couldn't save the brush preset index: {e}")),
+ }
+ }
+ }
+
+ fn write_group(&mut self, file: &str, group: &str, items: &[&BrushPreset]) -> Result<(), String> {
+ let others: u64 = self.groups.iter().filter(|(f, _)| f.as_str() != file).map(|(_, g)| g.bytes).sum::<u64>() + self.tips.values().sum::<u64>();
+ let mut stored = Vec::with_capacity(items.len());
+ let mut hashes = Vec::new();
+ let mut new_bytes = 0u64;
+ for p in items {
+ let (brush, bitmaps) = split_tips(p.brush.clone());
+ let mut refs = [None, None, None];
+ for (slot, t) in refs.iter_mut().zip(bitmaps) {
+ let Some(t) = t else { continue };
+ if !t.is_valid() {
+ return Err(format!("preset `{}` has an invalid tip", p.name));
+ }
+ let h = tip_hash(&t);
+ if !self.tips.contains_key(&h) {
+ let bytes = encode_tip(&t);
+ if bytes.is_empty() || bytes.len() as u64 > MAX_TIP_BYTES {
+ return Err(format!("the tip of `{}` is too large to save", p.name));
+ }
+ new_bytes += bytes.len() as u64;
+ if others + new_bytes > MAX_STORE_BYTES {
+ return Err(format!("the preset store is full ({} MB limit)", MAX_STORE_BYTES >> 20));
+ }
+ self.backend.write(&tip_file(&h), &bytes)?;
+ self.tips.insert(h.clone(), bytes.len() as u64);
+ }
+ hashes.push(h.clone());
+ *slot = Some(h);
+ }
+ let [tip, dual_tip, texture] = refs;
+ stored.push(StoredPreset { name: p.name.clone(), brush, tips: TipRefs { tip, dual_tip, texture } });
+ }
+ let gf = GroupFile { format: GROUP_FORMAT.into(), version: 1, group: group.to_string(), presets: stored };
+ let bytes = serde_json::to_vec(&gf).map_err(|e| e.to_string())?;
+ if bytes.len() as u64 > MAX_GROUP_BYTES {
+ return Err(format!("the group is too large to save ({} MB limit)", MAX_GROUP_BYTES >> 20));
+ }
+ if others + new_bytes + bytes.len() as u64 > MAX_STORE_BYTES {
+ return Err(format!("the preset store is full ({} MB limit)", MAX_STORE_BYTES >> 20));
+ }
+ self.backend.write(file, &bytes)?;
+ self.groups.insert(file.to_string(), Synced { presets: items.iter().map(|p| (*p).clone()).collect(), tips: hashes, bytes: bytes.len() as u64 });
+ Ok(())
+ }
+}
+
+fn builtin_names() -> &'static [String] {
+ static NAMES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
+ NAMES.get_or_init(|| photocraft_paint::presets::builtin().into_iter().map(|p| p.name).collect())
+}
+
+impl Session {
+ /// Record a brush preset change (create, delete, rename, import…): the attached store, if
+ /// any, syncs after the running command.
+ pub fn brush_presets_changed(&mut self) {
+ self.tools.presets_rev += 1;
+ }
+
+ /// Attach a loaded store: merge its presets into the library (a stored preset replaces the
+ /// built-in of the same name; presets created before the store finished loading win), hide
+ /// deleted built-ins, then sync. Returns the load warnings.
+ pub fn attach_preset_store(&mut self, opened: Opened) -> Vec<String> {
+ let Opened { store, presets, hidden_builtins, mut warnings } = opened;
+ let lib = &mut self.tools.presets;
+ lib.retain(|p| !(p.builtin && hidden_builtins.iter().any(|h| h.eq_ignore_ascii_case(&p.name))));
+ for p in presets {
+ match lib.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&p.name)) {
+ Some(x) if x.builtin => *x = p,
+ Some(_) => {}
+ None => lib.push(p),
+ }
+ }
+ self.preset_store = Some(store);
+ self.brush_presets_changed();
+ self.sync_preset_store();
+ if let Some(st) = self.preset_store.as_mut() {
+ warnings.extend(st.take_warnings());
+ }
+ warnings
+ }
+
+ /// Write pending brush preset changes to the attached store (no-op without one).
+ pub fn sync_preset_store(&mut self) {
+ let rev = self.tools.presets_rev;
+ if let Some(st) = self.preset_store.as_mut()
+ && st.synced_rev != Some(rev)
+ {
+ st.sync(&self.tools.presets);
+ st.synced_rev = Some(rev);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs
new file mode 100644
index 000000000..e8c24eff9
--- /dev/null
+++ b/crates/engine/src/preset_store/tests.rs
@@ -0,0 +1,326 @@
+use super::*;
+use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12};
+use serde_json::json;
+use std::path::PathBuf;
+
+/// A fresh, empty directory under the system temp dir (tests never write anywhere else).
+struct TempDir(PathBuf);
+
+impl TempDir {
+ fn new(tag: &str) -> Self {
+ static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let d = std::env::temp_dir().join(format!("pc-preset-store-{}-{tag}-{n}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ TempDir(d)
+ }
+ fn files(&self) -> Vec<String> {
+ let mut v: Vec<String> = DirBackend::new(&self.0).list().unwrap().into_iter().map(|(n, _)| n).collect();
+ v.sort();
+ v
+ }
+}
+
+impl Drop for TempDir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+}
+
+/// A session with the store in `dir` attached.
+fn session(dir: &TempDir) -> (Session, Vec<String>) {
+ let mut s = Session::new();
+ let w = s.attach_preset_store(open_dir(&dir.0));
+ (s, w)
+}
+
+fn tip8(w: u32, h: u32, seed: u32) -> GrayTile {
+ GrayTile::from_fn(w, h, |x, y| ((x * 7 + y * 13 + seed) % 256) as f32 / 255.0)
+}
+
+fn tip16(w: u32, h: u32, seed: u32) -> GrayTile {
+ let data = (0..w * h).map(|i| (i.wrapping_mul(2654435761).wrapping_add(seed) >> 16) as u16).collect();
+ GrayTile { width: w, height: h, data }
+}
+
+fn sampled(name: &str, group: &str, tip: GrayTile) -> BrushPreset {
+ let brush = BrushSettings { size: 42.0, spacing: 0.1, tip: TipShape::Sampled(tip), ..Default::default() };
+ BrushPreset { name: name.into(), brush, builtin: false, group: group.into() }
+}
+
+fn user(s: &Session) -> Vec<BrushPreset> {
+ s.tools.presets.iter().filter(|p| !p.builtin).cloned().collect()
+}
+
+#[test]
+fn sessions_have_no_store_by_default() {
+ let mut s = Session::new();
+ assert!(s.preset_store.is_none(), "headless sessions must stay hermetic");
+ s.execute("brush.presets.save", json!({"name": "Mine"})).unwrap();
+ assert!(s.preset_store.is_none());
+}
+
+#[test]
+fn tip_codec_round_trips_8_and_16_bit() {
+ let t8 = tip8(37, 21, 3);
+ let t16 = tip16(40, 33, 9);
+ let e8 = encode_tip(&t8);
+ let e16 = encode_tip(&t16);
+ assert_eq!(e8[6], 8, "8-bit sourced tips are stored at 8 bits");
+ assert_eq!(e16[6], 16);
+ assert_eq!(decode_tip(&e8).unwrap(), t8);
+ assert_eq!(decode_tip(&e16).unwrap(), t16);
+}
+
+#[test]
+fn tip_decoder_rejects_garbage() {
+ let good = encode_tip(&tip16(16, 16, 1));
+ for n in 0..good.len() {
+ assert!(decode_tip(&good[..n]).is_err(), "truncated at {n}");
+ }
+ let mut bad = good.clone();
+ bad[6] = 12;
+ assert!(decode_tip(&bad).is_err());
+ // A header claiming a huge bitmap is refused before allocating.
+ let mut huge = good.clone();
+ huge[7..11].copy_from_slice(&u32::MAX.to_le_bytes());
+ assert!(decode_tip(&huge).is_err());
+ let mut big = good.clone();
+ big[7..11].copy_from_slice(&MAX_TIP_SIDE.to_le_bytes());
+ big[11..15].copy_from_slice(&MAX_TIP_SIDE.to_le_bytes());
+ assert!(decode_tip(&big).is_err());
+ let mut rng = 0x1234_5678u32;
+ for _ in 0..200 {
+ let len = (rng % 64) as usize;
+ let v: Vec<u8> = (0..len)
+ .map(|_| {
+ rng ^= rng << 13;
+ rng ^= rng >> 17;
+ rng ^= rng << 5;
+ rng as u8
+ })
+ .collect();
+ let _ = decode_tip(&v);
+ let mut w = TIP_MAGIC.to_vec();
+ w.extend_from_slice(&v);
+ let _ = decode_tip(&w);
+ }
+}
+
+#[test]
+fn group_with_sampled_8_and_16_bit_tips_round_trips() {
+ let dir = TempDir::new("roundtrip");
+ let (mut s, w) = session(&dir);
+ assert!(w.is_empty(), "{w:?}");
+ assert!(dir.files().is_empty(), "attaching an empty store writes nothing");
+ let mut a = sampled("Eight", "Inks", tip8(64, 48, 1));
+ a.brush.dual_brush.tip = TipShape::Sampled(tip8(12, 12, 5));
+ a.brush.texture.pattern = Pattern::Tile(tip16(32, 32, 7));
+ let b = sampled("Sixteen", "Inks", tip16(50, 70, 2));
+ let mut c = sampled("Shared tip", "Other", tip8(64, 48, 1));
+ c.brush.size = 9.0;
+ s.tools.presets.extend([a, b, c]);
+ s.brush_presets_changed();
+ s.sync_preset_store();
+ let files = dir.files();
+ assert_eq!(files.iter().filter(|f| f.ends_with(".pcbrushes")).count(), 2, "{files:?}");
+ // Four distinct bitmaps: the 64×48 tip is shared by two presets.
+ assert_eq!(files.iter().filter(|f| f.starts_with("tips/")).count(), 4, "{files:?}");
+ assert!(files.contains(&INDEX_FILE.to_string()));
+
+ let (t, w) = session(&dir);
+ assert!(w.is_empty(), "{w:?}");
+ assert_eq!(user(&t), user(&s));
+ let order: Vec<String> = user(&t).into_iter().map(|p| p.name).collect();
+ assert_eq!(order, ["Eight", "Sixteen", "Shared tip"]);
+ // Nothing changed: reloading rewrote nothing.
+ let before: Vec<_> = DirBackend::new(&dir.0).list().unwrap();
+ let mut t = t;
+ t.brush_presets_changed();
+ t.sync_preset_store();
+ assert_eq!(DirBackend::new(&dir.0).list().unwrap(), before);
+}
+
+#[test]
+fn commands_persist_and_delete_removes_from_disk() {
+ let dir = TempDir::new("commands");
+ let (mut s, _) = session(&dir);
+ s.tools.brush.tip = TipShape::Sampled(tip16(20, 20, 4));
+ s.execute("brush.presets.save", json!({"name": "Scribble"})).unwrap();
+ assert_eq!(dir.files().iter().filter(|f| f.starts_with("tips/")).count(), 1);
+ let (t, _) = session(&dir);
+ let p = photocraft_paint::presets::find(&t.tools.presets, "Scribble").expect("saved preset reloads");
+ assert_eq!(p.brush.tip, s.tools.brush.tip);
+
+ // Rename through the Preset Manager, then delete.
+ s.execute("edit.presets.presetManager", json!({"action": "rename", "kind": "brushes", "name": "Scribble", "newName": "Doodle"})).unwrap();
+ let (t, _) = session(&dir);
+ assert!(photocraft_paint::presets::find(&t.tools.presets, "Doodle").is_some());
+ assert!(photocraft_paint::presets::find(&t.tools.presets, "Scribble").is_none());
+ s.execute("brush.presets.delete", json!({"name": "Doodle"})).unwrap();
+ assert_eq!(dir.files(), [INDEX_FILE], "the group file and its tip are gone");
+ let (t, _) = session(&dir);
+ assert!(photocraft_paint::presets::find(&t.tools.presets, "Doodle").is_none());
+}
+
+#[test]
+fn imported_abr_group_persists() {
+ let dir = TempDir::new("abr");
+ let (mut s, _) = session(&dir);
+ let tip = AbrSample { id: String::new(), width: 6, height: 4, depth: 8, data: (0..24).map(|i| i * 10).collect() };
+ let abr = write_v12(
+ 2,
+ &[
+ LegacyBrush { name: "Grit".into(), spacing: 25, anti_alias: true, tip: LegacyTip::Sampled(tip) },
+ LegacyBrush {
+ name: "Round 9".into(),
+ spacing: 10,
+ anti_alias: true,
+ tip: LegacyTip::Computed { diameter: 9, hardness: 100, angle: 0, roundness: 100 },
+ },
+ ],
+ true,
+ )
+ .unwrap();
+ let data = photocraft_paint::tile::b64_encode(&abr);
+ s.execute("brush.presets.importAbr", json!({"data": data, "group": "Legacy Set"})).unwrap();
+ let (t, w) = session(&dir);
+ assert!(w.is_empty(), "{w:?}");
+ let grp: Vec<&BrushPreset> = t.tools.presets.iter().filter(|p| p.group == "Legacy Set").collect();
+ assert_eq!(grp.len(), 2);
+ assert_eq!(user(&t), user(&s));
+ // Deleting every preset of the group removes its file and tips.
+ let names: Vec<String> = grp.iter().map(|p| p.name.clone()).collect();
+ for n in names {
+ s.execute("brush.presets.delete", json!({"name": n})).unwrap();
+ }
+ assert!(!dir.files().iter().any(|f| f.ends_with(".pcbrushes") || f.starts_with("tips/")), "{:?}", dir.files());
+}
+
+#[test]
+fn deleted_builtins_stay_deleted_and_overrides_replace_them() {
+ let dir = TempDir::new("builtins");
+ let (mut s, _) = session(&dir);
+ let first = s.tools.presets[0].name.clone();
+ let second = s.tools.presets[1].name.clone();
+ s.execute("brush.presets.delete", json!({"name": first})).unwrap();
+ s.tools.brush.size = 77.0;
+ s.execute("brush.presets.save", json!({"name": second})).unwrap();
+ let (t, _) = session(&dir);
+ assert!(photocraft_paint::presets::find(&t.tools.presets, &first).is_none());
+ let p = photocraft_paint::presets::find(&t.tools.presets, &second).unwrap();
+ assert_eq!((p.builtin, p.brush.size), (false, 77.0));
+ assert_eq!(t.tools.presets.iter().filter(|p| p.name.eq_ignore_ascii_case(&second)).count(), 1);
+ // No built-in is ever written.
+ let n = dir.files().iter().filter(|f| f.ends_with(".pcbrushes")).count();
+ assert_eq!(n, 1);
+}
+
+#[test]
+fn startup_with_many_groups_loads_them_all() {
+ let dir = TempDir::new("many");
+ let (mut s, _) = session(&dir);
+ for g in 0..25 {
+ for i in 0..4 {
+ s.tools.presets.push(sampled(&format!("P{g}-{i}"), &format!("Group {g}"), tip8(16 + i, 16, g)));
+ }
+ }
+ s.brush_presets_changed();
+ s.sync_preset_store();
+ let (t, w) = session(&dir);
+ assert!(w.is_empty(), "{w:?}");
+ assert_eq!(user(&t).len(), 100);
+ let groups: Vec<String> = user(&t).iter().map(|p| p.group.clone()).fold(Vec::new(), |mut v, g| {
+ if !v.contains(&g) {
+ v.push(g);
+ }
+ v
+ });
+ assert_eq!(groups, (0..25).map(|g| format!("Group {g}")).collect::<Vec<_>>(), "group order survives");
+}
+
+#[test]
+fn corrupt_and_oversized_files_are_skipped_with_a_warning() {
+ let dir = TempDir::new("corrupt");
+ let (mut s, _) = session(&dir);
+ s.tools.presets.push(sampled("Good", "Fine", tip8(8, 8, 1)));
+ s.tools.presets.push(sampled("Lost", "Broken tip", tip16(9, 9, 2)));
+ s.brush_presets_changed();
+ s.sync_preset_store();
+ let be = DirBackend::new(&dir.0);
+ be.write("junk-00000000.pcbrushes", b"{not json").unwrap();
+ be.write("wrong-00000000.pcbrushes", br#"{"format":"other","version":1,"group":"x","presets":[]}"#).unwrap();
+ // Corrupt the 16-bit tip of "Broken tip".
+ let h = tip_hash(&tip16(9, 9, 2));
+ be.write(&tip_file(&h), b"PCTIP1\x10garbage").unwrap();
+ let (mut t, w) = session(&dir);
+ assert_eq!(w.len(), 4, "{w:?}");
+ assert!(photocraft_paint::presets::find(&t.tools.presets, "Good").is_some());
+ assert!(photocraft_paint::presets::find(&t.tools.presets, "Lost").is_none());
+ // The broken files are left alone for the user (never deleted by a sync).
+ t.execute("brush.presets.save", json!({"name": "Another"})).unwrap();
+ let files = dir.files();
+ assert!(files.contains(&"junk-00000000.pcbrushes".to_string()) && files.contains(&tip_file(&h)), "{files:?}");
+
+ // Oversized files are refused without reading them whole.
+ let mem = MemBackend::default();
+ mem.files.lock().unwrap().insert("big-00000000.pcbrushes".into(), vec![b' '; MAX_GROUP_BYTES as usize + 1]);
+ mem.files.lock().unwrap().insert(INDEX_FILE.into(), b"[1,2".to_vec());
+ let o = open(Box::new(mem));
+ assert!(o.presets.is_empty());
+ assert_eq!(o.warnings.len(), 2, "{:?}", o.warnings);
+}
+
+#[test]
+fn write_failures_are_warnings() {
+ let dir = TempDir::new("readonly");
+ // The store "directory" is a file: every write fails.
+ std::fs::write(&dir.0, b"not a dir").unwrap();
+ let mut s = Session::new();
+ s.attach_preset_store(open_dir(&dir.0));
+ s.tools.brush.tip = TipShape::Sampled(tip8(4, 4, 0));
+ s.execute("brush.presets.save", json!({"name": "Nope"})).unwrap();
+ let w = s.preset_store.as_mut().unwrap().take_warnings();
+ assert!(!w.is_empty());
+ let _ = std::fs::remove_file(&dir.0);
+}
+
+#[test]
+fn backends_refuse_paths_outside_the_store() {
+ let mem = MemBackend::default();
+ for n in ["../x.pcbrushes", "a/b.pcbrushes", "tips/../x", ".hidden", "", "tips/"] {
+ assert!(mem.write(n, b"x").is_err(), "{n}");
+ }
+ assert!(group_file_name("../../etc/passwd").ends_with(".pcbrushes"));
+ assert!(valid_name(&group_file_name("../../etc/passwd")));
+ assert!(valid_name(&group_file_name("")));
+ assert!(valid_name(&group_file_name("日本語 ブラシ")));
+ assert_ne!(group_file_name("a/b"), group_file_name("a_b"));
+}
+
+/// `cargo test --release -p photocraft-engine --lib preset_store::tests::bench_load_500 -- --ignored --nocapture`
+#[test]
+#[ignore]
+fn bench_load_500_sampled_presets() {
+ let dir = TempDir::new("bench");
+ let (mut s, _) = session(&dir);
+ for i in 0..500u32 {
+ // A mix of 8-bit (most .abr tips) and 16-bit tips, 64..319 px.
+ let side = 64 + (i * 37) % 256;
+ let t = if i % 4 == 0 { tip16(side, side, i) } else { tip8(side, side, i) };
+ s.tools.presets.push(sampled(&format!("Brush {i}"), &format!("Set {}", i / 50), t));
+ }
+ s.brush_presets_changed();
+ let t0 = std::time::Instant::now();
+ s.sync_preset_store();
+ let write = t0.elapsed();
+ let bytes = s.preset_store.as_ref().unwrap().bytes();
+ let t0 = std::time::Instant::now();
+ let o = open_dir(&dir.0);
+ let load = t0.elapsed();
+ assert_eq!(o.presets.len(), 500);
+ let t0 = std::time::Instant::now();
+ s.execute("edit.presets.presetManager", json!({"action": "rename", "kind": "brushes", "name": "Brush 3", "newName": "Renamed"})).unwrap();
+ let rename = t0.elapsed();
+ eprintln!("500 sampled presets: {:.1} MB on disk; write {write:?}, load {load:?}, rename {rename:?}", bytes as f64 / 1e6);
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 6d63b2777..b4593b96e 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -174,6 +174,10 @@ pub struct Services {
pub append_text: Option<AppendTextFn>,
/// OS requests (macOS open-documents / quit Apple events), polled every frame.
pub os_events: Option<OsEventsFn>,
+ /// The persistent brush preset store, loading in the background (desktop; see
+ /// `photocraft_engine::preset_store`). Attached to the session once it arrives; without
+ /// one, brush presets are session-only (web, tests).
+ pub preset_store: Option<std::sync::mpsc::Receiver<photocraft_engine::preset_store::Opened>>,
}
pub struct PhotocraftApp {
diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs
index 61d2f2cb7..0bb95e5c6 100644
--- a/crates/ui-egui/src/prefs_ui.rs
+++ b/crates/ui-egui/src/prefs_ui.rs
@@ -121,6 +121,27 @@ pub fn load(app: &mut PhotocraftApp) {
}
}
+/// Attach the brush preset store once its background load finishes, and surface write
+/// failures in the status bar.
+fn presets_store(app: &mut PhotocraftApp) {
+ if let Some(rx) = &app.services.preset_store {
+ match rx.try_recv() {
+ Ok(opened) => {
+ app.services.preset_store = None;
+ let warnings = app.session.attach_preset_store(opened);
+ if let Some(w) = warnings.first() {
+ app.ui.status = if warnings.len() == 1 { w.clone() } else { format!("{w} (+{} more brush preset warnings)", warnings.len() - 1) };
+ }
+ }
+ Err(std::sync::mpsc::TryRecvError::Empty) => {}
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => app.services.preset_store = None,
+ }
+ }
+ if let Some(w) = app.session.preset_store.as_mut().map(|s| s.take_warnings()).and_then(|w| w.into_iter().next()) {
+ app.ui.status = w;
+ }
+}
+
/// Per-frame upkeep: theme sync, persistence, autosave and the history log.
pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) {
if !app.prefs_rt.loaded {
@@ -139,6 +160,7 @@ pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) {
app.session.prefs.edit(|p| p.interface.theme = t);
app.prefs_rt.theme_pref = Some(t);
}
+ presets_store(app);
if app.session.prefs.rev() != app.prefs_rt.saved_rev {
app.prefs_rt.saved_rev = app.session.prefs.rev();
let text = app.session.prefs_to_json();
@@ -1053,6 +1075,28 @@ mod tests {
assert!(store2.lock().unwrap().as_ref().unwrap().contains("classic"));
}
+ #[test]
+ fn brush_preset_store_attaches_when_loaded_and_persists() {
+ use photocraft_engine::preset_store::{MemBackend, open};
+ let mem = MemBackend::default();
+ let ctx = egui::Context::default();
+ let (tx, rx) = std::sync::mpsc::channel();
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { preset_store: Some(rx), ..Default::default() });
+ // Still loading: presets made now are kept and written once the store arrives.
+ tick(&mut app, &ctx);
+ app.run("brush.presets.save", json!({"name": "Early"})).unwrap();
+ assert!(mem.files.lock().unwrap().is_empty());
+ tx.send(open(Box::new(mem.clone()))).unwrap();
+ tick(&mut app, &ctx);
+ assert!(app.services.preset_store.is_none() && app.session.preset_store.is_some());
+ app.run("brush.presets.save", json!({"name": "Late"})).unwrap();
+ let mut s2 = photocraft_engine::Session::new();
+ assert!(s2.attach_preset_store(open(Box::new(mem))).is_empty());
+ for n in ["Early", "Late"] {
+ assert!(s2.tools.presets.iter().any(|p| p.name == n), "{n}");
+ }
+ }
+
#[test]
fn preferences_dialog_round_trip() {
let (mut app, _) = app_with_store();
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 2463fcba3..1a2dc8a60 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -102,6 +102,13 @@ The desktop app stores them in `preferences.json` in the platform config directo
`$XDG_CONFIG_HOME/photocraft`; override with `PHOTOCRAFT_CONFIG_DIR`); autosaves go to its
`Recovery` folder. The web build keeps them in `localStorage`.
+User and imported (`.abr`) brush presets live in the config directory's `Presets` folder: one
+`.pcbrushes` JSON file per preset group, content-addressed tip bitmaps under `tips/`, and an
+`index.json` with the group order and deleted built-ins (see `photocraft_engine::preset_store`).
+The store loads in the background at launch and syncs after every brush preset change; built-ins
+are never written. Headless CLI/MCP sessions and the web build keep brush presets for the session
+only. Gradient presets (including imported `.grd` groups) persist with the preferences.
+
## Snapping
With View › Snap on, tool gestures snap to the View › Snap To targets (guides and grid while they