Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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 @@ -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
5 changes: 3 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,8 @@ 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}` (current album
/// name), `{date}` (YYYYMMDD) and `{hour}` (hhmm) variables, expanded at export time.
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
42 changes: 38 additions & 4 deletions crates/engine/src/export/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,44 @@ 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.
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();
}
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.
pub fn expand_subfolder(template: &str, album: Option<&str>, now: Option<chrono::NaiveDateTime>) -> String {
let now = now.unwrap_or_else(|| {
let since = std::time::SystemTime::now().duration_since(std::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()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
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("{album}", &album_str).replace("{date}", &date_str).replace("{hour}", &hour_str);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

clean_subfolder(&res)
}

impl<'a> Placer<'a> {
pub(super) fn new(
o: &'a ExportOptions,
Expand All @@ -82,7 +115,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 +130,7 @@ impl<'a> Placer<'a> {
d.to_string()
}
};
let sub = clean_subfolder(&self.o.subfolder);
let sub = subfolder.map(str::to_string).unwrap_or_else(|| expand_subfolder(&self.o.subfolder, None, None));
Ok(if sub.is_empty() { base } else { join_path(&base, &sub) })
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

Expand All @@ -108,12 +141,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
16 changes: 13 additions & 3 deletions crates/engine/src/export/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ 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>,
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 +89,16 @@ 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)
prepare_guarded(session, id, o, seq, guard, None)
}

/// [`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 = std::time::SystemTime::now().duration_since(std::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());
Comment thread
bd78 marked this conversation as resolved.
Resolved
ids.iter().enumerate().map(|(i, id)| prepare_guarded(session, *id, o, i + 1, guard.clone(), now)).collect()
}

fn prepare_guarded(
Expand All @@ -103,10 +107,16 @@ fn prepare_guarded(
o: &ExportOptions,
seq: usize,
guard: std::sync::Arc<crate::originals::OriginalGuard>,
now: Option<chrono::NaiveDateTime>,
) -> 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 album_name = match session.source {
crate::LibrarySource::Album(aid) => session.catalog.album(aid).map(|a| a.name.clone()),
_ => session.catalog.albums_of(id).first().and_then(|&aid| session.catalog.album(aid)).map(|a| a.name.clone()),
};
let subfolder = super::place::expand_subfolder(&o.subfolder, album_name.as_deref(), now);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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 +172,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
54 changes: 54 additions & 0 deletions crates/engine/src/tests/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,60 @@ 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(" "), "");

// 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");

// 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]);
}

#[test]
fn prepared_exports_run_on_another_thread() {
fn send<T: Send>(_: &T) {}
Expand Down
33 changes: 29 additions & 4 deletions crates/ui-egui/src/dialogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1763,11 +1763,36 @@ fn export_destination_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Token
});
});
}
let subfolder_id = egui::Id::unique("export-subfolder");
field(ui, "Subfolder", |ui| {
crate::widgets::named(
ui.add(egui::TextEdit::singleline(&mut opts.subfolder).hint_text(crate::i18n::tr("none")).desired_width(f32::INFINITY)),
crate::i18n::tr("Subfolder"),
)
trailing_button_row(ui, |ui| {
let mut chosen = None;
let c = crate::widgets::combo_box("exportSubfolderTags").width(90.0).selected_text(crate::i18n::tr("Insert…")).show_ui(ui, |ui| {
if ui.selectable_label(false, "{album}").on_hover_text(crate::i18n::tr("Album name")).clicked() {
chosen = Some("{album}");
}
if ui.selectable_label(false, "{date}").on_hover_text(crate::i18n::tr("Date (YYYYMMDD)")).clicked() {
chosen = Some("{date}");
}
if ui.selectable_label(false, "{hour}").on_hover_text(crate::i18n::tr("Hour (hhmm)")).clicked() {
chosen = Some("{hour}");
}
});
crate::widgets::name_combo(&c.response, crate::i18n::tr("Insert variable"));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
crate::widgets::register(ui, "combo:exportSubfolderTags", c.response.rect);
if let Some(tag) = chosen {
crate::import::insert_at_cursor(ui.ctx(), subfolder_id, &mut opts.subfolder, tag);
}
crate::widgets::named(
ui.add(
egui::TextEdit::singleline(&mut opts.subfolder)
.id(subfolder_id)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.hint_text(crate::i18n::tr("none"))
.desired_width(ui.available_width()),
),
crate::i18n::tr("Subfolder"),
);
});
});
use lightcraft_engine::export::Conflict as K;
choices(ui, "If file exists", "exportConflict", &[(K::Unique, "Add number"), (K::Overwrite, "Overwrite"), (K::Skip, "Skip")], &mut opts.conflict);
Expand Down
2 changes: 1 addition & 1 deletion crates/ui-egui/src/dialogs/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub(crate) use scan::cards_seen;
#[cfg(test)]
pub(crate) use scan::{HELD_RESOLVES, ScanEnd, scan_by_hand, stall_scan, stall_scan_of};
pub use scan::{ScanTask, browse, open, poll_scan, running};
pub(crate) use tags::{tag_field_width, tag_help, tag_toggle, unknown_tags_warning};
pub(crate) use tags::{insert_at_cursor, tag_field_width, tag_help, tag_toggle, unknown_tags_warning};
pub use task::{ImportTask, start, start_paths, tick};

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
Expand Down
12 changes: 12 additions & 0 deletions crates/ui-egui/src/tests/dialogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,18 @@ fn a_click_outside_an_open_dropdown_keeps_the_dialog() {
assert!(h.app.ui.dialog.is_some(), "but not the dialog");
}

#[test]
fn export_subfolder_variable_dropdown() {
let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"}));
h.app.run("dialog.export", json!({})).unwrap();
h.step();
h.step();
let r = h.request("ui.clickWidget", json!({"id": "combo:exportSubfolderTags"}), T);
assert_eq!(r["ok"], true, "{r}");
h.step();
assert!(egui::Popup::is_any_open(&h.view.ctx), "the subfolder tags dropdown is open");
}

#[test]
fn modal_dialogs_close_background_menus() {
let mut h = demo([1400.0, 1000.0], json!({"view": "detail", "right": "edit"}));
Expand Down
Loading