Load new math resources in the native Web editor
This commit is contained in:
1 parent
8b6dab8d52
commit
fe86163767
12 files changed
+838
-106
No files matched your search
@@ -19,6 +19,7 @@ let sequence = 0;
|
||||
let publishedRevision = null;
|
||||
let draft = null;
|
||||
let frame;
|
||||
const projectPrefix = location.pathname.startsWith("/p/") ? location.pathname.slice(0, -1) : "";
|
||||
const previewDraft = new URLSearchParams(location.hash.slice(1)).get("preview") !== "published";
|
||||
|
||||
function attachWebControls() {
|
||||
@@ -38,7 +39,9 @@ function attachWebControls() {
|
||||
download.textContent = "下载 PDF";
|
||||
document.querySelector("#export-pdf").replaceWith(download);
|
||||
|
||||
document.querySelector("#back-button").hidden = true;
|
||||
const back = document.querySelector("#back-button");
|
||||
back.hidden = !location.pathname.startsWith("/p/");
|
||||
back.addEventListener("click", () => { location.href = "/"; });
|
||||
document.querySelector("#toggle-engine").hidden = true;
|
||||
document.querySelector("#header-actions").textContent = "原生 Beta";
|
||||
document.querySelector("footer").textContent = "Ctrl/Cmd+S 保存源码副本";
|
||||
@@ -115,14 +118,14 @@ function restorePublishedPages() {
|
||||
function acceptPublication(revision, previous) {
|
||||
revokeDetached(previous);
|
||||
publishedRevision = revision;
|
||||
pdf.href = `/pdf?revision=${revision}`;
|
||||
pdf.href = projectPrefix + `/pdf?revision=${revision}`;
|
||||
pdf.hidden = false;
|
||||
draft = null;
|
||||
}
|
||||
|
||||
async function publicationStatus(edit, revision) {
|
||||
while (edit === sequence) {
|
||||
const response = await fetch(`/publication?revision=${revision}`);
|
||||
const response = await fetch(projectPrefix + `/publication?revision=${revision}`);
|
||||
const result = await response.json();
|
||||
if (!response.ok || result.state === "failed") throw new Error(result.error);
|
||||
if (result.state === "published") return result;
|
||||
@@ -134,7 +137,7 @@ async function publicationStatus(edit, revision) {
|
||||
async function compile(edit, submitted, changes) {
|
||||
const replacements = [];
|
||||
try {
|
||||
const response = await fetch("/preview", {
|
||||
const response = await fetch(projectPrefix + "/preview", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -227,7 +230,7 @@ async function saveSources() {
|
||||
saved.hidden = false;
|
||||
saved.textContent = "正在保存源文件";
|
||||
try {
|
||||
const response = await fetch("/save", {
|
||||
const response = await fetch(projectPrefix + "/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sequence, files: Object.fromEntries(edits) }),
|
||||
@@ -244,7 +247,7 @@ async function saveSources() {
|
||||
|
||||
async function openProject() {
|
||||
try {
|
||||
const response = await fetch("/project");
|
||||
const response = await fetch(projectPrefix + "/project");
|
||||
if (!response.ok) throw new Error("无法打开源文件");
|
||||
const project = await response.json();
|
||||
files = new Map(Object.entries(project.files));
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"use strict";
|
||||
|
||||
const list = document.querySelector("#projects-view");
|
||||
const grid = document.querySelector("#project-grid");
|
||||
const empty = document.querySelector("#projects-empty");
|
||||
const upload = document.querySelector("#upload-zip");
|
||||
const input = document.querySelector("#zip-input");
|
||||
const drop = document.querySelector("#drop-zone");
|
||||
const create = document.querySelector("#new-project");
|
||||
const message = document.querySelector("#toast");
|
||||
|
||||
list.hidden = false;
|
||||
document.querySelector("#header-actions").textContent = "原生 Beta";
|
||||
document.querySelector("footer").textContent = "";
|
||||
|
||||
async function request(path, options) {
|
||||
const response = await fetch(path, options);
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error);
|
||||
return result;
|
||||
}
|
||||
|
||||
function open(project) {
|
||||
location.href = "/p/" + encodeURIComponent(project.id) + "/";
|
||||
}
|
||||
|
||||
function projectCard(project) {
|
||||
const card = document.createElement("article");
|
||||
card.className = "project-card";
|
||||
const body = document.createElement("div");
|
||||
body.className = "project-body";
|
||||
const title = document.createElement("h3");
|
||||
title.textContent = project.name;
|
||||
const details = document.createElement("p");
|
||||
details.className = "project-meta";
|
||||
details.textContent = project.mainFile || "没有 TeX 主文件";
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "project-actions";
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "btn primary";
|
||||
button.textContent = "打开";
|
||||
button.disabled = !project.mainFile;
|
||||
button.addEventListener("click", () => open(project));
|
||||
actions.append(button);
|
||||
body.append(title, details, actions);
|
||||
card.append(body);
|
||||
return card;
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const { projects } = await request("/api/projects");
|
||||
grid.replaceChildren(...projects.map(projectCard));
|
||||
empty.hidden = projects.length > 0;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function showError(error) {
|
||||
message.hidden = false;
|
||||
message.textContent = error.message;
|
||||
}
|
||||
|
||||
async function importFile(file) {
|
||||
if (!file || upload.disabled) return;
|
||||
if (!file.name.toLowerCase().endsWith(".zip")) {
|
||||
showError(new Error("请选择 ZIP 压缩包"));
|
||||
return;
|
||||
}
|
||||
upload.disabled = true;
|
||||
message.hidden = true;
|
||||
try {
|
||||
const name = file.name.slice(0, -4);
|
||||
const project = await request("/api/projects?name=" + encodeURIComponent(name), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/zip" },
|
||||
body: file,
|
||||
});
|
||||
open(project);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
input.value = "";
|
||||
upload.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
upload.addEventListener("click", () => input.click());
|
||||
input.addEventListener("change", () => importFile(input.files[0]));
|
||||
drop.addEventListener("dragover", (event) => event.preventDefault());
|
||||
drop.addEventListener("drop", (event) => {
|
||||
event.preventDefault();
|
||||
importFile(event.dataTransfer.files[0]);
|
||||
});
|
||||
create.addEventListener("click", async () => {
|
||||
const name = prompt("项目名称");
|
||||
if (!name) return;
|
||||
create.disabled = true;
|
||||
try {
|
||||
const project = await request("/api/projects/new", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
open(project);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
create.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
refresh();
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::{EditorSession, InputProfile, fs, json, prepare, projects::ProjectStore, reply};
|
||||
use std::{
|
||||
io::{ErrorKind, Read},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use tiny_http::Request;
|
||||
|
||||
pub(super) const SCRIPT: &str = include_str!("library.js");
|
||||
const MAX_ZIP_UPLOAD: u64 = 64 * 1024 * 1024;
|
||||
|
||||
pub(super) struct Library {
|
||||
store: ProjectStore,
|
||||
format: PathBuf,
|
||||
manifest: PathBuf,
|
||||
runs: PathBuf,
|
||||
profile: InputProfile,
|
||||
}
|
||||
|
||||
impl Library {
|
||||
pub(super) fn new(
|
||||
store: PathBuf,
|
||||
format: PathBuf,
|
||||
manifest: PathBuf,
|
||||
runs: PathBuf,
|
||||
profile: InputProfile,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
fs::create_dir_all(&store)?;
|
||||
let store = store.canonicalize()?;
|
||||
fs::create_dir_all(&runs)?;
|
||||
let runs = runs.canonicalize()?;
|
||||
if runs.starts_with(&store) || store.starts_with(&runs) {
|
||||
return Err("Project and compilation directories must be separate".into());
|
||||
}
|
||||
Ok(Self {
|
||||
store: ProjectStore::new(store)?,
|
||||
format,
|
||||
manifest,
|
||||
runs,
|
||||
profile,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn list(&self, request: Request) {
|
||||
match self.store.list() {
|
||||
Ok(projects) => reply(request, 200, json!({"projects": projects})),
|
||||
Err(error) => reply(request, 500, json!({"error": error})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn import(&self, mut request: Request) {
|
||||
if !request.headers().iter().any(|header| {
|
||||
header.field.equiv("Content-Type")
|
||||
&& header.value.as_str().split(';').next() == Some("application/zip")
|
||||
}) {
|
||||
reply(request, 415, json!({"error": "Expected a ZIP archive"}));
|
||||
return;
|
||||
}
|
||||
let name = project_name(&request);
|
||||
let mut bytes = Vec::new();
|
||||
if let Err(error) = request
|
||||
.as_reader()
|
||||
.take(MAX_ZIP_UPLOAD + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
{
|
||||
reply(request, 400, json!({"error": error.to_string()}));
|
||||
return;
|
||||
}
|
||||
if bytes.len() as u64 > MAX_ZIP_UPLOAD {
|
||||
reply(request, 413, json!({"error": "ZIP upload exceeds 64 MB"}));
|
||||
return;
|
||||
}
|
||||
match self.store.create_from_zip(&name, &bytes) {
|
||||
Ok(project) => reply(request, 201, json!(project)),
|
||||
Err(error) => reply(request, 422, json!({"error": error})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create(&self, mut request: Request) {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct NewProject {
|
||||
name: String,
|
||||
}
|
||||
if !request.headers().iter().any(|header| {
|
||||
header.field.equiv("Content-Type")
|
||||
&& header.value.as_str().split(';').next() == Some("application/json")
|
||||
}) {
|
||||
reply(
|
||||
request,
|
||||
415,
|
||||
json!({"error": "Expected JSON project details"}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let project: NewProject = match super::read_json(&mut request) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
reply(request, 400, json!({"error": error}));
|
||||
return;
|
||||
}
|
||||
};
|
||||
match self.store.create_empty(&project.name) {
|
||||
Ok(project) => reply(request, 201, json!(project)),
|
||||
Err(error) => reply(request, 422, json!({"error": error})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open(&self, id: &str) -> Result<EditorSession, Box<dyn std::error::Error>> {
|
||||
let root = self.store.project_dir(id)?;
|
||||
if fs::symlink_metadata(&root)?.file_type().is_symlink() {
|
||||
return Err("The project directory must be a local working copy".into());
|
||||
}
|
||||
let info = self.store.info(id)?;
|
||||
if info.main_file.is_empty() {
|
||||
return Err("The project does not contain a TeX entry file".into());
|
||||
}
|
||||
let source = self.store.file_path(id, &info.main_file)?.canonicalize()?;
|
||||
let files = info
|
||||
.files
|
||||
.iter()
|
||||
.filter(|file| file.path != info.main_file)
|
||||
.map(|file| PathBuf::from(&file.path))
|
||||
.collect::<Vec<_>>();
|
||||
let run = fresh_run(&self.runs, id)?;
|
||||
let mut session = EditorSession::new(run, |run| {
|
||||
prepare(
|
||||
&root,
|
||||
&source,
|
||||
&self.format,
|
||||
&self.manifest,
|
||||
run,
|
||||
&files,
|
||||
self.profile,
|
||||
)
|
||||
})?;
|
||||
session.id = Some(info.id);
|
||||
Ok(session)
|
||||
}
|
||||
}
|
||||
|
||||
fn fresh_run(parent: &Path, id: &str) -> std::io::Result<PathBuf> {
|
||||
for index in 1.. {
|
||||
let candidate = parent.join(format!("{id}-{}-{index}", std::process::id()));
|
||||
match fs::create_dir(&candidate) {
|
||||
Ok(()) => return Ok(candidate),
|
||||
Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn project_name(request: &Request) -> String {
|
||||
let name = request
|
||||
.url()
|
||||
.split_once('?')
|
||||
.and_then(|(_, query)| query.split('&').find_map(|pair| pair.strip_prefix("name=")))
|
||||
.unwrap_or("Project");
|
||||
let mut bytes = Vec::with_capacity(name.len());
|
||||
let mut input = name.as_bytes().iter().copied();
|
||||
while let Some(byte) = input.next() {
|
||||
match byte {
|
||||
b'%' => {
|
||||
let hex = |byte: u8| char::from(byte).to_digit(16);
|
||||
if let Some(value) = input.next().and_then(hex).zip(input.next().and_then(hex)) {
|
||||
bytes.push((value.0 * 16 + value.1) as u8);
|
||||
}
|
||||
}
|
||||
b'+' => bytes.push(b' '),
|
||||
_ => bytes.push(byte),
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
}
|
||||
+327
-87
@@ -8,7 +8,7 @@ use std::{
|
||||
path::{Component, Path, PathBuf},
|
||||
sync::{
|
||||
Arc, Condvar, Mutex,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
@@ -19,10 +19,15 @@ use texrra_engine::native::{
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
execution::InputProfile,
|
||||
resources::{InputPolicy, SearchPath, WorldConfig},
|
||||
resources::{InputPolicy, ResourceKind, SearchPath, WorldConfig},
|
||||
};
|
||||
use tiny_http::{Header, Method, Request, Response, Server};
|
||||
|
||||
mod library;
|
||||
#[path = "../../src/projects.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod projects;
|
||||
mod resource_capture;
|
||||
mod saved_project;
|
||||
|
||||
const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024;
|
||||
@@ -177,6 +182,7 @@ struct Publication {
|
||||
|
||||
#[derive(Default)]
|
||||
struct Queue {
|
||||
closed: AtomicBool,
|
||||
next: Mutex<Option<Work>>,
|
||||
available: Condvar,
|
||||
current: AtomicU64,
|
||||
@@ -188,7 +194,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
std::process::exit(status);
|
||||
}
|
||||
let mut args = std::env::args_os().skip(1).peekable();
|
||||
let usage = "native_editor [--input-profile tex8bit|unicode|xetex] [--web-dir DIR] SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...]";
|
||||
let usage = "native_editor [--input-profile PROFILE] [--web-dir DIR] [--source-root DIR] SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...] or native_editor [--input-profile PROFILE] --web-dir DIR --projects STORE FORMAT FORMAT_RESOURCES RUNS [PORT]";
|
||||
let input_profile = if args.next_if(|arg| arg == "--input-profile").is_some() {
|
||||
match args.next().as_deref().and_then(std::ffi::OsStr::to_str) {
|
||||
Some("tex8bit") => InputProfile::TeX8Bit,
|
||||
@@ -205,63 +211,172 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut args = args.map(PathBuf::from);
|
||||
let source = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let manifest = args.next().ok_or(usage)?;
|
||||
let run = args.next().ok_or(usage)?;
|
||||
let port = args
|
||||
.next()
|
||||
.map(|s| s.to_string_lossy().parse())
|
||||
.transpose()?
|
||||
.unwrap_or(0u16);
|
||||
let additional = args.collect::<Vec<_>>();
|
||||
fs::create_dir(&run)?;
|
||||
let run = run.canonicalize()?;
|
||||
let EditorProject {
|
||||
mut project,
|
||||
entry,
|
||||
editable,
|
||||
declared,
|
||||
options,
|
||||
} = prepare(&source, &format, &manifest, &run, &additional, input_profile)?;
|
||||
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let source_root = if args.next_if(|arg| arg == "--source-root").is_some() {
|
||||
Some(PathBuf::from(args.next().ok_or(usage)?).canonicalize()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut args = args.map(PathBuf::from).peekable();
|
||||
let library = if args.next_if(|arg| arg == Path::new("--projects")).is_some() {
|
||||
let store = args.next().ok_or(usage)?;
|
||||
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let manifest = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let runs = args.next().ok_or(usage)?;
|
||||
Some(library::Library::new(
|
||||
store,
|
||||
format,
|
||||
manifest,
|
||||
runs,
|
||||
input_profile,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if library.is_some() && web.is_none() {
|
||||
return Err("The project library requires --web-dir".into());
|
||||
}
|
||||
let (port, mut session) = if library.is_some() {
|
||||
(read_port(args.next())?, None)
|
||||
} else {
|
||||
let source = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let manifest = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let run = args.next().ok_or(usage)?;
|
||||
let port = read_port(args.next())?;
|
||||
let additional = args.collect::<Vec<_>>();
|
||||
fs::create_dir(&run)?;
|
||||
let run = run.canonicalize()?;
|
||||
let root = source_root
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| source.parent().expect("a source file has a parent"));
|
||||
(
|
||||
port,
|
||||
Some(EditorSession::new(run, |run| {
|
||||
prepare(
|
||||
root,
|
||||
&source,
|
||||
&format,
|
||||
&manifest,
|
||||
run,
|
||||
&additional,
|
||||
input_profile,
|
||||
)
|
||||
})?),
|
||||
)
|
||||
};
|
||||
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
|
||||
let queue = Arc::new(Queue {
|
||||
current: AtomicU64::new(project.version().revision),
|
||||
..Queue::default()
|
||||
});
|
||||
std::thread::spawn({
|
||||
let queue = queue.clone();
|
||||
move || worker(&queue)
|
||||
});
|
||||
let mut save_number = 0;
|
||||
println!("Native editor http://{}", server.server_addr());
|
||||
for request in server.incoming_requests() {
|
||||
let path = request.url().to_owned();
|
||||
match (request.method(), path.as_str()) {
|
||||
(&Method::Get, "/") => respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref().map_or_else(|| PAGE.into(), |assets| assets.index.clone()),
|
||||
),
|
||||
(&Method::Get, "/styles.css") if web.is_some() => respond(
|
||||
request, 200, "text/css; charset=utf-8", web.as_ref().unwrap().styles.clone(),
|
||||
),
|
||||
(&Method::Get, "/favicon.svg") if web.is_some() => respond(
|
||||
request, 200, "image/svg+xml", web.as_ref().unwrap().favicon.clone(),
|
||||
),
|
||||
// The shared Web shell requests this stylesheet. Native preview
|
||||
// pages carry their glyph outlines in their SVG output.
|
||||
(&Method::Get, "/fonts.css") if web.is_some() => {
|
||||
respond(request, 200, "text/css; charset=utf-8", Vec::new())
|
||||
let url = request.url().to_owned();
|
||||
let path = url.as_str();
|
||||
if let (&Method::Get, Some(assets)) = (request.method(), &web) {
|
||||
if let Some((kind, bytes)) = assets.file(path) {
|
||||
respond(request, 200, kind, bytes);
|
||||
continue;
|
||||
}
|
||||
(&Method::Get, "/app.js") => respond(
|
||||
}
|
||||
if path == "/app.js" && request.method() == &Method::Get {
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/javascript; charset=utf-8",
|
||||
SCRIPT.into(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let mut session_path = path;
|
||||
if let Some(library) = &library {
|
||||
if path == "/" && request.method() == &Method::Get {
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref().unwrap().dashboard.clone(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if path == "/library.js" && request.method() == &Method::Get {
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/javascript; charset=utf-8",
|
||||
library::SCRIPT.into(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if path == "/api/projects" && request.method() == &Method::Get {
|
||||
library.list(request);
|
||||
continue;
|
||||
}
|
||||
if path.starts_with("/api/projects?") && request.method() == &Method::Post {
|
||||
library.import(request);
|
||||
continue;
|
||||
}
|
||||
if path == "/api/projects/new" && request.method() == &Method::Post {
|
||||
library.create(request);
|
||||
continue;
|
||||
}
|
||||
let Some((id, rest)) = path
|
||||
.strip_prefix("/p/")
|
||||
.and_then(|path| path.split_once('/'))
|
||||
else {
|
||||
reply(request, 404, json!({"error": "Not found"}));
|
||||
continue;
|
||||
};
|
||||
if rest.is_empty() && request.method() == &Method::Get {
|
||||
if session.as_ref().and_then(|s| s.id.as_deref()) != Some(id) {
|
||||
match library.open(id) {
|
||||
Ok(next) => session = Some(next),
|
||||
Err(error) => {
|
||||
reply(request, 422, json!({"error": error.to_string()}));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref().unwrap().index.clone(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if session.as_ref().and_then(|s| s.id.as_deref()) != Some(id) {
|
||||
reply(
|
||||
request,
|
||||
409,
|
||||
json!({"error": "The project is no longer open. Reload to reopen it."}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
session_path = &path[path.len() - rest.len() - 1..];
|
||||
}
|
||||
let Some(session) = &mut session else {
|
||||
reply(request, 404, json!({"error": "Not found"}));
|
||||
continue;
|
||||
};
|
||||
let EditorSession {
|
||||
run,
|
||||
compiler,
|
||||
queue,
|
||||
save_number,
|
||||
editor,
|
||||
..
|
||||
} = session;
|
||||
let EditorProject {
|
||||
project,
|
||||
entry,
|
||||
editable,
|
||||
declared,
|
||||
options,
|
||||
} = editor;
|
||||
match (request.method(), session_path) {
|
||||
(&Method::Get, "/") => respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref()
|
||||
.map_or_else(|| PAGE.into(), |assets| assets.index.clone()),
|
||||
),
|
||||
(&Method::Get, "/project") => {
|
||||
let file = project.file(&entry).expect("the editor owns its entry");
|
||||
@@ -274,7 +389,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
request,
|
||||
200,
|
||||
json!({
|
||||
"name": entry.file_name().unwrap().to_string_lossy(),
|
||||
"name": entry.strip_prefix(run.as_path()).unwrap().to_string_lossy(),
|
||||
"source": std::str::from_utf8(&file.data)?,
|
||||
"files": files,
|
||||
"sequence": queue.current.load(Ordering::Acquire),
|
||||
@@ -306,7 +421,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let path = editable
|
||||
.get(&name)
|
||||
.ok_or_else(|| format!("File is not editable: {name}"))?;
|
||||
if *path == entry && value.is_none() {
|
||||
if path == entry && value.is_none() {
|
||||
return Err("The entry file cannot be removed".into());
|
||||
}
|
||||
Ok((path.clone(), value.map(|text| Arc::from(text.into_bytes()))))
|
||||
@@ -322,7 +437,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
project.with_file_changes(edit.sequence, updates)
|
||||
});
|
||||
project = match next {
|
||||
*project = match next {
|
||||
Ok(project) => project,
|
||||
Err(error) => {
|
||||
reply(request, 422, json!({ "error": error }));
|
||||
@@ -367,17 +482,31 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
};
|
||||
if save.sequence < queue.current.load(Ordering::Acquire) {
|
||||
reply(request, 409, json!({"error": "A newer edit is already queued"}));
|
||||
reply(
|
||||
request,
|
||||
409,
|
||||
json!({"error": "A newer edit is already queued"}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let changes: Option<BTreeMap<_, _>> = save.files.iter()
|
||||
.map(|(name, data)| editable.get(name).map(|path| (path.as_path(), data.as_bytes())))
|
||||
let changes: Option<BTreeMap<_, _>> = save
|
||||
.files
|
||||
.iter()
|
||||
.map(|(name, data)| {
|
||||
editable
|
||||
.get(name)
|
||||
.map(|path| (path.as_path(), data.as_bytes()))
|
||||
})
|
||||
.collect();
|
||||
let Some(changes) = changes else {
|
||||
reply(request, 422, json!({"error": "The save refers to an unknown source file"}));
|
||||
reply(
|
||||
request,
|
||||
422,
|
||||
json!({"error": "The save refers to an unknown source file"}),
|
||||
);
|
||||
continue;
|
||||
};
|
||||
match saved_project::save(&run, &entry, &declared, &project, changes, &mut save_number) {
|
||||
match saved_project::save(run, entry, declared, project, changes, save_number) {
|
||||
Ok(path) => reply(request, 200, json!({"directory": path})),
|
||||
Err(error) => reply(request, 500, json!({"error": error.to_string()})),
|
||||
}
|
||||
@@ -442,6 +571,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
|
||||
struct WebAssets {
|
||||
dashboard: Vec<u8>,
|
||||
index: Vec<u8>,
|
||||
styles: Vec<u8>,
|
||||
favicon: Vec<u8>,
|
||||
@@ -449,12 +579,77 @@ struct WebAssets {
|
||||
|
||||
impl WebAssets {
|
||||
fn load(path: &Path) -> std::io::Result<Self> {
|
||||
let index = fs::read_to_string(path.join("index.html"))?;
|
||||
let dashboard = index.replace("src=\"/app.js\"", "src=\"/library.js\"");
|
||||
Ok(Self {
|
||||
index: fs::read(path.join("index.html"))?,
|
||||
dashboard: dashboard.into_bytes(),
|
||||
index: index.into_bytes(),
|
||||
styles: fs::read(path.join("styles.css"))?,
|
||||
favicon: fs::read(path.join("favicon.svg"))?,
|
||||
})
|
||||
}
|
||||
|
||||
fn file(&self, path: &str) -> Option<(&'static str, Vec<u8>)> {
|
||||
match path {
|
||||
"/styles.css" => Some(("text/css; charset=utf-8", self.styles.clone())),
|
||||
"/favicon.svg" => Some(("image/svg+xml", self.favicon.clone())),
|
||||
"/fonts.css" => Some(("text/css; charset=utf-8", Vec::new())),
|
||||
"/app.js" => Some(("text/javascript; charset=utf-8", SCRIPT.into())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_port(value: Option<PathBuf>) -> Result<u16, std::num::ParseIntError> {
|
||||
value.map_or(Ok(0), |port| port.to_string_lossy().parse())
|
||||
}
|
||||
|
||||
struct EditorSession {
|
||||
id: Option<String>,
|
||||
run: PathBuf,
|
||||
compiler: NativeCompiler,
|
||||
queue: Arc<Queue>,
|
||||
save_number: u64,
|
||||
editor: EditorProject,
|
||||
}
|
||||
|
||||
impl EditorSession {
|
||||
fn new(
|
||||
run: PathBuf,
|
||||
prepare_editor: impl FnOnce(&Path) -> Result<EditorProject, Box<dyn std::error::Error>>,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let editor = prepare_editor(&run)?;
|
||||
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let queue = Arc::new(Queue {
|
||||
current: AtomicU64::new(editor.project.version().revision),
|
||||
..Queue::default()
|
||||
});
|
||||
std::thread::spawn({
|
||||
let queue = queue.clone();
|
||||
move || worker(&queue)
|
||||
});
|
||||
Ok(Self {
|
||||
id: None,
|
||||
run,
|
||||
compiler,
|
||||
queue,
|
||||
save_number: 0,
|
||||
editor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EditorSession {
|
||||
fn drop(&mut self) {
|
||||
let mut pending = self.queue.next.lock().unwrap();
|
||||
self.queue.closed.store(true, Ordering::Release);
|
||||
// A fresh revision cancels any work still running on the old session.
|
||||
self.compiler.start();
|
||||
if let Some(old) = pending.take() {
|
||||
reply(old.request, 409, json!({"error": "The project has closed"}));
|
||||
}
|
||||
self.queue.available.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn read_json<T: serde::de::DeserializeOwned>(request: &mut Request) -> Result<T, String> {
|
||||
@@ -479,6 +674,7 @@ struct EditorProject {
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
source_root: &Path,
|
||||
source: &Path,
|
||||
format: &Path,
|
||||
manifest: &Path,
|
||||
@@ -491,16 +687,24 @@ fn prepare(
|
||||
let mut world = WorldConfig::from_environment(run, roots)?;
|
||||
world.input_policy = InputPolicy::Tex;
|
||||
let name = source
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.strip_prefix(source_root)?
|
||||
.to_str()
|
||||
.ok_or("Source needs a UTF-8 filename")?;
|
||||
let entry = run.join(name);
|
||||
let entry_dir = entry.parent().expect("the entry has a parent");
|
||||
fs::create_dir_all(entry_dir)?;
|
||||
if entry_dir != run {
|
||||
world
|
||||
.paths
|
||||
.entry(ResourceKind::Tex)
|
||||
.or_insert_with(|| vec![SearchPath::Defaults])
|
||||
.insert(0, SearchPath::directory(entry_dir, false));
|
||||
}
|
||||
let original = fs::read(source)?;
|
||||
std::str::from_utf8(&original)?;
|
||||
fs::write(&entry, &original)?;
|
||||
let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]);
|
||||
let mut files = BTreeMap::<PathBuf, Arc<[u8]>>::from([(entry.clone(), Arc::from(original))]);
|
||||
let source_root = source.parent().expect("the entry has a parent");
|
||||
let mut declared = BTreeSet::from([entry.clone()]);
|
||||
let mut directories = BTreeSet::new();
|
||||
for relative in additional {
|
||||
@@ -561,12 +765,14 @@ fn prepare(
|
||||
files.insert(logical, data);
|
||||
}
|
||||
}
|
||||
let mut request = CompileRequest::new(
|
||||
world.clone(),
|
||||
&entry,
|
||||
entry.with_extension("pdf"),
|
||||
job_time()?,
|
||||
);
|
||||
let mut output = entry.with_extension("pdf");
|
||||
if declared.contains(&output) || declared.contains(&output.with_extension("log")) {
|
||||
let directory = run.join(".texrra-output");
|
||||
fs::create_dir(&directory)?;
|
||||
directories.insert(directory.clone());
|
||||
output = directory.join(output.file_name().expect("the output has a filename"));
|
||||
}
|
||||
let mut request = CompileRequest::new(world.clone(), &entry, output, job_time()?);
|
||||
request.entry = Entry::Format(format.into());
|
||||
request.etex = true;
|
||||
request.input_profile = input_profile;
|
||||
@@ -574,13 +780,28 @@ fn prepare(
|
||||
request = request.observe_generated_initial();
|
||||
// Provision the finite, immutable resource bundle used by this trial.
|
||||
// The seed uses the same native compiler and actual package bytes.
|
||||
let seed = NativeCompiler::default().compile(request.clone())?;
|
||||
for (path, captured) in seed.inputs.files() {
|
||||
if !path.starts_with(run) {
|
||||
files.insert(path.to_owned(), captured?.data.clone());
|
||||
let seed = NativeCompiler::default().compile_detailed(request.clone());
|
||||
let (inputs, trace, generated) = match &seed {
|
||||
Ok(seed) => (
|
||||
Some(seed.inputs.as_ref()),
|
||||
Some(&seed.resources.trace),
|
||||
Some(&seed.resources.generated_artifacts),
|
||||
),
|
||||
Err(failure) if matches!(failure.error, CompileError::Execution(_)) => (
|
||||
failure.inputs.as_deref(),
|
||||
failure.trace.as_ref(),
|
||||
failure.resources.as_ref().map(|r| &r.generated_artifacts),
|
||||
),
|
||||
Err(failure) => return Err(failure.error.to_string().into()),
|
||||
};
|
||||
for (path, captured) in inputs.iter().flat_map(|inputs| inputs.files()) {
|
||||
if let Ok(file) = captured
|
||||
&& !path.starts_with(run)
|
||||
{
|
||||
files.insert(path.to_owned(), file.data.clone());
|
||||
}
|
||||
}
|
||||
for lookup in &seed.resources.trace.lookups {
|
||||
for lookup in trace.iter().flat_map(|trace| &trace.lookups) {
|
||||
if let Some(path) = &lookup.resolved
|
||||
&& !path.starts_with(run)
|
||||
&& !files.contains_key(path)
|
||||
@@ -605,11 +826,9 @@ fn prepare(
|
||||
coverage.insert(path.parent().ok_or("A resource needs a parent")?.to_owned());
|
||||
}
|
||||
}
|
||||
let generated = seed
|
||||
.resources
|
||||
.generated_artifacts
|
||||
.writes
|
||||
let generated = generated
|
||||
.iter()
|
||||
.flat_map(|artifacts| &artifacts.writes)
|
||||
.map(|write| write.path.clone())
|
||||
.collect();
|
||||
let project = ProjectSnapshot::new(ProjectDefinition {
|
||||
@@ -632,8 +851,16 @@ fn prepare(
|
||||
}
|
||||
|
||||
fn worker(queue: &Arc<Queue>) {
|
||||
let mut resources = resource_capture::ResourceCapture::default();
|
||||
loop {
|
||||
let Work {
|
||||
let work = queue
|
||||
.available
|
||||
.wait_while(queue.next.lock().unwrap(), |next| {
|
||||
next.is_none() && !queue.closed.load(Ordering::Acquire)
|
||||
})
|
||||
.unwrap()
|
||||
.take();
|
||||
let Some(Work {
|
||||
request,
|
||||
job,
|
||||
mut compile,
|
||||
@@ -641,12 +868,10 @@ fn worker(queue: &Arc<Queue>) {
|
||||
visible_revision,
|
||||
received,
|
||||
preview_draft,
|
||||
} = queue
|
||||
.available
|
||||
.wait_while(queue.next.lock().unwrap(), |next| next.is_none())
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("the worker was woken with an edit");
|
||||
}) = work
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let observer = Arc::new(EditorObserver {
|
||||
started: Instant::now(),
|
||||
ended: Mutex::new([0.0; 5]),
|
||||
@@ -659,7 +884,22 @@ fn worker(queue: &Arc<Queue>) {
|
||||
});
|
||||
let revision = job.revision();
|
||||
compile.observer = Some(observer.clone());
|
||||
let result = job.compile(compile);
|
||||
let mut project = compile
|
||||
.project
|
||||
.clone()
|
||||
.expect("the editor submits a project snapshot");
|
||||
project = resources
|
||||
.apply(&project)
|
||||
.expect("captured resources retain their original roots");
|
||||
let result = job
|
||||
.compile_expanding_project(compile.with_project(project.clone()), |failure| {
|
||||
if observer.request.lock().unwrap().is_none() || !observer.is_current() {
|
||||
return None;
|
||||
}
|
||||
project = resources.expand(&project, failure)?;
|
||||
Some(project.clone())
|
||||
})
|
||||
.map_err(|failure| failure.error);
|
||||
let compile_ms = observer.elapsed_ms();
|
||||
let request = observer.request.lock().unwrap().take();
|
||||
let Some(request) = request else {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
};
|
||||
use texrra_engine::native::CompileFailure;
|
||||
use texrra_tex_core::resources::{FileWorld, ProjectSnapshot, ResourceKind, SearchPath};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ResourceCapture {
|
||||
resources: BTreeMap<PathBuf, Arc<[u8]>>,
|
||||
host: Option<FileWorld>,
|
||||
}
|
||||
|
||||
impl ResourceCapture {
|
||||
pub(super) fn apply(
|
||||
&self,
|
||||
project: &Arc<ProjectSnapshot>,
|
||||
) -> Result<Arc<ProjectSnapshot>, String> {
|
||||
project.with_external_resources(&self.resources)
|
||||
}
|
||||
|
||||
pub(super) fn expand(
|
||||
&mut self,
|
||||
project: &Arc<ProjectSnapshot>,
|
||||
failure: &CompileFailure,
|
||||
) -> Option<Arc<ProjectSnapshot>> {
|
||||
let trace = failure.trace.as_ref()?;
|
||||
let config = project.configuration();
|
||||
let search_roots = config
|
||||
.texmf_roots
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(
|
||||
config
|
||||
.paths
|
||||
.values()
|
||||
.flatten()
|
||||
.filter_map(|path| match path {
|
||||
SearchPath::Directory { path, .. } => Some(config.cwd.join(path)),
|
||||
SearchPath::Defaults => None,
|
||||
}),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
let host = match &mut self.host {
|
||||
Some(host) => host,
|
||||
slot => slot.insert(FileWorld::new(config.clone()).ok()?),
|
||||
};
|
||||
let mut queried = BTreeSet::new();
|
||||
let mut added = BTreeMap::new();
|
||||
for lookup in trace
|
||||
.lookups
|
||||
.iter()
|
||||
.filter(|lookup| lookup.resolved.is_none())
|
||||
{
|
||||
if !queried.insert((lookup.kind, &lookup.name, &lookup.from)) {
|
||||
continue;
|
||||
}
|
||||
let resolved = if lookup.kind == ResourceKind::Tex {
|
||||
host.resolve_tex_input(&lookup.name, &lookup.from)
|
||||
} else {
|
||||
host.resolve(lookup.kind, &lookup.name, &lookup.from)
|
||||
};
|
||||
if let Ok(Some(path)) = resolved
|
||||
&& !path.starts_with(&config.cwd)
|
||||
&& search_roots.iter().any(|root| path.starts_with(root))
|
||||
&& project.file(&path).is_none()
|
||||
&& fs::metadata(&path).is_ok_and(|metadata| metadata.is_file())
|
||||
&& let Ok(bytes) = fs::read(&path)
|
||||
{
|
||||
added.insert(path, Arc::from(bytes));
|
||||
}
|
||||
}
|
||||
if added.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let expanded = project.with_external_resources(&added).ok()?;
|
||||
self.resources.extend(added);
|
||||
Some(expanded)
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,9 @@ pub(super) fn save(
|
||||
files.push(name);
|
||||
}
|
||||
}
|
||||
let entry_name = entry.file_name().expect("the entry has a name").to_str().unwrap();
|
||||
let entry_name = entry
|
||||
.strip_prefix(run)
|
||||
.expect("entry stays in the working copy");
|
||||
let manifest = fs::File::create(staging.join("project.json"))?;
|
||||
serde_json::to_writer_pretty(manifest, &serde_json::json!({
|
||||
"entry": entry_name, "files": files,
|
||||
|
||||
Reference in new issue
Block a user