Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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: 1 addition & 2 deletions crates/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,12 @@ 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 }
jiff = { 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) and `{hour}` (HHMM, both in local time) 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
104 changes: 100 additions & 4 deletions crates/engine/src/export/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,106 @@ 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 local date and time for `{date}` (YYYYMMDD) and `{hour}` (HHMM), as the person's clock shows it
/// ([`local_now`]); `None` uses the time now.
/// - Unknown tokens are left unchanged. The result passes through [`clean_subfolder`].
///
/// E.g. `"{album}/{date}_{hour}"` with album `"Vacation"` produces `"Vacation/20261107_0230"`.
///
/// 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.or_else(local_now).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)
}

/// The date and time now on the person's clock, for `{date}` and `{hour}`: the host's zone, with the offset in force
/// now ([`crate::import::local_civil`]; the web build has no zone to read and uses UTC). A folder named by its
/// export date is named by the day the person exported on, not by UTC's, which is the next or the previous day
/// for part of every day away from UTC.
pub(super) fn local_now() -> Option<chrono::NaiveDateTime> {
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::NaiveDateTime::parse_from_str(&crate::import::local_civil(secs), "%Y-%m-%dT%H:%M:%S").ok()
}

impl<'a> Placer<'a> {
pub(super) fn new(
o: &'a ExportOptions,
Expand All @@ -82,7 +177,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 +192,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 +203,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
22 changes: 19 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,23 @@ 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()
// the whole batch goes to one dated folder: the time is read once
let now = super::place::local_now();
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 +116,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 +178,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
Loading
Loading