use std::path::PathBuf; use dashmap::DashSet; use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use time::{OffsetDateTime, UtcOffset}; use tsify::Tsify; use typst::{ Feature, Features, Library, LibraryExt, World, diag::{FileError, FileResult}, foundations::{Bytes, Datetime, Dict, Duration, Value}, syntax::{FileId, Source}, text::{Font, FontBook}, utils::LazyHash, }; use typst_ide::IdeWorld; use typst_syntax::{VirtualPath, VirtualRoot, package::PackageSpec}; use crate::fonts::FontLoader; /// Implementation of Typst's `World` for Typbase, managing all loaded files, /// fonts, and compilation state. #[derive(Debug)] pub struct TypstWorld { /// The file [`World::main`] points at: the pristine synth, or the render /// source while a render session is active. pub main_id: Option, /// All loaded files (sources and binaries) by id. pub files: FxHashMap, /// Features the library is built with. features: Features, /// Values for `sys.inputs`, baked into the library at build time. inputs: Dict, /// The Typst standard library for this world. library: LazyHash, /// Font loader and font book. font_loader: FontLoader, /// Sources requested by Typst but not yet loaded. pub requested_sources: DashSet, /// Files requested by Typst but not yet loaded. pub requested_files: DashSet, /// Packages requested by Typst but not yet loaded. pub requested_packages: DashSet, } impl Default for TypstWorld { fn default() -> Self { let features: Features = [Feature::Html, Feature::A11yExtras].into_iter().collect(); let inputs = Dict::new(); let library = build_library(features.clone(), &inputs); Self { main_id: None, files: FxHashMap::default(), features, inputs, library, font_loader: FontLoader::default(), requested_sources: DashSet::default(), requested_files: DashSet::default(), requested_packages: DashSet::default(), } } } /// The library a world compiles with. `sys.inputs` is baked into the library's /// global scope, so changing the inputs rebuilds it. fn build_library(features: Features, inputs: &Dict) -> LazyHash { LazyHash::new( Library::builder() .with_features(features) .with_inputs(inputs.clone()) .build(), ) } impl TypstWorld { /// Replaces `sys.inputs`: the compiling page and workspace (both optional), /// the compile reason (`editor`, `resolve`, `render`, `chat`), and the /// output target (`html` or `paged`). Rebuilding the library drops memoized /// compiles, so callers set this when the values actually change. pub fn set_inputs( &mut self, page: Option, workspace: Option, reason: String, target: String, ) { let mut inputs = Dict::new(); if let Some(page) = page { inputs.insert("page".into(), Value::Str(page.into())); } if let Some(workspace) = workspace { inputs.insert("workspace".into(), Value::Str(workspace.into())); } inputs.insert("reason".into(), Value::Str(reason.into())); inputs.insert("target".into(), Value::Str(target.into())); self.inputs = inputs; self.library = build_library(self.features.clone(), &self.inputs); } pub fn insert_source(&mut self, id: FileId, text: String) { let source = Source::new(id, text); self.files.insert(id, FileSlot::Source(source)); } /// Inserts a prepared [`Source`]. Cloning a `Source` is cheap because its /// text is refcounted, so callers that need the same text under several /// ids should clone the source instead of the string. pub fn insert_source_object(&mut self, id: FileId, source: Source) { self.files.insert(id, FileSlot::Source(source)); } /// Installed font faces. Tests and the debug lab use this to watch for /// duplicate installs. #[must_use] pub fn font_count(&self) -> usize { self.font_loader.fonts.len() } pub fn remove_source(&mut self, id: &FileId) { self.files.remove(id); } /// Drops every file loaded under `spec`'s package root. Returns how many /// files were removed so the caller can skip a recompile when nothing /// changed. pub fn remove_package(&mut self, spec: &PackageSpec) -> usize { let before = self.files.len(); self.files.retain(|id, _| { match id.root() { VirtualRoot::Package(root) => root != spec, VirtualRoot::Project => true, } }); before - self.files.len() } pub fn insert_file(&mut self, id: FileId, bytes: Bytes) { self.files.insert(id, FileSlot::Bytes(bytes)); } pub fn get_source(&self, id: FileId) -> Option<&Source> { self.get_file(id).and_then(|file| file.source()) } pub fn get_file(&self, id: FileId) -> Option<&FileSlot> { // if !self.files.contains_key(&id) { // crate::error!("{id:#?} NOT FOUND"); // } self.files.get(&id) } // pub fn set_source(&mut self, id: &FileId, text: &str) { // self.files.get_mut(id).unwrap().replace(text); // } pub fn install_font(&mut self, bytes: Vec) { self.font_loader.install(bytes); } /// Drains the sources, files, and packages the compiler asked for since /// the last call and turns them into a request list. The JS side answers /// each request and recompiles. #[must_use] pub fn take_requests(&self) -> Vec { let mut requests = Vec::new(); self.requested_sources.retain(|source| { requests.push(TypstRequest::Source(PathBuf::from(source.get_with_slash()))); false }); self.requested_files.retain(|file| { requests.push(TypstRequest::File(PathBuf::from(file.get_with_slash()))); false }); self.requested_packages.retain(|package| { requests.push(TypstRequest::Package { namespace: package.namespace.to_string(), name: package.name.to_string(), version: package.version.to_string(), }); false }); requests } } impl World for TypstWorld { fn library(&self) -> &LazyHash { &self.library } fn book(&self) -> &LazyHash { &self.font_loader.book } fn main(&self) -> FileId { self.main_id.unwrap() } fn source(&self, id: FileId) -> FileResult { if let Some(source) = self.get_source(id) { Ok(source.clone()) } else { match id.root() { VirtualRoot::Project => self.requested_sources.insert(id.vpath().clone()), VirtualRoot::Package(spec) => self.requested_packages.insert(spec.clone()), }; Err(FileError::Other(None)) } } fn file(&self, id: FileId) -> FileResult { if let Some(file) = self.get_file(id) { Ok(file.bytes()) } else { match id.root() { VirtualRoot::Project => self.requested_files.insert(id.vpath().clone()), VirtualRoot::Package(spec) => self.requested_packages.insert(spec.clone()), }; Err(FileError::Other(None)) } } fn font(&self, index: usize) -> Option { Some(self.font_loader.fonts[index].clone()) } fn today(&self, offset: Option) -> Option { let now = if let Some(duration) = offset { #[allow(clippy::cast_possible_truncation)] OffsetDateTime::now_utc() .to_offset(UtcOffset::from_hms(duration.hours() as i8, 0, 0).unwrap()) } else { OffsetDateTime::now_utc() }; Some(Datetime::Date(now.date())) } } impl IdeWorld for TypstWorld { fn upcast(&self) -> &dyn World { self } } /// Slot for a loaded file in the world, either a source or binary. #[derive(Debug)] pub enum FileSlot { /// A Typst source file. Source(Source), /// A binary file (e.g., image, font, etc). Bytes(Bytes), } impl FileSlot { #[must_use] pub const fn source(&self) -> Option<&Source> { match self { FileSlot::Source(source) => Some(source), FileSlot::Bytes(..) => None, } } pub const fn source_mut(&mut self) -> Option<&mut Source> { match self { FileSlot::Source(source) => Some(source), FileSlot::Bytes(..) => None, } } #[must_use] pub fn bytes(&self) -> Bytes { match self { FileSlot::Source(source) => Bytes::from_string(source.text().to_string()), FileSlot::Bytes(file) => file.clone(), } } } /// A file, source, or package the compiler asked for but the world does not /// have. Every compile returns the requests it accumulated, and the caller /// resolves them (workspace source, blob bytes, package tarball) and recompiles. #[derive(Tsify, Serialize, Deserialize)] #[serde(tag = "type", content = "value", rename_all = "kebab-case")] pub enum TypstRequest { Source(PathBuf), File(PathBuf), Package { namespace: String, name: String, version: String, }, }