Skip to main content

typst_template/
world.rs

1//! The Typst [`World`] split into a reusable base and per-generation concrete
2//! worlds.
3
4use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use std::{fmt, fs};
8
9use typst::diag::{FileError, FileResult, SourceResult, Warned};
10use typst::foundations::{Bytes, Datetime, Dict, Str};
11use typst::layout::PagedDocument;
12use typst::syntax::{FileId, Source, VirtualPath};
13use typst::text::{Font, FontBook};
14use typst::utils::LazyHash;
15use typst::{Library, LibraryExt, World};
16use typst_kit::fonts::{FontSearcher, FontSlot, Fonts};
17use typst_pdf::{PdfOptions, pdf};
18
19use crate::value::{ToDict, ToValue};
20
21/// A long-lived, cheaply cloneable Typst world.
22///
23/// Holds the project root and the loaded font set. Build a `WorldBase` once and
24/// derive a [`ConcreteWorld`] from it for each document via
25/// [`concrete`](Self::concrete). Cloning shares the fonts through an [`Arc`].
26#[derive(Clone)]
27#[must_use]
28pub struct WorldBase {
29    inner: Arc<WorldBaseInner>,
30}
31
32struct WorldBaseInner {
33    root: PathBuf,
34    book: LazyHash<FontBook>,
35    fonts: Vec<FontSlot>,
36}
37
38impl fmt::Debug for WorldBase {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.debug_struct("WorldBase")
41            .field("root", &self.inner.root)
42            .finish_non_exhaustive()
43    }
44}
45
46/// Builder for a [`WorldBase`].
47///
48/// By default both system and embedded fonts are searched; add extra font
49/// directories with [`font_path`](Self::font_path).
50#[derive(Debug, Clone)]
51#[must_use]
52pub struct WorldBaseConfig {
53    root: PathBuf,
54    font_paths: Vec<PathBuf>,
55    system_fonts: bool,
56    embedded_fonts: bool,
57}
58
59impl WorldBaseConfig {
60    /// Starts a config rooted at `root`. Real files are resolved relative to it.
61    pub fn new(root: impl Into<PathBuf>) -> Self {
62        Self { root: root.into(), font_paths: Vec::new(), system_fonts: true, embedded_fonts: true }
63    }
64
65    /// Adds a directory to search for fonts (searched recursively).
66    pub fn font_path(mut self, path: impl Into<PathBuf>) -> Self {
67        self.font_paths.push(path.into());
68        self
69    }
70
71    /// Adds several font directories.
72    pub fn font_paths<P: Into<PathBuf>>(mut self, paths: impl IntoIterator<Item = P>) -> Self {
73        self.font_paths.extend(paths.into_iter().map(Into::into));
74        self
75    }
76
77    /// Whether to include fonts installed on the system (default `true`).
78    pub fn system_fonts(mut self, include: bool) -> Self {
79        self.system_fonts = include;
80        self
81    }
82
83    /// Whether to include the fonts embedded in `typst-assets` (default `true`).
84    pub fn embedded_fonts(mut self, include: bool) -> Self {
85        self.embedded_fonts = include;
86        self
87    }
88
89    /// Builds the base, searching for fonts now.
90    pub fn build(self) -> WorldBase {
91        let mut searcher = FontSearcher::new();
92        searcher.include_system_fonts(self.system_fonts);
93        searcher.include_embedded_fonts(self.embedded_fonts);
94        let Fonts { book, fonts } = searcher.search_with(&self.font_paths);
95        let inner = WorldBaseInner { root: self.root, book: LazyHash::new(book), fonts };
96        WorldBase { inner: Arc::new(inner) }
97    }
98}
99
100impl WorldBase {
101    /// Builds a base rooted at `root` with the default font configuration.
102    ///
103    /// Use [`WorldBaseConfig`] for finer control.
104    pub fn new(root: impl Into<PathBuf>) -> Self {
105        WorldBaseConfig::new(root).build()
106    }
107
108    /// Starts building a [`ConcreteWorld`] whose main file is `main` (a path
109    /// relative to the root, or a virtual path added with
110    /// [`file`](ConcreteWorldBuilder::file)).
111    pub fn concrete(&self, main: impl AsRef<Path>) -> ConcreteWorldBuilder {
112        ConcreteWorldBuilder {
113            base: self.clone(),
114            main: file_id(main),
115            inputs: Dict::new(),
116            files: HashMap::new(),
117            today: Today::default(),
118        }
119    }
120}
121
122impl WorldBaseInner {
123    fn load_file(&self, id: FileId) -> FileResult<Vec<u8>> {
124        let path = id
125            .vpath()
126            .resolve(&self.root)
127            .ok_or(FileError::AccessDenied)?;
128        // TODO: Cache reads in the base and re-validate against mtime on the
129        // next request. See TODO.md ("Disk file read cache").
130        fs::read(&path).map_err(|err| match err.kind() {
131            std::io::ErrorKind::NotFound => FileError::NotFound(path),
132            std::io::ErrorKind::PermissionDenied => FileError::AccessDenied,
133            std::io::ErrorKind::IsADirectory => FileError::IsDirectory,
134            _ => FileError::Other(Some(format!("{err}").into())),
135        })
136    }
137}
138
139/// Builder for a [`ConcreteWorld`].
140#[derive(Clone)]
141#[must_use]
142pub struct ConcreteWorldBuilder {
143    base: WorldBase,
144    main: FileId,
145    inputs: Dict,
146    files: HashMap<FileId, Bytes>,
147    today: Today,
148}
149
150impl fmt::Debug for ConcreteWorldBuilder {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.debug_struct("ConcreteWorldBuilder")
153            .field("main", &self.main)
154            .field("inputs", &self.inputs)
155            .finish_non_exhaustive()
156    }
157}
158
159impl ConcreteWorldBuilder {
160    /// Sets the whole `sys.inputs` dictionary, replacing any earlier inputs.
161    pub fn inputs(mut self, inputs: impl ToDict) -> Self {
162        self.inputs = inputs.into_dict();
163        self
164    }
165
166    /// Adds a single `sys.inputs` entry.
167    pub fn input(mut self, key: impl Into<Str>, value: impl ToValue) -> Self {
168        self.inputs.insert(key.into(), value.into_value());
169        self
170    }
171
172    /// Adds a virtual in-memory file at `path`, visible to the document instead
173    /// of any real file at that path.
174    pub fn file(mut self, path: impl AsRef<Path>, content: impl Into<Vec<u8>>) -> Self {
175        self.files.insert(file_id(path), Bytes::new(content.into()));
176        self
177    }
178
179    /// Pins `datetime.today()` to a fixed value.
180    ///
181    /// Answers only offset-less (`auto`) requests; `datetime.today(offset: N)`
182    /// returns nothing.
183    pub fn today(mut self, today: Datetime) -> Self {
184        self.today = Today::Fixed(today);
185        self
186    }
187
188    /// Makes `datetime.today()` read the system clock, treating "local" as the
189    /// operating system's time zone.
190    ///
191    /// With the `time` backend, "local" falls back to UTC when the OS offset is
192    /// unavailable (e.g. in a multithreaded process); use
193    /// [`today_system_in`](Self::today_system_in) for a specific zone.
194    #[cfg(any(feature = "chrono", feature = "time"))]
195    #[cfg_attr(docsrs, doc(cfg(any(feature = "chrono", feature = "time"))))]
196    pub fn today_system(mut self) -> Self {
197        self.today = Today::SystemLocal;
198        self
199    }
200
201    /// Makes `datetime.today()` read the system clock, treating "local" as the
202    /// given named time zone (DST-aware).
203    ///
204    /// Accepts a [`chrono_tz::Tz`](crate::chrono_tz::Tz) (feature `chrono-tz`)
205    /// or a `&'static` [`time_tz::Tz`](crate::time_tz::Tz) (feature `time-tz`)
206    /// via [`Into<Zone>`](Zone).
207    #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
208    #[cfg_attr(docsrs, doc(cfg(any(feature = "chrono-tz", feature = "time-tz"))))]
209    pub fn today_system_in(mut self, zone: impl Into<Zone>) -> Self {
210        self.today = Today::SystemZone(zone.into());
211        self
212    }
213
214    /// Makes `datetime.today()` return nothing.
215    pub fn today_disabled(mut self) -> Self {
216        self.today = Today::Disabled;
217        self
218    }
219
220    /// Builds the concrete world.
221    pub fn build(self) -> ConcreteWorld {
222        let library = Library::builder().with_inputs(self.inputs).build();
223        ConcreteWorld {
224            base: self.base.inner,
225            library: LazyHash::new(library),
226            files: self.files,
227            main: self.main,
228            today: self.today,
229        }
230    }
231}
232
233/// A single-document world: a [`WorldBase`] plus this generation's inputs and
234/// virtual files.
235///
236/// Build one via [`WorldBase::concrete`], then call
237/// [`render_pdf`](Self::render_pdf).
238#[must_use]
239pub struct ConcreteWorld {
240    base: Arc<WorldBaseInner>,
241    library: LazyHash<Library>,
242    files: HashMap<FileId, Bytes>,
243    main: FileId,
244    today: Today,
245}
246
247impl fmt::Debug for ConcreteWorld {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        f.debug_struct("ConcreteWorld")
250            .field("main", &self.main)
251            .finish_non_exhaustive()
252    }
253}
254
255impl ConcreteWorld {
256    /// Adds (or replaces) a virtual in-memory file after construction.
257    pub fn add_file(&mut self, path: impl AsRef<Path>, content: impl Into<Vec<u8>>) {
258        self.files.insert(file_id(path), Bytes::new(content.into()));
259    }
260
261    /// Compiles the document, returning the paged document (or errors) together
262    /// with any warnings.
263    pub fn compile(&self) -> Warned<SourceResult<PagedDocument>> {
264        typst::compile(self)
265    }
266
267    /// Compiles and exports to PDF, returning the bytes (or errors) together
268    /// with any compile warnings.
269    pub fn render_pdf(&self, options: &PdfOptions) -> Warned<SourceResult<Vec<u8>>> {
270        let Warned { output, warnings } = self.compile();
271        let output = output.and_then(|document| pdf(&document, options));
272        Warned { output, warnings }
273    }
274
275    /// Like [`render_pdf`](Self::render_pdf) with [`PdfOptions::default`].
276    pub fn render_pdf_default(&self) -> Warned<SourceResult<Vec<u8>>> {
277        self.render_pdf(&PdfOptions::default())
278    }
279
280    fn read(&self, id: FileId) -> FileResult<Bytes> {
281        match self.files.get(&id) {
282            Some(bytes) => Ok(bytes.clone()),
283            None => Ok(Bytes::new(self.base.load_file(id)?)),
284        }
285    }
286}
287
288impl World for ConcreteWorld {
289    fn library(&self) -> &LazyHash<Library> {
290        &self.library
291    }
292
293    fn book(&self) -> &LazyHash<FontBook> {
294        &self.base.book
295    }
296
297    fn main(&self) -> FileId {
298        self.main
299    }
300
301    fn source(&self, id: FileId) -> FileResult<Source> {
302        let bytes = self.read(id)?;
303        let text = std::str::from_utf8(&bytes).map_err(|_| FileError::InvalidUtf8)?;
304        Ok(Source::new(id, text.to_owned()))
305    }
306
307    fn file(&self, id: FileId) -> FileResult<Bytes> {
308        self.read(id)
309    }
310
311    fn font(&self, index: usize) -> Option<Font> {
312        self.base.fonts.get(index).and_then(FontSlot::get)
313    }
314
315    fn today(&self, offset: Option<i64>) -> Option<Datetime> {
316        self.today.resolve(offset)
317    }
318}
319
320/// How the world answers `datetime.today()`.
321#[derive(Clone)]
322enum Today {
323    /// `datetime.today()` returns nothing.
324    Disabled,
325    /// A fixed value; answers only offset-less requests.
326    Fixed(Datetime),
327    /// The system clock, with "local" meaning the operating system's time zone.
328    #[cfg(any(feature = "chrono", feature = "time"))]
329    SystemLocal,
330    /// The system clock, with "local" meaning a named time zone.
331    #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
332    SystemZone(Zone),
333}
334
335/// Defaults to the system clock when a `chrono`/`time` feature is enabled,
336/// otherwise leaves `datetime.today()` disabled.
337impl Default for Today {
338    fn default() -> Self {
339        #[cfg(any(feature = "chrono", feature = "time"))]
340        {
341            Today::SystemLocal
342        }
343        #[cfg(not(any(feature = "chrono", feature = "time")))]
344        {
345            Today::Disabled
346        }
347    }
348}
349
350impl Today {
351    fn resolve(&self, offset: Option<i64>) -> Option<Datetime> {
352        match self {
353            Today::Disabled => None,
354            // A fixed value answers only offset-less requests.
355            Today::Fixed(today) => match offset {
356                None => Some(*today),
357                Some(_) => None,
358            },
359            #[cfg(any(feature = "chrono", feature = "time"))]
360            Today::SystemLocal => match offset {
361                Some(hours) => offset_now(hours),
362                None => local_now(),
363            },
364            #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
365            // An explicit offset overrides the configured zone.
366            Today::SystemZone(zone) => match offset {
367                Some(hours) => offset_now(hours),
368                None => zone.now(),
369            },
370        }
371    }
372}
373
374/// A named time zone for [`today_system_in`](ConcreteWorldBuilder::today_system_in).
375///
376/// Build one with `.into()` from a [`chrono_tz::Tz`](crate::chrono_tz::Tz)
377/// (feature `chrono-tz`) or a `&'static` [`time_tz::Tz`](crate::time_tz::Tz)
378/// (feature `time-tz`). Both features may be enabled at once.
379#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
380#[derive(Clone)]
381pub struct Zone(ZoneRepr);
382
383#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
384impl fmt::Debug for Zone {
385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386        f.debug_struct("Zone").finish_non_exhaustive()
387    }
388}
389
390#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
391#[derive(Clone)]
392enum ZoneRepr {
393    #[cfg(feature = "chrono-tz")]
394    Chrono(chrono_tz::Tz),
395    #[cfg(feature = "time-tz")]
396    Time(&'static time_tz::Tz),
397}
398
399#[cfg(feature = "chrono-tz")]
400impl From<chrono_tz::Tz> for Zone {
401    fn from(tz: chrono_tz::Tz) -> Self {
402        Zone(ZoneRepr::Chrono(tz))
403    }
404}
405
406#[cfg(feature = "time-tz")]
407impl From<&'static time_tz::Tz> for Zone {
408    fn from(tz: &'static time_tz::Tz) -> Self {
409        Zone(ZoneRepr::Time(tz))
410    }
411}
412
413#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
414impl Zone {
415    fn now(&self) -> Option<Datetime> {
416        match &self.0 {
417            #[cfg(feature = "chrono-tz")]
418            ZoneRepr::Chrono(tz) => {
419                use chrono::{Datelike, Timelike, Utc};
420                let now = Utc::now().with_timezone(tz);
421                crate::convert::datetime(
422                    now.year(),
423                    now.month() as u8,
424                    now.day() as u8,
425                    now.hour() as u8,
426                    now.minute() as u8,
427                    now.second() as u8,
428                )
429            }
430            #[cfg(feature = "time-tz")]
431            ZoneRepr::Time(tz) => {
432                use time::OffsetDateTime;
433                use time_tz::OffsetDateTimeExt;
434                let now = OffsetDateTime::now_utc().to_timezone(*tz);
435                crate::convert::datetime(
436                    now.year(),
437                    u8::from(now.month()),
438                    now.day(),
439                    now.hour(),
440                    now.minute(),
441                    now.second(),
442                )
443            }
444        }
445    }
446}
447
448/// The current time in the OS-local time zone, via `chrono`.
449#[cfg(feature = "chrono")]
450fn local_now() -> Option<Datetime> {
451    use chrono::{Datelike, Local, Timelike};
452    let now = Local::now().naive_local();
453    crate::convert::datetime(
454        now.year(),
455        now.month() as u8,
456        now.day() as u8,
457        now.hour() as u8,
458        now.minute() as u8,
459        now.second() as u8,
460    )
461}
462
463/// The current time via `time`. Falls back to UTC when the OS-local offset is
464/// unavailable (e.g. in a multithreaded process); use
465/// [`today_system_in`](ConcreteWorldBuilder::today_system_in) for a specific
466/// zone.
467#[cfg(all(feature = "time", not(feature = "chrono")))]
468fn local_now() -> Option<Datetime> {
469    use time::OffsetDateTime;
470    let now = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
471    crate::convert::datetime(now.year(), u8::from(now.month()), now.day(), now.hour(), now.minute(), now.second())
472}
473
474/// The current time at a fixed UTC offset (in hours). Uses `chrono` if enabled,
475/// otherwise `time`. Returns `None` if the offset is too large to apply.
476#[cfg(feature = "chrono")]
477fn offset_now(hours: i64) -> Option<Datetime> {
478    use chrono::{Datelike, Duration, Timelike, Utc};
479    let now = Utc::now()
480        .checked_add_signed(Duration::try_hours(hours)?)?
481        .naive_utc();
482    crate::convert::datetime(
483        now.year(),
484        now.month() as u8,
485        now.day() as u8,
486        now.hour() as u8,
487        now.minute() as u8,
488        now.second() as u8,
489    )
490}
491
492#[cfg(all(feature = "time", not(feature = "chrono")))]
493fn offset_now(hours: i64) -> Option<Datetime> {
494    use time::OffsetDateTime;
495    let seconds = hours.checked_mul(3600)?;
496    let now = OffsetDateTime::now_utc().checked_add(time::Duration::seconds(seconds))?;
497    crate::convert::datetime(now.year(), u8::from(now.month()), now.day(), now.hour(), now.minute(), now.second())
498}
499
500fn file_id(path: impl AsRef<Path>) -> FileId {
501    FileId::new(None, VirtualPath::new(path))
502}