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
use dnd::{DndEvent, DndSurface};

use crate::{
    application::UserEventWrapper,
    futures::futures::{
        channel::mpsc,
        task::{Context, Poll},
        Sink,
    },
};
use std::pin::Pin;

/// An event loop proxy that implements `Sink`.
#[derive(Debug)]
pub struct Proxy<Message: 'static> {
    pub(crate) raw: winit::event_loop::EventLoopProxy<Message>,
}

impl<Message: 'static> Clone for Proxy<Message> {
    fn clone(&self) -> Self {
        Self {
            raw: self.raw.clone(),
        }
    }
}

impl<Message: 'static> Proxy<Message> {
    /// Creates a new [`Proxy`] from an `EventLoopProxy`.
    pub fn new(raw: winit::event_loop::EventLoopProxy<Message>) -> Self {
        Self { raw }
    }
}

impl<Message: 'static> Sink<Message> for Proxy<Message> {
    type Error = mpsc::SendError;

    fn poll_ready(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn start_send(
        self: Pin<&mut Self>,
        message: Message,
    ) -> Result<(), Self::Error> {
        let _ = self.raw.send_event(message);

        Ok(())
    }

    fn poll_flush(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
}

impl<M> dnd::Sender<DndSurface> for Proxy<UserEventWrapper<M>> {
    fn send(
        &self,
        event: DndEvent<DndSurface>,
    ) -> Result<(), std::sync::mpsc::SendError<DndEvent<DndSurface>>> {
        self.raw
            .send_event(UserEventWrapper::Dnd(event))
            .map_err(|_err| {
                std::sync::mpsc::SendError(DndEvent::Offer(
                    None,
                    dnd::OfferEvent::Leave,
                ))
            })
    }
}