Skip to content

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

Brushes: drag a brush folder into another folder (#2014) (#3851)

David Mann6231325aeadb
diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs
index 614127f29..03b281433 100644
--- a/crates/engine/src/brush_preset_cmds.rs
+++ b/crates/engine/src/brush_preset_cmds.rs
@@ -4,7 +4,9 @@
//! Groups are the panel's top-level folders ([`BrushPreset::group`]); a group can hold nested
//! folders ([`BrushPreset::folder`], a path inside the group, e.g. the folders of an imported
//! `.abr` file). The group commands take an optional `folder` path to act on a nested folder
-//! instead of the whole group. A folder exists while a preset is in it (or below it).
+//! instead of the whole group, and `moveGroup` can move a group or folder `into` another folder
+//! or group, or out to the top level (dragging a folder onto a folder in Photoshop's panel). A
+//! folder exists while a preset is in it (or below it).
//!
//! The library order is the panel order: groups appear in order of their first preset, and a
//! group's folders and presets in order of their first preset too. Every
@@ -247,9 +249,116 @@ fn move_folder(s: &mut Session, p: &Value, g: String, f: Vec<String>, cmd: &str)
Ok(json!({ "group": g, "folder": f, "index": at }))
}
+/// Where `into` puts a folder: `Some(None)` = the top level (it becomes a group), `Some(Some((group,
+/// folder)))` = inside that folder of that group (`[]`: directly in the group). `None` without `into`.
+type Dest = Option<(String, Vec<String>)>;
+
+fn into_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Dest>> {
+ let into = match p.get("into") {
+ None | Some(Value::Null) => return Ok(None),
+ Some(v @ Value::Object(_)) => v,
+ Some(_) => return Err(bad(cmd, "`into` must be an object {group?, folder?}")),
+ };
+ let Some(g) = group_param(into, "group", cmd)? else {
+ if folder_param(into, cmd)?.is_some_and(|f| !f.is_empty()) {
+ return Err(bad(cmd, "`into.folder` needs `into.group`"));
+ }
+ return Ok(Some(None));
+ };
+ group_block(s, &g, cmd)?;
+ let f = folder_param(into, cmd)?.unwrap_or_default();
+ if !s.tools.presets.iter().any(|x| in_folder(x, &g, &f)) {
+ return Err(bad(cmd, format!("no folder `{}` in brush preset group `{g}`", f.join("/"))));
+ }
+ Ok(Some(Some((g, f))))
+}
+
+/// Move folder `f` of group `g` (the whole group when `f` is empty) into `dest`, keeping its
+/// content and the order of its presets: Photoshop's drag of a folder onto another folder. It
+/// lands at the end of the destination, or before the sibling folder (group at the top level)
+/// named by `before`.
+fn move_into(s: &mut Session, p: &Value, g: String, f: Vec<String>, dest: Dest, cmd: &str) -> Result<Value> {
+ if p.get("index").is_some_and(|v| !v.is_null()) {
+ return Err(bad(cmd, "`index` can't be combined with `into` (use `before`)"));
+ }
+ let leaf = match f.last() {
+ Some(l) => l.clone(),
+ None if g.is_empty() => return Err(bad(cmd, "the ungrouped presets are not a folder that can be moved")),
+ None => g.clone(),
+ };
+ let moving = |x: &BrushPreset| in_folder(x, &g, &f);
+ let rest_of = |x: &BrushPreset| x.folder.get(f.len()..).unwrap_or_default().to_vec();
+ let before = match p.get("before") {
+ None | Some(Value::Null) => None,
+ Some(Value::String(b)) => Some(b.trim().to_string()),
+ Some(_) => return Err(bad(cmd, "`before` must be a folder name")),
+ };
+ // The destination's own folders and groups, without the one being moved.
+ let others: Vec<BrushPreset> = s.tools.presets.iter().filter(|x| !moving(x)).cloned().collect();
+ let (new_group, new_prefix, siblings) = match &dest {
+ None => {
+ if f.is_empty() {
+ return Err(bad(cmd, "`into`: the group is already at the top level"));
+ }
+ (leaf.clone(), Vec::new(), group_order(&others))
+ }
+ Some((dg, df)) => {
+ if *dg == g && df.starts_with(&f) {
+ return Err(bad(cmd, "`into` names the folder being moved or one of its own folders"));
+ }
+ let mut prefix = df.clone();
+ prefix.push(leaf.clone());
+ (dg.clone(), prefix, subfolder_order(&others, dg, df))
+ }
+ };
+ if siblings.contains(&leaf) {
+ return Err(bad(cmd, format!("a folder named `{leaf}` already exists there")));
+ }
+ if let Some(b) = &before
+ && !siblings.contains(b)
+ {
+ return Err(bad(cmd, format!("`before`: no folder named `{b}` there")));
+ }
+ let deepest = s.tools.presets.iter().filter(|x| moving(x)).map(|x| new_prefix.len() + rest_of(x).len()).max().unwrap_or(0);
+ if deepest > MAX_FOLDER_DEPTH {
+ return Err(bad(cmd, format!("folders can be nested at most {MAX_FOLDER_DEPTH} deep")));
+ }
+ let lib = std::mem::take(&mut s.tools.presets);
+ let (mut block, mut rest): (Vec<BrushPreset>, Vec<BrushPreset>) = lib.into_iter().partition(|x| in_folder(x, &g, &f));
+ for x in &mut block {
+ let tail = rest_of(x);
+ x.group.clone_from(&new_group);
+ x.folder = new_prefix.iter().cloned().chain(tail).collect();
+ x.builtin = false;
+ }
+ let pos = match (&dest, &before) {
+ (None, Some(b)) => rest.iter().position(|x| x.group == *b),
+ (None, None) => None,
+ (Some((dg, df)), Some(b)) => {
+ let sib: Vec<String> = df.iter().cloned().chain(std::iter::once(b.clone())).collect();
+ rest.iter().position(|x| in_folder(x, dg, &sib))
+ }
+ (Some((dg, df)), None) => rest.iter().rposition(|x| in_folder(x, dg, df)).map(|k| k + 1),
+ };
+ let tail = rest.split_off(pos.unwrap_or(rest.len()).min(rest.len()));
+ rest.extend(block);
+ rest.extend(tail);
+ s.tools.presets = rest;
+ s.brush_presets_changed();
+ let folder = new_prefix.get(..new_prefix.len().saturating_sub(1)).unwrap_or_default();
+ let at = match &dest {
+ None => group_order(&s.tools.presets).iter().position(|x| *x == new_group),
+ Some(_) => subfolder_order(&s.tools.presets, &new_group, folder).iter().position(|x| *x == leaf),
+ };
+ Ok(json!({ "group": new_group, "folder": new_prefix, "index": at.unwrap_or(0) }))
+}
+
fn move_group(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "brush.presets.moveGroup";
let (g, f) = target_folder(s, p, cmd)?;
+ if let Some(dest) = into_param(s, p, cmd)? {
+ return move_into(s, p, g, f, dest, cmd);
+ }
if !f.is_empty() {
return move_folder(s, p, g, f, cmd);
}
@@ -348,7 +457,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"brush.presets.moveGroup",
"Move Brush Group",
- r##"{"group":string,"folder":[name]? (move this nested folder among its sibling folders instead),"before":group? (or sibling folder name) | "index":n? (group or sibling folder position)=end} → {group, folder?, index}"##,
+ r##"{"group":string,"folder":[name]? (move this nested folder instead),"into":{"group":string?,"folder":[name]?}? (move it inside that folder of that group, [] = directly in the group; no group = out to the top level as a group of its own; the folder keeps its content),"before":group? (or sibling folder name, in its new place with `into`) | "index":n? (group or sibling folder position, without `into`)=end} → {group, folder?, index}"##,
move_group
),
spec!(
@@ -572,4 +681,84 @@ mod tests {
assert_eq!(s.tools.presets, before);
s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "index": u64::MAX})).unwrap();
}
+
+ fn paths(s: &Session) -> Vec<String> {
+ s.tools.presets.iter().filter(|x| !x.builtin).map(|x| format!("{}:{}:{}", x.group, x.folder.join("/"), x.name)).collect()
+ }
+
+ /// `with_folders` plus group "Other" holding O1, and folder Box (B1) in it.
+ fn with_two_groups() -> Session {
+ let mut s = with_folders();
+ for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] {
+ let folder = f.iter().map(|x| x.to_string()).collect();
+ s.tools.presets.push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, group: "Other".into(), folder });
+ }
+ s
+ }
+
+ #[test]
+ fn folders_move_into_folders_and_groups() {
+ let mut s = with_two_groups();
+ // A nested folder into a sibling folder: its subtree follows, order kept.
+ let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}})).unwrap();
+ assert_eq!(r, json!({"group": "Set", "folder": ["Ink", "Fine", "Dry"], "index": 0}));
+ assert_eq!(folder_of(&s, "D1"), ["Ink", "Fine", "Dry"]);
+ // Into another group, before one of its folders.
+ let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Other"}, "before": "Box"})).unwrap();
+ assert_eq!(r["folder"], json!(["Ink"]));
+ assert_eq!(paths(&s), ["Set::S0", "Other::O1", "Other:Ink:I1", "Other:Ink/Fine:F1", "Other:Ink/Fine/Dry:D1", "Other:Ink:I2", "Other:Box:B1"]);
+ // Out to the top level: the folder becomes a group of its own.
+ let r = s.execute("brush.presets.moveGroup", json!({"group": "Other", "folder": ["Ink", "Fine"], "into": {}})).unwrap();
+ assert_eq!(r["group"], "Fine");
+ assert_eq!(folder_of(&s, "D1"), ["Dry"]);
+ assert_eq!(photocraft_paint::presets::find(&s.tools.presets, "F1").unwrap().group, "Fine");
+ // A whole group into another group's folder.
+ s.execute("brush.presets.moveGroup", json!({"group": "Fine", "into": {"group": "Set"}})).unwrap();
+ assert!(names(&s, "Fine").is_empty());
+ assert_eq!(folder_of(&s, "D1"), ["Fine", "Dry"]);
+ assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Fine"]);
+ }
+
+ #[test]
+ fn bad_moves_into_folders_fail_without_changes() {
+ let mut s = with_two_groups();
+ // A chain 31 deep under Set/Deep.
+ let deep: Vec<String> = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect();
+ s.tools.presets.push(BrushPreset { name: "Z".into(), brush: Default::default(), builtin: false, group: "Set".into(), folder: deep.clone() });
+ s.tools.presets.push(BrushPreset { name: "Y".into(), brush: Default::default(), builtin: false, group: "Other".into(), folder: vec!["Dry".into()] });
+ let before = s.tools.presets.clone();
+ let deep_json = json!(deep);
+ for p in [
+ // Into itself or its own descendant.
+ json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink"]}}),
+ json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}),
+ json!({"group": "Set", "into": {"group": "Set", "folder": ["Dry"]}}),
+ json!({"group": "Set", "into": {"group": "Set"}}),
+ // A group already at the top level; the ungrouped presets.
+ json!({"group": "Set", "into": {}}),
+ // A name clash at the destination.
+ json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}}),
+ json!({"group": "Other", "folder": ["Box"], "into": {"group": "Set", "folder": ["Ink"]}, "before": "Nope"}),
+ json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink"]}, "index": 0}),
+ // Missing destinations and bad shapes.
+ json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Nope"}}),
+ json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other", "folder": ["Nope"]}}),
+ json!({"group": "Set", "folder": ["Dry"], "into": {"folder": ["Box"]}}),
+ json!({"group": "Set", "folder": ["Dry"], "into": "Other"}),
+ json!({"group": "Set", "folder": ["Dry"], "into": {"group": 5}}),
+ json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}, "before": 3}),
+ // Deeper than MAX_FOLDER_DEPTH once moved (Ink/Fine is 2 deep: 2 + 31 > 32).
+ json!({"group": "Set", "folder": ["Deep"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}),
+ json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": deep_json}}),
+ ] {
+ assert!(s.execute("brush.presets.moveGroup", p.clone()).is_err(), "{p}");
+ }
+ assert_eq!(s.tools.presets, before);
+ // Ink/Fine into Set itself: a clash with nothing, so it moves up a level.
+ s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap();
+ assert_eq!(folder_of(&s, "F1"), ["Fine"]);
+ // An ungrouped preset's group can't move.
+ s.tools.presets.push(BrushPreset { name: "U".into(), brush: Default::default(), builtin: false, group: String::new(), folder: Vec::new() });
+ assert!(s.execute("brush.presets.moveGroup", json!({"group": "", "into": {"group": "Set"}})).is_err());
+ }
}
diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs
index b7f175867..513bc56c1 100644
--- a/crates/engine/src/preset_store/tests.rs
+++ b/crates/engine/src/preset_store/tests.rs
@@ -624,6 +624,40 @@ fn imported_abr_folders_persist_and_old_stores_load_flat() {
assert!(photocraft_paint::presets::find(&d.tools.presets, "Blank").unwrap().folder.is_empty());
}
+/// Moving a group into another group's folder rewrites the target group's file and removes the
+/// moved group's; moving a folder out to the top level makes a group file for it (#2014).
+#[test]
+fn folders_moved_into_other_folders_persist() {
+ let dir = TempDir::new("folder-into");
+ let (mut s, _) = session(&dir);
+ let set = abr_with_folders(&[("Kit Loose", &[]), ("Kit Pen", &["Inks"]), ("Kit Nib", &["Inks", "Fine"])]);
+ let other = abr_with_folders(&[("Pack Chalk", &["Dry"])]);
+ s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&set), "group": "Kit"})).unwrap();
+ s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&other), "group": "Pack"})).unwrap();
+ let group_files = |d: &TempDir| -> Vec<String> { d.files().into_iter().filter(|f| f.ends_with(".pcbrushes")).collect() };
+ let mut both = vec![group_file_name("Kit"), group_file_name("Pack")];
+ both.sort();
+ assert_eq!(group_files(&dir), both);
+ s.execute("brush.presets.moveGroup", json!({"group": "Pack", "into": {"group": "Kit", "folder": ["Inks"]}})).unwrap();
+ assert_eq!(group_files(&dir), [group_file_name("Kit")]);
+ let (t, w) = session(&dir);
+ assert!(w.is_empty(), "{w:?}");
+ assert_eq!(user(&t), user(&s));
+ let folder = |s: &Session, n: &str| {
+ let p = photocraft_paint::presets::find(&s.tools.presets, n).unwrap();
+ format!("{}:{}", p.group, p.folder.join("/"))
+ };
+ assert_eq!(folder(&t, "Pack Chalk"), "Kit:Inks/Pack/Dry");
+ // Out to the top level: a group (and file) of its own.
+ s.execute("brush.presets.moveGroup", json!({"group": "Kit", "folder": ["Inks", "Pack"], "into": {}})).unwrap();
+ let mut both = vec![group_file_name("Kit"), group_file_name("Pack")];
+ both.sort();
+ assert_eq!(group_files(&dir), both);
+ let (t, _) = session(&dir);
+ assert_eq!(folder(&t, "Pack Chalk"), "Pack:Dry");
+ assert_eq!(folder(&t, "Kit Nib"), "Kit:Inks/Fine");
+}
+
#[test]
fn a_group_file_that_failed_to_load_is_not_overwritten() {
// e.g. written by a newer PhotoCraft: skipped on load, so a save must not replace it.
diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel_tests.rs
index c61b48c1b..7d5a51e4f 100644
--- a/crates/ui-egui/src/brush_panel_tests.rs
+++ b/crates/ui-egui/src/brush_panel_tests.rs
@@ -635,6 +635,90 @@ fn folder_actions_become_folder_commands() {
assert_eq!(last_journal(&app).unwrap(), ("brush.presets.moveGroup".to_string(), json!({ "group": "Kit", "folder": ["Dry"], "before": "Inks" })));
}
+/// Dragging a folder or group header onto another header (#2014): the upper edge places it
+/// before, the rest puts it inside; the action runs `brush.presets.moveGroup` with `into`.
+#[test]
+fn folder_drops_map_to_move_commands() {
+ use crate::brushes_tab::{Action, apply, folder_drop};
+ let v = |p: &[&str]| p.iter().map(|s| s.to_string()).collect::<Vec<String>>();
+ // Into: a folder onto another folder, a group onto a group.
+ assert_eq!(
+ folder_drop("Kit", &v(&["Dry"]), "Kit", &v(&["Inks"]), false),
+ Some(Action::MoveInto { group: "Kit".into(), folder: v(&["Dry"]), into: Some(("Kit".into(), v(&["Inks"]))), before: None })
+ );
+ assert_eq!(
+ folder_drop("Pack", &[], "Kit", &v(&["Inks"]), false),
+ Some(Action::MoveInto { group: "Pack".into(), folder: vec![], into: Some(("Kit".into(), v(&["Inks"]))), before: None })
+ );
+ // Onto itself, into its own folder, or into the folder it is already in: nothing.
+ assert_eq!(folder_drop("Kit", &v(&["Inks"]), "Kit", &v(&["Inks"]), false), None);
+ assert_eq!(folder_drop("Kit", &v(&["Inks"]), "Kit", &v(&["Inks", "Fine"]), true), None);
+ assert_eq!(folder_drop("Kit", &[], "Kit", &v(&["Inks"]), false), None);
+ assert_eq!(folder_drop("Kit", &v(&["Inks", "Fine"]), "Kit", &v(&["Inks"]), false), None);
+ // Upper edge: siblings reorder; a nested folder before a group goes to the top level; a
+ // folder before a folder elsewhere moves next to it.
+ assert_eq!(
+ folder_drop("Kit", &v(&["Dry"]), "Kit", &v(&["Inks"]), true),
+ Some(Action::MoveGroup { group: "Kit".into(), folder: v(&["Dry"]), before: Some("Inks".into()) })
+ );
+ assert_eq!(folder_drop("Pack", &[], "Kit", &[], true), Some(Action::MoveGroup { group: "Pack".into(), folder: vec![], before: Some("Kit".into()) }));
+ assert_eq!(
+ folder_drop("Kit", &v(&["Inks", "Fine"]), "Pack", &[], true),
+ Some(Action::MoveInto { group: "Kit".into(), folder: v(&["Inks", "Fine"]), into: None, before: Some("Pack".into()) })
+ );
+ assert_eq!(
+ folder_drop("Kit", &v(&["Inks", "Fine"]), "Pack", &v(&["Box"]), true),
+ Some(Action::MoveInto { group: "Kit".into(), folder: v(&["Inks", "Fine"]), into: Some(("Pack".into(), vec![])), before: Some("Box".into()) })
+ );
+
+ let mut app = app();
+ for p in [kit("Kit Pen", &["Inks"]), kit("Kit Nib", &["Inks", "Fine"]), kit("Kit Chalk", &["Dry"])] {
+ app.session.tools.presets.push(p);
+ }
+ let into = folder_drop("Kit", &v(&["Dry"]), "Kit", &v(&["Inks", "Fine"]), false).unwrap();
+ apply(&mut app, vec![into]);
+ assert_eq!(paint::presets::find(&app.session.tools.presets, "Kit Chalk").unwrap().folder, ["Inks", "Fine", "Dry"]);
+ assert_eq!(
+ last_journal(&app).unwrap(),
+ ("brush.presets.moveGroup".to_string(), json!({ "group": "Kit", "folder": ["Dry"], "into": {"group": "Kit", "folder": ["Inks", "Fine"]} }))
+ );
+ // Out to the top level, before a group.
+ let out = folder_drop("Kit", &v(&["Inks", "Fine"]), "Kit", &[], true).unwrap();
+ apply(&mut app, vec![out]);
+ let chalk = paint::presets::find(&app.session.tools.presets, "Kit Chalk").unwrap();
+ assert_eq!((chalk.group.as_str(), chalk.folder.clone()), ("Fine", v(&["Dry"])));
+ let order = photocraft_engine::brush_preset_cmds::group_order(&app.session.tools.presets);
+ assert!(order.iter().position(|g| g == "Fine") < order.iter().position(|g| g == "Kit"));
+}
+
+/// A folder header dragged onto another folder's header in the Brushes panel goes inside it.
+#[test]
+fn dragging_a_folder_header_onto_another_moves_it_inside() {
+ use egui_kittest::kittest::Queryable;
+ let mut h = harness(1, 0);
+ let builtin_groups: Vec<String> = grouped_presets(&h.state().session.tools.presets).into_iter().map(|(g, _)| g).collect();
+ h.state_mut().ui.brushes_panel.collapsed = builtin_groups;
+ for p in [kit("Kit Pen", &["Test Inks"]), kit("Kit Chalk", &["Test Dry"])] {
+ h.state_mut().session.tools.presets.push(p);
+ }
+ h.run_steps(3);
+ let from = h.get_by_label("Test Dry").rect().center();
+ let to = h.get_by_label("Test Inks").rect();
+ let to = egui::pos2(to.center().x, to.top() + to.height() * 0.7);
+ h.hover_at(from);
+ h.run();
+ h.drag_at(from);
+ h.run();
+ for k in 1..=6 {
+ h.hover_at(from + (to - from) * (k as f32 / 6.0));
+ h.run();
+ }
+ h.drop_at(to);
+ h.run_steps(3);
+ assert_eq!(paint::presets::find(&h.state().session.tools.presets, "Kit Chalk").unwrap().folder, ["Test Inks", "Test Dry"]);
+ assert_eq!(last_journal(h.state()).unwrap().0, "brush.presets.moveGroup");
+}
+
/// A fresh session with the Brush tool: shortcuts, the options bar and the Brush Settings window,
/// in the default theme (#258).
fn app_harness() -> Harness<'static, PhotocraftApp> {
diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rs
index b6d96f6bd..31c1161b9 100644
--- a/crates/ui-egui/src/brushes_tab.rs
+++ b/crates/ui-egui/src/brushes_tab.rs
@@ -2,9 +2,10 @@
//! preview, name) or a grid of tips, with a size slider and a search field.
//!
//! Presets and groups are organised like Photoshop's panel: drag a preset within its group or
-//! into another group or folder (onto a preset, or onto a header to append), drag a group's
-//! header to reorder groups (a nested folder's header to reorder it among its sibling folders),
-//! and right-click for Rename and Delete. Groups hold nested folders ([`BrushPreset::folder`],
+//! into another group or folder (onto a preset, or onto a header to append), drag a group's or
+//! folder's header onto another header to put it inside that folder (or onto the header's upper
+//! edge to place it before, which reorders siblings and moves a folder out to the top level), and
+//! right-click for Rename and Delete. Groups hold nested folders ([`BrushPreset::folder`],
//! e.g. an imported `.abr` file's own folders), drawn indented under their group and opened or
//! closed like groups. Every change is a `brush.presets.*` command, so it is journaled, drivable,
//! and persisted by the preset store.
@@ -59,6 +60,15 @@ pub enum Action {
folder: Vec<String>,
before: Option<String>,
},
+ /// Move a group (`folder` empty) or nested folder into another folder: `into` is (group,
+ /// folder path, `[]` = directly in the group), or `None` for the top level (it becomes a
+ /// group). `before` is a folder (or top-level group) there to land before.
+ MoveInto {
+ group: String,
+ folder: Vec<String>,
+ into: Option<(String, Vec<String>)>,
+ before: Option<String>,
+ },
/// View only: show the rename bar for a preset or group ([`preset_list`] applies it).
BeginRename(Renaming),
/// Commit a rename typed in the rename bar.
@@ -238,6 +248,20 @@ pub fn apply(app: &mut PhotocraftApp, acts: Vec<Action>) {
}
run_or_status(app, "brush.presets.moveGroup", p);
}
+ Action::MoveInto { group, folder, into, before } => {
+ let into = match into {
+ Some((g, f)) => json!({ "group": g, "folder": f }),
+ None => json!({}),
+ };
+ let mut p = json!({ "group": group, "into": into });
+ if !folder.is_empty() {
+ p["folder"] = json!(folder);
+ }
+ if let Some(b) = before {
+ p["before"] = json!(b);
+ }
+ run_or_status(app, "brush.presets.moveGroup", p);
+ }
Action::Rename(r) => {
let text = r.text.trim().to_string();
let old = r.folder.last().unwrap_or(&r.name);
@@ -582,9 +606,41 @@ fn preset_card(
/// Indent of one nested folder level.
const FOLDER_INDENT: f32 = 16.0;
-/// A group's or nested folder's header: chevron, folder, name, count. Click toggles; drag
-/// reorders groups (a folder among its sibling folders); a preset dropped here moves to the end of
-/// the group or folder. `key` is the group key, `folder` the nested folder's path (empty for the
+/// What dropping the group or folder (`src_group`, `src_folder`; a group when `src_folder` is
+/// empty) on the header of (`group`, `folder`) does, as in Photoshop's Brushes panel: on the
+/// header's upper edge (`edge`) it lands before that folder, next to it (reordering when they are
+/// siblings); anywhere else it goes into that folder. `None` when the drop does nothing: onto
+/// itself, into one of its own folders, or into the folder it is already in.
+pub fn folder_drop(src_group: &str, src_folder: &[String], group: &str, folder: &[String], edge: bool) -> Option<Action> {
+ if src_group == group && folder.starts_with(src_folder) {
+ return None;
+ }
+ let src = (src_group.to_string(), src_folder.to_vec());
+ if !edge {
+ let parent = src_folder.split_last().map(|(_, p)| p);
+ if src_group == group && parent == Some(folder) {
+ return None;
+ }
+ return Some(Action::MoveInto { group: src.0, folder: src.1, into: Some((group.to_string(), folder.to_vec())), before: None });
+ }
+ match folder.split_last() {
+ // Before a top-level group: groups reorder; a nested folder moves out to the top level.
+ None if src_folder.is_empty() => Some(Action::MoveGroup { group: src.0, folder: src.1, before: Some(group.to_string()) }),
+ None => Some(Action::MoveInto { group: src.0, folder: src.1, into: None, before: Some(group.to_string()) }),
+ Some((leaf, parent)) => {
+ let sibling = src_group == group && src_folder.split_last().map(|(_, p)| p) == Some(parent);
+ if sibling {
+ Some(Action::MoveGroup { group: src.0, folder: src.1, before: Some(leaf.clone()) })
+ } else {
+ Some(Action::MoveInto { group: src.0, folder: src.1, into: Some((group.to_string(), parent.to_vec())), before: Some(leaf.clone()) })
+ }
+ }
+ }
+}
+
+/// A group's or nested folder's header: chevron, folder, name, count. Click toggles; a group or
+/// folder dragged here lands before it (its upper edge) or goes into it ([`folder_drop`]); a
+/// preset dropped here moves to the end of the group or folder. `key` is the group key, `folder` the nested folder's path (empty for the
/// group), `label` the group's panel label.
fn group_header(ui: &mut egui::Ui, label: &str, key: &str, folder: &[String], open: bool, count: usize, acts: &mut Vec<Action>) {
let t = Tokens::get(ui.ctx());
@@ -616,31 +672,27 @@ fn group_header(ui: &mut egui::Ui, label: &str, key: &str, folder: &[String], op
[] => BrushDrag::Group(key.to_string()),
f => BrushDrag::Folder { group: key.to_string(), folder: f.to_vec() },
};
- // A folder moves among its siblings: same group, same parent, not itself.
- let sibling = |g: &str, f: &[String]| {
- g == key && !folder.is_empty() && f.len() == folder.len() && f != folder && f.split_last().map(|x| x.1) == folder.split_last().map(|x| x.1)
- };
resp.dnd_set_drag_payload(me);
+ // The upper third of the header places a dragged folder before this one; the rest drops it in.
+ let edge = ui.ctx().pointer_interact_pos().is_some_and(|p| p.y < r.top() + r.height() / 3.0);
+ let folder_action = |d: &BrushDrag| match d {
+ BrushDrag::Group(g) => folder_drop(g, &[], key, folder, edge),
+ BrushDrag::Folder { group, folder: f } => folder_drop(group, f, key, folder, edge),
+ BrushDrag::Preset(_) => None,
+ };
if let Some(d) = resp.dnd_hover_payload::<BrushDrag>() {
- match &*d {
- BrushDrag::Group(g) if folder.is_empty() && g != key => widgets::drop_line(ui, r, false, false, &t),
- BrushDrag::Folder { group, folder: f } if sibling(group, f) => widgets::drop_line(ui, r, false, false, &t),
- BrushDrag::Preset(_) => {
+ match (&*d, folder_action(&d)) {
+ (BrushDrag::Preset(_), _) | (_, Some(Action::MoveInto { before: None, .. })) => {
ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside);
}
+ (_, Some(_)) => widgets::drop_line(ui, r, false, false, &t),
_ => {}
}
}
if let Some(d) = resp.dnd_release_payload::<BrushDrag>() {
match &*d {
- BrushDrag::Group(g) if folder.is_empty() && g != key => {
- acts.push(Action::MoveGroup { group: g.clone(), folder: Vec::new(), before: Some(key.to_string()) })
- }
- BrushDrag::Folder { group, folder: f } if sibling(group, f) => {
- acts.push(Action::MoveGroup { group: group.clone(), folder: f.clone(), before: Some(shown.to_string()) })
- }
BrushDrag::Preset(n) => acts.push(Action::Move { name: n.clone(), group: key.to_string(), folder: Some(folder.to_vec()), index: None }),
- _ => {}
+ other => acts.extend(folder_action(other)),
}
}
if resp.clicked() {