Capture editor file dates and make desktop ZIP import observable
This commit is contained in:
1 parent
0ea71d57a9
commit
fbc339f5c4
11 files changed
+231
-72
No files matched your search
@@ -255,7 +255,7 @@ pub struct FileModificationTime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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) {
|
let nanos = match time.duration_since(SystemTime::UNIX_EPOCH) {
|
||||||
Ok(duration) => duration.as_nanos() as i128,
|
Ok(duration) => duration.as_nanos() as i128,
|
||||||
Err(error) => -(error.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 {
|
fn valid(self) -> bool {
|
||||||
self.nanoseconds < 1_000_000_000
|
self.nanoseconds < 1_000_000_000
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -158,6 +158,15 @@ impl ProjectSnapshot {
|
|||||||
pub fn with_external_resources(
|
pub fn with_external_resources(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
resources: &BTreeMap<PathBuf, Arc<[u8]>>,
|
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> {
|
) -> Result<Arc<Self>, String> {
|
||||||
if resources.keys().all(|path| self.files.contains_key(path)) {
|
if resources.keys().all(|path| self.files.contains_key(path)) {
|
||||||
return Ok(self.clone());
|
return Ok(self.clone());
|
||||||
@@ -175,6 +184,9 @@ impl ProjectSnapshot {
|
|||||||
}
|
}
|
||||||
next.files
|
next.files
|
||||||
.insert(path.clone(), Self::capture(path.clone(), data.clone()));
|
.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
|
next.directories
|
||||||
.extend(path.ancestors().skip(1).map(Path::to_path_buf));
|
.extend(path.ancestors().skip(1).map(Path::to_path_buf));
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
Tauri 将现有项目库和原生预览工作台放入 Windows 窗口。安装包携带本轮的
|
Tauri 将现有项目库和原生预览工作台放入 Windows 窗口。安装包携带本轮的
|
||||||
Route-D 引擎、已验证的 LaTeX 格式和 Web 界面。此版面向已有
|
Route-D 引擎、已验证的 LaTeX 格式和 Web 界面。此版面向已有
|
||||||
FedoraLinux-44、对应 TeX 资源和 WebView2 的当前测试电脑。
|
FedoraLinux-44、对应 TeX 资源和 WebView2 的当前测试电脑。桌面版使用
|
||||||
|
Windows 当前默认的 WSL 发行版。配置多个发行版时可用 TEXRRA_WSL_DISTRO
|
||||||
|
指定具备相同 TeX 资源的发行版。项目工作目录在启动时按当前 Fedora 用户生成。
|
||||||
|
|
||||||
安装后从开始菜单打开 Texrra。也可以解压便携包,运行同目录的
|
安装后从开始菜单打开 Texrra。也可以解压便携包,运行同目录的
|
||||||
Texrra 桌面程序。在项目库导入包含主 .tex 文件的 ZIP,打开项目后编辑
|
Texrra 桌面程序。在项目库导入包含主 .tex 文件的 ZIP,打开项目后编辑
|
||||||
|
|||||||
Generated
+1
-1
@@ -3237,7 +3237,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "texrra-desktop"
|
name = "texrra-desktop"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "texrra-desktop"
|
name = "texrra-desktop"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.92"
|
rust-version = "1.92"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ use std::{
|
|||||||
|
|
||||||
use tauri::{Manager, RunEvent, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
|
use tauri::{Manager, RunEvent, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder};
|
||||||
|
|
||||||
const DISTRO: &str = "FedoraLinux-44";
|
|
||||||
const HIDE_CONSOLE: u32 = 0x08000000;
|
const HIDE_CONSOLE: u32 = 0x08000000;
|
||||||
const READY_PREFIX: &str = "Native editor ";
|
const READY_PREFIX: &str = "Native editor ";
|
||||||
|
|
||||||
@@ -41,7 +40,10 @@ impl Backend {
|
|||||||
fn wsl() -> Command {
|
fn wsl() -> Command {
|
||||||
let mut command = Command::new("wsl.exe");
|
let mut command = Command::new("wsl.exe");
|
||||||
command.creation_flags(HIDE_CONSOLE);
|
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
|
command
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,7 +52,7 @@ fn linux_path(path: &Path) -> Result<String, String> {
|
|||||||
.args(["wslpath", "-a", "-u"])
|
.args(["wslpath", "-a", "-u"])
|
||||||
.arg(path)
|
.arg(path)
|
||||||
.output()
|
.output()
|
||||||
.map_err(|e| format!("无法打开 {DISTRO}。{e}"))?;
|
.map_err(|e| format!("无法启动 Windows 的 WSL 环境。{e}"))?;
|
||||||
if !result.status.success() {
|
if !result.status.success() {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"无法读取桌面版引擎资源。{}",
|
"无法读取桌面版引擎资源。{}",
|
||||||
@@ -113,7 +115,7 @@ fn start_engine(backend: &Backend, launcher: &Path) -> Result<Url, String> {
|
|||||||
.map_err(|error| match error {
|
.map_err(|error| match error {
|
||||||
mpsc::RecvTimeoutError::Timeout => "启动本地引擎超时。".to_owned(),
|
mpsc::RecvTimeoutError::Timeout => "启动本地引擎超时。".to_owned(),
|
||||||
mpsc::RecvTimeoutError::Disconnected => {
|
mpsc::RecvTimeoutError::Disconnected => {
|
||||||
format!("本地引擎启动失败。请确认 {DISTRO} 可以正常打开。")
|
"本地引擎启动失败。请确认当前默认的 WSL 发行版可以正常打开。".to_owned()
|
||||||
}
|
}
|
||||||
})?
|
})?
|
||||||
}
|
}
|
||||||
@@ -156,6 +158,7 @@ fn main() {
|
|||||||
.title("Texrra")
|
.title("Texrra")
|
||||||
.inner_size(1280.0, 900.0)
|
.inner_size(1280.0, 900.0)
|
||||||
.min_inner_size(780.0, 540.0)
|
.min_inner_size(780.0, 540.0)
|
||||||
|
.disable_drag_drop_handler()
|
||||||
.on_navigation(move |url| {
|
.on_navigation(move |url| {
|
||||||
matches!(
|
matches!(
|
||||||
url.as_str(),
|
url.as_str(),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Texrra",
|
"productName": "Texrra",
|
||||||
"version": "0.1.0",
|
"version": "0.1.1",
|
||||||
"identifier": "org.texrra.desktop",
|
"identifier": "org.texrra.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../startup"
|
"frontendDist": "../startup"
|
||||||
|
|||||||
@@ -9,19 +9,46 @@ const drop = document.querySelector("#drop-zone");
|
|||||||
const create = document.querySelector("#new-project");
|
const create = document.querySelector("#new-project");
|
||||||
const message = document.querySelector("#toast");
|
const message = document.querySelector("#toast");
|
||||||
|
|
||||||
|
let busy = false;
|
||||||
|
|
||||||
list.hidden = false;
|
list.hidden = false;
|
||||||
|
message.setAttribute("role", "status");
|
||||||
document.querySelector("#header-actions").textContent = "原生 Beta";
|
document.querySelector("#header-actions").textContent = "原生 Beta";
|
||||||
document.querySelector("footer").textContent = "";
|
document.querySelector("footer").textContent = "";
|
||||||
|
|
||||||
async function request(path, options) {
|
function setBusy(value) {
|
||||||
const response = await fetch(path, options);
|
busy = value;
|
||||||
const result = await response.json();
|
upload.disabled = value;
|
||||||
if (!response.ok) throw new Error(result.error);
|
create.disabled = value;
|
||||||
return result;
|
grid.inert = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
function open(project) {
|
function showMessage(text, failed = false) {
|
||||||
location.href = "/p/" + encodeURIComponent(project.id) + "/";
|
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) {
|
function projectCard(project) {
|
||||||
@@ -41,7 +68,16 @@ function projectCard(project) {
|
|||||||
button.className = "btn primary";
|
button.className = "btn primary";
|
||||||
button.textContent = "打开";
|
button.textContent = "打开";
|
||||||
button.disabled = !project.mainFile;
|
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);
|
actions.append(button);
|
||||||
body.append(title, details, actions);
|
body.append(title, details, actions);
|
||||||
card.append(body);
|
card.append(body);
|
||||||
@@ -49,51 +85,63 @@ function projectCard(project) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function refresh() {
|
async function refresh() {
|
||||||
try {
|
const { projects } = await request("/api/projects");
|
||||||
const { projects } = await request("/api/projects");
|
grid.replaceChildren(...projects.map(projectCard));
|
||||||
grid.replaceChildren(...projects.map(projectCard));
|
empty.hidden = projects.length > 0;
|
||||||
empty.hidden = projects.length > 0;
|
|
||||||
} catch (error) {
|
|
||||||
showError(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function showError(error) {
|
|
||||||
message.hidden = false;
|
|
||||||
message.textContent = error.message;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function importFile(file) {
|
async function importFile(file) {
|
||||||
if (!file || upload.disabled) return;
|
if (!file || busy) return;
|
||||||
if (!file.name.toLowerCase().endsWith(".zip")) {
|
if (!file.name.toLowerCase().endsWith(".zip")) {
|
||||||
showError(new Error("请选择 ZIP 压缩包"));
|
showMessage("请选择 ZIP 压缩包", true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
upload.disabled = true;
|
setBusy(true);
|
||||||
message.hidden = true;
|
showMessage("正在导入「" + file.name + "」…");
|
||||||
|
let project;
|
||||||
try {
|
try {
|
||||||
const name = file.name.slice(0, -4);
|
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",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/zip" },
|
headers: { "Content-Type": "application/zip" },
|
||||||
body: file,
|
body: file,
|
||||||
});
|
});
|
||||||
open(project);
|
await openProject(project);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showError(error);
|
showMessage((project ? "ZIP 已导入,打开项目失败:" : "导入 ZIP 失败:") + error.message, true);
|
||||||
} finally {
|
if (project) await refresh().catch(() => {});
|
||||||
input.value = "";
|
setBusy(false);
|
||||||
upload.disabled = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
upload.addEventListener("click", () => input.click());
|
upload.addEventListener("click", () => input.click());
|
||||||
input.addEventListener("change", () => importFile(input.files[0]));
|
input.addEventListener("change", () => {
|
||||||
drop.addEventListener("dragover", (event) => event.preventDefault());
|
const file = input.files[0];
|
||||||
drop.addEventListener("drop", (event) => {
|
input.value = "";
|
||||||
event.preventDefault();
|
importFile(file);
|
||||||
importFile(event.dataTransfer.files[0]);
|
|
||||||
});
|
});
|
||||||
|
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.
|
// An in-page form works in embeddable browsers that suppress JS prompts.
|
||||||
const projectDialog = document.createElement("dialog");
|
const projectDialog = document.createElement("dialog");
|
||||||
projectDialog.style.cssText = "width:min(26rem, calc(100% - 2rem));padding:1.25rem;border:1px solid #d5dce3;border-radius:12px";
|
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);
|
document.body.append(projectDialog);
|
||||||
|
|
||||||
create.addEventListener("click", () => {
|
create.addEventListener("click", () => {
|
||||||
|
if (busy) return;
|
||||||
projectName.value = "";
|
projectName.value = "";
|
||||||
projectName.setCustomValidity("");
|
projectName.setCustomValidity("");
|
||||||
projectError.hidden = true;
|
projectError.hidden = true;
|
||||||
@@ -136,31 +185,49 @@ create.addEventListener("click", () => {
|
|||||||
projectName.focus();
|
projectName.focus();
|
||||||
});
|
});
|
||||||
cancel.addEventListener("click", () => projectDialog.close());
|
cancel.addEventListener("click", () => projectDialog.close());
|
||||||
|
projectDialog.addEventListener("cancel", (event) => {
|
||||||
|
if (busy) event.preventDefault();
|
||||||
|
});
|
||||||
projectName.addEventListener("input", () => projectName.setCustomValidity(""));
|
projectName.addEventListener("input", () => projectName.setCustomValidity(""));
|
||||||
projectForm.addEventListener("submit", async (event) => {
|
projectForm.addEventListener("submit", async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (submit.disabled) return;
|
if (busy) return;
|
||||||
const name = projectName.value.trim();
|
const name = projectName.value.trim();
|
||||||
if (!name) {
|
if (!name) {
|
||||||
projectName.setCustomValidity("请输入项目名称");
|
projectName.setCustomValidity("请输入项目名称");
|
||||||
projectName.reportValidity();
|
projectName.reportValidity();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
setBusy(true);
|
||||||
submit.disabled = true;
|
submit.disabled = true;
|
||||||
|
cancel.disabled = true;
|
||||||
|
submit.textContent = "正在创建…";
|
||||||
projectError.hidden = true;
|
projectError.hidden = true;
|
||||||
|
let project;
|
||||||
try {
|
try {
|
||||||
const project = await request("/api/projects/new", {
|
project = await request("/api/projects/new", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ name }),
|
body: JSON.stringify({ name }),
|
||||||
});
|
});
|
||||||
open(project);
|
projectDialog.close();
|
||||||
|
await openProject(project);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
projectError.textContent = error.message;
|
if (project) {
|
||||||
projectError.hidden = false;
|
showMessage("项目已创建,打开失败:" + error.message, true);
|
||||||
|
await refresh().catch(() => {});
|
||||||
|
} else {
|
||||||
|
projectError.textContent = error.message;
|
||||||
|
projectError.hidden = false;
|
||||||
|
}
|
||||||
|
setBusy(false);
|
||||||
} finally {
|
} finally {
|
||||||
submit.disabled = false;
|
submit.disabled = false;
|
||||||
|
cancel.disabled = false;
|
||||||
|
submit.textContent = "创建项目";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
refresh();
|
refresh().catch((error) => {
|
||||||
|
if (!busy) showMessage("读取项目列表失败:" + error.message, true);
|
||||||
|
});
|
||||||
@@ -4,13 +4,13 @@ use serde_json::{Value, json};
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet},
|
collections::{BTreeMap, BTreeSet},
|
||||||
fs,
|
fs,
|
||||||
io::Read,
|
io::{Read, Write},
|
||||||
path::{Component, Path, PathBuf},
|
path::{Component, Path, PathBuf},
|
||||||
sync::{
|
sync::{
|
||||||
Arc, Condvar, Mutex, mpsc,
|
Arc, Condvar, Mutex, mpsc,
|
||||||
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
|
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
|
||||||
},
|
},
|
||||||
time::Instant,
|
time::{Instant, SystemTime},
|
||||||
};
|
};
|
||||||
use texrra_engine::native::{
|
use texrra_engine::native::{
|
||||||
CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage,
|
CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage,
|
||||||
@@ -20,7 +20,7 @@ use texrra_engine::native::{
|
|||||||
};
|
};
|
||||||
use texrra_tex_core::{
|
use texrra_tex_core::{
|
||||||
execution::InputProfile,
|
execution::InputProfile,
|
||||||
resources::{InputPolicy, ResourceKind, SearchPath, WorldConfig},
|
resources::{FileModificationTime, InputPolicy, ResourceKind, SearchPath, WorldConfig},
|
||||||
};
|
};
|
||||||
use thread_usage::ThreadUsage;
|
use thread_usage::ThreadUsage;
|
||||||
use tiny_http::{Header, Method, Request, Response, Server};
|
use tiny_http::{Header, Method, Request, Response, Server};
|
||||||
@@ -761,6 +761,21 @@ struct EditorProject {
|
|||||||
options: CompileRequest,
|
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(
|
fn prepare(
|
||||||
source_root: &Path,
|
source_root: &Path,
|
||||||
source: &Path,
|
source: &Path,
|
||||||
@@ -788,9 +803,10 @@ fn prepare(
|
|||||||
.or_insert_with(|| vec![SearchPath::Defaults])
|
.or_insert_with(|| vec![SearchPath::Defaults])
|
||||||
.insert(0, SearchPath::directory(entry_dir, false));
|
.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)?;
|
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 editable = BTreeMap::from([(name.to_owned(), entry.clone())]);
|
||||||
let mut files = BTreeMap::<PathBuf, Arc<[u8]>>::from([(entry.clone(), Arc::from(original))]);
|
let mut files = BTreeMap::<PathBuf, Arc<[u8]>>::from([(entry.clone(), Arc::from(original))]);
|
||||||
let mut declared = BTreeSet::from([entry.clone()]);
|
let mut declared = BTreeSet::from([entry.clone()]);
|
||||||
@@ -812,8 +828,8 @@ fn prepare(
|
|||||||
return Err(format!("Project file is listed twice: {}", relative.display()).into());
|
return Err(format!("Project file is listed twice: {}", relative.display()).into());
|
||||||
}
|
}
|
||||||
let physical = source_root.join(relative);
|
let physical = source_root.join(relative);
|
||||||
let data = match physical.canonicalize() {
|
let captured = match physical.canonicalize() {
|
||||||
Ok(path) if path.starts_with(source_root) => Some(Arc::<[u8]>::from(fs::read(path)?)),
|
Ok(path) if path.starts_with(source_root) => Some(resource_capture::read_with_date(&path)?),
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"Project file is outside the entry directory: {}",
|
"Project file is outside the entry directory: {}",
|
||||||
@@ -842,15 +858,15 @@ fn prepare(
|
|||||||
.map(Path::to_owned),
|
.map(Path::to_owned),
|
||||||
);
|
);
|
||||||
if let Some(name) = relative.to_str()
|
if let Some(name) = relative.to_str()
|
||||||
&& data
|
&& captured
|
||||||
.as_deref()
|
.as_ref()
|
||||||
.is_none_or(|bytes| std::str::from_utf8(bytes).is_ok())
|
.is_none_or(|(bytes, _)| std::str::from_utf8(bytes).is_ok())
|
||||||
{
|
{
|
||||||
editable.insert(name.into(), logical.clone());
|
editable.insert(name.into(), logical.clone());
|
||||||
}
|
}
|
||||||
if let Some(data) = data {
|
if let Some((data, modified)) = captured {
|
||||||
fs::write(&logical, &data)?;
|
copy_with_date(&logical, &data, modified, &mut dates)?;
|
||||||
files.insert(logical, data);
|
files.insert(logical, Arc::from(data));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut output = entry.with_extension("pdf");
|
let mut output = entry.with_extension("pdf");
|
||||||
@@ -897,6 +913,24 @@ fn prepare(
|
|||||||
files.insert(path.clone(), Arc::from(fs::read(path)?));
|
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());
|
let mut coverage = BTreeSet::from_iter(world.texmf_roots.iter().cloned());
|
||||||
coverage.insert(run.to_owned());
|
coverage.insert(run.to_owned());
|
||||||
// A successful lookup can follow a miss in an explicit search directory.
|
// A successful lookup can follow a miss in an explicit search directory.
|
||||||
@@ -919,7 +953,7 @@ fn prepare(
|
|||||||
.flat_map(|artifacts| &artifacts.writes)
|
.flat_map(|artifacts| &artifacts.writes)
|
||||||
.map(|write| write.path.clone())
|
.map(|write| write.path.clone())
|
||||||
.collect();
|
.collect();
|
||||||
let project = ProjectSnapshot::new(ProjectDefinition {
|
let project = ProjectSnapshot::with_file_modifications(ProjectDefinition {
|
||||||
configuration: world,
|
configuration: world,
|
||||||
revision: 1,
|
revision: 1,
|
||||||
roots: coverage,
|
roots: coverage,
|
||||||
@@ -928,7 +962,7 @@ fn prepare(
|
|||||||
aliases: BTreeMap::new(),
|
aliases: BTreeMap::new(),
|
||||||
generated_roots: BTreeSet::from([run.to_owned()]),
|
generated_roots: BTreeSet::from([run.to_owned()]),
|
||||||
generated,
|
generated,
|
||||||
})?;
|
}, dates)?;
|
||||||
Ok(EditorProject {
|
Ok(EditorProject {
|
||||||
project,
|
project,
|
||||||
entry,
|
entry,
|
||||||
|
|||||||
@@ -1,15 +1,31 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet},
|
collections::{BTreeMap, BTreeSet},
|
||||||
fs,
|
fs,
|
||||||
path::PathBuf,
|
io::{self, Read},
|
||||||
|
path::{Path, PathBuf},
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
|
time::SystemTime,
|
||||||
};
|
};
|
||||||
use texrra_engine::native::CompileFailure;
|
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)]
|
#[derive(Default)]
|
||||||
pub(super) struct ResourceCapture {
|
pub(super) struct ResourceCapture {
|
||||||
resources: BTreeMap<PathBuf, Arc<[u8]>>,
|
resources: BTreeMap<PathBuf, Arc<[u8]>>,
|
||||||
|
dates: BTreeMap<PathBuf, FileModificationTime>,
|
||||||
host: Option<FileWorld>,
|
host: Option<FileWorld>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,7 +34,7 @@ impl ResourceCapture {
|
|||||||
&self,
|
&self,
|
||||||
project: &Arc<ProjectSnapshot>,
|
project: &Arc<ProjectSnapshot>,
|
||||||
) -> Result<Arc<ProjectSnapshot>, String> {
|
) -> Result<Arc<ProjectSnapshot>, String> {
|
||||||
project.with_external_resources(&self.resources)
|
project.with_external_resources_and_dates(&self.resources, &self.dates)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn expand(
|
pub(super) fn expand(
|
||||||
@@ -49,6 +65,7 @@ impl ResourceCapture {
|
|||||||
};
|
};
|
||||||
let mut queried = BTreeSet::new();
|
let mut queried = BTreeSet::new();
|
||||||
let mut added = BTreeMap::new();
|
let mut added = BTreeMap::new();
|
||||||
|
let mut dates = BTreeMap::new();
|
||||||
for lookup in trace
|
for lookup in trace
|
||||||
.lookups
|
.lookups
|
||||||
.iter()
|
.iter()
|
||||||
@@ -67,16 +84,20 @@ impl ResourceCapture {
|
|||||||
&& search_roots.iter().any(|root| path.starts_with(root))
|
&& search_roots.iter().any(|root| path.starts_with(root))
|
||||||
&& project.file(&path).is_none()
|
&& project.file(&path).is_none()
|
||||||
&& fs::metadata(&path).is_ok_and(|metadata| metadata.is_file())
|
&& 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));
|
added.insert(path, Arc::from(bytes));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if added.is_empty() {
|
if added.is_empty() {
|
||||||
return None;
|
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.resources.extend(added);
|
||||||
|
self.dates.extend(dates);
|
||||||
Some(expanded)
|
Some(expanded)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet},
|
collections::{BTreeMap, BTreeSet},
|
||||||
fs, io,
|
fs, io::{self, Write},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
};
|
};
|
||||||
use texrra_engine::native::ProjectSnapshot;
|
use texrra_engine::native::ProjectSnapshot;
|
||||||
@@ -44,7 +44,14 @@ pub(super) fn save(
|
|||||||
.copied()
|
.copied()
|
||||||
.or_else(|| project.file(path).map(|file| file.data.as_ref()))
|
.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 {
|
if path != entry {
|
||||||
files.push(name);
|
files.push(name);
|
||||||
|
|||||||
Reference in new issue
Block a user