Build a standalone Windows desktop with opt-in project removal
This commit is contained in:
1 parent
2c5b9b5f10
commit
2c99cade7d
24 files changed
+1404
-168
No files matched your search
@@ -1,5 +1,44 @@
|
||||
# Texrra Windows 桌面测试版
|
||||
|
||||
## Windows 原生版
|
||||
|
||||
Windows x64 原生版直接运行包内的引擎、TeX 资源和 BibTeX。项目在
|
||||
当前用户的 `%LOCALAPPDATA%\TexrraData\projects`。首次启动为本机
|
||||
生成 LaTeX 格式,后续复用。`backend` 须保留在程序旁边。最终用户
|
||||
需要 WebView2。包含 EPS 图片的项目需要同时提供对应 PDF,例如
|
||||
`fig.eps` 对应 `fig-eps-converted-to.pdf`。
|
||||
|
||||
交互式卸载默认保留项目。在卸载界面勾选删除应用数据,再核对显示
|
||||
的发行版和目录并选择确认,即可清空该版本的项目保存目录。静默
|
||||
卸载和升级保留项目。Windows 原生版和 WSL 版各自使用自己的项目
|
||||
目录。
|
||||
|
||||
### 准备 Windows 原生版资源
|
||||
|
||||
构建 x64 原生引擎。可以在 Windows 使用 MSVC,或在 Fedora WSL
|
||||
使用仓库的 Windows 构建工具链运行 `cargo xwin build`。
|
||||
|
||||
```sh
|
||||
cargo build --locked --release --target x86_64-pc-windows-msvc --example native_editor
|
||||
```
|
||||
|
||||
从同一 TeX Live 镜像保存 `archive/bibtex.windows.tar.xz`、
|
||||
`archive/kpathsea.windows.tar.xz` 和 `tlpkg/texlive.tlpdb.xz`
|
||||
至同一目录。使用已核验的 WSL 发布版作为 TeX 资源和 Web 界面的
|
||||
来源。该命令在可访问参考包中 TeX 资源树的构建机上运行。
|
||||
|
||||
```sh
|
||||
python3 desktop/build-windows-backend.py desktop/src-tauri/backend \
|
||||
--editor path/to/native_editor.exe \
|
||||
--reference path/to/verified/wsl/backend \
|
||||
--downloads path/to/texlive-tool-archives \
|
||||
--commit full-engine-git-commit
|
||||
```
|
||||
|
||||
按下文的 Tauri 构建方法将生成的 Windows `backend` 装入 NSIS。
|
||||
|
||||
## WSL 版
|
||||
|
||||
Tauri 将现有项目库和原生预览工作台放入 Windows 窗口。安装包携带本轮的
|
||||
Route-D 引擎、已验证的 LaTeX 格式和 Web 界面。此版面向已有
|
||||
FedoraLinux-44、对应 TeX 资源和 WebView2 的当前测试电脑。桌面版使用
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stage a self-contained Windows native editor and its TeX resource trees."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import lzma
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
|
||||
MIRROR = "https://ctan.math.illinois.edu/systems/texlive/tlnet"
|
||||
WEB_FILES = ("index.html", "styles.css", "favicon.svg", "app.js")
|
||||
TOOLS = {
|
||||
"bibtex.windows": ("bibtex.exe",),
|
||||
"kpathsea.windows": ("kpsewhich.exe", "kpathsealibw64.dll", "msvcr100.dll"),
|
||||
}
|
||||
|
||||
|
||||
def digest(path, algorithm="sha256"):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, algorithm).hexdigest()
|
||||
|
||||
|
||||
def require_amd64_pe(path):
|
||||
with path.open("rb") as stream:
|
||||
header = stream.read(64)
|
||||
if len(header) == 64 and header[:2] == b"MZ":
|
||||
stream.seek(struct.unpack_from("<I", header, 60)[0])
|
||||
if stream.read(6) == b"PE\0\0\x64\x86":
|
||||
return
|
||||
raise ValueError(f"Expected an x64 Windows executable: {path}")
|
||||
|
||||
|
||||
def stage_bibtex(output, downloads):
|
||||
output.mkdir(parents=True)
|
||||
with lzma.open(downloads / "texlive.tlpdb.xz", "rt") as stream:
|
||||
db = stream.read()
|
||||
receipts = {}
|
||||
for package, names in TOOLS.items():
|
||||
record = next(block for block in db.split("\n\n") if block.startswith(f"name {package}\n"))
|
||||
fields = dict(line.split(" ", 1) for line in record.splitlines() if " " in line)
|
||||
archive = downloads / f"{package}.tar.xz"
|
||||
checksum = fields["containerchecksum"]
|
||||
if digest(archive, "sha512") != checksum:
|
||||
raise ValueError(f"TeX Live archive checksum differs for {package}")
|
||||
with tarfile.open(archive, "r:xz") as bundle:
|
||||
for name in names:
|
||||
member = bundle.getmember(f"bin/windows/{name}")
|
||||
if not member.isfile():
|
||||
raise ValueError(f"Expected a regular TeX Live file: {name}")
|
||||
with bundle.extractfile(member) as source, (output / name).open("wb") as target:
|
||||
shutil.copyfileobj(source, target)
|
||||
require_amd64_pe(output / name)
|
||||
receipts[package] = {"revision": fields["revision"], "sha512": checksum}
|
||||
(output / "texmf.cnf").write_text(
|
||||
"BIBINPUTS = .\nBSTINPUTS = .\nopenin_any = p\nopenout_any = p\nshell_escape = f\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
return receipts
|
||||
|
||||
|
||||
def copy_texmf(source, target, skip_generated):
|
||||
target.mkdir(parents=True)
|
||||
for path in sorted(source.rglob("*")):
|
||||
if path.is_symlink() or not path.is_file():
|
||||
continue
|
||||
if skip_generated and path.suffix in {".fmt", ".log"}:
|
||||
continue
|
||||
staged = target / path.relative_to(source)
|
||||
staged.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, staged)
|
||||
|
||||
|
||||
def stage(args, output):
|
||||
reference = json.loads((args.reference / "bundle.json").read_text())
|
||||
desktop = json.loads((args.reference / "desktop-bundle.json").read_text())
|
||||
tree_names = ("overlay", "dist", "var")
|
||||
roots = reference["texmf_roots"]
|
||||
if len(roots) != len(tree_names):
|
||||
raise ValueError("Expected overlay, distribution and generated TeX trees")
|
||||
texmf = output / "texmf"
|
||||
for name, path in zip(tree_names, roots, strict=True):
|
||||
copy_texmf(Path(path).resolve(strict=True), texmf / name, name == "var")
|
||||
font_maps = Path(reference["environment"]["TEXFONTMAPS"].rstrip(":"))
|
||||
(texmf / "fonts").mkdir()
|
||||
shutil.copy2(font_maps / "pdftex.map", texmf / "fonts")
|
||||
if not (texmf / "dist/tex/latex/tex-ini-files/pdflatex.ini").is_file():
|
||||
raise ValueError("Missing pdfLaTeX initialization source")
|
||||
|
||||
web = output / "web"
|
||||
web.mkdir()
|
||||
for name in WEB_FILES:
|
||||
source = args.reference / "web" / name
|
||||
if digest(source) != desktop["sha256"][f"web/{name}"]:
|
||||
raise ValueError(f"Reference Web asset has changed: {name}")
|
||||
shutil.copyfile(source, web / name)
|
||||
tools = stage_bibtex(output / "tools/bibtex", args.downloads)
|
||||
(output / "bin").mkdir()
|
||||
require_amd64_pe(args.editor)
|
||||
shutil.copyfile(args.editor, output / "bin/native_editor.exe")
|
||||
(output / "THIRD-PARTY.txt").write_text(
|
||||
"TeX Live resources and bundled BibTeX and Kpathsea binaries\n"
|
||||
"TeX Live licensing and sources: https://tug.org/texlive/copying.html\n"
|
||||
"TeX Live source archives: https://tug.org/texlive/svn/\n"
|
||||
f"TeX Live binaries and package metadata: {MIRROR}\n",
|
||||
encoding="ascii",
|
||||
)
|
||||
license_source = Path(__file__).resolve().with_name("licenses")
|
||||
shutil.copytree(license_source, output / "licenses")
|
||||
|
||||
files = {
|
||||
path.relative_to(output).as_posix(): digest(path)
|
||||
for path in sorted(output.rglob("*")) if path.is_file()
|
||||
}
|
||||
fingerprints = json.dumps(files, sort_keys=True).encode("utf-8")
|
||||
(output / "windows-bundle.json").write_text(json.dumps({
|
||||
"schema": 1,
|
||||
"engine_source": args.commit,
|
||||
"web_commit": desktop["web_commit"],
|
||||
"resources_sha256": hashlib.sha256(fingerprints).hexdigest(),
|
||||
"texlive_tools": tools,
|
||||
"sha256": files,
|
||||
}, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("output", type=Path)
|
||||
parser.add_argument("--editor", type=Path, required=True)
|
||||
parser.add_argument("--reference", type=Path, required=True)
|
||||
parser.add_argument("--downloads", type=Path, required=True)
|
||||
parser.add_argument("--commit", required=True)
|
||||
args = parser.parse_args()
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
if args.output.exists():
|
||||
parser.error(f"Output already exists: {args.output}")
|
||||
if len(args.commit) != 40 or any(char not in "0123456789abcdef" for char in args.commit):
|
||||
parser.error("A full Git commit is required")
|
||||
with tempfile.TemporaryDirectory(prefix=".windows-backend-", dir=args.output.parent) as temporary:
|
||||
output = Path(temporary) / "backend"
|
||||
stage(args, output)
|
||||
output.rename(args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Frank Denis <[email protected]>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,41 @@
|
||||
UNICODE LICENSE V3
|
||||
|
||||
COPYRIGHT AND PERMISSION NOTICE
|
||||
|
||||
Copyright © 2019-2025 Unicode, Inc.
|
||||
|
||||
NOTICE TO USER: Carefully read the following legal agreement. BY
|
||||
DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
|
||||
SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
|
||||
TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
|
||||
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of data files and any associated documentation (the "Data Files") or
|
||||
software and any associated documentation (the "Software") to deal in the
|
||||
Data Files or Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, and/or sell
|
||||
copies of the Data Files or Software, and to permit persons to whom the
|
||||
Data Files or Software are furnished to do so, provided that either (a)
|
||||
this copyright and permission notice appear with all copies of the Data
|
||||
Files or Software, or (b) this copyright and permission notice appear in
|
||||
associated Documentation.
|
||||
|
||||
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
|
||||
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
|
||||
THIRD PARTY RIGHTS.
|
||||
|
||||
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
|
||||
BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
|
||||
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
||||
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
|
||||
FILES OR SOFTWARE.
|
||||
|
||||
Except as contained in this notice, the name of a copyright holder shall
|
||||
not be used in advertising or otherwise to promote the sale, use or other
|
||||
dealings in these Data Files or Software without prior written
|
||||
authorization of the copyright holder.
|
||||
|
||||
SPDX-License-Identifier: Unicode-3.0
|
||||
Generated
+1
-1
@@ -3237,7 +3237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "texrra-desktop"
|
||||
version = "0.1.8"
|
||||
version = "0.1.9"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"tauri",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "texrra-desktop"
|
||||
version = "0.1.8"
|
||||
version = "0.1.9"
|
||||
edition = "2024"
|
||||
rust-version = "1.92"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
||||
+111
-28
@@ -1,6 +1,9 @@
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod uninstall_projects;
|
||||
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
io::{BufRead, BufReader},
|
||||
os::windows::process::CommandExt,
|
||||
path::{Path, PathBuf},
|
||||
@@ -80,14 +83,60 @@ fn ready_url(text: &str) -> Option<Url> {
|
||||
.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])
|
||||
enum Launcher {
|
||||
Windows { directory: PathBuf, data: PathBuf },
|
||||
Wsl(PathBuf),
|
||||
}
|
||||
|
||||
impl Launcher {
|
||||
fn command(&self) -> Result<Command, String> {
|
||||
match self {
|
||||
Self::Windows { directory, data } => {
|
||||
let mut command = Command::new(directory.join("bin/native_editor.exe"));
|
||||
command
|
||||
.creation_flags(HIDE_CONSOLE)
|
||||
.arg("--windows-desktop")
|
||||
.arg(directory)
|
||||
.arg(data);
|
||||
Ok(command)
|
||||
}
|
||||
Self::Wsl(launcher) => {
|
||||
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 command = wsl();
|
||||
command.args(["python3", &script, "launch", "--instance", &instance]);
|
||||
Ok(command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn timeout(&self) -> Duration {
|
||||
Duration::from_secs(match self {
|
||||
Self::Windows { .. } => 300,
|
||||
Self::Wsl(_) => 60,
|
||||
})
|
||||
}
|
||||
|
||||
fn disconnected(&self) -> String {
|
||||
match self {
|
||||
Self::Windows { .. } => "本地 Windows 引擎启动失败。请检查安装文件。".to_owned(),
|
||||
Self::Wsl(_) => {
|
||||
"本地引擎启动失败。请确认当前默认的 WSL 发行版可以正常打开。".to_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_engine(
|
||||
backend: &Backend,
|
||||
launcher: &Launcher,
|
||||
on_preparing: impl Fn() + Send + 'static,
|
||||
) -> Result<Url, String> {
|
||||
let mut child = launcher
|
||||
.command()?
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
@@ -99,6 +148,10 @@ fn start_engine(backend: &Backend, launcher: &Path) -> Result<Url, String> {
|
||||
thread::spawn(move || {
|
||||
let mut send = Some(send);
|
||||
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
||||
if line == "Texrra desktop preparing format" {
|
||||
on_preparing();
|
||||
continue;
|
||||
}
|
||||
let Some(result) = ready_url(&line).map(Ok).or_else(|| {
|
||||
line.strip_prefix("Texrra desktop error ")
|
||||
.map(|error| Err(error.to_owned()))
|
||||
@@ -111,16 +164,14 @@ fn start_engine(backend: &Backend, launcher: &Path) -> Result<Url, String> {
|
||||
}
|
||||
});
|
||||
reply
|
||||
.recv_timeout(Duration::from_secs(60))
|
||||
.recv_timeout(launcher.timeout())
|
||||
.map_err(|error| match error {
|
||||
mpsc::RecvTimeoutError::Timeout => "启动本地引擎超时。".to_owned(),
|
||||
mpsc::RecvTimeoutError::Disconnected => {
|
||||
"本地引擎启动失败。请确认当前默认的 WSL 发行版可以正常打开。".to_owned()
|
||||
}
|
||||
mpsc::RecvTimeoutError::Disconnected => launcher.disconnected(),
|
||||
})?
|
||||
}
|
||||
|
||||
fn show_error(window: &WebviewWindow, message: &str) {
|
||||
fn show_status(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};"
|
||||
@@ -128,31 +179,55 @@ fn show_error(window: &WebviewWindow, message: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
fn backend_launcher(app: &tauri::App) -> Result<PathBuf, String> {
|
||||
fn windows_data_home() -> Result<PathBuf, String> {
|
||||
std::env::var_os("LOCALAPPDATA")
|
||||
.map(PathBuf::from)
|
||||
.filter(|path| path.is_absolute())
|
||||
.map(|path| path.join("TexrraData"))
|
||||
.ok_or_else(|| "无法读取当前 Windows 用户的数据目录。".into())
|
||||
}
|
||||
|
||||
fn backend_launcher(app: &tauri::App) -> Result<Launcher, 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);
|
||||
}
|
||||
.join("backend");
|
||||
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);
|
||||
let portable = executable.with_file_name("backend");
|
||||
for directory in [bundled, portable] {
|
||||
if directory.join("bin/native_editor.exe").is_file() {
|
||||
return Ok(Launcher::Windows {
|
||||
directory,
|
||||
data: windows_data_home()?,
|
||||
});
|
||||
}
|
||||
let launcher = directory.join("wsl-launch.py");
|
||||
if launcher.is_file() {
|
||||
return Ok(Launcher::Wsl(launcher));
|
||||
}
|
||||
}
|
||||
Err("缺少同目录的 backend 文件夹。请先解压整个 Texrra 桌面版。".into())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
if args.next().as_deref() == Some(OsStr::new("--uninstall-projects")) {
|
||||
let status = match (args.next(), args.next(), args.next(), windows_data_home()) {
|
||||
(Some(action), Some(ticket_dir), None, Ok(home)) => {
|
||||
uninstall_projects::run(&action, Path::new(&ticket_dir), &home.join("projects"))
|
||||
}
|
||||
_ => 1,
|
||||
};
|
||||
std::process::exit(status);
|
||||
}
|
||||
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 startup_status = Arc::new(Mutex::new(None::<String>));
|
||||
let deferred_status = Arc::clone(&startup_status);
|
||||
let window =
|
||||
WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
|
||||
.title("Texrra")
|
||||
@@ -171,8 +246,8 @@ fn main() {
|
||||
})
|
||||
.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);
|
||||
if let Some(status) = deferred_status.lock().unwrap().as_deref() {
|
||||
show_status(&window, status);
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -181,7 +256,15 @@ fn main() {
|
||||
let handle = app.handle().clone();
|
||||
thread::spawn(move || {
|
||||
let backend = handle.state::<Backend>();
|
||||
let start = launcher.and_then(|launcher| start_engine(&backend, &launcher));
|
||||
let progress_window = window.clone();
|
||||
let progress_status = Arc::clone(&startup_status);
|
||||
let start = launcher.and_then(|launcher| {
|
||||
start_engine(&backend, &launcher, move || {
|
||||
let message = "正在为此电脑初始化 LaTeX 格式,首次启动可能需要几分钟。";
|
||||
*progress_status.lock().unwrap() = Some(message.to_owned());
|
||||
show_status(&progress_window, message);
|
||||
})
|
||||
});
|
||||
let result = start.and_then(|url| {
|
||||
*allowed.lock().unwrap() = Some(url.clone());
|
||||
window
|
||||
@@ -190,8 +273,8 @@ fn main() {
|
||||
});
|
||||
if let Err(error) = result {
|
||||
backend.stop();
|
||||
*startup_error.lock().unwrap() = Some(error.clone());
|
||||
show_error(&window, &error);
|
||||
*startup_status.lock().unwrap() = Some(error.clone());
|
||||
show_status(&window, &error);
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::path::{Component, Path, Prefix};
|
||||
|
||||
const FILE_READ_ATTRIBUTES: u32 = 0x80;
|
||||
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
|
||||
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
const FILE_SHARE_READ_WRITE: u32 = 0x3;
|
||||
const FILE_SHARE_DELETE: u32 = 0x4;
|
||||
const FILE_ID_INFO_CLASS: i32 = 18;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct FileIdInfo {
|
||||
volume: u64,
|
||||
file_id: [u8; 16],
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GetFileInformationByHandleEx(
|
||||
file: *mut std::ffi::c_void,
|
||||
class: i32,
|
||||
information: *mut FileIdInfo,
|
||||
size: u32,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
fn unsafe_location() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, "unsafe project location")
|
||||
}
|
||||
|
||||
fn directory(path: &Path, share_mode: u32) -> io::Result<File> {
|
||||
let handle = OpenOptions::new()
|
||||
.access_mode(FILE_READ_ATTRIBUTES)
|
||||
.share_mode(share_mode)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
let metadata = handle.metadata()?;
|
||||
if !metadata.is_dir() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
|
||||
return Err(unsafe_location());
|
||||
}
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
fn directory_identity(handle: &File) -> io::Result<FileIdInfo> {
|
||||
let mut identity = FileIdInfo::default();
|
||||
// The live handle and the initialized buffer match Windows' FILE_ID_INFO layout.
|
||||
let success = unsafe {
|
||||
GetFileInformationByHandleEx(
|
||||
handle.as_raw_handle(),
|
||||
FILE_ID_INFO_CLASS,
|
||||
&mut identity,
|
||||
std::mem::size_of::<FileIdInfo>() as u32,
|
||||
)
|
||||
};
|
||||
if success == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn operate(action: &OsStr, tickets: &Path, projects: &Path) -> io::Result<()> {
|
||||
let parent = projects.parent().ok_or_else(unsafe_location)?;
|
||||
if parent.file_name() != Some(OsStr::new("TexrraData"))
|
||||
|| projects.file_name() != Some(OsStr::new("projects"))
|
||||
|| !projects.is_absolute()
|
||||
|| !matches!(
|
||||
projects.components().next(),
|
||||
Some(Component::Prefix(prefix))
|
||||
if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_))
|
||||
)
|
||||
|| projects
|
||||
.components()
|
||||
.any(|part| part == Component::ParentDir)
|
||||
{
|
||||
return Err(unsafe_location());
|
||||
}
|
||||
let display = projects.to_str().ok_or_else(unsafe_location)?;
|
||||
let path_bytes: Vec<_> = projects
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect();
|
||||
if path_bytes.len() > 1240
|
||||
|| display.chars().any(|char| {
|
||||
char.is_control()
|
||||
|| matches!(char, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
|
||||
})
|
||||
{
|
||||
return Err(unsafe_location());
|
||||
}
|
||||
|
||||
// Keeping ancestor handles without FILE_SHARE_DELETE prevents redirects above the store.
|
||||
let _ancestors = parent
|
||||
.ancestors()
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|path| directory(path, FILE_SHARE_READ_WRITE))
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let handle = directory(projects, FILE_SHARE_READ_WRITE | FILE_SHARE_DELETE)?;
|
||||
let backend_lock = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.share_mode(FILE_SHARE_READ_WRITE)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(parent.join("backend.lock"))
|
||||
.map_err(|error| {
|
||||
if error.kind() == io::ErrorKind::NotFound {
|
||||
unsafe_location()
|
||||
} else {
|
||||
error
|
||||
}
|
||||
})?;
|
||||
let lock_metadata = backend_lock.metadata()?;
|
||||
if !lock_metadata.is_file()
|
||||
|| lock_metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
|
||||
{
|
||||
return Err(unsafe_location());
|
||||
}
|
||||
backend_lock.try_lock().map_err(io::Error::from)?;
|
||||
let identity = directory_identity(&handle)?;
|
||||
let mut ticket = path_bytes.clone();
|
||||
ticket.extend_from_slice(&identity.volume.to_le_bytes());
|
||||
ticket.extend_from_slice(&identity.file_id);
|
||||
let identity_path = tickets.join("projects-identity.bin");
|
||||
if action == "inspect" {
|
||||
write_new(&identity_path, &ticket)?;
|
||||
write_new(&tickets.join("projects-path.txt"), &path_bytes)
|
||||
} else if action == "delete" {
|
||||
if fs::read(identity_path)? != ticket {
|
||||
return Err(unsafe_location());
|
||||
}
|
||||
// On Windows, remove_dir_all removes reparse points without traversing them.
|
||||
fs::remove_dir_all(projects)
|
||||
} else {
|
||||
Err(unsafe_location())
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)?
|
||||
.write_all(data)
|
||||
}
|
||||
|
||||
pub(crate) fn run(action: &OsStr, ticket_dir: &Path, projects: &Path) -> i32 {
|
||||
match operate(action, ticket_dir, projects) {
|
||||
Ok(()) => 0,
|
||||
Err(error) if action == "inspect" && error.kind() == io::ErrorKind::NotFound => 2,
|
||||
Err(_) => 1,
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Texrra",
|
||||
"version": "0.1.8",
|
||||
"version": "0.1.9",
|
||||
"identifier": "org.texrra.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../startup"
|
||||
@@ -14,14 +14,19 @@
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["nsis"],
|
||||
"targets": [
|
||||
"nsis"
|
||||
],
|
||||
"resources": {
|
||||
"backend/": "backend/"
|
||||
},
|
||||
"icon": ["icons/icon.ico"],
|
||||
"icon": [
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"installMode": "currentUser"
|
||||
"installMode": "currentUser",
|
||||
"installerHooks": "uninstall-projects.nsh"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
Var TexrraCleanupDistro
|
||||
Var TexrraCleanupPath
|
||||
Var TexrraCleanupWsl
|
||||
Var TexrraCleanupMode
|
||||
Var TexrraCleanupStatus
|
||||
|
||||
; Distro names are passed as a single Windows argument.
|
||||
!macro TexrraValidateDistro
|
||||
StrCpy $2 0
|
||||
${Do}
|
||||
StrCpy $1 $TexrraCleanupDistro 1 $2
|
||||
${IfThen} $1 == "" ${|} ${ExitDo} ${|}
|
||||
${If} $1 == "$\""
|
||||
${OrIf} $1 == "\"
|
||||
${OrIf} $1 == "$\r"
|
||||
${OrIf} $1 == "$\n"
|
||||
Goto texrra_cleanup_unavailable
|
||||
${EndIf}
|
||||
IntOp $2 $2 + 1
|
||||
${Loop}
|
||||
!macroend
|
||||
|
||||
!macro TexrraRunWslCleanup action options
|
||||
${If} $TexrraCleanupDistro == ""
|
||||
nsExec::Exec ${options} '"$TexrraCleanupWsl" --cd "$PLUGINSDIR" --exec python3 -B ./uninstall-projects.py ${action}'
|
||||
${Else}
|
||||
nsExec::Exec ${options} '"$TexrraCleanupWsl" --distribution "$TexrraCleanupDistro" --cd "$PLUGINSDIR" --exec python3 -B ./uninstall-projects.py ${action}'
|
||||
${EndIf}
|
||||
Pop $TexrraCleanupStatus
|
||||
!macroend
|
||||
|
||||
!macro TexrraReadCleanupFile name output
|
||||
ClearErrors
|
||||
FileOpen $0 "$PLUGINSDIR\${name}" r
|
||||
IfErrors texrra_cleanup_unavailable
|
||||
FileReadUTF16LE $0 ${output}
|
||||
FileClose $0
|
||||
${IfThen} ${output} == "" ${|} Goto texrra_cleanup_unavailable ${|}
|
||||
!macroend
|
||||
|
||||
!macro NSIS_HOOK_PREUNINSTALL
|
||||
; Updates, automated uninstalls and elevated accounts always preserve projects.
|
||||
${If} ${Silent}
|
||||
${OrIf} $PassiveMode = 1
|
||||
${OrIf} $UpdateMode = 1
|
||||
${OrIf} $DeleteAppDataCheckboxState <> 1
|
||||
Goto texrra_cleanup_done
|
||||
${EndIf}
|
||||
ReadRegStr $0 HKCU "${MANUPRODUCTKEY}" ""
|
||||
${IfThen} $0 != $INSTDIR ${|} Goto texrra_cleanup_done ${|}
|
||||
System::Call 'shell32::IsUserAnAdmin() i .r0'
|
||||
${IfThen} $0 != 0 ${|} Goto texrra_cleanup_done ${|}
|
||||
|
||||
${If} ${FileExists} "$INSTDIR\backend\bin\native_editor.exe"
|
||||
${AndIfNot} ${FileExists} "$INSTDIR\backend\wsl-launch.py"
|
||||
ReadEnvStr $0 "LOCALAPPDATA"
|
||||
${IfThen} $0 != $LOCALAPPDATA ${|} Goto texrra_cleanup_unavailable ${|}
|
||||
StrCpy $TexrraCleanupMode "native"
|
||||
${ElseIf} ${FileExists} "$INSTDIR\backend\wsl-launch.py"
|
||||
${AndIfNot} ${FileExists} "$INSTDIR\backend\bin\native_editor.exe"
|
||||
StrCpy $TexrraCleanupMode "wsl"
|
||||
${Else}
|
||||
Goto texrra_cleanup_done
|
||||
${EndIf}
|
||||
|
||||
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
||||
InitPluginsDir
|
||||
DetailPrint "Checking the Texrra project location..."
|
||||
${If} $TexrraCleanupMode == "native"
|
||||
nsExec::Exec /TIMEOUT=20000 '"$INSTDIR\${MAINBINARYNAME}.exe" --uninstall-projects inspect "$PLUGINSDIR"'
|
||||
Pop $TexrraCleanupStatus
|
||||
${Else}
|
||||
StrCpy $TexrraCleanupWsl "$WINDIR\Sysnative\wsl.exe"
|
||||
${IfNot} ${FileExists} "$TexrraCleanupWsl"
|
||||
StrCpy $TexrraCleanupWsl "$SYSDIR\wsl.exe"
|
||||
${IfNot} ${FileExists} "$TexrraCleanupWsl"
|
||||
Goto texrra_cleanup_unavailable
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
ReadEnvStr $TexrraCleanupDistro "TEXRRA_WSL_DISTRO"
|
||||
!insertmacro TexrraValidateDistro
|
||||
Push $OUTDIR
|
||||
SetOutPath "$PLUGINSDIR"
|
||||
File /oname=uninstall-projects.py "${TAURIDIR}/uninstall-projects.py"
|
||||
Pop $0
|
||||
SetOutPath $0
|
||||
!insertmacro TexrraRunWslCleanup "inspect" "/TIMEOUT=20000"
|
||||
${EndIf}
|
||||
|
||||
${IfThen} $TexrraCleanupStatus == 2 ${|} Goto texrra_cleanup_done ${|}
|
||||
${IfThen} $TexrraCleanupStatus != 0 ${|} Goto texrra_cleanup_unavailable ${|}
|
||||
!insertmacro TexrraReadCleanupFile "projects-path.txt" "$TexrraCleanupPath"
|
||||
${If} $TexrraCleanupMode == "wsl"
|
||||
!insertmacro TexrraReadCleanupFile "projects-distro.txt" "$TexrraCleanupDistro"
|
||||
!insertmacro TexrraValidateDistro
|
||||
MessageBox MB_YESNO|MB_ICONEXCLAMATION|MB_DEFBUTTON2 \
|
||||
"Permanently delete all Texrra project files in this folder?$\r$\n$\r$\nWSL distribution: $TexrraCleanupDistro$\r$\n$TexrraCleanupPath" \
|
||||
IDYES texrra_cleanup_delete
|
||||
${Else}
|
||||
MessageBox MB_YESNO|MB_ICONEXCLAMATION|MB_DEFBUTTON2 \
|
||||
"Permanently delete all Texrra project files in this folder?$\r$\n$\r$\n$TexrraCleanupPath" \
|
||||
IDYES texrra_cleanup_delete
|
||||
${EndIf}
|
||||
Goto texrra_cleanup_done
|
||||
|
||||
texrra_cleanup_delete:
|
||||
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
||||
DetailPrint "Deleting projects in $TexrraCleanupPath..."
|
||||
${If} $TexrraCleanupMode == "native"
|
||||
nsExec::Exec '"$INSTDIR\${MAINBINARYNAME}.exe" --uninstall-projects delete "$PLUGINSDIR"'
|
||||
Pop $TexrraCleanupStatus
|
||||
${Else}
|
||||
!insertmacro TexrraRunWslCleanup "delete" ""
|
||||
${EndIf}
|
||||
${If} $TexrraCleanupStatus != 0
|
||||
MessageBox MB_OK|MB_ICONEXCLAMATION "Texrra could not finish deleting all files in:$\r$\n$TexrraCleanupPath"
|
||||
${EndIf}
|
||||
Goto texrra_cleanup_done
|
||||
|
||||
texrra_cleanup_unavailable:
|
||||
MessageBox MB_OK|MB_ICONEXCLAMATION "Texrra could not safely open the project folder. Project files will be kept."
|
||||
texrra_cleanup_done:
|
||||
!macroend
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Inspect or delete only the active WSL user's Texrra project store."""
|
||||
|
||||
from contextlib import ExitStack
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import unicodedata
|
||||
|
||||
|
||||
def write_display(name, value, max_units):
|
||||
encoded = value.encode("utf-16-le")
|
||||
if not encoded or len(encoded) > max_units * 2 or any(
|
||||
unicodedata.category(char) in ("Cc", "Cf") for char in value
|
||||
):
|
||||
raise ValueError("The project location cannot be displayed safely")
|
||||
with open(name, "xb") as display:
|
||||
display.write(encoded)
|
||||
|
||||
|
||||
def mounted_project_tree(projects):
|
||||
for line in Path("/proc/self/mountinfo").read_bytes().splitlines():
|
||||
mount = re.sub(rb"\\([0-7]{3})", lambda match: bytes([int(match[1], 8)]), line.split()[4])
|
||||
mount = Path(os.fsdecode(mount))
|
||||
if mount == projects or projects in mount.parents:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def run(action):
|
||||
uid = os.geteuid()
|
||||
distro = os.environ.get("WSL_DISTRO_NAME", "")
|
||||
if not uid or not distro or '"' in distro or "\\" in distro:
|
||||
raise ValueError("The WSL user or distribution is unavailable")
|
||||
|
||||
data = Path(os.environ.get("XDG_DATA_HOME", ""))
|
||||
if not data.is_absolute():
|
||||
data = Path.home() / ".local/share"
|
||||
if data.anchor != "/" or ".." in data.parts:
|
||||
raise ValueError("The WSL data location is unsafe")
|
||||
home = data / "texrra-desktop"
|
||||
projects = home / "projects"
|
||||
|
||||
if not shutil.rmtree.avoids_symlink_attacks:
|
||||
raise ValueError("Safe recursive deletion is unavailable")
|
||||
directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
with ExitStack() as held:
|
||||
parent = None
|
||||
try:
|
||||
for part in home.parts:
|
||||
parent = os.open(part, directory_flags, dir_fd=parent)
|
||||
held.callback(os.close, parent)
|
||||
info = os.stat("projects", dir_fd=parent, follow_symlinks=False)
|
||||
except FileNotFoundError:
|
||||
return 2
|
||||
|
||||
if (
|
||||
os.fstat(parent).st_uid != uid
|
||||
or info.st_uid != uid
|
||||
or not stat.S_ISDIR(info.st_mode)
|
||||
or mounted_project_tree(projects)
|
||||
):
|
||||
raise ValueError("The project location is unsafe")
|
||||
|
||||
# Use the same lock as the desktop launcher. An active editor keeps its data.
|
||||
lock = os.open("backend.lock", os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, dir_fd=parent)
|
||||
held.callback(os.close, lock)
|
||||
lock_info = os.fstat(lock)
|
||||
if not stat.S_ISREG(lock_info.st_mode) or lock_info.st_uid != uid or lock_info.st_nlink != 1:
|
||||
raise ValueError("The project store has no safe editor lock")
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
|
||||
if os.stat("projects", dir_fd=parent, follow_symlinks=False) != info:
|
||||
raise ValueError("The project location changed while acquiring the editor lock")
|
||||
identity = [distro, uid, str(projects), info.st_dev, info.st_ino, info.st_ctime_ns]
|
||||
if action == "inspect":
|
||||
write_display("projects-distro.txt", distro, 160)
|
||||
write_display("projects-path.txt", str(projects), 620)
|
||||
with open("projects-identity.json", "x", encoding="utf-8") as ticket:
|
||||
json.dump(identity, ticket)
|
||||
elif action == "delete":
|
||||
with open("projects-identity.json", encoding="utf-8") as ticket:
|
||||
if json.load(ticket) != identity:
|
||||
raise ValueError("The project location changed after confirmation")
|
||||
shutil.rmtree("projects", dir_fd=parent)
|
||||
else:
|
||||
raise ValueError("Unknown cleanup action")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(run(sys.argv[1]))
|
||||
except (OSError, ValueError, IndexError):
|
||||
sys.exit(1)
|
||||
Reference in new issue
Block a user