Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
45501dd
export: support {album}, {date}, and {hour} variables in subfolder field
bd78 Nov 6, 2026
ebabbfc
engine: move chrono to common dependencies for wasm support
bd78 Nov 6, 2026
fb4c77b
export: address PR review feedback for subfolder variables
bd78 Nov 7, 2026
7e17abd
gitignore: ignore bdu scratch files and action plans
bd78 Nov 7, 2026
131f98f
export: insert '_' after base for Windows device names and recognize …
bd78 Nov 7, 2026
7eae4e9
i18n: provide native translations for subfolder variable keys across …
bd78 Nov 7, 2026
47b5eae
Merge branch 'main' into export-album-var
bd78 Nov 7, 2026
948e35c
docs: enrich subfolder variable documentation in user guide, whats-ne…
bd78 Nov 7, 2026
4f0c09f
tests: split subfolder export tests into focused cases to satisfy cog…
bd78 Nov 7, 2026
2686638
docs: revert unreleased feature text in export user guide per docs/us…
bd78 Nov 7, 2026
3efd10f
Merge branch 'main' into export-album-var
bd78 Nov 11, 2026
15de4c9
Merge branch 'main' into export-album-var
bd78 Nov 11, 2026
0888bcb
Merge origin/main into export-album-var
bd78 Nov 18, 2026
54446ba
Merge remote-tracking branch 'origin/export-album-var'
bd78 Nov 18, 2026
ac7a66c
Drop an unrelated .gitignore entry from the export subfolder branch
bd78 Nov 18, 2026
32f3b91
Merge branch 'main' into export-album-var
bd78 Nov 25, 2026
a3281b7
Merge main (5ced0a20dc) into export-album-var
FredApps Nov 26, 2026
914fc9f
Export subfolder: {date} and {hour} in local time, not UTC (the day t…
FredApps Nov 26, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ plan/

# Python tools import their public operator family.
__pycache__/

# Scratch / agent action plans
bdu-*.md
3 changes: 1 addition & 2 deletions crates/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,11 @@ harfrust = { version = "0.13", default-features = false, features = ["std"] }
unicode-normalization = "0.1"
unicode-segmentation = "1.13"
lightcraft-segment = { workspace = true, optional = true }
chrono = { workspace = true }

# model downloads run natively only (the web build fetches no models)
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
lightcraft-fetch = { workspace = true }
# capture-time parsing for face recognition (native only)
chrono = { workspace = true }
# free space of the drive holding the preview cache (the low-disk alert; pure Rust: rustix / windows-sys)
fs4 = { workspace = true }

Expand Down
7 changes: 5 additions & 2 deletions crates/engine/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub use params::{
};
#[cfg(test)]
use place::Placer;
pub use place::{write_file, write_file_durable, write_file_new};
pub use place::{clean_album_name, clean_subfolder, expand_subfolder, write_file, write_file_durable, write_file_new};
pub use prepare::{
AfterExport, Destination, DngCompression, Exported, PreparedExport, export_batch, export_photo, output_size, prepare_batch, prepare_export,
};
Expand Down Expand Up @@ -74,7 +74,10 @@ pub struct ExportOptions {
pub start_number: u32,
/// A specific folder for the whole batch, or each photo's own folder.
pub destination_mode: DestinationMode,
/// Created inside the destination folder (empty = none).
/// Created inside the destination folder (empty = none). Supports `{album}`, `{date}`
/// (YYYYMMDD, UTC) and `{hour}` (HHMM, UTC) variables, expanded during batch preparation
/// once per batch using the active album view (or empty outside an album view). Presets store
/// the raw template.
pub subfolder: String,
/// When a file of the same name exists in the destination folder.
pub conflict: Conflict,
Expand Down
11 changes: 6 additions & 5 deletions crates/engine/src/export/batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,13 @@ pub(super) fn run_batch_with(
if !progress(i, &item.file_name) {
break;
}
let (photo, name, guard, source_dir) = (item.photo, item.file_name.clone(), item.guard.clone(), item.source_dir.clone());
placer.place(photo, name, source_dir.as_deref(), &guard, run_gated(item))?;
let (photo, name, guard, source_dir, subfolder) =
(item.photo, item.file_name.clone(), item.guard.clone(), item.source_dir.clone(), item.subfolder.clone());
placer.place(photo, name, source_dir.as_deref(), Some(&subfolder), &guard, run_gated(item))?;
}
return Ok(std::mem::take(&mut placer.out));
}
let heads: Vec<_> = items.iter().map(|i| (i.photo, i.file_name.clone(), i.guard.clone(), i.source_dir.clone())).collect();
let heads: Vec<_> = items.iter().map(|i| (i.photo, i.file_name.clone(), i.guard.clone(), i.source_dir.clone(), i.subfolder.clone())).collect();
let queue = Queue {
lane: std::sync::Mutex::new(Lane { items: items.into_iter().map(Some).collect(), next: 0, placed: 0, stop: false, done: Default::default() }),
cv: std::sync::Condvar::new(),
Expand All @@ -74,12 +75,12 @@ pub(super) fn run_batch_with(
}
}
let placed = || {
for (i, (photo, name, guard, source_dir)) in heads.into_iter().enumerate() {
for (i, (photo, name, guard, source_dir, subfolder)) in heads.into_iter().enumerate() {
if !progress(i, &name) {
break;
}
let e = queue.result(i);
placer.place(photo, name, source_dir.as_deref(), &guard, e)?;
placer.place(photo, name, source_dir.as_deref(), Some(&subfolder), &guard, e)?;
}
Ok::<_, String>(())
};
Expand Down
95 changes: 91 additions & 4 deletions crates/engine/src/export/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,97 @@ fn join_path(a: &str, b: &str) -> String {
/// A subfolder that stays inside the destination folder (issue #2571): `\`, `:` and NUL become `_`
/// (so no drive, root or Windows separator), and empty, `.` and `..` parts are dropped; `a/b` still
/// nests. Applied where the folder is used, so presets and the Export dialog's field are covered too.
pub(super) fn clean_subfolder(s: &str) -> String {
pub fn clean_subfolder(s: &str) -> String {
let s = s.trim().replace(['\\', ':', '\0'], "_");
s.split('/').map(str::trim).filter(|p| !p.is_empty() && *p != "." && *p != "..").collect::<Vec<_>>().join("/")
}

/// Clean an album name so it is safe to use as a directory or path component.
///
/// Characters `/ \ : * ? " < > | \0` and control characters become `_`, and surrounding
/// whitespace and dots are trimmed. Windows-reserved device names (`CON`, `PRN`, `AUX`, `NUL`,
/// `COM1`–`COM9`, `LPT1`–`LPT9`, plus superscript forms `COM¹`–`COM³`, `LPT¹`–`LPT³`, case-insensitive)
/// get `_` inserted after the base component so they remain usable directory components. The result
/// may be empty if the album name consisted entirely of dots or whitespace.
pub fn clean_album_name(album: &str) -> String {
let mut s: String = album
.chars()
.map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0') || c.is_control() { '_' } else { c })
.collect();
loop {
let trimmed = s.trim().trim_matches('.');
if trimmed == s {
break;
}
s = trimmed.to_string();
}
let base = s.split('.').next().unwrap_or(&s);
let upper = base.to_uppercase();
if matches!(
upper.as_str(),
"CON"
| "PRN"
| "AUX"
| "NUL"
| "COM1"
| "COM2"
| "COM3"
| "COM4"
| "COM5"
| "COM6"
| "COM7"
| "COM8"
| "COM9"
| "LPT1"
| "LPT2"
| "LPT3"
| "LPT4"
| "LPT5"
| "LPT6"
| "LPT7"
| "LPT8"
| "LPT9"
| "COM¹"
| "COM²"
| "COM³"
| "LPT¹"
| "LPT²"
| "LPT³"
) {
s.insert(base.len(), '_');
}
s
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// Expand `{album}`, `{date}`, `{hour}` variables in a subfolder template, and clean the result
/// so it stays safely inside the destination folder.
///
/// `{date}` and `{hour}` are expanded before `{album}`, so an album name that contains token-like
/// text (such as `{date}` or `{hour}`) is never double-expanded.
///
/// - `album`: the active album name, cleaned with [`clean_album_name`]; `None` expands `{album}` to `""`.
/// - `now`: the UTC timestamp for `{date}` (YYYYMMDD) and `{hour}` (HHMM); `None` uses current UTC time.
/// - Unknown tokens are left unchanged. The result passes through [`clean_subfolder`].
///
/// Returns immediately without timestamp formatting or album lookup if `template` is empty or has no `{`.
pub fn expand_subfolder(template: &str, album: Option<&str>, now: Option<chrono::NaiveDateTime>) -> String {
if template.is_empty() || !template.contains('{') {
return clean_subfolder(template);
}
let now = now.unwrap_or_else(|| {
let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default();
let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX);
chrono::DateTime::from_timestamp(secs, 0).map(|dt| dt.naive_utc()).unwrap_or_default()
});
let date_str = now.format("%Y%m%d").to_string();
let hour_str = now.format("%H%M").to_string();
let album_str = album.map(clean_album_name).unwrap_or_default();

let res = template.replace("{date}", &date_str).replace("{hour}", &hour_str).replace("{album}", &album_str);

clean_subfolder(&res)
}

impl<'a> Placer<'a> {
pub(super) fn new(
o: &'a ExportOptions,
Expand All @@ -82,7 +168,7 @@ impl<'a> Placer<'a> {
/// The folder photo `name` (its original in `source_dir`) is written to: the batch's folder or
/// the photo's own ([`DestinationMode`]), plus the subfolder. An error for a photo with no
/// folder of its own, or whose folder is gone: never a file written somewhere else instead.
fn folder_for(&self, name: &str, source_dir: Option<&str>) -> Result<String, String> {
fn folder_for(&self, name: &str, source_dir: Option<&str>, subfolder: Option<&str>) -> Result<String, String> {
let base = match self.o.destination_mode {
DestinationMode::SpecificFolder => self.to.dir.clone(),
DestinationMode::SameAsOriginal => {
Expand All @@ -97,7 +183,7 @@ impl<'a> Placer<'a> {
d.to_string()
}
};
let sub = clean_subfolder(&self.o.subfolder);
let sub = subfolder.map(clean_subfolder).unwrap_or_else(|| expand_subfolder(&self.o.subfolder, None, None));
Ok(if sub.is_empty() { base } else { join_path(&base, &sub) })
}

Expand All @@ -108,12 +194,13 @@ impl<'a> Placer<'a> {
photo: lightcraft_catalog::PhotoId,
name: String,
source_dir: Option<&str>,
subfolder: Option<&str>,
guard: &crate::originals::OriginalGuard,
e: Result<Exported, String>,
) -> Result<(), String> {
use serde_json::json;
// an exact file path needs no folder
let dir = if self.to.exact.is_some() && self.single { Ok(String::new()) } else { self.folder_for(&name, source_dir) };
let dir = if self.to.exact.is_some() && self.single { Ok(String::new()) } else { self.folder_for(&name, source_dir, subfolder) };
let (o, exists) = (self.o, self.exists);
let (dir, e) = match dir.and_then(|dir| e.map(|e| (dir, e))) {
Ok(v) => v,
Expand Down
23 changes: 20 additions & 3 deletions crates/engine/src/export/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ pub struct PreparedExport {
/// The folder of the photo's original on disk ([`DestinationMode::SameAsOriginal`]); `None`
/// for a demo photo or one in the browser's storage.
pub source_dir: Option<String>,
/// The already-expanded, cleaned subfolder path for this item. Resolved once per batch at
/// preparation time; no raw variable tokens are present.
pub subfolder: String,
work: Work,
/// The library's originals, which [`run_batch`] never writes over (shared by a batch).
pub(super) guard: std::sync::Arc<crate::originals::OriginalGuard>,
Expand Down Expand Up @@ -88,13 +91,24 @@ pub fn prepare_export(
seq: usize,
) -> Result<PreparedExport, String> {
let guard = std::sync::Arc::new(session.original_guard());
prepare_guarded(session, id, o, seq, guard)
let album_name = match session.source {
crate::LibrarySource::Album(aid) => session.catalog.album(aid).map(|a| a.name.clone()),
_ => None,
};
prepare_guarded(session, id, o, seq, guard, None, album_name.as_deref())
}

/// [`prepare_export`] for each of `ids` in order (`{seq}` = position, from 1).
pub fn prepare_batch(session: &mut crate::Session, ids: &[lightcraft_catalog::PhotoId], o: &ExportOptions) -> Result<Vec<PreparedExport>, String> {
let guard = std::sync::Arc::new(session.original_guard());
ids.iter().enumerate().map(|(i, id)| prepare_guarded(session, *id, o, i + 1, guard.clone())).collect()
let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default();
let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX);
let now = chrono::DateTime::from_timestamp(secs, 0).map(|dt| dt.naive_utc());
let album_name = match session.source {
crate::LibrarySource::Album(aid) => session.catalog.album(aid).map(|a| a.name.clone()),
_ => None,
};
ids.iter().enumerate().map(|(i, id)| prepare_guarded(session, *id, o, i + 1, guard.clone(), now, album_name.as_deref())).collect()
}

fn prepare_guarded(
Expand All @@ -103,10 +117,13 @@ fn prepare_guarded(
o: &ExportOptions,
seq: usize,
guard: std::sync::Arc<crate::originals::OriginalGuard>,
now: Option<chrono::NaiveDateTime>,
album: Option<&str>,
) -> Result<PreparedExport, String> {
let p = session.catalog.photo(id).ok_or("no such photo")?;
let file_name = o.file_name_for(p, seq);
let source_dir = original_folder(&p.source);
let subfolder = super::place::expand_subfolder(&o.subfolder, album, now);
// HDR output only for photos edited in HDR; the rest of the batch exports as usual
let sdr_opts;
let o = if o.hdr && !p.develop.hdr.enabled {
Expand Down Expand Up @@ -162,7 +179,7 @@ fn prepare_guarded(
};
(work, weight)
};
Ok(PreparedExport { photo: id, file_name, source_dir, work, guard, weight })
Ok(PreparedExport { photo: id, file_name, source_dir, subfolder, work, guard, weight })
}

/// The folder a photo's original is in, for [`DestinationMode::SameAsOriginal`]. None for a demo
Expand Down
110 changes: 110 additions & 0 deletions crates/engine/src/tests/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,116 @@ fn a_subfolder_never_leaves_the_destination_folder() {
assert_eq!(o.subfolder, "up");
}

#[test]
fn subfolder_variables_expansion_and_presets() {
use crate::export::{Destination, clean_album_name, expand_subfolder, export_batch};

// Album name cleaning
assert_eq!(clean_album_name("Summer 2026"), "Summer 2026");
assert_eq!(clean_album_name("Trip: Tokyo / Kyoto * 2026?"), "Trip_ Tokyo _ Kyoto _ 2026_");
assert_eq!(clean_album_name("..hidden.."), "hidden");
assert_eq!(clean_album_name("..."), "");
assert_eq!(clean_album_name(" "), "");
// Windows reserved device names (bare and with extension, ASCII and superscript)
assert_eq!(clean_album_name("CON"), "CON_");
assert_eq!(clean_album_name("con"), "con_");
assert_eq!(clean_album_name("con.txt"), "con_.txt");
assert_eq!(clean_album_name("PRN"), "PRN_");
assert_eq!(clean_album_name("AUX"), "AUX_");
assert_eq!(clean_album_name("NUL"), "NUL_");
assert_eq!(clean_album_name("COM1"), "COM1_");
assert_eq!(clean_album_name("com9"), "com9_");
assert_eq!(clean_album_name("LPT1"), "LPT1_");
assert_eq!(clean_album_name("lpt9"), "lpt9_");
assert_eq!(clean_album_name("NUL.tar.gz"), "NUL_.tar.gz");
assert_eq!(clean_album_name("COM¹"), "COM¹_");
assert_eq!(clean_album_name("com²"), "com²_");
assert_eq!(clean_album_name("lpt³"), "lpt³_");
assert_eq!(clean_album_name("com¹.backup"), "com¹_.backup");

// Expand variables with fixed date/time: 2026-11-05 14:30
let fixed_time = chrono::NaiveDate::from_ymd_opt(2026, 11, 5).unwrap().and_hms_opt(14, 30, 0);
assert_eq!(expand_subfolder("{album}", Some("Vacation"), fixed_time), "Vacation");
assert_eq!(expand_subfolder("{album}", None, fixed_time), "");
assert_eq!(expand_subfolder("{date}", None, fixed_time), "20261105");
assert_eq!(expand_subfolder("{hour}", None, fixed_time), "1430");
assert_eq!(expand_subfolder("{album}/{date}_{hour}", Some("Portraits / 2026"), fixed_time), "Portraits _ 2026/20261105_1430");
assert_eq!(expand_subfolder("Exports/{album}/{date}", None, fixed_time), "Exports/20261105");

// Token replacement order: album named literally {date} or {hour} is not double-expanded
assert_eq!(expand_subfolder("{album}", Some("{date}"), fixed_time), "{date}");
assert_eq!(expand_subfolder("{album}/{date}", Some("{date}"), fixed_time), "{date}/20261105");
assert_eq!(expand_subfolder("{album}/{hour}", Some("{hour}"), fixed_time), "{hour}/1430");

// Presets save and restore subfolder with variables intact
let mut s = Session::with_demo();
s.execute(
"export.savePreset",
&json!({
"name": "Date & Album",
"params": {
"format": "jpeg",
"subfolder": "{album}/{date}_{hour}"
}
}),
)
.unwrap();
let loaded = s.export_params(&json!({"preset": "Date & Album"})).unwrap();
assert_eq!(loaded["subfolder"], "{album}/{date}_{hour}");
let opts = ExportOptions::from_json(&loaded);
assert_eq!(opts.subfolder, "{album}/{date}_{hour}");

// Export batch with active album view
let id = s.active().unwrap();
let album_id = s.execute("album.create", &json!({"name": "Holiday: Spain", "addSelected": true})).unwrap()["id"].as_u64().unwrap();
s.source = crate::LibrarySource::Album(lightcraft_catalog::AlbumId(album_id));

let to = Destination { dir: "out".into(), exact: None };
let mut written = Vec::new();
let mut write = |p: &str, _: &[u8]| {
written.push(p.to_string());
Ok(())
};
export_batch(&mut s, &[id], &opts, &to, &mut write, &|_| false).unwrap();
assert_eq!(written.len(), 1);
assert!(written[0].starts_with("out/Holiday_ Spain/"), "actual: {}", written[0]);
assert!(!written[0].contains("{date}"), "date not expanded: {}", written[0]);
assert!(!written[0].contains("{hour}"), "hour not expanded: {}", written[0]);

// Multi-photo batch: verify both photos resolve date and hour, use the exact same batch timestamp
// and do not cross minute boundaries
let mut written_multi = Vec::new();
let mut write_multi = |p: &str, _: &[u8]| {
written_multi.push(p.to_string());
Ok(())
};
export_batch(&mut s, &[id, id], &opts, &to, &mut write_multi, &|_| false).unwrap();
assert_eq!(written_multi.len(), 2);
// Both items must have identical subfolder paths
let sub0 = written_multi[0].strip_prefix("out/Holiday_ Spain/").unwrap_or("");
let sub1 = written_multi[1].strip_prefix("out/Holiday_ Spain/").unwrap_or("");
let dir0 = sub0.split('/').next().unwrap_or("");
let dir1 = sub1.split('/').next().unwrap_or("");
assert_eq!(dir0, dir1, "batch items must share the exact same timestamp subfolder");
let (d, h) = dir0.split_once('_').unwrap_or(("", ""));
assert_eq!(d.len(), 8, "date segment must be YYYYMMDD (8 digits): {d}");
assert_eq!(h.len(), 4, "hour segment must be HHMM (4 digits): {h}");
assert!(d.chars().all(|c| c.is_ascii_digit()), "date must be digits: {d}");
assert!(h.chars().all(|c| c.is_ascii_digit()), "hour must be digits: {h}");

// Outside album view: {album} expands to empty string, not an arbitrary first album
s.source = crate::LibrarySource::All;
let mut written_outside = Vec::new();
let mut write_outside = |p: &str, _: &[u8]| {
written_outside.push(p.to_string());
Ok(())
};
export_batch(&mut s, &[id], &opts, &to, &mut write_outside, &|_| false).unwrap();
assert_eq!(written_outside.len(), 1);
assert!(!written_outside[0].contains("Holiday"), "outside album view should not use album name: {}", written_outside[0]);
assert!(!written_outside[0].contains("//"), "clean_subfolder prevents double slashes: {}", written_outside[0]);
}

#[test]
fn prepared_exports_run_on_another_thread() {
fn send<T: Send>(_: &T) {}
Expand Down
8 changes: 7 additions & 1 deletion crates/ui-egui/locales/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -2472,5 +2472,11 @@
"Welcome": "Vítejte",
"Next": "Další",
"Get Started": "Začít",
"Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie"
"Stopped at the scan limit: there may be more photos": "Zastaveno na limitu skenování: je možné, že existují další fotografie",
"Album name (empty outside an album view)": "Název alba (prázdné mimo zobrazení alba)",
"Export date, UTC (YYYYMMDD)": "Datum exportu, UTC (YYYYMMDD)",
"Export time, UTC (HHMM)": "Čas exportu, UTC (HHMM)",
"Insert variable": "Vložit proměnnou",
"Insert…": "Vložit…",
"none ({album}, {date}, {hour})": "žádné ({album}, {date}, {hour})"
}
Loading
Loading