Skip to main content

egui_pop_api/files/
groups.rs

1//! Grouped files: files that go together show as one entry of the in-app
2//! picker (a RAW with its sidecars, Lightroom's and digiKam's habit), and
3//! choosing it gives the main file, with the others beside it.
4//!
5//! egui-pop has the mechanism and no rule of its own: nothing groups until an
6//! application declares a [`FileGrouping`], with [`FilesPlugin::grouping`] or
7//! [`Groupings::register`]. A [`SidecarRule`] covers the usual case, by
8//! extension; a grouping of its own reads the names as it likes.
9//!
10//! ```
11//! use egui_pop_api::files::groups::{Groupings, SidecarRule};
12//! use std::path::Path;
13//! use std::sync::Arc;
14//!
15//! let photos = SidecarRule::new("my_app.photos", &["cr3", "nef"], &["xmp", "jpg"])
16//!     .badge("jpg", "JPEG");
17//! let groupings = Groupings::default();
18//! groupings.register(Arc::new(photos));
19//!
20//! let names = ["a.cr3", "a.cr3.xmp", "a.jpg", "b.jpg", "c.nef", "c.xmp"];
21//! let groups = groupings.in_folder(Path::new("/shoot"), &names);
22//! assert_eq!(groups[0].main, Path::new("/shoot/a.cr3"));
23//! assert_eq!(groups[0].badges, ["XMP", "JPEG"]);
24//! assert_eq!(groups[1].main, Path::new("/shoot/c.nef"));
25//! assert_eq!(groups.len(), 2, "b.jpg has no RAW: it stays a file of its own");
26//! ```
27//!
28//! [`FilesPlugin::grouping`]: super::FilesPlugin::grouping
29
30use std::collections::{HashMap, HashSet};
31use std::fmt;
32use std::panic::{AssertUnwindSafe, catch_unwind};
33use std::path::{Path, PathBuf};
34use std::sync::{Arc, Mutex};
35
36use egui_pop_core::lock;
37use serde_json::{Value as Json, json};
38
39use super::extension_dot;
40use super::fs::SharedFs;
41
42/// One group as a [`FileGrouping`] finds it, by the names of a folder's files.
43#[derive(Clone, Debug, Default, PartialEq, Eq)]
44pub struct NameGroup {
45    /// The file the entry stands for.
46    pub main: String,
47    /// The files that go with it.
48    pub members: Vec<String>,
49}
50
51/// Which of a folder's files go together: declared by the application, asked
52/// once per listing on the interface thread (the picker reads a folder there
53/// too), with names and nothing else, so that it reads no file.
54pub trait FileGrouping: fmt::Debug + Send + Sync {
55    /// Its id: registering another with this id replaces it.
56    fn id(&self) -> &str;
57
58    /// The groups among these names: the folder's files, without folders or
59    /// hidden files. What makes no sense is ignored, and the file stays an
60    /// entry of its own: a name that is not there, a member that is its own
61    /// main, or a file an earlier group or grouping took.
62    fn groups(&self, names: &[&str]) -> Vec<NameGroup>;
63
64    /// What the entry's badge says of a member (the picker adds the `+`): its
65    /// extension in capitals, by default.
66    fn badge(&self, member: &str) -> String {
67        extension_dot(member).map_or_else(String::new, |dot| member[dot + 1..].to_uppercase())
68    }
69}
70
71/// The usual grouping, by extension: `x.jpg`, `x.xmp` and `x.cr3.xmp` belong to
72/// `x.cr3`. The stem has to be the same, whatever the case of the extensions.
73///
74/// Main extensions come in the order they win: with `["cr3", "jpg"]`, `x.jpg`
75/// belongs to `x.cr3` when there is one and is a main of its own otherwise, for
76/// `x.xmp`. A sidecar goes to the first main that claims it, and members come
77/// in the order of `sidecars`.
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct SidecarRule {
80    id: String,
81    mains: Vec<String>,
82    sidecars: Vec<String>,
83    badges: Vec<(String, String)>,
84}
85
86impl SidecarRule {
87    /// Files with one of the `mains` extensions head a group of the files with
88    /// the same stem or the whole name before one of the `sidecars` extensions.
89    pub fn new(id: &str, mains: &[&str], sidecars: &[&str]) -> Self {
90        let lower = |list: &[&str]| list.iter().map(|e| e.to_lowercase()).collect();
91        Self {
92            id: id.into(),
93            mains: lower(mains),
94            sidecars: lower(sidecars),
95            badges: Vec::new(),
96        }
97    }
98
99    /// What the badge says of a sidecar with this extension, in place of the
100    /// extension in capitals: `.badge("jpg", "JPEG")`.
101    pub fn badge(mut self, extension: &str, badge: &str) -> Self {
102        self.badges.push((extension.to_lowercase(), badge.into()));
103        self
104    }
105}
106
107/// A name with its extension in lower case, as a [`SidecarRule`] compares them.
108fn folded(name: &str) -> String {
109    match extension_dot(name) {
110        Some(dot) => format!("{}{}", &name[..=dot], name[dot + 1..].to_lowercase()),
111        None => name.to_string(),
112    }
113}
114
115impl FileGrouping for SidecarRule {
116    fn id(&self) -> &str {
117        &self.id
118    }
119
120    fn groups(&self, names: &[&str]) -> Vec<NameGroup> {
121        let by_folded: HashMap<String, &str> = names.iter().map(|n| (folded(n), *n)).collect();
122        let mut taken: HashSet<&str> = HashSet::new();
123        let mut out = Vec::new();
124        for main_extension in &self.mains {
125            for name in names {
126                let Some(dot) = extension_dot(name) else {
127                    continue;
128                };
129                if name[dot + 1..].to_lowercase() != *main_extension || taken.contains(name) {
130                    continue;
131                }
132                let mut members = Vec::new();
133                for sidecar in &self.sidecars {
134                    for form in [
135                        format!("{}.{sidecar}", &name[..dot]),
136                        format!("{name}.{sidecar}"),
137                    ] {
138                        if let Some(member) = by_folded.get(&form)
139                            && member != name
140                            && taken.insert(member)
141                        {
142                            members.push((*member).to_string());
143                        }
144                    }
145                }
146                taken.insert(name);
147                if !members.is_empty() {
148                    out.push(NameGroup {
149                        main: (*name).to_string(),
150                        members,
151                    });
152                }
153            }
154        }
155        out
156    }
157
158    fn badge(&self, member: &str) -> String {
159        let Some(dot) = extension_dot(member) else {
160            return String::new();
161        };
162        let extension = &member[dot + 1..];
163        self.badges
164            .iter()
165            .find(|(e, _)| e.eq_ignore_ascii_case(extension))
166            .map_or_else(|| extension.to_uppercase(), |(_, badge)| badge.clone())
167    }
168}
169
170/// A group, as the picker shows it and as a choice gives it.
171#[derive(Clone, Debug, Default, PartialEq, Eq)]
172pub struct FileGroup {
173    /// The file the entry stands for: what choosing it gives.
174    pub main: PathBuf,
175    /// The files that go with it.
176    pub members: Vec<PathBuf>,
177    /// What the entry's badges say, each once, without the `+`.
178    pub badges: Vec<String>,
179}
180
181impl FileGroup {
182    /// The names of its members.
183    pub fn member_names(&self) -> Vec<String> {
184        self.members
185            .iter()
186            .filter_map(|m| m.file_name())
187            .map(|n| n.to_string_lossy().into_owned())
188            .collect()
189    }
190
191    fn to_json(&self) -> Json {
192        json!({
193            "main": self.main.display().to_string(),
194            "members": self.members.iter().map(|m| m.display().to_string()).collect::<Vec<_>>(),
195            "badges": self.badges,
196        })
197    }
198
199    fn from_json(json: &Json) -> Option<FileGroup> {
200        let strings = |key: &str| {
201            json.get(key)?
202                .as_array()
203                .map(|a| a.iter().filter_map(Json::as_str).map(String::from))
204                .map(Iterator::collect::<Vec<_>>)
205        };
206        Some(FileGroup {
207            main: PathBuf::from(json.get("main")?.as_str()?),
208            members: strings("members")?.into_iter().map(PathBuf::from).collect(),
209            badges: strings("badges").unwrap_or_default(),
210        })
211    }
212}
213
214/// Groups as a choice's result and the `file.chosen` step say them.
215pub(super) fn to_json(groups: &[FileGroup]) -> Json {
216    Json::Array(groups.iter().map(FileGroup::to_json).collect())
217}
218
219/// The groups a choice's result or the `file.chosen` step's arguments hold.
220pub(super) fn from_json(json: &Json) -> Vec<FileGroup> {
221    json.get("groups")
222        .and_then(Json::as_array)
223        .map(|a| a.iter().filter_map(FileGroup::from_json).collect())
224        .unwrap_or_default()
225}
226
227/// The groupings declared, as a service of [`Files`](super::Files).
228#[derive(Clone, Debug, Default)]
229pub struct Groupings(Arc<Mutex<Vec<Arc<dyn FileGrouping>>>>);
230
231impl Groupings {
232    /// Adds a grouping, or replaces the one with its id. Earlier ones win a
233    /// file both claim. Pickers open now take it at their next listing. A
234    /// plugin registering one takes it back in its `disconnect`.
235    pub fn register(&self, grouping: Arc<dyn FileGrouping>) {
236        let mut list = lock(&self.0);
237        list.retain(|g| g.id() != grouping.id());
238        list.push(grouping);
239    }
240
241    /// Takes a grouping away; says whether it was there.
242    pub fn unregister(&self, id: &str) -> bool {
243        let mut list = lock(&self.0);
244        let before = list.len();
245        list.retain(|g| g.id() != id);
246        list.len() != before
247    }
248
249    /// The ids of the groupings, in the order they apply.
250    pub fn ids(&self) -> Vec<String> {
251        lock(&self.0).iter().map(|g| g.id().to_string()).collect()
252    }
253
254    /// Whether none is declared: nothing groups.
255    pub fn is_empty(&self) -> bool {
256        lock(&self.0).is_empty()
257    }
258
259    /// The groups among the names of the files of a folder, from every
260    /// grouping. A grouping that panics counts for nothing, and the log says so.
261    pub fn in_folder(&self, dir: &Path, names: &[&str]) -> Vec<FileGroup> {
262        let list = lock(&self.0).clone();
263        let present: HashSet<&str> = names.iter().copied().collect();
264        let mut members_taken: HashSet<String> = HashSet::new();
265        let mut at: HashMap<String, usize> = HashMap::new();
266        let mut out: Vec<FileGroup> = Vec::new();
267        for grouping in list {
268            let found = catch_unwind(AssertUnwindSafe(|| grouping.groups(names)));
269            let Ok(found) = found else {
270                log::warn!(target: "egui_pop", "files: the grouping {} panicked", grouping.id());
271                continue;
272            };
273            for group in found {
274                if !present.contains(group.main.as_str()) || members_taken.contains(&group.main) {
275                    continue;
276                }
277                let members: Vec<String> = group
278                    .members
279                    .into_iter()
280                    .filter(|m| {
281                        present.contains(m.as_str())
282                            && *m != group.main
283                            && !at.contains_key(m)
284                            && !members_taken.contains(m)
285                    })
286                    .collect();
287                let mut kept = Vec::new();
288                for member in members {
289                    if members_taken.insert(member.clone()) {
290                        kept.push(member);
291                    }
292                }
293                if kept.is_empty() {
294                    continue;
295                }
296                let n = *at.entry(group.main.clone()).or_insert_with(|| {
297                    out.push(FileGroup {
298                        main: dir.join(&group.main),
299                        ..FileGroup::default()
300                    });
301                    out.len() - 1
302                });
303                for member in kept {
304                    let badge = grouping.badge(&member);
305                    if !badge.is_empty() && !out[n].badges.contains(&badge) {
306                        out[n].badges.push(badge);
307                    }
308                    out[n].members.push(dir.join(member));
309                }
310            }
311        }
312        out
313    }
314
315    /// The groups these paths head, each path's folder read once: what a choice
316    /// gives, whoever answered it. A path heading none has no group, and a path
317    /// that is a group's member is no more than that file.
318    pub fn of_paths(&self, fs: &SharedFs, paths: &[PathBuf]) -> Vec<FileGroup> {
319        if self.is_empty() {
320            return Vec::new();
321        }
322        let mut folders: HashMap<&Path, Vec<FileGroup>> = HashMap::new();
323        let mut out = Vec::new();
324        for path in paths {
325            let Some(dir) = path.parent() else {
326                continue;
327            };
328            let groups = folders.entry(dir).or_insert_with(|| {
329                let items = fs.read_dir(dir).unwrap_or_default();
330                let names: Vec<&str> = items
331                    .iter()
332                    .filter(|e| !e.is_dir && !e.name.starts_with('.'))
333                    .map(|e| e.name.as_str())
334                    .collect();
335                self.in_folder(dir, &names)
336            });
337            if let Some(group) = groups.iter().find(|g| g.main == *path)
338                && !out.contains(group)
339            {
340                out.push(group.clone());
341            }
342        }
343        out
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    /// As the rule gives them: main, then members.
352    fn found(rule: &SidecarRule, names: &[&str]) -> Vec<Vec<String>> {
353        rule.groups(names)
354            .into_iter()
355            .map(|g| {
356                let mut line = vec![g.main];
357                line.extend(g.members);
358                line
359            })
360            .collect()
361    }
362
363    fn photos() -> SidecarRule {
364        SidecarRule::new("photos", &["cr3", "nef"], &["xmp", "jpg"])
365    }
366
367    #[test]
368    fn a_rule_finds_both_forms_of_a_sidecar_and_the_same_stem_only() {
369        let names = [
370            "a.cr3",
371            "a.xmp",
372            "a.cr3.xmp",
373            "a.jpg",
374            "ab.xmp",
375            "a.b.cr3",
376            "a.b.xmp",
377            "lone.jpg",
378            "lone.xmp",
379            "x.txt",
380        ];
381        assert_eq!(
382            found(&photos(), &names),
383            [
384                vec!["a.cr3", "a.xmp", "a.cr3.xmp", "a.jpg"],
385                vec!["a.b.cr3", "a.b.xmp"],
386            ]
387        );
388    }
389
390    #[test]
391    fn extensions_match_in_any_case_and_stems_exactly() {
392        let names = ["IMG_1.CR3", "IMG_1.xmp", "IMG_1.CR3.XMP", "img_1.JPG"];
393        assert_eq!(
394            found(&photos(), &names),
395            [vec!["IMG_1.CR3", "IMG_1.xmp", "IMG_1.CR3.XMP"]]
396        );
397    }
398
399    #[test]
400    fn a_sidecar_goes_to_the_first_main_and_the_order_of_mains_wins() {
401        let names = ["a.nef", "a.cr3", "a.xmp", "a.nef.xmp"];
402        assert_eq!(
403            found(&photos(), &names),
404            [vec!["a.cr3", "a.xmp"], vec!["a.nef", "a.nef.xmp"]]
405        );
406        // A JPEG heads its own group only without its RAW.
407        let rule = SidecarRule::new("r", &["cr3", "jpg"], &["jpg", "xmp"]);
408        assert_eq!(
409            found(&rule, &["a.cr3", "a.jpg", "a.xmp", "b.jpg", "b.xmp"]),
410            [vec!["a.cr3", "a.jpg", "a.xmp"], vec!["b.jpg", "b.xmp"]]
411        );
412    }
413
414    #[test]
415    fn a_rule_says_its_badges() {
416        let rule = photos().badge("JPG", "JPEG");
417        assert_eq!(FileGrouping::badge(&rule, "a.jpg"), "JPEG");
418        assert_eq!(FileGrouping::badge(&rule, "a.JPG"), "JPEG");
419        assert_eq!(FileGrouping::badge(&rule, "a.cr3.xmp"), "XMP");
420        assert_eq!(FileGrouping::badge(&rule, "none"), "");
421    }
422
423    /// Gives what it is told, whatever the names.
424    #[derive(Debug)]
425    struct Fixed(&'static str, Vec<(&'static str, Vec<&'static str>)>);
426
427    impl FileGrouping for Fixed {
428        fn id(&self) -> &str {
429            self.0
430        }
431        fn groups(&self, _: &[&str]) -> Vec<NameGroup> {
432            self.1
433                .iter()
434                .map(|(main, members)| NameGroup {
435                    main: (*main).into(),
436                    members: members.iter().map(|m| (*m).into()).collect(),
437                })
438                .collect()
439        }
440    }
441
442    #[derive(Debug)]
443    struct Panics;
444
445    impl FileGrouping for Panics {
446        fn id(&self) -> &str {
447            "panics"
448        }
449        fn groups(&self, _: &[&str]) -> Vec<NameGroup> {
450            panic!("this grouping cannot read");
451        }
452    }
453
454    fn in_d(groupings: &Groupings, names: &[&str]) -> Vec<(String, Vec<String>)> {
455        groupings
456            .in_folder(Path::new("/d"), names)
457            .into_iter()
458            .map(|g| {
459                let main = g.main.file_name().unwrap().to_string_lossy().into_owned();
460                (main, g.member_names())
461            })
462            .collect()
463    }
464
465    #[test]
466    fn what_makes_no_sense_stays_a_file_of_its_own() {
467        let g = Groupings::default();
468        g.register(Arc::new(Fixed(
469            "odd",
470            vec![
471                ("gone", vec!["b"]),
472                ("a", vec!["a", "gone", "b"]),
473                ("c", vec!["b"]),
474                ("b", vec!["c"]),
475            ],
476        )));
477        assert_eq!(in_d(&g, &["a", "b", "c"]), [("a".into(), vec!["b".into()])]);
478    }
479
480    #[test]
481    fn earlier_groupings_win_and_a_main_gathers_what_later_ones_add() {
482        let g = Groupings::default();
483        g.register(Arc::new(Fixed("one", vec![("a", vec!["b"])])));
484        g.register(Arc::new(Fixed(
485            "two",
486            vec![("c", vec!["b", "a"]), ("a", vec!["d"]), ("b", vec!["e"])],
487        )));
488        assert_eq!(
489            in_d(&g, &["a", "b", "c", "d", "e"]),
490            [("a".into(), vec!["b".into(), "d".into()])]
491        );
492    }
493
494    #[test]
495    fn a_grouping_that_panics_counts_for_nothing() {
496        let g = Groupings::default();
497        g.register(Arc::new(Panics));
498        g.register(Arc::new(Fixed("fine", vec![("a", vec!["b"])])));
499        assert_eq!(in_d(&g, &["a", "b"]), [("a".into(), vec!["b".into()])]);
500    }
501
502    #[test]
503    fn the_same_id_replaces_and_unregistering_takes_it_away() {
504        let g = Groupings::default();
505        assert!(g.is_empty());
506        g.register(Arc::new(Fixed("one", vec![("a", vec!["b"])])));
507        g.register(Arc::new(Fixed("one", vec![("b", vec!["a"])])));
508        assert_eq!(g.ids(), ["one"]);
509        assert_eq!(in_d(&g, &["a", "b"]), [("b".into(), vec!["a".into()])]);
510        assert!(g.unregister("one"));
511        assert!(!g.unregister("one"));
512        assert!(in_d(&g, &["a", "b"]).is_empty());
513    }
514
515    #[test]
516    fn badges_say_each_thing_once() {
517        let g = Groupings::default();
518        g.register(Arc::new(photos().badge("jpg", "JPEG")));
519        let groups = g.in_folder(Path::new("/d"), &["a.cr3", "a.xmp", "a.cr3.xmp", "a.jpg"]);
520        assert_eq!(groups[0].badges, ["XMP", "JPEG"]);
521        assert_eq!(from_json(&json!({ "groups": to_json(&groups) })), groups);
522        assert!(from_json(&json!({ "paths": [] })).is_empty());
523    }
524}