Build a standalone Windows desktop with opt-in project removal

This commit is contained in:
gloamxun committed 2026-12-02 18:20:38 +08:00
1 parent 2c5b9b5f10
commit 2c99cade7d
24 files changed
+1404 -168

No files matched your search

+1 -1
View File
@@ -3237,7 +3237,7 @@ dependencies = [
[[package]]
name = "texrra-desktop"
version = "0.1.8"
version = "0.1.9"
dependencies = [
"serde_json",
"tauri",
+1 -1
View File
@@ -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
View File
@@ -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(())
+161
View File
@@ -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,
}
}
+9 -4
View File
@@ -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"
}
}
}
+123
View File
@@ -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
+99
View File
@@ -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)