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

+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,
}
}