Keep desktop previews visible and open project sources before compiling
This commit is contained in:
1 parent
a2c4a2b3a9
commit
68e5260d40
7 files changed
+355
-128
No files matched your search
Generated
+1
-1
@@ -3237,7 +3237,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "texrra-desktop"
|
name = "texrra-desktop"
|
||||||
version = "0.1.4"
|
version = "0.1.5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "texrra-desktop"
|
name = "texrra-desktop"
|
||||||
version = "0.1.4"
|
version = "0.1.5"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.92"
|
rust-version = "1.92"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
|
|||||||
@@ -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.4",
|
"version": "0.1.5",
|
||||||
"identifier": "org.texrra.desktop",
|
"identifier": "org.texrra.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../startup"
|
"frontendDist": "../startup"
|
||||||
|
|||||||
@@ -23,8 +23,10 @@ const PREVIEW_SOCKET_RETRY_MS = 1000;
|
|||||||
let files;
|
let files;
|
||||||
let projectFiles = [];
|
let projectFiles = [];
|
||||||
let activeFile;
|
let activeFile;
|
||||||
|
let preparingProject = false;
|
||||||
let sequence = 0;
|
let sequence = 0;
|
||||||
let publishedRevision = null;
|
let publishedRevision = null;
|
||||||
|
let visibleRevision = null;
|
||||||
let draft = null;
|
let draft = null;
|
||||||
let composing = false;
|
let composing = false;
|
||||||
let compileTimer;
|
let compileTimer;
|
||||||
@@ -137,7 +139,9 @@ function pageFrame(page) {
|
|||||||
|
|
||||||
function revokeDetached(frames) {
|
function revokeDetached(frames) {
|
||||||
for (const frame of frames) {
|
for (const frame of frames) {
|
||||||
if (!frame.isConnected) URL.revokeObjectURL(frame.querySelector("img").src);
|
if (!frame.isConnected && !draft?.previous.includes(frame)) {
|
||||||
|
URL.revokeObjectURL(frame.querySelector("img").src);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,7 +157,8 @@ function applyPages(update, replacements) {
|
|||||||
}
|
}
|
||||||
while (pages.children.length > update.page_count) pages.lastElementChild.remove();
|
while (pages.children.length > update.page_count) pages.lastElementChild.remove();
|
||||||
}
|
}
|
||||||
document.body.dataset.visibleRevision = update.revision;
|
visibleRevision = update.revision;
|
||||||
|
document.body.dataset.visibleRevision = visibleRevision;
|
||||||
return previous;
|
return previous;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,11 +166,12 @@ function restorePublishedPages() {
|
|||||||
if (!draft) return;
|
if (!draft) return;
|
||||||
const discarded = [...pages.children];
|
const discarded = [...pages.children];
|
||||||
pages.replaceChildren(...draft.previous);
|
pages.replaceChildren(...draft.previous);
|
||||||
revokeDetached(discarded);
|
|
||||||
if (publishedRevision === null) delete document.body.dataset.visibleRevision;
|
|
||||||
else document.body.dataset.visibleRevision = publishedRevision;
|
|
||||||
pdf.hidden = publishedRevision === null;
|
|
||||||
draft = null;
|
draft = null;
|
||||||
|
revokeDetached(discarded);
|
||||||
|
visibleRevision = publishedRevision;
|
||||||
|
if (visibleRevision === null) delete document.body.dataset.visibleRevision;
|
||||||
|
else document.body.dataset.visibleRevision = visibleRevision;
|
||||||
|
pdf.hidden = publishedRevision === null;
|
||||||
if (publishedRevision !== null && textLayerRevision !== publishedRevision) {
|
if (publishedRevision !== null && textLayerRevision !== publishedRevision) {
|
||||||
requestPreviewText(publishedRevision);
|
requestPreviewText(publishedRevision);
|
||||||
}
|
}
|
||||||
@@ -195,18 +201,20 @@ function requestPreviewText(revision) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function acceptPublication(revision, previous) {
|
function acceptPublication(revision, previous) {
|
||||||
revokeDetached(previous);
|
const discarded = draft ? new Set([...previous, ...draft.previous]) : previous;
|
||||||
|
draft = null;
|
||||||
|
revokeDetached(discarded);
|
||||||
publishedRevision = revision;
|
publishedRevision = revision;
|
||||||
pdf.href = projectPrefix + `/pdf?revision=${revision}`;
|
pdf.href = projectPrefix + `/pdf?revision=${revision}`;
|
||||||
pdf.hidden = false;
|
pdf.hidden = false;
|
||||||
draft = null;
|
|
||||||
requestPreviewText(revision);
|
requestPreviewText(revision);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function publicationStatus(edit, revision) {
|
async function publicationStatus(pendingDraft, revision) {
|
||||||
while (edit === sequence) {
|
while (draft === pendingDraft) {
|
||||||
const response = await fetch(projectPrefix + `/publication?revision=${revision}`);
|
const response = await fetch(projectPrefix + `/publication?revision=${revision}`);
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
|
if (draft !== pendingDraft) return null;
|
||||||
if (!response.ok || result.state === "failed") throw new Error(result.error);
|
if (!response.ok || result.state === "failed") throw new Error(result.error);
|
||||||
if (result.state === "published") return result;
|
if (result.state === "published") return result;
|
||||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||||
@@ -292,10 +300,13 @@ async function requestHttpPreview(payload) {
|
|||||||
|
|
||||||
async function compile(edit, submitted, changes) {
|
async function compile(edit, submitted, changes) {
|
||||||
const replacements = [];
|
const replacements = [];
|
||||||
|
let pendingDraft;
|
||||||
try {
|
try {
|
||||||
const payload = {
|
const payload = {
|
||||||
sequence: edit,
|
sequence: edit,
|
||||||
visible_revision: publishedRevision,
|
// A retained draft might not have published. In that case the
|
||||||
|
// server sends a complete preview instead of a delta for another base.
|
||||||
|
visible_revision: visibleRevision,
|
||||||
files: changes,
|
files: changes,
|
||||||
preview_draft: previewDraft,
|
preview_draft: previewDraft,
|
||||||
};
|
};
|
||||||
@@ -316,7 +327,7 @@ async function compile(edit, submitted, changes) {
|
|||||||
const result = response.body;
|
const result = response.body;
|
||||||
if (response.status < 200 || response.status >= 300) throw new Error(result.error);
|
if (response.status < 200 || response.status >= 300) throw new Error(result.error);
|
||||||
const update = result.update;
|
const update = result.update;
|
||||||
if (result.sequence !== edit || (update.base_revision !== null && update.base_revision !== publishedRevision)) {
|
if (result.sequence !== edit || (update.base_revision !== null && update.base_revision !== visibleRevision)) {
|
||||||
throw new Error("预览版本与当前页面不一致");
|
throw new Error("预览版本与当前页面不一致");
|
||||||
}
|
}
|
||||||
for (const page of update.pages) replacements.push(pageFrame(page));
|
for (const page of update.pages) replacements.push(pageFrame(page));
|
||||||
@@ -327,7 +338,9 @@ async function compile(edit, submitted, changes) {
|
|||||||
}
|
}
|
||||||
const previous = applyPages(update, replacements);
|
const previous = applyPages(update, replacements);
|
||||||
if (result.pending_publication) {
|
if (result.pending_publication) {
|
||||||
draft = { previous };
|
pendingDraft = { previous: draft?.previous ?? previous };
|
||||||
|
draft = pendingDraft;
|
||||||
|
revokeDetached(previous);
|
||||||
pdf.hidden = true;
|
pdf.hidden = true;
|
||||||
status.textContent = "正在写入文件";
|
status.textContent = "正在写入文件";
|
||||||
} else {
|
} else {
|
||||||
@@ -336,7 +349,6 @@ async function compile(edit, submitted, changes) {
|
|||||||
errorPanel.hidden = true;
|
errorPanel.hidden = true;
|
||||||
await new Promise(requestAnimationFrame);
|
await new Promise(requestAnimationFrame);
|
||||||
await new Promise(requestAnimationFrame);
|
await new Promise(requestAnimationFrame);
|
||||||
if (edit !== sequence) return;
|
|
||||||
const sample = {
|
const sample = {
|
||||||
sequence: edit,
|
sequence: edit,
|
||||||
revision: update.revision,
|
revision: update.revision,
|
||||||
@@ -358,11 +370,13 @@ async function compile(edit, submitted, changes) {
|
|||||||
pendingPublication: result.pending_publication === true,
|
pendingPublication: result.pending_publication === true,
|
||||||
deferredStateFingerprint: result.deferred_state_fingerprint === true,
|
deferredStateFingerprint: result.deferred_state_fingerprint === true,
|
||||||
};
|
};
|
||||||
|
if (edit === sequence) {
|
||||||
window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample }));
|
window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample }));
|
||||||
if (result.pending_publication) {
|
}
|
||||||
const committed = await publicationStatus(edit, update.revision);
|
if (pendingDraft) {
|
||||||
if (edit !== sequence || !committed) return;
|
const committed = await publicationStatus(pendingDraft, update.revision);
|
||||||
acceptPublication(update.revision, draft.previous);
|
if (draft !== pendingDraft || !committed) return;
|
||||||
|
acceptPublication(update.revision, []);
|
||||||
window.dispatchEvent(new CustomEvent("texrra-preview-published", {
|
window.dispatchEvent(new CustomEvent("texrra-preview-published", {
|
||||||
detail: {
|
detail: {
|
||||||
sequence: edit,
|
sequence: edit,
|
||||||
@@ -372,11 +386,13 @@ async function compile(edit, submitted, changes) {
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
if (edit === sequence) {
|
||||||
status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`;
|
status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`;
|
||||||
|
}
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
revokeDetached(replacements);
|
revokeDetached(replacements);
|
||||||
if (edit === sequence) {
|
if (edit === sequence) {
|
||||||
restorePublishedPages();
|
if (pendingDraft && draft === pendingDraft) restorePublishedPages();
|
||||||
showError(failure.message);
|
showError(failure.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -387,10 +403,10 @@ function invalidatePreview() {
|
|||||||
clearTimeout(compileTimer);
|
clearTimeout(compileTimer);
|
||||||
compileTimer = undefined;
|
compileTimer = undefined;
|
||||||
promptCompilePending = false;
|
promptCompilePending = false;
|
||||||
restorePublishedPages();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function queueCompile(immediate = false) {
|
function queueCompile(immediate = false) {
|
||||||
|
if (preparingProject) return;
|
||||||
const submitted = performance.now();
|
const submitted = performance.now();
|
||||||
// Edits arriving before the first dispatch share its prompt submission.
|
// Edits arriving before the first dispatch share its prompt submission.
|
||||||
const prompt = immediate || promptCompilePending || submitted - lastTypingAt >= EDIT_IDLE_MS;
|
const prompt = immediate || promptCompilePending || submitted - lastTypingAt >= EDIT_IDLE_MS;
|
||||||
@@ -529,9 +545,7 @@ async function openProject() {
|
|||||||
source.setAttribute("autocomplete", "off");
|
source.setAttribute("autocomplete", "off");
|
||||||
addFormulaButtons();
|
addFormulaButtons();
|
||||||
sequence = project.sequence;
|
sequence = project.sequence;
|
||||||
advertisePreviewSocket(project.preview_socket);
|
preparingProject = project.preparing === true;
|
||||||
save.disabled = false;
|
|
||||||
recompile.disabled = false;
|
|
||||||
recompile.title = "重新编译主文件 " + project.name + "(Ctrl/Cmd+Enter)";
|
recompile.title = "重新编译主文件 " + project.name + "(Ctrl/Cmd+Enter)";
|
||||||
save.addEventListener("click", saveSources);
|
save.addEventListener("click", saveSources);
|
||||||
document.addEventListener("keydown", (event) => {
|
document.addEventListener("keydown", (event) => {
|
||||||
@@ -575,6 +589,18 @@ async function openProject() {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
indentSource();
|
indentSource();
|
||||||
});
|
});
|
||||||
|
if (preparingProject) {
|
||||||
|
status.textContent = "正在准备编译资源";
|
||||||
|
const ready = await fetch(projectPrefix + "/ready");
|
||||||
|
if (!ready.ok) {
|
||||||
|
const failure = await ready.json();
|
||||||
|
throw new Error(failure.error ?? "准备项目失败");
|
||||||
|
}
|
||||||
|
preparingProject = false;
|
||||||
|
}
|
||||||
|
save.disabled = false;
|
||||||
|
recompile.disabled = false;
|
||||||
|
advertisePreviewSocket(project.preview_socket);
|
||||||
queueCompile(true);
|
queueCompile(true);
|
||||||
} catch (failure) {
|
} catch (failure) {
|
||||||
showError(failure.message);
|
showError(failure.message);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::{EditorSession, InputProfile, fs, json, prepare, projects::ProjectStore, reply};
|
use super::{InputProfile, OpeningEditor, fs, json, projects::ProjectStore, reply, stage_sources};
|
||||||
use std::{
|
use std::{
|
||||||
io::{ErrorKind, Read},
|
io::{ErrorKind, Read},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
@@ -104,7 +104,7 @@ impl Library {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn open(&self, id: &str) -> Result<EditorSession, Box<dyn std::error::Error>> {
|
pub(super) fn open(&self, id: &str) -> Result<OpeningEditor, Box<dyn std::error::Error>> {
|
||||||
let root = self.store.project_dir(id)?;
|
let root = self.store.project_dir(id)?;
|
||||||
if fs::symlink_metadata(&root)?.file_type().is_symlink() {
|
if fs::symlink_metadata(&root)?.file_type().is_symlink() {
|
||||||
return Err("The project directory must be a local working copy".into());
|
return Err("The project directory must be a local working copy".into());
|
||||||
@@ -121,19 +121,10 @@ impl Library {
|
|||||||
.map(|file| PathBuf::from(&file.path))
|
.map(|file| PathBuf::from(&file.path))
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
let run = fresh_run(&self.runs, id)?;
|
let run = fresh_run(&self.runs, id)?;
|
||||||
let mut session = EditorSession::new(run, |run| {
|
let staged = stage_sources(
|
||||||
prepare(
|
&root, &source, &self.format, &self.manifest, &run, &files, self.profile,
|
||||||
&root,
|
)?;
|
||||||
&source,
|
OpeningEditor::start(info.id, run, staged)
|
||||||
&self.format,
|
|
||||||
&self.manifest,
|
|
||||||
run,
|
|
||||||
&files,
|
|
||||||
self.profile,
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
session.id = Some(info.id);
|
|
||||||
Ok(session)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+226
-84
@@ -7,7 +7,7 @@ use std::{
|
|||||||
io::{Read, Write},
|
io::{Read, Write},
|
||||||
path::{Component, Path, PathBuf},
|
path::{Component, Path, PathBuf},
|
||||||
sync::{
|
sync::{
|
||||||
Arc, Condvar, Mutex, mpsc,
|
Arc, Condvar, Mutex, OnceLock, mpsc,
|
||||||
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
|
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
|
||||||
},
|
},
|
||||||
time::{Instant, SystemTime},
|
time::{Instant, SystemTime},
|
||||||
@@ -328,22 +328,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let root = source_root
|
let root = source_root
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.unwrap_or_else(|| source.parent().expect("a source file has a parent"));
|
.unwrap_or_else(|| source.parent().expect("a source file has a parent"));
|
||||||
(
|
let staged = stage_sources(
|
||||||
port,
|
root, &source, &format, &manifest, &run, &additional, input_profile,
|
||||||
Some(EditorSession::new(run, |run| {
|
)?;
|
||||||
prepare(
|
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||||
root,
|
let editor = finish_prepare(staged, &run, &compiler, None)?;
|
||||||
&source,
|
(port, Some(EditorSession::new(run, editor, compiler)))
|
||||||
&format,
|
|
||||||
&manifest,
|
|
||||||
run,
|
|
||||||
&additional,
|
|
||||||
input_profile,
|
|
||||||
)
|
|
||||||
})?),
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
let mut session = session.map(|session| Arc::new(Mutex::new(session)));
|
let mut session = session.map(|session| Arc::new(Mutex::new(session)));
|
||||||
|
let mut opening: Option<OpeningEditor> = None;
|
||||||
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
|
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
|
||||||
println!("Native editor http://{}", server.server_addr());
|
println!("Native editor http://{}", server.server_addr());
|
||||||
for request in server.incoming_requests() {
|
for request in server.incoming_requests() {
|
||||||
@@ -408,13 +401,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
reply(request, 404, json!({"error": "Not found"}));
|
reply(request, 404, json!({"error": "Not found"}));
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
if let Some(Ok(ready)) = opening.as_ref().and_then(|opening| opening.ready.get()) {
|
||||||
|
session = Some(ready.clone());
|
||||||
|
opening = None;
|
||||||
|
}
|
||||||
let project_open = session
|
let project_open = session
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|session| session.lock().unwrap().id.as_deref() == Some(id));
|
.is_some_and(|session| session.lock().unwrap().id.as_deref() == Some(id));
|
||||||
|
let pending = opening.as_ref().filter(|opening| opening.id == id);
|
||||||
if rest.is_empty() && request.method() == &Method::Get {
|
if rest.is_empty() && request.method() == &Method::Get {
|
||||||
if !project_open {
|
if !project_open && !pending.is_some_and(|opening| opening.ready.get().is_none()) {
|
||||||
match library.open(id) {
|
match library.open(id) {
|
||||||
Ok(next) => session = Some(Arc::new(Mutex::new(next))),
|
Ok(next) => {
|
||||||
|
session = None;
|
||||||
|
opening = Some(next);
|
||||||
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
reply(request, 422, json!({"error": error.to_string()}));
|
reply(request, 422, json!({"error": error.to_string()}));
|
||||||
continue;
|
continue;
|
||||||
@@ -429,6 +430,27 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if request.method() == &Method::Get {
|
||||||
|
match (rest, pending) {
|
||||||
|
("project", Some(opening)) => {
|
||||||
|
reply(request, 200, opening.sources.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
("ready", Some(opening)) => {
|
||||||
|
let ready = opening.ready.clone();
|
||||||
|
std::thread::spawn(move || match ready.wait() {
|
||||||
|
Ok(_) => reply(request, 200, json!({})),
|
||||||
|
Err(error) => reply(request, 422, json!({"error": error})),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
("ready", None) if project_open => {
|
||||||
|
reply(request, 200, json!({}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
if !project_open {
|
if !project_open {
|
||||||
reply(
|
reply(
|
||||||
request,
|
request,
|
||||||
@@ -464,6 +486,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
id,
|
id,
|
||||||
run,
|
run,
|
||||||
compiler,
|
compiler,
|
||||||
|
first_preview_revision,
|
||||||
queue,
|
queue,
|
||||||
save_number,
|
save_number,
|
||||||
editor,
|
editor,
|
||||||
@@ -476,6 +499,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
declared,
|
declared,
|
||||||
..
|
..
|
||||||
} = editor;
|
} = editor;
|
||||||
|
let published_at = |revision: Option<u64>| compiler.latest().filter(|document| {
|
||||||
|
Some(document.revision()) == revision && document.revision() >= *first_preview_revision
|
||||||
|
});
|
||||||
match (request.method(), session_path) {
|
match (request.method(), session_path) {
|
||||||
(&Method::Get, "/") => respond(
|
(&Method::Get, "/") => respond(
|
||||||
request,
|
request,
|
||||||
@@ -485,28 +511,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
.map_or_else(|| PAGE.into(), |assets| assets.index.clone()),
|
.map_or_else(|| PAGE.into(), |assets| assets.index.clone()),
|
||||||
),
|
),
|
||||||
(&Method::Get, "/project") => {
|
(&Method::Get, "/project") => {
|
||||||
let file = project.file(&entry).expect("the editor owns its entry");
|
let files = editable.iter().filter_map(|(name, path)| {
|
||||||
let files = editable
|
project.file(path).map(|file| (name.as_str(), file.data.as_ref()))
|
||||||
.iter()
|
});
|
||||||
.filter_map(|(name, path)| project.file(path).map(|file| (name, file)))
|
let payload = project_payload(
|
||||||
.map(|(name, file)| Ok((name, std::str::from_utf8(&file.data)?)))
|
run, entry, declared, files, queue.current.load(Ordering::Acquire), id.as_deref(),
|
||||||
.collect::<Result<BTreeMap<_, _>, std::str::Utf8Error>>()?;
|
)?;
|
||||||
reply(
|
reply(request, 200, payload);
|
||||||
request,
|
|
||||||
200,
|
|
||||||
json!({
|
|
||||||
"name": entry.strip_prefix(run.as_path()).unwrap().to_string_lossy(),
|
|
||||||
"source": std::str::from_utf8(&file.data)?,
|
|
||||||
"files": files,
|
|
||||||
"project_files": declared.iter()
|
|
||||||
.filter_map(|path| path.strip_prefix(run.as_path()).ok()?.to_str())
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
"sequence": queue.current.load(Ordering::Acquire),
|
|
||||||
"preview_socket": id.as_deref().map_or_else(
|
|
||||||
|| "/preview-socket".to_owned(), |id| format!("/p/{id}/preview-socket"),
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
(&Method::Post, "/save") => {
|
(&Method::Post, "/save") => {
|
||||||
let mut request = request;
|
let mut request = request;
|
||||||
@@ -580,11 +591,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}
|
}
|
||||||
(&Method::Get, path) if path.starts_with("/pdf?revision=") => {
|
(&Method::Get, path) if path.starts_with("/pdf?revision=") => {
|
||||||
let revision = path["/pdf?revision=".len()..].parse::<u64>().ok();
|
let revision = path["/pdf?revision=".len()..].parse::<u64>().ok();
|
||||||
match compiler
|
match published_at(revision).and_then(|doc| doc.pdf.clone()) {
|
||||||
.latest()
|
|
||||||
.filter(|doc| Some(doc.revision()) == revision)
|
|
||||||
.and_then(|doc| doc.pdf.clone())
|
|
||||||
{
|
|
||||||
Some(pdf) => respond(request, 200, "application/pdf", pdf.to_vec()),
|
Some(pdf) => respond(request, 200, "application/pdf", pdf.to_vec()),
|
||||||
None => reply(
|
None => reply(
|
||||||
request,
|
request,
|
||||||
@@ -595,7 +602,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}
|
}
|
||||||
(&Method::Get, path) if path.starts_with("/text-layer?revision=") => {
|
(&Method::Get, path) if path.starts_with("/text-layer?revision=") => {
|
||||||
let revision = path["/text-layer?revision=".len()..].parse::<u64>().ok();
|
let revision = path["/text-layer?revision=".len()..].parse::<u64>().ok();
|
||||||
if let Some(document) = compiler.latest().filter(|doc| Some(doc.revision()) == revision) {
|
if let Some(document) = published_at(revision) {
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
reply(request, 200, json!(text_layer::for_document(&document)));
|
reply(request, 200, json!(text_layer::for_document(&document)));
|
||||||
});
|
});
|
||||||
@@ -609,10 +616,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}
|
}
|
||||||
(&Method::Get, path) if path.starts_with("/source-map?revision=") => {
|
(&Method::Get, path) if path.starts_with("/source-map?revision=") => {
|
||||||
let revision = path["/source-map?revision=".len()..].parse::<u64>().ok();
|
let revision = path["/source-map?revision=".len()..].parse::<u64>().ok();
|
||||||
match compiler
|
match published_at(revision) {
|
||||||
.latest()
|
|
||||||
.filter(|doc| Some(doc.revision()) == revision)
|
|
||||||
{
|
|
||||||
Some(doc) => reply(request, 200, json!(doc.source_map)),
|
Some(doc) => reply(request, 200, json!(doc.source_map)),
|
||||||
None => reply(
|
None => reply(
|
||||||
request,
|
request,
|
||||||
@@ -668,10 +672,91 @@ fn read_port(value: Option<PathBuf>) -> Result<u16, std::num::ParseIntError> {
|
|||||||
value.map_or(Ok(0), |port| port.to_string_lossy().parse())
|
value.map_or(Ok(0), |port| port.to_string_lossy().parse())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ReadyEditor = Result<Arc<Mutex<EditorSession>>, String>;
|
||||||
|
|
||||||
|
struct OpeningEditor {
|
||||||
|
id: String,
|
||||||
|
sources: Value,
|
||||||
|
ready: Arc<OnceLock<ReadyEditor>>,
|
||||||
|
compiler: NativeCompiler,
|
||||||
|
superseded: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OpeningEditor {
|
||||||
|
fn start(
|
||||||
|
id: String,
|
||||||
|
run: PathBuf,
|
||||||
|
staged: StagedProject,
|
||||||
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
|
let files = staged.editable.iter().filter_map(|(name, path)| {
|
||||||
|
staged.files.get(path).map(|bytes| (name.as_str(), bytes.as_ref()))
|
||||||
|
});
|
||||||
|
let mut sources = project_payload(&run, &staged.entry, &staged.declared, files, 1, Some(&id))?;
|
||||||
|
sources["preparing"] = json!(true);
|
||||||
|
let opening = Self {
|
||||||
|
id,
|
||||||
|
sources,
|
||||||
|
ready: Arc::new(OnceLock::new()),
|
||||||
|
compiler: NativeCompiler::default().with_automatic_entry_checkpoints(),
|
||||||
|
superseded: Arc::new(AtomicBool::new(false)),
|
||||||
|
};
|
||||||
|
let id = opening.id.clone();
|
||||||
|
let ready = opening.ready.clone();
|
||||||
|
let compiler = opening.compiler.clone();
|
||||||
|
let superseded = opening.superseded.clone();
|
||||||
|
std::thread::Builder::new().name("texrra-open-project".into()).spawn(move || {
|
||||||
|
let result = finish_prepare(staged, &run, &compiler, Some(&superseded))
|
||||||
|
.map(|editor| {
|
||||||
|
let mut session = EditorSession::new(run, editor, compiler);
|
||||||
|
session.id = Some(id);
|
||||||
|
Arc::new(Mutex::new(session))
|
||||||
|
})
|
||||||
|
.map_err(|error| error.to_string());
|
||||||
|
let _ = ready.set(result);
|
||||||
|
})?;
|
||||||
|
Ok(opening)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for OpeningEditor {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if self.ready.get().is_none() {
|
||||||
|
self.superseded.store(true, Ordering::Release);
|
||||||
|
self.compiler.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn project_payload<'a>(
|
||||||
|
run: &Path,
|
||||||
|
entry: &Path,
|
||||||
|
declared: &BTreeSet<PathBuf>,
|
||||||
|
contents: impl Iterator<Item = (&'a str, &'a [u8])>,
|
||||||
|
sequence: u64,
|
||||||
|
id: Option<&str>,
|
||||||
|
) -> Result<Value, std::str::Utf8Error> {
|
||||||
|
let name = entry.strip_prefix(run).unwrap().to_str().expect("validated entry filename");
|
||||||
|
let files = contents.map(|(name, bytes)| Ok((name, std::str::from_utf8(bytes)?)))
|
||||||
|
.collect::<Result<BTreeMap<_, _>, std::str::Utf8Error>>()?;
|
||||||
|
Ok(json!({
|
||||||
|
"name": name,
|
||||||
|
"source": files[name],
|
||||||
|
"files": files,
|
||||||
|
"project_files": declared.iter()
|
||||||
|
.filter_map(|path| path.strip_prefix(run).ok()?.to_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
"sequence": sequence,
|
||||||
|
"preview_socket": id.map_or_else(
|
||||||
|
|| "/preview-socket".to_owned(), |id| format!("/p/{id}/preview-socket"),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
struct EditorSession {
|
struct EditorSession {
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
run: PathBuf,
|
run: PathBuf,
|
||||||
compiler: NativeCompiler,
|
compiler: NativeCompiler,
|
||||||
|
first_preview_revision: u64,
|
||||||
bibliography_compiler: Option<NativeCompiler>,
|
bibliography_compiler: Option<NativeCompiler>,
|
||||||
queue: Arc<Queue>,
|
queue: Arc<Queue>,
|
||||||
save_number: u64,
|
save_number: u64,
|
||||||
@@ -681,10 +766,12 @@ struct EditorSession {
|
|||||||
impl EditorSession {
|
impl EditorSession {
|
||||||
fn new(
|
fn new(
|
||||||
run: PathBuf,
|
run: PathBuf,
|
||||||
prepare_editor: impl FnOnce(&Path) -> Result<EditorProject, Box<dyn std::error::Error>>,
|
editor: EditorProject,
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
compiler: NativeCompiler,
|
||||||
let editor = prepare_editor(&run)?;
|
) -> Self {
|
||||||
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
// Resource discovery warms the compiler's caches. Only preview jobs
|
||||||
|
// may expose a revision to the editor.
|
||||||
|
let first_preview_revision = compiler.latest().map_or(1, |document| document.revision() + 1);
|
||||||
let queue = Arc::new(Queue {
|
let queue = Arc::new(Queue {
|
||||||
current: AtomicU64::new(editor.project.version().revision),
|
current: AtomicU64::new(editor.project.version().revision),
|
||||||
..Queue::default()
|
..Queue::default()
|
||||||
@@ -701,15 +788,16 @@ impl EditorSession {
|
|||||||
let queue = queue.clone();
|
let queue = queue.clone();
|
||||||
move || worker(&queue, settled_bibliography)
|
move || worker(&queue, settled_bibliography)
|
||||||
});
|
});
|
||||||
Ok(Self {
|
Self {
|
||||||
id: None,
|
id: None,
|
||||||
run,
|
run,
|
||||||
compiler,
|
compiler,
|
||||||
|
first_preview_revision,
|
||||||
bibliography_compiler,
|
bibliography_compiler,
|
||||||
queue,
|
queue,
|
||||||
save_number: 0,
|
save_number: 0,
|
||||||
editor,
|
editor,
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn submit_edit(&mut self, edit: Edit, received: Instant, respond_to: PreviewReply) {
|
fn submit_edit(&mut self, edit: Edit, received: Instant, respond_to: PreviewReply) {
|
||||||
@@ -832,7 +920,18 @@ fn copy_with_date(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prepare(
|
struct StagedProject {
|
||||||
|
world: WorldConfig,
|
||||||
|
entry: PathBuf,
|
||||||
|
editable: BTreeMap<String, PathBuf>,
|
||||||
|
declared: BTreeSet<PathBuf>,
|
||||||
|
files: BTreeMap<PathBuf, Arc<[u8]>>,
|
||||||
|
directories: BTreeSet<PathBuf>,
|
||||||
|
dates: BTreeMap<PathBuf, FileModificationTime>,
|
||||||
|
options: CompileRequest,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stage_sources(
|
||||||
source_root: &Path,
|
source_root: &Path,
|
||||||
source: &Path,
|
source: &Path,
|
||||||
format: &Path,
|
format: &Path,
|
||||||
@@ -840,10 +939,14 @@ fn prepare(
|
|||||||
run: &Path,
|
run: &Path,
|
||||||
additional: &[PathBuf],
|
additional: &[PathBuf],
|
||||||
input_profile: InputProfile,
|
input_profile: InputProfile,
|
||||||
) -> Result<EditorProject, Box<dyn std::error::Error>> {
|
) -> Result<StagedProject, Box<dyn std::error::Error>> {
|
||||||
let format_resources: Value = serde_json::from_slice(&fs::read(manifest)?)?;
|
#[derive(Deserialize)]
|
||||||
let roots: Vec<PathBuf> = serde_json::from_value(format_resources["texmf_roots"].clone())?;
|
struct FormatResources {
|
||||||
let mut world = WorldConfig::from_environment(run, roots)?;
|
texmf_roots: Vec<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
let resources: FormatResources = serde_json::from_slice(&fs::read(manifest)?)?;
|
||||||
|
let mut world = WorldConfig::from_environment(run, resources.texmf_roots)?;
|
||||||
world.input_policy = InputPolicy::Tex;
|
world.input_policy = InputPolicy::Tex;
|
||||||
let name = source
|
let name = source
|
||||||
.strip_prefix(source_root)?
|
.strip_prefix(source_root)?
|
||||||
@@ -925,27 +1028,6 @@ fn prepare(
|
|||||||
files.insert(logical, Arc::from(data));
|
files.insert(logical, Arc::from(data));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let figures = additional.iter().filter_map(|relative| {
|
|
||||||
let input = run.join(relative);
|
|
||||||
let data = files.get(&input)?;
|
|
||||||
let converted = run.join(figure_conversion::converted_relative_path(relative, data)?);
|
|
||||||
if files.contains_key(&converted) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let date = dates.get(&input).and_then(|time| time.to_system_time());
|
|
||||||
Some((converted, data.clone(), date))
|
|
||||||
}).collect::<Vec<_>>();
|
|
||||||
for (path, source, date) in figures {
|
|
||||||
match figure_conversion::convert(run, &source) {
|
|
||||||
Ok(Some(pdf)) => {
|
|
||||||
let modified = date.unwrap_or_else(SystemTime::now);
|
|
||||||
copy_with_date(&path, &pdf, Some(modified), &mut dates)?;
|
|
||||||
files.insert(path, Arc::from(pdf));
|
|
||||||
}
|
|
||||||
Ok(None) => {}
|
|
||||||
Err(error) => eprintln!("Editor EPS conversion for {}: {error}", path.display()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut output = entry.with_extension("pdf");
|
let mut output = entry.with_extension("pdf");
|
||||||
if declared.contains(&output) || declared.contains(&output.with_extension("log")) {
|
if declared.contains(&output) || declared.contains(&output.with_extension("log")) {
|
||||||
let directory = run.join(".texrra-output");
|
let directory = run.join(".texrra-output");
|
||||||
@@ -959,10 +1041,70 @@ fn prepare(
|
|||||||
request.input_profile = input_profile;
|
request.input_profile = input_profile;
|
||||||
request.limits.steps = 600_000_000;
|
request.limits.steps = 600_000_000;
|
||||||
request = request.observe_generated_initial();
|
request = request.observe_generated_initial();
|
||||||
|
Ok(StagedProject {
|
||||||
|
world,
|
||||||
|
entry,
|
||||||
|
editable,
|
||||||
|
declared,
|
||||||
|
files,
|
||||||
|
directories,
|
||||||
|
dates,
|
||||||
|
options: request,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_prepare(
|
||||||
|
staged: StagedProject,
|
||||||
|
run: &Path,
|
||||||
|
compiler: &NativeCompiler,
|
||||||
|
superseded: Option<&AtomicBool>,
|
||||||
|
) -> Result<EditorProject, Box<dyn std::error::Error>> {
|
||||||
|
let StagedProject {
|
||||||
|
world,
|
||||||
|
entry,
|
||||||
|
editable,
|
||||||
|
declared,
|
||||||
|
mut files,
|
||||||
|
directories,
|
||||||
|
mut dates,
|
||||||
|
options: request,
|
||||||
|
} = staged;
|
||||||
|
let check_current = || -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
if superseded.is_some_and(|flag| flag.load(Ordering::Acquire)) {
|
||||||
|
return Err("The project has closed".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
let figures = declared.iter().filter_map(|input| {
|
||||||
|
let relative = input.strip_prefix(run).ok()?;
|
||||||
|
let data = files.get(input)?;
|
||||||
|
let converted = run.join(figure_conversion::converted_relative_path(relative, data)?);
|
||||||
|
if files.contains_key(&converted) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let date = dates.get(input).and_then(|time| time.to_system_time());
|
||||||
|
Some((converted, data.clone(), date))
|
||||||
|
}).collect::<Vec<_>>();
|
||||||
|
for (path, source, date) in figures {
|
||||||
|
check_current()?;
|
||||||
|
match figure_conversion::convert(run, &source) {
|
||||||
|
Ok(Some(pdf)) => {
|
||||||
|
let modified = date.unwrap_or_else(SystemTime::now);
|
||||||
|
copy_with_date(&path, &pdf, Some(modified), &mut dates)?;
|
||||||
|
files.insert(path, Arc::from(pdf));
|
||||||
|
}
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(error) => eprintln!("Editor EPS conversion for {}: {error}", path.display()),
|
||||||
|
}
|
||||||
|
}
|
||||||
// Provision the finite, immutable resource bundle used by this trial.
|
// Provision the finite, immutable resource bundle used by this trial.
|
||||||
// The seed uses the same native compiler and actual package bytes.
|
// The seed uses the same native compiler and actual package bytes.
|
||||||
let compiler = NativeCompiler::default();
|
let compile_seed = || -> Result<_, Box<dyn std::error::Error>> {
|
||||||
let mut seed = compiler.compile_detailed(request.clone());
|
let job = compiler.start();
|
||||||
|
check_current()?;
|
||||||
|
Ok(job.compile_detailed(request.clone()))
|
||||||
|
};
|
||||||
|
let mut seed = compile_seed()?;
|
||||||
let mut bibliography = None;
|
let mut bibliography = None;
|
||||||
if let Ok(initial) = &seed {
|
if let Ok(initial) = &seed {
|
||||||
match bibliography::from_seed(&request, &initial.resources.generated_artifacts, &files) {
|
match bibliography::from_seed(&request, &initial.resources.generated_artifacts, &files) {
|
||||||
@@ -971,7 +1113,7 @@ fn prepare(
|
|||||||
copy_with_date(&path, &contents, Some(SystemTime::now()), &mut dates)?;
|
copy_with_date(&path, &contents, Some(SystemTime::now()), &mut dates)?;
|
||||||
files.insert(path, contents);
|
files.insert(path, contents);
|
||||||
bibliography = Some(plan);
|
bibliography = Some(plan);
|
||||||
seed = compiler.compile_detailed(request.clone());
|
seed = compile_seed()?;
|
||||||
}
|
}
|
||||||
Ok(None) => {}
|
Ok(None) => {}
|
||||||
Err(error) => eprintln!("Editor bibliography: {error}"),
|
Err(error) => eprintln!("Editor bibliography: {error}"),
|
||||||
|
|||||||
@@ -145,6 +145,7 @@ enum ExecutionCandidate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const SOURCE_INTERVALS: usize = 4;
|
const SOURCE_INTERVALS: usize = 4;
|
||||||
|
const MIN_PREAMBLE_INTERVAL_BYTES: usize = 4096;
|
||||||
const DENSE_SETTLED_PAGES: usize = 4;
|
const DENSE_SETTLED_PAGES: usize = 4;
|
||||||
const SPARSE_SETTLED_SLOTS: usize = 4;
|
const SPARSE_SETTLED_SLOTS: usize = 4;
|
||||||
|
|
||||||
@@ -165,6 +166,7 @@ struct CaptureSchedule {
|
|||||||
fixed_frontier: Option<usize>,
|
fixed_frontier: Option<usize>,
|
||||||
pending_edit_frontier: Option<usize>,
|
pending_edit_frontier: Option<usize>,
|
||||||
pending_edit_fallback: Option<usize>,
|
pending_edit_fallback: Option<usize>,
|
||||||
|
pending_preamble: Option<usize>,
|
||||||
pending_line_end: Option<(usize, CaptureSlots, usize)>,
|
pending_line_end: Option<(usize, CaptureSlots, usize)>,
|
||||||
settled_page: usize,
|
settled_page: usize,
|
||||||
}
|
}
|
||||||
@@ -175,6 +177,7 @@ struct CaptureSlots {
|
|||||||
early: bool,
|
early: bool,
|
||||||
page: bool,
|
page: bool,
|
||||||
edit: bool,
|
edit: bool,
|
||||||
|
preamble: bool,
|
||||||
next_page: usize,
|
next_page: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,11 +239,21 @@ impl CaptureSchedule {
|
|||||||
fixed_frontier,
|
fixed_frontier,
|
||||||
pending_edit_frontier: edit_frontier,
|
pending_edit_frontier: edit_frontier,
|
||||||
pending_edit_fallback: None,
|
pending_edit_fallback: None,
|
||||||
|
pending_preamble: None,
|
||||||
pending_line_end: None,
|
pending_line_end: None,
|
||||||
settled_page: 0,
|
settled_page: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn with_preamble_anchor(mut self, source: &[u8]) -> Self {
|
||||||
|
if self.fixed_frontier.is_none() && self.stride >= MIN_PREAMBLE_INTERVAL_BYTES {
|
||||||
|
// The first grid interval can span both package loading and
|
||||||
|
// LaTeX's generated-input reads. Keep one boundary between them.
|
||||||
|
self.pending_preamble = preamble_frontier(source, self.stride);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
fn select_source(&mut self, source: CheckpointSource<'_>, pages: usize) -> Option<Capture> {
|
fn select_source(&mut self, source: CheckpointSource<'_>, pages: usize) -> Option<Capture> {
|
||||||
let regular = self.select(source.frontier, pages);
|
let regular = self.select(source.frontier, pages);
|
||||||
let mut line_end = None;
|
let mut line_end = None;
|
||||||
@@ -305,6 +318,7 @@ impl CaptureSchedule {
|
|||||||
early: true,
|
early: true,
|
||||||
page: false,
|
page: false,
|
||||||
edit: false,
|
edit: false,
|
||||||
|
preamble: false,
|
||||||
next_page: self.next_page,
|
next_page: self.next_page,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -321,11 +335,13 @@ impl CaptureSchedule {
|
|||||||
self.next_page = pages.saturating_add((pages / 8).max(1).next_power_of_two());
|
self.next_page = pages.saturating_add((pages / 8).max(1).next_power_of_two());
|
||||||
}
|
}
|
||||||
let edit = !entry_complete && self.take_edit_frontier(frontier, early || page);
|
let edit = !entry_complete && self.take_edit_frontier(frontier, early || page);
|
||||||
(early || page || edit).then_some(CaptureSlots {
|
let preamble = self.pending_preamble.take_if(|pending| *pending == frontier).is_some();
|
||||||
|
(early || page || edit || preamble).then_some(CaptureSlots {
|
||||||
interval,
|
interval,
|
||||||
early,
|
early,
|
||||||
page,
|
page,
|
||||||
edit,
|
edit,
|
||||||
|
preamble,
|
||||||
next_page: self.next_page,
|
next_page: self.next_page,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -346,6 +362,8 @@ impl CaptureSchedule {
|
|||||||
early,
|
early,
|
||||||
edit: frontier < self.bytes
|
edit: frontier < self.bytes
|
||||||
&& self.take_edit_frontier(frontier, early || slots.page),
|
&& self.take_edit_frontier(frontier, early || slots.page),
|
||||||
|
preamble: frontier < self.bytes
|
||||||
|
&& self.pending_preamble.take_if(|pending| *pending == frontier).is_some(),
|
||||||
..slots
|
..slots
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -358,6 +376,7 @@ struct CapturedEntries<'a> {
|
|||||||
early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
||||||
shipped: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
shipped: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
||||||
edit: Option<Arc<CachedCheckpoint>>,
|
edit: Option<Arc<CachedCheckpoint>>,
|
||||||
|
preamble: Option<Arc<CachedCheckpoint>>,
|
||||||
nested: [[Option<Arc<CachedCheckpoint>>; NESTED_INTERVALS]; NESTED_FILES],
|
nested: [[Option<Arc<CachedCheckpoint>>; NESTED_INTERVALS]; NESTED_FILES],
|
||||||
changed: bool,
|
changed: bool,
|
||||||
settled: BTreeMap<usize, SettledCheckpoint>,
|
settled: BTreeMap<usize, SettledCheckpoint>,
|
||||||
@@ -377,6 +396,7 @@ impl<'a> CapturedEntries<'a> {
|
|||||||
early: Default::default(),
|
early: Default::default(),
|
||||||
shipped: Default::default(),
|
shipped: Default::default(),
|
||||||
edit: None,
|
edit: None,
|
||||||
|
preamble: None,
|
||||||
nested: Default::default(),
|
nested: Default::default(),
|
||||||
changed: false,
|
changed: false,
|
||||||
settled: BTreeMap::new(),
|
settled: BTreeMap::new(),
|
||||||
@@ -401,6 +421,9 @@ impl<'a> CapturedEntries<'a> {
|
|||||||
if slots.edit {
|
if slots.edit {
|
||||||
self.edit = Some(checkpoint.clone());
|
self.edit = Some(checkpoint.clone());
|
||||||
}
|
}
|
||||||
|
if slots.preamble {
|
||||||
|
self.preamble = Some(checkpoint.clone());
|
||||||
|
}
|
||||||
if slots.page {
|
if slots.page {
|
||||||
self.shipped[slots.interval] = Some(checkpoint);
|
self.shipped[slots.interval] = Some(checkpoint);
|
||||||
}
|
}
|
||||||
@@ -524,6 +547,7 @@ impl<'a> CapturedEntries<'a> {
|
|||||||
early: false,
|
early: false,
|
||||||
page: true,
|
page: true,
|
||||||
edit: false,
|
edit: false,
|
||||||
|
preamble: false,
|
||||||
next_page: page.saturating_add(1),
|
next_page: page.saturating_add(1),
|
||||||
};
|
};
|
||||||
self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host);
|
self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host);
|
||||||
@@ -580,6 +604,11 @@ impl<'a> CapturedEntries<'a> {
|
|||||||
.expect("the full schedule has ordinary continuations");
|
.expect("the full schedule has ordinary continuations");
|
||||||
entries.remove(index);
|
entries.remove(index);
|
||||||
}
|
}
|
||||||
|
if let Some(preamble) = self.preamble
|
||||||
|
&& !entries.iter().any(|entry| Arc::ptr_eq(entry, &preamble))
|
||||||
|
{
|
||||||
|
entries.push(preamble);
|
||||||
|
}
|
||||||
let before_child = recording.prefix().and_then(|(_, calls)| {
|
let before_child = recording.prefix().and_then(|(_, calls)| {
|
||||||
// Keep one existing parent anchor before a child's first size
|
// Keep one existing parent anchor before a child's first size
|
||||||
// observation. It can still replay when a new size invalidates
|
// observation. It can still replay when a new size invalidates
|
||||||
@@ -753,7 +782,8 @@ impl CheckpointCache {
|
|||||||
Result<Arc<RevisionExecution>, RevisionFailure>,
|
Result<Arc<RevisionExecution>, RevisionFailure>,
|
||||||
Option<Arc<CheckpointSet>>,
|
Option<Arc<CheckpointSet>>,
|
||||||
) {
|
) {
|
||||||
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None);
|
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None)
|
||||||
|
.with_preamble_anchor(&source.data);
|
||||||
let mut captures = CapturedEntries::new(request, files);
|
let mut captures = CapturedEntries::new(request, files);
|
||||||
let mut recording = RecordingHost::new(files);
|
let mut recording = RecordingHost::new(files);
|
||||||
let mut nested = NestedSchedule::default();
|
let mut nested = NestedSchedule::default();
|
||||||
@@ -1097,7 +1127,7 @@ impl SelectedCheckpoint {
|
|||||||
source.data.len(),
|
source.data.len(),
|
||||||
None,
|
None,
|
||||||
changed.or(self.set.edit_frontier),
|
changed.or(self.set.edit_frontier),
|
||||||
);
|
).with_preamble_anchor(&source.data);
|
||||||
// A comment-only line can be consumed without an observation.
|
// A comment-only line can be consumed without an observation.
|
||||||
// Keep an earlier anchor for this editing boundary.
|
// Keep an earlier anchor for this editing boundary.
|
||||||
schedule.pending_edit_fallback =
|
schedule.pending_edit_fallback =
|
||||||
@@ -1404,6 +1434,20 @@ fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn preamble_frontier(bytes: &[u8], limit: usize) -> Option<usize> {
|
||||||
|
let mut start = 0;
|
||||||
|
for line in bytes.split_inclusive(|&byte| matches!(byte, b'\r' | b'\n')) {
|
||||||
|
if start >= limit {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if line.trim_ascii() == br"\begin{document}" {
|
||||||
|
return (start > 0).then_some(start);
|
||||||
|
}
|
||||||
|
start += line.len();
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn preceding_command_frontier(bytes: &[u8], edit: usize) -> Option<usize> {
|
fn preceding_command_frontier(bytes: &[u8], edit: usize) -> Option<usize> {
|
||||||
let mut frontier = edit;
|
let mut frontier = edit;
|
||||||
while frontier > 0 {
|
while frontier > 0 {
|
||||||
@@ -2541,6 +2585,30 @@ fn immutable_file_creation_and_removal_replay_real_lookup_results() {
|
|||||||
assert_eq!(pdfs.values().collect::<BTreeSet<_>>().len(), 4);
|
assert_eq!(pdfs.values().collect::<BTreeSet<_>>().len(), 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn large_automatic_schedule_keeps_a_preamble_anchor_once() {
|
||||||
|
let prefix = b"% \\begin{document}\r\ntext \\begin{document}\r\n\\relax\r\n";
|
||||||
|
let mut source = prefix.to_vec();
|
||||||
|
source.extend_from_slice(b" \\begin{document}\r\n");
|
||||||
|
source.resize(4 * MIN_PREAMBLE_INTERVAL_BYTES, b'x');
|
||||||
|
let mut schedule = CaptureSchedule::new(source.len(), None, None).with_preamble_anchor(&source);
|
||||||
|
assert!(schedule.select(1, 0).unwrap().early);
|
||||||
|
let anchor = schedule.select(prefix.len(), 0).unwrap();
|
||||||
|
assert!(anchor.preamble && !anchor.early && !anchor.edit && !anchor.page);
|
||||||
|
assert!(schedule.select(prefix.len(), 0).is_none());
|
||||||
|
|
||||||
|
let mut schedule = CaptureSchedule::new(source.len(), None, Some(prefix.len()))
|
||||||
|
.with_preamble_anchor(&source);
|
||||||
|
let combined = schedule.select(prefix.len(), 0).unwrap();
|
||||||
|
assert!(combined.preamble && combined.early && combined.edit);
|
||||||
|
assert!(schedule.select(prefix.len(), 0).is_none());
|
||||||
|
assert!(CaptureSchedule::new(source.len(), Some(1), None)
|
||||||
|
.with_preamble_anchor(&source).pending_preamble.is_none());
|
||||||
|
assert!(CaptureSchedule::new(prefix.len(), None, None)
|
||||||
|
.with_preamble_anchor(prefix).pending_preamble.is_none());
|
||||||
|
assert_eq!(preamble_frontier(prefix, prefix.len()), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn edit_only_entry_checkpoint_advances_to_its_line_end() {
|
fn edit_only_entry_checkpoint_advances_to_its_line_end() {
|
||||||
let mut schedule = CaptureSchedule::new(400, None, Some(290));
|
let mut schedule = CaptureSchedule::new(400, None, Some(290));
|
||||||
|
|||||||
Reference in new issue
Block a user