diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index 944ef6b..d254294 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -255,7 +255,7 @@ pub struct FileModificationTime { } impl FileModificationTime { - fn from_system_time(time: SystemTime) -> Result { + pub fn from_system_time(time: SystemTime) -> Result { let nanos = match time.duration_since(SystemTime::UNIX_EPOCH) { Ok(duration) => duration.as_nanos() as i128, Err(error) => -(error.duration().as_nanos() as i128), @@ -268,6 +268,19 @@ impl FileModificationTime { }) } + pub fn to_system_time(self) -> Option { + if !self.valid() { + return None; + } + let seconds = std::time::Duration::from_secs(self.unix_seconds.unsigned_abs()); + let whole = if self.unix_seconds < 0 { + SystemTime::UNIX_EPOCH.checked_sub(seconds)? + } else { + SystemTime::UNIX_EPOCH.checked_add(seconds)? + }; + whole.checked_add(std::time::Duration::from_nanos(self.nanoseconds.into())) + } + fn valid(self) -> bool { self.nanoseconds < 1_000_000_000 } diff --git a/crates/texrra-tex-core/src/resources/project.rs b/crates/texrra-tex-core/src/resources/project.rs index c76f25d..437034a 100644 --- a/crates/texrra-tex-core/src/resources/project.rs +++ b/crates/texrra-tex-core/src/resources/project.rs @@ -158,6 +158,15 @@ impl ProjectSnapshot { pub fn with_external_resources( self: &Arc, resources: &BTreeMap>, + ) -> Result, String> { + self.with_external_resources_and_dates(resources, &BTreeMap::new()) + } + + /// Attach dates captured with newly observed external resource bytes. + pub fn with_external_resources_and_dates( + self: &Arc, + resources: &BTreeMap>, + dates: &BTreeMap, ) -> Result, String> { if resources.keys().all(|path| self.files.contains_key(path)) { return Ok(self.clone()); @@ -175,6 +184,9 @@ impl ProjectSnapshot { } next.files .insert(path.clone(), Self::capture(path.clone(), data.clone())); + if let Some(&date) = dates.get(path) { + next.file_modifications.insert(path.clone(), date); + } next.directories .extend(path.ancestors().skip(1).map(Path::to_path_buf)); } diff --git a/desktop/README.md b/desktop/README.md index 175f21d..3653566 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -2,7 +2,9 @@ Tauri 将现有项目库和原生预览工作台放入 Windows 窗口。安装包携带本轮的 Route-D 引擎、已验证的 LaTeX 格式和 Web 界面。此版面向已有 -FedoraLinux-44、对应 TeX 资源和 WebView2 的当前测试电脑。 +FedoraLinux-44、对应 TeX 资源和 WebView2 的当前测试电脑。桌面版使用 +Windows 当前默认的 WSL 发行版。配置多个发行版时可用 TEXRRA_WSL_DISTRO +指定具备相同 TeX 资源的发行版。项目工作目录在启动时按当前 Fedora 用户生成。 安装后从开始菜单打开 Texrra。也可以解压便携包,运行同目录的 Texrra 桌面程序。在项目库导入包含主 .tex 文件的 ZIP,打开项目后编辑 diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 548b3bb..c78e7b7 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.0" +version = "0.1.1" dependencies = [ "serde_json", "tauri", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index f31fc2a..1125309 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "texrra-desktop" -version = "0.1.0" +version = "0.1.1" 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 cbb376a..652e056 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -12,7 +12,6 @@ use std::{ use tauri::{Manager, RunEvent, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder}; -const DISTRO: &str = "FedoraLinux-44"; const HIDE_CONSOLE: u32 = 0x08000000; const READY_PREFIX: &str = "Native editor "; @@ -41,7 +40,10 @@ impl Backend { fn wsl() -> Command { let mut command = Command::new("wsl.exe"); command.creation_flags(HIDE_CONSOLE); - command.args(["--distribution", DISTRO, "--exec"]); + if let Some(distribution) = std::env::var_os("TEXRRA_WSL_DISTRO").filter(|d| !d.is_empty()) { + command.arg("--distribution").arg(distribution); + } + command.arg("--exec"); command } @@ -50,7 +52,7 @@ fn linux_path(path: &Path) -> Result { .args(["wslpath", "-a", "-u"]) .arg(path) .output() - .map_err(|e| format!("无法打开 {DISTRO}。{e}"))?; + .map_err(|e| format!("无法启动 Windows 的 WSL 环境。{e}"))?; if !result.status.success() { return Err(format!( "无法读取桌面版引擎资源。{}", @@ -113,7 +115,7 @@ fn start_engine(backend: &Backend, launcher: &Path) -> Result { .map_err(|error| match error { mpsc::RecvTimeoutError::Timeout => "启动本地引擎超时。".to_owned(), mpsc::RecvTimeoutError::Disconnected => { - format!("本地引擎启动失败。请确认 {DISTRO} 可以正常打开。") + "本地引擎启动失败。请确认当前默认的 WSL 发行版可以正常打开。".to_owned() } })? } @@ -156,6 +158,7 @@ fn main() { .title("Texrra") .inner_size(1280.0, 900.0) .min_inner_size(780.0, 540.0) + .disable_drag_drop_handler() .on_navigation(move |url| { matches!( url.as_str(), diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 58ccd0c..9470314 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.0", + "version": "0.1.1", "identifier": "org.texrra.desktop", "build": { "frontendDist": "../startup" diff --git a/examples/native_editor/library.js b/examples/native_editor/library.js index 13a56aa..422e747 100644 --- a/examples/native_editor/library.js +++ b/examples/native_editor/library.js @@ -9,19 +9,46 @@ const drop = document.querySelector("#drop-zone"); const create = document.querySelector("#new-project"); const message = document.querySelector("#toast"); +let busy = false; + list.hidden = false; +message.setAttribute("role", "status"); document.querySelector("#header-actions").textContent = "原生 Beta"; document.querySelector("footer").textContent = ""; -async function request(path, options) { - const response = await fetch(path, options); - const result = await response.json(); - if (!response.ok) throw new Error(result.error); - return result; +function setBusy(value) { + busy = value; + upload.disabled = value; + create.disabled = value; + grid.inert = value; } -function open(project) { - location.href = "/p/" + encodeURIComponent(project.id) + "/"; +function showMessage(text, failed = false) { + message.textContent = text; + message.classList.toggle("error", failed); + message.hidden = false; +} + +async function responseError(response) { + const body = await response.json().catch(() => null); + return new Error(body?.error || "请求失败(" + response.status + ")"); +} + +async function request(path, options) { + const response = await fetch(path, options); + if (!response.ok) throw await responseError(response); + return response.json(); +} + +async function openProject(project) { + if (!project.mainFile) throw new Error("项目没有可打开的 TeX 主文件"); + const path = "/p/" + encodeURIComponent(project.id) + "/"; + showMessage("正在打开「" + project.name + "」…"); + // The project may have been saved even if preparing its editor fails. + // Surface that failure on the project list instead of navigating to JSON. + const response = await fetch(path, { cache: "no-store" }); + if (!response.ok) throw await responseError(response); + location.assign(path); } function projectCard(project) { @@ -41,7 +68,16 @@ function projectCard(project) { button.className = "btn primary"; button.textContent = "打开"; button.disabled = !project.mainFile; - button.addEventListener("click", () => open(project)); + button.addEventListener("click", async () => { + if (busy) return; + setBusy(true); + try { + await openProject(project); + } catch (error) { + setBusy(false); + showMessage("打开项目失败:" + error.message, true); + } + }); actions.append(button); body.append(title, details, actions); card.append(body); @@ -49,51 +85,63 @@ function projectCard(project) { } async function refresh() { - try { - const { projects } = await request("/api/projects"); - grid.replaceChildren(...projects.map(projectCard)); - empty.hidden = projects.length > 0; - } catch (error) { - showError(error); - } -} - -function showError(error) { - message.hidden = false; - message.textContent = error.message; + const { projects } = await request("/api/projects"); + grid.replaceChildren(...projects.map(projectCard)); + empty.hidden = projects.length > 0; } async function importFile(file) { - if (!file || upload.disabled) return; + if (!file || busy) return; if (!file.name.toLowerCase().endsWith(".zip")) { - showError(new Error("请选择 ZIP 压缩包")); + showMessage("请选择 ZIP 压缩包", true); return; } - upload.disabled = true; - message.hidden = true; + setBusy(true); + showMessage("正在导入「" + file.name + "」…"); + let project; try { const name = file.name.slice(0, -4); - const project = await request("/api/projects?name=" + encodeURIComponent(name), { + project = await request("/api/projects?name=" + encodeURIComponent(name), { method: "POST", headers: { "Content-Type": "application/zip" }, body: file, }); - open(project); + await openProject(project); } catch (error) { - showError(error); - } finally { - input.value = ""; - upload.disabled = false; + showMessage((project ? "ZIP 已导入,打开项目失败:" : "导入 ZIP 失败:") + error.message, true); + if (project) await refresh().catch(() => {}); + setBusy(false); } } upload.addEventListener("click", () => input.click()); -input.addEventListener("change", () => importFile(input.files[0])); -drop.addEventListener("dragover", (event) => event.preventDefault()); -drop.addEventListener("drop", (event) => { - event.preventDefault(); - importFile(event.dataTransfer.files[0]); +input.addEventListener("change", () => { + const file = input.files[0]; + input.value = ""; + importFile(file); }); +document.addEventListener("dragover", (event) => { + if (!Array.from(event.dataTransfer?.types ?? []).includes("Files")) return; + event.preventDefault(); + event.dataTransfer.dropEffect = busy ? "none" : "copy"; + drop.classList.toggle("dragging", !busy); +}); +document.addEventListener("dragleave", (event) => { + if (!event.relatedTarget) drop.classList.remove("dragging"); +}); +document.addEventListener("drop", (event) => { + const transfer = event.dataTransfer; + if (!transfer || !(transfer.files.length || Array.from(transfer.types).includes("Files"))) return; + event.preventDefault(); + drop.classList.remove("dragging"); + if (busy) return; + if (transfer.files.length !== 1) { + showMessage("请一次拖入一个 ZIP 压缩包", true); + return; + } + importFile(transfer.files[0]); +}); + // An in-page form works in embeddable browsers that suppress JS prompts. const projectDialog = document.createElement("dialog"); projectDialog.style.cssText = "width:min(26rem, calc(100% - 2rem));padding:1.25rem;border:1px solid #d5dce3;border-radius:12px"; @@ -129,6 +177,7 @@ projectDialog.append(projectForm); document.body.append(projectDialog); create.addEventListener("click", () => { + if (busy) return; projectName.value = ""; projectName.setCustomValidity(""); projectError.hidden = true; @@ -136,31 +185,49 @@ create.addEventListener("click", () => { projectName.focus(); }); cancel.addEventListener("click", () => projectDialog.close()); +projectDialog.addEventListener("cancel", (event) => { + if (busy) event.preventDefault(); +}); projectName.addEventListener("input", () => projectName.setCustomValidity("")); projectForm.addEventListener("submit", async (event) => { event.preventDefault(); - if (submit.disabled) return; + if (busy) return; const name = projectName.value.trim(); if (!name) { projectName.setCustomValidity("请输入项目名称"); projectName.reportValidity(); return; } + setBusy(true); submit.disabled = true; + cancel.disabled = true; + submit.textContent = "正在创建…"; projectError.hidden = true; + let project; try { - const project = await request("/api/projects/new", { + project = await request("/api/projects/new", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }), }); - open(project); + projectDialog.close(); + await openProject(project); } catch (error) { - projectError.textContent = error.message; - projectError.hidden = false; + if (project) { + showMessage("项目已创建,打开失败:" + error.message, true); + await refresh().catch(() => {}); + } else { + projectError.textContent = error.message; + projectError.hidden = false; + } + setBusy(false); } finally { submit.disabled = false; + cancel.disabled = false; + submit.textContent = "创建项目"; } }); -refresh(); +refresh().catch((error) => { + if (!busy) showMessage("读取项目列表失败:" + error.message, true); +}); diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 83320eb..61053bc 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -4,13 +4,13 @@ use serde_json::{Value, json}; use std::{ collections::{BTreeMap, BTreeSet}, fs, - io::Read, + io::{Read, Write}, path::{Component, Path, PathBuf}, sync::{ Arc, Condvar, Mutex, mpsc, atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, }, - time::Instant, + time::{Instant, SystemTime}, }; use texrra_engine::native::{ CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, @@ -20,7 +20,7 @@ use texrra_engine::native::{ }; use texrra_tex_core::{ execution::InputProfile, - resources::{InputPolicy, ResourceKind, SearchPath, WorldConfig}, + resources::{FileModificationTime, InputPolicy, ResourceKind, SearchPath, WorldConfig}, }; use thread_usage::ThreadUsage; use tiny_http::{Header, Method, Request, Response, Server}; @@ -761,6 +761,21 @@ struct EditorProject { options: CompileRequest, } +fn copy_with_date( + path: &Path, + bytes: &[u8], + modified: Option, + dates: &mut BTreeMap, +) -> Result<(), Box> { + let mut copy = fs::File::create(path)?; + copy.write_all(bytes)?; + if let Some(modified) = modified { + copy.set_times(fs::FileTimes::new().set_modified(modified))?; + dates.insert(path.to_owned(), FileModificationTime::from_system_time(modified)?); + } + Ok(()) +} + fn prepare( source_root: &Path, source: &Path, @@ -788,9 +803,10 @@ fn prepare( .or_insert_with(|| vec![SearchPath::Defaults]) .insert(0, SearchPath::directory(entry_dir, false)); } - let original = fs::read(source)?; + let mut dates = BTreeMap::new(); + let (original, modified) = resource_capture::read_with_date(source)?; std::str::from_utf8(&original)?; - fs::write(&entry, &original)?; + copy_with_date(&entry, &original, modified, &mut dates)?; let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]); let mut files = BTreeMap::>::from([(entry.clone(), Arc::from(original))]); let mut declared = BTreeSet::from([entry.clone()]); @@ -812,8 +828,8 @@ fn prepare( return Err(format!("Project file is listed twice: {}", relative.display()).into()); } let physical = source_root.join(relative); - let data = match physical.canonicalize() { - Ok(path) if path.starts_with(source_root) => Some(Arc::<[u8]>::from(fs::read(path)?)), + let captured = match physical.canonicalize() { + Ok(path) if path.starts_with(source_root) => Some(resource_capture::read_with_date(&path)?), Ok(_) => { return Err(format!( "Project file is outside the entry directory: {}", @@ -842,15 +858,15 @@ fn prepare( .map(Path::to_owned), ); if let Some(name) = relative.to_str() - && data - .as_deref() - .is_none_or(|bytes| std::str::from_utf8(bytes).is_ok()) + && captured + .as_ref() + .is_none_or(|(bytes, _)| std::str::from_utf8(bytes).is_ok()) { editable.insert(name.into(), logical.clone()); } - if let Some(data) = data { - fs::write(&logical, &data)?; - files.insert(logical, data); + if let Some((data, modified)) = captured { + copy_with_date(&logical, &data, modified, &mut dates)?; + files.insert(logical, Arc::from(data)); } } let mut output = entry.with_extension("pdf"); @@ -897,6 +913,24 @@ fn prepare( files.insert(path.clone(), Arc::from(fs::read(path)?)); } } + // Keep timestamps already observed by the seed and provide dates for + // external files which may first be queried after an edit. + if let Some(trace) = trace { + for item in &trace.file_modifications { + if let Ok(Some(date)) = &item.result + && files.contains_key(&item.path) + { + dates.entry(item.path.clone()).or_insert(date.time); + } + } + } + for path in files.keys().filter(|path| !path.starts_with(run)) { + if !dates.contains_key(path) + && let Ok(modified) = fs::metadata(path).and_then(|m| m.modified()) + { + dates.insert(path.clone(), FileModificationTime::from_system_time(modified)?); + } + } let mut coverage = BTreeSet::from_iter(world.texmf_roots.iter().cloned()); coverage.insert(run.to_owned()); // A successful lookup can follow a miss in an explicit search directory. @@ -919,7 +953,7 @@ fn prepare( .flat_map(|artifacts| &artifacts.writes) .map(|write| write.path.clone()) .collect(); - let project = ProjectSnapshot::new(ProjectDefinition { + let project = ProjectSnapshot::with_file_modifications(ProjectDefinition { configuration: world, revision: 1, roots: coverage, @@ -928,7 +962,7 @@ fn prepare( aliases: BTreeMap::new(), generated_roots: BTreeSet::from([run.to_owned()]), generated, - })?; + }, dates)?; Ok(EditorProject { project, entry, diff --git a/examples/native_editor/resource_capture.rs b/examples/native_editor/resource_capture.rs index 8561a38..05dd578 100644 --- a/examples/native_editor/resource_capture.rs +++ b/examples/native_editor/resource_capture.rs @@ -1,15 +1,31 @@ use std::{ collections::{BTreeMap, BTreeSet}, fs, - path::PathBuf, + io::{self, Read}, + path::{Path, PathBuf}, sync::Arc, + time::SystemTime, }; use texrra_engine::native::CompileFailure; -use texrra_tex_core::resources::{FileWorld, ProjectSnapshot, ResourceKind, SearchPath}; +use texrra_tex_core::resources::{FileModificationTime, FileWorld, ProjectSnapshot, ResourceKind, SearchPath}; + +// Use the opened file for both observations so a renamed path cannot supply +// a date from a different file. +pub(super) fn read_with_date(path: &Path) -> io::Result<(Vec, Option)> { + let mut file = fs::File::open(path)?; + let modified = file.metadata()?.modified().ok(); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes)?; + if file.metadata()?.modified().ok() != modified { + return Err(io::Error::other(format!("Input changed during capture: {}", path.display()))); + } + Ok((bytes, modified)) +} #[derive(Default)] pub(super) struct ResourceCapture { resources: BTreeMap>, + dates: BTreeMap, host: Option, } @@ -18,7 +34,7 @@ impl ResourceCapture { &self, project: &Arc, ) -> Result, String> { - project.with_external_resources(&self.resources) + project.with_external_resources_and_dates(&self.resources, &self.dates) } pub(super) fn expand( @@ -49,6 +65,7 @@ impl ResourceCapture { }; let mut queried = BTreeSet::new(); let mut added = BTreeMap::new(); + let mut dates = BTreeMap::new(); for lookup in trace .lookups .iter() @@ -67,16 +84,20 @@ impl ResourceCapture { && search_roots.iter().any(|root| path.starts_with(root)) && project.file(&path).is_none() && fs::metadata(&path).is_ok_and(|metadata| metadata.is_file()) - && let Ok(bytes) = fs::read(&path) + && let Ok((bytes, modified)) = read_with_date(&path) { + if let Some(date) = modified.and_then(|time| FileModificationTime::from_system_time(time).ok()) { + dates.insert(path.clone(), date); + } added.insert(path, Arc::from(bytes)); } } if added.is_empty() { return None; } - let expanded = project.with_external_resources(&added).ok()?; + let expanded = project.with_external_resources_and_dates(&added, &dates).ok()?; self.resources.extend(added); + self.dates.extend(dates); Some(expanded) } } diff --git a/examples/native_editor/saved_project.rs b/examples/native_editor/saved_project.rs index bf5f221..d3827a6 100644 --- a/examples/native_editor/saved_project.rs +++ b/examples/native_editor/saved_project.rs @@ -1,6 +1,6 @@ use std::{ collections::{BTreeMap, BTreeSet}, - fs, io, + fs, io::{self, Write}, path::{Path, PathBuf}, }; use texrra_engine::native::ProjectSnapshot; @@ -44,7 +44,14 @@ pub(super) fn save( .copied() .or_else(|| project.file(path).map(|file| file.data.as_ref())) { - fs::write(&saved, data)?; + let mut file = fs::File::create(&saved)?; + file.write_all(data)?; + if let Some(date) = project.modification_time(path) { + let modified = date.to_system_time().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "Project file date is out of range") + })?; + file.set_times(fs::FileTimes::new().set_modified(modified))?; + } } if path != entry { files.push(name);