mirror of
https://github.com/storytold/designcraft.git
synced 2026-10-27 11:46:51 -06:00
Conflict: crates/ui-egui/src/lib.rs: next's missing-fonts test; the branch's side repeated control_bar_shows_its_second_row (next's newer copy stays) and key_names_sent_as_text_are_dropped, whose IME version replaces next's copy in place
179 lines
7.1 KiB
Rust
179 lines
7.1 KiB
Rust
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
|
|
|
|
use super::browser_policy::{has_query_flag, mime_for};
|
|
use designcraft_engine::Session;
|
|
use designcraft_ui_egui::{DesignApp, ImportRequest, ImportedFile, Inbox, Services};
|
|
use wasm_bindgen::JsCast as _;
|
|
|
|
const DOC_EXTS: &[&str] = &["designcraft", "idml", "indd", "indt"];
|
|
const IMAGE_EXTS: &[&str] = &[
|
|
"png",
|
|
"jpg",
|
|
"jpeg",
|
|
"gif",
|
|
"webp",
|
|
"tif",
|
|
"tiff",
|
|
"bmp",
|
|
"psd",
|
|
"svg",
|
|
"pdf",
|
|
"ai",
|
|
"txt",
|
|
"docx",
|
|
"rtf",
|
|
"md",
|
|
"xlsx",
|
|
"idml",
|
|
"designcraft",
|
|
];
|
|
const CANVAS_ID: &str = "designcraft_canvas";
|
|
const LOADING_ID: &str = "designcraft_loading";
|
|
|
|
pub fn start() {
|
|
eframe::WebLogger::init(log::LevelFilter::Info).ok();
|
|
wasm_bindgen_futures::spawn_local(async {
|
|
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
|
|
log::error!("no document");
|
|
return;
|
|
};
|
|
let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
|
|
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
|
return;
|
|
};
|
|
let mut options = eframe::WebOptions::default();
|
|
if has_query_flag(&query(), "webgl")
|
|
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
|
|
{
|
|
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
|
|
}
|
|
let result = eframe::WebRunner::new()
|
|
.start(
|
|
canvas,
|
|
options,
|
|
Box::new(move |cc| {
|
|
if let Some(rs) = &cc.wgpu_render_state {
|
|
log::info!("designcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
|
|
}
|
|
let inbox: Inbox = Inbox::default();
|
|
let mut app = DesignApp::new(Session::new(), services(inbox.clone(), cc.egui_ctx.clone()));
|
|
if has_query_flag(&query(), "sample") {
|
|
let _ = app.run("file.newSample", serde_json::json!({}));
|
|
}
|
|
Ok(Box::new(WebShell { app, inbox }))
|
|
}),
|
|
)
|
|
.await;
|
|
if let Some(el) = document.get_element_by_id(LOADING_ID) {
|
|
match result {
|
|
Ok(()) => el.remove(),
|
|
Err(e) => el.set_inner_html(&format!("<p>DesignCraft failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>")),
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
fn query() -> String {
|
|
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
|
|
}
|
|
|
|
/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously)
|
|
/// and feed them through the inbox.
|
|
struct WebShell {
|
|
app: DesignApp,
|
|
inbox: Inbox,
|
|
}
|
|
|
|
impl eframe::App for WebShell {
|
|
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
|
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
|
|
for f in dropped {
|
|
let request = self.app.import_request("drop");
|
|
let inbox = self.inbox.clone();
|
|
let ctx = ctx.clone();
|
|
wasm_bindgen_futures::spawn_local(async move {
|
|
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
|
match f.bytes_async().await {
|
|
Ok(bytes) => {
|
|
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name, bytes });
|
|
ctx.request_repaint();
|
|
}
|
|
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
|
}
|
|
});
|
|
}
|
|
self.app.logic(ctx);
|
|
}
|
|
|
|
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
|
designcraft_ui_egui::drop_key_name_text(raw, ctx.text_edit_focused() || self.app.canvas_ime());
|
|
self.app.raw_input_hook(raw);
|
|
}
|
|
|
|
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
|
self.app.ui(ui);
|
|
}
|
|
}
|
|
|
|
fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
|
let open_inbox = inbox.clone();
|
|
Services {
|
|
open_async: Some(Box::new(move |request: ImportRequest| {
|
|
let inbox = open_inbox.clone();
|
|
let ctx = ctx.clone();
|
|
let dialog = if request.purpose == "swatches" {
|
|
rfd::AsyncFileDialog::new().add_filter("Swatch Exchange (ASE)", &["ase"])
|
|
} else if request.purpose == "place" {
|
|
rfd::AsyncFileDialog::new().add_filter("Graphics", IMAGE_EXTS)
|
|
} else {
|
|
rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS)
|
|
};
|
|
wasm_bindgen_futures::spawn_local(async move {
|
|
let Some(file) = dialog.pick_file().await else {
|
|
return;
|
|
};
|
|
let bytes = file.read().await;
|
|
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes });
|
|
ctx.request_repaint();
|
|
});
|
|
})),
|
|
// Exports ask for a name; the browser decides where the download goes.
|
|
pick_save: Some(Box::new(|name: &str| Some(name.to_string()))),
|
|
write: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes))),
|
|
download: Some(Box::new(|name: &str, bytes: &[u8]| {
|
|
if let Err(e) = download(name, bytes) {
|
|
log::error!("download of {name} failed: {e}");
|
|
}
|
|
})),
|
|
inbox: Some(inbox),
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
/// Trigger a browser download of `bytes` named after the last component of `path`.
|
|
fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
|
|
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
|
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "designcraft".into());
|
|
let window = web_sys::window().ok_or("no window")?;
|
|
let document = window.document().ok_or("no document")?;
|
|
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
|
let opts = web_sys::BlobPropertyBag::new();
|
|
opts.set_type(mime_for(&name));
|
|
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
|
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
|
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
|
|
a.set_href(&url);
|
|
a.set_download(&name);
|
|
a.style().set_property("display", "none").map_err(js)?;
|
|
let body = document.body().ok_or("no body")?;
|
|
body.append_child(&a).map_err(js)?;
|
|
a.click();
|
|
a.remove();
|
|
// Revoke after the click has been dispatched; the download keeps its own reference.
|
|
let revoke = wasm_bindgen::closure::Closure::once_into_js(move || {
|
|
web_sys::Url::revoke_object_url(&url).ok();
|
|
});
|
|
window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?;
|
|
Ok(())
|
|
}
|