app_size_handler.rs (2419B)
1 use std::time::{Duration, Instant}; 2 3 use egui::Context; 4 use tracing::info; 5 6 use crate::storage::{write_file, DataPath, DataPathType, Directory}; 7 8 pub struct AppSizeHandler { 9 directory: Directory, 10 saved_size: Option<egui::Vec2>, 11 last_saved: Instant, 12 } 13 14 static FILE_NAME: &str = "app_size.json"; 15 static DELAY: Duration = Duration::from_millis(500); 16 17 impl AppSizeHandler { 18 pub fn new(path: &DataPath) -> Self { 19 let directory = Directory::new(path.path(DataPathType::Setting)); 20 21 Self { 22 directory, 23 saved_size: None, 24 last_saved: Instant::now() - DELAY, 25 } 26 } 27 28 pub fn try_save_app_size(&mut self, ctx: &Context) { 29 // There doesn't seem to be a way to check if user is resizing window, so if the rect is different than last saved, we'll wait DELAY before saving again to avoid spamming io 30 if self.last_saved.elapsed() >= DELAY { 31 internal_try_save_app_size(&self.directory, &mut self.saved_size, ctx); 32 self.last_saved = Instant::now(); 33 } 34 } 35 36 pub fn get_app_size(&self) -> Option<egui::Vec2> { 37 if self.saved_size.is_some() { 38 return self.saved_size; 39 } 40 41 if let Ok(file_contents) = self.directory.get_file(FILE_NAME.to_owned()) { 42 if let Ok(rect) = serde_json::from_str::<egui::Vec2>(&file_contents) { 43 return Some(rect); 44 } 45 } else { 46 info!("Could not find {}", FILE_NAME); 47 } 48 49 None 50 } 51 } 52 53 fn internal_try_save_app_size( 54 interactor: &Directory, 55 maybe_saved_size: &mut Option<egui::Vec2>, 56 ctx: &Context, 57 ) { 58 let cur_size = ctx.input(|i| i.screen_rect.size()); 59 if let Some(saved_size) = maybe_saved_size { 60 if cur_size != *saved_size { 61 try_save_size(interactor, cur_size, maybe_saved_size); 62 } 63 } else { 64 try_save_size(interactor, cur_size, maybe_saved_size); 65 } 66 } 67 68 fn try_save_size( 69 interactor: &Directory, 70 cur_size: egui::Vec2, 71 maybe_saved_size: &mut Option<egui::Vec2>, 72 ) { 73 if let Ok(serialized_rect) = serde_json::to_string(&cur_size) { 74 if write_file( 75 &interactor.file_path, 76 FILE_NAME.to_owned(), 77 &serialized_rect, 78 ) 79 .is_ok() 80 { 81 info!("wrote size {}", cur_size,); 82 *maybe_saved_size = Some(cur_size); 83 } 84 } 85 }