Skip to main content

eframe/
epi.rs

1//! Platform-agnostic interface for writing apps using [`egui`] (epi = egui programming interface).
2//!
3//! `epi` provides interfaces for window management and serialization.
4//!
5//! Start by looking at the [`App`] trait, and implement [`App::ui`].
6
7#![warn(missing_docs)] // Let's keep `epi` well-documented.
8
9#[cfg(target_arch = "wasm32")]
10use core::any::Any;
11
12#[cfg(not(target_arch = "wasm32"))]
13#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
14pub use crate::native::winit_integration::UserEvent;
15
16#[cfg(not(target_arch = "wasm32"))]
17use raw_window_handle::{
18    DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle,
19    RawWindowHandle, WindowHandle,
20};
21#[cfg(not(target_arch = "wasm32"))]
22use static_assertions::assert_not_impl_any;
23
24#[cfg(not(target_arch = "wasm32"))]
25#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
26pub use winit::{event_loop::EventLoopBuilder, window::WindowAttributes};
27
28/// Hook into the building of an event loop before it is run
29///
30/// You can configure any platform specific details required on top of the default configuration
31/// done by `EFrame`.
32#[cfg(not(target_arch = "wasm32"))]
33#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
34pub type EventLoopBuilderHook = Box<dyn FnOnce(&mut EventLoopBuilder<UserEvent>)>;
35
36/// Hook into the building of a the native window.
37///
38/// You can configure any platform specific details required on top of the default configuration
39/// done by `eframe`.
40#[cfg(not(target_arch = "wasm32"))]
41#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
42pub type WindowBuilderHook = Box<dyn FnOnce(egui::ViewportBuilder) -> egui::ViewportBuilder>;
43
44type DynError = Box<dyn core::error::Error + Send + Sync>;
45
46/// This is how your app is created.
47///
48/// You can use the [`CreationContext`] to setup egui, restore state, setup OpenGL things, etc.
49pub type AppCreator<'app> =
50    Box<dyn 'app + FnOnce(&CreationContext<'_>) -> Result<Box<dyn 'app + App>, DynError>>;
51
52/// Data that is passed to [`AppCreator`] that can be used to setup and initialize your app.
53pub struct CreationContext<'s> {
54    /// The egui Context.
55    ///
56    /// You can use this to customize the look of egui, e.g to call [`egui::Context::set_fonts`],
57    /// [`egui::Context::set_visuals_of`] etc.
58    pub egui_ctx: egui::Context,
59
60    /// Information about the surrounding environment.
61    pub integration_info: IntegrationInfo,
62
63    /// You can use the storage to restore app state(requires the "persistence" feature).
64    pub storage: Option<&'s dyn Storage>,
65
66    /// The [`glow::Context`] allows you to initialize OpenGL resources (e.g. shaders) that
67    /// you might want to use later from a [`egui::PaintCallback`].
68    ///
69    /// Only available when compiling with the `glow` feature and using [`Renderer::Glow`].
70    #[cfg(feature = "glow")]
71    pub gl: Option<std::sync::Arc<glow::Context>>,
72
73    /// The `get_proc_address` wrapper of underlying GL context
74    #[cfg(feature = "glow")]
75    pub get_proc_address:
76        Option<std::sync::Arc<dyn Fn(&core::ffi::CStr) -> *const core::ffi::c_void + Send + Sync>>,
77
78    /// The underlying WGPU render state.
79    ///
80    /// Only available when compiling with the `wgpu` feature and using [`Renderer::Wgpu`].
81    ///
82    /// Can be used to manage GPU resources for custom rendering with WGPU using [`egui::PaintCallback`]s.
83    #[cfg(feature = "wgpu_no_default_features")]
84    pub wgpu_render_state: Option<egui_wgpu::RenderState>,
85
86    /// The root [`winit::window::Window`].
87    #[cfg(not(target_arch = "wasm32"))]
88    pub(crate) window: Option<std::sync::Arc<winit::window::Window>>,
89
90    /// Raw platform window handle
91    #[cfg(not(target_arch = "wasm32"))]
92    pub(crate) raw_window_handle: Result<RawWindowHandle, HandleError>,
93
94    /// Raw platform display handle for window
95    #[cfg(not(target_arch = "wasm32"))]
96    pub(crate) raw_display_handle: Result<RawDisplayHandle, HandleError>,
97}
98
99#[expect(unsafe_code)]
100#[cfg(not(target_arch = "wasm32"))]
101impl HasWindowHandle for CreationContext<'_> {
102    fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
103        // Safety: the lifetime is correct.
104        unsafe { Ok(WindowHandle::borrow_raw(self.raw_window_handle.clone()?)) }
105    }
106}
107
108#[expect(unsafe_code)]
109#[cfg(not(target_arch = "wasm32"))]
110impl HasDisplayHandle for CreationContext<'_> {
111    fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
112        // Safety: the lifetime is correct.
113        unsafe { Ok(DisplayHandle::borrow_raw(self.raw_display_handle.clone()?)) }
114    }
115}
116
117impl CreationContext<'_> {
118    /// Create a new empty [CreationContext] for testing [App]s in kittest.
119    #[doc(hidden)]
120    pub fn _new_kittest(egui_ctx: egui::Context) -> Self {
121        Self {
122            egui_ctx,
123            integration_info: IntegrationInfo::mock(),
124            storage: None,
125            #[cfg(feature = "glow")]
126            gl: None,
127            #[cfg(feature = "glow")]
128            get_proc_address: None,
129            #[cfg(feature = "wgpu_no_default_features")]
130            wgpu_render_state: None,
131            #[cfg(not(target_arch = "wasm32"))]
132            window: None,
133            #[cfg(not(target_arch = "wasm32"))]
134            raw_window_handle: Err(HandleError::NotSupported),
135            #[cfg(not(target_arch = "wasm32"))]
136            raw_display_handle: Err(HandleError::NotSupported),
137        }
138    }
139
140    /// Access to the root [`winit::window::Window`].
141    ///
142    /// `None` for headless (tests etc).
143    #[cfg(not(target_arch = "wasm32"))]
144    pub fn winit_window(&self) -> Option<&std::sync::Arc<winit::window::Window>> {
145        self.window.as_ref()
146    }
147}
148
149// ----------------------------------------------------------------------------
150
151/// Implement this trait to write apps that can be compiled for both web/wasm and desktop/native using [`eframe`](https://github.com/emilk/egui/tree/main/crates/eframe).
152pub trait App {
153    /// Called once before each call to [`Self::ui`],
154    /// and additionally also called when the UI is hidden, but [`egui::Context::request_repaint`] was called.
155    ///
156    /// You may NOT show any ui or do any painting during the call to [`Self::logic`].
157    ///
158    /// While the window is hidden, `eframe` runs no egui pass at all (so that no ui state is
159    /// disturbed), and calls this via [`egui::Context::run_logic`] instead.
160    /// You can then still tell that the window is hidden with
161    /// [`egui::InputState::viewport`], but the rest of [`egui::Context::input`]
162    /// (events, time, …) is that of the last shown frame.
163    ///
164    /// Send [`egui::ViewportCommand::RequestPaintWhileHidden`] if you want `App::ui` to be called
165    /// even if the application is hidden.
166    ///
167    /// The [`egui::Context`] can be cloned and saved if you like.
168    ///
169    /// To force another call to [`Self::logic`], call [`egui::Context::request_repaint`] at any time (e.g. from another thread).
170    fn logic(&mut self, ctx: &egui::Context, frame: &mut Frame) {
171        _ = (ctx, frame);
172    }
173
174    /// Called each time the UI needs repainting, which may be many times per second.
175    ///
176    /// The given [`egui::Ui`] has no margin or background color.
177    /// You can wrap your UI code in [`egui::CentralPanel`] or a [`egui::Frame::central_panel`] to remedy this.
178    ///
179    /// The [`egui::Ui::ctx`] can be cloned and saved if you like.
180    /// To force a repaint, call [`egui::Context::request_repaint`] at any time (e.g. from another thread).
181    ///
182    /// This is called for the root viewport ([`egui::ViewportId::ROOT`]).
183    /// Use [`egui::Context::show_viewport_deferred`] to spawn additional viewports (windows).
184    /// (A "viewport" in egui means an native OS window).
185    fn ui(&mut self, ui: &mut egui::Ui, frame: &mut Frame);
186
187    /// Get a handle to the app.
188    ///
189    /// Can be used from web to interact or other external context.
190    ///
191    /// You need to implement this if you want to be able to access the application from JS using [`crate::WebRunner::app_mut`].
192    ///
193    /// This is needed because downcasting `Box<dyn App>` -> `Box<dyn Any>` to get &`ConcreteApp` is not simple in current rust.
194    ///
195    /// Just copy-paste this as your implementation:
196    /// ```ignore
197    /// #[cfg(target_arch = "wasm32")]
198    /// fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
199    ///     Some(&mut *self)
200    /// }
201    /// ```
202    #[cfg(target_arch = "wasm32")]
203    fn as_any_mut(&mut self) -> Option<&mut dyn Any> {
204        None
205    }
206
207    /// Called on shutdown, and perhaps at regular intervals. Allows you to save state.
208    ///
209    /// Only called when the "persistence" feature is enabled.
210    ///
211    /// On web the state is stored to "Local Storage".
212    ///
213    /// On native the path is picked using [`crate::storage_dir`].
214    /// The path can be customized via [`NativeOptions::persistence_path`].
215    fn save(&mut self, _storage: &mut dyn Storage) {}
216
217    /// Called once on shutdown, after [`Self::save`].
218    ///
219    /// If you need to abort an exit check `ctx.input(|i| i.viewport().close_requested())`
220    /// and respond with [`egui::ViewportCommand::CancelClose`].
221    ///
222    /// To get a [`glow`] context you need to compile with the `glow` feature flag,
223    /// and run eframe with the glow backend.
224    #[cfg(feature = "glow")]
225    fn on_exit(&mut self, _gl: Option<&glow::Context>) {}
226
227    /// Called once on shutdown, after [`Self::save`].
228    ///
229    /// If you need to abort an exit use [`Self::on_close_event`].
230    #[cfg(not(feature = "glow"))]
231    fn on_exit(&mut self) {}
232
233    // ---------
234    // Settings:
235
236    /// Time between automatic calls to [`Self::save`]
237    fn auto_save_interval(&self) -> core::time::Duration {
238        core::time::Duration::from_secs(30)
239    }
240
241    /// Background color values for the app, e.g. what is sent to `gl.clearColor`.
242    ///
243    /// This is the background of your windows if you don't set a central panel.
244    ///
245    /// ATTENTION:
246    /// Since these float values go to the render as-is, any color space conversion as done
247    /// e.g. by converting from [`egui::Color32`] to [`egui::Rgba`] may cause incorrect results.
248    /// egui recommends that rendering backends use a normal "gamma-space" (non-sRGB-aware) blending,
249    ///  which means the values you return here should also be in `sRGB` gamma-space in the 0-1 range.
250    /// You can use [`egui::Color32::to_normalized_gamma_f32`] for this.
251    fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
252        // NOTE: a bright gray makes the shadows of the windows look weird.
253        // We use a bit of transparency so that if the user switches on the
254        // `transparent()` option they get immediate results.
255        egui::Color32::from_rgba_unmultiplied(12, 12, 12, 180).to_normalized_gamma_f32()
256
257        // _visuals.window_fill() would also be a natural choice
258    }
259
260    /// Controls whether or not the egui memory (window positions etc) will be
261    /// persisted (only if the "persistence" feature is enabled).
262    fn persist_egui_memory(&self) -> bool {
263        true
264    }
265
266    /// A hook for manipulating or filtering raw input before it is processed by [`Self::ui`].
267    ///
268    /// This function provides a way to modify or filter input events before they are processed by egui.
269    ///
270    /// It can be used to prevent specific keyboard shortcuts or mouse events from being processed by egui.
271    ///
272    /// Additionally, it can be used to inject custom keyboard or mouse events into the input stream, which can be useful for implementing features like a virtual keyboard.
273    ///
274    /// # Arguments
275    ///
276    /// * `_ctx` - The context of the egui, which provides access to the current state of the egui.
277    /// * `_raw_input` - The raw input events that are about to be processed. This can be modified to change the input that egui processes.
278    ///
279    /// # Note
280    ///
281    /// This function does not return a value. Any changes to the input should be made directly to `_raw_input`.
282    fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw_input: &mut egui::RawInput) {}
283}
284
285/// Options controlling the behavior of a native window.
286///
287/// Additional windows can be opened using (egui viewports)[`egui::viewport`].
288///
289/// Set the window title and size using [`Self::viewport`].
290///
291/// ### Application id
292/// [`egui::ViewportBuilder::with_app_id`] is used for determining the folder to persist the app to.
293///
294/// On native the path is picked using [`crate::storage_dir`].
295///
296/// If you don't set an app id, the title argument to [`crate::run_native`]
297/// will be used as app id instead.
298#[cfg(not(target_arch = "wasm32"))]
299pub struct NativeOptions {
300    /// Controls the native window of the root viewport.
301    ///
302    /// This is where you set things like window title and size.
303    ///
304    /// If you don't set an icon, a default egui icon will be used.
305    /// To avoid this, set the icon to [`egui::IconData::default`].
306    pub viewport: egui::ViewportBuilder,
307
308    /// Set the level of the multisampling anti-aliasing (MSAA).
309    ///
310    /// Must be a power-of-two. Higher = more smooth 3D.
311    ///
312    /// A value of `0` turns it off (default).
313    ///
314    /// `egui` already performs anti-aliasing via "feathering"
315    /// (controlled by [`egui::epaint::TessellationOptions`]),
316    /// but if you are embedding 3D in egui you may want to turn on multisampling.
317    pub multisampling: u16,
318
319    /// Sets the number of bits in the depth buffer.
320    ///
321    /// `egui` doesn't need the depth buffer, so the default value is 0.
322    pub depth_buffer: u8,
323
324    /// Sets the number of bits in the stencil buffer.
325    ///
326    /// `egui` doesn't need the stencil buffer, so the default value is 0.
327    pub stencil_buffer: u8,
328
329    /// What rendering backend to use.
330    #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
331    pub renderer: Renderer,
332
333    /// This controls what happens when you close the main eframe window.
334    ///
335    /// If `true`, execution will continue after the eframe window is closed.
336    /// If `false`, the app will close once the eframe window is closed.
337    ///
338    /// This is `true` by default, and the `false` option is only there
339    /// so we can revert if we find any bugs.
340    ///
341    /// This feature was introduced in <https://github.com/emilk/egui/pull/1889>.
342    ///
343    /// When `true`, [`winit::platform::run_on_demand::EventLoopExtRunOnDemand`] is used.
344    /// When `false`, [`winit::event_loop::EventLoop::run`] is used.
345    pub run_and_return: bool,
346
347    /// Hook into the building of an event loop before it is run.
348    ///
349    /// Specify a callback here in case you need to make platform specific changes to the
350    /// event loop before it is run.
351    ///
352    /// Note: A [`NativeOptions`] clone will not include any `event_loop_builder` hook.
353    #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
354    pub event_loop_builder: Option<EventLoopBuilderHook>,
355
356    /// Hook into the building of a window.
357    ///
358    /// Specify a callback here in case you need to make platform specific changes to the
359    /// window appearance.
360    ///
361    /// Note: A [`NativeOptions`] clone will not include any `window_builder` hook.
362    #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
363    pub window_builder: Option<WindowBuilderHook>,
364
365    /// On desktop: make the window position to be centered at initialization.
366    ///
367    /// Platform specific:
368    ///
369    /// Wayland desktop currently not supported.
370    pub centered: bool,
371
372    /// Configures glow instance.
373    #[cfg(feature = "glow")]
374    pub glow_options: egui_glow::GlowConfiguration,
375
376    /// Configures wgpu instance/device/adapter/surface creation and renderloop.
377    #[cfg(feature = "wgpu_no_default_features")]
378    pub wgpu_options: egui_wgpu::WgpuConfiguration,
379
380    /// Controls whether or not the native window position and size will be
381    /// persisted (only if the "persistence" feature is enabled).
382    pub persist_window: bool,
383
384    /// Load system fonts on demand for characters that the installed fonts lack,
385    /// e.g. CJK, Arabic, or Devanagari (only if the `system_fonts` feature is enabled).
386    ///
387    /// Turn this off if you bundle fonts that cover everything your app shows,
388    /// or if you need identical text rendering on all machines.
389    ///
390    /// Default: `true`.
391    pub system_font_fallback: bool,
392
393    /// The folder where `eframe` will store the app state. If not set, eframe will use a default
394    /// data storage path for each target system.
395    pub persistence_path: Option<std::path::PathBuf>,
396
397    /// Controls whether to apply dithering to minimize banding artifacts.
398    ///
399    /// Dithering assumes an sRGB output and thus will apply noise to any input value that lies between
400    /// two 8bit values after applying the sRGB OETF function, i.e. if it's not a whole 8bit value in "gamma space".
401    /// This means that only inputs from texture interpolation and vertex colors should be affected in practice.
402    ///
403    /// Defaults to true.
404    pub dithering: bool,
405
406    /// Should the platform clipboard keyboard shortcuts
407    /// (e.g. <kbd>Cmd/Ctrl</kbd>+<kbd>X</kbd>/<kbd>C</kbd>/<kbd>V</kbd>)
408    /// be translated into [`egui::Event::Cut`], [`egui::Event::Copy`] and [`egui::Event::Paste`]?
409    ///
410    /// Set this to `false` if you want to handle these key combinations yourself.
411    /// They will then arrive as ordinary [`egui::Event::Key`] events instead.
412    /// Note that built-in widgets such as [`egui::TextEdit`] will then no longer
413    /// respond to these shortcuts.
414    ///
415    /// This applies to all viewports.
416    /// See also `egui_winit::State::set_clipboard_shortcuts`.
417    ///
418    /// There is no web equivalent: on the web, Cut/Copy/Paste come from the browser's
419    /// clipboard events (which can also be triggered from e.g. the browser menu),
420    /// and the key presses are always also delivered as [`egui::Event::Key`].
421    ///
422    /// Defaults to true.
423    pub clipboard_shortcuts: bool,
424
425    /// Android application for `winit`'s event loop.
426    ///
427    /// This value is required on Android to correctly create the event loop. See
428    /// [`EventLoopBuilder::build`] and [`with_android_app`] for details.
429    ///
430    /// [`EventLoopBuilder::build`]: winit::event_loop::EventLoopBuilder::build
431    /// [`with_android_app`]: winit::platform::android::EventLoopBuilderExtAndroid::with_android_app
432    #[cfg(target_os = "android")]
433    pub android_app: Option<winit::platform::android::activity::AndroidApp>,
434}
435
436#[cfg(not(target_arch = "wasm32"))]
437impl Clone for NativeOptions {
438    fn clone(&self) -> Self {
439        Self {
440            viewport: self.viewport.clone(),
441
442            #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
443            event_loop_builder: None, // Skip any builder callbacks if cloning
444
445            #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
446            window_builder: None, // Skip any builder callbacks if cloning
447
448            #[cfg(feature = "glow")]
449            glow_options: self.glow_options.clone(),
450
451            #[cfg(feature = "wgpu_no_default_features")]
452            wgpu_options: self.wgpu_options.clone(),
453
454            persistence_path: self.persistence_path.clone(),
455
456            #[cfg(target_os = "android")]
457            android_app: self.android_app.clone(),
458
459            ..*self
460        }
461    }
462}
463
464#[cfg(not(target_arch = "wasm32"))]
465impl Default for NativeOptions {
466    fn default() -> Self {
467        Self {
468            viewport: Default::default(),
469
470            multisampling: 0,
471            depth_buffer: 0,
472            stencil_buffer: 0,
473
474            #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
475            renderer: Renderer::default(),
476
477            run_and_return: true,
478
479            #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
480            event_loop_builder: None,
481
482            #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
483            window_builder: None,
484
485            centered: false,
486
487            #[cfg(feature = "glow")]
488            glow_options: egui_glow::GlowConfiguration::default(),
489
490            #[cfg(feature = "wgpu_no_default_features")]
491            wgpu_options: egui_wgpu::WgpuConfiguration::default()
492                .with_surface_config(egui_wgpu::SurfaceConfig::LOW_LATENCY),
493
494            persist_window: true,
495
496            system_font_fallback: true,
497
498            persistence_path: None,
499
500            dithering: true,
501
502            clipboard_shortcuts: true,
503
504            #[cfg(target_os = "android")]
505            android_app: None,
506        }
507    }
508}
509
510// ----------------------------------------------------------------------------
511
512/// Options when using `eframe` in a web page.
513#[cfg(target_arch = "wasm32")]
514pub struct WebOptions {
515    /// What rendering backend to use.
516    #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
517    pub renderer: Renderer,
518
519    /// Sets the number of bits in the depth buffer.
520    ///
521    /// `egui` doesn't need the depth buffer, so the default value is 0.
522    /// Unused by webgl context as of writing.
523    pub depth_buffer: u8,
524
525    /// Which version of WebGL context to select
526    ///
527    /// Default: [`WebGlContextOption::BestFirst`].
528    #[cfg(feature = "glow")]
529    pub webgl_context_option: WebGlContextOption,
530
531    /// Configures glow instance.
532    #[cfg(feature = "glow")]
533    pub glow_options: egui_glow::GlowConfiguration,
534
535    /// Configures wgpu instance/device/adapter/surface creation and renderloop.
536    #[cfg(feature = "wgpu_no_default_features")]
537    pub wgpu_options: egui_wgpu::WgpuConfiguration,
538
539    /// Controls whether to apply dithering to minimize banding artifacts.
540    ///
541    /// Dithering assumes an sRGB output and thus will apply noise to any input value that lies between
542    /// two 8bit values after applying the sRGB OETF function, i.e. if it's not a whole 8bit value in "gamma space".
543    /// This means that only inputs from texture interpolation and vertex colors should be affected in practice.
544    ///
545    /// Defaults to true.
546    pub dithering: bool,
547
548    /// If the web event corresponding to an egui event should be propagated
549    /// to the rest of the web page.
550    ///
551    /// The default is `true`, meaning
552    /// [`stopPropagation`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
553    /// is called on every event, and the event is not propagated to the rest of the web page.
554    pub should_stop_propagation: Box<dyn Fn(&egui::Event) -> bool>,
555
556    /// Whether the web event corresponding to an egui event should have `prevent_default` called
557    /// on it or not.
558    ///
559    /// Defaults to true.
560    pub should_prevent_default: Box<dyn Fn(&egui::Event) -> bool>,
561
562    /// Maximum rate at which to repaint. This can be used to artificially reduce the repaint rate below
563    /// vsync in order to save resources.
564    pub max_fps: Option<u32>,
565}
566
567#[cfg(target_arch = "wasm32")]
568impl Default for WebOptions {
569    fn default() -> Self {
570        Self {
571            #[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
572            renderer: Renderer::default(),
573
574            depth_buffer: 0,
575
576            #[cfg(feature = "glow")]
577            webgl_context_option: WebGlContextOption::BestFirst,
578
579            #[cfg(feature = "glow")]
580            glow_options: egui_glow::GlowConfiguration::default(),
581
582            #[cfg(feature = "wgpu_no_default_features")]
583            wgpu_options: egui_wgpu::WgpuConfiguration::default(),
584
585            dithering: true,
586
587            should_stop_propagation: Box::new(|_| true),
588            should_prevent_default: Box::new(|_| true),
589
590            max_fps: None,
591        }
592    }
593}
594
595// ----------------------------------------------------------------------------
596
597/// WebGL Context options
598#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
599#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
600pub enum WebGlContextOption {
601    /// Force Use WebGL1.
602    WebGl1,
603
604    /// Force use WebGL2.
605    WebGl2,
606
607    /// Use WebGL2 first.
608    BestFirst,
609
610    /// Use WebGL1 first
611    CompatibilityFirst,
612}
613
614// ----------------------------------------------------------------------------
615
616/// What rendering backend to use.
617///
618/// You need to enable the "glow" and "wgpu" features to have a choice.
619#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
620#[derive(Clone, Copy, Debug, PartialEq, Eq)]
621#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
622#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
623pub enum Renderer {
624    /// Use [`egui_glow`] renderer for [`glow`](https://github.com/grovesNL/glow).
625    #[cfg(feature = "glow")]
626    Glow,
627
628    /// Use [`egui_wgpu`] renderer for [`wgpu`](https://github.com/gfx-rs/wgpu).
629    #[cfg(feature = "wgpu_no_default_features")]
630    Wgpu,
631}
632
633#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
634impl Default for Renderer {
635    fn default() -> Self {
636        #[cfg(not(feature = "glow"))]
637        #[cfg(not(feature = "wgpu_no_default_features"))]
638        compile_error!(
639            "eframe: you must enable at least one of the rendering backend features: 'glow' or 'wgpu'"
640        );
641
642        #[cfg(feature = "glow")]
643        #[cfg(not(feature = "wgpu_no_default_features"))]
644        return Self::Glow;
645
646        #[cfg(not(feature = "glow"))]
647        #[cfg(feature = "wgpu_no_default_features")]
648        return Self::Wgpu;
649
650        // It's weird that the user has enabled both glow and wgpu,
651        // but let's pick the better of the two (wgpu):
652        #[cfg(feature = "glow")]
653        #[cfg(feature = "wgpu_no_default_features")]
654        return Self::Wgpu;
655    }
656}
657
658#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
659impl core::fmt::Display for Renderer {
660    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
661        match self {
662            #[cfg(feature = "glow")]
663            Self::Glow => "glow".fmt(f),
664
665            #[cfg(feature = "wgpu_no_default_features")]
666            Self::Wgpu => "wgpu".fmt(f),
667        }
668    }
669}
670
671#[cfg(any(feature = "glow", feature = "wgpu_no_default_features"))]
672impl core::str::FromStr for Renderer {
673    type Err = String;
674
675    fn from_str(name: &str) -> Result<Self, String> {
676        match name.to_lowercase().as_str() {
677            #[cfg(feature = "glow")]
678            "glow" => Ok(Self::Glow),
679
680            #[cfg(feature = "wgpu_no_default_features")]
681            "wgpu" => Ok(Self::Wgpu),
682
683            _ => Err(format!(
684                "eframe renderer {name:?} is not available. Make sure that the corresponding eframe feature is enabled."
685            )),
686        }
687    }
688}
689
690// ----------------------------------------------------------------------------
691
692/// Represents the surroundings of your app.
693///
694/// It provides methods to inspect the surroundings (are we on the web?),
695/// access to persistent storage, and access to the rendering backend.
696pub struct Frame {
697    /// Information about the integration.
698    pub(crate) info: IntegrationInfo,
699
700    /// A place where you can store custom data in a way that persists when you restart the app.
701    pub(crate) storage: Option<Box<dyn Storage>>,
702
703    /// A reference to the underlying [`glow`] (OpenGL) context.
704    #[cfg(feature = "glow")]
705    pub(crate) gl: Option<std::sync::Arc<glow::Context>>,
706
707    /// Used to convert user custom [`glow::Texture`] to [`egui::TextureId`]
708    #[cfg(all(feature = "glow", not(target_arch = "wasm32")))]
709    pub(crate) glow_register_native_texture:
710        Option<Box<dyn FnMut(glow::Texture) -> egui::TextureId>>,
711
712    /// Can be used to manage GPU resources for custom rendering with WGPU using [`egui::PaintCallback`]s.
713    #[cfg(feature = "wgpu_no_default_features")]
714    #[doc(hidden)]
715    pub wgpu_render_state: Option<egui_wgpu::RenderState>,
716
717    /// The surface config the app wants the `wgpu` renderer to use.
718    ///
719    /// `None` unless we are rendering with `wgpu`.
720    ///
721    /// eframe pushes this into the painter once per frame, before painting.
722    #[cfg(feature = "wgpu_no_default_features")]
723    #[doc(hidden)]
724    pub wgpu_surface_config: Option<egui_wgpu::SurfaceConfig>,
725
726    /// The current [`winit::window::Window`] (i.e. the one the active viewport is rendered to).
727    #[cfg(not(target_arch = "wasm32"))]
728    pub(crate) window: Option<std::sync::Arc<winit::window::Window>>,
729
730    /// Raw platform window handle
731    #[cfg(not(target_arch = "wasm32"))]
732    pub(crate) raw_window_handle: Result<RawWindowHandle, HandleError>,
733
734    /// Raw platform display handle for window
735    #[cfg(not(target_arch = "wasm32"))]
736    pub(crate) raw_display_handle: Result<RawDisplayHandle, HandleError>,
737
738    /// The activation token the windowing system last handed us, waiting to be
739    /// taken by the app. See [`Frame::request_activation_token`].
740    #[cfg(not(target_arch = "wasm32"))]
741    pub(crate) activation_token: Option<String>,
742}
743
744// Implementing `Clone` would violate the guarantees of `HasWindowHandle` and `HasDisplayHandle`.
745#[cfg(not(target_arch = "wasm32"))]
746assert_not_impl_any!(Frame: Clone);
747
748#[expect(unsafe_code)]
749#[cfg(not(target_arch = "wasm32"))]
750impl HasWindowHandle for Frame {
751    fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
752        // Safety: the lifetime is correct.
753        unsafe { Ok(WindowHandle::borrow_raw(self.raw_window_handle.clone()?)) }
754    }
755}
756
757#[expect(unsafe_code)]
758#[cfg(not(target_arch = "wasm32"))]
759impl HasDisplayHandle for Frame {
760    fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
761        // Safety: the lifetime is correct.
762        unsafe { Ok(DisplayHandle::borrow_raw(self.raw_display_handle.clone()?)) }
763    }
764}
765
766impl Frame {
767    /// Create a new empty [Frame] for testing [App]s in kittest.
768    #[doc(hidden)]
769    pub fn _new_kittest() -> Self {
770        Self {
771            #[cfg(feature = "glow")]
772            gl: None,
773            #[cfg(all(feature = "glow", not(target_arch = "wasm32")))]
774            glow_register_native_texture: None,
775            info: IntegrationInfo::mock(),
776            #[cfg(not(target_arch = "wasm32"))]
777            raw_display_handle: Err(HandleError::NotSupported),
778            #[cfg(not(target_arch = "wasm32"))]
779            raw_window_handle: Err(HandleError::NotSupported),
780            #[cfg(not(target_arch = "wasm32"))]
781            window: None,
782            #[cfg(not(target_arch = "wasm32"))]
783            activation_token: None,
784            storage: None,
785            #[cfg(feature = "wgpu_no_default_features")]
786            wgpu_render_state: None,
787            #[cfg(feature = "wgpu_no_default_features")]
788            wgpu_surface_config: None,
789        }
790    }
791
792    /// True if you are in a web environment.
793    ///
794    /// Equivalent to `cfg!(target_arch = "wasm32")`
795    #[expect(clippy::unused_self)]
796    pub fn is_web(&self) -> bool {
797        cfg!(target_arch = "wasm32")
798    }
799
800    /// Information about the integration.
801    pub fn info(&self) -> &IntegrationInfo {
802        &self.info
803    }
804
805    /// A place where you can store custom data in a way that persists when you restart the app.
806    pub fn storage(&self) -> Option<&dyn Storage> {
807        self.storage.as_deref()
808    }
809
810    /// A place where you can store custom data in a way that persists when you restart the app.
811    pub fn storage_mut(&mut self) -> Option<&mut (dyn Storage + 'static)> {
812        self.storage.as_deref_mut()
813    }
814
815    /// Access to the current [`winit::window::Window`] (i.e. the one the active viewport is rendered to).
816    ///
817    /// `None` for headless (tests etc).
818    #[cfg(not(target_arch = "wasm32"))]
819    pub fn winit_window(&self) -> Option<&std::sync::Arc<winit::window::Window>> {
820        self.window.as_ref()
821    }
822
823    /// Position the native macOS "traffic lights" (close/minimize/maximize buttons)
824    /// in a custom title bar.
825    ///
826    /// The buttons are centered vertically in `title_bar_y`
827    /// (the y-range of your title bar, measured from the top of the window),
828    /// with the close button `left_margin` from the left edge.
829    ///
830    /// Both arguments are in egui points.
831    /// Call this every frame: `AppKit` resets the position of the buttons whenever it lays out
832    /// the window again (e.g. on resize), and this way they also follow changes to the zoom factor.
833    ///
834    /// The native spacing between the buttons is preserved.
835    ///
836    /// This is meant to be used together with [`egui::ViewportBuilder::with_fullsize_content_view`].
837    ///
838    /// Does nothing on other platforms.
839    pub fn set_traffic_lights_position(
840        &self,
841        egui_ctx: &egui::Context,
842        title_bar_y: egui::Rangef,
843        left_margin: f32,
844    ) {
845        cfg_select! {
846            all(
847                target_os = "macos",
848                any(feature = "glow", feature = "wgpu_no_default_features")
849            ) => {
850                if let Ok(window_handle) = &self.raw_window_handle {
851                    // Convert from egui points to native points:
852                    let zoom_factor = egui_ctx.zoom_factor();
853                    crate::native::macos::position_traffic_lights(
854                        window_handle,
855                        zoom_factor * title_bar_y,
856                        zoom_factor * left_margin,
857                    );
858                }
859            }
860            _ => {
861                let _ = (self, egui_ctx, title_bar_y, left_margin);
862            }
863        }
864    }
865
866    /// Ask the windowing system for a fresh activation token (Linux only).
867    ///
868    /// The token lets you hand your focus to a process you are about to spawn:
869    /// pass it in the `XDG_ACTIVATION_TOKEN` environment variable and the
870    /// compositor grants the new window focus instead of tripping its
871    /// focus-stealing prevention. On X11 the token is a startup-notification id,
872    /// which the child reads from `DESKTOP_STARTUP_ID`.
873    ///
874    /// The answer arrives asynchronously, a frame or more later — collect it
875    /// with [`Frame::take_activation_token`]. Nothing is delivered on platforms
876    /// without an activation protocol, so give up after a deadline of your own
877    /// rather than waiting forever.
878    ///
879    /// This is a no-op off Linux, and when running headless.
880    #[cfg(not(target_arch = "wasm32"))]
881    pub fn request_activation_token(&self) {
882        let Some(window) = self.window.as_ref() else {
883            return;
884        };
885
886        cfg_select! {
887            all(any(feature = "wayland", feature = "x11"), target_os = "linux") => {
888                use winit::platform::startup_notify::WindowExtStartupNotify as _;
889                if let Err(err) = window.request_activation_token() {
890                    log::debug!("request_activation_token failed: {err}");
891                }
892            }
893            _ => {
894                let _ = window;
895            }
896        }
897    }
898
899    /// Take the activation token asked for with
900    /// [`Frame::request_activation_token`], if one has arrived.
901    ///
902    /// Returns it at most once: a token is single-use, and the compositor
903    /// invalidates it shortly after issuing it, so spawn the child process
904    /// with it right away rather than storing it.
905    #[cfg(not(target_arch = "wasm32"))]
906    pub fn take_activation_token(&mut self) -> Option<String> {
907        self.activation_token.take()
908    }
909
910    /// A reference to the underlying [`glow`] (OpenGL) context.
911    ///
912    /// This can be used, for instance, to:
913    /// * Render things to offscreen buffers.
914    /// * Read the pixel buffer from the previous frame (`glow::Context::read_pixels`).
915    /// * Render things behind the egui windows.
916    ///
917    /// Note that all egui painting is deferred to after the call to [`App::ui`]
918    /// ([`egui`] only collects [`egui::Shape`]s and then eframe paints them all in one go later on).
919    ///
920    /// To get a [`glow`] context you need to compile with the `glow` feature flag,
921    /// and run eframe using [`Renderer::Glow`].
922    #[cfg(feature = "glow")]
923    pub fn gl(&self) -> Option<&std::sync::Arc<glow::Context>> {
924        self.gl.as_ref()
925    }
926
927    /// Register your own [`glow::Texture`],
928    /// and then you can use the returned [`egui::TextureId`] to render your texture with [`egui`].
929    ///
930    /// This function will take the ownership of your [`glow::Texture`], so please do not delete your [`glow::Texture`] after registering.
931    #[cfg(all(feature = "glow", not(target_arch = "wasm32")))]
932    pub fn register_native_glow_texture(&mut self, native: glow::Texture) -> egui::TextureId {
933        #[expect(clippy::unwrap_used)]
934        self.glow_register_native_texture.as_mut().unwrap()(native)
935    }
936
937    /// The underlying WGPU render state.
938    ///
939    /// Only available when compiling with the `wgpu` feature and using [`Renderer::Wgpu`].
940    ///
941    /// Can be used to manage GPU resources for custom rendering with WGPU using [`egui::PaintCallback`]s.
942    #[cfg(feature = "wgpu_no_default_features")]
943    pub fn wgpu_render_state(&self) -> Option<&egui_wgpu::RenderState> {
944        self.wgpu_render_state.as_ref()
945    }
946
947    /// The surface config (present mode, frame latency) the app wants the `wgpu`
948    /// renderer to use.
949    ///
950    /// `None` unless we are rendering with `wgpu`.
951    #[cfg(feature = "wgpu_no_default_features")]
952    pub fn wgpu_surface_config(&self) -> Option<egui_wgpu::SurfaceConfig> {
953        self.wgpu_surface_config
954    }
955
956    /// Set the surface config (present mode, frame latency) the app wants the `wgpu`
957    /// renderer to use.
958    ///
959    /// No-op unless we are rendering with `wgpu`.
960    ///
961    /// The config might not take effect if the surface does not support the
962    /// requested present mode. On web the config is ignored, since the browser
963    /// controls presentation via `requestAnimationFrame`.
964    #[cfg(feature = "wgpu_no_default_features")]
965    pub fn set_wgpu_surface_config(&mut self, config: egui_wgpu::SurfaceConfig) {
966        if let Some(current) = &mut self.wgpu_surface_config {
967            *current = config;
968        }
969    }
970}
971
972/// Information about the web environment (if applicable).
973#[derive(Clone, Debug)]
974#[cfg(target_arch = "wasm32")]
975pub struct WebInfo {
976    /// The browser user agent.
977    pub user_agent: String,
978
979    /// Information about the URL.
980    pub location: Location,
981}
982
983/// Information about the URL.
984///
985/// Everything has been percent decoded (`%20` -> ` ` etc).
986#[cfg(target_arch = "wasm32")]
987#[derive(Clone, Debug)]
988pub struct Location {
989    /// The full URL (`location.href`) without the hash, percent-decoded.
990    ///
991    /// Example: `"http://www.example.com:80/index.html?foo=bar"`.
992    pub url: String,
993
994    /// `location.protocol`
995    ///
996    /// Example: `"http:"`.
997    pub protocol: String,
998
999    /// `location.host`
1000    ///
1001    /// Example: `"example.com:80"`.
1002    pub host: String,
1003
1004    /// `location.hostname`
1005    ///
1006    /// Example: `"example.com"`.
1007    pub hostname: String,
1008
1009    /// `location.port`
1010    ///
1011    /// Example: `"80"`.
1012    pub port: String,
1013
1014    /// The "#fragment" part of "www.example.com/index.html?query#fragment".
1015    ///
1016    /// Note that the leading `#` is included in the string.
1017    /// Also known as "hash-link" or "anchor".
1018    pub hash: String,
1019
1020    /// The "query" part of "www.example.com/index.html?query#fragment".
1021    ///
1022    /// Note that the leading `?` is NOT included in the string.
1023    ///
1024    /// Use [`Self::query_map`] to get the parsed version of it.
1025    pub query: String,
1026
1027    /// The parsed "query" part of "www.example.com/index.html?query#fragment".
1028    ///
1029    /// "foo=hello&bar%20&foo=world" is parsed as `{"bar ": [""], "foo": ["hello", "world"]}`
1030    pub query_map: std::collections::BTreeMap<String, Vec<String>>,
1031
1032    /// `location.origin`
1033    ///
1034    /// Example: `"http://www.example.com:80"`.
1035    pub origin: String,
1036}
1037
1038/// Information about the integration passed to the use app each frame.
1039#[derive(Clone, Debug)]
1040pub struct IntegrationInfo {
1041    /// Information about the surrounding web environment.
1042    #[cfg(target_arch = "wasm32")]
1043    pub web_info: WebInfo,
1044
1045    /// Seconds of cpu usage (in seconds) on the previous frame.
1046    ///
1047    /// This includes [`App::ui`] as well as rendering (except for vsync waiting).
1048    ///
1049    /// For a more detailed view of cpu usage, connect your preferred profiler by enabling it's feature in [`profiling`](https://crates.io/crates/profiling).
1050    ///
1051    /// `None` if this is the first frame.
1052    pub cpu_usage: Option<f32>,
1053}
1054
1055impl IntegrationInfo {
1056    fn mock() -> Self {
1057        Self {
1058            #[cfg(target_arch = "wasm32")]
1059            web_info: WebInfo {
1060                user_agent: "kittest".to_owned(),
1061                location: Location {
1062                    url: "http://localhost".to_owned(),
1063                    protocol: "http:".to_owned(),
1064                    host: "localhost".to_owned(),
1065                    hostname: "localhost".to_owned(),
1066                    port: "80".to_owned(),
1067                    hash: String::new(),
1068                    query: String::new(),
1069                    query_map: Default::default(),
1070                    origin: "http://localhost".to_owned(),
1071                },
1072            },
1073            cpu_usage: None,
1074        }
1075    }
1076}
1077
1078// ----------------------------------------------------------------------------
1079
1080/// A place where you can store custom data in a way that persists when you restart the app.
1081///
1082/// On the web this is backed by [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
1083/// On desktop this is backed by the file system.
1084///
1085/// See [`CreationContext::storage`] and [`App::save`].
1086pub trait Storage {
1087    /// Get the value for the given key.
1088    fn get_string(&self, key: &str) -> Option<String>;
1089
1090    /// Set the value for the given key.
1091    fn set_string(&mut self, key: &str, value: String);
1092
1093    /// Remove a given key.
1094    fn remove_string(&mut self, key: &str);
1095
1096    /// write-to-disk or similar
1097    fn flush(&mut self);
1098}
1099
1100/// Get and deserialize the [RON](https://github.com/ron-rs/ron) stored at the given key.
1101#[cfg(feature = "ron")]
1102pub fn get_value<T: serde::de::DeserializeOwned>(storage: &dyn Storage, key: &str) -> Option<T> {
1103    profiling::function_scope!(key);
1104    let value = storage.get_string(key)?;
1105    match ron::from_str(&value) {
1106        Ok(value) => Some(value),
1107        Err(err) => {
1108            // This happens on when we break the format, e.g. when updating egui.
1109            log::debug!("Failed to decode RON: {err}");
1110            None
1111        }
1112    }
1113}
1114
1115/// Serialize the given value as [RON](https://github.com/ron-rs/ron) and store with the given key.
1116#[cfg(feature = "ron")]
1117pub fn set_value<T: serde::Serialize>(storage: &mut dyn Storage, key: &str, value: &T) {
1118    profiling::function_scope!(key);
1119    match ron::ser::to_string(value) {
1120        Ok(string) => storage.set_string(key, string),
1121        Err(err) => log::error!("eframe failed to encode data using ron: {err}"),
1122    }
1123}
1124
1125/// [`Storage`] key used for app
1126pub const APP_KEY: &str = "app";