PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Show camera data in File Info (#2424) (#2692)
Fabio Lussi1ccdac4c940c
diff --git a/crates/algo/src/exif.rs b/crates/algo/src/exif.rsindex 445f51498..d18bcdec9 100644--- a/crates/algo/src/exif.rs+++ b/crates/algo/src/exif.rs@@ -17,6 +17,8 @@ pub struct CameraInfo {pub focal_length: Option<f64>,/// 35 mm-equivalent focal length in millimetres.pub focal_length_35mm: Option<f64>,+ /// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`).+ pub date_taken: Option<String>,}impl CameraInfo {@@ -35,11 +37,11 @@ struct Tiff<'a> {impl Tiff<'_> {fn u16(&self, o: usize) -> Option<u16> {- let s = self.b.get(o..o + 2)?;+ let s = self.b.get(o..o.checked_add(2)?)?;Some(if self.le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) })}fn u32(&self, o: usize) -> Option<u32> {- let s = self.b.get(o..o + 4)?;+ let s = self.b.get(o..o.checked_add(4)?)?;let a = [s[0], s[1], s[2], s[3]];Some(if self.le { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) })}@@ -48,20 +50,25 @@ impl Tiff<'_> {let Some(n) = self.u16(off) else { return Vec::new() };(0..n as usize).filter_map(|k| {- let e = off + 2 + k * 12;- Some((self.u16(e)?, self.u16(e + 2)?, self.u32(e + 4)?, e + 8))+ // Checked: offsets come from the file, and usize is 32 bits on wasm.+ let e = off.checked_add(2)?.checked_add(k * 12)?;+ Some((self.u16(e)?, self.u16(e.checked_add(2)?)?, self.u32(e.checked_add(4)?)?, e.checked_add(8)?))}).collect()}fn data_at(&self, typ: u16, count: u32, field: usize) -> Option<usize> {let size = match typ {- 1 | 2 | 6 | 7 => 1,+ 1 | 2 | 6 | 7 => 1usize,3 | 8 => 2,4 | 9 | 11 => 4,5 | 10 | 12 => 8,_ => return None,- } * count as usize;- if size <= 4 { Some(field) } else { self.u32(field).map(|v| v as usize) }+ }+ .checked_mul(usize::try_from(count).ok()?)?;+ let at = if size <= 4 { field } else { usize::try_from(self.u32(field)?).ok()? };+ // The whole value must lie inside the payload, not just its first element.+ self.b.get(at..at.checked_add(size)?)?;+ Some(at)}fn number(&self, typ: u16, count: u32, field: usize) -> Option<f64> {let at = self.data_at(typ, count, field)?;@@ -69,11 +76,11 @@ impl Tiff<'_> {3 => self.u16(at).map(f64::from),4 => self.u32(at).map(f64::from),5 => {- let (n, d) = (self.u32(at)?, self.u32(at + 4)?);+ let (n, d) = (self.u32(at)?, self.u32(at.checked_add(4)?)?);(d != 0).then(|| n as f64 / d as f64)}10 => {- let (n, d) = (self.u32(at)? as i32, self.u32(at + 4)? as i32);+ let (n, d) = (self.u32(at)? as i32, self.u32(at.checked_add(4)?)? as i32);(d != 0).then(|| n as f64 / d as f64)}_ => None,@@ -84,7 +91,7 @@ impl Tiff<'_> {return None;}let at = self.data_at(typ, count, field)?;- let s = self.b.get(at..at + count as usize)?;+ let s = self.b.get(at..at.checked_add(usize::try_from(count).ok()?)?)?;let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string();(!s.is_empty()).then_some(s)}@@ -118,6 +125,7 @@ pub fn read(exif: &[u8]) -> CameraInfo {0x920A => info.focal_length = t.number(typ, count, field),0xA405 => info.focal_length_35mm = t.number(typ, count, field).filter(|v| *v > 0.0),0xA434 => info.lens = t.text(typ, count, field),+ 0x9003 => info.date_taken = t.text(typ, count, field),0x8769 => {if let Some(p) = t.u32(field) {queue.push(p as usize);@@ -161,6 +169,9 @@ pub fn build(info: &CameraInfo) -> Vec<u8> {if let Some(v) = info.iso {exif.push((0x8827, 3, 1, (v as u16).to_le_bytes().to_vec()));}+ if let Some(s) = &info.date_taken {+ exif.push((0x9003, 2, s.len() as u32 + 1, text(s)));+ }if let Some(v) = info.focal_length {exif.push((0x920A, 5, 1, rational(v)));}@@ -224,6 +235,7 @@ mod tests {iso: Some(200.0),focal_length: Some(35.0),focal_length_35mm: Some(52.0),+ date_taken: Some("2024:02:17 12:40:19".into()),};let b = build(&info);let r = read(&b);@@ -237,4 +249,53 @@ mod tests {let _ = read(&b[..cut]);}}++ /// Hostile payloads: huge counts, offsets near `u32::MAX`, self-referencing IFDs and random+ /// bytes read as `None` fields instead of panicking or overflowing (usize is 32 bits on wasm).+ #[test]+ fn hostile_payloads_never_panic() {+ let entry = |tag: u16, typ: u16, count: u32, value: u32| {+ let mut e = tag.to_le_bytes().to_vec();+ e.extend_from_slice(&typ.to_le_bytes());+ e.extend_from_slice(&count.to_le_bytes());+ e.extend_from_slice(&value.to_le_bytes());+ e+ };+ let mut b = b"II*\0".to_vec();+ b.extend_from_slice(&8u32.to_le_bytes());+ let entries = [+ entry(0x010F, 2, u32::MAX, 8), // Make: count far past the end+ entry(0x0110, 2, 16, u32::MAX - 1), // Model: offset at the top of the range+ entry(0x829A, 5, u32::MAX, 20), // ExposureTime: count overflows the size+ entry(0x829D, 5, 1, u32::MAX - 3), // FNumber: rational straddles u32::MAX+ entry(0x9003, 2, 0x4000_0000, 8), // DateTimeOriginal: size overflow on 32 bits+ entry(0x8769, 4, 1, 8), // Exif IFD pointing back at IFD0+ entry(0x8769, 4, 1, u32::MAX), // ... and past the end+ ];+ b.extend_from_slice(&(entries.len() as u16 + 3).to_le_bytes()); // claims more entries than exist+ for e in entries {+ b.extend_from_slice(&e);+ }+ assert_eq!(read(&b), CameraInfo::default());+ let mut be = b"MM\0*".to_vec();+ be.extend_from_slice(&u32::MAX.to_be_bytes());+ assert_eq!(read(&be), CameraInfo::default());+ // Deterministic noise behind a valid header, and every truncation of a real payload.+ let mut x = 0x2545_F491u32;+ for _ in 0..200 {+ let mut n = b"II*\0\x08\0\0\0".to_vec();+ for _ in 0..96 {+ x ^= x << 13;+ x ^= x >> 17;+ x ^= x << 5;+ n.push(x as u8);+ }+ let _ = read(&n);+ }+ let good =+ build(&CameraInfo { make: Some("Make".into()), date_taken: Some("2024:02:17 12:40:19".into()), exposure_time: Some(0.004), ..Default::default() });+ for cut in 0..good.len() {+ let _ = read(&good[..cut]);+ }+ }}diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 9eeb98a2c..5b826915a 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -559,6 +559,106 @@ pub fn read_file_info(xmp: Option<&str>) -> Value {Value::Object(m)}+/// File Info's read-only Camera Data, as (result key, English label) in display order.+pub const CAMERA_FIELDS: [(&str, &str); 9] = [+ ("make", "Make"),+ ("model", "Model"),+ ("dateTaken", "Date Taken"),+ ("exposure", "Exposure"),+ ("fNumber", "F-Stop"),+ ("iso", "ISO Speed"),+ ("focalLength", "Focal Length"),+ ("focalLength35mm", "Focal Length (35 mm)"),+ ("lens", "Lens"),+];++/// `v` with at most `decimals` decimals and no trailing zeros (33.10 → "33.1", 8.0 → "8").+fn short_num(v: f64, decimals: usize) -> String {+ let s = format!("{v:.decimals$}");+ if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s }+}++/// Exposure time as cameras print it: "1/250 s" for fractions of a second, "0.4 s" or "2 s"+/// when the reciprocal isn't a whole number or the exposure is a second or longer.+fn exposure_text(t: f64) -> Option<String> {+ if !(t.is_finite() && t > 0.0) {+ return None;+ }+ let r = 1.0 / t;+ if t < 1.0 && (r - r.round()).abs() <= r * 0.01 {+ return Some(format!("1/{} s", r.round()));+ }+ Some(format!("{} s", short_num(t, if t < 1.0 { 2 } else { 1 })))+}++/// EXIF (`2024:02:17 12:40:19`) or XMP (`2024-02-17T12:40:19.00+01:00`) dates as+/// `2024-02-17 12:40:19`; anything else is shown as stored.+fn date_text(s: &str) -> String {+ let b = s.trim().as_bytes();+ let digits = |r: &[usize]| r.iter().all(|&i| b.get(i).is_some_and(u8::is_ascii_digit));+ let sep = |i: usize, set: &[u8]| b.get(i).is_some_and(|c| set.contains(c));+ let ch = |i: usize| b.get(i).map_or('0', |&c| c as char);+ let part = |r: std::ops::Range<usize>| r.map(ch).collect::<String>();+ if !(digits(&[0, 1, 2, 3, 5, 6, 8, 9]) && sep(4, b":-") && sep(7, b":-")) {+ return s.trim().to_string();+ }+ let date = format!("{}-{}-{}", part(0..4), part(5..7), part(8..10));+ if digits(&[11, 12, 14, 15, 17, 18]) && sep(10, b" T") && sep(13, b":") && sep(16, b":") { format!("{date} {}", part(11..19)) } else { date }+}++/// A single XMP value: the first `rdf:li` of a container, element text or attribute.+fn xmp_value(x: &str, prop: &str) -> Option<String> {+ let v = match find_element(x, prop) {+ Some((_, _, inner)) => li_values(inner).into_iter().next(),+ None => find_attr(x, prop).map(|(_, _, v)| xml_unescape(v)),+ }?;+ let v = v.trim().to_string();+ (!v.is_empty()).then_some(v)+}++/// An XMP number: a rational "331/10" or a decimal.+fn xmp_number(x: &str, prop: &str) -> Option<f64> {+ let v = xmp_value(x, prop)?;+ let n = match v.split_once('/') {+ Some((a, b)) => {+ let (a, b) = (a.trim().parse::<f64>().ok()?, b.trim().parse::<f64>().ok()?);+ (b != 0.0).then(|| a / b)?+ }+ None => v.parse::<f64>().ok()?,+ };+ n.is_finite().then_some(n)+}++/// File Info's read-only Camera Data (keys of [`CAMERA_FIELDS`], present ones only), formatted+/// for display. Read from the EXIF block (JPEG APP1, PSD resource 1058, …); properties it lacks+/// fall back to the XMP `tiff:`/`exif:`/`aux:` copies (files without an EXIF block).+pub fn camera_data(exif: Option<&[u8]>, xmp: Option<&str>) -> Value {+ let e = exif.map(photocraft_algo::exif::read).unwrap_or_default();+ let x = xmp.unwrap_or("");+ let text = |v: Option<String>, props: &[&str]| v.or_else(|| props.iter().find_map(|p| xmp_value(x, p)));+ let num =+ |v: Option<f64>, props: &[&str]| v.filter(|v| v.is_finite() && *v > 0.0).or_else(|| props.iter().find_map(|p| xmp_number(x, p))).filter(|v| *v > 0.0);+ let values = [+ text(e.make, &["tiff:Make"]),+ text(e.model, &["tiff:Model"]),+ text(e.date_taken, &["exif:DateTimeOriginal"]).map(|d| date_text(&d)),+ num(e.exposure_time, &["exif:ExposureTime"]).and_then(exposure_text),+ num(e.f_number, &["exif:FNumber"]).map(|n| format!("f/{}", short_num(n, 1))),+ num(e.iso, &["exif:ISOSpeedRatings", "exifEX:PhotographicSensitivity"]).map(|n| format!("ISO {}", n.round())),+ num(e.focal_length, &["exif:FocalLength"]).map(|f| format!("{} mm", short_num(f, 1))),+ num(e.focal_length_35mm, &["exif:FocalLengthIn35mmFilm"]).map(|f| format!("{} mm", short_num(f, 1))),+ text(e.lens, &["exifEX:LensModel", "aux:Lens"]),+ ];+ let mut m = serde_json::Map::new();+ for ((key, _), v) in CAMERA_FIELDS.into_iter().zip(values) {+ // Hostile files can carry megabytes of "lens name"; the dialog shows a line.+ if let Some(v) = v.map(|v| v.chars().take(200).collect::<String>()).filter(|v| !v.is_empty()) {+ m.insert(key.into(), json!(v));+ }+ }+ Value::Object(m)+}+/// Rewrites only changed File Info fields of an XMP packet (creating one when there is none),/// keeping the other properties verbatim. Edited properties move into their own/// `rdf:Description` (several descriptions per packet are valid XMP).@@ -634,7 +734,11 @@ fn file_info(s: &mut Session, p: &Value) -> Result<Value> {})?;}let d = s.active().ok_or(EngineError::NoDocument)?;- Ok(read_file_info(d.doc.metadata.xmp.as_deref()))+ let mut info = read_file_info(d.doc.metadata.xmp.as_deref());+ if let Value::Object(m) = &mut info {+ m.insert("camera".into(), camera_data(d.doc.metadata.exif.as_deref().map(Vec::as_slice), d.doc.metadata.xmp.as_deref()));+ }+ Ok(info)}// ---------- Automate ----------@@ -1322,7 +1426,7 @@ pub fn specs() -> Vec<CommandSpec> {"File Info…",&["File"],Some("Cmd+Alt+Shift+I"),- r##"{"title":str?,"author":str?,"authorTitle":str?,"description":str?,"keywords":[str]|"a; b"?,"copyright":str?,"copyrightStatus":"unknown|copyrighted|publicDomain"?,"copyrightUrl":str?} (no keys: read)"##,+ r##"{"title":str?,"author":str?,"authorTitle":str?,"description":str?,"keywords":[str]|"a; b"?,"copyright":str?,"copyrightStatus":"unknown|copyrighted|publicDomain"?,"copyrightUrl":str?} (no keys: read; the result also has read-only "camera":{"make","model","dateTaken","exposure","fNumber","iso","focalLength","focalLength35mm","lens"}, present keys only)"##,has_doc,file_info),diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rsindex e5b17a200..05c864bdb 100644--- a/crates/engine/src/file_cmds/tests.rs+++ b/crates/engine/src/file_cmds/tests.rs@@ -260,6 +260,77 @@ fn file_info_round_trips_through_xmp_and_psd() {assert_eq!(read_file_info(Some(&out))["authorTitle"], "Artist");}+fn camera_exif() -> Vec<u8> {+ photocraft_algo::exif::build(&photocraft_algo::exif::CameraInfo {+ make: Some("SONY".into()),+ model: Some("ILCE-7RM5".into()),+ lens: Some("24-70mm F2.8".into()),+ exposure_time: Some(1.0 / 250.0),+ f_number: Some(8.0),+ iso: Some(400.0),+ focal_length: Some(33.1),+ focal_length_35mm: Some(50.0),+ date_taken: Some("2024:02:17 12:40:19".into()),+ })+}++#[test]+fn file_info_reads_camera_data_from_jpeg_and_psd_exif() {+ let mut s = session(8, 8, 8);+ assert_eq!(s.execute("file.fileInfo", json!({})).unwrap()["camera"], json!({}));+ s.edit("exif", |doc, _| {+ doc.metadata.exif = Some(Arc::new(camera_exif()));+ Ok(())+ })+ .unwrap();+ let want = json!({+ "make": "SONY", "model": "ILCE-7RM5", "dateTaken": "2024-02-17 12:40:19", "exposure": "1/250 s", "fNumber": "f/8",+ "iso": "ISO 400", "focalLength": "33.1 mm", "focalLength35mm": "50 mm", "lens": "24-70mm F2.8"+ });+ for name in ["x.jpg", "x.psd"] {+ let (bytes, _) = encode(doc(&s), name, None).unwrap();+ let back = photocraft_io::import(name, &bytes).unwrap().document;+ let mut t = Session::new();+ t.add_document(back, None);+ assert_eq!(t.execute("file.fileInfo", json!({})).unwrap()["camera"], want, "{name}");+ // Editing the description fields leaves the read-only camera data alone.+ let edited = t.execute("file.fileInfo", json!({"title": "Pier", "camera": {"make": "ignored"}})).unwrap();+ assert_eq!(edited["camera"], want, "{name}");+ }+}++#[test]+fn camera_data_formats_like_photoshop_and_falls_back_to_xmp() {+ let info = |t: Option<f64>, n: Option<f64>, f: Option<f64>| {+ let exif = photocraft_algo::exif::build(&photocraft_algo::exif::CameraInfo { exposure_time: t, f_number: n, focal_length: f, ..Default::default() });+ camera_data(Some(&exif), None)+ };+ assert_eq!(info(Some(2.0), Some(2.8), Some(35.0)), json!({"exposure": "2 s", "fNumber": "f/2.8", "focalLength": "35 mm"}));+ assert_eq!(info(Some(0.5), Some(5.6), None), json!({"exposure": "1/2 s", "fNumber": "f/5.6"}));+ assert_eq!(info(Some(0.4), None, None), json!({"exposure": "0.4 s"}));+ assert_eq!(info(Some(1.0 / 2000.0), None, None), json!({"exposure": "1/2000 s"}));+ assert_eq!(info(Some(0.0), Some(0.0), Some(0.0)), json!({}));+ // No EXIF block (a raw import, XMP-only files): Photoshop's exif:/tiff:/aux: properties.+ let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">+<rdf:Description rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" xmlns:exif="http://ns.adobe.com/exif/1.0/" xmlns:aux="http://ns.adobe.com/exif/1.0/aux/"+ tiff:Make="SONY" tiff:Model="ILCE-7RM5" exif:ExposureTime="1/250" exif:FNumber="8/1" exif:FocalLength="331/10"+ exif:FocalLengthIn35mmFilm="50" exif:DateTimeOriginal="2024-02-17T12:40:19.00+01:00" aux:Lens="Lens & Co">+<exif:ISOSpeedRatings><rdf:Seq><rdf:li>400</rdf:li></rdf:Seq></exif:ISOSpeedRatings>+</rdf:Description></rdf:RDF></x:xmpmeta>"#;+ let want = json!({+ "make": "SONY", "model": "ILCE-7RM5", "dateTaken": "2024-02-17 12:40:19", "exposure": "1/250 s", "fNumber": "f/8",+ "iso": "ISO 400", "focalLength": "33.1 mm", "focalLength35mm": "50 mm", "lens": "Lens & Co"+ });+ assert_eq!(camera_data(None, Some(xmp)), want);+ // EXIF wins; XMP only fills what EXIF lacks.+ let exif = photocraft_algo::exif::build(&photocraft_algo::exif::CameraInfo { make: Some("Other".into()), ..Default::default() });+ let both = camera_data(Some(&exif), Some(xmp));+ assert_eq!(both["make"], "Other");+ assert_eq!(both["exposure"], "1/250 s");+ // Garbage in either block reads as no data, never a panic.+ assert_eq!(camera_data(Some(b"II*\0\xff\xff\xff\xff"), Some("<exif:FNumber>0/0</exif:FNumber> exif:ExposureTime=\"-1/0\"")), json!({}));+}+const MULTILINGUAL_XMP: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/"diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 5d512872d..46190cd40 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2434,6 +2434,17 @@ fontWeight Italic KurzívaQuick Selection found nothing there Rychlý výběr zde nic nenašelObject Selection found nothing there — try a tighter rectangle Výběr objektu zde nic nenašel — zkuste těsnější obdélníkNo subject found — try a rectangle around the object Nebyl nalezen žádný objekt — zkuste obdélník kolem objektu+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+ Camera Data Údaje fotoaparátu+cameraData Make Výrobce+cameraData Model Model+cameraData Date Taken Datum pořízení+cameraData Exposure Expoziční čas+cameraData F-Stop Clona+cameraData ISO Speed Citlivost ISO+cameraData Focal Length Ohnisková vzdálenost+cameraData Focal Length (35 mm) Ohnisková vzdálenost (35 mm)+cameraData Lens Objektiv# Shared panel dockingActivate Panel Aktivovat panelChange Panel Group Změnit skupinu panelůdiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 07c6e9e49..bff7de733 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2472,6 +2472,17 @@ fontWeight Italic KursivQuick Selection found nothing there Die Schnellauswahl hat dort nichts gefundenObject Selection found nothing there — try a tighter rectangle Die Objektauswahl hat dort nichts gefunden — versuchen Sie ein engeres RechteckNo subject found — try a rectangle around the object Kein Motiv gefunden — versuchen Sie ein Rechteck um das Objekt+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+ Camera Data Kameradaten+cameraData Make Hersteller+cameraData Model Modell+cameraData Date Taken Aufnahmedatum+cameraData Exposure Belichtungszeit+cameraData F-Stop Blende+cameraData ISO Speed ISO-Empfindlichkeit+cameraData Focal Length Brennweite+cameraData Focal Length (35 mm) Brennweite (35 mm)+cameraData Lens Objektiv# Shared panel dockingActivate Panel Bedienfeld aktivierenChange Panel Group Bedienfeldgruppe änderndiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex d154de7ff..31f8a3f07 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3541,6 +3541,16 @@ fontWeight Thin Πολύ λεπτάQuick Selection found nothing there Η Γρήγορη επιλογή δεν βρήκε τίποτα εκείObject Selection found nothing there — try a tighter rectangle Η Επιλογή αντικειμένου δεν βρήκε τίποτα εκεί — δοκιμάστε ένα πιο στενό ορθογώνιοNo subject found — try a rectangle around the object Δεν βρέθηκε θέμα — δοκιμάστε ένα ορθογώνιο γύρω από το αντικείμενο+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Κατασκευαστής+cameraData Model Μοντέλο+cameraData Date Taken Ημερομηνία λήψης+cameraData Exposure Χρόνος έκθεσης+cameraData F-Stop Διάφραγμα+cameraData ISO Speed Ευαισθησία ISO+cameraData Focal Length Εστιακή απόσταση+cameraData Focal Length (35 mm) Εστιακή απόσταση (35 mm)+cameraData Lens Φακός# Shared panel dockingActivate Panel Ενεργοποίηση πάνελChange Panel Group Αλλαγή ομάδας πάνελdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 7dbe065bc..75d4769c4 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2501,6 +2501,17 @@ fontWeight Italic CursivaQuick Selection found nothing there Selección rápida no encontró nada ahíObject Selection found nothing there — try a tighter rectangle Selección de objeto no encontró nada ahí — pruebe un rectángulo más ajustadoNo subject found — try a rectangle around the object No se encontró ningún sujeto — pruebe un rectángulo alrededor del objeto+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+ Camera Data Datos de cámara+cameraData Make Marca+cameraData Model Modelo+cameraData Date Taken Fecha de captura+cameraData Exposure Tiempo de exposición+cameraData F-Stop Número f+cameraData ISO Speed Sensibilidad ISO+cameraData Focal Length Longitud focal+cameraData Focal Length (35 mm) Longitud focal (35 mm)+cameraData Lens Objetivo# Shared panel dockingActivate Panel Activar panelChange Panel Group Cambiar grupo de panelesdiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 91b3010ed..4f14a381d 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2851,6 +2851,16 @@ fontWeight Italic ItaliqueQuick Selection found nothing there La Sélection rapide n'a rien trouvé à cet endroitObject Selection found nothing there — try a tighter rectangle La Sélection d'objet n'a rien trouvé à cet endroit — essayez un rectangle plus serréNo subject found — try a rectangle around the object Aucun sujet trouvé — essayez un rectangle autour de l'objet+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Marque+cameraData Model Modèle+cameraData Date Taken Date de prise de vue+cameraData Exposure Temps de pose+cameraData F-Stop Ouverture+cameraData ISO Speed Sensibilité ISO+cameraData Focal Length Focale+cameraData Focal Length (35 mm) Focale (35 mm)+cameraData Lens Objectif# Shared panel dockingActivate Panel Activer le panneauChange Panel Group Modifier le groupe de panneauxdiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 1e20656c9..75923eb57 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2838,6 +2838,16 @@ fontWeight Italic MiringQuick Selection found nothing there Seleksi Cepat tidak menemukan apa pun di sanaObject Selection found nothing there — try a tighter rectangle Seleksi Objek tidak menemukan apa pun di sana — coba persegi panjang yang lebih rapatNo subject found — try a rectangle around the object Subjek tidak ditemukan — coba persegi panjang di sekitar objek+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Merek+cameraData Model Model+cameraData Date Taken Tanggal Diambil+cameraData Exposure Waktu Eksposur+cameraData F-Stop Bukaan+cameraData ISO Speed Sensitivitas ISO+cameraData Focal Length Panjang Fokal+cameraData Focal Length (35 mm) Panjang Fokal (35 mm)+cameraData Lens Lensa# Shared panel dockingActivate Panel Aktifkan PanelChange Panel Group Ubah Grup Paneldiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 77cfe99e4..3ee565406 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2503,6 +2503,17 @@ fontWeight Italic CorsivoQuick Selection found nothing there Selezione rapida non ha trovato nulla lìObject Selection found nothing there — try a tighter rectangle Selezione oggetto non ha trovato nulla lì — prova un rettangolo più strettoNo subject found — try a rectangle around the object Nessun soggetto trovato — prova un rettangolo attorno all'oggetto+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+ Camera Data Dati fotocamera+cameraData Make Marca+cameraData Model Modello+cameraData Date Taken Data di scatto+cameraData Exposure Tempo di esposizione+cameraData F-Stop Diaframma+cameraData ISO Speed Sensibilità ISO+cameraData Focal Length Lunghezza focale+cameraData Focal Length (35 mm) Lunghezza focale (35 mm)+cameraData Lens Obiettivo# Shared panel dockingActivate Panel Attiva pannelloChange Panel Group Cambia gruppo di pannellidiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 240897c93..e31bae079 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3452,6 +3452,16 @@ fontWeight Italic 斜体Quick Selection found nothing there クイック選択ではそこに何も見つかりませんでしたObject Selection found nothing there — try a tighter rectangle オブジェクト選択ではそこに何も見つかりませんでした — より狭い長方形で試してくださいNo subject found — try a rectangle around the object 被写体が見つかりません — オブジェクトを囲む長方形を試してください+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make メーカー+cameraData Model モデル+cameraData Date Taken 撮影日時+cameraData Exposure 露出時間+cameraData F-Stop 絞り値+cameraData ISO Speed ISO 感度+cameraData Focal Length 焦点距離+cameraData Focal Length (35 mm) 焦点距離 (35 mm 換算)+cameraData Lens レンズ# Shared panel dockingActivate Panel パネルをアクティブにするChange Panel Group パネルグループを変更diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex d162f5b7a..1ec3bf60a 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3012,6 +3012,17 @@ fontWeight Italic 기울임Quick Selection found nothing there 빠른 선택으로 해당 위치에서 아무것도 찾지 못했습니다Object Selection found nothing there — try a tighter rectangle 개체 선택으로 해당 위치에서 아무것도 찾지 못했습니다 — 더 좁은 사각형을 사용해 보세요No subject found — try a rectangle around the object 피사체를 찾을 수 없습니다 — 개체 주위에 사각형을 그려 보세요+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+ Camera Data 카메라 데이터+cameraData Make 제조사+cameraData Model 모델+cameraData Date Taken 촬영 날짜+cameraData Exposure 노출 시간+cameraData F-Stop 조리개 값+cameraData ISO Speed ISO 감도+cameraData Focal Length 초점 거리+cameraData Focal Length (35 mm) 초점 거리(35mm 환산)+cameraData Lens 렌즈# Shared panel dockingActivate Panel 패널 활성화Change Panel Group 패널 그룹 변경diff --git a/crates/ui-egui/src/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rsindex 9c1f69caa..206629a2e 100644--- a/crates/ui-egui/src/i18n/live_tests.rs+++ b/crates/ui-egui/src/i18n/live_tests.rs@@ -113,6 +113,44 @@ fn fill_dialog_and_contour_choices_have_translations_and_draw_in_the_selected_la});}+#[test]+fn file_info_camera_data_has_translations_and_draws_read_only() {+ for language in Lang::all().filter(|language| language.complete_menus()) {+ assert!(has(language, "Camera Data"), "{}: untranslated Camera Data", language.code());+ for (_, label) in photocraft_engine::file_cmds::CAMERA_FIELDS {+ assert!(language.catalog().contextual("cameraData", label).is_some(), "{}: untranslated cameraData {label}", language.code());+ }+ }+ with_language(Lang::EN, || {+ let mut h = harness();+ let exif = photocraft_algo::exif::build(&photocraft_algo::exif::CameraInfo {+ make: Some("SONY".into()),+ exposure_time: Some(1.0 / 250.0),+ f_number: Some(8.0),+ ..Default::default()+ });+ h.state_mut()+ .session+ .edit("exif", |doc, _| {+ doc.metadata.exif = Some(std::sync::Arc::new(exif));+ Ok(())+ })+ .expect("exif");+ h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": "de"})).expect("language");+ let ctx = h.ctx.clone();+ let dialog = crate::menus::invoke(h.state_mut(), &ctx, "file.fileInfo", json!({})).expect("file info")["dialog"].as_u64().expect("dialog id");+ assert_eq!(h.state_mut().ui.dialog_mut(dialog).expect("open").fields["__camera"]["exposure"], "1/250 s");+ h.run_steps(4);+ let text = drawn_text(&h);+ for want in ["Kameradaten", "Hersteller", "SONY", "Belichtungszeit", "1/250 s", "Blende", "f/8"] {+ assert!(text.iter().any(|text| text == want), "missing {want}: {text:?}");+ }+ // Read-only: confirming submits only the editable fields.+ crate::dialogs::confirm(h.state_mut(), dialog).expect("confirm");+ assert_eq!(h.state_mut().run("file.fileInfo", json!({})).expect("info")["camera"]["make"], "SONY");+ });+}+#[test]fn cjk_font_order_follows_the_selected_language() {use photocraft_text::cjk::CjkScript;diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 145532cd0..297b0dc46 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3610,6 +3610,16 @@ cameraRaw Whites WittenQuick Selection found nothing there Snelle selectie heeft daar niets gevondenObject Selection found nothing there — try a tighter rectangle Objectselectie heeft daar niets gevonden — probeer een krappere rechthoekNo subject found — try a rectangle around the object Geen onderwerp gevonden — probeer een rechthoek rond het object+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Merk+cameraData Model Model+cameraData Date Taken Opnamedatum+cameraData Exposure Sluitertijd+cameraData F-Stop Diafragma+cameraData ISO Speed ISO-waarde+cameraData Focal Length Brandpuntsafstand+cameraData Focal Length (35 mm) Brandpuntsafstand (35 mm)+cameraData Lens Lens# Shared panel dockingActivate Panel Paneel activerenChange Panel Group Paneelgroep wijzigendiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex b66d95096..e09a94bb7 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3452,6 +3452,16 @@ cameraRaw Roughness ChropowatośćQuick Selection found nothing there Szybkie zaznaczanie nic tam nie znalazłoObject Selection found nothing there — try a tighter rectangle Zaznaczanie obiektu nic tam nie znalazło — spróbuj ciaśniejszego prostokątaNo subject found — try a rectangle around the object Nie znaleziono obiektu — spróbuj prostokąta wokół obiektu+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Producent+cameraData Model Model+cameraData Date Taken Data wykonania+cameraData Exposure Czas naświetlania+cameraData F-Stop Przysłona+cameraData ISO Speed Czułość ISO+cameraData Focal Length Ogniskowa+cameraData Focal Length (35 mm) Ogniskowa (35 mm)+cameraData Lens Obiektyw# Shared panel dockingActivate Panel Aktywuj panelChange Panel Group Zmień grupę panelidiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 3821f6cf1..b4f17afee 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2859,6 +2859,16 @@ fontWeight Italic ItálicoQuick Selection found nothing there A Seleção rápida não encontrou nada aliObject Selection found nothing there — try a tighter rectangle A Seleção de objeto não encontrou nada ali — tente um retângulo mais justoNo subject found — try a rectangle around the object Nenhum assunto encontrado — tente um retângulo ao redor do objeto+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Fabricante+cameraData Model Modelo+cameraData Date Taken Data de captura+cameraData Exposure Tempo de exposição+cameraData F-Stop Abertura+cameraData ISO Speed Sensibilidade ISO+cameraData Focal Length Distância focal+cameraData Focal Length (35 mm) Distância focal (35 mm)+cameraData Lens Lente# Shared panel dockingActivate Panel Ativar painelChange Panel Group Alterar grupo de painéisdiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 0af1516a6..aa6c705a2 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2716,6 +2716,16 @@ fontWeight Italic КурсивMissing delete command Отсутствует команда удаленияInvalid delete command Недопустимая команда удаленияLayer deleted, but confirmation preference could not be saved: {error} Слой удалён, но не удалось сохранить настройку подтверждения: {error}+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Производитель+cameraData Model Модель+cameraData Date Taken Дата съёмки+cameraData Exposure Выдержка+cameraData F-Stop Диафрагма+cameraData ISO Speed Светочувствительность ISO+cameraData Focal Length Фокусное расстояние+cameraData Focal Length (35 mm) Фокусное расстояние (35 мм)+cameraData Lens Объектив# Shared panel dockingActivate Panel Активировать панельChange Panel Group Изменить группу панелейdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 28beeab34..ea0014e21 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3538,6 +3538,16 @@ cameraRaw Masking МаскуванняQuick Selection found nothing there Швидке виділення нічого тут не знайшлоObject Selection found nothing there — try a tighter rectangle Виділення об'єктів нічого тут не знайшло — спробуйте вужчий прямокутникNo subject found — try a rectangle around the object Об'єкт не знайдено — спробуйте прямокутник навколо об'єкта+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+cameraData Make Виробник+cameraData Model Модель+cameraData Date Taken Дата зйомки+cameraData Exposure Витримка+cameraData F-Stop Діафрагма+cameraData ISO Speed Світлочутливість ISO+cameraData Focal Length Фокусна відстань+cameraData Focal Length (35 mm) Фокусна відстань (35 мм)+cameraData Lens Об'єктив# Shared panel dockingActivate Panel Активувати панельChange Panel Group Змінити групу панелейdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 0283ca3c5..84a7017d8 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2441,6 +2441,17 @@ fontWeight Italic 斜体Quick Selection found nothing there 快速选择在该处未找到任何内容Object Selection found nothing there — try a tighter rectangle 对象选择在该处未找到任何内容 — 请尝试更紧凑的矩形No subject found — try a rectangle around the object 未找到主体 — 请尝试在对象周围绘制矩形+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+ Camera Data 相机数据+cameraData Make 制造商+cameraData Model 型号+cameraData Date Taken 拍摄日期+cameraData Exposure 曝光时间+cameraData F-Stop 光圈值+cameraData ISO Speed ISO 感光度+cameraData Focal Length 焦距+cameraData Focal Length (35 mm) 焦距(35 毫米等效)+cameraData Lens 镜头# Shared panel dockingActivate Panel 激活面板Change Panel Group 更改面板组diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 42948b8d9..b00e15fbc 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2411,6 +2411,17 @@ fontWeight Italic 斜體Quick Selection found nothing there 快速選取在該處找不到任何內容Object Selection found nothing there — try a tighter rectangle 物件選取在該處找不到任何內容 — 請嘗試更緊密的矩形No subject found — try a rectangle around the object 找不到主體 — 請嘗試在物件周圍繪製矩形+# File Info ▸ Camera Data (read-only EXIF fields; "Make" is the camera maker, not the verb).+ Camera Data 相機資料+cameraData Make 製造商+cameraData Model 型號+cameraData Date Taken 拍攝日期+cameraData Exposure 曝光時間+cameraData F-Stop 光圈值+cameraData ISO Speed ISO 感光度+cameraData Focal Length 焦距+cameraData Focal Length (35 mm) 焦距(35 公釐等效)+cameraData Lens 鏡頭# Shared panel dockingActivate Panel 啟用面板Change Panel Group 變更面板群組diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex e5c4d39fa..1b2fcfb9f 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -888,6 +888,24 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {ui.end_row();}});+ camera_data(ui, f);+}++/// File Info's read-only Camera Data section (`__camera`, from the document's EXIF/XMP).+fn camera_data(ui: &mut egui::Ui, f: &Map<String, Value>) {+ let Some(camera) = f.get("__camera").and_then(Value::as_object).filter(|c| !c.is_empty()) else { return };+ ui.add_space(10.0);+ ui.label(egui::RichText::new(tl!("Camera Data")).font(crate::theme::semibold(13.0)));+ ui.add_space(4.0);+ egui::Grid::new("form-camera-data").num_columns(2).spacing([12.0, 4.0]).show(ui, |ui| {+ for (key, label) in photocraft_engine::file_cmds::CAMERA_FIELDS {+ if let Some(v) = camera.get(key).and_then(Value::as_str) {+ ui.label(crate::i18n::tr_ctx(crate::i18n::current(), "cameraData", label));+ ui.add(egui::Label::new(v).selectable(true));+ ui.end_row();+ }+ }+ });}/// Folder the batch dialogs start from: next to the active document, else the working directory.@@ -972,7 +990,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Vallet kw = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ")).unwrap_or_default();dialog(app,- json!({"title": info["title"], "author": info["author"], "authorTitle": info["authorTitle"], "description": info["description"], "keywords": kw, "copyright": info["copyright"], "copyrightStatus": info["copyrightStatus"], "copyrightUrl": info["copyrightUrl"]}),+ json!({"title": info["title"], "author": info["author"], "authorTitle": info["authorTitle"], "description": info["description"], "keywords": kw, "copyright": info["copyright"], "copyrightStatus": info["copyrightStatus"], "copyrightUrl": info["copyrightUrl"], "__camera": info["camera"]}),json!({"copyrightStatus": ["unknown", "copyrighted", "publicDomain"]}),)}