Skip to main content

capsule_core/import/
group.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3
4type StemKey = (Option<PathBuf>, String);
5type StemFiles = Vec<(PathBuf, String)>;
6
7use crate::domain::{DetectionMethod, MemberRole, StackType};
8use crate::import::scan::ImportCandidate;
9use crate::metadata::AssetType;
10
11// ── Extension sets ──────────────────────────────────────────────────────────
12
13pub const RAW_EXTS: &[&str] = &[
14    "arw", "cr2", "cr3", "nef", "nrw", "rw2", "orf", "pef", "raf", "srw", "3fr", "dcr", "dng",
15    "erf", "mef", "mos", "mrw", "ptx", "rwl", "x3f",
16];
17
18pub const PRIMARY_EXTS: &[&str] = &["jpg", "jpeg", "heic", "heif", "avif", "png", "tiff", "tif"];
19
20pub const VIDEO_EXTS: &[&str] = &["mp4", "mov", "m4v", "avi", "mkv", "mts", "m2ts"];
21
22const XMP_EXT: &str = "xmp";
23
24pub(crate) fn is_raw(ext: &str) -> bool {
25    RAW_EXTS.contains(&ext.to_lowercase().as_str())
26}
27pub(crate) fn is_primary(ext: &str) -> bool {
28    PRIMARY_EXTS.contains(&ext.to_lowercase().as_str())
29}
30pub fn is_video(ext: &str) -> bool {
31    VIDEO_EXTS.contains(&ext.to_lowercase().as_str())
32}
33pub(crate) fn is_xmp(ext: &str) -> bool {
34    ext.to_lowercase() == XMP_EXT
35}
36
37// ── Grouping ─────────────────────────────────────────────────────────────────
38
39/// Group a flat list of files by directory+stem, assigning member roles.
40///
41/// RAW+primary pairs → `RawJpeg` stack.
42/// RAW-only (no primary) → standalone (no stack_hint).
43/// Primary-only → standalone.
44/// Video → always standalone, even beside a same-stem still.
45/// XMP → paired with the same-stem RAW+primary stack, or, among unpaired same-stem stills,
46/// with the first in path order only; standalone if no still shares its stem.
47/// Ungrouped extensions → standalone Sidecar.
48///
49/// Every input file lands in exactly one candidate.
50///
51/// Files in different parent directories are never grouped together.
52pub fn group_by_stem(files: &[PathBuf]) -> Vec<ImportCandidate> {
53    // Map: (parent, lowercase_stem) → Vec<(path, lowercase_ext)>
54    let mut by_stem: HashMap<StemKey, StemFiles> = HashMap::new();
55
56    for path in files {
57        let parent = path.parent().map(PathBuf::from);
58        let stem = path
59            .file_stem()
60            .unwrap_or_default()
61            .to_string_lossy()
62            .to_lowercase();
63        let ext = path
64            .extension()
65            .unwrap_or_default()
66            .to_string_lossy()
67            .to_lowercase();
68        by_stem
69            .entry((parent, stem))
70            .or_default()
71            .push((path.clone(), ext));
72    }
73
74    let mut candidates = Vec::new();
75
76    for ((_, stem), paths_exts) in by_stem {
77        let raws: Vec<PathBuf> = paths_exts
78            .iter()
79            .filter(|(_, e)| is_raw(e))
80            .map(|(p, _)| p.clone())
81            .collect();
82        let primaries: Vec<PathBuf> = paths_exts
83            .iter()
84            .filter(|(_, e)| is_primary(e))
85            .map(|(p, _)| p.clone())
86            .collect();
87        let videos: Vec<PathBuf> = paths_exts
88            .iter()
89            .filter(|(_, e)| is_video(e))
90            .map(|(p, _)| p.clone())
91            .collect();
92        let xmps: Vec<PathBuf> = paths_exts
93            .iter()
94            .filter(|(_, e)| is_xmp(e))
95            .map(|(p, _)| p.clone())
96            .collect();
97        let others: Vec<PathBuf> = paths_exts
98            .iter()
99            .filter(|(_, e)| !is_raw(e) && !is_primary(e) && !is_video(e) && !is_xmp(e))
100            .map(|(p, _)| p.clone())
101            .collect();
102
103        if !raws.is_empty() && !primaries.is_empty() {
104            // RAW+primary pair → RawJpeg stack
105            let mut members: Vec<(PathBuf, MemberRole)> = Vec::new();
106            for p in &primaries {
107                members.push((p.clone(), MemberRole::Primary));
108            }
109            for p in &raws {
110                members.push((p.clone(), MemberRole::Raw));
111            }
112            for p in &xmps {
113                members.push((p.clone(), MemberRole::Sidecar));
114            }
115            let source_paths: Vec<PathBuf> = members.iter().map(|(p, _)| p.clone()).collect();
116            candidates.push(ImportCandidate {
117                source_paths,
118                detected_type: AssetType::Photo,
119                stack_type: Some(StackType::RawJpeg),
120                detection_method: Some(DetectionMethod::FilenameStem),
121                detection_key: Some(stem.clone()),
122                members,
123            });
124        } else if !raws.is_empty() || !primaries.is_empty() {
125            // RAW-only or primary-only: each still is its own standalone candidate. The
126            // same-stem XMPs ride with the first still in path order only, so one XMP never
127            // lands in two candidates whatever order the scan listed the files in (issue #788).
128            let mut stills = if raws.is_empty() {
129                primaries.clone()
130            } else {
131                raws.clone()
132            };
133            stills.sort();
134            for (index, still) in stills.iter().enumerate() {
135                let mut members = vec![(still.clone(), MemberRole::Primary)];
136                if index == 0 {
137                    for xmp in &xmps {
138                        members.push((xmp.clone(), MemberRole::Sidecar));
139                    }
140                }
141                let source_paths = members.iter().map(|(p, _)| p.clone()).collect();
142                candidates.push(ImportCandidate {
143                    source_paths,
144                    detected_type: AssetType::Photo,
145                    stack_type: None,
146                    detection_method: None,
147                    detection_key: None,
148                    members,
149                });
150            }
151        }
152
153        // Every video is its own standalone candidate, whether or not a still shares its stem:
154        // an unpaired `IMG_0001.JPG` + `IMG_0001.MOV` is two originals, and neither may be
155        // dropped (issue #695). Live Photo pairs were matched by content identifier before
156        // this grouping ran.
157        for video in &videos {
158            candidates.push(ImportCandidate {
159                source_paths: vec![video.clone()],
160                detected_type: AssetType::Video,
161                stack_type: None,
162                detection_method: None,
163                detection_key: None,
164                members: vec![(video.clone(), MemberRole::Primary)],
165            });
166        }
167
168        // An XMP rides with a same-stem still above; with no still to ride with (alone, or
169        // beside a video only) it is kept as its own candidate.
170        if raws.is_empty() && primaries.is_empty() {
171            for xmp in &xmps {
172                candidates.push(ImportCandidate {
173                    source_paths: vec![xmp.clone()],
174                    detected_type: AssetType::Sidecar,
175                    stack_type: None,
176                    detection_method: None,
177                    detection_key: None,
178                    members: vec![(xmp.clone(), MemberRole::Sidecar)],
179                });
180            }
181        }
182
183        // Unrecognised extensions → each is kept as its own standalone candidate. The
184        // extension lists above decide grouping only, never whether a file is backed up.
185        for other in &others {
186            candidates.push(ImportCandidate {
187                source_paths: vec![other.clone()],
188                detected_type: AssetType::Sidecar,
189                stack_type: None,
190                detection_method: None,
191                detection_key: None,
192                members: vec![(other.clone(), MemberRole::Sidecar)],
193            });
194        }
195    }
196
197    candidates
198}
199
200// ── Tests ────────────────────────────────────────────────────────────────────
201
202#[cfg(test)]
203mod tests;