Skip to content

Commit e142e2f

Browse files
authored
Merge PR storytold#2470: integration of 43 reviewed PRs (round 1)
2 parents abb49bd + 22ae8bc commit e142e2f

133 files changed

Lines changed: 5617 additions & 722 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/freebsd.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,4 @@ jobs:
3333
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
3434
with:
3535
require-craft-fonts: true
36-
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
36+
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc

‎.github/workflows/release.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ jobs:
2626
with:
2727
app-name: lightcraft
2828
app-title: LightCraft
29-
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
29+
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
3030
version: ${{ inputs.version }}
3131
secrets:
3232
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}

‎apps/lightcraft-cli/src/main.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -732,12 +732,13 @@ fn render(args: &[String]) -> Result<(), String> {
732732
for (k, v) in opts {
733733
p[k] = v;
734734
}
735-
let mut o = ExportOptions::from_params(&p).map_err(|e| e.to_string())?;
736735
if p.get("format").is_none() {
737736
let ext = Path::new(&output).extension().map(|e| e.to_string_lossy().to_string()).unwrap_or_default();
738-
o.format = ExportFormat::parse(&ext)
739-
.ok_or_else(|| format!("{output}: unknown extension (use .jpg .png .tif .webp .avif .dng or --opt format=…)"))?;
737+
ExportFormat::parse(&ext).ok_or_else(|| format!("{output}: unknown extension (use .jpg .png .tif .webp .avif .dng or --opt format=…)"))?;
738+
// given before validating, so `bitDepth` is checked against the format written (issue #1952)
739+
p["format"] = json!(ext);
740740
}
741+
let o = ExportOptions::from_params(&p).map_err(|e| e.to_string())?;
741742
// Add to Apple Photos: refused before anything is written when it can't be done
742743
let after = s.after_export(&o)?;
743744
let e = export_photo(&mut s, lightcraft_engine::catalog::PhotoId(id), &o, 1)?;

‎apps/lightcraft-web/src/backend.rs‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ fn err(e: JsValue) -> String {
2222
e.as_string().or_else(|| e.dyn_ref::<js_sys::Error>().map(|e| String::from(e.message()))).unwrap_or_else(|| format!("{e:?}"))
2323
}
2424

25+
/// Did an OPFS call fail because the entry doesn't exist (`NotFoundError`)? Any other failure
26+
/// (security, type mismatch, an unreadable or evicted store) is an error, never "absent" (#1507).
27+
fn not_found(e: &JsValue) -> bool {
28+
crate::files::is_not_found(Reflect::get(e, &"name".into()).ok().and_then(|n| n.as_string()).as_deref())
29+
}
30+
2531
/// `navigator.storage` in a window or a worker.
2632
fn storage_manager() -> Option<web_sys::StorageManager> {
2733
let g = js_sys::global();
@@ -134,10 +140,7 @@ impl Backend {
134140
opts.set_create(create);
135141
match JsFuture::from(dir.get_directory_handle_with_options(p, &opts)).await {
136142
Ok(d) => dir = d.unchecked_into(),
137-
Err(e) if !create => {
138-
let _ = e;
139-
return Ok(None);
140-
}
143+
Err(e) if !create && not_found(&e) => return Ok(None),
141144
Err(e) => return Err(err(e)),
142145
}
143146
}
@@ -150,7 +153,7 @@ impl Backend {
150153
opts.set_create(create);
151154
match JsFuture::from(dir.get_file_handle_with_options(&name, &opts)).await {
152155
Ok(h) => Ok(Some(h.unchecked_into())),
153-
Err(_) if !create => Ok(None),
156+
Err(e) if !create && not_found(&e) => Ok(None),
154157
Err(e) => Err(err(e)),
155158
}
156159
}
@@ -250,7 +253,7 @@ impl Backend {
250253
let Some((dir, name)) = Self::parent(root, path, false).await? else { return Ok(()) };
251254
match JsFuture::from(dir.remove_entry(&name)).await {
252255
Ok(_) => Ok(()),
253-
Err(e) if Reflect::get(&e, &"name".into()).ok().and_then(|n| n.as_string()).as_deref() == Some("NotFoundError") => Ok(()),
256+
Err(e) if not_found(&e) => Ok(()),
254257
Err(e) => Err(err(e)),
255258
}
256259
}

‎apps/lightcraft-web/src/backup.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,18 @@ pub fn valid_hash(h: &str) -> bool {
5252
!h.is_empty() && h.len() <= 128 && h.chars().all(|c| c.is_ascii_alphanumeric())
5353
}
5454

55+
/// Why a backup can't start yet, given [`lightcraft_engine::Session::unsaved`]: changes applied in
56+
/// the app but not yet written to browser storage (a save failed). The zip copies the stored
57+
/// library files, so it would report success while missing them; `None` when everything is saved.
58+
pub fn unsaved_refusal(unsaved: Option<(usize, &str)>) -> Option<String> {
59+
let (ops, why) = unsaved?;
60+
let changes = if ops == 1 { "1 change".to_string() } else { format!("{ops} changes") };
61+
Some(format!(
62+
"Backup not started: {changes} could not be saved to browser storage yet ({why}), so the backup would miss them. \
63+
Free up storage space; LightCraft retries the save with every change. Back up once nothing is left unsaved."
64+
))
65+
}
66+
5567
/// Zip entry name for an original.
5668
pub fn original_entry(hash: &str, file_name: &str) -> String {
5769
let name: String = file_name.chars().map(|c| if c == '/' || c == '\\' || c.is_control() { '_' } else { c }).collect();

‎apps/lightcraft-web/src/files.rs‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,27 @@ impl Store for FilesStore {
198198
/// Names of the library files read at start-up.
199199
pub const LIBRARY_FILES: [&str; 6] = ["catalog.snap", "catalog.log", "presets.json", "view.json", "prefs.json", "ui.json"];
200200

201+
/// Is a browser storage error, by its `DOMException` name, "the entry doesn't exist"? Only
202+
/// `NotFoundError` is; anything else (security, type mismatch, an unreadable store) is a failure.
203+
pub fn is_not_found(dom_exception_name: Option<&str>) -> bool {
204+
dom_exception_name == Some("NotFoundError")
205+
}
206+
207+
/// Preload the library files read at start-up (`None`: the file doesn't exist yet). A file that
208+
/// exists but couldn't be read stops start-up instead (#1507): opening the library without it
209+
/// would show an incomplete catalog and then save over the stored copy.
210+
pub fn preload_library(files: &Files, reads: Vec<(&str, Result<Option<Vec<u8>>, String>)>) -> Result<(), String> {
211+
let mut failed = Vec::new();
212+
for (name, read) in reads {
213+
match read {
214+
Ok(Some(data)) => files.preload(name, data),
215+
Ok(None) => {}
216+
Err(e) => failed.push(format!("{name}: {e}")),
217+
}
218+
}
219+
if failed.is_empty() { Ok(()) } else { Err(format!("couldn't read the library from browser storage ({})", failed.join("; "))) }
220+
}
221+
201222
#[cfg(test)]
202223
mod tests {
203224
use super::*;
@@ -282,6 +303,66 @@ mod tests {
282303
assert_eq!(s2.catalog.photo(id).unwrap().rating, 5, "the rating survived");
283304
}
284305

306+
/// A backup copies the stored library files, so while a save is failing it would miss the
307+
/// queued changes: it is refused with the reason until they are written (#1508).
308+
#[test]
309+
fn backup_is_refused_while_changes_are_unsaved() {
310+
let files = Files::default();
311+
let mut s = Session::new();
312+
let stores = LibraryStores { dir: "browser".into(), catalog: Box::new(files.store()), files: Box::new(files.store()), on_disk: false };
313+
s.open_library_in(stores, true).unwrap();
314+
assert_eq!(crate::backup::unsaved_refusal(s.unsaved()), None, "everything saved: the backup may start");
315+
files.set_error(Some("QuotaExceededError".into()));
316+
let _ = s.execute("photo.rate", &json!({"rating": 5}));
317+
let refusal = crate::backup::unsaved_refusal(s.unsaved()).expect("refused while the rating is unsaved");
318+
assert!(refusal.contains("could not be saved") && refusal.contains("QuotaExceeded"), "{refusal}");
319+
files.set_error(None);
320+
s.persist_if_dirty();
321+
s.persist().unwrap();
322+
assert_eq!(crate::backup::unsaved_refusal(s.unsaved()), None, "allowed again once the change is written");
323+
}
324+
325+
#[test]
326+
fn unsaved_refusal_counts_changes() {
327+
use crate::backup::unsaved_refusal;
328+
assert!(unsaved_refusal(Some((1, "quota"))).unwrap().contains("1 change could not"));
329+
assert!(unsaved_refusal(Some((3, "quota"))).unwrap().contains("3 changes could not"));
330+
}
331+
332+
/// Start-up only treats a missing file as absent: a stored file that couldn't be read stops
333+
/// it, naming the file, instead of opening an incomplete library (#1507).
334+
#[test]
335+
fn unreadable_library_file_stops_start_up() {
336+
let files = Files::default();
337+
let reads = vec![
338+
("catalog.snap", Ok(Some(b"snap".to_vec()))),
339+
("catalog.log", Err("NotReadableError: the file could not be read".to_string())),
340+
("presets.json", Ok(None)),
341+
];
342+
let e = preload_library(&files, reads).unwrap_err();
343+
assert!(e.contains("catalog.log") && e.contains("NotReadableError"), "{e}");
344+
}
345+
346+
/// A new library (nothing stored yet) still starts.
347+
#[test]
348+
fn missing_library_files_are_a_new_library() {
349+
let files = Files::default();
350+
let reads = LIBRARY_FILES.iter().map(|n| (*n, Ok(None))).collect();
351+
preload_library(&files, reads).unwrap();
352+
assert!(files.get("catalog.snap").is_none());
353+
let reads = vec![("catalog.snap", Ok(Some(b"snap".to_vec()))), ("catalog.log", Ok(None))];
354+
preload_library(&files, reads).unwrap();
355+
assert_eq!(files.get("catalog.snap").as_deref(), Some(&b"snap"[..]));
356+
}
357+
358+
#[test]
359+
fn only_not_found_errors_mean_absent() {
360+
assert!(is_not_found(Some("NotFoundError")));
361+
for name in [Some("SecurityError"), Some("TypeMismatchError"), Some("NotReadableError"), Some("InvalidStateError"), None] {
362+
assert!(!is_not_found(name), "{name:?}");
363+
}
364+
}
365+
285366
#[test]
286367
fn library_survives_reload_through_flushes() {
287368
let mut disk = BTreeMap::new();

‎apps/lightcraft-web/src/web.rs‎

Lines changed: 72 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
173173
screen_profile: None,
174174
backup_library: Some(Box::new(move |session: &mut Session| {
175175
let Some(b) = backup_backend.clone() else { return Err("nothing is stored in this browser session (?store=memory)".into()) };
176+
if let Some(why) = crate::backup::unsaved_refusal(session.unsaved()) {
177+
return Err(why);
178+
}
176179
// the photos' own names for the originals in the zip
177180
let names: std::collections::HashMap<String, String> = session
178181
.catalog
@@ -280,6 +283,9 @@ struct Boot {
280283
index: ThumbIndex,
281284
/// The library folder in storage (`library`, or a restored backup's).
282285
lib_dir: String,
286+
/// Library files that exist but couldn't be read (#1507): the library isn't opened and
287+
/// nothing is saved, so the stored copy stays as it was.
288+
load_error: Option<String>,
283289
}
284290

285291
async fn boot(opts: Options) -> Boot {
@@ -298,6 +304,7 @@ async fn boot(opts: Options) -> Boot {
298304
let files = Files::default();
299305
let mut index = ThumbIndex::default();
300306
let mut lib_dir = DEFAULT_LIBRARY_DIR.to_string();
307+
let mut load_error = None;
301308
if let Some(b) = &backend {
302309
if opts.reset {
303310
// everything this site keeps in the browser, photos included: never without asking
@@ -315,21 +322,32 @@ async fn boot(opts: Options) -> Boot {
315322
}
316323
}
317324
// a restored backup lives in its own folder (see `backup`)
318-
if let Ok(Some(d)) = b.read(ACTIVE_LIBRARY).await {
319-
let d = String::from_utf8_lossy(&d).trim().to_string();
320-
if valid_library_dir(&d) {
321-
lib_dir = d;
325+
match b.read(ACTIVE_LIBRARY).await {
326+
Ok(Some(d)) => {
327+
let d = String::from_utf8_lossy(&d).trim().to_string();
328+
if valid_library_dir(&d) {
329+
lib_dir = d;
330+
}
322331
}
332+
Ok(None) => {}
333+
// not knowing which library is in use, any library opened could be the wrong one
334+
Err(e) => load_error = Some(format!("couldn't read which library is in use from browser storage ({e})")),
323335
}
324-
for name in LIBRARY_FILES {
325-
match b.read(&library_key(&lib_dir, name)).await {
326-
Ok(Some(data)) => files.preload(name, data),
327-
Ok(None) => {}
328-
Err(e) => log::error!("reading {name}: {e}"),
336+
if load_error.is_none() {
337+
let mut reads = Vec::new();
338+
for name in LIBRARY_FILES {
339+
reads.push((name, b.read(&library_key(&lib_dir, name)).await));
340+
}
341+
if let Err(e) = crate::files::preload_library(&files, reads) {
342+
log::error!("{e}");
343+
load_error = Some(e);
329344
}
330345
}
331-
if let Ok(Some(j)) = b.read(THUMB_INDEX).await {
332-
index = ThumbIndex::from_json(&j);
346+
let index_read = b.read(THUMB_INDEX).await;
347+
match &index_read {
348+
Ok(Some(j)) => index = ThumbIndex::from_json(j),
349+
Ok(None) => {}
350+
Err(e) => log::warn!("reading the thumbnail index: {e}"),
333351
}
334352
crate::backend::request_persistence(|granted| {
335353
if !granted {
@@ -339,7 +357,8 @@ async fn boot(opts: Options) -> Boot {
339357
);
340358
}
341359
});
342-
// thumbnails stored without an index entry (index saved late, or lost): delete them
360+
// thumbnails stored without an index entry (index saved late, or lost): delete them; not
361+
// when the index couldn't be read, which would make every thumbnail look unindexed
343362
let b2 = b.clone();
344363
let known: std::collections::HashSet<String> = b
345364
.list("thumbs")
@@ -349,7 +368,7 @@ async fn boot(opts: Options) -> Boot {
349368
.filter(|n| n.ends_with(".jpg"))
350369
.map(|n| n.trim_end_matches(".jpg").to_string())
351370
.collect();
352-
let orphans: Vec<String> = known.into_iter().filter(|k| !index.contains(k)).collect();
371+
let orphans: Vec<String> = if index_read.is_ok() { known.into_iter().filter(|k| !index.contains(k)).collect() } else { Vec::new() };
353372
if !orphans.is_empty() {
354373
wasm_bindgen_futures::spawn_local(async move {
355374
for k in &orphans {
@@ -366,7 +385,7 @@ async fn boot(opts: Options) -> Boot {
366385
index.len(),
367386
index.total() as f64 / 1e6
368387
);
369-
Boot { opts, backend, files, index, lib_dir }
388+
Boot { opts, backend, files, index, lib_dir, load_error }
370389
}
371390

372391
struct WebApp {
@@ -389,7 +408,7 @@ struct WebApp {
389408

390409
impl WebApp {
391410
fn new(cc: &eframe::CreationContext<'_>, boot: Boot, chinese_font: Vec<u8>) -> Self {
392-
let Boot { opts, backend, files, index, lib_dir } = boot;
411+
let Boot { opts, backend, files, index, lib_dir, load_error } = boot;
393412
let originals = Originals::default();
394413
let t = perf_now();
395414
let mut session = Session::new();
@@ -401,7 +420,13 @@ impl WebApp {
401420
on_disk: false,
402421
};
403422
let mut problem = None;
404-
match session.open_library_in(stores, true).cloned() {
423+
// a library that couldn't be read is not opened: it would show incomplete, then save over the stored copy
424+
let read_failed = load_error.is_some();
425+
let opened = match load_error {
426+
Some(e) => Err(format!("{e}. Nothing was changed in storage")),
427+
None => session.open_library_in(stores, true).cloned().map_err(|e| e.to_string()),
428+
};
429+
match opened {
405430
Ok(r) => log::info!(
406431
"lightcraft: library {} in {:.0} ms ({} photos; snapshot seq {}, {} ops replayed)",
407432
if r.created { "created" } else { "loaded" },
@@ -432,7 +457,8 @@ impl WebApp {
432457
}
433458
// previews are large (≤ 2560 px, f32): keep few in a 32-bit address space
434459
session.media.preview_capacity = 3;
435-
let frozen = Rc::new(Cell::new(false));
460+
// nothing is saved while the stored library couldn't be read
461+
let frozen = Rc::new(Cell::new(read_failed));
436462
let mut app = LightcraftApp::new(session, services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone()))
437463
.with_chinese_font(chinese_font);
438464
let ui_written = files.get("ui.json").unwrap_or_default();
@@ -667,11 +693,40 @@ impl eframe::App for WebApp {
667693
}
668694
}
669695

696+
/// "Auto" follows the browser's languages (issue #2085): the first of `navigator.languages` (else
697+
/// `navigator.language`) that LightCraft ships becomes the UI's default. Every step is fallible
698+
/// (as in [`crate::safety::acquire_tab_lock`]): without a usable navigator Auto stays English,
699+
/// as before.
700+
fn install_browser_language() {
701+
let Ok(navigator) = js_sys::Reflect::get(&js_sys::global(), &"navigator".into()) else { return };
702+
let mut tags: Vec<String> = Vec::new();
703+
if let Ok(languages) = js_sys::Reflect::get(&navigator, &"languages".into())
704+
&& let Some(languages) = languages.dyn_ref::<js_sys::Array>()
705+
{
706+
for tag in languages.iter() {
707+
if let Some(tag) = tag.as_string() {
708+
tags.push(tag);
709+
}
710+
}
711+
}
712+
if tags.is_empty()
713+
&& let Ok(language) = js_sys::Reflect::get(&navigator, &"language".into())
714+
&& let Some(language) = language.as_string()
715+
{
716+
tags.push(language);
717+
}
718+
if let Some(language) = lightcraft_ui_egui::i18n::locale_from_tags(&tags) {
719+
lightcraft_ui_egui::i18n::set_default_language(language);
720+
log::info!("lightcraft: default language {language:?} from the browser's languages");
721+
}
722+
}
723+
670724
/// Start the app with the separately fetched Simplified Chinese font (empty in font-free builds).
671725
#[wasm_bindgen]
672726
pub fn start(chinese_font: Vec<u8>) {
673727
eframe::WebLogger::init(log::LevelFilter::Info).ok();
674728
safety::install_panic_hook();
729+
install_browser_language();
675730
log::info!("lightcraft: wasm instantiated at {:.0} ms", perf_now());
676731
if chinese_font.is_empty() {
677732
log::warn!("lightcraft: no Simplified Chinese font supplied; Chinese-only glyphs will show as boxes");

‎contributors/people.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,7 @@ sync_github_name = false
5757
[people.egegl]
5858
real_name = "Ege Gursel"
5959
sync_github_name = true
60+
61+
[people.mahmatias]
62+
display_name = "Márcio Matias de Andrade"
63+
sync_github_name = true

‎crates/catalog/src/dates.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,15 @@ mod tests {
233233
assert_eq!(iso_seconds("2026-01-01T10:00+02:00"), iso_seconds("2026-01-01T10:00"));
234234
}
235235

236+
#[test]
237+
fn impossible_times_are_rejected_not_rolled_over() {
238+
for bad in ["2026-04-01T10:75:00", "2026-04-01 10:00:75", "2026-04-01T10:60", "2026-04-01T24:00:00", "2026-04-01T10:59:60"] {
239+
assert_eq!(normalize_iso(bad), None, "{bad}");
240+
assert_eq!(shift_iso(bad, 5), None, "{bad}");
241+
}
242+
assert_eq!(normalize_iso("2026-04-01T23:59:59").as_deref(), Some("2026-04-01T23:59:59"));
243+
}
244+
236245
#[test]
237246
fn runs_by_day_month_year_keep_stacks_together() {
238247
let mut c = Catalog::new();

‎crates/catalog/src/stacks.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,9 @@ pub fn iso_seconds(s: &str) -> Option<i64> {
296296
}
297297
let (hh, mm, ss) =
298298
if s.len() >= 16 { (num(11, 13)?, num(14, 16)?, if s.get(16..17) == Some(":") { num(17, 19).unwrap_or(0) } else { 0 }) } else { (0, 0, 0) };
299+
if hh >= 24 || mm >= 60 || ss >= 60 {
300+
return None;
301+
}
299302
// days from civil (proleptic Gregorian)
300303
let y2 = if m <= 2 { y - 1 } else { y };
301304
let era = y2.div_euclid(400);

0 commit comments

Comments
 (0)