1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//! Event sources related functionnality
//!
//! Different event sources can be registered to event loops additionnaly
//! to the wayland listening and clients sockets. This module contains types
//! associated with this functionnality, notably the `Source` type.
//!
//! See the methods of the `LoopToken` type for the methods used to create these
//! event sources.

use std::cell::RefCell;
use std::rc::Rc;
use std::io::Error as IoError;
use std::os::raw::{c_int, c_void};
use std::os::unix::io::RawFd;

#[cfg(feature = "native_lib")]
use wayland_sys::server::*;

use wayland_commons::Implementation;

/// A handle to an event source
///
/// This object is obtained as the result of methods on the `LoopToken`
/// object adding event sources to the event loop. And can be used to
/// interact with the event source afterwards, modifying (if applicable)
/// or destroying it.
///
/// Dropping this object will *not* remove the event source from the event
/// loop, you need to use the `remove()` method for that.
pub struct Source<E> {
    _e: ::std::marker::PhantomData<*const E>,
    #[cfg(feature = "native_lib")]
    ptr: *mut wl_event_source,
    #[cfg(feature = "native_lib")]
    data: *mut Box<Implementation<(), E>>,
}

impl<E> Source<E> {
    #[cfg(feature = "native_lib")]
    pub(crate) fn make(ptr: *mut wl_event_source, data: Box<Box<Implementation<(), E>>>) -> Source<E> {
        Source {
            _e: ::std::marker::PhantomData,
            ptr: ptr,
            data: Box::into_raw(data),
        }
    }

    /// Remove this event source from the event loop
    ///
    /// You are returned the implementation you provided
    /// for this event source at creation.
    pub fn remove(self) -> Box<Implementation<(), E>> {
        #[cfg(not(feature = "native_lib"))]
        {
            unimplemented!()
        }
        #[cfg(feature = "native_lib")]
        {
            unsafe {
                ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_event_source_remove, self.ptr);
                let data = Box::from_raw(self.data);
                *data
            }
        }
    }
}

// FD event source

bitflags!{
    /// Flags to register interest on a file descriptor
    pub struct FdInterest: u32 {
        /// Interest to be notified when the file descriptor is readable
        const READ  = 0x01;
        /// Interest to be notified when the file descriptor is writable
        const WRITE = 0x02;
    }
}

/// An event generated by an FD event source
pub enum FdEvent {
    /// The FD is ready to be acted upon
    Ready {
        /// The concerned FD
        fd: RawFd,
        /// Mask indicating if the FD is ready for reading or writing
        mask: FdInterest,
    },
    /// An error occured while polling the FD
    Error {
        /// The concerned FD
        fd: RawFd,
        /// The reported error
        error: IoError,
    },
}

impl Source<FdEvent> {
    /// Change the registered interest for this FD
    pub fn update_mask(&mut self, mask: FdInterest) {
        #[cfg(not(feature = "native_lib"))]
        {
            unimplemented!()
        }
        #[cfg(feature = "native_lib")]
        {
            unsafe {
                ffi_dispatch!(
                    WAYLAND_SERVER_HANDLE,
                    wl_event_source_fd_update,
                    self.ptr,
                    mask.bits()
                );
            }
        }
    }
}

pub(crate) unsafe extern "C" fn event_source_fd_dispatcher(fd: c_int, mask: u32, data: *mut c_void) -> c_int {
    // We don't need to worry about panic-safeness, because if there is a panic,
    // we'll abort the process, so no access to corrupted data is possible.
    let ret = ::std::panic::catch_unwind(move || {
        let implem = &mut *(data as *mut Box<Implementation<(), FdEvent>>);
        if mask & 0x08 > 0 {
            // EPOLLERR
            use nix::sys::socket;
            let err = match socket::getsockopt(fd, socket::sockopt::SocketError) {
                Ok(err) => err,
                Err(_) => {
                    // error while retrieving the error code ???
                    eprintln!(
                        "[wayland-server error] Error while retrieving error code on socket {}, aborting.",
                        fd
                    );
                    ::libc::abort();
                }
            };
            implem.receive(
                FdEvent::Error {
                    fd: fd,
                    error: IoError::from_raw_os_error(err),
                },
                (),
            );
        } else if mask & 0x04 > 0 {
            // EPOLLHUP
            implem.receive(
                FdEvent::Error {
                    fd: fd,
                    error: IoError::new(::std::io::ErrorKind::ConnectionAborted, ""),
                },
                (),
            );
        } else {
            let mut bits = FdInterest::empty();
            if mask & 0x02 > 0 {
                bits = bits | FdInterest::WRITE;
            }
            if mask & 0x01 > 0 {
                bits = bits | FdInterest::READ;
            }
            implem.receive(FdEvent::Ready { fd: fd, mask: bits }, ());
        }
    });
    match ret {
        Ok(()) => return 0, // all went well
        Err(_) => {
            // a panic occured
            eprintln!(
                "[wayland-server error] A handler for fd {} event source panicked, aborting.",
                fd
            );
            ::libc::abort();
        }
    }
}

// Timer event source

/// A timer generated event.
pub struct TimerEvent;

impl Source<TimerEvent> {
    /// Set the delay of this timer
    ///
    /// The callback will be called during the next dispatch of the
    /// event loop after this time (in milliseconds) is elapsed.
    ///
    /// Manually the delay to 0 stops the timer (the callback won't be
    /// called).
    pub fn set_delay_ms(&mut self, delay: i32) {
        unsafe {
            ffi_dispatch!(
                WAYLAND_SERVER_HANDLE,
                wl_event_source_timer_update,
                self.ptr,
                delay
            );
        }
    }
}

pub(crate) unsafe extern "C" fn event_source_timer_dispatcher(data: *mut c_void) -> c_int {
    // We don't need to worry about panic-safeness, because if there is a panic,
    // we'll abort the process, so no access to corrupted data is possible.
    let ret = ::std::panic::catch_unwind(move || {
        let implem = &mut *(data as *mut Box<Implementation<(), TimerEvent>>);
        implem.receive(TimerEvent, ());
    });
    match ret {
        Ok(()) => return 0, // all went well
        Err(_) => {
            // a panic occured
            eprintln!("[wayland-server error] A handler for a timer event source panicked, aborting.",);
            ::libc::abort();
        }
    }
}

// Signal event source

/// An event generated by an UNIX signal event source
///
/// Contains an enum indicating which signal was received.
pub struct SignalEvent(::nix::sys::signal::Signal);

pub(crate) unsafe extern "C" fn event_source_signal_dispatcher(signal: c_int, data: *mut c_void) -> c_int {
    // We don't need to worry about panic-safeness, because if there is a panic,
    // we'll abort the process, so no access to corrupted data is possible.
    let ret = ::std::panic::catch_unwind(move || {
        let implem = &mut *(data as *mut Box<Implementation<(), SignalEvent>>);
        let sig = match ::nix::sys::signal::Signal::from_c_int(signal) {
            Ok(sig) => sig,
            Err(_) => {
                // Actually, this cannot happen, as we cannot register an event source for
                // an unknown signal...
                eprintln!(
                    "[wayland-server error] Unknown signal in signal event source: {}, aborting.",
                    signal
                );
                ::libc::abort();
            }
        };
        implem.receive(SignalEvent(sig), ());
    });
    match ret {
        Ok(()) => return 0, // all went well
        Err(_) => {
            // a panic occured
            eprintln!("[wayland-server error] A handler for a timer event source panicked, aborting.",);
            ::libc::abort();
        }
    }
}

// Idle event source

/// Idle event source
///
/// A handle to an idle event source, see `LoopToken::add_idle_event_source()`.
///
/// Dropping this struct does not remove the event source,
/// use the `remove` method for that.
pub struct IdleSource {
    ptr: *mut wl_event_source,
    data: Rc<RefCell<(Box<Implementation<(), ()>>, bool)>>,
}

impl IdleSource {
    #[cfg(feature = "native_lib")]
    pub(crate) fn make(
        ptr: *mut wl_event_source,
        data: Rc<RefCell<(Box<Implementation<(), ()>>, bool)>>,
    ) -> IdleSource {
        IdleSource {
            ptr: ptr,
            data: data,
        }
    }

    /// Remove this event source from its event loop
    ///
    /// You retrieve the associated implementation. The event source
    /// is removed and if it hadn't been fired yet, it is cancelled.
    pub fn remove(self) -> Box<Implementation<(), ()>> {
        let dispatched = self.data.borrow().1;
        if !dispatched {
            unsafe {
                // unregister this event source
                ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_event_source_remove, self.ptr);
                // recreate the outstanding reference that was not consumed
                let _ = Rc::from_raw(&*self.data);
            }
        }
        // we are now the only oustanding reference
        let data = Rc::try_unwrap(self.data)
            .unwrap_or_else(|_| panic!("Idle Rc was not singly owned."))
            .into_inner();
        data.0
    }
}

pub(crate) unsafe extern "C" fn event_source_idle_dispatcher(data: *mut c_void) {
    // We don't need to worry about panic-safeness, because if there is a panic,
    // we'll abort the process, so no access to corrupted data is possible.
    let ret = ::std::panic::catch_unwind(move || {
        let data = &*(data as *mut RefCell<(Box<Implementation<(), ()>>, bool)>);
        let mut data = data.borrow_mut();
        data.0.receive((), ());
    });
    match ret {
        Ok(()) => {
            // all went well
            // free the refence to the idata, as this event source cannot be called again
            let data = Rc::from_raw(data as *mut RefCell<(Box<Implementation<(), ()>>, bool)>);
            // store that the dispatching occured
            data.borrow_mut().1 = true;
        }
        Err(_) => {
            // a panic occured
            eprintln!("[wayland-server error] A handler for a timer event source panicked, aborting.",);
            ::libc::abort();
        }
    }
}