Skip to main content

egui_pop_api/files/
sort.rs

1//! The order of the in-app picker's entries: by which column, up or down,
2//! folders first or among the files, names read naturally.
3//!
4//! ```
5//! use std::cmp::Ordering;
6//! use egui_pop_api::files::sort::{PickerSort, SortColumn, natural_cmp};
7//!
8//! assert_eq!(natural_cmp("IMG_9.cr3", "IMG_10.cr3"), Ordering::Less);
9//! let newest = PickerSort::default().click(SortColumn::Modified);
10//! assert_eq!(newest.as_text(), "-modified");
11//! assert_eq!(PickerSort::parse("-modified"), Some(newest));
12//! ```
13
14use std::cmp::Ordering;
15use std::time::SystemTime;
16
17use super::extension_dot;
18#[cfg(test)]
19use super::{Entry, fs::Meta};
20
21/// What the picker's and the file browser's entries are sorted by.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
23#[non_exhaustive]
24pub enum SortColumn {
25    /// The name, read naturally ([`natural_cmp`]).
26    #[default]
27    Name,
28    /// A file's size in bytes.
29    Size,
30    /// When it last changed.
31    Modified,
32    /// A file's extension.
33    Type,
34    /// When a photo was taken, as an application's source says
35    /// ([`SourceEntry::taken`](super::browser::SourceEntry::taken)); the
36    /// time it last changed when the source does not say.
37    Taken,
38}
39
40impl SortColumn {
41    /// Its name in the store and to agents.
42    pub fn as_str(self) -> &'static str {
43        match self {
44            SortColumn::Name => "name",
45            SortColumn::Size => "size",
46            SortColumn::Modified => "modified",
47            SortColumn::Type => "type",
48            SortColumn::Taken => "taken",
49        }
50    }
51
52    /// The column of a name in the store.
53    pub fn parse(name: &str) -> Option<SortColumn> {
54        match name {
55            "name" => Some(SortColumn::Name),
56            "size" => Some(SortColumn::Size),
57            "modified" => Some(SortColumn::Modified),
58            "type" => Some(SortColumn::Type),
59            "taken" => Some(SortColumn::Taken),
60            _ => None,
61        }
62    }
63
64    /// Every column, in the order a sort menu lists them.
65    pub const ALL: [SortColumn; 5] = [
66        SortColumn::Name,
67        SortColumn::Modified,
68        SortColumn::Taken,
69        SortColumn::Size,
70        SortColumn::Type,
71    ];
72
73    /// Which way a first click sorts: the newest and the largest first, as
74    /// Finder and Nautilus do; those are what people look for in these
75    /// columns.
76    pub fn starts_descending(self) -> bool {
77        matches!(
78            self,
79            SortColumn::Size | SortColumn::Modified | SortColumn::Taken
80        )
81    }
82}
83
84/// The order of the picker's entries. A listing always has one: unlike the
85/// data table's, a header's click goes up and down, never to no order.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
87pub struct PickerSort {
88    pub column: SortColumn,
89    pub descending: bool,
90}
91
92impl PickerSort {
93    /// What a click on `column`'s header asks for.
94    pub fn click(self, column: SortColumn) -> PickerSort {
95        PickerSort {
96            column,
97            descending: if self.column == column {
98                !self.descending
99            } else {
100                column.starts_descending()
101            },
102        }
103    }
104
105    /// As the store keeps it: `name`, `-name` (descending), as the data
106    /// table does.
107    pub fn as_text(self) -> String {
108        let column = self.column.as_str();
109        if self.descending {
110            format!("-{column}")
111        } else {
112            column.to_string()
113        }
114    }
115
116    /// The order of a text in the store.
117    pub fn parse(text: &str) -> Option<PickerSort> {
118        let (column, descending) = match text.strip_prefix('-') {
119            Some(column) => (column, true),
120            None => (text, false),
121        };
122        SortColumn::parse(column).map(|column| PickerSort { column, descending })
123    }
124}
125
126/// Compares names as people read them: a run of digits is a number
127/// (`IMG_9` before `IMG_10`), and case does not matter. Names that read the
128/// same (`a` and `A`, `01` and `1`) take the order of their characters, so
129/// that this is a total order. It compares characters, not a language's
130/// collation: `é` comes after `z`.
131pub fn natural_cmp(a: &str, b: &str) -> Ordering {
132    let (mut x, mut y) = (a, b);
133    loop {
134        let (Some(c), Some(d)) = (x.chars().next(), y.chars().next()) else {
135            return x.len().cmp(&y.len()).then_with(|| a.cmp(b));
136        };
137        let order = if c.is_ascii_digit() && d.is_ascii_digit() {
138            let (m, rest_x) = digits(x);
139            let (n, rest_y) = digits(y);
140            x = rest_x;
141            y = rest_y;
142            m.len().cmp(&n.len()).then_with(|| m.cmp(n))
143        } else {
144            x = &x[c.len_utf8()..];
145            y = &y[d.len_utf8()..];
146            c.to_lowercase().cmp(d.to_lowercase())
147        };
148        if order != Ordering::Equal {
149            return order;
150        }
151    }
152}
153
154/// The number a text starts with, without its leading zeros, and what
155/// follows it.
156fn digits(text: &str) -> (&str, &str) {
157    let end = text
158        .find(|c: char| !c.is_ascii_digit())
159        .unwrap_or(text.len());
160    let (number, rest) = text.split_at(end);
161    (number.trim_start_matches('0'), rest)
162}
163
164/// What an entry is sorted by, in the column sorted. All of one kind.
165#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
166enum Value {
167    Size(u64),
168    Time(SystemTime),
169    Extension(String),
170}
171
172/// A file's extension in lower case, empty without one.
173fn extension(name: &str) -> String {
174    extension_dot(name).map_or_else(String::new, |dot| name[dot + 1..].to_lowercase())
175}
176
177/// What [`sort_by`] asks of each item it sorts.
178pub(super) struct SortFacts<'a> {
179    pub name: &'a str,
180    pub is_dir: bool,
181    pub size: Option<u64>,
182    pub modified: Option<SystemTime>,
183    pub taken: Option<SystemTime>,
184}
185
186/// Puts entries in `sort`'s order ([`sort_by`]), `facts` asked only when the
187/// column needs them: the tests' way to read the order.
188#[cfg(test)]
189pub(super) fn sort_entries(
190    entries: Vec<Entry>,
191    sort: PickerSort,
192    folders_first: bool,
193    facts: impl Fn(&Entry) -> Option<Meta>,
194) -> Vec<Entry> {
195    let needs_facts = matches!(
196        sort.column,
197        SortColumn::Size | SortColumn::Modified | SortColumn::Taken
198    );
199    let mut keyed: Vec<(Option<Meta>, Entry)> = entries
200        .into_iter()
201        .map(|e| (needs_facts.then(|| facts(&e)).flatten(), e))
202        .collect();
203    sort_by(&mut keyed, sort, folders_first, |(m, e)| SortFacts {
204        name: &e.name,
205        is_dir: e.is_dir,
206        size: m.as_ref().filter(|m| !m.is_dir).map(|m| m.len),
207        modified: m.as_ref().and_then(|m| m.modified),
208        // A file system knows no capture time.
209        taken: None,
210    });
211    keyed.into_iter().map(|(_, e)| e).collect()
212}
213
214/// Sorts `items` in `sort`'s order. Folders stay first when `folders_first`,
215/// in the same direction among themselves. What has no value in the column (a
216/// folder's size and type, a time the file system does not say) goes last either
217/// way, and the name settles what ties: upwards, except in the name's own column.
218pub(super) fn sort_by<T>(
219    items: &mut [T],
220    sort: PickerSort,
221    folders_first: bool,
222    facts: impl Fn(&T) -> SortFacts<'_>,
223) {
224    let value = |f: &SortFacts<'_>| match sort.column {
225        SortColumn::Name => None,
226        SortColumn::Size => f.size.filter(|_| !f.is_dir).map(Value::Size),
227        SortColumn::Modified => f.modified.map(Value::Time),
228        SortColumn::Taken => f.taken.or(f.modified).map(Value::Time),
229        SortColumn::Type => (!f.is_dir).then(|| Value::Extension(extension(f.name))),
230    };
231    let mut order: Vec<(Option<Value>, usize)> = items
232        .iter()
233        .enumerate()
234        .map(|(i, t)| (value(&facts(t)), i))
235        .collect();
236    order.sort_by(|(v, i), (w, j)| {
237        let (a, b) = (facts(&items[*i]), facts(&items[*j]));
238        let group = if folders_first {
239            b.is_dir.cmp(&a.is_dir)
240        } else {
241            Ordering::Equal
242        };
243        let values = || match (v, w) {
244            (Some(v), Some(w)) if sort.descending => w.cmp(v),
245            (Some(v), Some(w)) => v.cmp(w),
246            (None, Some(_)) => Ordering::Greater,
247            (Some(_), None) => Ordering::Less,
248            (None, None) => Ordering::Equal,
249        };
250        let names = || {
251            let order = natural_cmp(a.name, b.name);
252            if sort.descending && sort.column == SortColumn::Name {
253                order.reverse()
254            } else {
255                order
256            }
257        };
258        group.then_with(values).then_with(names)
259    });
260    apply_order(items, order.into_iter().map(|(_, i)| i).collect());
261}
262
263/// Moves `items` into `order` (each an index of where the item is now), in
264/// place.
265fn apply_order<T>(items: &mut [T], mut order: Vec<usize>) {
266    // Follow each cycle of the permutation once.
267    for start in 0..order.len() {
268        let mut at = start;
269        while order[at] != start {
270            let from = order[at];
271            items.swap(at, from);
272            order[at] = at;
273            at = from;
274        }
275        order[at] = at;
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use std::path::PathBuf;
283    use std::time::Duration;
284
285    #[test]
286    fn names_sort_as_people_read_them() {
287        let mut names = vec![
288            "IMG_10.cr3",
289            "b",
290            "IMG_9.cr3",
291            "A",
292            "IMG_009.cr3",
293            "img_2.cr3",
294            "a",
295            "10",
296            "9",
297            "été",
298            "z",
299            "x18446744073709551616000",
300            "x18446744073709551617",
301        ];
302        names.sort_by(|a, b| natural_cmp(a, b));
303        assert_eq!(
304            names,
305            [
306                "9",
307                "10",
308                "A",
309                "a",
310                "b",
311                "img_2.cr3",
312                "IMG_009.cr3",
313                "IMG_9.cr3",
314                "IMG_10.cr3",
315                "x18446744073709551617",
316                "x18446744073709551616000",
317                "z",
318                "été",
319            ]
320        );
321        assert_eq!(natural_cmp("a", "a"), Ordering::Equal);
322        assert_eq!(natural_cmp("", "a"), Ordering::Less);
323        assert_eq!(natural_cmp("a1", "a"), Ordering::Greater);
324        assert_eq!(natural_cmp("a", "a1"), Ordering::Less);
325        // Digits among other characters: the order holds for any three.
326        assert_eq!(natural_cmp("a!", "a1"), Ordering::Less);
327        assert_eq!(natural_cmp("a1", "ab"), Ordering::Less);
328        assert_eq!(natural_cmp("a!", "ab"), Ordering::Less);
329        // Zeros alone, and a number against its own start.
330        assert_eq!(natural_cmp("0", "00"), Ordering::Less);
331        assert_eq!(natural_cmp("0", "1"), Ordering::Less);
332    }
333
334    #[test]
335    fn the_stored_text_round_trips_and_nonsense_is_none() {
336        for column in [
337            SortColumn::Name,
338            SortColumn::Size,
339            SortColumn::Modified,
340            SortColumn::Type,
341        ] {
342            for descending in [false, true] {
343                let sort = PickerSort { column, descending };
344                assert_eq!(PickerSort::parse(&sort.as_text()), Some(sort));
345            }
346        }
347        assert_eq!(PickerSort::parse("colour"), None);
348        assert_eq!(PickerSort::parse(""), None);
349        assert_eq!(PickerSort::parse("-"), None);
350    }
351
352    #[test]
353    fn a_click_turns_the_column_or_starts_it_its_own_way() {
354        let name = PickerSort::default();
355        assert_eq!(name.click(SortColumn::Name).as_text(), "-name");
356        assert_eq!(name.click(SortColumn::Name).click(SortColumn::Name), name);
357        assert_eq!(name.click(SortColumn::Size).as_text(), "-size");
358        assert_eq!(name.click(SortColumn::Modified).as_text(), "-modified");
359        assert_eq!(name.click(SortColumn::Type).as_text(), "type");
360        let down = name.click(SortColumn::Name);
361        assert_eq!(down.click(SortColumn::Type).as_text(), "type");
362    }
363
364    fn entry(name: &str, is_dir: bool) -> Entry {
365        Entry {
366            path: PathBuf::from("/d").join(name),
367            name: name.into(),
368            is_dir,
369        }
370    }
371
372    fn sorted(text: &str, folders_first: bool) -> Vec<String> {
373        let entries = vec![
374            entry("b.png", false),
375            entry("IMG_10.jpg", false),
376            entry("IMG_9.png", false),
377            entry("old", true),
378            entry("New 2", true),
379            entry("New 10", true),
380            entry("README", false),
381        ];
382        let facts = |e: &Entry| {
383            let (len, secs) = match e.name.as_str() {
384                "b.png" => (5, Some(30)),
385                "IMG_10.jpg" => (5, Some(10)),
386                "IMG_9.png" => (9, Some(20)),
387                "README" => (1, None),
388                "old" => (0, Some(5)),
389                "New 2" => (0, Some(50)),
390                _ => (0, None),
391            };
392            Some(Meta {
393                is_dir: e.is_dir,
394                len,
395                modified: secs.map(|s| SystemTime::UNIX_EPOCH + Duration::from_secs(s)),
396            })
397        };
398        let sort = PickerSort::parse(text).unwrap();
399        sort_entries(entries, sort, folders_first, facts)
400            .into_iter()
401            .map(|e| e.name)
402            .collect()
403    }
404
405    #[test]
406    fn folders_stay_first_in_every_order_unless_asked_otherwise() {
407        assert_eq!(
408            sorted("name", true),
409            [
410                "New 2",
411                "New 10",
412                "old",
413                "b.png",
414                "IMG_9.png",
415                "IMG_10.jpg",
416                "README"
417            ]
418        );
419        assert_eq!(
420            sorted("-name", true),
421            [
422                "old",
423                "New 10",
424                "New 2",
425                "README",
426                "IMG_10.jpg",
427                "IMG_9.png",
428                "b.png"
429            ]
430        );
431        assert_eq!(
432            sorted("name", false),
433            [
434                "b.png",
435                "IMG_9.png",
436                "IMG_10.jpg",
437                "New 2",
438                "New 10",
439                "old",
440                "README"
441            ]
442        );
443    }
444
445    #[test]
446    fn size_and_time_order_and_what_has_none_goes_last_either_way() {
447        // Ties go up by name in both directions.
448        assert_eq!(
449            sorted("size", true),
450            [
451                "New 2",
452                "New 10",
453                "old",
454                "README",
455                "b.png",
456                "IMG_10.jpg",
457                "IMG_9.png"
458            ]
459        );
460        assert_eq!(
461            sorted("-size", true),
462            [
463                "New 2",
464                "New 10",
465                "old",
466                "IMG_9.png",
467                "b.png",
468                "IMG_10.jpg",
469                "README"
470            ]
471        );
472        // Mixed with the files, a folder has no size.
473        assert_eq!(
474            sorted("-size", false),
475            [
476                "IMG_9.png",
477                "b.png",
478                "IMG_10.jpg",
479                "README",
480                "New 2",
481                "New 10",
482                "old"
483            ]
484        );
485        assert_eq!(
486            sorted("modified", false),
487            [
488                "old",
489                "IMG_10.jpg",
490                "IMG_9.png",
491                "b.png",
492                "New 2",
493                "New 10",
494                "README"
495            ]
496        );
497        assert_eq!(
498            sorted("-modified", false),
499            [
500                "New 2",
501                "b.png",
502                "IMG_9.png",
503                "IMG_10.jpg",
504                "old",
505                "New 10",
506                "README"
507            ]
508        );
509    }
510
511    #[test]
512    fn the_type_is_the_extension_whatever_its_case() {
513        assert_eq!(extension("a.PNG"), "png");
514        assert_eq!(extension("README"), "");
515        assert_eq!(extension(".config"), "");
516        assert_eq!(
517            sorted("type", true),
518            [
519                "New 2",
520                "New 10",
521                "old",
522                "README",
523                "IMG_10.jpg",
524                "b.png",
525                "IMG_9.png"
526            ]
527        );
528        assert_eq!(
529            sorted("-type", true),
530            [
531                "New 2",
532                "New 10",
533                "old",
534                "b.png",
535                "IMG_9.png",
536                "IMG_10.jpg",
537                "README"
538            ]
539        );
540    }
541
542    #[test]
543    fn name_and_type_read_no_facts() {
544        for text in ["name", "-name", "type"] {
545            let sort = PickerSort::parse(text).unwrap();
546            let out = sort_entries(
547                vec![entry("a", false), entry("b", true)],
548                sort,
549                true,
550                |_| panic!("no facts for {text}"),
551            );
552            assert_eq!(out.len(), 2);
553        }
554    }
555
556    #[test]
557    fn the_picker_sorts_by_capture_time_as_by_change_time() {
558        assert_eq!(sorted("taken", true), sorted("modified", true));
559        assert_eq!(sorted("-taken", false), sorted("-modified", false));
560    }
561
562    #[test]
563    fn a_capture_time_comes_before_the_change_time_and_stands_in_for_none() {
564        // (name, modified, taken)
565        let mut items = vec![
566            ("a", Some(1), Some(30)),
567            ("b", Some(20), None),
568            ("c", None, Some(10)),
569            ("d", None, None),
570        ];
571        let at = |s: Option<u64>| s.map(|s| SystemTime::UNIX_EPOCH + Duration::from_secs(s));
572        let sort = PickerSort::parse("taken").unwrap();
573        sort_by(&mut items, sort, true, |&(name, modified, taken)| {
574            SortFacts {
575                name,
576                is_dir: false,
577                size: None,
578                modified: at(modified),
579                taken: at(taken),
580            }
581        });
582        let names: Vec<&str> = items.iter().map(|i| i.0).collect();
583        assert_eq!(names, ["c", "b", "a", "d"]);
584    }
585
586    #[test]
587    fn an_order_is_applied_in_place_whatever_its_cycles() {
588        for order in [
589            vec![0, 1, 2, 3, 4],
590            vec![4, 3, 2, 1, 0],
591            vec![1, 2, 3, 4, 0],
592            vec![2, 0, 1, 4, 3],
593        ] {
594            let mut items = vec!['a', 'b', 'c', 'd', 'e'];
595            let want: Vec<char> = order.iter().map(|&i| items[i]).collect();
596            apply_order(&mut items, order);
597            assert_eq!(items, want);
598        }
599    }
600}