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
use std::ffi::{CStr, CString};
use std::ops;

use crate::protocol::wl_registry::GlobalArgs;
use crate::proxy::Proxy;
use crate::{Connection, EventCtx};

pub type Global = GlobalArgs;
pub type Globals = [Global];

#[derive(Debug, thiserror::Error)]
pub enum BindError {
    #[error("global has interface {actual:?} but {requested:?} was requested")]
    IncorrectInterface {
        actual: CString,
        requested: &'static CStr,
    },
    #[error("global has version {actual} but a minimum version of {min} was requested")]
    UnsupportedVersion { actual: u32, min: u32 },
    #[error("global with interface {0:?} not found")]
    GlobalNotFound(&'static CStr),
}

pub trait GlobalExt {
    fn is<P: Proxy>(&self) -> bool;

    /// Bind a global.
    ///
    /// The version argmuent can be a:
    /// - Number - require a specific version
    /// - Range to inclusive (`..=b` - bind a version in range `[1, b]`)
    /// - Range inclusive (`a..=b` - bind a version in range `[a, b]`)
    fn bind<P: Proxy, D>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
    ) -> Result<P, BindError>;

    /// Same as [`bind`](Self::bind) but also sets the callback
    fn bind_with_cb<P: Proxy, D, F: FnMut(EventCtx<D, P>) + Send + 'static>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
        cb: F,
    ) -> Result<P, BindError>;
}

pub trait GlobalsExt {
    fn bind<P: Proxy, D>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
    ) -> Result<P, BindError>;

    /// Same as [`bind`](Self::bind) but also sets the callback
    fn bind_with_cb<P: Proxy, D, F: FnMut(EventCtx<D, P>) + Send + 'static>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
        cb: F,
    ) -> Result<P, BindError>;
}

impl GlobalExt for Global {
    fn is<P: Proxy>(&self) -> bool {
        P::INTERFACE.name == self.interface.as_c_str()
    }

    /// Bind the first instance of a global. Works great for singletons.
    ///
    /// The version argmuent can be a:
    /// - Number - require a specific version
    /// - Range to inclusive (`..=b` - bind a version in range `[1, b]`)
    /// - Range inclusive (`a..=b` - bind a version in range `[a, b]`)
    fn bind<P: Proxy, D>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
    ) -> Result<P, BindError> {
        if !self.is::<P>() {
            return Err(BindError::IncorrectInterface {
                actual: self.interface.to_owned(),
                requested: P::INTERFACE.name,
            });
        }

        assert!(version.upper() <= P::INTERFACE.version);

        if self.version < version.lower() {
            return Err(BindError::UnsupportedVersion {
                actual: self.version,
                min: version.lower(),
            });
        }

        let reg = conn.registry();
        let version = u32::min(version.upper(), self.version);

        Ok(reg.bind(conn, self.name, version))
    }

    /// Same as [`bind`](Self::bind) but also sets the callback
    fn bind_with_cb<P: Proxy, D, F: FnMut(EventCtx<D, P>) + Send + 'static>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
        cb: F,
    ) -> Result<P, BindError> {
        if !self.is::<P>() {
            return Err(BindError::IncorrectInterface {
                actual: self.interface.to_owned(),
                requested: P::INTERFACE.name,
            });
        }

        assert!(version.upper() <= P::INTERFACE.version);

        if self.version < version.lower() {
            return Err(BindError::UnsupportedVersion {
                actual: self.version,
                min: version.lower(),
            });
        }

        let reg = conn.registry();
        let version = u32::min(version.upper(), self.version);

        Ok(reg.bind_with_cb(conn, self.name, version, cb))
    }
}

impl GlobalsExt for Globals {
    fn bind<P: Proxy, D>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
    ) -> Result<P, BindError> {
        let global = self
            .iter()
            .find(|g| g.is::<P>())
            .ok_or(BindError::GlobalNotFound(P::INTERFACE.name))?;
        global.bind(conn, version)
    }

    fn bind_with_cb<P: Proxy, D, F: FnMut(EventCtx<D, P>) + Send + 'static>(
        &self,
        conn: &mut Connection<D>,
        version: impl VersionBounds,
        cb: F,
    ) -> Result<P, BindError> {
        let global = self
            .iter()
            .find(|g| g.is::<P>())
            .ok_or(BindError::GlobalNotFound(P::INTERFACE.name))?;
        global.bind_with_cb(conn, version, cb)
    }
}

pub trait VersionBounds: private::Sealed {
    fn lower(&self) -> u32;
    fn upper(&self) -> u32;
}

mod private {
    pub trait Sealed {}
}

macro_rules! impl_version_bounds {
    ($($ty:ty => ($self:ident) => $lower:expr, $upper:expr;)*) => {
        $(
            impl private::Sealed for $ty {}
            impl VersionBounds for $ty {
                fn lower(&$self) -> u32 {
                    $lower
                }
                fn upper(&$self) -> u32 {
                    $upper
                }
            }
        )*
    };
}

impl_version_bounds! [
    u32 => (self) => *self, *self;
    ops::RangeToInclusive<u32> => (self) => 1, self.end;
    ops::RangeInclusive<u32> => (self) => *self.start(), *self.end();
];