/ epi / src / lib.rs
lib.rs
  1  //! Backend-agnostic interface for writing apps using [`egui`].
  2  //!
  3  //! `epi` provides interfaces for window management and serialization.
  4  //! An app written for `epi` can then be plugged into [`eframe`](https://docs.rs/eframe),
  5  //! the egui framework crate.
  6  //!
  7  //! Start by looking at the [`App`] trait, and implement [`App::update`].
  8  
  9  #![warn(missing_docs)] // Let's keep `epi` well-documented.
 10  
 11  /// File storage which can be used by native backends.
 12  #[cfg(feature = "file_storage")]
 13  pub mod file_storage;
 14  
 15  pub use egui; // Re-export for user convenience
 16  pub use glow; // Re-export for user convenience
 17  
 18  /// The is is how your app is created.
 19  ///
 20  /// You can use the [`CreationContext`] to setup egui, restore state, setup OpenGL things, etc.
 21  pub type AppCreator = Box<dyn FnOnce(&CreationContext<'_>) -> Box<dyn App>>;
 22  
 23  /// Data that is passed to [`AppCreator`] that can be used to setup and initialize your app.
 24  pub struct CreationContext<'s> {
 25      /// The egui Context.
 26      ///
 27      /// You can use this to customize the look of egui, e.g to call [`egui::Context::set_fonts`],
 28      /// [`egui::Context::set_visuals`] etc.
 29      pub egui_ctx: egui::Context,
 30  
 31      /// Information about the surrounding environment.
 32      pub integration_info: IntegrationInfo,
 33  
 34      /// You can use the storage to restore app state(requires the "persistence" feature).
 35      pub storage: Option<&'s dyn Storage>,
 36  
 37      /// The [`glow::Context`] allows you to initialize OpenGL resources (e.g. shaders) that
 38      /// you might want to use later from a [`egui::PaintCallback`].
 39      pub gl: std::rc::Rc<glow::Context>,
 40  }
 41  
 42  // ----------------------------------------------------------------------------
 43  
 44  /// Implement this trait to write apps that can be compiled both natively using the [`egui_glium`](https://github.com/emilk/egui/tree/master/egui_glium) crate,
 45  /// and deployed as a web site using the [`egui_web`](https://github.com/emilk/egui/tree/master/egui_web) crate.
 46  pub trait App {
 47      /// Called each time the UI needs repainting, which may be many times per second.
 48      ///
 49      /// Put your widgets into a [`egui::SidePanel`], [`egui::TopBottomPanel`], [`egui::CentralPanel`], [`egui::Window`] or [`egui::Area`].
 50      ///
 51      /// The [`egui::Context`] can be cloned and saved if you like.
 52      ///
 53      /// To force a repaint, call [`egui::Context::request_repaint`] at any time (e.g. from another thread).
 54      fn update(&mut self, ctx: &egui::Context, frame: &mut Frame);
 55  
 56      /// Called on shutdown, and perhaps at regular intervals. Allows you to save state.
 57      ///
 58      /// Only called when the "persistence" feature is enabled.
 59      ///
 60      /// On web the state is stored to "Local Storage".
 61      /// On native the path is picked using [`directories_next::ProjectDirs::data_dir`](https://docs.rs/directories-next/2.0.0/directories_next/struct.ProjectDirs.html#method.data_dir) which is:
 62      /// * Linux:   `/home/UserName/.local/share/APPNAME`
 63      /// * macOS:   `/Users/UserName/Library/Application Support/APPNAME`
 64      /// * Windows: `C:\Users\UserName\AppData\Roaming\APPNAME`
 65      ///
 66      /// where `APPNAME` is what is given to `eframe::run_native`.
 67      fn save(&mut self, _storage: &mut dyn Storage) {}
 68  
 69      /// Called before an exit that can be aborted.
 70      /// By returning `false` the exit will be aborted. To continue the exit return `true`.
 71      ///
 72      /// A scenario where this method will be run is after pressing the close button on a native
 73      /// window, which allows you to ask the user whether they want to do something before exiting.
 74      /// See the example `eframe/examples/confirm_exit.rs` for practical usage.
 75      ///
 76      /// It will _not_ be called on the web or when the window is forcefully closed.
 77      fn on_exit_event(&mut self) -> bool {
 78          true
 79      }
 80  
 81      /// Called once on shutdown, after [`Self::save`].
 82      ///
 83      /// If you need to abort an exit use [`Self::on_exit_event`].
 84      fn on_exit(&mut self, _gl: &glow::Context) {}
 85  
 86      // ---------
 87      // Settings:
 88  
 89      /// Time between automatic calls to [`Self::save`]
 90      fn auto_save_interval(&self) -> std::time::Duration {
 91          std::time::Duration::from_secs(30)
 92      }
 93  
 94      /// The size limit of the web app canvas.
 95      ///
 96      /// By default the max size is [`egui::Vec2::INFINITY`], i.e. unlimited.
 97      ///
 98      /// A large canvas can lead to bad frame rates on some older browsers on some platforms
 99      /// (see <https://bugzilla.mozilla.org/show_bug.cgi?id=1010527#c0>).
100      fn max_size_points(&self) -> egui::Vec2 {
101          egui::Vec2::INFINITY
102      }
103  
104      /// Background color for the app, e.g. what is sent to `gl.clearColor`.
105      /// This is the background of your windows if you don't set a central panel.
106      fn clear_color(&self) -> egui::Rgba {
107          // NOTE: a bright gray makes the shadows of the windows look weird.
108          // We use a bit of transparency so that if the user switches on the
109          // `transparent()` option they get immediate results.
110          egui::Color32::from_rgba_unmultiplied(12, 12, 12, 180).into()
111      }
112  
113      /// Controls whether or not the native window position and size will be
114      /// persisted (only if the "persistence" feature is enabled).
115      fn persist_native_window(&self) -> bool {
116          true
117      }
118  
119      /// Controls whether or not the egui memory (window positions etc) will be
120      /// persisted (only if the "persistence" feature is enabled).
121      fn persist_egui_memory(&self) -> bool {
122          true
123      }
124  
125      /// If `true` a warm-up call to [`Self::update`] will be issued where
126      /// `ctx.memory().everything_is_visible()` will be set to `true`.
127      ///
128      /// This can help pre-caching resources loaded by different parts of the UI, preventing stutter later on.
129      ///
130      /// In this warm-up call, all painted shapes will be ignored.
131      ///
132      /// The default is `false`, and it is unlikely you will want to change this.
133      fn warm_up_enabled(&self) -> bool {
134          false
135      }
136  }
137  
138  /// Options controlling the behavior of a native window.
139  ///
140  /// Only a single native window is currently supported.
141  #[derive(Clone)]
142  pub struct NativeOptions {
143      /// Sets whether or not the window will always be on top of other windows.
144      pub always_on_top: bool,
145  
146      /// Show window in maximized mode
147      pub maximized: bool,
148  
149      /// On desktop: add window decorations (i.e. a frame around your app)?
150      /// If false it will be difficult to move and resize the app.
151      pub decorated: bool,
152  
153      /// On Windows: enable drag and drop support. Drag and drop can
154      /// not be disabled on other platforms.
155      ///
156      /// See [winit's documentation][drag_and_drop] for information on why you
157      /// might want to disable this on windows.
158      ///
159      /// [drag_and_drop]: https://docs.rs/winit/latest/x86_64-pc-windows-msvc/winit/platform/windows/trait.WindowBuilderExtWindows.html#tymethod.with_drag_and_drop
160      pub drag_and_drop_support: bool,
161  
162      /// The application icon, e.g. in the Windows task bar etc.
163      pub icon_data: Option<IconData>,
164  
165      /// The initial (inner) position of the native window in points (logical pixels).
166      pub initial_window_pos: Option<egui::Pos2>,
167  
168      /// The initial inner size of the native window in points (logical pixels).
169      pub initial_window_size: Option<egui::Vec2>,
170  
171      /// The minimum inner window size
172      pub min_window_size: Option<egui::Vec2>,
173  
174      /// The maximum inner window size
175      pub max_window_size: Option<egui::Vec2>,
176  
177      /// Should the app window be resizable?
178      pub resizable: bool,
179  
180      /// On desktop: make the window transparent.
181      /// You control the transparency with [`App::clear_color()`].
182      /// You should avoid having a [`egui::CentralPanel`], or make sure its frame is also transparent.
183      pub transparent: bool,
184  
185      /// Turn on vertical syncing, limiting the FPS to the display refresh rate.
186      ///
187      /// The default is `true`.
188      pub vsync: bool,
189  
190      /// Set the level of the multisampling anti-aliasing (MSAA).
191      ///
192      /// Must be a power-of-two. Higher = more smooth 3D.
193      ///
194      /// A value of `0` turns it off (default).
195      ///
196      /// `egui` already performs anti-aliasing via "feathering"
197      /// (controlled by [`egui::epaint::TessellationOptions`]),
198      /// but if you are embedding 3D in egui you may want to turn on multisampling.
199      pub multisampling: u16,
200  
201      /// Sets the number of bits in the depth buffer.
202      ///
203      /// `egui` doesn't need the depth buffer, so the default value is 0.
204      pub depth_buffer: u8,
205  
206      /// Sets the number of bits in the stencil buffer.
207      ///
208      /// `egui` doesn't need the stencil buffer, so the default value is 0.
209      pub stencil_buffer: u8,
210  }
211  
212  impl Default for NativeOptions {
213      fn default() -> Self {
214          Self {
215              always_on_top: false,
216              maximized: false,
217              decorated: true,
218              drag_and_drop_support: true,
219              icon_data: None,
220              initial_window_pos: None,
221              initial_window_size: None,
222              min_window_size: None,
223              max_window_size: None,
224              resizable: true,
225              transparent: false,
226              vsync: true,
227              multisampling: 0,
228              depth_buffer: 0,
229              stencil_buffer: 0,
230          }
231      }
232  }
233  
234  /// Image data for the icon.
235  #[derive(Clone)]
236  pub struct IconData {
237      /// RGBA pixels, unmultiplied.
238      pub rgba: Vec<u8>,
239  
240      /// Image width. This should be a multiple of 4.
241      pub width: u32,
242  
243      /// Image height. This should be a multiple of 4.
244      pub height: u32,
245  }
246  
247  /// Represents the surroundings of your app.
248  ///
249  /// It provides methods to inspect the surroundings (are we on the web?),
250  /// allocate textures, and change settings (e.g. window size).
251  pub struct Frame {
252      /// Information about the integration.
253      #[doc(hidden)]
254      pub info: IntegrationInfo,
255  
256      /// Where the app can issue commands back to the integration.
257      #[doc(hidden)]
258      pub output: backend::AppOutput,
259  
260      /// A place where you can store custom data in a way that persists when you restart the app.
261      #[doc(hidden)]
262      pub storage: Option<Box<dyn Storage>>,
263  
264      /// A reference to the underlying [`glow`] (OpenGL) context.
265      #[doc(hidden)]
266      pub gl: std::rc::Rc<glow::Context>,
267  }
268  
269  impl Frame {
270      /// True if you are in a web environment.
271      pub fn is_web(&self) -> bool {
272          self.info.web_info.is_some()
273      }
274  
275      /// Information about the integration.
276      pub fn info(&self) -> IntegrationInfo {
277          self.info.clone()
278      }
279  
280      /// A place where you can store custom data in a way that persists when you restart the app.
281      pub fn storage(&self) -> Option<&dyn Storage> {
282          self.storage.as_deref()
283      }
284  
285      /// A place where you can store custom data in a way that persists when you restart the app.
286      pub fn storage_mut(&mut self) -> Option<&mut (dyn Storage + 'static)> {
287          self.storage.as_deref_mut()
288      }
289  
290      /// A reference to the underlying [`glow`] (OpenGL) context.
291      ///
292      /// This can be used, for instance, to:
293      /// * Render things to offscreen buffers.
294      /// * Read the pixel buffer from the previous frame (`glow::Context::read_pixels`).
295      /// * Render things behind the egui windows.
296      ///
297      /// Note that all egui painting is deferred to after the call to [`App::update`]
298      /// ([`egui`] only collects [`egui::Shape`]s and then eframe paints them all in one go later on).
299      pub fn gl(&self) -> &std::rc::Rc<glow::Context> {
300          &self.gl
301      }
302  
303      /// Signal the app to stop/exit/quit the app (only works for native apps, not web apps).
304      /// The framework will not quit immediately, but at the end of the this frame.
305      pub fn quit(&mut self) {
306          self.output.quit = true;
307      }
308  
309      /// Set the desired inner size of the window (in egui points).
310      pub fn set_window_size(&mut self, size: egui::Vec2) {
311          self.output.window_size = Some(size);
312      }
313  
314      /// Set the desired title of the window.
315      pub fn set_window_title(&mut self, title: &str) {
316          self.output.window_title = Some(title.to_owned());
317      }
318  
319      /// Set whether to show window decorations (i.e. a frame around you app).
320      /// If false it will be difficult to move and resize the app.
321      pub fn set_decorations(&mut self, decorated: bool) {
322          self.output.decorated = Some(decorated);
323      }
324  
325      /// When called, the native window will follow the
326      /// movement of the cursor while the primary mouse button is down.
327      ///
328      /// Does not work on the web.
329      pub fn drag_window(&mut self) {
330          self.output.drag_window = true;
331      }
332  
333      /// for integrations only: call once per frame
334      #[doc(hidden)]
335      pub fn take_app_output(&mut self) -> crate::backend::AppOutput {
336          std::mem::take(&mut self.output)
337      }
338  }
339  
340  /// Information about the web environment (if applicable).
341  #[derive(Clone, Debug)]
342  pub struct WebInfo {
343      /// Information about the URL.
344      pub location: Location,
345  }
346  
347  /// Information about the URL.
348  ///
349  /// Everything has been percent decoded (`%20` -> ` ` etc).
350  #[derive(Clone, Debug)]
351  pub struct Location {
352      /// The full URL (`location.href`) without the hash.
353      ///
354      /// Example: `"http://www.example.com:80/index.html?foo=bar"`.
355      pub url: String,
356  
357      /// `location.protocol`
358      ///
359      /// Example: `"http:"`.
360      pub protocol: String,
361  
362      /// `location.host`
363      ///
364      /// Example: `"example.com:80"`.
365      pub host: String,
366  
367      /// `location.hostname`
368      ///
369      /// Example: `"example.com"`.
370      pub hostname: String,
371  
372      /// `location.port`
373      ///
374      /// Example: `"80"`.
375      pub port: String,
376  
377      /// The "#fragment" part of "www.example.com/index.html?query#fragment".
378      ///
379      /// Note that the leading `#` is included in the string.
380      /// Also known as "hash-link" or "anchor".
381      pub hash: String,
382  
383      /// The "query" part of "www.example.com/index.html?query#fragment".
384      ///
385      /// Note that the leading `?` is NOT included in the string.
386      ///
387      /// Use [`Self::web_query_map]` to get the parsed version of it.
388      pub query: String,
389  
390      /// The parsed "query" part of "www.example.com/index.html?query#fragment".
391      ///
392      /// "foo=42&bar%20" is parsed as `{"foo": "42",  "bar ": ""}`
393      pub query_map: std::collections::BTreeMap<String, String>,
394  
395      /// `location.origin`
396      ///
397      /// Example: `"http://www.example.com:80"`.
398      pub origin: String,
399  }
400  
401  /// Information about the integration passed to the use app each frame.
402  #[derive(Clone, Debug)]
403  pub struct IntegrationInfo {
404      /// The name of the integration, e.g. `egui_web`, `egui_glium`, `egui_glow`
405      pub name: &'static str,
406  
407      /// If the app is running in a Web context, this returns information about the environment.
408      pub web_info: Option<WebInfo>,
409  
410      /// Does the system prefer dark mode (over light mode)?
411      /// `None` means "don't know".
412      pub prefer_dark_mode: Option<bool>,
413  
414      /// Seconds of cpu usage (in seconds) of UI code on the previous frame.
415      /// `None` if this is the first frame.
416      pub cpu_usage: Option<f32>,
417  
418      /// The OS native pixels-per-point
419      pub native_pixels_per_point: Option<f32>,
420  }
421  
422  /// Abstraction for platform dependent texture reference
423  pub trait NativeTexture {
424      /// The native texture type.
425      type Texture;
426  
427      /// Bind native texture to an egui texture id.
428      fn register_native_texture(&mut self, native: Self::Texture) -> egui::TextureId;
429  
430      /// Change what texture the given id refers to.
431      fn replace_native_texture(&mut self, id: egui::TextureId, replacing: Self::Texture);
432  }
433  
434  // ----------------------------------------------------------------------------
435  
436  /// A place where you can store custom data in a way that persists when you restart the app.
437  ///
438  /// On the web this is backed by [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
439  /// On desktop this is backed by the file system.
440  pub trait Storage {
441      /// Get the value for the given key.
442      fn get_string(&self, key: &str) -> Option<String>;
443      /// Set the value for the given key.
444      fn set_string(&mut self, key: &str, value: String);
445  
446      /// write-to-disk or similar
447      fn flush(&mut self);
448  }
449  
450  /// Stores nothing.
451  #[derive(Clone, Default)]
452  pub struct DummyStorage {}
453  
454  impl Storage for DummyStorage {
455      fn get_string(&self, _key: &str) -> Option<String> {
456          None
457      }
458      fn set_string(&mut self, _key: &str, _value: String) {}
459      fn flush(&mut self) {}
460  }
461  
462  /// Get and deserialize the [RON](https://github.com/ron-rs/ron) stored at the given key.
463  #[cfg(feature = "ron")]
464  pub fn get_value<T: serde::de::DeserializeOwned>(storage: &dyn Storage, key: &str) -> Option<T> {
465      storage
466          .get_string(key)
467          .and_then(|value| ron::from_str(&value).ok())
468  }
469  
470  /// Serialize the given value as [RON](https://github.com/ron-rs/ron) and store with the given key.
471  #[cfg(feature = "ron")]
472  pub fn set_value<T: serde::Serialize>(storage: &mut dyn Storage, key: &str, value: &T) {
473      storage.set_string(key, ron::ser::to_string(value).unwrap());
474  }
475  
476  /// [`Storage`] key used for app
477  pub const APP_KEY: &str = "app";
478  
479  // ----------------------------------------------------------------------------
480  
481  /// You only need to look here if you are writing a backend for `epi`.
482  #[doc(hidden)]
483  pub mod backend {
484      use super::*;
485  
486      /// Action that can be taken by the user app.
487      #[derive(Clone, Debug, Default)]
488      #[must_use]
489      pub struct AppOutput {
490          /// Set to `true` to stop the app.
491          /// This does nothing for web apps.
492          pub quit: bool,
493  
494          /// Set to some size to resize the outer window (e.g. glium window) to this size.
495          pub window_size: Option<egui::Vec2>,
496  
497          /// Set to some string to rename the outer window (e.g. glium window) to this title.
498          pub window_title: Option<String>,
499  
500          /// Set to some bool to change window decorations.
501          pub decorated: Option<bool>,
502  
503          /// Set to true to drag window while primary mouse button is down.
504          pub drag_window: bool,
505      }
506  }