Skip to content

Commit df7e1fc

Browse files
committed
simplify
1 parent 201eedf commit df7e1fc

File tree

9 files changed

+63
-520
lines changed

9 files changed

+63
-520
lines changed

app/Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

app/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "solar-screen-brightness"
3-
version = "0.2.0"
3+
version = "2.0.0"
44
authors = ["Jacob Halsey <[email protected]>"]
55
edition = "2021"
66
build = "build.rs"

app/src/common.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use anyhow::Context;
44
use log::LevelFilter;
5-
use simplelog::{ColorChoice, CombinedLogger, Config, TermLogger, TerminalMode, WriteLogger};
5+
use simplelog::{ColorChoice, CombinedLogger, TermLogger, TerminalMode, WriteLogger};
66
use std::fs;
77
use std::fs::File;
88
use std::path::PathBuf;
@@ -34,14 +34,14 @@ pub fn config_directory() -> anyhow::Result<PathBuf> {
3434
pub fn install_logger(filter: LevelFilter) -> anyhow::Result<()> {
3535
let path = local_data_directory()?.join("log.txt");
3636
let file = File::create(&path).context("Unable to create log file")?;
37-
let file_logger = WriteLogger::new(filter, Config::default(), file);
37+
let config = simplelog::ConfigBuilder::default()
38+
.add_filter_ignore_str("wgpu")
39+
.add_filter_ignore_str("naga")
40+
.set_target_level(LevelFilter::Debug)
41+
.build();
42+
let file_logger = WriteLogger::new(filter, config.clone(), file);
3843
CombinedLogger::init(vec![
39-
TermLogger::new(
40-
filter,
41-
Config::default(),
42-
TerminalMode::Stderr,
43-
ColorChoice::Auto,
44-
),
44+
TermLogger::new(filter, config, TerminalMode::Stderr, ColorChoice::Auto),
4545
file_logger,
4646
])?;
4747
Ok(())

app/src/gui/mod.rs

Lines changed: 20 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,24 @@ mod app;
22

33
use crate::common::APP_NAME;
44
use crate::gui::app::SsbEguiApp;
5+
use crate::tray::read_icon;
56
use crate::UserEvent;
67
use egui_winit::winit;
78
use egui_winit::winit::event::{Event, WindowEvent};
89
use egui_winit::winit::event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget};
10+
use egui_winit::winit::window::Icon;
911
use std::sync::{Arc, Mutex};
1012
use std::time::Instant;
1113

1214
#[derive(Debug)]
1315
pub enum NextPaint {
1416
/// Wait for an event
1517
Wait,
16-
17-
/// Causes a synchronous repaint inside the event handler. This should only
18-
/// be used in special situations if the window must be repainted while
19-
/// handling a specific event. This occurs on Windows when handling resizes.
20-
///
21-
/// `RepaintNow` creates a new frame synchronously, and should therefore
22-
/// only be used for extremely urgent repaints.
23-
RepaintNow,
24-
2518
/// Queues a repaint for once the event loop handles its next redraw. Exists
26-
/// so that multiple input events can be handled in one frame. Does not
27-
/// cause any delay like `RepaintNow`.
19+
/// so that multiple input events can be handled in one frame.
2820
RepaintNext,
29-
3021
/// Repaint at a particular time
3122
RepaintAt(Instant),
32-
3323
/// Exit the event loop
3424
Exit,
3525
}
@@ -53,13 +43,17 @@ impl Drop for WgpuWinitRunning {
5343
pub struct WgpuWinitApp {
5444
repaint_proxy: Arc<Mutex<EventLoopProxy<UserEvent>>>,
5545
running: Option<WgpuWinitRunning>,
46+
icon: Icon,
5647
}
5748

5849
impl WgpuWinitApp {
5950
pub fn new(event_loop: &EventLoop<UserEvent>) -> Self {
51+
let (buf, info) = read_icon();
52+
let icon = Icon::from_rgba(buf, info.width, info.height).unwrap();
6053
Self {
6154
repaint_proxy: Arc::new(Mutex::new(event_loop.create_proxy())),
6255
running: None,
56+
icon,
6357
}
6458
}
6559

@@ -76,7 +70,9 @@ impl WgpuWinitApp {
7670
width: 800,
7771
height: 600,
7872
})
73+
.with_window_icon(Some(self.icon.clone()))
7974
.build(&event_loop)?;
75+
8076
window.set_ime_allowed(true);
8177

8278
let mut painter =
@@ -122,7 +118,7 @@ impl WgpuWinitApp {
122118
egui_winit,
123119
});
124120

125-
Ok(NextPaint::RepaintNow)
121+
Ok(NextPaint::RepaintNext)
126122
}
127123

128124
pub fn frame_nr(&self) -> u64 {
@@ -191,27 +187,19 @@ impl WgpuWinitApp {
191187
Ok(match event {
192188
Event::Resumed if self.running.is_none() => self.launch_window(event_loop)?,
193189

190+
Event::UserEvent(UserEvent::RequestRepaint { when, frame_nr }) => {
191+
if self.frame_nr() == *frame_nr {
192+
NextPaint::RepaintAt(*when)
193+
} else {
194+
// old request - we've already repainted
195+
NextPaint::Wait
196+
}
197+
}
198+
194199
Event::WindowEvent { event, .. } => {
195200
if let Some(running) = &mut self.running {
196-
// On Windows, if a window is resized by the user, it should repaint synchronously, inside the
197-
// event handler.
198-
//
199-
// If this is not done, the compositor will assume that the window does not want to redraw,
200-
// and continue ahead.
201-
//
202-
// In eframe's case, that causes the window to rapidly flicker, as it struggles to deliver
203-
// new frames to the compositor in time.
204-
//
205-
// The flickering is technically glutin or glow's fault, but we should be responding properly
206-
// to resizes anyway, as doing so avoids dropping frames.
207-
//
208-
// See: https://github.com/emilk/egui/issues/903
209-
let mut repaint_asap = false;
210-
211201
match &event {
212202
WindowEvent::Resized(physical_size) => {
213-
repaint_asap = true;
214-
215203
// Resize with 0 width and height is used by winit to signal a minimize event on Windows.
216204
// See: https://github.com/rust-windowing/winit/issues/208
217205
// This solves an issue where the app would panic when minimizing on Windows.
@@ -222,7 +210,6 @@ impl WgpuWinitApp {
222210
}
223211
}
224212
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
225-
repaint_asap = true;
226213
running
227214
.painter
228215
.on_window_resized(new_inner_size.width, new_inner_size.height);
@@ -242,11 +229,7 @@ impl WgpuWinitApp {
242229
let event_response = running.egui_winit.on_event(&running.egui_ctx, event);
243230

244231
if event_response.repaint {
245-
if repaint_asap {
246-
NextPaint::RepaintNow
247-
} else {
248-
NextPaint::RepaintNext
249-
}
232+
NextPaint::RepaintNext
250233
} else {
251234
NextPaint::Wait
252235
}

app/src/main.rs

Lines changed: 27 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,19 @@ mod calculator;
44
mod common;
55
mod config;
66
mod gui;
7-
mod tray2;
7+
mod tray;
88
mod unique;
99

1010
use crate::common::{install_logger, APP_NAME};
1111
use crate::gui::{NextPaint, WgpuWinitApp};
1212
use crate::unique::SsbUniqueInstance;
1313
use egui_winit::winit;
1414
use log::LevelFilter;
15-
use std::time::{Duration, Instant};
15+
use std::time::Instant;
1616
use winit::event::Event;
1717
use winit::event_loop::EventLoopBuilder;
1818
use winit::platform::run_return::EventLoopExtRunReturn;
1919

20-
fn extremely_far_future() -> Instant {
21-
Instant::now() + Duration::from_secs(10_000_000_000)
22-
}
23-
2420
#[derive(Debug)]
2521
pub enum UserEvent {
2622
OpenWindow,
@@ -41,12 +37,12 @@ fn run() -> anyhow::Result<()> {
4137

4238
let mut event_loop = EventLoopBuilder::<UserEvent>::with_user_event().build();
4339

44-
let _tray = tray2::create(&event_loop)?;
40+
let _tray = tray::create(&event_loop)?;
4541

46-
let mut egui_app = WgpuWinitApp::new(&event_loop);
42+
let mut framework = WgpuWinitApp::new(&event_loop);
4743

4844
let mut returned_result = Ok(());
49-
let mut next_repaint_time = Instant::now();
45+
let mut next_repaint_time = Some(Instant::now());
5046

5147
event_loop.run_return(|event, event_loop, control_flow| {
5248
let event_result = match &event {
@@ -55,23 +51,13 @@ fn run() -> anyhow::Result<()> {
5551
// See: https://github.com/rust-windowing/winit/issues/1619
5652
#[cfg(target_os = "windows")]
5753
Event::RedrawEventsCleared => {
58-
next_repaint_time = extremely_far_future();
59-
Ok(egui_app.paint())
54+
next_repaint_time = None;
55+
Ok(framework.paint())
6056
}
6157
#[cfg(not(target_os = "windows"))]
6258
Event::RedrawRequested(_) => {
63-
next_repaint_time = extremely_far_future();
64-
Ok(egui_app.paint())
65-
}
66-
67-
Event::UserEvent(UserEvent::RequestRepaint { when, frame_nr }) => {
68-
Ok(if egui_app.frame_nr() == *frame_nr {
69-
log::trace!("UserEvent::RequestRepaint scheduling repaint at {when:?}");
70-
NextPaint::RepaintAt(*when)
71-
} else {
72-
log::trace!("Got outdated UserEvent::RequestRepaint");
73-
NextPaint::Wait // old request - we've already repainted
74-
})
59+
next_repaint_time = None;
60+
Ok(framework.paint())
7561
}
7662

7763
Event::UserEvent(UserEvent::Exit) => {
@@ -81,21 +67,16 @@ fn run() -> anyhow::Result<()> {
8167

8268
Event::UserEvent(UserEvent::OpenWindow) => {
8369
log::info!("Received OpenWindow action");
84-
if let Some(window) = egui_app.window() {
70+
if let Some(window) = framework.window() {
8571
window.set_minimized(false);
8672
window.focus_window();
8773
Ok(NextPaint::Wait)
8874
} else {
89-
egui_app.launch_window(event_loop)
75+
framework.launch_window(event_loop)
9076
}
9177
}
9278

93-
Event::NewEvents(winit::event::StartCause::ResumeTimeReached { .. }) => {
94-
log::trace!("Woke up to check next_repaint_time");
95-
Ok(NextPaint::Wait)
96-
}
97-
98-
event => egui_app.on_event(event_loop, event),
79+
event => framework.on_event(event_loop, event),
9980
};
10081

10182
match event_result {
@@ -106,41 +87,32 @@ fn run() -> anyhow::Result<()> {
10687
return;
10788
}
10889
Ok(NextPaint::Wait) => {}
109-
Ok(NextPaint::RepaintNow) => {
110-
log::trace!("Repaint caused by winit::Event: {:?}", event);
111-
if cfg!(target_os = "windows") {
112-
// Fix flickering on Windows, see https://github.com/emilk/egui/pull/2280
113-
next_repaint_time = extremely_far_future();
114-
egui_app.paint();
115-
} else {
116-
// Fix for https://github.com/emilk/egui/issues/2425
117-
next_repaint_time = Instant::now();
118-
}
119-
}
12090
Ok(NextPaint::RepaintNext) => {
121-
log::trace!("Repaint caused by winit::Event: {:?}", event);
122-
next_repaint_time = Instant::now();
91+
next_repaint_time = Some(Instant::now());
12392
}
12493
Ok(NextPaint::RepaintAt(repaint_time)) => {
125-
next_repaint_time = next_repaint_time.min(repaint_time);
94+
next_repaint_time =
95+
Some(next_repaint_time.unwrap_or(repaint_time).min(repaint_time));
12696
}
12797
Ok(NextPaint::Exit) => {
128-
log::debug!("Asking to exit event loop…");
12998
control_flow.set_exit();
13099
return;
131100
}
132101
}
133102

134-
if next_repaint_time <= Instant::now() {
135-
if let Some(window) = egui_app.window() {
136-
log::trace!("request_redraw");
137-
window.request_redraw();
138-
}
139-
next_repaint_time = extremely_far_future();
140-
control_flow.set_poll();
103+
if let Some(time) = next_repaint_time {
104+
if time <= Instant::now() {
105+
if let Some(window) = framework.window() {
106+
window.request_redraw();
107+
}
108+
next_repaint_time = None;
109+
control_flow.set_poll();
110+
} else {
111+
control_flow.set_wait_until(time);
112+
};
141113
} else {
142-
control_flow.set_wait_until(next_repaint_time);
143-
};
114+
control_flow.set_wait();
115+
}
144116
});
145117

146118
return returned_result;
@@ -172,25 +144,6 @@ fn main() {
172144
}
173145
}
174146

175-
// fn launch() -> i32 {
176-
// init_logger();
177-
// match unique::acquire() {
178-
// Ok(lock) => {
179-
// let config = SsbConfig::load().ok().unwrap_or_default();
180-
// let controller = Arc::new(BrightnessController::new(config));
181-
// controller.start();
182-
// tray::run_tray_application(controller, lock, true);
183-
// log::info!("Program exiting gracefully");
184-
// EXIT_SUCCESS
185-
// }
186-
// Err(e) => {
187-
// log::error!("Failed to acquire unique - the application is already running");
188-
// e.show_console_in_owning_process();
189-
// EXIT_FAILURE
190-
// }
191-
// }
192-
// }
193-
194147
#[cfg(not(windows))]
195148
fn set_panic_hook() {}
196149

app/src/tray2.rs renamed to app/src/tray.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,17 @@ use tray_icon::{ClickType, Icon, TrayIcon, TrayIconBuilder, TrayIconEvent};
88
const MENU_ID_OPEN: &str = "OPEN";
99
const MENU_ID_EXIT: &str = "EXIT";
1010

11-
pub fn create(event_loop: &EventLoop<UserEvent>) -> anyhow::Result<TrayIcon> {
11+
pub fn read_icon() -> (Vec<u8>, png::OutputInfo) {
1212
let mut decoder = png::Decoder::new(include_bytes!("../../assets/icon-256.png").as_slice());
1313
decoder.set_transformations(png::Transformations::EXPAND);
1414
let mut reader = decoder.read_info().unwrap();
1515
let mut buf = vec![0u8; reader.output_buffer_size()];
1616
let info = reader.next_frame(&mut buf).unwrap();
17+
(buf, info)
18+
}
19+
20+
pub fn create(event_loop: &EventLoop<UserEvent>) -> anyhow::Result<TrayIcon> {
21+
let (buf, info) = read_icon();
1722
let icon = Icon::from_rgba(buf, info.width, info.height).unwrap();
1823

1924
let tray_loop = Arc::new(Mutex::new(event_loop.create_proxy()));

0 commit comments

Comments
 (0)