mirror of
https://github.com/emilk/egui.git
synced 2026-08-30 21:30:03 -04:00
[eframe] Make persistence, http and time optional features
Saves on compile times.
This commit is contained in:
@@ -1,12 +1,32 @@
|
||||
use crate::{window_settings::WindowSettings, *};
|
||||
use egui::Color32;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::{storage::WindowSettings, *};
|
||||
|
||||
pub use egui::Color32;
|
||||
|
||||
#[cfg(feature = "persistence")]
|
||||
const EGUI_MEMORY_KEY: &str = "egui";
|
||||
#[cfg(feature = "persistence")]
|
||||
const WINDOW_KEY: &str = "window";
|
||||
|
||||
#[cfg(feature = "persistence")]
|
||||
fn deserialize_window_settings(storage: &Option<Box<dyn epi::Storage>>) -> Option<WindowSettings> {
|
||||
epi::get_value(&**storage.as_ref()?, WINDOW_KEY)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "persistence"))]
|
||||
fn deserialize_window_settings(_: &Option<Box<dyn epi::Storage>>) -> Option<WindowSettings> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "persistence")]
|
||||
fn deserialize_memory(storage: &Option<Box<dyn epi::Storage>>) -> Option<egui::Memory> {
|
||||
epi::get_value(&**storage.as_ref()?, EGUI_MEMORY_KEY)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "persistence"))]
|
||||
fn deserialize_memory(_: &Option<Box<dyn epi::Storage>>) -> Option<egui::Memory> {
|
||||
None
|
||||
}
|
||||
|
||||
impl epi::TextureAllocator for Painter {
|
||||
fn alloc(&mut self) -> egui::TextureId {
|
||||
self.alloc_user_texture()
|
||||
@@ -69,6 +89,12 @@ fn create_display(
|
||||
display
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "persistence"))]
|
||||
fn create_storage(_app_name: &str) -> Option<Box<dyn epi::Storage>> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "persistence")]
|
||||
fn create_storage(app_name: &str) -> Option<Box<dyn epi::Storage>> {
|
||||
if let Some(proj_dirs) = directories_next::ProjectDirs::from("", "", app_name) {
|
||||
let data_dir = proj_dirs.data_dir().to_path_buf();
|
||||
@@ -81,7 +107,7 @@ fn create_storage(app_name: &str) -> Option<Box<dyn epi::Storage>> {
|
||||
} else {
|
||||
let mut config_dir = data_dir;
|
||||
config_dir.push("app.json");
|
||||
let storage = crate::storage::FileStorage::from_path(config_dir);
|
||||
let storage = crate::persistence::FileStorage::from_path(config_dir);
|
||||
Some(Box::new(storage))
|
||||
}
|
||||
} else {
|
||||
@@ -97,7 +123,7 @@ fn integration_info(
|
||||
epi::IntegrationInfo {
|
||||
web_info: None,
|
||||
cpu_usage: previous_frame_time,
|
||||
seconds_since_midnight: Some(seconds_since_midnight()),
|
||||
seconds_since_midnight: seconds_since_midnight(),
|
||||
native_pixels_per_point: Some(native_pixels_per_point(&display)),
|
||||
}
|
||||
}
|
||||
@@ -110,9 +136,7 @@ pub fn run(mut app: Box<dyn epi::App>) -> ! {
|
||||
app.load(storage.as_ref());
|
||||
}
|
||||
|
||||
let window_settings: Option<WindowSettings> = storage
|
||||
.as_mut()
|
||||
.and_then(|storage| epi::get_value(storage.as_ref(), WINDOW_KEY));
|
||||
let window_settings = deserialize_window_settings(&storage);
|
||||
let event_loop = glutin::event_loop::EventLoop::with_user_event();
|
||||
let display = create_display(app.name(), window_settings, app.is_resizable(), &event_loop);
|
||||
|
||||
@@ -121,10 +145,7 @@ pub fn run(mut app: Box<dyn epi::App>) -> ! {
|
||||
)));
|
||||
|
||||
let mut ctx = egui::CtxRef::default();
|
||||
*ctx.memory() = storage
|
||||
.as_mut()
|
||||
.and_then(|storage| epi::get_value(storage.as_ref(), EGUI_MEMORY_KEY))
|
||||
.unwrap_or_default();
|
||||
*ctx.memory() = deserialize_memory(&storage).unwrap_or_default();
|
||||
|
||||
app.setup(&ctx);
|
||||
|
||||
@@ -135,8 +156,10 @@ pub fn run(mut app: Box<dyn epi::App>) -> ! {
|
||||
let mut painter = Painter::new(&display);
|
||||
let mut clipboard = init_clipboard();
|
||||
|
||||
#[cfg(feature = "persistence")]
|
||||
let mut last_auto_save = Instant::now();
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
let http = std::sync::Arc::new(crate::http::GliumHttp {});
|
||||
|
||||
if app.warm_up_enabled() {
|
||||
@@ -151,6 +174,7 @@ pub fn run(mut app: Box<dyn epi::App>) -> ! {
|
||||
let mut frame = epi::backend::FrameBuilder {
|
||||
info: integration_info(&display, None),
|
||||
tex_allocator: Some(&mut painter),
|
||||
#[cfg(feature = "http")]
|
||||
http: http.clone(),
|
||||
output: &mut app_output,
|
||||
repaint_signal: repaint_signal.clone(),
|
||||
@@ -183,6 +207,7 @@ pub fn run(mut app: Box<dyn epi::App>) -> ! {
|
||||
let mut frame = epi::backend::FrameBuilder {
|
||||
info: integration_info(&display, previous_frame_time),
|
||||
tex_allocator: Some(&mut painter),
|
||||
#[cfg(feature = "http")]
|
||||
http: http.clone(),
|
||||
output: &mut app_output,
|
||||
repaint_signal: repaint_signal.clone(),
|
||||
@@ -236,6 +261,7 @@ pub fn run(mut app: Box<dyn epi::App>) -> ! {
|
||||
|
||||
handle_output(egui_output, &display, clipboard.as_mut());
|
||||
|
||||
#[cfg(feature = "persistence")]
|
||||
if let Some(storage) = &mut storage {
|
||||
let now = Instant::now();
|
||||
if now - last_auto_save > app.auto_save_interval() {
|
||||
@@ -265,6 +291,7 @@ pub fn run(mut app: Box<dyn epi::App>) -> ! {
|
||||
}
|
||||
glutin::event::Event::LoopDestroyed => {
|
||||
app.on_exit();
|
||||
#[cfg(feature = "persistence")]
|
||||
if let Some(storage) = &mut storage {
|
||||
epi::set_value(
|
||||
storage.as_mut(),
|
||||
|
||||
@@ -13,7 +13,9 @@ mod backend;
|
||||
#[cfg(feature = "http")]
|
||||
pub mod http;
|
||||
mod painter;
|
||||
pub mod storage;
|
||||
#[cfg(feature = "persistence")]
|
||||
pub mod persistence;
|
||||
pub mod window_settings;
|
||||
|
||||
pub use backend::*;
|
||||
pub use painter::Painter;
|
||||
@@ -279,10 +281,17 @@ pub fn init_clipboard() -> Option<ClipboardContext> {
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Time of day as seconds since midnight. Used for clock in demo app.
|
||||
pub fn seconds_since_midnight() -> f64 {
|
||||
use chrono::Timelike;
|
||||
let time = chrono::Local::now().time();
|
||||
time.num_seconds_from_midnight() as f64 + 1e-9 * (time.nanosecond() as f64)
|
||||
pub fn seconds_since_midnight() -> Option<f64> {
|
||||
#[cfg(feature = "time")]
|
||||
{
|
||||
use chrono::Timelike;
|
||||
let time = chrono::Local::now().time();
|
||||
let seconds_since_midnight =
|
||||
time.num_seconds_from_midnight() as f64 + 1e-9 * (time.nanosecond() as f64);
|
||||
Some(seconds_since_midnight)
|
||||
}
|
||||
#[cfg(not(feature = "time"))]
|
||||
None
|
||||
}
|
||||
|
||||
pub fn screen_size_in_pixels(display: &glium::Display) -> Vec2 {
|
||||
|
||||
87
egui_glium/src/persistence.rs
Normal file
87
egui_glium/src/persistence.rs
Normal file
@@ -0,0 +1,87 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// A key-value store backed by a JSON file on disk.
|
||||
/// Used to restore egui state, glium window position/size and app state.
|
||||
pub struct FileStorage {
|
||||
path: PathBuf,
|
||||
kv: HashMap<String, String>,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
impl FileStorage {
|
||||
pub fn from_path(path: impl Into<PathBuf>) -> Self {
|
||||
let path: PathBuf = path.into();
|
||||
Self {
|
||||
kv: read_json(&path).unwrap_or_default(),
|
||||
path,
|
||||
dirty: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl epi::Storage for FileStorage {
|
||||
fn get_string(&self, key: &str) -> Option<String> {
|
||||
self.kv.get(key).cloned()
|
||||
}
|
||||
|
||||
fn set_string(&mut self, key: &str, value: String) {
|
||||
if self.kv.get(key) != Some(&value) {
|
||||
self.kv.insert(key.to_owned(), value);
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) {
|
||||
if self.dirty {
|
||||
serde_json::to_writer(std::fs::File::create(&self.path).unwrap(), &self.kv).unwrap();
|
||||
self.dirty = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
pub fn read_json<T>(memory_json_path: impl AsRef<Path>) -> Option<T>
|
||||
where
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
match std::fs::File::open(memory_json_path) {
|
||||
Ok(file) => {
|
||||
let reader = std::io::BufReader::new(file);
|
||||
match serde_json::from_reader(reader) {
|
||||
Ok(value) => Some(value),
|
||||
Err(err) => {
|
||||
eprintln!("ERROR: Failed to parse json: {}", err);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_err) => {
|
||||
// File probably doesn't exist. That's fine.
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Alternative to `FileStorage`
|
||||
pub fn read_memory(ctx: &egui::Context, memory_json_path: impl AsRef<std::path::Path>) {
|
||||
let memory: Option<egui::Memory> = read_json(memory_json_path);
|
||||
if let Some(memory) = memory {
|
||||
*ctx.memory() = memory;
|
||||
}
|
||||
}
|
||||
|
||||
/// Alternative to `FileStorage`
|
||||
pub fn write_memory(
|
||||
ctx: &egui::Context,
|
||||
memory_json_path: impl AsRef<std::path::Path>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
serde_json::to_writer_pretty(std::fs::File::create(memory_json_path)?, &*ctx.memory())?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// A key-value store backed by a JSON file on disk.
|
||||
/// Used to restore egui state, glium window position/size and app state.
|
||||
pub struct FileStorage {
|
||||
path: PathBuf,
|
||||
kv: HashMap<String, String>,
|
||||
dirty: bool,
|
||||
}
|
||||
|
||||
impl FileStorage {
|
||||
pub fn from_path(path: impl Into<PathBuf>) -> Self {
|
||||
let path: PathBuf = path.into();
|
||||
Self {
|
||||
kv: read_json(&path).unwrap_or_default(),
|
||||
path,
|
||||
dirty: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl epi::Storage for FileStorage {
|
||||
fn get_string(&self, key: &str) -> Option<String> {
|
||||
self.kv.get(key).cloned()
|
||||
}
|
||||
|
||||
fn set_string(&mut self, key: &str, value: String) {
|
||||
if self.kv.get(key) != Some(&value) {
|
||||
self.kv.insert(key.to_owned(), value);
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) {
|
||||
if self.dirty {
|
||||
serde_json::to_writer(std::fs::File::create(&self.path).unwrap(), &self.kv).unwrap();
|
||||
self.dirty = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
pub fn read_json<T>(memory_json_path: impl AsRef<Path>) -> Option<T>
|
||||
where
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
match std::fs::File::open(memory_json_path) {
|
||||
Ok(file) => {
|
||||
let reader = std::io::BufReader::new(file);
|
||||
match serde_json::from_reader(reader) {
|
||||
Ok(value) => Some(value),
|
||||
Err(err) => {
|
||||
eprintln!("ERROR: Failed to parse json: {}", err);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_err) => {
|
||||
// File probably doesn't exist. That's fine.
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Alternative to `FileStorage`
|
||||
pub fn read_memory(ctx: &egui::Context, memory_json_path: impl AsRef<std::path::Path>) {
|
||||
let memory: Option<egui::Memory> = read_json(memory_json_path);
|
||||
if let Some(memory) = memory {
|
||||
*ctx.memory() = memory;
|
||||
}
|
||||
}
|
||||
|
||||
/// Alternative to `FileStorage`
|
||||
pub fn write_memory(
|
||||
ctx: &egui::Context,
|
||||
memory_json_path: impl AsRef<std::path::Path>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
serde_json::to_writer_pretty(std::fs::File::create(memory_json_path)?, &*ctx.memory())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
use glium::glutin;
|
||||
|
||||
#[derive(Default, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct WindowSettings {
|
||||
/// outer position of window in physical pixels
|
||||
pos: Option<egui::Pos2>,
|
||||
/// Inner size of window in logical pixels
|
||||
inner_size_points: Option<egui::Vec2>,
|
||||
}
|
||||
|
||||
impl WindowSettings {
|
||||
pub fn from_json_file(
|
||||
settings_json_path: impl AsRef<std::path::Path>,
|
||||
) -> Option<WindowSettings> {
|
||||
read_json(settings_json_path)
|
||||
}
|
||||
|
||||
pub fn from_display(display: &glium::Display) -> Self {
|
||||
let scale_factor = display.gl_window().window().scale_factor();
|
||||
let inner_size_points = display
|
||||
.gl_window()
|
||||
.window()
|
||||
.inner_size()
|
||||
.to_logical::<f32>(scale_factor);
|
||||
|
||||
Self {
|
||||
pos: display
|
||||
.gl_window()
|
||||
.window()
|
||||
.outer_position()
|
||||
.ok()
|
||||
.map(|p| egui::pos2(p.x as f32, p.y as f32)),
|
||||
|
||||
inner_size_points: Some(egui::vec2(
|
||||
inner_size_points.width as f32,
|
||||
inner_size_points.height as f32,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize_size(
|
||||
&self,
|
||||
window: glutin::window::WindowBuilder,
|
||||
) -> glutin::window::WindowBuilder {
|
||||
if let Some(inner_size_points) = self.inner_size_points {
|
||||
window.with_inner_size(glutin::dpi::LogicalSize {
|
||||
width: inner_size_points.x as f64,
|
||||
height: inner_size_points.y as f64,
|
||||
})
|
||||
} else {
|
||||
window
|
||||
}
|
||||
|
||||
// Not yet available in winit: https://github.com/rust-windowing/winit/issues/1190
|
||||
// if let Some(pos) = self.pos {
|
||||
// *window = window.with_outer_pos(glutin::dpi::PhysicalPosition {
|
||||
// x: pos.x as f64,
|
||||
// y: pos.y as f64,
|
||||
// });
|
||||
// }
|
||||
}
|
||||
|
||||
pub fn restore_positions(&self, display: &glium::Display) {
|
||||
// not needed, done by `initialize_size`
|
||||
// let size = self.size.unwrap_or_else(|| vec2(1024.0, 800.0));
|
||||
// display
|
||||
// .gl_window()
|
||||
// .window()
|
||||
// .set_inner_size(glutin::dpi::PhysicalSize {
|
||||
// width: size.x as f64,
|
||||
// height: size.y as f64,
|
||||
// });
|
||||
|
||||
if let Some(pos) = self.pos {
|
||||
display
|
||||
.gl_window()
|
||||
.window()
|
||||
.set_outer_position(glutin::dpi::PhysicalPosition::new(
|
||||
pos.x as f64,
|
||||
pos.y as f64,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
85
egui_glium/src/window_settings.rs
Normal file
85
egui_glium/src/window_settings.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use glium::glutin;
|
||||
|
||||
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct WindowSettings {
|
||||
/// outer position of window in physical pixels
|
||||
pos: Option<egui::Pos2>,
|
||||
/// Inner size of window in logical pixels
|
||||
inner_size_points: Option<egui::Vec2>,
|
||||
}
|
||||
|
||||
impl WindowSettings {
|
||||
#[cfg(feature = "persistence")]
|
||||
pub fn from_json_file(
|
||||
settings_json_path: impl AsRef<std::path::Path>,
|
||||
) -> Option<WindowSettings> {
|
||||
crate::persistence::read_json(settings_json_path)
|
||||
}
|
||||
|
||||
pub fn from_display(display: &glium::Display) -> Self {
|
||||
let scale_factor = display.gl_window().window().scale_factor();
|
||||
let inner_size_points = display
|
||||
.gl_window()
|
||||
.window()
|
||||
.inner_size()
|
||||
.to_logical::<f32>(scale_factor);
|
||||
|
||||
Self {
|
||||
pos: display
|
||||
.gl_window()
|
||||
.window()
|
||||
.outer_position()
|
||||
.ok()
|
||||
.map(|p| egui::pos2(p.x as f32, p.y as f32)),
|
||||
|
||||
inner_size_points: Some(egui::vec2(
|
||||
inner_size_points.width as f32,
|
||||
inner_size_points.height as f32,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize_size(
|
||||
&self,
|
||||
window: glutin::window::WindowBuilder,
|
||||
) -> glutin::window::WindowBuilder {
|
||||
if let Some(inner_size_points) = self.inner_size_points {
|
||||
window.with_inner_size(glutin::dpi::LogicalSize {
|
||||
width: inner_size_points.x as f64,
|
||||
height: inner_size_points.y as f64,
|
||||
})
|
||||
} else {
|
||||
window
|
||||
}
|
||||
|
||||
// Not yet available in winit: https://github.com/rust-windowing/winit/issues/1190
|
||||
// if let Some(pos) = self.pos {
|
||||
// *window = window.with_outer_pos(glutin::dpi::PhysicalPosition {
|
||||
// x: pos.x as f64,
|
||||
// y: pos.y as f64,
|
||||
// });
|
||||
// }
|
||||
}
|
||||
|
||||
pub fn restore_positions(&self, display: &glium::Display) {
|
||||
// not needed, done by `initialize_size`
|
||||
// let size = self.size.unwrap_or_else(|| vec2(1024.0, 800.0));
|
||||
// display
|
||||
// .gl_window()
|
||||
// .window()
|
||||
// .set_inner_size(glutin::dpi::PhysicalSize {
|
||||
// width: size.x as f64,
|
||||
// height: size.y as f64,
|
||||
// });
|
||||
|
||||
if let Some(pos) = self.pos {
|
||||
display
|
||||
.gl_window()
|
||||
.window()
|
||||
.set_outer_position(glutin::dpi::PhysicalPosition::new(
|
||||
pos.x as f64,
|
||||
pos.y as f64,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user