web: fix red-team breaks in restore, drop-open, and plot paths

Three attack agents (state-machine tracing, executable input fuzzing,
browser-API review) found two breaks and several degradations; all are
fixed here, with the fuzzer's 22 tests kept as regression suites.

Breaks:
- Untitled tabs (and dot-names like ".dxf") autosave as DXF, but the
  restore name defaulted to .dwg — the worker dispatches its reader by
  the name's extension, so the only copy of unsaved work could never
  be restored and was re-offered forever. recovered_name now uses the
  worker's rsplit('.') convention and defaults extensionless names to
  dxf, matching new-document serialization.
- " (recovered)" stacked one suffix per crash-restore cycle; the
  marker is now stripped idempotently before appending.
- Opening a file (Ctrl+O / OPEN / automation) while a web open was in
  flight clobbered it: the in-flight open's bytes were lost and every
  queued restore prompt stalled for the session. on_open_file now
  refuses while an open is running (web only).

Hardening:
- Escape on the Recover Drawing modal defers instead of deleting the
  only snapshot; the Discard button still removes it.
- A cap-rejected restore enqueue warns in-app and re-offers the next
  snapshot; the drop queue cap rises to 32.
- Exiting mid-round no longer races snapshot removals (deferrals are
  drained, the sweep skips while a round is in flight); closing a tab
  with "Don't save" now also removes its web snapshot; the snapshot
  key derivation is shared via web_autosave_key.
- The plot-preview overlay no longer leaks a full PDF copy per preview
  (the Download closure lives in a replaceable registry).
- A corrupt autosave index.json fails the round/boot instead of
  silently resetting every row; plot pages with non-finite or non-
  positive sheet dimensions error instead of emitting a NaN MediaBox.
- The drop filter accepts dot-less "DWG"/"dxf" names the worker
  parses (same rsplit convention on both gates).
This commit is contained in:
Afonsop committed 2026-09-16 13:56:08 +01:00
1 parent 64160fd68d
commit 3eab00bfbf
35 files changed
+1356 -76

No files matched your search

+5
View File
@@ -2034,6 +2034,11 @@ pub enum Message {
/// Web: delete the offered autosave snapshot (and offer the next, if any).
#[cfg(target_arch = "wasm32")]
WebAutosaveDiscard,
/// Web: close the restore prompt WITHOUT deleting the offered snapshot
/// (Escape/✕): it is simply re-offered on the next boot. Only the
/// Discard button deletes.
#[cfg(target_arch = "wasm32")]
WebAutosaveDefer,
/// Web: the offered snapshot's bytes are in; queue them for the guarded
/// open poll. The OPFS copy is consumed only once that open succeeds.
#[cfg(target_arch = "wasm32")]
+17
View File
@@ -205,6 +205,23 @@ pub(super) fn on_ribbon_tool_click(&mut self, tool_id: String, event: ModuleEven
// Discarded — drop this tab's autosave recovery copy.
#[cfg(not(target_arch = "wasm32"))]
let _ = std::fs::remove_file(self.autosave_target(idx));
// Web counterpart: the OPFS snapshot must go too, or
// the drawing the user just declined to save is
// offered back at the next boot. A snapshot round
// still writing this tab's key would resurrect it
// after the remove, so defer to the round's end
// (the same guard the save flow uses).
#[cfg(target_arch = "wasm32")]
{
let key = Self::web_autosave_key(&self.tabs[idx]);
if self.web_autosave_in_flight {
self.web_autosave_clear_after.push(key);
} else {
wasm_bindgen_futures::spawn_local(async move {
let _ = crate::io::web_autosave::remove(&key).await;
});
}
}
if self.tabs.len() == 1 {
self.tab_counter += 1;
self.tabs[0] =
+80 -26
View File
@@ -995,6 +995,19 @@ impl OpenCADStudio {
// Native: pick a path, then load on a worker thread. Web: the
// browser hands back bytes, so pick + parse in one step and feed
// the shared `FileOpened` handler directly.
// Web guard: a second open (Ctrl+O, the OPEN command, host
// automation) while a drop/restore/picker open is still in flight
// would overwrite `self.opening` — the in-flight open's
// `WebFileOpened` then misses the id check and its bytes are lost,
// and any pending restore prompt stalls for the session. Native
// keeps the old behaviour: its `OpenPathPicked` round-trip is
// guarded downstream.
#[cfg(target_arch = "wasm32")]
if self.opening.is_some() {
self.command_line
.push_info(crate::tf!("An open is already in progress.").as_ref());
return Task::none();
}
#[cfg(not(target_arch = "wasm32"))]
{
Task::perform(crate::io::pick_open_path(), Message::OpenPathPicked)
@@ -1908,12 +1921,7 @@ impl OpenCADStudio {
let mut recent_task = Task::none();
// The name the autosave snapshot for this tab is keyed by — capture it
// before the save re-points `current_path` at the download name.
let autosave_key = self.tabs[i]
.current_path
.as_ref()
.and_then(|path| path.file_name())
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| self.tabs[i].tab_display_name());
let autosave_key = Self::web_autosave_key(&self.tabs[i]);
let saved = match crate::io::save_to_bytes(&self.tabs[i].scene.document, &ext, version) {
Ok(bytes) => {
crate::sys::download_bytes(&filename, &bytes);
@@ -2881,6 +2889,21 @@ impl OpenCADStudio {
}
}
/// The OPFS autosave snapshot key for `tab`: the drawing's display name
/// (the recent copy's name), or the tab title for untitled tabs — the
/// single derivation every web snapshot/remove site must agree on, or a
/// remove misses the snapshot a round wrote (and vice versa).
#[cfg(target_arch = "wasm32")]
pub(super) fn web_autosave_key(
tab: &crate::app::document::DocumentTab,
) -> String {
tab.current_path
.as_ref()
.and_then(|path| path.file_name())
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| tab.tab_display_name())
}
/// Periodic autosave (SAVETIME): write a `.sv$` recovery copy for every
/// dirty tab — beside the file if it's saved, else under the temp dir — at
/// the document's own DWG version. Best-effort and non-destructive: it never
@@ -2936,12 +2959,7 @@ impl OpenCADStudio {
// Key by the drawing's display name (the recent copy's name), so
// the boot scan can compare the two; untitled tabs use the tab
// title, which is what Save would download as.
let name = tab
.current_path
.as_ref()
.and_then(|path| path.file_name())
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| tab.tab_display_name());
let name = Self::web_autosave_key(tab);
let is_dxf = crate::io::source_is_dxf(tab.current_path.as_deref(), &tab.scene.document);
let ext = if is_dxf { "dxf" } else { "dwg" }.to_string();
let version = tab.scene.document.version;
@@ -3081,6 +3099,21 @@ impl OpenCADStudio {
Task::none()
}
/// Defer the offered snapshot (Escape/✕ on the restore modal): unlike
/// Discard the OPFS copy is NOT removed — one stray keystroke must not
/// destroy the only recovery copy — it is simply re-offered on the next
/// boot. The prompt moves on to the next queued snapshot, if any.
#[cfg(target_arch = "wasm32")]
pub(super) fn on_web_autosave_defer(&mut self) -> Task<Message> {
if !self.web_autosave_pending.is_empty() {
self.web_autosave_pending.remove(0);
}
if self.web_autosave_pending.is_empty() {
self.close_active_modal();
}
Task::none()
}
/// The offered snapshot's bytes arrived (or did not). On success the
/// bytes ride the 50 ms poll's guarded open queue — the poll starts an
/// open only when the slot is free, so the recovered drawing can
@@ -3101,7 +3134,19 @@ impl OpenCADStudio {
// (`web_autosave_opened` / the failure hook), not here — the
// poll has not started the open yet, so queueing now would
// show the modal before the recovered drawing loads.
crate::io::web_drop::enqueue_restore(open_name, bytes, key);
// Exception: a rejected enqueue (queue full) means no open
// will ever start for these bytes, so the prompt cycle must
// continue here or stall for the session. The snapshot
// survives in OPFS and is re-offered on the next boot.
if !crate::io::web_drop::enqueue_restore(open_name, bytes, key) {
self.command_line.push_warning(
crate::tf!(
"Autosave copy could not be queued: too many pending opens"
)
.as_ref(),
);
self.queue_next_web_autosave_prompt();
}
Task::none()
}
Err(error) => {
@@ -3128,30 +3173,39 @@ impl OpenCADStudio {
/// Delete the `.sv$` autosave recovery files for all open drawings. They
/// exist only to survive a crash, so a clean save or exit removes them.
pub(in crate::app) fn cleanup_autosaves(&self) {
pub(in crate::app) fn cleanup_autosaves(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
for i in 0..self.tabs.len() {
let _ = std::fs::remove_file(self.autosave_target(i));
}
// Web counterpart: drop each open tab's OPFS snapshot. A tab close is
// not an exit, so this only runs on the explicit exit path; anything
// the teardown race leaves behind is caught by the next boot scan.
// Web counterpart: drop each open tab's OPFS snapshot, plus any
// removes a save deferred while a snapshot round was still writing.
// A tab close is not an exit, so this only runs on the explicit exit
// path; anything the teardown race leaves behind is caught by the
// next boot scan.
#[cfg(target_arch = "wasm32")]
for tab in &self.tabs {
let name = tab
.current_path
.as_ref()
.and_then(|path| path.file_name())
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| tab.tab_display_name());
{
let mut keys = std::mem::take(&mut self.web_autosave_clear_after);
// An in-flight round may still be writing snapshots right now;
// its late writes would land AFTER these removes and resurrect
// exactly what was removed, so the per-tab sweep is pointless in
// that race — skip it entirely (the boot scan bounds leftovers:
// `SNAPSHOT_CAP` eviction discards the oldest overflow).
if !self.web_autosave_in_flight {
for tab in &self.tabs {
keys.push(Self::web_autosave_key(tab));
}
}
wasm_bindgen_futures::spawn_local(async move {
let _ = crate::io::web_autosave::remove(&name).await;
for key in &keys {
let _ = crate::io::web_autosave::remove(key).await;
}
});
}
}
/// Remove the autosave recovery files, then quit the application.
pub(in crate::app) fn exit_app(&self) -> Task<Message> {
pub(in crate::app) fn exit_app(&mut self) -> Task<Message> {
self.cleanup_autosaves();
iced::exit()
}
+12 -5
View File
@@ -846,12 +846,15 @@ impl OpenCADStudio {
// not be clobbered (its bytes are gone once dequeued), so the
// entry goes back to the queue for the next poll tick.
if self.opening.is_some() {
match restore_key {
// A full queue rejects the bytes here; io-side console
// warning only (the drop path has no user-facing
// surface for rejections by design — see QUEUE_CAP).
let _ = match restore_key {
Some(key) => {
crate::io::web_drop::enqueue_restore(name, bytes, key)
}
None => crate::io::web_drop::enqueue_open(name, bytes),
}
};
return Task::none();
}
let state = std::sync::Arc::new(crate::io::OpenProgressState::new(
@@ -1022,6 +1025,8 @@ impl OpenCADStudio {
#[cfg(target_arch = "wasm32")]
Message::WebAutosaveDiscard => self.on_web_autosave_discard(),
#[cfg(target_arch = "wasm32")]
Message::WebAutosaveDefer => self.on_web_autosave_defer(),
#[cfg(target_arch = "wasm32")]
Message::WebAutosaveBytes(name, key, result) => {
self.on_web_autosave_bytes(name, key, result)
}
@@ -7121,11 +7126,13 @@ impl OpenCADStudio {
if self.active_modal == Some(super::ModalKind::RecoveryPrompt) {
return self.update(Message::RecoveryDecline);
}
// Closing the crash-recovery prompt (✕ or Escape) discards
// the offered snapshot — otherwise it would requeue itself.
// Closing the crash-recovery prompt (✕ or Escape) DEFERS:
// one stray keystroke must not delete the only recovery
// copy, so the snapshot survives and is re-offered on the
// next boot. Only the Discard button deletes.
#[cfg(target_arch = "wasm32")]
if self.active_modal == Some(super::ModalKind::AutosaveRestore) {
return self.update(Message::WebAutosaveDiscard);
return self.update(Message::WebAutosaveDefer);
}
// Closing the shortcut editor with un-applied rows needs an
// explicit discard; a second close attempt (or the overlay's
+11
View File
@@ -517,6 +517,17 @@ fn append_pdf_page(
page: &PdfPageInput,
fallback_plot_style: Option<&PlotStyleTable>,
) -> Result<(), String> {
// Paper dimensions are validated like the content coordinates below: a
// NaN/inf/zero sheet (`width < MIN` compares false for NaN) would be
// serialized verbatim into a MediaBox no conforming viewer can display,
// and printpdf's own parser would still accept it.
if !page.paper_w.is_finite()
|| !page.paper_h.is_finite()
|| page.paper_w <= 0.0
|| page.paper_h <= 0.0
{
return Err("plot sheet size is not valid".into());
}
let PlotContent {
wires,
hatches,
+93 -26
View File
@@ -83,24 +83,44 @@ pub(crate) fn cap_evictions(
(entries, evicted)
}
/// The marker `recovered_name` appends (and strips when it is already
/// there, so it never stacks across crash cycles).
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] // unit-tested on native
const RECOVERED_MARKER: &str = " (recovered)";
/// The name a restored drawing carries as a tab and download: the drawing's
/// stem plus " (recovered)" and its own extension (DWG when the stored name
/// has none, matching how autosave serializes untitled tabs). The extension
/// must survive intact because the web parser picks the format from it.
/// stem plus " (recovered)" and its own extension. The extension split
/// follows the WORKER convention (`name.rsplit('.').next()`, the whole name
/// when there is no dot): a dot-file like ".dxf" is a DXF name to the parse
/// worker, and `Path::extension` would misread it as extensionless —
/// restoring DXF bytes under a ".dwg" name jams the restore door. A name
/// with no extension at all defaults to DXF, matching how autosave
/// serializes untitled tabs (`source_is_dxf` → `dwg_source_version.is_none()`).
/// An existing trailing marker is stripped first, so "(recovered)" stacks
/// at most once no matter how many crash cycles re-snapshotted a previously
/// recovered name.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] // unit-tested on native
pub(crate) fn recovered_name(drawing: &str) -> String {
let path = std::path::Path::new(drawing);
let stem = path
.file_stem()
.map(|stem| stem.to_string_lossy().into_owned())
.filter(|stem| !stem.is_empty())
.unwrap_or_else(|| drawing.to_string());
let ext = path
.extension()
.map(|ext| ext.to_string_lossy().into_owned())
.filter(|ext| !ext.is_empty())
.unwrap_or_else(|| "dwg".to_string());
format!("{stem} (recovered).{ext}")
let (head, ext) = match drawing.rsplit_once('.') {
Some((head, ext)) if !ext.is_empty() => (head, ext.to_string()),
// No dot (or a trailing one): the whole name is the stem.
_ => (drawing, "dxf".to_string()),
};
// A hostile stored name must not smuggle path separators into the tab
// title / download name: keep only the final component of the head.
let head = head.rsplit(['/', '\\']).next().unwrap_or_default();
// When the split consumed everything (".dxf") fall back to the whole
// stored name, like `Path::file_stem`'s empty-stem fallback did.
let mut stem = if head.is_empty() {
drawing
} else {
head
};
// Idempotent: strip every trailing marker, then append exactly one.
while let Some(stripped) = stem.strip_suffix(RECOVERED_MARKER) {
stem = stripped;
}
format!("{stem}{RECOVERED_MARKER}.{ext}")
}
/// Overwrite (or create) the snapshot for `name`. The optional thumbnail is
@@ -108,7 +128,7 @@ pub(crate) fn recovered_name(drawing: &str) -> String {
#[cfg(target_arch = "wasm32")]
pub async fn snapshot(name: &str, bytes: &[u8], thumbnail: Option<&[u8]>) -> Result<(), String> {
let directory = autosave_directory(true).await?;
let mut names = read_index(&directory).await;
let mut names = read_index(&directory).await?;
if !names.iter().any(|stored| stored == name) {
names.push(name.to_string());
write_index(&directory, &names).await?;
@@ -140,7 +160,9 @@ pub async fn remove(name: &str) -> Result<(), String> {
.await
.map_err(super::web_recent::js_error);
let _ = JsFuture::from(directory.remove_entry(&thumbnail_key(name))).await;
let mut names = read_index(&directory).await;
// A corrupt index must abort the rewrite (not reset it to `names`),
// or this remove would orphan every other row's snapshot.
let mut names = read_index(&directory).await?;
let before = names.len();
names.retain(|stored| stored != name);
if names.len() != before {
@@ -161,7 +183,9 @@ pub async fn scan() -> Result<Vec<WebAutosaveEntry>, String> {
let directory = autosave_directory(false).await?;
let mut entries = Vec::new();
let mut dead: Vec<String> = Vec::new();
for name in read_index(&directory).await {
// An unreadable index fails the whole boot scan: guessing an empty list
// would cap-evict and remove snapshots the index can no longer name.
for name in read_index(&directory).await? {
let file = match super::web_recent::get_file(&directory, &snapshot_key(&name)).await {
Ok(file) => file,
// Crash between the index and snapshot writes: the row points
@@ -212,12 +236,23 @@ fn thumbnail_key(name: &str) -> String {
}
#[cfg(target_arch = "wasm32")]
async fn read_index(directory: &web_sys::FileSystemDirectoryHandle) -> Vec<String> {
super::web_recent::read_entry(directory, INDEX_KEY)
.await
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
async fn read_index(
directory: &web_sys::FileSystemDirectoryHandle,
) -> Result<Vec<String>, String> {
let bytes = match super::web_recent::read_entry(directory, INDEX_KEY).await {
Ok(bytes) => bytes,
// A missing index is a fresh store.
Err(_) => return Ok(Vec::new()),
};
// An empty (freshly created or truncated) index is an empty store.
if bytes.is_empty() {
return Ok(Vec::new());
}
// A non-empty file that fails to parse is real data we cannot name:
// returning it as empty would let the next write reset the index and
// silently orphan every other row's snapshot. Surface the failure so
// callers skip the round/boot and leave the file untouched.
serde_json::from_slice(&bytes).map_err(|error| error.to_string())
}
#[cfg(target_arch = "wasm32")]
@@ -266,10 +301,42 @@ mod tests {
fn recovered_names_keep_a_parseable_extension() {
assert_eq!(recovered_name("plan.dwg"), "plan (recovered).dwg");
assert_eq!(recovered_name("sketch.dxf"), "sketch (recovered).dxf");
assert_eq!(recovered_name("Drawing1"), "Drawing1 (recovered).dwg");
// Extensionless names (untitled tabs) restore as DXF: that is what
// autosave serializes them as (`source_is_dxf` → no DWG source
// version), and the parse worker dispatches on the final extension.
assert_eq!(recovered_name("Drawing1"), "Drawing1 (recovered).dxf");
// Multi-dot names keep everything but the final extension in the stem.
assert_eq!(recovered_name("a.b.dwg"), "a.b (recovered).dwg");
assert_eq!(recovered_name(""), " (recovered).dwg");
// A dot-file like ".dxf" is a DXF name under the worker's
// `rsplit('.')` convention — the extension must not flip to dwg.
assert_eq!(recovered_name(".dxf"), ".dxf (recovered).dxf");
assert_eq!(recovered_name(".dwg"), ".dwg (recovered).dwg");
assert_eq!(recovered_name(""), " (recovered).dxf");
}
#[test]
fn the_recovered_marker_never_stacks() {
// Restoring sets the tab name to the recovered name; a later
// autosave round snapshots under it. One marker per drawing:
assert_eq!(
recovered_name("plan (recovered).dwg"),
"plan (recovered).dwg"
);
// Idempotent even for names that already stacked (old cycles).
assert_eq!(
recovered_name("plan (recovered) (recovered).dwg"),
"plan (recovered).dwg"
);
// Extensionless stacked names de-stack too, then gain ".dxf".
assert_eq!(
recovered_name("plan (recovered)"),
"plan (recovered).dxf"
);
// A marker embedded in the middle (not a suffix) is left alone.
assert_eq!(
recovered_name("(recovered) plan.dwg"),
"(recovered) plan (recovered).dwg"
);
}
#[test]
+29 -14
View File
@@ -12,7 +12,8 @@ use wasm_bindgen_futures::JsFuture;
/// A stray multi-drop must not grow the queue without bound; extras are
/// rejected with a console warning instead of being silently dropped.
const QUEUE_CAP: usize = 8;
/// Entries are just name+bytes; 32 drawings is a realistic folder drop.
const QUEUE_CAP: usize = 32;
/// One queued open. `restore_key` tags an autosave-restore file so its
/// snapshot is deleted only when THIS open succeeds — matching by identity,
@@ -41,7 +42,9 @@ fn lock_queue() -> std::sync::MutexGuard<'static, VecDeque<QueuedOpen>> {
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn push(entry: QueuedOpen) {
/// Returns `false` (after a console warning) when the queue is full and the
/// entry was NOT stored — the caller decides how to surface the loss.
fn push(entry: QueuedOpen) -> bool {
let name = entry.name.clone();
let mut queue = lock_queue();
if queue.len() >= QUEUE_CAP {
@@ -49,35 +52,40 @@ fn push(entry: QueuedOpen) {
warn(&format!(
"ocs: dropped-file queue full; ignoring \"{name}\""
));
return;
return false;
}
queue.push_back(entry);
true
}
/// Queue already-read drawing bytes (drag-and-drop) for the 50 ms poll to
/// open through the guarded web-picker flow.
pub fn enqueue_open(name: String, bytes: Vec<u8>) {
/// open through the guarded web-picker flow. Returns `false` when the queue
/// is full and the bytes were dropped.
pub fn enqueue_open(name: String, bytes: Vec<u8>) -> bool {
push(QueuedOpen {
name,
bytes,
restore_key: None,
});
})
}
/// Queue an autosave-restore file tagged with its snapshot key.
pub fn enqueue_restore(name: String, bytes: Vec<u8>, restore_key: String) {
/// Queue an autosave-restore file tagged with its snapshot key. Returns
/// `false` when the queue is full and the bytes were dropped (the OPFS
/// snapshot survives; the caller must not wait for an open that will
/// never start).
pub fn enqueue_restore(name: String, bytes: Vec<u8>, restore_key: String) -> bool {
push(QueuedOpen {
name,
bytes,
restore_key: Some(restore_key),
});
})
}
/// JS-callable entry (same shape as `ocs_control_submit`) for hosts that
/// forward drops themselves.
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn ocs_web_drop_file(name: String, bytes: js_sys::Uint8Array) {
enqueue_open(name, bytes.to_vec());
let _ = enqueue_open(name, bytes.to_vec());
}
/// Pop the oldest dropped file that the poll has not started opening yet.
@@ -179,7 +187,10 @@ pub fn install() {
for (name, read) in reads {
match JsFuture::from(read).await {
Ok(buffer) => {
enqueue_open(name, js_sys::Uint8Array::new(&buffer).to_vec())
// A full queue warns on the console; the drop
// handler has no command line to talk to.
let _ =
enqueue_open(name, js_sys::Uint8Array::new(&buffer).to_vec());
}
Err(error) => {
web_sys::console::error_1(&wasm_bindgen::JsValue::from_str(&format!(
@@ -203,7 +214,11 @@ pub fn install() {
}
fn is_drawing_name(name: &str) -> bool {
name.rsplit_once('.').is_some_and(|(_, extension)| {
matches!(extension.to_ascii_lowercase().as_str(), "dwg" | "dxf")
})
// Same convention as the worker's reader dispatch (`rsplit('.').next()`):
// a dot-less name is its own extension, so a file literally named
// "DWG"/"dxf" parses and must not be filtered out here.
matches!(
name.rsplit('.').next().unwrap_or_default().to_ascii_lowercase().as_str(),
"dwg" | "dxf"
)
}
+2
View File
@@ -4608,6 +4608,8 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static
"Autosave copy could not be stored: {error}" => Some(("common", "autosave-copy-could-not-be-stored")),
"Restored \"{}\" from the autosave copy" => Some(("common", "restored-from-the-autosave-copy")),
"Autosave copy could not be read: {error}" => Some(("common", "autosave-copy-could-not-be-read")),
"An open is already in progress." => Some(("common", "an-open-is-already-in-progress")),
"Autosave copy could not be queued: too many pending opens" => Some(("common", "autosave-copy-could-not-be-queued-too-many-pending-opens")),
_ => None,
}
}
+29 -5
View File
@@ -385,9 +385,11 @@ pub fn show_pdf_preview(name: &str, pdf_bytes: &[u8], page_pngs: &[Vec<u8>], tot
let Some(document) = window.document() else {
return;
};
// One preview at a time: a replotted preview replaces its predecessor and
// revokes its blob URLs, so repeated previews cannot stack overlays or
// leak the images underneath.
// One preview at a time: a replotted preview replaces its predecessor,
// revokes its blob URLs and DROPS its Download closure (freeing the full
// PDF copy the closure captured — a `forget()` would leak one per
// preview), so repeated previews cannot stack overlays or leak the
// images underneath.
const OVERLAY_ID: &str = "ocs-plot-preview";
if let Some(previous) = document.get_element_by_id(OVERLAY_ID) {
previous.remove();
@@ -399,6 +401,11 @@ pub fn show_pdf_preview(name: &str, pdf_bytes: &[u8], page_pngs: &[Vec<u8>], tot
{
let _ = web_sys::Url::revoke_object_url(&url);
}
// Take the previous closure out so it destructs BEFORE the new preview
// stores its own: removing the overlay element already released the JS
// handler reference, so this drop is the last one and actually frees
// the captured bytes.
drop(PREVIEW_DOWNLOAD_CLOSURE.with(|slot| slot.borrow_mut().take()));
if page_pngs.is_empty() {
// Rasterisation produced nothing: deliver the PDF itself rather than
// show an empty frame.
@@ -501,13 +508,16 @@ pub fn show_pdf_preview(name: &str, pdf_bytes: &[u8], page_pngs: &[Vec<u8>], tot
let name = name.to_string();
let bytes = pdf_bytes.to_vec();
// A plain FnMut stays usable for every click; the one-shot variant
// throws on the second click, and users click Download twice.
// throws on the second click, and users click Download twice. The
// closure is HELD in a registry (not `forget()`ed): replacing or
// closing the overlay drops it and frees the captured PDF copy,
// while the cloned JS function keeps the live handler working.
let closure: wasm_bindgen::closure::Closure<dyn FnMut()> =
wasm_bindgen::closure::Closure::new(move || {
download_bytes(&name, &bytes);
});
let click: js_sys::Function = closure.as_ref().unchecked_ref::<js_sys::Function>().clone();
closure.forget();
PREVIEW_DOWNLOAD_CLOSURE.with(|slot| *slot.borrow_mut() = Some(closure));
dl.set_onclick(Some(&click));
bar.append_child(&dl).ok();
}
@@ -543,6 +553,20 @@ fn preview_urls() -> &'static std::sync::Mutex<Vec<String>> {
URLS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
}
// The live preview overlay's Download-button closure. The closure captures
// a full copy of the PDF bytes, so `forget()`-ing it would leak one PDF per
// preview; holding it here lets the next `show_pdf_preview` drop and free
// the previous one (the overlay element's removal already released the JS
// handler reference). A thread-local `RefCell` rather than a static
// `Mutex` like `preview_urls`: `Closure` is not `Send`, and the overlay
// only ever lives on the one UI thread.
#[cfg(target_arch = "wasm32")]
thread_local! {
static PREVIEW_DOWNLOAD_CLOSURE:
std::cell::RefCell<Option<wasm_bindgen::closure::Closure<dyn FnMut()>>> =
std::cell::RefCell::new(None);
}
/// Short platform string for bug reports: OS + architecture on the desktop,
/// the browser user-agent on the web.
#[cfg(not(target_arch = "wasm32"))]