background_picker/
scanner.rs1use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5
6use walkdir::WalkDir;
7
8const IMAGE_EXTENSIONS: &[&str] = &["jpg", "jpeg", "png", "gif", "bmp", "webp"];
9
10#[must_use]
11pub fn is_image_file(path: &Path) -> bool {
12 path.extension()
13 .and_then(|ext| ext.to_str())
14 .is_some_and(|ext_str| {
15 IMAGE_EXTENSIONS
16 .iter()
17 .any(|&valid_ext| valid_ext.eq_ignore_ascii_case(ext_str))
18 })
19}
20
21#[derive(Clone)]
22pub struct ImageInfo {
23 pub path: PathBuf,
24 pub thumbnail: Option<egui::TextureHandle>,
25 pub relative_path: String,
26 pub loading: bool,
27}
28
29pub struct ScanResult {
32 pub images: Vec<ImageInfo>,
33 pub folder_tree: BTreeMap<String, Vec<usize>>,
34}
35
36#[must_use]
39pub fn scan(base_path: &Path) -> ScanResult {
40 let mut images = Vec::new();
41 let mut folder_tree: BTreeMap<String, Vec<usize>> = BTreeMap::new();
42
43 let entries = WalkDir::new(base_path)
44 .into_iter()
45 .filter_map(Result::ok)
46 .filter(|e| e.file_type().is_file() && is_image_file(e.path()));
47
48 for entry in entries {
49 let relative_path = entry.path().strip_prefix(base_path).map_or_else(
50 |_| entry.path().to_string_lossy().into_owned(),
51 |p| p.to_string_lossy().into_owned(),
52 );
53
54 let folder = entry
55 .path()
56 .parent()
57 .and_then(|p| p.strip_prefix(base_path).ok())
58 .map_or_else(|| ".".to_owned(), |p| p.to_string_lossy().into_owned());
59
60 let image_index = images.len();
61 images.push(ImageInfo {
62 path: entry.path().to_path_buf(),
63 thumbnail: None,
64 relative_path,
65 loading: false,
66 });
67
68 folder_tree.entry(folder).or_default().push(image_index);
69 }
70
71 ScanResult {
72 images,
73 folder_tree,
74 }
75}