Files
texrra-engine/src/projects.rs
T
gloamxun bb1d9e0561 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.
2026-10-19 11:41:46 +08:00

765 lines
26 KiB
Rust

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());
}