Package the native web editor as a Tauri Windows test app

This commit is contained in:
gloamxun committed 2026-12-02 07:47:05 +08:00
1 parent 7f068c7a30
commit 65e60a13e2
11 files changed
+4842 -3

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
# Texrra Windows 桌面测试版
Tauri 将现有项目库和原生预览工作台放入 Windows 窗口。安装包携带本轮的
Route-D 引擎、已验证的 LaTeX 格式和 Web 界面。此版面向已有
FedoraLinux-44、对应 TeX 资源和 WebView2 的当前测试电脑。
安装后从开始菜单打开 Texrra。也可以解压便携包,运行同目录的
Texrra 桌面程序。在项目库导入包含主 .tex 文件的 ZIP,打开项目后编辑
正文或公式,等待预览更新并下载 PDF。桌面项目保存在 Fedora 用户目录的
.local/share/texrra-desktop/projects。窗口关闭时,桌面端停止自己启动的
后台引擎。
## 构建
在引擎仓库根目录使用已经完成定向回归的原生 release 构建回执,准备
desktop/src-tauri/backend。脚本校验发布提交、二进制、格式和 Web 资源的
指纹。输出目录须可新建。
```sh
python3 desktop/build-backend.py prepare desktop/src-tauri/backend \
--artifact-dir path/to/verified/native-editor/build \
--commit full-engine-git-commit
```
在 Windows 上使用 Tauri 的 MSVC 工具链构建。在 Fedora WSL 上使用
cargo-xwin、Windows SDK、LLVM 和 NSIS。
```sh
cd desktop
cargo tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc -- --locked
```
安装包位于 desktop/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis,
或由 CARGO_TARGET_DIR 指定的对应目录。便携试用由 Windows 可执行文件
和同目录的 backend 组成。 [Tauri Windows 打包文档](https://v2.tauri.app/distribute/windows-installer/)
+265
View File
@@ -0,0 +1,265 @@
#!/usr/bin/env python3
"""Stage and run the native editor bundle for the Fedora WSL desktop app."""
import argparse
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import select
import shutil
import signal
import subprocess
import sys
import tempfile
WEB_COMMIT = "e14b7aa169d4fc7acf4162e24acb262c257a8275"
WEB_FILES = ("index.html", "styles.css", "favicon.svg", "app.js")
NATIVE_FILES = ("latex.tfx", "format-resources.json")
EDITOR = "bin/native_editor"
RECEIPT = "desktop-bundle.json"
PAYLOAD = (
EDITOR, *NATIVE_FILES, "bundle.json", "native-beta.py", "wsl-launch.py",
*(f"web/{name}" for name in WEB_FILES),
)
INSTANCE_ENV = "TEXRRA_DESKTOP_INSTANCE"
def require(condition, message):
if not condition:
raise ValueError(message)
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def write_json(path, value):
path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def is_sha(value):
return isinstance(value, str) and re.fullmatch(r"[a-f0-9]{64}", value) is not None
def git_blob(repo, commit, path):
return subprocess.check_output(["git", "-C", repo, "show", f"{commit}:{path}"])
def package_receipt(directory):
data = (directory / RECEIPT).read_bytes()
receipt = json.loads(data)
files = receipt.get("sha256", {})
require(receipt.get("schema") == 1 and set(files) == set(PAYLOAD), "Invalid desktop bundle receipt")
require(all(is_sha(value) for value in files.values()), "Invalid desktop bundle hashes")
return data, files
def check_file(path, expected):
require(path.is_file() and not path.is_symlink() and digest(path) == expected,
f"Desktop bundle file is missing or has changed: {path}")
def prepare(args, repo):
artifact = args.artifact_dir.resolve(strict=True)
reference = args.reference_bundle.resolve(strict=True)
web = args.web_repo.resolve(strict=True)
output = args.output.resolve()
require(not output.exists(), f"Desktop bundle output already exists: {output}")
require(re.fullmatch(r"[a-f0-9]{40}", args.commit), "A full Git commit is required")
require((artifact / "source-commit.txt").read_text().strip() == args.commit,
"The binary build receipt belongs to a different Git commit")
require((artifact / "editor-build.exit").read_text().strip() == "0", "Native editor build did not finish successfully")
with (artifact / "editor-build.jsonl").open() as stream:
rows = [json.loads(line) for line in stream]
required = {"native_editor", "texrra_tex_core"}
optimized = {
row["target"]["name"] for row in rows
if row["reason"] == "compiler-artifact"
and row["profile"]["opt_level"] == "3"
and not row["profile"]["debug_assertions"]
and not row["profile"]["test"]
}
require(required <= optimized, "Missing opt-level 3 engine and editor build receipts")
editor = artifact / "binary/native_editor"
editor_sha = (artifact / "binary.sha256").read_text().split()[0]
require(is_sha(editor_sha), "Invalid native editor digest in the build receipt")
with editor.open("rb") as stream:
elf = stream.read(20)
require(elf.startswith(b"\x7fELF\x02\x01\x01") and elf[18:20] == b"\x3e\x00",
"Desktop backend must be an x86-64 Linux ELF")
manifest = json.loads((reference / "bundle.json").read_text(encoding="utf-8"))
native_sha = {name: manifest["sha256"][name] for name in NATIVE_FILES}
normal_launcher = git_blob(repo, args.commit, "scripts/native-beta.py")
require(normal_launcher == (reference / "native-beta.py").read_bytes(),
"The frozen bundle and the release disagree on the native Beta launcher")
output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".desktop-backend-", dir=output.parent) as temporary:
bundle = Path(temporary) / "backend"
(bundle / "bin").mkdir(parents=True)
(bundle / "web").mkdir()
shutil.copyfile(editor, bundle / EDITOR)
check_file(bundle / EDITOR, editor_sha)
(bundle / EDITOR).chmod(0o700)
for name, value in native_sha.items():
shutil.copyfile(reference / name, bundle / name)
check_file(bundle / name, value)
shutil.copyfile(__file__, bundle / "wsl-launch.py")
(bundle / "native-beta.py").write_bytes(normal_launcher)
for name in WEB_FILES:
(bundle / "web" / name).write_bytes(git_blob(web, WEB_COMMIT, name))
manifest["sha256"] = {EDITOR: editor_sha, **native_sha}
write_json(bundle / "bundle.json", manifest)
hashes = {EDITOR: editor_sha, **native_sha}
hashes.update({name: digest(bundle / name) for name in PAYLOAD if name not in hashes})
write_json(bundle / RECEIPT, {
"schema": 1, "native_commit": args.commit, "web_commit": WEB_COMMIT, "sha256": hashes,
})
require(not output.exists(), f"Desktop bundle output already exists: {output}")
bundle.rename(output)
print(f"Desktop backend staged at {output}")
def private_home():
return Path.home() / ".local/share/texrra-desktop"
def install(package, home):
receipt, files = package_receipt(package)
runtime = home / "runtime"
runtime.mkdir(mode=0o700, exist_ok=True)
destination = runtime / hashlib.sha256(receipt).hexdigest()
if destination.exists():
require((destination / RECEIPT).read_bytes() == receipt, "Installed desktop receipt differs")
for name, expected in files.items():
check_file(destination / name, expected)
return destination
with tempfile.TemporaryDirectory(prefix=".install-", dir=runtime) as temporary:
bundle = Path(temporary) / "backend"
bundle.mkdir(mode=0o700)
for name, expected in files.items():
path = bundle / name
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(package / name, path)
check_file(path, expected)
(bundle / EDITOR).chmod(0o700)
(bundle / RECEIPT).write_bytes(receipt)
(bundle / "state").symlink_to(home / "state", target_is_directory=True)
bundle.rename(destination)
return destination
def launch_error(message):
detail = " ".join(str(message).splitlines())
print(f"Texrra desktop error {detail}", flush=True)
def launch(args):
def interrupt(_signum, _frame):
raise KeyboardInterrupt
def lease_ended(timeout):
return select.select([sys.stdin], [], [], timeout)[0] and not os.read(sys.stdin.fileno(), 4096)
signal.signal(signal.SIGTERM, interrupt)
os.umask(0o077)
home = private_home()
home.mkdir(mode=0o700, parents=True, exist_ok=True)
with (home / "backend.lock").open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as error:
raise ValueError("The Texrra desktop backend is already running in this Fedora account") from error
for name in ("projects", "state"):
(home / name).mkdir(mode=0o700, exist_ok=True)
bundle = install(Path(__file__).resolve().parent, home)
if lease_ended(0):
return 0
command = [
sys.executable, bundle / "native-beta.py", "web", "--web-dir", bundle / "web",
"--projects-dir", home / "projects", "--port", "0",
]
with subprocess.Popen(command, stdin=subprocess.DEVNULL,
env=dict(os.environ, **{INSTANCE_ENV: args.instance})) as child:
try:
print(f"Texrra desktop PID {child.pid}", flush=True)
while child.poll() is None:
if lease_ended(0.25):
return 0
launch_error(f"Native editor exited unexpectedly (exit {child.returncode})")
return child.returncode or 1
finally:
if child.poll() is None:
child.terminate()
try:
child.wait(timeout=3)
except subprocess.TimeoutExpired:
child.kill()
child.wait()
def stop(args):
require(args.pid > 1, "The desktop backend PID must be greater than one")
try:
pid = os.pidfd_open(args.pid)
except ProcessLookupError:
return
try:
proc = Path(f"/proc/{args.pid}")
token = f"{INSTANCE_ENV}={args.instance}".encode()
runtime = private_home() / "runtime"
environ = (proc / "environ").read_bytes().split(b"\0")
command = (proc / "cmdline").read_bytes().split(b"\0")
exe = (proc / "exe").readlink()
candidates = (exe, Path(os.fsdecode(command[1]))) if len(command) > 1 else (exe,)
owned = any(path.is_relative_to(runtime) and
path.name in ("native_editor", "native-beta.py") for path in candidates)
require(owned and token in environ, "The process does not match this desktop backend")
signal.pidfd_send_signal(pid, signal.SIGTERM)
except (ProcessLookupError, FileNotFoundError):
pass
finally:
os.close(pid)
def main():
repo = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="action", required=True)
stage = commands.add_parser("prepare", help="stage a new installer resource directory")
stage.add_argument("output", type=Path)
stage.add_argument("--artifact-dir", type=Path, required=True)
stage.add_argument("--commit", required=True)
stage.add_argument("--reference-bundle", type=Path,
default=repo / "target/p4-a4-child-release/browser-bundle")
stage.add_argument("--web-repo", type=Path, default=repo.parent / "texrra-web")
run = commands.add_parser("launch", help="run the backend while its stdin lease is open")
close = commands.add_parser("stop", help="stop only the selected desktop backend")
close.add_argument("--pid", type=int, required=True)
for command in (run, close):
command.add_argument("--instance", required=True)
args = parser.parse_args()
if args.action != "prepare" and not re.fullmatch(r"[0-9a-f]{16,128}", args.instance):
parser.error("--instance must be 16 to 128 lowercase hexadecimal characters")
try:
if args.action == "prepare":
prepare(args, repo)
elif args.action == "launch":
return launch(args)
else:
stop(args)
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
if args.action == "launch":
launch_error(error)
parser.exit(1, f"{error}\n")
except KeyboardInterrupt:
return 0
if __name__ == "__main__":
sys.exit(main())
+2
View File
@@ -0,0 +1,2 @@
/backend/
/target/
+4260
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "texrra-desktop"
version = "0.1.0"
edition = "2024"
rust-version = "1.92"
license = "MIT OR Apache-2.0"
[workspace]
[build-dependencies]
tauri-build = "2"
[dependencies]
serde_json = "1"
tauri = "2"
[features]
custom-protocol = ["tauri/custom-protocol"]
[profile.release]
strip = true
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+203
View File
@@ -0,0 +1,203 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::{
io::{BufRead, BufReader},
os::windows::process::CommandExt,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::{Arc, Mutex, mpsc},
thread,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tauri::{Manager, RunEvent, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
const DISTRO: &str = "FedoraLinux-44";
const HIDE_CONSOLE: u32 = 0x08000000;
const READY_PREFIX: &str = "Native editor ";
#[derive(Default)]
struct Backend(Mutex<Option<Child>>);
impl Backend {
fn stop(&self) {
let Some(mut child) = self.0.lock().unwrap().take() else {
return;
};
// The private launcher takes EOF as the end of its desktop lease.
drop(child.stdin.take());
let deadline = Instant::now() + Duration::from_secs(4);
while Instant::now() < deadline {
if !matches!(child.try_wait(), Ok(None)) {
return;
}
thread::sleep(Duration::from_millis(40));
}
let _ = child.kill();
let _ = child.wait();
}
}
fn wsl() -> Command {
let mut command = Command::new("wsl.exe");
command.creation_flags(HIDE_CONSOLE);
command.args(["--distribution", DISTRO, "--exec"]);
command
}
fn linux_path(path: &Path) -> Result<String, String> {
let result = wsl()
.args(["wslpath", "-a", "-u"])
.arg(path)
.output()
.map_err(|e| format!("无法打开 {DISTRO}。{e}"))?;
if !result.status.success() {
return Err(format!(
"无法读取桌面版引擎资源。{}",
String::from_utf8_lossy(&result.stderr).trim()
));
}
let converted = String::from_utf8(result.stdout).map_err(|e| e.to_string())?;
let path = converted.trim();
if !path.starts_with('/') {
return Err("桌面版引擎资源路径无效。".into());
}
Ok(path.to_owned())
}
fn ready_url(text: &str) -> Option<Url> {
let url = Url::parse(text.strip_prefix(READY_PREFIX)?.trim()).ok()?;
(url.scheme() == "http"
&& url.host_str() == Some("127.0.0.1")
&& url.port().is_some()
&& url.path() == "/"
&& url.query().is_none()
&& url.fragment().is_none()
&& url.username().is_empty()
&& url.password().is_none())
.then_some(url)
}
fn start_engine(backend: &Backend, launcher: &Path) -> Result<Url, String> {
let script = linux_path(launcher)?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let instance = format!("{:08x}{:032x}", std::process::id(), now.as_nanos());
let mut child = wsl()
.args(["python3", &script, "launch", "--instance", &instance])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(|e| format!("无法启动本地引擎。{e}"))?;
let stdout = child.stdout.take().unwrap();
*backend.0.lock().unwrap() = Some(child);
let (send, reply) = mpsc::sync_channel(1);
thread::spawn(move || {
let mut send = Some(send);
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
let Some(result) = ready_url(&line).map(Ok).or_else(|| {
line.strip_prefix("Texrra desktop error ")
.map(|error| Err(error.to_owned()))
}) else {
continue;
};
if let Some(send) = send.take() {
let _ = send.send(result);
}
}
});
reply
.recv_timeout(Duration::from_secs(60))
.map_err(|error| match error {
mpsc::RecvTimeoutError::Timeout => "启动本地引擎超时。".to_owned(),
mpsc::RecvTimeoutError::Disconnected => {
format!("本地引擎启动失败。请确认 {DISTRO} 可以正常打开。")
}
})?
}
fn show_error(window: &WebviewWindow, message: &str) {
if let Ok(text) = serde_json::to_string(message) {
let _ = window.eval(&format!(
"if (document.querySelector('#status')) document.querySelector('#status').textContent = {text};"
));
}
}
fn backend_launcher(app: &tauri::App) -> Result<PathBuf, String> {
let bundled = app
.path()
.resource_dir()
.map_err(|e| e.to_string())?
.join("backend/wsl-launch.py");
if bundled.is_file() {
return Ok(bundled);
}
let executable = std::env::current_exe().map_err(|e| e.to_string())?;
let portable = executable.with_file_name("backend").join("wsl-launch.py");
if portable.is_file() {
return Ok(portable);
}
Err("缺少同目录的 backend 文件夹。请先解压整个 Texrra 桌面版。".into())
}
fn main() {
tauri::Builder::default()
.manage(Backend::default())
.setup(|app| {
let allowed = Arc::new(Mutex::new(None::<Url>));
let navigation = Arc::clone(&allowed);
let startup_error = Arc::new(Mutex::new(None::<String>));
let deferred_error = Arc::clone(&startup_error);
let window =
WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
.title("Texrra")
.inner_size(1280.0, 900.0)
.min_inner_size(780.0, 540.0)
.on_navigation(move |url| {
matches!(
url.as_str(),
"http://tauri.localhost/" | "http://tauri.localhost/index.html"
) || navigation
.lock()
.unwrap()
.as_ref()
.is_some_and(|origin| origin.origin() == url.origin())
})
.on_page_load(move |window, payload| {
if payload.url().host_str() == Some("tauri.localhost") {
if let Some(error) = deferred_error.lock().unwrap().as_deref() {
show_error(&window, error);
}
}
})
.build()?;
let launcher = backend_launcher(app);
let handle = app.handle().clone();
thread::spawn(move || {
let backend = handle.state::<Backend>();
let start = launcher.and_then(|launcher| start_engine(&backend, &launcher));
let result = start.and_then(|url| {
*allowed.lock().unwrap() = Some(url.clone());
window
.navigate(url)
.map_err(|error| format!("工作台打开失败。{error}"))
});
if let Err(error) = result {
backend.stop();
*startup_error.lock().unwrap() = Some(error.clone());
show_error(&window, &error);
}
});
Ok(())
})
.build(tauri::generate_context!())
.expect("Texrra desktop could not initialize")
.run(|app, event| {
if matches!(event, RunEvent::Exit) {
app.state::<Backend>().stop();
}
});
}
+28
View File
@@ -0,0 +1,28 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Texrra",
"version": "0.1.0",
"identifier": "org.texrra.desktop",
"build": {
"frontendDist": "../startup"
},
"app": {
"windows": [],
"security": {
"capabilities": []
}
},
"bundle": {
"active": true,
"targets": ["nsis"],
"resources": {
"backend/": "backend/"
},
"icon": ["icons/icon.ico"],
"windows": {
"nsis": {
"installMode": "currentUser"
}
}
}
}
+21
View File
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Texrra</title>
<style>
:root { font-family: system-ui, "Microsoft YaHei", sans-serif; color: #172033; background: #f6f7f9; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; }
main { max-width: 36rem; margin: 2rem; }
h1 { font-family: Georgia, serif; font-size: 2rem; margin: 0 0 .75rem; }
p { color: #4b566c; line-height: 1.6; margin: 0; overflow-wrap: anywhere; }
</style>
</head>
<body>
<main>
<h1>Texrra</h1>
<p id="status" role="status">正在启动本地排版引擎…</p>
</main>
</body>
</html>
+4 -3
View File
@@ -4,10 +4,11 @@
## 2026-12-02 当前开发目标的收尾条件
用户要求先完成 XeTeX 整行编辑复用和浏览器 100 ms 可见时延。
两项都用实际编译和页面交付验证后,可以结束当前开发目标。
用户要求完成 XeTeX 整行编辑复用,并在当前测试笔记本上继续降低浏览器实际
首帧延迟。当前开发轮次以可复验的兼容性、实际性能记录和能在这台电脑上运行
的 Windows Tauri 测试包交付为收尾。100 ms 保留为后续性能参照。
后续模板由用户补充,按实际项目出现的兼容问题继续适配。
下方记录正式版的长期能力范围和原来的统一验收条件。
正式版的能力范围和统一验收条件见下文。
## Beta 优先交付