//! The browser shell: platform services, the embedding page, and the eframe web runner. use std::sync::Arc; use craft::automation::control::ControlChannel; use craft::host::target::ShellInfo; use craft::host::{AppInfo, Host, Wake}; use craft::platform::browser_files::BrowserFiles; use craft::platform::open::{DroppedFile, FileIntake, IntakeSender}; use craft::settings::Location; use craft::ui::runtime::InstallSpec; use craft::ui::runtime::env::SystemReader; use craft::web_host::link::role_token; use craft::window::policy::Frame; use craft::window::system::SystemWindows; use deckcraft_ui_egui::{Platform, SlideApp}; use wasm_bindgen::JsCast as _; const CANVAS_ID: &str = "deckcraft_canvas"; const LOADING_ID: &str = "deckcraft_loading"; /// Start the browser shell: install logging, locate the canvas, launch the eframe runner, /// build the sample or blank deck, and replace the loading element when launch finishes. pub fn start() { eframe::WebLogger::init(log::LevelFilter::Info).ok(); craft::font_catalog::app::start(craft::font_catalog::app::AppFonts { store_poll: None, ..Default::default() }); 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::().ok()) else { log::error!("missing "); return; }; // Host modes (`craft-web-host`): `?host=parent`, a same-origin page framing DeckCraft, // opens presentations in it and stores what it saves (`host`); `data-host="page"` on the // canvas opts a page in that runs DeckCraft in its own document. The presenter popup is // never the framed page. let hash = web_sys::window().and_then(|window| window.location().hash().ok()).unwrap_or_default(); let hosted = role_token(&hash).is_none(); let bridge = if hosted { crate::host::Bridge::detect(&canvas) } else { None }; if hosted && bridge.is_none() && query_param("host").as_deref() == Some("parent") { log::warn!("?host=parent needs a framing page on the same origin; saves download instead"); } let app_bridge = bridge.clone(); let mut options = eframe::WebOptions::default(); if query_has("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!("deckcraft-web {}: wgpu backend {:?}", env!("CARGO_PKG_VERSION"), rs.adapter.get_info().backend); } let shell_info = ShellInfo::default(); let repaint = cc.egui_ctx.clone(); let install = InstallSpec::new(shell_info, Arc::new(SystemWindows)) .system(SystemReader::start(move || repaint.request_repaint())) .app_id(deckcraft_ui_egui::os_window::app_id()); if role_token(&hash).is_some() { let presenter = crate::presenter::PopupApp::new(&cc.egui_ctx, install).map_err(std::io::Error::other)?; return Ok(Box::new(presenter) as Box); } let wake = cc.egui_ctx.clone(); let files = BrowserFiles::new(move || wake.request_repaint()); let files = if app_bridge.is_some() { files.page_saves(craft::web_host::files::page_save) } else { files }; let host = Host::builder(AppInfo { id: "deckcraft", name: "DeckCraft", version: env!("CARGO_PKG_VERSION") }) .files(Arc::new(files)) .build(); let wake = cc.egui_ctx.clone(); let (intake, drops) = FileIntake::new(Wake::new(move || wake.request_repaint())); let platform = Platform { install, host, settings: Location::Memory, intake: Some(intake), audio_out: None, control: Some(ControlChannel::new(crate::api::install(cc.egui_ctx.clone()))), frame: Frame::Native, at_exit: None, }; if let Some(bridge) = &app_bridge { bridge.listen(cc.egui_ctx.clone()); } let mut app = SlideApp::new(&cc.egui_ctx, platform).map_err(|error| std::io::Error::other(error.to_string()))?; app.services.presenter = crate::presenter::opener(&cc.egui_ctx); // In host mode the parent sends the presentation to edit; no sample meanwhile. if app_bridge.is_some() { if let Err(e) = app.start_for_host() { log::error!("new presentation: {e}"); } } else if !query_has("blank") { if let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) { log::error!("sample deck: {e}"); } } else if let Err(e) = app.run("file.new", serde_json::json!({})) { log::error!("new presentation: {e}"); } if query_has("show") { app.start_show(0, false); } if app_bridge.is_some() && let Some(author) = query_param("author") { crate::host::Bridge::set_author(&mut app, &author); } Ok(Box::new(WebShell { app, bridge: app_bridge, drops })) }), ) .await; // Ready only once the runner is up: starting can still fail after the app is made. if let Some(bridge) = &bridge { match &result { Ok(()) => bridge.post_ready(), Err(e) => bridge.post_failed(&format!("{e:?}")), } } if let Some(el) = document.get_element_by_id(LOADING_ID) { match result { Ok(()) => el.remove(), Err(e) => { el.set_text_content(None); for text in [format!("DeckCraft failed to start: {e:?}"), "A browser with WebGPU or WebGL2 is required.".to_owned()] { match document.create_element("p") { Ok(paragraph) => { paragraph.set_text_content(Some(&text)); if let Err(error) = el.append_child(¶graph) { log::error!("couldn't display startup failure: {error:?}"); } } Err(error) => log::error!("couldn't display startup failure: {error:?}"), } } } } } }); } fn query() -> String { web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default() } fn query_param(key: &str) -> Option { web_sys::UrlSearchParams::new_with_str(&query()).ok()?.get(key) } /// Whether the URL has the flag `key` (`?show`, `&blank=1`). A whole parameter, never a substring: /// `?author=` is free text. fn query_has(key: &str) -> bool { web_sys::UrlSearchParams::new_with_str(&query()).is_ok_and(|q| q.has(key)) } /// Opens the embedding page's files before app logic and reports dirtiness afterwards. struct WebShell { app: SlideApp, /// The parent page that keeps the files (`?host=parent`). bridge: Option, /// Feeds the files dropped on the canvas into the app's intake once the browser has read them. drops: IntakeSender, } impl eframe::App for WebShell { /// Delegate one eframe logic pass to the wrapped application, opening the files the parent /// page sent first and telling it about unsaved changes after. fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { if let Some(bridge) = &self.bridge { bridge.open_files(&mut self.app); } self.app.logic(ctx); if let Some(bridge) = &self.bridge { bridge.report_dirty(&self.app); } if self.app.show.is_none() && let Some(host) = self.app.services.presenter.as_mut() { host.close(); } } /// Delegate only this pass's input to the app's framework hooks. Browsers read dropped files /// only asynchronously: this pass's drops are taken here and reach the app's intake, in drop /// order, once read. A file that cannot be read arrives without bytes, which the app reports. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { let dropped = std::mem::take(&mut raw.dropped_files); if !dropped.is_empty() { let drops = self.drops.clone(); wasm_bindgen_futures::spawn_local(async move { let mut files = Vec::with_capacity(dropped.len()); for file in dropped { let name = file.path().file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(); let bytes = match file.bytes_async().await { Ok(bytes) => Some(bytes.into()), Err(error) => { log::error!("couldn't read dropped file {name}: {error}"); None } }; files.push(DroppedFile { path: None, name, bytes }); } drops.dropped(files); }); } self.app.raw_input_hook(ctx, raw); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.app.ui(ui); } }