From 447dae2012f61ddfa9250156f327dfb77d64a29b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 03:23:17 +0000 Subject: [PATCH] platform-w2: net change of 2 commits - platform-w2: written by an agent - platform-w2: review fixes (review-1) --- crates/host/src/files.rs | 18 ++-- crates/host/src/queue_tests.rs | 17 +++- crates/platform/src/browser_files.rs | 24 +++-- crates/platform/src/browser_files_tests.rs | 97 ++++++++++++++++++++ crates/ui-contract/src/runtime/egui/files.rs | 10 +- crates/web-host/README.md | 9 +- crates/web-host/src/lib.rs | 21 +++-- crates/web-host/src/web.rs | 22 +++-- 8 files changed, 181 insertions(+), 37 deletions(-) diff --git a/crates/host/src/files.rs b/crates/host/src/files.rs index 3311c6da16..a83824ed01 100644 --- a/crates/host/src/files.rs +++ b/crates/host/src/files.rs @@ -312,8 +312,15 @@ pub trait Files: Send + Sync { /// Returns whether the path is a regular file and its byte length before reading. /// Native metadata failures are preserved; browser file systems report unsupported. fn read_metadata(&self, path: &Path) -> Result<(bool, u64), FileError> { - let _ = path; - todo!("sh.F16") + #[cfg(not(target_arch = "wasm32"))] + { + std::fs::metadata(path).map(|metadata| (metadata.is_file(), metadata.len())).map_err(|error| with_path(error, path)) + } + #[cfg(target_arch = "wasm32")] + { + let _ = path; + Err(FileError::Unsupported) + } } /// Reads the whole file at `path`. @@ -534,8 +541,8 @@ impl ScriptedFiles { /// A service that stands in for a page that hosts the app and keeps its file: [`Files::saves_to_page`] answers true. /// Combines with [`in_browser`](ScriptedFiles::in_browser) and [`saving_suggested`](ScriptedFiles::saving_suggested). pub fn hosted(self) -> Self { - let _ = self; - todo!("pf.F16") + self.state().hosted = true; + self } /// Puts a file in memory, for [`Files::read`]. @@ -627,8 +634,7 @@ impl ScriptedFiles { impl Files for ScriptedFiles { fn read_metadata(&self, path: &Path) -> Result<(bool, u64), FileError> { - let _ = path; - todo!("sh.F16") + self.state().files.get(path).map(|bytes| (true, bytes.len() as u64)).ok_or_else(|| FileError::NotFound(path.to_owned())) } fn pick(&self, request: PickRequest) -> PickId { diff --git a/crates/host/src/queue_tests.rs b/crates/host/src/queue_tests.rs index 86565c9792..075b3362d0 100644 --- a/crates/host/src/queue_tests.rs +++ b/crates/host/src/queue_tests.rs @@ -37,7 +37,22 @@ fn drain(queue: &JobQueue<&'static str, &'static str>) -> Vec<&'static str> { std::iter::from_fn(|| queue.try_recv()).map(|Finished { result, .. }| result).collect() } -// A second submit for a waiting key runs only the second job; the first never runs. +/// A second submit for a waiting key runs only the second job; the first never runs. +#[test] +fn a_second_submit_for_a_waiting_key_replaces_the_first() { + let (queue, jobs, _) = queue(1); + let stale_runs = Arc::new(AtomicUsize::new(0)); + let ran = stale_runs.clone(); + queue.submit("preview", Priority::VISIBLE, move |_| { + ran.fetch_add(1, Ordering::Relaxed); + "stale" + }); + let newest = "newest"; + queue.submit("preview", Priority::VISIBLE, move |_| newest); + jobs.run_all(); + assert_eq!(drain(&queue), [newest], "only the replacement result arrives"); + assert_eq!(stale_runs.load(Ordering::Relaxed), 0, "the replaced job never renders"); +} // With two lanes: a key's second job waits until its first ends, while another key's job runs. #[test] diff --git a/crates/platform/src/browser_files.rs b/crates/platform/src/browser_files.rs index 82ff72a55e..c72aeb2347 100644 --- a/crates/platform/src/browser_files.rs +++ b/crates/platform/src/browser_files.rs @@ -100,9 +100,9 @@ impl BrowserFiles { Self { state: Arc::new(Mutex::new(State::default())), wake: Wake::new(wake), limits: PickLimits::DEFAULT, page_save: None } } - /// The service whose [`Files::write`] goes to the page embedding the app (a host that saves the document back - /// itself, as a file manager's viewer does) whenever `save` answers; otherwise, and with no `save`, a write - /// downloads the bytes. + /// The service whose [`Files::save`] and [`Files::write`] go first to the page embedding the app, + /// which keeps the document's file. When `save` answers `None`, the browser picker or download handles the save. + /// Installing this callback makes [`Files::saves_to_page`] true. pub fn page_saves(self, save: impl Fn(&str, &[u8], bool) -> Option> + Send + Sync + 'static) -> Self { Self { page_save: Some(Arc::new(save)), ..self } } @@ -138,7 +138,9 @@ fn mime_for(name: &str) -> &'static str { match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() { Some("png") => "image/png", Some("jpg" | "jpeg") => "image/jpeg", + Some("gif") => "image/gif", Some("pdf") => "application/pdf", + Some("pptx") => "application/vnd.openxmlformats-officedocument.presentationml.presentation", Some("docx") => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", Some("odt") => "application/vnd.oasis.opendocument.text", Some("ott") => "application/vnd.oasis.opendocument.text-template", @@ -180,10 +182,15 @@ fn write_name(path: &Path) -> String { } /// The pick answer when the embedding page took a save, `None` when no page did. -#[allow(dead_code)] // P3(platform-w2): pf.F12 pub(crate) fn page_saved(page: Option<&PageSaveFn>, name: &str, bytes: &[u8], save_as: bool) -> Option { - let _ = (page, name, bytes, save_as); - todo!("pf.F12") + page_answer(page, name, bytes, save_as).map(|answer| match answer { + Ok(()) => Picked::Saved { path: name.into(), file_type: None }, + Err(error) => Picked::Failed(error), + }) +} + +fn page_answer(page: Option<&PageSaveFn>, name: &str, bytes: &[u8], save_as: bool) -> Option> { + page.and_then(|save| save(name, bytes, save_as)) } /// A write's route: the embedding page when `page` answers (`Ok(true)`), else `download` (`Ok(false)`). @@ -194,7 +201,7 @@ pub(crate) fn page_or_download( save_as: bool, download: impl FnOnce() -> Result<(), String>, ) -> Result { - match page.and_then(|save| save(name, bytes, save_as)) { + match page_answer(page, name, bytes, save_as) { Some(answer) => answer.map(|()| true).map_err(FileError::Other), None => download().map(|()| false).map_err(FileError::Other), } @@ -356,6 +363,9 @@ impl Files for BrowserFiles { fn save(&self, request: PickRequest, bytes: Vec) -> PickId { let name = save_name(&request); + if let Some(picked) = page_saved(self.page_save.as_deref(), &name, &bytes, request.save_as) { + return self.answer_now(picked); + } let mime = mime_for(&name); let ext = Path::new(&name) .extension() diff --git a/crates/platform/src/browser_files_tests.rs b/crates/platform/src/browser_files_tests.rs index c2ab10a064..f7e9083d82 100644 --- a/crates/platform/src/browser_files_tests.rs +++ b/crates/platform/src/browser_files_tests.rs @@ -1,6 +1,7 @@ //! The browser save picker's refusal rule (#1246). use craft_host::Picked; +use wasm_bindgen::JsValue; use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure}; use crate::browser_files::{page_or_download, rejected}; @@ -75,3 +76,99 @@ fn a_write_goes_to_the_embedding_page_and_downloads_only_without_one() { ); assert_eq!(downloads, 2, "without a page each write downloads once"); } + +/// A page save must finish inside the gesture and record its file before any picker or download starts. +#[wasm_bindgen_test] +fn a_save_goes_to_the_embedding_page_with_save_as_and_records_its_file() -> Result<(), JsValue> { + use std::cell::Cell; + use std::path::Path; + use std::rc::Rc; + use std::sync::{Arc, Mutex}; + + use craft_host::{Files, PickRequest}; + use js_sys::{Object, Reflect}; + use wasm_bindgen::closure::Closure; + + use crate::browser_files::BrowserFiles; + + struct SavePatches { + window: web_sys::Window, + prototype: JsValue, + original_picker: JsValue, + original_click: JsValue, + } + + impl Drop for SavePatches { + fn drop(&mut self) { + let _ = Reflect::set(&self.window, &JsValue::from_str("showSaveFilePicker"), &self.original_picker); + let _ = Reflect::set(&self.prototype, &JsValue::from_str("click"), &self.original_click); + } + } + + let window = web_sys::window().ok_or_else(|| JsValue::from_str("no browser window"))?; + let picker_key = JsValue::from_str("showSaveFilePicker"); + let original_picker = Reflect::get(&window, &picker_key)?; + let anchor = Reflect::get(&window, &JsValue::from_str("HTMLAnchorElement"))?; + let prototype = Reflect::get(&anchor, &JsValue::from_str("prototype"))?; + let click_key = JsValue::from_str("click"); + let original_click = Reflect::get(&prototype, &click_key)?; + + let picker_calls = Rc::new(Cell::new(0)); + let calls = picker_calls.clone(); + let aborted = Object::new(); + Reflect::set(&aborted, &JsValue::from_str("name"), &JsValue::from_str("AbortError"))?; + let picker = Closure:: Result>::new(move || { + calls.set(calls.get() + 1); + Err(aborted.clone().into()) + }); + let downloads = Rc::new(Cell::new(0)); + let clicks = downloads.clone(); + let click = Closure::::new(move || clicks.set(clicks.get() + 1)); + let _patches = SavePatches { window: window.clone(), prototype: prototype.clone(), original_picker, original_click }; + Reflect::set(&window, &picker_key, picker.as_ref())?; + // Observe the real download path without navigating the test page. + Reflect::set(&prototype, &click_key, click.as_ref())?; + + let received = Arc::new(Mutex::new(Vec::new())); + let received_by_page = received.clone(); + let files = BrowserFiles::new(|| {}).page_saves(move |name, bytes, save_as| { + received_by_page.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((name.to_owned(), bytes.to_vec(), save_as)); + Some(Ok(())) + }); + let name = "Report.pdf"; + let bytes = b"page contents"; + let mut answers = Vec::new(); + for save_as in [false, true] { + let request = PickRequest::save("document").file_name(format!("folder/{name}")).save_as(save_as); + let id = files.save(request, bytes.to_vec()); + answers.push(files.take_answer(id)); + } + let hosted_pickers = picker_calls.get(); + let hosted_downloads = downloads.get(); + + let unhosted = BrowserFiles::new(|| {}).page_saves(|_, _, _| None); + let request = PickRequest::save("document").file_name(name); + let cancelled = unhosted.save(request.clone(), bytes.to_vec()); + // The mock throws AbortError synchronously, so save answers before returning. + let cancelled = unhosted.take_answer(cancelled); + Reflect::set(&window, &picker_key, &JsValue::UNDEFINED)?; + let downloaded = unhosted.save(request, bytes.to_vec()); + let downloaded = unhosted.take_answer(downloaded); + + for answer in answers { + let answer = answer.ok_or_else(|| JsValue::from_str("the page must answer synchronously"))?; + assert!(answer.records_file()); + assert!(matches!(answer, Picked::Saved { path, .. } if path == Path::new(name))); + } + assert_eq!( + *received.lock().unwrap_or_else(std::sync::PoisonError::into_inner), + [false, true].map(|save_as| (name.to_owned(), bytes.to_vec(), save_as)) + ); + assert_eq!(hosted_pickers, 0, "a page save never opens the picker"); + assert_eq!(hosted_downloads, 0, "a page save never downloads"); + assert_eq!(picker_calls.get(), 1, "a page that declines leaves the picker available"); + assert_eq!(cancelled, Some(Picked::Cancelled)); + assert_eq!(downloaded, Some(Picked::Downloaded(name.to_owned()))); + assert_eq!(downloads.get(), 1, "without a page or picker the save downloads once"); + Ok(()) +} diff --git a/crates/ui-contract/src/runtime/egui/files.rs b/crates/ui-contract/src/runtime/egui/files.rs index d09c70cc72..00a371e22e 100644 --- a/crates/ui-contract/src/runtime/egui/files.rs +++ b/crates/ui-contract/src/runtime/egui/files.rs @@ -133,9 +133,15 @@ fn read_later(ctx: &Context, viewport: ViewportId, files: Vec for file in files { let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { - let bytes = file.bytes_async().await.ok(); let name = name_of(file.path()); - post(&ctx, viewport, bytes.map(|bytes| OsFile { name, path: None, mime: String::new(), bytes: Some(bytes.into()) })); + let file = match file.bytes_async().await { + Ok(bytes) => Some(OsFile { name, path: None, mime: String::new(), bytes: Some(bytes.into()) }), + Err(error) => { + log::warn!("couldn't read dropped file {name}: {error}"); + None + } + }; + post(&ctx, viewport, file); }); } } diff --git a/crates/web-host/README.md b/crates/web-host/README.md index 4da95b7e74..1e838ee6e6 100644 --- a/crates/web-host/README.md +++ b/crates/web-host/README.md @@ -6,7 +6,7 @@ The crate has three parts: - **The contract** (all targets): the message kinds and their `:` types, the contract version, how the hosting mode is read from the URL and the canvas, and the clean-up of file names a host passes in. Pure, tested natively. - **The bridge** (`web`, wasm32 only): `Host::connect(app, canvas)` finds the host, `listen` hears its messages, and `post_ready`, `post_save`, `post_dirty`, `post_failed` and `post_handoff` answer it. Only the same-origin parent window is heard and answered; with a parent on another origin the app runs as if unframed. -- **The file service** (`files`, wasm32 only, deprecated): `BrowserFiles::new(wake, max_read)` wraps `craft_platform::browser_files::BrowserFiles`, which holds its picks and saves (`Files::save`). Only `write` is its own: it posts the bytes to the page through the connection `Host::connect` made, or downloads them when no page hosts the app. New code uses the platform service directly. +- **The file service** (`files`, wasm32 only, deprecated): `BrowserFiles::new(wake, max_read)` wraps `craft_platform::browser_files::BrowserFiles`, which holds its picks and saves (`Files::save`). It installs `page_saves` so saves and writes post the bytes through the connection `Host::connect` made; when no page takes a save, the browser picker or download handles it. New code uses the platform service directly. ## Messages @@ -14,7 +14,7 @@ The crate has three parts: |---|---|---|---| | `ready` | app → host | `version`, `appVersion?`, `file?` | the app can take a document; `file: true` means it reads a `File`/`Blob` in slices | | `host` | host → app | `version`, `handoff?` | what the host supports; `handoff: true` means it routes hand-offs | -| `open` | host → app | `name`, and `bytes` or `file` + `size` | open a document as File › Open would | +| `open` | host → app | `name?`, and `bytes` or `file` + `size` | open a document as File › Open would | | `save` | app → host | `name`, `bytes`, `id?`, `saveAs?` | Save, Save As or Export: the host stores the file | | `saved` | host → app | `id` | the save with that `id` is stored; the app clears dirty | | `dirty` | app → host | `dirty` | unsaved changes appeared or went away | @@ -39,6 +39,7 @@ Compatibility with the bridges shipped before this crate: if let Some(host) = craft_web_host::web::Host::connect("pdfcraft", &canvas) { host.listen(move |message| match message { craft_web_host::web::Message::Open { name, data } => { + // name: Option, None when the host sent no usable name. // Check data.size() against the app's limit before copying it in. } craft_web_host::web::Message::Saved { id } => { /* clear dirty for that save */ } @@ -50,3 +51,7 @@ if let Some(host) = craft_web_host::web::Host::connect("pdfcraft", &canvas) { ``` The page command API is [`craft-web-api`](../web-api/README.md) (storytold/craft-libs#413): `window..request` and the command functions. It sits beside these messages. Opening, saving, the document name and the dirty flag stay here. + +## Second window + +A popup link (`popup::PopupOpener`, `popup::PopupPeer`, and `link::WindowLink`) carries app text between an app window and a window it opened, over same-origin `postMessage`, bounded by `link::LinkLimits`. diff --git a/crates/web-host/src/lib.rs b/crates/web-host/src/lib.rs index 5fe5a7549e..26f147febd 100644 --- a/crates/web-host/src/lib.rs +++ b/crates/web-host/src/lib.rs @@ -25,7 +25,9 @@ //! The app is hosted when its URL has `?host=parent` (framed by a same-origin page: messages go //! through `postMessage`) or its canvas has `data-host="page"` (the page runs it directly: //! messages are `CustomEvent`s on the canvas, the fields in `detail`). This module is the contract -//! itself and builds everywhere; `web` (wasm32 only) is the bridge an app's web shell calls, and +//! itself and builds everywhere; `link` carries bounded app text between windows on every target, +//! and `popup` (wasm32 only) connects windows over same-origin `postMessage`. +//! `web` (wasm32 only) is the bridge an app's web shell calls, and //! `files` (wasm32 only) is the `craft_host::Files` service of a web build, whose writes go to the //! page through that bridge when one hosts the app and download otherwise. @@ -149,19 +151,18 @@ pub fn message_type(app: &str, kind: &str) -> String { /// characters dropped, surrounding space trimmed, at most [`MAX_NAME_CHARS`] characters, and /// `fallback` when nothing is left. pub fn file_name(raw: Option<&str>, fallback: &str) -> String { - let base = raw.unwrap_or_default().rsplit(['/', '\\']).next().unwrap_or_default(); - let cleaned: String = base.chars().filter(|c| !c.is_control()).collect(); - let trimmed = cleaned.trim(); - if trimmed.is_empty() || trimmed == "." || trimmed == ".." { - return fallback.to_string(); - } - trimmed.chars().take(MAX_NAME_CHARS).collect() + cleaned_name(raw).unwrap_or_else(|| fallback.to_string()) } /// A file name from a host, cleaned as [`file_name`] cleans it, or `None` when nothing is left. pub fn cleaned_name(raw: Option<&str>) -> Option { - let _ = raw; - todo!("pf.F18") + let base = raw.unwrap_or_default().rsplit(['/', '\\']).next().unwrap_or_default(); + let cleaned: String = base.chars().filter(|c| !c.is_control()).collect(); + let trimmed = cleaned.trim(); + if trimmed.is_empty() || trimmed == "." || trimmed == ".." { + return None; + } + Some(trimmed.chars().take(MAX_NAME_CHARS).collect()) } /// Remember `next` before the send. A page host can, while that send is still diff --git a/crates/web-host/src/web.rs b/crates/web-host/src/web.rs index 9b83e8644a..a75b5c8ca7 100644 --- a/crates/web-host/src/web.rs +++ b/crates/web-host/src/web.rs @@ -14,7 +14,7 @@ use wasm_bindgen::closure::Closure; use wasm_bindgen::{JsCast as _, JsValue}; use web_sys::js_sys; -use crate::{Inbox, Incoming, Mode, Outgoing, VERSION, file_name, message_type}; +use crate::{Inbox, Incoming, Mode, Outgoing, VERSION, cleaned_name, file_name, message_type}; /// A file the host passes in, not yet copied into the app's memory: check its size first. pub enum FileData { @@ -92,6 +92,10 @@ impl Host { return None; } let origin = window.location().origin().ok()?; + // An opaque origin cannot be a postMessage target. + if origin == "null" { + return None; + } // Reading another origin's location throws, which is `None` too. if parent.location().origin().ok()? != origin { return None; @@ -123,7 +127,7 @@ impl Host { Transport::Parent { window, parent, origin } => { let (parent, origin, inbox) = (parent.clone(), origin.clone(), inbox.clone()); let on_message = Closure::::new(move |event: web_sys::MessageEvent| { - if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) { + if !same_source(&event, &parent, &origin) { return; } let data = event.data(); @@ -219,10 +223,8 @@ impl Host { } /// Whether `event` came from `source` at `origin`. -#[allow(dead_code)] // P3(platform-w2): ss.F12 pub(crate) fn same_source(event: &web_sys::MessageEvent, source: &web_sys::Window, origin: &str) -> bool { - let _ = (event, source, origin); - todo!("ss.F12") + event.origin() == origin && event.source().is_some_and(|sender| js_sys::Object::is(&sender, source)) } /// The message a host's object describes, or `None` when a required field is missing. @@ -233,8 +235,8 @@ fn read(kind: Incoming, data: &JsValue) -> Option { handoff: get(data, "handoff").as_bool() == Some(true), }, Incoming::Open => { - let name = file_name(string(data, "name").as_deref(), "document"); - Message::Open { name: Some(name), data: file_data(data)? } // P3(platform-w2): pf.F17 + let name = cleaned_name(string(data, "name").as_deref()); + Message::Open { name, data: file_data(data)? } } Incoming::AttachPdf => { let FileData::Bytes(bytes) = file_data(data)? else { return None }; @@ -284,7 +286,8 @@ fn file_data(data: &JsValue) -> Option { } } -fn object(head: &[(&str, JsValue)], fields: &[(&str, JsValue)]) -> Result { +/// Builds one message object so both window transports use the same field encoding. +pub(crate) fn object(head: &[(&str, JsValue)], fields: &[(&str, JsValue)]) -> Result { let m = js_sys::Object::new(); for (key, value) in head.iter().chain(fields) { js_sys::Reflect::set(&m, &JsValue::from_str(key), value).map_err(|_| "couldn't build the message".to_string())?; @@ -296,7 +299,8 @@ fn get(data: &JsValue, key: &str) -> JsValue { js_sys::Reflect::get(data, &JsValue::from_str(key)).unwrap_or(JsValue::UNDEFINED) } -fn string(data: &JsValue, key: &str) -> Option { +/// Reads a string field without coercing malformed message data. +pub(crate) fn string(data: &JsValue, key: &str) -> Option { get(data, key).as_string() }