From c9598b5adc7b8eefad83665427f3763d4dea7b10 Mon Sep 17 00:00:00 2001 From: Michael Zhang Date: Mon, 22 Mar 2021 18:15:23 -0500 Subject: [PATCH] switch to async event loop to not use busy waiting --- Cargo.lock | 1 + Cargo.toml | 2 +- src/ui/mod.rs | 17 +++++++++-------- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 66e6c76..7ced088 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -527,6 +527,7 @@ checksum = "7c36c10130df424b2f3552fcc2ddcd9b28a27b1e54b358b45874f88d1ca6888c" dependencies = [ "bitflags 1.2.1", "crossterm_winapi 0.7.0", + "futures-core", "lazy_static", "libc", "mio", diff --git a/Cargo.toml b/Cargo.toml index e8a55a9..3083462 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ async-trait = "0.1.48" cfg-if = "1.0.0" chrono = "0.4.19" chrono-humanize = "0.1.2" -crossterm = "0.19.0" +crossterm = { version = "0.19.0", features = ["event-stream"] } fern = { version = "0.6.0", features = ["colored"] } format-bytes = "0.2.2" futures = "0.3.13" diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 4a062ab..c51e17a 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -22,7 +22,7 @@ use anyhow::Result; use chrono::{Local, TimeZone}; use crossterm::{ cursor, - event::{self, Event, KeyCode, KeyEvent}, + event::{self, Event, KeyCode, KeyEvent, EventStream}, style, terminal, }; use downcast_rs::Downcast; @@ -63,6 +63,7 @@ pub async fn run_ui2( let backend = CrosstermBackend::new(&mut stdout); let mut term = Terminal::new(backend)?; + let mut ui_events = EventStream::new(); let should_exit = Arc::new(AtomicBool::new(false)); @@ -85,20 +86,20 @@ pub async fn run_ui2( ui.draw(f); })?; - // handle events coming from the UI - if event::poll(FRAME_DURATION)? { - let event = event::read()?; - ui.process_event(event)?; - } - select! { // got an event from the mail thread evt = mail2ui_rx.recv().fuse() => if let Some(evt) = evt { ui.process_mail_event(evt); }, + // got an event from the ui thread + evt = ui_events.next().fuse() => if let Some(evt) = evt { + let evt = evt?; + ui.process_event(evt)?; + } + // wait for approx 60fps - _ = time::sleep(FRAME_DURATION).fuse() => {}, + // _ = time::sleep(FRAME_DURATION).fuse() => {}, } }