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
@@ -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);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user