platform-w2: net change of 2 commits

- platform-w2: written by an agent
- platform-w2: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-27 03:23:17 +00:00
1 parent af9d0b795f
commit 447dae2012
8 files changed
+181 -37

No files matched your search

+12 -6
View File
@@ -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 {
+16 -1
View File
@@ -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]
+17 -7
View File
@@ -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<Result<(), String>> + 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<Picked> {
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<Result<(), String>> {
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<bool, FileError> {
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<u8>) -> 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()
@@ -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::<dyn FnMut() -> Result<JsValue, JsValue>>::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::<dyn FnMut()>::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(())
}
+8 -2
View File
@@ -133,9 +133,15 @@ fn read_later(ctx: &Context, viewport: ViewportId, files: Vec<DroppedFileHandle>
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);
});
}
}
+7 -2
View File
@@ -6,7 +6,7 @@ The crate has three parts:
- **The contract** (all targets): the message kinds and their `<app>:<kind>` 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<String>, 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.<app>.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`.
+11 -10
View File
@@ -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<String> {
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
+13 -9
View File
@@ -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::<dyn Fn(web_sys::MessageEvent)>::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<Message> {
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<FileData> {
}
}
fn object(head: &[(&str, JsValue)], fields: &[(&str, JsValue)]) -> Result<js_sys::Object, String> {
/// Builds one message object so both window transports use the same field encoding.
pub(crate) fn object(head: &[(&str, JsValue)], fields: &[(&str, JsValue)]) -> Result<js_sys::Object, String> {
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<String> {
/// Reads a string field without coercing malformed message data.
pub(crate) fn string(data: &JsValue, key: &str) -> Option<String> {
get(data, key).as_string()
}