diff --git a/crates/metadata/src/datetime.rs b/crates/metadata/src/datetime.rs index 0ecedae36..13ab90bca 100644 --- a/crates/metadata/src/datetime.rs +++ b/crates/metadata/src/datetime.rs @@ -14,6 +14,30 @@ pub struct DateTime { /// Sub-second part in milliseconds. pub millis: u16, pub offset_minutes: Option, + /// How much of the date was stated. XMP dates may stop at the year (`1983`) or the month + /// (`1983-04`), as for a scanned print whose day isn't known; the missing parts read as 1 and + /// the time as midnight, and the date writes back as stated. + #[serde(default, skip_serializing_if = "DatePrecision::is_full")] + pub precision: DatePrecision, +} + +/// How much of a [`DateTime`] was stated. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum DatePrecision { + /// The day at least (a time of day may be midnight because none was given). + #[default] + Full, + /// The year and month only (`1983-04`). + Month, + /// The year only (`1983`). + Year, +} + +impl DatePrecision { + pub fn is_full(&self) -> bool { + *self == DatePrecision::Full + } } fn num(s: &str) -> Option { @@ -66,6 +90,7 @@ impl DateTime { second: second.try_into().ok()?, millis: 0, offset_minutes: None, + precision: DatePrecision::Full, } .valid() } @@ -102,7 +127,8 @@ impl DateTime { self } - /// ISO 8601 (XMP date): `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDThh:mm[:ss[.s+]][TZD]`. + /// ISO 8601 (XMP date): `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDThh:mm[:ss[.s+]][TZD]`. A + /// year or a month alone keeps its [`DatePrecision`]. pub fn parse_iso(s: &str) -> Option { let s = s.trim(); let (d, t) = match s.split_once('T') { @@ -117,8 +143,17 @@ impl DateTime { if dp.len() > 3 { return None; } - let mut dt = DateTime { year, month, day, ..Default::default() }; + let precision = match dp.len() { + 1 => DatePrecision::Year, + 2 => DatePrecision::Month, + _ => DatePrecision::Full, + }; + let mut dt = DateTime { year, month, day, precision, ..Default::default() }; if !t.is_empty() { + // a time of day needs the day it is on + if !dt.precision.is_full() { + return None; + } let (clock, off) = match t.find(['Z', '+', '-']) { Some(i) => (&t[..i], Some(&t[i..])), None => (t, None), @@ -151,13 +186,25 @@ impl DateTime { dt.valid() } + /// Whether the day was stated: Exif's date form can't say a year or a month alone, so only a + /// full date is written there. + pub fn is_full(&self) -> bool { + self.precision.is_full() + } + /// Exif form `YYYY:MM:DD HH:MM:SS`. pub fn to_exif(&self) -> String { format!("{:04}:{:02}:{:02} {:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second) } - /// ISO 8601 with milliseconds when non-zero and the offset when known. + /// ISO 8601 with milliseconds when non-zero and the offset when known; a year or a month + /// alone as stated (`1983`, `1983-04`). pub fn to_iso(&self) -> String { + match self.precision { + DatePrecision::Year => return format!("{:04}", self.year), + DatePrecision::Month => return format!("{:04}-{:02}", self.year, self.month), + DatePrecision::Full => {} + } let mut s = format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second); if self.millis != 0 { s += &format!(".{:03}", self.millis); @@ -233,6 +280,29 @@ mod tests { } } + /// XMP dates may stop at the year or the month (a scanned print's `photoshop:DateCreated`): + /// read with that precision, written back as stated, and never as an Exif date. + #[test] + fn a_year_or_month_alone_reads_and_writes_as_stated() { + for (iso, precision) in [("1983", DatePrecision::Year), ("1983-04", DatePrecision::Month)] { + let d = DateTime::parse_iso(iso).unwrap(); + assert_eq!((d.year, d.month, d.day, d.precision), (1983, if iso.len() == 7 { 4 } else { 1 }, 1, precision), "{iso}"); + assert!(!d.is_full()); + assert_eq!(d.to_iso(), iso); + let meta = crate::Metadata { capture_time: Some(d), ..Default::default() }; + let xmp = crate::write_xmp(&meta); + assert!(!xmp.contains("DateTimeOriginal"), "{xmp}"); + assert_eq!(crate::parse_xmp(&xmp).unwrap().metadata.capture_time, Some(d), "{xmp}"); + assert_eq!(crate::read_exif(&crate::write_exif(&meta)).capture_time, None, "Exif can't say {iso}"); + } + for not in ["0000", "1983-00", "1983-13", "1983-04T10:00:00", "1983T10:00"] { + assert_eq!(DateTime::parse_iso(not), None, "{not}"); + } + let full = DateTime::parse_iso("1983-04-12").unwrap(); + assert!(full.is_full()); + assert_eq!(full.to_iso(), "1983-04-12T00:00:00"); + } + #[test] fn offsets() { assert_eq!(DateTime::parse_offset("+02:00"), Some(120)); @@ -299,8 +369,8 @@ mod tests { #[test] fn iso_validates_clock_while_preserving_supported_forms() { - assert_eq!(DateTime::parse_iso("2019").unwrap().to_iso(), "2019-01-01T00:00:00"); - assert_eq!(DateTime::parse_iso("2019-07").unwrap().to_iso(), "2019-07-01T00:00:00"); + assert_eq!(DateTime::parse_iso("2019").unwrap().to_iso(), "2019"); + assert_eq!(DateTime::parse_iso("2019-07").unwrap().to_iso(), "2019-07"); assert_eq!(DateTime::parse_iso("2019-07-04").unwrap().to_iso(), "2019-07-04T00:00:00"); assert_eq!(DateTime::parse_iso("2019-07-04T10:11").unwrap().to_iso(), "2019-07-04T10:11:00"); assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12").unwrap().to_iso(), "2019-07-04T10:11:12"); diff --git a/crates/metadata/src/exif.rs b/crates/metadata/src/exif.rs index 1eaf0dde3..c691b7fb0 100644 --- a/crates/metadata/src/exif.rs +++ b/crates/metadata/src/exif.rs @@ -965,7 +965,8 @@ pub fn write_exif(meta: &Metadata) -> Vec { (t::ARTIST, ascii(&meta.artist)), (t::COPYRIGHT, ascii(&meta.copyright)), (t::IMAGE_DESCRIPTION, ascii(&meta.caption)), - (t::DATE_TIME, meta.capture_time.map(|d| Value::Ascii(d.to_exif()))), + // Exif's date can't say a year or a month alone (an XMP date can) + (t::DATE_TIME, meta.capture_time.filter(DateTime::is_full).map(|d| Value::Ascii(d.to_exif()))), (t::ORIENTATION, meta.orientation.map(|o| Value::Short(vec![o.to_exif()]))), ] { if let Some(v) = v { @@ -979,7 +980,7 @@ pub fn write_exif(meta: &Metadata) -> Vec { ex.set(t::EXIF_VERSION, Value::Undefined(b"0232".to_vec())); let r = |v: Option| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| Value::Rational(vec![rational(v)])); for (tag, v) in [ - (t::DATE_TIME_ORIGINAL, meta.capture_time.map(|d| Value::Ascii(d.to_exif()))), + (t::DATE_TIME_ORIGINAL, meta.capture_time.filter(DateTime::is_full).map(|d| Value::Ascii(d.to_exif()))), (t::EXPOSURE_TIME, reciprocal(meta.exposure_time).or_else(|| r(meta.exposure_time))), (t::F_NUMBER, r(meta.f_number)), (t::FOCAL_LENGTH, r(meta.focal_length)), diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index a74b12e7f..16b2dbec8 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -32,7 +32,7 @@ mod xmp; mod xmp_merge; pub use container::{Embedded, embedded, jpeg_segments, png_chunks, webp_chunks}; -pub use datetime::DateTime; +pub use datetime::{DatePrecision, DateTime}; pub use exif::{from_tiff, read_exif, strip_exif_header, try_read_exif, try_read_exif_with, write_exif}; pub use focus::FocusPoint; pub use geom::{Orientation, Point, Rect}; diff --git a/crates/metadata/src/xmp.rs b/crates/metadata/src/xmp.rs index d5d62bb44..9f982b45a 100644 --- a/crates/metadata/src/xmp.rs +++ b/crates/metadata/src/xmp.rs @@ -714,7 +714,9 @@ pub fn write_xmp_with(meta: &Metadata, with: &XmpWrite) -> String { push("xmp:CreatorTool", meta.software.clone()); push("xmp:Rating", meta.rating.map(|v| v.to_string())); push("xmp:Label", meta.label.clone()); - push("exif:DateTimeOriginal", meta.capture_time.map(|d| d.to_iso())); + // a year or a month alone goes in `photoshop:DateCreated` only, as Lightroom writes it: Exif's + // date can't say it + push("exif:DateTimeOriginal", meta.capture_time.filter(DateTime::is_full).map(|d| d.to_iso())); push("photoshop:DateCreated", meta.capture_time.map(|d| d.to_iso())); push("exif:ExposureTime", meta.exposure_time.map(frac)); push("exif:FNumber", meta.f_number.map(frac));