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, Duration, Str};
11use typst::syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot};
12use typst::text::{Font, FontBook};
13use typst::utils::LazyHash;
14use typst::{Library, LibraryExt, World};
15use typst_kit::fonts::{self, FontStore};
16use typst_layout::PagedDocument;
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 fonts: FontStore,
35}
36
37impl fmt::Debug for WorldBase {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.debug_struct("WorldBase")
40 .field("root", &self.inner.root)
41 .finish_non_exhaustive()
42 }
43}
44
45#[derive(Debug, Clone)]
50#[must_use]
51pub struct WorldBaseConfig {
52 root: PathBuf,
53 font_paths: Vec<PathBuf>,
54 system_fonts: bool,
55 embedded_fonts: bool,
56}
57
58impl WorldBaseConfig {
59 pub fn new(root: impl Into<PathBuf>) -> Self {
61 Self { root: root.into(), font_paths: Vec::new(), system_fonts: true, embedded_fonts: true }
62 }
63
64 pub fn font_path(mut self, path: impl Into<PathBuf>) -> Self {
66 self.font_paths.push(path.into());
67 self
68 }
69
70 pub fn font_paths<P: Into<PathBuf>>(mut self, paths: impl IntoIterator<Item = P>) -> Self {
72 self.font_paths.extend(paths.into_iter().map(Into::into));
73 self
74 }
75
76 pub fn system_fonts(mut self, include: bool) -> Self {
78 self.system_fonts = include;
79 self
80 }
81
82 pub fn embedded_fonts(mut self, include: bool) -> Self {
84 self.embedded_fonts = include;
85 self
86 }
87
88 pub fn build(self) -> WorldBase {
90 let mut store = FontStore::new();
92 for path in &self.font_paths {
93 store.extend(fonts::scan(path));
94 }
95 if self.system_fonts {
96 store.extend(fonts::system());
97 }
98 if self.embedded_fonts {
99 store.extend(fonts::embedded());
100 }
101 let inner = WorldBaseInner { root: self.root, fonts: store };
102 WorldBase { inner: Arc::new(inner) }
103 }
104}
105
106impl WorldBase {
107 pub fn new(root: impl Into<PathBuf>) -> Self {
111 WorldBaseConfig::new(root).build()
112 }
113
114 pub fn concrete(&self, main: impl AsRef<Path>) -> ConcreteWorldBuilder {
118 ConcreteWorldBuilder {
119 base: self.clone(),
120 main: file_id(main),
121 inputs: Dict::new(),
122 files: HashMap::new(),
123 today: Today::default(),
124 }
125 }
126}
127
128impl WorldBaseInner {
129 fn load_file(&self, id: FileId) -> FileResult<Vec<u8>> {
130 let path = id
131 .vpath()
132 .realize(&self.root)
133 .map_err(|_| FileError::AccessDenied)?;
134 fs::read(&path).map_err(|err| match err.kind() {
137 std::io::ErrorKind::NotFound => FileError::NotFound(path),
138 std::io::ErrorKind::PermissionDenied => FileError::AccessDenied,
139 std::io::ErrorKind::IsADirectory => FileError::IsDirectory,
140 _ => FileError::Other(Some(format!("{err}").into())),
141 })
142 }
143}
144
145#[derive(Clone)]
147#[must_use]
148pub struct ConcreteWorldBuilder {
149 base: WorldBase,
150 main: FileId,
151 inputs: Dict,
152 files: HashMap<FileId, Bytes>,
153 today: Today,
154}
155
156impl fmt::Debug for ConcreteWorldBuilder {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 f.debug_struct("ConcreteWorldBuilder")
159 .field("main", &self.main)
160 .field("inputs", &self.inputs)
161 .finish_non_exhaustive()
162 }
163}
164
165impl ConcreteWorldBuilder {
166 pub fn inputs(mut self, inputs: impl ToDict) -> Self {
168 self.inputs = inputs.into_dict();
169 self
170 }
171
172 pub fn input(mut self, key: impl Into<Str>, value: impl ToValue) -> Self {
174 self.inputs.insert(key.into(), value.into_value());
175 self
176 }
177
178 pub fn file(mut self, path: impl AsRef<Path>, content: impl Into<Vec<u8>>) -> Self {
181 self.files.insert(file_id(path), Bytes::new(content.into()));
182 self
183 }
184
185 pub fn today(mut self, today: Datetime) -> Self {
190 self.today = Today::Fixed(today);
191 self
192 }
193
194 #[cfg(any(feature = "chrono", feature = "time"))]
201 #[cfg_attr(docsrs, doc(cfg(any(feature = "chrono", feature = "time"))))]
202 pub fn today_system(mut self) -> Self {
203 self.today = Today::SystemLocal;
204 self
205 }
206
207 #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
214 #[cfg_attr(docsrs, doc(cfg(any(feature = "chrono-tz", feature = "time-tz"))))]
215 pub fn today_system_in(mut self, zone: impl Into<Zone>) -> Self {
216 self.today = Today::SystemZone(zone.into());
217 self
218 }
219
220 pub fn today_disabled(mut self) -> Self {
222 self.today = Today::Disabled;
223 self
224 }
225
226 pub fn build(self) -> ConcreteWorld {
228 let library = Library::builder().with_inputs(self.inputs).build();
229 ConcreteWorld {
230 base: self.base.inner,
231 library: LazyHash::new(library),
232 files: self.files,
233 main: self.main,
234 today: self.today,
235 }
236 }
237}
238
239#[must_use]
245pub struct ConcreteWorld {
246 base: Arc<WorldBaseInner>,
247 library: LazyHash<Library>,
248 files: HashMap<FileId, Bytes>,
249 main: FileId,
250 today: Today,
251}
252
253impl fmt::Debug for ConcreteWorld {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.debug_struct("ConcreteWorld")
256 .field("main", &self.main)
257 .finish_non_exhaustive()
258 }
259}
260
261impl ConcreteWorld {
262 pub fn add_file(&mut self, path: impl AsRef<Path>, content: impl Into<Vec<u8>>) {
264 self.files.insert(file_id(path), Bytes::new(content.into()));
265 }
266
267 pub fn compile(&self) -> Warned<SourceResult<PagedDocument>> {
270 typst::compile(self)
271 }
272
273 pub fn render_pdf(&self, options: &PdfOptions) -> Warned<SourceResult<Vec<u8>>> {
276 let Warned { output, warnings } = self.compile();
277 let output = output.and_then(|document| pdf(&document, options));
278 Warned { output, warnings }
279 }
280
281 pub fn render_pdf_default(&self) -> Warned<SourceResult<Vec<u8>>> {
283 self.render_pdf(&PdfOptions::default())
284 }
285
286 fn read(&self, id: FileId) -> FileResult<Bytes> {
287 match self.files.get(&id) {
288 Some(bytes) => Ok(bytes.clone()),
289 None => Ok(Bytes::new(self.base.load_file(id)?)),
290 }
291 }
292}
293
294impl World for ConcreteWorld {
295 fn library(&self) -> &LazyHash<Library> {
296 &self.library
297 }
298
299 fn book(&self) -> &LazyHash<FontBook> {
300 self.base.fonts.book()
301 }
302
303 fn main(&self) -> FileId {
304 self.main
305 }
306
307 fn source(&self, id: FileId) -> FileResult<Source> {
308 let bytes = self.read(id)?;
309 let text = std::str::from_utf8(&bytes).map_err(|_| FileError::InvalidUtf8)?;
310 Ok(Source::new(id, text.to_owned()))
311 }
312
313 fn file(&self, id: FileId) -> FileResult<Bytes> {
314 self.read(id)
315 }
316
317 fn font(&self, index: usize) -> Option<Font> {
318 self.base.fonts.font(index)
319 }
320
321 fn today(&self, offset: Option<Duration>) -> Option<Datetime> {
322 self.today.resolve(offset.map(|d| d.seconds() as i64))
325 }
326}
327
328#[derive(Clone)]
330enum Today {
331 Disabled,
333 Fixed(Datetime),
335 #[cfg(any(feature = "chrono", feature = "time"))]
337 SystemLocal,
338 #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
340 SystemZone(Zone),
341}
342
343impl Default for Today {
346 fn default() -> Self {
347 #[cfg(any(feature = "chrono", feature = "time"))]
348 {
349 Today::SystemLocal
350 }
351 #[cfg(not(any(feature = "chrono", feature = "time")))]
352 {
353 Today::Disabled
354 }
355 }
356}
357
358impl Today {
359 fn resolve(&self, offset_secs: Option<i64>) -> Option<Datetime> {
360 match self {
361 Today::Disabled => None,
362 Today::Fixed(today) => match offset_secs {
364 None => Some(*today),
365 Some(_) => None,
366 },
367 #[cfg(any(feature = "chrono", feature = "time"))]
368 Today::SystemLocal => match offset_secs {
369 Some(secs) => offset_now(secs),
370 None => local_now(),
371 },
372 #[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
373 Today::SystemZone(zone) => match offset_secs {
375 Some(secs) => offset_now(secs),
376 None => zone.now(),
377 },
378 }
379 }
380}
381
382#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
388#[derive(Clone)]
389pub struct Zone(ZoneRepr);
390
391#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
392impl fmt::Debug for Zone {
393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 f.debug_struct("Zone").finish_non_exhaustive()
395 }
396}
397
398#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
399#[derive(Clone)]
400enum ZoneRepr {
401 #[cfg(feature = "chrono-tz")]
402 Chrono(chrono_tz::Tz),
403 #[cfg(feature = "time-tz")]
404 Time(&'static time_tz::Tz),
405}
406
407#[cfg(feature = "chrono-tz")]
408impl From<chrono_tz::Tz> for Zone {
409 fn from(tz: chrono_tz::Tz) -> Self {
410 Zone(ZoneRepr::Chrono(tz))
411 }
412}
413
414#[cfg(feature = "time-tz")]
415impl From<&'static time_tz::Tz> for Zone {
416 fn from(tz: &'static time_tz::Tz) -> Self {
417 Zone(ZoneRepr::Time(tz))
418 }
419}
420
421#[cfg(any(feature = "chrono-tz", feature = "time-tz"))]
422impl Zone {
423 fn now(&self) -> Option<Datetime> {
424 match &self.0 {
425 #[cfg(feature = "chrono-tz")]
426 ZoneRepr::Chrono(tz) => {
427 use chrono::{Datelike, Timelike, Utc};
428 let now = Utc::now().with_timezone(tz);
429 crate::convert::datetime(
430 now.year(),
431 now.month() as u8,
432 now.day() as u8,
433 now.hour() as u8,
434 now.minute() as u8,
435 now.second() as u8,
436 )
437 }
438 #[cfg(feature = "time-tz")]
439 ZoneRepr::Time(tz) => {
440 use time::OffsetDateTime;
441 use time_tz::OffsetDateTimeExt;
442 let now = OffsetDateTime::now_utc().to_timezone(*tz);
443 crate::convert::datetime(
444 now.year(),
445 u8::from(now.month()),
446 now.day(),
447 now.hour(),
448 now.minute(),
449 now.second(),
450 )
451 }
452 }
453 }
454}
455
456#[cfg(feature = "chrono")]
458fn local_now() -> Option<Datetime> {
459 use chrono::{Datelike, Local, Timelike};
460 let now = Local::now().naive_local();
461 crate::convert::datetime(
462 now.year(),
463 now.month() as u8,
464 now.day() as u8,
465 now.hour() as u8,
466 now.minute() as u8,
467 now.second() as u8,
468 )
469}
470
471#[cfg(all(feature = "time", not(feature = "chrono")))]
476fn local_now() -> Option<Datetime> {
477 use time::OffsetDateTime;
478 let now = OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
479 crate::convert::datetime(now.year(), u8::from(now.month()), now.day(), now.hour(), now.minute(), now.second())
480}
481
482#[cfg(feature = "chrono")]
485fn offset_now(secs: i64) -> Option<Datetime> {
486 use chrono::{Datelike, Duration, Timelike, Utc};
487 let now = Utc::now()
488 .checked_add_signed(Duration::try_seconds(secs)?)?
489 .naive_utc();
490 crate::convert::datetime(
491 now.year(),
492 now.month() as u8,
493 now.day() as u8,
494 now.hour() as u8,
495 now.minute() as u8,
496 now.second() as u8,
497 )
498}
499
500#[cfg(all(feature = "time", not(feature = "chrono")))]
501fn offset_now(secs: i64) -> Option<Datetime> {
502 use time::OffsetDateTime;
503 let now = OffsetDateTime::now_utc().checked_add(time::Duration::seconds(secs))?;
504 crate::convert::datetime(now.year(), u8::from(now.month()), now.day(), now.hour(), now.minute(), now.second())
505}
506
507fn file_id(path: impl AsRef<Path>) -> FileId {
512 let raw = path.as_ref().to_string_lossy();
513 let mut segments: Vec<&str> = Vec::new();
514 for segment in raw.split(['/', '\\']) {
515 match segment {
516 "" | "." => {}
517 ".." => {
518 segments.pop();
519 }
520 normal => segments.push(normal),
521 }
522 }
523 let vpath = VirtualPath::new(segments.join("/")).expect("normalized path is a valid vpath");
526 FileId::new(RootedPath::new(VirtualRoot::Project, vpath))
527}