event loop: Decouple event timeout from event type

This commit is contained in:
Dorota Czaplejewicz
2022-11-28 14:21:30 +00:00
parent 9c9f371f91
commit 23d6beee8e
2 changed files with 19 additions and 5 deletions

View File

@ -44,11 +44,15 @@ pub mod driver;
// and the loop parametrized over them. // and the loop parametrized over them.
use crate::main::Commands; use crate::main::Commands;
use crate::state; use crate::state;
use crate::state::Event;
use std::cmp; use std::cmp;
use std::time::{ Duration, Instant }; use std::time::{ Duration, Instant };
pub trait Event: Clone {
fn get_timeout_reached(&self) -> Option<Instant>;
}
/// This keeps the state of the tracker loop between iterations /// This keeps the state of the tracker loop between iterations
#[derive(Clone)] #[derive(Clone)]
struct State { struct State {
@ -75,7 +79,7 @@ impl State {
/// It returns the new state, and the message to send onwards. /// It returns the new state, and the message to send onwards.
fn handle_event( fn handle_event(
mut loop_state: State, mut loop_state: State,
event: Event, event: state::Event,
now: Instant, now: Instant,
) -> (State, Commands) { ) -> (State, Commands) {
// Calculate changes to send to the consumer, // Calculate changes to send to the consumer,
@ -93,8 +97,8 @@ fn handle_event(
.get_commands_to_reach(&new_outcome); .get_commands_to_reach(&new_outcome);
// Timeout events are special: they affect the scheduled timeout. // Timeout events are special: they affect the scheduled timeout.
loop_state.scheduled_wakeup = match event { loop_state.scheduled_wakeup = match event.get_timeout_reached() {
Event::TimeoutReached(when) => { Some(when) => {
if when > now { if when > now {
// Special handling for scheduled events coming in early. // Special handling for scheduled events coming in early.
// Wait at least 10 ms to avoid Zeno's paradox. // Wait at least 10 ms to avoid Zeno's paradox.
@ -112,7 +116,7 @@ fn handle_event(
None None
} }
}, },
_ => loop_state.scheduled_wakeup.clone(), None => loop_state.scheduled_wakeup.clone(),
}; };
// Reschedule timeout if the new state calls for it. // Reschedule timeout if the new state calls for it.

View File

@ -7,6 +7,7 @@
use crate::animation; use crate::animation;
use crate::debug; use crate::debug;
use crate::event_loop;
use crate::imservice::{ ContentHint, ContentPurpose }; use crate::imservice::{ ContentHint, ContentPurpose };
use crate::layout::ArrangementKind; use crate::layout::ArrangementKind;
use crate::main; use crate::main;
@ -80,6 +81,15 @@ pub enum Event {
TimeoutReached(Instant), TimeoutReached(Instant),
} }
impl event_loop::Event for Event {
fn get_timeout_reached(&self) -> Option<Instant> {
match self {
Self::TimeoutReached(when) => Some(*when),
_ => None,
}
}
}
impl From<InputMethod> for Event { impl From<InputMethod> for Event {
fn from(im: InputMethod) -> Self { fn from(im: InputMethod) -> Self {
Self::InputMethod(im) Self::InputMethod(im)