Tunal/crates/tunal/src/folder/sort.rs
astar76 c0584791f5 feat: icon sizes, default view that applies, sort menus; fix grid columns
- Default view (Details, Icons, Large icons) now applies to every folder that
  keeps no view of its own: on opening, on leaving a folder with a saved view,
  and at once in open panes when the setting changes.
- Grid icon sizes small / medium / large / extra large: Ctrl+scroll over a pane,
  Ctrl+plus, Ctrl+minus, Ctrl+0; per pane, kept in `.directory` (IconSize) with
  the rest of a remembered view.
- A Sort button in the toolbar opens the sort menu (keys, ascending/descending,
  folders first, group by); the context menu of empty space and folders gets
  Sort by and View mode submenus (new action ids, also in the menu editor).
- Grid in a new tab showed one item per row: the reused pane view never
  reported its column count to the new folder model. FolderState now carries
  the model's columns and the grid reports again when they differ.
- Item and the sort functions are pure modules now (folder/item.rs, sort.rs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-19 10:00:51 -06:00

190 lines
6.1 KiB
Rust

//! Row order: natural name compare, sort keys, group buckets. Pure: the integration tests
//! (`tests/sort.rs`) use it through the library target.
use std::cmp::Ordering;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tunal_core::playlist::Ranks;
use super::item::Item;
use crate::icons::Category;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SortKey {
Name,
Size,
Type,
Modified,
/// Index into the folder's playlists.
Playlist(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroupBy {
None,
Type,
Modified,
Size,
}
/// How entries are ordered: the part of a pane's view settings that sorting reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Order {
pub key: SortKey,
pub descending: bool,
pub folders_first: bool,
}
/// Compares lower-cased names with digit runs as numbers: `file2` < `file10`.
pub fn natural_cmp(a: &str, b: &str) -> Ordering {
let (mut a, mut b) = (a, b);
loop {
match (a.chars().next(), b.chars().next()) {
(None, None) => return Ordering::Equal,
(None, _) => return Ordering::Less,
(_, None) => return Ordering::Greater,
(Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
let (da, ra) = split_digits(a);
let (db, rb) = split_digits(b);
let (ta, tb) = (da.trim_start_matches('0'), db.trim_start_matches('0'));
let order = ta
.len()
.cmp(&tb.len())
.then_with(|| ta.cmp(tb))
// Same value: fewer leading zeros first.
.then_with(|| da.len().cmp(&db.len()));
if order != Ordering::Equal {
return order;
}
(a, b) = (ra, rb);
}
(Some(x), Some(y)) => {
if x != y {
return x.cmp(&y);
}
(a, b) = (&a[x.len_utf8()..], &b[y.len_utf8()..]);
}
}
}
}
fn split_digits(s: &str) -> (&str, &str) {
s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()))
}
/// Natural order, then the exact names so the order is total.
pub fn name_cmp(a: &Item, b: &Item) -> Ordering {
natural_cmp(&a.key, &b.key)
.then_with(|| a.entry.display_name.cmp(&b.entry.display_name))
.then_with(|| a.entry.name.cmp(&b.entry.name))
}
/// Order of two items under `settings` (without groups). `ranks` is the playlist in use.
pub fn compare(a: &Item, b: &Item, settings: &Order, ranks: Option<&Ranks>) -> Ordering {
if let SortKey::Playlist(_) = settings.key {
let rank = |i: &Item| ranks.and_then(|r| r.rank(&i.entry.name, i.is_dir));
// Listed first in playlist order, the rest by name; descending reverses it all.
let order = match (rank(a), rank(b)) {
(Some(x), Some(y)) => x.cmp(&y).then_with(|| name_cmp(a, b)),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => name_cmp(a, b),
};
return if settings.descending {
order.reverse()
} else {
order
};
}
if settings.folders_first && a.is_dir != b.is_dir {
return b.is_dir.cmp(&a.is_dir);
}
let order = match settings.key {
SortKey::Size => a.size().cmp(&b.size()),
SortKey::Type => a
.category
.cmp(&b.category)
.then_with(|| a.entry.mime.cmp(b.entry.mime)),
SortKey::Modified => a.entry.mtime.cmp(&b.entry.mtime),
SortKey::Name | SortKey::Playlist(_) => Ordering::Equal,
}
.then_with(|| name_cmp(a, b));
if settings.descending {
order.reverse()
} else {
order
}
}
/// Start of today, yesterday, this week, this month and this year in local time.
pub struct Calendar {
starts: [SystemTime; 5],
}
impl Calendar {
pub fn now() -> Self {
let now = jiff::Zoned::now();
let day = now.start_of_day().unwrap_or_else(|_| now.clone());
let back = |days: i64| {
day.checked_sub(jiff::Span::new().days(days))
.unwrap_or_else(|_| day.clone())
};
let week = back(i64::from(day.weekday().to_monday_zero_offset()));
let month = back(i64::from(day.day()) - 1);
let year = back(i64::from(day.day_of_year()) - 1);
let to_system = |z: &jiff::Zoned| {
let secs = z.timestamp().as_second();
UNIX_EPOCH + Duration::from_secs(secs.max(0) as u64)
};
Self {
starts: [&day, &back(1), &week, &month, &year].map(to_system),
}
}
/// Bucket of a modification time: 0 today … 5 older, 6 unknown.
fn bucket(&self, mtime: Option<SystemTime>) -> u8 {
match mtime {
None => 6,
Some(t) => self.starts.iter().position(|s| t >= *s).unwrap_or(5) as u8,
}
}
}
const DATE_GROUPS: [&str; 7] = [
"Today",
"Yesterday",
"Earlier this week",
"Earlier this month",
"Earlier this year",
"Older",
"Unknown date",
];
const SIZE_GROUPS: [(u64, &str); 6] = [
(1, "Empty"),
(16 << 10, "Tiny (under 16 KiB)"),
(1 << 20, "Small (under 1 MiB)"),
(128 << 20, "Medium (under 128 MiB)"),
(1 << 30, "Large (under 1 GiB)"),
(u64::MAX, "Huge (1 GiB and more)"),
];
/// Group of an item as (rank, label); groups show in rank order.
pub fn group(item: &Item, group: GroupBy, calendar: &Calendar) -> (u8, &'static str) {
match group {
GroupBy::None => (0, ""),
GroupBy::Type => (item.category as u8, item.category.group_label()),
GroupBy::Modified => {
let b = calendar.bucket(item.entry.mtime);
(b, DATE_GROUPS[b as usize])
}
GroupBy::Size if item.category == Category::Folder => (0, "Folders"),
GroupBy::Size => {
let i = SIZE_GROUPS
.iter()
.position(|(limit, _)| item.entry.size < *limit)
.unwrap_or(SIZE_GROUPS.len() - 1);
(i as u8 + 1, SIZE_GROUPS[i].1)
}
}
}