| 1 |
use std::cell::{Cell, RefCell}; |
| 2 |
use std::fmt::Debug; |
| 3 |
use std::io; |
| 4 |
use std::os::unix::io::AsRawFd; |
| 5 |
use std::rc::Rc; |
| 6 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 7 |
use std::sync::Arc; |
| 8 |
use std::time::{Duration, Instant}; |
| 9 |
|
| 10 |
use slotmap::SlotMap; |
| 11 |
|
| 12 |
use crate::sources::{Dispatcher, EventSource, Idle, IdleDispatcher}; |
| 13 |
use crate::{EventDispatcher, InsertError, Poll, PostAction, TokenFactory}; |
| 14 |
|
| 15 |
type IdleCallback<'i, Data> = Rc<RefCell<dyn IdleDispatcher<Data> + 'i>>; |
| 16 |
|
| 17 |
slotmap::new_key_type! { |
| 18 |
pub(crate) struct CalloopKey; |
| 19 |
} |
| 20 |
|
| 21 |
/// A token representing a registration in the [`EventLoop`]. |
| 22 |
/// |
| 23 |
/// This token is given to you by the [`EventLoop`] when an [`EventSource`] is inserted or |
| 24 |
/// a [`Dispatcher`] is registered. You can use it to [disable](LoopHandle#method.disable), |
| 25 |
/// [enable](LoopHandle#method.enable), [update`](LoopHandle#method.update), |
| 26 |
/// [remove](LoopHandle#method.remove) or [kill](LoopHandle#method.kill) it. |
| 27 |
#[derive(Debug, PartialEq, Clone, Copy)] |
| 28 |
pub struct RegistrationToken { |
| 29 |
key: CalloopKey, |
| 30 |
} |
| 31 |
|
| 32 |
pub(crate) struct LoopInner<'l, Data> { |
| 33 |
pub(crate) poll: RefCell<Poll>, |
| 34 |
pub(crate) sources: RefCell<SlotMap<CalloopKey, Rc<dyn EventDispatcher<Data> + 'l>>>, |
| 35 |
idles: RefCell<Vec<IdleCallback<'l, Data>>>, |
| 36 |
pending_action: Cell<PostAction>, |
| 37 |
} |
| 38 |
|
| 39 |
/// An handle to an event loop |
| 40 |
/// |
| 41 |
/// This handle allows you to insert new sources and idles in this event loop, |
| 42 |
/// it can be cloned, and it is possible to insert new sources from within a source |
| 43 |
/// callback. |
| 44 |
pub struct LoopHandle<'l, Data> { |
| 45 |
inner: Rc<LoopInner<'l, Data>>, |
| 46 |
} |
| 47 |
|
| 48 |
impl<'l, Data> std::fmt::Debug for LoopHandle<'l, Data> { |
| 49 |
#[cfg_attr(coverage, no_coverage)] |
| 50 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 51 |
f.write_str("LoopHandle { ... }") |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
impl<'l, Data> Clone for LoopHandle<'l, Data> { |
| 56 |
#[cfg_attr(coverage, no_coverage)] |
| 57 |
fn clone(&self) -> Self { |
| 58 |
LoopHandle { |
| 59 |
inner: self.inner.clone(), |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
impl<'l, Data> LoopHandle<'l, Data> { |
| 65 |
/// Inserts a new event source in the loop. |
| 66 |
/// |
| 67 |
/// The provided callback will be called during the dispatching cycles whenever the |
| 68 |
/// associated source generates events, see `EventLoop::dispatch(..)` for details. |
| 69 |
/// |
| 70 |
/// This function takes ownership of the event source. Use `register_dispatcher` |
| 71 |
/// if you need access to the event source after this call. |
| 72 |
pub fn insert_source<S, F>( |
| 73 |
&self, |
| 74 |
source: S, |
| 75 |
callback: F, |
| 76 |
) -> Result<RegistrationToken, InsertError<S>> |
| 77 |
where |
| 78 |
S: EventSource + 'l, |
| 79 |
F: FnMut(S::Event, &mut S::Metadata, &mut Data) -> S::Ret + 'l, |
| 80 |
{ |
| 81 |
let dispatcher = Dispatcher::new(source, callback); |
| 82 |
self.register_dispatcher(dispatcher.clone()) |
| 83 |
.map_err(|error| InsertError { |
| 84 |
error, |
| 85 |
inserted: dispatcher.into_source_inner(), |
| 86 |
}) |
| 87 |
} |
| 88 |
|
| 89 |
/// Registers a `Dispatcher` in the loop. |
| 90 |
/// |
| 91 |
/// Use this function if you need access to the event source after its insertion in the loop. |
| 92 |
/// |
| 93 |
/// See also `insert_source`. |
| 94 |
pub fn register_dispatcher<S>( |
| 95 |
&self, |
| 96 |
dispatcher: Dispatcher<'l, S, Data>, |
| 97 |
) -> crate::Result<RegistrationToken> |
| 98 |
where |
| 99 |
S: EventSource + 'l, |
| 100 |
{ |
| 101 |
let mut sources = self.inner.sources.borrow_mut(); |
| 102 |
let mut poll = self.inner.poll.borrow_mut(); |
| 103 |
|
| 104 |
let key = sources.insert(dispatcher.clone_as_event_dispatcher()); |
| 105 |
let ret = sources |
| 106 |
.get(key) |
| 107 |
.unwrap() |
| 108 |
.register(&mut *poll, &mut TokenFactory::new(key)); |
| 109 |
|
| 110 |
if let Err(error) = ret { |
| 111 |
sources.remove(key).expect("Source was just inserted?!"); |
| 112 |
return Err(error); |
| 113 |
} |
| 114 |
|
| 115 |
Ok(RegistrationToken { key }) |
| 116 |
} |
| 117 |
|
| 118 |
/// Inserts an idle callback. |
| 119 |
/// |
| 120 |
/// This callback will be called during a dispatching cycle when the event loop has |
| 121 |
/// finished processing all pending events from the sources and becomes idle. |
| 122 |
pub fn insert_idle<'i, F: FnOnce(&mut Data) + 'l + 'i>(&self, callback: F) -> Idle<'i> { |
| 123 |
let mut opt_cb = Some(callback); |
| 124 |
let callback = Rc::new(RefCell::new(Some(move |data: &mut Data| { |
| 125 |
if let Some(cb) = opt_cb.take() { |
| 126 |
cb(data); |
| 127 |
} |
| 128 |
}))); |
| 129 |
self.inner.idles.borrow_mut().push(callback.clone()); |
| 130 |
Idle { callback } |
| 131 |
} |
| 132 |
|
| 133 |
/// Enables this previously disabled event source. |
| 134 |
/// |
| 135 |
/// This previously disabled source will start generating events again. |
| 136 |
/// |
| 137 |
/// **Note:** this cannot be done from within the source callback. |
| 138 |
pub fn enable(&self, token: &RegistrationToken) -> crate::Result<()> { |
| 139 |
if let Some(source) = self.inner.sources.borrow().get(token.key) { |
| 140 |
source.register( |
| 141 |
&mut *self.inner.poll.borrow_mut(), |
| 142 |
&mut TokenFactory::new(token.key), |
| 143 |
)?; |
| 144 |
} |
| 145 |
Ok(()) |
| 146 |
} |
| 147 |
|
| 148 |
/// Makes this source update its registration. |
| 149 |
/// |
| 150 |
/// If after accessing the source you changed its parameters in a way that requires |
| 151 |
/// updating its registration. |
| 152 |
pub fn update(&self, token: &RegistrationToken) -> crate::Result<()> { |
| 153 |
if let Some(source) = self.inner.sources.borrow().get(token.key) { |
| 154 |
if !source.reregister( |
| 155 |
&mut *self.inner.poll.borrow_mut(), |
| 156 |
&mut TokenFactory::new(token.key), |
| 157 |
)? { |
| 158 |
// we are in a callback, store for later processing |
| 159 |
self.inner.pending_action.set(PostAction::Reregister); |
| 160 |
} |
| 161 |
} |
| 162 |
Ok(()) |
| 163 |
} |
| 164 |
|
| 165 |
/// Disables this event source. |
| 166 |
/// |
| 167 |
/// The source remains in the event loop, but it'll no longer generate events |
| 168 |
pub fn disable(&self, token: &RegistrationToken) -> crate::Result<()> { |
| 169 |
if let Some(source) = self.inner.sources.borrow().get(token.key) { |
| 170 |
if !source.unregister(&mut *self.inner.poll.borrow_mut())? { |
| 171 |
// we are in a callback, store for later processing |
| 172 |
self.inner.pending_action.set(PostAction::Disable); |
| 173 |
} |
| 174 |
} |
| 175 |
Ok(()) |
| 176 |
} |
| 177 |
|
| 178 |
/// Removes this source from the event loop. |
| 179 |
pub fn remove(&self, token: RegistrationToken) { |
| 180 |
if let Some(source) = self.inner.sources.borrow_mut().remove(token.key) { |
| 181 |
if let Err(e) = source.unregister(&mut self.inner.poll.borrow_mut()) { |
| 182 |
log::warn!( |
| 183 |
"[calloop] Failed to unregister source from the polling system: {:?}", |
| 184 |
e |
| 185 |
); |
| 186 |
} |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
/// Wrap an IO object into an async adapter |
| 191 |
/// |
| 192 |
/// This adapter turns the IO object into an async-aware one that can be used in futures. |
| 193 |
/// The readiness of these futures will be driven by the event loop. |
| 194 |
/// |
| 195 |
/// The produced futures can be polled in any executor, and notably the one provided by |
| 196 |
/// calloop. |
| 197 |
pub fn adapt_io<F: AsRawFd>(&self, fd: F) -> crate::Result<crate::io::Async<'l, F>> { |
| 198 |
crate::io::Async::new(self.inner.clone(), fd) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
/// An event loop |
| 203 |
/// |
| 204 |
/// This loop can host several event sources, that can be dynamically added or removed. |
| 205 |
pub struct EventLoop<'l, Data> { |
| 206 |
handle: LoopHandle<'l, Data>, |
| 207 |
stop_signal: Arc<AtomicBool>, |
| 208 |
ping: crate::sources::ping::Ping, |
| 209 |
} |
| 210 |
|
| 211 |
impl<'l, Data> std::fmt::Debug for EventLoop<'l, Data> { |
| 212 |
#[cfg_attr(coverage, no_coverage)] |
| 213 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 214 |
f.write_str("EventLoop { ... }") |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
impl<'l, Data> EventLoop<'l, Data> { |
| 219 |
/// Create a new event loop |
| 220 |
/// |
| 221 |
/// Fails if the initialization of the polling system failed. |
| 222 |
pub fn try_new() -> crate::Result<Self> { |
| 223 |
Self::inner_new(false) |
| 224 |
} |
| 225 |
|
| 226 |
/// Create a new event loop in high precision mode |
| 227 |
/// |
| 228 |
/// On some platforms it requires to setup more resources to enable high-precision |
| 229 |
/// (sub millisecond) capabilities, so you should use this constructor if you need |
| 230 |
/// this kind of precision. |
| 231 |
/// |
| 232 |
/// Fails if the initialization of the polling system failed. |
| 233 |
pub fn try_new_high_precision() -> crate::Result<Self> { |
| 234 |
Self::inner_new(true) |
| 235 |
} |
| 236 |
|
| 237 |
fn inner_new(high_precision: bool) -> crate::Result<Self> { |
| 238 |
let poll = Poll::new(high_precision)?; |
| 239 |
let handle = LoopHandle { |
| 240 |
inner: Rc::new(LoopInner { |
| 241 |
poll: RefCell::new(poll), |
| 242 |
sources: RefCell::new(SlotMap::with_key()), |
| 243 |
idles: RefCell::new(Vec::new()), |
| 244 |
pending_action: Cell::new(PostAction::Continue), |
| 245 |
}), |
| 246 |
}; |
| 247 |
let (ping, ping_source) = crate::sources::ping::make_ping()?; |
| 248 |
handle.insert_source(ping_source, |_, _, _| {})?; |
| 249 |
Ok(EventLoop { |
| 250 |
handle, |
| 251 |
stop_signal: Arc::new(AtomicBool::new(false)), |
| 252 |
ping, |
| 253 |
}) |
| 254 |
} |
| 255 |
|
| 256 |
/// Retrieve a loop handle |
| 257 |
pub fn handle(&self) -> LoopHandle<'l, Data> { |
| 258 |
self.handle.clone() |
| 259 |
} |
| 260 |
|
| 261 |
fn dispatch_events( |
| 262 |
&mut self, |
| 263 |
mut timeout: Option<Duration>, |
| 264 |
data: &mut Data, |
| 265 |
) -> crate::Result<()> { |
| 266 |
let now = Instant::now(); |
| 267 |
let events = { |
| 268 |
let mut poll = self.handle.inner.poll.borrow_mut(); |
| 269 |
loop { |
| 270 |
let result = poll.poll(timeout); |
| 271 |
|
| 272 |
match result { |
| 273 |
Ok(events) => break events, |
| 274 |
Err(crate::Error::IoError(err)) if err.kind() == io::ErrorKind::Interrupted => { |
| 275 |
// Interrupted by a signal. Update timeout and retry. |
| 276 |
if let Some(to) = timeout { |
| 277 |
let elapsed = now.elapsed(); |
| 278 |
if elapsed >= to { |
| 279 |
return Ok(()); |
| 280 |
} else { |
| 281 |
timeout = Some(to - elapsed); |
| 282 |
} |
| 283 |
} |
| 284 |
} |
| 285 |
Err(err) => return Err(err), |
| 286 |
}; |
| 287 |
} |
| 288 |
}; |
| 289 |
|
| 290 |
for event in events { |
| 291 |
let opt_disp = self |
| 292 |
.handle |
| 293 |
.inner |
| 294 |
.sources |
| 295 |
.borrow() |
| 296 |
.get(event.token.key) |
| 297 |
.cloned(); |
| 298 |
|
| 299 |
if let Some(disp) = opt_disp { |
| 300 |
let mut ret = disp.process_events(event.readiness, event.token, data)?; |
| 301 |
|
| 302 |
// if the returned PostAction is Continue, it may be overwritten by an user-specified pending action |
| 303 |
let pending_action = self |
| 304 |
.handle |
| 305 |
.inner |
| 306 |
.pending_action |
| 307 |
.replace(PostAction::Continue); |
| 308 |
if let PostAction::Continue = ret { |
| 309 |
ret = pending_action; |
| 310 |
} |
| 311 |
|
| 312 |
match ret { |
| 313 |
PostAction::Reregister => { |
| 314 |
disp.reregister( |
| 315 |
&mut self.handle.inner.poll.borrow_mut(), |
| 316 |
&mut TokenFactory::new(event.token.key), |
| 317 |
)?; |
| 318 |
} |
| 319 |
PostAction::Disable => { |
| 320 |
disp.unregister(&mut self.handle.inner.poll.borrow_mut())?; |
| 321 |
} |
| 322 |
PostAction::Remove => { |
| 323 |
// delete the source from the list, it'll be cleaned up with the if just below |
| 324 |
self.handle |
| 325 |
.inner |
| 326 |
.sources |
| 327 |
.borrow_mut() |
| 328 |
.remove(event.token.key); |
| 329 |
} |
| 330 |
PostAction::Continue => {} |
| 331 |
} |
| 332 |
|
| 333 |
if !self |
| 334 |
.handle |
| 335 |
.inner |
| 336 |
.sources |
| 337 |
.borrow() |
| 338 |
.contains_key(event.token.key) |
| 339 |
{ |
| 340 |
// the source has been removed from within its callback, unregister it |
| 341 |
let mut poll = self.handle.inner.poll.borrow_mut(); |
| 342 |
if let Err(e) = disp.unregister(&mut *poll) { |
| 343 |
log::warn!( |
| 344 |
"[calloop] Failed to unregister source from the polling system: {:?}", |
| 345 |
e |
| 346 |
); |
| 347 |
} |
| 348 |
} |
| 349 |
} else { |
| 350 |
log::warn!( |
| 351 |
"[calloop] Received an event for non-existence source: {:?}", |
| 352 |
event.token.key |
| 353 |
); |
| 354 |
} |
| 355 |
} |
| 356 |
|
| 357 |
Ok(()) |
| 358 |
} |
| 359 |
|
| 360 |
fn dispatch_idles(&mut self, data: &mut Data) { |
| 361 |
let idles = std::mem::take(&mut *self.handle.inner.idles.borrow_mut()); |
| 362 |
for idle in idles { |
| 363 |
idle.borrow_mut().dispatch(data); |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
fn invoke_pre_run(&self, data: &mut Data) -> crate::Result<()> { |
| 368 |
let sources = self |
| 369 |
.handle |
| 370 |
.inner |
| 371 |
.sources |
| 372 |
.borrow() |
| 373 |
.values() |
| 374 |
.cloned() |
| 375 |
.collect::<Vec<_>>(); |
| 376 |
|
| 377 |
for source in sources { |
| 378 |
source.pre_run(data)?; |
| 379 |
} |
| 380 |
|
| 381 |
Ok(()) |
| 382 |
} |
| 383 |
|
| 384 |
fn invoke_post_run(&self, data: &mut Data) -> crate::Result<()> { |
| 385 |
let sources = self |
| 386 |
.handle |
| 387 |
.inner |
| 388 |
.sources |
| 389 |
.borrow() |
| 390 |
.values() |
| 391 |
.cloned() |
| 392 |
.collect::<Vec<_>>(); |
| 393 |
|
| 394 |
for source in sources { |
| 395 |
source.post_run(data)?; |
| 396 |
} |
| 397 |
|
| 398 |
Ok(()) |
| 399 |
} |
| 400 |
|
| 401 |
/// Dispatch pending events to their callbacks |
| 402 |
/// |
| 403 |
/// If some sources have events available, their callbacks will be immediatly called. |
| 404 |
/// Otherwise this will wait until an event is receive or the provided `timeout` |
| 405 |
/// is reached. If `timeout` is `None`, it will wait without a duration limit. |
| 406 |
/// |
| 407 |
/// Once pending events have been processed or the timeout is reached, all pending |
| 408 |
/// idle callbacks will be fired before this method returns. |
| 409 |
pub fn dispatch<D: Into<Option<Duration>>>( |
| 410 |
&mut self, |
| 411 |
timeout: D, |
| 412 |
data: &mut Data, |
| 413 |
) -> crate::Result<()> { |
| 414 |
self.invoke_pre_run(data)?; |
| 415 |
self.dispatch_events(timeout.into(), data)?; |
| 416 |
self.dispatch_idles(data); |
| 417 |
self.invoke_post_run(data)?; |
| 418 |
|
| 419 |
Ok(()) |
| 420 |
} |
| 421 |
|
| 422 |
/// Get a signal to stop this event loop from running |
| 423 |
/// |
| 424 |
/// To be used in conjunction with the `run()` method. |
| 425 |
pub fn get_signal(&self) -> LoopSignal { |
| 426 |
LoopSignal { |
| 427 |
signal: self.stop_signal.clone(), |
| 428 |
ping: self.ping.clone(), |
| 429 |
} |
| 430 |
} |
| 431 |
|
| 432 |
/// Run this event loop |
| 433 |
/// |
| 434 |
/// This will repeatedly try to dispatch events (see the `dispatch()` method) on |
| 435 |
/// this event loop, waiting at most `timeout` every time. |
| 436 |
/// |
| 437 |
/// Between each dispatch wait, your provided callback will be called. |
| 438 |
/// |
| 439 |
/// You can use the `get_signal()` method to retrieve a way to stop or wakeup |
| 440 |
/// the event loop from anywhere. |
| 441 |
pub fn run<F, D: Into<Option<Duration>>>( |
| 442 |
&mut self, |
| 443 |
timeout: D, |
| 444 |
data: &mut Data, |
| 445 |
mut cb: F, |
| 446 |
) -> crate::Result<()> |
| 447 |
where |
| 448 |
F: FnMut(&mut Data), |
| 449 |
{ |
| 450 |
let timeout = timeout.into(); |
| 451 |
self.stop_signal.store(false, Ordering::Release); |
| 452 |
self.invoke_pre_run(data)?; |
| 453 |
while !self.stop_signal.load(Ordering::Acquire) { |
| 454 |
self.dispatch_events(timeout, data)?; |
| 455 |
self.dispatch_idles(data); |
| 456 |
cb(data); |
| 457 |
} |
| 458 |
self.invoke_post_run(data)?; |
| 459 |
Ok(()) |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
/// A signal that can be shared between thread to stop or wakeup a running |
| 464 |
/// event loop |
| 465 |
#[derive(Clone)] |
| 466 |
pub struct LoopSignal { |
| 467 |
signal: Arc<AtomicBool>, |
| 468 |
ping: crate::sources::ping::Ping, |
| 469 |
} |
| 470 |
|
| 471 |
impl std::fmt::Debug for LoopSignal { |
| 472 |
#[cfg_attr(coverage, no_coverage)] |
| 473 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 474 |
f.write_str("LoopSignal { ... }") |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
impl LoopSignal { |
| 479 |
/// Stop the event loop |
| 480 |
/// |
| 481 |
/// Once this method is called, the next time the event loop has finished |
| 482 |
/// waiting for events, it will return rather than starting to wait again. |
| 483 |
/// |
| 484 |
/// This is only usefull if you are using the `EventLoop::run()` method. |
| 485 |
pub fn stop(&self) { |
| 486 |
self.signal.store(true, Ordering::Release); |
| 487 |
} |
| 488 |
|
| 489 |
/// Wake up the event loop |
| 490 |
/// |
| 491 |
/// This sends a dummy event to the event loop to simulate the reception |
| 492 |
/// of an event, making the wait return early. Called after `stop()`, this |
| 493 |
/// ensures the event loop will terminate quickly if you specified a long |
| 494 |
/// timeout (or no timeout at all) to the `dispatch` or `run` method. |
| 495 |
pub fn wakeup(&self) { |
| 496 |
self.ping.ping(); |
| 497 |
} |
| 498 |
} |
| 499 |
|
| 500 |
#[cfg(test)] |
| 501 |
mod tests { |
| 502 |
use std::time::Duration; |
| 503 |
|
| 504 |
use crate::{ |
| 505 |
generic::Generic, ping::*, Dispatcher, Interest, Mode, Poll, PostAction, Readiness, |
| 506 |
RegistrationToken, Token, TokenFactory, |
| 507 |
}; |
| 508 |
|
| 509 |
use super::EventLoop; |
| 510 |
|
| 511 |
#[test] |
| 512 |
fn dispatch_idle() { |
| 513 |
let mut event_loop = EventLoop::try_new().unwrap(); |
| 514 |
|
| 515 |
let mut dispatched = false; |
| 516 |
|
| 517 |
event_loop.handle().insert_idle(|d| { |
| 518 |
*d = true; |
| 519 |
}); |
| 520 |
|
| 521 |
event_loop |
| 522 |
.dispatch(Some(Duration::ZERO), &mut dispatched) |
| 523 |
.unwrap(); |
| 524 |
|
| 525 |
assert!(dispatched); |
| 526 |
} |
| 527 |
|
| 528 |
#[test] |
| 529 |
fn cancel_idle() { |
| 530 |
let mut event_loop = EventLoop::try_new().unwrap(); |
| 531 |
|
| 532 |
let mut dispatched = false; |
| 533 |
|
| 534 |
let handle = event_loop.handle(); |
| 535 |
let idle = handle.insert_idle(move |d| { |
| 536 |
*d = true; |
| 537 |
}); |
| 538 |
|
| 539 |
idle.cancel(); |
| 540 |
|
| 541 |
event_loop |
| 542 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 543 |
.unwrap(); |
| 544 |
|
| 545 |
assert!(!dispatched); |
| 546 |
} |
| 547 |
|
| 548 |
#[test] |
| 549 |
fn wakeup() { |
| 550 |
let mut event_loop = EventLoop::try_new().unwrap(); |
| 551 |
|
| 552 |
let signal = event_loop.get_signal(); |
| 553 |
|
| 554 |
::std::thread::spawn(move || { |
| 555 |
::std::thread::sleep(Duration::from_millis(500)); |
| 556 |
signal.wakeup(); |
| 557 |
}); |
| 558 |
|
| 559 |
// the test should return |
| 560 |
event_loop.dispatch(None, &mut ()).unwrap(); |
| 561 |
} |
| 562 |
|
| 563 |
#[test] |
| 564 |
fn wakeup_stop() { |
| 565 |
let mut event_loop = EventLoop::try_new().unwrap(); |
| 566 |
|
| 567 |
let signal = event_loop.get_signal(); |
| 568 |
|
| 569 |
::std::thread::spawn(move || { |
| 570 |
::std::thread::sleep(Duration::from_millis(500)); |
| 571 |
signal.stop(); |
| 572 |
signal.wakeup(); |
| 573 |
}); |
| 574 |
|
| 575 |
// the test should return |
| 576 |
event_loop.run(None, &mut (), |_| {}).unwrap(); |
| 577 |
} |
| 578 |
|
| 579 |
#[test] |
| 580 |
fn insert_bad_source() { |
| 581 |
let event_loop = EventLoop::<()>::try_new().unwrap(); |
| 582 |
let ret = event_loop.handle().insert_source( |
| 583 |
crate::sources::generic::Generic::new(420, Interest::READ, Mode::Level), |
| 584 |
|_, _, _| Ok(PostAction::Continue), |
| 585 |
); |
| 586 |
assert!(ret.is_err()); |
| 587 |
} |
| 588 |
|
| 589 |
#[test] |
| 590 |
fn insert_source_no_interest() { |
| 591 |
let event_loop = EventLoop::<()>::try_new().unwrap(); |
| 592 |
let ret = event_loop.handle().insert_source( |
| 593 |
crate::sources::generic::Generic::new(0, Interest::EMPTY, Mode::Level), |
| 594 |
|_, _, _| Ok(PostAction::Continue), |
| 595 |
); |
| 596 |
assert!(ret.is_ok()); |
| 597 |
} |
| 598 |
|
| 599 |
#[test] |
| 600 |
fn disarm_rearm() { |
| 601 |
let mut event_loop = EventLoop::<bool>::try_new().unwrap(); |
| 602 |
let (ping, ping_source) = make_ping().unwrap(); |
| 603 |
|
| 604 |
let ping_token = event_loop |
| 605 |
.handle() |
| 606 |
.insert_source(ping_source, |(), &mut (), dispatched| { |
| 607 |
*dispatched = true; |
| 608 |
}) |
| 609 |
.unwrap(); |
| 610 |
|
| 611 |
ping.ping(); |
| 612 |
let mut dispatched = false; |
| 613 |
event_loop |
| 614 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 615 |
.unwrap(); |
| 616 |
assert!(dispatched); |
| 617 |
|
| 618 |
// disable the source |
| 619 |
ping.ping(); |
| 620 |
event_loop.handle().disable(&ping_token).unwrap(); |
| 621 |
let mut dispatched = false; |
| 622 |
event_loop |
| 623 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 624 |
.unwrap(); |
| 625 |
assert!(!dispatched); |
| 626 |
|
| 627 |
// disabling it again is an error |
| 628 |
event_loop.handle().disable(&ping_token).unwrap_err(); |
| 629 |
|
| 630 |
// reenable it, the previous ping now gets dispatched |
| 631 |
event_loop.handle().enable(&ping_token).unwrap(); |
| 632 |
let mut dispatched = false; |
| 633 |
event_loop |
| 634 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 635 |
.unwrap(); |
| 636 |
assert!(dispatched); |
| 637 |
} |
| 638 |
|
| 639 |
#[test] |
| 640 |
fn multiple_tokens() { |
| 641 |
struct DoubleSource { |
| 642 |
ping1: PingSource, |
| 643 |
ping2: PingSource, |
| 644 |
} |
| 645 |
|
| 646 |
impl crate::EventSource for DoubleSource { |
| 647 |
type Event = u32; |
| 648 |
type Metadata = (); |
| 649 |
type Ret = (); |
| 650 |
type Error = PingError; |
| 651 |
|
| 652 |
fn process_events<F>( |
| 653 |
&mut self, |
| 654 |
readiness: Readiness, |
| 655 |
token: Token, |
| 656 |
mut callback: F, |
| 657 |
) -> Result<PostAction, Self::Error> |
| 658 |
where |
| 659 |
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret, |
| 660 |
{ |
| 661 |
self.ping1 |
| 662 |
.process_events(readiness, token, |(), &mut ()| callback(1, &mut ()))?; |
| 663 |
self.ping2 |
| 664 |
.process_events(readiness, token, |(), &mut ()| callback(2, &mut ()))?; |
| 665 |
Ok(PostAction::Continue) |
| 666 |
} |
| 667 |
|
| 668 |
fn register( |
| 669 |
&mut self, |
| 670 |
poll: &mut Poll, |
| 671 |
token_factory: &mut TokenFactory, |
| 672 |
) -> crate::Result<()> { |
| 673 |
self.ping1.register(poll, token_factory)?; |
| 674 |
self.ping2.register(poll, token_factory)?; |
| 675 |
Ok(()) |
| 676 |
} |
| 677 |
|
| 678 |
fn reregister( |
| 679 |
&mut self, |
| 680 |
poll: &mut Poll, |
| 681 |
token_factory: &mut TokenFactory, |
| 682 |
) -> crate::Result<()> { |
| 683 |
self.ping1.reregister(poll, token_factory)?; |
| 684 |
self.ping2.reregister(poll, token_factory)?; |
| 685 |
Ok(()) |
| 686 |
} |
| 687 |
|
| 688 |
fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> { |
| 689 |
self.ping1.unregister(poll)?; |
| 690 |
self.ping2.unregister(poll)?; |
| 691 |
Ok(()) |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
let mut event_loop = EventLoop::<u32>::try_new().unwrap(); |
| 696 |
|
| 697 |
let (ping1, source1) = make_ping().unwrap(); |
| 698 |
let (ping2, source2) = make_ping().unwrap(); |
| 699 |
|
| 700 |
let source = DoubleSource { |
| 701 |
ping1: source1, |
| 702 |
ping2: source2, |
| 703 |
}; |
| 704 |
|
| 705 |
event_loop |
| 706 |
.handle() |
| 707 |
.insert_source(source, |i, _, d| { |
| 708 |
eprintln!("Dispatching {}", i); |
| 709 |
*d += i |
| 710 |
}) |
| 711 |
.unwrap(); |
| 712 |
|
| 713 |
let mut dispatched = 0; |
| 714 |
ping1.ping(); |
| 715 |
event_loop |
| 716 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 717 |
.unwrap(); |
| 718 |
assert_eq!(dispatched, 1); |
| 719 |
|
| 720 |
dispatched = 0; |
| 721 |
ping2.ping(); |
| 722 |
event_loop |
| 723 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 724 |
.unwrap(); |
| 725 |
assert_eq!(dispatched, 2); |
| 726 |
|
| 727 |
dispatched = 0; |
| 728 |
ping1.ping(); |
| 729 |
ping2.ping(); |
| 730 |
event_loop |
| 731 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 732 |
.unwrap(); |
| 733 |
assert_eq!(dispatched, 3); |
| 734 |
} |
| 735 |
|
| 736 |
#[test] |
| 737 |
fn change_interests() { |
| 738 |
use nix::sys::socket::{recv, socketpair, AddressFamily, MsgFlags, SockFlag, SockType}; |
| 739 |
use nix::unistd::write; |
| 740 |
let mut event_loop = EventLoop::<bool>::try_new().unwrap(); |
| 741 |
|
| 742 |
let (sock1, sock2) = socketpair( |
| 743 |
AddressFamily::Unix, |
| 744 |
SockType::Stream, |
| 745 |
None, |
| 746 |
SockFlag::empty(), // recv with DONTWAIT will suffice for platforms without SockFlag::SOCK_NONBLOCKING such as macOS |
| 747 |
) |
| 748 |
.unwrap(); |
| 749 |
|
| 750 |
let source = Generic::new(sock1, Interest::READ, Mode::Level); |
| 751 |
let dispatcher = Dispatcher::new(source, |_, &mut fd, dispatched| { |
| 752 |
*dispatched = true; |
| 753 |
// read all contents available to drain the socket |
| 754 |
let mut buf = [0u8; 32]; |
| 755 |
loop { |
| 756 |
match recv(fd, &mut buf, MsgFlags::MSG_DONTWAIT) { |
| 757 |
Ok(0) => break, // closed pipe, we are now inert |
| 758 |
Ok(_) => {} |
| 759 |
Err(e) => { |
| 760 |
let e: std::io::Error = e.into(); |
| 761 |
if e.kind() == std::io::ErrorKind::WouldBlock { |
| 762 |
break; |
| 763 |
// nothing more to read |
| 764 |
} else { |
| 765 |
// propagate error |
| 766 |
return Err(e); |
| 767 |
} |
| 768 |
} |
| 769 |
} |
| 770 |
} |
| 771 |
Ok(PostAction::Continue) |
| 772 |
}); |
| 773 |
|
| 774 |
let sock_token_1 = event_loop |
| 775 |
.handle() |
| 776 |
.register_dispatcher(dispatcher.clone()) |
| 777 |
.unwrap(); |
| 778 |
|
| 779 |
// first dispatch, nothing is readable |
| 780 |
let mut dispatched = false; |
| 781 |
event_loop |
| 782 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 783 |
.unwrap(); |
| 784 |
assert!(!dispatched); |
| 785 |
|
| 786 |
// write something, the socket becomes readable |
| 787 |
write(sock2, &[1, 2, 3]).unwrap(); |
| 788 |
dispatched = false; |
| 789 |
event_loop |
| 790 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 791 |
.unwrap(); |
| 792 |
assert!(dispatched); |
| 793 |
|
| 794 |
// All has been read, no longer readable |
| 795 |
dispatched = false; |
| 796 |
event_loop |
| 797 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 798 |
.unwrap(); |
| 799 |
assert!(!dispatched); |
| 800 |
|
| 801 |
// change the interests for writability instead |
| 802 |
dispatcher.as_source_mut().interest = Interest::WRITE; |
| 803 |
event_loop.handle().update(&sock_token_1).unwrap(); |
| 804 |
|
| 805 |
// the socket is writable |
| 806 |
dispatched = false; |
| 807 |
event_loop |
| 808 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 809 |
.unwrap(); |
| 810 |
assert!(dispatched); |
| 811 |
|
| 812 |
// change back to readable |
| 813 |
dispatcher.as_source_mut().interest = Interest::READ; |
| 814 |
event_loop.handle().update(&sock_token_1).unwrap(); |
| 815 |
|
| 816 |
// the socket is not readable |
| 817 |
dispatched = false; |
| 818 |
event_loop |
| 819 |
.dispatch(Duration::ZERO, &mut dispatched) |
| 820 |
.unwrap(); |
| 821 |
assert!(!dispatched); |
| 822 |
} |
| 823 |
|
| 824 |
#[test] |
| 825 |
fn kill_source() { |
| 826 |
let mut event_loop = EventLoop::<Option<RegistrationToken>>::try_new().unwrap(); |
| 827 |
|
| 828 |
let handle = event_loop.handle(); |
| 829 |
let (ping, ping_source) = make_ping().unwrap(); |
| 830 |
let ping_token = event_loop |
| 831 |
.handle() |
| 832 |
.insert_source(ping_source, move |(), &mut (), opt_src| { |
| 833 |
if let Some(src) = opt_src.take() { |
| 834 |
handle.remove(src); |
| 835 |
} |
| 836 |
}) |
| 837 |
.unwrap(); |
| 838 |
|
| 839 |
ping.ping(); |
| 840 |
|
| 841 |
let mut opt_src = Some(ping_token); |
| 842 |
|
| 843 |
event_loop.dispatch(Duration::ZERO, &mut opt_src).unwrap(); |
| 844 |
|
| 845 |
assert!(opt_src.is_none()); |
| 846 |
} |
| 847 |
|
| 848 |
#[test] |
| 849 |
fn non_static_data() { |
| 850 |
use std::sync::mpsc; |
| 851 |
|
| 852 |
let (sender, receiver) = mpsc::channel(); |
| 853 |
|
| 854 |
{ |
| 855 |
struct RefSender<'a>(&'a mpsc::Sender<()>); |
| 856 |
let mut ref_sender = RefSender(&sender); |
| 857 |
|
| 858 |
let mut event_loop = EventLoop::<RefSender<'_>>::try_new().unwrap(); |
| 859 |
let (ping, ping_source) = make_ping().unwrap(); |
| 860 |
let _ping_token = event_loop |
| 861 |
.handle() |
| 862 |
.insert_source(ping_source, |_, _, ref_sender| { |
| 863 |
ref_sender.0.send(()).unwrap(); |
| 864 |
}) |
| 865 |
.unwrap(); |
| 866 |
|
| 867 |
ping.ping(); |
| 868 |
|
| 869 |
event_loop |
| 870 |
.dispatch(Duration::ZERO, &mut ref_sender) |
| 871 |
.unwrap(); |
| 872 |
} |
| 873 |
|
| 874 |
receiver.recv().unwrap(); |
| 875 |
// sender still usable (e.g. for another EventLoop) |
| 876 |
drop(sender); |
| 877 |
} |
| 878 |
|
| 879 |
// A dummy EventSource to test insertion and removal of sources |
| 880 |
struct DummySource; |
| 881 |
|
| 882 |
impl crate::EventSource for DummySource { |
| 883 |
type Event = (); |
| 884 |
type Metadata = (); |
| 885 |
type Ret = (); |
| 886 |
type Error = crate::Error; |
| 887 |
|
| 888 |
fn process_events<F>( |
| 889 |
&mut self, |
| 890 |
_: Readiness, |
| 891 |
_: Token, |
| 892 |
mut callback: F, |
| 893 |
) -> Result<PostAction, Self::Error> |
| 894 |
where |
| 895 |
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret, |
| 896 |
{ |
| 897 |
callback((), &mut ()); |
| 898 |
Ok(PostAction::Continue) |
| 899 |
} |
| 900 |
|
| 901 |
fn register(&mut self, _: &mut Poll, _: &mut TokenFactory) -> crate::Result<()> { |
| 902 |
Ok(()) |
| 903 |
} |
| 904 |
|
| 905 |
fn reregister(&mut self, _: &mut Poll, _: &mut TokenFactory) -> crate::Result<()> { |
| 906 |
Ok(()) |
| 907 |
} |
| 908 |
|
| 909 |
fn unregister(&mut self, _: &mut Poll) -> crate::Result<()> { |
| 910 |
Ok(()) |
| 911 |
} |
| 912 |
} |
| 913 |
} |