Capture editor file dates and make desktop ZIP import observable

This commit is contained in:
gloamxun committed 2026-12-02 10:07:43 +08:00
1 parent 0ea71d57a9
commit fbc339f5c4
11 files changed
+231 -72

No files matched your search

+14 -1
View File
@@ -255,7 +255,7 @@ pub struct FileModificationTime {
}
impl FileModificationTime {
fn from_system_time(time: SystemTime) -> Result<Self, String> {
pub fn from_system_time(time: SystemTime) -> Result<Self, String> {
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<SystemTime> {
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
}
@@ -158,6 +158,15 @@ impl ProjectSnapshot {
pub fn with_external_resources(
self: &Arc<Self>,
resources: &BTreeMap<PathBuf, Arc<[u8]>>,
) -> Result<Arc<Self>, 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<Self>,
resources: &BTreeMap<PathBuf, Arc<[u8]>>,
dates: &BTreeMap<PathBuf, FileModificationTime>,
) -> Result<Arc<Self>, 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));
}
+3 -1
View File
@@ -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,打开项目后编辑
+1 -1
View File
@@ -3237,7 +3237,7 @@ dependencies = [
[[package]]
name = "texrra-desktop"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"serde_json",
"tauri",
+1 -1
View File
@@ -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"
+7 -4
View File
@@ -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<String, String> {
.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<Url, String> {
.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(),
+1 -1
View File
@@ -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"
+108 -41
View File
@@ -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);
});
+49 -15
View File
@@ -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<SystemTime>,
dates: &mut BTreeMap<PathBuf, FileModificationTime>,
) -> Result<(), Box<dyn std::error::Error>> {
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::<PathBuf, Arc<[u8]>>::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,
+26 -5
View File
@@ -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<u8>, Option<SystemTime>)> {
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<PathBuf, Arc<[u8]>>,
dates: BTreeMap<PathBuf, FileModificationTime>,
host: Option<FileWorld>,
}
@@ -18,7 +34,7 @@ impl ResourceCapture {
&self,
project: &Arc<ProjectSnapshot>,
) -> Result<Arc<ProjectSnapshot>, 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)
}
}
+9 -2
View File
@@ -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);