Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/typst_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub extern "C" fn create_compiler(
};

let input_str = unsafe { CStr::from_ptr(input).to_str().unwrap_or("") };
let input_path = PathBuf::from(input_str);
let sys_inputs_str = unsafe { CStr::from_ptr(sys_inputs).to_str().unwrap_or("{}") };

let font_paths_vec: Vec<PathBuf> = unsafe {
Expand All @@ -91,7 +92,7 @@ pub extern "C" fn create_compiler(
root,
&font_paths_vec,
inputs,
input_str,
input_path,
!ignore_system_fonts,
) {
Ok(world) => Box::into_raw(Box::new(Compiler(world))),
Expand Down
29 changes: 15 additions & 14 deletions src/typst_core/src/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};

use ecow::eco_format;
use chrono::{DateTime, Datelike, Local};
use typst::diag::{FileError, FileResult, StrResult};
use typst::foundations::{Bytes, Datetime};
Expand Down Expand Up @@ -81,20 +82,25 @@ impl SystemWorld {
root: PathBuf,
font_paths: &[PathBuf],
inputs: typst::foundations::Dict,
main_content: &str,
input: PathBuf,
include_system_fonts: bool,
) -> StrResult<Self> {
let mut font_searcher = FontSearcher::new();
font_searcher.include_system_fonts(include_system_fonts);
let fonts = font_searcher.search_with(font_paths);

let mut slots = HashMap::new();
let main_id = FileId::new_fake(VirtualPath::new("<main>"));
let mut main_slot = FileSlot::new(main_id);
main_slot
.source
.init(Source::new(main_id, main_content.to_string()));
slots.insert(main_id, main_slot);
// Resolve the main file path relative to the root
// If the input path is absolute, try to make it relative to the root.
// If it's already relative, assume it's relative to the root.
let relative_path = if input.is_absolute() {
input.strip_prefix(&root).map_err(|_| {
eco_format!("input file must be contained in the project root")
})?
} else {
&input
};

let main_id = FileId::new(None, VirtualPath::new(relative_path));

Ok(Self {
root,
Expand All @@ -107,7 +113,7 @@ impl SystemWorld {
),
book: LazyHash::new(fonts.book.clone()),
fonts: Arc::new(fonts),
slots: Mutex::new(slots),
slots: Mutex::new(HashMap::new()),
package_storage: PackageStorage::new(None, None, crate::download::downloader()),
now: OnceLock::new(),
})
Expand Down Expand Up @@ -204,11 +210,6 @@ impl<T: Clone> SlotCell<T> {
}
}

fn init(&mut self, data: T) {
self.data = Some(Ok(data));
self.accessed = true;
}

fn get_or_init(
&mut self,
path: impl FnOnce() -> FileResult<PathBuf>,
Expand Down
3 changes: 2 additions & 1 deletion src/typstsharp.cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ Data item is #data.item and this is a number
A things is #data.things
""";

using var client = new TypstCompiler(input);
File.WriteAllText("input.typ", input);
using var client = new TypstCompiler("input.typ");

var sw = Stopwatch.StartNew();

Expand Down
9 changes: 5 additions & 4 deletions src/typstsharp/TypstCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,19 @@ public unsafe class TypstCompiler : IDisposable
/// <summary>
/// Initializes a new instance of the <see cref="TypstCompiler"/> class.
/// </summary>
/// <param name="input">The Typst source code to compile.</param>
/// <param name="inputPath">The path to the Typst source file to compile.</param>
/// <param name="fonts">Font settings, including system fonts and custom font paths.</param>
/// <param name="sysInputs">Initial system inputs (legacy, prefer SetSysInputs).</param>
/// <param name="root">The root directory for the compilation, used for resolving relative paths.</param>
/// <exception cref="Exception">Thrown when the Typst compiler fails to initialize.</exception>
public TypstCompiler(string input, Fonts? fonts = null, Dictionary<string, object>? sysInputs = null, string? root = null)
public TypstCompiler(string inputPath, Fonts? fonts = null, Dictionary<string, object>? sysInputs = null)
{
fonts ??= new Fonts();
var fontPaths = fonts.FontPaths ?? Enumerable.Empty<string>();
bool ignoreSystemFonts = !fonts.IncludeSystemFonts;

var inputPtr = Marshal.StringToHGlobalAnsi(input);
var inputPtr = Marshal.StringToHGlobalAnsi(inputPath);

var root = inputPath != null ? Path.GetDirectoryName(Path.GetFullPath(inputPath)) : null;
IntPtr rootPtr = IntPtr.Zero;
if (!string.IsNullOrWhiteSpace(root))
{
Expand Down
Loading