* Update egui/eframe to 0.37 (WIP) egui, eframe and egui-wgpu 0.36 -> 0.37. SolidCraft's egui-wgpu patch is rebased onto 0.37.0; the vendored accesskit_macos is dropped (0.27.2 has the #7535 fix). Not finished: 36 solidcraft-ui-egui lib tests fail, and the full lib run crashes with SIGSEGV when tests run in parallel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tests: clear texture deltas that egui 0.37 refuses to drop Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Drop non-finite pointer input before egui; keep test time monotonic egui 0.37 debug-asserts on NaN wheel deltas, on time moving backwards in the pointer history, and on add_space inside a Grid. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Hold a click that follows typing in the same frame until the next frame egui 0.37 drops a field's focus on a click elsewhere when the field first reads its style, before it reads the frame's typing, so text typed in the frame of a click was lost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Name a document tab's close button "Close tab" egui 0.37 names an unnamed widget after its tooltip, so the tab's × became a second control named Close beside a dialog's. The space mouse guard test now clicks where each button was: by name it found nothing behind the guard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Turn on egui's default_fonts: 0.37 no longer does The built-in Hack is the UI's symbol fallback (#2955). The app got it through eframe, but solidcraft-ui-egui on its own (its tests) did not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Text menu: act on the selection the menu click took the focus from egui 0.37 drops a field's focus on a click elsewhere before the field draws, and an unfocused field loses its selection, so Copy, Cut and Paste from the right-click menu saw no selection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Placement field: keep its native height under egui 0.37's interact floor Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tests: pin the theme's 2/3 point radii; measure Japanese ribbon labels with a Japanese face egui 0.37 rounds widgets 4 points by default, which the theme deliberately does not follow. The ribbon test measured Japanese with missing glyphs, whose width changed in 0.37; with BIZ UDPGothic, 駆動 wraps after its particle like 変換 does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Tests: click the render inspector's Perspective checkbox by position egui 0.37 orders the accessibility tree differently, so the name found the stage's Perspective segment first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Translate "Close tab" for the complete catalogs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Point the focus workarounds at emilk/egui#8763 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Cargo.lock: update only what egui 0.37 needs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Web: Id::new -> Id::unique for the wasm-only windows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Command search: keep its hint centred under egui 0.37's interact floor Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * egui 0.37 renames in code main added since the branch Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * egui 0.37 renames in code main added since the last rebase Id::new to Id::unique, ui.id() to ui.scope_id(), WidgetType to Role, the wheel events' source, and the button stroke read from the widget visuals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Review: disclosures report expanded, late screenshots drained, chat width reset on both sides A disclosure's node says whether it is open as expanded, as egui's own collapsing header does. The screenshot channel is drained every frame, so a shot whose request was cancelled is dropped. Resetting the chat panel's width forgets both sides' state, as before 0.37, and the request stays with its window when tabs switch. Tests main added since the last rebase clear their texture deltas. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
162 lines
7.5 KiB
Rust
162 lines
7.5 KiB
Rust
//! Bounded HTTPS or same-origin downloads, handed to the normal design-open command as unsaved copies.
|
|
use std::{cell::RefCell, rc::Rc};
|
|
|
|
use js_sys::{Reflect, Uint8Array};
|
|
use solidcraft_engine::io::vfs;
|
|
use solidcraft_ui_egui::{SolveApp, ui_kit};
|
|
use wasm_bindgen::{JsCast as _, JsValue};
|
|
use wasm_bindgen_futures::{JsFuture, spawn_local};
|
|
|
|
use crate::{check_download_size, design_url};
|
|
|
|
type Reply = Result<(String, Vec<u8>), String>;
|
|
|
|
#[derive(Default)]
|
|
pub struct Download {
|
|
reply: Rc<RefCell<Option<Reply>>>,
|
|
pending: Option<(String, Vec<u8>)>,
|
|
/// The downloaded design being opened (a few features a frame, #10198): the answer to come,
|
|
/// the name it takes and the file it was read from.
|
|
opening: Option<(std::sync::mpsc::Receiver<serde_json::Value>, String, String)>,
|
|
}
|
|
|
|
impl Download {
|
|
pub fn start(url: Option<&str>, ctx: &egui::Context) -> Self {
|
|
let download = Self::default();
|
|
if let Some(url) = url {
|
|
let url = url.to_owned();
|
|
let slot = download.reply.clone();
|
|
let ctx = ctx.clone();
|
|
spawn_local(async move {
|
|
*slot.borrow_mut() = Some(fetch(&url).await);
|
|
ctx.request_repaint();
|
|
});
|
|
}
|
|
download
|
|
}
|
|
|
|
pub fn tick(&mut self, app: &mut SolveApp, ctx: &egui::Context) {
|
|
self.opened(app);
|
|
if let Some(reply) = self.reply.borrow_mut().take() {
|
|
match reply {
|
|
Ok(file) => self.pending = Some(file),
|
|
Err(error) => app.set_status(format!("Could not open design link: {error}"), true),
|
|
}
|
|
}
|
|
if self.pending.is_none() || self.opening.is_some() || app.file_picker_busy() {
|
|
return;
|
|
}
|
|
if solidcraft_ui_egui::documents::any_dirty(app) {
|
|
let mut answer = None;
|
|
let closed = ui_kit::Window::new(egui::Id::unique("open_link"), "status_warning", solidcraft_ui_egui::i18n::tr("web.open_link"))
|
|
.required()
|
|
.show_body(ctx, |ui| {
|
|
ui.label(solidcraft_ui_egui::i18n::tr("web.open_link_confirm"));
|
|
ui.horizontal(|ui| {
|
|
if ui_kit::button(ui, solidcraft_ui_egui::i18n::tr("ui.open"), ui_kit::Button::Normal).clicked() {
|
|
answer = Some(true);
|
|
}
|
|
if ui_kit::button(ui, solidcraft_ui_egui::i18n::tr("ui.cancel"), ui_kit::Button::Normal).clicked() {
|
|
answer = Some(false);
|
|
}
|
|
});
|
|
});
|
|
match answer {
|
|
Some(true) => {}
|
|
Some(false) => {
|
|
self.pending = None;
|
|
return;
|
|
}
|
|
None if closed => {
|
|
self.pending = None;
|
|
return;
|
|
}
|
|
None => return,
|
|
}
|
|
}
|
|
let Some((name, bytes)) = self.pending.take() else { return };
|
|
// The extension selects the design loader even when the URL has no extension. Named
|
|
// after the link, as the progress card shows the file's name.
|
|
let file: String = name.chars().map(|c| if matches!(c, '/' | '\\') { '_' } else { c }).collect();
|
|
let path = format!("/linked/{}.{}", if file.is_empty() { "design" } else { &file }, solidcraft_engine::io::DESIGN_EXT);
|
|
vfs::insert(&path, bytes);
|
|
// Opened as any design is, with its progress and Cancel; finished in `opened`.
|
|
self.opening = Some((app.open_path_answered(&path), name, path));
|
|
self.opened(app);
|
|
}
|
|
|
|
/// The downloaded design is in: it is an unsaved copy under the link's name.
|
|
fn opened(&mut self, app: &mut SolveApp) {
|
|
let Some((rx, _, _)) = &self.opening else { return };
|
|
let (ok, cancelled) = match rx.try_recv() {
|
|
Ok(reply) => (reply["ok"].as_bool() == Some(true), reply["error"].as_str().is_some_and(|e| e.contains("cancelled"))),
|
|
Err(std::sync::mpsc::TryRecvError::Empty) => return,
|
|
Err(std::sync::mpsc::TryRecvError::Disconnected) => (false, false),
|
|
};
|
|
let Some((_, name, path)) = self.opening.take() else { return };
|
|
if ok && app.session.path.as_deref() == Some(path.as_str()) {
|
|
app.session.path = None;
|
|
app.session.doc_mut().name = name;
|
|
app.session.mark_unsaved();
|
|
} else if !ok && !cancelled {
|
|
app.set_status("Could not open design link: the downloaded file is not a valid SolidCraft design", true);
|
|
}
|
|
let _ = vfs::remove(&path);
|
|
}
|
|
}
|
|
|
|
async fn fetch(value: &str) -> Reply {
|
|
let window = web_sys::window().ok_or("No browser window")?;
|
|
let page_origin = window.location().origin().map_err(|_| "Cannot read page origin")?;
|
|
let url = design_url(value, &page_origin)?;
|
|
let name = url.path_segments().and_then(|mut segments| segments.next_back()).filter(|name| !name.is_empty()).unwrap_or("Design");
|
|
let decoded = js_sys::decode_uri_component(name).ok().and_then(|name| name.as_string()).unwrap_or_else(|| name.to_owned());
|
|
// `arm.sc` (or a legacy `arm.solidcraft`) is named `arm`.
|
|
let stem = match decoded.rsplit_once('.') {
|
|
Some((stem, ext)) if !stem.is_empty() && solidcraft_engine::io::is_design_ext(ext) => stem,
|
|
_ => decoded.as_str(),
|
|
};
|
|
let name: String = stem.chars().take(255).collect();
|
|
let response = JsFuture::from(window.fetch_with_str(url.as_str())).await.map_err(|_| "Network request failed or the host refused CORS access")?;
|
|
let response: web_sys::Response = response.dyn_into().map_err(|_| "Invalid download response")?;
|
|
design_url(&response.url(), &page_origin).map_err(|_| "Design redirected to a URL that does not use HTTPS or the page's own origin")?;
|
|
if !response.ok() {
|
|
return Err(format!("HTTP {} {}", response.status(), response.status_text()));
|
|
}
|
|
let length = response
|
|
.headers()
|
|
.get("Content-Length")
|
|
.map_err(|_| "Cannot read download size")?
|
|
.map(|value| value.parse::<u64>().map_err(|_| "Invalid Content-Length"))
|
|
.transpose()?;
|
|
if let Some(length) = length {
|
|
check_download_size(0, length)?;
|
|
}
|
|
let stream = response.body().ok_or("Download has no body")?;
|
|
let reader: web_sys::ReadableStreamDefaultReader = stream.get_reader().dyn_into().map_err(|_| "Cannot read download stream")?;
|
|
let result = read(&reader).await;
|
|
if result.is_err() {
|
|
let _ = JsFuture::from(reader.cancel()).await;
|
|
}
|
|
// Fetch rejects interrupted HTTP bodies and decodes Content-Encoding. Content-Length
|
|
// can describe compressed bytes, so the streamed limit also checks the decoded size.
|
|
let bytes = result?;
|
|
Ok((name, bytes))
|
|
}
|
|
|
|
async fn read(reader: &web_sys::ReadableStreamDefaultReader) -> Result<Vec<u8>, String> {
|
|
let mut bytes = Vec::new();
|
|
// Bound even a stream which keeps returning empty chunks.
|
|
for _ in 0..1_000_000 {
|
|
let chunk = JsFuture::from(reader.read()).await.map_err(|_| "Download interrupted")?;
|
|
if Reflect::get(&chunk, &JsValue::from_str("done")).map_err(|_| "Invalid download stream")?.as_bool() == Some(true) {
|
|
return Ok(bytes);
|
|
}
|
|
let value = Reflect::get(&chunk, &JsValue::from_str("value")).map_err(|_| "Invalid download chunk")?;
|
|
let chunk: Uint8Array = value.dyn_into().map_err(|_| "Invalid download bytes")?;
|
|
check_download_size(bytes.len(), u64::from(chunk.length()))?;
|
|
bytes.extend_from_slice(&chunk.to_vec());
|
|
}
|
|
Err("Download returned too many chunks".into())
|
|
}
|