Skip to main content

eframe/web/
mod.rs

1//! [`egui`] bindings for web apps (compiling to WASM).
2
3#![expect(clippy::missing_errors_doc)] // So many `-> Result<_, JsValue>`
4#![expect(clippy::unwrap_used)] // TODO(emilk): remove unwraps
5
6mod app_runner;
7mod backend;
8mod canvas_glyphs;
9mod dropped_file;
10mod events;
11mod input;
12mod panic_handler;
13mod text_agent;
14mod web_logger;
15mod web_runner;
16
17/// Access to the browser screen reader.
18#[cfg(feature = "web_screen_reader")]
19pub mod screen_reader;
20
21/// Access to local browser storage.
22pub mod storage;
23
24pub(crate) use app_runner::AppRunner;
25pub use panic_handler::{PanicHandler, PanicSummary};
26pub use web_logger::WebLogger;
27pub use web_runner::WebRunner;
28
29#[cfg(not(any(feature = "glow", feature = "wgpu_no_default_features")))]
30compile_error!("You must enable either the 'glow' or 'wgpu' feature");
31
32mod web_painter;
33
34#[cfg(feature = "glow")]
35mod web_painter_glow;
36
37#[cfg(feature = "wgpu_no_default_features")]
38mod web_painter_wgpu;
39
40pub use backend::*;
41
42use egui::Theme;
43use js_sys::Object;
44use wasm_bindgen::prelude::*;
45use web_sys::{Document, MediaQueryList, Node};
46
47use input::{
48    button_from_mouse_event, modifiers_from_kb_event, modifiers_from_mouse_event,
49    modifiers_from_wheel_event, pos_from_mouse_event, primary_touch_pos, push_touches,
50    text_from_keyboard_event, translate_key,
51};
52
53// ----------------------------------------------------------------------------
54
55/// Debug browser resizing?
56const DEBUG_RESIZE: bool = false;
57
58pub(crate) fn string_from_js_value(value: &JsValue) -> String {
59    value.as_string().unwrap_or_else(|| format!("{value:#?}"))
60}
61
62/// Returns the `Element` with active focus.
63///
64/// Elements can only be focused if they are:
65/// - `<a>`/`<area>` with an `href` attribute
66/// - `<input>`/`<select>`/`<textarea>`/`<button>` which aren't `disabled`
67/// - any other element with a `tabindex` attribute
68pub(crate) fn focused_element(root: &Node) -> Option<web_sys::Element> {
69    if let Some(document) = root.dyn_ref::<Document>() {
70        document.active_element()
71    } else if let Some(shadow) = root.dyn_ref::<web_sys::ShadowRoot>() {
72        shadow.active_element()
73    } else {
74        None
75    }
76}
77
78pub(crate) fn has_focus<T: JsCast>(element: &T) -> bool {
79    fn try_has_focus<T: JsCast>(element: &T) -> Option<bool> {
80        let element = element.dyn_ref::<web_sys::Element>()?;
81        let root = element.get_root_node();
82
83        let focused_element = focused_element(&root)?;
84        Some(element == &focused_element)
85    }
86    try_has_focus(element).unwrap_or(false)
87}
88
89/// Focus the given element without scrolling it into view.
90///
91/// Scrolling the element into view would scroll the whole page when
92/// the app is embedded in a larger scrollable page,
93/// see <https://github.com/emilk/egui/issues/8295>.
94pub(crate) fn focus_without_scroll(element: &web_sys::HtmlElement) -> Result<(), JsValue> {
95    let options = web_sys::FocusOptions::new();
96    options.set_prevent_scroll(true);
97    element.focus_with_options(&options)
98}
99
100/// Current time in seconds (since undefined point in time).
101///
102/// Monotonically increasing.
103pub fn now_sec() -> f64 {
104    web_sys::window()
105        .expect("should have a Window")
106        .performance()
107        .expect("should have a Performance")
108        .now()
109        / 1000.0
110}
111
112/// The native GUI scale factor, taking into account the browser zoom.
113///
114/// Corresponds to [`window.devicePixelRatio`](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio) in JavaScript.
115pub fn native_pixels_per_point() -> f32 {
116    let pixels_per_point = web_sys::window().unwrap().device_pixel_ratio() as f32;
117    if pixels_per_point > 0.0 && pixels_per_point.is_finite() {
118        pixels_per_point
119    } else {
120        1.0
121    }
122}
123
124/// Ask the browser about the preferred system theme.
125///
126/// `None` means unknown.
127pub fn system_theme() -> Option<egui::Theme> {
128    let window = web_sys::window()?;
129    if does_prefer_color_scheme(&window, Theme::Dark) == Some(true) {
130        Some(Theme::Dark)
131    } else if does_prefer_color_scheme(&window, Theme::Light) == Some(true) {
132        Some(Theme::Light)
133    } else {
134        None
135    }
136}
137
138fn does_prefer_color_scheme(window: &web_sys::Window, theme: Theme) -> Option<bool> {
139    Some(prefers_color_scheme(window, theme).ok()??.matches())
140}
141
142fn prefers_color_scheme(
143    window: &web_sys::Window,
144    theme: Theme,
145) -> Result<Option<MediaQueryList>, JsValue> {
146    let theme = match theme {
147        Theme::Dark => "dark",
148        Theme::Light => "light",
149    };
150    window.match_media(format!("(prefers-color-scheme: {theme})").as_str())
151}
152
153/// Returns the canvas in client coordinates.
154fn canvas_content_rect(canvas: &web_sys::HtmlCanvasElement) -> egui::Rect {
155    let bounding_rect = canvas.get_bounding_client_rect();
156
157    let mut rect = egui::Rect::from_min_max(
158        egui::pos2(bounding_rect.left() as f32, bounding_rect.top() as f32),
159        egui::pos2(bounding_rect.right() as f32, bounding_rect.bottom() as f32),
160    );
161
162    // We need to subtract padding and border:
163    if let Some(window) = web_sys::window()
164        && let Ok(Some(style)) = window.get_computed_style(canvas)
165    {
166        let get_property = |name: &str| -> Option<f32> {
167            let property = style.get_property_value(name).ok()?;
168            property.trim_end_matches("px").parse::<f32>().ok()
169        };
170
171        rect.min.x += get_property("padding-left").unwrap_or_default();
172        rect.min.y += get_property("padding-top").unwrap_or_default();
173        rect.max.x -= get_property("padding-right").unwrap_or_default();
174        rect.max.y -= get_property("padding-bottom").unwrap_or_default();
175    }
176
177    rect
178}
179
180fn canvas_size_in_points(canvas: &web_sys::HtmlCanvasElement, ctx: &egui::Context) -> egui::Vec2 {
181    // ctx.pixels_per_point can be outdated
182
183    let pixels_per_point = ctx.zoom_factor() * native_pixels_per_point();
184
185    egui::vec2(
186        canvas.width() as f32 / pixels_per_point,
187        canvas.height() as f32 / pixels_per_point,
188    )
189}
190
191// ----------------------------------------------------------------------------
192
193/// Set the cursor icon.
194fn set_cursor_icon(canvas: &web_sys::HtmlCanvasElement, cursor: egui::CursorIcon) -> Option<()> {
195    canvas
196        .style()
197        .set_property("cursor", cursor_web_name(cursor))
198        .ok()
199}
200
201/// Set the clipboard text.
202fn set_clipboard_text(s: &str) {
203    if let Some(window) = web_sys::window() {
204        if !window.is_secure_context() {
205            log::error!(
206                "Clipboard is not available because we are not in a secure context. \
207                See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
208            );
209            return;
210        }
211        let promise = window.navigator().clipboard().write_text(s);
212        let future = async move {
213            if let Err(err) = promise.await {
214                log::error!("Copy/cut action failed: {}", string_from_js_value(&err));
215            }
216        };
217        js_sys::futures::spawn_local(future);
218    }
219}
220
221/// Set the clipboard image.
222fn set_clipboard_image(image: &egui::ColorImage) {
223    if let Some(window) = web_sys::window() {
224        if !window.is_secure_context() {
225            log::error!(
226                "Clipboard is not available because we are not in a secure context. \
227                See https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts"
228            );
229            return;
230        }
231
232        let png_bytes = to_image(image).and_then(|image| to_png_bytes(&image));
233        let png_bytes = match png_bytes {
234            Ok(png_bytes) => png_bytes,
235            Err(err) => {
236                log::error!("Failed to encode image to png: {err}");
237                return;
238            }
239        };
240
241        let mime = "image/png";
242
243        let item = match create_clipboard_item(mime, &png_bytes) {
244            Ok(item) => item,
245            Err(err) => {
246                log::error!("Failed to copy image: {}", string_from_js_value(&err));
247                return;
248            }
249        };
250        let items = js_sys::Array::of1(&item);
251        let promise = window.navigator().clipboard().write(&items);
252        let future = async move {
253            if let Err(err) = promise.await {
254                log::error!(
255                    "Copy/cut image action failed: {}",
256                    string_from_js_value(&err)
257                );
258            }
259        };
260        js_sys::futures::spawn_local(future);
261    }
262}
263
264fn to_image(image: &egui::ColorImage) -> Result<image::RgbaImage, String> {
265    profiling::function_scope!();
266    image::RgbaImage::from_raw(
267        image.width() as _,
268        image.height() as _,
269        bytemuck::cast_slice(&image.pixels).to_vec(),
270    )
271    .ok_or_else(|| "Invalid IconData".to_owned())
272}
273
274fn to_png_bytes(image: &image::RgbaImage) -> Result<Vec<u8>, String> {
275    profiling::function_scope!();
276    let mut png_bytes: Vec<u8> = Vec::new();
277    image
278        .write_to(
279            &mut std::io::Cursor::new(&mut png_bytes),
280            image::ImageFormat::Png,
281        )
282        .map_err(|err| err.to_string())?;
283    Ok(png_bytes)
284}
285
286fn create_clipboard_item(mime: &str, bytes: &[u8]) -> Result<web_sys::ClipboardItem, JsValue> {
287    let array = js_sys::Uint8Array::from(bytes);
288    let blob_parts = js_sys::Array::new();
289    blob_parts.push(&array);
290
291    let options = web_sys::BlobPropertyBag::new();
292    options.set_type(mime);
293
294    let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&blob_parts, &options)?;
295
296    let items = js_sys::Object::new();
297
298    #[expect(unsafe_code, unused_unsafe)] // Weird false positive
299    // SAFETY: I hope so
300    unsafe {
301        js_sys::Reflect::set(&items, &JsValue::from_str(mime), &blob)?
302    };
303
304    let clipboard_item = web_sys::ClipboardItem::new_with_record_from_str_to_blob_promise(&items)?;
305
306    Ok(clipboard_item)
307}
308
309fn cursor_web_name(cursor: egui::CursorIcon) -> &'static str {
310    match cursor {
311        egui::CursorIcon::Alias => "alias",
312        egui::CursorIcon::AllScroll => "all-scroll",
313        egui::CursorIcon::Cell => "cell",
314        egui::CursorIcon::ContextMenu => "context-menu",
315        egui::CursorIcon::Copy => "copy",
316        egui::CursorIcon::Crosshair => "crosshair",
317        egui::CursorIcon::Default => "default",
318        egui::CursorIcon::Grab => "grab",
319        egui::CursorIcon::Grabbing => "grabbing",
320        egui::CursorIcon::Help => "help",
321        egui::CursorIcon::Move => "move",
322        egui::CursorIcon::NoDrop => "no-drop",
323        egui::CursorIcon::None => "none",
324        egui::CursorIcon::NotAllowed => "not-allowed",
325        egui::CursorIcon::PointingHand => "pointer",
326        egui::CursorIcon::Progress => "progress",
327        egui::CursorIcon::ResizeHorizontal => "ew-resize",
328        egui::CursorIcon::ResizeNeSw => "nesw-resize",
329        egui::CursorIcon::ResizeNwSe => "nwse-resize",
330        egui::CursorIcon::ResizeVertical => "ns-resize",
331
332        egui::CursorIcon::ResizeEast => "e-resize",
333        egui::CursorIcon::ResizeSouthEast => "se-resize",
334        egui::CursorIcon::ResizeSouth => "s-resize",
335        egui::CursorIcon::ResizeSouthWest => "sw-resize",
336        egui::CursorIcon::ResizeWest => "w-resize",
337        egui::CursorIcon::ResizeNorthWest => "nw-resize",
338        egui::CursorIcon::ResizeNorth => "n-resize",
339        egui::CursorIcon::ResizeNorthEast => "ne-resize",
340        egui::CursorIcon::ResizeColumn => "col-resize",
341        egui::CursorIcon::ResizeRow => "row-resize",
342
343        egui::CursorIcon::Text => "text",
344        egui::CursorIcon::VerticalText => "vertical-text",
345        egui::CursorIcon::Wait => "wait",
346        egui::CursorIcon::ZoomIn => "zoom-in",
347        egui::CursorIcon::ZoomOut => "zoom-out",
348    }
349}
350
351/// Open the given url in the browser.
352pub fn open_url(url: &str, new_tab: bool) -> Option<()> {
353    let name = if new_tab { "_blank" } else { "_self" };
354
355    web_sys::window()?
356        .open_with_url_and_target(url, name)
357        .ok()?;
358    Some(())
359}
360
361/// e.g. "#fragment" part of "www.example.com/index.html#fragment",
362///
363/// Percent decoded
364pub fn location_hash() -> String {
365    percent_decode(
366        &web_sys::window()
367            .unwrap()
368            .location()
369            .hash()
370            .unwrap_or_default(),
371    )
372}
373
374/// Percent-decodes a string.
375pub fn percent_decode(s: &str) -> String {
376    percent_encoding::percent_decode_str(s)
377        .decode_utf8_lossy()
378        .to_string()
379}
380
381/// Are we running inside the Safari browser?
382pub fn is_safari_browser() -> bool {
383    web_sys::window().is_some_and(|window| Object::has_own(&window, &JsValue::from("safari")))
384}