Skip to main content

eframe/web/
app_runner.rs

1use std::sync::Arc;
2
3use egui::{ScreenshotCallback, TexturesDelta, ViewportCommand};
4
5use crate::{App, epi, web::web_painter::WebPainter};
6
7use super::{NeedRepaint, now_sec, text_agent::TextAgent};
8
9pub struct AppRunner {
10    #[allow(clippy::allow_attributes, dead_code)]
11    pub(crate) web_options: crate::WebOptions,
12    pub(crate) frame: epi::Frame,
13    egui_ctx: egui::Context,
14    painter: Box<dyn WebPainter>,
15    pub(crate) input: super::WebInput,
16    app: Box<dyn epi::App>,
17    pub(crate) needs_repaint: Arc<NeedRepaint>,
18    last_save_time: f64,
19    pub(crate) text_agent: TextAgent,
20
21    // If not empty, the painter should capture n frames from now.
22    // zero means capture the exact next frame.
23    screenshot_commands_with_frame_delay: Vec<(ScreenshotCallback, usize)>,
24
25    // Output for the last run:
26    textures_delta: TexturesDelta,
27    clipped_primitives: Option<Vec<egui::ClippedPrimitive>>,
28}
29
30impl Drop for AppRunner {
31    fn drop(&mut self) {
32        log::debug!("AppRunner has fully dropped");
33    }
34}
35
36impl AppRunner {
37    /// # Errors
38    /// Failure to initialize WebGL renderer, or failure to create app.
39    #[cfg_attr(
40        not(feature = "wgpu_no_default_features"),
41        expect(clippy::unused_async)
42    )]
43    pub async fn new(
44        canvas: web_sys::HtmlCanvasElement,
45        web_options: crate::WebOptions,
46        app_creator: epi::AppCreator<'static>,
47        text_agent: TextAgent,
48    ) -> Result<Self, String> {
49        let egui_ctx = egui::Context::default();
50        egui_ctx.add_glyph_rasterizer(super::canvas_glyphs::glyph_rasterizer());
51
52        #[allow(clippy::allow_attributes, unused_assignments)]
53        #[cfg(feature = "glow")]
54        let mut gl = None;
55
56        #[allow(clippy::allow_attributes, unused_assignments)]
57        #[cfg(feature = "wgpu_no_default_features")]
58        let mut wgpu_render_state = None;
59
60        let painter = match web_options.renderer {
61            #[cfg(feature = "glow")]
62            epi::Renderer::Glow => {
63                log::debug!("Using the glow renderer");
64                let painter = super::web_painter_glow::WebPainterGlow::new(
65                    egui_ctx.clone(),
66                    canvas,
67                    &web_options,
68                )?;
69                gl = Some(Arc::clone(painter.gl()));
70                Box::new(painter) as Box<dyn WebPainter>
71            }
72
73            #[cfg(feature = "wgpu_no_default_features")]
74            epi::Renderer::Wgpu => {
75                log::debug!("Using the wgpu renderer");
76                let painter = super::web_painter_wgpu::WebPainterWgpu::new(
77                    egui_ctx.clone(),
78                    canvas,
79                    &web_options,
80                )
81                .await?;
82                wgpu_render_state = painter.render_state();
83                Box::new(painter) as Box<dyn WebPainter>
84            }
85        };
86
87        let info = epi::IntegrationInfo {
88            web_info: epi::WebInfo {
89                user_agent: super::user_agent().unwrap_or_default(),
90                location: super::web_location(),
91            },
92            cpu_usage: None,
93        };
94        let storage = LocalStorage::default();
95
96        egui_ctx.set_os(egui::os::OperatingSystem::from_user_agent(
97            &super::user_agent().unwrap_or_default(),
98        ));
99        super::storage::load_memory(&egui_ctx);
100
101        egui_ctx.options_mut(|o| {
102            // On web by default egui follows the zoom factor of the browser,
103            // and lets the browser handle the zoom shortcuts.
104            // A user can still zoom egui separately by calling [`egui::Context::set_zoom_factor`].
105            o.zoom_with_keyboard = false;
106            o.zoom_factor = 1.0;
107        });
108
109        // Tell egui right away about native_pixels_per_point
110        // so that the app knows about it during app creation:
111        egui_ctx.input_mut(|i| {
112            let viewport_info = i.raw.viewports.entry(egui::ViewportId::ROOT).or_default();
113            viewport_info.native_pixels_per_point = Some(super::native_pixels_per_point());
114            i.pixels_per_point = super::native_pixels_per_point();
115        });
116
117        let cc = epi::CreationContext {
118            egui_ctx: egui_ctx.clone(),
119            integration_info: info.clone(),
120            storage: Some(&storage),
121
122            #[cfg(feature = "glow")]
123            gl: gl.clone(),
124
125            #[cfg(feature = "glow")]
126            get_proc_address: None,
127
128            #[cfg(feature = "wgpu_no_default_features")]
129            wgpu_render_state: wgpu_render_state.clone(),
130        };
131        let app = app_creator(&cc).map_err(|err| err.to_string())?;
132
133        let frame = epi::Frame {
134            info,
135            storage: Some(Box::new(storage)),
136
137            #[cfg(feature = "glow")]
138            gl,
139
140            #[cfg(feature = "wgpu_no_default_features")]
141            // We only care about the surface config if we are using wgpu
142            wgpu_surface_config: wgpu_render_state
143                .is_some()
144                .then_some(web_options.wgpu_options.surface),
145
146            #[cfg(feature = "wgpu_no_default_features")]
147            wgpu_render_state,
148        };
149
150        let needs_repaint: Arc<NeedRepaint> = Arc::new(NeedRepaint::new(web_options.max_fps));
151        {
152            let needs_repaint = Arc::clone(&needs_repaint);
153            egui_ctx.set_request_repaint_callback(move |info| {
154                needs_repaint.repaint_after(info.delay.as_secs_f64());
155            });
156        }
157
158        let mut runner = Self {
159            web_options,
160            frame,
161            egui_ctx,
162            painter,
163            input: Default::default(),
164            app,
165            needs_repaint,
166            last_save_time: now_sec(),
167            text_agent,
168            screenshot_commands_with_frame_delay: vec![],
169            textures_delta: Default::default(),
170            clipped_primitives: None,
171        };
172
173        runner.input.raw.max_texture_side = Some(runner.painter.max_texture_side());
174        runner
175            .input
176            .raw
177            .viewports
178            .entry(egui::ViewportId::ROOT)
179            .or_default()
180            .native_pixels_per_point = Some(super::native_pixels_per_point());
181        runner.input.raw.system_theme = super::system_theme();
182
183        Ok(runner)
184    }
185
186    pub fn egui_ctx(&self) -> &egui::Context {
187        &self.egui_ctx
188    }
189
190    /// Get mutable access to the concrete [`App`] we enclose.
191    ///
192    /// This will panic if your app does not implement [`App::as_any_mut`].
193    pub fn app_mut<ConcreteApp: 'static + App>(&mut self) -> &mut ConcreteApp {
194        self.app
195            .as_any_mut()
196            .expect("Your app must implement `as_any_mut`, but it doesn't")
197            .downcast_mut::<ConcreteApp>()
198            .expect("app_mut got the wrong type of App")
199    }
200
201    pub fn auto_save_if_needed(&mut self) {
202        let time_since_last_save = now_sec() - self.last_save_time;
203        if time_since_last_save > self.app.auto_save_interval().as_secs_f64() {
204            self.save();
205        }
206    }
207
208    pub fn save(&mut self) {
209        if self.app.persist_egui_memory() {
210            super::storage::save_memory(&self.egui_ctx);
211        }
212        if let Some(storage) = self.frame.storage_mut() {
213            self.app.save(storage);
214        }
215        self.last_save_time = now_sec();
216    }
217
218    pub fn canvas(&self) -> &web_sys::HtmlCanvasElement {
219        self.painter.canvas()
220    }
221
222    pub fn destroy(mut self) {
223        log::debug!("Destroying AppRunner");
224        self.egui_ctx.on_exit();
225        self.painter.destroy();
226    }
227
228    pub fn has_outstanding_paint_data(&self) -> bool {
229        self.clipped_primitives.is_some()
230    }
231
232    /// Does the eframe app have focus?
233    ///
234    /// Technically: does either the canvas or the [`TextAgent`] have focus?
235    pub fn has_focus(&self) -> bool {
236        let window = web_sys::window().unwrap();
237        let document = window.document().unwrap();
238        if document.hidden() {
239            return false;
240        }
241
242        super::has_focus(self.canvas()) || self.text_agent.has_focus()
243    }
244
245    pub fn update_focus(&mut self) {
246        let has_focus = self.has_focus();
247        if self.input.raw.focused != has_focus {
248            log::trace!("{} Focus changed to {has_focus}", self.canvas().id());
249            self.input.set_focus(has_focus);
250
251            if !has_focus {
252                // We lost focus - good idea to save
253                self.save();
254            }
255            self.egui_ctx().request_repaint();
256        }
257    }
258
259    /// Runs the logic, but doesn't paint the result.
260    ///
261    /// The result can be painted later with a call to [`Self::run_and_paint`] or [`Self::paint`].
262    pub fn logic(&mut self) {
263        // We sometimes miss blur/focus events due to the text agent, so let's just poll each frame:
264        self.update_focus();
265
266        let canvas_size = super::canvas_size_in_points(self.canvas(), self.egui_ctx());
267        let mut raw_input = self.input.new_frame(canvas_size);
268
269        if super::DEBUG_RESIZE {
270            log::info!(
271                "egui running at canvas size: {}x{}, DPR: {}, zoom_factor: {}. egui size: {}x{} points",
272                self.canvas().width(),
273                self.canvas().height(),
274                super::native_pixels_per_point(),
275                self.egui_ctx.zoom_factor(),
276                canvas_size.x,
277                canvas_size.y,
278            );
279        }
280
281        self.app.raw_input_hook(&self.egui_ctx, &mut raw_input);
282
283        let is_visible = raw_input
284            .viewports
285            .get(&egui::ViewportId::ROOT)
286            .and_then(|v| v.visible())
287            .unwrap_or(true);
288
289        if is_visible {
290            let full_output = self.egui_ctx.run_ui(raw_input, |ui| {
291                self.app.logic(ui.ctx(), &mut self.frame);
292                self.app.ui(ui, &mut self.frame);
293            });
294            let egui::FullOutput {
295                platform_output,
296                textures_delta,
297                shapes,
298                pixels_per_point,
299                viewport_output,
300            } = full_output;
301
302            if viewport_output.len() > 1 {
303                log::warn!("Multiple viewports not yet supported on the web");
304            }
305            self.handle_viewport_commands(
306                viewport_output
307                    .into_values()
308                    .flat_map(|viewport_output| viewport_output.commands),
309            );
310
311            self.handle_platform_output(platform_output);
312            self.textures_delta.append(textures_delta);
313            self.clipped_primitives = Some(self.egui_ctx.tessellate(shapes, pixels_per_point));
314        } else {
315            // The tab is hidden, so we run no egui pass at all.
316            // That way all ui state is left untouched, and is still there
317            // when the tab is shown again.
318
319            let egui::LogicOutput {
320                platform_output,
321                viewport_commands,
322            } = self.egui_ctx.run_logic(&raw_input, |ctx| {
323                self.app.logic(ctx, &mut self.frame);
324            });
325
326            // No pass consumed the input, so save it for the next one:
327            self.input.raw.append(raw_input);
328
329            self.handle_viewport_commands(viewport_commands.into_values().flatten());
330            self.handle_platform_output(platform_output);
331        }
332    }
333
334    fn handle_viewport_commands(&mut self, commands: impl Iterator<Item = ViewportCommand>) {
335        for command in commands {
336            match command {
337                ViewportCommand::Screenshot(callback) => {
338                    self.screenshot_commands_with_frame_delay
339                        .push((callback, 1));
340                }
341                ViewportCommand::SetTheme(_) => {
342                    // Web has no window decorations to theme, egui visuals follow the configured theme.
343                }
344                _ => {
345                    // TODO(emilk): handle some of the commands
346                    log::warn!(
347                        "Unhandled egui viewport command: {command:?} - not implemented in web backend"
348                    );
349                }
350            }
351        }
352    }
353
354    /// Paint the results of the last call to [`Self::logic`].
355    pub fn paint(&mut self) {
356        let clipped_primitives = core::mem::take(&mut self.clipped_primitives);
357
358        if let Some(clipped_primitives) = clipped_primitives {
359            let mut screenshot_commands = vec![];
360            self.screenshot_commands_with_frame_delay
361                .retain_mut(|(callback, frame_delay)| {
362                    if *frame_delay == 0 {
363                        screenshot_commands.push(callback.clone());
364                        false
365                    } else {
366                        *frame_delay -= 1;
367                        true
368                    }
369                });
370            if !self.screenshot_commands_with_frame_delay.is_empty() {
371                self.egui_ctx().request_repaint();
372            }
373
374            if let Err(err) = self.painter.paint_and_update_textures(
375                self.app.clear_color(&self.egui_ctx.global_style().visuals),
376                &clipped_primitives,
377                self.egui_ctx.pixels_per_point(),
378                &mut self.textures_delta,
379                screenshot_commands,
380            ) {
381                log::error!("Failed to paint: {}", super::string_from_js_value(&err));
382            }
383        }
384    }
385
386    pub fn report_frame_time(&mut self, cpu_usage_seconds: f32) {
387        self.frame.info.cpu_usage = Some(cpu_usage_seconds);
388    }
389
390    fn handle_platform_output(&self, platform_output: egui::PlatformOutput) {
391        #[cfg(feature = "web_screen_reader")]
392        if self.egui_ctx.options(|o| o.screen_reader) {
393            super::screen_reader::speak(&platform_output.events_description());
394        }
395
396        let egui::PlatformOutput {
397            commands,
398            cursor_icon,
399            cursor_image: _, // TODO(alextournai): support custom bitmap cursors on the web (via CSS `url(...)`)
400            events: _,       // already handled
401            mutable_text_under_cursor: _, // TODO(#4569): https://github.com/emilk/egui/issues/4569
402            ime,
403            accesskit_update: _,        // not currently implemented
404            num_completed_passes: _,    // handled by `Context::run`
405            request_discard_reasons: _, // handled by `Context::run`
406        } = platform_output;
407
408        for command in commands {
409            match command {
410                egui::OutputCommand::CopyText(text) => {
411                    super::set_clipboard_text(&text);
412                }
413                egui::OutputCommand::TextSelectionSettled(_) => {} // No PRIMARY selection on web
414                egui::OutputCommand::CopyImage(image) => {
415                    super::set_clipboard_image(&image);
416                }
417                egui::OutputCommand::OpenUrl(open_url) => {
418                    super::open_url(&open_url.url, open_url.new_tab);
419                }
420            }
421        }
422
423        super::set_cursor_icon(self.canvas(), cursor_icon);
424
425        if self.has_focus() {
426            // The eframe app has focus.
427            if let Some(ime) = ime {
428                if ime.should_interrupt_composition {
429                    self.text_agent.interrupt_ime_composition();
430                }
431                // We are editing text: give the focus to the text agent.
432                self.text_agent.focus();
433            } else {
434                // We are not editing text - give the focus to the canvas.
435                self.text_agent.blur();
436                super::focus_without_scroll(self.canvas()).ok();
437            }
438        }
439
440        if let Err(err) = self
441            .text_agent
442            .update(ime, self.canvas(), self.egui_ctx.zoom_factor())
443        {
444            log::error!(
445                "failed to update text agent position: {}",
446                super::string_from_js_value(&err)
447            );
448        }
449    }
450}
451
452// ----------------------------------------------------------------------------
453
454#[derive(Default)]
455struct LocalStorage {}
456
457impl epi::Storage for LocalStorage {
458    fn get_string(&self, key: &str) -> Option<String> {
459        super::storage::local_storage_get(key)
460    }
461
462    fn set_string(&mut self, key: &str, value: String) {
463        super::storage::local_storage_set(key, &value);
464    }
465
466    fn remove_string(&mut self, key: &str) {
467        super::storage::local_storage_remove(key);
468    }
469
470    fn flush(&mut self) {}
471}