mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 02:38:30 -06:00
Web: optional external file providers, disabled by default (#2593)
Adds an optional file-provider bridge for a trusted same-origin CADCraft web host. It is off until the host calls registerProvider. Provider Save and Open transfer single DXF files in memory and refuse drawings with external images or xrefs. Contributed by @alejocapo04.
This commit is contained in:
@@ -22,6 +22,10 @@ Generated-in-code assets are original and have no file to list:
|
||||
- the sample drawings (`crates/engine/src/sample.rs`);
|
||||
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
|
||||
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
|
||||
- the self-contained line drawings/DXF bytes generated by provider regressions in
|
||||
`crates/ui-egui/src/file_provider_app/tests.rs` and
|
||||
`apps/cadcraft-web/src/file_providers/browser_tests.rs` (CADCraft contributors, original test
|
||||
code/data, MIT OR Apache-2.0; no vendor drawing, external image, font or other asset is added).
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
|
||||
Generated
+71
@@ -959,6 +959,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
@@ -1022,6 +1023,12 @@ dependencies = [
|
||||
"wayland-client",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.10.0"
|
||||
@@ -4064,6 +4071,16 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minicov"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
@@ -4263,6 +4280,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
@@ -4798,6 +4824,12 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
||||
|
||||
[[package]]
|
||||
name = "open"
|
||||
version = "5.4.5"
|
||||
@@ -6824,6 +6856,45 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test"
|
||||
version = "0.3.79"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"cast",
|
||||
"js-sys",
|
||||
"libm",
|
||||
"minicov",
|
||||
"nu-ansi-term",
|
||||
"num-traits",
|
||||
"oorandom",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test-macro",
|
||||
"wasm-bindgen-test-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-macro"
|
||||
version = "0.3.79"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-shared"
|
||||
version = "0.2.129"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
|
||||
|
||||
[[package]]
|
||||
name = "wayland-backend"
|
||||
version = "0.3.17"
|
||||
|
||||
@@ -85,6 +85,7 @@ egui = { version = "0.37", default-features = false, features = ["default_fonts"
|
||||
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
|
||||
egui_extras = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
wasm-bindgen-test = "0.3.79"
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui-wgpu = "0.37"
|
||||
# Monotonic time on native and web (performance.now on wasm).
|
||||
|
||||
@@ -37,3 +37,6 @@ wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
||||
wasm-bindgen-test = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Same-origin file-provider bridge. Persistence belongs to the registered provider, not WASM.
|
||||
//!
|
||||
//! Callbacks enqueue commands for a later egui frame. Exporting bytes never acknowledges them.
|
||||
|
||||
use cadcraft_ui_egui::file_providers::{Host, Resource};
|
||||
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure, prelude::wasm_bindgen};
|
||||
|
||||
thread_local! {
|
||||
static CURRENT_CONTEXT: std::cell::RefCell<Option<egui::Context>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
const API: &str = "cadcraftFileProviders";
|
||||
const EVENT: &str = "cadcraft-file-provider";
|
||||
const MAX_BYTES: u32 = 80 * 1024 * 1024;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(catch, js_namespace = Uint8Array, js_name = from)]
|
||||
fn copy_event_bytes(bytes: &[u8]) -> Result<Uint8Array, JsValue>;
|
||||
}
|
||||
|
||||
fn error(message: impl ToString) -> JsValue {
|
||||
JsValue::from_str(&message.to_string())
|
||||
}
|
||||
|
||||
fn object(value: &serde_json::Value) -> Result<JsValue, JsValue> {
|
||||
js_sys::JSON::parse(&value.to_string())
|
||||
}
|
||||
|
||||
fn set(target: &JsValue, key: &str, value: &JsValue) -> Result<(), JsValue> {
|
||||
if Reflect::set(target, &key.into(), value)? { Ok(()) } else { Err(error("file-provider API is not writable")) }
|
||||
}
|
||||
|
||||
// Inspect UTF-16 length before copying a host string into WASM memory.
|
||||
fn bounded_string(value: JsValue, max_units: u32) -> Result<String, JsValue> {
|
||||
let text = value.dyn_into::<js_sys::JsString>().map_err(|_| error("resource fields must be strings"))?;
|
||||
if text.length() > max_units {
|
||||
return Err(error("resource field is too large"));
|
||||
}
|
||||
text.as_string().ok_or_else(|| error("invalid resource field"))
|
||||
}
|
||||
|
||||
fn resource(value: JsValue) -> Result<Resource, JsValue> {
|
||||
if value.is_null() || !value.is_object() || Array::is_array(&value) {
|
||||
return Err(error("resource entries must be objects"));
|
||||
}
|
||||
let entry = value.dyn_into::<Object>()?;
|
||||
let id = bounded_string(Reflect::get(&entry, &"id".into())?, 160)?;
|
||||
let name = bounded_string(Reflect::get(&entry, &"name".into())?, 255)?;
|
||||
let updated = Reflect::get(&entry, &"updatedAt".into())?;
|
||||
let updated_at = if updated.is_undefined() { String::new() } else { bounded_string(updated, 100)? };
|
||||
Ok(Resource { id, name, updated_at })
|
||||
}
|
||||
|
||||
fn wake_later(ctx: &egui::Context) {
|
||||
let fallback = ctx.clone();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
CURRENT_CONTEXT.with(|current| current.borrow().as_ref().unwrap_or(&fallback).request_repaint());
|
||||
});
|
||||
}
|
||||
|
||||
/// Makes the capability discoverable without enabling it or changing the browser's writer.
|
||||
pub fn install(host: Host, ctx: egui::Context) -> Result<(), JsValue> {
|
||||
let window = web_sys::window().ok_or_else(|| error("no window"))?;
|
||||
CURRENT_CONTEXT.with(|current| *current.borrow_mut() = Some(ctx.clone()));
|
||||
if Reflect::has(&window, &API.into())? {
|
||||
// A graphics restart keeps the page capability and pending requests, and renews its wake target.
|
||||
return Ok(());
|
||||
}
|
||||
// A delayed result from an earlier page must never address a new document's request.
|
||||
let crypto = Reflect::get(&window, &"crypto".into())?;
|
||||
let random = Reflect::get(&crypto, &"getRandomValues".into())?.dyn_into::<Function>()?;
|
||||
let nonce = Uint8Array::new_with_length(16);
|
||||
random.call1(&crypto, &nonce)?;
|
||||
host.set_session(nonce.to_vec().iter().map(|byte| format!("{byte:02x}")).collect()).map_err(error)?;
|
||||
|
||||
let api = Object::new();
|
||||
set(&api, "protocolVersion", &1.into())?;
|
||||
set(&api, "app", &"cadcraft".into())?;
|
||||
set(&api, "capabilities", &object(&serde_json::json!(["revisionAck", "externalRecents", "saveDestination", "openBytes"]))?)?;
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let register = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<String, JsValue>>::new(move |id, label, namespace| {
|
||||
let id = bounded_string(id, 160)?;
|
||||
let label = bounded_string(label, 100)?;
|
||||
let namespace = bounded_string(namespace, 160)?;
|
||||
let connection = h.connect(id, label, namespace).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(connection)
|
||||
});
|
||||
set(&api, "registerProvider", register.as_ref())?;
|
||||
register.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let unregister = Closure::<dyn FnMut() -> Result<bool, JsValue>>::new(move || {
|
||||
h.disconnect().map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(true)
|
||||
});
|
||||
set(&api, "unregisterProvider", unregister.as_ref())?;
|
||||
unregister.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let enabled = Closure::<dyn FnMut(JsValue) -> Result<bool, JsValue>>::new(move |value: JsValue| {
|
||||
let value = value.as_bool().ok_or_else(|| error("enabled must be a boolean"))?;
|
||||
h.set_enabled(value).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(true)
|
||||
});
|
||||
set(&api, "setEnabled", enabled.as_ref())?;
|
||||
enabled.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let resources = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |connection, value: JsValue| {
|
||||
let connection = bounded_string(connection, 160)?;
|
||||
if !Array::is_array(&value) {
|
||||
return Err(error("resources must be an array of at most 100 entries"));
|
||||
}
|
||||
let entries = value.dyn_into::<Array>()?;
|
||||
if entries.length() > 100 {
|
||||
return Err(error("resources must be an array of at most 100 entries"));
|
||||
}
|
||||
// Read only bounded metadata; do not copy or serialize arbitrary host properties.
|
||||
let resources = entries.iter().map(resource).collect::<Result<Vec<_>, _>>()?;
|
||||
h.set_resources(&connection, resources).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "setResources", resources.as_ref())?;
|
||||
resources.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let request_open = Closure::<dyn FnMut(JsValue) -> Result<String, JsValue>>::new(move |resource| {
|
||||
let resource = bounded_string(resource, 160)?;
|
||||
let request = h.request_open(&resource).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(request)
|
||||
});
|
||||
set(&api, "requestOpen", request_open.as_ref())?;
|
||||
request_open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let open = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, name, value: JsValue| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let name = bounded_string(name, 255)?;
|
||||
let bytes = value.dyn_into::<Uint8Array>().map_err(|_| error("bytes must be a Uint8Array"))?;
|
||||
if bytes.length() > MAX_BYTES {
|
||||
return Err(error("file exceeds the provider limit"));
|
||||
}
|
||||
h.open(request, name, bytes.to_vec()).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "openResource", open.as_ref())?;
|
||||
open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let cancel_open = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, message| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let message = bounded_string(message, 1024)?;
|
||||
h.cancel_open(request, message).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "cancelOpen", cancel_open.as_ref())?;
|
||||
cancel_open.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let result = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, status, resource| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let status = bounded_string(status, 8)?;
|
||||
let resource = bounded_string(resource, 160)?;
|
||||
h.result(request, status, resource).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "saveResult", result.as_ref())?;
|
||||
result.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let wake = ctx.clone();
|
||||
let dialog = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, destination, name| {
|
||||
let request = bounded_string(request, 160)?;
|
||||
let destination = bounded_string(destination, 8)?;
|
||||
let name = bounded_string(name, 255)?;
|
||||
h.resolve_dialog(&request, &destination, &name).map_err(error)?;
|
||||
wake_later(&wake);
|
||||
Ok(())
|
||||
});
|
||||
set(&api, "resolveSaveDialog", dialog.as_ref())?;
|
||||
dialog.forget();
|
||||
|
||||
let h = host.clone();
|
||||
let snapshot = Closure::<dyn FnMut() -> Result<JsValue, JsValue>>::new(move || object(&h.snapshot()));
|
||||
set(&api, "snapshot", snapshot.as_ref())?;
|
||||
snapshot.forget();
|
||||
set(&window, API, &Object::freeze(&api))?;
|
||||
dispatch(&serde_json::json!({"type": "ready", "protocolVersion": 1}), None)
|
||||
}
|
||||
|
||||
fn dispatch(metadata: &serde_json::Value, bytes: Option<Vec<u8>>) -> Result<(), JsValue> {
|
||||
let detail = object(metadata)?;
|
||||
if let Some(bytes) = bytes {
|
||||
set(&detail, "bytes", ©_event_bytes(&bytes)?.into())?;
|
||||
}
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_detail(&detail);
|
||||
let event = web_sys::CustomEvent::new_with_event_init_dict(EVENT, &init)?;
|
||||
web_sys::window().ok_or_else(|| error("no window"))?.dispatch_event(&event)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn publish(host: &Host) {
|
||||
if host.publish_events_with(dispatch, |error| log::error!("file-provider event delivery failed: {error:?}")) {
|
||||
CURRENT_CONTEXT.with(|current| {
|
||||
if let Some(ctx) = current.borrow().as_ref() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod browser_tests;
|
||||
@@ -0,0 +1,271 @@
|
||||
//! Original, self-contained DXF fixture. Rust closures create genuine JS exceptions; no JS source.
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use cadcraft_engine::{Session, cmd::file};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
|
||||
use serde_json::json;
|
||||
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
fn error(message: impl ToString) -> JsValue {
|
||||
JsValue::from_str(&message.to_string())
|
||||
}
|
||||
fn field(object: &JsValue, name: &str) -> Result<JsValue, JsValue> {
|
||||
Reflect::get(object, &name.into())
|
||||
}
|
||||
fn text(object: &JsValue, name: &str) -> Result<String, JsValue> {
|
||||
field(object, name)?.as_string().ok_or_else(|| error(format!("missing string field {name}")))
|
||||
}
|
||||
fn call(object: &JsValue, name: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
let function = field(object, name)?.dyn_into::<Function>()?;
|
||||
let array = Array::new();
|
||||
for argument in arguments {
|
||||
array.push(argument);
|
||||
}
|
||||
function.apply(object, &array)
|
||||
}
|
||||
|
||||
struct Page {
|
||||
window: web_sys::Window,
|
||||
api: JsValue,
|
||||
host: cadcraft_ui_egui::file_providers::Host,
|
||||
ctx: egui::Context,
|
||||
events: Rc<RefCell<Vec<JsValue>>>,
|
||||
listener: Closure<dyn FnMut(web_sys::Event)>,
|
||||
}
|
||||
impl Page {
|
||||
fn install(app: &CadApp) -> Result<Self, JsValue> {
|
||||
let window = web_sys::window().ok_or_else(|| error("no browser window"))?;
|
||||
if Reflect::has(&window, &super::API.into())? {
|
||||
return Err(error("fixture requires a fresh owned page"));
|
||||
}
|
||||
let host = app.file_providers.clone();
|
||||
let ctx = egui::Context::default();
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = events.clone();
|
||||
let listener = Closure::<dyn FnMut(web_sys::Event)>::new(move |event: web_sys::Event| {
|
||||
if let Ok(event) = event.dyn_into::<web_sys::CustomEvent>() {
|
||||
seen.borrow_mut().push(event.detail());
|
||||
}
|
||||
});
|
||||
window.add_event_listener_with_callback(super::EVENT, listener.as_ref().unchecked_ref())?;
|
||||
let mut page = Self { window, api: JsValue::UNDEFINED, host, ctx, events, listener };
|
||||
super::install(page.host.clone(), page.ctx.clone())?;
|
||||
page.api = field(&page.window, super::API)?;
|
||||
Ok(page)
|
||||
}
|
||||
fn api(&self, method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
call(&self.api, method, arguments)
|
||||
}
|
||||
fn latest(&self, kind: &str) -> Result<JsValue, JsValue> {
|
||||
self.events
|
||||
.borrow()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|event| text(event, "type").is_ok_and(|name| name == kind))
|
||||
.cloned()
|
||||
.ok_or_else(|| error(format!("missing real window event {kind}")))
|
||||
}
|
||||
fn tick(&self, app: &mut CadApp) {
|
||||
self.ctx.run_ui(Default::default(), |ui| app.logic(ui.ctx())).drop_without_applying_deltas();
|
||||
}
|
||||
fn choose(&self, app: &mut CadApp) -> Result<String, JsValue> {
|
||||
let value = app.run("qsave", serde_json::Value::Null).map_err(error)?;
|
||||
value
|
||||
.get("requestId")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| error("qsave did not create a real provider choice"))
|
||||
}
|
||||
fn captured_save(&self, app: &mut CadApp) -> Result<String, JsValue> {
|
||||
let request = self.choose(app)?;
|
||||
super::publish(&self.host);
|
||||
assert_eq!(text(&self.latest("saveDialog")?, "requestId")?, request);
|
||||
self.api("resolveSaveDialog", &[request.clone().into(), "provider".into(), "Fixture.dxf".into()])?;
|
||||
Ok(request)
|
||||
}
|
||||
// Both the injected callback and production publisher are entered through catch-enabled
|
||||
// Function::call0. Restore the exact own descriptor (or remove our inherited-method shadow)
|
||||
// BEFORE assertions, even when an uncaught production exception returns Err from call0.
|
||||
fn with_replacement(&self, target: &JsValue, key: &str, replacement: &JsValue) -> Result<Result<JsValue, JsValue>, JsValue> {
|
||||
let object = field(&js_sys::global(), "Object")?;
|
||||
let descriptor = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
|
||||
let original = field(target, key)?;
|
||||
let host = self.host.clone();
|
||||
let operation = Closure::<dyn FnMut()>::new(move || super::publish(&host));
|
||||
let outcome = match Reflect::set(target, &key.into(), replacement) {
|
||||
Ok(true) => operation.as_ref().unchecked_ref::<Function>().call0(&JsValue::UNDEFINED),
|
||||
Ok(false) => Err(error("injected method is not writable")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
if descriptor.is_undefined() {
|
||||
if !Reflect::delete_property(target.unchecked_ref::<Object>(), &key.into())? {
|
||||
return Err(error("could not remove injected method"));
|
||||
}
|
||||
} else {
|
||||
call(&object, "defineProperty", &[target.clone(), key.into(), descriptor.clone()])?;
|
||||
}
|
||||
let restored = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
|
||||
if field(target, key)? != original || restored.is_undefined() != descriptor.is_undefined() {
|
||||
return Err(error("injected property was not restored exactly"));
|
||||
}
|
||||
if !descriptor.is_undefined() {
|
||||
for attribute in ["value", "get", "set", "writable", "enumerable", "configurable"] {
|
||||
if field(&restored, attribute)? != field(&descriptor, attribute)? {
|
||||
return Err(error("injected property descriptor changed"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
fn fail_copy(&self) -> Result<u32, JsValue> {
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let seen = calls.clone();
|
||||
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |_| {
|
||||
seen.set(seen.get() + 1);
|
||||
Err(js_sys::RangeError::new("synthetic CAD byte-copy failure").into())
|
||||
});
|
||||
let array = field(&js_sys::global(), "Uint8Array")?;
|
||||
self.with_replacement(&array, "from", fault.as_ref())??;
|
||||
Ok(calls.get())
|
||||
}
|
||||
fn fail_dispatch(&self, kind: &str) -> Result<u32, JsValue> {
|
||||
let original = field(&self.window, "dispatchEvent")?.dyn_into::<Function>()?;
|
||||
let window: JsValue = self.window.clone().into();
|
||||
let wanted = kind.to_string();
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let seen = calls.clone();
|
||||
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |event: JsValue| {
|
||||
if text(&field(&event, "detail")?, "type")? == wanted {
|
||||
seen.set(seen.get() + 1);
|
||||
Err(js_sys::RangeError::new("synthetic CAD metadata dispatch failure").into())
|
||||
} else {
|
||||
original.call1(&window, &event)
|
||||
}
|
||||
});
|
||||
self.with_replacement(&self.window, "dispatchEvent", fault.as_ref())??;
|
||||
Ok(calls.get())
|
||||
}
|
||||
}
|
||||
impl Drop for Page {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.window.remove_event_listener_with_callback(super::EVENT, self.listener.as_ref().unchecked_ref());
|
||||
let _ = Reflect::delete_property(self.window.unchecked_ref::<Object>(), &super::API.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn real_window_delivery_recovery_preserves_dxf_and_consumes_actual_cad_actions() -> Result<(), JsValue> {
|
||||
// Production codec hooks, on this fixture's fresh browser page only. Native app fixtures
|
||||
// use cadcraft_io directly and never replace their process-global test hooks.
|
||||
file::set_io(file::IoHooks {
|
||||
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|error| error.to_string()),
|
||||
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|error| error.to_string()),
|
||||
plot: None,
|
||||
});
|
||||
file::set_write_as(|drawing, name, options| {
|
||||
cadcraft_io::write_with(drawing, name, &cadcraft_io::SaveOptions { version: options.version, binary: options.binary })
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
let mut app = CadApp::new(Session::new(), Services { no_file_system: true, ..Default::default() });
|
||||
app.run("line", json!({"points":[[0,0],[10,10]]})).map_err(error)?;
|
||||
let page = Page::install(&app)?;
|
||||
let connection = page.api("registerProvider", &["fixture".into(), "Fixture storage".into(), "account-one".into()])?;
|
||||
let resources = Array::new();
|
||||
for id in ["file-1", "file-2"] {
|
||||
let resource = Object::new();
|
||||
Reflect::set(&resource, &"id".into(), &id.into())?;
|
||||
Reflect::set(&resource, &"name".into(), &"Fixture.dxf".into())?;
|
||||
Reflect::set(&resource, &"updatedAt".into(), &"".into())?;
|
||||
resources.push(&resource);
|
||||
}
|
||||
page.api("setResources", &[connection.clone(), resources.into()])?;
|
||||
let uid = app.session.state().map_err(error)?.uid;
|
||||
let checkpoint = app.session.state().map_err(error)?.saved.clone();
|
||||
let chooser = page.choose(&mut app)?;
|
||||
assert_eq!(page.fail_dispatch("saveDialog")?, 1);
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, chooser);
|
||||
assert!(page.api("resolveSaveDialog", &[chooser.into(), "provider".into(), "Late.dxf".into()]).is_err());
|
||||
assert!(!page.host.busy());
|
||||
assert!(Arc::ptr_eq(&app.session.state().map_err(error)?.saved, &checkpoint));
|
||||
|
||||
let read = page.api("requestOpen", &["file-2".into()])?;
|
||||
assert_eq!(page.fail_dispatch("openRequested")?, 1);
|
||||
let failed_read = page.latest("openFailed")?;
|
||||
assert_eq!(field(&failed_read, "requestId")?, read);
|
||||
assert_eq!(text(&failed_read, "resourceId")?, "file-2");
|
||||
assert_eq!(field(&failed_read, "connectionId")?, connection);
|
||||
assert!(!page.host.busy());
|
||||
|
||||
let failed = page.captured_save(&mut app)?;
|
||||
let later_read = page.api("requestOpen", &["file-2".into()])?;
|
||||
app.set_status("Awaiting the synthetic byte-copy failure");
|
||||
assert_eq!(page.fail_copy()?, 1, "actual catch-enabled production copy must throw exactly once");
|
||||
assert!(!page.events.borrow().iter().any(|event| text(event, "type").is_ok_and(|kind| kind == "save")));
|
||||
assert_eq!(field(&page.latest("openRequested")?, "requestId")?, later_read);
|
||||
assert!(page.api("saveResult", &[failed.clone().into(), "saved".into(), "file-1".into()]).is_err());
|
||||
page.api("cancelOpen", &[later_read, "".into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, failed);
|
||||
let state = app.session.state().map_err(error)?;
|
||||
assert_eq!(state.uid, uid);
|
||||
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &checkpoint));
|
||||
assert!(!page.host.busy() && page.host.bound_document("file-1").is_none());
|
||||
assert!(app.status.as_ref().is_some_and(|(message, _)| message.contains("File provider save failed")));
|
||||
|
||||
let retry = page.captured_save(&mut app)?;
|
||||
assert_ne!(retry, failed);
|
||||
super::publish(&page.host);
|
||||
let saved = page.latest("save")?;
|
||||
assert_eq!(text(&saved, "requestId")?, retry);
|
||||
assert_eq!(text(&saved, "filename")?, "Fixture.dxf");
|
||||
assert_eq!(text(&saved, "documentId")?, uid.to_string());
|
||||
assert_eq!(field(&saved, "connectionId")?, connection);
|
||||
let bytes = field(&saved, "bytes")?.dyn_into::<Uint8Array>()?;
|
||||
assert!(bytes.length() > 0);
|
||||
let drawing = cadcraft_io::read(&bytes.to_vec(), "Fixture.dxf").map_err(error)?;
|
||||
assert_eq!(drawing.model.len(), app.session.state().map_err(error)?.doc.model.len());
|
||||
assert!(!drawing.model.is_empty());
|
||||
assert!(page.host.pending_for(uid) && app.session.state().map_err(error)?.is_dirty());
|
||||
let captured = app.session.state().map_err(error)?.doc.clone();
|
||||
let captured_revision = app.session.state().map_err(error)?.revision;
|
||||
app.run("line", json!({"points":[[20,20],[30,30]]})).map_err(error)?;
|
||||
page.api("saveResult", &[retry.clone().into(), "saved".into(), "file-1".into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
let terminal = page.latest("saved")?;
|
||||
assert_eq!(text(&terminal, "requestId")?, retry);
|
||||
assert_eq!(text(&terminal, "resourceId")?, "file-1");
|
||||
assert_eq!(text(&terminal, "revision")?, captured_revision.to_string());
|
||||
let state = app.session.state().map_err(error)?;
|
||||
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &captured), "ACK owns its snapshot, never later edits");
|
||||
assert_eq!(page.host.bound_document("file-1"), Some(uid));
|
||||
assert!(!page.host.busy());
|
||||
|
||||
let open = page.api("requestOpen", &["file-2".into()])?;
|
||||
super::publish(&page.host);
|
||||
page.api("openResource", &[open.clone(), "Fixture.dxf".into(), bytes.into()])?;
|
||||
page.tick(&mut app);
|
||||
super::publish(&page.host);
|
||||
let opened = page.latest("opened")?;
|
||||
assert_eq!(field(&opened, "requestId")?, open);
|
||||
assert_eq!(text(&opened, "resourceId")?, "file-2");
|
||||
assert_eq!(field(&opened, "connectionId")?, connection);
|
||||
assert_eq!(text(&opened, "namespace")?, "account-one");
|
||||
let imported = app.session.state().map_err(error)?;
|
||||
assert_ne!(imported.uid, uid);
|
||||
assert_eq!(imported.doc.model.len(), drawing.model.len());
|
||||
let original = app.session.docs.iter().find(|doc| doc.uid == uid).ok_or_else(|| error("original drawing was lost on provider open"))?;
|
||||
assert!(original.is_dirty() && Arc::ptr_eq(&original.saved, &captured));
|
||||
assert!(!page.host.busy());
|
||||
page.api("unregisterProvider", &[])?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,6 +15,8 @@ mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod download;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod file_providers;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
@@ -47,6 +49,7 @@ mod web {
|
||||
self.1.drain(&mut self.0);
|
||||
self.0.system_animations = self.3.as_ref().map(|reduced| !reduced.matches());
|
||||
self.0.logic(ctx);
|
||||
crate::file_providers::publish(&self.0.file_providers);
|
||||
let drawing = self.0.session.state().ok();
|
||||
crate::push_title(&mut self.4, drawing.map(|d| d.title.as_str()), drawing.is_some_and(|d| d.is_dirty()), set_page_title);
|
||||
// The crate suppresses duplicates, so reporting after every logic callback
|
||||
@@ -82,6 +85,7 @@ mod web {
|
||||
self.1.take_dropped(ui.ctx());
|
||||
}
|
||||
self.0.ui(ui);
|
||||
crate::file_providers::publish(&self.0.file_providers);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +185,13 @@ mod web {
|
||||
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
|
||||
let control = crate::api::install(cc.egui_ctx.clone());
|
||||
let mut app = CadApp::new(session, services()).with_control(control);
|
||||
// The provider capability is independent of the parent and same-document host modes.
|
||||
// Avoid two hosts competing for the same Save command.
|
||||
if app_bridge.is_none() {
|
||||
if let Err(error) = crate::file_providers::install(app.file_providers.clone(), cc.egui_ctx.clone()) {
|
||||
log::error!("file provider capability could not be installed: {error:?}");
|
||||
}
|
||||
}
|
||||
app.system_languages =
|
||||
web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default();
|
||||
if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) {
|
||||
|
||||
@@ -552,9 +552,23 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
y += 44.0;
|
||||
}
|
||||
let main = Rect::from_min_max(pos2(left.right() + 36.0, r.top() + 40.0), r.max);
|
||||
p.text(main.min, egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
|
||||
let mut local_top = main.top();
|
||||
if app.file_providers.enabled() {
|
||||
let mut provider_ui = ui.new_child(egui::UiBuilder::new().max_rect(main).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
let resource = egui::ScrollArea::vertical()
|
||||
.id_salt("provider-recents")
|
||||
.max_height((r.height() * 0.4).clamp(80.0, 240.0))
|
||||
.show(&mut provider_ui, |ui| app.file_providers.provider_recent_ui(ui))
|
||||
.inner;
|
||||
app.file_providers.device_recent_ui(&mut provider_ui);
|
||||
local_top += provider_ui.min_rect().height() + 20.0;
|
||||
if let Some(resource) = resource {
|
||||
let _ = app.run(crate::menus::PROVIDER_RECENT_OPEN, serde_json::json!({"resource":resource}));
|
||||
}
|
||||
}
|
||||
p.text(pos2(main.left(), local_top), egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
|
||||
let mut recent = None;
|
||||
let mut y = main.top() + 44.0;
|
||||
let mut y = local_top + 44.0;
|
||||
for (i, path) in app.ui.recent_files.iter().enumerate() {
|
||||
let row = Rect::from_min_size(pos2(main.left(), y), vec2((r.right() - main.left() - 36.0).clamp(0.0, 640.0), 42.0));
|
||||
let resp = ui.interact(row, ui.scope_id().with(("recent", i)), Sense::click());
|
||||
|
||||
@@ -68,6 +68,10 @@ impl CadApp {
|
||||
/// about each drawing first and quit once all are dealt with. Returns whether the close has to
|
||||
/// wait (the caller then cancels the window close).
|
||||
pub fn request_quit(&mut self) -> bool {
|
||||
if self.file_providers.busy() {
|
||||
self.set_status("Finish or cancel the pending file provider operation before quitting");
|
||||
return true;
|
||||
}
|
||||
if self.quit_confirmed || !self.session.docs.iter().any(|d| d.is_dirty()) {
|
||||
return false;
|
||||
}
|
||||
@@ -171,6 +175,10 @@ impl CadApp {
|
||||
}
|
||||
|
||||
fn begin_close(&mut self, uids: Vec<u64>) {
|
||||
if self.file_providers.busy() {
|
||||
self.set_status("Finish or cancel the pending file provider operation before closing");
|
||||
return;
|
||||
}
|
||||
if self.closing.is_some() {
|
||||
// A prompt is already open; it has to be answered first.
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! DXF capture over the existing format hooks; no storage backend or filesystem authority.
|
||||
use crate::{CadApp, file_providers::Action};
|
||||
use cadcraft_engine::cmd::file::{self, SaveAs};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(crate) fn save(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
|
||||
let result = capture(app, save_as);
|
||||
if let Err(error) = &result {
|
||||
app.session.echo(error.clone());
|
||||
app.set_status(error.clone());
|
||||
}
|
||||
result
|
||||
}
|
||||
/// Queue a provider read through CadApp::run without creating a filesystem picker.
|
||||
pub(crate) fn open_recent(app: &mut CadApp, params: &Value) -> Result<Value, String> {
|
||||
let result = params
|
||||
.get("resource")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| "a file provider resource ID is required".to_string())
|
||||
.and_then(|resource| app.file_providers.request_open(resource))
|
||||
.map(|request| json!({"pending":"fileProvider","requestId":request}));
|
||||
if let Err(error) = &result {
|
||||
app.session.echo(error.clone());
|
||||
app.set_status(error.clone());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn capture(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
|
||||
let host = app.file_providers.clone();
|
||||
let state = app.session.state().map_err(|e| e.to_string())?;
|
||||
if host.pending_for(state.uid) {
|
||||
return Err("a provider save is already pending for this drawing".into());
|
||||
}
|
||||
if state.block_unsaved() {
|
||||
return Err("save or discard Block Editor changes before saving with a provider".into());
|
||||
}
|
||||
let drawing = state.drawing();
|
||||
// This single-file transfer does not upload external image or drawing bytes.
|
||||
if has_external_files(drawing) {
|
||||
return Err(
|
||||
"DXF references external images or drawings; make a self-contained drawing before provider save (external files are not uploaded)".into(),
|
||||
);
|
||||
}
|
||||
let mut name = host.bound_filename(state.uid).unwrap_or_else(|| match state.title.rsplit_once('.') {
|
||||
Some((_, extension)) if extension.eq_ignore_ascii_case("dxf") => state.title.clone(),
|
||||
Some((stem, extension)) if extension.eq_ignore_ascii_case("dwg") => format!("{stem}.dxf"),
|
||||
_ => format!("{}.dxf", state.title),
|
||||
});
|
||||
if name.trim() == ".dxf" {
|
||||
name = "Drawing.dxf".into();
|
||||
}
|
||||
let bytes = match file::write_as() {
|
||||
Some(writer) => writer(drawing, &name, &SaveAs::default())?,
|
||||
None => (file::io().ok_or("file formats are unavailable")?.write)(drawing, &name)?,
|
||||
};
|
||||
let request = host.begin(vec![state.clone()], state.uid, state.revision, name, bytes, save_as)?;
|
||||
app.set_status("Choose where to save the DXF drawing");
|
||||
Ok(json!({"pending":"fileProvider","requestId":request}))
|
||||
}
|
||||
pub(crate) fn tick(app: &mut CadApp) {
|
||||
let host = app.file_providers.clone();
|
||||
if !host.connected() {
|
||||
return;
|
||||
}
|
||||
for action in host.take_actions() {
|
||||
match action {
|
||||
Action::Save { request, capture, status, resource } => {
|
||||
let alive = app.session.docs.iter().any(|d| d.uid == capture.doc);
|
||||
if status == "saved" {
|
||||
for snapshot in &capture.snapshots {
|
||||
if let Some(doc) = app.session.docs.iter_mut().find(|d| d.uid == snapshot.uid) {
|
||||
doc.saved = snapshot.drawing().clone();
|
||||
doc.path = None;
|
||||
}
|
||||
}
|
||||
app.set_status("Drawing saved with file provider");
|
||||
} else if status == "failed" {
|
||||
app.set_status("File provider save failed; drawing remains unsaved");
|
||||
}
|
||||
host.finish_save(&request, &capture, &status, &resource, alive);
|
||||
}
|
||||
Action::Open { request, resource, name, bytes } => {
|
||||
let result = open_resource(app, &resource, &name, &bytes);
|
||||
if let Err(error) = &result {
|
||||
app.open_failed(error);
|
||||
}
|
||||
host.finish_open(&request, &resource, &name, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
host.refresh(app.session.docs.iter().map(|d| (d.uid, d.revision, d.title.clone(), d.is_dirty())).collect());
|
||||
}
|
||||
|
||||
/// The same modeled dependency boundary applies before provider Save and Open. In particular,
|
||||
/// provider bytes must not reach native OPEN's automatic IMAGE/XREF filesystem loaders.
|
||||
fn has_external_files(drawing: &cadcraft_doc::Drawing) -> bool {
|
||||
drawing
|
||||
.model
|
||||
.iter()
|
||||
.chain(drawing.layouts.iter().flat_map(|layout| layout.entities.iter()))
|
||||
.chain(drawing.blocks.values().flat_map(|block| block.entities.iter()))
|
||||
.any(|entity| matches!(&entity.kind, cadcraft_doc::EntityKind::Image(image) if !image.path.is_empty()))
|
||||
|| drawing.blocks.values().any(|block| block.xref_path.as_ref().is_some_and(|path| !path.is_empty()))
|
||||
}
|
||||
|
||||
fn open_resource(app: &mut CadApp, resource: &str, name: &str, bytes: &[u8]) -> Result<u64, String> {
|
||||
if let Some((index, uid)) =
|
||||
app.file_providers.bound_document(resource).and_then(|uid| app.session.docs.iter().position(|doc| doc.uid == uid).map(|index| (index, uid)))
|
||||
{
|
||||
return app.run("document.switch", json!({"index":index})).map(|_| uid);
|
||||
}
|
||||
// Host admission already bounds these bytes. Preflight with the installed native decoder,
|
||||
// before any document is opened or the unchanged native command follows external paths.
|
||||
// The actual Open still runs through CadApp's existing command route and format hooks.
|
||||
let hooks = file::io().ok_or("file formats are unavailable")?;
|
||||
// `catch_unwind` only helps native builds: a panic aborts on wasm, where this bridge runs, so the
|
||||
// readers must stay panic-free and nothing here may rely on recovering from one.
|
||||
let drawing = std::panic::catch_unwind(|| (hooks.read)(bytes, name)).map_err(|_| "file provider drawing decoder failed".to_string())??;
|
||||
if has_external_files(&drawing) {
|
||||
return Err(
|
||||
"DXF references external images or drawings; open a self-contained drawing with the file provider (external files are not loaded)".into(),
|
||||
);
|
||||
}
|
||||
drop(drawing);
|
||||
app.run("open", json!({"data":file::base64_encode(bytes),"name":name})).and_then(|value| {
|
||||
app.opened(Ok(value));
|
||||
app.session.state().map(|doc| doc.uid).map_err(|error| error.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,210 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use cadcraft_engine::Session;
|
||||
fn pending() -> (CadApp, String, u64) {
|
||||
let app = CadApp::new(Session::new(), crate::Services::default());
|
||||
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
|
||||
let doc = app.session.state().unwrap().clone();
|
||||
let uid = doc.uid;
|
||||
// Lifecycle fixture: a fake capture is isolated from the engine's process-global format hooks.
|
||||
let request = app.file_providers.begin(vec![doc.clone()], uid, doc.revision, "Drawing.dxf".into(), vec![1], false).unwrap();
|
||||
(app, request, uid)
|
||||
}
|
||||
#[test]
|
||||
fn rejected_provider_save_is_reported_without_consuming_the_capture() {
|
||||
let (mut app, _, uid) = pending();
|
||||
let error = save(&mut app, false).unwrap_err();
|
||||
assert!(error.contains("already pending"));
|
||||
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
|
||||
assert_eq!(app.session.log.last(), Some(&error));
|
||||
assert!(app.file_providers.pending_for(uid));
|
||||
}
|
||||
#[test]
|
||||
fn ack_owns_its_document_and_does_not_clean_newer_edits() {
|
||||
let (mut app, request, uid) = pending();
|
||||
app.file_providers.resolve_dialog(&request, "provider", "Drawing.dxf").unwrap();
|
||||
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
|
||||
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
|
||||
app.session.new_drawing(false);
|
||||
app.file_providers.result(request, "saved".into(), "drawing-1".into()).unwrap();
|
||||
tick(&mut app);
|
||||
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
|
||||
assert_eq!(app.file_providers.bound_document("drawing-1"), Some(uid));
|
||||
}
|
||||
#[test]
|
||||
fn device_result_is_terminal_without_claiming_durable_storage() {
|
||||
let (mut app, request, uid) = pending();
|
||||
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
|
||||
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
|
||||
app.file_providers.resolve_dialog(&request, "device", "Drawing.dxf").unwrap();
|
||||
app.file_providers.result(request, "download".into(), String::new()).unwrap();
|
||||
tick(&mut app);
|
||||
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
|
||||
assert!(app.file_providers.bound_document("drawing-1").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_dxf_delivery_failure_preserves_the_owned_drawing_and_later_edits_through_retry() {
|
||||
let mut app = CadApp::new(Session::new(), crate::Services::default());
|
||||
app.run("line", json!({"points":[[0,0],[10,10]]})).unwrap();
|
||||
let host = app.file_providers.clone();
|
||||
host.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
host.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
|
||||
let snapshot = app.session.state().unwrap().clone();
|
||||
let uid = snapshot.uid;
|
||||
let checkpoint = snapshot.saved.clone();
|
||||
// Use the actual native drawing codec without mutating process-global engine hooks.
|
||||
let bytes = cadcraft_io::write(&snapshot.doc, "Owned.dxf").unwrap();
|
||||
assert_eq!(cadcraft_io::read(&bytes, "Owned.dxf").unwrap().model.len(), snapshot.doc.model.len());
|
||||
let request = host.begin(vec![snapshot.clone()], uid, snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
|
||||
host.take_events();
|
||||
host.resolve_dialog(&request, "provider", "Owned.dxf").unwrap();
|
||||
app.run("line", json!({"points":[[20,20],[30,30]]})).unwrap();
|
||||
let later_revision = app.session.state().unwrap().revision;
|
||||
app.session.new_drawing(false);
|
||||
let active = app.session.state().unwrap().uid;
|
||||
assert!(host.publish_events_with(
|
||||
|metadata, bytes| {
|
||||
assert_eq!(metadata["type"], "save");
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert!(bytes.is_some_and(|bytes| !bytes.is_empty()));
|
||||
Err("synthetic native delivery exception")
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert!(host.pending_for(uid));
|
||||
tick(&mut app);
|
||||
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
|
||||
assert_eq!(owned.revision, later_revision);
|
||||
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &checkpoint));
|
||||
assert_eq!(app.session.state().unwrap().uid, active);
|
||||
assert!(app.status.as_ref().unwrap().0.contains("File provider save failed"));
|
||||
assert!(host.result(request.clone(), "saved".into(), "late".into()).is_err());
|
||||
let mut failed = 0;
|
||||
assert!(!host.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert_eq!(metadata["type"], "saveFailed");
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert_eq!(metadata["documentId"], uid.to_string());
|
||||
failed += 1;
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(failed, 1);
|
||||
assert!(!host.busy());
|
||||
let retry_snapshot = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap().clone();
|
||||
let bytes = cadcraft_io::write(&retry_snapshot.doc, "Owned.dxf").unwrap();
|
||||
let retry = host.begin(vec![retry_snapshot.clone()], uid, retry_snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
|
||||
host.take_events();
|
||||
host.resolve_dialog(&retry, "provider", "Owned.dxf").unwrap();
|
||||
assert!(!host.publish_events_with(
|
||||
|metadata, bytes| {
|
||||
assert_eq!(metadata["requestId"], retry);
|
||||
assert_eq!(cadcraft_io::read(&bytes.unwrap(), "Owned.dxf").unwrap().model.len(), retry_snapshot.doc.model.len());
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
let index = app.session.docs.iter().position(|doc| doc.uid == uid).unwrap();
|
||||
app.run("document.switch", json!({"index":index})).unwrap();
|
||||
app.run("line", json!({"points":[[40,40],[50,50]]})).unwrap();
|
||||
let current_revision = app.session.state().unwrap().revision;
|
||||
let back = app.session.docs.iter().position(|doc| doc.uid == active).unwrap();
|
||||
app.run("document.switch", json!({"index":back})).unwrap();
|
||||
host.result(retry.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
tick(&mut app);
|
||||
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
|
||||
assert_eq!(owned.revision, current_revision);
|
||||
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &retry_snapshot.doc));
|
||||
assert_eq!(app.session.state().unwrap().uid, active);
|
||||
assert_eq!(host.bound_document("file-1"), Some(uid));
|
||||
assert_eq!(host.take_events()[0].metadata["type"], "saved");
|
||||
assert!(!host.busy());
|
||||
}
|
||||
|
||||
fn recent_provider_app() -> CadApp {
|
||||
let app = CadApp::new(Session::new(), crate::Services::default());
|
||||
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
let connection = app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
|
||||
app.file_providers
|
||||
.set_resources(
|
||||
&connection,
|
||||
vec![
|
||||
crate::file_providers::Resource { id: "owned".into(), name: "Owned.dxf".into(), updated_at: String::new() },
|
||||
crate::file_providers::Resource { id: "other".into(), name: "Other.dxf".into(), updated_at: String::new() },
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
app.file_providers.take_events();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_recent_command_queues_only_the_selected_resource_without_retargeting_the_drawing() {
|
||||
let mut app = recent_provider_app();
|
||||
let before = app.session.state().unwrap().clone();
|
||||
let local = app.ui.recent_files.clone();
|
||||
assert!(crate::menus::is_ui_command(crate::menus::PROVIDER_RECENT_OPEN));
|
||||
let result = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap();
|
||||
assert_eq!(result["pending"], "fileProvider");
|
||||
let events = app.file_providers.take_events();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].metadata["type"], "openRequested");
|
||||
assert_eq!(events[0].metadata["resourceId"], "owned");
|
||||
assert_eq!(events[0].metadata["requestId"], result["requestId"]);
|
||||
let after = app.session.state().unwrap();
|
||||
assert_eq!((after.uid, after.revision), (before.uid, before.revision));
|
||||
assert!(std::sync::Arc::ptr_eq(&after.doc, &before.doc));
|
||||
assert_eq!(after.path, before.path);
|
||||
assert_eq!(app.ui.recent_files, local);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_recent_command_backpressure_remains_in_status_and_command_history() {
|
||||
let mut app = recent_provider_app();
|
||||
let mut full = false;
|
||||
for _ in 0..128 {
|
||||
if app.file_providers.request_open("owned").is_err() {
|
||||
full = true;
|
||||
break;
|
||||
}
|
||||
app.file_providers.take_events();
|
||||
}
|
||||
assert!(full, "the fixture must reach the actual bounded read capacity");
|
||||
let before = app.session.state().unwrap().clone();
|
||||
let error = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
|
||||
assert!(app.file_providers.take_events().is_empty(), "a refused command cannot publish a partial read");
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| app.logic(ctx));
|
||||
output.textures_delta.clear();
|
||||
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
|
||||
assert_eq!(app.session.log.last(), Some(&error));
|
||||
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_recent_command_rejects_malformed_and_disabled_requests_without_opening_files() {
|
||||
let mut app = CadApp::new(Session::new(), crate::Services::default());
|
||||
let before = app.session.state().unwrap().clone();
|
||||
for params in [Value::Null, json!({}), json!({"resource":42}), json!({"resource":""}), json!({"resource":"owned"})] {
|
||||
assert!(app.run(crate::menus::PROVIDER_RECENT_OPEN, params).is_err());
|
||||
assert!(!app.file_providers.enabled());
|
||||
assert!(app.file_providers.take_events().is_empty());
|
||||
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
|
||||
assert!(std::sync::Arc::ptr_eq(&app.session.state().unwrap().doc, &before.doc));
|
||||
}
|
||||
|
||||
let mut connected = recent_provider_app();
|
||||
let before = connected.session.state().unwrap().clone();
|
||||
let connection = connected.file_providers.snapshot()["connectionId"].clone();
|
||||
connected.file_providers.set_enabled(false).unwrap();
|
||||
connected.file_providers.take_events();
|
||||
let error = connected.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
|
||||
assert!(connected.file_providers.connected() && !connected.file_providers.enabled());
|
||||
assert_eq!(connected.file_providers.snapshot()["connectionId"], connection);
|
||||
assert!(connected.file_providers.take_events().is_empty());
|
||||
assert!(std::sync::Arc::ptr_eq(&connected.session.state().unwrap().doc, &before.doc));
|
||||
assert_eq!(connected.session.log.last(), Some(&error));
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Optional same-origin storage capability. No provider is enabled by default.
|
||||
//!
|
||||
//! Requests own immutable native project captures. A host result never selects a live tab,
|
||||
//! revision, filesystem path or account. This module contains no storage or authentication.
|
||||
use cadcraft_engine::DocState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
const MAX_BYTES: usize = 80 * 1024 * 1024;
|
||||
const MAX_PENDING: usize = 16;
|
||||
const MAX_EVENTS: usize = 64;
|
||||
const MAX_RESOURCES: usize = 100;
|
||||
const EXTENSION: &str = ".dxf";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Resource {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub updated_at: String,
|
||||
}
|
||||
pub struct Event {
|
||||
pub metadata: Value,
|
||||
pub bytes: Option<Vec<u8>>,
|
||||
}
|
||||
impl Event {
|
||||
fn terminal(&self) -> bool {
|
||||
matches!(
|
||||
self.metadata.get("type").and_then(Value::as_str),
|
||||
Some("saved" | "downloaded" | "saveCancelled" | "saveFailed" | "opened" | "openFailed" | "openCancelled")
|
||||
)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Identity {
|
||||
provider_id: String,
|
||||
label: String,
|
||||
namespace: String,
|
||||
}
|
||||
/// The exact states encoded at Save, including a main document's branch tabs where applicable.
|
||||
pub(crate) struct Capture {
|
||||
pub doc: u64,
|
||||
pub revision: u64,
|
||||
pub snapshots: Vec<DocState>,
|
||||
pub name: String,
|
||||
intent: String,
|
||||
destination: String,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
pub(crate) enum Action {
|
||||
Save { request: String, capture: Capture, status: String, resource: String },
|
||||
Open { request: String, resource: String, name: String, bytes: Vec<u8> },
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
enum TerminalOwner {
|
||||
Open,
|
||||
Save,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Terminal {
|
||||
request: String,
|
||||
metadata: Value,
|
||||
owner: TerminalOwner,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
provider: Option<Identity>,
|
||||
enabled: bool,
|
||||
nonce: String,
|
||||
serial: u64,
|
||||
connection: String,
|
||||
resources: Vec<Resource>,
|
||||
bindings: HashMap<u64, String>,
|
||||
names: HashMap<u64, String>,
|
||||
dialogs: HashMap<String, Capture>,
|
||||
pending: HashMap<String, Capture>,
|
||||
// Keep every captured document alias owned until its terminal event can be queued.
|
||||
finishing_saves: HashMap<String, Vec<u64>>,
|
||||
opens: HashMap<String, String>,
|
||||
queued_opens: HashSet<String>,
|
||||
actions: Vec<Action>,
|
||||
// Only captures already admitted in dialogs/pending enter this inbox: at most 16, no bytes.
|
||||
delivery_failures: Vec<Action>,
|
||||
events: Vec<Event>,
|
||||
// At most MAX_PENDING saves plus MAX_PENDING reads; never stores transfer bytes.
|
||||
finished: VecDeque<Terminal>,
|
||||
publishing_terminals: usize,
|
||||
documents: Value,
|
||||
}
|
||||
impl State {
|
||||
fn busy(&self) -> bool {
|
||||
!self.dialogs.is_empty()
|
||||
|| !self.pending.is_empty()
|
||||
|| !self.finishing_saves.is_empty()
|
||||
|| !self.opens.is_empty()
|
||||
|| !self.actions.is_empty()
|
||||
|| !self.delivery_failures.is_empty()
|
||||
|| !self.finished.is_empty()
|
||||
|| self.events.iter().any(Event::terminal)
|
||||
|| self.publishing_terminals != 0
|
||||
}
|
||||
fn next(&mut self, kind: &str) -> Result<String, String> {
|
||||
if self.nonce.is_empty() {
|
||||
return Err("file provider session is not initialized".into());
|
||||
}
|
||||
self.serial = self.serial.checked_add(1).ok_or("file provider request counter exhausted")?;
|
||||
Ok(format!("{}-{kind}-{}", self.nonce, self.serial))
|
||||
}
|
||||
fn event(&mut self, mut metadata: Value, bytes: Option<Vec<u8>>) {
|
||||
if let (Some(provider), Some(fields)) = (&self.provider, metadata.as_object_mut()) {
|
||||
fields.insert("providerId".into(), provider.provider_id.clone().into());
|
||||
fields.insert("namespace".into(), provider.namespace.clone().into());
|
||||
fields.insert("connectionId".into(), self.connection.clone().into());
|
||||
}
|
||||
self.events.push(Event { metadata, bytes });
|
||||
}
|
||||
fn retained_bytes(&self) -> usize {
|
||||
let captures = self.dialogs.values().chain(self.pending.values()).map(|p| p.bytes.as_ref().map_or(0, Vec::len));
|
||||
let events = self.events.iter().map(|e| e.bytes.as_ref().map_or(0, Vec::len));
|
||||
let actions = self.actions.iter().chain(&self.delivery_failures).map(|a| match a {
|
||||
Action::Open { bytes, .. } => bytes.len(),
|
||||
_ => 0,
|
||||
});
|
||||
captures.chain(events).chain(actions).fold(0, usize::saturating_add)
|
||||
}
|
||||
fn pending_for(&self, doc: u64) -> bool {
|
||||
self.dialogs.values().chain(self.pending.values()).any(|c| c.snapshots.iter().any(|d| d.uid == doc))
|
||||
|| self.finishing_saves.values().any(|aliases| aliases.contains(&doc))
|
||||
|| self.actions.iter().any(|a| matches!(a, Action::Save { capture, .. } if capture.snapshots.iter().any(|d| d.uid == doc)))
|
||||
}
|
||||
fn flush_finished(&mut self) {
|
||||
while self.events.len() < MAX_EVENTS {
|
||||
let Some(terminal) = self.finished.pop_front() else { break };
|
||||
self.event(terminal.metadata, None);
|
||||
match terminal.owner {
|
||||
TerminalOwner::Open => {
|
||||
self.opens.remove(&terminal.request);
|
||||
self.queued_opens.remove(&terminal.request);
|
||||
}
|
||||
TerminalOwner::Save => {
|
||||
self.finishing_saves.remove(&terminal.request);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn take_events(&mut self) -> Vec<Event> {
|
||||
let events = std::mem::take(&mut self.events);
|
||||
self.flush_finished();
|
||||
if events.is_empty() { std::mem::take(&mut self.events) } else { events }
|
||||
}
|
||||
fn fail_delivery(&mut self, metadata: &Value) {
|
||||
let Some(request) = metadata.get("requestId").and_then(Value::as_str) else { return };
|
||||
match metadata.get("type").and_then(Value::as_str) {
|
||||
Some(kind @ ("save" | "saveDialog")) => {
|
||||
let capture = if kind == "save" { self.pending.remove(request) } else { self.dialogs.remove(request) };
|
||||
if let Some(mut capture) = capture {
|
||||
capture.bytes = None;
|
||||
self.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
|
||||
self.delivery_failures.push(Action::Save { request: request.into(), capture, status: "failed".into(), resource: String::new() });
|
||||
}
|
||||
}
|
||||
Some("openRequested") if !self.queued_opens.contains(request) => {
|
||||
if let Some(resource) = self.opens.get(request).cloned() {
|
||||
// The terminal can wait behind a full event queue. Reject late payloads
|
||||
// now, while retaining the read's account owner until it can be queued.
|
||||
self.queued_opens.insert(request.into());
|
||||
self.finished.push_back(Terminal {
|
||||
request: request.into(),
|
||||
metadata: json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":"file-provider event delivery failed"}),
|
||||
owner: TerminalOwner::Open,
|
||||
});
|
||||
self.flush_finished();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Host(Arc<Mutex<State>>);
|
||||
struct PublishingBatch {
|
||||
host: Host,
|
||||
terminals: usize,
|
||||
}
|
||||
impl Drop for PublishingBatch {
|
||||
fn drop(&mut self) {
|
||||
let mut state = self.host.state();
|
||||
state.publishing_terminals = state.publishing_terminals.saturating_sub(self.terminals);
|
||||
}
|
||||
}
|
||||
impl Host {
|
||||
fn state(&self) -> MutexGuard<'_, State> {
|
||||
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
pub fn set_session(&self, nonce: String) -> Result<(), String> {
|
||||
let mut s = self.state();
|
||||
if !s.nonce.is_empty() || s.provider.is_some() || !valid_id(&nonce) || nonce.len() < 16 {
|
||||
return Err("invalid or already initialized file provider session".into());
|
||||
}
|
||||
s.nonce = nonce;
|
||||
Ok(())
|
||||
}
|
||||
pub fn connect(&self, provider_id: String, label: String, namespace: String) -> Result<String, String> {
|
||||
if !valid_id(&provider_id) || !valid_label(&label) || !valid_id(&namespace) {
|
||||
return Err("invalid file provider identity".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
let identity = Identity { provider_id, label, namespace };
|
||||
if let Some(current) = &s.provider {
|
||||
return if *current == identity { Ok(s.connection.clone()) } else { Err("unregister before changing provider or account".into()) };
|
||||
}
|
||||
s.connection = s.next("connection")?;
|
||||
s.provider = Some(identity);
|
||||
s.enabled = true;
|
||||
Ok(s.connection.clone())
|
||||
}
|
||||
pub fn disconnect(&self) -> Result<(), String> {
|
||||
let mut s = self.state();
|
||||
if s.busy() {
|
||||
return Err("finish or cancel pending operations and consume completion events before unregistering".into());
|
||||
}
|
||||
s.provider = None;
|
||||
s.enabled = false;
|
||||
s.connection.clear();
|
||||
s.resources.clear();
|
||||
s.bindings.clear();
|
||||
s.names.clear();
|
||||
s.events.clear();
|
||||
s.documents = Value::Null;
|
||||
Ok(())
|
||||
}
|
||||
pub fn connected(&self) -> bool {
|
||||
self.state().provider.is_some()
|
||||
}
|
||||
pub fn enabled(&self) -> bool {
|
||||
let s = self.state();
|
||||
s.provider.is_some() && s.enabled
|
||||
}
|
||||
pub fn set_enabled(&self, enabled: bool) -> Result<(), String> {
|
||||
let mut s = self.state();
|
||||
if s.provider.is_none() {
|
||||
return Err("file provider is not connected".into());
|
||||
}
|
||||
s.enabled = enabled;
|
||||
Ok(())
|
||||
}
|
||||
pub fn busy(&self) -> bool {
|
||||
self.state().busy()
|
||||
}
|
||||
pub fn pending_for(&self, doc: u64) -> bool {
|
||||
self.state().pending_for(doc)
|
||||
}
|
||||
pub fn bound_document(&self, resource: &str) -> Option<u64> {
|
||||
self.state().bindings.iter().find(|(_, r)| r.as_str() == resource).map(|(d, _)| *d)
|
||||
}
|
||||
pub fn bound_filename(&self, doc: u64) -> Option<String> {
|
||||
self.state().names.get(&doc).cloned()
|
||||
}
|
||||
/// Captures are produced synchronously by the editor before this event is issued.
|
||||
pub(crate) fn begin(
|
||||
&self,
|
||||
snapshots: Vec<DocState>,
|
||||
doc: u64,
|
||||
revision: u64,
|
||||
name: String,
|
||||
bytes: Vec<u8>,
|
||||
save_as: bool,
|
||||
) -> Result<String, String> {
|
||||
let mut s = self.state();
|
||||
if s.provider.is_none()
|
||||
|| !s.enabled
|
||||
|| !valid_native_name(&name)
|
||||
|| bytes.is_empty()
|
||||
|| bytes.len() > MAX_BYTES
|
||||
|| s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES
|
||||
|| s.pending_for(doc)
|
||||
|| s.dialogs.len() + s.pending.len() + s.finishing_saves.len() >= MAX_PENDING
|
||||
|| s.events.len() >= MAX_EVENTS
|
||||
|| !snapshots.iter().any(|snapshot| snapshot.uid == doc)
|
||||
{
|
||||
return Err("provider unavailable, a save is pending, or capture exceeds 80 MiB".into());
|
||||
}
|
||||
let request = s.next("dialog")?;
|
||||
let intent = if save_as { "saveAs" } else { "save" }.to_string();
|
||||
s.event(json!({"type":"saveDialog","requestId":request,"documentId":doc.to_string(),"revision":revision.to_string(),"intent":intent,"filename":name}), None);
|
||||
s.dialogs.insert(request.clone(), Capture { doc, revision, snapshots, name, intent, destination: String::new(), bytes: Some(bytes) });
|
||||
Ok(request)
|
||||
}
|
||||
pub fn resolve_dialog(&self, request: &str, destination: &str, name: &str) -> Result<(), String> {
|
||||
if !matches!(destination, "provider" | "device" | "cancel") || (destination != "cancel" && !valid_native_name(name)) {
|
||||
return Err("choose provider, device or cancel and a native project filename".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.events.len() >= MAX_EVENTS {
|
||||
return Err("provider event queue is full".into());
|
||||
}
|
||||
let mut capture = s.dialogs.remove(request).ok_or("unknown or completed save dialog")?;
|
||||
if destination == "cancel" {
|
||||
capture.bytes = None;
|
||||
s.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
|
||||
s.actions.push(Action::Save { request: request.into(), capture, status: "cancel".into(), resource: String::new() });
|
||||
return Ok(());
|
||||
}
|
||||
capture.name = name.into();
|
||||
capture.destination = destination.into();
|
||||
let resource = if capture.intent == "save" { s.bindings.get(&capture.doc).cloned() } else { None };
|
||||
let bytes = capture.bytes.take();
|
||||
s.event(json!({"type":"save","requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"intent":capture.intent,"filename":name,"resourceId":resource,"destination":destination}), bytes);
|
||||
s.pending.insert(request.into(), capture);
|
||||
Ok(())
|
||||
}
|
||||
pub fn result(&self, request: String, status: String, resource: String) -> Result<(), String> {
|
||||
if !matches!(status.as_str(), "saved" | "download" | "failed" | "cancel") || (!resource.is_empty() && !valid_id(&resource)) {
|
||||
return Err("invalid provider result".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
let capture = s.pending.get(&request).ok_or("unknown or completed save request")?;
|
||||
if (status == "saved" && (capture.destination != "provider" || !valid_id(&resource)))
|
||||
|| (status == "download" && capture.destination != "device")
|
||||
{
|
||||
return Err("result does not match the chosen destination".into());
|
||||
}
|
||||
if status == "saved" && s.bindings.iter().any(|(doc, id)| *doc != capture.doc && *id == resource) {
|
||||
return Err("resource is bound to another open document".into());
|
||||
}
|
||||
if status == "saved" && capture.intent == "saveAs" && s.bindings.get(&capture.doc) == Some(&resource) {
|
||||
return Err("Save As must produce a distinct resource".into());
|
||||
}
|
||||
if s.actions.len() >= MAX_PENDING {
|
||||
return Err("provider command queue is full".into());
|
||||
}
|
||||
let capture = s.pending.remove(&request).ok_or("unknown save request")?;
|
||||
s.finishing_saves.insert(request.clone(), capture.snapshots.iter().map(|doc| doc.uid).collect());
|
||||
s.actions.push(Action::Save { request, capture, status, resource });
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_resources(&self, connection: &str, resources: Vec<Resource>) -> Result<(), String> {
|
||||
let mut seen = HashSet::new();
|
||||
if resources.len() > MAX_RESOURCES
|
||||
|| resources.iter().any(|r| !valid_id(&r.id) || !valid_native_name(&r.name) || r.updated_at.len() > 100 || !seen.insert(r.id.clone()))
|
||||
{
|
||||
return Err("invalid native project resource list".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.provider.is_none() || s.connection != connection {
|
||||
return Err("resource list belongs to another connection".into());
|
||||
}
|
||||
s.resources = resources;
|
||||
Ok(())
|
||||
}
|
||||
pub fn request_open(&self, resource: &str) -> Result<String, String> {
|
||||
let mut s = self.state();
|
||||
if !s.enabled
|
||||
|| s.provider.is_none()
|
||||
|| s.opens.len() >= MAX_PENDING
|
||||
|| s.events.len() >= MAX_EVENTS
|
||||
|| !s.resources.iter().any(|r| r.id == resource)
|
||||
{
|
||||
return Err("resource is unavailable in the current provider account".into());
|
||||
}
|
||||
let request = s.next("open")?;
|
||||
s.opens.insert(request.clone(), resource.into());
|
||||
s.event(json!({"type":"openRequested","requestId":request,"resourceId":resource}), None);
|
||||
Ok(request)
|
||||
}
|
||||
pub fn open(&self, request: String, name: String, bytes: Vec<u8>) -> Result<(), String> {
|
||||
if !valid_native_name(&name) || bytes.is_empty() || bytes.len() > MAX_BYTES {
|
||||
return Err("invalid native project resource".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.actions.len() >= MAX_PENDING || s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES {
|
||||
return Err("provider command queue is full".into());
|
||||
}
|
||||
if s.queued_opens.contains(&request) {
|
||||
return Err("open response already queued".into());
|
||||
}
|
||||
let resource = s.opens.get(&request).cloned().ok_or("unknown or completed open request")?;
|
||||
s.queued_opens.insert(request.clone());
|
||||
s.actions.push(Action::Open { request, resource, name, bytes });
|
||||
Ok(())
|
||||
}
|
||||
pub fn cancel_open(&self, request: String, error: String) -> Result<(), String> {
|
||||
if error.len() > 1024 {
|
||||
return Err("invalid open result".into());
|
||||
}
|
||||
let mut s = self.state();
|
||||
if s.queued_opens.contains(&request) {
|
||||
return Err("open response already queued".into());
|
||||
}
|
||||
if s.events.len() >= MAX_EVENTS {
|
||||
return Err("provider event queue is full".into());
|
||||
}
|
||||
let resource = s.opens.remove(&request).ok_or("unknown or completed open request")?;
|
||||
s.event(json!({"type":if error.is_empty(){"openCancelled"}else{"openFailed"},"requestId":request,"resourceId":resource,"error":error}), None);
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn take_actions(&self) -> Vec<Action> {
|
||||
let mut state = self.state();
|
||||
let mut actions = std::mem::take(&mut state.actions);
|
||||
actions.append(&mut state.delivery_failures);
|
||||
actions
|
||||
}
|
||||
pub fn take_events(&self) -> Vec<Event> {
|
||||
self.state().take_events()
|
||||
}
|
||||
/// Failed publication consumes only a still-owned request, never an accepted callback.
|
||||
/// Recovery actions retain captured aliases until the real application produces a terminal.
|
||||
/// Returns whether the platform must request a repaint for failure consumption.
|
||||
pub fn publish_events_with<E>(&self, mut dispatch: impl FnMut(&Value, Option<Vec<u8>>) -> Result<(), E>, mut on_error: impl FnMut(E)) -> bool {
|
||||
let mut failed = false;
|
||||
for _ in 0..2 {
|
||||
let (events, _publishing) = {
|
||||
let mut state = self.state();
|
||||
let events = state.take_events();
|
||||
let terminals = events.iter().filter(|event| event.terminal()).count();
|
||||
state.publishing_terminals = state.publishing_terminals.saturating_add(terminals);
|
||||
(events, PublishingBatch { host: self.clone(), terminals })
|
||||
};
|
||||
if events.is_empty() {
|
||||
break;
|
||||
}
|
||||
for event in events {
|
||||
if let Err(error) = dispatch(&event.metadata, event.bytes) {
|
||||
failed = true;
|
||||
self.state().fail_delivery(&event.metadata);
|
||||
on_error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
failed
|
||||
}
|
||||
pub fn snapshot(&self) -> Value {
|
||||
let s = self.state();
|
||||
json!({"protocolVersion":1,"enabled":s.enabled && s.provider.is_some(),"provider":s.provider.as_ref().map(|p|json!({"id":p.provider_id,"label":p.label,"namespace":p.namespace})),"connectionId":s.connection,"resources":s.resources,"documents":s.documents,"pending":s.busy()})
|
||||
}
|
||||
pub(crate) fn refresh(&self, docs: Vec<(u64, u64, String, bool)>) {
|
||||
let mut s = self.state();
|
||||
let live: HashSet<_> = docs.iter().map(|d| d.0).collect();
|
||||
s.bindings.retain(|id, _| live.contains(id));
|
||||
s.names.retain(|id, _| live.contains(id));
|
||||
s.documents = json!(docs.into_iter().map(|(id,rev,name,dirty)|json!({"id":id.to_string(),"revision":rev.to_string(),"name":name,"dirty":dirty,"resourceId":s.bindings.get(&id)})).collect::<Vec<_>>());
|
||||
}
|
||||
pub(crate) fn finish_save(&self, request: &str, capture: &Capture, status: &str, resource: &str, alive: bool) {
|
||||
let mut s = self.state();
|
||||
if !s.finishing_saves.get(request).is_some_and(|aliases| aliases.contains(&capture.doc))
|
||||
|| s.finished.iter().any(|terminal| terminal.request == request)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if status == "saved" {
|
||||
if alive {
|
||||
s.bindings.insert(capture.doc, resource.into());
|
||||
s.names.insert(capture.doc, capture.name.clone());
|
||||
}
|
||||
s.resources.retain(|r| r.id != resource);
|
||||
s.resources.insert(0, Resource { id: resource.into(), name: capture.name.clone(), updated_at: String::new() });
|
||||
s.resources.truncate(MAX_RESOURCES);
|
||||
}
|
||||
let metadata = json!({"type":match status { "saved"=>"saved", "download"=>"downloaded", "cancel"=>"saveCancelled", _=>"saveFailed" },"requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"resourceId":resource,"filename":capture.name,"documentOpen":alive});
|
||||
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Save });
|
||||
s.flush_finished();
|
||||
}
|
||||
pub(crate) fn finish_open(&self, request: &str, resource: &str, name: &str, result: Result<u64, String>) {
|
||||
let mut s = self.state();
|
||||
if !s.opens.get(request).is_some_and(|owned| owned == resource)
|
||||
|| !s.queued_opens.contains(request)
|
||||
|| s.finished.iter().any(|terminal| terminal.request == request)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let metadata = match result {
|
||||
Ok(doc) => {
|
||||
s.bindings.insert(doc, resource.into());
|
||||
s.names.insert(doc, name.into());
|
||||
json!({"type":"opened","requestId":request,"resourceId":resource,"documentId":doc.to_string()})
|
||||
}
|
||||
Err(error) => json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":bounded_error(&error)}),
|
||||
};
|
||||
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Open });
|
||||
s.flush_finished();
|
||||
}
|
||||
/// Draw the recent lists and return a selected resource; the caller dispatches its command.
|
||||
pub fn recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
|
||||
let selected = self.provider_recent_ui(ui);
|
||||
self.device_recent_ui(ui);
|
||||
selected
|
||||
}
|
||||
pub(crate) fn provider_recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
|
||||
let (label, resources, enabled) = {
|
||||
let s = self.state();
|
||||
(s.provider.as_ref().map(|p| p.label.clone()), s.resources.clone(), s.enabled)
|
||||
};
|
||||
let label = label.filter(|_| enabled)?;
|
||||
ui.add_space(12.0);
|
||||
ui.strong(format!("Recent files — {label}"));
|
||||
if resources.is_empty() {
|
||||
ui.weak("No recent files from this provider");
|
||||
}
|
||||
let mut selected = None;
|
||||
for resource in resources {
|
||||
if ui.button(&resource.name).on_hover_text(&resource.updated_at).clicked() {
|
||||
selected = Some(resource.id);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
selected
|
||||
}
|
||||
pub(crate) fn device_recent_ui(&self, ui: &mut egui::Ui) {
|
||||
if self.enabled() {
|
||||
ui.separator();
|
||||
ui.weak("Recent files on this device");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn bounded_error(message: &str) -> String {
|
||||
let mut error = String::new();
|
||||
for ch in message.chars().filter(|ch| !ch.is_control()) {
|
||||
if error.len().saturating_add(ch.len_utf8()) > 1024 {
|
||||
break;
|
||||
}
|
||||
error.push(ch);
|
||||
}
|
||||
error
|
||||
}
|
||||
fn valid_id(value: &str) -> bool {
|
||||
!value.is_empty() && value.len() <= 160 && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b':'))
|
||||
}
|
||||
fn valid_label(value: &str) -> bool {
|
||||
!value.trim().is_empty() && value.len() <= 100 && !value.chars().any(char::is_control)
|
||||
}
|
||||
fn valid_native_name(value: &str) -> bool {
|
||||
!value.trim().is_empty()
|
||||
&& value.len() <= 255
|
||||
&& !value.chars().any(|c| c.is_control() || matches!(c, '/' | '\\'))
|
||||
&& value.to_ascii_lowercase().ends_with(EXTENSION)
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,518 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use cadcraft_engine::Session;
|
||||
fn host() -> Host {
|
||||
let h = Host::default();
|
||||
h.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
|
||||
h.connect("test".into(), "Test storage".into(), "account-a".into()).unwrap();
|
||||
h
|
||||
}
|
||||
fn capture(h: &Host, save_as: bool) -> (String, u64) {
|
||||
let mut session = Session::new();
|
||||
session.execute("new", &json!({})).unwrap();
|
||||
let doc = session.state().unwrap().clone();
|
||||
let uid = doc.uid;
|
||||
(h.begin(vec![doc.clone()], uid, doc.revision, "example.dxf".into(), vec![1, 2, 3], save_as).unwrap(), uid)
|
||||
}
|
||||
#[test]
|
||||
fn off_until_explicit_registration_and_session_is_single_use() {
|
||||
let h = Host::default();
|
||||
assert!(!h.enabled());
|
||||
assert!(!h.connected());
|
||||
assert!(h.connect("test".into(), "Test".into(), "a".into()).is_err());
|
||||
assert!(host().set_session("0123456789abcdef".into()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn each_save_has_a_choice_and_cancel_never_acknowledges_a_document() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
assert_eq!(h.take_events()[0].metadata["type"], "saveDialog");
|
||||
assert!(h.pending_for(uid));
|
||||
h.resolve_dialog(&request, "cancel", "").unwrap();
|
||||
let actions = h.take_actions();
|
||||
assert!(matches!(&actions[..],[Action::Save { status, .. }] if status == "cancel"));
|
||||
assert!(h.state().bindings.is_empty());
|
||||
assert!(h.result(request, "saved".into(), "file".into()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn durable_ack_owns_its_capture_and_is_single_use() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.take_events();
|
||||
assert!(h.disconnect().is_err());
|
||||
h.resolve_dialog(&request, "provider", "durable.dxf").unwrap();
|
||||
let event = h.take_events().remove(0);
|
||||
assert_eq!(event.metadata["type"], "save");
|
||||
assert_eq!(event.bytes, Some(vec![1, 2, 3]));
|
||||
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
assert!(h.result(request, "saved".into(), "file-1".into()).is_err());
|
||||
assert!(matches!(h.take_actions().as_slice(),[Action::Save { capture,resource,.. }] if capture.doc==uid && resource=="file-1"));
|
||||
}
|
||||
#[test]
|
||||
fn replies_cannot_cross_the_chosen_destination_or_an_open_resource_alias() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.resolve_dialog(&request, "device", "local.dxf").unwrap();
|
||||
assert!(h.result(request.clone(), "saved".into(), "remote".into()).is_err());
|
||||
h.result(request, "download".into(), String::new()).unwrap();
|
||||
h.take_actions();
|
||||
h.take_events();
|
||||
let (request, _) = capture(&h, false);
|
||||
h.state().bindings.insert(uid, "already-open".into());
|
||||
h.resolve_dialog(&request, "provider", "new.dxf").unwrap();
|
||||
assert!(h.result(request, "saved".into(), "already-open".into()).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn unregister_clears_cached_account_documents_before_reconnect() {
|
||||
let h = host();
|
||||
h.state().bindings.insert(42, "account-a-resource".into());
|
||||
h.state().names.insert(42, "Account A.dxf".into());
|
||||
h.refresh(vec![(42, 1, "Account A.dxf".into(), false)]);
|
||||
assert_eq!(h.snapshot()["documents"][0]["resourceId"], "account-a-resource");
|
||||
h.disconnect().unwrap();
|
||||
let disconnected = h.snapshot();
|
||||
assert!(disconnected["documents"].is_null());
|
||||
assert!(disconnected["resources"].as_array().unwrap().is_empty());
|
||||
assert!(h.state().bindings.is_empty());
|
||||
assert!(h.state().names.is_empty());
|
||||
h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
|
||||
assert!(h.snapshot()["documents"].is_null());
|
||||
}
|
||||
#[test]
|
||||
fn resource_reads_and_lists_are_scoped_to_current_account_connection() {
|
||||
let h = host();
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let rows = vec![Resource { id: "file-1".into(), name: "remote.dxf".into(), updated_at: String::new() }];
|
||||
assert!(h.set_resources("another-connection", rows.clone()).is_err());
|
||||
h.set_resources(&connection, rows).unwrap();
|
||||
assert!(h.request_open("unknown").is_err());
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
assert!(h.open("forged".into(), "remote.dxf".into(), vec![1]).is_err());
|
||||
h.open(request.clone(), "remote.dxf".into(), vec![1]).unwrap();
|
||||
assert!(h.open(request.clone(), "remote.dxf".into(), vec![1]).is_err());
|
||||
assert!(h.cancel_open(request.clone(), String::new()).is_err());
|
||||
assert!(h.disconnect().is_err());
|
||||
h.take_actions();
|
||||
h.finish_open(&request, "file-1", "remote.dxf", Err("invalid archive".into()));
|
||||
assert!(h.disconnect().is_err());
|
||||
let completion = h.take_events();
|
||||
assert!(completion.iter().any(|event| event.metadata["type"] == "openFailed" && event.metadata["requestId"] == request));
|
||||
h.disconnect().unwrap();
|
||||
let next = h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
|
||||
assert_ne!(connection, next);
|
||||
assert!(h.set_resources(&connection, Vec::new()).is_err());
|
||||
assert!(h.snapshot()["resources"].as_array().unwrap().is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn names_are_native_filenames_and_resource_ids_are_opaque() {
|
||||
assert!(valid_native_name("with accents áé.dxf"));
|
||||
assert!(!valid_native_name("../project.dxf"));
|
||||
assert!(!valid_native_name("project.svg"));
|
||||
assert!(!valid_id("../../project"));
|
||||
assert!(!valid_native_name("project.dxf\0"));
|
||||
}
|
||||
#[test]
|
||||
fn disabled_provider_does_not_discard_a_capture_already_awaiting_ack() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.set_enabled(false).unwrap();
|
||||
assert!(!h.enabled());
|
||||
assert!(h.pending_for(uid));
|
||||
h.resolve_dialog(&request, "provider", "in-flight.dxf").unwrap();
|
||||
h.result(request, "saved".into(), "file-1".into()).unwrap();
|
||||
assert!(matches!(h.take_actions().as_slice(),[Action::Save { status,.. }] if status=="saved"));
|
||||
}
|
||||
|
||||
fn fill_transport_event_queue(h: &Host) {
|
||||
let mut state = h.state();
|
||||
for ordinal in state.events.len()..MAX_EVENTS {
|
||||
state.event(json!({"type":"queued","ordinal":ordinal}), None);
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal_resource(h: &Host) -> String {
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let filename = format!("Remote{EXTENSION}");
|
||||
h.set_resources(&connection, vec![Resource { id: "file-1".into(), name: filename.clone(), updated_at: String::new() }]).unwrap();
|
||||
filename
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_event_queue_retains_open_terminals_until_ordered_drain() {
|
||||
let h = host();
|
||||
let filename = terminal_resource(&h);
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let success = h.request_open("file-1").unwrap();
|
||||
h.open(success.clone(), filename.clone(), vec![1]).unwrap();
|
||||
let failure = h.request_open("file-1").unwrap();
|
||||
h.open(failure.clone(), filename.clone(), vec![1]).unwrap();
|
||||
h.take_actions();
|
||||
fill_transport_event_queue(&h);
|
||||
h.finish_open(&success, "file-1", &filename, Ok(42));
|
||||
h.finish_open(&failure, "file-1", &filename, Err("é\n".repeat(1000)));
|
||||
h.finish_open(&success, "file-1", &filename, Err("duplicate".into()));
|
||||
h.finish_open("unowned", "file-1", &filename, Ok(99));
|
||||
assert_eq!(h.state().events.len(), MAX_EVENTS);
|
||||
assert_eq!(h.state().finished.len(), 2);
|
||||
assert!(h.disconnect().is_err());
|
||||
let first = h.take_events();
|
||||
assert_eq!(first.len(), MAX_EVENTS);
|
||||
assert!(!first.iter().any(|event| matches!(event.metadata["type"].as_str(), Some("opened" | "openFailed"))));
|
||||
let terminals = h.take_events();
|
||||
assert_eq!(terminals.len(), 2);
|
||||
assert_eq!(terminals[0].metadata["type"], "opened");
|
||||
assert_eq!(terminals[1].metadata["type"], "openFailed");
|
||||
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), [success.as_str(), failure.as_str()]);
|
||||
for event in &terminals {
|
||||
assert_eq!(event.metadata["connectionId"], connection);
|
||||
assert_eq!(event.metadata["namespace"], "account-a");
|
||||
}
|
||||
let error = terminals[1].metadata["error"].as_str().unwrap();
|
||||
assert!(error.len() <= 1024 && error.chars().all(|ch| !ch.is_control()));
|
||||
assert_eq!(h.bound_document("file-1"), Some(42));
|
||||
assert!(!h.busy());
|
||||
assert!(h.take_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_event_queue_retains_save_failure_without_duplicate_or_unowned_terminals() {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
|
||||
h.result(request.clone(), "failed".into(), String::new()).unwrap();
|
||||
let Action::Save { capture, .. } = h.take_actions().remove(0) else { panic!("expected save action") };
|
||||
fill_transport_event_queue(&h);
|
||||
h.finish_save(&request, &capture, "failed", "", true);
|
||||
h.finish_save(&request, &capture, "failed", "", true);
|
||||
h.finish_save("unowned", &capture, "failed", "", true);
|
||||
assert_eq!(h.state().events.len(), MAX_EVENTS);
|
||||
assert_eq!(h.state().finished.len(), 1);
|
||||
assert!(h.pending_for(uid));
|
||||
assert_eq!(h.take_events().len(), MAX_EVENTS);
|
||||
let terminals = h.take_events();
|
||||
assert_eq!(terminals.len(), 1);
|
||||
assert_eq!(terminals[0].metadata["type"], "saveFailed");
|
||||
assert_eq!(terminals[0].metadata["requestId"], request);
|
||||
assert!(!h.pending_for(uid));
|
||||
assert!(!h.busy());
|
||||
assert!(h.take_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_terminals_are_bounded_by_admitted_reads_and_saves() {
|
||||
let h = host();
|
||||
let filename = terminal_resource(&h);
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
for _ in 0..MAX_PENDING {
|
||||
let (request, _) = capture(&h, false);
|
||||
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
|
||||
h.result(request, "failed".into(), String::new()).unwrap();
|
||||
}
|
||||
let saves: Vec<_> = h
|
||||
.take_actions()
|
||||
.into_iter()
|
||||
.map(|action| match action {
|
||||
Action::Save { request, capture, .. } => (request, capture),
|
||||
_ => panic!("expected save action"),
|
||||
})
|
||||
.collect();
|
||||
assert!(h.state().events.len() < MAX_EVENTS);
|
||||
let mut extra = saves[0].1.snapshots.clone();
|
||||
extra[0].uid = u64::MAX;
|
||||
assert!(h.begin(extra, u64::MAX, 1, format!("Extra{EXTENSION}"), vec![1], false).is_err());
|
||||
let mut reads = Vec::new();
|
||||
for _ in 0..MAX_PENDING {
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
h.open(request.clone(), filename.clone(), vec![1]).unwrap();
|
||||
reads.push(request);
|
||||
}
|
||||
h.take_actions();
|
||||
fill_transport_event_queue(&h);
|
||||
for (request, capture) in &saves {
|
||||
h.finish_save(request, capture, "failed", "", true);
|
||||
}
|
||||
for request in &reads {
|
||||
h.finish_open(request, "file-1", &filename, Err("read failed".into()));
|
||||
}
|
||||
assert_eq!(h.state().finished.len(), 2 * MAX_PENDING);
|
||||
assert_eq!(h.state().finishing_saves.len(), MAX_PENDING);
|
||||
assert_eq!(h.state().opens.len(), MAX_PENDING);
|
||||
assert!(h.request_open("file-1").is_err());
|
||||
assert!(h.disconnect().is_err());
|
||||
assert_eq!(h.take_events().len(), MAX_EVENTS);
|
||||
let terminals = h.take_events();
|
||||
assert_eq!(terminals.len(), 2 * MAX_PENDING);
|
||||
let expected: Vec<_> = saves.iter().map(|(request, _)| request.as_str()).chain(reads.iter().map(String::as_str)).collect();
|
||||
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), expected);
|
||||
for event in &terminals {
|
||||
assert_eq!(event.metadata["connectionId"], connection);
|
||||
assert_eq!(event.metadata["namespace"], "account-a");
|
||||
}
|
||||
assert!(!h.busy());
|
||||
assert!(h.take_events().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_target_must_belong_to_its_snapshot_aliases() {
|
||||
let h = host();
|
||||
let (request, _) = capture(&h, false);
|
||||
let snapshots = h.state().dialogs.get(&request).unwrap().snapshots.clone();
|
||||
assert!(h.begin(snapshots, u64::MAX, 1, format!("Other{EXTENSION}"), vec![1], false).is_err());
|
||||
assert!(!h.pending_for(u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_save_delivery_has_a_bounded_inbox_and_keeps_all_captured_aliases() {
|
||||
let h = host();
|
||||
let mut session = Session::new();
|
||||
session.execute("new", &json!({})).unwrap();
|
||||
let first = session.state().unwrap().clone();
|
||||
session.execute("new", &json!({})).unwrap();
|
||||
let alias = session.state().unwrap().clone();
|
||||
let request = h.begin(vec![first.clone(), alias.clone()], first.uid, first.revision, "Captured.dxf".into(), vec![1, 2, 3], false).unwrap();
|
||||
h.take_events();
|
||||
h.resolve_dialog(&request, "provider", "Captured.dxf").unwrap();
|
||||
let name = terminal_resource(&h);
|
||||
for _ in 0..MAX_PENDING {
|
||||
let read = h.request_open("file-1").unwrap();
|
||||
h.open(read, name.clone(), vec![1]).unwrap();
|
||||
}
|
||||
assert!(h.result(request.clone(), "saved".into(), "file-1".into()).unwrap_err().contains("queue is full"));
|
||||
let mut errors = 0;
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, bytes| {
|
||||
if metadata["type"] == "save" {
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert_eq!(bytes, Some(vec![1, 2, 3]));
|
||||
Err("copy failed")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| errors += 1,
|
||||
));
|
||||
assert_eq!(errors, 1);
|
||||
assert_eq!(h.state().actions.len(), MAX_PENDING, "ordinary admission capacity is unchanged");
|
||||
assert_eq!(h.state().delivery_failures.len(), 1);
|
||||
assert!(h.pending_for(first.uid) && h.pending_for(alias.uid));
|
||||
assert!(h.result(request.clone(), "saved".into(), "late".into()).is_err());
|
||||
let actions = h.take_actions();
|
||||
assert_eq!(actions.len(), MAX_PENDING + 1);
|
||||
for action in actions {
|
||||
match action {
|
||||
Action::Save { request: owned, capture, status, resource } => {
|
||||
assert_eq!(owned, request);
|
||||
assert_eq!((capture.doc, capture.revision), (first.uid, first.revision));
|
||||
assert_eq!(capture.snapshots.iter().map(|doc| doc.uid).collect::<Vec<_>>(), vec![first.uid, alias.uid]);
|
||||
assert!(Arc::ptr_eq(&capture.snapshots[0].doc, &first.doc));
|
||||
assert!(capture.bytes.is_none() && resource.is_empty());
|
||||
assert_eq!(status, "failed");
|
||||
h.finish_save(&owned, &capture, &status, &resource, true);
|
||||
}
|
||||
Action::Open { request, resource, name, .. } => h.finish_open(&request, &resource, &name, Err("fixture complete".into())),
|
||||
}
|
||||
}
|
||||
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
|
||||
assert!(!h.busy() && !h.pending_for(first.uid) && !h.pending_for(alias.uid));
|
||||
assert!(h.bound_document("file-1").is_none());
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_and_reentrant_save_results_are_not_replaced_by_delivery_recovery() {
|
||||
for reentrant in [false, true] {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
h.take_events();
|
||||
h.resolve_dialog(&request, "provider", "Original.dxf").unwrap();
|
||||
let failed = h.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert_eq!(metadata["type"], "save");
|
||||
if reentrant {
|
||||
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
Err("dispatch failed after an accepted result")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
assert_eq!(failed, reentrant);
|
||||
assert!(h.state().delivery_failures.is_empty());
|
||||
if !reentrant {
|
||||
assert!(h.pending_for(uid), "successful delivery is not an ACK");
|
||||
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
|
||||
}
|
||||
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected save action") };
|
||||
assert_eq!((owned.as_str(), status.as_str(), resource.as_str()), (request.as_str(), "saved", "file-1"));
|
||||
h.finish_save(&owned, &capture, &status, &resource, true);
|
||||
assert!(h.disconnect().is_err(), "the queued saved terminal still owns its account");
|
||||
assert_eq!(h.take_events()[0].metadata["type"], "saved");
|
||||
assert_eq!(h.bound_document("file-1"), Some(uid));
|
||||
assert!(!h.busy());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_chooser_delivery_preserves_capacity_errors_and_synchronous_resolution() {
|
||||
for accepted in [false, true] {
|
||||
let h = host();
|
||||
let (request, uid) = capture(&h, false);
|
||||
if !accepted {
|
||||
fill_transport_event_queue(&h);
|
||||
assert!(h.resolve_dialog(&request, "provider", "Retry.dxf").is_err());
|
||||
assert!(h.state().dialogs.contains_key(&request));
|
||||
}
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, _| {
|
||||
if metadata["type"] == "saveDialog" {
|
||||
if accepted {
|
||||
h.resolve_dialog(&request, "provider", "Accepted.dxf").unwrap();
|
||||
}
|
||||
Err("chooser delivery failed")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
if accepted {
|
||||
assert!(h.state().pending.contains_key(&request));
|
||||
assert!(h.state().delivery_failures.is_empty());
|
||||
h.result(request.clone(), "failed".into(), String::new()).unwrap();
|
||||
} else {
|
||||
assert!(h.resolve_dialog(&request, "provider", "Late.dxf").is_err());
|
||||
assert_eq!(h.state().delivery_failures.len(), 1);
|
||||
}
|
||||
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected failure action") };
|
||||
assert_eq!(owned, request);
|
||||
assert_eq!(status, "failed");
|
||||
assert!(capture.bytes.is_none());
|
||||
h.finish_save(&owned, &capture, &status, &resource, true);
|
||||
let terminal = h.take_events();
|
||||
assert_eq!(terminal[0].metadata["type"], "saveFailed");
|
||||
assert_eq!(terminal[0].metadata["requestId"], request);
|
||||
assert!(!h.busy() && !h.pending_for(uid));
|
||||
let retry = h.begin(capture.snapshots.clone(), capture.doc, capture.revision, "Retry.dxf".into(), vec![1], false).unwrap();
|
||||
assert_ne!(retry, request);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_read_delivery_releases_only_unconsumed_owners_and_preserves_queued_open() {
|
||||
let h = host();
|
||||
let name = terminal_resource(&h);
|
||||
let failed = h.request_open("file-1").unwrap();
|
||||
let accepted = h.request_open("file-1").unwrap();
|
||||
let mut terminals = Vec::new();
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, _| {
|
||||
if metadata["type"] == "openRequested" {
|
||||
if metadata["requestId"] == accepted {
|
||||
h.open(accepted.clone(), name.clone(), vec![7]).unwrap();
|
||||
}
|
||||
Err("open request delivery failed")
|
||||
} else {
|
||||
terminals.push(metadata.clone());
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(terminals.len(), 1);
|
||||
assert_eq!(terminals[0]["type"], "openFailed");
|
||||
assert_eq!(terminals[0]["requestId"], failed);
|
||||
assert_eq!(terminals[0]["resourceId"], "file-1");
|
||||
assert!(h.open(failed, name.clone(), vec![1]).is_err());
|
||||
let actions = h.take_actions();
|
||||
assert_eq!(actions.len(), 1);
|
||||
let Action::Open { request, resource, name, bytes } = &actions[0] else { panic!("expected accepted open") };
|
||||
assert_eq!(request, &accepted);
|
||||
assert_eq!(bytes.as_slice(), [7]);
|
||||
h.finish_open(request, resource, name, Err("fixture complete".into()));
|
||||
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
|
||||
assert!(!h.busy());
|
||||
let retry = h.request_open("file-1").unwrap();
|
||||
h.cancel_open(retry, String::new()).unwrap();
|
||||
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_batch_and_nested_terminal_delivery_keep_the_original_account_owned() {
|
||||
let h = host();
|
||||
let name = terminal_resource(&h);
|
||||
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
h.open(request.clone(), name.clone(), vec![7]).unwrap();
|
||||
h.take_actions();
|
||||
h.finish_open(&request, "file-1", &name, Ok(42));
|
||||
let mut delivered = Vec::new();
|
||||
assert!(!h.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert!(h.disconnect().is_err());
|
||||
assert_eq!(h.snapshot()["connectionId"], connection);
|
||||
if metadata["type"] == "openRequested" {
|
||||
let nested = h.request_open("file-1").unwrap();
|
||||
h.cancel_open(nested, String::new()).unwrap();
|
||||
assert!(!h.publish_events_with(
|
||||
|_, _| {
|
||||
assert!(h.disconnect().is_err(), "nested delivery cannot release an outer taken terminal");
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert!(h.disconnect().is_err());
|
||||
} else {
|
||||
delivered.push(metadata.clone());
|
||||
}
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(delivered.len(), 1);
|
||||
assert_eq!(delivered[0]["type"], "opened");
|
||||
assert_eq!(delivered[0]["requestId"], request);
|
||||
assert_eq!(delivered[0]["connectionId"], connection);
|
||||
assert_eq!(h.bound_document("file-1"), Some(42));
|
||||
assert!(!h.busy());
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_delivery_recovery_retains_its_terminal_through_a_reentrant_full_event_queue() {
|
||||
let h = host();
|
||||
terminal_resource(&h);
|
||||
let request = h.request_open("file-1").unwrap();
|
||||
assert!(h.publish_events_with(
|
||||
|metadata, _| {
|
||||
if metadata["type"] == "openRequested" {
|
||||
fill_transport_event_queue(&h);
|
||||
Err("delivery failed after another callback filled the queue")
|
||||
} else {
|
||||
assert_eq!(metadata["type"], "queued");
|
||||
assert!(h.disconnect().is_err());
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
|_| {
|
||||
assert!(h.open(request.clone(), "Remote.dxf".into(), vec![1]).is_err(), "a retained failure cannot accept a late payload");
|
||||
assert!(h.cancel_open(request.clone(), String::new()).is_err());
|
||||
},
|
||||
));
|
||||
assert!(h.busy() && h.disconnect().is_err(), "bounded drains leave the undelivered terminal owned for the next call");
|
||||
let mut seen = 0;
|
||||
assert!(!h.publish_events_with(
|
||||
|metadata, _| {
|
||||
assert_eq!(metadata["type"], "openFailed");
|
||||
assert_eq!(metadata["requestId"], request);
|
||||
assert!(h.disconnect().is_err());
|
||||
seen += 1;
|
||||
Ok::<(), &str>(())
|
||||
},
|
||||
|_| {},
|
||||
));
|
||||
assert_eq!(seen, 1);
|
||||
assert!(!h.busy());
|
||||
h.disconnect().unwrap();
|
||||
}
|
||||
@@ -499,6 +499,7 @@
|
||||
One of the Crafting Apps by the ArtCraft team and community. 由 ArtCraft 团队和社区打造的 Crafting 系列应用之一。
|
||||
Oops 恢复已擦除对象
|
||||
Open (⌘O) 打开 (⌘O)
|
||||
Open Provider File 打开提供方文件
|
||||
Open Sample Drawing 打开示例图形
|
||||
Open sample drawing 打开示例图形
|
||||
Open... 打开...
|
||||
|
||||
|
@@ -81,6 +81,8 @@ pub mod vpscale;
|
||||
pub mod wblock;
|
||||
|
||||
pub mod exchange;
|
||||
mod file_provider_app;
|
||||
pub mod file_providers;
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::mpsc::Receiver;
|
||||
@@ -304,6 +306,8 @@ pub struct CadApp {
|
||||
/// The interface's own preferences from the Options dialog ([`options`]).
|
||||
pub options: options::UiOptions,
|
||||
pub services: Services,
|
||||
/// Disabled until an explicit same-origin web host registers a provider.
|
||||
pub file_providers: file_providers::Host,
|
||||
pub canvas: canvas::CanvasState,
|
||||
/// Desktop HID status and navigation preferences; the web host supplies no HID backend.
|
||||
pub spacemouse: spacemouse::State,
|
||||
@@ -414,6 +418,7 @@ impl CadApp {
|
||||
ui: UiState::default(),
|
||||
options: options::UiOptions::default(),
|
||||
services,
|
||||
file_providers: file_providers::Host::default(),
|
||||
canvas: canvas::CanvasState::default(),
|
||||
spacemouse: spacemouse::State::default(),
|
||||
quickcalc: palettes::quickcalc::State::default(),
|
||||
@@ -620,6 +625,9 @@ impl CadApp {
|
||||
|
||||
/// Run a command programmatically (or a UI command).
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
|
||||
if self.file_providers.busy() && matches!(id, "close" | "closeall" | "revert") {
|
||||
return Err("finish or cancel the pending file provider operation before closing or reverting".into());
|
||||
}
|
||||
if let Some(r) = menus::run_ui_command(self, id, ¶ms) {
|
||||
return r;
|
||||
}
|
||||
@@ -1007,6 +1015,7 @@ impl CadApp {
|
||||
/// pass index is zero. `current_pass_index() == 0` is therefore the frame guard: true on the
|
||||
/// first pass and every hidden tick, false on later passes.
|
||||
pub fn logic(&mut self, ctx: &egui::Context) {
|
||||
file_provider_app::tick(self);
|
||||
// Consume-based queues: each item is handled once, whichever callback delivers it. A
|
||||
// reply arriving during a later pass is never starved until the next frame.
|
||||
self.drain_control(ctx);
|
||||
|
||||
@@ -74,6 +74,8 @@ pub const OPEN_RECENT: &str = "Open Recent";
|
||||
pub const CLEAR_RECENT: &str = "Clear Recent Files";
|
||||
const RECENT_ITEM: &str = "ui.recent.";
|
||||
pub const RECENT_CLEAR: &str = "ui.recent.clear";
|
||||
/// Open a resource from the registered provider through the ordinary application command route.
|
||||
pub const PROVIDER_RECENT_OPEN: &str = "ui.provider.open";
|
||||
|
||||
/// UI-only commands: (id, label, menu path, shortcut).
|
||||
pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
@@ -83,6 +85,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
("ui.dock", "Arrange Panel", &[], None),
|
||||
("ui.dock.reset", "Reset Panel Layout", &["Window", "Reset Panel Layout"], None),
|
||||
("ui.open", "Open...", &[], Some("Cmd+O")),
|
||||
(PROVIDER_RECENT_OPEN, "Open Provider File", &[], None),
|
||||
("ui.newtemplate", "New from Template...", &["File", "New from Template..."], None),
|
||||
("ui.saveas", "Save As...", &[], None),
|
||||
("ui.sample", "Open Sample Drawing", &["Help", "Open Sample Drawing"], None),
|
||||
@@ -211,6 +214,19 @@ fn run_recent_file_command(app: &mut CadApp, id: &str) -> Option<Result<Value, S
|
||||
None
|
||||
}
|
||||
|
||||
fn run_provider_file_command(app: &mut CadApp, id: &str, params: &Value, no_path: bool) -> Option<Result<Value, String>> {
|
||||
let result = match id {
|
||||
PROVIDER_RECENT_OPEN => crate::file_provider_app::open_recent(app, params),
|
||||
"ui.saveas" | "saveas" if no_path && app.file_providers.enabled() => match suggested_save_format(params, crate::SaveFormat::Dxf) {
|
||||
Ok(crate::SaveFormat::Dxf) => crate::file_provider_app::save(app, true),
|
||||
Ok(crate::SaveFormat::Dwg) => return None,
|
||||
Err(error) => Err(error),
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
Some(result)
|
||||
}
|
||||
|
||||
fn run_preference_command(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
let r = match id {
|
||||
"ui.theme.system" | "ui.theme.light" | "ui.theme.dark" => {
|
||||
@@ -387,12 +403,31 @@ fn should_pick_file_path(id: &str, params: &Value) -> bool {
|
||||
/// content asks first. `None` lets the engine save. JSON calls carry params and never get here;
|
||||
/// they report the loss in their result instead.
|
||||
fn user_qsave(app: &mut CadApp) -> Option<Result<Value, String>> {
|
||||
if app.file_providers.enabled() {
|
||||
return Some(crate::file_provider_app::save(app, false));
|
||||
}
|
||||
if app.session.state().is_ok_and(|s| s.path.is_none()) {
|
||||
return run_ui_command(app, "ui.saveas", &Value::Null);
|
||||
}
|
||||
app.hold_lossy_save().then_some(Ok(Value::Null))
|
||||
}
|
||||
|
||||
fn run_settings_and_close_command(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
if let Some(result) = run_preference_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_ui_toggle_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_language_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_close_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
if let Some(result) = route_ui_subsystems(app, id, params) {
|
||||
return Some(result);
|
||||
@@ -404,16 +439,10 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re
|
||||
if let Some(result) = run_recent_file_command(app, id) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_preference_command(app, id, params) {
|
||||
if let Some(result) = run_settings_and_close_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_ui_toggle_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_language_command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
if let Some(result) = run_close_command(app, id, params) {
|
||||
if let Some(result) = run_provider_file_command(app, id, params, no_path) {
|
||||
return Some(result);
|
||||
}
|
||||
// FIND typed, or chosen from Edit ▸ Find..., opens the window; a JSON call carries `find`
|
||||
@@ -807,8 +836,16 @@ pub fn menu_bar(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
// Titles first, so a hovered title can take over before any menu is drawn.
|
||||
let titles: Vec<egui::Response> = tree.iter().map(|(name, _)| ui.add(egui::Button::new(crate::i18n::menu(name)))).collect();
|
||||
switch_on_hover(ui.ctx(), &titles);
|
||||
for ((_, entries), title) in tree.iter().zip(&titles) {
|
||||
for ((menu, entries), title) in tree.iter().zip(&titles) {
|
||||
egui::Popup::menu(title).show(|ui| {
|
||||
if menu == "File" && app.file_providers.enabled() {
|
||||
let resource = ui.menu_button("Open Recent — file provider", |ui| app.file_providers.recent_ui(ui)).inner.flatten();
|
||||
if let Some(resource) = resource
|
||||
&& app.run(PROVIDER_RECENT_OPEN, json!({"resource":resource})).is_ok()
|
||||
{
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
for e in entries {
|
||||
entry_ui(ui, e, &mut clicked);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
//! Real CadApp command/format boundaries. This integration binary owns its process-global
|
||||
//! format hooks: every hook delegates to cadcraft-io, and no writer reports synthetic success.
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_write_as};
|
||||
use cadcraft_engine::doc::geom::Vec3;
|
||||
use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Image, Layout, Line};
|
||||
use cadcraft_engine::{DocState, Session};
|
||||
use cadcraft_ui_egui::file_providers::{Event, Resource};
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use serde_json::{Value, json};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[path = "support/temp_dir.rs"]
|
||||
mod temp_dir;
|
||||
|
||||
use temp_dir::TempDir;
|
||||
|
||||
const EXTERNAL_REFERENCE_ERROR: &str =
|
||||
"DXF references external images or drawings; make a self-contained drawing before provider save (external files are not uploaded)";
|
||||
|
||||
thread_local! {
|
||||
// Hooks run synchronously on the command's thread. Parallel cases cannot consume one
|
||||
// another's observations; all cases install exactly the same immutable OnceLock hooks.
|
||||
static WRITES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn real_read(bytes: &[u8], name: &str) -> Result<Drawing, String> {
|
||||
cadcraft_io::read(bytes, name).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn real_write(drawing: &Drawing, name: &str) -> Result<Vec<u8>, String> {
|
||||
WRITES.with(|writes| writes.borrow_mut().push(name.into()));
|
||||
cadcraft_io::write(drawing, name).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn real_write_as(drawing: &Drawing, name: &str, options: &SaveAs) -> Result<Vec<u8>, String> {
|
||||
WRITES.with(|writes| writes.borrow_mut().push(name.into()));
|
||||
let options = cadcraft_io::SaveOptions { version: options.version, binary: options.binary };
|
||||
cadcraft_io::write_with(drawing, name, &options).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn writes() -> Vec<String> {
|
||||
WRITES.with(|writes| writes.borrow().clone())
|
||||
}
|
||||
|
||||
/// Observe the actual picker invocation without replacing either the encoder or disk writer.
|
||||
fn picker(path: Option<String>) -> (Services, Rc<RefCell<Vec<String>>>) {
|
||||
let names = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = names.clone();
|
||||
let services = Services {
|
||||
pick_save: Some(Box::new(move |name| {
|
||||
seen.borrow_mut().push(name.into());
|
||||
path.clone()
|
||||
})),
|
||||
..Services::default()
|
||||
};
|
||||
(services, names)
|
||||
}
|
||||
|
||||
fn app_with_real_formats(services: Services) -> Result<CadApp, String> {
|
||||
set_io(IoHooks { read: real_read, write: real_write, plot: None });
|
||||
set_write_as(real_write_as);
|
||||
WRITES.with(|writes| writes.borrow_mut().clear());
|
||||
let mut app = CadApp::new(Session::new(), services);
|
||||
app.run("line", json!({"points":[[0,0],[10,20]]}))?;
|
||||
assert!(app.session.state().map_err(|error| error.to_string())?.is_dirty());
|
||||
app.ui.recent_files = vec!["existing-local-history.dxf".into()];
|
||||
Ok(app)
|
||||
}
|
||||
|
||||
fn logic(app: &mut CadApp) {
|
||||
let ctx = egui::Context::default();
|
||||
let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| app.logic(ctx));
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
|
||||
fn connect(app: &mut CadApp) -> Result<(), String> {
|
||||
let host = &app.file_providers;
|
||||
host.set_session("0123456789abcdef0123456789abcdef".into())?;
|
||||
let connection = host.connect("boundary-provider".into(), "Boundary storage".into(), "boundary-account".into())?;
|
||||
host.set_resources(
|
||||
&connection,
|
||||
vec![Resource { id: "existing-provider-resource".into(), name: "Existing.dxf".into(), updated_at: "before".into() }],
|
||||
)?;
|
||||
logic(app);
|
||||
assert!(app.file_providers.take_events().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Before {
|
||||
document: DocState,
|
||||
active: usize,
|
||||
epoch: u64,
|
||||
document_count: usize,
|
||||
recents: Vec<String>,
|
||||
provider: Value,
|
||||
log_len: usize,
|
||||
}
|
||||
|
||||
fn before(app: &CadApp) -> Result<Before, String> {
|
||||
Ok(Before {
|
||||
document: app.session.state().map_err(|error| error.to_string())?.clone(),
|
||||
active: app.session.active,
|
||||
epoch: app.session.doc_epoch,
|
||||
document_count: app.session.docs.len(),
|
||||
recents: app.ui.recent_files.clone(),
|
||||
provider: app.file_providers.snapshot(),
|
||||
log_len: app.session.log.len(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A refusal or an unacknowledged capture must not change the drawing or its saved checkpoint.
|
||||
fn assert_document_unchanged(app: &CadApp, before: &Before) -> Result<(), String> {
|
||||
let after = app.session.state().map_err(|error| error.to_string())?;
|
||||
let original = &before.document;
|
||||
assert_eq!((app.session.active, app.session.doc_epoch, app.session.docs.len()), (before.active, before.epoch, before.document_count));
|
||||
assert_eq!((after.uid, after.revision), (original.uid, original.revision));
|
||||
assert!(Arc::ptr_eq(&after.doc, &original.doc));
|
||||
assert!(Arc::ptr_eq(&after.saved, &original.saved));
|
||||
assert_eq!((&after.path, &after.title, &after.space), (&original.path, &original.title, &original.space));
|
||||
assert_eq!((&after.selection, &after.previous_selection), (&original.selection, &original.previous_selection));
|
||||
assert_eq!((after.undo.len(), after.redo.len(), after.is_dirty()), (original.undo.len(), original.redo.len(), original.is_dirty()));
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ImageSpace {
|
||||
Model,
|
||||
Layout,
|
||||
Block,
|
||||
}
|
||||
|
||||
fn insert_external_image(app: &mut CadApp, space: ImageSpace) -> Result<(), String> {
|
||||
let state = app.session.state_mut().map_err(|error| error.to_string())?;
|
||||
let drawing = Arc::make_mut(&mut state.doc);
|
||||
let handle = drawing.new_handle();
|
||||
let image = Entity::new(handle, EntityKind::Image(Image { path: "synthetic-external-image.png".into(), ..Image::default() }));
|
||||
match space {
|
||||
ImageSpace::Model => drawing.model.push(image),
|
||||
ImageSpace::Layout => {
|
||||
let mut layout = Layout::new("External image layout", 3);
|
||||
layout.entities.push(image);
|
||||
drawing.layouts.push(layout);
|
||||
}
|
||||
ImageSpace::Block => {
|
||||
let mut block = Block::new("ExternalImageBlock");
|
||||
block.entities.push(image);
|
||||
drawing.blocks.insert(block.name.clone(), Arc::new(block));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_external_xref(app: &mut CadApp) -> Result<(), String> {
|
||||
let state = app.session.state_mut().map_err(|error| error.to_string())?;
|
||||
let drawing = Arc::make_mut(&mut state.doc);
|
||||
let mut block = Block::new("ExternalDrawing");
|
||||
block.xref_path = Some("synthetic-external-drawing.dxf".into());
|
||||
drawing.blocks.insert(block.name.clone(), Arc::new(block));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_refused_before_encoding(app: &mut CadApp, command: &str) -> Result<(), String> {
|
||||
// Refresh the public document snapshot after the synthetic fixture was installed.
|
||||
logic(app);
|
||||
let before = before(app)?;
|
||||
let error = app.run(command, Value::Null).err().ok_or("external references unexpectedly admitted a provider capture")?;
|
||||
assert_eq!(error, EXTERNAL_REFERENCE_ERROR);
|
||||
assert!(writes().is_empty(), "the app must refuse external references before calling its real encoder");
|
||||
assert_document_unchanged(app, &before)?;
|
||||
assert!(!app.file_providers.busy());
|
||||
assert!(!app.file_providers.pending_for(before.document.uid));
|
||||
assert!(app.file_providers.take_events().is_empty(), "no provider chooser, write or ACK may be published");
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(EXTERNAL_REFERENCE_ERROR));
|
||||
assert_eq!(app.session.log.len(), before.log_len + 1);
|
||||
assert_eq!(app.session.log.last(), Some(&error));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_save_and_save_as_refuse_external_images_in_model_layout_and_blocks() -> Result<(), String> {
|
||||
for space in [ImageSpace::Model, ImageSpace::Layout, ImageSpace::Block] {
|
||||
for command in ["qsave", "ui.saveas"] {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
insert_external_image(&mut app, space)?;
|
||||
assert_refused_before_encoding(&mut app, command)?;
|
||||
assert!(picked.borrow().is_empty(), "{space:?}/{command} must not fall back to a local picker");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_save_and_save_as_refuse_external_xrefs_before_encoding_or_admission() -> Result<(), String> {
|
||||
for command in ["qsave", "ui.saveas"] {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
insert_external_xref(&mut app)?;
|
||||
assert_refused_before_encoding(&mut app, command)?;
|
||||
assert!(picked.borrow().is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_open_refuses_external_images_and_xrefs_before_native_path_loading() -> Result<(), String> {
|
||||
for image_space in [Some(ImageSpace::Model), Some(ImageSpace::Layout), Some(ImageSpace::Block), None] {
|
||||
let mut incoming = app_with_real_formats(Services::default())?;
|
||||
if let Some(space) = image_space {
|
||||
insert_external_image(&mut incoming, space)?;
|
||||
} else {
|
||||
insert_external_xref(&mut incoming)?;
|
||||
}
|
||||
let bytes =
|
||||
cadcraft_io::write(incoming.session.doc().map_err(|error| error.to_string())?, "External.dxf").map_err(|error| error.to_string())?;
|
||||
let mut app = app_with_real_formats(Services::default())?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
let value = app.run("ui.provider.open", json!({"resource":"existing-provider-resource"}))?;
|
||||
let request = value["requestId"].as_str().ok_or("provider Open omitted its request ID")?;
|
||||
only_event(&app, "openRequested", request)?;
|
||||
app.file_providers.open(request.into(), "External.dxf".into(), bytes)?;
|
||||
logic(&mut app);
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
assert!(app.file_providers.bound_document("existing-provider-resource").is_none());
|
||||
let terminal = only_event(&app, "openFailed", request)?;
|
||||
assert_eq!(terminal.metadata["resourceId"], "existing-provider-resource");
|
||||
assert_eq!(
|
||||
terminal.metadata["error"],
|
||||
"DXF references external images or drawings; open a self-contained drawing with the file provider (external files are not loaded)"
|
||||
);
|
||||
assert!(!app.file_providers.busy());
|
||||
assert!(app.file_providers.request_open("existing-provider-resource").is_ok(), "a refused Open must release its owner for retry");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn only_event(app: &CadApp, event_type: &str, request: &str) -> Result<Event, String> {
|
||||
let events = app.file_providers.take_events();
|
||||
assert_eq!(events.len(), 1, "expected exactly one {event_type}");
|
||||
let event = events.into_iter().next().ok_or("missing provider event")?;
|
||||
assert_eq!(event.metadata["type"], event_type);
|
||||
assert_eq!(event.metadata["requestId"], request);
|
||||
Ok(event)
|
||||
}
|
||||
|
||||
/// Check actual native decoder output rather than accepting arbitrary nonempty writer bytes.
|
||||
fn assert_native_line(bytes: &[u8], name: &str) -> Result<(), String> {
|
||||
let drawing = real_read(bytes, name)?;
|
||||
assert_eq!(drawing.model.len(), 1);
|
||||
let entity = drawing.model.iter().next().ok_or("native format lost the synthetic line")?;
|
||||
assert_eq!(entity.kind, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 20.0, 0.0) }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn provider_positive_control(command: &str, intent: &str) -> Result<(), String> {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
let value = app.run(command, Value::Null)?;
|
||||
assert_eq!(value["pending"], "fileProvider");
|
||||
let request = value["requestId"].as_str().ok_or("save command did not return its capture ID")?;
|
||||
let dialog = only_event(&app, "saveDialog", request)?;
|
||||
assert_eq!(dialog.metadata["documentId"], before.document.uid.to_string());
|
||||
assert_eq!(dialog.metadata["revision"], before.document.revision.to_string());
|
||||
assert_eq!(dialog.metadata["intent"], intent);
|
||||
let encoded_name = dialog.metadata["filename"].as_str().ok_or("save dialog lost its native filename")?;
|
||||
assert_eq!(encoded_name, format!("{}.dxf", before.document.title));
|
||||
assert_eq!(writes(), vec![encoded_name.to_string()]);
|
||||
assert!(dialog.bytes.is_none());
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
app.file_providers.resolve_dialog(request, "provider", "SelfContained.dxf")?;
|
||||
let save = only_event(&app, "save", request)?;
|
||||
assert_eq!(save.metadata["destination"], "provider");
|
||||
assert_eq!(save.metadata["documentId"], before.document.uid.to_string());
|
||||
assert_eq!(save.metadata["revision"], before.document.revision.to_string());
|
||||
assert_eq!(save.metadata["filename"], "SelfContained.dxf");
|
||||
assert_native_line(save.bytes.as_deref().ok_or("provider write omitted its real DXF bytes")?, "SelfContained.dxf")?;
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
assert_eq!(app.file_providers.snapshot()["resources"], before.provider["resources"]);
|
||||
app.file_providers.result(request.into(), "saved".into(), "self-contained-resource".into())?;
|
||||
assert_document_unchanged(&app, &before)?;
|
||||
logic(&mut app);
|
||||
assert_provider_ack(&app, &before, request)?;
|
||||
assert!(picked.borrow().is_empty());
|
||||
assert_eq!(writes().len(), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_provider_ack(app: &CadApp, before: &Before, request: &str) -> Result<(), String> {
|
||||
let state = app.session.state().map_err(|error| error.to_string())?;
|
||||
assert_eq!((state.uid, state.revision), (before.document.uid, before.document.revision));
|
||||
assert!(Arc::ptr_eq(&state.doc, &before.document.doc));
|
||||
assert!(Arc::ptr_eq(&state.saved, &before.document.doc));
|
||||
assert!(!state.is_dirty());
|
||||
assert_eq!(state.path, before.document.path);
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
assert_eq!(app.file_providers.bound_document("self-contained-resource"), Some(state.uid));
|
||||
let terminal = only_event(app, "saved", request)?;
|
||||
assert_eq!(terminal.metadata["documentId"], state.uid.to_string());
|
||||
assert_eq!(terminal.metadata["revision"], before.document.revision.to_string());
|
||||
assert_eq!(terminal.metadata["resourceId"], "self-contained-resource");
|
||||
assert!(terminal.bytes.is_none());
|
||||
assert!(!app.file_providers.busy());
|
||||
assert_eq!(app.file_providers.snapshot()["resources"][0]["name"], "SelfContained.dxf");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_contained_provider_save_and_save_as_encode_real_dxf_and_wait_for_app_ack() -> Result<(), String> {
|
||||
for (command, intent) in [("qsave", "save"), ("ui.saveas", "saveAs")] {
|
||||
provider_positive_control(command, intent)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn assert_local_save(app: &CadApp, path: &str, value: &Value) -> Result<(), String> {
|
||||
let bytes = std::fs::read(path).map_err(|error| error.to_string())?;
|
||||
assert_eq!(value["path"], path);
|
||||
assert_eq!(value["bytes"].as_u64(), Some(bytes.len() as u64));
|
||||
assert_native_line(&bytes, path)?;
|
||||
let state = app.session.state().map_err(|error| error.to_string())?;
|
||||
assert_eq!(state.path.as_deref(), Some(path));
|
||||
assert!(Arc::ptr_eq(&state.doc, &state.saved));
|
||||
assert!(!state.is_dirty());
|
||||
assert_eq!(writes(), vec![path.to_string()]);
|
||||
assert!(!app.file_providers.busy());
|
||||
assert!(!app.file_providers.pending_for(state.uid));
|
||||
assert!(app.file_providers.take_events().is_empty(), "a local file must not create a provider chooser, write or ACK");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))]
|
||||
fn provider_connected_explicit_dwg_save_as_uses_the_real_local_format_and_writer() -> Result<(), String> {
|
||||
// The DWG writer and reader only handle this fixture's own synthetic drawing.
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let directory = TempDir::new("provider-explicit-local-dwg");
|
||||
let path = directory.path_str("Explicit local drawing.dwg");
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
let value = app.run("saveas", json!({"path":path,"version":2018}))?;
|
||||
assert_local_save(&app, &path, &value)?;
|
||||
let bytes = std::fs::read(&path).map_err(|error| error.to_string())?;
|
||||
assert!(bytes.starts_with(b"AC1032"), "the actual local file must be a 2018 DWG, not renamed DXF");
|
||||
assert!(picked.borrow().is_empty(), "a programmatic explicit path must not open either chooser");
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
assert_eq!(app.session.state().map_err(|error| error.to_string())?.uid, before.document.uid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_save_as_preserves_explicit_format_validation_and_the_local_dwg_picker() -> Result<(), String> {
|
||||
let (services, picked) = picker(None);
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
connect(&mut app)?;
|
||||
let before = before(&app)?;
|
||||
|
||||
assert!(app.run("ui.saveas", json!({"format":"unknown"})).is_err());
|
||||
assert!(app.run("ui.saveas", json!({"format":42})).is_err());
|
||||
assert!(picked.borrow().is_empty());
|
||||
|
||||
app.run("ui.saveas", json!({"format":"dwg"}))?;
|
||||
assert_eq!(*picked.borrow(), vec![format!("{}.dwg", before.document.title)]);
|
||||
assert!(writes().is_empty());
|
||||
assert!(app.file_providers.take_events().is_empty());
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_document_unchanged(&app, &before)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_provider_save_as_keeps_the_ordinary_picker_and_real_local_dxf_writer() -> Result<(), String> {
|
||||
let directory = TempDir::new("provider-disabled-local-picker");
|
||||
let path = directory.path_str("Picked local drawing.dxf");
|
||||
let (services, picked) = picker(Some(path.clone()));
|
||||
let mut app = app_with_real_formats(services)?;
|
||||
assert!(!app.file_providers.connected() && !app.file_providers.enabled());
|
||||
let before = before(&app)?;
|
||||
let value = app.run("ui.saveas", Value::Null)?;
|
||||
assert_local_save(&app, &path, &value)?;
|
||||
assert_eq!(*picked.borrow(), vec![format!("{}.dxf", before.document.title)]);
|
||||
assert_eq!(app.file_providers.snapshot(), before.provider);
|
||||
assert_eq!(app.ui.recent_files, before.recents);
|
||||
assert!(!app.file_providers.connected() && !app.file_providers.enabled());
|
||||
Ok(())
|
||||
}
|
||||
@@ -136,6 +136,75 @@ fn start_page_lists_recent_files_and_opens_one_on_click() {
|
||||
assert_eq!(app.ui.recent_files, [plan, section]);
|
||||
}
|
||||
|
||||
/// The same native Start page with the storage capability absent and connected. Optional PNGs
|
||||
/// use the existing offscreen renderer; no app window, backend, or provider filesystem is made.
|
||||
#[test]
|
||||
fn provider_recents_render_separately_from_device_history() {
|
||||
let directory = std::env::var_os("CRAFT_PROVIDER_UI_FIXTURES").map(std::path::PathBuf::from);
|
||||
if let Some(path) = &directory {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
}
|
||||
for (enabled, provider_count) in [(false, 0), (true, 1), (true, 100)] {
|
||||
let (_dir, plan, _) = drawings("provider-home");
|
||||
let mut app = CadApp::new(Session::empty(), Services::default());
|
||||
app.ui.recent_files = vec![plan];
|
||||
if enabled {
|
||||
let host = &app.file_providers;
|
||||
host.set_session("fixture-session-0123456789abcdef".into()).unwrap();
|
||||
let connection = host.connect("fixture".into(), "External storage".into(), "fixture-account".into()).unwrap();
|
||||
host.set_resources(
|
||||
&connection,
|
||||
(0..provider_count)
|
||||
.map(|index| cadcraft_ui_egui::file_providers::Resource {
|
||||
id: format!("provider-drawing-{index}"),
|
||||
name: if index == 0 { "Provider drawing.dxf".into() } else { format!("Provider drawing {index}.dxf") },
|
||||
updated_at: String::new(),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let mut builder = Harness::builder().with_size(vec2(1280.0, 900.0));
|
||||
if directory.is_some() {
|
||||
builder = builder.wgpu();
|
||||
}
|
||||
let mut ready = false;
|
||||
let mut h = builder.build_ui_state(
|
||||
move |ui, app: &mut CadApp| {
|
||||
if !ready {
|
||||
ready = true;
|
||||
return;
|
||||
}
|
||||
app.logic(&ui.ctx().clone());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.input_mut().max_texture_side = Some(8192);
|
||||
h.run_steps(6);
|
||||
let mut found = Vec::new();
|
||||
for shape in &h.output().shapes {
|
||||
texts(&shape.shape, &mut found);
|
||||
}
|
||||
assert!(found.iter().any(|(text, _)| text == "plan.dxf"), "{found:?}");
|
||||
assert_eq!(found.iter().any(|(text, _)| text == "Provider drawing.dxf"), enabled, "{found:?}");
|
||||
assert_eq!(found.iter().any(|(text, _)| text == "Recent files — External storage"), enabled, "{found:?}");
|
||||
assert_eq!(found.iter().any(|(text, _)| text == "Recent files on this device"), enabled, "{found:?}");
|
||||
let mut visible = Vec::new();
|
||||
for shape in &h.output().shapes {
|
||||
let mut labels = Vec::new();
|
||||
texts(&shape.shape, &mut labels);
|
||||
visible.extend(labels.into_iter().filter(|(_, rect)| shape.clip_rect.contains_rect(*rect)));
|
||||
}
|
||||
assert_eq!(visible.iter().any(|(text, _)| text == "Recent files on this device"), enabled, "{visible:?}");
|
||||
assert!(visible.iter().any(|(text, _)| text == "plan.dxf"), "device history remains visible even when provider files overflow: {visible:?}");
|
||||
if let Some(path) = directory.as_ref().filter(|_| provider_count <= 1) {
|
||||
let state = if enabled { "on" } else { "off" };
|
||||
h.render().unwrap().save(path.join(format!("cadcraft-provider-recents-{state}.png"))).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recent_file_that_no_longer_exists_is_dropped_when_opening_it_fails() {
|
||||
let (_dir, plan, _section) = drawings("missing");
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
# Optional external file providers (web)
|
||||
|
||||
The web editor can delegate native project persistence to one **trusted same-origin host**.
|
||||
The capability is **disabled by default**. Merely loading the editor exposes a protocol object;
|
||||
it does not enable storage, render provider Recents, change ordinary local saves, or contact a server.
|
||||
A host must explicitly call registerProvider. No server, account system, login, VM, domain,
|
||||
filesystem mount or cloud vendor is built into this feature.
|
||||
|
||||
## Contract
|
||||
|
||||
window.cadcraftFileProviders has protocolVersion 1 and app cadcraft. Events are dispatched on window
|
||||
as cadcraft-file-provider CustomEvents; detail contains bounded metadata and, on save,
|
||||
a Uint8Array named bytes. The host subscribes before registering, and can discover an already-ready
|
||||
editor through the protocol object. The capability is independent of the optional control API.
|
||||
|
||||
The application command `ui.provider.open` accepts `{"resource":"resource-id"}` and returns
|
||||
the queued provider request ID. Home and File-menu provider Recents both dispatch through
|
||||
`CadApp::run`; rejected reads remain in the status and command history instead of a one-frame
|
||||
inline label. This command uses the current account's resource list and never opens a local path.
|
||||
|
||||
| Method | Arguments / result |
|
||||
| --- | --- |
|
||||
| registerProvider | (providerId, label, namespace) -> connectionId. Repeating the exact identity is idempotent. |
|
||||
| unregisterProvider | No arguments. Refused while an operation is unresolved; clears account resources and bindings. |
|
||||
| setEnabled | (boolean). Suspends new provider choices/Recents without discarding pending work. |
|
||||
| setResources | (connectionId, resources). Replace this account's native project list. |
|
||||
| requestOpen | (resourceId) -> requestId. IDs must occur in the current connection's resource list. |
|
||||
| openResource | (requestId, filename, Uint8Array). Replies only to a live, single-use open request. |
|
||||
| cancelOpen | (requestId, error). Empty error means cancellation. |
|
||||
| resolveSaveDialog | (requestId, destination, filename). destination is provider, device or cancel. |
|
||||
| saveResult | (requestId, status, resourceId). status is saved, download, failed or cancel. |
|
||||
| snapshot | Returns provider/namespace/connectionId, enabled, resources, documents and pending state. |
|
||||
|
||||
The namespace must identify the authenticated account, not its display name. A new connection ID
|
||||
and per-page cryptographic request nonce prevent old account/page callbacks from matching new work.
|
||||
This is correlation and separation of identities, **not authentication**. The host and its backend
|
||||
must authenticate users, authorize every list/read/write, and scope durable storage by account.
|
||||
Do not trust a filename, user-supplied account ID, browser page or request ID as an authorization check.
|
||||
Only the hosting page's own script environment can use this capability; no postMessage listener,
|
||||
foreign-origin message channel or filesystem authority is added.
|
||||
|
||||
Every script executing in the editor page, including third-party analytics, can call registerProvider
|
||||
and receive saved drawings through provider events. Load only scripts you trust with drawing contents.
|
||||
The host/backend remains responsible for authenticating users and authorizing each account-scoped operation.
|
||||
|
||||
A resource is an object with id, name and optional updatedAt strings. IDs are opaque and never used as
|
||||
paths. The list is limited to 100 unique resources. Names must be native .dxf filenames, at most
|
||||
255 UTF-8 bytes, with no path separators or control characters. IDs/namespaces are at most 160 ASCII
|
||||
characters (letters, numbers, dash, underscore, dot, colon). Labels are at most 100 UTF-8 bytes.
|
||||
Native captures/read responses are limited to 80 MiB; retained transfer bytes and pending work are bounded.
|
||||
The WASM adapter checks string/array lengths before copying host input and accepts only Uint8Array bytes.
|
||||
|
||||
## Save and Save As
|
||||
|
||||
With the provider enabled, interactive Save and Save As capture a native DXF and emit saveDialog.
|
||||
A Save As requested with `format: "dwg"` opens the ordinary local file picker.
|
||||
The event carries requestId, documentId, revision, intent and suggested filename. The host presents
|
||||
its own choice of **provider / device / cancel**, then calls resolveSaveDialog. The editor owns the
|
||||
captured state while the choice is open, so changing tabs or editing cannot silently change the target.
|
||||
No save happens merely because a dialog was opened or a byte capture was produced.
|
||||
|
||||
Choosing provider emits save with the immutable native bytes, filename, intent, documentId, revision,
|
||||
providerId, namespace, connectionId and requestId. Save includes a previously bound resourceId;
|
||||
Save As requests a distinct resource. The provider must finish its durable write before returning
|
||||
saveResult(requestId, saved, resourceId). An ACK cannot nominate a document or revision, cannot be
|
||||
replayed, and cannot bind a resource already owned by another open document. Failed/cancelled writes
|
||||
keep edits unsaved. Later edits remain dirty when an older capture succeeds. There is no pretend local
|
||||
path for an external resource.
|
||||
|
||||
Choosing device emits save with destination device and the capture. The host hands the bytes to the device using the
|
||||
browser's ordinary download mechanism, then returns download as the result. This is a terminal transfer
|
||||
result, **not durable provider confirmation**, and does not clear the document's saved checkpoint.
|
||||
Save Copy, Export and programmatic commands keep their existing local behavior. With the capability
|
||||
disabled or unregistered, the original browser/native save flow remains in use.
|
||||
|
||||
Provider Save/Save As captures one native DXF. DXF stores external image/drawing references as paths, not their bytes. To prevent an incomplete upload being marked saved, this bridge refuses provider capture when the modeled drawing contains external images or xrefs; bind/remove those references first. Provider Open checks the decoded drawing for those same modeled references before running the native Open command, so provider bytes cannot trigger its automatic image/xref filesystem loaders. A refusal leaves existing documents unchanged and reports the correlated openFailed terminal. Ordinary local Open keeps its existing native behavior.
|
||||
|
||||
Single-file transfers inherit the existing [DXF codec limits](file-format-parity.md). Font files, including SHX/bigfonts, and other dependencies are not collected or packaged. The bridge does not certify arbitrary foreign DXF as lossless or scan unmodeled records for dependencies. It adds no linked-file negotiation, resource-set checkpoints, attachment bundle or atomic multi-file save. The host receives the one DXF produced by the native writer and remains responsible for its durable storage.
|
||||
Use the existing local Copy/Export commands for interchange formats. The host must preserve the native
|
||||
extension; changing a suffix cannot turn native bytes into PDF, SVG or another interchange format.
|
||||
Native capture uses the existing IoHooks / write_as DXF encoder. The existing ?host=parent and data-host="page" host modes are preserved. The optional provider capability is installed only when neither mode connects, so two hosts do not compete for Save. DWG and interchange outputs remain in the original local flow.
|
||||
|
||||
Normal close/revert actions wait or refuse while provider work is unresolved. The browser can still
|
||||
force-close/reload a tab; the host should provide an unsaved-work warning and must not acknowledge a
|
||||
write it cannot recover. This bridge does not add automatic saving, cross-client conflict resolution,
|
||||
offline persistence, autosave recovery or an inactivity/login implementation.
|
||||
|
||||
## Open and Recents
|
||||
|
||||
The existing Home screen and File > Open Recent display a separate provider section while enabled.
|
||||
Local Recents retain their own storage and behavior. Publish only the current account's native files
|
||||
with setResources; the editor never scans a VM or guesses a path from a name.
|
||||
|
||||
A click emits openRequested with requestId and resourceId. After authorization, the provider fetches
|
||||
bytes and responds with openResource using that request ID. The editor parses the native project before
|
||||
emitting opened or openFailed. Selecting an already-bound open resource focuses its existing document
|
||||
without replacing unsaved edits. Unknown, duplicate or cancelled request replies are rejected.
|
||||
The host handles failed fetches using cancelOpen rather than leaving the operation pending forever.
|
||||
|
||||
Completion events are saved, downloaded, saveFailed, saveCancelled, opened, openFailed and openCancelled.
|
||||
Events associated with an account include providerId, namespace and connectionId. Storage keys should
|
||||
use the provider/account/resource identities, never display names, and the backend should use versioning
|
||||
or conditional writes if it allows concurrent clients.
|
||||
|
||||
## Recoverable publication failures
|
||||
|
||||
The byte publisher calls an explicit catch-enabled `Uint8Array.from` import. Recoverable JavaScript
|
||||
copy/allocation errors become returned errors, are logged, and do not bypass later events in the
|
||||
batch. This is not recovery from fatal memory exhaustion, WASM traps or process termination; DOM
|
||||
listener exceptions swallowed by the browser are not assumed to propagate from dispatchEvent.
|
||||
|
||||
A failed `save` or `saveDialog` moves only its still-owned capture into a bounded failure inbox.
|
||||
It retains every captured document alias in finishing-saves ownership until the actual CAD
|
||||
application consumes the failed Action and queues its correlated `saveFailed` terminal. Retained
|
||||
bytes are discarded. No saved checkpoint, binding or durable acknowledgement is manufactured.
|
||||
Public action/result admission checks are unchanged. At most 16 previously admitted captures can
|
||||
await failure consumption separately, including when the ordinary queue is full. Repaint is requested through
|
||||
the installed editor context. Accepted synchronous results/choices remain authoritative.
|
||||
|
||||
A failed `openRequested` retires only an unanswered read and retains its correlated `openFailed`
|
||||
terminal across event-queue capacity limits. An already queued open response survives a later
|
||||
dispatch error. Fresh choices/reads can retry after failure consumption; IDs are never reused.
|
||||
|
||||
Busy/account ownership includes all seven completion event types while queued or in a taken
|
||||
publication batch. Batch protection is acquired atomically and released independently for nested
|
||||
publishers. Hosts must defer unregisterProvider until the publication batch returns and all outstanding
|
||||
operations and terminal deliveries finish. Independent save/open admission rules are unchanged.
|
||||
The publisher still performs two bounded drains in order.
|
||||
|
||||
## Validation
|
||||
|
||||
Regression fixtures cover the default-off gate, single-use/late replies, account reconnection, resource
|
||||
scope and alias rejection, cancellation, immutable captures, switching tabs, edits after capture and
|
||||
conservative device results. The source includes the WASM adapter and native encoder/decoder integration.
|
||||
Run the required repository CI and the actual Window fixture on the complete candidate. This document does not claim those checks
|
||||
have been executed merely because fixtures are present.
|
||||
|
||||
New source regressions cover full ordinary action queues, a bounded failure inbox, captured aliases,
|
||||
failed chooser/read publication, accepted reentrant callbacks, current/nested terminal ownership
|
||||
and recovery through a full event queue. The native application fixture uses the real DXF codec and
|
||||
CAD failure consumer without altering process-global format hooks, preserving another active drawing
|
||||
and later edits. The WASM fixture uses the exported window API, production publisher, actual CadApp
|
||||
logic and native DXF encoder/decoder. Rust closures produce real JS RangeErrors for byte and metadata
|
||||
dispatch failures; catch-enabled calls restore exact property descriptors before assertions. It
|
||||
observes continuation, correlated failure terminals, a nonempty DXF retry and opening that payload
|
||||
under a distinct resource, without marking later edits saved.
|
||||
|
||||
The native provider_format_boundaries integration binary covers the real DXF Save/Save As refusal,
|
||||
self-contained capture and ACK, ordinary explicit DWG and disabled-provider local save behavior. Its
|
||||
provider_open_refuses_external_images_and_xrefs_before_native_path_loading fixture exercises provider
|
||||
Open refusals for model/layout/block images and xrefs without adding a document or binding.
|
||||
|
||||
The actual Window fixture is in
|
||||
[browser_tests.rs](../apps/cadcraft-web/src/file_providers/browser_tests.rs). With a real browser and
|
||||
the wasm-bindgen-test browser runner configured, run the existing WASM main harness:
|
||||
|
||||
```sh
|
||||
cargo test --locked --offline -j1 -p cadcraft-web --bin cadcraft-web --target wasm32-unknown-unknown file_providers::browser_tests:: -- --nocapture
|
||||
```
|
||||
|
||||
Simulated user Save/Save As uses the existing Null parameter form. JSON object parameters continue
|
||||
to mean explicit programmatic operations and never acquire dialogs.
|
||||
|
||||
These are authored fixtures, not execution receipts. Real browser/runner execution remains required;
|
||||
native tests or WASM compilation alone do not establish the window assertions. The fixture does not
|
||||
run a rendered WebRunner, prove backend durability or simulate true out-of-memory failure. The web
|
||||
test dependency is wasm32-only; the UI's existing workspace IO crate is a test-only dependency for
|
||||
real drawing-codec fixtures. The existing locked graph is retained; its candidate must be reviewed
|
||||
before checks.
|
||||
|
||||
Contributor credit: @alejocapo04.
|
||||
|
||||
## Native UI evidence
|
||||
|
||||
The existing recent-files test harness covers the real Start page with the optional provider absent
|
||||
and connected, retaining the separate device history in both states. It uses synthetic drawing names
|
||||
and metadata, with no storage or authentication backend. The native label assertions also run without
|
||||
a GPU when the output variable is unset.
|
||||
|
||||
```sh
|
||||
CRAFT_PROVIDER_UI_FIXTURES=/absolute/output cargo test --locked -p cadcraft-ui-egui --test recent_files provider_recents_render_separately_from_device_history -- --exact --test-threads=1
|
||||
```
|
||||
|
||||
This saves `cadcraft-provider-recents-off.png` and `cadcraft-provider-recents-on.png` using
|
||||
egui_kittest's existing offscreen renderer. Keep the generated review artifacts outside Git.
|
||||
Reference in New Issue
Block a user