diff --git a/Cargo.lock b/Cargo.lock index 645aa7a..0bde522 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1263,6 +1263,12 @@ version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +[[package]] +name = "revera" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d75e7646f24e2e5b7c017c39348fbdaa35177b0f936698d450e5fa194716a56" + [[package]] name = "rmp" version = "0.8.15" @@ -1746,6 +1752,7 @@ dependencies = [ "md5", "png 0.18.1", "read-fonts 0.47.0", + "revera", "rusttype", "rustybuzz", "serde", diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index cd074d0..e5fdd25 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -29,3 +29,6 @@ unicode-normalization = "=0.1.25" [target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies] libc = "0.2" + +[target.'cfg(not(all(target_os = "linux", target_env = "gnu")))'.dependencies] +revera = "=0.2.1" diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_match.rs b/crates/texrra-tex-core/src/execution/engine/pdf_match.rs index db2b238..baeec51 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_match.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_match.rs @@ -1,8 +1,12 @@ use super::*; -use std::ffi::{CString, c_int}; -use std::mem::MaybeUninit; use std::ops::Range; -use std::ptr; + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +#[path = "pdf_match/glibc.rs"] +mod backend; +#[cfg(not(all(target_os = "linux", target_env = "gnu")))] +#[path = "pdf_match/portable.rs"] +mod backend; #[derive(PartialEq, Eq)] pub(super) struct PdfMatch { @@ -26,7 +30,7 @@ pub enum RegexOutcome { } pub fn match_pdf_regex(request: &RegexRequest) -> Result { - match search( + match backend::search( request.pattern.clone(), request.input.clone(), request.count, @@ -80,7 +84,7 @@ impl Executor { self.check_cancellation()?; let text = match result.map_err(|message| self.error(message, origin.span))? { RegexOutcome::Match(captures) => { - let input = as_c_string(request.input).into_bytes(); + let input = before_nul(request.input); if captures .iter() .flatten() @@ -114,106 +118,10 @@ enum SearchError { Runtime(String), } -struct CLocale { - active: libc::locale_t, - previous: libc::locale_t, -} - -impl CLocale { - fn enter() -> Result { - // The reference engine treats matching as C-locale byte processing. - // Changing only this thread leaves concurrent jobs and the host alone. - let active = unsafe { libc::newlocale(libc::LC_ALL_MASK, c"C".as_ptr(), ptr::null_mut()) }; - if active.is_null() { - return Err(SearchError::Runtime("cannot create pdfTeX C locale".into())); - } - let previous = unsafe { libc::uselocale(active) }; - if previous.is_null() { - unsafe { libc::freelocale(active) }; - return Err(SearchError::Runtime("cannot enter pdfTeX C locale".into())); - } - Ok(Self { active, previous }) - } -} - -impl Drop for CLocale { - fn drop(&mut self) { - // previous is the still-live locale returned by uselocale above. - unsafe { - libc::uselocale(self.previous); - libc::freelocale(self.active); - } - } -} - -struct CompiledRegex(libc::regex_t); - -impl Drop for CompiledRegex { - fn drop(&mut self) { - // This wrapper is created only after successful regcomp. - unsafe { libc::regfree(&mut self.0) }; - } -} - -fn regex_error(code: c_int) -> String { - // An error code can be described without referring to a compiled regex. - let length = unsafe { libc::regerror(code, ptr::null(), ptr::null_mut(), 0) }; - let mut message = vec![0u8; length]; - unsafe { libc::regerror(code, ptr::null(), message.as_mut_ptr().cast(), length) }; - message.pop(); - String::from_utf8_lossy(&message).into_owned() -} - -fn as_c_string(mut bytes: Vec) -> CString { +fn before_nul(mut bytes: Vec) -> Vec { // pdfTeX's makecstring passes the prefix through the first NUL. if let Some(end) = bytes.iter().position(|&byte| byte == 0) { bytes.truncate(end); } - CString::new(bytes).expect("regex bytes were truncated at the first NUL") -} - -fn search( - pattern: Vec, - input: Vec, - requested: usize, - insensitive: bool, -) -> Result, SearchError> { - let _locale = CLocale::enter()?; - let pattern = as_c_string(pattern); - let input = as_c_string(input); - let flags = libc::REG_EXTENDED | if insensitive { libc::REG_ICASE } else { 0 }; - let mut regex = MaybeUninit::uninit(); - // regcomp initializes the regex storage on success. The pattern is - // NUL-terminated and valid throughout the call. - let status = unsafe { libc::regcomp(regex.as_mut_ptr(), pattern.as_ptr(), flags) }; - if status != 0 { - return Err(SearchError::Pattern(regex_error(status))); - } - let regex = CompiledRegex(unsafe { regex.assume_init() }); - // Group starts cannot outnumber pattern bytes. Requests beyond that - // bound are observable only as missing captures. - let count = requested.min(pattern.as_bytes().len() + 1); - let mut ranges = vec![ - libc::regmatch_t { - rm_so: -1, - rm_eo: -1 - }; - count - ]; - // Both C strings and the initialized regex live through the call. - // A zero count asks regexec to skip writing capture positions. - let status = unsafe { libc::regexec(®ex.0, input.as_ptr(), count, ranges.as_mut_ptr(), 0) }; - if status != 0 { - return Ok(None); - } - let input = input.into_bytes(); - let captures = ranges - .into_iter() - .map(|range| { - let start = usize::try_from(range.rm_so).ok()?; - let end = usize::try_from(range.rm_eo).ok()?; - (start <= end && end <= input.len()).then_some(start..end) - }) - .collect(); - Ok(Some(PdfMatch { input, captures })) + bytes } diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_match/glibc.rs b/crates/texrra-tex-core/src/execution/engine/pdf_match/glibc.rs new file mode 100644 index 0000000..e0c9b4a --- /dev/null +++ b/crates/texrra-tex-core/src/execution/engine/pdf_match/glibc.rs @@ -0,0 +1,104 @@ +use super::{PdfMatch, SearchError, before_nul}; +use std::ffi::{CString, c_int}; +use std::mem::MaybeUninit; +use std::ptr; + +fn as_c_string(bytes: Vec) -> CString { + CString::new(before_nul(bytes)).expect("regex bytes were truncated at the first NUL") +} + +struct CLocale { + active: libc::locale_t, + previous: libc::locale_t, +} + +impl CLocale { + fn enter() -> Result { + // The reference engine treats matching as C-locale byte processing. + // Changing only this thread leaves concurrent jobs and the host alone. + let active = unsafe { libc::newlocale(libc::LC_ALL_MASK, c"C".as_ptr(), ptr::null_mut()) }; + if active.is_null() { + return Err(SearchError::Runtime("cannot create pdfTeX C locale".into())); + } + let previous = unsafe { libc::uselocale(active) }; + if previous.is_null() { + unsafe { libc::freelocale(active) }; + return Err(SearchError::Runtime("cannot enter pdfTeX C locale".into())); + } + Ok(Self { active, previous }) + } +} + +impl Drop for CLocale { + fn drop(&mut self) { + // previous is the still-live locale returned by uselocale above. + unsafe { + libc::uselocale(self.previous); + libc::freelocale(self.active); + } + } +} + +struct CompiledRegex(libc::regex_t); + +impl Drop for CompiledRegex { + fn drop(&mut self) { + // This wrapper is created only after successful regcomp. + unsafe { libc::regfree(&mut self.0) }; + } +} + +fn regex_error(code: c_int) -> String { + // An error code can be described without referring to a compiled regex. + let length = unsafe { libc::regerror(code, ptr::null(), ptr::null_mut(), 0) }; + let mut message = vec![0u8; length]; + unsafe { libc::regerror(code, ptr::null(), message.as_mut_ptr().cast(), length) }; + message.pop(); + String::from_utf8_lossy(&message).into_owned() +} + +pub(super) fn search( + pattern: Vec, + input: Vec, + requested: usize, + insensitive: bool, +) -> Result, SearchError> { + let _locale = CLocale::enter()?; + let pattern = as_c_string(pattern); + let input = as_c_string(input); + let flags = libc::REG_EXTENDED | if insensitive { libc::REG_ICASE } else { 0 }; + let mut regex = MaybeUninit::uninit(); + // regcomp initializes the regex storage on success. The pattern is + // NUL-terminated and valid throughout the call. + let status = unsafe { libc::regcomp(regex.as_mut_ptr(), pattern.as_ptr(), flags) }; + if status != 0 { + return Err(SearchError::Pattern(regex_error(status))); + } + let regex = CompiledRegex(unsafe { regex.assume_init() }); + // Group starts cannot outnumber pattern bytes. Requests beyond that + // bound are observable only as missing captures. + let count = requested.min(pattern.as_bytes().len() + 1); + let mut ranges = vec![ + libc::regmatch_t { + rm_so: -1, + rm_eo: -1 + }; + count + ]; + // Both C strings and the initialized regex live through the call. + // A zero count asks regexec to skip writing capture positions. + let status = unsafe { libc::regexec(®ex.0, input.as_ptr(), count, ranges.as_mut_ptr(), 0) }; + if status != 0 { + return Ok(None); + } + let input = input.into_bytes(); + let captures = ranges + .into_iter() + .map(|range| { + let start = usize::try_from(range.rm_so).ok()?; + let end = usize::try_from(range.rm_eo).ok()?; + (start <= end && end <= input.len()).then_some(start..end) + }) + .collect(); + Ok(Some(PdfMatch { input, captures })) +} diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_match/portable.rs b/crates/texrra-tex-core/src/execution/engine/pdf_match/portable.rs new file mode 100644 index 0000000..b0369ac --- /dev/null +++ b/crates/texrra-tex-core/src/execution/engine/pdf_match/portable.rs @@ -0,0 +1,112 @@ +use super::{PdfMatch, SearchError, before_nul}; +use revera::RegexBuilder; + +pub(super) fn search( + pattern: Vec, + input: Vec, + requested: usize, + insensitive: bool, +) -> Result, SearchError> { + let pattern = before_nul(pattern); + let input = before_nul(input); + let count = requested.min(pattern.len() + 1); + if pattern.is_empty() { + let captures = (count > 0).then_some(Some(0..0)).into_iter().collect(); + return Ok(Some(PdfMatch { input, captures })); + } + let pattern = encode_pattern(&pattern); + let subject: String = input.iter().copied().map(c_locale_byte).collect(); + let regex = RegexBuilder::new(&pattern) + .case_insensitive(insensitive) + .build() + .map_err(|error| SearchError::Pattern(error.to_string()))?; + let Some(matches) = regex + .captures(&subject) + .map_err(|error| SearchError::Runtime(error.to_string()))? + else { + return Ok(None); + }; + let starts: Vec<_> = subject + .char_indices() + .map(|(offset, _)| offset) + .chain(std::iter::once(subject.len())) + .collect(); + let mut captures: Vec<_> = matches + .iter() + .take(count) + .map(|matched| { + let matched = matched?; + let start = starts.binary_search(&matched.start()).ok()?; + let end = starts.binary_search(&matched.end()).ok()?; + Some(start..end) + }) + .collect(); + captures.resize(count, None); + Ok(Some(PdfMatch { input, captures })) +} + +fn c_locale_byte(byte: u8) -> char { + // Private-use code points preserve byte order above ASCII without + // giving high bytes Unicode case folds or character classifications. + if byte.is_ascii() { + char::from(byte) + } else { + char::from_u32(0xE000 + u32::from(byte)).unwrap() + } +} + +fn encode_pattern(mut bytes: &[u8]) -> String { + let mut pattern = String::new(); + while let Some((&next, remaining)) = bytes.split_first() { + bytes = remaining; + match next { + b'\\' if !bytes.is_empty() => { + let escaped = bytes[0]; + bytes = &bytes[1..]; + match escaped { + b'w' => pattern.push_str("[[:alnum:]_]"), + b'W' => pattern.push_str("[^[:alnum:]_]"), + b's' => pattern.push_str("[[:space:]]"), + b'S' => pattern.push_str("[^[:space:]]"), + _ => { + pattern.push('\\'); + pattern.push(c_locale_byte(escaped)); + } + } + } + b'[' => { + let end = bracket_end(bytes); + pattern.push('['); + pattern.extend(bytes[..end].iter().copied().map(c_locale_byte)); + bytes = &bytes[end..]; + } + _ => pattern.push(c_locale_byte(next)), + } + } + pattern +} + +fn bracket_end(bytes: &[u8]) -> usize { + let mut position = usize::from(bytes.starts_with(b"^")); + if bytes.get(position) == Some(&b']') { + position += 1; + } + while let Some(&next) = bytes.get(position) { + position += 1; + if next == b']' { + break; + } + if next == b'[' + && let Some(delimiter @ (b'.' | b'=' | b':')) = bytes.get(position) + { + let closing = [*delimiter, b']']; + if let Some(end) = bytes[position + 1..] + .windows(2) + .position(|pair| pair == closing) + { + position += 3 + end; + } + } + } + position +} diff --git a/crates/texrra-tex-core/src/resources/project.rs b/crates/texrra-tex-core/src/resources/project.rs index 437034a..311ea34 100644 --- a/crates/texrra-tex-core/src/resources/project.rs +++ b/crates/texrra-tex-core/src/resources/project.rs @@ -466,7 +466,12 @@ impl ProjectSnapshot { let mut links = 0; while let Some(part) = queue.pop_front() { match Path::new(&part).components().next().unwrap() { - Component::Prefix(_) => current.push(&part), + Component::Prefix(_) => { + // A Windows volume prefix only names a directory once + // its root component has been appended. + current.push(&part); + continue; + } Component::RootDir => current.push(&part), Component::CurDir => {} Component::ParentDir => { diff --git a/desktop/README.md b/desktop/README.md index d3a07a9..d74d671 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -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 的当前测试电脑。桌面版使用 diff --git a/desktop/build-windows-backend.py b/desktop/build-windows-backend.py new file mode 100644 index 0000000..cf38577 --- /dev/null +++ b/desktop/build-windows-backend.py @@ -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(" + +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. diff --git a/desktop/licenses/revera-Unicode-3.0.txt b/desktop/licenses/revera-Unicode-3.0.txt new file mode 100644 index 0000000..ca907d7 --- /dev/null +++ b/desktop/licenses/revera-Unicode-3.0.txt @@ -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 diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index a04864f..fd8113d 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -3237,7 +3237,7 @@ dependencies = [ [[package]] name = "texrra-desktop" -version = "0.1.8" +version = "0.1.9" dependencies = [ "serde_json", "tauri", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 7c99d48..4fb436c 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -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" diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 652e056..65bfd52 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -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 { .then_some(url) } -fn start_engine(backend: &Backend, launcher: &Path) -> Result { - 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 { + 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 { + let mut child = launcher + .command()? .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() @@ -99,6 +148,10 @@ fn start_engine(backend: &Backend, launcher: &Path) -> Result { 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 { } }); 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 { +fn windows_data_home() -> Result { + 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 { 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::)); let navigation = Arc::clone(&allowed); - let startup_error = Arc::new(Mutex::new(None::)); - let deferred_error = Arc::clone(&startup_error); + let startup_status = Arc::new(Mutex::new(None::)); + 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::(); - 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(()) diff --git a/desktop/src-tauri/src/uninstall_projects.rs b/desktop/src-tauri/src/uninstall_projects.rs new file mode 100644 index 0000000..65bf427 --- /dev/null +++ b/desktop/src-tauri/src/uninstall_projects.rs @@ -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 { + 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 { + 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::() 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::>() + .into_iter() + .rev() + .map(|path| directory(path, FILE_SHARE_READ_WRITE)) + .collect::>>()?; + 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, + } +} diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 8cbb3ee..64b169c 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -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" } } } diff --git a/desktop/src-tauri/uninstall-projects.nsh b/desktop/src-tauri/uninstall-projects.nsh new file mode 100644 index 0000000..62536dd --- /dev/null +++ b/desktop/src-tauri/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 diff --git a/desktop/src-tauri/uninstall-projects.py b/desktop/src-tauri/uninstall-projects.py new file mode 100644 index 0000000..a515acc --- /dev/null +++ b/desktop/src-tauri/uninstall-projects.py @@ -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) diff --git a/examples/native_editor/bibliography.rs b/examples/native_editor/bibliography.rs index d1f6b9e..e8a1b12 100644 --- a/examples/native_editor/bibliography.rs +++ b/examples/native_editor/bibliography.rs @@ -16,6 +16,8 @@ use texrra_engine::native::{CompileRequest, GeneratedArtifacts, ProjectSnapshot} use texrra_tex_core::resources::ResourceVersion; mod cache; +#[cfg(windows)] +mod windows; const MAX_AUX_BYTES: u64 = 2 * 1024 * 1024; const MAX_INPUT_BYTES: u64 = 32 * 1024 * 1024; @@ -381,6 +383,10 @@ fn find_style(scratch: &Path, style: &Path, roots: &[PathBuf]) -> Result Result<(Vec, bool), String> { }; #[cfg(not(target_os = "linux"))] let mut command = Command::new("bibtex"); - let mut child = private_environment(&mut command, scratch) + private_environment(&mut command, scratch); + #[cfg(windows)] + if let Some(directory) = windows::bundled_directory() { + command = windows::bundled_command(&directory, scratch)?; + } + let mut child = command .env("BIBINPUTS", ".") .env("BSTINPUTS", ".") .arg(JOB) diff --git a/examples/native_editor/bibliography/cache.rs b/examples/native_editor/bibliography/cache.rs index 8f70d71..6a40190 100644 --- a/examples/native_editor/bibliography/cache.rs +++ b/examples/native_editor/bibliography/cache.rs @@ -59,7 +59,15 @@ pub(super) fn write(path: &Path, key: &[u8; 32], output: &[u8]) -> io::Result<() result } -#[cfg(not(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu")))] +#[cfg(windows)] +pub(super) fn tool_identity(_scratch: &Path) -> Option<[u8; 32]> { + super::windows::tool_identity() +} + +#[cfg(not(any( + windows, + all(target_os = "linux", target_arch = "x86_64", target_env = "gnu") +)))] pub(super) fn tool_identity(_scratch: &Path) -> Option<[u8; 32]> { None } diff --git a/examples/native_editor/bibliography/windows.rs b/examples/native_editor/bibliography/windows.rs new file mode 100644 index 0000000..e6e623b --- /dev/null +++ b/examples/native_editor/bibliography/windows.rs @@ -0,0 +1,105 @@ +use super::{MAX_INPUT_BYTES, bib_error, private_environment, read_limited, stage}; +use sha2::{Digest, Sha256}; +use std::{ + env, fs, + os::windows::process::CommandExt, + path::{Path, PathBuf}, + process::Command, + sync::Arc, +}; + +const CREATE_NO_WINDOW: u32 = 0x0800_0000; + +pub(super) fn bundled_directory() -> Option { + let backend = PathBuf::from(env::var_os("TEXRRA_WINDOWS_BACKEND")?); + if !backend.is_absolute() + || env::current_exe().ok()?.canonicalize().ok()? != backend.join("bin/native_editor.exe") + { + return None; + } + Some(backend.join("tools/bibtex")) +} + +pub(super) fn tool_identity() -> Option<[u8; 32]> { + let directory = bundled_directory()?; + let mut hash = Sha256::new(); + hash.update(b"texrra Windows BibTeX 1"); + for name in [ + "bibtex.exe", + "kpsewhich.exe", + "kpathsealibw64.dll", + "msvcr100.dll", + "texmf.cnf", + ] { + let file = directory.join(name); + if !fs::symlink_metadata(&file).ok()?.is_file() { + return None; + } + let bytes = read_limited(&file, 16 * 1024 * 1024).ok()?; + super::cache::field(&mut hash, name.as_bytes()); + super::cache::field(&mut hash, &bytes); + } + Some(hash.finalize().into()) +} + +pub(super) fn bundled_command(directory: &Path, scratch: &Path) -> Result { + // Keep Kpathsea's search relative to its working directory. The tool + // never needs to interpret a canonical Windows path or a user search list. + let configuration = read_limited(&directory.join("texmf.cnf"), 64 * 1024).map_err(bib_error)?; + stage(scratch, Path::new("texmf.cnf"), &configuration).map_err(bib_error)?; + let executable = win32_path(&directory.join("bibtex.exe"))?; + let working_directory = win32_path(scratch)?; + let mut command = Command::new(executable); + private_environment(&mut command, &working_directory) + .creation_flags(CREATE_NO_WINDOW) + .env_remove("PATH") + .env("HOME", ".") + .env("TEXMFHOME", ".") + .env("TEXMFVAR", ".") + .env("TEXMFCONFIG", ".") + .env("TEXMFCNF", "."); + if let Some(root) = env::var_os("SystemRoot") { + command.env("SystemRoot", root); + } + Ok(command) +} + +// The packaged Kpathsea rejects the verbatim prefix in the executable +// spelling it receives from the Windows process launcher. +fn win32_path(path: &Path) -> Result { + let value = path.to_str().ok_or("BibTeX needs Unicode Windows paths")?; + if let Some(rest) = value.strip_prefix(r"\\?\UNC\") { + return Ok(format!(r"\\{rest}").into()); + } + Ok(value.strip_prefix(r"\\?\").unwrap_or(value).into()) +} + +pub(super) fn find_style(style: &Path, roots: &[PathBuf]) -> Result, String> { + for root in roots { + let style_root = root.join("bibtex/bst"); + let mut directories = vec![style_root]; + while let Some(directory) = directories.pop() { + let candidate = directory.join(style); + if candidate.is_file() { + let path = candidate.canonicalize().map_err(bib_error)?; + if path.starts_with(root) { + return read_limited(&path, MAX_INPUT_BYTES) + .map(Into::into) + .map_err(bib_error); + } + } + // Bundled resources are ordinary files. Keep root priority and + // a stable first match, without following directory links. + if let Ok(entries) = fs::read_dir(directory) { + let mut children = entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) + .map(|entry| entry.path()) + .collect::>(); + children.sort_unstable(); + directories.extend(children.into_iter().rev()); + } + } + } + Err(format!("BibTeX style missing: {}", style.display())) +} diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 170523d..26f1e2d 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -37,6 +37,8 @@ mod resource_capture; mod saved_project; mod text_layer; mod thread_usage; +#[cfg(windows)] +mod windows_format; const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024; const PAGE: &str = include_str!("index.html"); @@ -275,6 +277,14 @@ fn main() -> Result<(), Box> { std::process::exit(status); } let mut args = std::env::args_os().skip(1).peekable(); + #[cfg(windows)] + if args.next_if(|arg| arg == "--windows-desktop").is_some() { + return windows_format::run(args).map_err(|error| { + let detail = error.to_string().replace(['\r', '\n'], " "); + println!("Texrra desktop error {detail}"); + error + }); + } 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) { @@ -337,6 +347,15 @@ fn main() -> Result<(), Box> { let editor = finish_prepare(staged, &run, &compiler, None, None)?; (port, Some(EditorSession::new(run, editor, compiler, None))) }; + serve(web, library, port, session) +} + +fn serve( + web: Option, + library: Option, + port: u16, + session: Option, +) -> Result<(), Box> { let mut session = session.map(|session| Arc::new(Mutex::new(session))); let mut opening: Option = None; let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?; diff --git a/examples/native_editor/windows_format.rs b/examples/native_editor/windows_format.rs new file mode 100644 index 0000000..27ecb36 --- /dev/null +++ b/examples/native_editor/windows_format.rs @@ -0,0 +1,181 @@ +//! Bootstrap the installed Windows editor from the packaged TeX resources. +use crate::{WebAssets, library::Library, serve}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::{ + env, + ffi::{OsStr, OsString}, + fs::{self, File, OpenOptions}, + io::{self, Read, Write}, + path::{Path, PathBuf}, +}; +use texrra_engine::native::{CompileRequest, Entry, dump_format, job_time}; +use texrra_tex_core::{ + execution::{Cancellation, InputProfile}, + resources::WorldConfig, +}; + +type LaunchResult = Result>; + +#[derive(Deserialize)] +struct Bundle { + schema: u32, + resources_sha256: String, +} + +pub(super) fn run(mut arguments: impl Iterator) -> LaunchResult<()> { + let usage = "native_editor --windows-desktop BACKEND_DIRECTORY DATA_DIRECTORY"; + let backend = PathBuf::from(arguments.next().ok_or(usage)?); + let home = PathBuf::from(arguments.next().ok_or(usage)?); + if arguments.next().is_some() || !backend.is_absolute() || !home.is_absolute() { + return Err(usage.into()); + } + let backend = backend.canonicalize()?; + fs::create_dir_all(&home)?; + let home = home.canonicalize()?; + if home.starts_with(&backend) || backend.starts_with(&home) { + return Err("Packaged resources and desktop data must be separate".into()); + } + let _lock = lock_backend(&home)?; + + let receipt = fs::read(backend.join("windows-bundle.json"))?; + let bundle: Bundle = serde_json::from_slice(&receipt)?; + if bundle.schema != 1 + || bundle.resources_sha256.len() != 64 + || !bundle + .resources_sha256 + .bytes() + .all(|byte| byte.is_ascii_hexdigit()) + { + return Err("Invalid Windows desktop bundle receipt".into()); + } + let mut key = Sha256::new(); + key.update(b"texrra Windows LaTeX format 1"); + key.update(Sha256::digest(&receipt)); + key.update(backend.as_os_str().as_encoded_bytes()); + let runtime = home.join("runtime").join(format!("{:x}", key.finalize())); + fs::create_dir_all(&runtime)?; + let runtime = runtime.canonicalize()?; + + let texmf = backend.join("texmf"); + let roots = ["overlay", "dist", "var"] + .map(|directory| texmf.join(directory).canonicalize()) + .into_iter() + .collect::>>()?; + let font_maps = texmf.join("fonts").canonicalize()?; + if roots + .iter() + .chain([&font_maps]) + .any(|root| !root.is_dir() || !root.starts_with(&backend)) + || !font_maps.join("pdftex.map").is_file() + { + return Err("The Windows desktop TeX resources are incomplete".into()); + } + let state = home.join("state"); + fs::create_dir_all(&state)?; + configure_environment(&backend, &state, &font_maps)?; + start_lease()?; + + let format = runtime.join("latex.tfx"); + if !format.is_file() { + let ini = roots[1].join("tex/latex/tex-ini-files/pdflatex.ini"); + build_format(&ini, &runtime, &format, &roots)?; + } + let manifest = runtime.join("format-resources.json"); + let manifest_bytes = serde_json::to_vec(&serde_json::json!({"texmf_roots": roots}))?; + if fs::read(&manifest).ok().as_deref() != Some(&manifest_bytes) { + fs::write(&manifest, manifest_bytes)?; + } + let web = WebAssets::load(&backend.join("web"))?; + let library = Library::new( + home.join("projects"), + format.canonicalize()?, + manifest.canonicalize()?, + runtime.join("web-runs"), + InputProfile::TeX8Bit, + )?; + serve(Some(web), Some(library), 0, None) +} + +fn lock_backend(home: &Path) -> io::Result { + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(home.join("backend.lock"))?; + match file.try_lock() { + Ok(()) => Ok(file), + Err(std::fs::TryLockError::WouldBlock) => Err(io::Error::other( + "The Texrra desktop is already running for this Windows data directory", + )), + Err(std::fs::TryLockError::Error(error)) => Err(error), + } +} + +fn configure_environment(backend: &Path, state: &Path, font_maps: &Path) -> LaunchResult<()> { + let search = env::join_paths([font_maps.as_os_str(), OsStr::new("")])?; + // These changes happen during Windows startup before any worker is started. + // The Windows environment is also thread-safe for Rust's environment API. + unsafe { + for variable in [ + "TEXRRA_TEXMF", + "TEXINPUTS", + "TFMFONTS", + "VFFONTS", + "T1FONTS", + "OPENTYPEFONTS", + "TTFONTS", + "PKFONTS", + "ENCFONTS", + "TEXFORMATS", + "TEXMFCNF", + "MISCFONTS", + "SFDFONTS", + "CMAPFONTS", + "texmf_casefold_search", + "FONTCONFIG_FILE", + "FONTCONFIG_PATH", + ] { + env::remove_var(variable); + } + env::set_var("TEXFONTMAPS", search); + env::set_var("TEXRRA_WINDOWS_BACKEND", backend); + env::set_var("TEXRRA_STATE_DIR", state); + env::set_var("SOURCE_DATE_EPOCH", "1783900800"); + env::set_var("FORCE_SOURCE_DATE", "1"); + } + Ok(()) +} + +fn start_lease() -> io::Result<()> { + std::thread::Builder::new() + .name("texrra-desktop-lease".into()) + .spawn(|| { + let mut stdin = io::stdin().lock(); + let mut buffer = [0; 32]; + loop { + match stdin.read(&mut buffer) { + Ok(0) => break, + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(_) => break, + } + } + std::process::exit(0); + })?; + Ok(()) +} + +fn build_format(ini: &Path, runtime: &Path, format: &Path, roots: &[PathBuf]) -> LaunchResult<()> { + let ini = ini.canonicalize()?; + let world = WorldConfig::from_environment(runtime, roots.to_vec())?; + let mut request = CompileRequest::new(world, ini, format, job_time()?); + request.entry = Entry::Initex; + request.etex = true; + request.limits.steps = 600_000_000; + println!("Texrra desktop preparing format"); + io::stdout().flush()?; + dump_format(request, Cancellation::default())?; + Ok(()) +} diff --git a/src/native_regex.rs b/src/native_regex.rs index 2d062ac..4904cb5 100644 --- a/src/native_regex.rs +++ b/src/native_regex.rs @@ -58,9 +58,20 @@ pub(crate) struct Worker { impl Worker { pub(crate) fn start() -> Result { - // Re-execute the current image, even if an installer has replaced its - // original path since the process opened the project. - let mut child = Command::new("/proc/self/exe") + // Linux can re-execute the loaded image if its path has been replaced. + #[cfg(target_os = "linux")] + let executable = "/proc/self/exe"; + #[cfg(not(target_os = "linux"))] + let executable = + std::env::current_exe().map_err(|e| format!("pdfTeX regex worker executable: {e}"))?; + let mut command = Command::new(executable); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + let mut child = command .arg(WORKER_ARGUMENT) .stdin(Stdio::piped()) .stdout(Stdio::piped()) diff --git a/src/projects.rs b/src/projects.rs index e80d024..a10854a 100644 --- a/src/projects.rs +++ b/src/projects.rs @@ -129,27 +129,38 @@ impl ProjectStore { MAX_PROJECT_FILES )); } + let entries: Vec<_> = entries + .into_iter() + .filter_map(|(entry, data)| entry_path(&entry).map(|path| (path, data))) + .collect(); + if entries.is_empty() { + return Err("the archive does not contain any usable files".to_string()); + } let id = self.unique_id(&slug(&name)); let dir = self.root.join(&id); - fs::create_dir_all(&dir).map_err(|error| format!("could not create project: {error}"))?; - let mut names = Vec::new(); - for (entry, data) in &entries { - let Some(path) = entry_path(entry) else { - continue; - }; - let target = dir.join(&path); + fs::create_dir(&dir).map_err(|error| format!("could not create project: {error}"))?; + let extracted = entries.iter().try_for_each(|(relative, data)| { + let target = dir.join(relative); if let Some(parent) = target.parent() { fs::create_dir_all(parent) .map_err(|error| format!("could not create {}: {error}", parent.display()))?; } - fs::write(&target, data) - .map_err(|error| format!("could not write {}: {error}", target.display()))?; - names.push(entry.clone()); - } - if names.is_empty() { + let written = if cfg!(windows) { + fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&target) + .and_then(|mut file| file.write_all(data)) + } else { + fs::write(&target, data) + }; + written.map_err(|error| format!("could not write {}: {error}", target.display())) + }); + if let Err(error) = extracted { let _ = fs::remove_dir_all(&dir); - return Err("the archive does not contain any usable files".to_string()); + return Err(error); } + let names: Vec<_> = entries.into_iter().map(|(path, _)| path).collect(); let main_file = detect_main(&dir, &names).unwrap_or_else(|| { names .iter() @@ -331,16 +342,10 @@ impl ProjectStore { if relative.is_empty() { return Err("missing file path".to_string()); } - if relative.contains('\\') { + if !valid_relative(relative) { return Err("invalid file path".to_string()); } - let mut path = dir.clone(); - for component in Path::new(relative).components() { - match component { - Component::Normal(name) => path.push(name), - _ => return Err("invalid file path".to_string()), - } - } + let path = dir.join(relative); if !path.starts_with(&dir) { return Err("invalid file path".to_string()); } @@ -372,7 +377,9 @@ impl ProjectStore { fn unique_id(&self, base: &str) -> String { let mut candidate = base.to_string(); let mut index = 2; - while self.root.join(&candidate).exists() { + while self.root.join(&candidate).exists() + || cfg!(windows) && !windows_file_component(&candidate) + { candidate = format!("{base}-{index}"); index += 1; } @@ -501,6 +508,7 @@ fn slug(name: &str) -> String { fn valid_id(id: &str) -> bool { !id.is_empty() + && (!cfg!(windows) || windows_file_component(id)) && id.len() <= 64 && id.chars().all(|character| { character.is_ascii_alphanumeric() || character == '-' || character == '_' @@ -511,9 +519,41 @@ fn valid_relative(path: &str) -> bool { !path.is_empty() && !path.starts_with('/') && !path.contains('\\') - && Path::new(path) - .components() - .all(|component| matches!(component, Component::Normal(_))) + && Path::new(path).components().all(|component| { + matches!(component, Component::Normal(name) if + !cfg!(windows) || name.to_str().is_some_and(windows_file_component)) + }) +} + +fn windows_file_component(name: &str) -> bool { + if name.ends_with([' ', '.']) + || name + .bytes() + .any(|byte| byte < 32 || b"<>:\"|?*".contains(&byte)) + { + return false; + } + let stem = name + .split('.') + .next() + .unwrap_or_default() + .trim_end_matches(' '); + let stem = stem.to_ascii_uppercase(); + if matches!( + stem.as_str(), + "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" + ) { + return false; + } + !stem + .strip_prefix("COM") + .or_else(|| stem.strip_prefix("LPT")) + .is_some_and(|suffix| { + matches!( + suffix, + "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" + ) + }) } fn entry_path(entry: &str) -> Option {