Skip to content

Commit

Permalink
simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob-pro committed Dec 9, 2023
1 parent f2ac9ee commit 6c63dab
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 103 deletions.
1 change: 0 additions & 1 deletion app/src/gui/epi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ pub trait App {
/// To force a repaint, call [`egui::Context::request_repaint`] at any time (e.g. from another thread).
fn update(&mut self, ctx: &egui::Context);


/// Background color values for the app, e.g. what is sent to `gl.clearColor`.
///
/// This is the background of your windows if you don't set a central panel.
Expand Down
2 changes: 1 addition & 1 deletion app/src/gui/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod wgpu_app;
pub mod epi;
pub mod wgpu_app;
152 changes: 62 additions & 90 deletions app/src/gui/wgpu_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
use std::time::Instant;

use winit::event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget};
use egui_winit::winit;
use std::sync::Arc;
use winit::event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget};

use super::epi;
use crate::common::APP_NAME;
use crate::run;
use egui_winit::egui;
use egui_winit::egui::Visuals;
use egui_winit::winit::event::Event;
use crate::common::APP_NAME;
use crate::run;
use super::epi;

#[derive(Debug)]
pub enum UserEvent {
Expand Down Expand Up @@ -47,15 +47,11 @@ pub enum EventResult {
Exit,
}

/// State that is initialized when the application is first starts running via
/// a Resumed event. On Android this ensures that any graphics state is only
/// initialized once the application has an associated `SurfaceView`.
struct WgpuWinitRunning {
painter: egui_wgpu::winit::Painter,
app: Box<dyn epi::App>,
window: winit::window::Window,
follow_system_theme: bool,

egui_ctx: egui::Context,
pending_full_output: egui::FullOutput,
egui_winit: egui_winit::State,
Expand All @@ -70,21 +66,19 @@ pub struct WgpuWinitApp {
}

impl WgpuWinitApp {
pub fn new(
event_loop: &EventLoop<UserEvent>,
app: AppCreator,
) -> Self {
pub fn new(event_loop: &EventLoop<UserEvent>, app: AppCreator) -> Self {
Self {
repaint_proxy: Arc::new(std::sync::Mutex::new(event_loop.create_proxy())),
running: None,
app,
}
}

pub fn create_window(
pub fn init_run_state(
&mut self,
event_loop: &EventLoopWindowTarget<UserEvent>,
) -> Result<winit::window::Window, winit::error::OsError> {
winit::window::WindowBuilder::new()
) -> anyhow::Result<()> {
let window = winit::window::WindowBuilder::new()
.with_decorations(true)
.with_resizable(true)
.with_transparent(false)
Expand All @@ -93,74 +87,58 @@ impl WgpuWinitApp {
width: 800,
height: 600,
})
.build(&event_loop)
}
.build(&event_loop)?;
window.set_ime_allowed(true);

pub fn init_run_state(
&mut self,
event_loop: &EventLoopWindowTarget<UserEvent>,
window: winit::window::Window,
) -> std::result::Result<(), egui_wgpu::WgpuError> {
let mut painter = egui_wgpu::winit::Painter::new(
egui_wgpu::WgpuConfiguration::default(),
1,
None,
false,
);
pollster::block_on(painter.set_window(Some(&window)))?;
let mut painter =
egui_wgpu::winit::Painter::new(egui_wgpu::WgpuConfiguration::default(), 1, None, false);

let max_texture_side = painter.max_texture_side().unwrap_or(2048);
pollster::block_on(painter.set_window(Some(&window)))?;

let egui_ctx = egui::Context::default();
let mut egui_winit = egui_winit::State::new(event_loop);

let memory = Default::default();
egui_ctx.memory_mut(|mem| *mem = memory);
let max_texture_side = painter.max_texture_side().unwrap_or(2048);
egui_winit.set_max_texture_side(max_texture_side);

let native_pixels_per_point = window.scale_factor() as f32;

let mut egui_winit = egui_winit::State::new(event_loop);
egui_winit.set_max_texture_side(max_texture_side);
egui_winit.set_pixels_per_point(native_pixels_per_point);

let system_theme = window.theme();
egui_ctx.set_visuals(system_theme.map(visuals_from_winit_theme).unwrap_or(Visuals::light()));

window.set_ime_allowed(true);
let egui_ctx = egui::Context::default();

{
let event_loop_proxy = self.repaint_proxy.clone();
egui_ctx
.set_request_repaint_callback(move |info| {
log::trace!("request_repaint_callback: {info:?}");
let when = Instant::now() + info.after;
let frame_nr = info.current_frame_nr;
event_loop_proxy
.lock()
.unwrap()
.send_event(UserEvent::RequestRepaint { when, frame_nr })
.ok();
});
}
let system_theme = window.theme();
egui_ctx.set_visuals(
system_theme
.map(visuals_from_winit_theme)
.unwrap_or(Visuals::light()),
);

let app = (self.app)();
let event_loop_proxy = self.repaint_proxy.clone();
egui_ctx.set_request_repaint_callback(move |info| {
log::trace!("request_repaint_callback: {info:?}");
let when = Instant::now() + info.after;
let frame_nr = info.current_frame_nr;
event_loop_proxy
.lock()
.unwrap()
.send_event(UserEvent::RequestRepaint { when, frame_nr })
.ok();
});

self.running = Some(WgpuWinitRunning {
painter,
app,
app: (self.app)(),
window,
follow_system_theme: system_theme.is_some(),
egui_ctx,
pending_full_output: Default::default(),
egui_winit
egui_winit,
});

Ok(())
}

pub fn frame_nr(&self) -> u64 {
self.running
.as_ref()
.map_or(0, |r| r.egui_ctx.frame_nr())
self.running.as_ref().map_or(0, |r| r.egui_ctx.frame_nr())
}

pub fn window(&self) -> Option<&winit::window::Window> {
Expand All @@ -175,7 +153,6 @@ impl WgpuWinitApp {

pub fn run_ui_and_paint(&mut self) -> EventResult {
if let Some(running) = &mut self.running {

let raw_input = running.egui_winit.take_egui_input(&running.window);

// Run user code:
Expand All @@ -193,13 +170,13 @@ impl WgpuWinitApp {
shapes,
} = full_output;

running.egui_winit
.handle_platform_output(&running.window, &running.egui_ctx, platform_output);

running.egui_winit.handle_platform_output(
&running.window,
&running.egui_ctx,
platform_output,
);

let clipped_primitives = {
running.egui_ctx.tessellate(shapes)
};
let clipped_primitives = { running.egui_ctx.tessellate(shapes) };

running.painter.paint_and_update_textures(
running.egui_ctx.pixels_per_point(),
Expand All @@ -212,7 +189,7 @@ impl WgpuWinitApp {
let control_flow = if repaint_after.is_zero() {
EventResult::RepaintNext
} else if let Some(repaint_after_instant) =
std::time::Instant::now().checked_add(repaint_after)
Instant::now().checked_add(repaint_after)
{
// if repaint_after is something huge and can't be added to Instant,
// we will use `ControlFlow::Wait` instead.
Expand Down Expand Up @@ -243,16 +220,15 @@ impl WgpuWinitApp {
event: &Event<'_, UserEvent>,
) -> anyhow::Result<EventResult> {
Ok(match event {
e if matches!(e, Event::Resumed) || matches!(e, Event::UserEvent(UserEvent::OpenWindow)) => {
e if matches!(e, Event::Resumed)
|| matches!(e, Event::UserEvent(UserEvent::OpenWindow)) =>
{
if self.running.is_none() {
let window = Self::create_window(event_loop)?;
self.init_run_state(event_loop, window)?;
self.init_run_state(event_loop)?;
}
EventResult::RepaintNow
}
Event::Suspended => {
EventResult::Wait
}
Event::Suspended => EventResult::Wait,

Event::WindowEvent { event, .. } => {
if let Some(running) = &mut self.running {
Expand All @@ -279,27 +255,26 @@ impl WgpuWinitApp {
// See: https://github.com/rust-windowing/winit/issues/208
// This solves an issue where the app would panic when minimizing on Windows.
if physical_size.width > 0 && physical_size.height > 0 {
running.painter.on_window_resized(
physical_size.width,
physical_size.height,
);
running
.painter
.on_window_resized(physical_size.width, physical_size.height);
}
}
winit::event::WindowEvent::ScaleFactorChanged {
new_inner_size,
..
new_inner_size, ..
} => {
repaint_asap = true;
running
.painter
.on_window_resized(new_inner_size.width, new_inner_size.height);
}
winit::event::WindowEvent::CloseRequested =>
{
log::debug!("Received WindowEvent::CloseRequested");
return Ok(EventResult::Exit);
}
winit::event::WindowEvent::ThemeChanged(winit_theme) if running.follow_system_theme => {
winit::event::WindowEvent::CloseRequested => {
log::debug!("Received WindowEvent::CloseRequested");
return Ok(EventResult::Exit);
}
winit::event::WindowEvent::ThemeChanged(winit_theme)
if running.follow_system_theme =>
{
let visuals = visuals_from_winit_theme(*winit_theme);
running.egui_ctx.set_visuals(visuals);
}
Expand All @@ -308,7 +283,6 @@ impl WgpuWinitApp {

let event_response = running.egui_winit.on_event(&running.egui_ctx, event);


if event_response.repaint {
if repaint_asap {
EventResult::RepaintNow
Expand All @@ -323,16 +297,14 @@ impl WgpuWinitApp {
}
}


_ => EventResult::Wait,
})
}
}


fn visuals_from_winit_theme(theme: winit::window::Theme) -> Visuals {
match theme {
winit::window::Theme::Dark => Visuals::dark(),
winit::window::Theme::Light => Visuals::light(),
}
}
}
17 changes: 8 additions & 9 deletions app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,20 @@ mod apply;
mod calculator;
mod common;
mod config;
mod gui;
mod tray2;
mod unique;
mod gui;

use crate::common::{install_logger, APP_NAME};
use crate::gui::wgpu_app::{EventResult, UserEvent, WgpuWinitApp};
use crate::unique::SsbUniqueInstance;
use egui_winit::winit::event::WindowEvent;
use egui_winit::{egui, winit};
use log::LevelFilter;
use std::time::{Duration, Instant};
use egui_winit::winit::event::WindowEvent;
use winit::event::Event;
use winit::event_loop::{ControlFlow, EventLoopBuilder};
use winit::platform::run_return::EventLoopExtRunReturn;
use crate::gui::wgpu_app::{EventResult, UserEvent, WgpuWinitApp};


#[derive(Default)]
struct MyEguiApp {
Expand Down Expand Up @@ -51,10 +50,7 @@ fn run() -> anyhow::Result<()> {

let tray = tray2::create(&event_loop)?;

let mut winit_app = WgpuWinitApp::new(
&event_loop,
Box::new(|| Box::new(MyEguiApp::default())),
);
let mut winit_app = WgpuWinitApp::new(&event_loop, Box::new(|| Box::new(MyEguiApp::default())));

let mut returned_result = Ok(());
let mut next_repaint_time = Instant::now();
Expand Down Expand Up @@ -95,7 +91,10 @@ fn run() -> anyhow::Result<()> {
EventResult::Wait
}

Event::WindowEvent { window_id: _, event: WindowEvent::CloseRequested } => {
Event::WindowEvent {
window_id: _,
event: WindowEvent::CloseRequested,
} => {
winit_app.destroy();
EventResult::Wait
}
Expand Down
4 changes: 2 additions & 2 deletions app/src/tray2.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::common::APP_NAME;
use crate::gui::wgpu_app::UserEvent;
use egui_winit::winit::event_loop::EventLoop;
use std::sync::{Arc, Mutex};
use tray_icon::menu::{Menu, MenuEvent, MenuId, MenuItemBuilder};
use tray_icon::{ClickType, Icon, TrayIcon, TrayIconBuilder, TrayIconEvent};
use egui_winit::winit::event_loop::EventLoop;
use crate::gui::wgpu_app::UserEvent;

const MENU_ID_OPEN: &str = "OPEN";
const MENU_ID_EXIT: &str = "EXIT";
Expand Down

0 comments on commit 6c63dab

Please sign in to comment.