GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.

use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};

use photocraft_doc::Document;
use photocraft_ui_egui::i18n;
use photocraft_ui_egui::served_fonts;
use photocraft_ui_egui::theme::AppTheme;
use photocraft_ui_egui::{FileDialogAnswer, FileDialogRequest, PhotocraftApp, Services};
use wasm_bindgen::JsCast as _;

use crate::preset_bridge::{ActionRecovery, SaveWarning};

type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
type PlaceInbox = photocraft_ui_egui::PlaceInbox;

/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and
/// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl) and swatches (.aco, .act, .ase), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
    "pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico",
    "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3", "iff", "lbm", "ilbm", "heic",
    "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", "aco", "act", "ase", "af",
    "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
/// Set once the module has trapped: the page is dead, so nothing is left to protect.
static STOPPED: AtomicBool = AtomicBool::new(false);
const CANVAS_ID: &str = "photocraft_canvas";

/// Fonts the host serves next to the page (`photocraft_ui_egui::served_fonts`): craft-fonts' manifest
/// format, each file relative to the site root. No manifest (a 404) means no served fonts.
const FONTS_MANIFEST: &str = "fonts/manifest.txt";

/// The served fonts: the manifest once read, and what the network has delivered.
#[derive(Default)]
struct ServedFonts {
    /// Font files by family, each with its Subresource Integrity value when the manifest has one.
    files: HashMap<String, Vec<(String, Option<String>)>>,
    /// Families fetched or being fetched: each one once per page load.
    fetched: HashSet<String>,
    /// Downloaded files waiting for the next frame: (family, bytes).
    arrived: Vec<(String, Vec<u8>)>,
}

type Served = Arc<Mutex<ServedFonts>>;

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 q = query();
        let force_cpu = q.contains("cpu");
        // `?free-mb=N`: the memory gates and the low-memory warning see only N MiB (diagnostics).
        if let Some(mb) = crate::diagnostics::free_mb(&q) {
            photocraft_raster::headroom::simulate_available(Some(crate::diagnostics::free_bytes(mb)));
        }
        let mut options = eframe::WebOptions::default();
        photocraft_ui_egui::gpu_canvas::use_adapter_limits(&mut options.wgpu_options.wgpu_setup);
        if q.contains("webgl")
            && let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
        {
            create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
        }
        // Hydrate before constructing an interactive session: a late load must never undo a
        // user deletion/reorder. Storage denial or timeout still opens a usable session.
        let (database, presets, mut preset_warnings) = match crate::indexed_presets::load().await {
            Ok((db, bridge, warnings)) => (Some(db), bridge, warnings),
            Err(e) => {
                let bridge = crate::preset_bridge::Bridge::default();
                bridge.unavailable(e);
                (None, bridge, Vec::new())
            }
        };
        let pen_target = canvas.clone();
        let runner = eframe::WebRunner::new();
        // After the runner's own panic handler, so the message is kept and the runner's handler
        // still runs (a panic aborts the module).
        keep_panic_message();
        // Before the app is built: a trap while building it shows the stopped message too.
        listen_for_trap();
        let result = runner
            .start(
                canvas,
                options,
                Box::new(move |cc| {
                    PhotocraftApp::setup_context(&cc.egui_ctx, AppTheme::pro());
                    let inbox: Inbox = Arc::default();
                    let place_inbox: PlaceInbox = Arc::default();
                    let served: Served = Arc::default();
                    load_font_manifest(served.clone(), cc.egui_ctx.clone());
                    let (session, warnings) = crate::preset_bridge::session(presets.clone());
                    let actions_revision = session.actions.list.revision();
                    preset_warnings.extend(warnings);
                    let drag = listen_drag(&pen_target);
                    let mut services = services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag));
                    let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions.list.actions().is_empty()));
                    services.load_prefs = Some(Box::new(move || initial.take().unwrap_or_else(stored_preferences)));
                    let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, services);
                    if !preset_warnings.is_empty() {
                        photocraft_ui_egui::notices::post(
                            &mut app,
                            i18n::t("Some brush presets could not be loaded"),
                            preset_warnings,
                            photocraft_ui_egui::notices::Tone::Bad,
                            None,
                        );
                    }
                    listen_pen(&pen_target, app.stylus.feed.clone());
                    app.set_theme(&cc.egui_ctx, AppTheme::pro());
                    if let Some(rs) = cc.wgpu_render_state.clone()
                        && !force_cpu
                    {
                        log::info!("photocraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
                        app.set_wgpu(rs);
                    }
                    let unsaved = Arc::new(AtomicBool::new(false));
                    guard_unload(unsaved.clone());
                    Ok(Box::new(WebShell {
                        app,
                        inbox,
                        place_inbox,
                        unsaved,
                        served,
                        database,
                        presets,
                        ui_language: "",
                        actions_revision,
                        prefs_revision: None,
                    }))
                }),
            )
            .await;
        if let Some(el) = document.get_element_by_id("photocraft_loading") {
            match result {
                Ok(()) => el.remove(),
                Err(e) => el.set_inner_html(&format!("<p>PhotoCraft failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>")),
            }
        }
    });
}

/// Pen pressure, tilt, twist and the eraser button from Pointer Events (eframe forwards none of them for pens) into
/// the app's stylus feed. The sample is kept through `pointerup` so the stroke's last points keep
/// their pressure; hovering, a mouse, or leaving the canvas clears it.
fn listen_pen(target: &web_sys::HtmlCanvasElement, feed: photocraft_ui_egui::stylus::StylusFeed) {
    use photocraft_ui_egui::stylus::PenSample;
    use wasm_bindgen::closure::Closure;
    for kind in ["pointerdown", "pointermove", "pointerup", "pointercancel", "pointerleave"] {
        let feed = feed.clone();
        let cb = Closure::<dyn FnMut(web_sys::PointerEvent)>::new(move |e: web_sys::PointerEvent| {
            let ty = e.type_();
            if ty == "pointerup" && e.pointer_type() == "pen" {
                return;
            }
            let pen = e.pointer_type() == "pen" && e.buttons() != 0 && ty != "pointercancel" && ty != "pointerleave";
            // W3C Pointer Events: `buttons` bit 5 (32) is the pen's eraser.
            let eraser = e.buttons() & 32 != 0;
            feed.set(pen.then(|| PenSample {
                pressure: e.pressure(),
                tilt_x: e.tilt_x() as f32,
                tilt_y: e.tilt_y() as f32,
                rotation: e.twist() as f32,
                eraser,
            }));
        });
        if target.add_event_listener_with_callback(kind, cb.as_ref().unchecked_ref()).is_ok() {
            cb.forget();
        }
    }
}

/// The pointer in a drag over the page, in CSS pixels relative to the viewport (`clientX`,
/// `clientY`): the last `dragover` or `drop` event's.
type DragPos = Rc<Cell<Option<(f32, f32)>>>;

/// Follows files dragged over the canvas. eframe's drop events carry no pointer position and the
/// page gets no pointer events during a drag, so this is where a drop lands: on the document's
/// canvas it places the files, elsewhere it opens them (#5749).
fn listen_drag(target: &web_sys::HtmlCanvasElement) -> DragPos {
    use wasm_bindgen::closure::Closure;
    let pos = DragPos::default();
    for kind in ["dragover", "drop"] {
        let pos = pos.clone();
        // A DragEvent is a MouseEvent: only its client position is read.
        let cb = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |e: web_sys::MouseEvent| pos.set(Some((e.client_x() as f32, e.client_y() as f32))));
        if target.add_event_listener_with_callback(kind, cb.as_ref().unchecked_ref()).is_ok() {
            cb.forget();
        }
    }
    pos
}

/// `Services::cursor_pos` for the web: the last drag position in egui points, mapped as eframe
/// maps pointer events (relative to the canvas, divided by the zoom factor).
fn drag_pos_service(canvas: web_sys::HtmlCanvasElement, pos: DragPos) -> photocraft_ui_egui::CursorPosFn {
    Box::new(move |ctx: &egui::Context| {
        let (x, y) = pos.get()?;
        let rect = canvas.get_bounding_client_rect();
        let zoom = ctx.zoom_factor();
        (zoom.is_finite() && zoom > 0.0).then(|| egui::pos2((x - rect.left() as f32) / zoom, (y - rect.top() as f32) / zoom))
    })
}

/// Closing or reloading the tab while a document has unsaved changes asks first, as closing the
/// desktop window does: the browser shows its own "Leave site?" prompt (#1380). `unsaved` is
/// refreshed every frame by [`WebShell`]. Once the module has stopped ([`STOPPED`]) the prompt is
/// skipped: the document can't be saved any more, and Reload is the only way on.
fn guard_unload(unsaved: Arc<AtomicBool>) {
    use wasm_bindgen::closure::Closure;
    let Some(window) = web_sys::window() else { return };
    let cb = Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
        if STOPPED.load(Ordering::Relaxed) {
            return;
        }
        if unsaved.load(Ordering::Relaxed) {
            e.prevent_default();
            // Older browsers show the prompt only when a return value is set.
            e.set_return_value("");
        }
    });
    if window.add_event_listener_with_callback("beforeunload", cb.as_ref().unchecked_ref()).is_ok() {
        cb.forget();
    }
}

/// Keeps the message of a panic, then calls the handler that was installed before (the web
/// runner's, which logs it). A panic aborts the module, so the trap that follows has no message of
/// its own; this is what lets the stopped page tell an internal error from running out of memory.
fn keep_panic_message() {
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        crate::diagnostics::record_panic(&info.to_string());
        previous(info);
    }));
}

/// Shows the page's static `#photocraft_stopped` message when the module traps. The page learns of
/// a trap as an uncaught `WebAssembly.RuntimeError` (the `error` event) or, inside a spawned
/// future, an unhandled rejection. The module may be mid-call and its runner still borrowed, so
/// the handler touches no app state: it sets [`STOPPED`] and the element, nothing more.
fn listen_for_trap() {
    use wasm_bindgen::closure::Closure;
    let Some(window) = web_sys::window() else { return };
    let on_error = Closure::<dyn FnMut(web_sys::ErrorEvent)>::new(move |e: web_sys::ErrorEvent| {
        let error = e.error();
        let (name, message) = error_parts(&error, &e.message());
        if crate::diagnostics::is_trap(&name, &message) {
            show_stopped(&message);
        }
    });
    if window.add_event_listener_with_callback("error", on_error.as_ref().unchecked_ref()).is_ok() {
        on_error.forget();
    }
    let on_rejection = Closure::<dyn FnMut(web_sys::PromiseRejectionEvent)>::new(move |e: web_sys::PromiseRejectionEvent| {
        let (name, message) = error_parts(&e.reason(), "");
        if crate::diagnostics::is_trap(&name, &message) {
            show_stopped(&message);
        }
    });
    if window.add_event_listener_with_callback("unhandledrejection", on_rejection.as_ref().unchecked_ref()).is_ok() {
        on_rejection.forget();
    }
}

/// The name and message of a thrown value; `fallback` is the event's own message when the value
/// is not an `Error`.
fn error_parts(value: &wasm_bindgen::JsValue, fallback: &str) -> (String, String) {
    match value.dyn_ref::<js_sys::Error>() {
        Some(error) => (String::from(error.name()), String::from(error.message())),
        None => (String::new(), value.as_string().unwrap_or_else(|| fallback.to_owned())),
    }
}

/// Reveals `#photocraft_stopped` with the cause. Does as little as possible.
fn show_stopped(trap_message: &str) {
    STOPPED.store(true, Ordering::Relaxed);
    let detail = crate::diagnostics::detail(crate::diagnostics::take_panic().as_deref(), trap_message);
    let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
    if let Some(el) = document.get_element_by_id("photocraft_stopped_detail") {
        el.set_text_content(Some(&detail));
    }
    if let Some(el) = document.get_element_by_id("photocraft_stopped") {
        let _ = el.remove_attribute("hidden");
    }
}

fn query() -> String {
    web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}

/// Reads the served font manifest, if the host has one, and lists its families in the font menus.
fn load_font_manifest(served: Served, ctx: egui::Context) {
    wasm_bindgen_futures::spawn_local(async move {
        // Most hosts serve no fonts: a missing manifest is the normal case, not an error.
        let Ok(bytes) = fetch_bytes(FONTS_MANIFEST, None).await else { return };
        let text = String::from_utf8_lossy(&bytes);
        // A host that answers unknown paths with its HTML page (single-page app fallback).
        if text.trim_start().starts_with('<') {
            return;
        }
        let (fonts, skipped) = served_fonts::parse_manifest(&text);
        for s in skipped {
            log::warn!("{FONTS_MANIFEST}: skipped {s}");
        }
        let mut files: HashMap<String, Vec<(String, Option<String>)>> = HashMap::new();
        for f in &fonts {
            files.entry(f.family.clone()).or_default().push((f.file.clone(), f.integrity.clone()));
        }
        log::info!("photocraft-web: {} served font families", files.len());
        served.lock().unwrap_or_else(PoisonError::into_inner).files = files;
        // The families for the font menus, and the script fallbacks (the manifest's `scripts`).
        served_fonts::add_fonts(&fonts);
        // Fetch now the fallbacks of the scripts the browser's languages use (an Arabic reader gets
        // the Arabic font before typing); the rest is fetched when text or a font menu needs it.
        // Also the interface language's: `serve_fonts` asked for it once already, maybe before
        // this manifest arrived, when no fallback was registered yet.
        let ui_language = photocraft_ui_egui::i18n::current().code();
        served_fonts::request_for_languages(browser_languages().iter().map(String::as_str).chain([ui_language]));
        ctx.request_repaint();
    });
}

/// The browser's preferred languages (`navigator.languages`, e.g. `["ar-EG", "en"]`).
fn browser_languages() -> Vec<String> {
    web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|l| l.as_string()).collect()).unwrap_or_default()
}

/// GET `url` (a relative path on the same origin) and read the whole body. With `integrity` (a
/// Subresource Integrity value), the browser rejects a body whose hash differs.
async fn fetch_bytes(url: &str, integrity: Option<&str>) -> Result<Vec<u8>, String> {
    use wasm_bindgen_futures::JsFuture;
    if !served_fonts::is_relative_path(url) {
        return Err("url must be a relative path".into());
    }
    let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
    let window = web_sys::window().ok_or("no window")?;
    let init = web_sys::RequestInit::new();
    init.set_mode(web_sys::RequestMode::SameOrigin);
    if let Some(sri) = integrity {
        init.set_integrity(sri);
    }
    let request = window.fetch_with_str_and_init(url, &init);
    let resp: web_sys::Response = JsFuture::from(request).await.map_err(js)?.dyn_into().map_err(|_| "not a Response")?;
    if !resp.ok() {
        return Err(format!("HTTP {}", resp.status()));
    }
    let body = JsFuture::from(resp.array_buffer().map_err(js)?).await.map_err(js)?;
    Ok(js_sys::Uint8Array::new(&body).to_vec())
}

/// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously,
/// so the app's own drop path can't handle them) and feed them through the inboxes.
struct WebShell {
    app: Box<PhotocraftApp>,
    /// Dropped files to open as documents.
    inbox: Inbox,
    /// Dropped files to place on the active document's canvas.
    place_inbox: PlaceInbox,
    /// Read by the `beforeunload` listener ([`guard_unload`]).
    unsaved: Arc<AtomicBool>,
    served: Served,
    database: Option<web_sys::IdbDatabase>,
    presets: crate::preset_bridge::Bridge,
    actions_revision: u64,
    prefs_revision: Option<u64>,
    /// The interface language whose served script font was last asked for.
    ui_language: &'static str,
}

impl WebShell {
    fn save_presets(&mut self, ctx: &egui::Context) {
        let session = &self.app.session;
        if self.actions_revision != session.actions.list.revision() {
            // The engine can reject an oversized definition before calling the backend.
            // Never stage that edit's keys with the last successfully queued definitions.
            self.presets.verify_action_definitions(&session.actions);
            self.actions_revision = session.actions.list.revision();
        }
        let prefs_revision = session.prefs.rev();
        if self.prefs_revision != Some(prefs_revision) {
            self.presets.stage_action_keys(crate::preset_bridge::ActionKeys::from_preferences(session.prefs()));
            self.prefs_revision = Some(prefs_revision);
        }
        if let Some(db) = self.database.clone()
            && let Some(batch) = self.presets.begin()
        {
            let presets = self.presets.clone();
            let wake = ctx.clone();
            wasm_bindgen_futures::spawn_local(async move {
                let result = crate::indexed_presets::write(&db, &batch).await;
                if let Err(e) = &result {
                    log::error!("Could not save browser presets: {}", e.message());
                }
                presets.finish(batch, result);
                wake.request_repaint();
            });
        }
        self.unsaved.store(self.app.has_unsaved_work() || self.presets.unsaved(), Ordering::Relaxed);
    }

    /// Fetches the served families asked for (picked in a font menu, or needed by a layout) and
    /// installs the files that arrived.
    fn serve_fonts(&mut self, ctx: &egui::Context) {
        // The interface language's script font draws its labels (Arabic, Japanese…).
        let ui_language = photocraft_ui_egui::i18n::current().code();
        if ui_language != self.ui_language {
            self.ui_language = ui_language;
            served_fonts::request_for_languages([ui_language]);
        }
        let requested = served_fonts::take_requests();
        let (fetch, arrived) = {
            let mut s = self.served.lock().unwrap_or_else(PoisonError::into_inner);
            let mut fetch = Vec::new();
            for family in requested {
                if let Some(files) = s.files.get(&family).cloned()
                    && s.fetched.insert(family.clone())
                {
                    fetch.extend(files.into_iter().map(|(file, integrity)| (family.clone(), file, integrity)));
                }
            }
            (fetch, std::mem::take(&mut s.arrived))
        };
        for (family, file, integrity) in fetch {
            let served = self.served.clone();
            let ctx = ctx.clone();
            wasm_bindgen_futures::spawn_local(async move {
                match fetch_bytes(&file, integrity.as_deref()).await {
                    Ok(bytes) => {
                        served.lock().unwrap_or_else(PoisonError::into_inner).arrived.push((family, bytes));
                        ctx.request_repaint();
                    }
                    Err(e) => log::error!("couldn't fetch served font {file}: {e}"),
                }
            });
        }
        served_fonts::install(&mut self.app, ctx, arrived);
    }
}

impl eframe::App for WebShell {
    fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
        // A tap reaches eframe as Pointer Events and Touch Events: keep one press per tap, or the
        // twin press closes the menu the first one opened (#2095).
        photocraft_ui_egui::touch_twins::drop_twins(ctx, raw_input);
        // The clipboard key mapping (`Event::PasteImage`), legacy pinch, pen-hold and titlebar
        // normalization live in the app hook and must run here too.
        eframe::App::raw_input_hook(&mut self.app, ctx, raw_input);
    }

    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));
        if !dropped.is_empty() {
            let names: Vec<String> =
                dropped.iter().map(|f| f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into())).collect();
            // Decided now, where the drop landed: on the document's canvas the files are placed
            // as layers (as on the desktop), elsewhere opened.
            let places = self.app.dropped_on_canvas(ctx, &names);
            let target_doc = self.app.session.active().map(|st| st.doc.id);
            let files: Vec<_> = dropped.into_iter().zip(names).zip(places).map(|((f, name), place)| (f, name, place, target_doc)).collect();
            let (inbox, place_inbox) = (self.inbox.clone(), self.place_inbox.clone());
            let ctx = ctx.clone();
            // One after another, so they open or place in the order they were dropped.
            wasm_bindgen_futures::spawn_local(async move {
                for (f, name, place, target_doc) in files {
                    match f.bytes_async().await {
                        Ok(bytes) => {
                            if place {
                                if let Some(doc) = target_doc {
                                    let mut queued = place_inbox.lock().unwrap_or_else(PoisonError::into_inner);
                                    let held = queued.iter().fold(0usize, |sum, (_, _, b)| sum.saturating_add(b.len()));
                                    // Reads that finish before the next frame drains the inbox are
                                    // bounded like the app's own drop queue.
                                    if photocraft_ui_egui::file_open::place_inbox_takes(queued.len(), held, bytes.len()) {
                                        queued.push((doc, name, bytes));
                                    } else {
                                        log::warn!("dropped file {name} wasn't placed: too many dropped files are waiting");
                                    }
                                }
                            } else {
                                inbox.lock().unwrap_or_else(PoisonError::into_inner).push((name, bytes));
                            }
                            ctx.request_repaint();
                        }
                        Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
                    }
                }
            });
        }
        self.serve_fonts(ctx);
        self.app.logic_frame(ctx, frame);
        self.save_presets(ctx);
    }

    fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
        // Only while a change is unsaved. Storage the browser denies from the start (a
        // sandboxed iframe, blocked site data) loses nothing until the first change, and that
        // change brings the banner with the reason.
        if self.presets.unsaved()
            && let Some(warning) = self.presets.error()
        {
            egui::Panel::top("browser_preset_storage").show(ui, |ui| {
                let tokens = self.app.ui.theme.tokens();
                // Put retry first so floating brush windows cannot cover the control.
                ui.horizontal_wrapped(|ui| {
                    if self.database.is_some() && ui.button(i18n::t("Retry saving presets")).clicked() {
                        self.presets.retry();
                        ui.ctx().request_repaint();
                    }
                    match &warning {
                        SaveWarning::Actions(error, _) => {
                            ui.colored_label(tokens.warning, i18n::t("Actions"));
                            ui.colored_label(tokens.warning, error.as_str());
                        }
                        SaveWarning::Presets(error) => {
                            ui.colored_label(tokens.warning, i18n::fmt(i18n::t("Brush preset changes are not saved: {error}"), &[("error", error)]));
                        }
                    }
                });
                match warning {
                    SaveWarning::Actions(_, Some(ActionRecovery::Reopen)) => {
                        ui.label(i18n::t("Export a copy of any unsaved Actions before reopening this page. Reopening can discard unsaved changes."));
                    }
                    SaveWarning::Actions(_, Some(ActionRecovery::Preserve)) => {
                        ui.label(i18n::t("Keep this tab open and export a copy of any available Actions."));
                    }
                    SaveWarning::Actions(_, None) => {}
                    SaveWarning::Presets(_) => {
                        ui.label(if self.database.is_some() {
                            i18n::t("Keep this tab open to retain your brushes.")
                        } else {
                            i18n::t("Browser storage is unavailable; brushes are session-only. Keep this tab open to retain them.")
                        });
                    }
                }
            });
        }
        self.app.ui_frame(ui, frame);
        self.save_presets(ui.ctx());
    }
}

fn services(inbox: Inbox, place_inbox: PlaceInbox, cursor_pos: photocraft_ui_egui::CursorPosFn) -> Services {
    Services {
        import: Some(Box::new(|name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions| {
            photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
        })),
        export: Some(Box::new(|doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings| {
            photocraft_io::export(doc, path, &settings.io_options()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())
        })),
        file_dialog: Some(Box::new(|request, _parent, reply| match request {
            // The browser's file picker hands over the files' contents, not paths. File › Open
            // asks for several files (`multiple`), each opened in its own tab.
            FileDialogRequest::Open { multiple, extensions, .. } => wasm_bindgen_futures::spawn_local(async move {
                let dialog = if let Some(exts) = extensions {
                    rfd::AsyncFileDialog::new().add_filter("Supported Files", &exts)
                } else {
                    rfd::AsyncFileDialog::new().add_filter("All Formats", OPEN_EXTS).add_filter("SVG", SVG_EXTS)
                };
                let answer = if multiple {
                    match dialog.pick_files().await {
                        Some(picked) if !picked.is_empty() => {
                            let mut files = Vec::with_capacity(picked.len());
                            for file in picked {
                                files.push((file.file_name(), file.read().await));
                            }
                            Some(FileDialogAnswer::ContentsMany(files))
                        }
                        _ => None,
                    }
                } else {
                    match dialog.pick_file().await {
                        Some(file) => Some(FileDialogAnswer::Contents(file.file_name(), file.read().await)),
                        None => None,
                    }
                };
                reply.send(answer);
            }),
            // Browser folder handles cannot be represented as filesystem paths for engine commands.
            FileDialogRequest::Folder { .. } => reply.send(None),
            // No save dialog on the web: the suggested name becomes the download name.
            FileDialogRequest::Save { suggested } => {
                let name = std::path::Path::new(&suggested).file_name().map_or_else(|| suggested.clone(), |n| n.to_string_lossy().to_string());
                reply.send(Some(FileDialogAnswer::SaveTo(name)));
            }
        })),
        write: Some(Box::new(|path: &str, bytes: &[u8]| download(path, bytes))),
        // A download may be cancelled and never reports back: it doesn't save the document.
        write_unconfirmed: true,
        inbox: Some(inbox),
        place_inbox: Some(place_inbox),
        cursor_pos: Some(cursor_pos),
        save_prefs: Some(Box::new(save_local_preferences)),
        load_gpu_memo: None,
        save_gpu_memo: None,
        shader_compiler: None,
        ..Default::default()
    }
}

const PREFS_KEY: &str = "photocraft.preferences";

fn local_storage() -> Option<web_sys::Storage> {
    web_sys::window()?.local_storage().ok().flatten()
}

fn stored_preferences() -> Option<String> {
    local_storage()?.get_item(PREFS_KEY).ok().flatten()
}

fn load_initial_preferences(presets: &crate::preset_bridge::Bridge, legacy_definitions_loaded: bool) -> Option<String> {
    use crate::preset_bridge::ActionKeys;
    use serde_json::{Value, json};

    let stored = stored_preferences();
    let mut prefs: Value = stored.as_deref().and_then(|text| serde_json::from_str(text).ok()).filter(Value::is_object).unwrap_or_else(|| json!({}));
    if let Some(keys) = presets.committed_action_keys().or_else(|| (!legacy_definitions_loaded).then(ActionKeys::default)) {
        // An authoritative empty map also replaces old rows. When storage could not be read,
        // the old localStorage rows cannot be matched with a known definition generation.
        for section in ["shortcuts", "alternateShortcuts"] {
            if !prefs.get(section).is_some_and(Value::is_object) {
                prefs[section] = json!({});
            }
        }
        keys.overlay(&mut prefs).ok()?;
        Some(prefs.to_string())
    } else {
        presets.load_action_keys(0, ActionKeys::from_legacy(&prefs));
        stored
    }
}

fn save_local_preferences(text: &str) -> Result<(), String> {
    let storage = local_storage().ok_or("no localStorage")?;
    let stored = storage.get_item(PREFS_KEY).map_err(|e| format!("{e:?}"))?;
    let legacy = stored.as_deref().and_then(|text| serde_json::from_str(text).ok()).unwrap_or(serde_json::Value::Null);
    let mut ordinary = serde_json::from_str(text).map_err(|e| e.to_string())?;
    // A crash before the first v2 write still needs the original legacy keys. New Action
    // bindings, including removals, belong to the same IndexedDB record as their definitions.
    crate::preset_bridge::replace_action_keys(&mut ordinary, &legacy)?;
    storage.set_item(PREFS_KEY, &ordinary.to_string()).map_err(|e| format!("{e:?}"))
}

/// 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(|| "photocraft".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(())
}

fn mime_for(name: &str) -> &'static str {
    match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("tif" | "tiff") => "image/tiff",
        Some("webp") => "image/webp",
        Some("gif") => "image/gif",
        Some("psd" | "psb") => "image/vnd.adobe.photoshop",
        Some("ora") => "image/openraster",
        Some("kra" | "krz") => "application/x-krita",
        _ => "application/octet-stream",
    }
}