1use std::collections::{BTreeSet, HashMap, HashSet};
17use std::fmt;
18use std::ops::Range;
19use std::path::{Path, PathBuf};
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::mpsc;
22use std::sync::{Arc, Mutex, MutexGuard};
23use std::time::SystemTime;
24
25use egui::{AtomExt as _, Modifiers, Ui};
26
27use egui_pop_core::icon::Icon;
28use egui_pop_core::indicator::{Anchor, Indicator};
29use egui_pop_core::kit::Kit;
30use egui_pop_core::placeholder::SkeletonTokens;
31use egui_pop_core::strings;
32use egui_pop_core::theme::Tokens;
33pub use egui_pop_core::thumbnail::GridResize;
34use egui_pop_core::thumbnail::{self, Thumbnail};
35use egui_pop_core::thumbnail::{Band, ThumbnailGrid};
36use egui_pop_core::widgets;
37
38use super::fs::{Meta, SharedFs};
39use super::groups::{FileGroup, Groupings};
40use super::preview::{Previews, Shown};
41use super::sort::{PickerSort, SortColumn, SortFacts, sort_by};
42
43fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
44 m.lock().unwrap_or_else(|e| e.into_inner())
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub enum EntryKind {
54 File,
55 Folder,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct SourceEntry {
61 pub path: PathBuf,
62 pub name: String,
63 pub kind: EntryKind,
64 pub size: Option<u64>,
66 pub modified: Option<SystemTime>,
67 pub taken: Option<SystemTime>,
70 pub app_id: Option<u64>,
72}
73
74impl SourceEntry {
75 pub fn is_dir(&self) -> bool {
76 self.kind == EntryKind::Folder
77 }
78
79 pub fn meta(&self) -> Meta {
81 Meta {
82 is_dir: self.is_dir(),
83 len: self.size.unwrap_or(0),
84 modified: self.modified,
85 }
86 }
87}
88
89#[derive(Clone, Debug, PartialEq, Eq)]
91pub enum SourceError {
92 NotFound(PathBuf),
93 Denied(PathBuf),
94 Io(String),
95 Unsupported,
96}
97
98impl fmt::Display for SourceError {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 match self {
101 SourceError::NotFound(p) => write!(f, "{} does not exist", p.display()),
102 SourceError::Denied(p) => write!(f, "{} cannot be read", p.display()),
103 SourceError::Io(e) => f.write_str(e),
104 SourceError::Unsupported => f.write_str("this source cannot do that"),
105 }
106 }
107}
108
109#[derive(Clone, Debug, PartialEq, Eq)]
111pub enum Page {
112 Entries(Vec<SourceEntry>),
113 Updated(Vec<SourceEntry>),
115 Removed(Vec<PathBuf>),
116 Changed,
118 Done,
119 Failed(SourceError),
120}
121
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
124pub struct ListOptions {
125 pub hidden: bool,
127}
128
129#[derive(Debug)]
132pub struct Listing {
133 rx: mpsc::Receiver<Page>,
134 cancel: Arc<AtomicBool>,
135}
136
137#[derive(Clone, Debug)]
139pub struct ListingSender {
140 tx: mpsc::Sender<Page>,
141 cancel: Arc<AtomicBool>,
142}
143
144impl ListingSender {
145 pub fn send(&self, page: Page) -> bool {
147 !self.cancelled() && self.tx.send(page).is_ok()
148 }
149
150 pub fn cancelled(&self) -> bool {
151 self.cancel.load(Ordering::Relaxed)
152 }
153}
154
155impl Listing {
156 pub fn channel() -> (ListingSender, Listing) {
158 let (tx, rx) = mpsc::channel();
159 let cancel = Arc::new(AtomicBool::new(false));
160 (
161 ListingSender {
162 tx,
163 cancel: cancel.clone(),
164 },
165 Listing { rx, cancel },
166 )
167 }
168
169 pub fn poll(&self) -> Vec<Page> {
171 self.rx.try_iter().collect()
172 }
173
174 pub fn cancel(&self) {
175 self.cancel.store(true, Ordering::Relaxed);
176 }
177}
178
179impl Drop for Listing {
180 fn drop(&mut self) {
181 self.cancel();
182 }
183}
184
185pub trait FileSource: Send + Sync + fmt::Debug {
188 fn id(&self) -> &str;
190
191 fn list(&self, place: &Path, options: &ListOptions) -> Listing;
193
194 fn can_watch(&self) -> bool {
196 false
197 }
198
199 fn watch(&self, _place: &Path) -> Result<(), SourceError> {
201 Err(SourceError::Unsupported)
202 }
203}
204
205#[derive(Clone, Debug)]
209pub struct FsSource {
210 fs: SharedFs,
211 page_size: usize,
212}
213
214impl FsSource {
215 pub const PAGE_SIZE: usize = 512;
216
217 pub fn new(fs: SharedFs) -> Self {
218 Self {
219 fs,
220 page_size: Self::PAGE_SIZE,
221 }
222 }
223
224 pub fn page_size(mut self, n: usize) -> Self {
225 self.page_size = n.max(1);
226 self
227 }
228
229 fn run(fs: &SharedFs, place: &Path, options: ListOptions, page: usize, out: &ListingSender) {
230 if out.cancelled() {
232 return;
233 }
234 let items = match fs.read_dir(place) {
235 Ok(items) => items,
236 Err(e) => {
237 let err = match e.kind() {
238 std::io::ErrorKind::NotFound => SourceError::NotFound(place.to_path_buf()),
239 std::io::ErrorKind::PermissionDenied => {
240 SourceError::Denied(place.to_path_buf())
241 }
242 _ => SourceError::Io(e.to_string()),
243 };
244 out.send(Page::Failed(err));
245 return;
246 }
247 };
248 let mut batch = Vec::with_capacity(page.min(items.len()));
249 for item in items {
250 if out.cancelled() {
253 return;
254 }
255 if !options.hidden && item.name.starts_with('.') {
256 continue;
257 }
258 let path = place.join(&item.name);
259 let meta = fs.metadata(&path).ok();
260 batch.push(SourceEntry {
261 kind: if item.is_dir {
262 EntryKind::Folder
263 } else {
264 EntryKind::File
265 },
266 size: meta.filter(|m| !m.is_dir).map(|m| m.len),
267 modified: meta.and_then(|m| m.modified),
268 taken: None,
269 app_id: None,
270 name: item.name,
271 path,
272 });
273 if batch.len() == page && !out.send(Page::Entries(std::mem::take(&mut batch))) {
274 return;
275 }
276 }
277 if !batch.is_empty() && !out.send(Page::Entries(batch)) {
278 return;
279 }
280 out.send(Page::Done);
281 }
282}
283
284impl FileSource for FsSource {
285 fn id(&self) -> &str {
286 "egui_pop.fs"
287 }
288
289 fn list(&self, place: &Path, options: &ListOptions) -> Listing {
290 let (tx, listing) = Listing::channel();
291 let (fs, place, options, page) = (
292 self.fs.clone(),
293 place.to_path_buf(),
294 *options,
295 self.page_size,
296 );
297 if self.fs.is_native() && !cfg!(target_arch = "wasm32") {
298 std::thread::spawn(move || Self::run(&fs, &place, options, page, &tx));
299 } else {
300 Self::run(&fs, &place, options, page, &tx);
301 }
302 listing
303 }
304}
305
306#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
312pub enum Priority {
313 Visible,
315 Near,
317 Background,
318}
319
320#[derive(Clone, Copy, Debug)]
322pub struct ThumbRequest<'a> {
323 pub entry: &'a SourceEntry,
324 pub size: u32,
326 pub priority: Priority,
327}
328
329#[derive(Clone)]
331pub enum ThumbState {
332 Ready(egui::TextureHandle),
333 Loading,
334 None,
336 Failed(String),
337}
338
339impl fmt::Debug for ThumbState {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 match self {
342 ThumbState::Ready(t) => write!(f, "Ready({:?})", t.size()),
343 ThumbState::Loading => f.write_str("Loading"),
344 ThumbState::None => f.write_str("None"),
345 ThumbState::Failed(why) => write!(f, "Failed({why:?})"),
346 }
347 }
348}
349
350pub trait ThumbnailProvider: Send + Sync {
356 fn begin_frame(&self, _ctx: &egui::Context) {}
357 fn request(&self, ctx: &egui::Context, request: &ThumbRequest<'_>) -> ThumbState;
359 fn end_frame(&self, _ctx: &egui::Context) {}
360 fn cancel(&self, _path: &Path) {}
362}
363
364#[derive(Debug, Default)]
367pub struct Renewals {
368 asked: Vec<(Priority, usize, PathBuf, Meta)>,
369 before: HashSet<PathBuf>,
370}
371
372impl Renewals {
373 pub fn begin(&mut self) {
374 self.before = self.asked.drain(..).map(|(_, _, p, _)| p).collect();
375 }
376
377 pub fn ask(&mut self, entry: &SourceEntry, priority: Priority) {
378 if self.asked.iter().any(|(_, _, p, _)| *p == entry.path) {
379 return;
380 }
381 let n = self.asked.len();
382 self.asked
383 .push((priority, n, entry.path.clone(), entry.meta()));
384 }
385
386 pub fn wanted(&mut self) -> Vec<(PathBuf, Meta)> {
388 self.asked.sort_by_key(|(p, n, _, _)| (*p, *n));
389 self.asked
390 .iter()
391 .map(|(_, _, p, m)| (p.clone(), *m))
392 .collect()
393 }
394
395 pub fn dropped(&self) -> Vec<PathBuf> {
397 let now: HashSet<&PathBuf> = self.asked.iter().map(|(_, _, p, _)| p).collect();
398 let mut gone: Vec<PathBuf> = self
399 .before
400 .iter()
401 .filter(|p| !now.contains(p))
402 .cloned()
403 .collect();
404 gone.sort();
405 gone
406 }
407}
408
409#[allow(
413 missing_debug_implementations,
414 reason = "its preview worker and file system have no Debug"
415)]
416pub struct PreviewThumbnails {
417 previews: Previews,
418 fs: SharedFs,
419 renewals: Mutex<Renewals>,
420}
421
422impl PreviewThumbnails {
423 pub fn new(previews: Previews, fs: SharedFs) -> Self {
424 Self {
425 previews,
426 fs,
427 renewals: Mutex::default(),
428 }
429 }
430}
431
432impl ThumbnailProvider for PreviewThumbnails {
433 fn begin_frame(&self, _ctx: &egui::Context) {
434 lock(&self.renewals).begin();
435 }
436
437 fn request(&self, ctx: &egui::Context, request: &ThumbRequest<'_>) -> ThumbState {
438 if request.entry.is_dir() {
439 return ThumbState::None;
440 }
441 lock(&self.renewals).ask(request.entry, request.priority);
442 match self
443 .previews
444 .thumbnail(&request.entry.path, &request.entry.meta())
445 {
446 Shown::Ready(ready) => match ready.texture(ctx, 0) {
447 Some(t) => ThumbState::Ready(t),
448 None => ThumbState::None,
449 },
450 Shown::Loading => ThumbState::Loading,
451 Shown::Nothing => ThumbState::None,
452 Shown::Failed(why) => ThumbState::Failed(why),
453 }
454 }
455
456 fn end_frame(&self, ctx: &egui::Context) {
457 let wanted = lock(&self.renewals).wanted();
458 self.previews.want(ctx, &self.fs, &wanted);
460 }
461}
462
463#[derive(Clone, Debug, Default, PartialEq, Eq)]
469pub struct Selection {
470 pub paths: BTreeSet<PathBuf>,
471 pub anchor: Option<PathBuf>,
472}
473
474impl Selection {
475 pub fn contains(&self, path: &Path) -> bool {
476 self.paths.contains(path)
477 }
478
479 pub fn len(&self) -> usize {
480 self.paths.len()
481 }
482
483 pub fn is_empty(&self) -> bool {
484 self.paths.is_empty()
485 }
486
487 fn only(&mut self, path: &Path) {
488 self.paths.clear();
489 self.paths.insert(path.to_path_buf());
490 self.anchor = Some(path.to_path_buf());
491 }
492}
493
494#[derive(Clone, Copy, Debug, PartialEq, Eq)]
500pub enum ModeKey {
501 Up,
502 Down,
503 Left,
504 Right,
505 PageUp,
506 PageDown,
507 Home,
508 End,
509}
510
511#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
513pub struct ModeNeeds {
514 pub thumbnails: bool,
515 pub time: bool,
517 pub hierarchy: bool,
520}
521
522#[derive(Clone, Debug, Default, PartialEq, Eq)]
525pub struct Column {
526 pub place: PathBuf,
528 pub entries: Vec<SourceEntry>,
531 pub open: Option<usize>,
533 pub loading: bool,
535}
536
537#[derive(Clone, Debug, PartialEq, Eq)]
540pub struct Reach {
541 pub place: PathBuf,
542 pub focus: Option<PathBuf>,
543}
544
545#[derive(Clone, Copy, Debug, PartialEq, Eq)]
547pub enum Travel {
548 Into,
550 Out,
552}
553
554#[derive(Clone, Debug, PartialEq)]
556pub struct ModeInfo {
557 pub id: String,
559 pub label: String,
562 pub icon: String,
565 pub keys: Vec<(String, String)>,
567 pub gestures: Vec<String>,
569 pub persist: String,
571 pub role: egui::Role,
573 pub needs: ModeNeeds,
574}
575
576#[derive(Clone, Debug, PartialEq)]
578pub struct ModeSettings {
579 pub thumbnail_size: f32,
582 pub agenda: AgendaSettings,
584}
585
586impl Default for ModeSettings {
587 fn default() -> Self {
588 Self {
589 thumbnail_size: 128.0,
590 agenda: AgendaSettings::default(),
591 }
592 }
593}
594
595#[derive(Clone, Copy, Debug, PartialEq)]
608pub enum ThumbZoom {
609 PerRow(u32),
611 Points(f32),
616}
617
618impl Default for ThumbZoom {
619 fn default() -> Self {
620 ThumbZoom::PerRow(ThumbZoom::DEFAULT_PER_ROW)
621 }
622}
623
624impl ThumbZoom {
625 pub const DEFAULT_PER_ROW: u32 = 5;
627 pub const STEPS: [u32; 13] = [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32];
630 pub const MOST: u32 = 64;
632
633 pub fn from_points(points: f32, width: f32, gap: f32) -> ThumbZoom {
637 let points = if points.is_finite() {
638 points.max(ThumbnailsMode::MIN_SIZE)
639 } else {
640 ThumbnailsMode::MIN_SIZE
641 };
642 ThumbZoom::PerRow(fitting(points, width, gap))
643 }
644
645 pub fn most_per_row(width: f32, gap: f32) -> u32 {
649 fitting(ThumbnailsMode::MIN_SIZE, width, gap)
650 }
651
652 pub fn per_row(self) -> Option<u32> {
654 match self {
655 ThumbZoom::PerRow(n) => Some(n.clamp(1, Self::MOST)),
656 ThumbZoom::Points(_) => None,
657 }
658 }
659
660 #[must_use]
663 pub fn resolved(self, width: f32, gap: f32) -> ThumbZoom {
664 match self {
665 ThumbZoom::PerRow(n) => ThumbZoom::PerRow(n.clamp(1, Self::MOST)),
666 ThumbZoom::Points(p) => ThumbZoom::from_points(p, width, gap),
667 }
668 }
669
670 pub fn shown_per_row(self, width: f32, gap: f32) -> u32 {
673 let n = self.resolved(width, gap).per_row().unwrap_or(1);
674 n.min(Self::most_per_row(width, gap))
675 }
676
677 pub fn side(self, width: f32, gap: f32) -> f32 {
681 let n = self.shown_per_row(width, gap) as f32;
682 ((width + gap) / n - gap).floor().max(1.0)
683 }
684
685 #[must_use]
691 pub fn under(self, resize: GridResize, width: f32, gap: f32) -> ThumbZoom {
692 if !(width.is_finite() && width >= ThumbnailsMode::MIN_SIZE) {
693 return self;
694 }
695 match (resize, self) {
696 (GridResize::PerRow, _) => self.resolved(width, gap),
697 (GridResize::FixedSize, ThumbZoom::Points(p)) => {
698 let p = if p.is_finite() { p } else { 0.0 };
699 ThumbZoom::Points(p.clamp(
700 ThumbnailsMode::MIN_SIZE,
701 width.max(ThumbnailsMode::MIN_SIZE),
702 ))
703 }
704 (GridResize::FixedSize, ThumbZoom::PerRow(_)) => {
705 ThumbZoom::Points(self.side(width, gap).max(ThumbnailsMode::MIN_SIZE))
706 }
707 }
708 }
709
710 #[must_use]
713 pub fn zoomed_in(self, width: f32, gap: f32) -> ThumbZoom {
714 let n = self.shown_per_row(width, gap);
715 ThumbZoom::PerRow(
716 Self::STEPS
717 .iter()
718 .rev()
719 .copied()
720 .find(|&s| s < n)
721 .unwrap_or(1),
722 )
723 }
724
725 #[must_use]
727 pub fn zoomed_out(self, width: f32, gap: f32) -> ThumbZoom {
728 let n = self.shown_per_row(width, gap);
729 let next = Self::STEPS
730 .iter()
731 .copied()
732 .find(|&s| s > n)
733 .unwrap_or_else(|| (n as f32 * 1.25).ceil() as u32);
734 ThumbZoom::PerRow(
735 next.min(Self::most_per_row(width, gap))
736 .clamp(1, Self::MOST),
737 )
738 }
739}
740
741fn fitting(size: f32, width: f32, gap: f32) -> u32 {
744 let n = ((width + gap) / (size + gap)).floor();
745 if n.is_finite() && n >= 1.0 {
746 (n as u32).min(ThumbZoom::MOST)
747 } else {
748 1
749 }
750}
751
752#[derive(Clone, Debug, Default, PartialEq, Eq)]
759pub struct EntryMarks {
760 pub badges: Vec<String>,
762 pub chips: Vec<MarkChip>,
764 pub dimmed: bool,
765}
766
767impl EntryMarks {
768 pub fn label(&self, name: &str) -> String {
771 let mut label = name.to_owned();
772 let mut said: Vec<&str> = Vec::new();
773 for b in self.badges.iter().chain(self.chips.iter().map(|c| &c.name)) {
774 if said.contains(&b.as_str()) {
776 continue;
777 }
778 said.push(b);
779 label.push_str(" · ");
780 label.push_str(b);
781 }
782 label
783 }
784
785 fn is_plain(&self) -> bool {
787 self.badges.is_empty() && self.chips.is_empty()
788 }
789}
790
791#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
794pub enum MarkCorner {
795 TopLeft,
796 #[default]
798 TopRight,
799 BottomRight,
801}
802
803#[derive(Clone, Debug, PartialEq, Eq)]
808pub struct MarkChip {
809 pub icon: Option<String>,
812 pub text: String,
814 pub name: String,
816 pub tone: egui_pop_core::kit::Tone,
817 pub corner: MarkCorner,
818}
819
820impl MarkChip {
821 pub fn icon(icon: impl Into<String>, name: impl Into<String>) -> MarkChip {
823 MarkChip {
824 icon: Some(icon.into()),
825 text: String::new(),
826 name: name.into(),
827 tone: egui_pop_core::kit::Tone::Neutral,
828 corner: MarkCorner::TopRight,
829 }
830 }
831
832 pub fn text(text: impl Into<String>, name: impl Into<String>) -> MarkChip {
834 MarkChip {
835 icon: None,
836 text: text.into(),
837 name: name.into(),
838 tone: egui_pop_core::kit::Tone::Neutral,
839 corner: MarkCorner::BottomRight,
840 }
841 }
842
843 #[must_use]
844 pub fn tone(mut self, tone: egui_pop_core::kit::Tone) -> MarkChip {
845 self.tone = tone;
846 self
847 }
848
849 #[must_use]
850 pub fn corner(mut self, corner: MarkCorner) -> MarkChip {
851 self.corner = corner;
852 self
853 }
854}
855
856pub type MarkEntries = dyn Fn(&SourceEntry) -> EntryMarks + Send + Sync;
858
859#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
861pub enum AgendaLevel {
862 #[default]
863 Day,
864 Month,
865 Year,
866}
867
868impl AgendaLevel {
869 pub const ALL: [AgendaLevel; 3] = [AgendaLevel::Day, AgendaLevel::Month, AgendaLevel::Year];
871
872 pub fn coarser(self) -> Self {
874 match self {
875 AgendaLevel::Day => AgendaLevel::Month,
876 _ => AgendaLevel::Year,
877 }
878 }
879
880 pub fn finer(self) -> Self {
882 match self {
883 AgendaLevel::Year => AgendaLevel::Month,
884 _ => AgendaLevel::Day,
885 }
886 }
887
888 pub fn group(self, day: i64) -> i64 {
891 match self {
892 AgendaLevel::Day => day,
893 AgendaLevel::Month => {
894 let (y, m, _) = civil(day);
895 y * 12 + i64::from(m) - 1
896 }
897 AgendaLevel::Year => civil(day).0,
898 }
899 }
900
901 pub fn heading(self, group: i64) -> String {
903 match self {
904 AgendaLevel::Day => {
905 let (y, m, d) = civil(group);
906 format!("{y:04}-{m:02}-{d:02}")
907 }
908 AgendaLevel::Month => {
909 format!(
910 "{:04}-{:02}",
911 group.div_euclid(12),
912 group.rem_euclid(12) + 1
913 )
914 }
915 AgendaLevel::Year => format!("{group:04}"),
916 }
917 }
918
919 fn label(self) -> &'static strings::StrKey {
920 match self {
921 AgendaLevel::Day => &crate::strings::FILES_AGENDA_DAY,
922 AgendaLevel::Month => &crate::strings::FILES_AGENDA_MONTH,
923 AgendaLevel::Year => &crate::strings::FILES_AGENDA_YEAR,
924 }
925 }
926}
927
928#[derive(Clone, Debug, Default, PartialEq, Eq)]
931pub struct AgendaSettings {
932 pub level: AgendaLevel,
933 pub collapsed: BTreeSet<Option<i64>>,
934}
935
936impl AgendaSettings {
937 pub fn set_level(&mut self, level: AgendaLevel) -> bool {
939 if self.level == level {
940 return false;
941 }
942 self.level = level;
943 self.collapsed.clear();
944 true
945 }
946
947 pub fn set_collapsed(&mut self, group: Option<i64>, collapsed: bool) -> bool {
949 if collapsed {
950 self.collapsed.insert(group)
951 } else {
952 self.collapsed.remove(&group)
953 }
954 }
955}
956
957#[allow(
959 missing_debug_implementations,
960 reason = "borrows trait objects (thumbnails, drawer) that have no Debug"
961)]
962pub struct ModeContext<'a> {
963 pub entries: &'a [SourceEntry],
965 pub selection: &'a Selection,
966 pub focus: Option<usize>,
968 pub thumbnails: &'a dyn ThumbnailProvider,
969 pub settings: &'a mut ModeSettings,
970 pub id: egui::Id,
972 pub reveal_focus: bool,
974 pub max_height: Option<f32>,
976 pub drawer: Option<&'a mut dyn EntryDrawer>,
978 pub name: Option<String>,
982 pub many: bool,
984 pub place: &'a Path,
986 pub ancestors: &'a [Column],
989 pub peek: Option<&'a Column>,
992 pub loading: bool,
994 pub generation: u64,
997 pub marks: Option<&'a MarkEntries>,
999}
1000
1001#[derive(Clone, Debug, Default, PartialEq)]
1003pub struct ModeOutput {
1004 pub clicked: Option<(usize, Modifiers)>,
1005 pub activated: Option<usize>,
1007 pub visible: Range<usize>,
1009 pub focused: Option<egui::Id>,
1012 pub columns: usize,
1014 pub reach: Option<Reach>,
1017 pub pointed: Option<(usize, egui::Rect)>,
1019 pub pointed_beside: Option<(PathBuf, egui::Rect)>,
1022}
1023
1024pub trait ViewMode: Send {
1027 fn describe(&self) -> ModeInfo;
1028
1029 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput;
1030
1031 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize;
1034
1035 fn travel(&self, _key: ModeKey) -> Option<Travel> {
1039 None
1040 }
1041
1042 fn toolbar(&mut self, _ui: &mut Ui, _settings: &mut ModeSettings) -> bool {
1045 false
1046 }
1047
1048 fn own_key(
1052 &mut self,
1053 _key: egui::Key,
1054 _modifiers: Modifiers,
1055 _focus: Option<usize>,
1056 _settings: &mut ModeSettings,
1057 ) -> bool {
1058 false
1059 }
1060}
1061
1062type ModeFactory = Arc<dyn Fn() -> Box<dyn ViewMode> + Send + Sync>;
1063
1064#[derive(Clone)]
1067pub struct ViewModes(Arc<Mutex<Vec<(String, ModeFactory)>>>);
1068
1069impl fmt::Debug for ViewModes {
1070 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1071 f.debug_list().entries(self.ids()).finish()
1072 }
1073}
1074
1075impl Default for ViewModes {
1076 fn default() -> Self {
1077 let modes = ViewModes(Arc::default());
1078 modes
1079 .register("details", Arc::new(|| Box::new(DetailsMode::default())))
1080 .expect("first");
1081 modes
1082 .register(
1083 "thumbnails",
1084 Arc::new(|| Box::new(ThumbnailsMode::default())),
1085 )
1086 .expect("second");
1087 modes
1088 }
1089}
1090
1091impl ViewModes {
1092 pub fn folders() -> Self {
1094 let modes = ViewModes(Arc::default());
1095 modes
1096 .register(MODE_DETAILS, Arc::new(|| Box::new(DetailsMode::default())))
1097 .expect("first");
1098 modes
1099 .register(MODE_COLUMNS, Arc::new(|| Box::new(ColumnsMode::default())))
1100 .expect("second");
1101 modes
1102 }
1103
1104 pub fn built_in() -> Self {
1107 let modes = ViewModes::default();
1108 modes
1109 .register(
1110 MODE_FILMSTRIP,
1111 Arc::new(|| Box::new(FilmstripMode::default())),
1112 )
1113 .expect("built-in");
1114 modes
1115 .register(MODE_COLUMNS, Arc::new(|| Box::new(ColumnsMode::default())))
1116 .expect("built-in");
1117 modes
1118 .register(
1119 MODE_CAROUSEL,
1120 Arc::new(|| Box::new(CarouselMode::default())),
1121 )
1122 .expect("built-in");
1123 modes
1124 .register(MODE_AGENDA, Arc::new(|| Box::new(AgendaMode::default())))
1125 .expect("built-in");
1126 modes
1127 }
1128
1129 pub fn empty() -> Self {
1131 ViewModes(Arc::default())
1132 }
1133
1134 pub fn register(&self, id: &str, factory: ModeFactory) -> Result<(), String> {
1136 let mut modes = lock(&self.0);
1137 if modes.iter().any(|(m, _)| m == id) {
1138 return Err(format!("view mode {id} is registered already"));
1139 }
1140 modes.push((id.to_owned(), factory));
1141 Ok(())
1142 }
1143
1144 pub fn unregister(&self, id: &str) -> bool {
1146 let mut modes = lock(&self.0);
1147 let before = modes.len();
1148 modes.retain(|(m, _)| m != id);
1149 modes.len() != before
1150 }
1151
1152 pub fn ids(&self) -> Vec<String> {
1153 lock(&self.0).iter().map(|(m, _)| m.clone()).collect()
1154 }
1155
1156 pub fn make(&self, id: &str) -> Option<Box<dyn ViewMode>> {
1158 let factory = lock(&self.0)
1159 .iter()
1160 .find(|(m, _)| m == id)
1161 .map(|(_, f)| f.clone())?;
1162 Some(factory())
1163 }
1164}
1165
1166fn human_size(n: u64) -> String {
1171 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
1172 let mut v = n as f64;
1173 let mut u = 0;
1174 while v >= 1000.0 && u < UNITS.len() - 1 {
1175 v /= 1000.0;
1176 u += 1;
1177 }
1178 if u == 0 {
1179 format!("{n} B")
1180 } else {
1181 format!("{v:.1} {}", UNITS[u])
1182 }
1183}
1184
1185fn entry_response(resp: &egui::Response, entry: &SourceEntry, selected: bool) {
1186 let name = entry.name.clone();
1187 resp.widget_info(|| {
1188 egui::WidgetInfo::selected(egui::Role::ListBoxOption, true, selected, &name)
1189 });
1190}
1191
1192fn report(resp: &egui::Response, i: usize, out: &mut ModeOutput) {
1193 if resp.contains_pointer() {
1195 out.pointed = Some((i, resp.rect));
1196 }
1197 if resp.double_clicked() {
1198 out.activated = Some(i);
1199 } else if resp.clicked() {
1200 out.clicked = Some((i, resp.ctx.input(|inp| inp.modifiers)));
1201 }
1202}
1203
1204pub trait EntryDrawer {
1211 fn headers(&mut self, _ui: &mut Ui, _width: f32) {}
1214 fn empty(&mut self, _ui: &mut Ui) {}
1216 fn row_size(&self, ui: &Ui, width: f32) -> egui::Vec2;
1218 fn row(&mut self, ui: &mut Ui, n: usize, size: egui::Vec2) -> egui::Response;
1220 fn cell_size(&self, ui: &Ui, side: f32) -> egui::Vec2;
1222 fn cell(
1224 &mut self,
1225 ui: &mut Ui,
1226 n: usize,
1227 size: egui::Vec2,
1228 thumbnail: ThumbState,
1229 ) -> egui::Response;
1230}
1231
1232#[allow(
1235 missing_debug_implementations,
1236 reason = "borrows the application's marks, a closure without Debug"
1237)]
1238pub struct PlainDrawer<'a> {
1239 pub entries: &'a [SourceEntry],
1240 pub selection: &'a Selection,
1241 pub focus: Option<usize>,
1242 pub marks: Option<&'a MarkEntries>,
1244}
1245
1246impl PlainDrawer<'_> {
1247 pub const FACTS_WIDTH: f32 = 320.0;
1249
1250 fn marks_of(&self, n: usize) -> EntryMarks {
1252 self.marks.map(|m| m(&self.entries[n])).unwrap_or_default()
1253 }
1254
1255 fn folders_only(&self) -> bool {
1258 self.entries.iter().all(SourceEntry::is_dir)
1259 }
1260
1261 fn ring(&self, ui: &Ui, r: &egui::Response, n: usize) {
1263 if self.focus != Some(n) {
1264 return;
1265 }
1266 egui_pop_core::focus::own_ring(ui.ctx(), r.id);
1267 if !egui_pop_core::focus::ring_shown(ui.ctx()) {
1268 return;
1269 }
1270 let t = Tokens::of(ui.ctx());
1271 ui.painter().rect_stroke(
1272 r.rect,
1273 t.radius.widget,
1274 egui::Stroke::new(1.0, t.focus_ring),
1275 egui::StrokeKind::Inside,
1276 );
1277 }
1278}
1279
1280fn shown_name(e: &SourceEntry) -> String {
1283 if e.is_dir() {
1284 format!("{}/", e.name)
1285 } else {
1286 e.name.clone()
1287 }
1288}
1289
1290fn entry_said(facts: &[String]) -> String {
1293 facts.join(", ")
1294}
1295
1296fn as_option(ui: &Ui, r: &egui::Response, said: &str) {
1298 let said = said.to_owned();
1299 ui.ctx().accesskit_node_builder(r.id, |node| {
1300 node.set_role(egui::accesskit::Role::ListBoxOption);
1301 if !said.is_empty() {
1302 node.set_description(said);
1303 }
1304 });
1305}
1306
1307fn mark_indicator(path: &Path, chip: &MarkChip) -> Indicator {
1311 let base = match &chip.icon {
1312 Some(icon) => Indicator::icon(icon.as_str()),
1313 None => Indicator::text(chip.text.as_str()),
1314 };
1315 let said = if chip.icon.is_some() {
1316 chip.name.as_str()
1317 } else {
1318 chip.text.as_str()
1319 };
1320 base.tone(chip.tone)
1321 .overhang(false)
1322 .id(format!("files.badge:{}:{said}", path.display()))
1323 .tooltip(chip.name.clone())
1324}
1325
1326fn mark_chips(marks: &EntryMarks) -> Vec<MarkChip> {
1329 marks
1330 .badges
1331 .iter()
1332 .map(|b| MarkChip::text(b.clone(), b.clone()))
1333 .chain(marks.chips.iter().cloned())
1334 .collect()
1335}
1336
1337fn paint_mark_row(ui: &mut Ui, path: &Path, host: egui::Rect, anchor: Anchor, chips: &[MarkChip]) {
1340 let gap = Tokens::of(ui.ctx()).space.xs;
1341 let mut host = host;
1342 for chip in chips.iter().rev() {
1343 let mark = mark_indicator(path, chip);
1344 let width = mark.measure(ui).x;
1345 if width > host.width() {
1346 break;
1347 }
1348 mark.paint_at(ui, host, anchor);
1349 host.set_right(host.right() - width - gap);
1350 }
1351}
1352
1353fn marks_width(ui: &Ui, path: &Path, chips: &[MarkChip]) -> f32 {
1355 let gap = Tokens::of(ui.ctx()).space.xs;
1356 chips
1357 .iter()
1358 .map(|c| mark_indicator(path, c).measure(ui).x + gap)
1359 .sum()
1360}
1361
1362impl EntryDrawer for PlainDrawer<'_> {
1363 fn row_size(&self, ui: &Ui, width: f32) -> egui::Vec2 {
1364 egui::vec2(width, row_height(ui))
1365 }
1366
1367 fn row(&mut self, ui: &mut Ui, n: usize, size: egui::Vec2) -> egui::Response {
1368 let e = &self.entries[n];
1369 let marks = self.marks_of(n);
1370 let selected = self.selection.contains(&e.path);
1371 if size.x < Self::FACTS_WIDTH {
1373 let (rect, resp) = ui.allocate_exact_size(size, egui::Sense::click());
1374 let visuals = ui.visuals();
1375 if selected {
1376 ui.painter()
1377 .rect_filled(rect, 2.0, visuals.selection.bg_fill);
1378 } else if resp.hovered() {
1379 ui.painter()
1380 .rect_filled(rect, 2.0, visuals.widgets.hovered.weak_bg_fill);
1381 }
1382 let text = if selected {
1383 visuals.selection.stroke.color
1384 } else if marks.dimmed {
1385 visuals.weak_text_color()
1386 } else {
1387 visuals.text_color()
1388 };
1389 paint_row_name(ui, rect, e, text);
1390 let name = marks.label(&e.name);
1391 resp.widget_info(|| {
1392 egui::WidgetInfo::selected(egui::Role::ListBoxOption, true, selected, &name)
1393 });
1394 as_option(ui, &resp, "");
1395 self.ring(ui, &resp, n);
1396 return resp;
1397 }
1398 let t = Tokens::of(ui.ctx());
1399 let label = shown_name(e);
1400 let columns = list_columns(ui, size.x, self.folders_only());
1401 let height = row_height(ui) - 2.0 * ui.spacing().button_padding.y;
1402 let name_column = columns.first().map_or(0.0, |c| c.width);
1403 let chips = mark_chips(&marks);
1406 let marks_room = marks_width(ui, &e.path, &chips).min(name_column / 2.0);
1407 let reserved = if chips.is_empty() {
1408 0.0
1409 } else {
1410 marks_room + t.space.m
1411 };
1412 let mut atoms = egui::Atoms::default();
1413 let mut facts = Vec::new();
1414 let weak = marks.dimmed && !selected;
1415 for c in &columns {
1416 let (text, align) = match c.column {
1417 SortColumn::Name => {
1418 let width = (c.width - reserved).max(0.0);
1419 let text = if weak {
1420 egui::RichText::new(label.clone()).weak()
1421 } else {
1422 egui::RichText::new(label.clone())
1423 };
1424 atoms.push_right(
1425 text.atom_max_width(width)
1426 .atom_size(egui::vec2(width, height))
1427 .atom_align(egui::Align2::LEFT_CENTER),
1428 );
1429 if !chips.is_empty() {
1430 atoms.push_right(String::new().atom_size(egui::vec2(marks_room, height)));
1433 }
1434 continue;
1435 }
1436 column => {
1437 let fact = fact_text(ui.ctx(), e, column);
1438 if !fact.is_empty() {
1439 facts.push(fact.clone());
1440 }
1441 let align = if column == SortColumn::Size {
1442 egui::Align2::RIGHT_CENTER
1443 } else {
1444 egui::Align2::LEFT_CENTER
1445 };
1446 (fact, align)
1447 }
1448 };
1449 atoms.push_right(
1450 text.atom_max_width(c.width)
1451 .atom_size(egui::vec2(c.width, height))
1452 .atom_align(align),
1453 );
1454 }
1455 let font = egui::TextStyle::Body.resolve(ui.style());
1456 let cut = ui
1457 .painter()
1458 .layout_no_wrap(label.clone(), font, egui::Color32::PLACEHOLDER)
1459 .size()
1460 .x
1461 > name_column - reserved;
1462 let r = ui
1464 .push_id(&e.path, |ui| {
1465 ui.spacing_mut().icon_spacing = t.space.m;
1466 ui.with_layout(egui::Layout::top_down_justified(egui::Align::Min), |ui| {
1467 ui.add(widgets::SelectableRow::new(selected, atoms).name(marks.label(&e.name)))
1468 })
1469 .inner
1470 })
1471 .inner;
1472 as_option(ui, &r, &entry_said(&facts));
1473 if let Some(c) = columns.first().filter(|_| !chips.is_empty()) {
1474 let left = r.rect.left() + c.left;
1475 let host = egui::Rect::from_x_y_ranges(left..=left + c.width, r.rect.y_range());
1476 paint_mark_row(ui, &e.path, host, Anchor::End, &chips);
1477 }
1478 self.ring(ui, &r, n);
1479 if cut { r.on_hover_text(label) } else { r }
1480 }
1481
1482 fn cell_size(&self, ui: &Ui, side: f32) -> egui::Vec2 {
1483 egui::vec2(side, side + thumbnail::caption_height(ui))
1484 }
1485
1486 fn cell(
1487 &mut self,
1488 ui: &mut Ui,
1489 n: usize,
1490 size: egui::Vec2,
1491 thumbnail: ThumbState,
1492 ) -> egui::Response {
1493 let e = &self.entries[n];
1494 let marks = self.marks_of(n);
1495 let selected = self.selection.contains(&e.path);
1496 let mut cell = Thumbnail::new(marks.label(&e.name))
1497 .caption(e.name.as_str())
1498 .size(size)
1499 .selected(selected);
1500 let mut failed = None;
1501 cell = match thumbnail {
1502 _ if e.is_dir() => cell.icon(Icon::Folder),
1503 ThumbState::Ready(t) => {
1504 let [w, h] = t.size();
1505 cell.image(t.id(), [w as u32, h as u32])
1506 }
1507 ThumbState::Loading => cell.placeholder(SkeletonTokens::of(ui.ctx()).fill),
1508 ThumbState::None => cell.icon(Icon::File),
1509 ThumbState::Failed(why) => {
1510 failed = Some(why);
1511 cell.icon(Icon::Warning)
1512 }
1513 };
1514 let r = ui.push_id(&e.path, |ui| ui.add(cell)).inner;
1516 as_option(ui, &r, "");
1517 if marks.dimmed {
1518 let t = Tokens::of(ui.ctx());
1519 ui.painter().rect_filled(
1520 r.rect,
1521 t.radius.widget,
1522 ui.visuals().extreme_bg_color.gamma_multiply(0.6),
1523 );
1524 }
1525 let host = r.rect.shrink(Tokens::of(ui.ctx()).space.xs);
1526 let chips = mark_chips(&marks);
1527 if !chips.is_empty() {
1528 paint_mark_row(ui, &e.path, host, Anchor::TopEnd, &chips);
1529 }
1530 self.ring(ui, &r, n);
1531 match failed {
1532 Some(why) => r.on_hover_text(why),
1533 None => r,
1534 }
1535 }
1536}
1537
1538#[derive(Clone, Copy, Debug, PartialEq)]
1544pub(crate) struct ListColumn {
1545 pub(crate) column: SortColumn,
1546 pub(crate) left: f32,
1548 pub(crate) width: f32,
1549}
1550
1551pub(crate) fn row_height(ui: &Ui) -> f32 {
1553 let text = ui.text_style_height(&egui::TextStyle::Body);
1554 ui.spacing()
1555 .interact_size
1556 .y
1557 .max(text + 2.0 * ui.spacing().button_padding.y)
1558}
1559
1560pub(crate) fn fit_columns(
1565 room: f32,
1566 gap: f32,
1567 padding: f32,
1568 wanted: &[(SortColumn, f32)],
1569) -> Vec<ListColumn> {
1570 let mut kept = wanted.len();
1571 let name_width = loop {
1572 let others: f32 = wanted[..kept].iter().map(|(_, w)| w + gap).sum();
1573 let name = room - 2.0 * padding - others;
1574 if name >= super::NAME_MIN_WIDTH || kept == 0 {
1575 break name.max(0.0);
1576 }
1577 kept -= 1;
1578 };
1579 let mut out = vec![ListColumn {
1580 column: SortColumn::Name,
1581 left: padding,
1582 width: name_width,
1583 }];
1584 let mut left = padding + name_width + gap;
1585 for &(column, width) in &wanted[..kept] {
1586 out.push(ListColumn {
1587 column,
1588 left,
1589 width,
1590 });
1591 left += width + gap;
1592 }
1593 out
1594}
1595
1596pub(crate) fn list_columns(ui: &Ui, width: f32, folders_only: bool) -> Vec<ListColumn> {
1599 let ctx = ui.ctx();
1600 let font = egui::TextStyle::Body.resolve(ui.style());
1601 let measure = |text: String| {
1602 ui.painter()
1603 .layout_no_wrap(text, font.clone(), egui::Color32::PLACEHOLDER)
1604 .size()
1605 };
1606 let inset = header_inset(ui, &Kit::of(ctx), &font);
1607 let wanted = |column: SortColumn, sample: &str| {
1608 let title = measure(strings::tr(ctx, column.title()));
1609 let header = title.x + title.y * 1.25 + inset;
1611 (column, measure(sample.to_string()).x.max(header).ceil())
1612 };
1613 let folder = strings::tr(ctx, &crate::strings::FILES_KIND_FOLDER);
1614 let mut columns = vec![wanted(SortColumn::Modified, "0000-00-00 00:00 UTC")];
1615 if !folders_only {
1616 columns.push(wanted(SortColumn::Size, "999 MB"));
1617 columns.push(wanted(SortColumn::Type, &folder));
1618 }
1619 let gap = Tokens::of(ctx).space.m;
1620 fit_columns(width, gap, ui.spacing().button_padding.x, &columns)
1621}
1622
1623fn header_inset(ui: &Ui, kit: &Kit, font: &egui::FontId) -> f32 {
1625 let galley =
1626 ui.painter()
1627 .layout_no_wrap("A".to_string(), font.clone(), egui::Color32::PLACEHOLDER);
1628 let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 40.0));
1629 let part = egui_pop_core::kit::Part {
1630 rect,
1631 room: rect,
1632 state: egui_pop_core::kit::State::REST,
1633 label: Some(&galley),
1634 };
1635 kit.table_header_cell
1636 .label_rect(&part, galley.size())
1637 .left()
1638}
1639
1640fn fact_text(ctx: &egui::Context, e: &SourceEntry, column: SortColumn) -> String {
1643 match column {
1644 SortColumn::Name => e.name.clone(),
1645 SortColumn::Size if e.is_dir() => String::new(),
1646 SortColumn::Size => e.size.map_or_else(String::new, super::preview::size_text),
1647 SortColumn::Modified => e
1648 .modified
1649 .map_or_else(String::new, super::preview::time_text),
1650 SortColumn::Taken => e
1651 .taken
1652 .or(e.modified)
1653 .map_or_else(String::new, super::preview::time_text),
1654 SortColumn::Type if e.is_dir() => strings::tr(ctx, &crate::strings::FILES_KIND_FOLDER),
1655 SortColumn::Type => match e.name.rfind('.').filter(|&dot| dot > 0) {
1656 Some(dot) => e.name[dot + 1..].to_uppercase(),
1657 None => strings::tr(ctx, &crate::strings::FILES_KIND_FILE),
1658 },
1659 }
1660}
1661
1662pub(crate) fn sort_headers(
1667 ui: &mut Ui,
1668 columns: &[ListColumn],
1669 width: f32,
1670 sort: PickerSort,
1671 ranked: bool,
1672) -> Option<PickerSort> {
1673 let ctx = ui.ctx().clone();
1674 let height = row_height(ui);
1675 let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
1676 let kit = Kit::of(&ctx);
1677 let font = egui::TextStyle::Body.resolve(ui.style());
1678 let inset = header_inset(ui, &kit, &font);
1679 let mut clicked = None;
1680 ui.add_enabled_ui(!ranked, |ui| {
1681 for (n, c) in columns.iter().enumerate() {
1682 let left = (rect.left() + c.left - inset).max(rect.left());
1683 let right = columns
1684 .get(n + 1)
1685 .map_or(rect.right(), |next| rect.left() + next.left - inset);
1686 let at = egui::Rect::from_min_max(
1687 egui::pos2(left, rect.top()),
1688 egui::pos2(right, rect.bottom()),
1689 );
1690 let title = strings::tr(&ctx, c.column.title());
1691 let descending = (!ranked && sort.column == c.column).then_some(sort.descending);
1692 let name = match descending {
1693 Some(true) => strings::tr_args(
1694 &ctx,
1695 &crate::strings::FILES_SORTED_DOWN,
1696 &[("column", &title)],
1697 ),
1698 Some(false) => strings::tr_args(
1699 &ctx,
1700 &crate::strings::FILES_SORTED_UP,
1701 &[("column", &title)],
1702 ),
1703 None => title.clone(),
1704 };
1705 let id = ui
1706 .scope_id()
1707 .with("egui_pop.files.header")
1708 .with(c.column.as_str());
1709 let r = widgets::SortHeader {
1710 title: &title,
1711 name: &name,
1712 descending,
1713 sortable: true,
1714 }
1715 .show(ui, &kit, at, id)
1716 .on_disabled_hover_text(strings::tr(&ctx, &crate::strings::FILES_SORT_RANKED));
1717 if r.clicked() {
1718 clicked = Some(sort.click(c.column));
1719 }
1720 }
1721 });
1722 clicked
1723}
1724
1725pub fn paint_marks(ui: &Ui, rect: egui::Rect, marks: &EntryMarks) -> Vec<egui::Rect> {
1729 if !marks.dimmed && marks.is_plain() {
1730 return Vec::new();
1731 }
1732 let visuals = ui.visuals();
1733 let caption = ui.text_style_height(&egui::TextStyle::Small) + 4.0;
1734 let side = (rect.width() - 8.0)
1735 .min(rect.height() - caption - 8.0)
1736 .max(1.0);
1737 let image = egui::Rect::from_min_size(rect.min + egui::vec2(4.0, 4.0), egui::vec2(side, side));
1738 let painter = ui.painter().with_clip_rect(rect);
1739 if marks.dimmed {
1740 painter.rect_filled(image, 4.0, visuals.extreme_bg_color.gamma_multiply(0.6));
1741 }
1742 let font = egui::TextStyle::Small.resolve(ui.style());
1743 let mut bottom = image.bottom() - 4.0;
1744 for badge in &marks.badges {
1745 let galley =
1746 painter.layout_no_wrap(badge.clone(), font.clone(), visuals.strong_text_color());
1747 let at = egui::pos2(image.left() + 4.0, bottom - galley.size().y);
1748 painter.rect_filled(
1749 egui::Rect::from_min_size(at, galley.size()).expand(2.0),
1750 2.0,
1751 visuals.widgets.inactive.bg_fill,
1752 );
1753 bottom = at.y - 4.0;
1754 painter.galley(at, galley, visuals.strong_text_color());
1755 }
1756 paint_chips(&painter, image, &marks.chips, font)
1757}
1758
1759fn paint_chips(
1762 painter: &egui::Painter,
1763 image: egui::Rect,
1764 chips: &[MarkChip],
1765 font: egui::FontId,
1766) -> Vec<egui::Rect> {
1767 use egui_pop_core::kit::{Kit, KitCx, Part, State};
1768 if chips.is_empty() {
1769 return Vec::new();
1770 }
1771 let kit = Kit::of(painter.ctx());
1772 let cx = KitCx {
1773 painter,
1774 ppp: painter.ctx().pixels_per_point(),
1775 };
1776 let glyph = font.size;
1777 let pad = 4.0;
1778 let mut ends = [0.0f32; 3];
1780 let mut rects = Vec::with_capacity(chips.len());
1781 for chip in chips {
1782 let state = State::REST.toned(chip.tone);
1783 let galley = chip.icon.is_none().then(|| {
1784 painter.layout_no_wrap(chip.text.clone(), font.clone(), egui::Color32::PLACEHOLDER)
1785 });
1786 let inner = galley
1787 .as_ref()
1788 .map_or(egui::vec2(glyph, glyph), |g| g.size());
1789 let size = kit.pill.measure(inner);
1790 let (slot, anchor, at) = match chip.corner {
1791 MarkCorner::TopLeft => (
1792 0,
1793 egui::Align2::LEFT_TOP,
1794 image.left_top() + egui::vec2(pad, pad),
1795 ),
1796 MarkCorner::TopRight => (
1797 1,
1798 egui::Align2::RIGHT_TOP,
1799 image.right_top() + egui::vec2(-pad, pad),
1800 ),
1801 MarkCorner::BottomRight => (
1802 2,
1803 egui::Align2::RIGHT_BOTTOM,
1804 image.right_bottom() - egui::vec2(pad, pad),
1805 ),
1806 };
1807 let shift = if chip.corner == MarkCorner::TopLeft {
1808 ends[slot]
1809 } else {
1810 -ends[slot]
1811 };
1812 let r = anchor.anchor_size(at + egui::vec2(shift, 0.0), size);
1813 ends[slot] += size.x + 3.0;
1814 let part = Part {
1815 rect: r,
1816 room: r,
1817 state,
1818 label: galley.as_ref(),
1819 };
1820 kit.pill.paint_part(&cx, &part);
1821 if let Some(icon) = &chip.icon {
1822 let colour = kit.pill.style(state).text;
1823 egui_pop_core::icon::registry::resolve(icon, "files.marks")
1824 .unwrap_or(egui_pop_core::icon::PLACEHOLDER)
1825 .paint(
1826 painter,
1827 egui::Rect::from_center_size(r.center(), egui::vec2(glyph, glyph)),
1828 colour,
1829 );
1830 }
1831 rects.push(r);
1832 }
1833 rects
1834}
1835
1836pub fn paint_cell(ui: &Ui, rect: egui::Rect, e: &SourceEntry, thumbnail: ThumbState) {
1838 let visuals = ui.visuals();
1839 let caption = ui.text_style_height(&egui::TextStyle::Small) + 4.0;
1840 let side = (rect.width() - 8.0)
1841 .min(rect.height() - caption - 8.0)
1842 .max(1.0);
1843 let image = egui::Rect::from_min_size(rect.min + egui::vec2(4.0, 4.0), egui::vec2(side, side));
1844 match thumbnail {
1845 ThumbState::Ready(t) => {
1846 let s = t.size_vec2();
1847 let scale = (side / s.x.max(s.y)).min(1.0);
1848 let r = egui::Rect::from_center_size(image.center(), s * scale);
1849 ui.painter().image(
1850 t.id(),
1851 r,
1852 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
1853 egui::Color32::WHITE,
1854 );
1855 }
1856 other => {
1857 let glyph = match other {
1858 _ if e.is_dir() => "Folder",
1859 ThumbState::Failed(_) => "!",
1860 ThumbState::Loading => "...",
1861 _ => "File",
1862 };
1863 ui.painter()
1864 .rect_filled(image, 4.0, visuals.extreme_bg_color);
1865 ui.painter().text(
1866 image.center(),
1867 egui::Align2::CENTER_CENTER,
1868 glyph,
1869 egui::FontId::proportional(side * 0.15),
1870 visuals.weak_text_color(),
1871 );
1872 }
1873 }
1874 ui.painter().with_clip_rect(rect).text(
1875 egui::pos2(rect.center().x, image.bottom() + 2.0 + caption / 2.0),
1876 egui::Align2::CENTER_CENTER,
1877 &e.name,
1878 egui::TextStyle::Small.resolve(ui.style()),
1879 visuals.text_color(),
1880 );
1881}
1882
1883#[allow(
1889 clippy::too_many_arguments,
1890 reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1891)]
1892fn lay_out(
1893 ui: &mut Ui,
1894 band: Option<egui::Id>,
1895 container: Option<(&str, bool)>,
1896 drawer: &mut dyn EntryDrawer,
1897 salt: egui::Id,
1898 count: usize,
1899 cell: egui::Vec2,
1900 max_height: Option<f32>,
1901 reveal: Option<usize>,
1902 focus: Option<usize>,
1903 out: &mut ModeOutput,
1904 mut draw: impl FnMut(&mut dyn EntryDrawer, &mut Ui, usize) -> egui::Response,
1905) -> usize {
1906 let mut grid = ThumbnailGrid::new(count, cell)
1907 .id_salt(salt)
1908 .reveal(reveal)
1909 .rubber_band(band.is_some());
1910 if let Some(h) = max_height {
1911 grid = grid.max_height(h);
1912 }
1913 let mut first = usize::MAX;
1914 let mut end = 0;
1915 let mut columns = 1;
1916 let mut add = |ui: &mut Ui, out: &mut ModeOutput| {
1917 if count == 0 {
1918 drawer.empty(ui);
1919 }
1920 let shown = grid.clone().show_with_band(ui, |ui, n| {
1921 let r = draw(&mut *drawer, ui, n);
1922 if focus == Some(n) {
1923 out.focused = Some(r.id);
1924 }
1925 report(&r, n, out);
1926 first = first.min(n);
1927 end = end.max(n + 1);
1928 });
1929 columns = shown.per_row;
1930 if let (Some(key), Some(told)) = (band, shown.band) {
1931 ui.ctx().data_mut(|d| d.insert_temp(key, told));
1932 }
1933 };
1934 in_container(ui, container, out, &mut add);
1935 out.visible = if first == usize::MAX {
1936 0..0
1937 } else {
1938 first..end
1939 };
1940 columns.max(1)
1941}
1942
1943pub(crate) fn take_band(ctx: &egui::Context, id: egui::Id) -> Option<Band> {
1947 ctx.data_mut(|d| {
1948 let key = band_key(id);
1949 let band = d.get_temp::<Band>(key);
1950 d.remove::<Band>(key);
1951 band
1952 })
1953}
1954
1955fn band_key(id: egui::Id) -> egui::Id {
1958 id.with("egui_pop.file_browser.band")
1959}
1960
1961fn in_container(
1964 ui: &mut Ui,
1965 container: Option<(&str, bool)>,
1966 out: &mut ModeOutput,
1967 add: &mut dyn FnMut(&mut Ui, &mut ModeOutput),
1968) {
1969 match container {
1970 Some((name, many)) => {
1971 ui.scope_builder(
1972 egui::UiBuilder::new()
1973 .accessibility_role(egui::accesskit::Role::ListBox)
1974 .accessibility_label(name),
1975 |ui| {
1976 add(ui, out);
1977 let current = out.focused;
1978 ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
1979 if many {
1980 node.set_multiselectable();
1981 }
1982 if let Some(id) = current {
1983 node.set_active_descendant(id.accesskit_id());
1984 }
1985 });
1986 },
1987 );
1988 }
1989 None => add(ui, out),
1990 }
1991}
1992
1993#[derive(Clone, Debug, Default)]
1995pub struct DetailsMode {
1996 rows_in_view: usize,
1997}
1998
1999impl DetailsMode {
2000 pub const ROW_HEIGHT: f32 = 20.0;
2001}
2002
2003impl ViewMode for DetailsMode {
2004 fn describe(&self) -> ModeInfo {
2005 ModeInfo {
2006 id: "details".into(),
2007 label: "Details".into(),
2008 icon: "phosphor:list".into(),
2009 keys: vec![
2010 ("Up, Down".into(), "Previous, next entry".into()),
2011 ("Page Up, Page Down".into(), "A page up or down".into()),
2012 ("Home, End".into(), "First, last entry".into()),
2013 ],
2014 gestures: vec!["Wheel: scroll".into()],
2015 persist: "details".into(),
2016 role: egui::Role::ListBox,
2017 needs: ModeNeeds::default(),
2018 }
2019 }
2020
2021 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
2022 let mut out = ModeOutput::default();
2023 let mut plain = PlainDrawer {
2024 entries: cx.entries,
2025 selection: cx.selection,
2026 focus: cx.focus,
2027 marks: cx.marks,
2028 };
2029 let drawer: &mut dyn EntryDrawer = match cx.drawer {
2030 Some(d) => d,
2031 None => &mut plain,
2032 };
2033 let width = ui.available_width();
2034 drawer.headers(ui, width);
2035 let n = cx.entries.len();
2036 let size = drawer.row_size(ui, width - ui.spacing().scroll.allocated_width());
2037 let reveal = cx.focus.filter(|_| cx.reveal_focus && n > 0);
2038 lay_out(
2039 ui,
2040 None,
2041 cx.name.as_deref().map(|n| (n, cx.many)),
2042 drawer,
2043 cx.id.with("details"),
2044 n,
2045 size,
2046 cx.max_height,
2047 reveal,
2048 cx.focus,
2049 &mut out,
2050 |d, ui, i| d.row(ui, i, size),
2051 );
2052 self.rows_in_view = out.visible.len().max(1);
2053 out.columns = 1;
2054 out
2055 }
2056
2057 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
2058 let last = count.saturating_sub(1);
2059 let page = self.rows_in_view.max(1);
2060 match key {
2061 ModeKey::Up | ModeKey::Left => from.saturating_sub(1),
2062 ModeKey::Down | ModeKey::Right => (from + 1).min(last),
2063 ModeKey::PageUp => from.saturating_sub(page),
2064 ModeKey::PageDown => (from + page).min(last),
2065 ModeKey::Home => 0,
2066 ModeKey::End => last,
2067 }
2068 }
2069}
2070
2071fn civil(z: i64) -> (i64, u32, u32) {
2073 let z = z + 719_468;
2074 let era = z.div_euclid(146_097);
2075 let doe = z.rem_euclid(146_097);
2076 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
2077 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2078 let mp = (5 * doy + 2) / 153;
2079 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
2080 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
2081 (yoe + era * 400 + i64::from(m <= 2), m, d)
2082}
2083
2084#[derive(Clone, Debug, Default)]
2088pub struct ThumbnailsMode {
2089 columns: usize,
2090 rows_in_view: usize,
2091}
2092
2093impl ThumbnailsMode {
2094 pub const MIN_SIZE: f32 = 64.0;
2096 pub const MAX_SIZE: f32 = 256.0;
2099}
2100
2101impl ViewMode for ThumbnailsMode {
2102 fn describe(&self) -> ModeInfo {
2103 ModeInfo {
2104 id: "thumbnails".into(),
2105 label: "Thumbnails".into(),
2106 icon: "phosphor:squares-four".into(),
2107 keys: vec![
2108 ("Arrows".into(), "Move in the grid".into()),
2109 ("Page Up, Page Down".into(), "A page up or down".into()),
2110 ("Home, End".into(), "First, last entry".into()),
2111 ],
2112 gestures: vec!["Wheel: scroll".into()],
2113 persist: "thumbnails".into(),
2114 role: egui::Role::ListBox,
2115 needs: ModeNeeds {
2116 thumbnails: true,
2117 ..ModeNeeds::default()
2118 },
2119 }
2120 }
2121
2122 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
2123 let mut out = ModeOutput::default();
2124 let side = cx.settings.thumbnail_size.max(Self::MIN_SIZE);
2126 let mut plain = PlainDrawer {
2127 entries: cx.entries,
2128 selection: cx.selection,
2129 focus: cx.focus,
2130 marks: cx.marks,
2131 };
2132 let drawer: &mut dyn EntryDrawer = match cx.drawer {
2133 Some(d) => d,
2134 None => &mut plain,
2135 };
2136 let width = ui.available_width();
2137 drawer.headers(ui, width);
2138 let n = cx.entries.len();
2139 let cell = drawer.cell_size(ui, side);
2140 let pixels = (side * ui.ctx().pixels_per_point()).round() as u32;
2141 let ctx = ui.ctx().clone();
2142 let thumbnails = cx.thumbnails;
2143 let entries = cx.entries;
2144 let ask = |i: usize, priority| {
2145 thumbnails.request(
2146 &ctx,
2147 &ThumbRequest {
2148 entry: &entries[i],
2149 size: pixels,
2150 priority,
2151 },
2152 )
2153 };
2154 let reveal = cx.focus.filter(|_| cx.reveal_focus && n > 0);
2155 let columns = lay_out(
2156 ui,
2157 Some(band_key(cx.id)),
2158 cx.name.as_deref().map(|n| (n, cx.many)),
2159 drawer,
2160 cx.id.with("thumbnails"),
2161 n,
2162 cell,
2163 cx.max_height,
2164 reveal,
2165 cx.focus,
2166 &mut out,
2167 |d, ui, i| d.cell(ui, i, cell, ask(i, Priority::Visible)),
2169 );
2170 let end = out.visible.end;
2172 for i in end..(end + columns).min(n) {
2173 ask(i, Priority::Near);
2174 }
2175 self.columns = columns;
2176 self.rows_in_view = out.visible.len().div_ceil(columns).max(1);
2177 out.columns = columns;
2178 out
2179 }
2180
2181 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
2182 let last = count.saturating_sub(1);
2183 let c = self.columns.max(1);
2184 let page = c * self.rows_in_view.max(1);
2185 match key {
2186 ModeKey::Left => from.saturating_sub(1),
2187 ModeKey::Right => (from + 1).min(last),
2188 ModeKey::Up if from >= c => from - c,
2189 ModeKey::Up => from,
2190 ModeKey::Down if from + c <= last => from + c,
2191 ModeKey::Down if from / c < last / c => last,
2193 ModeKey::Down => from,
2194 ModeKey::PageUp => from.saturating_sub(page),
2195 ModeKey::PageDown => (from + page).min(last),
2196 ModeKey::Home => 0,
2197 ModeKey::End => last,
2198 }
2199 }
2200}
2201
2202#[derive(Clone, Debug, Default)]
2207pub struct ColumnsMode {
2208 rows_in_view: usize,
2209}
2210
2211impl ColumnsMode {
2212 pub const COLUMN_WIDTH: f32 = 200.0;
2214
2215 fn side(
2219 ui: &mut Ui,
2220 column: &Column,
2221 height: f32,
2222 salt: egui::Id,
2223 out: &mut ModeOutput,
2224 ) -> Option<PathBuf> {
2225 let mut clicked = None;
2226 let name = column.place.file_name().map_or_else(
2227 || column.place.display().to_string(),
2228 |n| n.to_string_lossy().into_owned(),
2229 );
2230 ui.scope_builder(
2231 egui::UiBuilder::new()
2232 .accessibility_role(egui::accesskit::Role::ListBox)
2233 .accessibility_label(name),
2234 |ui| {
2235 egui::ScrollArea::vertical()
2236 .id_salt(salt)
2237 .max_height(height)
2238 .auto_shrink([false, false])
2239 .show_rows(
2240 ui,
2241 DetailsMode::ROW_HEIGHT,
2242 column.entries.len() + usize::from(column.loading),
2243 |ui, range| {
2244 for i in range {
2245 let Some(e) = column.entries.get(i) else {
2246 busy_row(ui);
2247 continue;
2248 };
2249 let on = column.open == Some(i);
2250 let (rect, resp) = ui.allocate_exact_size(
2251 egui::vec2(ui.available_width(), DetailsMode::ROW_HEIGHT),
2252 egui::Sense::click(),
2253 );
2254 entry_response(&resp, e, on);
2255 let visuals = ui.visuals();
2256 if on {
2257 ui.painter().rect_filled(
2258 rect,
2259 2.0,
2260 visuals.widgets.active.weak_bg_fill,
2261 );
2262 } else if resp.hovered() {
2263 ui.painter().rect_filled(
2264 rect,
2265 2.0,
2266 visuals.widgets.hovered.weak_bg_fill,
2267 );
2268 }
2269 paint_row_name(ui, rect, e, visuals.text_color());
2270 if resp.contains_pointer() && e.is_dir() {
2271 out.pointed_beside = Some((e.path.clone(), rect));
2272 }
2273 if resp.clicked() {
2274 clicked = Some(e.path.clone());
2275 }
2276 }
2277 },
2278 );
2279 },
2280 );
2281 clicked
2282 }
2283}
2284
2285fn busy_row(ui: &mut Ui) {
2288 let text = strings::tr(ui.ctx(), &crate::strings::FILES_LISTING);
2289 let (rect, resp) = ui.allocate_exact_size(
2290 egui::vec2(ui.available_width(), DetailsMode::ROW_HEIGHT),
2291 egui::Sense::hover(),
2292 );
2293 let name = text.clone();
2294 resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ProgressIndicator, true, &name));
2295 let side = DetailsMode::ROW_HEIGHT - 6.0;
2296 let spinner = egui::Rect::from_center_size(
2297 egui::pos2(rect.left() + 4.0 + side / 2.0, rect.center().y),
2298 egui::vec2(side, side),
2299 );
2300 egui::Spinner::new().size(side).paint_at(ui, spinner);
2301 ui.painter().text(
2302 egui::pos2(spinner.right() + 6.0, rect.center().y),
2303 egui::Align2::LEFT_CENTER,
2304 text,
2305 egui::TextStyle::Body.resolve(ui.style()),
2306 ui.visuals().weak_text_color(),
2307 );
2308}
2309
2310fn paint_row_name(ui: &Ui, rect: egui::Rect, e: &SourceEntry, color: egui::Color32) {
2312 let font = egui::TextStyle::Body.resolve(ui.style());
2313 let y = rect.center().y;
2314 let chevron = 14.0;
2315 ui.painter()
2316 .with_clip_rect(rect.with_max_x(rect.right() - chevron))
2317 .text(
2318 egui::pos2(rect.left() + 4.0, y),
2319 egui::Align2::LEFT_CENTER,
2320 &e.name,
2321 font.clone(),
2322 color,
2323 );
2324 if e.is_dir() {
2325 ui.painter().text(
2326 egui::pos2(rect.right() - 4.0, y),
2327 egui::Align2::RIGHT_CENTER,
2328 ">",
2329 font,
2330 color,
2331 );
2332 }
2333}
2334
2335impl ViewMode for ColumnsMode {
2336 fn describe(&self) -> ModeInfo {
2337 ModeInfo {
2338 id: MODE_COLUMNS.into(),
2339 label: "Columns".into(),
2340 icon: "phosphor:columns".into(),
2341 keys: vec![
2342 ("Up, Down".into(), "Previous, next entry".into()),
2343 ("Right".into(), "Into the folder".into()),
2344 ("Left".into(), "Back to the parent".into()),
2345 ],
2346 gestures: vec!["Wheel: scroll".into()],
2347 persist: MODE_COLUMNS.into(),
2348 role: egui::Role::ListBox,
2349 needs: ModeNeeds {
2352 hierarchy: true,
2353 ..ModeNeeds::default()
2354 },
2355 }
2356 }
2357
2358 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
2359 let mut out = ModeOutput::default();
2360 let w = Self::COLUMN_WIDTH;
2361 let height = cx
2362 .max_height
2363 .unwrap_or_else(|| ui.available_height())
2364 .max(DetailsMode::ROW_HEIGHT * 3.0);
2365 let mut plain = PlainDrawer {
2366 entries: cx.entries,
2367 selection: cx.selection,
2368 focus: cx.focus,
2369 marks: cx.marks,
2370 };
2371 let drawer: &mut dyn EntryDrawer = match cx.drawer {
2372 Some(d) => d,
2373 None => &mut plain,
2374 };
2375 let n = cx.entries.len();
2376 let reveal = cx.focus.filter(|_| cx.reveal_focus && n > 0);
2377 let reveal_column = cx.reveal_focus;
2378 let ctx = ui.ctx().clone();
2379 let thumbnails = cx.thumbnails;
2380 let focused = cx.focus.and_then(|i| cx.entries.get(i));
2381 let busy = if cx.loading {
2383 DetailsMode::ROW_HEIGHT
2384 } else {
2385 0.0
2386 };
2387 egui::ScrollArea::horizontal()
2388 .id_salt(cx.id.with("columns"))
2389 .auto_shrink([false, true])
2390 .show(ui, |ui| {
2391 ui.horizontal_top(|ui| {
2392 let column = |ui: &mut Ui, add: &mut dyn FnMut(&mut Ui)| {
2393 ui.allocate_ui_with_layout(
2394 egui::vec2(w, height),
2395 egui::Layout::top_down(egui::Align::Min),
2396 |ui| {
2397 ui.set_width(w);
2398 ui.set_min_height(height);
2399 add(ui);
2400 },
2401 )
2402 .response
2403 };
2404 for (k, a) in cx.ancestors.iter().enumerate() {
2405 column(ui, &mut |ui| {
2406 if let Some(p) =
2407 Self::side(ui, a, height, cx.id.with(("ancestor", k)), &mut out)
2408 {
2409 out.reach = Some(Reach {
2410 place: a.place.clone(),
2411 focus: Some(p),
2412 });
2413 }
2414 });
2415 ui.separator();
2416 }
2417 let here = column(ui, &mut |ui| {
2418 let size = drawer.row_size(ui, w - ui.spacing().scroll.allocated_width());
2419 lay_out(
2420 ui,
2421 None,
2422 cx.name.as_deref().map(|n| (n, cx.many)),
2423 &mut *drawer,
2424 cx.id.with("columns.here"),
2425 n,
2426 size,
2427 Some(height - busy),
2428 reveal,
2429 cx.focus,
2430 &mut out,
2431 |d, ui, i| d.row(ui, i, size),
2432 );
2433 if cx.loading {
2435 busy_row(ui);
2436 }
2437 });
2438 if let Some(f) = focused {
2439 ui.separator();
2440 column(ui, &mut |ui| match cx.peek {
2441 Some(p) if f.is_dir() => {
2442 if let Some(e) =
2443 Self::side(ui, p, height, cx.id.with("peek"), &mut out)
2444 {
2445 out.reach = Some(Reach {
2446 place: p.place.clone(),
2447 focus: Some(e),
2448 });
2449 }
2450 }
2451 _ if f.is_dir() => {}
2452 _ => {
2453 let side = w - 8.0;
2454 let pixels = (side * ctx.pixels_per_point()).round() as u32;
2455 let state = thumbnails.request(
2456 &ctx,
2457 &ThumbRequest {
2458 entry: f,
2459 size: pixels,
2460 priority: Priority::Visible,
2461 },
2462 );
2463 let cell = egui::vec2(w, side + DetailsMode::ROW_HEIGHT + 8.0);
2464 let (rect, _) = ui.allocate_exact_size(cell, egui::Sense::hover());
2465 paint_cell(ui, rect, f, state);
2466 if let Some(s) = f.size {
2467 ui.weak(human_size(s));
2468 }
2469 }
2470 });
2471 }
2472 if reveal_column {
2473 ui.scroll_to_rect(here.rect, None);
2474 }
2475 });
2476 });
2477 self.rows_in_view = out.visible.len().max(1);
2478 out.columns = 1;
2479 out
2480 }
2481
2482 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
2483 let last = count.saturating_sub(1);
2484 let page = self.rows_in_view.max(1);
2485 match key {
2486 ModeKey::Up => from.saturating_sub(1),
2487 ModeKey::Down => (from + 1).min(last),
2488 ModeKey::Left | ModeKey::Right => from,
2489 ModeKey::PageUp => from.saturating_sub(page),
2490 ModeKey::PageDown => (from + page).min(last),
2491 ModeKey::Home => 0,
2492 ModeKey::End => last,
2493 }
2494 }
2495
2496 fn travel(&self, key: ModeKey) -> Option<Travel> {
2497 match key {
2498 ModeKey::Right => Some(Travel::Into),
2499 ModeKey::Left => Some(Travel::Out),
2500 _ => None,
2501 }
2502 }
2503}
2504
2505fn strip_row(
2508 ui: &mut Ui,
2509 count: usize,
2510 cell: egui::Vec2,
2511 salt: egui::Id,
2512 reveal: Option<usize>,
2513 mut item: impl FnMut(&mut Ui, usize),
2514) {
2515 let gap = ui.spacing().item_spacing.x;
2516 let pitch = cell.x + gap;
2517 egui::ScrollArea::horizontal()
2518 .id_salt(salt)
2519 .auto_shrink([false, true])
2520 .animated(false)
2521 .show_viewport(ui, |ui, viewport| {
2522 let total = (pitch * count as f32 - gap).max(0.0);
2523 ui.set_width(total);
2524 ui.set_height(cell.y);
2525 let origin = ui.max_rect().min;
2526 if let Some(i) = reveal {
2527 let r = egui::Rect::from_min_size(origin + egui::vec2(i as f32 * pitch, 0.0), cell);
2528 ui.scroll_to_rect(r, None);
2529 ui.ctx().request_repaint();
2530 }
2531 let first = ((viewport.min.x / pitch).floor().max(0.0) as usize).min(count);
2532 let end = ((viewport.max.x / pitch).ceil().max(0.0) as usize + 1).min(count);
2533 for i in first..end {
2534 let rect =
2535 egui::Rect::from_min_size(origin + egui::vec2(i as f32 * pitch, 0.0), cell);
2536 ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| item(ui, i));
2537 }
2538 });
2539}
2540
2541fn paint_large(
2544 ui: &mut Ui,
2545 rect: egui::Rect,
2546 e: &SourceEntry,
2547 state: ThumbState,
2548 name: &str,
2549) -> egui::Response {
2550 let resp = ui.allocate_rect(rect, egui::Sense::hover());
2551 let label = name.to_owned();
2552 resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, &label));
2553 let visuals = ui.visuals();
2554 ui.painter()
2555 .rect_filled(rect, 4.0, visuals.extreme_bg_color);
2556 match state {
2557 ThumbState::Ready(t) => {
2558 let s = t.size_vec2();
2559 let scale = (rect.width() / s.x).min(rect.height() / s.y);
2560 ui.painter().image(
2561 t.id(),
2562 egui::Rect::from_center_size(rect.center(), s * scale),
2563 egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
2564 egui::Color32::WHITE,
2565 );
2566 }
2567 other => {
2568 let glyph = match other {
2569 _ if e.is_dir() => "Folder",
2570 ThumbState::Failed(_) => "!",
2571 ThumbState::Loading => "...",
2572 _ => "File",
2573 };
2574 ui.painter().text(
2575 rect.center(),
2576 egui::Align2::CENTER_CENTER,
2577 glyph,
2578 egui::FontId::proportional((rect.height() * 0.1).clamp(12.0, 48.0)),
2579 visuals.weak_text_color(),
2580 );
2581 }
2582 }
2583 resp
2584}
2585
2586fn pixels_of(ui: &Ui, rect: egui::Rect) -> u32 {
2588 (rect.width().max(rect.height()) * ui.ctx().pixels_per_point()).round() as u32
2589}
2590
2591#[derive(Clone, Debug, Default)]
2595pub struct FilmstripMode {
2596 in_view: usize,
2597}
2598
2599impl FilmstripMode {
2600 pub const MAX_STRIP: f32 = 128.0;
2602}
2603
2604impl ViewMode for FilmstripMode {
2605 fn describe(&self) -> ModeInfo {
2606 ModeInfo {
2607 id: MODE_FILMSTRIP.into(),
2608 label: "Filmstrip".into(),
2609 icon: "phosphor:film-strip".into(),
2610 keys: vec![
2611 ("Left, Right".into(), "Previous, next entry".into()),
2612 ("Page Up, Page Down".into(), "A strip's width".into()),
2613 ("Home, End".into(), "First, last entry".into()),
2614 ],
2615 gestures: vec!["Wheel: scroll the strip".into()],
2616 persist: MODE_FILMSTRIP.into(),
2617 role: egui::Role::ListBox,
2618 needs: ModeNeeds {
2619 thumbnails: true,
2620 ..ModeNeeds::default()
2621 },
2622 }
2623 }
2624
2625 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
2626 let mut out = ModeOutput::default();
2627 let side = cx
2628 .settings
2629 .thumbnail_size
2630 .clamp(ThumbnailsMode::MIN_SIZE, Self::MAX_STRIP);
2631 let mut plain = PlainDrawer {
2632 entries: cx.entries,
2633 selection: cx.selection,
2634 focus: cx.focus,
2635 marks: cx.marks,
2636 };
2637 let drawer: &mut dyn EntryDrawer = match cx.drawer {
2638 Some(d) => d,
2639 None => &mut plain,
2640 };
2641 let n = cx.entries.len();
2642 let cell = drawer.cell_size(ui, side);
2643 let height = cx
2644 .max_height
2645 .unwrap_or_else(|| ui.available_height())
2646 .max(cell.y * 2.0);
2647 let ctx = ui.ctx().clone();
2648 let thumbnails = cx.thumbnails;
2649 let entries = cx.entries;
2650 let shown = cx.focus.or((n > 0).then_some(0));
2652 let big_h = (height
2653 - cell.y
2654 - ui.spacing().item_spacing.y * 2.0
2655 - ui.spacing().scroll.allocated_width())
2656 .max(cell.y);
2657 let (big, _) = ui.allocate_exact_size(
2658 egui::vec2(ui.available_width(), big_h),
2659 egui::Sense::hover(),
2660 );
2661 if let Some(i) = shown {
2662 let e = &entries[i];
2663 let state = thumbnails.request(
2664 &ctx,
2665 &ThumbRequest {
2666 entry: e,
2667 size: pixels_of(ui, big),
2668 priority: Priority::Visible,
2669 },
2670 );
2671 let name = strings::tr_args(
2672 &ctx,
2673 &crate::strings::FILES_PREVIEW_OF,
2674 &[("name", &e.name)],
2675 );
2676 let mut child = ui.new_child(egui::UiBuilder::new().max_rect(big));
2677 paint_large(&mut child, big, e, state, &name);
2678 } else {
2679 drawer.empty(ui);
2680 }
2681 let pixels = (side * ctx.pixels_per_point()).round() as u32;
2682 let ask = |i: usize, priority| {
2683 thumbnails.request(
2684 &ctx,
2685 &ThumbRequest {
2686 entry: &entries[i],
2687 size: pixels,
2688 priority,
2689 },
2690 )
2691 };
2692 let reveal = cx.focus.filter(|_| cx.reveal_focus && n > 0);
2693 let mut first = usize::MAX;
2694 let mut end = 0;
2695 let focus = cx.focus;
2696 let mut add = |ui: &mut Ui, out: &mut ModeOutput| {
2697 strip_row(ui, n, cell, cx.id.with("filmstrip"), reveal, |ui, i| {
2698 let r = drawer.cell(ui, i, cell, ask(i, Priority::Visible));
2699 if focus == Some(i) {
2700 out.focused = Some(r.id);
2701 }
2702 report(&r, i, out);
2703 first = first.min(i);
2704 end = end.max(i + 1);
2705 });
2706 };
2707 in_container(
2708 ui,
2709 cx.name.as_deref().map(|n| (n, cx.many)),
2710 &mut out,
2711 &mut add,
2712 );
2713 out.visible = if first == usize::MAX {
2714 0..0
2715 } else {
2716 first..end
2717 };
2718 let screen = out.visible.len();
2720 for i in end..(end + screen).min(n) {
2721 ask(i, Priority::Near);
2722 }
2723 self.in_view = screen.max(1);
2724 out.columns = n.max(1);
2725 out
2726 }
2727
2728 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
2729 let last = count.saturating_sub(1);
2730 let page = self.in_view.max(1);
2731 match key {
2732 ModeKey::Left => from.saturating_sub(1),
2733 ModeKey::Right => (from + 1).min(last),
2734 ModeKey::Up | ModeKey::Down => from,
2735 ModeKey::PageUp => from.saturating_sub(page),
2736 ModeKey::PageDown => (from + page).min(last),
2737 ModeKey::Home => 0,
2738 ModeKey::End => last,
2739 }
2740 }
2741}
2742
2743#[derive(Clone, Debug, Default)]
2750pub struct CarouselMode {
2751 per_side: usize,
2752}
2753
2754impl CarouselMode {
2755 pub const SHRINK: f32 = 0.55;
2757 pub const MIN_SIDE: f32 = 24.0;
2759 pub const MIDDLE: f32 = 0.3;
2762
2763 fn fit(drawer: &dyn EntryDrawer, ui: &Ui, wanted: f32, room: egui::Vec2) -> f32 {
2767 let mut side = wanted.max(Self::MIN_SIDE);
2768 for _ in 0..8 {
2771 let cell = drawer.cell_size(ui, side);
2772 let over = (cell.x - room.x).max(cell.y - room.y);
2773 if over <= 0.5 || side <= Self::MIN_SIDE {
2774 break;
2775 }
2776 side = (side - over).max(Self::MIN_SIDE);
2777 }
2778 side
2779 }
2780}
2781
2782impl ViewMode for CarouselMode {
2783 fn describe(&self) -> ModeInfo {
2784 ModeInfo {
2785 id: MODE_CAROUSEL.into(),
2786 label: "Carousel".into(),
2787 icon: "phosphor:slideshow".into(),
2788 keys: vec![
2789 ("Left, Right".into(), "Previous, next entry".into()),
2790 (
2791 "Page Up, Page Down".into(),
2792 "The neighbours on one side".into(),
2793 ),
2794 ("Home, End".into(), "First, last entry".into()),
2795 ],
2796 gestures: vec!["Click a neighbour: bring it to the middle".into()],
2797 persist: MODE_CAROUSEL.into(),
2798 role: egui::Role::ListBox,
2799 needs: ModeNeeds {
2800 thumbnails: true,
2801 ..ModeNeeds::default()
2802 },
2803 }
2804 }
2805
2806 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
2807 let mut out = ModeOutput::default();
2808 let mut plain = PlainDrawer {
2809 entries: cx.entries,
2810 selection: cx.selection,
2811 focus: cx.focus,
2812 marks: cx.marks,
2813 };
2814 let drawer: &mut dyn EntryDrawer = match cx.drawer {
2815 Some(d) => d,
2816 None => &mut plain,
2817 };
2818 let n = cx.entries.len();
2819 let width = ui.available_width();
2820 let height = cx
2821 .max_height
2822 .unwrap_or_else(|| ui.available_height())
2823 .max(4.0 * Self::MIN_SIDE);
2824 let middle = Self::fit(
2827 drawer,
2828 ui,
2829 cx.settings.thumbnail_size,
2830 egui::vec2(width * Self::MIDDLE, height),
2831 );
2832 let gap = ui.spacing().item_spacing.x;
2833 let mut steps = Vec::new();
2837 let mut side = middle;
2838 let mut reach = drawer.cell_size(ui, middle).x / 2.0;
2839 loop {
2840 let next = side * Self::SHRINK;
2841 let w = drawer.cell_size(ui, next).x;
2842 if next < Self::MIN_SIDE || reach + gap + w > width / 2.0 {
2843 break;
2844 }
2845 steps.push((next, reach + gap + w / 2.0));
2846 side = next;
2847 reach += gap + w;
2848 }
2849 let beyond = side;
2850 let ctx = ui.ctx().clone();
2851 let thumbnails = cx.thumbnails;
2852 let entries = cx.entries;
2853 let ask = |i: usize, side: f32, priority| {
2854 thumbnails.request(
2855 &ctx,
2856 &ThumbRequest {
2857 entry: &entries[i],
2858 size: (side * ctx.pixels_per_point()).round() as u32,
2859 priority,
2860 },
2861 )
2862 };
2863 let shown = cx.focus.or((n > 0).then_some(0));
2864 let focus = cx.focus;
2865 let mut per_side = 0;
2866 let mut first = usize::MAX;
2867 let mut end = 0;
2868 let mut add = |ui: &mut Ui, out: &mut ModeOutput| {
2869 let (area, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
2870 let Some(at) = shown else {
2871 drawer.empty(ui);
2872 return;
2873 };
2874 let mut place = |ui: &mut Ui, i: usize, side: f32, x: f32, priority| {
2875 let size = drawer.cell_size(ui, side);
2876 let rect = egui::Rect::from_center_size(egui::pos2(x, area.center().y), size);
2877 let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
2878 let r = drawer.cell(&mut child, i, size, ask(i, side, priority));
2879 if focus == Some(i) {
2880 out.focused = Some(r.id);
2881 }
2882 report(&r, i, out);
2883 first = first.min(i);
2884 end = end.max(i + 1);
2885 };
2886 place(ui, at, middle, area.center().x, Priority::Visible);
2887 for (k, &(next, offset)) in (1..).zip(&steps) {
2888 if at + k < n {
2889 place(
2890 ui,
2891 at + k,
2892 next,
2893 area.center().x + offset,
2894 Priority::Visible,
2895 );
2896 }
2897 if let Some(i) = at.checked_sub(k) {
2898 place(ui, i, next, area.center().x - offset, Priority::Visible);
2899 }
2900 per_side = k;
2901 }
2902 let k = steps.len() + 1;
2904 if at + k < n {
2905 ask(at + k, beyond, Priority::Near);
2906 }
2907 if let Some(i) = at.checked_sub(k) {
2908 ask(i, beyond, Priority::Near);
2909 }
2910 };
2911 in_container(
2912 ui,
2913 cx.name.as_deref().map(|n| (n, cx.many)),
2914 &mut out,
2915 &mut add,
2916 );
2917 out.visible = if first == usize::MAX {
2918 0..0
2919 } else {
2920 first..end
2921 };
2922 self.per_side = per_side;
2923 out.columns = n.max(1);
2924 out
2925 }
2926
2927 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
2928 let last = count.saturating_sub(1);
2929 let page = self.per_side.max(1);
2930 match key {
2931 ModeKey::Left => from.saturating_sub(1),
2932 ModeKey::Right => (from + 1).min(last),
2933 ModeKey::Up | ModeKey::Down => from,
2934 ModeKey::PageUp => from.saturating_sub(page),
2935 ModeKey::PageDown => (from + page).min(last),
2936 ModeKey::Home => 0,
2937 ModeKey::End => last,
2938 }
2939 }
2940}
2941
2942fn agenda_time(e: &SourceEntry) -> Option<i128> {
2945 let t = e.taken.or(e.modified)?;
2946 Some(match t.duration_since(SystemTime::UNIX_EPOCH) {
2947 Ok(d) => d.as_nanos() as i128,
2948 Err(e) => -(e.duration().as_nanos() as i128),
2949 })
2950}
2951
2952const NANOS_PER_DAY: i128 = 86_400 * 1_000_000_000;
2953
2954#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2956enum AgendaLine {
2957 Heading(usize),
2959 Cells(usize, usize),
2961}
2962
2963#[derive(Clone, Debug, Default)]
2967struct AgendaIndex {
2968 built: bool,
2969 generation: u64,
2970 count: usize,
2971 order: Vec<usize>,
2974 days: Vec<Option<i64>>,
2976 level: AgendaLevel,
2977 groups: Vec<(Option<i64>, Range<usize>)>,
2980}
2981
2982impl AgendaIndex {
2983 fn update(&mut self, entries: &[SourceEntry], generation: u64, level: AgendaLevel) -> bool {
2986 let fresh = !self.built || self.generation != generation || self.count != entries.len();
2987 if fresh {
2988 let times: Vec<Option<i128>> = entries.iter().map(agenda_time).collect();
2989 let mut order: Vec<usize> = (0..entries.len()).collect();
2990 order.sort_by(|&a, &b| match (times[a], times[b]) {
2991 (Some(x), Some(y)) => y.cmp(&x).then(a.cmp(&b)),
2992 (Some(_), None) => std::cmp::Ordering::Less,
2993 (None, Some(_)) => std::cmp::Ordering::Greater,
2994 (None, None) => a.cmp(&b),
2995 });
2996 self.days = times
2997 .iter()
2998 .map(|t| t.map(|t| t.div_euclid(NANOS_PER_DAY) as i64))
2999 .collect();
3000 self.order = order;
3001 self.built = true;
3002 self.generation = generation;
3003 self.count = entries.len();
3004 }
3005 if fresh || self.level != level || self.groups.is_empty() != self.order.is_empty() {
3006 self.level = level;
3007 self.groups.clear();
3008 let key = |i: usize| self.days[i].map(|d| level.group(d));
3009 let mut start = 0;
3010 while start < self.order.len() {
3011 let k = key(self.order[start]);
3012 let len = self.order[start..]
3013 .iter()
3014 .take_while(|&&i| key(i) == k)
3015 .count();
3016 self.groups.push((k, start..start + len));
3017 start += len;
3018 }
3019 }
3020 fresh
3021 }
3022}
3023
3024type LayoutKey = (u64, usize, AgendaLevel, usize, BTreeSet<Option<i64>>);
3027
3028#[derive(Clone, Debug, Default)]
3031struct AgendaLayout {
3032 key: Option<LayoutKey>,
3033 shown: Vec<usize>,
3035 position: Vec<Option<usize>>,
3038 group_of: Vec<usize>,
3040 heading_of: Vec<usize>,
3042 line_of: Vec<usize>,
3044 lines: Vec<AgendaLine>,
3045}
3046
3047impl AgendaLayout {
3048 fn update(&mut self, index: &AgendaIndex, columns: usize, collapsed: &BTreeSet<Option<i64>>) {
3049 let key = (
3050 index.generation,
3051 index.count,
3052 index.level,
3053 columns,
3054 collapsed.clone(),
3055 );
3056 if self.key.as_ref() == Some(&key) {
3057 return;
3058 }
3059 let n = index.count;
3060 let mut shown = Vec::with_capacity(n);
3061 let mut position = vec![None; n];
3062 let mut group_of = vec![0; n];
3063 let mut heading_of = Vec::with_capacity(index.groups.len());
3064 let mut line_of = Vec::with_capacity(n);
3065 let mut lines = Vec::new();
3066 for (g, (k, span)) in index.groups.iter().enumerate() {
3067 heading_of.push(lines.len());
3068 lines.push(AgendaLine::Heading(g));
3069 for &i in &index.order[span.clone()] {
3070 group_of[i] = g;
3071 }
3072 if collapsed.contains(k) {
3073 continue;
3074 }
3075 let start = shown.len();
3076 for &i in &index.order[span.clone()] {
3077 position[i] = Some(shown.len());
3078 shown.push(i);
3079 }
3080 let end = shown.len();
3081 let mut at = start;
3082 while at < end {
3083 let to = (at + columns).min(end);
3084 line_of.extend(std::iter::repeat_n(lines.len(), to - at));
3085 lines.push(AgendaLine::Cells(at, to));
3086 at = to;
3087 }
3088 }
3089 *self = AgendaLayout {
3090 key: Some(key),
3091 shown,
3092 position,
3093 group_of,
3094 heading_of,
3095 line_of,
3096 lines,
3097 };
3098 }
3099}
3100
3101#[derive(Clone, Debug, Default)]
3110pub struct AgendaMode {
3111 index: AgendaIndex,
3112 layout: AgendaLayout,
3113 rows_in_view: usize,
3114}
3115
3116impl AgendaMode {
3117 fn arranged_id() -> egui::Id {
3118 egui::Id::unique("egui_pop.file_browser.agenda_arranged")
3119 }
3120
3121 pub fn arrangements(ctx: &egui::Context) -> u64 {
3124 ctx.data(|d| d.get_temp::<u64>(Self::arranged_id()))
3125 .unwrap_or(0)
3126 }
3127
3128 fn rows_from(&self, p: usize, rows: isize) -> usize {
3131 let l = &self.layout;
3132 let Some(&line) = l.line_of.get(p) else {
3133 return p;
3134 };
3135 let AgendaLine::Cells(start, _) = l.lines[line] else {
3136 return p;
3137 };
3138 let column = p - start;
3139 let mut at = line;
3140 let mut target = None;
3141 let mut left = rows.unsigned_abs();
3142 while left > 0 {
3143 let next = if rows < 0 {
3144 at.checked_sub(1)
3145 } else {
3146 Some(at + 1).filter(|&k| k < l.lines.len())
3147 };
3148 let Some(next) = next else { break };
3149 at = next;
3150 if let AgendaLine::Cells(s, e) = l.lines[at] {
3151 target = Some(s + column.min(e - s - 1));
3152 left -= 1;
3153 }
3154 }
3155 target.unwrap_or(p)
3156 }
3157}
3158
3159impl ViewMode for AgendaMode {
3160 fn describe(&self) -> ModeInfo {
3161 ModeInfo {
3162 id: MODE_AGENDA.into(),
3163 label: "Agenda".into(),
3164 icon: "phosphor:calendar".into(),
3165 keys: vec![
3166 ("Arrows".into(), "Move across the groups".into()),
3167 ("Page Up, Page Down".into(), "A page up or down".into()),
3168 ("Home, End".into(), "Newest, oldest entry".into()),
3169 ("Ctrl+Up, Ctrl+Down".into(), "By year, month or day".into()),
3170 (
3171 "Ctrl+Left, Ctrl+Right".into(),
3172 "Collapse, expand the group".into(),
3173 ),
3174 ],
3175 gestures: vec![
3176 "Wheel: scroll".into(),
3177 "Click on a heading: collapse or expand".into(),
3178 ],
3179 persist: MODE_AGENDA.into(),
3180 role: egui::Role::ListBox,
3181 needs: ModeNeeds {
3182 thumbnails: true,
3183 time: true,
3184 ..ModeNeeds::default()
3185 },
3186 }
3187 }
3188
3189 fn toolbar(&mut self, ui: &mut Ui, settings: &mut ModeSettings) -> bool {
3190 let ctx = ui.ctx().clone();
3191 let mut changed = false;
3192 ui.separator();
3193 ui.scope(|ui| {
3194 ui.spacing_mut().item_spacing.x = 0.0;
3195 for level in AgendaLevel::ALL {
3196 let label = strings::tr(&ctx, level.label());
3197 let on = settings.agenda.level == level;
3198 let r = widgets::selectable_label(ui, on, label.as_str());
3199 r.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, &label));
3200 let r = r.on_hover_text("Ctrl+Up, Ctrl+Down");
3201 if r.clicked() {
3202 changed |= settings.agenda.set_level(level);
3203 }
3204 }
3205 });
3206 changed
3207 }
3208
3209 fn own_key(
3210 &mut self,
3211 key: egui::Key,
3212 modifiers: Modifiers,
3213 focus: Option<usize>,
3214 settings: &mut ModeSettings,
3215 ) -> bool {
3216 if !modifiers.command || modifiers.shift || modifiers.alt {
3217 return false;
3218 }
3219 let a = &mut settings.agenda;
3220 match key {
3221 egui::Key::ArrowUp => {
3222 a.set_level(a.level.coarser());
3223 }
3224 egui::Key::ArrowDown => {
3225 a.set_level(a.level.finer());
3226 }
3227 egui::Key::ArrowLeft | egui::Key::ArrowRight => {
3228 let group = focus
3229 .and_then(|i| self.layout.group_of.get(i))
3230 .and_then(|&g| self.index.groups.get(g))
3231 .map(|(k, _)| *k);
3232 if let Some(g) = group {
3233 a.set_collapsed(g, key == egui::Key::ArrowLeft);
3234 }
3235 }
3236 _ => return false,
3237 }
3238 true
3239 }
3240
3241 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
3242 let mut out = ModeOutput::default();
3243 let ctx = ui.ctx().clone();
3244 let level = cx.settings.agenda.level;
3245 if self.index.update(cx.entries, cx.generation, level) {
3246 ctx.data_mut(|d| {
3247 *d.get_temp_mut_or_default::<u64>(Self::arranged_id()) += 1;
3248 });
3249 }
3250 let side = cx
3251 .settings
3252 .thumbnail_size
3253 .clamp(ThumbnailsMode::MIN_SIZE, ThumbnailsMode::MAX_SIZE);
3254 let mut plain = PlainDrawer {
3255 entries: cx.entries,
3256 selection: cx.selection,
3257 focus: cx.focus,
3258 marks: cx.marks,
3259 };
3260 let drawer: &mut dyn EntryDrawer = match cx.drawer {
3261 Some(d) => d,
3262 None => &mut plain,
3263 };
3264 let n = cx.entries.len();
3265 let cell = drawer.cell_size(ui, side);
3266 let gap = ui.spacing().item_spacing;
3267 let width = ui.available_width() - ui.spacing().scroll.allocated_width();
3268 let columns = (((width + gap.x) / (cell.x + gap.x)).floor() as usize).max(1);
3269 self.layout
3270 .update(&self.index, columns, &cx.settings.agenda.collapsed);
3271 let (index, layout) = (&self.index, &self.layout);
3272 let heading_h = ui.text_style_height(&egui::TextStyle::Heading) + 2.0 * gap.y;
3273 let row_h = cell.y + gap.y;
3274 let mut tops = Vec::with_capacity(layout.lines.len() + 1);
3275 let mut y = 0.0;
3276 for line in &layout.lines {
3277 tops.push(y);
3278 y += match line {
3279 AgendaLine::Heading(..) => heading_h,
3280 AgendaLine::Cells(..) => row_h,
3281 };
3282 }
3283 tops.push(y);
3284 let total = y;
3285 let thumbnails = cx.thumbnails;
3286 let entries = cx.entries;
3287 let pixels = (side * ctx.pixels_per_point()).round() as u32;
3288 let ask = |i: usize, priority| {
3289 thumbnails.request(
3290 &ctx,
3291 &ThumbRequest {
3292 entry: &entries[i],
3293 size: pixels,
3294 priority,
3295 },
3296 )
3297 };
3298 let undated = strings::tr(&ctx, &crate::strings::FILES_AGENDA_UNDATED);
3299 let reveal = cx
3301 .focus
3302 .filter(|&i| cx.reveal_focus && i < layout.position.len())
3303 .map(|i| match layout.position[i] {
3304 Some(p) => layout.line_of[p],
3305 None => layout.heading_of[layout.group_of[i]],
3306 });
3307 let focus = cx.focus;
3308 let collapsed = &cx.settings.agenda.collapsed;
3309 let mut toggled = None;
3310 let mut first = usize::MAX;
3311 let mut end = 0;
3312 let mut drawn_rows = 0;
3313 let mut near = None;
3314 let mut area = egui::ScrollArea::vertical()
3315 .id_salt(cx.id.with("agenda"))
3316 .auto_shrink([false, false])
3317 .animated(false);
3318 if let Some(h) = cx.max_height {
3319 area = area.max_height(h);
3320 }
3321 let mut add = |ui: &mut Ui, out: &mut ModeOutput| {
3322 if n == 0 {
3323 drawer.empty(ui);
3324 }
3325 area.clone().show_viewport(ui, |ui, viewport| {
3326 ui.set_height(total);
3327 ui.set_width(width);
3328 let origin = ui.max_rect().min;
3329 if let Some(l) = reveal {
3330 let r = egui::Rect::from_min_max(
3331 origin + egui::vec2(0.0, tops[l]),
3332 origin + egui::vec2(width, tops[l + 1]),
3333 );
3334 ui.scroll_to_rect(r, None);
3335 ui.ctx().request_repaint();
3336 }
3337 for (l, line) in layout.lines.iter().enumerate() {
3338 if tops[l + 1] < viewport.min.y {
3339 continue;
3340 }
3341 if tops[l] > viewport.max.y {
3342 near = layout.lines[l..].iter().find_map(|line| match *line {
3344 AgendaLine::Cells(s, e) => Some(s..e),
3345 AgendaLine::Heading(..) => None,
3346 });
3347 break;
3348 }
3349 let top = origin + egui::vec2(0.0, tops[l]);
3350 match *line {
3351 AgendaLine::Heading(g) => {
3352 let (key, span) = &index.groups[g];
3353 let shut = collapsed.contains(key);
3354 let text = match key {
3355 Some(k) => index.level.heading(*k),
3356 None => undated.clone(),
3357 };
3358 let rect = egui::Rect::from_min_size(top, egui::vec2(width, heading_h));
3359 let resp = ui.interact(
3360 rect,
3361 cx.id.with(("agenda.heading", *key)),
3362 egui::Sense::click(),
3363 );
3364 let name = text.clone();
3365 resp.widget_info(|| {
3366 egui::WidgetInfo::labeled(egui::Role::Heading, true, &name)
3367 });
3368 ui.ctx().accesskit_node_builder(resp.id, |node| {
3369 node.set_expanded(!shut);
3370 });
3371 if resp.clicked() {
3372 toggled = Some((*key, !shut));
3373 }
3374 let visuals = ui.visuals();
3375 if resp.hovered() {
3376 ui.painter().rect_filled(
3377 rect,
3378 2.0,
3379 visuals.widgets.hovered.weak_bg_fill,
3380 );
3381 }
3382 let color = visuals.strong_text_color();
3383 let c = egui::pos2(rect.left() + 10.0, rect.center().y);
3385 let r = 4.5;
3386 let points = if shut {
3387 vec![
3388 c + egui::vec2(-r * 0.6, -r),
3389 c + egui::vec2(r, 0.0),
3390 c + egui::vec2(-r * 0.6, r),
3391 ]
3392 } else {
3393 vec![
3394 c + egui::vec2(-r, -r * 0.6),
3395 c + egui::vec2(r, -r * 0.6),
3396 c + egui::vec2(0.0, r),
3397 ]
3398 };
3399 ui.painter().add(egui::Shape::convex_polygon(
3400 points,
3401 color,
3402 egui::Stroke::NONE,
3403 ));
3404 let font = egui::TextStyle::Heading.resolve(ui.style());
3405 let at = egui::pos2(rect.left() + 22.0, rect.center().y);
3406 let galley = ui.painter().layout_no_wrap(text, font, color);
3407 let after = at.x + galley.size().x + 8.0;
3408 ui.painter().galley(
3409 at - egui::vec2(0.0, galley.size().y / 2.0),
3410 galley,
3411 color,
3412 );
3413 ui.painter().text(
3414 egui::pos2(after, rect.center().y),
3415 egui::Align2::LEFT_CENTER,
3416 span.len().to_string(),
3417 egui::TextStyle::Body.resolve(ui.style()),
3418 visuals.weak_text_color(),
3419 );
3420 }
3421 AgendaLine::Cells(s, e) => {
3422 drawn_rows += 1;
3423 for (c, &i) in layout.shown[s..e].iter().enumerate() {
3424 let rect = egui::Rect::from_min_size(
3425 top + egui::vec2(c as f32 * (cell.x + gap.x), 0.0),
3426 cell,
3427 );
3428 let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
3429 let r = drawer.cell(&mut child, i, cell, ask(i, Priority::Visible));
3430 if focus == Some(i) {
3431 out.focused = Some(r.id);
3432 }
3433 report(&r, i, out);
3434 first = first.min(s);
3435 end = end.max(e);
3436 }
3437 }
3438 }
3439 }
3440 });
3441 };
3442 in_container(
3443 ui,
3444 cx.name.as_deref().map(|n| (n, cx.many)),
3445 &mut out,
3446 &mut add,
3447 );
3448 if let Some(r) = near {
3449 for &i in &layout.shown[r] {
3450 ask(i, Priority::Near);
3451 }
3452 }
3453 if let Some((key, shut)) = toggled {
3454 cx.settings.agenda.set_collapsed(key, shut);
3455 ctx.request_repaint();
3456 }
3457 out.visible = if first == usize::MAX {
3459 0..0
3460 } else {
3461 first..end
3462 };
3463 self.rows_in_view = drawn_rows.max(1);
3464 out.columns = columns;
3465 out
3466 }
3467
3468 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
3469 let last = count.saturating_sub(1);
3470 let l = &self.layout;
3471 if l.position.len() != count || from >= count {
3473 return match key {
3474 ModeKey::Left | ModeKey::Up | ModeKey::PageUp => from.saturating_sub(1),
3475 ModeKey::Right | ModeKey::Down | ModeKey::PageDown => (from + 1).min(last),
3476 ModeKey::Home => 0,
3477 ModeKey::End => last,
3478 };
3479 }
3480 let (Some(&first), Some(&final_)) = (l.shown.first(), l.shown.last()) else {
3481 return from;
3483 };
3484 let back = matches!(
3485 key,
3486 ModeKey::Left | ModeKey::Up | ModeKey::PageUp | ModeKey::Home
3487 );
3488 let Some(p) = l.position[from] else {
3489 let g = l.group_of[from];
3491 return match key {
3492 ModeKey::Home => first,
3493 ModeKey::End => final_,
3494 _ if back => l
3495 .shown
3496 .iter()
3497 .rev()
3498 .find(|&&i| l.group_of[i] < g)
3499 .copied()
3500 .unwrap_or(first),
3501 _ => l
3502 .shown
3503 .iter()
3504 .find(|&&i| l.group_of[i] > g)
3505 .copied()
3506 .unwrap_or(final_),
3507 };
3508 };
3509 let last_p = l.shown.len() - 1;
3510 let page = self.rows_in_view.max(1) as isize;
3511 let to = match key {
3512 ModeKey::Left => p.saturating_sub(1),
3513 ModeKey::Right => (p + 1).min(last_p),
3514 ModeKey::Up => self.rows_from(p, -1),
3515 ModeKey::Down => self.rows_from(p, 1),
3516 ModeKey::PageUp => self.rows_from(p, -page),
3517 ModeKey::PageDown => self.rows_from(p, page),
3518 ModeKey::Home => 0,
3519 ModeKey::End => last_p,
3520 };
3521 l.shown[to]
3522 }
3523}
3524
3525pub const MODE_DETAILS: &str = "details";
3531pub const MODE_THUMBNAILS: &str = "thumbnails";
3533pub const MODE_COLUMNS: &str = "columns";
3535pub const MODE_FILMSTRIP: &str = "filmstrip";
3537pub const MODE_CAROUSEL: &str = "carousel";
3539pub const MODE_AGENDA: &str = "agenda";
3541pub const SEGMENTED_MAX: usize = 4;
3544pub const MODE_KEYS: usize = 9;
3546
3547fn request_id() -> egui::Id {
3548 egui::Id::unique("egui_pop.file_browser.mode_request")
3549}
3550
3551fn focused_id() -> egui::Id {
3552 egui::Id::unique("egui_pop.file_browser.focused")
3553}
3554
3555pub fn mode_label(ctx: &egui::Context, info: &ModeInfo) -> String {
3558 strings::lookup(
3559 ctx,
3560 &format!("egui-pop-files-mode-{}", info.id),
3561 &info.label,
3562 )
3563}
3564
3565pub fn request_mode(ctx: &egui::Context, n: usize) {
3569 ctx.data_mut(|d| d.insert_temp(request_id(), n));
3570 ctx.request_repaint();
3571}
3572
3573pub fn take_focused(ctx: &egui::Context) -> bool {
3576 ctx.data_mut(|d| d.remove_temp::<bool>(focused_id()))
3577 .unwrap_or(false)
3578}
3579
3580pub fn mode_key(ui: &mut Ui) -> Option<usize> {
3583 const KEYS: [egui::Key; MODE_KEYS] = [
3584 egui::Key::Num1,
3585 egui::Key::Num2,
3586 egui::Key::Num3,
3587 egui::Key::Num4,
3588 egui::Key::Num5,
3589 egui::Key::Num6,
3590 egui::Key::Num7,
3591 egui::Key::Num8,
3592 egui::Key::Num9,
3593 ];
3594 ui.input_mut(|i| {
3595 KEYS.iter()
3596 .position(|k| i.consume_key(Modifiers::COMMAND, *k))
3597 .map(|n| n + 1)
3598 })
3599}
3600
3601pub fn mode_switcher(
3607 ui: &mut Ui,
3608 id: egui::Id,
3609 modes: &[ModeInfo],
3610 current: &str,
3611) -> Option<(String, egui::Response)> {
3612 let ctx = ui.ctx().clone();
3613 let tip = |n: usize, info: &ModeInfo| {
3614 let mut lines = Vec::new();
3615 if n < MODE_KEYS {
3616 lines.push(format!("Ctrl+{}", n + 1));
3617 }
3618 lines.extend(info.keys.iter().map(|(k, what)| format!("{k}: {what}")));
3619 lines.join("\n")
3620 };
3621 let mut picked = None;
3622 if modes.len() <= SEGMENTED_MAX {
3623 ui.scope(|ui| {
3624 ui.spacing_mut().item_spacing.x = 0.0;
3625 for (n, info) in modes.iter().enumerate() {
3626 let label = mode_label(&ctx, info);
3627 let on = info.id == current;
3628 let glyph = Icon::by_name(&info.icon)
3631 .and_then(Icon::glyph)
3632 .filter(|_| egui_pop_core::icon::font_ready(&ctx));
3633 let r = match glyph {
3634 Some(g) => {
3635 let family = egui::FontFamily::Name(egui_pop_core::icon::FAMILY.into());
3636 let icon = egui::RichText::new(g).family(family);
3637 widgets::selectable_label(ui, on, (icon, label.as_str()))
3638 }
3639 None => widgets::selectable_label(ui, on, label.as_str()),
3640 };
3641 r.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, &label));
3643 let r = r.on_hover_text(tip(n, info));
3644 if r.clicked() {
3645 picked = Some((info.id.clone(), r));
3646 }
3647 }
3648 });
3649 } else {
3650 let shown = modes
3651 .iter()
3652 .find(|m| m.id == current)
3653 .map(|m| mode_label(&ctx, m))
3654 .unwrap_or_default();
3655 let r = egui::ComboBox::from_id_salt(id.with("modes"))
3656 .selected_text(shown)
3657 .show_ui(ui, |ui| {
3658 for (n, info) in modes.iter().enumerate() {
3659 let on = info.id == current;
3660 let r = widgets::selectable_label(ui, on, mode_label(&ctx, info))
3661 .on_hover_text(tip(n, info));
3662 if r.clicked() {
3663 picked = Some((info.id.clone(), r));
3664 }
3665 }
3666 });
3667 let name = strings::tr(&ctx, &crate::strings::FILES_MODES);
3668 r.response
3669 .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, &name));
3670 }
3671 picked
3672}
3673
3674#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3680pub enum SelectMode {
3681 One,
3682 Many,
3683}
3684
3685#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3687pub enum Selectable {
3688 Files,
3690 Folders,
3692 #[default]
3694 Any,
3695}
3696
3697impl Selectable {
3698 pub fn accepts(self, kind: EntryKind) -> bool {
3700 match self {
3701 Selectable::Files => kind == EntryKind::File,
3702 Selectable::Folders => kind == EntryKind::Folder,
3703 Selectable::Any => true,
3704 }
3705 }
3706}
3707
3708#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3713#[non_exhaustive]
3714pub struct SelectionPolicy {
3715 pub selectable: Selectable,
3716 pub mode: SelectMode,
3717 pub keeps_filtered: bool,
3721}
3722
3723impl Default for SelectionPolicy {
3724 fn default() -> Self {
3726 Self::any(SelectMode::Many)
3727 }
3728}
3729
3730impl SelectionPolicy {
3731 pub fn new(selectable: Selectable, mode: SelectMode) -> Self {
3732 Self {
3733 selectable,
3734 mode,
3735 keeps_filtered: false,
3736 }
3737 }
3738
3739 pub fn keeping_filtered(mut self, on: bool) -> Self {
3742 self.keeps_filtered = on;
3743 self
3744 }
3745
3746 pub fn files(mode: SelectMode) -> Self {
3748 Self::new(Selectable::Files, mode)
3749 }
3750
3751 pub fn folders(mode: SelectMode) -> Self {
3753 Self::new(Selectable::Folders, mode)
3754 }
3755
3756 pub fn any(mode: SelectMode) -> Self {
3758 Self::new(Selectable::Any, mode)
3759 }
3760}
3761
3762#[derive(Clone, Debug, Default, PartialEq, Eq)]
3767#[non_exhaustive]
3768pub struct EntryFilter {
3769 pub extensions: Vec<String>,
3772 pub kind: Option<EntryKind>,
3774}
3775
3776impl EntryFilter {
3777 pub fn all() -> Self {
3779 Self::default()
3780 }
3781
3782 pub fn extensions(extensions: &[&str]) -> Self {
3784 Self {
3785 extensions: extensions.iter().map(|e| e.to_lowercase()).collect(),
3786 kind: None,
3787 }
3788 }
3789
3790 pub fn kind(kind: EntryKind) -> Self {
3792 Self::all().with_kind(kind)
3793 }
3794
3795 pub fn with_kind(mut self, kind: EntryKind) -> Self {
3797 self.kind = Some(kind);
3798 self
3799 }
3800
3801 pub fn is_all(&self) -> bool {
3803 self.extensions.is_empty() && self.kind.is_none()
3804 }
3805
3806 pub fn accepts(&self, entry: &SourceEntry) -> bool {
3808 if self.kind.is_some_and(|k| k != entry.kind) {
3809 return false;
3810 }
3811 entry.is_dir() || has_extension(&self.extensions, &entry.path)
3812 }
3813}
3814
3815impl From<&super::FileFilter> for EntryFilter {
3816 fn from(f: &super::FileFilter) -> Self {
3817 Self {
3818 extensions: f.extensions.clone(),
3819 kind: None,
3820 }
3821 }
3822}
3823
3824pub(crate) fn has_extension(extensions: &[String], path: &Path) -> bool {
3827 extensions.is_empty()
3828 || path
3829 .extension()
3830 .and_then(|e| e.to_str())
3831 .is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
3832}
3833
3834pub(crate) fn rank_by_names<T>(
3837 items: &[T],
3838 query: &str,
3839 names: impl Fn(&T) -> Vec<String>,
3840) -> Vec<usize> {
3841 let mut all = Vec::with_capacity(items.len());
3842 for (n, it) in items.iter().enumerate() {
3843 all.extend(names(it).into_iter().map(|name| (n, name)));
3844 }
3845 let mut seen = HashSet::new();
3846 egui_pop_model::fuzzy::rank(&all, query, |(_, name)| name.clone())
3847 .into_iter()
3848 .map(|(i, _)| all[i].0)
3849 .filter(|n| seen.insert(*n))
3850 .collect()
3851}
3852
3853#[derive(Clone, Debug, Default, PartialEq, Eq)]
3855pub struct BrowserOutput {
3856 pub activated: Option<PathBuf>,
3858 pub selection_changed: bool,
3859 pub mode_changed: bool,
3860 pub place_changed: bool,
3863 pub dropped: Option<DropOffer>,
3865}
3866
3867#[derive(Clone, Debug, Default)]
3869struct TypeAhead {
3870 prefix: String,
3871 at: f64,
3872}
3873
3874pub struct FileBrowser {
3880 id: egui::Id,
3881 source: Arc<dyn FileSource>,
3882 place: PathBuf,
3883 options: ListOptions,
3884 listing: Option<Listing>,
3885 entries: Vec<SourceEntry>,
3886 error: Option<SourceError>,
3887 selection: Selection,
3888 focus: Option<PathBuf>,
3889 policy: SelectionPolicy,
3891 modes: ViewModes,
3892 mode_id: String,
3893 mode: Box<dyn ViewMode>,
3894 settings: ModeSettings,
3895 zoom: ThumbZoom,
3898 resize: GridResize,
3900 grid_room: (f32, f32),
3903 thumbnails: Arc<dyn ThumbnailProvider>,
3904 type_ahead: TypeAhead,
3905 mode_took: Vec<(String, f64)>,
3909 reveal: bool,
3910 restored: bool,
3911 root: Option<PathBuf>,
3912 columns: ColumnListings,
3915 generation: u64,
3917 drops: Option<DropPolicy>,
3919 drop_targets: Vec<AppDropTarget>,
3920 drop_hover: Option<(DropOffer, bool)>,
3922 focus_first: bool,
3925 quick_look: bool,
3927 marks: Option<Arc<MarkEntries>>,
3929 sort: PickerSort,
3931 folders_first: bool,
3932 band_base: Option<BTreeSet<PathBuf>>,
3934 groupings: Option<Groupings>,
3936 grouped: bool,
3938 grouper: Option<Grouper>,
3940 groups: Arc<HashMap<PathBuf, FileGroup>>,
3942 absorbed: HashMap<PathBuf, SourceEntry>,
3944 filter: EntryFilter,
3946 query: String,
3949 filtered_out: Vec<SourceEntry>,
3951}
3952
3953fn sort_entries(entries: &mut [SourceEntry]) {
3956 sort_in(entries, PickerSort::default(), true);
3957}
3958
3959fn sort_in(entries: &mut [SourceEntry], sort: PickerSort, folders_first: bool) {
3962 sort_by(entries, sort, folders_first, |e| SortFacts {
3963 name: &e.name,
3964 is_dir: e.is_dir(),
3965 size: e.size,
3966 modified: e.modified,
3967 taken: e.taken,
3968 });
3969}
3970
3971fn pump_column(column: &mut Column, listing: &mut Option<Listing>, folders_only: bool) -> bool {
3974 let Some(l) = listing else {
3975 return false;
3976 };
3977 let mut changed = false;
3978 let mut done = false;
3979 for page in l.poll() {
3980 match page {
3981 Page::Entries(mut e) => {
3982 if folders_only {
3983 e.retain(SourceEntry::is_dir);
3984 }
3985 column.entries.append(&mut e);
3986 changed = true;
3987 }
3988 Page::Updated(e) => {
3989 for u in e {
3990 if let Some(old) = column.entries.iter_mut().find(|o| o.path == u.path) {
3991 *old = u;
3992 }
3993 }
3994 }
3995 Page::Removed(paths) => column.entries.retain(|e| !paths.contains(&e.path)),
3996 Page::Changed => column.entries.clear(),
3997 Page::Done | Page::Failed(_) => done = true,
3998 }
3999 }
4000 if changed {
4001 sort_entries(&mut column.entries);
4002 }
4003 if done {
4004 *listing = None;
4005 }
4006 column.loading = listing.is_some();
4007 column.loading
4008}
4009
4010#[derive(Debug, Default)]
4017pub struct ColumnListings {
4018 ancestors: Vec<Column>,
4019 listings: Vec<Option<Listing>>,
4020 peek: Option<(Column, Option<Listing>)>,
4021 options: ListOptions,
4022 folders_only: bool,
4023}
4024
4025impl ColumnListings {
4026 pub fn folders_only(mut self, on: bool) -> Self {
4028 self.folders_only = on;
4029 self
4030 }
4031
4032 pub fn sync(
4039 &mut self,
4040 source: &dyn FileSource,
4041 options: &ListOptions,
4042 wanted: &[PathBuf],
4043 place: &Path,
4044 peek: Option<&Path>,
4045 ) -> bool {
4046 if self.options != *options {
4047 self.clear();
4048 self.options = *options;
4049 }
4050 if self.ancestors.iter().map(|c| &c.place).ne(wanted.iter()) {
4051 let mut old: Vec<(Column, Option<Listing>)> = self
4052 .ancestors
4053 .drain(..)
4054 .zip(self.listings.drain(..))
4055 .collect();
4056 for place in wanted {
4057 match old.iter().position(|(c, _)| &c.place == place) {
4058 Some(i) => {
4059 let (c, l) = old.swap_remove(i);
4060 self.ancestors.push(c);
4061 self.listings.push(l);
4062 }
4063 None => {
4064 let l = source.list(place, options);
4065 self.ancestors.push(Column {
4066 place: place.clone(),
4067 loading: true,
4068 ..Column::default()
4069 });
4070 self.listings.push(Some(l));
4071 }
4072 }
4073 }
4074 }
4076 let mut busy = false;
4077 for (c, l) in self.ancestors.iter_mut().zip(self.listings.iter_mut()) {
4078 busy |= pump_column(c, l, self.folders_only);
4079 }
4080 let n = self.ancestors.len();
4082 for k in 0..n {
4083 let next = if k + 1 < n {
4084 self.ancestors[k + 1].place.clone()
4085 } else {
4086 place.to_path_buf()
4087 };
4088 let c = &mut self.ancestors[k];
4089 c.open = c.entries.iter().position(|e| e.path == next);
4090 }
4091 match peek {
4092 Some(f) => {
4093 if self.peek.as_ref().is_none_or(|(c, _)| c.place != f) {
4094 let l = source.list(f, options);
4096 self.peek = Some((
4097 Column {
4098 place: f.to_path_buf(),
4099 loading: true,
4100 ..Column::default()
4101 },
4102 Some(l),
4103 ));
4104 }
4105 if let Some((c, l)) = &mut self.peek {
4106 busy |= pump_column(c, l, self.folders_only);
4107 }
4108 }
4109 None => self.peek = None,
4110 }
4111 busy
4112 }
4113
4114 pub fn ancestors(&self) -> &[Column] {
4116 &self.ancestors
4117 }
4118
4119 pub fn peek(&self) -> Option<&Column> {
4121 self.peek.as_ref().map(|(c, _)| c)
4122 }
4123
4124 pub fn loading(&self) -> bool {
4126 self.listings.iter().any(Option::is_some)
4127 || self.peek.as_ref().is_some_and(|(_, l)| l.is_some())
4128 }
4129
4130 pub fn clear(&mut self) {
4133 self.ancestors.clear();
4134 self.listings.clear();
4135 self.peek = None;
4136 }
4137}
4138
4139#[derive(Debug)]
4145enum GroupWork {
4146 Add(Vec<String>),
4147 Remove(Vec<String>),
4148}
4149
4150#[derive(Debug)]
4152struct GroupWorker {
4153 tx: mpsc::Sender<GroupWork>,
4154 rx: mpsc::Receiver<(u64, Vec<FileGroup>)>,
4155}
4156
4157#[derive(Debug)]
4164struct Grouper {
4165 dir: PathBuf,
4166 groupings: Groupings,
4167 names: Vec<String>,
4169 worker: Option<GroupWorker>,
4170 sent: u64,
4172 answered: u64,
4173 ready: Option<Vec<FileGroup>>,
4175}
4176
4177impl Grouper {
4178 const INLINE_NAMES: usize = 2048;
4180
4181 fn new(dir: PathBuf, groupings: Groupings) -> Self {
4182 Self {
4183 dir,
4184 groupings,
4185 names: Vec::new(),
4186 worker: None,
4187 sent: 0,
4188 answered: 0,
4189 ready: None,
4190 }
4191 }
4192
4193 fn names_of<'a>(entries: impl IntoIterator<Item = &'a SourceEntry>) -> Vec<String> {
4195 entries
4196 .into_iter()
4197 .filter(|e| !e.is_dir() && !e.name.starts_with('.'))
4198 .map(|e| e.name.clone())
4199 .collect()
4200 }
4201
4202 fn tell(&mut self, work: GroupWork) {
4203 if let Some(w) = &self.worker {
4204 if w.tx.send(work).is_ok() {
4205 self.sent += 1;
4206 }
4207 return;
4208 }
4209 match work {
4210 GroupWork::Add(mut names) => self.names.append(&mut names),
4211 GroupWork::Remove(names) => {
4212 let gone: HashSet<String> = names.into_iter().collect();
4213 self.names.retain(|n| !gone.contains(n));
4214 }
4215 }
4216 if self.names.len() > Self::INLINE_NAMES && self.spawn() {
4217 return;
4218 }
4219 let names: Vec<&str> = self.names.iter().map(String::as_str).collect();
4220 self.ready = Some(self.groupings.in_folder(&self.dir, &names));
4221 }
4222
4223 fn spawn(&mut self) -> bool {
4226 if cfg!(target_arch = "wasm32") {
4227 return false;
4228 }
4229 let (tx, work) = mpsc::channel::<GroupWork>();
4230 let (answer, rx) = mpsc::channel();
4231 let (dir, groupings) = (self.dir.clone(), self.groupings.clone());
4232 let spawned = std::thread::Builder::new()
4233 .name("egui-pop-file-groups".into())
4234 .spawn(move || {
4235 let mut names: Vec<String> = Vec::new();
4236 let mut seen = 0u64;
4237 while let Ok(first) = work.recv() {
4238 for w in std::iter::once(first).chain(work.try_iter()) {
4240 seen += 1;
4241 match w {
4242 GroupWork::Add(mut more) => names.append(&mut more),
4243 GroupWork::Remove(gone) => {
4244 let gone: HashSet<String> = gone.into_iter().collect();
4245 names.retain(|n| !gone.contains(n));
4246 }
4247 }
4248 }
4249 let refs: Vec<&str> = names.iter().map(String::as_str).collect();
4250 if answer
4251 .send((seen, groupings.in_folder(&dir, &refs)))
4252 .is_err()
4253 {
4254 return;
4255 }
4256 }
4257 });
4258 if spawned.is_err() {
4259 return false;
4260 }
4261 let names = std::mem::take(&mut self.names);
4262 self.worker = Some(GroupWorker { tx, rx });
4263 self.ready = None;
4264 self.tell(GroupWork::Add(names));
4265 true
4266 }
4267
4268 fn poll(&mut self) -> Option<Vec<FileGroup>> {
4270 let Some(w) = &self.worker else {
4271 return self.ready.take();
4272 };
4273 let mut last = None;
4274 for (seen, groups) in w.rx.try_iter() {
4275 self.answered = seen;
4276 last = Some(groups);
4277 }
4278 last
4279 }
4280
4281 fn pending(&self) -> bool {
4283 self.worker.is_some() && self.answered < self.sent
4284 }
4285}
4286
4287pub(crate) struct GroupThumbnails<'a> {
4291 pub(crate) inner: &'a dyn ThumbnailProvider,
4292 pub(crate) groups: &'a HashMap<PathBuf, FileGroup>,
4293 pub(crate) absorbed: &'a HashMap<PathBuf, SourceEntry>,
4294}
4295
4296impl ThumbnailProvider for GroupThumbnails<'_> {
4297 fn begin_frame(&self, ctx: &egui::Context) {
4298 self.inner.begin_frame(ctx);
4299 }
4300
4301 fn request(&self, ctx: &egui::Context, request: &ThumbRequest<'_>) -> ThumbState {
4302 let own = self.inner.request(ctx, request);
4303 if !matches!(own, ThumbState::None | ThumbState::Failed(_)) {
4304 return own;
4305 }
4306 let Some(group) = self.groups.get(&request.entry.path) else {
4307 return own;
4308 };
4309 for member in group.members.iter().filter_map(|m| self.absorbed.get(m)) {
4310 let state = self.inner.request(
4311 ctx,
4312 &ThumbRequest {
4313 entry: member,
4314 ..*request
4315 },
4316 );
4317 if matches!(state, ThumbState::Ready(_) | ThumbState::Loading) {
4318 return state;
4319 }
4320 }
4321 own
4322 }
4323
4324 fn end_frame(&self, ctx: &egui::Context) {
4325 self.inner.end_frame(ctx);
4326 }
4327
4328 fn cancel(&self, path: &Path) {
4329 self.inner.cancel(path);
4330 }
4331}
4332
4333pub(crate) fn group_chips(ctx: &egui::Context, group: &FileGroup) -> Vec<MarkChip> {
4337 let members = group.member_names().join(", ");
4338 let name = strings::tr_args(
4339 ctx,
4340 &crate::strings::FILES_GROUP_WITH,
4341 &[("members", &members)],
4342 );
4343 if group.badges.is_empty() {
4344 return vec![MarkChip::text(format!("+{}", group.members.len()), name)];
4345 }
4346 group
4347 .badges
4348 .iter()
4349 .map(|b| MarkChip::text(format!("+{b}"), name.clone()))
4350 .collect()
4351}
4352
4353impl fmt::Debug for FileBrowser {
4354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4355 f.debug_struct("FileBrowser")
4356 .field("id", &self.id)
4357 .field("source", &self.source.id())
4358 .field("place", &self.place)
4359 .field("entries", &self.entries.len())
4360 .field("mode", &self.mode_id)
4361 .finish_non_exhaustive()
4362 }
4363}
4364
4365#[derive(Debug, Default)]
4367pub struct NoThumbnails;
4368
4369impl ThumbnailProvider for NoThumbnails {
4370 fn request(&self, _ctx: &egui::Context, _r: &ThumbRequest<'_>) -> ThumbState {
4371 ThumbState::None
4372 }
4373}
4374
4375impl FileBrowser {
4376 pub const TYPE_AHEAD_RESET: f64 = 1.0;
4378
4379 pub fn new(
4382 id: impl std::hash::Hash + fmt::Debug,
4383 source: Arc<dyn FileSource>,
4384 place: impl Into<PathBuf>,
4385 ) -> Self {
4386 let modes = ViewModes::default();
4387 let mode_id = modes.ids().first().cloned().unwrap_or_default();
4388 let mode = modes
4389 .make(&mode_id)
4390 .unwrap_or_else(|| Box::new(DetailsMode::default()));
4391 let mut b = Self {
4392 id: egui::Id::unique(("egui_pop.file_browser", id)),
4393 source,
4394 place: place.into(),
4395 options: ListOptions::default(),
4396 listing: None,
4397 entries: Vec::new(),
4398 error: None,
4399 selection: Selection::default(),
4400 focus: None,
4401 policy: SelectionPolicy::default(),
4402 modes,
4403 mode_id,
4404 mode,
4405 settings: ModeSettings::default(),
4406 zoom: ThumbZoom::default(),
4407 resize: GridResize::default(),
4408 grid_room: (800.0, 4.0),
4409 thumbnails: Arc::new(NoThumbnails),
4410 type_ahead: TypeAhead::default(),
4411 mode_took: Vec::new(),
4412 reveal: false,
4413 restored: false,
4414 root: None,
4415 columns: ColumnListings::default(),
4416 generation: 0,
4417 drops: None,
4418 drop_targets: Vec::new(),
4419 drop_hover: None,
4420 focus_first: false,
4421 quick_look: false,
4422 marks: None,
4423 sort: PickerSort::default(),
4424 folders_first: true,
4425 band_base: None,
4426 groupings: None,
4427 grouped: true,
4428 grouper: None,
4429 groups: Arc::default(),
4430 absorbed: HashMap::new(),
4431 filter: EntryFilter::all(),
4432 query: String::new(),
4433 filtered_out: Vec::new(),
4434 };
4435 b.reload();
4436 b
4437 }
4438
4439 pub fn with_modes(mut self, modes: ViewModes) -> Self {
4440 self.modes = modes;
4441 if let Some(first) = self.modes.ids().first().cloned() {
4442 self.set_mode(&first);
4443 }
4444 self
4445 }
4446
4447 pub fn with_thumbnails(mut self, provider: Arc<dyn ThumbnailProvider>) -> Self {
4448 self.thumbnails = provider;
4449 self
4450 }
4451
4452 pub fn with_select(mut self, select: SelectMode) -> Self {
4453 self.policy.mode = select;
4454 self
4455 }
4456
4457 pub fn with_selection_policy(mut self, policy: SelectionPolicy) -> Self {
4459 self.set_selection_policy(policy);
4460 self
4461 }
4462
4463 pub fn set_selection_policy(&mut self, policy: SelectionPolicy) {
4466 self.policy = policy;
4467 let kept: Vec<PathBuf> = self.selection.paths.iter().cloned().collect();
4468 self.set_selection(kept);
4469 }
4470
4471 pub fn selection_policy(&self) -> SelectionPolicy {
4473 self.policy
4474 }
4475
4476 pub fn with_filter(mut self, filter: EntryFilter) -> Self {
4478 self.set_filter(filter);
4479 self
4480 }
4481
4482 pub fn set_filter(&mut self, filter: EntryFilter) {
4486 if filter != self.filter {
4487 self.filter = filter;
4488 self.resort();
4489 }
4490 }
4491
4492 pub fn filter(&self) -> &EntryFilter {
4493 &self.filter
4494 }
4495
4496 pub fn set_query(&mut self, query: &str) {
4500 if query == self.query {
4501 return;
4502 }
4503 self.query = query.to_owned();
4504 self.arrange();
4505 if !self.query.trim().is_empty()
4506 && let Some(first) = self.entries.first().map(|e| e.path.clone())
4507 {
4508 self.focus = Some(first.clone());
4509 if self.policy.mode == SelectMode::One {
4510 self.select_only(&first);
4511 }
4512 self.reveal = true;
4513 }
4514 }
4515
4516 pub fn query(&self) -> &str {
4518 &self.query
4519 }
4520
4521 fn can_select(&self, path: &Path) -> bool {
4523 self.entries
4524 .iter()
4525 .find(|e| e.path == path)
4526 .is_none_or(|e| self.policy.selectable.accepts(e.kind))
4527 }
4528
4529 fn select_only(&mut self, path: &Path) {
4532 if self.can_select(path) {
4533 self.selection.only(path);
4534 } else {
4535 self.selection.paths.clear();
4536 self.selection.anchor = Some(path.to_path_buf());
4537 }
4538 }
4539
4540 fn follow_mains(&mut self) {
4544 if self.groups.is_empty() {
4545 return;
4546 }
4547 let filter = &self.filter;
4548 let passes = |main: &Path| {
4549 filter.kind.is_none_or(|k| k == EntryKind::File)
4550 && has_extension(&filter.extensions, main)
4551 };
4552 let main_of: HashMap<&PathBuf, &PathBuf> = (self.groups.values())
4553 .flat_map(|g| g.members.iter().map(move |m| (m, &g.main)))
4554 .collect();
4555 let back: Vec<PathBuf> = (self.absorbed.keys())
4556 .filter(|m| main_of.get(m).is_some_and(|main| !passes(main)))
4557 .cloned()
4558 .collect();
4559 let absorbed = &mut self.absorbed;
4560 self.entries.retain(|e| match main_of.get(&e.path) {
4561 Some(main) if passes(main) => {
4562 absorbed.insert(e.path.clone(), e.clone());
4563 false
4564 }
4565 _ => true,
4566 });
4567 for m in back {
4568 if let Some(e) = self.absorbed.remove(&m) {
4569 self.entries.push(e);
4570 }
4571 }
4572 }
4573
4574 fn arrange(&mut self) {
4577 self.entries.append(&mut self.filtered_out);
4578 self.follow_mains();
4579 let query = self.query.trim().to_owned();
4580 if !self.filter.is_all() {
4581 let filter = &self.filter;
4582 let (keep, out): (Vec<_>, Vec<_>) = std::mem::take(&mut self.entries)
4583 .into_iter()
4584 .partition(|e| filter.accepts(e));
4585 self.entries = keep;
4586 self.filtered_out = out;
4587 }
4588 sort_in(&mut self.entries, self.sort, self.folders_first);
4589 if !query.is_empty() {
4590 let groups = Arc::clone(&self.groups);
4591 let order = rank_by_names(&self.entries, &query, |e| {
4592 let mut names = vec![e.name.clone()];
4593 if let Some(g) = groups.get(&e.path) {
4594 names.extend(g.member_names());
4595 }
4596 names
4597 });
4598 let mut slots: Vec<Option<SourceEntry>> = std::mem::take(&mut self.entries)
4599 .into_iter()
4600 .map(Some)
4601 .collect();
4602 self.entries = order.iter().filter_map(|&i| slots[i].take()).collect();
4603 self.filtered_out.extend(slots.into_iter().flatten());
4604 }
4605 if !self.filtered_out.is_empty() {
4606 let shown: HashSet<&Path> = self.entries.iter().map(|e| e.path.as_path()).collect();
4607 if !self.policy.keeps_filtered {
4608 self.selection.paths.retain(|p| shown.contains(p.as_path()));
4609 }
4610 if self
4611 .selection
4612 .anchor
4613 .as_ref()
4614 .is_some_and(|a| !shown.contains(a.as_path()))
4615 {
4616 self.selection.anchor = None;
4617 }
4618 if self
4619 .focus
4620 .as_ref()
4621 .is_some_and(|f| !shown.contains(f.as_path()))
4622 {
4623 self.focus = None;
4624 }
4625 }
4626 self.generation += 1;
4627 }
4628
4629 pub fn with_marks(
4634 mut self,
4635 marks: impl Fn(&SourceEntry) -> EntryMarks + Send + Sync + 'static,
4636 ) -> Self {
4637 self.marks = Some(Arc::new(marks));
4638 self
4639 }
4640
4641 pub fn with_sort(mut self, sort: PickerSort) -> Self {
4644 self.set_sort(sort);
4645 self
4646 }
4647
4648 pub fn with_folders_first(mut self, on: bool) -> Self {
4651 self.set_folders_first(on);
4652 self
4653 }
4654
4655 pub fn set_sort(&mut self, sort: PickerSort) {
4663 if sort != self.sort {
4664 self.sort = sort;
4665 self.resort();
4666 }
4667 }
4668
4669 pub fn sort(&self) -> PickerSort {
4670 self.sort
4671 }
4672
4673 pub fn set_folders_first(&mut self, on: bool) {
4675 if on != self.folders_first {
4676 self.folders_first = on;
4677 self.resort();
4678 }
4679 }
4680
4681 pub fn folders_first(&self) -> bool {
4682 self.folders_first
4683 }
4684
4685 fn resort(&mut self) {
4687 self.arrange();
4688 self.reveal = self.focus.is_some();
4689 }
4690
4691 pub fn with_grouping(mut self, groupings: Groupings) -> Self {
4701 self.groupings = Some(groupings);
4702 self.regroup();
4703 self
4704 }
4705
4706 pub fn set_grouped(&mut self, on: bool) {
4711 if on != self.grouped {
4712 self.grouped = on;
4713 self.regroup();
4714 }
4715 }
4716
4717 pub fn grouped(&self) -> bool {
4718 self.grouped
4719 }
4720
4721 fn grouping_on(&self) -> bool {
4723 self.grouped && self.groupings.as_ref().is_some_and(|g| !g.is_empty())
4724 }
4725
4726 pub fn group_of(&self, path: &Path) -> Option<&FileGroup> {
4728 self.groups.get(path)
4729 }
4730
4731 pub(crate) fn groups(&self) -> Arc<HashMap<PathBuf, FileGroup>> {
4733 Arc::clone(&self.groups)
4734 }
4735
4736 pub(crate) fn absorbed(&self) -> &HashMap<PathBuf, SourceEntry> {
4738 &self.absorbed
4739 }
4740
4741 pub fn groups_pending(&self) -> bool {
4743 self.grouper.as_ref().is_some_and(Grouper::pending)
4744 }
4745
4746 fn regroup(&mut self) {
4749 self.grouper = None;
4750 self.apply_groups(Vec::new());
4751 if self.grouping_on()
4752 && let Some(groupings) = self.groupings.clone()
4753 {
4754 let mut grouper = Grouper::new(self.place.clone(), groupings);
4755 grouper.tell(GroupWork::Add(Grouper::names_of(&self.entries)));
4756 self.grouper = Some(grouper);
4757 self.take_groups();
4758 }
4759 }
4760
4761 fn take_groups(&mut self) {
4763 if let Some(found) = self.grouper.as_mut().and_then(Grouper::poll) {
4764 self.apply_groups(found);
4765 }
4766 }
4767
4768 fn apply_groups(&mut self, found: Vec<FileGroup>) {
4772 let groups: HashMap<PathBuf, FileGroup> =
4773 found.into_iter().map(|g| (g.main.clone(), g)).collect();
4774 if groups == *self.groups {
4775 return;
4776 }
4777 let main_of: HashMap<&PathBuf, &PathBuf> = groups
4778 .values()
4779 .flat_map(|g| g.members.iter().map(move |m| (m, &g.main)))
4780 .collect();
4781 let back: Vec<PathBuf> = (self.absorbed.keys())
4782 .filter(|p| !main_of.contains_key(p))
4783 .cloned()
4784 .collect();
4785 let restored = !back.is_empty();
4786 for p in back {
4787 if let Some(e) = self.absorbed.remove(&p) {
4788 self.entries.push(e);
4789 }
4790 }
4791 let absorbed = &mut self.absorbed;
4792 let mut absorb = |e: &SourceEntry| {
4793 if main_of.contains_key(&e.path) {
4794 absorbed.insert(e.path.clone(), e.clone());
4795 false
4796 } else {
4797 true
4798 }
4799 };
4800 self.entries.retain(&mut absorb);
4801 self.filtered_out.retain(&mut absorb);
4802 let to_main = |p: &mut PathBuf| {
4803 if let Some(main) = main_of.get(p) {
4804 *p = (*main).clone();
4805 }
4806 };
4807 if let Some(f) = &mut self.focus {
4808 to_main(f);
4809 }
4810 if let Some(a) = &mut self.selection.anchor {
4811 to_main(a);
4812 }
4813 if self.selection.paths.iter().any(|p| main_of.contains_key(p)) {
4814 let paths = std::mem::take(&mut self.selection.paths);
4815 self.selection.paths = paths
4816 .into_iter()
4817 .map(|mut p| {
4818 to_main(&mut p);
4819 p
4820 })
4821 .collect();
4822 }
4823 drop(main_of);
4824 self.groups = Arc::new(groups);
4825 if restored || !self.filter.is_all() || !self.query.trim().is_empty() {
4826 self.arrange();
4827 }
4828 self.generation += 1;
4829 }
4830
4831 pub fn set_selection(&mut self, paths: impl IntoIterator<Item = PathBuf>) {
4835 let aside: &[SourceEntry] = if self.policy.keeps_filtered {
4836 &self.filtered_out
4837 } else {
4838 &[]
4839 };
4840 let listed: HashSet<&Path> = (self.entries.iter().chain(aside))
4841 .map(|e| e.path.as_path())
4842 .collect();
4843 let selectable: HashSet<&Path> = (self.entries.iter().chain(aside))
4844 .filter(|e| self.policy.selectable.accepts(e.kind))
4845 .map(|e| e.path.as_path())
4846 .collect();
4847 let mut chosen: BTreeSet<PathBuf> = paths
4848 .into_iter()
4849 .filter(|p| listed.contains(p.as_path()) && selectable.contains(p.as_path()))
4850 .collect();
4851 if self.policy.mode == SelectMode::One {
4852 chosen = chosen.into_iter().take(1).collect();
4853 }
4854 if self
4855 .selection
4856 .anchor
4857 .as_ref()
4858 .is_some_and(|a| !chosen.contains(a))
4859 {
4860 self.selection.anchor = chosen.iter().next().cloned();
4861 }
4862 self.selection.paths = chosen;
4863 }
4864
4865 pub fn id(&self) -> egui::Id {
4866 self.id
4867 }
4868
4869 pub fn with_root(mut self, root: impl Into<PathBuf>) -> Self {
4872 self.root = Some(root.into());
4873 self
4874 }
4875
4876 pub fn ancestors(&self) -> &[Column] {
4879 self.columns.ancestors()
4880 }
4881
4882 pub fn peek(&self) -> Option<&Column> {
4885 self.columns.peek()
4886 }
4887
4888 pub fn with_drops(
4898 mut self,
4899 accept: impl Fn(&DropOffer) -> bool + Send + Sync + 'static,
4900 ) -> Self {
4901 self.drops = Some(Arc::new(accept));
4902 self
4903 }
4904
4905 pub fn with_drop_targets(mut self, targets: Vec<AppDropTarget>) -> Self {
4909 self.drop_targets = targets;
4910 self
4911 }
4912
4913 pub fn drop_hover(&self) -> Option<&(DropOffer, bool)> {
4916 self.drop_hover.as_ref()
4917 }
4918
4919 fn wanted_ancestors(&self) -> Vec<PathBuf> {
4922 if let Some(root) = &self.root
4923 && !self.place.starts_with(root)
4924 {
4925 return Vec::new();
4926 }
4927 let mut up: Vec<PathBuf> = Vec::new();
4928 for a in self.place.ancestors().skip(1) {
4929 if self.root.as_deref().is_some_and(|r| !a.starts_with(r)) {
4930 break;
4931 }
4932 up.push(a.to_path_buf());
4933 }
4934 up.reverse();
4935 up
4936 }
4937
4938 fn sync_columns(&mut self) -> bool {
4942 let wanted = self.wanted_ancestors();
4943 let folder = self
4944 .focus_index()
4945 .map(|i| &self.entries[i])
4946 .filter(|e| e.is_dir())
4947 .map(|e| e.path.clone());
4948 self.columns.sync(
4949 self.source.as_ref(),
4950 &self.options,
4951 &wanted,
4952 &self.place,
4953 folder.as_deref(),
4954 )
4955 }
4956
4957 pub fn travel(&mut self, travel: Travel) -> bool {
4960 match travel {
4961 Travel::Into => {
4962 let Some(folder) = self
4963 .focus_index()
4964 .map(|i| &self.entries[i])
4965 .filter(|e| e.is_dir())
4966 .map(|e| e.path.clone())
4967 else {
4968 return false;
4969 };
4970 self.open(folder);
4971 self.focus_first = true;
4972 self.settle_focus();
4973 true
4974 }
4975 Travel::Out => {
4976 if self.root.as_deref() == Some(self.place.as_path()) {
4977 return false;
4978 }
4979 let Some(parent) = self.place.parent().map(Path::to_path_buf) else {
4980 return false;
4981 };
4982 let left = self.place.clone();
4983 self.reach(&Reach {
4984 place: parent,
4985 focus: Some(left),
4986 });
4987 true
4988 }
4989 }
4990 }
4991
4992 pub fn reach(&mut self, reach: &Reach) {
4995 if reach.place != self.place {
4996 self.open(reach.place.clone());
4997 }
4998 if let Some(f) = &reach.focus {
4999 self.select_only(f);
5000 self.focus = Some(f.clone());
5001 self.reveal = true;
5002 }
5003 }
5004
5005 pub fn quick_look(&self) -> bool {
5007 self.quick_look
5008 }
5009
5010 pub fn set_quick_look(&mut self, open: bool) {
5014 self.quick_look = open && self.focus_index().is_some();
5015 }
5016
5017 fn quick_look_keys(&mut self, ui: &mut Ui) -> bool {
5020 let (close, back, next) = ui.input_mut(|i| {
5021 let close = i.consume_key(Modifiers::NONE, egui::Key::Escape)
5022 || i.consume_key(Modifiers::COMMAND, egui::Key::Y)
5023 || i.consume_key(Modifiers::NONE, egui::Key::Space);
5024 let back = i.consume_key(Modifiers::NONE, egui::Key::ArrowLeft)
5025 || i.consume_key(Modifiers::NONE, egui::Key::ArrowUp);
5026 let next = i.consume_key(Modifiers::NONE, egui::Key::ArrowRight)
5027 || i.consume_key(Modifiers::NONE, egui::Key::ArrowDown);
5028 (close, back, next)
5029 });
5030 if close {
5031 self.quick_look = false;
5032 } else if (back || next)
5033 && let Some(at) = self.focus_index()
5034 {
5035 {
5036 let to = if next {
5037 (at + 1).min(self.entries.len() - 1)
5038 } else {
5039 at.saturating_sub(1)
5040 };
5041 let path = self.entries[to].path.clone();
5042 self.focus = Some(path.clone());
5043 if self.policy.mode == SelectMode::One {
5044 self.select_only(&path);
5045 }
5046 self.reveal = true;
5047 }
5048 }
5049 close || back || next
5050 }
5051
5052 fn show_quick_look(&self, ui: &mut Ui, rect: egui::Rect, thumbnails: &dyn ThumbnailProvider) {
5055 let Some(e) = self.focus_index().map(|i| &self.entries[i]) else {
5056 return;
5057 };
5058 let ctx = ui.ctx().clone();
5059 let name = strings::tr_args(
5060 &ctx,
5061 &crate::strings::FILES_QUICK_LOOK,
5062 &[("name", &e.name)],
5063 );
5064 egui_pop_core::layers::rank_from(
5067 &ctx,
5068 egui::LayerId::new(egui::Order::Foreground, self.id.with("quick_look")),
5069 egui_pop_core::layers::Rank::Overlay,
5070 ui.layer_id(),
5071 );
5072 egui::Area::new(self.id.with("quick_look"))
5073 .order(egui::Order::Foreground)
5074 .fixed_pos(rect.min)
5075 .show(&ctx, |ui| {
5076 ui.set_min_size(rect.size());
5077 let visuals = ui.visuals().clone();
5078 ui.painter()
5079 .rect_filled(rect, 6.0, visuals.window_fill.gamma_multiply(0.97));
5080 let caption = ui.text_style_height(&egui::TextStyle::Body) + 8.0;
5081 let image = egui::Rect::from_min_max(
5082 rect.min + egui::vec2(12.0, 12.0),
5083 egui::pos2(rect.right() - 12.0, rect.bottom() - caption - 12.0),
5084 );
5085 if image.width() < 1.0 || image.height() < 1.0 {
5086 return;
5087 }
5088 let state = thumbnails.request(
5089 &ctx,
5090 &ThumbRequest {
5091 entry: e,
5092 size: pixels_of(ui, image),
5093 priority: Priority::Visible,
5094 },
5095 );
5096 paint_large(ui, image, e, state, &name);
5097 ui.painter().text(
5098 egui::pos2(rect.center().x, rect.bottom() - caption / 2.0 - 6.0),
5099 egui::Align2::CENTER_CENTER,
5100 &e.name,
5101 egui::TextStyle::Body.resolve(ui.style()),
5102 visuals.text_color(),
5103 );
5104 });
5105 }
5106
5107 fn settle_focus(&mut self) {
5109 if !self.focus_first {
5110 return;
5111 }
5112 if let Some(first) = self.entries.first().map(|e| e.path.clone()) {
5113 self.focus_first = false;
5114 self.focus = Some(first.clone());
5115 self.select_only(&first);
5116 self.reveal = true;
5117 } else if !self.loading() {
5118 self.focus_first = false;
5119 }
5120 }
5121
5122 pub fn place(&self) -> &Path {
5123 &self.place
5124 }
5125
5126 pub fn open(&mut self, place: impl Into<PathBuf>) {
5128 self.place = place.into();
5129 self.selection = Selection::default();
5130 self.focus = None;
5131 self.reload();
5132 }
5133
5134 pub fn set_show_hidden(&mut self, on: bool) {
5137 if on != self.options.hidden {
5138 self.options.hidden = on;
5139 self.reload();
5140 }
5141 }
5142
5143 pub fn show_hidden(&self) -> bool {
5145 self.options.hidden
5146 }
5147
5148 pub fn reload(&mut self) {
5150 self.entries.clear();
5151 self.filtered_out.clear();
5152 self.absorbed.clear();
5153 self.groups = Arc::default();
5154 self.generation += 1;
5155 self.error = None;
5156 self.listing = Some(self.source.list(&self.place, &self.options));
5157 self.regroup();
5158 self.pump();
5159 }
5160
5161 pub fn pump(&mut self) {
5163 let Some(listing) = &self.listing else {
5164 self.take_groups();
5165 return;
5166 };
5167 let mut done = false;
5168 let mut changed = false;
5169 for page in listing.poll() {
5170 match page {
5171 Page::Entries(mut e) => {
5172 if let Some(g) = &mut self.grouper {
5173 g.tell(GroupWork::Add(Grouper::names_of(&e)));
5174 }
5175 self.entries.append(&mut e);
5176 changed = true;
5177 }
5178 Page::Updated(e) => {
5179 for u in e {
5180 if let Some(old) = self.absorbed.get_mut(&u.path) {
5181 *old = u;
5182 } else if let Some(old) = (self.entries.iter_mut())
5183 .chain(self.filtered_out.iter_mut())
5184 .find(|o| o.path == u.path)
5185 {
5186 *old = u;
5187 }
5188 }
5189 changed = true;
5191 }
5192 Page::Removed(paths) => {
5193 if let Some(g) = &mut self.grouper {
5194 let names = paths
5195 .iter()
5196 .filter_map(|p| p.file_name())
5197 .map(|n| n.to_string_lossy().into_owned())
5198 .collect();
5199 g.tell(GroupWork::Remove(names));
5200 }
5201 self.entries.retain(|e| !paths.contains(&e.path));
5202 self.filtered_out.retain(|e| !paths.contains(&e.path));
5203 self.generation += 1;
5204 for p in &paths {
5205 self.absorbed.remove(p);
5206 self.selection.paths.remove(p);
5207 }
5208 }
5209 Page::Changed => {
5210 self.reload();
5211 return;
5212 }
5213 Page::Done => done = true,
5214 Page::Failed(e) => {
5215 self.error = Some(e);
5216 done = true;
5217 }
5218 }
5219 }
5220 if changed {
5221 self.arrange();
5222 }
5223 if done {
5224 self.listing = None;
5225 }
5226 self.take_groups();
5227 self.settle_focus();
5228 }
5229
5230 pub fn loading(&self) -> bool {
5232 self.listing.is_some()
5233 }
5234
5235 pub fn error(&self) -> Option<&SourceError> {
5236 self.error.as_ref()
5237 }
5238
5239 pub fn filtered_out_count(&self) -> usize {
5242 self.filtered_out.len()
5243 }
5244
5245 pub fn entries(&self) -> &[SourceEntry] {
5248 &self.entries
5249 }
5250
5251 pub fn selection(&self) -> &Selection {
5252 &self.selection
5253 }
5254
5255 pub fn focus(&self) -> Option<&Path> {
5256 self.focus.as_deref()
5257 }
5258
5259 pub fn set_focus(&mut self, path: Option<&Path>) {
5262 match path {
5263 Some(p) if self.entries.iter().any(|e| e.path == p) => {
5264 self.focus = Some(p.to_path_buf());
5265 self.reveal = true;
5266 }
5267 Some(_) => {}
5268 None => self.focus = None,
5269 }
5270 self.focus_first = false;
5271 }
5272
5273 pub(crate) fn focus_index(&self) -> Option<usize> {
5274 let f = self.focus.as_ref()?;
5275 self.entries.iter().position(|e| &e.path == f)
5276 }
5277
5278 pub fn modes(&self) -> Vec<String> {
5280 self.modes.ids()
5281 }
5282
5283 pub fn mode(&self) -> &str {
5284 &self.mode_id
5285 }
5286
5287 pub fn set_mode(&mut self, id: &str) -> bool {
5290 if id == self.mode_id {
5291 return true;
5292 }
5293 let Some(mode) = self.modes.make(id) else {
5294 return false;
5295 };
5296 self.mode = mode;
5297 self.mode_id = id.to_owned();
5298 self.reveal = true;
5299 true
5300 }
5301
5302 pub fn set_thumbnail_size(&mut self, side: f32) {
5305 self.zoom = ThumbZoom::Points(side.max(ThumbnailsMode::MIN_SIZE));
5306 }
5307
5308 pub fn zoom(&self) -> ThumbZoom {
5312 self.zoom
5313 }
5314
5315 #[must_use]
5319 pub fn with_resize(mut self, resize: GridResize) -> Self {
5320 self.resize = resize;
5321 self
5322 }
5323
5324 pub fn set_resize(&mut self, resize: GridResize) {
5326 self.resize = resize;
5327 }
5328
5329 pub fn resize(&self) -> GridResize {
5331 self.resize
5332 }
5333
5334 pub fn set_zoom(&mut self, zoom: ThumbZoom) {
5336 self.zoom = zoom;
5337 self.reveal = true;
5338 }
5339
5340 pub fn set_thumbnails_per_row(&mut self, per_row: u32) {
5342 self.set_zoom(ThumbZoom::PerRow(per_row.clamp(1, ThumbZoom::MOST)));
5343 }
5344
5345 pub fn focus_on(&mut self, path: &Path, extend: bool) {
5348 let Some(at) = self.entries.iter().position(|e| e.path == path) else {
5349 return;
5350 };
5351 let from = self.focus_index();
5352 self.focus = Some(path.to_path_buf());
5353 self.reveal = true;
5354 if extend && self.policy.mode == SelectMode::Many {
5355 let anchor = self
5357 .selection
5358 .anchor
5359 .as_ref()
5360 .and_then(|a| self.entries.iter().position(|e| &e.path == a))
5361 .or(from)
5362 .unwrap_or(at);
5363 self.selection.anchor = Some(self.entries[anchor].path.clone());
5364 let (lo, hi) = (anchor.min(at), anchor.max(at));
5365 self.selection.paths = self.entries[lo..=hi]
5366 .iter()
5367 .filter(|e| self.policy.selectable.accepts(e.kind))
5368 .map(|e| e.path.clone())
5369 .collect();
5370 } else if self.policy.mode == SelectMode::One {
5371 self.select_only(path);
5372 } else {
5373 self.selection.anchor = Some(path.to_path_buf());
5376 }
5377 }
5378
5379 pub fn click(&mut self, path: &Path, modifiers: Modifiers) {
5382 if modifiers.shift && self.policy.mode == SelectMode::Many {
5383 self.focus_on(path, true);
5384 } else if modifiers.command && self.policy.mode == SelectMode::Many {
5385 if !self.selection.paths.remove(path) && self.can_select(path) {
5386 self.selection.paths.insert(path.to_path_buf());
5387 }
5388 self.selection.anchor = Some(path.to_path_buf());
5389 self.focus = Some(path.to_path_buf());
5390 } else {
5391 self.select_only(path);
5392 self.focus = Some(path.to_path_buf());
5393 }
5394 }
5395
5396 pub fn key(&mut self, key: ModeKey, shift: bool) -> bool {
5398 if let Some(t) = self.mode.travel(key) {
5399 return self.travel(t);
5400 }
5401 let n = self.entries.len();
5402 if n == 0 {
5403 return false;
5404 }
5405 let to = match self.focus_index() {
5406 Some(from) => self.mode.step(from, n, key),
5407 None => 0,
5408 };
5409 let path = self.entries[to].path.clone();
5410 let before = self.selection.paths.clone();
5411 self.focus_on(&path, shift);
5412 before != self.selection.paths
5413 }
5414
5415 pub(crate) fn apply_band(&mut self, band: &Band) -> bool {
5419 if self.policy.mode == SelectMode::One {
5420 self.band_base = None;
5422 return false;
5423 }
5424 let keep = band.modifiers.command || band.modifiers.shift;
5425 let base = self
5426 .band_base
5427 .get_or_insert_with(|| {
5428 if keep {
5429 self.selection.paths.clone()
5430 } else {
5431 BTreeSet::new()
5432 }
5433 })
5434 .clone();
5435 let mut paths = base;
5436 paths.extend(
5437 band.cells
5438 .iter()
5439 .filter_map(|&i| self.entries.get(i))
5440 .filter(|e| self.policy.selectable.accepts(e.kind))
5441 .map(|e| e.path.clone()),
5442 );
5443 let changed = paths != self.selection.paths;
5444 self.selection.paths = paths;
5445 if band.finished {
5446 self.band_base = None;
5447 if let Some(last) = band.cells.last().and_then(|&i| self.entries.get(i)) {
5448 self.focus = Some(last.path.clone());
5449 self.selection.anchor = Some(last.path.clone());
5450 }
5451 }
5452 changed
5453 }
5454
5455 pub fn select_all(&mut self) {
5458 if self.policy.mode == SelectMode::Many {
5459 let shown = (self.entries.iter())
5460 .filter(|e| self.policy.selectable.accepts(e.kind))
5461 .map(|e| e.path.clone());
5462 if self.policy.keeps_filtered {
5463 self.selection.paths.extend(shown);
5464 } else {
5465 self.selection.paths = shown.collect();
5466 }
5467 }
5468 }
5469
5470 fn took_text(&mut self, text: &str) -> bool {
5472 let text = text.to_lowercase();
5473 match self.mode_took.iter().position(|(t, _)| *t == text) {
5474 Some(i) => {
5475 self.mode_took.remove(i);
5476 true
5477 }
5478 None => false,
5479 }
5480 }
5481
5482 pub fn type_ahead(&mut self, text: &str, now: f64) -> bool {
5486 if text.is_empty() {
5487 return false;
5488 }
5489 if now - self.type_ahead.at > Self::TYPE_AHEAD_RESET {
5490 self.type_ahead.prefix.clear();
5491 }
5492 self.type_ahead.at = now;
5493 let lower = text.to_lowercase();
5494 let same_letter = {
5495 let p = &self.type_ahead.prefix;
5496 !p.is_empty() && p.chars().all(|c| lower.chars().all(|t| t == c))
5497 };
5498 let starts = |e: &SourceEntry, p: &str| e.name.to_lowercase().starts_with(p);
5499 let found = if same_letter {
5500 let p = lower.clone();
5502 let from = self.focus_index().map_or(0, |i| i + 1);
5503 let n = self.entries.len();
5504 (0..n)
5505 .map(|k| (from + k) % n)
5506 .find(|&i| starts(&self.entries[i], &p))
5507 } else {
5508 self.type_ahead.prefix.push_str(&lower);
5509 let p = self.type_ahead.prefix.clone();
5510 self.entries.iter().position(|e| starts(e, &p))
5511 };
5512 match found {
5513 Some(i) => {
5514 let path = self.entries[i].path.clone();
5515 self.focus = Some(path.clone());
5516 if self.policy.mode == SelectMode::One {
5517 self.select_only(&path);
5518 }
5519 self.reveal = true;
5520 true
5521 }
5522 None => false,
5523 }
5524 }
5525
5526 pub fn mode_infos(&self) -> Vec<ModeInfo> {
5528 self.modes
5529 .ids()
5530 .iter()
5531 .filter_map(|id| self.modes.make(id).map(|m| m.describe()))
5532 .collect()
5533 }
5534
5535 pub fn set_mode_index(&mut self, n: usize) -> bool {
5538 let Some(id) = n
5539 .checked_sub(1)
5540 .and_then(|i| self.modes.ids().get(i).cloned())
5541 else {
5542 return false;
5543 };
5544 id != self.mode_id && self.set_mode(&id)
5545 }
5546
5547 pub fn show_in(
5551 &mut self,
5552 ui: &mut Ui,
5553 app: &crate::app::AppHandle,
5554 dialog: &str,
5555 ) -> BrowserOutput {
5556 if !self.restored {
5557 self.restored = true;
5558 if let Some(kept) = super::view_for(app, dialog) {
5559 self.set_mode(&kept);
5560 }
5561 }
5562 let out = self.show(ui);
5563 if out.mode_changed {
5564 super::want_view_for(app, dialog, &self.mode_id);
5565 }
5566 out
5567 }
5568
5569 fn sort_menu(&mut self, ui: &mut Ui) {
5573 let ctx = ui.ctx().clone();
5574 let said = |sort: PickerSort| {
5575 let column = strings::tr(&ctx, sort.column.title());
5576 let key = if sort.descending {
5577 &crate::strings::FILES_SORTED_DOWN
5578 } else {
5579 &crate::strings::FILES_SORTED_UP
5580 };
5581 strings::tr_args(&ctx, key, &[("column", &column)])
5582 };
5583 let name = strings::tr(&ctx, &crate::strings::FILES_SORT_BY);
5584 let shown = strings::tr(&ctx, self.sort.column.title());
5585 let mut sort = self.sort;
5586 let mut folders_first = self.folders_first;
5587 let mut grouped = self.grouped;
5588 let can_group = self.groupings.as_ref().is_some_and(|g| !g.is_empty());
5589 let r = widgets::combo_box(self.id.with("sort"))
5590 .selected_text(shown)
5591 .show_ui(ui, |ui| {
5592 for column in SortColumn::ALL {
5593 let on = sort.column == column;
5594 let label = strings::tr(&ctx, column.title());
5595 let r = widgets::selectable_label(ui, on, label.as_str());
5596 r.widget_info(|| {
5597 egui::WidgetInfo::selected(egui::Role::MenuItemRadio, true, on, &label)
5598 });
5599 if r.clicked() {
5600 sort = sort.click(column);
5601 }
5602 }
5603 ui.separator();
5604 widgets::checkbox(
5605 ui,
5606 &mut folders_first,
5607 strings::tr(&ctx, &crate::strings::FILES_FOLDERS_FIRST),
5608 );
5609 if can_group {
5610 widgets::checkbox(
5611 ui,
5612 &mut grouped,
5613 strings::tr(&ctx, &crate::strings::FILES_GROUP),
5614 )
5615 .on_hover_text(strings::tr(&ctx, &crate::strings::FILES_GROUP_TIP));
5616 }
5617 });
5618 let current = said(self.sort);
5619 r.response.widget_info(|| {
5620 egui::WidgetInfo::labeled(egui::Role::ComboBox, true, format!("{name}: {current}"))
5621 });
5622 r.response.on_hover_text(name);
5623 let side = ui.spacing().interact_size.y;
5626 let (rect, r) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::click());
5627 r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, ¤t));
5628 let visuals = ui.style().interact(&r);
5629 if r.hovered() {
5630 ui.painter()
5631 .rect_filled(rect, visuals.corner_radius, visuals.bg_fill);
5632 }
5633 let glyph = egui_pop_core::kit::Kit::of(&ctx).glyph(if self.sort.descending {
5634 egui_pop_core::kit::Glyph::SortDescending
5635 } else {
5636 egui_pop_core::kit::Glyph::SortAscending
5637 });
5638 glyph.paint(ui.painter(), rect.shrink(side * 0.25), visuals.text_color());
5639 if r.clicked() {
5640 sort.descending = !sort.descending;
5641 }
5642 self.set_sort(sort);
5643 self.set_folders_first(folders_first);
5644 self.set_grouped(grouped);
5645 }
5646
5647 pub fn show(&mut self, ui: &mut Ui) -> BrowserOutput {
5649 let mut out = BrowserOutput::default();
5650 self.pump();
5651 if self.loading() || self.groups_pending() {
5652 ui.ctx().request_repaint();
5653 }
5654 ui.horizontal(|ui| {
5656 let infos = self.mode_infos();
5657 if let Some((id, _)) = mode_switcher(ui, self.id, &infos, &self.mode_id)
5658 && id != self.mode_id
5659 && self.set_mode(&id)
5660 {
5661 out.mode_changed = true;
5662 }
5663 if infos
5664 .iter()
5665 .any(|m| m.id == self.mode_id && m.needs.thumbnails)
5666 {
5667 let name = strings::tr(ui.ctx(), &crate::strings::FILES_THUMBNAIL_SIZE);
5668 let (width, gap) = self.grid_room;
5669 match self.resize {
5670 GridResize::PerRow => {
5671 let most = ThumbZoom::most_per_row(width, gap);
5673 let mut per_row = self.zoom.shown_per_row(width, gap);
5674 let r = ui.add(
5675 egui::Slider::new(&mut per_row, most..=1)
5676 .show_value(false)
5677 .text(name),
5678 );
5679 if r.changed() {
5680 self.set_thumbnails_per_row(per_row);
5681 }
5682 }
5683 GridResize::FixedSize => {
5684 let least = ThumbnailsMode::MIN_SIZE;
5686 let most = width.max(least);
5687 let mut side = match self.zoom.under(self.resize, width, gap) {
5688 ThumbZoom::Points(p) => p,
5689 ThumbZoom::PerRow(_) => self.zoom.side(width, gap),
5690 };
5691 let r = ui.add(
5692 egui::Slider::new(&mut side, least..=most)
5693 .show_value(false)
5694 .text(name),
5695 );
5696 if r.changed() {
5697 self.set_zoom(ThumbZoom::Points(side.round()));
5698 }
5699 }
5700 }
5701 }
5702 if !infos.iter().any(|m| m.id == self.mode_id && m.needs.time) {
5704 self.sort_menu(ui);
5705 }
5706 if self.mode.toolbar(ui, &mut self.settings) {
5708 self.reveal = true;
5709 }
5710 });
5711 if let Some(e) = &self.error {
5712 ui.label(e.to_string());
5713 return out;
5714 }
5715 let drag = self.drops.as_ref().and_then(|_| dragged(ui.ctx()));
5717 let zones = self.drop_zones(ui);
5719 let keys_id = self.id.with("entries");
5721 let focused = ui.memory(|m| m.has_focus(keys_id));
5722 let looking = self.quick_look && self.quick_look_keys(ui);
5724 if self.quick_look && focused {
5725 ui.ctx().data_mut(|d| d.insert_temp(focused_id(), true));
5726 }
5727 if focused && !self.quick_look && !looking {
5728 ui.ctx().data_mut(|d| d.insert_temp(focused_id(), true));
5729 let asked = mode_key(ui)
5731 .or_else(|| ui.ctx().data_mut(|d| d.remove_temp::<usize>(request_id())));
5732 if let Some(n) = asked
5733 && self.set_mode_index(n)
5734 {
5735 out.mode_changed = true;
5736 }
5737 let (events, modifiers) = ui.input(|i| (i.events.clone(), i.modifiers));
5738 let before = self.place.clone();
5739 let typing = !self.type_ahead.prefix.is_empty()
5742 && ui.input(|i| i.time) - self.type_ahead.at <= Self::TYPE_AHEAD_RESET;
5743 let mut spaced = false;
5744 let now = ui.input(|i| i.time);
5747 self.mode_took
5748 .retain(|(_, at)| now - *at <= Self::TYPE_AHEAD_RESET);
5749 for ev in events {
5750 match ev {
5751 egui::Event::Key {
5752 key,
5753 pressed: true,
5754 modifiers: mods,
5755 ..
5756 } if self
5757 .mode
5758 .own_key(key, mods, self.focus_index(), &mut self.settings) =>
5759 {
5760 self.reveal = true;
5761 self.mode_took
5762 .push((key.symbol_or_name().to_lowercase(), now));
5763 }
5764 egui::Event::Key {
5765 key, pressed: true, ..
5766 } => {
5767 let mk = match key {
5768 egui::Key::ArrowUp => Some(ModeKey::Up),
5769 egui::Key::ArrowDown => Some(ModeKey::Down),
5770 egui::Key::ArrowLeft => Some(ModeKey::Left),
5771 egui::Key::ArrowRight => Some(ModeKey::Right),
5772 egui::Key::PageUp => Some(ModeKey::PageUp),
5773 egui::Key::PageDown => Some(ModeKey::PageDown),
5774 egui::Key::Home => Some(ModeKey::Home),
5775 egui::Key::End => Some(ModeKey::End),
5776 _ => None,
5777 };
5778 if let Some(mk) = mk {
5779 out.selection_changed |= self.key(mk, modifiers.shift);
5780 } else if key == egui::Key::Enter {
5781 out.activated = self.focus.clone();
5782 } else if key == egui::Key::A && modifiers.command {
5783 self.select_all();
5784 out.selection_changed = true;
5785 } else if key == egui::Key::Space
5786 && modifiers.command
5787 && let Some(f) = self.focus.clone()
5788 {
5789 self.click(&f, Modifiers::COMMAND);
5790 out.selection_changed = true;
5791 } else if (key == egui::Key::Y && modifiers.command)
5792 || (key == egui::Key::Space && modifiers.is_none() && !typing)
5793 {
5794 self.set_quick_look(true);
5795 spaced |= key == egui::Key::Space;
5796 }
5797 }
5798 egui::Event::Text(t) if self.took_text(&t) => {}
5799 egui::Event::Text(t) if !(modifiers.command || spaced && t == " ") => {
5800 let now = ui.input(|i| i.time);
5801 self.type_ahead(&t, now);
5802 }
5803 _ => {}
5804 }
5805 }
5806 out.place_changed |= self.place != before;
5807 ui.memory_mut(|m| {
5809 m.set_focus_lock_filter(
5810 keys_id,
5811 egui::EventFilter {
5812 horizontal_arrows: true,
5813 vertical_arrows: true,
5814 tab: false,
5815 escape: false,
5816 },
5817 )
5818 });
5819 }
5820 let hierarchy = self.mode.describe().needs.hierarchy;
5821 if hierarchy {
5822 if self.sync_columns() {
5823 ui.ctx().request_repaint();
5824 }
5825 } else {
5826 self.columns.clear();
5828 }
5829 let focus = self.focus_index();
5830 let reveal = std::mem::take(&mut self.reveal);
5831 let (groups, app_marks) = (self.groups.clone(), self.marks.clone());
5834 let ctx = ui.ctx().clone();
5835 let with_groups = move |e: &SourceEntry| {
5836 let mut marks = app_marks.as_ref().map(|m| m(e)).unwrap_or_default();
5837 if let Some(g) = groups.get(&e.path) {
5838 marks.chips.extend(group_chips(&ctx, g));
5839 }
5840 marks
5841 };
5842 let grouped_thumbnails = GroupThumbnails {
5843 inner: self.thumbnails.as_ref(),
5844 groups: &self.groups,
5845 absorbed: &self.absorbed,
5846 };
5847 let (marks, thumbnails): (Option<&MarkEntries>, &dyn ThumbnailProvider) =
5848 if self.groups.is_empty() {
5849 (self.marks.as_deref(), self.thumbnails.as_ref())
5850 } else {
5851 (Some(&with_groups), &grouped_thumbnails)
5852 };
5853 thumbnails.begin_frame(ui.ctx());
5854 let inner = ui.scope(|ui| {
5855 let (width, gap) = ThumbnailGrid::room(ui);
5858 self.grid_room = (width, gap);
5859 self.zoom = self.zoom.under(self.resize, width, gap);
5860 self.settings.thumbnail_size = self.zoom.side(width, gap);
5861 self.mode.show(
5862 ui,
5863 ModeContext {
5864 entries: &self.entries,
5865 selection: &self.selection,
5866 focus,
5867 thumbnails,
5868 settings: &mut self.settings,
5869 id: self.id,
5870 reveal_focus: reveal,
5871 max_height: None,
5872 drawer: None,
5873 name: None,
5874 many: false,
5875 place: &self.place,
5876 ancestors: self.columns.ancestors(),
5877 peek: self.columns.peek(),
5878 loading: self.listing.is_some(),
5879 generation: self.generation,
5880 marks,
5881 },
5882 )
5883 });
5884 if self.quick_look && self.focus_index().is_none() {
5886 self.quick_look = false;
5887 }
5888 if self.quick_look {
5889 self.show_quick_look(ui, inner.response.rect, thumbnails);
5890 }
5891 thumbnails.end_frame(ui.ctx());
5892 let mode_out = inner.inner;
5893 let band = ui.ctx().data_mut(|d| {
5896 let key = band_key(self.id);
5897 let band = d.get_temp::<Band>(key);
5898 d.remove::<Band>(key);
5899 band
5900 });
5901 match band {
5902 Some(band) if self.policy.mode == SelectMode::Many => {
5903 out.selection_changed |= self.apply_band(&band);
5904 if band.finished {
5905 ui.memory_mut(|m| m.request_focus(keys_id));
5906 }
5907 }
5908 _ => self.band_base = None,
5909 }
5910 let container = ui.interact(
5912 inner.response.rect,
5913 keys_id,
5914 egui::Sense::focusable_noninteractive(),
5915 );
5916 let label = format!("Entries, {}", self.mode_id);
5917 container.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListBox, true, &label));
5918 if let Some((i, mods)) = mode_out.clicked {
5919 let path = self.entries[i].path.clone();
5920 self.click(&path, mods);
5921 self.reveal = true;
5924 out.selection_changed = true;
5925 ui.memory_mut(|m| m.request_focus(keys_id));
5926 }
5927 if let Some(i) = mode_out.activated {
5928 out.activated = Some(self.entries[i].path.clone());
5929 ui.memory_mut(|m| m.request_focus(keys_id));
5930 }
5931 self.drop_hover = None;
5933 if let Some((paths, origin, released)) = drag {
5934 let at = ui.input(|i| i.pointer.latest_pos());
5935 let entries_rect = inner.response.rect;
5936 let target = self.drop_target(at, entries_rect, &zones, &mode_out);
5937 if let Some((target, rect)) = target {
5938 let offer = DropOffer {
5939 target,
5940 paths,
5941 origin,
5942 };
5943 let accepted = self.accepts(&offer);
5944 self.paint_drop(ui, entries_rect, rect, &offer, accepted);
5945 if origin == DropOrigin::System {
5946 crate::bus::files::shown(ui.ctx());
5948 }
5949 if released {
5950 if accepted {
5951 match origin {
5952 DropOrigin::App => egui::DragAndDrop::clear_payload(ui.ctx()),
5953 DropOrigin::System => crate::bus::files::take(
5956 ui.ctx(),
5957 match &offer.target {
5958 DropTarget::Folder(p) | DropTarget::Place(p) => {
5959 format!("a file browser took them into `{}`", p.display())
5960 }
5961 DropTarget::App(id) => {
5962 format!("a file browser took them for `{id}`")
5963 }
5964 },
5965 ),
5966 }
5967 out.dropped = Some(offer);
5968 }
5969 } else {
5970 self.drop_hover = Some((offer, accepted));
5971 }
5972 }
5973 }
5974 if let Some(r) = mode_out.reach {
5975 self.reach(&r);
5976 out.selection_changed = true;
5977 out.place_changed = true;
5978 ui.memory_mut(|m| m.request_focus(keys_id));
5979 }
5980 out
5981 }
5982
5983 fn drop_zones(&self, ui: &mut Ui) -> Vec<(String, egui::Rect)> {
5986 if self.drops.is_none() || self.drop_targets.is_empty() {
5987 return Vec::new();
5988 }
5989 let mut zones = Vec::new();
5990 ui.horizontal(|ui| {
5991 for t in &self.drop_targets {
5992 let lit = self
5993 .drop_hover
5994 .as_ref()
5995 .filter(|(o, _)| o.target == DropTarget::App(t.id.clone()));
5996 let visuals = ui.visuals();
5997 let (stroke, fill) = match lit {
5998 Some((_, true)) => (
5999 egui::Stroke::new(2.0, visuals.selection.stroke.color),
6000 visuals.selection.bg_fill.gamma_multiply(0.5),
6001 ),
6002 Some((_, false)) => (
6003 egui::Stroke::new(2.0, visuals.error_fg_color),
6004 egui::Color32::TRANSPARENT,
6005 ),
6006 None => (
6007 egui::Stroke::new(1.0, visuals.widgets.noninteractive.bg_stroke.color),
6008 egui::Color32::TRANSPARENT,
6009 ),
6010 };
6011 let r = egui::Frame::new()
6012 .inner_margin(egui::Margin::symmetric(10, 4))
6013 .corner_radius(4.0)
6014 .stroke(stroke)
6015 .fill(fill)
6016 .show(ui, |ui| ui.label(&t.label))
6017 .response;
6018 zones.push((t.id.clone(), r.rect));
6019 }
6020 });
6021 zones
6022 }
6023
6024 fn drop_target(
6029 &self,
6030 at: Option<egui::Pos2>,
6031 entries: egui::Rect,
6032 zones: &[(String, egui::Rect)],
6033 mode_out: &ModeOutput,
6034 ) -> Option<(DropTarget, egui::Rect)> {
6035 let Some(at) = at else {
6036 return Some((DropTarget::Place(self.place.clone()), entries));
6037 };
6038 if let Some((id, r)) = zones.iter().find(|(_, r)| r.contains(at)) {
6039 return Some((DropTarget::App(id.clone()), *r));
6040 }
6041 if !entries.contains(at) {
6042 return None;
6043 }
6044 if let Some((i, r)) = mode_out.pointed
6045 && let Some(e) = self.entries.get(i).filter(|e| e.is_dir())
6046 {
6047 return Some((DropTarget::Folder(e.path.clone()), r));
6048 }
6049 if let Some((p, r)) = &mode_out.pointed_beside {
6050 return Some((DropTarget::Folder(p.clone()), *r));
6051 }
6052 Some((DropTarget::Place(self.place.clone()), entries))
6053 }
6054
6055 fn accepts(&self, offer: &DropOffer) -> bool {
6058 let into = match &offer.target {
6059 DropTarget::Folder(f) | DropTarget::Place(f) => Some(f),
6060 DropTarget::App(_) => None,
6061 };
6062 if into.is_some_and(|f| offer.paths.iter().any(|p| f.starts_with(p))) {
6063 return false;
6064 }
6065 self.drops.as_ref().is_some_and(|accept| accept(offer))
6066 }
6067
6068 fn paint_drop(
6073 &self,
6074 ui: &mut Ui,
6075 entries: egui::Rect,
6076 rect: egui::Rect,
6077 offer: &DropOffer,
6078 accepted: bool,
6079 ) {
6080 let ctx = ui.ctx().clone();
6081 let visuals = ui.visuals().clone();
6082 let color = if accepted {
6083 visuals.selection.stroke.color
6084 } else {
6085 visuals.error_fg_color
6086 };
6087 let painter = ctx.layer_painter(egui::LayerId::new(
6088 egui::Order::Foreground,
6089 self.id.with("drop"),
6090 ));
6091 if accepted {
6092 painter.rect_filled(rect, 4.0, visuals.selection.bg_fill.gamma_multiply(0.35));
6093 }
6094 painter.rect_stroke(
6095 rect.shrink(1.0),
6096 4.0,
6097 egui::Stroke::new(2.0, color),
6098 egui::StrokeKind::Inside,
6099 );
6100 ctx.set_cursor_icon(if accepted {
6101 egui::CursorIcon::Copy
6102 } else {
6103 egui::CursorIcon::NoDrop
6104 });
6105 let text = if accepted {
6106 let name = match &offer.target {
6107 DropTarget::Folder(p) | DropTarget::Place(p) => p.file_name().map_or_else(
6108 || p.display().to_string(),
6109 |n| n.to_string_lossy().into_owned(),
6110 ),
6111 DropTarget::App(id) => self
6112 .drop_targets
6113 .iter()
6114 .find(|t| &t.id == id)
6115 .map_or_else(|| id.clone(), |t| t.label.clone()),
6116 };
6117 strings::tr_args(&ctx, &crate::strings::FILES_DROP_INTO, &[("name", &name)])
6118 } else {
6119 strings::tr(&ctx, &crate::strings::FILES_DROP_REFUSED)
6120 };
6121 let font = egui::TextStyle::Body.resolve(ui.style());
6122 let galley = painter.layout_no_wrap(text.clone(), font, visuals.strong_text_color());
6123 let size = galley.size() + egui::vec2(16.0, 8.0);
6124 let shown = entries.intersect(ui.clip_rect());
6126 let shown = if shown.is_positive() { shown } else { entries };
6127 let caption = egui::Rect::from_center_size(
6128 egui::pos2(shown.center().x, shown.bottom() - size.y / 2.0 - 8.0),
6129 size,
6130 );
6131 painter.rect_filled(caption, 4.0, visuals.window_fill);
6132 painter.rect_stroke(
6133 caption,
6134 4.0,
6135 egui::Stroke::new(1.0, color),
6136 egui::StrokeKind::Inside,
6137 );
6138 painter.galley(
6139 caption.center() - galley.size() / 2.0,
6140 galley,
6141 visuals.strong_text_color(),
6142 );
6143 let r = ui.interact(caption, self.id.with("drop.caption"), egui::Sense::hover());
6144 r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &text));
6145 }
6146}
6147
6148#[derive(Clone, Debug, PartialEq, Eq)]
6152pub struct DraggedPaths(pub Vec<PathBuf>);
6153
6154#[derive(Clone, Debug, PartialEq, Eq, Hash)]
6156pub enum DropTarget {
6157 Folder(PathBuf),
6160 Place(PathBuf),
6162 App(String),
6164}
6165
6166#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6168pub enum DropOrigin {
6169 App,
6171 System,
6174}
6175
6176#[derive(Clone, Debug, PartialEq, Eq)]
6181pub struct DropOffer {
6182 pub target: DropTarget,
6183 pub paths: Vec<PathBuf>,
6184 pub origin: DropOrigin,
6185}
6186
6187#[derive(Clone, Debug, PartialEq, Eq)]
6190pub struct AppDropTarget {
6191 pub id: String,
6192 pub label: String,
6193}
6194
6195impl AppDropTarget {
6196 pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
6197 Self {
6198 id: id.into(),
6199 label: label.into(),
6200 }
6201 }
6202}
6203
6204type DropPolicy = Arc<dyn Fn(&DropOffer) -> bool + Send + Sync>;
6205
6206fn dragged(ctx: &egui::Context) -> Option<(Vec<PathBuf>, DropOrigin, bool)> {
6209 if let Some((paths, dropped)) = crate::bus::files::system_drag(ctx) {
6212 return Some((paths, DropOrigin::System, dropped));
6213 }
6214 let released = ctx.input(|i| i.pointer.any_released());
6215 let payload = egui::DragAndDrop::payload::<DraggedPaths>(ctx)?;
6216 Some((payload.0.clone(), DropOrigin::App, released))
6217}
6218
6219#[derive(Debug, Default)]
6221pub struct RecordedThumbnails {
6222 pub frames: Vec<Vec<(PathBuf, Priority)>>,
6224 pub cancelled: Vec<Vec<PathBuf>>,
6226}
6227
6228#[derive(Debug, Default)]
6231pub struct RecordingThumbnails {
6232 renewals: Mutex<Renewals>,
6233 current: Mutex<Vec<(PathBuf, Priority)>>,
6234 pub record: Mutex<RecordedThumbnails>,
6235}
6236
6237impl ThumbnailProvider for RecordingThumbnails {
6238 fn begin_frame(&self, _ctx: &egui::Context) {
6239 lock(&self.renewals).begin();
6240 lock(&self.current).clear();
6241 }
6242
6243 fn request(&self, _ctx: &egui::Context, r: &ThumbRequest<'_>) -> ThumbState {
6244 let mut cur = lock(&self.current);
6245 if !cur.iter().any(|(p, _)| *p == r.entry.path) {
6246 cur.push((r.entry.path.clone(), r.priority));
6247 }
6248 lock(&self.renewals).ask(r.entry, r.priority);
6249 ThumbState::Loading
6250 }
6251
6252 fn end_frame(&self, _ctx: &egui::Context) {
6253 let mut renewals = lock(&self.renewals);
6254 let _ = renewals.wanted();
6255 let dropped = renewals.dropped();
6256 let mut rec = lock(&self.record);
6257 rec.frames.push(lock(&self.current).clone());
6258 rec.cancelled.push(dropped);
6259 }
6260}
6261
6262pub type ThumbnailCache = HashMap<PathBuf, ThumbState>;
6264
6265#[cfg(test)]
6266mod tests {
6267 use super::*;
6268 use crate::files::fs::MemoryFs;
6269
6270 fn source() -> Arc<dyn FileSource> {
6271 let mut fs = MemoryFs::new().dir("/p").dir("/p/sub");
6272 for i in 1..=12 {
6273 fs = fs.file(format!("/p/IMG_{i}.png"), vec![0; i]);
6274 }
6275 Arc::new(FsSource::new(Arc::new(fs)).page_size(5))
6276 }
6277
6278 #[test]
6279 fn the_source_pages_and_the_browser_sorts() {
6280 let b = FileBrowser::new("t", source(), "/p");
6281 assert!(!b.loading());
6282 let names: Vec<_> = b.entries().iter().map(|e| e.name.as_str()).collect();
6283 assert_eq!(names[0], "sub");
6284 assert_eq!(names[1], "IMG_1.png");
6285 assert_eq!(names[2], "IMG_2.png");
6286 assert_eq!(names.len(), 13);
6287 }
6288
6289 #[test]
6290 fn a_missing_place_is_an_error() {
6291 let b = FileBrowser::new("t", source(), "/nope");
6292 assert_eq!(b.error(), Some(&SourceError::NotFound("/nope".into())));
6293 }
6294
6295 #[test]
6296 fn the_registry_refuses_a_taken_id_and_gives_modes_back() {
6297 let m = ViewModes::default();
6298 assert_eq!(m.ids(), ["details", "thumbnails"]);
6299 assert!(
6300 m.register("details", Arc::new(|| Box::new(DetailsMode::default())))
6301 .is_err()
6302 );
6303 assert!(m.unregister("thumbnails"));
6304 assert_eq!(m.ids(), ["details"]);
6305 assert!(m.make("thumbnails").is_none());
6306 }
6307
6308 #[test]
6309 fn switching_modes_keeps_selection_and_focus() {
6310 let mut b = FileBrowser::new("t", source(), "/p");
6311 b.click(Path::new("/p/IMG_2.png"), Modifiers::NONE);
6312 b.click(Path::new("/p/IMG_4.png"), Modifiers::SHIFT);
6313 let sel = b.selection().clone();
6314 assert_eq!(sel.len(), 3);
6315 assert!(b.set_mode("thumbnails"));
6316 assert_eq!(b.selection(), &sel);
6317 assert_eq!(b.focus(), Some(Path::new("/p/IMG_4.png")));
6318 assert!(b.set_mode("details"));
6319 assert_eq!(b.selection(), &sel);
6320 assert!(!b.set_mode("nope"));
6321 }
6322
6323 #[test]
6324 fn type_ahead_jumps_resets_and_cycles() {
6325 let mut b = FileBrowser::new("t", source(), "/p");
6326 assert!(b.type_ahead("i", 0.0));
6327 assert_eq!(b.focus(), Some(Path::new("/p/IMG_1.png")));
6328 assert!(b.type_ahead("mg_1", 0.2));
6329 assert_eq!(b.focus(), Some(Path::new("/p/IMG_1.png")));
6330 assert!(b.type_ahead("s", 5.0));
6332 assert_eq!(b.focus(), Some(Path::new("/p/sub")));
6333 assert!(b.type_ahead("i", 10.0));
6335 assert_eq!(b.focus(), Some(Path::new("/p/IMG_1.png")));
6336 assert!(b.type_ahead("i", 10.1));
6337 assert_eq!(b.focus(), Some(Path::new("/p/IMG_2.png")));
6338 }
6339
6340 #[test]
6341 fn each_mode_steps_by_its_layout() {
6342 let d = DetailsMode { rows_in_view: 4 };
6343 assert_eq!(d.step(3, 13, ModeKey::Down), 4);
6344 assert_eq!(d.step(3, 13, ModeKey::PageDown), 7);
6345 assert_eq!(d.step(0, 13, ModeKey::Up), 0);
6346 let t = ThumbnailsMode {
6347 columns: 4,
6348 rows_in_view: 2,
6349 };
6350 assert_eq!(t.step(1, 13, ModeKey::Down), 5);
6351 assert_eq!(t.step(5, 13, ModeKey::Up), 1);
6352 assert_eq!(t.step(5, 13, ModeKey::Right), 6);
6353 assert_eq!(t.step(10, 13, ModeKey::Down), 12);
6355 assert_eq!(t.step(0, 13, ModeKey::PageDown), 8);
6356 assert_eq!(t.step(12, 13, ModeKey::End), 12);
6357 }
6358
6359 #[test]
6360 fn the_carousel_steps_along_one_row() {
6361 let c = CarouselMode { per_side: 3 };
6362 assert_eq!(c.step(5, 13, ModeKey::Right), 6);
6363 assert_eq!(c.step(5, 13, ModeKey::Left), 4);
6364 assert_eq!(c.step(5, 13, ModeKey::Up), 5);
6365 assert_eq!(c.step(5, 13, ModeKey::PageDown), 8);
6366 assert_eq!(c.step(1, 13, ModeKey::PageUp), 0);
6367 assert_eq!(c.step(5, 13, ModeKey::End), 12);
6368 }
6369
6370 fn dated(name: &str, day: u64, taken: Option<u64>) -> SourceEntry {
6371 let at =
6372 |d: u64| SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(d * 86_400 + 3600);
6373 SourceEntry {
6374 path: PathBuf::from(format!("/p/{name}")),
6375 name: name.into(),
6376 kind: EntryKind::File,
6377 size: None,
6378 modified: (day > 0).then(|| at(day)),
6379 taken: taken.map(at),
6380 app_id: None,
6381 }
6382 }
6383
6384 fn laid(
6386 entries: &[SourceEntry],
6387 columns: usize,
6388 level: AgendaLevel,
6389 collapsed: &[Option<i64>],
6390 ) -> AgendaMode {
6391 let mut a = AgendaMode {
6392 rows_in_view: 2,
6393 ..AgendaMode::default()
6394 };
6395 a.index.update(entries, 1, level);
6396 a.layout
6397 .update(&a.index, columns, &collapsed.iter().copied().collect());
6398 a
6399 }
6400
6401 #[test]
6402 fn the_agenda_files_entries_by_day_the_newest_first_the_taken_time_first() {
6403 let entries = [
6404 dated("a", 10, None),
6405 dated("b", 12, None),
6406 dated("c", 12, Some(3)),
6408 dated("d", 10, None),
6409 dated("e", 0, None),
6410 dated("f", 10, None),
6411 ];
6412 let a = laid(&entries, 2, AgendaLevel::Day, &[]);
6413 assert_eq!(a.index.order, [1, 0, 3, 5, 2, 4]);
6414 let keys: Vec<_> = a.index.groups.iter().map(|(k, r)| (*k, r.len())).collect();
6415 assert_eq!(
6416 keys,
6417 [(Some(12), 1), (Some(10), 3), (Some(3), 1), (None, 1)]
6418 );
6419 assert_eq!(
6420 a.layout.lines,
6421 [
6422 AgendaLine::Heading(0),
6423 AgendaLine::Cells(0, 1),
6424 AgendaLine::Heading(1),
6425 AgendaLine::Cells(1, 3),
6426 AgendaLine::Cells(3, 4),
6427 AgendaLine::Heading(2),
6428 AgendaLine::Cells(4, 5),
6429 AgendaLine::Heading(3),
6430 AgendaLine::Cells(5, 6),
6431 ]
6432 );
6433 }
6434
6435 #[test]
6436 fn the_agenda_groups_by_month_and_by_year() {
6437 let entries = [
6439 dated("a", 10, None),
6440 dated("b", 12, None),
6441 dated("c", 45, None),
6442 dated("d", 365, None),
6443 ];
6444 let a = laid(&entries, 4, AgendaLevel::Month, &[]);
6445 let heads: Vec<_> = a
6446 .index
6447 .groups
6448 .iter()
6449 .map(|(k, r)| (AgendaLevel::Month.heading(k.unwrap()), r.len()))
6450 .collect();
6451 assert_eq!(
6452 heads,
6453 [
6454 ("1971-01".into(), 1),
6455 ("1970-02".into(), 1),
6456 ("1970-01".into(), 2)
6457 ]
6458 );
6459 let a = laid(&entries, 4, AgendaLevel::Year, &[]);
6460 let heads: Vec<_> = a
6461 .index
6462 .groups
6463 .iter()
6464 .map(|(k, r)| (AgendaLevel::Year.heading(k.unwrap()), r.len()))
6465 .collect();
6466 assert_eq!(heads, [("1971".into(), 1), ("1970".into(), 3)]);
6467 assert_eq!(AgendaLevel::Day.coarser().coarser(), AgendaLevel::Year);
6468 assert_eq!(AgendaLevel::Year.coarser(), AgendaLevel::Year);
6469 assert_eq!(AgendaLevel::Year.finer().finer(), AgendaLevel::Day);
6470 }
6471
6472 #[test]
6473 fn the_agenda_steps_across_its_days() {
6474 let entries = [
6475 dated("a", 10, None),
6476 dated("b", 12, None),
6477 dated("c", 3, None),
6478 dated("d", 10, None),
6479 dated("e", 10, None),
6480 ];
6481 let a = laid(&entries, 2, AgendaLevel::Day, &[]);
6483 assert_eq!(a.step(1, 5, ModeKey::Right), 0);
6485 assert_eq!(a.step(4, 5, ModeKey::Right), 2);
6486 assert_eq!(a.step(0, 5, ModeKey::Left), 1);
6487 assert_eq!(a.step(1, 5, ModeKey::Down), 0);
6489 assert_eq!(a.step(3, 5, ModeKey::Down), 4);
6490 assert_eq!(a.step(4, 5, ModeKey::Down), 2);
6491 assert_eq!(a.step(3, 5, ModeKey::Up), 1);
6492 assert_eq!(a.step(2, 5, ModeKey::Down), 2);
6493 assert_eq!(a.step(1, 5, ModeKey::PageDown), 4);
6494 assert_eq!(a.step(0, 5, ModeKey::Home), 1);
6495 assert_eq!(a.step(0, 5, ModeKey::End), 2);
6496 assert_eq!(a.step(1, 9, ModeKey::Right), 2);
6498 }
6499
6500 #[test]
6501 fn the_agenda_skips_a_collapsed_group() {
6502 let entries = [
6503 dated("a", 10, None),
6504 dated("b", 12, None),
6505 dated("c", 3, None),
6506 dated("d", 10, None),
6507 ];
6508 let a = laid(&entries, 2, AgendaLevel::Day, &[Some(10)]);
6510 assert_eq!(a.layout.shown, [1, 2]);
6511 assert_eq!(a.step(1, 4, ModeKey::Right), 2);
6512 assert_eq!(a.step(1, 4, ModeKey::Down), 2);
6513 assert_eq!(a.step(0, 4, ModeKey::Down), 2);
6515 assert_eq!(a.step(3, 4, ModeKey::Up), 1);
6516 assert_eq!(a.step(0, 4, ModeKey::End), 2);
6517 let all = laid(
6518 &entries,
6519 2,
6520 AgendaLevel::Day,
6521 &[Some(12), Some(10), Some(3)],
6522 );
6523 assert_eq!(all.step(0, 4, ModeKey::Down), 0);
6524 }
6525
6526 #[test]
6527 fn renewals_order_by_priority_and_drop_what_was_not_asked_again() {
6528 let e = |n: &str| SourceEntry {
6529 path: n.into(),
6530 name: n.into(),
6531 kind: EntryKind::File,
6532 size: None,
6533 modified: None,
6534 taken: None,
6535 app_id: None,
6536 };
6537 let mut r = Renewals::default();
6538 r.begin();
6539 r.ask(&e("near"), Priority::Near);
6540 r.ask(&e("a"), Priority::Visible);
6541 r.ask(&e("b"), Priority::Visible);
6542 let w: Vec<_> = r.wanted().into_iter().map(|(p, _)| p).collect();
6543 assert_eq!(w, [PathBuf::from("a"), "b".into(), "near".into()]);
6544 r.begin();
6545 r.ask(&e("b"), Priority::Visible);
6546 assert_eq!(r.dropped(), [PathBuf::from("a"), "near".into()]);
6547 }
6548}