diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 699d69d..64c73b1 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -3237,7 +3237,7 @@ dependencies = [ [[package]] name = "texrra-desktop" -version = "0.1.5" +version = "0.1.6" dependencies = [ "serde_json", "tauri", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index bd0bb4d..bebe5f7 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "texrra-desktop" -version = "0.1.5" +version = "0.1.6" edition = "2024" rust-version = "1.92" license = "MIT OR Apache-2.0" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index a503bd8..80310ee 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Texrra", - "version": "0.1.5", + "version": "0.1.6", "identifier": "org.texrra.desktop", "build": { "frontendDist": "../startup" diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index 141bc30..451c5ed 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -54,6 +54,14 @@ recompile.disabled = true; previewView.toolbar.prepend(recompile); recompile.addEventListener("click", manualCompile); +const cachedPreviewStatus = document.createElement("span"); +cachedPreviewStatus.id = "cached-preview-status"; +cachedPreviewStatus.className = "texrra-preview-history"; +cachedPreviewStatus.setAttribute("role", "status"); +cachedPreviewStatus.textContent = "上次成功预览"; +cachedPreviewStatus.hidden = true; +previewView.toolbar.prepend(cachedPreviewStatus); + function attachWebControls() { const button = document.createElement("button"); button.type = "button"; @@ -158,6 +166,7 @@ function applyPages(update, replacements) { while (pages.children.length > update.page_count) pages.lastElementChild.remove(); } visibleRevision = update.revision; + cachedPreviewStatus.hidden = true; document.body.dataset.visibleRevision = visibleRevision; return previous; } @@ -169,6 +178,7 @@ function restorePublishedPages() { draft = null; revokeDetached(discarded); visibleRevision = publishedRevision; + cachedPreviewStatus.hidden = visibleRevision !== null || pages.childElementCount === 0; if (visibleRevision === null) delete document.body.dataset.visibleRevision; else document.body.dataset.visibleRevision = visibleRevision; pdf.hidden = publishedRevision === null; @@ -177,6 +187,30 @@ function restorePublishedPages() { } } +async function showCachedPreview() { + const frames = []; + try { + const response = await fetch(projectPrefix + "/cached-preview"); + if (!response.ok || visibleRevision !== null) return; + const { page_count, pages: savedPages } = await response.json(); + if (visibleRevision !== null || !Array.isArray(savedPages) || savedPages.length === 0 + || savedPages.length !== page_count || savedPages.some((page, index) => + page?.index !== index || typeof page.svg !== "string")) return; + const first = pageFrame(savedPages[0]); + frames.push(first); + // The rest of the saved document can decode after the first page is ready. + await first.querySelector("img").decode(); + if (visibleRevision !== null) return; + for (const page of savedPages.slice(1)) frames.push(pageFrame(page)); + pages.replaceChildren(...frames); + cachedPreviewStatus.hidden = false; + } catch { + // Cache errors do not interrupt the live compile. + } finally { + revokeDetached(frames); + } +} + function requestPreviewText(revision) { clearTimeout(textLayerTimer); textLayerRequest?.abort(); @@ -589,6 +623,7 @@ async function openProject() { event.preventDefault(); indentSource(); }); + if (project.cached_preview === true) void showCachedPreview(); if (preparingProject) { status.textContent = "正在准备编译资源"; const ready = await fetch(projectPrefix + "/ready"); diff --git a/examples/native_editor/library.rs b/examples/native_editor/library.rs index ba8cf36..124e19c 100644 --- a/examples/native_editor/library.rs +++ b/examples/native_editor/library.rs @@ -124,7 +124,10 @@ impl Library { let staged = stage_sources( &root, &source, &self.format, &self.manifest, &run, &files, self.profile, )?; - OpeningEditor::start(info.id, run, staged) + let cache = super::preview_cache::PreviewCache::for_project( + &self.runs, &info.id, &run, &staged, &self.format, &self.manifest, + ); + OpeningEditor::start(info.id, run, staged, cache) } } diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index eec451c..6bbcc57 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -28,6 +28,7 @@ use tiny_http::{Header, Method, Request, Response, Server}; mod bibliography; mod figure_conversion; mod library; +mod preview_cache; mod preview_socket; #[path = "../../src/projects.rs"] #[allow(dead_code)] @@ -84,6 +85,7 @@ impl PreviewReply { } struct Work { + cache: Option, respond_to: PreviewReply, job: CompileJob, bibliography_pass: Option, @@ -333,7 +335,7 @@ fn main() -> Result<(), Box> { )?; let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); let editor = finish_prepare(staged, &run, &compiler, None)?; - (port, Some(EditorSession::new(run, editor, compiler))) + (port, Some(EditorSession::new(run, editor, compiler, None))) }; let mut session = session.map(|session| Arc::new(Mutex::new(session))); let mut opening: Option = None; @@ -436,6 +438,23 @@ fn main() -> Result<(), Box> { reply(request, 200, opening.sources.clone()); continue; } + ("cached-preview", _) if pending.is_some() || project_open => { + let cache = pending.and_then(|opening| opening.cache.clone()) + .or_else(|| { + if project_open { + session.as_ref()?.lock().unwrap().cache.clone() + } else { + None + } + }); + std::thread::spawn(move || { + match cache.and_then(|cache| cache.read().ok()) { + Some(bytes) => respond(request, 200, "application/json; charset=utf-8", bytes), + None => reply(request, 404, json!({"error": "No cached preview"})), + } + }); + continue; + } ("ready", Some(opening)) => { let ready = opening.ready.clone(); std::thread::spawn(move || match ready.wait() { @@ -486,6 +505,7 @@ fn main() -> Result<(), Box> { id, run, compiler, + cache, first_preview_revision, queue, save_number, @@ -514,9 +534,12 @@ fn main() -> Result<(), Box> { let files = editable.iter().filter_map(|(name, path)| { project.file(path).map(|file| (name.as_str(), file.data.as_ref())) }); - let payload = project_payload( + let mut payload = project_payload( run, entry, declared, files, queue.current.load(Ordering::Acquire), id.as_deref(), )?; + if cache.as_ref().is_some_and(preview_cache::PreviewCache::exists) { + payload["cached_preview"] = json!(true); + } reply(request, 200, payload); } (&Method::Post, "/save") => { @@ -676,6 +699,7 @@ type ReadyEditor = Result>, String>; struct OpeningEditor { id: String, + cache: Option, sources: Value, ready: Arc>, compiler: NativeCompiler, @@ -687,14 +711,19 @@ impl OpeningEditor { id: String, run: PathBuf, staged: StagedProject, + cache: Option, ) -> Result> { 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); + if cache.as_ref().is_some_and(preview_cache::PreviewCache::exists) { + sources["cached_preview"] = json!(true); + } let opening = Self { id, + cache, sources, ready: Arc::new(OnceLock::new()), compiler: NativeCompiler::default().with_automatic_entry_checkpoints(), @@ -704,10 +733,11 @@ impl OpeningEditor { let ready = opening.ready.clone(); let compiler = opening.compiler.clone(); let superseded = opening.superseded.clone(); + let cache = opening.cache.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); + let mut session = EditorSession::new(run, editor, compiler, cache); session.id = Some(id); Arc::new(Mutex::new(session)) }) @@ -754,6 +784,7 @@ fn project_payload<'a>( struct EditorSession { id: Option, + cache: Option, run: PathBuf, compiler: NativeCompiler, first_preview_revision: u64, @@ -768,6 +799,7 @@ impl EditorSession { run: PathBuf, editor: EditorProject, compiler: NativeCompiler, + cache: Option, ) -> Self { // Resource discovery warms the compiler's caches. Only preview jobs // may expose a revision to the editor. @@ -790,6 +822,7 @@ impl EditorSession { }); Self { id: None, + cache, run, compiler, first_preview_revision, @@ -851,6 +884,7 @@ impl EditorSession { let bibliography_pass = self.bibliography_compiler.as_ref().map(NativeCompiler::start); self.queue.current.store(edit.sequence, Ordering::Release); let replaced = self.queue.next.lock().unwrap().replace(Work { + cache: self.cache.as_ref().filter(|cache| cache.matches_saved_sources(project)).cloned(), respond_to, job, bibliography_pass, @@ -1222,6 +1256,7 @@ fn worker( .unwrap() .take(); let Some(Work { + cache, respond_to, job, bibliography_pass, @@ -1293,7 +1328,7 @@ fn worker( .as_mut() .filter(|p| p.revision == revision) .expect("the worker owns the current publication"); - let state = match result { + let state = match &result { Ok(_) => json!({ "state": "published", "compile_ms": compile_ms, @@ -1302,6 +1337,12 @@ fn worker( Err(error) => json!({ "state": "failed", "error": error.to_string() }), }; publication.result = Some(state); + drop(current); + if let (Some(cache), Ok(document)) = (cache, result) + && observer.is_current() + { + cache.refresh(document); + } continue; }; let document = match result { @@ -1321,15 +1362,20 @@ fn worker( continue; } match preview { - Ok(update) => respond_to.send( - 200, - observer.preview_payload( - update, - document.execution.execution.steps, - &document.entry_checkpoint_work, - Some(compile_ms), - ), - ), + Ok(update) => { + respond_to.send( + 200, + observer.preview_payload( + update, + document.execution.execution.steps, + &document.entry_checkpoint_work, + Some(compile_ms), + ), + ); + if let Some(cache) = cache { + cache.refresh(document); + } + } Err(error) => respond_to.send(422, json!({ "error": error, "sequence": sequence })), } } diff --git a/examples/native_editor/preview_cache.rs b/examples/native_editor/preview_cache.rs new file mode 100644 index 0000000..2157dae --- /dev/null +++ b/examples/native_editor/preview_cache.rs @@ -0,0 +1,244 @@ +use super::StagedProject; +use flate2::{Compression, read::GzDecoder, write::GzEncoder}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + fs::{self, File, OpenOptions}, + io::{self, BufReader, BufWriter, Read, Write}, + path::{Path, PathBuf}, + sync::{ + Arc, OnceLock, + atomic::{AtomicU64, Ordering}, + mpsc, + }, +}; +use texrra_engine::native::{CompiledDocument, PreviewPage, PreviewUpdate, ProjectSnapshot}; +use texrra_tex_core::resources::FileModificationTime; + +const MAGIC: &[u8; 16] = b"texrra-preview1\n"; +const LIMIT: usize = 32 * 1024 * 1024; + +#[derive(Clone)] +pub(super) struct PreviewCache(Arc); + +struct CacheEntry { + path: PathBuf, + key: [u8; 32], + originals: BTreeMap>, Option)>, +} + +impl PreviewCache { + pub(super) fn for_project( + runs: &Path, + id: &str, + run: &Path, + staged: &StagedProject, + format: &Path, + manifest: &Path, + ) -> Option { + let mut key = Sha256::new(); + hash_field( + &mut key, + staged + .entry + .strip_prefix(run) + .ok()? + .as_os_str() + .as_encoded_bytes(), + ); + hash_field( + &mut key, + &serde_json::to_vec(&staged.options.input_profile).ok()?, + ); + // Desktop run directories already belong to the verified package digest. + // Including file stamps also gives direct library runs a format/engine namespace. + for path in [format, manifest, &std::env::current_exe().ok()?] { + let metadata = fs::metadata(path).ok()?; + hash_field(&mut key, path.as_os_str().as_encoded_bytes()); + key.update(metadata.len().to_le_bytes()); + hash_date( + &mut key, + FileModificationTime::from_system_time(metadata.modified().ok()?).ok(), + ); + } + for path in &staged.declared { + hash_field( + &mut key, + path.strip_prefix(run).ok()?.as_os_str().as_encoded_bytes(), + ); + let data = staged.files.get(path); + key.update([u8::from(data.is_some())]); + if let Some(data) = data { + hash_field(&mut key, data); + } + hash_date(&mut key, staged.dates.get(path).copied()); + } + let originals = staged + .editable + .values() + .map(|path| { + ( + path.clone(), + ( + staged.files.get(path).cloned(), + staged.dates.get(path).copied(), + ), + ) + }) + .collect(); + Some(Self(Arc::new(CacheEntry { + path: runs.join(".cached-previews").join(format!("{id}.preview")), + key: key.finalize().into(), + originals, + }))) + } + + pub(super) fn matches_saved_sources(&self, project: &ProjectSnapshot) -> bool { + self.0.originals.iter().all(|(path, (original, date))| { + let current = project.file(path).map(|file| &file.data); + current == original.as_ref() && project.modification_time(path) == *date + }) + } + + pub(super) fn exists(&self) -> bool { + self.open().is_ok() + } + + pub(super) fn read(&self) -> io::Result> { + let mut bytes = Vec::new(); + // The gzip trailer protects the completed JSON from truncated or corrupt + // cache files. Bound both the compressed file and the decoded body. + GzDecoder::new(self.open()?) + .take(LIMIT as u64 + 1) + .read_to_end(&mut bytes)?; + if bytes.is_empty() || bytes.len() > LIMIT { + return Err(io::Error::other("Invalid cached preview size")); + } + Ok(bytes) + } + + fn open(&self) -> io::Result> { + let metadata = fs::symlink_metadata(&self.0.path)?; + if !metadata.is_file() || metadata.len() > LIMIT as u64 { + return Err(io::Error::other("Invalid cached preview file")); + } + let mut file = BufReader::new(File::open(&self.0.path)?); + let mut magic = [0; MAGIC.len()]; + let mut key = [0; 32]; + file.read_exact(&mut magic)?; + file.read_exact(&mut key)?; + if &magic != MAGIC || key != self.0.key { + return Err(io::Error::other("Cached preview version changed")); + } + Ok(file) + } + + pub(super) fn refresh(self, document: Arc) { + type CacheJob = (PreviewCache, Arc); + static WRITER: OnceLock>> = OnceLock::new(); + let writer = WRITER.get_or_init(|| { + let (sender, receiver) = mpsc::sync_channel::(1); + std::thread::Builder::new() + .name("texrra-preview-cache".into()) + .spawn(move || { + while let Ok((cache, doc)) = receiver.recv() { + if let Ok(preview) = doc.preview_since(None) { + let _ = cache.write(&preview); + } + } + }) + .ok()?; + Some(sender) + }); + if let Some(writer) = writer { + let _ = writer.try_send((self, document)); + } + } + + fn write(&self, preview: &PreviewUpdate) -> io::Result<()> { + if preview.base_revision.is_some() + || preview.page_count == 0 + || preview.pages.len() != preview.page_count + { + return Ok(()); + } + #[derive(Serialize)] + struct Pages<'a> { + page_count: usize, + pages: &'a [PreviewPage], + } + static TEMP_NUMBER: AtomicU64 = AtomicU64::new(0); + let directory = self.0.path.parent().expect("cache has a directory"); + fs::create_dir_all(directory)?; + let temporary = self.0.path.with_extension(format!( + "preview.{}.{}.new", + std::process::id(), + TEMP_NUMBER.fetch_add(1, Ordering::Relaxed) + )); + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary)?; + let result = (|| { + let mut file = BufWriter::new(file); + file.write_all(MAGIC)?; + file.write_all(&self.0.key)?; + let mut compressed = GzEncoder::new(file, Compression::fast()); + serde_json::to_writer( + LimitedWriter { + inner: &mut compressed, + remaining: LIMIT, + }, + &Pages { + page_count: preview.page_count, + pages: &preview.pages, + }, + )?; + let mut file = compressed.finish()?; + file.flush()?; + if file.get_ref().metadata()?.len() > LIMIT as u64 { + return Err(io::Error::other("Cached preview exceeds the size limit")); + } + file.get_ref().sync_all()?; + fs::rename(&temporary, &self.0.path) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + } + result + } +} + +fn hash_field(key: &mut Sha256, data: &[u8]) { + key.update((data.len() as u64).to_le_bytes()); + key.update(data); +} + +fn hash_date(key: &mut Sha256, date: Option) { + key.update([u8::from(date.is_some())]); + if let Some(date) = date { + key.update(date.unix_seconds.to_le_bytes()); + key.update(date.nanoseconds.to_le_bytes()); + } +} + +struct LimitedWriter { + inner: W, + remaining: usize, +} + +impl Write for LimitedWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + if buf.len() > self.remaining { + return Err(io::Error::other("Cached preview exceeds the size limit")); + } + let written = self.inner.write(buf)?; + self.remaining -= written; + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } +} diff --git a/examples/native_editor/preview_view.css b/examples/native_editor/preview_view.css index bdb14e3..4edbb36 100644 --- a/examples/native_editor/preview_view.css +++ b/examples/native_editor/preview_view.css @@ -11,6 +11,11 @@ font: 13px/1.3 system-ui, sans-serif; } +.texrra-preview-history { + margin-inline-end: auto; + color: #526577; +} + .texrra-preview-sticky { position: sticky; top: 0;