Skip to main content

pltrs_render/vector/
metadata.rs

1//! Document metadata: the title, creator and creation date the vector
2//! backends share, with matplotlib's `SOURCE_DATE_EPOCH` convention for
3//! reproducible builds, and the entries only SVG documents or PNG files
4//! record.
5
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use pltrs_codec::png;
9
10/// A moment in UTC, in whole seconds since the Unix epoch.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct Timestamp(pub i64);
13
14/// A calendar date and time of day in UTC.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16struct Civil {
17    year: i64,
18    month: u32,
19    day: u32,
20    hour: u32,
21    minute: u32,
22    second: u32,
23    /// 0 = Monday.
24    weekday: usize,
25}
26
27const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
28const MONTHS: [&str; 12] = [
29    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
30];
31
32impl Timestamp {
33    /// The current time.
34    pub fn now() -> Self {
35        let seconds = match SystemTime::now().duration_since(UNIX_EPOCH) {
36            Ok(elapsed) => elapsed.as_secs() as i64,
37            Err(before) => -(before.duration().as_secs() as i64),
38        };
39        Self(seconds)
40    }
41
42    /// `SOURCE_DATE_EPOCH` when set to a valid number of seconds, else the
43    /// current time (what matplotlib writes by default).
44    pub fn source_date_or_now() -> Self {
45        std::env::var("SOURCE_DATE_EPOCH")
46            .ok()
47            .and_then(|value| value.trim().parse().ok())
48            .map_or_else(Self::now, Self)
49    }
50
51    /// Howard Hinnant's `civil_from_days`.
52    fn civil(self) -> Civil {
53        let days = self.0.div_euclid(86_400);
54        let secs = self.0.rem_euclid(86_400) as u32;
55        let z = days + 719_468;
56        let era = z.div_euclid(146_097);
57        let doe = z.rem_euclid(146_097);
58        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
59        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
60        let mp = (5 * doy + 2) / 153;
61        let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
62        let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
63        let year = yoe + era * 400 + i64::from(month <= 2);
64        Civil {
65            year,
66            month,
67            day,
68            hour: secs / 3600,
69            minute: secs / 60 % 60,
70            second: secs % 60,
71            // 1970-01-01 was a Thursday.
72            weekday: (days + 3).rem_euclid(7) as usize,
73        }
74    }
75
76    /// ISO 8601 with a UTC offset (`2026-10-17T07:27:00+00:00`), as the SVG
77    /// backend writes `dc:date`.
78    pub fn iso8601(self) -> String {
79        let c = self.civil();
80        format!(
81            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}+00:00",
82            c.year, c.month, c.day, c.hour, c.minute, c.second
83        )
84    }
85
86    /// A PDF date string (`D:20261017072700Z`).
87    pub fn pdf(self) -> String {
88        let c = self.civil();
89        format!(
90            "D:{:04}{:02}{:02}{:02}{:02}{:02}Z",
91            c.year, c.month, c.day, c.hour, c.minute, c.second
92        )
93    }
94
95    /// `%a %b %d %H:%M:%S %Y`, as the PostScript backend writes
96    /// `%%CreationDate`.
97    pub fn ctime(self) -> String {
98        let c = self.civil();
99        format!(
100            "{} {} {:02} {:02}:{:02}:{:02} {}",
101            WEEKDAYS[c.weekday],
102            MONTHS[c.month as usize - 1],
103            c.day,
104            c.hour,
105            c.minute,
106            c.second,
107            c.year
108        )
109    }
110}
111
112/// Whether a PDF document has been trapped for printing (its `Trapped`
113/// entry).
114#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
115pub enum Trapped {
116    /// Trapping has been done.
117    True,
118    /// Trapping has not been done.
119    False,
120    /// Not known.
121    Unknown,
122}
123
124impl Trapped {
125    /// The PDF name of the value.
126    pub const fn name(self) -> &'static str {
127        match self {
128            Self::True => "True",
129            Self::False => "False",
130            Self::Unknown => "Unknown",
131        }
132    }
133}
134
135/// Metadata written into a saved document; `None` leaves an entry out.
136///
137/// Every vector format writes the title, creator and date; `svg` holds
138/// what only SVG documents record, and the other entries are keys of the
139/// PDF document information dictionary (SVG records the keywords too).
140/// PNG files record the text entries of `png` alone.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct Metadata {
143    /// Document title.
144    pub title: Option<String>,
145    /// The application that made the document.
146    pub creator: Option<String>,
147    /// The library that wrote it (PDF `Producer`).
148    pub producer: Option<String>,
149    /// Creation date.
150    pub date: Option<Timestamp>,
151    /// Who made the document (PDF `Author`).
152    pub author: Option<String>,
153    /// What the document is about (PDF `Subject`).
154    pub subject: Option<String>,
155    /// Keywords (PDF `Keywords`, the SVG subject).
156    pub keywords: Option<String>,
157    /// When the document was last changed (PDF `ModDate`).
158    pub modified: Option<Timestamp>,
159    /// Whether the document is trapped (PDF `Trapped`).
160    pub trapped: Option<Trapped>,
161    /// A PDF document's information dictionary as the program wrote it,
162    /// in place of the entries above: each key with its value written as
163    /// a PDF object (matplotlib's `pdfRepr` of the dictionary
164    /// `_create_pdf_info_dict` makes, keys it warns about included).
165    pub pdf_info: Option<Vec<(String, Vec<u8>)>>,
166    /// The further Dublin Core entries of SVG documents.
167    pub svg: SvgMetadata,
168    /// The text entries of PNG files.
169    pub png: PngMetadata,
170}
171
172impl Default for Metadata {
173    /// pltrs as creator and producer, dated by
174    /// [`Timestamp::source_date_or_now`]; the PNG `Software` entry
175    /// ([`PngMetadata::default`]).
176    fn default() -> Self {
177        let version = env!("CARGO_PKG_VERSION");
178        Self {
179            creator: Some(format!("pltrs v{version}")),
180            producer: Some(format!("pltrs v{version}")),
181            date: Some(Timestamp::source_date_or_now()),
182            svg: SvgMetadata::default(),
183            png: PngMetadata::default(),
184            ..Self::none()
185        }
186    }
187}
188
189impl Metadata {
190    /// No metadata at all (reproducible output).
191    pub const fn none() -> Self {
192        Self {
193            title: None,
194            creator: None,
195            producer: None,
196            date: None,
197            author: None,
198            subject: None,
199            keywords: None,
200            modified: None,
201            trapped: None,
202            pdf_info: None,
203            svg: SvgMetadata::none(),
204            png: PngMetadata::none(),
205        }
206    }
207}
208
209/// The Dublin Core entries of SVG documents besides the title, creator and
210/// date every format writes (matplotlib's SVG `metadata` keys), and the
211/// several agents, subjects and dates SVG can record where the shared
212/// entries hold one.
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub struct SvgMetadata {
215    /// The resource type URI (`Type`), the DCMI still image by default.
216    pub resource_type: Option<String>,
217    /// The media type (`Format`), `image/svg+xml` by default.
218    pub format: Option<String>,
219    /// `Coverage`.
220    pub coverage: Option<String>,
221    /// `Description`.
222    pub description: Option<String>,
223    /// `Identifier`.
224    pub identifier: Option<String>,
225    /// `Language`.
226    pub language: Option<String>,
227    /// `Relation`.
228    pub relation: Option<String>,
229    /// `Source`.
230    pub source: Option<String>,
231    /// Several creators (`Creator` as a list), written in place of
232    /// [`Metadata::creator`] when not empty.
233    pub creators: Vec<String>,
234    /// `Contributor` agents.
235    pub contributors: Vec<String>,
236    /// `Publisher` agents.
237    pub publishers: Vec<String>,
238    /// `Rights` holders.
239    pub rights: Vec<String>,
240    /// Several keywords (`Keywords` as a list), written in place of
241    /// [`Metadata::keywords`] when not empty.
242    pub keywords: Vec<String>,
243    /// Dates in ISO 8601, several making a period (`Date` as a list),
244    /// written in place of [`Metadata::date`] when not empty.
245    pub dates: Vec<String>,
246}
247
248impl Default for SvgMetadata {
249    /// The resource type and format matplotlib records by default.
250    fn default() -> Self {
251        Self {
252            resource_type: Some("http://purl.org/dc/dcmitype/StillImage".to_owned()),
253            format: Some("image/svg+xml".to_owned()),
254            ..Self::none()
255        }
256    }
257}
258
259impl SvgMetadata {
260    /// No entry at all.
261    pub const fn none() -> Self {
262        Self {
263            resource_type: None,
264            format: None,
265            coverage: None,
266            description: None,
267            identifier: None,
268            language: None,
269            relation: None,
270            source: None,
271            creators: Vec::new(),
272            contributors: Vec::new(),
273            publishers: Vec::new(),
274            rights: Vec::new(),
275            keywords: Vec::new(),
276            dates: Vec::new(),
277        }
278    }
279}
280
281/// The `Software` entry of pltrs' PNG files, where matplotlib writes its
282/// own name and version (`Matplotlib version3.11.2, https://matplotlib.org/`).
283pub const PNG_SOFTWARE: &str = concat!("pltrs v", env!("CARGO_PKG_VERSION"));
284
285/// The text entries of a PNG file (matplotlib's PNG `metadata`): any
286/// keywords, PNG's own being `Title`, `Author`, `Description`,
287/// `Copyright`, `Creation Time`, `Software`, `Disclaimer`, `Warning`,
288/// `Source` and `Comment`. They are written in order as `tEXt` chunks, or
289/// as `iTXt` chunks when the text is not Latin-1, as Pillow writes them.
290///
291/// matplotlib merges the `metadata` dictionary over its default
292/// `Software` entry and leaves out the keys set to `None`;
293/// [`PngMetadata::with`] and [`PngMetadata::without`] do the same.
294///
295/// ```
296/// use pltrs_render::PngMetadata;
297/// // matplotlib's `metadata={"Title": "Signal", "Software": None}`.
298/// let png = PngMetadata::default().with("Title", "Signal").without("Software");
299/// assert_eq!(png.entries(), [("Title".to_owned(), "Signal".to_owned())]);
300/// let defaults = PngMetadata::default();
301/// assert_eq!(defaults.entries()[0].0, "Software");
302/// ```
303#[derive(Clone, Debug, PartialEq, Eq)]
304pub struct PngMetadata {
305    /// Keywords and texts, in file order, each keyword once.
306    entries: Vec<(String, String)>,
307}
308
309impl Default for PngMetadata {
310    /// The `Software` entry naming pltrs ([`PNG_SOFTWARE`]), as matplotlib
311    /// names itself.
312    fn default() -> Self {
313        Self::none().with("Software", PNG_SOFTWARE)
314    }
315}
316
317impl PngMetadata {
318    /// No entry at all.
319    pub const fn none() -> Self {
320        Self {
321            entries: Vec::new(),
322        }
323    }
324
325    /// These entries with `keyword` set to `text`: in place when the
326    /// keyword has an entry, else as a new last entry (a key of
327    /// matplotlib's `metadata`).
328    #[must_use]
329    pub fn with(mut self, keyword: impl Into<String>, text: impl Into<String>) -> Self {
330        let (keyword, text) = (keyword.into(), text.into());
331        match self.entries.iter_mut().find(|(key, _)| *key == keyword) {
332            Some(entry) => entry.1 = text,
333            None => self.entries.push((keyword, text)),
334        }
335        self
336    }
337
338    /// These entries without `keyword` (a key of matplotlib's `metadata`
339    /// set to `None`).
340    #[must_use]
341    pub fn without(mut self, keyword: &str) -> Self {
342        self.entries.retain(|(key, _)| key != keyword);
343        self
344    }
345
346    /// The keywords and texts, in file order.
347    pub fn entries(&self) -> &[(String, String)] {
348        &self.entries
349    }
350
351    /// `encoder` writing these entries as text chunks, in order.
352    pub fn apply_to(&self, encoder: png::Encoder) -> png::Encoder {
353        self.entries
354            .iter()
355            .fold(encoder, |encoder, (keyword, text)| {
356                encoder.text(keyword, text)
357            })
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    #[test]
366    fn formats_dates() {
367        let t = Timestamp(1_792_222_020);
368        assert_eq!(t.iso8601(), "2026-10-17T07:27:00+00:00");
369        assert_eq!(t.pdf(), "D:20261017072700Z");
370        assert_eq!(t.ctime(), "Sat Oct 17 07:27:00 2026");
371        assert_eq!(Timestamp(0).ctime(), "Thu Jan 01 00:00:00 1970");
372        assert_eq!(Timestamp(-1).iso8601(), "1969-12-31T23:59:59+00:00");
373        assert_eq!(Timestamp(951_782_400).pdf(), "D:20000229000000Z");
374    }
375
376    #[test]
377    fn defaults_name_pltrs() {
378        let metadata = Metadata::default();
379        assert!(metadata.creator.is_some_and(|c| c.starts_with("pltrs")));
380        assert_eq!(Metadata::none().date, None);
381    }
382
383    #[test]
384    fn png_entries_merge_like_matplotlib_dictionaries() {
385        let png = PngMetadata::default()
386            .with("Title", "a")
387            .with("Software", "b")
388            .with("Title", "c");
389        let entries: Vec<(&str, &str)> = png
390            .entries()
391            .iter()
392            .map(|(key, text)| (key.as_str(), text.as_str()))
393            .collect();
394        assert_eq!(entries, [("Software", "b"), ("Title", "c")]);
395        let emptied = png.without("Software").without("Title");
396        assert_eq!(emptied.entries(), []);
397        assert_eq!(Metadata::none().png, PngMetadata::none());
398        assert_eq!(PngMetadata::default().entries()[0].1, PNG_SOFTWARE);
399    }
400}