Files
ab_glyph_rasterizer
adler
adler32
andrew
bitflags
bytemuck
byteorder
calloop
cfg_if
color_quant
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
deflate
dlib
downcast_rs
draw_state
either
event_loop
float
fnv
gfx
gfx_core
gfx_device_gl
gfx_gl
gfx_graphics
gfx_texture
gif
gl
glutin
glutin_egl_sys
glutin_glx_sys
glutin_window
graphics
graphics_api_version
image
input
instant
interpolation
iovec
jpeg_decoder
lazy_static
lazycell
libc
libloading
lock_api
log
maybe_uninit
memchr
memmap2
memoffset
miniz_oxide
mio
mio_extras
net2
nix
nom
num_cpus
num_integer
num_iter
num_rational
num_traits
once_cell
osmesa_sys
owned_ttf_parser
parking_lot
parking_lot_core
percent_encoding
piston
piston_window
png
proc_macro2
quote
raw_window_handle
rayon
rayon_core
read_color
rusttype
same_file
scoped_threadpool
scoped_tls
scopeguard
serde
serde_derive
shader_version
shaders_graphics2d
colored
textured
textured_color
shared_library
slab
smallvec
smithay_client_toolkit
spin_sleep
syn
texture
tiff
ttf_parser
unicode_xid
vecmath
viewport
walkdir
wayland_client
wayland_commons
wayland_cursor
wayland_egl
wayland_protocols
wayland_sys
weezl
window
winit
x11_dl
xcursor
xdg
xml
  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
use std::io;

use calloop::{
    generic::{Fd, Generic},
    EventSource, InsertError, Interest, LoopHandle, Mode, Source,
};

use wayland_client::EventQueue;

/// An adapter to insert a Wayland `EventQueue` into a calloop event loop
///
/// This is a struct that implements `calloop::EventSource`. It generates an
/// event whenever events need to be dispatched. At this point your calloop callback
/// will be given access to the `EventQueue` and you should call `.dispatch_pending()`
/// and forward its return value, allowing you to handle orphan events as you prefer.
///
/// If you don't use orphan events, the `quick_insert` method will firectly
/// insert the source into a provided `LoopHandle` with an adapter which will panic
/// whenever an oprhan event is encountered.
pub struct WaylandSource {
    queue: EventQueue,
    fd: Generic<Fd>,
}

impl WaylandSource {
    /// Wrap an `EventQueue` as a `WaylandSource`.
    pub fn new(queue: EventQueue) -> WaylandSource {
        let fd = queue.display().get_connection_fd();
        WaylandSource { queue, fd: Generic::from_fd(fd, Interest::Readable, Mode::Level) }
    }

    /// Insert this source into given event loop with an adapter that panics on orphan events
    pub fn quick_insert<Data: 'static>(
        self,
        handle: LoopHandle<Data>,
    ) -> Result<Source<WaylandSource>, InsertError<WaylandSource>> {
        handle.insert_source(self, |(), queue, ddata| {
            queue.dispatch_pending(ddata, |event, object, _| {
                panic!(
                    "[calloop] Encountered an orphan event: {}@{} : {}",
                    event.interface,
                    object.as_ref().id(),
                    event.name
                );
            })
        })
    }

    /// Access the underlying event queue
    ///
    /// This method can be used if you need to access the underlying `EventQueue` while this
    /// `WaylandSource` is currently inserted in an event loop.
    ///
    /// Note that you should be careful when interacting with it if you invoke methods that
    /// interact with the wayland socket (such as `dispatch()` or `prepare_read()`). These may
    /// interefere with the proper waking up of this event source in the event loop.
    pub fn queue(&mut self) -> &mut EventQueue {
        &mut self.queue
    }
}

impl EventSource for WaylandSource {
    type Event = ();
    type Metadata = EventQueue;
    type Ret = std::io::Result<u32>;

    fn process_events<F>(
        &mut self,
        _: calloop::Readiness,
        _: calloop::Token,
        mut callback: F,
    ) -> std::io::Result<()>
    where
        F: FnMut((), &mut EventQueue) -> std::io::Result<u32>,
    {
        // in case of readiness of the wayland socket we do the following in a loop, until nothing
        // more can be read:
        loop {
            // 1. read events from the socket if any are available
            if let Some(guard) = self.queue.prepare_read() {
                // might be None if some other thread read events before us, concurently
                if let Err(e) = guard.read_events() {
                    if e.kind() != io::ErrorKind::WouldBlock {
                        return Err(e);
                    }
                }
            }
            // 2. dispatch any pending event in the queue
            // propagate orphan events to the user
            let ret = callback((), &mut self.queue);
            match ret {
                Ok(0) => {
                    // no events were dispatched even after reading the socket,
                    // nothing more to do, stop here
                    break;
                }
                Ok(_) => {}
                Err(e) => {
                    // in case of error, forward it and fast-exit
                    return Err(e);
                }
            }
        }
        // 3. Once dispatching is finished, flush the responses to the compositor
        if let Err(e) = self.queue.display().flush() {
            if e.kind() != io::ErrorKind::WouldBlock {
                // in case of error, forward it and fast-exit
                return Err(e);
            }
            // WouldBlock error means the compositor could not process all our messages
            // quickly. Either it is slowed down or we are a spammer.
            // Should not really happen, if it does we do nothing and will flush again later
        }
        Ok(())
    }

    fn register(&mut self, poll: &mut calloop::Poll, token: calloop::Token) -> std::io::Result<()> {
        self.fd.register(poll, token)
    }

    fn reregister(
        &mut self,
        poll: &mut calloop::Poll,
        token: calloop::Token,
    ) -> std::io::Result<()> {
        self.fd.reregister(poll, token)
    }

    fn unregister(&mut self, poll: &mut calloop::Poll) -> std::io::Result<()> {
        self.fd.unregister(poll)
    }
}