1use 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#[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#[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 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 pub fn font_path(mut self, path: impl Into<PathBuf>) -> Self {
67 self.font_paths.push(path.into());
68 self
69 }
70
71 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 pub fn system_fonts(mut self, include: bool) -> Self {
79 self.system_fonts = include;
80 self
81 }
82
83 pub fn embedded_fonts(mut self, include: bool) -> Self {
85 self.embedded_fonts = include;
86 self
87 }
88
89 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 pub fn new(root: impl Into<PathBuf>) -> Self {
105 WorldBaseConfig::new(root).build()
106 }
107
108 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 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#[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 pub fn inputs(mut self, inputs: impl ToDict) -> Self {
162 self.inputs = inputs.into_dict();
163 self
164 }
165
166 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 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 pub fn today(mut self, today: Datetime) -> Self {
184 self.today = Today::Fixed(today);
185 self
186 }
187
188 #[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 #[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 pub fn today_disabled(mut self) -> Self {
216 self.today = Today::Disabled;
217 self
218 }
219
220 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#[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 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 pub fn compile(&self) -> Warned<SourceResult<PagedDocument>> {
264 typst::compile(self)
265 }
266
267 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 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#[derive(Clone)]
322enum Today {
323 Disabled,
325 Fixed(Datetime),
327 #[cfg(any(feature = "chrono", feature = "time"))]
329 SystemLocal,
330 #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
332 SystemZone(Zone),
333}
334
335impl 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 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 Today::SystemZone(zone) => match offset {
367 Some(hours) => offset_now(hours),
368 None => zone.now(),
369 },
370 }
371 }
372}
373
374#[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#[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#[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#[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}