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] | texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf]".into(), ); }; if command == "native" { let mut native_job_target = false; let mut initex = false; let mut dump_format = false; let mut limits = texrra_tex_core::execution::Limits::default(); let mut load_format = None; let mut etex = false; let mut input_profile = texrra_tex_core::execution::InputProfile::TeX8Bit; let mut texmf_roots = Vec::new(); let mut resource_manifest = None; let mut layout_manifest = None; let mut failure_manifest = None; let mut project_snapshot = None; let mut generated_initial = None; let mut observe_generated_initial = false; let mut input_policy_explicit = false; let mut input_policy = texrra_tex_core::resources::InputPolicy::Project; let input = loop { match args.next().as_deref() { Some("--input-profile") => { input_profile = match args.next().as_deref() { Some("tex8bit") => texrra_tex_core::execution::InputProfile::TeX8Bit, Some("unicode") => texrra_tex_core::execution::InputProfile::UnicodeScalar, _ => return Err("--input-profile requires tex8bit or unicode".into()), }; } Some("--job") => native_job_target = true, Some("--initex") => initex = true, Some("--etex") => etex = true, Some("--dump-format") => dump_format = true, Some("--step-limit") => { limits.steps = args .next() .and_then(|value| value.parse::().ok()) .filter(|value| *value > 0) .ok_or("--step-limit requires a positive integer")?; } Some("--load-format") => { load_format = Some(PathBuf::from( args.next().ok_or("--load-format requires a filename")?, )) } Some("--texmf-root") => texmf_roots.push(PathBuf::from( args.next().ok_or("--texmf-root requires a directory")?, )), Some("--layout-manifest") => { layout_manifest = Some(PathBuf::from( args.next().ok_or("--layout-manifest requires a filename")?, )); } Some("--resource-manifest") => { resource_manifest = Some(PathBuf::from( args.next() .ok_or("--resource-manifest requires a filename")?, )) } Some("--failure-manifest") => { failure_manifest = Some(PathBuf::from( args.next() .ok_or("--failure-manifest requires a filename")?, )); } Some("--project-snapshot") => { project_snapshot = Some(PathBuf::from( args.next() .ok_or("--project-snapshot requires a filename")?, )); } Some("--generated-initial") => { generated_initial = Some(PathBuf::from( args.next() .ok_or("--generated-initial requires a filename")?, )); } Some("--observe-generated-initial") => observe_generated_initial = true, Some("--input-policy") => { input_policy_explicit = true; input_policy = match args.next().as_deref() { Some("tex") => texrra_tex_core::resources::InputPolicy::Tex, Some("project") => texrra_tex_core::resources::InputPolicy::Project, _ => return Err("--input-policy requires tex or project".into()), } } Some(value) if value.starts_with('-') => { return Err(format!("unknown native option: {value}")); } Some(value) => break PathBuf::from(value), None => return Err("native requires input.tex".into()), } }; if generated_initial.is_some() && observe_generated_initial { return Err("select --generated-initial or --observe-generated-initial".into()); } if project_snapshot.is_some() && (!texmf_roots.is_empty() || input_policy_explicit) { return Err("--project-snapshot defines its resource paths and input policy; do not combine it with --texmf-root or --input-policy".into()); } if dump_format && (!initex || load_format.is_some()) || initex && load_format.is_some() { return Err( "format dump requires INITEX, and format load requires a new document job".into(), ); } if dump_format || load_format.is_some() { native_job_target = true; } if layout_manifest.is_some() && (!native_job_target || dump_format) { return Err("--layout-manifest requires a native document job".into()); } let output = args .next() .map(PathBuf::from) .unwrap_or_else(|| input.with_extension(if dump_format { "tfx" } else { "pdf" })); if args.next().is_some() { return Err("usage: texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf]".into()); } let diagnostic = native_pdf( &input, &output, initex, etex, &texmf_roots, resource_manifest.as_deref(), layout_manifest.as_deref(), failure_manifest.as_deref(), project_snapshot.as_deref(), generated_initial.as_deref(), observe_generated_initial, input_policy, input_profile, native_job_target, dump_format, load_format.as_deref(), limits, )?; if diagnostic { process::exit(1); } return Ok(()); } if command != "serve" { return Err("expected serve or native".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::().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 next to this checkout, or 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(()) } /// Strict native bootstrap entry: typed execution -> Route-D lists -> PDF. /// CLI adapter; the library owns compilation, export and publication. fn native_pdf( input: &Path, output: &Path, initex: bool, etex: bool, texmf_roots: &[PathBuf], manifest: Option<&Path>, layout_manifest: Option<&Path>, failure_manifest: Option<&Path>, project_snapshot: Option<&Path>, generated_initial: Option<&Path>, observe_generated_initial: bool, input_policy: texrra_tex_core::resources::InputPolicy, input_profile: texrra_tex_core::execution::InputProfile, native_job_target: bool, dump_format: bool, load_format: Option<&Path>, limits: texrra_tex_core::execution::Limits, ) -> Result { use texrra_engine::native::{self, CompileRequest, Entry, NativeCompiler, Target}; let project = project_snapshot .map(|path| -> Result<_, String> { let bytes = fs::read(path).map_err(|e| format!("project snapshot {}: {e}", path.display()))?; let project: native::ProjectSnapshot = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; project.validate()?; Ok(std::sync::Arc::new(project)) }) .transpose()?; let world = if let Some(project) = &project { project.configuration() } else { let mut world = texrra_tex_core::resources::WorldConfig::from_environment( env::current_dir().map_err(|e| e.to_string())?, texmf_roots.to_vec(), )?; world.input_policy = input_policy; world }; let mut request = CompileRequest::new(world, input, output, native::job_time()?); if let Some(project) = project { request = request.with_project(project); } if let Some(path) = generated_initial { let bytes = fs::read(path) .map_err(|e| format!("generated initial state {}: {e}", path.display()))?; let state: native::GeneratedInitialState = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; state.validate()?; request = request.with_generated_initial(state); } else if observe_generated_initial { request = request.observe_generated_initial(); } request.entry = if let Some(path) = load_format { Entry::Format(path.into()) } else if initex { Entry::Initex } else { Entry::Bootstrap }; request.target = if native_job_target { Target::Shipouts } else { Target::Paragraphs }; request.etex = etex; request.input_profile = input_profile; request.limits = limits; request.resource_manifest = manifest.map(Path::to_owned); request.layout_manifest = layout_manifest.map(Path::to_owned); request.failure_manifest = failure_manifest.map(Path::to_owned); request.terminal = true; let failure_message = |failure: native::CompileFailure| { for gap in &failure.evidence_gaps { eprintln!("native failure evidence: {gap}"); } failure.to_string() }; if dump_format { native::dump_format_detailed(request, texrra_tex_core::execution::Cancellation::default()) .map_err(failure_message)?; return Ok(false); } let result = NativeCompiler::default() .compile_detailed(request) .map_err(failure_message)?; if result.output.is_none() { println!("native Route-D execution complete (no pages)"); } else { println!( "wrote {} ({} pages, native Route-D)", output.display(), result.pages.len() ); } Ok(result.has_show_diagnostic()) } 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, "v1"), 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::(); 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", "route-d"); } match route_d::pdf_bytes(&source) { Ok(pdf) => { store_route_d_flat_pdf(key, &pdf); respond_pdf_with_cache(request, pdf, "miss", "route-d") } 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, 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"), Path::new("../texrra-web"), Path::new("texrra-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", "texrra\

texrra web frontend not found

\

Clone texrra-web next to this checkout, or set\ TEXRRA_WEB_DIR to its directory, then reload.

", ); }; 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 { 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, 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, 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, cache_state: &str, engine: &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())?; let engine = Header::from_bytes("X-Preview-Engine", engine) .map_err(|_| "invalid engine response header".to_string())?; request .respond( Response::from_data(pdf) .with_header(content_type) .with_header(disposition) .with_header(cache) .with_header(engine), ) .map_err(|error| format!("could not send PDF response: {error}")) } fn respond_pdf(request: Request, pdf: Vec, engine: &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 engine = Header::from_bytes("X-Preview-Engine", engine) .map_err(|_| "invalid engine response header".to_string())?; request .respond( Response::from_data(pdf) .with_header(content_type) .with_header(disposition) .with_header(engine), ) .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)> = Vec::new(); let mut passed_classes: Vec<(String, Vec)> = 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, depth: usize, ) -> Option { 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 { 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, 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 { 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, Vec)> { 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)>, 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)>, name: &str) -> Vec { 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) { 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)> { 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::>() .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)> = Vec::new(); let mut active: Vec = 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, 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, depth: usize, ) -> Option { 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)>> { static CACHE: OnceLock)>>> = OnceLock::new(); CACHE.get_or_init(|| Mutex::new(Vec::new())) } fn route_d_cached_pdf(key: &(String, u64)) -> Option> { 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> { static CACHE: OnceLock>> = OnceLock::new(); CACHE.get_or_init(|| Mutex::new(Vec::new())) } fn route_d_cached_flat_preview(key: u64) -> Option { 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)>> { static CACHE: OnceLock)>>> = OnceLock::new(); CACHE.get_or_init(|| Mutex::new(Vec::new())) } fn route_d_cached_flat_pdf(key: u64) -> Option> { 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, 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> { static CACHE: OnceLock>> = OnceLock::new(); CACHE.get_or_init(|| Mutex::new(Vec::new())) } fn route_d_cached_preview(key: &(String, u64)) -> Option { 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\"") } /// Keep only the pages listed in `changedPages`; the web client already has /// the other page SVGs from the previous revision. fn patch_preview_json(json: &str) -> Option { let mut value: serde_json::Value = serde_json::from_str(json).ok()?; let changed: Vec = value .get("changedPages")? .as_array()? .iter() .filter_map(|index| index.as_u64().map(|index| index as usize)) .collect(); let pages = value.get("pages")?.as_array()?.clone(); let patches: Vec = pages .into_iter() .filter(|page| { page.get("index") .and_then(|index| index.as_u64()) .is_some_and(|index| changed.contains(&(index as usize))) }) .collect(); value["pages"] = serde_json::Value::Array(patches); Some(value.to_string()) } 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); let expanded = expand_project_inputs(&expanded, store, id); expand_project_bibliography(&expanded, store, id) } /// Inline a project's BibTeX files as a `thebibliography` block so the /// route-D citation pass can resolve `\cite` without a BibTeX run. fn expand_project_bibliography(source: &str, store: &projects::ProjectStore, id: &str) -> String { let mut output = String::new(); let mut rest = source; while let Some(index) = rest.find("\\bibliography{") { let line_start = rest[..index].rfind('\n').map_or(0, |position| position + 1); let commented = rest[line_start..index].contains('%'); output.push_str(&rest[..index]); if commented { output.push_str("\\bibliography{"); rest = &rest[index + "\\bibliography{".len()..]; continue; } let after = &rest[index + "\\bibliography{".len()..]; let Some(end) = after.find('}') else { output.push_str(&rest[index..]); return output; }; let names = &after[..end]; let mut entries = Vec::new(); for name in names.split(',') { let name = name.trim(); if name.is_empty() { continue; } let path = if name.ends_with(".bib") { name.to_string() } else { format!("{name}.bib") }; let Ok(bytes) = store.read_file(id, &path) else { continue; }; let Ok(text) = String::from_utf8(bytes) else { continue; }; entries.extend(parse_bib_entries(&text)); } if entries.is_empty() { output.push_str("\\bibliography{"); output.push_str(names); output.push('}'); } else { // unsrtnat orders the bibliography by first citation, not by the // order entries happen to appear in the .bib file. let citations = citation_key_order(source); entries.sort_by_key(|(key, _, _)| { citations .iter() .position(|citation| citation == key) .unwrap_or(usize::MAX) }); let labels = disambiguate_bib_labels(&entries); output.push_str("\\begin{thebibliography}{99}\n"); for ((key, entry, _), label) in entries.iter().zip(labels) { output.push_str("\\bibitem["); output.push_str(&label); output.push_str("]{"); output.push_str(key); output.push_str("} "); output.push_str(&bib_entry_with_year_suffix(entry, &label)); output.push('\n'); } output.push_str("\\end{thebibliography}\n"); } rest = &after[end + 1..]; } output.push_str(rest); output } /// Collect citation keys in first-appearance order, including multi-key /// `\citep{a,b}` groups. fn citation_key_order(source: &str) -> Vec { let mut keys = Vec::new(); let mut rest = source; while let Some(index) = rest.find("\\cite") { let after = &rest[index + "\\cite".len()..]; let mut after = after; if let Some(close) = after.find(']') { let prefix = &after[..close]; if prefix.starts_with('[') { after = &after[close + 1..]; } } let Some(open) = after.find('{') else { rest = after; continue; }; let after_open = &after[open + 1..]; let Some(close) = after_open.find('}') else { break; }; for key in after_open[..close].split(',') { let key = key.trim(); if !key.is_empty() && !keys.iter().any(|known| known == key) { keys.push(key.to_string()); } } rest = &after_open[close + 1..]; } keys } /// `unsrtnat` prints 2014a/2014b in the reference list; carry the citation /// label's disambiguation suffix into the entry text. fn bib_entry_with_year_suffix(entry: &str, label: &str) -> String { let year = label .rsplit(", ") .next() .unwrap_or("") .trim_end_matches(')') .trim(); let Some(suffix) = year .chars() .last() .filter(|character| character.is_ascii_alphabetic()) else { return entry.to_string(); }; let base = &year[..year.len() - suffix.len_utf8()]; let needle = format!(", {base}."); let replacement = format!(", {year}."); entry.replacen(&needle, &replacement, 1) } /// Parse the small BibTeX subset used by paper templates: entries with /// braced or quoted field values. Unknown entry types are skipped. fn parse_bib_entries(text: &str) -> Vec<(String, String, String)> { let mut entries = Vec::new(); let mut cursor = 0usize; while let Some(relative) = text[cursor..].find('@') { let at = cursor + relative; let after_at = &text[at + 1..]; let Some(open) = after_at.find(['{', '(']) else { break; }; let kind = after_at[..open].trim().to_ascii_lowercase(); let open_character = after_at[open..].chars().next().unwrap_or('{'); let close_character = if open_character == '(' { ')' } else { '}' }; let body_start = at + 1 + open + 1; let mut depth = 0usize; let mut in_quote = false; let mut body_end = None; for (offset, character) in text[body_start..].char_indices() { if character == '"' { in_quote = !in_quote; continue; } if in_quote { continue; } if character == '{' { depth += 1; } else if character == '}' { if depth > 0 { depth -= 1; } else if close_character == '}' { body_end = Some(body_start + offset); break; } } else if character == close_character && depth == 0 { body_end = Some(body_start + offset); break; } } let Some(body_end) = body_end else { break; }; let body = &text[body_start..body_end]; cursor = body_end + 1; if kind == "comment" || kind == "preamble" || kind == "string" { continue; } let Some(comma) = body.find(',') else { continue; }; let key = body[..comma].trim(); if key.is_empty() { continue; } let fields = parse_bib_fields(&body[comma + 1..]); if let Some(entry) = format_bib_entry(&fields, &kind) { entries.push((key.to_string(), entry, bib_label(&fields))); } } entries } fn parse_bib_fields(text: &str) -> Vec<(String, String)> { let mut fields = Vec::new(); let mut rest = text; loop { rest = rest .trim_start_matches(|character: char| character.is_whitespace() || character == ','); if rest.is_empty() { break; } let name_end = rest .find(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) .unwrap_or(rest.len()); if name_end == 0 { break; } let name = rest[..name_end].to_ascii_lowercase(); rest = rest[name_end..].trim_start(); let Some(after_equals) = rest.strip_prefix('=') else { break; }; rest = after_equals.trim_start(); let value = if let Some(after_open) = rest.strip_prefix('{') { let mut depth = 1usize; let mut end = None; for (offset, character) in after_open.char_indices() { match character { '{' => depth += 1, '}' => { depth -= 1; if depth == 0 { end = Some(offset); break; } } _ => {} } } let Some(end) = end else { break; }; rest = &after_open[end + 1..]; &after_open[..end] } else if let Some(after_quote) = rest.strip_prefix('"') { let Some(end) = after_quote.find('"') else { break; }; rest = &after_quote[end + 1..]; &after_quote[..end] } else { let end = rest .find(|character: char| character == ',' || character.is_whitespace()) .unwrap_or(rest.len()); let value = &rest[..end]; rest = &rest[end..]; value }; let value = value .replace(['{', '}'], "") .replace('~', " ") .replace("--", "-") .split_whitespace() .collect::>() .join(" "); fields.push((name, value)); } fields } /// Author-year label for a BibTeX entry, e.g. `Kour and Saabne, 2014`. fn bib_label(fields: &[(String, String)]) -> String { let field = |name: &str| { fields .iter() .find(|(field, _)| field == name) .map(|(_, value)| value.as_str()) }; let authors: Vec<&str> = field("author") .unwrap_or("") .split(" and ") .map(|author| author.split(',').next().unwrap_or(author).trim()) .filter(|author| !author.is_empty()) .collect(); let names = match authors.as_slice() { [] => "Anon.".to_string(), [one] => (*one).to_string(), [one, two] => format!("{one} and {two}"), [one, ..] => format!("{one} et al."), }; match field("year") { Some(year) => format!("{names}, {year}"), None => names, } } /// Append a/b suffixes when two entries share the same author-year label. fn disambiguate_bib_labels(entries: &[(String, String, String)]) -> Vec { let mut totals: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); for (_, _, label) in entries { *totals.entry(label.as_str()).or_default() += 1; } let mut seen: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); entries .iter() .map(|(_, _, label)| { if totals.get(label.as_str()).copied().unwrap_or(0) <= 1 { return label.clone(); } let index = seen.entry(label.as_str()).or_default(); let suffix = char::from(b'a' + (*index).min(25) as u8); *index += 1; format!("{label}{suffix}") }) .collect() } fn format_bib_authors(raw: &str) -> String { let names: Vec = raw .split(" and ") .filter_map(|author| { let author = author.trim(); if author.is_empty() { return None; } Some(match author.split_once(',') { Some((last, first)) => format!("{} {}", first.trim(), last.trim()), None => author.to_string(), }) }) .collect(); match names.as_slice() { [] => String::new(), [one] => one.clone(), [one, two] => format!("{one} and {two}"), [first, middle @ .., last] => { let mut joined = first.clone(); for name in middle { joined.push_str(", "); joined.push_str(name); } joined.push_str(", and "); joined.push_str(last); joined } } } fn format_bib_entry(fields: &[(String, String)], kind: &str) -> Option { let field = |name: &str| { fields .iter() .find(|(field, _)| field == name) .map(|(_, value)| value.as_str()) }; let title = field("title")?; let authors = format_bib_authors(field("author").unwrap_or("")); let mut entry = String::new(); if !authors.is_empty() { entry.push_str(&authors); entry.push_str(". "); } entry.push_str(title.trim_end_matches('.')); entry.push('.'); if let Some(journal) = field("journal") { entry.push_str(" \\emph{"); entry.push_str(journal.trim_end_matches('.')); entry.push('}'); } else if let Some(booktitle) = field("booktitle") { entry.push_str(" In \\emph{"); entry.push_str(booktitle.trim_end_matches('.')); entry.push('}'); } if let Some(pages) = field("pages") { entry.push_str(", pages "); entry.push_str(pages); } if let Some(publisher) = field("publisher").or_else(|| field("organization")) { entry.push_str(". "); entry.push_str(publisher.trim_end_matches('.')); } if let Some(year) = field("year") { entry.push_str(", "); entry.push_str(year); } if let Some(doi) = field("doi") { entry.push_str(". doi:"); entry.push_str(doi); } entry.push('.'); let _ = kind; Some(entry) } /// Decode every `\includegraphics` file a project source references. fn load_project_images( source: &str, store: &projects::ProjectStore, id: &str, ) -> HashMap { 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::>(); 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 (mut source, file_name) = match store.main_source(id) { Ok(source) => source, Err(error) => return respond_api_error(request, 422, &error), }; if query_param(url, "buffer").is_some() { let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) { Ok(bytes) => bytes, Err(error) => return respond_api_error(request, 413, &error), }; source = match String::from_utf8(bytes) { Ok(source) => source, Err(_) => { return respond_api_error(request, 400, "preview buffer is not UTF-8"); } }; } 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) { let body = preview_without_changes(&json); let body = if query_param(url, "patch").is_some() { patch_preview_json(&body).unwrap_or(body) } else { body }; return respond_json_engine(request, 200, &body, "route-d"); } let patch = query_param(url, "patch").is_some(); let result = if patch { route_d::project_preview_patch_json_with_images(id, &expanded, &images) } else { route_d::project_preview_json_with_images(id, &expanded, &images) }; match result { Ok(json) => { store_route_d_preview(key, json.clone()); return respond_json_engine(request, 200, &json, "route-d"); } Err(_) => {} } } match compiler.preview_json(&source, &file_name) { 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, [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", "route-d"); } 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", "route-d"); } Err(_) => {} } } match compiler.compile(&source, &file_name) { Ok(pdf) => respond_pdf(request, pdf, "v1"), 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 { 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 { 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 { 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, 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" ); } } #[cfg(test)] mod bib_format_tests { use super::{citation_key_order, format_bib_authors, format_bib_entry}; fn fields(pairs: &[(&str, &str)]) -> Vec<(String, String)> { pairs .iter() .map(|(name, value)| ((*name).to_string(), (*value).to_string())) .collect() } #[test] fn bib_authors_and_conference_entry_follow_natbib() { assert_eq!( format_bib_authors("Kour, George and Saabne, Raid"), "George Kour and Raid Saabne" ); assert_eq!( format_bib_authors("Keshet, Renato and Maor, Alina and Kour, George"), "Renato Keshet, Alina Maor, and George Kour" ); let entry = format_bib_entry( &fields(&[ ("author", "Kour, George and Saabne, Raid"), ("title", "Real-time segmentation"), ("booktitle", "Frontiers in Handwriting Recognition"), ("pages", "417--422"), ("publisher", "IEEE"), ("year", "2014"), ]), "inproceedings", ) .expect("entry"); assert!(entry.starts_with("George Kour and Raid Saabne."), "{entry}"); assert!( entry.contains("In \\emph{Frontiers in Handwriting Recognition},"), "{entry}" ); assert!(entry.contains("pages 417--422. IEEE, 2014."), "{entry}"); assert!(!entry.contains("on.,"), "{entry}"); } #[test] fn citation_keys_follow_first_appearance() { let order = citation_key_order( "\\citep{kour2014real, keshet2016prediction} and \\citet{kour2014fast}", ); assert_eq!( order, ["kour2014real", "keshet2016prediction", "kour2014fast"] ); } }