Skip to main content

eframe/web/
app_runner.rs

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