From 086ab048fca69bd894d4073ff348b975aaafc0bd Mon Sep 17 00:00:00 2001 From: Stephen Seo Date: Tue, 14 Dec 2021 19:39:09 +0900 Subject: [PATCH] WIP Custom event_loop for forced low fps --- src/main.rs | 52 +++++++++++++++++++++++++++++++++++++++++++--- src/mpd_handler.rs | 10 ++++++++- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1312ee5..cbe84d0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,9 +2,12 @@ mod display; mod mpd_handler; use ggez::conf::{WindowMode, WindowSetup}; -use ggez::event; +use ggez::event::winit_event::KeyboardInput; +use ggez::event::{self, ControlFlow, EventHandler}; use ggez::ContextBuilder; use std::net::Ipv4Addr; +use std::thread; +use std::time::{Duration, Instant}; use structopt::StructOpt; #[derive(StructOpt, Debug)] @@ -41,7 +44,50 @@ fn main() -> Result<(), String> { .build() .expect("Failed to create ggez context"); - let display = display::MPDDisplay::new(&mut ctx, opt); + let mut display = display::MPDDisplay::new(&mut ctx, opt); - event::run(ctx, event_loop, display); + event_loop.run(move |mut event, _window_target, control_flow| { + if !ctx.continuing { + *control_flow = ControlFlow::Exit; + return; + } + + *control_flow = ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(100)); + + let ctx = &mut ctx; + + event::process_event(ctx, &mut event); + match event { + event::winit_event::Event::WindowEvent { event, .. } => match event { + event::winit_event::WindowEvent::CloseRequested => event::quit(ctx), + event::winit_event::WindowEvent::KeyboardInput { + device_id: _, + input: + KeyboardInput { + virtual_keycode: Some(keycode), + .. + }, + is_synthetic: _, + } => { + if let event::KeyCode::Escape = keycode { + *control_flow = ControlFlow::Exit; + } + } + x => println!("Other window event fired: {:?}", x), + }, + event::winit_event::Event::MainEventsCleared => { + ctx.timer_context.tick(); + + display.update(ctx).expect("Update failed"); + display.draw(ctx).expect("Draw failed"); + + ctx.mouse_context.reset_delta(); + + // sleep to force 10-11 fps + thread::sleep(Duration::from_millis(90)); + ggez::timer::yield_now(); + } + x => println!("Device event fired: {:?}", x), + } + }); } diff --git a/src/mpd_handler.rs b/src/mpd_handler.rs index 7369a8a..34ef9d8 100644 --- a/src/mpd_handler.rs +++ b/src/mpd_handler.rs @@ -58,7 +58,7 @@ pub struct MPDHandler { song_length_get_time: Instant, self_thread: Option>>>>, dirty_flag: Arc, - stop_flag: Arc, + pub stop_flag: Arc, } fn check_next_chars( @@ -314,6 +314,14 @@ impl MPDHandler { Err(()) } + pub fn is_dirty(h: Arc>) -> Result { + if let Ok(write_lock) = h.write() { + return Ok(write_lock.dirty_flag.swap(false, Ordering::Relaxed)); + } + + Err(()) + } + fn handler_loop(h: Arc>) -> Result<(), String> { let mut buf: [u8; BUF_SIZE] = [0; BUF_SIZE]; let mut saved: Vec = Vec::new();