Initial texrra engine

Rename the crate, binary, core crate, font families, env vars, and internal commands from texcraft/tex-engine to texrra. Serve the separately versioned texrra-web frontend from TEXRRA_WEB_DIR, ../web, or ./web instead of embedding index.html. Add starred section heading support and an arXiv template conformance fixture.
This commit is contained in:
gloamxun committed 2026-10-19 11:41:46 +08:00
commit bb1d9e0561
147 files changed
+66719

No files matched your search

+615
View File
@@ -0,0 +1,615 @@
use std::{
env,
fmt::Write as _,
fs,
path::{Path, PathBuf},
process,
};
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
mod projects;
mod 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, "/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),
);
}
};
match compiler.preview_json(&source, &input_path.display().to_string()) {
Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json),
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_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(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 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),
};
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),
};
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
)
}
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()
}
+764
View File
@@ -0,0 +1,764 @@
use std::{
fs,
io::{Read, Write},
path::{Component, Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
use flate2::{Compression, Crc, read::DeflateDecoder, write::DeflateEncoder};
const MAX_PROJECT_FILES: usize = 2000;
const MAX_PROJECT_BYTES: u64 = 64 * 1024 * 1024;
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
const ZIP64_MESSAGE: &str =
"ZIP64 archives are not supported; re-create the archive without ZIP64 extensions";
pub(super) struct ProjectFile {
pub(super) path: String,
pub(super) size: u64,
}
pub(super) struct ProjectInfo {
pub(super) id: String,
pub(super) name: String,
pub(super) main_file: String,
pub(super) created_at: u64,
pub(super) updated_at: u64,
pub(super) files: Vec<ProjectFile>,
}
struct Meta {
name: String,
main_file: String,
created_at: u64,
updated_at: u64,
}
pub(super) struct ProjectStore {
root: PathBuf,
meta: PathBuf,
}
impl ProjectStore {
pub(super) fn new(root: PathBuf) -> Result<Self, String> {
let meta = root.join(".meta");
fs::create_dir_all(&meta)
.map_err(|error| format!("could not create {}: {error}", meta.display()))?;
Ok(Self { root, meta })
}
pub(super) fn is_empty(&self) -> bool {
self.ids().map(|ids| ids.is_empty()).unwrap_or(true)
}
pub(super) fn list(&self) -> Result<Vec<ProjectInfo>, String> {
let mut projects = Vec::new();
for id in self.ids()? {
if let Ok(info) = self.info(&id) {
projects.push(info);
}
}
projects.sort_by(|left, right| right.updated_at.cmp(&left.updated_at));
Ok(projects)
}
pub(super) fn info(&self, id: &str) -> Result<ProjectInfo, String> {
let dir = self.project_dir(id)?;
if !dir.is_dir() {
return Err(format!("project `{id}` does not exist"));
}
let files = collect_files(&dir)?;
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
name: id.to_string(),
main_file: String::new(),
created_at: now_secs(),
updated_at: now_secs(),
});
meta.main_file = self.resolve_main(id, &dir, &files, &meta.main_file);
Ok(ProjectInfo {
id: id.to_string(),
name: meta.name,
main_file: meta.main_file,
created_at: meta.created_at,
updated_at: meta.updated_at,
files,
})
}
pub(super) fn create_empty(&self, name: &str) -> Result<ProjectInfo, String> {
let name = clean_name(name);
let id = self.unique_id(&slug(&name));
let dir = self.root.join(&id);
fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?;
let source =
"\\documentclass{article}\n\\begin{document}\nHello, world.\n\\end{document}\n";
fs::write(dir.join("main.tex"), source)
.map_err(|error| format!("could not write main.tex: {error}"))?;
self.save_meta(
&id,
&Meta {
name,
main_file: "main.tex".to_string(),
created_at: now_secs(),
updated_at: now_secs(),
},
)?;
self.info(&id)
}
pub(super) fn create_from_zip(&self, name: &str, bytes: &[u8]) -> Result<ProjectInfo, String> {
let name = clean_name(name);
let entries = read_zip(bytes)?;
if entries.is_empty() {
return Err("the archive does not contain any files".to_string());
}
let total: u64 = entries.iter().map(|(_, data)| data.len() as u64).sum();
if total > MAX_PROJECT_BYTES {
return Err(format!(
"the archive expands to {total} bytes, over the {} byte limit",
MAX_PROJECT_BYTES
));
}
if entries.len() > MAX_PROJECT_FILES {
return Err(format!(
"the archive contains {} files, over the {} file limit",
entries.len(),
MAX_PROJECT_FILES
));
}
let id = self.unique_id(&slug(&name));
let dir = self.root.join(&id);
fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?;
let mut names = Vec::new();
for (entry, data) in &entries {
let Some(path) = entry_path(entry) else {
continue;
};
let target = dir.join(&path);
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::write(&target, data)
.map_err(|error| format!("could not write {}: {error}", target.display()))?;
names.push(entry.clone());
}
if names.is_empty() {
let _ = fs::remove_dir_all(&dir);
return Err("the archive does not contain any usable files".to_string());
}
let main_file = detect_main(&dir, &names).unwrap_or_else(|| {
names
.iter()
.find(|name| name.ends_with(".tex"))
.cloned()
.unwrap_or_else(|| "main.tex".to_string())
});
self.save_meta(
&id,
&Meta {
name,
main_file,
created_at: now_secs(),
updated_at: now_secs(),
},
)?;
self.info(&id)
}
pub(super) fn delete(&self, id: &str) -> Result<(), String> {
let dir = self.project_dir(id)?;
if !dir.is_dir() {
return Err(format!("project `{id}` does not exist"));
}
fs::remove_dir_all(&dir)
.map_err(|error| format!("could not delete project `{id}`: {error}"))?;
let _ = fs::remove_file(self.meta.join(format!("{id}.meta")));
Ok(())
}
pub(super) fn zip(&self, id: &str) -> Result<Vec<u8>, String> {
let dir = self.project_dir(id)?;
if !dir.is_dir() {
return Err(format!("project `{id}` does not exist"));
}
let info = self.info(id)?;
let mut entries = Vec::new();
for file in &info.files {
let path = dir.join(Path::new(&file.path));
if let Ok(data) = fs::read(&path) {
entries.push((file.path.clone(), data));
}
}
Ok(write_zip(&entries))
}
pub(super) fn read_file(&self, id: &str, relative: &str) -> Result<Vec<u8>, String> {
let path = self.file_path(id, relative)?;
fs::read(&path).map_err(|error| format!("could not read {relative}: {error}"))
}
pub(super) fn write_file(&self, id: &str, relative: &str, bytes: &[u8]) -> Result<(), String> {
if bytes.len() as u64 > MAX_FILE_BYTES {
return Err(format!(
"file is too large ({} bytes, limit {MAX_FILE_BYTES})",
bytes.len()
));
}
let path = self.file_path(id, relative)?;
let info = self.info(id)?;
if !info.files.iter().any(|file| file.path == relative)
&& info.files.len() >= MAX_PROJECT_FILES
{
return Err(format!(
"project already contains {} files, over the {MAX_PROJECT_FILES} file limit",
info.files.len()
));
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("could not create {}: {error}", parent.display()))?;
}
fs::write(&path, bytes).map_err(|error| format!("could not write {relative}: {error}"))?;
self.touch(id)?;
Ok(())
}
pub(super) fn delete_file(&self, id: &str, relative: &str) -> Result<(), String> {
let path = self.file_path(id, relative)?;
if path.is_dir() {
return Err("path is a directory".to_string());
}
fs::remove_file(&path).map_err(|error| format!("could not delete {relative}: {error}"))?;
let root = self.project_dir(id)?;
let mut parent = path.parent().map(Path::to_path_buf);
while let Some(directory) = parent {
if directory == root || !directory.starts_with(&root) {
break;
}
if fs::remove_dir(&directory).is_err() {
break;
}
parent = directory.parent().map(Path::to_path_buf);
}
self.touch(id)?;
Ok(())
}
pub(super) fn main_source(&self, id: &str) -> Result<(String, String), String> {
let info = self.info(id)?;
if info.main_file.is_empty() {
return Err("project does not contain a TeX file".to_string());
}
let path = self.file_path(id, &info.main_file)?;
let source = fs::read_to_string(&path)
.map_err(|error| format!("could not read {}: {error}", info.main_file))?;
Ok((source, path.display().to_string()))
}
pub(super) fn seed_from_input(&self, input_path: &Path) -> Result<(), String> {
if !self.is_empty() {
return Ok(());
}
let Some(parent) = input_path.parent() else {
return Ok(());
};
let Some(file_name) = input_path.file_name().and_then(|name| name.to_str()) else {
return Ok(());
};
let stem = input_path
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or("project");
let id = self.unique_id(&slug(stem));
let dir = self.root.join(&id);
fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?;
let entries = match fs::read_dir(parent) {
Ok(entries) => entries,
Err(_) => return Ok(()),
};
let mut copied = 0;
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
continue;
};
if name.starts_with('.') {
continue;
}
let Ok(metadata) = entry.metadata() else {
continue;
};
if metadata.len() > MAX_FILE_BYTES {
continue;
}
if fs::copy(&path, dir.join(name)).is_ok() {
copied += 1;
}
}
if copied == 0 {
let _ = fs::remove_dir_all(&dir);
return Ok(());
}
self.save_meta(
&id,
&Meta {
name: stem.to_string(),
main_file: file_name.to_string(),
created_at: now_secs(),
updated_at: now_secs(),
},
)?;
Ok(())
}
pub(super) fn project_dir(&self, id: &str) -> Result<PathBuf, String> {
if !valid_id(id) {
return Err("invalid project id".to_string());
}
Ok(self.root.join(id))
}
pub(super) fn file_path(&self, id: &str, relative: &str) -> Result<PathBuf, String> {
let dir = self.project_dir(id)?;
let relative = relative.trim_start_matches('/');
if relative.is_empty() {
return Err("missing file path".to_string());
}
if relative.contains('\\') {
return Err("invalid file path".to_string());
}
let mut path = dir.clone();
for component in Path::new(relative).components() {
match component {
Component::Normal(name) => path.push(name),
_ => return Err("invalid file path".to_string()),
}
}
if !path.starts_with(&dir) {
return Err("invalid file path".to_string());
}
Ok(path)
}
fn ids(&self) -> Result<Vec<String>, String> {
let entries = match fs::read_dir(&self.root) {
Ok(entries) => entries,
Err(error) => return Err(format!("could not read projects: {error}")),
};
let mut ids = Vec::new();
for entry in entries.flatten() {
if !entry.path().is_dir() {
continue;
}
let Some(name) = entry.file_name().to_str().map(str::to_string) else {
continue;
};
if name.starts_with('.') || !valid_id(&name) {
continue;
}
ids.push(name);
}
ids.sort();
Ok(ids)
}
fn unique_id(&self, base: &str) -> String {
let mut candidate = base.to_string();
let mut index = 2;
while self.root.join(&candidate).exists() {
candidate = format!("{base}-{index}");
index += 1;
}
candidate
}
fn resolve_main(&self, id: &str, dir: &Path, files: &[ProjectFile], preferred: &str) -> String {
if !preferred.is_empty()
&& valid_relative(preferred)
&& files.iter().any(|file| file.path == preferred)
{
return preferred.to_string();
}
let _ = id;
let names = files
.iter()
.map(|file| file.path.clone())
.collect::<Vec<_>>();
detect_main(dir, &names)
.or_else(|| names.iter().find(|name| name.ends_with(".tex")).cloned())
.unwrap_or_default()
}
fn meta_path(&self, id: &str) -> PathBuf {
self.meta.join(format!("{id}.meta"))
}
fn load_meta(&self, id: &str) -> Option<Meta> {
let text = fs::read_to_string(self.meta_path(id)).ok()?;
let mut name = String::new();
let mut main_file = String::new();
let mut created_at = 0;
let mut updated_at = 0;
for line in text.lines() {
let Some((key, value)) = line.split_once('=') else {
continue;
};
match key {
"name" => name = value.to_string(),
"main" => main_file = value.to_string(),
"created" => created_at = value.parse().unwrap_or(0),
"updated" => updated_at = value.parse().unwrap_or(0),
_ => {}
}
}
Some(Meta {
name: if name.is_empty() {
id.to_string()
} else {
name
},
main_file,
created_at,
updated_at,
})
}
fn save_meta(&self, id: &str, meta: &Meta) -> Result<(), String> {
let text = format!(
"name={}\nmain={}\ncreated={}\nupdated={}\n",
meta.name.replace(['\n', '\r'], " "),
meta.main_file,
meta.created_at,
meta.updated_at
);
fs::write(self.meta_path(id), text)
.map_err(|error| format!("could not save project metadata: {error}"))
}
fn touch(&self, id: &str) -> Result<(), String> {
let mut meta = self.load_meta(id).unwrap_or_else(|| Meta {
name: id.to_string(),
main_file: String::new(),
created_at: now_secs(),
updated_at: now_secs(),
});
meta.updated_at = now_secs();
if meta.main_file.is_empty() {
let info = self.info(id)?;
meta.main_file = info.main_file;
}
self.save_meta(id, &meta)
}
}
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs())
.unwrap_or(0)
}
fn clean_name(input: &str) -> String {
let cleaned: String = input
.trim()
.chars()
.filter(|character| !character.is_control())
.take(80)
.collect();
if cleaned.is_empty() {
"Untitled project".to_string()
} else {
cleaned
}
}
fn slug(name: &str) -> String {
let mut output = String::new();
for character in name.chars() {
if character.is_ascii_alphanumeric() {
output.push(character.to_ascii_lowercase());
} else if character == '-' || character == '_' {
output.push(character);
} else if !output.ends_with('-') {
output.push('-');
}
}
let trimmed = output.trim_matches('-');
let truncated: String = trimmed.chars().take(48).collect();
if truncated.is_empty() {
"project".to_string()
} else {
truncated
}
}
fn valid_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 64
&& id.chars().all(|character| {
character.is_ascii_alphanumeric() || character == '-' || character == '_'
})
}
fn valid_relative(path: &str) -> bool {
!path.is_empty()
&& !path.starts_with('/')
&& !path.contains('\\')
&& Path::new(path)
.components()
.all(|component| matches!(component, Component::Normal(_)))
}
fn entry_path(entry: &str) -> Option<String> {
let normalized = entry.replace('\\', "/");
let trimmed = normalized.trim_start_matches("./");
let trimmed = trimmed.trim_end_matches('/');
if !valid_relative(trimmed) {
return None;
}
Some(trimmed.to_string())
}
fn detect_main(directory: &Path, names: &[String]) -> Option<String> {
for candidate in ["main.tex", "document.tex", "paper.tex", "article.tex"] {
if let Some(name) = names.iter().find(|name| name.as_str() == candidate) {
return Some(name.clone());
}
}
let tex_files = names
.iter()
.filter(|name| name.ends_with(".tex"))
.cloned()
.collect::<Vec<_>>();
for name in &tex_files {
if let Ok(text) = fs::read_to_string(directory.join(name)) {
if text.contains("\\documentclass") || text.contains("\\begin{document}") {
return Some(name.clone());
}
}
}
tex_files.into_iter().next()
}
fn collect_files(root: &Path) -> Result<Vec<ProjectFile>, String> {
let mut files = Vec::new();
let mut stack = vec![(root.to_path_buf(), String::new(), 0_usize)];
while let Some((directory, prefix, depth)) = stack.pop() {
if depth > 12 {
continue;
}
let entries = match fs::read_dir(&directory) {
Ok(entries) => entries,
Err(_) => continue,
};
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = entry.file_name().to_str().map(str::to_string) else {
continue;
};
if name.starts_with('.') {
continue;
}
let relative = if prefix.is_empty() {
name.clone()
} else {
format!("{prefix}/{name}")
};
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_symlink() {
continue;
}
if file_type.is_dir() {
stack.push((path, relative, depth + 1));
} else if file_type.is_file() {
let size = entry.metadata().map(|metadata| metadata.len()).unwrap_or(0);
files.push(ProjectFile {
path: relative,
size,
});
}
}
}
files.sort_by(|left, right| left.path.cmp(&right.path));
Ok(files)
}
fn find_eocd(bytes: &[u8]) -> Result<usize, String> {
if bytes.len() < 22 {
return Err("not a zip archive".to_string());
}
let lowest = bytes.len().saturating_sub(22 + 65_535);
let mut index = bytes.len() - 22;
loop {
if bytes[index..index + 4] == [0x50, 0x4b, 0x05, 0x06] {
return Ok(index);
}
if index == lowest {
break;
}
index -= 1;
}
Err("not a zip archive".to_string())
}
fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
let eocd = find_eocd(bytes)?;
let read_u16 = |offset: usize| -> Result<u16, String> {
bytes
.get(offset..offset + 2)
.map(|slice| u16::from_le_bytes([slice[0], slice[1]]))
.ok_or_else(|| "truncated zip archive".to_string())
};
let read_u32 = |offset: usize| -> Result<u32, String> {
bytes
.get(offset..offset + 4)
.map(|slice| u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
.ok_or_else(|| "truncated zip archive".to_string())
};
let count = read_u16(eocd + 10)? as usize;
let cd_size = read_u32(eocd + 12)? as usize;
let cd_offset = read_u32(eocd + 16)? as usize;
if count == 0xffff || cd_offset == 0xffff_ffff || cd_size == 0xffff_ffff {
return Err(ZIP64_MESSAGE.to_string());
}
let mut entries = Vec::new();
let mut cursor = cd_offset;
for _ in 0..count {
if read_u32(cursor)? != 0x0201_4b50 {
return Err("corrupt zip central directory".to_string());
}
let flags = read_u16(cursor + 8)?;
let method = read_u16(cursor + 10)?;
let compressed_size = read_u32(cursor + 20)? as usize;
let uncompressed_size = read_u32(cursor + 24)? as usize;
let name_length = read_u16(cursor + 28)? as usize;
let extra_length = read_u16(cursor + 30)? as usize;
let comment_length = read_u16(cursor + 32)? as usize;
let local_offset = read_u32(cursor + 42)? as usize;
let name_bytes = bytes
.get(cursor + 46..cursor + 46 + name_length)
.ok_or_else(|| "truncated zip archive".to_string())?;
let name = String::from_utf8_lossy(name_bytes).to_string();
cursor += 46 + name_length + extra_length + comment_length;
if name.ends_with('/') || name.ends_with('\\') {
continue;
}
if flags & 0x0001 != 0 {
return Err("encrypted zip entries are not supported".to_string());
}
if read_u32(local_offset)? != 0x0403_4b50 {
return Err("corrupt zip local header".to_string());
}
let local_name_length = read_u16(local_offset + 26)? as usize;
let local_extra_length = read_u16(local_offset + 28)? as usize;
let data_start = local_offset + 30 + local_name_length + local_extra_length;
let data = bytes
.get(data_start..data_start + compressed_size)
.ok_or_else(|| "truncated zip entry data".to_string())?;
let content = match method {
0 => data.to_vec(),
8 => {
let mut decoder = DeflateDecoder::new(data);
let mut output = Vec::new();
decoder
.read_to_end(&mut output)
.map_err(|error| format!("could not inflate `{name}`: {error}"))?;
output
}
other => {
return Err(format!(
"unsupported zip compression method {other} for `{name}`"
));
}
};
if content.len() != uncompressed_size {
return Err(format!("zip entry `{name}` has an inconsistent size"));
}
entries.push((name, content));
}
Ok(entries)
}
fn write_zip(entries: &[(String, Vec<u8>)]) -> Vec<u8> {
let mut output = Vec::new();
let mut directory = Vec::new();
for (name, data) in entries {
let offset = output.len() as u32;
let crc = crc32(data);
let compressed = deflate(data);
write_u32(&mut output, 0x0403_4b50);
write_u16(&mut output, 20);
write_u16(&mut output, 0);
write_u16(&mut output, 8);
write_u16(&mut output, 0);
write_u16(&mut output, 0x0021);
write_u32(&mut output, crc);
write_u32(&mut output, compressed.len() as u32);
write_u32(&mut output, data.len() as u32);
write_u16(&mut output, name.len() as u16);
write_u16(&mut output, 0);
output.extend_from_slice(name.as_bytes());
output.extend_from_slice(&compressed);
write_u32(&mut directory, 0x0201_4b50);
write_u16(&mut directory, 20);
write_u16(&mut directory, 20);
write_u16(&mut directory, 0);
write_u16(&mut directory, 8);
write_u16(&mut directory, 0);
write_u16(&mut directory, 0x0021);
write_u32(&mut directory, crc);
write_u32(&mut directory, compressed.len() as u32);
write_u32(&mut directory, data.len() as u32);
write_u16(&mut directory, name.len() as u16);
write_u16(&mut directory, 0);
write_u16(&mut directory, 0);
write_u16(&mut directory, 0);
write_u16(&mut directory, 0);
write_u32(&mut directory, 0);
write_u32(&mut directory, offset);
directory.extend_from_slice(name.as_bytes());
}
let directory_offset = output.len() as u32;
output.extend_from_slice(&directory);
write_u32(&mut output, 0x0605_4b50);
write_u16(&mut output, 0);
write_u16(&mut output, 0);
write_u16(&mut output, entries.len() as u16);
write_u16(&mut output, entries.len() as u16);
write_u32(&mut output, directory.len() as u32);
write_u32(&mut output, directory_offset);
write_u16(&mut output, 0);
output
}
fn crc32(data: &[u8]) -> u32 {
let mut crc = Crc::new();
crc.update(data);
crc.sum()
}
fn deflate(data: &[u8]) -> Vec<u8> {
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
encoder
.write_all(data)
.expect("writing to an in-memory deflate encoder cannot fail");
encoder
.finish()
.expect("finishing an in-memory deflate encoder cannot fail")
}
fn write_u16(output: &mut Vec<u8>, value: u16) {
output.extend_from_slice(&value.to_le_bytes());
}
fn write_u32(output: &mut Vec<u8>, value: u32) {
output.extend_from_slice(&value.to_le_bytes());
}
+1356
View File
File diff suppressed because it is too large. Load diff
+191
View File
@@ -0,0 +1,191 @@
use std::rc::Rc;
use boxworks::{self, ds};
use common::{Glue, Scaled, font as box_font};
use rusttype::{Font as RustFont, Scale as RustScale};
pub(super) struct BoxFont {
font: Option<Rc<RustFont<'static>>>,
size: u8,
}
impl BoxFont {
pub(super) fn new(font: Rc<RustFont<'static>>, size: u8) -> Self {
Self {
font: Some(font),
size,
}
}
pub(super) fn pair_kerning(&self, left: char, right: char) -> Scaled {
let Some(font) = &self.font else {
return Scaled::ZERO;
};
let scale = RustScale::uniform(glyph_height(font));
let kerning = font.pair_kerning(scale, font.glyph(left).id(), font.glyph(right).id())
* f32::from(self.size);
scaled_points(f64::from(kerning))
}
}
impl box_font::Format for BoxFont {
fn null() -> Self {
Self {
font: None,
size: 0,
}
}
fn width(&self, character: char) -> Option<Scaled> {
let font = self.font.as_ref()?;
let glyph_height = glyph_height(font);
let width = font
.glyph(character)
.scaled(RustScale::uniform(glyph_height))
.h_metrics()
.advance_width
* f32::from(self.size);
Some(scaled_points(f64::from(width)))
}
fn height(&self, _character: char) -> Option<Scaled> {
let font = self.font.as_ref()?;
let units_per_em = f32::from(font.units_per_em());
let ascent = font.v_metrics_unscaled().ascent / units_per_em * f32::from(self.size);
Some(scaled_points(f64::from(ascent)))
}
fn depth(&self, _character: char) -> Option<Scaled> {
let font = self.font.as_ref()?;
let units_per_em = f32::from(font.units_per_em());
let descent = -font.v_metrics_unscaled().descent / units_per_em * f32::from(self.size);
Some(scaled_points(f64::from(descent.max(0.0))))
}
fn default_space(&self) -> Glue {
let width = self.width(' ').unwrap_or_else(|| scaled_points(3.0));
Glue {
width,
stretch: Scaled(width.0 / 2),
stretch_order: common::GlueOrder::Normal,
shrink: Scaled(width.0 / 3),
shrink_order: common::GlueOrder::Normal,
}
}
fn extra_space(&self) -> Scaled {
Scaled::ZERO
}
}
/// Hyphenates words with plain TeX's English patterns.
///
/// TeX starts a word only at glue boundaries and requires at least two letters
/// before and three after the hyphen. Words are tracked across normal kerns so
/// that font pair kerning does not hide a word from the hyphenator.
pub(super) struct TeXHyphenator {
engine: hyphenate::Hyphenator,
lower_caser: hyphenate::AsciiLowerCaser,
}
const LEFT_HYPHEN_MIN: usize = 2;
const RIGHT_HYPHEN_MIN: usize = 3;
impl TeXHyphenator {
pub(super) fn get() -> &'static Self {
static HYPHENATOR: std::sync::OnceLock<TeXHyphenator> = std::sync::OnceLock::new();
HYPHENATOR.get_or_init(|| Self {
engine: hyphenate::Hyphenator::plain_tex_en_us(),
lower_caser: hyphenate::AsciiLowerCaser::default(),
})
}
fn collect_word_breaks(
&self,
letters: &[(usize, char, box_font::Id)],
breaks: &mut Vec<(usize, box_font::Id)>,
) {
if letters.len() < LEFT_HYPHEN_MIN + RIGHT_HYPHEN_MIN {
return;
}
let word = letters
.iter()
.map(|(_, character, _)| *character)
.collect::<String>();
let count = letters.len();
for position in self.engine.calculate_indices(&self.lower_caser, &word) {
if position >= LEFT_HYPHEN_MIN && count.saturating_sub(position) >= RIGHT_HYPHEN_MIN {
let (index, _, font) = letters[position];
breaks.push((index, font));
}
}
}
fn hyphenate_list(&self, list: &[ds::Horizontal]) -> Vec<ds::Horizontal> {
const INLINE_BOX_START: char = '\u{F1000}';
const INLINE_BOX_END: char = '\u{F1001}';
let mut breaks = Vec::new();
let mut letters = Vec::new();
let mut protected = false;
for (index, item) in list.iter().enumerate() {
match item {
ds::Horizontal::Char(character) if character.char == INLINE_BOX_START => {
protected = true;
self.collect_word_breaks(&letters, &mut breaks);
letters.clear();
}
ds::Horizontal::Char(character) if character.char == INLINE_BOX_END => {
protected = false;
self.collect_word_breaks(&letters, &mut breaks);
letters.clear();
}
ds::Horizontal::Char(character) if character.char.is_ascii_alphabetic() => {
if !protected {
letters.push((index, character.char, character.font));
}
}
ds::Horizontal::Kern(kern)
if kern.kind == ds::KernKind::Normal && !letters.is_empty() => {}
_ => {
if !protected {
self.collect_word_breaks(&letters, &mut breaks);
}
letters.clear();
}
}
}
self.collect_word_breaks(&letters, &mut breaks);
if breaks.is_empty() {
return list.to_vec();
}
let mut result = Vec::with_capacity(list.len() + breaks.len());
let mut breaks = breaks.into_iter().peekable();
for (index, item) in list.iter().enumerate() {
while let Some((_, font)) = breaks.next_if(|(at, _)| *at == index) {
result.push(ds::Horizontal::Discretionary(ds::Discretionary {
pre_break: vec![ds::DiscretionaryElem::Char(ds::Char { char: '-', font })],
post_break: Vec::new(),
replace_count: 0,
}));
}
result.push(item.clone());
}
result
}
}
impl boxworks::Hyphenator for TeXHyphenator {
fn hyphenate(&self, list: &mut Vec<ds::Horizontal>) {
*list = self.hyphenate_list(list);
}
}
fn glyph_height(font: &RustFont<'static>) -> f32 {
let metrics = font.v_metrics_unscaled();
(metrics.ascent - metrics.descent) / f32::from(font.units_per_em())
}
pub(super) fn scaled_points(points: f64) -> Scaled {
Scaled((points * 65_536.0).round() as i32)
}
+4
View File
@@ -0,0 +1,4 @@
pub(super) use texrra_core::document::{
Block, ColumnAlignment, DocumentModel, EquationNumber, ListBlock, RuleBox, Run,
};
pub(super) use texrra_core::math_expr::*;
+362
View File
@@ -0,0 +1,362 @@
//! TeX arithmetic assignment primitives backed by engine variables.
use std::fmt::Display;
use texlang::command::{self, StaticTag, Tag};
use texlang::error;
use texlang::traits::*;
use texlang::variable::{SupportedType, TypedVariable};
use texlang::{parse, token, vm};
static ADVANCE_TAG: StaticTag = StaticTag::new();
static MULTIPLY_TAG: StaticTag = StaticTag::new();
static DIVIDE_TAG: StaticTag = StaticTag::new();
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum ArithmeticOperation {
Advance,
Multiply,
Divide,
}
pub(crate) fn get_advance<S: TexlangState>() -> command::BuiltIn<S> {
get_command::<S, Advance>()
}
pub(crate) fn get_multiply<S: TexlangState>() -> command::BuiltIn<S> {
get_command::<S, Multiply>()
}
pub(crate) fn get_divide<S: TexlangState>() -> command::BuiltIn<S> {
get_command::<S, Divide>()
}
pub(crate) fn is_arithmetic_tag(tag: Tag) -> bool {
[Advance::tag(), Multiply::tag(), Divide::tag()].contains(&tag)
}
pub(crate) fn execute<S: TexlangState>(
operation: ArithmeticOperation,
token: token::Token,
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<()> {
match operation {
ArithmeticOperation::Advance => arithmetic_primitive::<S, Advance>(token, input),
ArithmeticOperation::Multiply => arithmetic_primitive::<S, Multiply>(token, input),
ArithmeticOperation::Divide => arithmetic_primitive::<S, Divide>(token, input),
}
}
fn get_command<S: TexlangState, O: Operation>() -> command::BuiltIn<S> {
command::BuiltIn::new_execution(arithmetic_primitive::<S, O>)
.with_tag(O::tag())
.with_doc(O::DOC)
}
trait ArithmeticNumber: Sized + Default + SupportedType + Copy + Display {
fn scan_rhs<S: TexlangState>(
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<Self>;
fn wrapping_add(lhs: Self, rhs: Self) -> Self;
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self>;
fn wrapping_mul(lhs: Self, rhs: i32) -> Self;
fn checked_div(lhs: Self, rhs: i32) -> Option<Self>;
}
impl ArithmeticNumber for i32 {
fn scan_rhs<S: TexlangState>(
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<Self> {
Self::parse(input)
}
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
lhs.wrapping_add(rhs)
}
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_mul(rhs)
}
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
lhs.wrapping_mul(rhs)
}
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_div(rhs)
}
}
impl ArithmeticNumber for common::Scaled {
fn scan_rhs<S: TexlangState>(
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<Self> {
Self::parse(input)
}
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
lhs.wrapping_add(rhs)
}
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_mul(rhs)
}
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
lhs.wrapping_mul(rhs)
}
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_div(rhs)
}
}
impl ArithmeticNumber for common::Glue {
fn scan_rhs<S: TexlangState>(
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<Self> {
Self::parse(input)
}
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
lhs.wrapping_add(rhs)
}
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_mul(rhs)
}
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
lhs.wrapping_mul(rhs)
}
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_div(rhs)
}
}
impl ArithmeticNumber for texlang::types::MuGlue {
fn scan_rhs<S: TexlangState>(
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<Self> {
Self::parse(input)
}
fn wrapping_add(lhs: Self, rhs: Self) -> Self {
lhs.wrapping_add(rhs)
}
fn checked_mul(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_mul(rhs)
}
fn wrapping_mul(lhs: Self, rhs: i32) -> Self {
lhs.wrapping_mul(rhs)
}
fn checked_div(lhs: Self, rhs: i32) -> Option<Self> {
lhs.checked_div(rhs)
}
}
trait Operation {
const DOC: &'static str;
const RHS_IS_SAME_TYPE: bool;
type Error: error::TexError;
fn tag() -> Tag;
fn apply<N: ArithmeticNumber>(
lhs: N,
rhs_integer: i32,
rhs_number: N,
) -> Result<N, Self::Error>;
fn apply_to_variable<S: TexlangState, N: ArithmeticNumber>(
variable: TypedVariable<S, N>,
input: &mut vm::ExecutionInput<S>,
scope: texcraft_stdext::collections::groupingmap::Scope,
) -> texlang::prelude::Result<()> {
let lhs = *variable.get(input.state());
let (rhs_integer, rhs_number) = if Self::RHS_IS_SAME_TYPE {
(0, N::scan_rhs(input)?)
} else {
(i32::parse(input)?, N::default())
};
let result = match Self::apply(lhs, rhs_integer, rhs_number) {
Ok(result) => result,
Err(error) => return input.error(error),
};
variable.set(input, scope, result);
Ok(())
}
}
struct Advance;
impl Operation for Advance {
const DOC: &'static str = "Add a quantity to a variable";
const RHS_IS_SAME_TYPE: bool = true;
type Error = ArithmeticOverflow;
fn tag() -> Tag {
ADVANCE_TAG.get()
}
fn apply<N: ArithmeticNumber>(lhs: N, _: i32, rhs_number: N) -> Result<N, Self::Error> {
Ok(N::wrapping_add(lhs, rhs_number))
}
}
struct Multiply;
impl Operation for Multiply {
const DOC: &'static str = "Multiply a variable by an integer";
const RHS_IS_SAME_TYPE: bool = false;
type Error = ArithmeticOverflow;
fn tag() -> Tag {
MULTIPLY_TAG.get()
}
fn apply<N: ArithmeticNumber>(lhs: N, rhs_integer: i32, _: N) -> Result<N, Self::Error> {
N::checked_mul(lhs, rhs_integer).ok_or_else(|| ArithmeticOverflow {
operation: "multiplication",
lhs: lhs.to_string(),
rhs: rhs_integer.to_string(),
wrapped_result: N::wrapping_mul(lhs, rhs_integer).to_string(),
})
}
}
struct Divide;
impl Operation for Divide {
const DOC: &'static str = "Divide a variable by an integer";
const RHS_IS_SAME_TYPE: bool = false;
type Error = DivisionByZero;
fn tag() -> Tag {
DIVIDE_TAG.get()
}
fn apply<N: ArithmeticNumber>(lhs: N, rhs_integer: i32, _: N) -> Result<N, Self::Error> {
N::checked_div(lhs, rhs_integer).ok_or_else(|| DivisionByZero {
numerator: lhs.to_string(),
})
}
}
fn arithmetic_primitive<S: TexlangState, O: Operation>(
_: token::Token,
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<()> {
let scope = TexlangState::variable_assignment_scope_hook(input.state_mut());
let token = input.next_or_err(ArithmeticVariableEndOfInput {})?;
match token.value() {
token::Value::CommandRef(command_ref) => match input
.commands_map()
.get_command(&command_ref)
{
None => input.error(
parse::Error::new("a variable", Some(token), "")
.with_got_override("got an undefined control sequence")
.with_annotation_override("undefined control sequence"),
),
Some(command::Command::Variable(command)) => {
if !command.is_arithmetic() {
input.error(
parse::Error::new("an arithmetic variable", Some(token), "")
.with_got_override("got a non-arithmetic variable"),
)?;
return Ok(());
}
let variable = command.clone().resolve(token, input.as_mut())?;
OptionalBy::parse(input)?;
match variable {
texlang::variable::Variable::Int(variable) => {
O::apply_to_variable(variable, input, scope)
}
texlang::variable::Variable::Dimen(variable) => {
O::apply_to_variable(variable, input, scope)
}
texlang::variable::Variable::Glue(variable) => {
O::apply_to_variable(variable, input, scope)
}
texlang::variable::Variable::MuGlue(variable) => {
O::apply_to_variable(variable, input, scope)
}
texlang::variable::Variable::SmallInt(_)
| texlang::variable::Variable::CatCode(_)
| texlang::variable::Variable::TokenList(_)
| texlang::variable::Variable::MathCode(_)
| texlang::variable::Variable::Font(_) => {
unreachable!("only arithmetic commands are considered")
}
}
}
Some(command) => input.error(
parse::Error::new("a variable", Some(token), "")
.with_got_override("got a non-variable command")
.with_annotation_override(format!("control sequence referencing {command}")),
),
},
_ => input.error(
parse::Error::new("a variable", Some(token), "")
.with_got_override("got a character token"),
),
}
}
#[derive(Debug)]
struct ArithmeticVariableEndOfInput;
impl error::EndOfInputError for ArithmeticVariableEndOfInput {
fn doing(&self) -> String {
"parsing an arithmetic variable".into()
}
}
struct OptionalBy;
impl Parsable for OptionalBy {
fn parse_impl<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
) -> texlang::prelude::Result<Self> {
parse::parse_keyword(input, "by")?;
Ok(Self)
}
}
#[derive(Debug)]
struct ArithmeticOverflow {
operation: &'static str,
lhs: String,
rhs: String,
wrapped_result: String,
}
impl error::TexError for ArithmeticOverflow {
fn kind(&self) -> error::Kind {
error::Kind::FailedPrecondition
}
fn title(&self) -> String {
format!("overflow in checked {}", self.operation)
}
fn notes(&self) -> Vec<error::display::Note> {
vec![
format!("left hand side evaluated to {}", self.lhs).into(),
format!("right hand side evaluated to {}", self.rhs).into(),
format!("wrapped result would be {}", self.wrapped_result).into(),
]
}
}
#[derive(Debug)]
struct DivisionByZero {
numerator: String,
}
impl error::TexError for DivisionByZero {
fn kind(&self) -> error::Kind {
error::Kind::FailedPrecondition
}
fn title(&self) -> String {
"division by zero".into()
}
fn notes(&self) -> Vec<error::display::Note> {
vec![format!("numerator evaluated to {}", self.numerator).into()]
}
}
@@ -0,0 +1 @@
pub(crate) use texrra_core::assignment_scope::AssignmentScopeKind;
+1
View File
@@ -0,0 +1 @@
pub(crate) use texrra_core::command::{EngineCommandMeaning, NativePrimitive};
+969
View File
@@ -0,0 +1,969 @@
use common::{Scaled, ScaledUnit};
use super::{
glue::{TeXGlue, TeXGlueOrder},
token::EngineCatCode,
};
use texrra_core::integer::{self, IntegerScanError, IntegerTokenStream};
pub(crate) trait DimensionTokenStream: IntegerTokenStream {
fn scan_internal_dimension(
&mut self,
token: Self::Token,
) -> Result<Option<Scaled>, Self::Error>;
fn scan_internal_glue(&mut self, token: Self::Token) -> Result<Option<TeXGlue>, Self::Error>;
fn scan_internal_math_glue(
&mut self,
token: Self::Token,
) -> Result<Option<TeXGlue>, Self::Error>;
fn scan_internal_math_dimension(
&mut self,
token: Self::Token,
) -> Result<Option<InternalMathDimension>, Self::Error>;
fn em_width(&self) -> Scaled;
fn ex_height(&self) -> Scaled;
fn magnification_ratio(&self) -> i32;
}
pub(crate) enum InternalMathDimension {
GlueWidth(Scaled),
Integer(i32),
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum UnitSystem {
Physical,
Math,
}
#[derive(Debug)]
pub(crate) enum DimensionScanError<T, E> {
Stream(E),
CompatibilityRequired,
MissingNumber(Option<T>),
IllegalUnit(Option<T>),
InvalidExpression(Option<T>),
TooLarge { token: Option<T>, negative: bool },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ScannedDimension {
pub(crate) value: Scaled,
pub(crate) order: TeXGlueOrder,
}
pub(crate) use texrra_core::integer::ScannedInteger;
pub(crate) fn scan_integer<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<i32, DimensionScanError<S::Token, S::Error>> {
integer::scan_integer(stream).map_err(map_integer_error)
}
pub(crate) fn scan_integer_with_token<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<ScannedInteger<S::Token>, DimensionScanError<S::Token, S::Error>> {
integer::scan_integer_with_token(stream).map_err(map_integer_error)
}
fn map_integer_error<T, E>(error: IntegerScanError<T, E>) -> DimensionScanError<T, E> {
match error {
IntegerScanError::Stream(error) => DimensionScanError::Stream(error),
IntegerScanError::CompatibilityRequired => DimensionScanError::CompatibilityRequired,
IntegerScanError::MissingNumber(token) => DimensionScanError::MissingNumber(token),
IntegerScanError::TooLarge { token, negative } => {
DimensionScanError::TooLarge { token, negative }
}
}
}
pub(crate) fn scan_dimension<S: DimensionTokenStream>(
stream: &mut S,
allow_infinite: bool,
) -> Result<ScannedDimension, DimensionScanError<S::Token, S::Error>> {
scan_dimension_with_units(stream, allow_infinite, UnitSystem::Physical)
}
fn scan_dimension_with_units<S: DimensionTokenStream>(
stream: &mut S,
allow_infinite: bool,
unit_system: UnitSystem,
) -> Result<ScannedDimension, DimensionScanError<S::Token, S::Error>> {
let (negative, first) = scan_signs(stream)?;
scan_dimension_from_first(stream, negative, first, allow_infinite, unit_system)
}
fn scan_dimension_from_first<S: DimensionTokenStream>(
stream: &mut S,
negative: bool,
first: S::Token,
allow_infinite: bool,
unit_system: UnitSystem,
) -> Result<ScannedDimension, DimensionScanError<S::Token, S::Error>> {
if stream.is_command_reference(&first) {
let name = stream.control_sequence_name(&first);
if unit_system == UnitSystem::Math && name.as_deref() == Some("muexpr") {
let glue = scan_glue_expression(stream, false, UnitSystem::Math)?;
let value = if negative { -glue.width } else { glue.width };
return Ok(ScannedDimension {
value,
order: TeXGlueOrder::Normal,
});
}
if unit_system == UnitSystem::Physical && name.as_deref() == Some("dimexpr") {
let mut value = scan_dimension_expression(stream, false)?;
if negative {
value = -value;
}
return Ok(ScannedDimension {
value,
order: TeXGlueOrder::Normal,
});
}
if unit_system == UnitSystem::Physical && name.as_deref() == Some("glueexpr") {
let glue = scan_glue_expression(stream, false, UnitSystem::Physical)?;
let value = if negative { -glue.width } else { glue.width };
return Ok(ScannedDimension {
value,
order: TeXGlueOrder::Normal,
});
}
let mut value = if unit_system == UnitSystem::Math {
match stream
.scan_internal_math_dimension(first.clone())
.map_err(DimensionScanError::Stream)?
{
Some(InternalMathDimension::GlueWidth(value)) => value,
Some(InternalMathDimension::Integer(integer)) => {
consume_optional_space(stream)?;
if !scan_keyword(stream, "mu")? {
return Err(DimensionScanError::IllegalUnit(next_token(stream)?));
}
consume_optional_space(stream)?;
Scaled::new(integer, Scaled::ZERO, ScaledUnit::Point).map_err(|_| {
DimensionScanError::TooLarge {
token: Some(first.clone()),
negative,
}
})?
}
None => return Err(DimensionScanError::CompatibilityRequired),
}
} else {
match stream
.scan_internal_dimension(first)
.map_err(DimensionScanError::Stream)?
{
Some(value) => value,
None => return Err(DimensionScanError::CompatibilityRequired),
}
};
if negative {
value = -value;
}
return Ok(ScannedDimension {
value,
order: TeXGlueOrder::Normal,
});
}
let (integer_part, fractional_part, first_token) = scan_number(stream, first, negative)?;
// TeX permits one optional space between the number and its unit.
consume_optional_space(stream)?;
let mut order = TeXGlueOrder::Normal;
let (unit, true_unit) = if unit_system == UnitSystem::Math {
scan_math_unit(stream, allow_infinite, &mut order)?
} else if allow_infinite {
if scan_keyword(stream, "fil")? {
order = TeXGlueOrder::Fil;
while scan_keyword(stream, "l")? {
order = match order {
TeXGlueOrder::Fil => TeXGlueOrder::Fill,
TeXGlueOrder::Fill => TeXGlueOrder::Filll,
TeXGlueOrder::Filll => {
return Err(DimensionScanError::IllegalUnit(next_token(stream)?));
}
TeXGlueOrder::Normal => unreachable!(),
};
}
(DimensionUnit::Infinite, false)
} else {
scan_finite_unit(stream)?
}
} else {
scan_finite_unit(stream)?
};
consume_optional_space(stream)?;
let mut value = match unit {
DimensionUnit::Scaled(unit) => Scaled::new(integer_part, fractional_part, unit),
DimensionUnit::FontMetric(metric) => {
let metric = match metric {
FontMetric::Em => stream.em_width(),
FontMetric::Ex => stream.ex_height(),
};
let fractional = metric.xn_over_d(fractional_part.0, Scaled::ONE.0);
fractional.and_then(|(fractional, _)| metric.nx_plus_y(integer_part, fractional))
}
DimensionUnit::Infinite => Scaled::new(integer_part, fractional_part, ScaledUnit::Point),
}
.map_err(|_| DimensionScanError::TooLarge {
token: Some(first_token.clone()),
negative,
})?;
if true_unit {
let magnification = stream.magnification_ratio();
if !(1..=32_768).contains(&magnification) {
return Err(DimensionScanError::TooLarge {
token: Some(first_token),
negative,
});
}
value = value
.xn_over_d(1000, magnification)
.map_err(|_| DimensionScanError::TooLarge {
token: Some(first_token.clone()),
negative,
})?
.0;
}
if value.0 > Scaled::MAX_DIMEN.0 {
return Err(DimensionScanError::TooLarge {
token: Some(first_token),
negative,
});
}
if negative {
value = -value;
}
Ok(ScannedDimension { value, order })
}
fn scan_dimension_expression<S: DimensionTokenStream>(
stream: &mut S,
stop_at_right_parenthesis: bool,
) -> Result<Scaled, DimensionScanError<S::Token, S::Error>> {
let mut value = scan_dimension_term(stream)?;
loop {
let Some(token) = next_non_space_token(stream)? else {
if stop_at_right_parenthesis {
return Err(DimensionScanError::InvalidExpression(None));
}
return Ok(value);
};
if let Some((operator, EngineCatCode::Other)) = stream.character(&token) {
match operator {
'+' | '-' => {
let right = scan_dimension_term(stream)?;
let signed_right = if operator == '-' {
-i64::from(right.0)
} else {
i64::from(right.0)
};
let sum = i64::from(value.0) + signed_right;
value =
checked_dimension_sum(value, right, operator == '-').ok_or_else(|| {
DimensionScanError::TooLarge {
token: Some(token),
negative: sum < 0,
}
})?;
continue;
}
')' if stop_at_right_parenthesis => {
stream.back_token(token);
return Ok(value);
}
_ => {}
}
} else if stream.control_sequence_name(&token).as_deref() == Some("relax") {
if stop_at_right_parenthesis {
return Err(DimensionScanError::InvalidExpression(Some(token)));
}
return Ok(value);
}
stream.back_token(token);
return Ok(value);
}
}
fn scan_dimension_term<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<Scaled, DimensionScanError<S::Token, S::Error>> {
let mut value = scan_dimension_factor(stream)?;
loop {
let Some(token) = next_non_space_token(stream)? else {
return Ok(value);
};
let Some((operator, EngineCatCode::Other)) = stream.character(&token) else {
stream.back_token(token);
return Ok(value);
};
if !matches!(operator, '*' | '/') {
stream.back_token(token);
return Ok(value);
}
let factor = scan_integer(stream)?;
if operator == '*' {
if let Some(next) = next_non_space_token(stream)? {
if matches!(stream.character(&next), Some(('/', EngineCatCode::Other))) {
let denominator = scan_integer(stream)?;
value = checked_dimension_scale(value, factor, denominator)
.ok_or_else(|| DimensionScanError::InvalidExpression(Some(next)))?;
continue;
}
stream.back_token(next);
}
let product = i64::from(value.0) * i64::from(factor);
value = checked_dimension_product(value, factor).ok_or_else(|| {
DimensionScanError::TooLarge {
token: Some(token),
negative: product < 0,
}
})?;
} else {
value = checked_dimension_quotient(value, factor)
.ok_or_else(|| DimensionScanError::InvalidExpression(Some(token)))?;
}
}
}
fn scan_dimension_factor<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<Scaled, DimensionScanError<S::Token, S::Error>> {
let (negative, first) = scan_signs(stream)?;
if matches!(stream.character(&first), Some(('(', EngineCatCode::Other))) {
let mut value = scan_dimension_expression(stream, true)?;
let closing = next_non_space_token(stream)?;
if !closing.as_ref().is_some_and(|token| {
matches!(stream.character(token), Some((')', EngineCatCode::Other)))
}) {
return Err(DimensionScanError::InvalidExpression(closing));
}
if negative {
value = -value;
}
return Ok(value);
}
Ok(scan_dimension_from_first(stream, negative, first, false, UnitSystem::Physical)?.value)
}
fn next_non_space_token<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<Option<S::Token>, DimensionScanError<S::Token, S::Error>> {
loop {
let Some(token) = next_token(stream)? else {
return Ok(None);
};
if !stream.is_space(&token) {
return Ok(Some(token));
}
}
}
fn checked_dimension_sum(left: Scaled, right: Scaled, subtract: bool) -> Option<Scaled> {
let right = if subtract {
-i64::from(right.0)
} else {
i64::from(right.0)
};
let value = i64::from(left.0).checked_add(right)?;
dimension_in_range(value).map(|value| Scaled(value as i32))
}
fn checked_dimension_product(value: Scaled, factor: i32) -> Option<Scaled> {
let product = i64::from(value.0).checked_mul(i64::from(factor))?;
dimension_in_range(product).map(|product| Scaled(product as i32))
}
fn checked_dimension_quotient(value: Scaled, factor: i32) -> Option<Scaled> {
checked_dimension_scale(value, 1, factor)
}
fn checked_dimension_scale(value: Scaled, numerator: i32, denominator: i32) -> Option<Scaled> {
if denominator == 0 {
return None;
}
let product = i64::from(value.0).checked_mul(i64::from(numerator))?;
let denominator = i64::from(denominator);
let negative = (product < 0) != (denominator < 0);
let product = product.abs();
let denominator = denominator.abs();
// TeX rounds scaled-point division to nearest, with ties away from zero.
let quotient = (product + denominator / 2) / denominator;
dimension_in_range(if negative { -quotient } else { quotient })
.map(|quotient| Scaled(quotient as i32))
}
fn dimension_in_range(value: i64) -> Option<i64> {
let limit = i64::from(Scaled::MAX_DIMEN.0);
(-limit..=limit).contains(&value).then_some(value)
}
pub(crate) fn scan_glue<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<TeXGlue, DimensionScanError<S::Token, S::Error>> {
let (negative, first) = scan_signs(stream)?;
scan_glue_from_first(stream, negative, first, UnitSystem::Physical)
}
pub(crate) fn scan_math_glue<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<TeXGlue, DimensionScanError<S::Token, S::Error>> {
let (negative, first) = scan_signs(stream)?;
scan_glue_from_first(stream, negative, first, UnitSystem::Math)
}
fn scan_glue_from_first<S: DimensionTokenStream>(
stream: &mut S,
negative: bool,
first: S::Token,
unit_system: UnitSystem,
) -> Result<TeXGlue, DimensionScanError<S::Token, S::Error>> {
if stream.is_command_reference(&first) {
let name = stream.control_sequence_name(&first);
let mut glue = if unit_system == UnitSystem::Math && name.as_deref() == Some("muexpr") {
scan_glue_expression(stream, false, UnitSystem::Math)?
} else if unit_system == UnitSystem::Physical && name.as_deref() == Some("glueexpr") {
scan_glue_expression(stream, false, UnitSystem::Physical)?
} else if unit_system == UnitSystem::Physical && name.as_deref() == Some("dimexpr") {
let width =
scan_dimension_from_first(stream, false, first, false, UnitSystem::Physical)?.value;
scan_glue_parts(stream, width, UnitSystem::Physical)?
} else if unit_system == UnitSystem::Math {
match stream
.scan_internal_math_glue(first.clone())
.map_err(DimensionScanError::Stream)?
{
Some(glue) => glue,
None => {
let width =
scan_dimension_from_first(stream, false, first, false, UnitSystem::Math)?
.value;
scan_glue_parts(stream, width, UnitSystem::Math)?
}
}
} else {
match stream
.scan_internal_glue(first.clone())
.map_err(DimensionScanError::Stream)?
{
Some(glue) => glue,
None => {
let width = scan_dimension_from_first(
stream,
false,
first,
false,
UnitSystem::Physical,
)?
.value;
scan_glue_parts(stream, width, UnitSystem::Physical)?
}
}
};
if negative {
glue = scale_glue(glue, -1, 1)
.ok_or_else(|| DimensionScanError::InvalidExpression(None))?;
}
return Ok(glue);
}
let width = scan_dimension_from_first(stream, negative, first, false, unit_system)?.value;
scan_glue_parts(stream, width, unit_system)
}
fn scan_glue_parts<S: DimensionTokenStream>(
stream: &mut S,
width: Scaled,
unit_system: UnitSystem,
) -> Result<TeXGlue, DimensionScanError<S::Token, S::Error>> {
let mut glue = TeXGlue {
width,
..TeXGlue::default()
};
if scan_keyword(stream, "plus")? {
let stretch = scan_dimension_with_units(stream, true, unit_system)?;
glue.stretch = stretch.value;
glue.stretch_order = stretch.order;
}
if scan_keyword(stream, "minus")? {
let shrink = scan_dimension_with_units(stream, true, unit_system)?;
glue.shrink = shrink.value;
glue.shrink_order = shrink.order;
}
Ok(glue)
}
fn scan_glue_expression<S: DimensionTokenStream>(
stream: &mut S,
stop_at_right_parenthesis: bool,
unit_system: UnitSystem,
) -> Result<TeXGlue, DimensionScanError<S::Token, S::Error>> {
let mut glue = scan_glue_term(stream, unit_system)?;
loop {
let Some(token) = next_non_space_token(stream)? else {
if stop_at_right_parenthesis {
return Err(DimensionScanError::InvalidExpression(None));
}
return Ok(glue);
};
if let Some((operator, EngineCatCode::Other)) = stream.character(&token) {
match operator {
'+' | '-' => {
let right = scan_glue_term(stream, unit_system)?;
glue = combine_glue(glue, right, operator == '-').ok_or_else(|| {
DimensionScanError::TooLarge {
token: Some(token),
negative: glue.width.0 < 0,
}
})?;
continue;
}
')' if stop_at_right_parenthesis => {
stream.back_token(token);
return Ok(glue);
}
_ => {}
}
} else if stream.control_sequence_name(&token).as_deref() == Some("relax") {
if stop_at_right_parenthesis {
return Err(DimensionScanError::InvalidExpression(Some(token)));
}
return Ok(glue);
}
stream.back_token(token);
return Ok(glue);
}
}
fn scan_glue_term<S: DimensionTokenStream>(
stream: &mut S,
unit_system: UnitSystem,
) -> Result<TeXGlue, DimensionScanError<S::Token, S::Error>> {
let mut glue = scan_glue_factor(stream, unit_system)?;
loop {
let Some(token) = next_non_space_token(stream)? else {
return Ok(glue);
};
let Some((operator, EngineCatCode::Other)) = stream.character(&token) else {
stream.back_token(token);
return Ok(glue);
};
if !matches!(operator, '*' | '/') {
stream.back_token(token);
return Ok(glue);
}
let factor = scan_integer(stream)?;
if operator == '*' {
if let Some(next) = next_non_space_token(stream)? {
if matches!(stream.character(&next), Some(('/', EngineCatCode::Other))) {
let denominator = scan_integer(stream)?;
glue = scale_glue(glue, factor, denominator)
.ok_or_else(|| DimensionScanError::InvalidExpression(Some(next)))?;
continue;
}
stream.back_token(next);
}
}
glue = if operator == '*' {
scale_glue(glue, factor, 1)
} else {
scale_glue(glue, 1, factor)
}
.ok_or_else(|| DimensionScanError::InvalidExpression(Some(token)))?;
}
}
fn scan_glue_factor<S: DimensionTokenStream>(
stream: &mut S,
unit_system: UnitSystem,
) -> Result<TeXGlue, DimensionScanError<S::Token, S::Error>> {
let (negative, first) = scan_signs(stream)?;
if matches!(stream.character(&first), Some(('(', EngineCatCode::Other))) {
let mut glue = scan_glue_expression(stream, true, unit_system)?;
let closing = next_non_space_token(stream)?;
if !closing.as_ref().is_some_and(|token| {
matches!(stream.character(token), Some((')', EngineCatCode::Other)))
}) {
return Err(DimensionScanError::InvalidExpression(closing));
}
if negative {
glue = scale_glue(glue, -1, 1)
.ok_or_else(|| DimensionScanError::InvalidExpression(None))?;
}
return Ok(glue);
}
scan_glue_from_first(stream, negative, first, unit_system)
}
fn combine_glue(left: TeXGlue, right: TeXGlue, subtract: bool) -> Option<TeXGlue> {
let width = checked_dimension_sum(left.width, right.width, subtract)?;
let (stretch, stretch_order) = combine_glue_component(
left.stretch,
left.stretch_order,
right.stretch,
right.stretch_order,
subtract,
)?;
let (shrink, shrink_order) = combine_glue_component(
left.shrink,
left.shrink_order,
right.shrink,
right.shrink_order,
subtract,
)?;
Some(TeXGlue {
width,
stretch,
stretch_order: if stretch.is_zero() {
TeXGlueOrder::Normal
} else {
stretch_order
},
shrink,
shrink_order: if shrink.is_zero() {
TeXGlueOrder::Normal
} else {
shrink_order
},
})
}
fn combine_glue_component(
left: Scaled,
left_order: TeXGlueOrder,
right: Scaled,
right_order: TeXGlueOrder,
subtract: bool,
) -> Option<(Scaled, TeXGlueOrder)> {
if left_order == right_order {
let value = checked_dimension_sum(left, right, subtract)?;
return Some((value, left_order));
}
// Glue keeps only the nonzero component with the higher infinity order.
if left_order.index() < right_order.index() && !right.is_zero() {
return Some((right, right_order));
}
Some((left, left_order))
}
fn scale_glue(glue: TeXGlue, numerator: i32, denominator: i32) -> Option<TeXGlue> {
let stretch = checked_dimension_scale(glue.stretch, numerator, denominator)?;
let shrink = checked_dimension_scale(glue.shrink, numerator, denominator)?;
Some(TeXGlue {
width: checked_dimension_scale(glue.width, numerator, denominator)?,
stretch,
stretch_order: if stretch.is_zero() {
TeXGlueOrder::Normal
} else {
glue.stretch_order
},
shrink,
shrink_order: if shrink.is_zero() {
TeXGlueOrder::Normal
} else {
glue.shrink_order
},
})
}
#[derive(Clone, Copy)]
enum FontMetric {
Em,
Ex,
}
#[derive(Clone, Copy)]
enum DimensionUnit {
Scaled(ScaledUnit),
FontMetric(FontMetric),
Infinite,
}
fn scan_finite_unit<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<(DimensionUnit, bool), DimensionScanError<S::Token, S::Error>> {
if scan_keyword(stream, "em")? {
return Ok((DimensionUnit::FontMetric(FontMetric::Em), false));
}
if scan_keyword(stream, "ex")? {
return Ok((DimensionUnit::FontMetric(FontMetric::Ex), false));
}
let true_unit = scan_keyword(stream, "true")?;
for (keyword, unit) in [
("pt", ScaledUnit::Point),
("in", ScaledUnit::Inch),
("pc", ScaledUnit::Pica),
("cm", ScaledUnit::Centimeter),
("mm", ScaledUnit::Millimeter),
("bp", ScaledUnit::BigPoint),
("dd", ScaledUnit::DidotPoint),
("cc", ScaledUnit::Cicero),
("sp", ScaledUnit::ScaledPoint),
] {
if scan_keyword(stream, keyword)? {
return Ok((DimensionUnit::Scaled(unit), true_unit));
}
}
if true_unit {
return Err(DimensionScanError::IllegalUnit(next_token(stream)?));
}
Err(DimensionScanError::IllegalUnit(next_token(stream)?))
}
fn scan_math_unit<S: DimensionTokenStream>(
stream: &mut S,
allow_infinite: bool,
order: &mut TeXGlueOrder,
) -> Result<(DimensionUnit, bool), DimensionScanError<S::Token, S::Error>> {
if allow_infinite && scan_keyword(stream, "fil")? {
*order = TeXGlueOrder::Fil;
while scan_keyword(stream, "l")? {
*order = match *order {
TeXGlueOrder::Fil => TeXGlueOrder::Fill,
TeXGlueOrder::Fill => TeXGlueOrder::Filll,
TeXGlueOrder::Filll => {
return Err(DimensionScanError::IllegalUnit(next_token(stream)?));
}
TeXGlueOrder::Normal => unreachable!(),
};
}
return Ok((DimensionUnit::Infinite, false));
}
if scan_keyword(stream, "mu")? {
Ok((DimensionUnit::Scaled(ScaledUnit::Point), false))
} else {
Err(DimensionScanError::IllegalUnit(next_token(stream)?))
}
}
fn scan_signs<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<(bool, S::Token), DimensionScanError<S::Token, S::Error>> {
let mut negative = false;
loop {
let Some(token) = next_token(stream)? else {
return Err(DimensionScanError::MissingNumber(None));
};
if stream.is_space(&token) {
continue;
}
if let Some((character, EngineCatCode::Other)) = stream.character(&token) {
match character {
'+' => continue,
'-' => {
negative = !negative;
continue;
}
_ => return Ok((negative, token)),
}
}
return Ok((negative, token));
}
}
fn scan_number<S: DimensionTokenStream>(
stream: &mut S,
first: S::Token,
negative: bool,
) -> Result<(i32, Scaled, S::Token), DimensionScanError<S::Token, S::Error>> {
let Some((first_character, EngineCatCode::Other)) = stream.character(&first) else {
if stream.is_command_reference(&first) {
return Err(DimensionScanError::CompatibilityRequired);
}
stream.back_token(first.clone());
return Err(DimensionScanError::MissingNumber(Some(first)));
};
let radix = match first_character {
'\'' => 8,
'"' => 16,
'`' => return Err(DimensionScanError::CompatibilityRequired),
_ => 10,
};
if radix != 10 {
let integer = scan_radix_integer(stream, first.clone(), radix, negative)?;
return Ok((integer, Scaled::ZERO, first));
}
let mut integer = 0_u64;
let mut digit_count = 0_usize;
let mut next = Some(first.clone());
let mut point = false;
while let Some(token) = next.take() {
match digit(stream, &token) {
Some(digit) => {
integer = integer
.checked_mul(10)
.and_then(|value| value.checked_add(u64::from(digit)))
.ok_or_else(|| DimensionScanError::TooLarge {
token: Some(first.clone()),
negative,
})?;
digit_count += 1;
}
None if matches!(
stream.character(&token),
Some(('.', EngineCatCode::Other) | (',', EngineCatCode::Other))
) && !point =>
{
point = true;
break;
}
None => {
stream.back_token(token);
break;
}
}
next = next_token(stream)?;
}
let mut fractional = Scaled::ZERO;
if point {
fractional = scan_fraction(stream)?;
}
if digit_count == 0 && !point {
return Err(DimensionScanError::MissingNumber(Some(first)));
}
if integer > i32::MAX as u64 {
return Err(DimensionScanError::TooLarge {
token: Some(first),
negative,
});
}
Ok((integer as i32, fractional, first))
}
fn scan_radix_integer<S: DimensionTokenStream>(
stream: &mut S,
first: S::Token,
radix: u8,
negative: bool,
) -> Result<i32, DimensionScanError<S::Token, S::Error>> {
let mut value = 0_u64;
let mut digit_count = 0;
loop {
let Some(token) = next_token(stream)? else {
break;
};
let digit = match stream.character(&token) {
Some((character, EngineCatCode::Other | EngineCatCode::Letter)) => {
character.to_digit(u32::from(radix))
}
_ => None,
};
let Some(digit) = digit else {
stream.back_token(token);
break;
};
value = value
.checked_mul(u64::from(radix))
.and_then(|value| value.checked_add(u64::from(digit)))
.ok_or_else(|| DimensionScanError::TooLarge {
token: Some(first.clone()),
negative,
})?;
digit_count += 1;
}
if digit_count == 0 || value > i32::MAX as u64 {
return Err(DimensionScanError::TooLarge {
token: Some(first),
negative,
});
}
Ok(value as i32)
}
fn scan_fraction<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<Scaled, DimensionScanError<S::Token, S::Error>> {
let mut digits = [0_u8; 17];
let mut count = 0;
loop {
let Some(token) = next_token(stream)? else {
break;
};
match digit(stream, &token) {
Some(digit) => {
if count < digits.len() {
digits[count] = digit;
count += 1;
}
}
None if stream.is_command_reference(&token) => {
return Err(DimensionScanError::CompatibilityRequired);
}
None => {
stream.back_token(token);
break;
}
}
}
Ok(Scaled::from_decimal_digits(&digits[..count]))
}
fn digit<S: DimensionTokenStream>(stream: &S, token: &S::Token) -> Option<u8> {
match stream.character(token) {
Some((character, EngineCatCode::Other)) => character.to_digit(10).map(|d| d as u8),
_ => None,
}
}
fn scan_keyword<S: DimensionTokenStream>(
stream: &mut S,
keyword: &str,
) -> Result<bool, DimensionScanError<S::Token, S::Error>> {
let mut matched = Vec::new();
for expected in keyword.chars() {
let Some(token) = next_token(stream)? else {
for token in matched.into_iter().rev() {
stream.back_token(token);
}
return Ok(false);
};
if let Some((character, EngineCatCode::Letter)) = stream.character(&token) {
if character.eq_ignore_ascii_case(&expected) {
matched.push(token);
continue;
}
}
if stream.is_command_reference(&token) {
if stream.control_sequence_name(&token).as_deref() == Some("relax") {
stream.back_token(token);
for token in matched.into_iter().rev() {
stream.back_token(token);
}
return Ok(false);
}
return Err(DimensionScanError::CompatibilityRequired);
}
stream.back_token(token);
for token in matched.into_iter().rev() {
stream.back_token(token);
}
return Ok(false);
}
Ok(true)
}
fn consume_optional_space<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<(), DimensionScanError<S::Token, S::Error>> {
if let Some(token) = next_token(stream)? {
if !stream.is_space(&token) {
stream.back_token(token);
}
}
Ok(())
}
fn next_token<S: DimensionTokenStream>(
stream: &mut S,
) -> Result<Option<S::Token>, DimensionScanError<S::Token, S::Error>> {
stream.next_token().map_err(DimensionScanError::Stream)
}
+1
View File
@@ -0,0 +1 @@
pub(crate) use texrra_core::environment::EnvironmentStack;
+1
View File
@@ -0,0 +1 @@
pub(crate) use texrra_core::expansion::*;
+1
View File
@@ -0,0 +1 @@
pub(crate) use texrra_core::glue::{TeXGlue, TeXGlueOrder};
+3
View File
@@ -0,0 +1,3 @@
pub(crate) use texrra_core::input::{
FileNameTokenStream, InputFrame, InputId, InputStack, scan_file_location,
};
@@ -0,0 +1,3 @@
pub(crate) use texrra_core::layout_primitive::{
LayoutEffect, LayoutPrimitive, LayoutPrimitiveInput, execute,
};
+1
View File
@@ -0,0 +1 @@
pub(crate) use texrra_core::macros::*;
+1
View File
@@ -0,0 +1 @@
pub(crate) use texrra_core::math_code::{MathCodeTable, UnicodeMathCode};
+18
View File
@@ -0,0 +1,18 @@
pub(super) mod arithmetic;
pub(super) mod assignment_scope;
pub(super) mod command;
pub(super) mod dimension;
pub(super) mod environment;
pub(super) mod expansion;
pub(super) mod glue;
pub(super) mod input;
pub(super) mod layout_primitive;
pub(super) mod macros;
pub(super) mod math_code;
pub(super) mod mouth;
pub(super) mod prefix;
pub(super) mod registers;
pub(super) mod state;
pub(super) mod texlang_dimension_adapter;
pub(super) mod token;
pub(super) mod variable;
+1
View File
@@ -0,0 +1 @@
pub(crate) use texrra_core::mouth::{CatCodeTable, Mouth, Token};
+176
View File
@@ -0,0 +1,176 @@
use texlang::{
command::{Command, StaticTag, Tag},
error,
token::{self, Token},
traits::TexlangState,
vm::{self, TokenStream},
};
static GLOBAL_TAG: StaticTag = StaticTag::new();
static LONG_TAG: StaticTag = StaticTag::new();
static OUTER_TAG: StaticTag = StaticTag::new();
static RELAX_TAG: StaticTag = StaticTag::new();
static GLOBAL_ASSIGNMENT_TAG: StaticTag = StaticTag::new();
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum PrefixKind {
Global,
Long,
Outer,
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct PrefixFlags {
pub(crate) global: bool,
pub(crate) long: bool,
pub(crate) outer: bool,
}
#[derive(Default)]
struct Prefixes {
global: Option<Token>,
long: Option<Token>,
outer: Option<Token>,
}
impl Prefixes {
fn add(&mut self, kind: PrefixKind, token: Token) {
let slot = match kind {
PrefixKind::Global => &mut self.global,
PrefixKind::Long => &mut self.long,
PrefixKind::Outer => &mut self.outer,
};
slot.get_or_insert(token);
}
fn first_token(&self) -> Token {
self.global
.or(self.long)
.or(self.outer)
.expect("prefix scan starts with a prefix")
}
fn error_token(&self) -> Token {
self.long
.or(self.outer)
.or(self.global)
.unwrap_or_else(|| self.first_token())
}
fn flags(&self) -> PrefixFlags {
PrefixFlags {
global: self.global.is_some(),
long: self.long.is_some(),
outer: self.outer.is_some(),
}
}
}
pub(crate) fn global_tag() -> Tag {
GLOBAL_TAG.get()
}
pub(crate) fn long_tag() -> Tag {
LONG_TAG.get()
}
pub(crate) fn outer_tag() -> Tag {
OUTER_TAG.get()
}
pub(crate) fn relax_tag() -> Tag {
RELAX_TAG.get()
}
pub(crate) fn global_assignment_tag() -> Tag {
GLOBAL_ASSIGNMENT_TAG.get()
}
pub(crate) fn process_prefixes<S: TexlangState>(
kind: PrefixKind,
token: Token,
input: &mut vm::ExecutionInput<S>,
) -> texlang::prelude::Result<PrefixFlags> {
let mut prefixes = Prefixes::default();
prefixes.add(kind, token);
loop {
let Some(next) = input.next()? else {
return Err(input.fatal_error(error::SimpleTokenError::new(
prefixes.first_token(),
"prefix command must be followed by an assignable command",
)));
};
if matches!(next.value(), token::Value::Space(_)) {
continue;
}
if let token::Value::CommandRef(command_ref) = next.value() {
let tag = input.vm().commands_map.get_tag(&command_ref);
if tag == Some(relax_tag()) {
continue;
}
let prefix_kind = if tag == Some(global_tag()) {
Some(PrefixKind::Global)
} else if tag == Some(long_tag()) {
Some(PrefixKind::Long)
} else if tag == Some(outer_tag()) {
Some(PrefixKind::Outer)
} else {
None
};
if let Some(prefix_kind) = prefix_kind {
prefixes.add(prefix_kind, next);
continue;
}
let command = input.vm().commands_map.get_command(&command_ref);
let target_tag = input.vm().commands_map.get_tag(&command_ref);
let is_definition = target_tag == Some(texlang_stdlib::def::def_tag());
let is_global_only = matches!(command, Some(Command::Variable(_) | Command::Font(_)))
|| target_tag.is_some_and(super::arithmetic::is_arithmetic_tag)
|| target_tag.is_some_and(|tag| {
[
texlang_stdlib::alias::let_tag(),
texlang_stdlib::registers::countdef_tag(),
global_assignment_tag(),
]
.contains(&tag)
});
if is_definition {
input.back(next);
return Ok(prefixes.flags());
}
if is_global_only && prefixes.global.is_some() {
if prefixes.long.is_some() || prefixes.outer.is_some() {
input.back(next);
return Err(input.fatal_error(error::SimpleTokenError::new(
prefixes.error_token(),
"\\long and \\outer can only prefix macro definitions",
)));
}
input.back(next);
return Ok(PrefixFlags {
global: true,
..PrefixFlags::default()
});
}
} else {
input.back(next);
}
let message = if prefixes.long.is_some() || prefixes.outer.is_some() {
"\\long and \\outer can only prefix macro definitions"
} else if prefixes.global.is_some() {
"\\global must prefix an assignable command"
} else {
"prefix command must be followed by a valid command"
};
return Err(input.fatal_error(error::SimpleTokenError::new(
prefixes.error_token(),
message,
)));
}
}
+63
View File
@@ -0,0 +1,63 @@
use std::collections::HashMap;
/// Sparse TeX register values with local/global group assignment semantics.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct RegisterTable<T> {
values: HashMap<usize, T>,
zero: T,
groups: Vec<HashMap<usize, Option<T>>>,
}
impl<T: Clone + Default> Default for RegisterTable<T> {
fn default() -> Self {
Self {
values: HashMap::new(),
zero: T::default(),
groups: Vec::new(),
}
}
}
impl<T: Clone> RegisterTable<T> {
pub(crate) fn get_index_ref(&self, index: usize) -> &T {
self.values.get(&index).unwrap_or(&self.zero)
}
pub(crate) fn get_index_mut_ref(&mut self, index: usize) -> &mut T
where
T: Default,
{
self.values.entry(index).or_default()
}
pub(crate) fn prepare_assignment(&mut self, index: usize, global: bool) {
if global {
for group in &mut self.groups {
group.remove(&index);
}
} else if let Some(group) = self.groups.last_mut() {
let previous = self.values.get(&index).cloned();
group.entry(index).or_insert(previous);
}
}
pub(crate) fn begin_group(&mut self) {
self.groups.push(HashMap::new());
}
pub(crate) fn end_group(&mut self) {
let Some(group) = self.groups.pop() else {
return;
};
for (index, value) in group {
match value {
Some(value) => {
self.values.insert(index, value);
}
None => {
self.values.remove(&index);
}
}
}
}
}
+96
View File
@@ -0,0 +1,96 @@
use std::ops::{Deref, DerefMut};
use super::{input::InputStack, registers::RegisterTable};
use texrra_core::state::EngineSemanticState;
/// TeX's `\\mag` parameter, stored as a ratio with 1000 meaning 1:1.
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub(crate) struct Magnification(i32);
impl Magnification {
pub(crate) fn value(&self) -> i32 {
self.0
}
pub(crate) fn reference(&self) -> &i32 {
&self.0
}
pub(crate) fn reference_mut(&mut self) -> &mut i32 {
&mut self.0
}
}
impl Default for Magnification {
fn default() -> Self {
Self(1000)
}
}
/// Runtime state for the current adapter around the Rust-owned TeX state.
///
/// Registers that still use Texlang value types and source I/O remain in this
/// application layer. Field access to engine semantics forwards to the core.
#[derive(serde::Serialize, serde::Deserialize, Default)]
pub(crate) struct TeXEngineState {
#[serde(default, flatten)]
semantic: EngineSemanticState,
pub(crate) count_registers: RegisterTable<i32>,
pub(crate) dimen_registers: RegisterTable<common::Scaled>,
pub(crate) skip_registers: RegisterTable<common::Glue>,
pub(crate) muskip_registers: RegisterTable<texlang::types::MuGlue>,
pub(crate) token_registers: RegisterTable<Vec<texlang::token::Token>>,
#[serde(default)]
pub(crate) magnification: Magnification,
/// Next free index for registers allocated by `\newlength` and friends.
///
/// The register tables are sparse, so allocation only needs to hand out
/// unused indices. Starting above the fixed compatibility registers keeps
/// style files and document-level allocations from colliding.
#[serde(default)]
pub(crate) next_skip_register: usize,
#[serde(skip)]
pub(crate) inputs: InputStack,
}
impl Deref for TeXEngineState {
type Target = EngineSemanticState;
fn deref(&self) -> &Self::Target {
&self.semantic
}
}
impl DerefMut for TeXEngineState {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.semantic
}
}
impl TeXEngineState {
pub(crate) fn begin_group(&mut self) {
self.semantic.begin_group();
self.count_registers.begin_group();
self.dimen_registers.begin_group();
self.skip_registers.begin_group();
self.muskip_registers.begin_group();
self.token_registers.begin_group();
}
pub(crate) fn allocate_skip_register(&mut self) -> usize {
const FIRST_ALLOCATED_SKIP: usize = 1_000;
let index = self.next_skip_register.max(FIRST_ALLOCATED_SKIP);
self.next_skip_register = index + 1;
index
}
pub(crate) fn end_group(&mut self) {
self.semantic.end_group();
self.count_registers.end_group();
self.dimen_registers.end_group();
self.skip_registers.end_group();
self.muskip_registers.end_group();
self.token_registers.end_group();
}
}
@@ -0,0 +1,438 @@
//! Temporary bridge from Texlang token streams to the Rust numeric scanners.
use texlang::{
token,
traits::TexlangState,
types::MuGlue,
variable::SupportedType,
vm::{self, TokenStream},
};
use texrra_core::{CatCode, MathCode, integer::IntegerTokenStream};
use super::{
dimension::{
self, DimensionScanError, DimensionTokenStream, InternalMathDimension, ScannedInteger,
},
glue::TeXGlue,
token::EngineCatCode,
};
pub(crate) struct TexlangDimensionTokenStream<'a, S: TexlangState> {
input: &'a mut vm::ExpandedStream<S>,
consumed: Vec<token::Token>,
}
impl<'a, S: TexlangState> TexlangDimensionTokenStream<'a, S> {
pub(crate) fn new(input: &'a mut vm::ExpandedStream<S>) -> Self {
Self {
input,
consumed: Vec::new(),
}
}
pub(crate) fn rollback(&mut self) {
for token in self.consumed.drain(..).rev() {
self.input.back(token);
}
}
fn variable_value<T>(&mut self, token: token::Token) -> Result<Option<T>, vm::ShutdownSignal>
where
T: SupportedType + Copy,
{
let token::Value::CommandRef(command_ref) = token.value() else {
return Ok(None);
};
let Some(texlang::command::Command::Variable(command)) = self
.input
.vm()
.commands_map
.get_command(&command_ref)
.cloned()
else {
return Ok(None);
};
let Some(variable) = command.resolve_type::<T>(token, self.input)? else {
return Ok(None);
};
Ok(Some(*variable.get(self.input.state())))
}
}
impl<S: TexlangState> IntegerTokenStream for TexlangDimensionTokenStream<'_, S> {
type Token = token::Token;
type Error = vm::ShutdownSignal;
fn next_token(&mut self) -> Result<Option<Self::Token>, Self::Error> {
let token = self.input.next()?;
if let Some(token) = token {
self.consumed.push(token);
Ok(Some(token))
} else {
Ok(None)
}
}
fn back_token(&mut self, token: Self::Token) {
if self.consumed.last() == Some(&token) {
self.consumed.pop();
}
self.input.back(token);
}
fn character(&self, token: &Self::Token) -> Option<(char, EngineCatCode)> {
token.value().char_and_cat_code()
}
fn is_space(&self, token: &Self::Token) -> bool {
matches!(token.value(), token::Value::Space(_))
}
fn is_command_reference(&self, token: &Self::Token) -> bool {
matches!(token.value(), token::Value::CommandRef(_))
}
fn control_sequence_name(&self, token: &Self::Token) -> Option<String> {
let token::Value::CommandRef(token::CommandRef::ControlSequence(name)) = token.value()
else {
return None;
};
self.input
.vm()
.cs_name_interner()
.resolve(name)
.map(str::to_owned)
}
fn scan_internal_integer(&mut self, token: Self::Token) -> Result<Option<i32>, Self::Error> {
if let Some(value) = self.variable_value::<i32>(token.clone())? {
return Ok(Some(value));
}
if let Some(value) = self.variable_value::<u8>(token.clone())? {
return Ok(Some(i32::from(value)));
}
if let Some(value) = self.variable_value::<CatCode>(token.clone())? {
return Ok(Some(value as i32));
}
if let Some(value) = self.variable_value::<MathCode>(token.clone())? {
return Ok(Some(value.0 as i32));
}
if let Some(value) = self.variable_value::<common::Scaled>(token.clone())? {
return Ok(Some(value.0));
}
if let Some(value) = self.variable_value::<common::Glue>(token.clone())? {
return Ok(Some(value.width.0));
}
if let Some(value) = self.variable_value::<MuGlue>(token.clone())? {
return Ok(Some(value.0.width.0));
}
Ok(None)
}
}
impl<S: TexlangState> DimensionTokenStream for TexlangDimensionTokenStream<'_, S> {
fn scan_internal_dimension(
&mut self,
token: Self::Token,
) -> Result<Option<common::Scaled>, Self::Error> {
if let Some(value) = self.variable_value::<common::Scaled>(token.clone())? {
return Ok(Some(value));
}
if let Some(value) = self.variable_value::<common::Glue>(token.clone())? {
return Ok(Some(value.width));
}
if let Some(value) = self.variable_value::<i32>(token.clone())? {
return Ok(Some(common::Scaled(value)));
}
Ok(None)
}
fn scan_internal_glue(&mut self, token: Self::Token) -> Result<Option<TeXGlue>, Self::Error> {
if let Some(value) = self.variable_value::<common::Glue>(token.clone())? {
return Ok(Some(TeXGlue::from(value)));
}
Ok(None)
}
fn scan_internal_math_glue(
&mut self,
token: Self::Token,
) -> Result<Option<TeXGlue>, Self::Error> {
if let Some(value) = self.variable_value::<MuGlue>(token.clone())? {
return Ok(Some(TeXGlue::from(value.0)));
}
Ok(None)
}
fn scan_internal_math_dimension(
&mut self,
token: Self::Token,
) -> Result<Option<InternalMathDimension>, Self::Error> {
if let Some(value) = self.variable_value::<MuGlue>(token.clone())? {
return Ok(Some(InternalMathDimension::GlueWidth(value.0.width)));
}
if let Some(value) = self.variable_value::<i32>(token.clone())? {
return Ok(Some(InternalMathDimension::Integer(value)));
}
if let Some(value) = self.variable_value::<u8>(token.clone())? {
return Ok(Some(InternalMathDimension::Integer(i32::from(value))));
}
if let Some(value) = self.variable_value::<CatCode>(token.clone())? {
return Ok(Some(InternalMathDimension::Integer(value as i32)));
}
if let Some(value) = self.variable_value::<MathCode>(token.clone())? {
return Ok(Some(InternalMathDimension::Integer(value.0 as i32)));
}
Ok(None)
}
fn em_width(&self) -> common::Scaled {
self.input.state().em_width()
}
fn ex_height(&self) -> common::Scaled {
self.input.state().ex_height()
}
fn magnification_ratio(&self) -> i32 {
self.input.state().magnification_ratio()
}
}
pub(crate) fn scan_integer_with_token<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
) -> Result<ScannedInteger<token::Token>, DimensionScanError<token::Token, vm::ShutdownSignal>> {
let mut stream = TexlangDimensionTokenStream::new(input);
let result = dimension::scan_integer_with_token(&mut stream);
if matches!(result, Err(DimensionScanError::CompatibilityRequired)) {
stream.rollback();
}
result
}
pub(crate) fn try_scan_integer<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
) -> texlang::prelude::Result<Option<i32>> {
let result = {
let mut stream = TexlangDimensionTokenStream::new(input);
let result = dimension::scan_integer(&mut stream);
if matches!(result, Err(DimensionScanError::CompatibilityRequired)) {
stream.rollback();
}
result
};
match result {
Ok(value) => Ok(Some(value)),
Err(DimensionScanError::Stream(signal)) => Err(signal),
Err(DimensionScanError::CompatibilityRequired) => Ok(None),
Err(error) => recover_integer_error(input, error).map(Some),
}
}
pub(crate) fn try_scan_dimension<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
) -> texlang::prelude::Result<Option<common::Scaled>> {
let result = {
let mut stream = TexlangDimensionTokenStream::new(input);
let result = dimension::scan_dimension(&mut stream, false);
if matches!(
result,
Err(DimensionScanError::CompatibilityRequired | DimensionScanError::IllegalUnit(_))
) {
stream.rollback();
}
result
};
match result {
Ok(dimension) => Ok(Some(dimension.value)),
Err(DimensionScanError::Stream(signal)) => Err(signal),
Err(DimensionScanError::CompatibilityRequired) => Ok(None),
Err(DimensionScanError::IllegalUnit(_)) => Ok(None),
Err(error) => recover_dimension_error(input, error).map(Some),
}
}
pub(crate) fn try_scan_glue<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
) -> texlang::prelude::Result<Option<common::Glue>> {
let result = {
let mut stream = TexlangDimensionTokenStream::new(input);
let result = dimension::scan_glue(&mut stream);
if matches!(
result,
Err(DimensionScanError::CompatibilityRequired | DimensionScanError::IllegalUnit(_))
) {
stream.rollback();
}
result
};
match result {
Ok(glue) => Ok(Some(glue.into())),
Err(DimensionScanError::Stream(signal)) => Err(signal),
Err(DimensionScanError::CompatibilityRequired) => Ok(None),
Err(DimensionScanError::IllegalUnit(_)) => Ok(None),
Err(error) => recover_dimension_error(input, error).map(|width| {
Some(common::Glue {
width,
..common::Glue::default()
})
}),
}
}
fn recover_integer_error<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
error: DimensionScanError<token::Token, vm::ShutdownSignal>,
) -> texlang::prelude::Result<i32> {
match error {
DimensionScanError::Stream(signal) => Err(signal),
DimensionScanError::CompatibilityRequired => unreachable!(),
DimensionScanError::MissingNumber(token)
| DimensionScanError::IllegalUnit(token)
| DimensionScanError::InvalidExpression(token) => {
input.error(texlang::parse::Error::new(
"an integer",
token,
"expected a TeX integer",
))?;
Ok(0)
}
DimensionScanError::TooLarge { token, .. } => {
input.error(
texlang::parse::Error::new(
"an integer in range",
token,
"the integer is too large",
)
.with_got_override("an integer that is too large"),
)?;
Ok(0)
}
}
}
pub(crate) fn try_scan_math_glue<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
) -> texlang::prelude::Result<Option<MuGlue>> {
let result = {
let mut stream = TexlangDimensionTokenStream::new(input);
let result = dimension::scan_math_glue(&mut stream);
if matches!(
result,
Err(DimensionScanError::CompatibilityRequired | DimensionScanError::IllegalUnit(_))
) {
stream.rollback();
}
result
};
match result {
Ok(glue) => Ok(Some(MuGlue(glue.into()))),
Err(DimensionScanError::Stream(signal)) => Err(signal),
Err(DimensionScanError::CompatibilityRequired) => Ok(None),
Err(DimensionScanError::IllegalUnit(_)) => Ok(None),
Err(error) => recover_math_glue_error(input, error).map(|width| {
Some(MuGlue(common::Glue {
width,
..common::Glue::default()
}))
}),
}
}
fn recover_math_glue_error<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
error: DimensionScanError<token::Token, vm::ShutdownSignal>,
) -> texlang::prelude::Result<common::Scaled> {
match error {
DimensionScanError::Stream(signal) => Err(signal),
DimensionScanError::CompatibilityRequired => unreachable!(),
DimensionScanError::MissingNumber(token) => {
input.error(texlang::parse::Error::new(
"the beginning of a math glue value",
token,
"a math glue value starts with a number, a math glue variable, or \\\\muexpr",
))?;
Ok(common::Scaled::ZERO)
}
DimensionScanError::IllegalUnit(token) => {
input.error(texlang::parse::Error::new(
"a math unit (mu)",
token,
"math glue values use mu units; stretch and shrink may also use fil, fill, or filll",
))?;
Ok(common::Scaled::ZERO)
}
DimensionScanError::InvalidExpression(token) => {
input.error(texlang::parse::Error::new(
"a valid math glue expression",
token,
"check the operators, parentheses, units, and arithmetic range in \\\\muexpr",
))?;
Ok(common::Scaled::ZERO)
}
DimensionScanError::TooLarge { token, negative } => {
input.error(
texlang::parse::Error::new(
"math glue in TeX's supported range",
token,
"the math glue value is too large",
)
.with_got_override("math glue that's too large"),
)?;
Ok(if negative {
-common::Scaled::MAX_DIMEN
} else {
common::Scaled::MAX_DIMEN
})
}
}
}
fn recover_dimension_error<S: TexlangState>(
input: &mut vm::ExpandedStream<S>,
error: DimensionScanError<token::Token, vm::ShutdownSignal>,
) -> texlang::prelude::Result<common::Scaled> {
match error {
DimensionScanError::Stream(signal) => Err(signal),
DimensionScanError::CompatibilityRequired => unreachable!(),
DimensionScanError::MissingNumber(token) => {
input.error(texlang::parse::Error::new(
"the beginning of a dimension",
token,
"a dimension starts with a number or a dimension variable",
))?;
Ok(common::Scaled::ZERO)
}
DimensionScanError::IllegalUnit(token) => {
input.error(texlang::parse::Error::new(
"a unit of measure",
token,
"dimensions can use pt, in, pc, cm, mm, bp, dd, cc, sp, em, or ex",
))?;
Ok(common::Scaled::ZERO)
}
DimensionScanError::InvalidExpression(token) => {
input.error(texlang::parse::Error::new(
"a valid dimension expression",
token,
"check the operators, parentheses, and arithmetic range in the expression",
))?;
Ok(common::Scaled::ZERO)
}
DimensionScanError::TooLarge { token, negative } => {
input.error(
texlang::parse::Error::new(
"a dimension in the range (-2^14pt, 2^14pt)",
token,
"the dimension is too large",
)
.with_got_override("a dimension that's too large"),
)?;
Ok(if negative {
-common::Scaled::MAX_DIMEN
} else {
common::Scaled::MAX_DIMEN
})
}
}
}
+2
View File
@@ -0,0 +1,2 @@
pub(crate) use texrra_core::CatCode as EngineCatCode;
pub(crate) use texrra_core::{EngineCommandName, EngineToken, EngineTokenValue};
+62
View File
@@ -0,0 +1,62 @@
//! Arithmetic variable assignment semantics owned by the Rust engine.
use texcraft_stdext::collections::groupingmap;
use texlang::{
error,
parse::{OptionalEquals, Parsable},
token,
traits::TexlangState,
variable::{self, SupportedType, TypedVariable},
vm,
};
pub(crate) fn assign_arithmetic<S: TexlangState>(
command: &variable::Command<S>,
token: token::Token,
input: &mut vm::ExecutionInput<S>,
scope: groupingmap::Scope,
) -> Option<texlang::prelude::Result<()>> {
if !command.is_arithmetic() {
return None;
}
Some(assign(command, token, input, scope))
}
fn assign<S: TexlangState>(
command: &variable::Command<S>,
token: token::Token,
input: &mut vm::ExecutionInput<S>,
scope: groupingmap::Scope,
) -> texlang::prelude::Result<()> {
let variable = command.resolve(token, input.as_mut())?;
input.with_operation(
token,
error::OperationKind::VariableAssignment,
|input| match variable {
variable::Variable::Int(variable) => assign_value(variable, input, scope),
variable::Variable::SmallInt(variable) => assign_value(variable, input, scope),
variable::Variable::Dimen(variable) => assign_value(variable, input, scope),
variable::Variable::Glue(variable) => assign_value(variable, input, scope),
variable::Variable::MuGlue(variable) => assign_value(variable, input, scope),
variable::Variable::CatCode(_)
| variable::Variable::MathCode(_)
| variable::Variable::TokenList(_)
| variable::Variable::Font(_) => unreachable!("non-arithmetic variable dispatched"),
},
)
}
fn assign_value<S, T>(
variable: TypedVariable<S, T>,
input: &mut vm::ExecutionInput<S>,
scope: groupingmap::Scope,
) -> texlang::prelude::Result<()>
where
S: TexlangState,
T: SupportedType,
{
let (_, value) = <(OptionalEquals, T)>::parse(input)?;
variable.set(input, scope, value);
Ok(())
}
+831
View File
@@ -0,0 +1,831 @@
use std::{
collections::hash_map::DefaultHasher,
env,
ffi::OsString,
fs,
hash::{Hash, Hasher},
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
use super::{read_control_sequence, source_directory, tex_expansion};
pub(super) use texrra_core::math_lowering::MathParseCache;
const PRELUDE: &str = r#"
\def\makeatletter{\catcode64=11\relax}
\def\makeatother{\catcode64=12\relax}
\def\bgroup{\begingroup}
\def\egroup{\endgroup}
\def\geometry#1{\texrrageometry{#1}}
\def\begin#1{\texrrabegin{#1}}
\def\end#1{\texrraend{#1}}
\def\title#1{\texrrametadatastart{title}#1\texrrametadataend{title}}
\def\author#1{\texrrametadatastart{author}#1\texrrametadataend{author}}
\def\date#1{\texrrametadatastart{date}#1\texrrametadataend{date}}
\def\today{__TEXRRA_TODAY__}
\def\maketitle{\texrramaketitle}
\def\tableofcontents{}
\def\noindent{}
\def\allowbreak{\penalty0}
\def\nobreak{\penalty10000}
\def\centering{}
\def\raggedright{}
\def\raggedleft{}
\def\bibliographystyle#1{}
\def\textbf#1{\texrrastylestart{bold}#1\texrrastyleend{bold}}
\def\emph#1{\texrrastylestart{italic}#1\texrrastyleend{italic}}
\def\textit#1{\texrrastylestart{italic}#1\texrrastyleend{italic}}
\def\mathit#1{\texrramathfontstart{italic}#1\texrramathfontend}
\def\phantom#1{\texrramathphantomstart{both}#1\texrramathphantomend}
\def\hphantom#1{\texrramathphantomstart{horizontal}#1\texrramathphantomend}
\def\vphantom#1{\texrramathphantomstart{vertical}#1\texrramathphantomend}
\def\texttt#1{\texrrastylestart{monospace}#1\texrrastyleend{monospace}}
\def\underline#1{\texrramathaccentstart{underline}#1\texrramathaccentend}
\def\hat#1{\texrramathaccentstart{hat}#1\texrramathaccentend}
\def\widehat#1{\texrramathaccentstart{widehat}#1\texrramathaccentend}
\def\tilde#1{\texrramathaccentstart{tilde}#1\texrramathaccentend}
\def\widetilde#1{\texrramathaccentstart{widetilde}#1\texrramathaccentend}
\def\overbrace#1{\texrramathaccentstart{overbrace}#1\texrramathaccentend}
\def\underbrace#1{\texrramathaccentstart{underbrace}#1\texrramathaccentend}
\def\vec#1{\Umathaccent 0 2 "20D7 {#1}}
\def\overleftarrow#1{\Umathaccent 0 2 "20D6 {#1}}
\def\overrightarrow#1{\Umathaccent 0 2 "20D7 {#1}}
\def\overleftrightarrow#1{\Umathaccent 0 2 "20E1 {#1}}
\def\underleftarrow#1{\Umathaccent bottom 0 2 "20EE {#1}}
\def\underrightarrow#1{\Umathaccent bottom 0 2 "20EF {#1}}
\def\underleftrightarrow#1{\Umathaccent bottom 0 2 "034D {#1}}
\def\xleftarrow#1{\Umathaccent bottom 3 2 "20EE {#1}}
\def\xrightarrow#1{\Umathaccent bottom 3 2 "20EF {#1}}
\def\xleftrightarrow#1{\Umathaccent bottom 3 2 "034D {#1}}
\def\text#1{\texrramathfontstart{text}#1\texrramathfontend}
\def\item{\texrraitem}
\def\newpage{\texrrapagebreak}
\def\clearpage{\texrrapagebreak}
\def\pagebreak{\texrrapagebreak}
\def\label#1{\texrralabel{#1}}
\def\ref#1{\texrraref{#1}}
\def\nonumber{\texrranonumber}
\def\notag{\texrranonumber}
\def\tag{\texrratag}
\def\cite#1{\texrracite{#1}}
\def\citep#1{\texrracite{#1}}
\def\citet#1{\texrracite{#1}}
\def\nocite#1{}
\def\newblock{ }
\def\caption#1{\texrracaptionstart#1\texrracaptionend}
\def\href#1#2{#2}
\def\hline{\texrratablerule}
\def\toprule{\texrratablerule}
\def\midrule{\texrratablerule}
\def\bottomrule{\texrratablerule}
\def\cline#1{\texrratablerule}
\def\multicolumn#1#2#3{#3}
\def\&{\texrraampersand}
\def\LaTeX{LaTeX}
\def\TeX{TeX}
\def\\{\texrrarowbreak}
\def\[{\texrradisplaymathstart}
\def\]{\texrradisplaymathend}
\def\({\texrrainlinemathstart}
\def\){\texrrainlinemathend}
\def\frac#1#2{\texrramathfractionstart{automatic}{rule}{plain}#1\texrramathfractionsep#2\texrramathfractionend}
\def\dfrac#1#2{\texrramathfractionstart{display}{rule}{plain}#1\texrramathfractionsep#2\texrramathfractionend}
\def\tfrac#1#2{\texrramathfractionstart{text}{rule}{plain}#1\texrramathfractionsep#2\texrramathfractionend}
\def\binom#1#2{\texrramathfractionstart{automatic}{no-rule}{parens}#1\texrramathfractionsep#2\texrramathfractionend}
\def\dbinom#1#2{\texrramathfractionstart{display}{no-rule}{parens}#1\texrramathfractionsep#2\texrramathfractionend}
\def\tbinom#1#2{\texrramathfractionstart{text}{no-rule}{parens}#1\texrramathfractionsep#2\texrramathfractionend}
\def\mathrm#1{\texrramathfontstart{roman}#1\texrramathfontend}
\def\mathbf#1{\texrramathfontstart{bold-roman}#1\texrramathfontend}
\def\mathtt#1{\texrramathfontstart{monospace}#1\texrramathfontend}
\def\mathsf#1{\texrramathfontstart{sans-serif}#1\texrramathfontend}
\def\mathcal#1{\texrramathfontstart{calligraphic}#1\texrramathfontend}
\def\mathbb#1{\texrramathfontstart{blackboard}#1\texrramathfontend}
\def\mathfrak#1{\texrramathfontstart{fraktur}#1\texrramathfontend}
\def\boldsymbol#1{\texrramathfontstart{bold}#1\texrramathfontend}
\def\operatorname#1{\texrraoperatorstart#1\texrraoperatorend}
\def\stackrel#1#2{\mathrel{\mathop{#2}\limits^{#1}}}
\def\overset#1#2{\mathop{#2}\limits^{#1}}
\def\underset#1#2{\mathop{#2}\limits_{#1}}
\def\substack#1{\begin{smallmatrix}#1\end{smallmatrix}}
\def\mathord#1{\texrramathclassstart{ordinary}#1\texrramathclassend}
\def\mathop#1{\texrramathclassstart{operator}#1\texrramathclassend}
\def\mathbin#1{\texrramathclassstart{binary}#1\texrramathclassend}
\def\mathrel#1{\texrramathclassstart{relation}#1\texrramathclassend}
\def\mathopen#1{\texrramathclassstart{opening}#1\texrramathclassend}
\def\mathclose#1{\texrramathclassstart{closing}#1\texrramathclassend}
\def\mathpunct#1{\texrramathclassstart{punctuation}#1\texrramathclassend}
\def\mathinner#1{\texrramathclassstart{inner}#1\texrramathclassend}
\def\overline#1{\texrramathaccentstart{overline}#1\texrramathaccentend}
\def\langle{⟨}
\def\rangle{⟩}
\def\{{\texrraopenbrace}
\def\}{\texrraclosebrace}
\def\lbrace{\texrraopenbrace}
\def\rbrace{\texrraclosebrace}
\def\lfloor{⌊}
\def\rfloor{⌋}
\def\lceil{⌈}
\def\rceil{⌉}
\def\vert{|}
\def\Vert{‖}
\def\|{‖}
\def\alpha{α}
\def\beta{β}
\def\gamma{γ}
\def\delta{δ}
\def\epsilon{ε}
\def\zeta{ζ}
\def\eta{η}
\def\theta{θ}
\def\vartheta{ϑ}
\def\iota{ι}
\def\kappa{κ}
\def\lambda{λ}
\def\mu{μ}
\def\nu{ν}
\def\xi{ξ}
\def\pi{π}
\def\varpi{ϖ}
\def\rho{ρ}
\def\varrho{ϱ}
\def\sigma{σ}
\def\varsigma{ς}
\def\tau{τ}
\def\upsilon{υ}
\def\phi{φ}
\def\varphi{ϕ}
\def\chi{χ}
\def\psi{ψ}
\def\omega{ω}
\def\Gamma{Γ}
\def\Delta{Δ}
\def\Theta{Θ}
\def\Xi{Ξ}
\def\Lambda{Λ}
\def\Pi{Π}
\def\Upsilon{Υ}
\def\Sigma{Σ}
\def\Phi{Φ}
\def\Psi{Ψ}
\def\Omega{Ω}
\def\times{×}
\def\cdot{·}
\def\pm{±}
\def\leq{≤}
\def\le{≤}
\def\geq{≥}
\def\ge{≥}
\def\neq{≠}
\def\approx{≈}
\def\equiv{≡}
\def\in{∈}
\def\notin{∉}
\def\partial{∂}
\def\nabla{∇}
\def\forall{∀}
\def\exists{∃}
\def\to{→}
\def\rightarrow{→}
\def\leftarrow{←}
\def\Rightarrow{⇒}
\def\Leftrightarrow{⇔}
\def\ldots{…}
\def\cdots{⋯}
\def\varepsilon{ϵ}
\def\infty{∞}
\def\sim{∼}
\def\simeq{≃}
\def\cong{≅}
\def\propto{∝}
\def\ll{≪}
\def\gg{≫}
\def\subset{⊂}
\def\subseteq{⊆}
\def\supset{⊃}
\def\supseteq{⊇}
\def\cup{∪}
\def\cap{∩}
\def\setminus{∖}
\def\emptyset{∅}
\def\varnothing{∅}
\def\wedge{∧}
\def\vee{∨}
\def\neg{¬}
\def\lnot{¬}
\def\oplus{⊕}
\def\otimes{⊗}
\def\perp{⊥}
\def\parallel{∥}
\def\angle{∠}
\def\triangle{△}
\def\ddots{⋱}
\def\vdots{⋮}
\def\hbar{ℏ}
\def\ell{ℓ}
\def\aleph{ℵ}
\def\imath{ı}
\def\jmath{ȷ}
\def\dagger{†}
\def\ddagger{‡}
\def\star{⋆}
\def\ast{∗}
\def\circ{∘}
\def\bullet{•}
\def\ldots{…}
\def\textdegree{°}
\def\degree{°}
\def\S{§}
\def\P{}
\def\copyright{©}
\def\pounds{£}
\def\sum{∑}
\def\prod{∏}
\def\int{∫}
\def\oint{∮}
\def\sin{\texrraoperatorstart sin\texrraoperatorend}
\def\cos{\texrraoperatorstart cos\texrraoperatorend}
\def\tan{\texrraoperatorstart tan\texrraoperatorend}
\def\log{\texrraoperatorstart log\texrraoperatorend}
\def\ln{\texrraoperatorstart ln\texrraoperatorend}
\def\exp{\texrraoperatorstart exp\texrraoperatorend}
\def\lim{\texrraoperatorstart lim\texrraoperatorend}
\def\max{\texrraoperatorstart max\texrraoperatorend}
\def\min{\texrraoperatorstart min\texrraoperatorend}
\def\quad{\hskip1em\relax}
\def\qquad{\hskip2em\relax}
\def\,{\texrramathspace{3}}
\def\:{\texrramathspace{4}}
\def\;{\texrramathspace{5}}
\def\!{\texrramathspace{-3}}
\def\big#1{\texrramathmanualdelimiter{17}{ordinary}#1}
\def\Big#1{\texrramathmanualdelimiter{23}{ordinary}#1}
\def\bigg#1{\texrramathmanualdelimiter{29}{ordinary}#1}
\def\Bigg#1{\texrramathmanualdelimiter{35}{ordinary}#1}
\def\bigl#1{\texrramathmanualdelimiter{17}{opening}#1}
\def\Bigl#1{\texrramathmanualdelimiter{23}{opening}#1}
\def\biggl#1{\texrramathmanualdelimiter{29}{opening}#1}
\def\Biggl#1{\texrramathmanualdelimiter{35}{opening}#1}
\def\bigm#1{\texrramathmanualdelimiter{17}{relation}#1}
\def\Bigm#1{\texrramathmanualdelimiter{23}{relation}#1}
\def\biggm#1{\texrramathmanualdelimiter{29}{relation}#1}
\def\Biggm#1{\texrramathmanualdelimiter{35}{relation}#1}
\def\bigr#1{\texrramathmanualdelimiter{17}{closing}#1}
\def\Bigr#1{\texrramathmanualdelimiter{23}{closing}#1}
\def\biggr#1{\texrramathmanualdelimiter{29}{closing}#1}
\def\Biggr#1{\texrramathmanualdelimiter{35}{closing}#1}
% ---- LaTeX compatibility layer -------------------------------------------
\def\ProvidesClass#1{}
\def\ProvidesPackage#1{}
\def\ProvidesFile#1{}
\def\rmdefault{cmr}
\def\sfdefault{cmss}
\def\ttdefault{cmtt}
\def\z@{0pt}
\def\p@{1pt}
\def\@plus{plus}
\def\@minus{minus}
\def\@xpt{10pt}
\def\@ixpt{9pt}
\def\@xipt{11pt}
\def\@xiipt{12pt}
\def\@xivpt{14pt}
\def\@xviipt{17pt}
\def\@xxpt{20pt}
\def\@xxvpt{25pt}
\def\@viipt{7pt}
\def\@viiipt{8pt}
\def\@vipt{6pt}
\def\@setfontsize#1#2#3{}
\def\normalsize{}
\def\small{}
\def\footnotesize{}
\def\scriptsize{}
\def\tiny{}
\def\large{}
\def\Large{}
\def\LARGE{}
\def\huge{}
\def\Huge{}
\def\flushbottom{}
\def\raggedbottom{}
\def\sloppy{}
\def\fussy{}
\def\protect{}
\def\leavevmode{}
\def\ignorespaces{}
\def\unskip{}
\def\addvspace#1{\vskip#1\relax}
\def\addpenalty#1{}
\def\medskipamount{6pt plus 2pt minus 2pt}
\def\smallskipamount{3pt plus 1pt minus 1pt}
\def\bigskipamount{12pt plus 4pt minus 4pt}
\def\medskip{\vskip6pt}
\def\smallskip{\vskip3pt}
\def\bigskip{\vskip12pt}
\def\textwidth{160mm}
\def\textheight{247mm}
\def\linewidth{\textwidth}
\def\columnwidth{\textwidth}
\def\smallbreak{\smallskip}
\def\medbreak{\medskip}
\def\bigbreak{\bigskip}
\def\tableofcontents{}
\def\listoffigures{}
\def\listoftables{}
\def\enspace{\hskip0.5em\relax}
\def\thinspace{\hskip0.16667em\relax}
\def\negthinspace{\hskip-0.16667em\relax}
\def\medspace{\hskip0.22222em\relax}
\def\negmedspace{\hskip-0.22222em\relax}
\def\thickspace{\hskip0.27778em\relax}
\def\negthickspace{\hskip-0.27778em\relax}
\def\space{ }
\def\nobreakspace{ }
\def\ { }
\def~{ }
\def\AtBeginDocument#1{#1}
\def\newgeometry#1{\texrrageometry{#1}}
\def\fancyhf{}
\def\fancyheadoffset#1{}
\def\fancyhead#1{}
\def\fancyfoot#1{}
\def\lhead#1{}
\def\chead#1{}
\def\rhead#1{}
\def\lfoot#1{}
\def\cfoot#1{}
\def\rfoot#1{}
\def\headrulewidth{0.4pt}
\def\footrulewidth{0pt}
\def\pagestyle#1{}
\def\thispagestyle#1{}
\def\thepage{1}
\def\hypersetup#1{}
\def\microtypesetup#1{}
\def\urlstyle#1{}
\def\fnsymbol#1{*}
\def\thefootnote{*}
\def\footnoterule{}
\def\footnote#1{}
\def\thanks#1{}
\def\@title{}
\def\@author{}
\def\@date{}
\def\@thanks{}
\def\@makefntext#1{}
\def\@makefnmark{}
\def\@thefnmark{}
\def\sc{}
\def\sf{}
\def\sl{}
\def\em{}
\def\scshape{\texrrascshape}
\def\S{§}
\def\P{}
\def\dag{†}
\def\ddag{‡}
\def\copyright{©}
\def\textbullet{•}
\def\textregistered{®}
\def\texttrademark{™}
\def\ldots{…}
\def\dots{…}
\def\textendash{–}
\def\textemdash{—}
\def\textquoteleft{‘}
\def\textquoteright{’}
\def\textquotedblleft{“}
\def\textquotedblright{”}
\def\textrm#1{{\rmfamily #1}}
\def\textup#1{{\upshape #1}}
\def\textmd#1{{\mdseries #1}}
\def\textsl#1{{\slshape #1}}
\def\textnormal#1{{\normalfont #1}}
\def\em{\itshape}
\def\ss{ß}
\def\ae{æ}
\def\AE{Æ}
\def\oe{œ}
\def\OE{Œ}
\def\aa{å}
\def\AA{Å}
\def\o{ø}
\def\O{Ø}
\def\l{ł}
\def\L{Ł}
\def\i{ı}
\def\textasciitilde{~}
\def\textasciicircum{^}
\def\textless{<}
\def\textgreater{>}
\def\textbar{|}
\def\textunderscore{_}
\def\guillemotleft{«}
\def\guillemotright{»}
\def\textquotesingle{'}
\def\texteuro{€}
\def\textsterling{£}
\def\textyen{¥}
\def\textcent{¢}
\def\textdegree{°}
\def\textpm{±}
\def\textmu{µ}
\def\textperthousand{‰}
\def\textonesuperior{¹}
\def\texttwosuperior{²}
\def\textthreesuperior{³}
\def\textonehalf{½}
\def\textonequarter{¼}
\def\textthreequarters{¾}
\def\textordfeminine{ª}
\def\textordmasculine{º}
\def\textohm{Ω}
\def\textcelsius{°C}
\def\checkmark{✓}
\def\textvisiblespace{␣}
\def\textbrokenbar{¦}
\def\textdagger{†}
\def\textdaggerdbl{‡}
\def\textperiodcentered{·}
\def\textsection{§}
\def\textparagraph{}
\def\sffamily{}
\def\textsc#1{{\texrrascshape #1}}
\def\nicefrac#1#2{#1/#2}
\def\cref#1{\texrraref{#1}}
\def\Cref#1{\texrraref{#1}}
\def\doi#1{#1}
\def\dots{...}
\def\textellipsis{...}
\def\and{ }
\def\And{ }
\def\AND{ }
\def\ifhmode{\iftrue}
\def\paragraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par}
\def\subparagraph#1{\par\texrraheadingstart{3}#1\texrraheadingend\par}
\def\@startsection#1#2#3#4#5#6#7{\par\texrraheadingstart{#2}#7\texrraheadingend\par}
\def\setlength#1#2{#1=#2\relax}
\def\addtolength#1#2{\advance#1#2\relax}
\def\stepcounter#1{}
\def\refstepcounter#1{}
\def\value#1{0}
\def\enlargethispage#1{}
\def\appendix{}
\def\listoffigures{}
\def\listoftables{}
\def\abstractname{Abstract}
\def\refname{References}
\def\bibname{References}
\def\figurename{Figure}
\def\tablename{Table}
\def\contentsname{Contents}
\def\keywords#1{\par\noindent\textbf{Keywords: }#1\par}
\def\hbox#1{#1}
\def\rule{\texrrarule}
\skipdef\parindent=100
\skipdef\parskip=101
\skipdef\baselineskip=102
\skipdef\lineskip=103
\skipdef\rightskip=104
\skipdef\leftskip=105
\skipdef\parfillskip=106
\skipdef\topskip=107
\skipdef\topsep=108
\skipdef\partopsep=109
\skipdef\itemsep=110
\skipdef\parsep=111
\skipdef\abovecaptionskip=112
\skipdef\belowcaptionskip=113
\skipdef\footnotesep=114
\skipdef\leftmargin=115
\skipdef\leftmarginii=116
\skipdef\leftmarginiii=117
\skipdef\leftmargini=122
\skipdef\leftmarginiv=123
\skipdef\leftmarginv=124
\skipdef\leftmarginvi=125
\skipdef\labelsep=118
\skipdef\labelwidth=119
\skipdef\itemindent=120
\skipdef\listparindent=121
\countdef\widowpenalty=200
\countdef\clubpenalty=201
\countdef\displaywidowpenalty=202
\countdef\brokenpenalty=203
\countdef\footins=204
\countdef\pretolerance=205
\countdef\tolerance=206
\countdef\hbadness=207
\countdef\vbadness=208
\countdef\looseness=209
\def\topfraction{0.7}
\def\bottomfraction{0.3}
\def\textfraction{0.2}
\def\floatpagefraction{0.5}
\def\dbltopfraction{0.7}
\def\arraystretch{1}
\def\tabcolsep{6pt}
\def\arrayrulewidth{0.4pt}
\def\doublerulesep{2pt}
\def\extrarowheight{0pt}
"#;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct PreprocessedSource {
source: tex_expansion::ExpandedSource,
file_name: String,
prelude: String,
style_search_path: Option<OsString>,
cacheable: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ExpandedTexSource {
source: tex_expansion::ExpandedSource,
dependencies: Vec<tex_expansion::SourceDependency>,
cacheable: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct LoweredDocumentSource {
pub(super) source: tex_expansion::ExpandedTokenStream,
pub(super) dependencies: Vec<tex_expansion::SourceDependency>,
pub(super) cacheable: bool,
}
struct SourceLines {
origin: PathBuf,
line_starts: Vec<usize>,
base_line: usize,
base_column: usize,
}
struct PreprocessOutput {
source: tex_expansion::ExpandedSource,
cacheable: bool,
}
impl SourceLines {
fn new(source: &str, origin: &Path, base: tex_expansion::SourceLocation) -> Self {
let mut line_starts = vec![0];
line_starts.extend(
source
.match_indices('\n')
.map(|(index, _)| index.saturating_add(1)),
);
Self {
origin: origin.to_path_buf(),
line_starts,
base_line: base.line,
base_column: base.column,
}
}
fn line_index_at(&self, offset: usize) -> usize {
self.line_starts
.partition_point(|line_start| *line_start <= offset)
.saturating_sub(1)
}
fn location_at(&self, source: &str, offset: usize) -> tex_expansion::SourceLocation {
let line_index = self.line_index_at(offset);
let line_start = self.line_starts[line_index];
let column = source[line_start..offset].chars().count()
+ if line_index == 0 { self.base_column } else { 0 };
tex_expansion::SourceLocation {
origin: tex_expansion::SourceOrigin::File(self.origin.clone()),
line: self.base_line + line_index,
column,
}
}
}
fn append_source_range(
output: &mut tex_expansion::ExpandedSource,
source: &str,
lines: &SourceLines,
range: std::ops::Range<usize>,
) {
let mut cursor = range.start;
while cursor < range.end {
let line_index = lines.line_index_at(cursor);
let line_end = lines
.line_starts
.get(line_index + 1)
.copied()
.unwrap_or(range.end)
.min(range.end);
let end = line_end.max(cursor + 1).min(range.end);
let output_start = output.text.len();
output.text.push_str(&source[cursor..end]);
output.segments.push(tex_expansion::SourceSegment {
output: output_start..output.text.len(),
location: lines.location_at(source, cursor),
column_advances: true,
column_character_starts: source[cursor..end]
.char_indices()
.map(|(offset, _)| offset)
.collect(),
});
cursor = end;
}
}
fn preprocess_latex(source: &str, source_path: &Path) -> Result<PreprocessOutput, String> {
let lines = SourceLines::new(
source,
source_path,
tex_expansion::SourceLocation {
origin: tex_expansion::SourceOrigin::File(source_path.to_path_buf()),
line: 1,
column: 0,
},
);
let mut expanded = tex_expansion::ExpandedSource {
text: String::with_capacity(source.len()),
segments: Vec::new(),
events: Vec::new(),
items: Vec::new(),
};
append_source_range(&mut expanded, source, &lines, 0..source.len());
Ok(PreprocessOutput {
source: expanded,
cacheable: can_cache_frontend_snapshot(source),
})
}
fn current_date_utc() -> String {
let days = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
/ 86_400;
let shifted_days = days + 719_468;
let era = if shifted_days >= 0 {
shifted_days
} else {
shifted_days - 146_096
} / 146_097;
let day_of_era = shifted_days - era * 146_097;
let year_of_era =
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let mut year = year_of_era + era * 400;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_part = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_part + 2) / 5 + 1;
let month = month_part + if month_part < 10 { 3 } else { -9 };
year += i64::from(month <= 2);
format!("{year:04}-{month:02}-{day:02}")
}
pub(super) fn can_cache_frontend_snapshot(source: &str) -> bool {
let dependency_commands = [
"\\include",
"\\endinput",
"\\@input",
"\\@@input",
"\\InputIfFileExists",
"\\IfFileExists",
"\\openin",
"\\read",
"\\openout",
"\\closeout",
"\\write",
"\\immediate",
"\\message",
"\\typeout",
"\\errmessage",
"\\special",
"\\time",
"\\day",
"\\month",
"\\year",
"\\csname",
"\\scantokens",
"\\uppercase",
"\\lowercase",
"\\lccode",
"\\uccode",
"\\endlinechar",
"\\catcode",
"\\makeatletter",
];
let mut cursor = 0usize;
while cursor < source.len() {
if source[cursor..].starts_with('%') {
cursor = source[cursor..]
.find('\n')
.map_or(source.len(), |offset| cursor + offset + 1);
continue;
}
if source[cursor..].starts_with('\\') {
let (command, after) = read_control_sequence(source, cursor);
if dependency_commands.contains(&command.as_str()) {
return false;
}
cursor = after;
continue;
}
let character = source[cursor..]
.chars()
.next()
.expect("valid UTF-8 boundary");
cursor += character.len_utf8();
}
true
}
pub(super) fn dependencies_unchanged(dependencies: &[tex_expansion::SourceDependency]) -> bool {
dependencies.iter().all(|dependency| {
fs::read_to_string(&dependency.path).is_ok_and(|contents| contents == dependency.contents)
})
}
pub(super) fn style_lookup_fingerprint(file_name: &str) -> u64 {
let mut hasher = DefaultHasher::new();
let directories = std::iter::once(source_directory(file_name).to_path_buf()).chain(
env::var_os("TEXRRA_STY_DIR")
.into_iter()
.flat_map(|paths| env::split_paths(&paths).collect::<Vec<_>>()),
);
for directory in directories {
directory.hash(&mut hasher);
match fs::read_dir(&directory) {
Ok(entries) => {
true.hash(&mut hasher);
let mut style_names = entries
.filter_map(Result::ok)
.map(|entry| entry.file_name())
.filter(|name| Path::new(name).extension().is_some_and(|ext| ext == "sty"))
.collect::<Vec<_>>();
style_names.sort();
style_names.hash(&mut hasher);
}
Err(_) => false.hash(&mut hasher),
}
}
hasher.finish()
}
pub(super) fn date_stamp() -> String {
current_date_utc()
}
pub(super) fn preprocess(source: &str, file_name: &str) -> Result<PreprocessedSource, String> {
let prelude = PRELUDE.replace("__TEXRRA_TODAY__", &current_date_utc());
let output = preprocess_latex(source, Path::new(file_name))?;
Ok(PreprocessedSource {
source: output.source,
file_name: file_name.to_string(),
prelude,
style_search_path: env::var_os("TEXRRA_STY_DIR"),
cacheable: output.cacheable,
})
}
pub(super) fn expand_tex(
source: PreprocessedSource,
cache: &mut tex_expansion::ExpansionCache,
) -> Result<ExpandedTexSource, String> {
let PreprocessedSource {
source,
file_name,
prelude,
cacheable: preprocess_cacheable,
style_search_path,
} = source;
let output = tex_expansion::expand(
source,
&file_name,
&prelude,
cache,
preprocess_cacheable,
style_search_path,
style_lookup_fingerprint(&file_name),
Vec::new(),
)?;
let cacheable = preprocess_cacheable
&& output
.dependencies
.iter()
.all(|dependency| can_cache_frontend_snapshot(&dependency.contents));
Ok(ExpandedTexSource {
source: output.source,
dependencies: output.dependencies,
cacheable,
})
}
pub(super) fn lower_math(
source: ExpandedTexSource,
math_parse_cache: &mut MathParseCache,
) -> Result<LoweredDocumentSource, String> {
let expanded = source.source.into_token_stream();
let collected = texrra_core::math_lowering::lower_math(expanded, math_parse_cache)?;
Ok(LoweredDocumentSource {
source: collected,
dependencies: source.dependencies,
cacheable: source.cacheable,
})
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+361
View File
@@ -0,0 +1,361 @@
// Rust reimplementation of the fixed-box, glue, and kern page-break slice from
// XeTeX's `xetex.web` (`vert_break` and `build_page`); TeX modes, inserts, and
// output routines remain outside this module.
use std::collections::HashSet;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) struct PageAnchor {
pub(super) block: usize,
pub(super) line: usize,
}
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)] // Preserve TeX's full glue-order model as syntax support expands.
pub(super) enum GlueOrder {
Normal,
Fil,
Fill,
Filll,
}
impl GlueOrder {
const fn index(self) -> usize {
match self {
Self::Normal => 0,
Self::Fil => 1,
Self::Fill => 2,
Self::Filll => 3,
}
}
}
impl From<super::engine::glue::TeXGlueOrder> for GlueOrder {
fn from(order: super::engine::glue::TeXGlueOrder) -> Self {
match order {
super::engine::glue::TeXGlueOrder::Normal => Self::Normal,
super::engine::glue::TeXGlueOrder::Fil => Self::Fil,
super::engine::glue::TeXGlueOrder::Fill => Self::Fill,
super::engine::glue::TeXGlueOrder::Filll => Self::Filll,
}
}
}
#[derive(Clone, Copy, Debug)]
pub(super) enum VerticalNode {
Box {
height: i64,
depth: i64,
anchor: Option<PageAnchor>,
},
Glue {
width: i64,
stretch: i64,
stretch_order: GlueOrder,
shrink: i64,
// The page-break cost uses total shrink; retain its order for later
// page-level glue setting in the positioned renderer.
#[allow(dead_code)]
shrink_order: GlueOrder,
},
Kern(i64),
Penalty(i32),
}
impl VerticalNode {
pub(super) fn fixed_glue(width: i64) -> Self {
Self::Glue {
width,
stretch: 0,
stretch_order: GlueOrder::Normal,
shrink: 0,
shrink_order: GlueOrder::Normal,
}
}
pub(super) fn glue(
width: i64,
stretch: i64,
stretch_order: GlueOrder,
shrink: i64,
shrink_order: GlueOrder,
) -> Self {
Self::Glue {
width,
stretch,
stretch_order,
shrink,
shrink_order,
}
}
}
#[derive(Clone, Copy, Debug, Default)]
struct PageDimensions {
// Mirrors TeX's page_total: the pending bottom depth is accounted for only
// when another box or vertical glue is added.
height: i64,
depth: i64,
stretch: [i64; 4],
shrink: i64,
}
#[derive(Clone, Copy, Debug)]
struct BreakCandidate {
node: usize,
dependency_end: usize,
cost: i64,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct PageBreakDecision {
pub(super) anchor: PageAnchor,
pub(super) dependency_end: usize,
}
#[derive(Default)]
pub(super) struct PlannedPageBreaks {
pub(super) anchors: HashSet<PageAnchor>,
pub(super) decisions: Vec<PageBreakDecision>,
}
const INFINITE_BADNESS: i64 = 10_000;
const AWFUL_BADNESS: i64 = 1_073_741_823;
const DEPLORABLE_COST: i64 = 100_000;
const INFINITE_PENALTY: i32 = 10_000;
const EJECT_PENALTY: i32 = -10_000;
pub(super) fn plan_page_breaks_with_dependencies(
nodes: &[VerticalNode],
start_node: usize,
page_goal: i64,
top_skip: i64,
max_depth: i64,
) -> PlannedPageBreaks {
let mut plan = PlannedPageBreaks::default();
let mut page_start = start_node.min(nodes.len());
while page_start < nodes.len() {
let Some(candidate) = find_page_break(nodes, page_start, page_goal, top_skip, max_depth)
else {
break;
};
let mut next_page_start = candidate.node + 1;
while next_page_start < nodes.len() && is_discardable(nodes[next_page_start]) {
next_page_start += 1;
}
if next_page_start <= page_start || next_page_start >= nodes.len() {
break;
}
if let Some(anchor) = nodes[next_page_start..].iter().find_map(|node| match node {
VerticalNode::Box { anchor, .. } => *anchor,
_ => None,
}) {
plan.anchors.insert(anchor);
plan.decisions.push(PageBreakDecision {
anchor,
dependency_end: candidate.dependency_end,
});
}
page_start = next_page_start;
}
plan
}
fn find_page_break(
nodes: &[VerticalNode],
start: usize,
page_goal: i64,
top_skip: i64,
max_depth: i64,
) -> Option<BreakCandidate> {
let mut dimensions = PageDimensions::default();
let mut best = None;
let mut least_cost = AWFUL_BADNESS;
let mut has_box = false;
let mut last_node_was_box = false;
for (offset, node) in nodes.iter().copied().enumerate().skip(start) {
match node {
VerticalNode::Box { height, depth, .. } => {
if !has_box {
dimensions.height = dimensions
.height
.saturating_add(top_skip.saturating_sub(height).max(0));
dimensions.height = dimensions.height.saturating_add(height);
has_box = true;
} else {
dimensions.height = dimensions
.height
.saturating_add(dimensions.depth)
.saturating_add(height);
}
dimensions.depth = depth;
if dimensions.depth > max_depth {
dimensions.height = dimensions
.height
.saturating_add(dimensions.depth - max_depth);
dimensions.depth = max_depth;
}
last_node_was_box = true;
}
VerticalNode::Glue {
width,
stretch,
stretch_order,
shrink,
shrink_order: _,
} => {
if !has_box {
last_node_was_box = false;
continue;
}
if last_node_was_box {
let candidate = make_candidate(offset, 0, dimensions, page_goal);
update_best(candidate, &mut best, &mut least_cost);
if dimensions.height > page_goal
&& dimensions.height - page_goal > dimensions.shrink
{
let mut selected = best.unwrap_or(candidate);
selected.dependency_end = offset;
return Some(selected);
}
}
dimensions.height = dimensions
.height
.saturating_add(dimensions.depth)
.saturating_add(width);
dimensions.depth = 0;
let stretch_order = stretch_order.index();
dimensions.stretch[stretch_order] =
dimensions.stretch[stretch_order].saturating_add(stretch.max(0));
dimensions.shrink = dimensions.shrink.saturating_add(shrink.max(0));
last_node_was_box = false;
}
VerticalNode::Penalty(penalty) => {
if !has_box {
last_node_was_box = false;
continue;
}
if penalty <= EJECT_PENALTY {
return Some(make_candidate(offset, penalty, dimensions, page_goal));
}
if has_box && penalty < INFINITE_PENALTY {
let candidate = make_candidate(offset, penalty, dimensions, page_goal);
update_best(candidate, &mut best, &mut least_cost);
if page_badness(dimensions, page_goal) == AWFUL_BADNESS {
let mut selected = best.unwrap_or(candidate);
selected.dependency_end = offset;
return Some(selected);
}
}
last_node_was_box = false;
}
VerticalNode::Kern(width) => {
if has_box
&& (offset + 1 == nodes.len()
|| matches!(nodes[offset + 1], VerticalNode::Glue { .. }))
{
let candidate = make_candidate(offset, 0, dimensions, page_goal);
update_best(candidate, &mut best, &mut least_cost);
if page_badness(dimensions, page_goal) == AWFUL_BADNESS {
let mut selected = best.unwrap_or(candidate);
selected.dependency_end = offset;
return Some(selected);
}
}
if has_box {
dimensions.height = dimensions
.height
.saturating_add(dimensions.depth)
.saturating_add(width);
dimensions.depth = 0;
}
last_node_was_box = false;
}
}
}
None
}
fn make_candidate(
node: usize,
penalty: i32,
dimensions: PageDimensions,
page_goal: i64,
) -> BreakCandidate {
let badness = page_badness(dimensions, page_goal);
let cost = if penalty <= EJECT_PENALTY {
i64::from(penalty)
} else if badness < AWFUL_BADNESS && badness < INFINITE_BADNESS {
badness + i64::from(penalty)
} else if badness < AWFUL_BADNESS {
DEPLORABLE_COST
} else {
AWFUL_BADNESS
};
BreakCandidate {
node,
dependency_end: node,
cost,
}
}
fn update_best(candidate: BreakCandidate, best: &mut Option<BreakCandidate>, least_cost: &mut i64) {
if candidate.cost <= *least_cost {
*best = Some(candidate);
*least_cost = candidate.cost;
}
}
fn page_badness(dimensions: PageDimensions, page_goal: i64) -> i64 {
let difference = page_goal.saturating_sub(dimensions.height);
if difference == 0 {
return 0;
}
if difference > 0 {
if dimensions.stretch[1..].iter().any(|stretch| *stretch > 0) {
return 0;
}
return ratio_badness(difference, dimensions.stretch[GlueOrder::Normal.index()]);
}
let excess = difference.saturating_neg();
if excess > dimensions.shrink {
AWFUL_BADNESS
} else {
ratio_badness(excess, dimensions.shrink)
}
}
fn ratio_badness(amount: i64, available: i64) -> i64 {
// TeX's `badness` routine in tex.web uses integer arithmetic so page-break
// choices do not depend on host floating-point behavior. The first branch
// keeps the multiply within the range used by TeX's scaled arithmetic.
if amount == 0 {
return 0;
}
if available <= 0 {
return INFINITE_BADNESS;
}
let ratio = if amount <= 7_230_584 {
amount.saturating_mul(297) / available
} else if available >= 1_663_497 {
amount / (available / 297)
} else {
amount
};
if ratio > 1_290 {
return INFINITE_BADNESS;
}
(ratio * ratio * ratio + 0x4_0000) / 0x10_0000
}
fn is_discardable(node: VerticalNode) -> bool {
matches!(
node,
VerticalNode::Glue { .. } | VerticalNode::Penalty(_) | VerticalNode::Kern(_)
)
}
+3
View File
@@ -0,0 +1,3 @@
pub(super) use texrra_core::document_parser::{
ParagraphParseCache, parse_dimension, parse_document,
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+358
View File
@@ -0,0 +1,358 @@
use std::{fmt::Write as _, path::Path};
use genpdf::{
Alignment, Mm,
fonts::{self, FontFamily},
};
use super::super::{encode_base64, image_mime_type, text_layout};
use super::layout::{scaled_units_to_mm, text_line_metrics_scaled};
use super::*;
const POINTS_TO_MM: f64 = 25.4 / 72.0;
pub(in crate::rust_typeset) struct PreviewPage {
pub(in crate::rust_typeset) svg: String,
}
pub(in crate::rust_typeset) fn render_pages(
model: &DocumentModel,
source_dir: &Path,
resources: &PreviewResources,
content_width_mm: f64,
content_height_mm: f64,
paragraph_layout_cache: &mut ParagraphLayoutCache,
page_layout_cache: &mut PageLayoutCache,
) -> Result<Option<Vec<PreviewPage>>, String> {
let timing_start = std::time::Instant::now();
let page_layout = layout_document(
model,
source_dir,
content_width_mm,
content_height_mm,
&resources.box_metrics,
&resources.font_cache,
resources.cjk_family,
resources.mono_family,
&resources.math_metrics,
&resources.math_layout,
paragraph_layout_cache,
page_layout_cache,
);
let Some(mut pages) = page_layout.pages else {
return Ok(None);
};
if let Some(snapshot) = page_layout.snapshot {
page_layout_cache.snapshot = Some(snapshot);
}
super::super::log_timing("preview.layout", timing_start);
let content_width = Mm::from(content_width_mm);
let mut rendered = Vec::with_capacity(pages.len());
for page in &mut pages {
rendered.push(PreviewPage {
svg: page_svg(page, model, resources, content_width),
});
}
super::super::log_timing("preview.svg", timing_start);
Ok(Some(rendered))
}
fn page_svg(
page: &mut PositionedPage,
model: &DocumentModel,
resources: &PreviewResources,
content_width: Mm,
) -> String {
let fonts = &resources.font_cache;
let cjk_family = resources.cjk_family;
let monospace_family = resources.mono_family;
let mut output = String::new();
let page_width = model.page.width_mm;
let page_height = model.page.height_mm;
let _ = write!(
output,
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{page_width}mm\" height=\"{page_height}mm\" viewBox=\"0 0 {page_width} {page_height}\" role=\"img\">"
);
let _ = write!(
output,
"<rect width=\"{page_width}\" height=\"{page_height}\" fill=\"#ffffff\" />"
);
let _ = write!(
output,
"<g transform=\"translate({:.4} {:.4})\" fill=\"#000000\">",
model.margins.left, model.margins.top
);
for item in &mut page.items {
match item {
PositionedPageItem::Line(line) => write_line_content(
&mut output,
&line.content,
Mm::from(scaled_units_to_mm(line.x)),
Mm::from(scaled_units_to_mm(line.y)),
if line.centered {
Alignment::Center
} else {
Alignment::Left
},
content_width,
fonts,
cjk_family,
monospace_family,
),
PositionedPageItem::DisplayMath {
element, style, y, ..
} => element.write_svg(
fonts,
*style,
monospace_family,
Mm::from(0.0),
Mm::from(scaled_units_to_mm(*y)),
&mut output,
),
PositionedPageItem::Table { element, y, .. } => write_table(
&mut output,
element,
Mm::from(scaled_units_to_mm(*y)),
content_width,
fonts,
cjk_family,
monospace_family,
),
PositionedPageItem::Centered { element, y, .. } => write_centered(
&mut output,
element,
Mm::from(scaled_units_to_mm(*y)),
content_width,
fonts,
cjk_family,
monospace_family,
),
PositionedPageItem::FramedBox { element, y, .. } => write_framed_box(
&mut output,
element,
Mm::from(scaled_units_to_mm(*y)),
fonts,
cjk_family,
monospace_family,
),
PositionedPageItem::Image { element, y, .. } => write_figure(
&mut output,
element,
Mm::from(scaled_units_to_mm(*y)),
content_width,
fonts,
cjk_family,
monospace_family,
),
}
}
output.push_str("</g></svg>");
output
}
fn write_table(
output: &mut String,
table: &mut PositionedTable,
y: Mm,
content_width: Mm,
fonts: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
) {
let width_mm = f64::from(content_width);
let column_width = Mm::from(width_mm / table.column_count.max(1) as f64);
let mut cursor = 0.0_f64;
for (row_index, row) in table.rows.iter_mut().enumerate() {
if table.rules.contains(&row_index) {
write_rule(output, 0.0, cursor, width_mm);
}
for (column_index, cell) in row.cells.iter_mut().enumerate() {
let x = Mm::from(column_index as f64 * f64::from(column_width));
let mut cell_y = 0.0;
for line in cell.iter_mut() {
let alignment = line.alignment;
write_line_content(
output,
&line.content,
x,
y + Mm::from(cursor + cell_y),
alignment,
column_width,
fonts,
cjk_family,
monospace_family,
);
cell_y += scaled_units_to_mm(line.height);
}
}
cursor += scaled_units_to_mm(row.height);
}
if table.rules.contains(&table.rows.len()) {
write_rule(output, 0.0, cursor, width_mm);
}
}
fn write_figure(
output: &mut String,
figure: &PositionedFigure,
y: Mm,
content_width: Mm,
fonts: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
) {
let height_mm = scaled_units_to_mm(figure.image_height);
let x = ((f64::from(content_width) - figure.image_width_mm).max(0.0)) / 2.0;
if let (Some(mime), Ok(bytes)) = (
image_mime_type(&figure.source),
std::fs::read(&figure.source),
) {
let _ = write!(
output,
"<image x=\"{x:.4}\" y=\"{:.4}\" width=\"{:.4}\" height=\"{height_mm:.4}\" preserveAspectRatio=\"none\" href=\"data:{mime};base64,{}\" />",
f64::from(y),
figure.image_width_mm,
encode_base64(&bytes),
);
}
let mut cursor = height_mm;
for line in &figure.caption {
write_line_content(
output,
&line.content,
Mm::from(0.0),
y + Mm::from(cursor),
Alignment::Center,
content_width,
fonts,
cjk_family,
monospace_family,
);
cursor += scaled_units_to_mm(line.height);
}
}
#[allow(clippy::too_many_arguments)]
fn write_line_content(
output: &mut String,
content: &PositionedLineContent,
x: Mm,
y: Mm,
alignment: Alignment,
area_width: Mm,
fonts: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
) {
match content {
PositionedLineContent::Text { line, font_size } => {
text_layout::TextLine::new(line, cjk_family, monospace_family, *font_size)
.aligned(alignment)
.write_svg(
fonts,
cjk_family,
monospace_family,
area_width,
x,
y,
output,
);
}
PositionedLineContent::InlineMath(element) => {
element.write_svg(
fonts,
cjk_family,
monospace_family,
alignment,
area_width,
x,
y,
output,
);
}
}
}
fn write_rule(output: &mut String, x: f64, y: f64, width: f64) {
let _ = write!(
output,
"<line x1=\"{x:.4}\" y1=\"{y:.4}\" x2=\"{:.4}\" y2=\"{y:.4}\" stroke=\"#000000\" stroke-width=\"{POINTS_TO_MM:.4}\" />",
x + width,
);
}
fn write_framed_box(
output: &mut String,
element: &PositionedFramedBox,
y: Mm,
fonts: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
) {
let width = scaled_units_to_mm(element.width);
let height = scaled_units_to_mm(element.height);
if element.frame {
let _ = write!(
output,
"<rect x=\"0\" y=\"{:.4}\" width=\"{:.4}\" height=\"{:.4}\" fill=\"none\" stroke=\"#000000\" stroke-width=\"0.1411\" />",
f64::from(y),
width,
height,
);
}
let mut line_y = y + Mm::from(element.inset_mm);
for line in &element.lines {
let (ascent, depth) =
text_line_metrics_scaled(fonts, line, cjk_family, monospace_family, 11);
let line_height = scaled_units_to_mm(ascent.saturating_add(depth));
let content = PositionedLineContent::Text {
line: line.clone(),
font_size: 11,
};
write_line_content(
output,
&content,
Mm::from(element.inset_mm),
line_y,
Alignment::Left,
Mm::from(width - 2.0 * element.inset_mm),
fonts,
cjk_family,
monospace_family,
);
line_y += Mm::from(line_height);
}
}
fn write_centered(
output: &mut String,
element: &PositionedCentered,
y: Mm,
content_width: Mm,
fonts: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
) {
let mut line_y = y;
for line in &element.lines {
let (ascent, depth) =
text_line_metrics_scaled(fonts, line, cjk_family, monospace_family, 11);
let line_height = scaled_units_to_mm(ascent.saturating_add(depth));
let content = PositionedLineContent::Text {
line: line.clone(),
font_size: 11,
};
write_line_content(
output,
&content,
Mm::from(0.0),
line_y,
Alignment::Center,
content_width,
fonts,
cjk_family,
monospace_family,
);
line_y += Mm::from(line_height);
}
}
File diff suppressed because it is too large. Load diff
+446
View File
@@ -0,0 +1,446 @@
use std::fmt::Write as _;
use common::Scaled;
use genpdf::{
Alignment, Context, Element, Mm, Position, RenderResult, Rotation, Scale, Size,
fonts::{self, FontFamily},
style::Style,
};
use super::{PDF_POINTS_PER_INCH, escape_html, is_cjk};
#[derive(Clone, PartialEq, Eq, Hash)]
pub(super) struct LineBox {
pub(super) width: Scaled,
pub(super) items: Vec<LineItem>,
pub(super) pre_display_size: Option<Scaled>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub(super) enum LineItem {
Glyph {
character: char,
bold: bool,
italic: bool,
monospace: bool,
},
Rule {
width: Scaled,
raise: Scaled,
height: Scaled,
},
Kern(Scaled),
Glue(Scaled),
}
struct TextSpan {
text: String,
style: Style,
}
pub(super) struct PositionedSpan {
pub(super) text: String,
pub(super) style: Style,
pub(super) x: Mm,
}
pub(super) struct TextLineLayout {
pub(super) spans: Vec<PositionedSpan>,
pub(super) rules: Vec<PositionedRule>,
pub(super) width: Mm,
pub(super) ascent: Mm,
pub(super) descent: Mm,
}
pub(super) fn svg_font_size(font_size: u8) -> f64 {
f64::from(font_size) * 25.4 / PDF_POINTS_PER_INCH
}
pub(super) struct TextLine {
width: Scaled,
items: Vec<TextLineItem>,
alignment: Alignment,
font_size: u8,
}
enum TextLineItem {
Text(TextSpan),
Rule { width: Mm, raise: Mm, height: Mm },
Kern(Mm),
Glue(Mm),
}
pub(super) struct PositionedRule {
pub(super) x: Mm,
pub(super) width: Mm,
pub(super) raise: Mm,
pub(super) height: Mm,
}
impl TextLine {
pub(super) fn new(
line: &LineBox,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
font_size: u8,
) -> Self {
let mut items = Vec::new();
let mut text = String::new();
let mut text_style = None;
for item in &line.items {
match item {
LineItem::Glyph {
character,
bold,
italic,
monospace,
} if is_cjk(*character) => {
flush_text(
&mut items,
&mut text,
&mut text_style,
cjk_family,
monospace_family,
font_size,
);
items.push(TextLineItem::Text(TextSpan {
text: character.to_string(),
style: text_style_for(
*bold,
*italic,
*monospace,
true,
cjk_family,
monospace_family,
font_size,
),
}));
}
LineItem::Glyph {
character,
bold,
italic,
monospace,
} => {
let style_key = (*bold, *italic, *monospace);
if text_style != Some(style_key) {
flush_text(
&mut items,
&mut text,
&mut text_style,
cjk_family,
monospace_family,
font_size,
);
text_style = Some(style_key);
}
text.push(*character);
}
LineItem::Rule {
width,
raise,
height,
} => {
flush_text(
&mut items,
&mut text,
&mut text_style,
cjk_family,
monospace_family,
font_size,
);
items.push(TextLineItem::Rule {
width: scaled_to_mm(*width),
raise: scaled_to_mm(*raise),
height: scaled_to_mm(*height),
});
}
LineItem::Glue(width) => {
flush_text(
&mut items,
&mut text,
&mut text_style,
cjk_family,
monospace_family,
font_size,
);
items.push(TextLineItem::Glue(scaled_to_mm(*width)));
}
LineItem::Kern(width) => {
flush_text(
&mut items,
&mut text,
&mut text_style,
cjk_family,
monospace_family,
font_size,
);
items.push(TextLineItem::Kern(scaled_to_mm(*width)));
}
}
}
flush_text(
&mut items,
&mut text,
&mut text_style,
cjk_family,
monospace_family,
font_size,
);
Self {
width: line.width,
items,
alignment: Alignment::Left,
font_size,
}
}
pub(super) fn centered(mut self) -> Self {
self.alignment = Alignment::Center;
self
}
pub(super) fn aligned(mut self, alignment: Alignment) -> Self {
self.alignment = alignment;
self
}
pub(super) fn layout_spans(&self, fonts: &fonts::FontCache) -> TextLineLayout {
let mut spans = Vec::with_capacity(self.items.len());
let mut rules = Vec::new();
let mut x = Mm::from(0.0);
let mut ascent = Mm::from(0.0);
let mut descent = Mm::from(0.0);
// Centered and right-aligned lines are not justified: use the natural
// space width so the line keeps its intrinsic width and can be shifted
// as a whole by the alignment offset.
let natural_space = Style::new()
.with_font_size(self.font_size)
.str_width(fonts, " ");
for item in &self.items {
match item {
TextLineItem::Rule {
width,
raise,
height,
} => {
if *height > Mm::from(0.0) {
ascent = ascent.max(*raise + *height);
descent = descent.max(Mm::from(0.0) - *raise);
rules.push(PositionedRule {
x,
width: *width,
raise: *raise,
height: *height,
});
}
}
TextLineItem::Text(span) => {
let font = span.style.font(fonts);
let glyph_height = font.glyph_height(span.style.font_size());
let line_height = span.style.line_height(fonts);
ascent = ascent.max(glyph_height);
descent = descent.max((line_height - glyph_height).max(Mm::from(0.0)));
spans.push(PositionedSpan {
text: span.text.clone(),
style: span.style,
x,
});
x += span.style.str_width(fonts, &span.text);
}
TextLineItem::Glue(width) => {
x += if self.alignment == Alignment::Left {
*width
} else {
natural_space
};
}
TextLineItem::Kern(width) => x += *width,
}
}
TextLineLayout {
spans,
rules,
width: x,
ascent,
descent,
}
}
pub(super) fn write_svg(
&self,
fonts: &fonts::FontCache,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
area_width: Mm,
x: Mm,
y: Mm,
output: &mut String,
) {
let layout = self.layout_spans(fonts);
let horizontal_offset = match self.alignment {
Alignment::Left => Mm::from(0.0),
Alignment::Center => (area_width - layout.width).max(Mm::from(0.0)) / 2.0,
Alignment::Right => (area_width - layout.width).max(Mm::from(0.0)),
};
let baseline = y + layout.ascent;
for rule in &layout.rules {
let _ = write!(
output,
"<rect x=\"{:.4}\" y=\"{:.4}\" width=\"{:.4}\" height=\"{:.4}\" fill=\"#000000\"/>",
f64::from(x + horizontal_offset + rule.x),
f64::from(baseline - rule.raise - rule.height),
f64::from(rule.width),
f64::from(rule.height),
);
}
for span in &layout.spans {
let regular = span.style.font_family(fonts).regular;
let family = if cjk_family.is_some_and(|family| family.regular == regular) {
"TexrraCjk"
} else if monospace_family.is_some_and(|family| family.regular == regular) {
"TexrraMono"
} else {
"TexrraSerif"
};
let weight = if span.style.is_bold() { 700 } else { 400 };
let slant = if span.style.is_italic() {
"italic"
} else {
"normal"
};
let _ = write!(
output,
"<text x=\"{:.4}\" y=\"{:.4}\" xml:space=\"preserve\" font-family=\"{family}\" font-size=\"{:.4}\" font-weight=\"{weight}\" font-style=\"{slant}\">{}</text>",
f64::from(x + horizontal_offset + span.x),
f64::from(baseline),
svg_font_size(span.style.font_size()),
escape_html(&span.text),
);
}
}
}
fn flush_text(
items: &mut Vec<TextLineItem>,
text: &mut String,
style_key: &mut Option<(bool, bool, bool)>,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
font_size: u8,
) {
if text.is_empty() {
*style_key = None;
return;
}
let (bold, italic, monospace) = style_key.take().unwrap_or_default();
items.push(TextLineItem::Text(TextSpan {
text: std::mem::take(text),
style: text_style_for(
bold,
italic,
monospace,
false,
cjk_family,
monospace_family,
font_size,
),
}));
}
fn text_style_for(
bold: bool,
italic: bool,
monospace: bool,
is_cjk: bool,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
font_size: u8,
) -> Style {
let mut style = Style::new().with_font_size(font_size);
if bold && !is_cjk {
style = style.bold();
}
if italic && !is_cjk {
style = style.italic();
}
if is_cjk {
if let Some(family) = cjk_family {
style = style.with_font_family(family);
}
} else if monospace && let Some(family) = monospace_family {
style = style.with_font_family(family);
}
style
}
fn scaled_to_mm(value: Scaled) -> Mm {
Mm::from(f64::from(value.0) / 65_536.0 * 25.4 / PDF_POINTS_PER_INCH)
}
impl Element for TextLine {
fn render(
&mut self,
context: &Context,
area: genpdf::render::Area<'_>,
inherited_style: Style,
) -> Result<RenderResult, genpdf::error::Error> {
let layout = self.layout_spans(&context.font_cache);
let height = layout.ascent + layout.descent;
let horizontal_offset = match self.alignment {
Alignment::Left => Mm::from(0.0),
Alignment::Center => (area.size().width - layout.width).max(Mm::from(0.0)) / 2.0,
Alignment::Right => (area.size().width - layout.width).max(Mm::from(0.0)),
};
if height > area.size().height {
return Ok(RenderResult {
has_more: true,
..RenderResult::default()
});
}
if !layout.rules.is_empty() {
let mut black = image::RgbImage::new(1, 1);
black.put_pixel(0, 0, image::Rgb([0_u8, 0, 0]));
let black = image::DynamicImage::ImageRgb8(black);
for rule in &layout.rules {
let scale_x = f64::from(rule.width) * 300.0 / 25.4;
let scale_y = f64::from(rule.height) * 300.0 / 25.4;
area.add_image(
&black,
Position::new(rule.x + horizontal_offset, layout.ascent - rule.raise),
Scale::new(scale_x, scale_y),
Rotation::default(),
Some(300.0),
);
}
}
let mut placements = Vec::with_capacity(layout.spans.len());
for span in &layout.spans {
let style = inherited_style.and(span.style);
let glyph_height = style
.font(&context.font_cache)
.glyph_height(style.font_size());
let position = Position::new(span.x + horizontal_offset, layout.ascent - glyph_height);
if area
.text_section(&context.font_cache, position, style)
.is_none()
{
return Ok(RenderResult {
has_more: true,
..RenderResult::default()
});
}
placements.push((span.text.as_str(), style, position));
}
for (text, style, position) in placements {
area.print_str(&context.font_cache, position, style, text)?;
}
Ok(RenderResult {
size: Size::new(scaled_to_mm(self.width), height),
has_more: false,
})
}
}