Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions apps/lightcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,16 @@ impl eframe::App for App {
const EXIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2);

fn main() -> eframe::Result {
// A metadata read runs in a disposable copy of this process, before logging, preferences or
// the window are initialised. Its parent can terminate a filesystem call that misses a deadline.
if std::env::args_os().nth(1).as_deref() == Some(std::ffi::OsStr::new(lightcraft_engine::metadata_read::WORKER_ARG)) {
let result = lightcraft_engine::metadata_read::worker_main();
if let Err(error) = result {
eprintln!("{error}");
std::process::exit(1);
}
return Ok(());
}
// Windows: the update helper is a copy of this program started with `--finish-update`.
#[cfg(windows)]
if let Some(result) = craft_update::self_update::finish(&lightcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
Expand Down
3 changes: 3 additions & 0 deletions contributors/people.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,6 @@ sync_github_name = true
[people.Peaperfish]
real_name = "Yule Wang"
display_name = "Brian Wang"

[people.pixelpuxel]
real_name = "Gabriel Schreiber"
25 changes: 2 additions & 23 deletions crates/engine/src/cmd/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,29 +128,8 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!(query "photo.allMetadata", "All Metadata", [], None, "{id?} → {exif: [{group, tag, name, value}], xmp: [{name, value}]} — every EXIF / TIFF / GPS tag of the file and its XMP properties", always, |s, p| {
let id = photo_arg(s, p, "photo.allMetadata")?;
let ph = s.catalog.photo(id).ok_or_else(|| super::bad("photo.allMetadata", "no such photo"))?.clone();
let lightcraft_catalog::Source::File { path } = &ph.source else {
return Ok(json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"}));
};
let bytes = match &s.media.file_bytes {
Some(r) => r(path),
None => std::fs::read(path).map_err(|e| format!("{path}: {e}")),
}
.map_err(|e| super::bad("photo.allMetadata", e))?;
let exif: Vec<Value> = lightcraft_meta::file_tag_rows(&bytes)
.into_iter()
.map(|r| json!({"group": r.group, "tag": r.tag, "name": r.name, "value": r.value}))
.collect();
// Keep sidecar precedence; reuse the loaded bytes for embedded XMP.
let packet = match s.sidecar_lookup(ph.id).find(path) {
Some(sc) => std::fs::read_to_string(sc).ok(),
None => lightcraft_meta::embedded(&bytes).xmp,
};
let xmp: Vec<Value> = packet
.and_then(|x| lightcraft_meta::parse_xmp(&x).ok())
.map(|d| d.properties.into_iter().filter(|(k, _)| !k.starts_with("lc:")).map(|(k, v)| json!({"name": k, "value": v.join("; ")})).collect())
.unwrap_or_default();
Ok(json!({"exif": exif, "xmp": xmp}))
crate::metadata_read::Request::new(s, id).and_then(|request| request.read())
.map_err(|e| super::bad("photo.allMetadata", e))
}),
cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| {
let all: Vec<Album> = s.catalog.albums().cloned().collect();
Expand Down
13 changes: 13 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub mod logging;
pub mod media;
pub mod memory;
pub mod merge;
pub mod metadata_read;
mod model_download;
pub mod open_path;
pub mod originals;
Expand Down Expand Up @@ -1138,6 +1139,18 @@ impl Session {
self.shelved_filter.is_some()
}

/// Clear matching view rules from both the live filter and the filter put aside by Enable Filters.
pub fn clear_view_rules(&mut self, rules: &lightcraft_catalog::RuleSet) {
if self.filter.rule_set.as_ref() == Some(rules) {
self.filter.rule_set = None;
}
if let Some(filter) = &mut self.shelved_filter
&& filter.rule_set.as_ref() == Some(rules)
{
filter.rule_set = None;
}
}

/// Photos shown in the grid/filmstrip for the current source, filter and sort.
pub fn visible(&mut self) -> &[PhotoId] {
let mut key =
Expand Down
152 changes: 152 additions & 0 deletions crates/engine/src/metadata_read.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//! A read-only metadata request that can be moved to a UI worker.

use crate::{Session, merge::ByteReader, sidecar::SidecarLookup};
use lightcraft_catalog::{PhotoId, Source};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

/// Private desktop subcommand used for a metadata read that the parent can terminate on timeout.
pub const WORKER_ARG: &str = "--metadata-read-worker";

type ReadResult = Result<(Value, Option<String>), String>;

#[derive(Serialize, Deserialize)]
struct WorkerInput {
path: String,
sidecar: SidecarLookup,
}

/// A detached request for all readable EXIF and XMP attached to one catalog photo.
pub struct Request {
source: Source,
read: Option<ByteReader>,
sidecar: SidecarLookup,
}

impl Request {
/// Capture the photo source, custom byte reader and sidecar policy from the session.
pub fn new(session: &Session, id: PhotoId) -> Result<Self, String> {
let photo = session.catalog.photo(id).ok_or("no such photo")?;
Ok(Self { source: photo.source.clone(), read: session.media.file_bytes.clone(), sidecar: session.sidecar_lookup(id) })
}

/// Return metadata in the command API shape, including a sidecar warning when present.
pub fn read(self) -> Result<Value, String> {
let (mut value, warning) = self.read_with_diagnostics()?;
if let Some(warning) = warning
&& let Some(fields) = value.as_object_mut()
{
fields.insert("warning".into(), Value::String(warning));
}
Ok(value)
}

/// Return metadata and a non-fatal sidecar warning as separate values for the UI.
pub fn read_with_diagnostics(self) -> ReadResult {
let Source::File { path } = self.source else {
return Ok((json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"}), None));
};
read_file(path, self.read, self.sidecar)
}

/// Read in a child process so a blocked filesystem call can be terminated at the deadline.
/// Custom readers stay in-process because their closures cannot cross a process boundary.
#[cfg(not(target_arch = "wasm32"))]
pub fn read_with_deadline(self, timeout: std::time::Duration) -> ReadResult {
if self.read.is_some() {
return self.read_with_diagnostics();
}
let Source::File { path } = self.source else {
return Ok((json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"}), None));
};
read_in_worker(WorkerInput { path, sidecar: self.sidecar }, timeout)
}
}

/// Read and parse the original plus its chosen XMP sidecar, if one exists.
fn read_file(path: String, read: Option<ByteReader>, sidecar: SidecarLookup) -> ReadResult {
let bytes = match read {
Some(read) => read(&path),
None => std::fs::read(&path).map_err(|e| format!("{path}: {e}")),
}?;
let exif: Vec<Value> = lightcraft_meta::file_tag_rows(&bytes)
.into_iter()
.map(|row| json!({"group": row.group, "tag": row.tag, "name": row.name, "value": row.value}))
.collect();
let packet = match sidecar.find(&path) {
Some(sidecar) => std::fs::read_to_string(&sidecar).map(Some).map_err(|error| format!("{}: {error}", sidecar.display())),
None => Ok(lightcraft_meta::embedded(&bytes).xmp),
};
let parsed = packet.and_then(|packet| packet.map(|xmp| lightcraft_meta::parse_xmp(&xmp).map_err(|error| format!("XMP: {error}"))).transpose());
let warning = parsed.as_ref().err().cloned();
let xmp: Vec<Value> = parsed
.ok()
.flatten()
.map(|d| {
d.properties
.into_iter()
.filter(|(key, _)| !key.starts_with("lc:"))
.map(|(key, values)| json!({"name": key, "value": values.join("; ")}))
.collect()
})
.unwrap_or_default();
Ok((json!({"exif": exif, "xmp": xmp}), warning))
}

/// Serve one request on standard input/output. The desktop app calls this before initialising UI.
#[cfg(not(target_arch = "wasm32"))]
pub fn worker_main() -> Result<(), String> {
let input: WorkerInput = serde_json::from_reader(std::io::stdin().lock()).map_err(|error| format!("metadata worker input: {error}"))?;
let result = read_file(input.path, None, input.sidecar);
serde_json::to_writer(std::io::stdout().lock(), &result).map_err(|error| format!("metadata worker output: {error}"))
}

/// The task remains alive after the deadline until the killed child is confirmed stopped. This
/// preserves the read cap even on a filesystem whose kernel call is temporarily uninterruptible.
#[cfg(not(target_arch = "wasm32"))]
fn read_in_worker(input: WorkerInput, timeout: std::time::Duration) -> ReadResult {
use std::io::{Read as _, Write as _};
use std::process::{Command, Stdio};

let exe = std::env::current_exe().map_err(|error| format!("metadata worker executable: {error}"))?;
let mut child = Command::new(exe)
.arg(WORKER_ARG)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|error| format!("metadata worker: {error}"))?;
let payload = serde_json::to_vec(&input).map_err(|error| format!("metadata worker input: {error}"))?;
let Some(mut stdin) = child.stdin.take() else { return Err("metadata worker has no input pipe".into()) };
stdin.write_all(&payload).map_err(|error| format!("metadata worker input: {error}"))?;
drop(stdin);
let Some(mut stdout) = child.stdout.take() else { return Err("metadata worker has no output pipe".into()) };
let output = std::thread::spawn(move || {
let mut bytes = Vec::new();
stdout.read_to_end(&mut bytes).map(|_| bytes)
});
let started = std::time::Instant::now();
let mut timed_out = false;
loop {
match child.try_wait().map_err(|error| format!("metadata worker: {error}"))? {
Some(status) => {
let bytes = output
.join()
.map_err(|_| "metadata worker output thread stopped".to_owned())?
.map_err(|error| format!("metadata worker output: {error}"))?;
if timed_out {
return Err("metadata read timed out. Try Refresh.".into());
}
if !status.success() {
return Err(format!("metadata worker stopped with {status}"));
}
return serde_json::from_slice(&bytes).map_err(|error| format!("metadata worker output: {error}"))?;
}
None if !timed_out && started.elapsed() >= timeout => {
timed_out = true;
let _ = child.kill();
}
None => std::thread::sleep(std::time::Duration::from_millis(10)),
}
}
}
2 changes: 1 addition & 1 deletion crates/engine/src/sidecar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub fn find_sidecar(original: &str, naming: SidecarNaming) -> Option<PathBuf> {
/// may read the shared stem sidecar (`IMG_0001.xmp`) of its stem. A photo that shares its stem
/// with a file that owns that sidecar (see [`Session::sidecar_naming`]) reads its own `<file>.xmp`
/// and never the packet of the sibling that owns the stem one (issue #1523).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SidecarLookup {
pub naming: SidecarNaming,
/// False when another file with the same stem owns the stem sidecar.
Expand Down
2 changes: 2 additions & 0 deletions crates/ui-egui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ egui = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
chrono = { workspace = true }
sys-locale = { version = "0.3", features = ["js"] }

[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
Expand Down
10 changes: 10 additions & 0 deletions crates/ui-egui/locales/de.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
{
"Waiting for an earlier metadata read to finish…": "Warte auf einen vorherigen Metadatenzugriff…",
"Metadata read timed out. Try Refresh.": "Zeitlimit beim Lesen der Metadaten erreicht. Versuche es mit Aktualisieren.",
"Refresh": "Aktualisieren",
"Keys": "Keys",
"Combine Albums": "Sammlungen verknüpfen",
"OR: any album": "ODER: beliebige Sammlung",
"AND: every album": "UND: jede Sammlung",
"First minus others": "Erste minus weitere",
"Only one album": "Nur in einer Sammlung",
"Cmd/Ctrl-click albums to combine. A plain click shows one album.": "Sammlungen mit Cmd/Strg-Klick verknüpfen. Ein einfacher Klick zeigt eine Sammlung.",
" (library default)": " (Bibliotheksstandard)",
" (inverted)": " (umgekehrt)",
" · best of its burst": " · bestes Foto der Serie",
Expand Down
Loading