tinymist_world/
system.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use std::{borrow::Cow, sync::Arc};

use tinymist_std::{error::prelude::*, ImmutPath};
use tinymist_vfs::{system::SystemAccessModel, ImmutDict, Vfs};
use typst::{utils::LazyHash, Features};

use crate::{
    args::{CompileFontArgs, CompilePackageArgs},
    config::{CompileFontOpts, CompileOpts},
    font::{system::SystemFontSearcher, FontResolverImpl},
    package::{registry::HttpRegistry, RegistryPathMapper},
    EntryState,
};

mod diag;
pub use diag::*;

/// type trait of [`TypstSystemWorld`].
#[derive(Debug, Clone, Copy)]
pub struct SystemCompilerFeat;

impl crate::CompilerFeat for SystemCompilerFeat {
    /// Uses [`FontResolverImpl`] directly.
    type FontResolver = FontResolverImpl;
    /// It accesses a physical file system.
    type AccessModel = SystemAccessModel;
    /// It performs native HTTP requests for fetching package data.
    type Registry = HttpRegistry;
}

/// The compiler universe in system environment.
pub type TypstSystemUniverse = crate::world::CompilerUniverse<SystemCompilerFeat>;
/// The compiler world in system environment.
pub type TypstSystemWorld = crate::world::CompilerWorld<SystemCompilerFeat>;
/// The compute graph in system environment.
pub type SystemWorldComputeGraph = crate::WorldComputeGraph<SystemCompilerFeat>;

impl TypstSystemUniverse {
    /// Create [`TypstSystemWorld`] with the given options.
    /// See SystemCompilerFeat for instantiation details.
    /// See [`CompileOpts`] for available options.
    pub fn new(mut opts: CompileOpts) -> Result<Self> {
        let registry: Arc<HttpRegistry> = Arc::default();
        let resolver = Arc::new(RegistryPathMapper::new(registry.clone()));
        let inputs = std::mem::take(&mut opts.inputs);

        // todo: enable html
        Ok(Self::new_raw(
            opts.entry.clone().try_into()?,
            Features::default(),
            Some(Arc::new(LazyHash::new(inputs))),
            Vfs::new(resolver, SystemAccessModel {}),
            registry,
            Arc::new(Self::resolve_fonts(opts)?),
        ))
    }

    /// Resolve fonts from given options.
    fn resolve_fonts(opts: CompileOpts) -> Result<FontResolverImpl> {
        let mut searcher = SystemFontSearcher::new();
        searcher.resolve_opts(opts.into())?;
        Ok(searcher.build())
    }
}

/// Builders for Typst universe.
pub struct SystemUniverseBuilder;

impl SystemUniverseBuilder {
    /// Create [`TypstSystemUniverse`] with the given options.
    /// See [`LspCompilerFeat`] for instantiation details.
    pub fn build(
        entry: EntryState,
        inputs: ImmutDict,
        font_resolver: Arc<FontResolverImpl>,
        package_registry: HttpRegistry,
    ) -> TypstSystemUniverse {
        let registry = Arc::new(package_registry);
        let resolver = Arc::new(RegistryPathMapper::new(registry.clone()));

        // todo: enable html
        TypstSystemUniverse::new_raw(
            entry,
            Features::default(),
            Some(inputs),
            Vfs::new(resolver, SystemAccessModel {}),
            registry,
            font_resolver,
        )
    }

    /// Resolve fonts from given options.
    pub fn resolve_fonts(args: CompileFontArgs) -> Result<FontResolverImpl> {
        let mut searcher = SystemFontSearcher::new();
        searcher.resolve_opts(CompileFontOpts {
            font_paths: args.font_paths,
            no_system_fonts: args.ignore_system_fonts,
            with_embedded_fonts: typst_assets::fonts().map(Cow::Borrowed).collect(),
        })?;
        Ok(searcher.build())
    }

    /// Resolve package registry from given options.
    pub fn resolve_package(
        cert_path: Option<ImmutPath>,
        args: Option<&CompilePackageArgs>,
    ) -> HttpRegistry {
        HttpRegistry::new(
            cert_path,
            args.and_then(|args| Some(args.package_path.clone()?.into())),
            args.and_then(|args| Some(args.package_cache_path.clone()?.into())),
        )
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::AtomicBool;

    use super::*;
    use clap::Parser;

    use crate::args::CompileOnceArgs;
    use crate::{CompileSnapshot, WorldComputable, WorldComputeGraph};

    #[test]
    fn test_args() {
        use tinymist_std::typst::TypstPagedDocument;

        let args = CompileOnceArgs::parse_from(["tinymist", "main.typ"]);
        let verse = args
            .resolve_system()
            .expect("failed to resolve system universe");

        let world = verse.snapshot();
        let _res = typst::compile::<TypstPagedDocument>(&world);
    }

    static FONT_COMPUTED: AtomicBool = AtomicBool::new(false);

    pub struct FontsOnce {
        fonts: Arc<FontResolverImpl>,
    }

    impl WorldComputable<SystemCompilerFeat> for FontsOnce {
        type Output = Self;

        fn compute(graph: &Arc<WorldComputeGraph<SystemCompilerFeat>>) -> Result<Self> {
            // Ensure that this function is only called once.
            if FONT_COMPUTED.swap(true, std::sync::atomic::Ordering::SeqCst) {
                bail!("font already computed");
            }

            Ok(Self {
                fonts: graph.snap.world.font_resolver.clone(),
            })
        }
    }

    #[test]
    fn compute_system_fonts() {
        let args = CompileOnceArgs::parse_from(["tinymist", "main.typ"]);
        let verse = args
            .resolve_system()
            .expect("failed to resolve system universe");

        let snap = CompileSnapshot::from_world(verse.snapshot());

        let graph = WorldComputeGraph::new(snap);

        let font = graph.compute::<FontsOnce>().expect("font").fonts.clone();
        let _ = font;

        let font = graph.compute::<FontsOnce>().expect("font").fonts.clone();
        let _ = font;

        assert!(FONT_COMPUTED.load(std::sync::atomic::Ordering::SeqCst));
    }
}