Files
texrra-engine/src/main.rs
T
gloamxun 371f05baaa Default project previews and PDFs to route-D
uses_route_d still treated v1 as the default unless TEXRRA_ENGINE=route-d was
set, so only the flat /preview endpoint had switched. Make route-D the default
there too: an explicit engine parameter still wins, TEXRRA_ENGINE=v1 forces the
old pipeline, and a route-D error now falls through to the v1 compiler instead
of answering 422 (both preview and PDF).

Because route-D follows pdfLaTeX's Letter default for geometry-less documents,
the two server tests that asserted the v1 A4 page now ask for ?engine=v1 or
expect 215.9mm. A new test starts a server without the environment variable and
checks a project preview uses route-D's italic math face with no literal $.
2026-10-27 00:32:45 +08:00

1574 lines
55 KiB
Rust

use std::{
collections::{HashMap, hash_map::DefaultHasher},
env,
fmt::Write as _,
fs,
hash::{Hash, Hasher},
path::{Path, PathBuf},
process,
sync::{Mutex, OnceLock},
};
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
mod projects;
mod route_d;
use texrra_engine::rust_typeset;
fn main() {
if let Err(error) = run() {
eprintln!("error: {error}");
process::exit(1);
}
}
fn run() -> Result<(), String> {
let mut args = env::args().skip(1);
let Some(command) = args.next() else {
return Err("usage: texrra serve [input.tex] [port]".into());
};
if command != "serve" {
return Err("the only command is `serve`".into());
}
let input_path = args
.next()
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("examples/hello.tex"));
let port = args
.next()
.map(|value| value.parse::<u16>().map_err(|_| "port must be a number"))
.transpose()?
.unwrap_or(4173);
if args.next().is_some() {
return Err("usage: texrra serve [input.tex] [port]".into());
}
if !input_path.is_file() {
return Err(format!(
"input file does not exist: {}",
input_path.display()
));
}
let projects_root = env::var_os("TEXRRA_PROJECTS_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("projects"));
let store = projects::ProjectStore::new(projects_root.clone())?;
store.seed_from_input(&input_path)?;
let web_root = find_web_root()?;
let address = format!("127.0.0.1:{port}");
let server =
Server::http(&address).map_err(|error| format!("could not start server: {error}"))?;
println!("texrra is listening at http://{address}");
println!("Projects are stored in {}", projects_root.display());
match &web_root {
Some(path) => println!("Serving the web frontend from {}", path.display()),
None => println!(
"warning: no web frontend found; clone texrra-web and set TEXRRA_WEB_DIR to its directory"
),
}
let mut compiler = rust_typeset::CompilerSession::default();
for request in server.incoming_requests() {
if let Err(error) = handle_request(
request,
&input_path,
&mut compiler,
&store,
web_root.as_deref(),
) {
eprintln!("request error: {error}");
}
}
Ok(())
}
fn handle_request(
mut request: Request,
input_path: &PathBuf,
compiler: &mut rust_typeset::CompilerSession,
store: &projects::ProjectStore,
web_root: Option<&Path>,
) -> Result<(), String> {
let url = request.url().to_string();
let path = url.split('?').next().unwrap_or(&url).to_string();
let method = request.method().clone();
if let Some(rest) = path.strip_prefix("/api/projects") {
return handle_project_request(request, &method, rest, &url, compiler, store);
}
match (&method, path.as_str()) {
(&Method::Get, "/") => serve_web_path(request, web_root, "/"),
(&Method::Get, "/source") => {
let source = fs::read_to_string(input_path)
.map_err(|error| format!("could not read {}: {error}", input_path.display()))?;
respond(request, 200, "text/plain; charset=utf-8", &source)
}
(&Method::Post, "/compile") => {
let source = match read_and_save(&mut request, input_path) {
Ok(source) => source,
Err(error) => {
return respond(request, 413, "text/plain; charset=utf-8", &error);
}
};
match compiler.compile(&source, &input_path.display().to_string()) {
Ok(pdf) => respond_pdf(request, pdf),
Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error),
}
}
(&Method::Get, "/fonts.css") => match rust_typeset::preview_font_css() {
Ok(css) => respond_with_cache(
request,
"text/css; charset=utf-8",
css.into_bytes(),
Some("public, max-age=3600"),
),
Err(error) => respond(request, 500, "text/plain; charset=utf-8", &error),
},
(&Method::Get, path) if path.starts_with("/fonts/") => {
let name = &path["/fonts/".len()..];
match rust_typeset::preview_font_file(name) {
Some(bytes) => respond_with_cache(
request,
"font/ttf",
bytes,
Some("public, max-age=31536000, immutable"),
),
None => respond(request, 404, "text/plain; charset=utf-8", "not found"),
}
}
(&Method::Post, path) if path.starts_with("/api/route-d/edit/") => {
let unit = path["/api/route-d/edit/".len()..].parse::<usize>();
let Ok(unit) = unit else {
return respond(request, 400, "text/plain; charset=utf-8", "invalid unit");
};
let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) {
Ok(bytes) => bytes,
Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error),
};
let source = match String::from_utf8(bytes) {
Ok(source) => source,
Err(_) => {
return respond(
request,
400,
"text/plain; charset=utf-8",
"source is not valid UTF-8",
);
}
};
match route_d::edit_json(&source, unit) {
Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json),
Err(error) => respond(request, 422, "application/json; charset=utf-8", &error),
}
}
(&Method::Post, "/api/route-d/pdf") => {
let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) {
Ok(bytes) => bytes,
Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error),
};
let source = match String::from_utf8(bytes) {
Ok(source) => source,
Err(_) => {
return respond(
request,
400,
"text/plain; charset=utf-8",
"source must be UTF-8",
);
}
};
let key = route_d_flat_cache_key(&source);
if let Some(pdf) = route_d_cached_flat_pdf(key) {
return respond_pdf_with_cache(request, pdf, "hit");
}
match route_d::pdf_bytes(&source) {
Ok(pdf) => {
store_route_d_flat_pdf(key, &pdf);
respond_pdf_with_cache(request, pdf, "miss")
}
Err(error) => respond_api_error(request, 422, &error),
}
}
(&Method::Post, "/api/route-d/preview") => {
let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) {
Ok(bytes) => bytes,
Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error),
};
let source = match String::from_utf8(bytes) {
Ok(source) => source,
Err(_) => {
return respond(
request,
400,
"text/plain; charset=utf-8",
"source is not valid UTF-8",
);
}
};
let key = route_d_flat_cache_key(&source);
if let Some(json) = route_d_cached_flat_preview(key) {
return respond_json_with_cache(request, &json, "hit");
}
match route_d::preview_json(&source) {
Ok(json) => {
store_route_d_flat_preview(key, &json);
respond_json_with_cache(request, &json, "miss")
}
Err(error) => respond_api_error(request, 422, &error),
}
}
(&Method::Post, "/preview") => {
let source = match read_and_save(&mut request, input_path) {
Ok(source) => source,
Err(error) => {
return respond(
request,
413,
"application/json; charset=utf-8",
&rust_typeset::preview_error_json(&error),
);
}
};
let force_v1 = url.contains("engine=v1");
if !force_v1 && let Ok(json) = route_d::preview_json(&source) {
return respond_json_engine(request, 200, &json, "route-d");
}
match compiler.preview_json(&source, &input_path.display().to_string()) {
Ok(json) => respond_json_engine(request, 200, &json, "v1"),
Err(error) => respond(
request,
422,
"application/json; charset=utf-8",
&rust_typeset::preview_error_json(&error),
),
}
}
(&Method::Post, "/texrra") => {
let source = match read_and_save(&mut request, input_path) {
Ok(source) => source,
Err(error) => {
return respond(request, 413, "text/plain; charset=utf-8", &error);
}
};
match compiler.render_html_preview(&source, &input_path.display().to_string()) {
Ok(html) => respond(request, 200, "text/html; charset=utf-8", &html),
Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error),
}
}
(&Method::Get, path) => serve_web_path(request, web_root, path),
_ => respond(request, 404, "text/plain; charset=utf-8", "not found"),
}
}
fn find_web_root() -> Result<Option<PathBuf>, String> {
if let Some(value) = env::var_os("TEXRRA_WEB_DIR") {
let path = PathBuf::from(value);
if !path.join("index.html").is_file() {
return Err(format!(
"TEXRRA_WEB_DIR does not contain index.html: {}",
path.display()
));
}
return Ok(Some(path));
}
for candidate in [Path::new("../web"), Path::new("web")] {
if candidate.join("index.html").is_file() {
return Ok(Some(candidate.to_path_buf()));
}
}
Ok(None)
}
fn serve_web_path(request: Request, web_root: Option<&Path>, path: &str) -> Result<(), String> {
let Some(web_root) = web_root else {
return respond(
request,
200,
"text/html; charset=utf-8",
"<!doctype html><meta charset=\"utf-8\"><title>texrra</title>\
<h1>texrra web frontend not found</h1>\
<p>Clone <code>texrra-web</code> next to this checkout, or set\
<code>TEXRRA_WEB_DIR</code> to its directory, then reload.</p>",
);
};
let mut relative = percent_decode(path.trim_start_matches('/'));
if relative.is_empty() {
relative = "index.html".to_string();
}
if relative.contains("..") || relative.contains('\\') || relative.starts_with('/') {
return respond(request, 404, "text/plain; charset=utf-8", "not found");
}
let file = web_root.join(&relative);
if !file.is_file() {
return respond(request, 404, "text/plain; charset=utf-8", "not found");
}
let canonical_root = web_root
.canonicalize()
.map_err(|error| format!("could not resolve web root: {error}"))?;
let canonical_file = file
.canonicalize()
.map_err(|error| format!("could not resolve {}: {error}", file.display()))?;
if !canonical_file.starts_with(&canonical_root) {
return respond(request, 404, "text/plain; charset=utf-8", "not found");
}
let body = fs::read(&canonical_file)
.map_err(|error| format!("could not read {}: {error}", canonical_file.display()))?;
respond_with_cache(request, web_content_type(&relative), body, Some("no-cache"))
}
fn web_content_type(path: &str) -> &'static str {
let extension = path
.rsplit_once('.')
.map(|(_, extension)| extension.to_ascii_lowercase())
.unwrap_or_default();
match extension.as_str() {
"html" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" | "mjs" => "text/javascript; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"ico" => "image/x-icon",
"json" => "application/json; charset=utf-8",
"woff2" => "font/woff2",
"woff" => "font/woff",
"ttf" => "font/ttf",
_ => "application/octet-stream",
}
}
const MAX_SOURCE_BYTES: usize = 4 * 1024 * 1024;
fn read_and_save(request: &mut Request, input_path: &Path) -> Result<String, String> {
let bytes = read_body_bytes(request, MAX_SOURCE_BYTES)?;
let source = String::from_utf8(bytes).map_err(|_| "source is not valid UTF-8".to_string())?;
fs::write(input_path, &source)
.map_err(|error| format!("could not save {}: {error}", input_path.display()))?;
Ok(source)
}
fn read_body_bytes(request: &mut Request, limit: usize) -> Result<Vec<u8>, String> {
if request.body_length().is_some_and(|length| length > limit) {
return Err(body_too_large_message(limit));
}
let mut bytes = Vec::new();
let mut buffer = [0_u8; 8192];
let mut total = 0_usize;
let reader = request.as_reader();
loop {
let read = reader
.read(&mut buffer)
.map_err(|error| format!("could not read request body: {error}"))?;
if read == 0 {
break;
}
total += read;
if total > limit {
return Err(body_too_large_message(limit));
}
bytes.extend_from_slice(&buffer[..read]);
}
Ok(bytes)
}
fn body_too_large_message(limit: usize) -> String {
format!("request body is too large (limit {limit} bytes)")
}
fn respond(request: Request, status: u16, content_type: &str, body: &str) -> Result<(), String> {
let header = Header::from_bytes("Content-Type", content_type)
.map_err(|_| "invalid response header".to_string())?;
let response = Response::from_string(body)
.with_status_code(StatusCode(status))
.with_header(header);
request
.respond(response)
.map_err(|error| format!("could not send response: {error}"))
}
fn respond_json_engine(
request: Request,
status: u16,
body: &str,
engine: &str,
) -> Result<(), String> {
let content_type = Header::from_bytes("Content-Type", "application/json; charset=utf-8")
.map_err(|_| "invalid response header".to_string())?;
let engine_header = Header::from_bytes("X-Preview-Engine", engine)
.map_err(|_| "invalid response header".to_string())?;
let response = Response::from_string(body)
.with_status_code(StatusCode(status))
.with_header(content_type)
.with_header(engine_header);
request
.respond(response)
.map_err(|error| format!("could not send response: {error}"))
}
fn respond_with_cache(
request: Request,
content_type: &str,
body: Vec<u8>,
cache_control: Option<&str>,
) -> Result<(), String> {
let content_type = Header::from_bytes("Content-Type", content_type)
.map_err(|_| "invalid response header".to_string())?;
let cache_header = cache_control
.map(|value| {
Header::from_bytes("Cache-Control", value)
.map_err(|_| "invalid response header".to_string())
})
.transpose()?;
let mut response = Response::from_data(body).with_header(content_type);
if let Some(cache_header) = cache_header {
response = response.with_header(cache_header);
}
request
.respond(response)
.map_err(|error| format!("could not send response: {error}"))
}
fn respond_pdf_with_cache(request: Request, pdf: Vec<u8>, cache_state: &str) -> Result<(), String> {
let content_type = Header::from_bytes("Content-Type", "application/pdf")
.map_err(|_| "invalid PDF response header".to_string())?;
let disposition = Header::from_bytes("Content-Disposition", "inline; filename=preview.pdf")
.map_err(|_| "invalid PDF response header".to_string())?;
let cache = Header::from_bytes("X-Texrra-Cache", cache_state)
.map_err(|_| "invalid cache response header".to_string())?;
request
.respond(
Response::from_data(pdf)
.with_header(content_type)
.with_header(disposition)
.with_header(cache),
)
.map_err(|error| format!("could not send PDF response: {error}"))
}
fn respond_pdf(request: Request, pdf: Vec<u8>) -> Result<(), String> {
let content_type = Header::from_bytes("Content-Type", "application/pdf")
.map_err(|_| "invalid PDF response header".to_string())?;
let disposition = Header::from_bytes("Content-Disposition", "inline; filename=preview.pdf")
.map_err(|_| "invalid PDF response header".to_string())?;
request
.respond(
Response::from_data(pdf)
.with_header(content_type)
.with_header(disposition),
)
.map_err(|error| format!("could not send PDF response: {error}"))
}
const MAX_ZIP_BYTES: usize = 32 * 1024 * 1024;
const MAX_UPLOAD_BYTES: usize = 16 * 1024 * 1024;
fn expand_project_packages(source: &str, store: &projects::ProjectStore, id: &str) -> String {
let mut output = String::new();
let mut loaded = Vec::new();
let mut passed_packages: Vec<(String, Vec<String>)> = Vec::new();
let mut passed_classes: Vec<(String, Vec<String>)> = Vec::new();
for line in source.lines() {
let trimmed = line.trim();
if trimmed.starts_with("\\PassOptionsToPackage") {
if let Some((options, names)) = pass_options_parts(trimmed, "\\PassOptionsToPackage") {
for name in names {
record_passed_options(&mut passed_packages, &name, &options);
}
continue;
}
} else if trimmed.starts_with("\\PassOptionsToClass") {
if let Some((options, names)) = pass_options_parts(trimmed, "\\PassOptionsToClass") {
for name in names {
record_passed_options(&mut passed_classes, &name, &options);
}
continue;
}
}
if trimmed.starts_with("\\usepackage") {
if let Some((options, names)) = use_package_parts(trimmed) {
let mut expanded = String::new();
let mut replaced = false;
for name in names {
let mut requested = split_options(&options);
requested.extend(take_passed_options(&mut passed_packages, &name));
dedupe_options(&mut requested);
if let Some(text) =
load_project_file(&name, "sty", &requested, store, id, &mut loaded, 1)
{
expanded.push_str(&text);
expanded.push('\n');
replaced = true;
}
}
if replaced {
output.push_str(&expanded);
continue;
}
}
} else if trimmed.starts_with("\\documentclass") {
if let Some((options, name)) = documentclass_parts(trimmed) {
let mut requested = split_options(&options);
requested.extend(take_passed_options(&mut passed_classes, &name));
dedupe_options(&mut requested);
if let Some(text) = load_project_class(&name, &requested, store, id, &mut loaded, 1)
{
output.push_str(&format!("\\documentclass{}{{{}}}", options, "article"));
output.push('\n');
output.push_str(&text);
output.push('\n');
continue;
}
}
}
output.push_str(line);
output.push('\n');
}
output
}
fn load_project_file(
name: &str,
extension: &str,
options: &[String],
store: &projects::ProjectStore,
id: &str,
loaded: &mut Vec<String>,
depth: usize,
) -> Option<String> {
if depth > 8 || loaded.iter().any(|loaded| loaded == name) {
return None;
}
let bytes = store.read_file(id, &format!("{name}.{extension}")).ok()?;
let text = String::from_utf8(bytes).ok()?;
loaded.push(name.to_string());
let expanded = expand_required_packages(&text, store, id, loaded, depth);
let expanded = expand_file_inputs(&expanded, store, id, depth);
let processed = if extension == "sty" {
apply_class_options(&expanded, options)
} else {
let inherited = expand_class_inheritance(&expanded, store, id, loaded, depth, options);
apply_class_options(&inherited, options)
};
let processed = expand_document_hooks(&processed);
Some(sanitize_package(&strip_makeat(&processed)))
}
fn expand_document_hooks(source: &str) -> String {
let mut output = String::new();
let mut rest = source;
while let Some(position) = rest
.find("\\AtBeginDocument")
.or_else(|| rest.find("\\AtEndDocument"))
{
output.push_str(&rest[..position]);
let command_end = position
+ if rest[position..].starts_with("\\AtBeginDocument") {
"\\AtBeginDocument".len()
} else {
"\\AtEndDocument".len()
};
let after = &rest[command_end..];
let trimmed = after.trim_start();
let Some(start) = after.len().checked_sub(trimmed.len()) else {
break;
};
match balanced_group_at(after, start) {
Some((body, consumed)) => {
output.push_str(&body);
rest = &after[consumed..];
}
None => rest = after,
}
}
output.push_str(rest);
output
}
fn strip_makeat(source: &str) -> String {
source
.replace("\\makeatletter", "")
.replace("\\makeatother", "")
}
fn expand_file_inputs(
source: &str,
store: &projects::ProjectStore,
id: &str,
depth: usize,
) -> String {
if depth > 8 {
return String::new();
}
let mut output = String::new();
let mut rest = source;
loop {
let input = rest.find("\\input{");
let include = rest.find("\\include{");
let found = match (input, include) {
(Some(left), Some(right)) => Some(left.min(right)),
(Some(position), None) | (None, Some(position)) => Some(position),
(None, None) => None,
};
let Some(position) = found else {
output.push_str(rest);
break;
};
output.push_str(&rest[..position]);
let after = &rest[position..];
let open = after.find('{').expect("input brace");
let Some(close) = after[open + 1..].find('}') else {
output.push_str(after);
break;
};
let name = after[open + 1..open + 1 + close].trim();
if let Some(text) = read_project_tex(store, id, name) {
output.push_str(&expand_file_inputs(&text, store, id, depth + 1));
output.push('\n');
}
rest = &after[open + 1 + close + 1..];
}
output
}
fn read_project_tex(store: &projects::ProjectStore, id: &str, name: &str) -> Option<String> {
for candidate in [
name.to_string(),
format!("{name}.tex"),
format!("{name}.clo"),
format!("{name}.sty"),
] {
if let Ok(bytes) = store.read_file(id, &candidate) {
if let Ok(text) = String::from_utf8(bytes) {
return Some(text);
}
}
}
None
}
fn expand_required_packages(
source: &str,
store: &projects::ProjectStore,
id: &str,
loaded: &mut Vec<String>,
depth: usize,
) -> String {
let mut output = String::new();
for line in source.lines() {
let trimmed = line.trim();
if trimmed.starts_with("\\RequirePackage") || trimmed.starts_with("\\usepackage") {
if let Some((options, names)) = use_package_parts(trimmed) {
let requested = split_options(&options);
for name in names {
if let Some(text) =
load_project_file(&name, "sty", &requested, store, id, loaded, depth + 1)
{
output.push_str(&text);
output.push('\n');
}
}
}
continue;
}
output.push_str(line);
output.push('\n');
}
output
}
fn split_options(options: &str) -> Vec<String> {
options
.trim_start_matches('[')
.trim_end_matches(']')
.split(',')
.map(str::trim)
.filter(|option| !option.is_empty())
.map(str::to_string)
.collect()
}
fn pass_options_parts(line: &str, command: &str) -> Option<(Vec<String>, Vec<String>)> {
let rest = line.strip_prefix(command)?.trim_start();
let rest = rest.strip_prefix('{')?;
let close = rest.find('}')?;
let options = split_options(&rest[..close]);
let rest = rest[close + 1..].trim_start();
let rest = rest.strip_prefix('{')?;
let close = rest.find('}')?;
let names = rest[..close]
.split(',')
.map(str::trim)
.filter(|name| !name.is_empty())
.map(str::to_string)
.collect();
Some((options, names))
}
fn record_passed_options(passed: &mut Vec<(String, Vec<String>)>, name: &str, options: &[String]) {
if let Some(entry) = passed.iter_mut().find(|(key, _)| key == name) {
entry.1.extend(options.iter().cloned());
} else {
passed.push((name.to_string(), options.to_vec()));
}
}
fn take_passed_options(passed: &mut Vec<(String, Vec<String>)>, name: &str) -> Vec<String> {
let mut options = Vec::new();
passed.retain(|(key, values)| {
if key == name {
options.extend(values.iter().cloned());
false
} else {
true
}
});
options
}
fn dedupe_options(options: &mut Vec<String>) {
let mut seen = Vec::new();
options.retain(|option| {
if seen.contains(option) {
false
} else {
seen.push(option.clone());
true
}
});
}
fn use_package_parts(line: &str) -> Option<(String, Vec<String>)> {
let mut rest = line
.strip_prefix("\\usepackage")
.or_else(|| line.strip_prefix("\\RequirePackage"))?
.trim_start();
let mut options = String::new();
if rest.starts_with('[') {
let close = rest.find(']')?;
options = rest[..=close].to_string();
rest = rest[close + 1..].trim_start();
}
let rest = rest.strip_prefix('{')?;
let close = rest.find('}')?;
Some((
options,
rest[..close]
.split(',')
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
.collect(),
))
}
fn documentclass_parts(line: &str) -> Option<(String, String)> {
let mut rest = line.strip_prefix("\\documentclass")?.trim_start();
let mut options = String::new();
if rest.starts_with('[') {
let close = rest.find(']')?;
options = rest[..=close].to_string();
rest = rest[close + 1..].trim_start();
}
let rest = rest.strip_prefix('{')?;
let close = rest.find('}')?;
Some((options, rest[..close].trim().to_string()))
}
fn sanitize_package(source: &str) -> String {
const BOILERPLATE: [&str; 12] = [
"\\ProvidesPackage",
"\\ProvidesClass",
"\\NeedsTeXFormat",
"\\RequirePackage",
"\\DeclareOption",
"\\ProcessOptions",
"\\ExecuteOptions",
"\\PassOptionsToPackage",
"\\PassOptionsToClass",
"\\LoadClass",
"\\LoadClassWithOptions",
"\\endinput",
];
source
.lines()
.filter(|line| {
let trimmed = line.trim();
!trimmed.starts_with('%')
&& !BOILERPLATE
.iter()
.any(|command| trimmed.starts_with(command))
})
.collect::<Vec<_>>()
.join("\n")
}
fn balanced_group_at(text: &str, start: usize) -> Option<(String, usize)> {
if !text[start..].starts_with('{') {
return None;
}
let mut depth = 0usize;
for (offset, character) in text[start..].char_indices() {
match character {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Some((
text[start + 1..start + offset].to_string(),
start + offset + 1,
));
}
}
_ => {}
}
}
None
}
/// Executes the `\DeclareOption` / `\ExecuteOptions` / `\ProcessOptions`
/// subset of a local class file. Options named by `\documentclass[...]` run
/// their declaration codes in declaration order, `\ExecuteOptions` supplies
/// defaults for options that were not requested, and `\DeclareOption*` runs
/// when an option has no declaration. The option machinery itself is removed
/// from the emitted class body.
fn apply_class_options(source: &str, requested: &[String]) -> String {
let mut declared: Vec<(Option<String>, String)> = Vec::new();
let mut active: Vec<String> = requested
.iter()
.filter(|option| !option.is_empty())
.cloned()
.collect();
let mut output = String::new();
let mut index = 0;
while index < source.len() {
let rest = &source[index..];
if let Some(after) = rest.strip_prefix("\\DeclareOption") {
let (default, after) = match after.strip_prefix('*') {
Some(tail) => (true, tail),
None => (false, after),
};
let after = after.trim_start();
if default {
if let Some((body, body_end)) = balanced_group_at(after, 0) {
let consumed = rest.len() - after[body_end..].len();
declared.push((None, body));
index += consumed;
continue;
}
} else if let Some((key, key_end)) = balanced_group_at(after, 0) {
let tail = after[key_end..].trim_start();
if let Some((body, body_end)) = balanced_group_at(tail, 0) {
let consumed = rest.len() - tail[body_end..].len();
declared.push((Some(key), body));
index += consumed;
continue;
}
}
}
if let Some(after) = rest.strip_prefix("\\ExecuteOptions") {
let after = after.trim_start();
if let Some((list, end)) = balanced_group_at(after, 0) {
for name in list.split(',') {
let name = name.trim();
if !name.is_empty() && !active.iter().any(|option| option == name) {
active.push(name.to_string());
}
}
index += rest.len() - after[end..].len();
continue;
}
}
if let Some(after) = rest.strip_prefix("\\ProcessOptions") {
let after = after.strip_prefix('*').unwrap_or(after);
let mut matched = vec![false; active.len()];
for (key, body) in &declared {
let Some(key) = key else {
continue;
};
for (position, option) in active.iter().enumerate() {
if option == key {
output.push_str(body);
output.push('\n');
matched[position] = true;
}
}
}
if matched.iter().any(|matched| !matched) {
for (key, body) in &declared {
if key.is_none() {
output.push_str(body);
output.push('\n');
}
}
}
index += rest.len() - after.len();
continue;
}
let character = rest.chars().next().expect("character");
output.push(character);
index += character.len_utf8();
}
output
}
/// Inlines local base classes requested by `\LoadClass` /
/// `\LoadClassWithOptions` inside a class file. Requests for classes that
/// are not part of the project keep LaTeX's article fallback, so the line is
/// dropped rather than leaking into the document body.
fn expand_class_inheritance(
source: &str,
store: &projects::ProjectStore,
id: &str,
loaded: &mut Vec<String>,
depth: usize,
inherited_options: &[String],
) -> String {
let mut output = String::new();
for line in source.lines() {
let trimmed = line.trim();
let load = trimmed
.strip_prefix("\\LoadClassWithOptions")
.map(|rest| (rest, inherited_options.to_vec()))
.or_else(|| {
trimmed
.strip_prefix("\\LoadClass")
.map(|rest| (rest, Vec::new()))
});
if let Some((mut rest, mut options)) = load {
rest = rest.trim_start();
if rest.starts_with('[') {
if let Some(close) = rest.find(']') {
options = rest[1..close]
.split(',')
.map(str::trim)
.filter(|option| !option.is_empty())
.map(str::to_string)
.collect();
rest = rest[close + 1..].trim_start();
}
}
if let Some((name, _)) = balanced_group_at(rest, 0) {
if let Some(text) =
load_project_class(name.trim(), &options, store, id, loaded, depth + 1)
{
output.push_str(&text);
output.push('\n');
}
continue;
}
}
output.push_str(line);
output.push('\n');
}
output
}
fn load_project_class(
name: &str,
options: &[String],
store: &projects::ProjectStore,
id: &str,
loaded: &mut Vec<String>,
depth: usize,
) -> Option<String> {
if depth > 8 || loaded.iter().any(|loaded| loaded == name) {
return None;
}
load_project_file(name, "cls", options, store, id, loaded, depth)
}
fn route_d_pdf_cache() -> &'static Mutex<Vec<((String, u64), Vec<u8>)>> {
static CACHE: OnceLock<Mutex<Vec<((String, u64), Vec<u8>)>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(Vec::new()))
}
fn route_d_cached_pdf(key: &(String, u64)) -> Option<Vec<u8>> {
let cache = route_d_pdf_cache().lock().expect("pdf cache");
cache
.iter()
.find(|(cached, _)| cached == key)
.map(|(_, pdf)| pdf.clone())
}
fn store_route_d_pdf(key: (String, u64), pdf: &[u8]) {
const MAX_PDFS: usize = 8;
let mut cache = route_d_pdf_cache().lock().expect("pdf cache");
if let Some(position) = cache.iter().position(|(cached, _)| *cached == key) {
cache.remove(position);
}
cache.push((key, pdf.to_vec()));
while cache.len() > MAX_PDFS {
cache.remove(0);
}
}
fn route_d_flat_cache_key(source: &str) -> u64 {
let mut hasher = DefaultHasher::new();
source.hash(&mut hasher);
hasher.finish()
}
fn route_d_flat_preview_cache() -> &'static Mutex<Vec<(u64, String)>> {
static CACHE: OnceLock<Mutex<Vec<(u64, String)>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(Vec::new()))
}
fn route_d_cached_flat_preview(key: u64) -> Option<String> {
let cache = route_d_flat_preview_cache().lock().expect("preview cache");
cache
.iter()
.find(|(cached, _)| *cached == key)
.map(|(_, json)| json.clone())
}
fn store_route_d_flat_preview(key: u64, json: &str) {
const MAX_PREVIEWS: usize = 32;
let mut cache = route_d_flat_preview_cache().lock().expect("preview cache");
if let Some(position) = cache.iter().position(|(cached, _)| *cached == key) {
cache.remove(position);
}
cache.push((key, json.to_string()));
while cache.len() > MAX_PREVIEWS {
cache.remove(0);
}
}
fn route_d_flat_pdf_cache() -> &'static Mutex<Vec<(u64, Vec<u8>)>> {
static CACHE: OnceLock<Mutex<Vec<(u64, Vec<u8>)>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(Vec::new()))
}
fn route_d_cached_flat_pdf(key: u64) -> Option<Vec<u8>> {
let cache = route_d_flat_pdf_cache().lock().expect("pdf cache");
cache
.iter()
.find(|(cached, _)| *cached == key)
.map(|(_, pdf)| pdf.clone())
}
fn store_route_d_flat_pdf(key: u64, pdf: &[u8]) {
const MAX_PDFS: usize = 8;
let mut cache = route_d_flat_pdf_cache().lock().expect("pdf cache");
if let Some(position) = cache.iter().position(|(cached, _)| *cached == key) {
cache.remove(position);
}
cache.push((key, pdf.to_vec()));
while cache.len() > MAX_PDFS {
cache.remove(0);
}
}
fn respond_json_with_cache(request: Request, json: &str, cache_state: &str) -> Result<(), String> {
let content_type = Header::from_bytes("Content-Type", "application/json; charset=utf-8")
.map_err(|_| "invalid JSON response header".to_string())?;
let cache = Header::from_bytes("X-Texrra-Cache", cache_state)
.map_err(|_| "invalid cache response header".to_string())?;
request
.respond(
Response::from_string(json)
.with_header(content_type)
.with_header(cache),
)
.map_err(|error| format!("could not send JSON response: {error}"))
}
fn route_d_cache_key(
id: &str,
source: &str,
images: &HashMap<String, route_d::RasterImage>,
) -> (String, u64) {
let mut hasher = DefaultHasher::new();
source.hash(&mut hasher);
let mut names: Vec<&String> = images.keys().collect();
names.sort();
for name in names {
name.hash(&mut hasher);
let image = &images[name];
image.width.hash(&mut hasher);
image.height.hash(&mut hasher);
image.rgb.hash(&mut hasher);
}
(id.to_string(), hasher.finish())
}
fn route_d_cache() -> &'static Mutex<Vec<((String, u64), String)>> {
static CACHE: OnceLock<Mutex<Vec<((String, u64), String)>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(Vec::new()))
}
fn route_d_cached_preview(key: &(String, u64)) -> Option<String> {
let cache = route_d_cache().lock().ok()?;
cache
.iter()
.find(|(cached, _)| cached == key)
.map(|(_, json)| json.clone())
}
fn replace_number_field(json: &str, field: &str, value: u64) -> String {
let Some(start) = json.find(field) else {
return json.to_string();
};
let Some(colon) = json[start..].find(':') else {
return json.to_string();
};
let value_start = start + colon + 1;
let rest = &json[value_start..];
let Some(end) = rest.find([',', '}']) else {
return json.to_string();
};
format!("{}{value}{}", &json[..value_start], &rest[end..])
}
fn replace_array_field(json: &str, field: &str) -> String {
let Some(start) = json.find(field) else {
return json.to_string();
};
let Some(open_rel) = json[start..].find('[') else {
return json.to_string();
};
let open = start + open_rel;
let Some(close_rel) = json[open..].find(']') else {
return json.to_string();
};
let close = open + close_rel;
format!("{}[]{}", &json[..open], &json[close + 1..])
}
fn preview_without_changes(json: &str) -> String {
let json = replace_number_field(json, "\"recomputedPages\"", 0);
replace_array_field(&json, "\"changedPages\"")
}
fn store_route_d_preview(key: (String, u64), json: String) {
if let Ok(mut cache) = route_d_cache().lock() {
cache.push((key, json));
if cache.len() > 32 {
cache.remove(0);
}
}
}
fn expand_project_source(source: &str, store: &projects::ProjectStore, id: &str) -> String {
let expanded = expand_project_inputs(source, store, id);
let expanded = expand_project_packages(&expanded, store, id);
expand_project_inputs(&expanded, store, id)
}
/// Decode every `\includegraphics` file a project source references.
fn load_project_images(
source: &str,
store: &projects::ProjectStore,
id: &str,
) -> HashMap<String, route_d::RasterImage> {
let mut images = HashMap::new();
let mut prefixes = vec![String::new()];
prefixes.extend(route_d::graphics_paths(source));
for path in route_d::image_paths(source) {
let bytes = prefixes.iter().find_map(|prefix| {
["", ".png", ".jpg", ".jpeg", ".bmp"]
.iter()
.find_map(|suffix| store.read_file(id, &format!("{prefix}{path}{suffix}")).ok())
});
let Some(bytes) = bytes else {
continue;
};
let Ok(decoded) = image::load_from_memory(&bytes) else {
continue;
};
let rgb = decoded.to_rgb8();
images.insert(
path,
route_d::RasterImage {
width: rgb.width(),
height: rgb.height(),
rgb: rgb.into_raw(),
},
);
}
images
}
fn expand_project_inputs(source: &str, store: &projects::ProjectStore, id: &str) -> String {
let read = |path: &str| {
let bytes = store
.read_file(id, path)
.ok()
.or_else(|| store.read_file(id, &format!("{path}.tex")).ok())?;
String::from_utf8(bytes).ok()
};
route_d::expand_inputs(source, read)
}
fn handle_project_request(
mut request: Request,
method: &Method,
rest: &str,
url: &str,
compiler: &mut rust_typeset::CompilerSession,
store: &projects::ProjectStore,
) -> Result<(), String> {
let segments = rest
.split('/')
.filter(|segment| !segment.is_empty())
.collect::<Vec<_>>();
match (method, segments.as_slice()) {
(&Method::Get, []) => match projects_json(store) {
Ok(json) => respond_json(request, 200, &json),
Err(error) => respond_api_error(request, 500, &error),
},
(&Method::Post, []) => {
let name = query_param(url, "name").unwrap_or_else(|| "project".to_string());
let bytes = match read_body_bytes(&mut request, MAX_ZIP_BYTES) {
Ok(bytes) => bytes,
Err(error) => return respond_api_error(request, 413, &error),
};
match store.create_from_zip(&name, &bytes) {
Ok(info) => respond_json(request, 201, &project_json(&info)),
Err(error) => respond_api_error(request, 400, &error),
}
}
(&Method::Post, ["new"]) => {
let name = query_param(url, "name").unwrap_or_else(|| "Untitled project".to_string());
match store.create_empty(&name) {
Ok(info) => respond_json(request, 201, &project_json(&info)),
Err(error) => respond_api_error(request, 500, &error),
}
}
(&Method::Get, [id]) => match store.info(id) {
Ok(info) => respond_json(request, 200, &project_json(&info)),
Err(error) => respond_api_error(request, 404, &error),
},
(&Method::Delete, [id]) => match store.delete(id) {
Ok(()) => respond_json(request, 200, "{\"deleted\":true}"),
Err(error) => respond_api_error(request, 404, &error),
},
(&Method::Get, [id, "zip"]) => match store.zip(id) {
Ok(bytes) => {
let name = format!("{id}.zip");
respond_file(request, "application/zip", bytes, Some(&name))
}
Err(error) => respond_api_error(request, 404, &error),
},
(&Method::Get, [id, "raw"]) => {
let Some(path) = query_param(url, "path") else {
return respond_api_error(request, 400, "missing file path");
};
match store.read_file(id, &path) {
Ok(bytes) => {
let download = query_param(url, "download").is_some();
let name = download.then(|| download_name(&path));
respond_file(request, file_content_type(&path), bytes, name.as_deref())
}
Err(error) => respond_api_error(request, 404, &error),
}
}
(&Method::Put, [id, "file"]) | (&Method::Post, [id, "files"]) => {
let Some(path) = query_param(url, "path") else {
return respond_api_error(request, 400, "missing file path");
};
let bytes = match read_body_bytes(&mut request, MAX_UPLOAD_BYTES) {
Ok(bytes) => bytes,
Err(error) => return respond_api_error(request, 413, &error),
};
match store.write_file(id, &path, &bytes) {
Ok(()) => respond_json(request, 200, "{\"saved\":true}"),
Err(error) => respond_api_error(request, 400, &error),
}
}
(&Method::Delete, [id, "file"]) => {
let Some(path) = query_param(url, "path") else {
return respond_api_error(request, 400, "missing file path");
};
match store.delete_file(id, &path) {
Ok(()) => respond_json(request, 200, "{\"deleted\":true}"),
Err(error) => respond_api_error(request, 404, &error),
}
}
(&Method::Post, [id, "preview"]) => {
let (source, file_name) = match store.main_source(id) {
Ok(source) => source,
Err(error) => return respond_api_error(request, 422, &error),
};
if uses_route_d(url) {
let expanded = expand_project_source(&source, &store, id);
let images = load_project_images(&expanded, &store, id);
let key = route_d_cache_key(id, &expanded, &images);
if let Some(json) = route_d_cached_preview(&key) {
return respond_json(request, 200, &preview_without_changes(&json));
}
match route_d::project_preview_json_with_images(id, &expanded, &images) {
Ok(json) => {
store_route_d_preview(key, json.clone());
return respond_json(request, 200, &json);
}
Err(_) => {}
}
}
match compiler.preview_json(&source, &file_name) {
Ok(json) => respond_json(request, 200, &json),
Err(error) => respond(
request,
422,
"application/json; charset=utf-8",
&rust_typeset::preview_error_json(&error),
),
}
}
(&Method::Post, [id, "pdf"]) => {
let (source, file_name) = match store.main_source(id) {
Ok(source) => source,
Err(error) => return respond_api_error(request, 422, &error),
};
if uses_route_d(url) {
let expanded = expand_project_source(&source, &store, id);
let images = load_project_images(&expanded, &store, id);
let key = route_d_cache_key(id, &expanded, &images);
if let Some(pdf) = route_d_cached_pdf(&key) {
return respond_pdf_with_cache(request, pdf, "hit");
}
match route_d::pdf_bytes_with_images(&expanded, &images) {
Ok(pdf) => {
store_route_d_pdf(key, &pdf);
return respond_pdf_with_cache(request, pdf, "miss");
}
Err(_) => {}
}
}
match compiler.compile(&source, &file_name) {
Ok(pdf) => respond_pdf(request, pdf),
Err(error) => respond(request, 422, "text/plain; charset=utf-8", &error),
}
}
_ => respond_api_error(request, 404, "not found"),
}
}
fn projects_json(store: &projects::ProjectStore) -> Result<String, String> {
let projects = store.list()?;
let mut output = String::from("{\"projects\":[");
for (index, info) in projects.iter().enumerate() {
if index > 0 {
output.push(',');
}
output.push_str(&project_json(info));
}
output.push_str("]}");
Ok(output)
}
fn project_json(info: &projects::ProjectInfo) -> String {
let mut files = String::new();
for (index, file) in info.files.iter().enumerate() {
if index > 0 {
files.push(',');
}
let _ = write!(
files,
"{{\"path\":{},\"size\":{}}}",
rust_typeset::json_string(&file.path),
file.size
);
}
format!(
"{{\"id\":{},\"name\":{},\"mainFile\":{},\"createdAt\":{},\"updatedAt\":{},\"files\":[{}]}}",
rust_typeset::json_string(&info.id),
rust_typeset::json_string(&info.name),
rust_typeset::json_string(&info.main_file),
info.created_at,
info.updated_at,
files
)
}
/// Chooses the renderer for a request. An explicit `engine` query parameter
/// wins, then `TEXRRA_ENGINE=v1` forces the old pipeline, and route-D is the
/// default (with a v1 fallback when route-D rejects the source).
fn uses_route_d(url: &str) -> bool {
match query_param(url, "engine").as_deref() {
Some("route-d") => true,
Some(_) => false,
None => std::env::var("TEXRRA_ENGINE")
.map(|engine| engine != "v1")
.unwrap_or(true),
}
}
fn query_param(url: &str, name: &str) -> Option<String> {
let (_, query) = url.split_once('?')?;
for pair in query.split('&') {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
if percent_decode(key) == name {
return Some(percent_decode(value));
}
}
None
}
fn percent_decode(value: &str) -> String {
let bytes = value.as_bytes();
let mut output = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'%' if index + 2 < bytes.len() => {
let high = hex_digit(bytes[index + 1]);
let low = hex_digit(bytes[index + 2]);
match (high, low) {
(Some(high), Some(low)) => {
output.push(high * 16 + low);
index += 3;
}
_ => {
output.push(b'%');
index += 1;
}
}
}
b'+' => {
output.push(b' ');
index += 1;
}
byte => {
output.push(byte);
index += 1;
}
}
}
String::from_utf8_lossy(&output).to_string()
}
fn hex_digit(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn respond_json(request: Request, status: u16, body: &str) -> Result<(), String> {
respond(request, status, "application/json; charset=utf-8", body)
}
fn respond_api_error(request: Request, status: u16, message: &str) -> Result<(), String> {
respond(
request,
status,
"application/json; charset=utf-8",
&format!("{{\"error\":{}}}", rust_typeset::json_string(message)),
)
}
fn respond_file(
request: Request,
content_type: &str,
body: Vec<u8>,
download_name: Option<&str>,
) -> Result<(), String> {
let content_type_header = Header::from_bytes("Content-Type", content_type)
.map_err(|_| "invalid response header".to_string())?;
let mut response = Response::from_data(body)
.with_status_code(StatusCode(200))
.with_header(content_type_header);
if let Some(name) = download_name {
let disposition = format!("attachment; filename=\"{}\"", ascii_file_name(name));
let header = Header::from_bytes("Content-Disposition", disposition)
.map_err(|_| "invalid response header".to_string())?;
response = response.with_header(header);
}
request
.respond(response)
.map_err(|error| format!("could not send response: {error}"))
}
fn file_content_type(path: &str) -> &'static str {
let extension = path
.rsplit_once('.')
.map(|(_, extension)| extension.to_ascii_lowercase())
.unwrap_or_default();
match extension.as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"bmp" => "image/bmp",
"webp" => "image/webp",
"pdf" => "application/pdf",
"zip" => "application/zip",
"ttf" => "font/ttf",
"otf" => "font/otf",
_ => "text/plain; charset=utf-8",
}
}
fn download_name(path: &str) -> String {
path.rsplit('/').next().unwrap_or(path).to_string()
}
fn ascii_file_name(name: &str) -> String {
name.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_' | ' ') {
character
} else {
'_'
}
})
.collect()
}
#[cfg(test)]
mod class_option_tests {
use super::{apply_class_options, expand_document_hooks, strip_makeat};
#[test]
fn declared_options_run_only_when_requested() {
let source = "\\DeclareOption{boxed}{BOX}\n\\DeclareOption*{DEFAULT}\n\\ProcessOptions";
assert_eq!(
apply_class_options(source, &["boxed".to_string()]).trim(),
"BOX"
);
assert_eq!(apply_class_options(source, &[]).trim(), "");
assert_eq!(
apply_class_options(source, &["other".to_string()]).trim(),
"DEFAULT"
);
}
#[test]
fn at_begin_document_runs_its_body() {
let source = "\\AtBeginDocument{\\newcommand{\\greet}{QZ}} tail";
let expanded = expand_document_hooks(source);
assert!(expanded.contains("\\newcommand{\\greet}{QZ}"));
assert!(!expanded.contains("AtBeginDocument"));
}
#[test]
fn at_end_document_is_dropped() {
assert_eq!(
expand_document_hooks("\\AtEndDocument{DONE}").trim(),
"DONE"
);
}
#[test]
fn makeat_commands_are_removed() {
assert_eq!(
strip_makeat("\\makeatletter\\def\\x{A}\\makeatother"),
"\\def\\x{A}"
);
}
#[test]
fn execute_options_supply_defaults() {
let source = "\\DeclareOption{plain}{PLAIN}\n\\DeclareOption{boxed}{BOX}\n\\ExecuteOptions{plain}\n\\ProcessOptions";
assert_eq!(apply_class_options(source, &[]).trim(), "PLAIN");
assert_eq!(
apply_class_options(source, &["boxed".to_string()]).trim(),
"PLAIN\nBOX"
);
}
}