Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Coroutines #412

Closed
wants to merge 25 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
78a85d6
Refactor Cocoa event handling
willglynn Jul 12, 2017
bf48df1
Add context::Context-based Cocoa event dispatching
willglynn Jul 16, 2017
278f13d
Add a runloop observer
willglynn Jul 16, 2017
f3d0958
Refactor the MacOS event loop
willglynn Jul 17, 2017
0f95f20
Switch to thread-local context storage
willglynn Jul 17, 2017
87b7e70
Remove unnecessary UserCallback struct
willglynn Jul 17, 2017
b464e5f
Add a timer to assist with waking the runloop
willglynn Jul 17, 2017
ed6a225
Small fixes
willglynn Jul 17, 2017
bf4dcb3
Context switch from enqueue_event() to get_event() directly
willglynn Jul 17, 2017
230e3f7
Spike: runloop refactor
willglynn Jul 18, 2017
b245574
Add a Runloop that runs in a coroutine
willglynn Jul 18, 2017
84e036f
Link enqueue_event() to Runloop::wake()
willglynn Jul 18, 2017
9b97567
Move receive_event_from_cocoa()/forward_event_to_cocoa() to nsevent
willglynn Jul 18, 2017
f777fa3
Hook up a runloop observer and a timer for the runloop coroutine
willglynn Jul 18, 2017
7d02e3d
Minor refactorings to better separate concerns
willglynn Jul 18, 2017
6253368
Ask Travis to test --features context too
willglynn Jul 18, 2017
cf4c6d6
The blocking runloop should wake itself by posting an event
willglynn Jul 23, 2017
9c4b2f8
Clean up unused functions
willglynn Jul 23, 2017
90559d6
Add wakeup latency tool
willglynn Jul 23, 2017
6b0cd65
Remove dead code and mark conditionally-dead code
willglynn Jul 23, 2017
cbe2be9
Replace runloop observer with dispatch
willglynn Aug 3, 2017
51c64f6
Replace the timer with dispatch after_ms()
willglynn Aug 3, 2017
0bb7811
Add doc comments
willglynn Aug 3, 2017
cb5df71
Avoid overlap in guard_against_lengthy_operations()
willglynn Aug 18, 2017
78c33ed
Merge branch 'master' into coroutines
sodiumjoe Feb 24, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ objc = "0.2"

[target.'cfg(target_os = "macos")'.dependencies]
objc = "0.2"
dispatch = "0.1"
context = { version = "2.0", optional = true }
cocoa = "0.14"
core-foundation = "0.5"
core-graphics = "0.13"
Expand Down
102 changes: 102 additions & 0 deletions examples/wakeup_latency.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
extern crate winit;

use std::thread;
use std::time::{Duration,Instant};
use std::sync::mpsc;
use std::collections::VecDeque;

enum Action {
WakeupSent(Instant),
AwakenedReceived(Instant),
}

fn calculate_latency(rx: mpsc::Receiver<Action>) {
thread::spawn(move || {
let mut wakeups_sent: VecDeque<Instant> = VecDeque::new();
let mut awakeneds_received: VecDeque<Instant> = VecDeque::new();

let mut latency_history: Vec<u64> = Vec::with_capacity(1000);

println!("wakeup() -> Event::Awakened latency (all times in µs)");
println!("mean\tmax\t99%\t95%\t50%\t5%\t1%\tmin");

while let Ok(action) = rx.recv() {
match action {
Action::WakeupSent(instant) => wakeups_sent.push_back(instant),
Action::AwakenedReceived(instant) => awakeneds_received.push_back(instant),
}

while wakeups_sent.len() > 0 && awakeneds_received.len() > 0 {
let sent = wakeups_sent.pop_front().unwrap();
let recvd = awakeneds_received.pop_front().unwrap();
if recvd > sent {
let latency = recvd.duration_since(sent);
let latency_us = latency.as_secs() * 1_000_000
+ (latency.subsec_nanos() / 1_000) as u64;
latency_history.push(latency_us);
}
}

if latency_history.len() > 300 {
latency_history.sort();

{
let mean = latency_history.iter()
.fold(0u64, |acc,&u| acc + u) / latency_history.len() as u64;
let max = latency_history.last().unwrap();
let pct99 = latency_history.get(latency_history.len() * 99 / 100).unwrap();
let pct95 = latency_history.get(latency_history.len() * 95 / 100).unwrap();
let pct50 = latency_history.get(latency_history.len() * 50 / 100).unwrap();
let pct5 = latency_history.get(latency_history.len() * 5 / 100).unwrap();
let pct1 = latency_history.get(latency_history.len() * 1 / 100).unwrap();
let min = latency_history.first().unwrap();
println!("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}", mean, max, pct99, pct95, pct50, pct5, pct1, min);
}

latency_history.clear();
}
}
});
}

fn send_wakeups(tx: mpsc::Sender<Action>, proxy: winit::EventsLoopProxy) {
thread::spawn(move || {
loop {
let sent_at = Instant::now();
proxy.wakeup().expect("wakeup");
tx.send(Action::WakeupSent(sent_at)).unwrap();

thread::sleep(Duration::from_secs(1) / 60);
}
});
}

fn main() {
let mut events_loop = winit::EventsLoop::new();

let _window = winit::WindowBuilder::new()
.with_title("A fantastic window!")
.build(&events_loop)
.unwrap();

let (tx,rx) = mpsc::channel::<Action>();

calculate_latency(rx);
send_wakeups(tx.clone(), events_loop.create_proxy());

events_loop.run_forever(|event| {
match event {
winit::Event::Awakened { .. } => {
// got awakened
tx.send(Action::AwakenedReceived(Instant::now())).unwrap();

winit::ControlFlow::Continue
}

winit::Event::WindowEvent { event: winit::WindowEvent::Closed, .. } => {
winit::ControlFlow::Break
},
_ => winit::ControlFlow::Continue,
}
});
}
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ extern crate cocoa;
extern crate core_foundation;
#[cfg(target_os = "macos")]
extern crate core_graphics;
#[cfg(target_os = "macos")]
extern crate dispatch;
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
extern crate x11_dl;
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
Expand All @@ -105,6 +107,9 @@ extern crate percent_encoding;
#[macro_use]
extern crate wayland_client;

#[cfg(feature="context")]
extern crate context;

pub use events::*;
pub use window::{AvailableMonitorsIter, MonitorId};

Expand Down
201 changes: 201 additions & 0 deletions src/platform/macos/events_loop/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
//! The MacOS event loop has a few components:
//!
//! `EventsLoop` is the user-facing object that encapsulates everything events related. It contains
//! a `Shared` object which keeps track of windows and contains an internal event queue. It also
//! contains a `Runloop` whose job is to interface with MacOS X, use the `nsevent` module to
//! translate Cocoa events into Winit events, and to deliver events to the `Shared` event queue.
//!
//! `Runloop` exposes three functions:
//!
//! * `Runloop::new(shared: Weak<Shared>) -> Runloop` to create a new `Runloop`
//! * `Runloop::work(&mut self, Timeout)` to drive the runloop either for one cycle or for the
//! specified `Timeout`, whichever comes first
//! * `Runloop::wake()` to wake up the runloop as quickly as possible
//!
//! There are two `Runloop` implementations: one which operates in a straighforward blocking manner,
//! and a second which runs in a coroutine.
//!
//! The coroutine-based runloop is necessary because Cocoa event processing can trigger internal
//! runloops, for example during a resize operation. The blocking `Runloop` cannot return from an
//! inner runloop even if it knows its timeout has expired, whereas the coroutine `Runloop` can
//! suspend itself from any configuration and return to the caller. For additional discussion, see
//! [tomaka/winit#219](https://github.com/tomaka/winit/issues/219#issuecomment-315830359).

use {ControlFlow, EventsLoopClosed};
use events::Event;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, Weak};
use super::window::{self, Window};

mod nsevent;

// Simple blocking runloop
#[cfg(not(feature="context"))]
mod runloop;

// Coroutine-based nonblocking runloop
#[cfg(feature="context")]
#[path="runloop_context.rs"]
mod runloop;

use self::runloop::Runloop;

pub struct EventsLoop {
pub shared: Arc<Shared>,
runloop: Runloop,
}

// State shared between the `EventsLoop` and its registered windows.
pub struct Shared {
pub windows: Mutex<Vec<Weak<Window>>>,

// A queue of events that are pending delivery to the library user.
pub pending_events: Mutex<VecDeque<Event>>,
}

impl Shared {
pub fn new() -> Self {
Shared {
windows: Mutex::new(Vec::new()),
pending_events: Mutex::new(VecDeque::new()),
}
}

// Enqueues the event for prompt delivery to the application.
pub fn enqueue_event(&self, event: Event) {
// Store the event
self.pending_events.lock().unwrap().push_back(event);

// Attempt to wake the runloop
Runloop::wake();
}

// Dequeues the first event, if any, from the queue.
fn dequeue_event(&self) -> Option<Event> {
self.pending_events.lock().unwrap().pop_front()
}

// Are there any events pending delivery?
#[allow(dead_code)]
fn has_queued_events(&self) -> bool {
!self.pending_events.lock().unwrap().is_empty()
}

// Removes the window with the given `Id` from the `windows` list.
//
// This is called when a window is either `Closed` or `Drop`ped.
pub fn find_and_remove_window(&self, id: super::window::Id) {
if let Ok(mut windows) = self.windows.lock() {
windows.retain(|w| match w.upgrade() {
Some(w) => w.id() != id,
None => true,
});
}
}
}

impl nsevent::WindowFinder for Shared {
fn find_window_by_id(&self, id: window::Id) -> Option<Arc<Window>> {
for window in self.windows.lock().unwrap().iter() {
if let Some(window) = window.upgrade() {
if window.id() == id {
return Some(window);
}
}
}

None
}
}

#[derive(Debug,Clone,Copy,Eq,PartialEq)]
pub enum Timeout {
Now,
Forever,
}

impl Timeout {
fn is_elapsed(&self) -> bool {
match self {
&Timeout::Now => true,
&Timeout::Forever => false,
}
}
}

impl EventsLoop {

pub fn new() -> Self {
let shared = Arc::new(Shared::new());
EventsLoop {
runloop: Runloop::new(Arc::downgrade(&shared)),
shared: shared,
}
}

// Attempt to get an Event by a specified timeout.
fn get_event(&mut self, timeout: Timeout) -> Option<Event> {
loop {
// Pop any queued events
// This is immediate, so no need to consider a timeout
if let Some(event) = self.shared.dequeue_event() {
return Some(event);
}

// Attempt to get more events from the runloop
self.runloop.work(timeout);

// Is our time up?
if timeout.is_elapsed() {
// Check the queue again before returning, just in case
return self.shared.dequeue_event();
}

// Loop around again
}
}

pub fn poll_events<F>(&mut self, mut callback: F)
where F: FnMut(Event),
{
// Return as many events as we can without blocking
while let Some(event) = self.get_event(Timeout::Now) {
callback(event);
}
}

pub fn run_forever<F>(&mut self, mut callback: F)
where F: FnMut(Event) -> ControlFlow
{
// Get events until we're told to stop
while let Some(event) = self.get_event(Timeout::Forever) {
// Send to the app
let control_flow = callback(event);

// Do what it says
match control_flow {
ControlFlow::Break => break,
ControlFlow::Continue => (),
}
}
}

pub fn create_proxy(&self) -> Proxy {
Proxy { shared: Arc::downgrade(&self.shared) }
}
}

pub struct Proxy {
shared: Weak<Shared>,
}

impl Proxy {
pub fn wakeup(&self) -> Result<(), EventsLoopClosed> {
if let Some(shared) = self.shared.upgrade() {
shared.enqueue_event(Event::Awakened);
Ok(())
} else {
Err(EventsLoopClosed)
}
}
}
Loading