Compare commits
4
Commits
fb557c09c6
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe86163767 | ||
|
|
8b6dab8d52 | ||
|
|
29193c03bc | ||
|
|
9841e88900 |
No files matched your search
@@ -10,8 +10,8 @@ where their state, file effects, and cancellation can be verified.
|
||||
The [product goal](docs/NATIVE_PRODUCT_GOAL.md) defines compatibility and live
|
||||
preview acceptance. The [publisher matrix](docs/PUBLISHER_TEMPLATE_MATRIX.md)
|
||||
covers original journals, two-column journals, conferences, and arXiv.
|
||||
The [local beta milestone](docs/NATIVE_PRODUCT_GOAL.md#beta-优先交付) describes
|
||||
the first supported projects and the edit, preview, and export workflow.
|
||||
The [local beta guide](docs/NATIVE_BETA.md) explains how to prepare a bundle,
|
||||
open a project in the native editor, and export a PDF.
|
||||
|
||||
## Native execution bootstrap
|
||||
|
||||
|
||||
@@ -625,7 +625,7 @@ impl DisplayList {
|
||||
write!(
|
||||
out,
|
||||
"<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"",
|
||||
escape(font), escape(glyph), escape(&label), path,
|
||||
escape_attribute(font), escape_attribute(glyph), escape_attribute(&label), path,
|
||||
).unwrap();
|
||||
if let Some([vx2, vy]) = vertical_origin {
|
||||
let vx = f64::from(vx2) / 2.0;
|
||||
@@ -680,7 +680,7 @@ impl DisplayList {
|
||||
write!(
|
||||
out,
|
||||
"<g data-font=\"{}\" data-glyph=\"{glyph}\" aria-label=\"{}\"><path d=\"{path}\" transform=\"translate({x:.5} {y:.5})",
|
||||
escape(&font.name), escape(text),
|
||||
escape_attribute(&font.name), escape_attribute(text),
|
||||
).unwrap();
|
||||
if transform.is_none() {
|
||||
if let Some([a, b, c, d, e, f]) = vertical {
|
||||
@@ -733,7 +733,7 @@ impl DisplayList {
|
||||
let scale = *size as f64 / 65_536_000.0;
|
||||
out.push_str(&format!(
|
||||
"<g data-font=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><use href=\"#math-{}-{slot}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/><text x=\"{x:.5}\" y=\"{y:.5}\" opacity=\"0\" aria-hidden=\"true\">{}</text></g>\n",
|
||||
face.name(), escape(&character.to_string()), face.0,
|
||||
escape_attribute(face.name()), escape_attribute(&character.to_string()), face.0,
|
||||
fill[0], fill[1], fill[2], escape(&character.to_string())
|
||||
));
|
||||
}
|
||||
@@ -1083,6 +1083,15 @@ fn base64(data: &[u8]) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn escape_attribute(text: &str) -> String {
|
||||
let escaped = escape(text);
|
||||
if text.contains('"') {
|
||||
escaped.replace('"', """)
|
||||
} else {
|
||||
escaped
|
||||
}
|
||||
}
|
||||
|
||||
fn escape(text: &str) -> String {
|
||||
text.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
|
||||
@@ -151,6 +151,34 @@ impl ProjectSnapshot {
|
||||
next.seal()
|
||||
}
|
||||
|
||||
/// Extend the immutable external inputs without changing project buffers
|
||||
/// or granting writes outside the original project.
|
||||
pub fn with_external_resources(
|
||||
self: &Arc<Self>,
|
||||
resources: &BTreeMap<PathBuf, Arc<[u8]>>,
|
||||
) -> Result<Arc<Self>, String> {
|
||||
if resources.keys().all(|path| self.files.contains_key(path)) {
|
||||
return Ok(self.clone());
|
||||
}
|
||||
let mut next = self.next_revision(self.version.revision)?;
|
||||
for (path, data) in resources {
|
||||
if next.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
if path.starts_with(&self.configuration.cwd) || !self.covered(path) {
|
||||
return Err(format!(
|
||||
"external resource is outside declared roots: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
next.files
|
||||
.insert(path.clone(), Self::capture(path.clone(), data.clone()));
|
||||
next.directories
|
||||
.extend(path.ancestors().skip(1).map(Path::to_path_buf));
|
||||
}
|
||||
next.seal()
|
||||
}
|
||||
|
||||
fn next_revision(&self, revision: u64) -> Result<Self, String> {
|
||||
self.validate()?;
|
||||
let mut next = self.clone();
|
||||
|
||||
@@ -6,11 +6,31 @@ use texrra_tex_core::math::{MathAtom, parse_math};
|
||||
use texrra_tex_core::math_font::MathFontId;
|
||||
use texrra_tex_core::paragraph::{HorizontalItem, InlineSegment, ParagraphFont, ParagraphStyle};
|
||||
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1};
|
||||
use texrra_tex_core::render::DisplayItem;
|
||||
use texrra_tex_core::render::{DisplayItem, DisplayList};
|
||||
use texrra_tex_core::{Document, Engine, Unit, VerticalItem};
|
||||
|
||||
const PT: i64 = 65_536;
|
||||
|
||||
#[test]
|
||||
fn svg_glyph_labels_escape_attribute_quotes() {
|
||||
let display = DisplayList {
|
||||
width: 12 * PT,
|
||||
height: 12 * PT,
|
||||
items: vec![DisplayItem::MathGlyph {
|
||||
x: 0,
|
||||
y: 6 * PT,
|
||||
size: 10 * PT,
|
||||
character: '"',
|
||||
face: MathFontId(0),
|
||||
slot: b'"',
|
||||
}],
|
||||
..DisplayList::default()
|
||||
};
|
||||
let svg = display.try_to_svg().unwrap();
|
||||
assert!(svg.contains(r#"aria-label="""><use"#));
|
||||
assert!(svg.contains(r#"aria-hidden="true">"</text>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_display_edits_replay_the_preceding_paragraph_dependency() {
|
||||
let style = ParagraphStyle {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# Route-D 本地 Beta
|
||||
|
||||
本地编辑器和命令行使用同一原生编译内核。准备时使用机器上已有的
|
||||
TeX Live、字体和宏包。生成的目录包含两个程序、原生格式、资源记录
|
||||
和 A4 多文件样例。格式沿用本机实际资源路径。
|
||||
|
||||
## 准备与启动
|
||||
|
||||
在安装了 Rust、Python 3.11 或更高版本与 TeX Live 的环境中,从仓库根目录运行。
|
||||
目前这套流程已在 Fedora WSL 验证。
|
||||
|
||||
```sh
|
||||
cargo build --locked --release --bin texrra --example native_editor
|
||||
python3 scripts/native-beta.py prepare target/local-beta
|
||||
python3 target/local-beta/native-beta.py open
|
||||
```
|
||||
|
||||
脚本调用 Route-D 执行 TeX Live 的原样 pdflatex.ini。首次准备会执行格式初始化。
|
||||
编辑器启动后会在终端显示本地网址。打开该网址即可切换样例的主文件和子文件,
|
||||
查看页面并下载 PDF。
|
||||
|
||||
准备 XeLaTeX 格式时加 `--input-profile xetex`。用 `--texmf-root` 指定额外
|
||||
宏包或字体所在的 TeX 树时,按查找顺序列出本机使用的全部树。也可以成对给出
|
||||
`--format-image` 和 `--format-resources`,使用在相同环境生成的格式与资源清单。
|
||||
准备过程把实际资源搜索配置写进 `bundle.json`,供编辑器与命令行共用。
|
||||
|
||||
## 打开自己的项目
|
||||
|
||||
```sh
|
||||
python3 target/local-beta/native-beta.py open /path/to/main.tex \
|
||||
--file chapter.tex --file figures/plot.pdf
|
||||
python3 target/local-beta/native-beta.py compile /path/to/main.tex /path/to/output.pdf
|
||||
```
|
||||
|
||||
`--file` 接收相对于主文件目录的路径,可列出子文件及实际使用的图像等资源。
|
||||
编辑器在试用目录中创建工作副本。命令行按项目实际读写作业文件。
|
||||
需要 BibTeX 的项目可在辅助文件生成后运行 BibTeX,再继续 LaTeX 编译到引用收敛。
|
||||
|
||||
## 使用项目的 Web 界面
|
||||
|
||||
将 texrra-web 放在引擎仓库旁边。从项目列表新建项目或拖入 ZIP。
|
||||
|
||||
~~~sh
|
||||
python3 target/local-beta/native-beta.py web --web-dir ../texrra-web --projects-dir target/local-projects
|
||||
~~~
|
||||
|
||||
导入后打开项目的主文件,左侧可切换源文件,右侧显示原生实时预览。
|
||||
ZIP 可包含子目录、源文件及图像等资源。库中的导入副本保留原样,
|
||||
编辑时点击「保存源文件」生成独立副本。当前本地服务同时打开一个项目。
|
||||
|
||||
也可用 Web 工作台直接打开样例或重开已保存的项目。
|
||||
|
||||
~~~sh
|
||||
python3 target/local-beta/native-beta.py open --web-dir ../texrra-web
|
||||
python3 target/local-beta/native-beta.py resume /path/to/saved-project --web-dir ../texrra-web
|
||||
~~~
|
||||
|
||||
## 输入公式
|
||||
|
||||
编辑源文件时用 $...$ 输入行内公式,用 \[...\] 输入陈列公式。
|
||||
使用 align 等环境时,在导言区加入 \usepackage{amsmath}。
|
||||
例如在正文中输入以下内容。
|
||||
|
||||
~~~latex
|
||||
行内公式 $E=mc^2$。
|
||||
\[
|
||||
\frac{\alpha+\beta}{\sqrt{1+x^2}}
|
||||
\]
|
||||
~~~
|
||||
|
||||
## 保存和重新打开
|
||||
|
||||
点击「保存源文件」将当前编辑与已声明的项目资源一起写入一个新目录。
|
||||
目录路径显示在编辑器中。里面的 sources 子目录包含可单独使用的项目文件,
|
||||
预览的 PDF 可通过「下载 PDF」另行取得。使用原 Beta 包打开保存目录。
|
||||
|
||||
~~~sh
|
||||
python3 target/local-beta/native-beta.py resume /path/to/texrra-sources-directory
|
||||
~~~
|
||||
|
||||
有编译错误的草稿也可以保存和重开。打开后可在编辑器修正错误。
|
||||
每次保存都会得到独立的一份。
|
||||
|
||||
## 已对照的项目
|
||||
|
||||
| 原样项目 | 编译模式 | 收敛页数 |
|
||||
| --- | --- | ---: |
|
||||
| 仓库 arXiv 样例 | pdfLaTeX | 3 |
|
||||
| PLOS ONE | pdfLaTeX | 5 |
|
||||
| Elsevier CAS 双栏 | pdfLaTeX | 6 |
|
||||
| IEEE 会议 | pdfLaTeX | 1 |
|
||||
| NeurIPS 2025 | XeLaTeX | 12 |
|
||||
|
||||
同一内核构建的实际参考对照见 [阶段记录](P2_M1_PROGRESS.md)。
|
||||
样例的上游来源和资源版本见 [出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。
|
||||
更广的兼容性与正式实时性能按 [产品总目标](NATIVE_PRODUCT_GOAL.md) 继续验收。
|
||||
@@ -18,6 +18,97 @@
|
||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 |
|
||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||
|
||||
## 2026-11-29 原生 Web Beta 公式与项目导入
|
||||
|
||||
空白正文首次编译后再编辑公式,旧版本会把尚未捕获的已安装数学字体
|
||||
和宏包判为缺失。原生编辑会话按失败查找记录,在声明的 TeX 资源树中
|
||||
解析实际文件,扩展只读输入快照并在同一修订重试。保留已有输入字节、
|
||||
输出权限和取消行为。真正的编译错误仍保留上一版可下载 PDF。
|
||||
|
||||
现有 Web 项目列表接通本地项目库和 ZIP 拖放。原样 A4 多文件放在
|
||||
ZIP 的子目录,已有同名 PDF 和额外图像保留原字节。Edge 中首次
|
||||
插入行内公式、陈列公式,再添加 amsmath 与 align。每次实际改变
|
||||
版面只替换第一页。未知命令显示诊断,恢复后能继续编辑。下载的
|
||||
PDF 与保存源码副本的独立命令行两轮编译逐字节一致。
|
||||
|
||||
证据在 target/native-beta-library/。SHA256SUMS 指纹为
|
||||
3e606a869968058f881f9faa440976e1a767fe5e49b2c99c6cb32b2386083b1c。
|
||||
试用包沿用已验证的 pdfLaTeX 格式和本机 TeX Live 资源。
|
||||
[Web 启动和公式输入](NATIVE_BETA.md#使用项目的-web-界面)
|
||||
|
||||
## 2026-11-29 原生 Beta 接入 texrra-web 工作台
|
||||
|
||||
本地启动器的 --web-dir 接入现有 texrra-web 的 HTML、样式和图标。
|
||||
原生会话脚本连接同一工作台的文件栏、编辑、报错、局部页面和 PDF
|
||||
下载,支持保存源码副本及快捷键。该入口一次打开一个指定项目。
|
||||
既有项目列表与 ZIP 导入的迁移属于后续集成。
|
||||
|
||||
固定 Web 仓库 e14b7aa 及 A4 原样多文件输入。在 Edge 验证工作台
|
||||
打开、子文件切换、修改、保存、错误和恢复。修改后只更新第一页,
|
||||
来源表记录本轮子文件字节。错版继续提供上次 PDF,恢复相同文本
|
||||
沿用已显示页。下载 PDF 及辅助文件与保存副本的独立 CLI 两轮收敛
|
||||
结果逐字节一致。保留真实浏览器截图及 HTML、样式和图标身份。
|
||||
|
||||
本机试用包位于 target/native-beta-web/beta-pdftex/。证据目录
|
||||
target/native-beta-web/ 的 SHA256SUMS 指纹为
|
||||
023b5d857af62da963b7d9b2e51157534c4f14f0c256dbf81d207923bc7d4bfe。
|
||||
[Web 启动方式](NATIVE_BETA.md#使用项目的-web-界面)
|
||||
|
||||
## 2026-11-29 Beta 源码保存和恢复
|
||||
|
||||
编辑器保存时将当前浏览器缓冲与已声明的输入资源一并写入一个
|
||||
源码副本。先完成全部文件和恢复清单,再发布新目录。保存与编译
|
||||
各自处理,已有输出继续按编译版本发布。resume 读取保存目录的
|
||||
入口和实际相对路径,建立新的编译工作目录。
|
||||
|
||||
用原样 A4 主文件和子文件在 Edge 验证。在同一次操作中修改两个
|
||||
文件并保存,随后收到更新的预览。额外声明的嵌套 PDF 资源按实际
|
||||
字节保存。引入未知命令的草稿可另存,错误期间仍可下载上次 PDF。
|
||||
两次源码副本保持独立。已验证旧版本、未知文件和非 JSON 请求均被
|
||||
拒绝,未创建额外副本。
|
||||
|
||||
重新启动有效副本后,浏览器缓冲、PDF 及辅助文件与独立 CLI 两轮
|
||||
收敛作业一致。测试输入文件指纹保持。错误草稿当前重开仍受首次
|
||||
编译限制,失败和保存下来的源文件均保留。下一批从错误草稿可打开
|
||||
的资源准备路径及原样多页项目的启动耗时继续推进。
|
||||
|
||||
本机包在 target/native-beta-save/beta-pdftex/。证据目录
|
||||
target/native-beta-save/ 的 SHA256SUMS 指纹为
|
||||
46d0ba4d0fd0afe15a3dad8f19915a7ef3048c3964cae240611fc60b05053c4c。
|
||||
[Beta 使用指南](NATIVE_BETA.md#保存和重新打开)
|
||||
|
||||
## 2026-11-29 本地 Beta 启动与五份原样模板
|
||||
|
||||
本地启动脚本准备同一构建的原生 CLI、编辑器、实际格式与资源配置。
|
||||
Fedora WSL 上实际执行原样 pdflatex.ini 生成格式,并用该格式打开
|
||||
A4 多文件。编辑器 PDF 与独立命令行从空 aux 收敛的 PDF 逐字节相同。
|
||||
两个 profile 的本地包都走通启动。[使用指南](NATIVE_BETA.md)
|
||||
|
||||
原样 arXiv、PLOS ONE、Elsevier CAS 双栏、IEEE 会议和 XeLaTeX
|
||||
NeurIPS 2025 合计 27 页、10,843 个词框。词序、词框和 144 DPI
|
||||
灰度光栅逐页与冻结参考一致。各轮 aux 及实际流程生成的 bbl 或 out
|
||||
逐字节一致。arXiv 首轮对照的首页含不同的编译日期。保持源文件与
|
||||
格式,明确使用冻结参考的 2026-11-20 日期复验后首页一致。
|
||||
保留初次差异。发布构建再次运行各项目的收敛作业,源输入和已核对的
|
||||
PDF、aux、bbl、out 指纹全部保持。
|
||||
|
||||
12 页 NeurIPS 在编辑器首次预览遇到两个问题,均保留失败材料。种子
|
||||
作业从一个显式字体路径找不到字形字体后,继续在 TeX 树解析成功。
|
||||
快照现在保留实际存在的显式资源搜索目录及读到的字节。四页原生 SVG
|
||||
随后暴露了字形属性中的未转义双引号。共享 SVG 输出修复了属性转义,
|
||||
并增加定向回归。最终在 Edge 实际绘制全部 12 页。编辑和故障恢复
|
||||
各只替换第 12 页,前 11 页保留 DOM 页面。错误请求保留可下载 PDF。
|
||||
编辑版 PDF、aux 和 out 与同一构建的独立命令行收敛作业逐字节一致,
|
||||
恢复 PDF 与原样导出逐字节一致。单次记录为首屏 20.54 秒、编辑后
|
||||
可见 2.60 秒、恢复 0.83 秒。该次执行期间同机在复验出版样例。
|
||||
|
||||
本地 Beta 现在提供试用入口。当前编辑内容保存在会话,下一批优先
|
||||
推进工作副本的源文件保存,并用原样多页项目定位首次预览与编辑耗时。
|
||||
正式完整迁移和实时门槛按产品总目标验收。
|
||||
|
||||
证据在 target/native-beta-validation/。SHA256SUMS 指纹为
|
||||
dd3d8a4d2dff519ad634eca6e75b04b6bff4ee2a87ca46ab2df9dfccd4cce439。
|
||||
|
||||
## 2026-11-29 行盒尺寸、分页返回与本地 Beta 验证
|
||||
|
||||
pdfTeX 的每行、首行和末行高度深度参数进入实际段落行盒。首行高度
|
||||
|
||||
+108
-17
@@ -1,10 +1,17 @@
|
||||
const workspace = document.querySelector("#workspace");
|
||||
if (workspace) attachWebControls();
|
||||
|
||||
const source = document.querySelector("#source");
|
||||
const pages = document.querySelector("#pages");
|
||||
const status = document.querySelector("#status");
|
||||
const error = document.querySelector("#error");
|
||||
const status = document.querySelector("#status, #preview-status");
|
||||
const error = document.querySelector("#error, #preview-error-text");
|
||||
const errorPanel = document.querySelector("#error, #preview-error");
|
||||
const pdf = document.querySelector("#pdf");
|
||||
const save = document.querySelector("#save");
|
||||
const saved = document.querySelector("#saved, #file-panel-foot");
|
||||
const selector = document.querySelector("#project-files");
|
||||
const name = document.querySelector("#name");
|
||||
const name = document.querySelector("#name, #open-file-path");
|
||||
const fileTree = document.querySelector("#file-tree");
|
||||
const edits = new Map();
|
||||
let files;
|
||||
let activeFile;
|
||||
@@ -12,18 +19,65 @@ 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() {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.id = "save";
|
||||
button.className = "btn";
|
||||
button.disabled = true;
|
||||
button.textContent = "保存源文件";
|
||||
document.querySelector(".file-tools").replaceChildren(button);
|
||||
|
||||
const download = document.createElement("a");
|
||||
download.id = "pdf";
|
||||
download.className = "btn small";
|
||||
download.download = "";
|
||||
download.hidden = true;
|
||||
download.textContent = "下载 PDF";
|
||||
document.querySelector("#export-pdf").replaceWith(download);
|
||||
|
||||
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 保存源码副本";
|
||||
document.querySelector("#source").disabled = true;
|
||||
document.querySelector("#file-panel-foot").setAttribute("role", "status");
|
||||
document.querySelector("#file-panel-foot").style.overflowWrap = "anywhere";
|
||||
workspace.hidden = false;
|
||||
}
|
||||
|
||||
function selectFile(filename) {
|
||||
activeFile = filename;
|
||||
name.textContent = filename;
|
||||
source.value = edits.get(filename) ?? files.get(filename);
|
||||
if (fileTree) {
|
||||
for (const row of fileTree.children) {
|
||||
const selected = row.dataset.path === activeFile;
|
||||
row.classList.toggle("active", selected);
|
||||
row.setAttribute("aria-pressed", selected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
status.textContent = "编译失败";
|
||||
error.textContent = message;
|
||||
error.hidden = false;
|
||||
errorPanel.hidden = false;
|
||||
}
|
||||
|
||||
function pageImage(page) {
|
||||
const img = new Image();
|
||||
img.alt = `第 ${page.index + 1} 页`;
|
||||
img.dataset.index = page.index;
|
||||
if (workspace) {
|
||||
img.className = "page";
|
||||
img.style.aspectRatio = "auto";
|
||||
}
|
||||
img.src = URL.createObjectURL(new Blob([page.svg], { type: "image/svg+xml" }));
|
||||
return img;
|
||||
}
|
||||
@@ -64,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;
|
||||
@@ -83,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({
|
||||
@@ -114,7 +168,7 @@ async function compile(edit, submitted, changes) {
|
||||
} else {
|
||||
acceptPublication(update.revision, previous);
|
||||
}
|
||||
error.hidden = true;
|
||||
errorPanel.hidden = true;
|
||||
await new Promise(requestAnimationFrame);
|
||||
await new Promise(requestAnimationFrame);
|
||||
if (edit !== sequence) return;
|
||||
@@ -171,26 +225,63 @@ function queueCompile() {
|
||||
frame = requestAnimationFrame(() => compile(edit, submitted, changes));
|
||||
}
|
||||
|
||||
async function saveSources() {
|
||||
save.disabled = true;
|
||||
saved.hidden = false;
|
||||
saved.textContent = "正在保存源文件";
|
||||
try {
|
||||
const response = await fetch(projectPrefix + "/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sequence, files: Object.fromEntries(edits) }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error);
|
||||
saved.textContent = "已保存源文件至 " + result.directory;
|
||||
} catch (failure) {
|
||||
saved.textContent = "保存失败:" + failure.message;
|
||||
} finally {
|
||||
save.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
activeFile = project.name;
|
||||
name.textContent = activeFile;
|
||||
source.value = files.get(activeFile);
|
||||
if (fileTree) {
|
||||
document.querySelector("#project-title").textContent = project.name;
|
||||
for (const filename of files.keys()) {
|
||||
const row = document.createElement("button");
|
||||
row.type = "button";
|
||||
row.className = "btn tree-row file-row";
|
||||
row.style.width = "100%";
|
||||
row.dataset.path = filename;
|
||||
row.textContent = filename;
|
||||
row.title = filename;
|
||||
row.addEventListener("click", () => selectFile(filename));
|
||||
fileTree.append(row);
|
||||
}
|
||||
}
|
||||
selectFile(project.name);
|
||||
source.disabled = false;
|
||||
sequence = project.sequence;
|
||||
if (files.size > 1) {
|
||||
save.disabled = false;
|
||||
save.addEventListener("click", saveSources);
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
||||
event.preventDefault();
|
||||
if (!save.disabled) saveSources();
|
||||
}
|
||||
});
|
||||
if (selector && files.size > 1) {
|
||||
for (const filename of files.keys()) selector.add(new Option(filename, filename));
|
||||
selector.value = activeFile;
|
||||
selector.hidden = false;
|
||||
name.hidden = true;
|
||||
selector.addEventListener("change", () => {
|
||||
activeFile = selector.value;
|
||||
source.value = edits.get(activeFile) ?? files.get(activeFile);
|
||||
});
|
||||
selector.addEventListener("change", () => selectFile(selector.value));
|
||||
}
|
||||
source.addEventListener("input", () => {
|
||||
edits.set(activeFile, source.value);
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
}
|
||||
header strong { letter-spacing: .02em; }
|
||||
header a { color: #bde5ff; }
|
||||
.actions { min-width: 0; display: flex; align-items: center; flex-wrap: wrap; gap: .6rem; }
|
||||
.actions span { overflow-wrap: anywhere; }
|
||||
main { display: grid; grid-template-columns: minmax(270px, 5fr) minmax(300px, 7fr); min-height: 0; }
|
||||
.edit { min-height: 0; display: grid; grid-template-rows: auto 1fr; background: white; }
|
||||
.file { padding: .6rem 1rem; border-bottom: 1px solid #d9e0e6; font: 14px/1.5 ui-monospace, monospace; }
|
||||
@@ -38,7 +40,11 @@
|
||||
<header>
|
||||
<strong>Texrra 原生预览</strong>
|
||||
<span id="status" role="status">正在打开文档</span>
|
||||
<a id="pdf" download hidden>下载 PDF</a>
|
||||
<div class="actions">
|
||||
<button id="save" type="button" disabled>保存源文件</button>
|
||||
<span id="saved" role="status" hidden></span>
|
||||
<a id="pdf" download hidden>下载 PDF</a>
|
||||
</div>
|
||||
</header>
|
||||
<main>
|
||||
<section class="edit" aria-label="源文件">
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
+400
-68
@@ -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,17 @@ use texrra_engine::native::{
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
execution::InputProfile,
|
||||
resources::{InputPolicy, 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;
|
||||
const PAGE: &str = include_str!("index.html");
|
||||
const SCRIPT: &str = include_str!("app.js");
|
||||
@@ -38,6 +45,12 @@ struct Edit {
|
||||
preview_draft: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Save {
|
||||
sequence: u64,
|
||||
files: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
struct Work {
|
||||
request: Request,
|
||||
job: CompileJob,
|
||||
@@ -169,6 +182,7 @@ struct Publication {
|
||||
|
||||
#[derive(Default)]
|
||||
struct Queue {
|
||||
closed: AtomicBool,
|
||||
next: Mutex<Option<Work>>,
|
||||
available: Condvar,
|
||||
current: AtomicU64,
|
||||
@@ -180,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] 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,
|
||||
@@ -191,45 +205,178 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
} else {
|
||||
InputProfile::TeX8Bit
|
||||
};
|
||||
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,
|
||||
options,
|
||||
} = prepare(&source, &format, &manifest, &run, &additional, input_profile)?;
|
||||
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let web = if args.next_if(|arg| arg == "--web-dir").is_some() {
|
||||
let path = PathBuf::from(args.next().ok_or(usage)?);
|
||||
Some(WebAssets::load(&path)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
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)
|
||||
});
|
||||
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", PAGE.into()),
|
||||
(&Method::Get, "/app.js") => respond(
|
||||
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;
|
||||
}
|
||||
}
|
||||
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");
|
||||
@@ -242,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),
|
||||
@@ -252,7 +399,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
(&Method::Post, "/preview") => {
|
||||
let received = Instant::now();
|
||||
let mut request = request;
|
||||
let edit = match read_edit(&mut request) {
|
||||
let edit: Edit = match read_json(&mut request) {
|
||||
Ok(edit) => edit,
|
||||
Err(error) => {
|
||||
reply(request, 400, json!({ "error": error }));
|
||||
@@ -274,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()))))
|
||||
@@ -290,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 }));
|
||||
@@ -318,6 +465,52 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
);
|
||||
}
|
||||
}
|
||||
(&Method::Post, "/save") => {
|
||||
let mut request = request;
|
||||
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 source edits"}));
|
||||
continue;
|
||||
}
|
||||
let save: Save = match read_json(&mut request) {
|
||||
Ok(save) => save,
|
||||
Err(error) => {
|
||||
reply(request, 400, json!({ "error": error }));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if save.sequence < queue.current.load(Ordering::Acquire) {
|
||||
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()))
|
||||
})
|
||||
.collect();
|
||||
let Some(changes) = changes else {
|
||||
reply(
|
||||
request,
|
||||
422,
|
||||
json!({"error": "The save refers to an unknown source file"}),
|
||||
);
|
||||
continue;
|
||||
};
|
||||
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()})),
|
||||
}
|
||||
}
|
||||
(&Method::Get, path) if path.starts_with("/publication?revision=") => {
|
||||
let revision = path["/publication?revision=".len()..].parse::<u64>().ok();
|
||||
let result = queue
|
||||
@@ -377,7 +570,89 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_edit(request: &mut Request) -> Result<Edit, String> {
|
||||
struct WebAssets {
|
||||
dashboard: Vec<u8>,
|
||||
index: Vec<u8>,
|
||||
styles: Vec<u8>,
|
||||
favicon: Vec<u8>,
|
||||
}
|
||||
|
||||
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 {
|
||||
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> {
|
||||
let mut body = Vec::new();
|
||||
request
|
||||
.as_reader()
|
||||
@@ -394,10 +669,12 @@ struct EditorProject {
|
||||
project: Arc<ProjectSnapshot>,
|
||||
entry: PathBuf,
|
||||
editable: BTreeMap<String, PathBuf>,
|
||||
declared: BTreeSet<PathBuf>,
|
||||
options: CompileRequest,
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
source_root: &Path,
|
||||
source: &Path,
|
||||
format: &Path,
|
||||
manifest: &Path,
|
||||
@@ -407,19 +684,27 @@ fn prepare(
|
||||
) -> Result<EditorProject, Box<dyn std::error::Error>> {
|
||||
let format_resources: Value = serde_json::from_slice(&fs::read(manifest)?)?;
|
||||
let roots: Vec<PathBuf> = serde_json::from_value(format_resources["texmf_roots"].clone())?;
|
||||
let mut world = WorldConfig::from_environment(run, roots.clone())?;
|
||||
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 {
|
||||
@@ -480,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;
|
||||
@@ -493,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)
|
||||
@@ -507,18 +809,26 @@ fn prepare(
|
||||
files.insert(path.clone(), Arc::from(fs::read(path)?));
|
||||
}
|
||||
}
|
||||
let mut coverage = BTreeSet::from_iter(roots);
|
||||
let mut coverage = BTreeSet::from_iter(world.texmf_roots.iter().cloned());
|
||||
coverage.insert(run.to_owned());
|
||||
// A successful lookup can follow a miss in an explicit search directory.
|
||||
// Keep those directories in the snapshot along with the resolved bytes.
|
||||
for search in world.paths.values().flatten() {
|
||||
if let SearchPath::Directory { path, .. } = search {
|
||||
let path = run.join(path);
|
||||
if path.is_dir() {
|
||||
coverage.insert(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
for path in files.keys() {
|
||||
if !coverage.iter().any(|root| path.starts_with(root)) {
|
||||
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 {
|
||||
@@ -535,13 +845,22 @@ fn prepare(
|
||||
project,
|
||||
entry,
|
||||
editable,
|
||||
declared,
|
||||
options: request,
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -549,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]),
|
||||
@@ -567,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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use texrra_engine::native::ProjectSnapshot;
|
||||
|
||||
pub(super) fn save(
|
||||
run: &Path,
|
||||
entry: &Path,
|
||||
declared: &BTreeSet<PathBuf>,
|
||||
project: &ProjectSnapshot,
|
||||
edits: BTreeMap<&Path, &[u8]>,
|
||||
next_number: &mut u64,
|
||||
) -> io::Result<PathBuf> {
|
||||
let parent = run.parent().expect("the working directory has a parent");
|
||||
let (staging, destination) = loop {
|
||||
*next_number += 1;
|
||||
let name = format!("texrra-sources-{}-{next_number}", std::process::id());
|
||||
let destination = parent.join(&name);
|
||||
if destination.symlink_metadata().is_ok() {
|
||||
continue;
|
||||
}
|
||||
let staging = parent.join(format!(".{name}.pending"));
|
||||
match fs::create_dir(&staging) {
|
||||
Ok(()) => break (staging, destination),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
};
|
||||
let result = (|| {
|
||||
let sources = staging.join("sources");
|
||||
fs::create_dir(&sources)?;
|
||||
let mut files = Vec::new();
|
||||
for path in declared {
|
||||
let relative = path.strip_prefix(run).expect("declared sources stay in the working copy");
|
||||
let name = relative.to_str().ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "A project file needs a UTF-8 name")
|
||||
})?;
|
||||
let saved = sources.join(relative);
|
||||
fs::create_dir_all(saved.parent().expect("a source file has a parent"))?;
|
||||
if let Some(data) = edits
|
||||
.get(path.as_path())
|
||||
.copied()
|
||||
.or_else(|| project.file(path).map(|file| file.data.as_ref()))
|
||||
{
|
||||
fs::write(&saved, data)?;
|
||||
}
|
||||
if path != entry {
|
||||
files.push(name);
|
||||
}
|
||||
}
|
||||
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,
|
||||
}))?;
|
||||
// Publish the metadata and every source at once.
|
||||
fs::rename(&staging, &destination)
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
return Err(error);
|
||||
}
|
||||
Ok(destination)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare and run a local Route-D editor and CLI with one TeX configuration."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
RESOURCE_ENV = (
|
||||
"TEXINPUTS", "TFMFONTS", "VFFONTS", "T1FONTS", "OPENTYPEFONTS", "TTFONTS",
|
||||
"PKFONTS", "ENCFONTS", "TEXFONTMAPS", "TEXFORMATS", "TEXMFCNF", "MISCFONTS",
|
||||
"SFDFONTS", "CMAPFONTS", "texmf_casefold_search",
|
||||
"FONTCONFIG_FILE", "FONTCONFIG_PATH", "TZ", "SOURCE_DATE_EPOCH", "FORCE_SOURCE_DATE",
|
||||
)
|
||||
FORMAT_ENTRIES = {"tex8bit": "pdflatex.ini", "xetex": "xelatex.ini"}
|
||||
MANIFEST = "bundle.json"
|
||||
FORMAT = "latex.tfx"
|
||||
RESOURCES = "format-resources.json"
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def installed_path(argument):
|
||||
output = subprocess.check_output(["kpsewhich", argument], text=True).strip()
|
||||
if not output:
|
||||
raise ValueError(f"TeX Live did not provide a path for {argument}")
|
||||
return Path(output).resolve(strict=True)
|
||||
|
||||
|
||||
def binary_name(name):
|
||||
return name + (".exe" if os.name == "nt" else "")
|
||||
|
||||
|
||||
def native_command(binary, profile, roots):
|
||||
command = [binary, "native", "--job", "--etex", "--input-profile", profile,
|
||||
"--input-policy", "tex", "--step-limit", "600000000"]
|
||||
for root in roots:
|
||||
command.extend(["--texmf-root", root])
|
||||
return command
|
||||
|
||||
|
||||
def roots_from_manifest(path):
|
||||
roots = json.loads(path.read_text(encoding="utf-8"))["texmf_roots"]
|
||||
for root in map(Path, roots):
|
||||
if not root.is_absolute() or not root.is_dir():
|
||||
raise ValueError(f"The TeX resource directory is unavailable: {root}")
|
||||
return roots
|
||||
|
||||
|
||||
def prepare(args):
|
||||
repo = Path(__file__).resolve().parent.parent
|
||||
target = repo / os.environ.get("CARGO_TARGET_DIR", "target") / "release"
|
||||
texrra = (args.texrra or target / binary_name("texrra")).resolve(strict=True)
|
||||
editor = (args.editor or target / "examples" / binary_name("native_editor")).resolve(strict=True)
|
||||
saved_format = args.format_image.resolve(strict=True) if args.format_image else None
|
||||
saved_resources = args.format_resources.resolve(strict=True) if args.format_resources else None
|
||||
if saved_format:
|
||||
roots_from_manifest(saved_resources)
|
||||
else:
|
||||
ini = (args.ini or installed_path(FORMAT_ENTRIES[args.input_profile])).resolve(strict=True)
|
||||
roots = args.texmf_root or [
|
||||
installed_path("-var-value=TEXMFDIST"),
|
||||
installed_path("-var-value=TEXMFSYSVAR"),
|
||||
]
|
||||
roots = [root.resolve(strict=True) for root in roots]
|
||||
|
||||
bundle = args.bundle.resolve()
|
||||
bundle.mkdir(parents=True)
|
||||
format_path = bundle / FORMAT
|
||||
resources = bundle / RESOURCES
|
||||
if saved_format:
|
||||
shutil.copyfile(saved_format, format_path)
|
||||
shutil.copyfile(saved_resources, resources)
|
||||
else:
|
||||
env = {**os.environ, "TEXRRA_STATE_DIR": str(bundle / "state")}
|
||||
command = native_command(texrra, args.input_profile, roots)
|
||||
with (bundle / "format.log").open("wb") as log:
|
||||
subprocess.run(
|
||||
[*command, "--initex", "--dump-format", "--resource-manifest", resources,
|
||||
ini, format_path],
|
||||
env=env, cwd=bundle, stdout=log, stderr=subprocess.STDOUT, check=True,
|
||||
)
|
||||
roots = roots_from_manifest(resources)
|
||||
|
||||
binary_dir = bundle / "bin"
|
||||
binary_dir.mkdir()
|
||||
texrra_path = binary_dir / binary_name("texrra")
|
||||
editor_path = binary_dir / binary_name("native_editor")
|
||||
shutil.copy2(texrra, texrra_path)
|
||||
shutil.copy2(editor, editor_path)
|
||||
shutil.copy2(Path(__file__), bundle / "native-beta.py")
|
||||
example = bundle / "a4-project"
|
||||
shutil.copytree(repo / "examples/native-format-stage/a4-project", example)
|
||||
files = [texrra_path, editor_path, format_path, resources, example / "main.tex",
|
||||
example / "chapter.tex"]
|
||||
receipt = {
|
||||
"input_profile": args.input_profile,
|
||||
"texmf_roots": roots,
|
||||
"environment": {name: os.environ[name] for name in RESOURCE_ENV if name in os.environ},
|
||||
"sha256": {path.relative_to(bundle).as_posix(): digest(path) for path in files},
|
||||
}
|
||||
(bundle / MANIFEST).write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"Beta bundle ready at {bundle}")
|
||||
print(f"Start the sample with python3 {shlex.quote(str(bundle / 'native-beta.py'))} open")
|
||||
|
||||
|
||||
def launch(args):
|
||||
bundle = Path(__file__).resolve().parent
|
||||
manifest = json.loads((bundle / MANIFEST).read_text(encoding="utf-8"))
|
||||
roots = roots_from_manifest(bundle / RESOURCES)
|
||||
if roots != manifest["texmf_roots"]:
|
||||
raise ValueError("The format resource roots differ from the prepared bundle")
|
||||
env = os.environ.copy()
|
||||
for name in (*RESOURCE_ENV, "TEXRRA_TEXMF"):
|
||||
env.pop(name, None)
|
||||
env.update(manifest["environment"])
|
||||
env["TEXRRA_STATE_DIR"] = str(bundle / "state")
|
||||
profile = manifest["input_profile"]
|
||||
if args.action == "web":
|
||||
command = [
|
||||
bundle / "bin" / binary_name("native_editor"), "--input-profile", profile,
|
||||
"--web-dir", args.web_dir.resolve(strict=True), "--projects",
|
||||
args.projects_dir.resolve(), bundle / FORMAT, bundle / RESOURCES,
|
||||
bundle / "web-runs", str(args.port),
|
||||
]
|
||||
elif args.action in ("open", "resume"):
|
||||
if args.action == "resume":
|
||||
saved = args.snapshot.resolve(strict=True)
|
||||
project = json.loads((saved / "project.json").read_text(encoding="utf-8"))
|
||||
entry = Path(project["entry"])
|
||||
if entry.is_absolute() or not entry.parts or ".." in entry.parts:
|
||||
raise ValueError("The saved project entry must be a relative path")
|
||||
source = (saved / "sources" / entry).resolve(strict=True)
|
||||
assets = project["files"]
|
||||
else:
|
||||
source = args.entry.resolve(strict=True) if args.entry else bundle / "a4-project/main.tex"
|
||||
assets = args.file if args.entry else ["chapter.tex", *args.file]
|
||||
runs = bundle / "runs"
|
||||
if args.run_dir:
|
||||
run = args.run_dir.resolve()
|
||||
else:
|
||||
runs.mkdir(exist_ok=True)
|
||||
run = Path(tempfile.mkdtemp(prefix="editor-", dir=runs)) / "project"
|
||||
command = [bundle / "bin" / binary_name("native_editor"), "--input-profile", profile]
|
||||
if args.web_dir:
|
||||
command.extend(["--web-dir", args.web_dir.resolve(strict=True)])
|
||||
if args.action == "resume":
|
||||
command.extend(["--source-root", saved / "sources"])
|
||||
command.extend([source, bundle / FORMAT, bundle / RESOURCES, run, str(args.port), *assets])
|
||||
else:
|
||||
command = native_command(bundle / "bin" / binary_name("texrra"), profile, roots)
|
||||
command.extend(["--load-format", bundle / FORMAT, args.entry.resolve(strict=True),
|
||||
args.output.resolve()])
|
||||
os.execve(command[0], command, env)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest="action", required=True)
|
||||
|
||||
setup = commands.add_parser("prepare", help="create a new local Beta directory")
|
||||
setup.add_argument("bundle", type=Path)
|
||||
setup.add_argument("--texrra", type=Path)
|
||||
setup.add_argument("--editor", type=Path)
|
||||
setup.add_argument("--input-profile", choices=FORMAT_ENTRIES, default="tex8bit")
|
||||
setup.add_argument("--texmf-root", action="append", type=Path)
|
||||
setup.add_argument("--ini", type=Path)
|
||||
setup.add_argument("--format-image", type=Path)
|
||||
setup.add_argument("--format-resources", type=Path)
|
||||
|
||||
editor = commands.add_parser("open", help="open a project or the bundled A4 sample")
|
||||
editor.add_argument("entry", type=Path, nargs="?")
|
||||
editor.add_argument("--file", action="append", default=[], help="path relative to the entry")
|
||||
resume = commands.add_parser("resume", help="reopen a saved source snapshot")
|
||||
resume.add_argument("snapshot", type=Path)
|
||||
for command in (editor, resume):
|
||||
command.add_argument("--web-dir", type=Path, help="use the texrra-web checkout")
|
||||
command.add_argument("--run-dir", type=Path)
|
||||
command.add_argument("--port", type=int, default=0)
|
||||
|
||||
web = commands.add_parser("web", help="open the native Web project library")
|
||||
web.add_argument("--web-dir", type=Path, required=True)
|
||||
web.add_argument("--projects-dir", type=Path, default=Path("projects"))
|
||||
web.add_argument("--port", type=int, default=0)
|
||||
|
||||
compiler = commands.add_parser("compile", help="produce a PDF with the bundle's native CLI")
|
||||
compiler.add_argument("entry", type=Path)
|
||||
compiler.add_argument("output", type=Path)
|
||||
|
||||
args = parser.parse_args()
|
||||
if args.action == "prepare":
|
||||
if bool(args.format_image) != bool(args.format_resources):
|
||||
setup.error("--format-image and --format-resources must be supplied together")
|
||||
if args.format_image and (args.ini or args.texmf_root):
|
||||
setup.error("--ini and --texmf-root apply when creating a format")
|
||||
try:
|
||||
if args.action == "prepare":
|
||||
prepare(args)
|
||||
else:
|
||||
launch(args)
|
||||
except subprocess.CalledProcessError as error:
|
||||
log = args.bundle.resolve() / "format.log"
|
||||
context = f". See {log}" if log.is_file() else ""
|
||||
parser.exit(1, f"Beta preparation failed (exit {error.returncode}){context}\n")
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
parser.exit(1, f"{error}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -982,6 +982,34 @@ impl CompileJob {
|
||||
}
|
||||
pub fn compile_detailed(
|
||||
self,
|
||||
request: CompileRequest,
|
||||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||||
self.compile_attempt(request)
|
||||
}
|
||||
|
||||
/// Retry a failed, unpublished attempt in the same revision after the
|
||||
/// caller supplies a new snapshot. A newer revision cancels every attempt.
|
||||
pub fn compile_expanding_project(
|
||||
self,
|
||||
mut request: CompileRequest,
|
||||
mut expand: impl FnMut(&CompileFailure) -> Option<Arc<ProjectSnapshot>>,
|
||||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||||
for _ in 0..24 {
|
||||
match self.compile_attempt(request.clone()) {
|
||||
Err(failure) if !self.job.cancellation().is_cancelled() => {
|
||||
let Some(project) = expand(&failure) else {
|
||||
return Err(failure);
|
||||
};
|
||||
request = request.with_project(project);
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
self.compile_attempt(request)
|
||||
}
|
||||
|
||||
fn compile_attempt(
|
||||
&self,
|
||||
mut request: CompileRequest,
|
||||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||||
if self.compiler.entry_checkpoints.is_some()
|
||||
|
||||
+13
-2
@@ -13,11 +13,14 @@ const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
|
||||
const ZIP64_MESSAGE: &str =
|
||||
"ZIP64 archives are not supported; re-create the archive without ZIP64 extensions";
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub(super) struct ProjectFile {
|
||||
pub(super) path: String,
|
||||
pub(super) size: u64,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct ProjectInfo {
|
||||
pub(super) id: String,
|
||||
pub(super) name: String,
|
||||
@@ -629,6 +632,7 @@ fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
let mut cursor = cd_offset;
|
||||
let mut expanded = 0u64;
|
||||
for _ in 0..count {
|
||||
if read_u32(cursor)? != 0x0201_4b50 {
|
||||
return Err("corrupt zip central directory".to_string());
|
||||
@@ -653,6 +657,13 @@ fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
if flags & 0x0001 != 0 {
|
||||
return Err("encrypted zip entries are not supported".to_string());
|
||||
}
|
||||
expanded += uncompressed_size as u64;
|
||||
if uncompressed_size as u64 > MAX_FILE_BYTES
|
||||
|| expanded > MAX_PROJECT_BYTES
|
||||
|| entries.len() >= MAX_PROJECT_FILES
|
||||
{
|
||||
return Err(format!("ZIP entry exceeds project limits: {name}"));
|
||||
}
|
||||
if read_u32(local_offset)? != 0x0403_4b50 {
|
||||
return Err("corrupt zip local header".to_string());
|
||||
}
|
||||
@@ -665,9 +676,9 @@ fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let content = match method {
|
||||
0 => data.to_vec(),
|
||||
8 => {
|
||||
let mut decoder = DeflateDecoder::new(data);
|
||||
let mut output = Vec::new();
|
||||
decoder
|
||||
DeflateDecoder::new(data)
|
||||
.take(uncompressed_size as u64 + 1)
|
||||
.read_to_end(&mut output)
|
||||
.map_err(|error| format!("could not inflate `{name}`: {error}"))?;
|
||||
output
|
||||
|
||||
Reference in new issue
Block a user