Skip to main content

get_registry/common/protocols_data/wayland/
wl_display.rs

1//! core global object
2//!
3//! The core global object.  This is a special singleton object.  It
4//! is used for internal Wayland protocol features.
5
6use super::super::all_types::*;
7use ::wl_client::builder::prelude::*;
8
9static INTERFACE: wl_interface = wl_interface {
10    name: c"wl_display".as_ptr(),
11    version: 1,
12    method_count: 2,
13    methods: {
14        static MESSAGES: [wl_message; 2] = [
15            wl_message {
16                name: c"sync".as_ptr(),
17                signature: c"n".as_ptr(),
18                types: {
19                    static TYPES: [Option<&'static wl_interface>; 1] =
20                        [Some(WlCallback::WL_INTERFACE)];
21                    TYPES.as_ptr().cast()
22                },
23            },
24            wl_message {
25                name: c"get_registry".as_ptr(),
26                signature: c"n".as_ptr(),
27                types: {
28                    static TYPES: [Option<&'static wl_interface>; 1] =
29                        [Some(WlRegistry::WL_INTERFACE)];
30                    TYPES.as_ptr().cast()
31                },
32            },
33        ];
34        MESSAGES.as_ptr()
35    },
36    event_count: 2,
37    events: {
38        static MESSAGES: [wl_message; 2] = [
39            wl_message {
40                name: c"error".as_ptr(),
41                signature: c"ous".as_ptr(),
42                types: {
43                    static TYPES: [Option<&'static wl_interface>; 3] = [None, None, None];
44                    TYPES.as_ptr().cast()
45                },
46            },
47            wl_message {
48                name: c"delete_id".as_ptr(),
49                signature: c"u".as_ptr(),
50                types: {
51                    static TYPES: [Option<&'static wl_interface>; 1] = [None];
52                    TYPES.as_ptr().cast()
53                },
54            },
55        ];
56        MESSAGES.as_ptr()
57    },
58};
59
60/// An owned wl_display proxy.
61///
62/// See the documentation of [the module][self] for the interface description.
63#[derive(Clone, Eq, PartialEq)]
64#[repr(transparent)]
65pub struct WlDisplay {
66    /// This proxy has the interface INTERFACE.
67    proxy: UntypedOwnedProxy,
68}
69
70/// A borrowed wl_display proxy.
71///
72/// See the documentation of [the module][self] for the interface description.
73#[derive(Eq, PartialEq)]
74#[repr(transparent)]
75pub struct WlDisplayRef {
76    /// This proxy has the interface INTERFACE.
77    proxy: UntypedBorrowedProxy,
78}
79
80// SAFETY: WlDisplay is a transparent wrapper around UntypedOwnedProxy
81unsafe impl UntypedOwnedProxyWrapper for WlDisplay {}
82
83// SAFETY: - INTERFACE is a valid wl_interface
84//         - The only invariant is that self.proxy has a compatible interface
85unsafe impl OwnedProxy for WlDisplay {
86    const INTERFACE: &'static str = "wl_display";
87    const WL_INTERFACE: &'static wl_interface = &INTERFACE;
88    const NO_OP_EVENT_HANDLER: Self::NoOpEventHandler =
89        private::EventHandler(private::NoOpEventHandler);
90    const MAX_VERSION: u32 = 1;
91
92    type Borrowed = WlDisplayRef;
93    type Api = private::ProxyApi;
94    type NoOpEventHandler = private::EventHandler<private::NoOpEventHandler>;
95}
96
97// SAFETY: WlDisplayRef is a transparent wrapper around UntypedBorrowedProxy
98unsafe impl UntypedBorrowedProxyWrapper for WlDisplayRef {}
99
100// SAFETY: - The only invariant is that self.proxy has a compatible interface
101unsafe impl BorrowedProxy for WlDisplayRef {
102    type Owned = WlDisplay;
103}
104
105impl Deref for WlDisplay {
106    type Target = WlDisplayRef;
107
108    fn deref(&self) -> &Self::Target {
109        proxy::low_level::deref(self)
110    }
111}
112
113mod private {
114    pub struct ProxyApi;
115
116    #[allow(dead_code)]
117    pub struct EventHandler<H>(pub(super) H);
118
119    #[allow(dead_code)]
120    pub struct NoOpEventHandler;
121}
122
123impl Debug for WlDisplay {
124    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
125        write!(f, "wl_display#{}", self.proxy.id())
126    }
127}
128
129impl Debug for WlDisplayRef {
130    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
131        write!(f, "wl_display#{}", self.proxy.id())
132    }
133}
134
135impl PartialEq<WlDisplayRef> for WlDisplay {
136    fn eq(&self, other: &WlDisplayRef) -> bool {
137        self.proxy == other.proxy
138    }
139}
140
141impl PartialEq<WlDisplay> for WlDisplayRef {
142    fn eq(&self, other: &WlDisplay) -> bool {
143        self.proxy == other.proxy
144    }
145}
146
147#[allow(dead_code)]
148impl WlDisplay {
149    /// Since when the sync request is available.
150    #[allow(dead_code)]
151    pub const REQ__SYNC__SINCE: u32 = 1;
152
153    /// Since when the get_registry request is available.
154    #[allow(dead_code)]
155    pub const REQ__GET_REGISTRY__SINCE: u32 = 1;
156}
157
158#[allow(dead_code)]
159impl WlDisplay {
160    /// asynchronous roundtrip
161    ///
162    /// The sync request asks the server to emit the 'done' event
163    /// on the returned wl_callback object.  Since requests are
164    /// handled in-order and events are delivered in-order, this can
165    /// be used as a barrier to ensure all previous requests and the
166    /// resulting events have been handled.
167    ///
168    /// The object returned by this request will be destroyed by the
169    /// compositor after the callback is fired and as such the client must not
170    /// attempt to use it after that point.
171    ///
172    /// The callback_data passed in the callback is undefined and should be ignored.
173    #[inline]
174    pub fn sync(&self) -> WlCallback {
175        let mut args = [wl_argument { n: 0 }];
176        // SAFETY: - self.proxy has the interface INTERFACE
177        //         - 0 < INTERFACE.method_count = 2
178        //         - the request signature is `n`
179        //         - OwnedProxy::WL_INTERFACE is always a valid interface
180        let data = unsafe {
181            self.proxy
182                .send_constructor::<false>(0, &mut args, WlCallback::WL_INTERFACE, None)
183        };
184        // SAFETY: data has the interface WlCallback::WL_INTERFACE
185        unsafe { proxy::low_level::from_untyped_owned(data) }
186    }
187
188    /// get global registry object
189    ///
190    /// This request creates a registry object that allows the client
191    /// to list and bind the global objects available from the
192    /// compositor.
193    ///
194    /// It should be noted that the server side resources consumed in
195    /// response to a get_registry request can only be released when the
196    /// client disconnects, not when the client side proxy is destroyed.
197    /// Therefore, clients should invoke get_registry as infrequently as
198    /// possible to avoid wasting memory.
199    #[inline]
200    pub fn get_registry(&self) -> WlRegistry {
201        let mut args = [wl_argument { n: 0 }];
202        // SAFETY: - self.proxy has the interface INTERFACE
203        //         - 1 < INTERFACE.method_count = 2
204        //         - the request signature is `n`
205        //         - OwnedProxy::WL_INTERFACE is always a valid interface
206        let data = unsafe {
207            self.proxy
208                .send_constructor::<false>(1, &mut args, WlRegistry::WL_INTERFACE, None)
209        };
210        // SAFETY: data has the interface WlRegistry::WL_INTERFACE
211        unsafe { proxy::low_level::from_untyped_owned(data) }
212    }
213}
214
215#[allow(dead_code)]
216impl WlDisplayRef {
217    /// asynchronous roundtrip
218    ///
219    /// The sync request asks the server to emit the 'done' event
220    /// on the returned wl_callback object.  Since requests are
221    /// handled in-order and events are delivered in-order, this can
222    /// be used as a barrier to ensure all previous requests and the
223    /// resulting events have been handled.
224    ///
225    /// The object returned by this request will be destroyed by the
226    /// compositor after the callback is fired and as such the client must not
227    /// attempt to use it after that point.
228    ///
229    /// The callback_data passed in the callback is undefined and should be ignored.
230    ///
231    /// # Arguments
232    ///
233    /// - `_queue`: The queue that the returned proxy is assigned to.
234    #[inline]
235    pub fn sync(&self, _queue: &Queue) -> WlCallback {
236        let mut args = [wl_argument { n: 0 }];
237        // SAFETY: - self.proxy has the interface INTERFACE
238        //         - 0 < INTERFACE.method_count = 2
239        //         - the request signature is `n`
240        //         - OwnedProxy::WL_INTERFACE is always a valid interface
241        let data = unsafe {
242            self.proxy
243                .send_constructor(_queue, 0, &mut args, WlCallback::WL_INTERFACE, None)
244        };
245        // SAFETY: data has the interface WlCallback::WL_INTERFACE
246        unsafe { proxy::low_level::from_untyped_owned(data) }
247    }
248
249    /// get global registry object
250    ///
251    /// This request creates a registry object that allows the client
252    /// to list and bind the global objects available from the
253    /// compositor.
254    ///
255    /// It should be noted that the server side resources consumed in
256    /// response to a get_registry request can only be released when the
257    /// client disconnects, not when the client side proxy is destroyed.
258    /// Therefore, clients should invoke get_registry as infrequently as
259    /// possible to avoid wasting memory.
260    ///
261    /// # Arguments
262    ///
263    /// - `_queue`: The queue that the returned proxy is assigned to.
264    #[inline]
265    pub fn get_registry(&self, _queue: &Queue) -> WlRegistry {
266        let mut args = [wl_argument { n: 0 }];
267        // SAFETY: - self.proxy has the interface INTERFACE
268        //         - 1 < INTERFACE.method_count = 2
269        //         - the request signature is `n`
270        //         - OwnedProxy::WL_INTERFACE is always a valid interface
271        let data = unsafe {
272            self.proxy
273                .send_constructor(_queue, 1, &mut args, WlRegistry::WL_INTERFACE, None)
274        };
275        // SAFETY: data has the interface WlRegistry::WL_INTERFACE
276        unsafe { proxy::low_level::from_untyped_owned(data) }
277    }
278}
279
280impl WlDisplay {
281    /// Since when the error event is available.
282    #[allow(dead_code)]
283    pub const EVT__ERROR__SINCE: u32 = 1;
284
285    /// Since when the delete_id event is available.
286    #[allow(dead_code)]
287    pub const EVT__DELETE_ID__SINCE: u32 = 1;
288}
289
290/// An event handler for [WlDisplay] proxies.
291#[allow(dead_code)]
292pub trait WlDisplayEventHandler {
293    type Data: 'static;
294
295    /// fatal error event
296    ///
297    /// The error event is sent out when a fatal (non-recoverable)
298    /// error has occurred.  The object_id argument is the object
299    /// where the error occurred, most often in response to a request
300    /// to that object.  The code identifies the error and is defined
301    /// by the object interface.  As such, each interface defines its
302    /// own set of error codes.  The message is a brief description
303    /// of the error, for (debugging) convenience.
304    ///
305    /// # Arguments
306    ///
307    /// - `object_id`: object where the error occurred
308    /// - `code`: error code
309    /// - `message`: error description
310    ///
311    /// All borrowed proxies passed to this function are guaranteed to be
312    /// immutable and non-null.
313    #[inline]
314    fn error(
315        &self,
316        _data: &mut Self::Data,
317        _slf: &WlDisplayRef,
318        object_id: Option<&UntypedBorrowedProxy>,
319        code: u32,
320        message: &str,
321    ) {
322        let _ = object_id;
323        let _ = code;
324        let _ = message;
325    }
326
327    /// acknowledge object ID deletion
328    ///
329    /// This event is used internally by the object ID management
330    /// logic. When a client deletes an object that it had created,
331    /// the server will send this event to acknowledge that it has
332    /// seen the delete request. When the client receives this event,
333    /// it will know that it can safely reuse the object ID.
334    ///
335    /// # Arguments
336    ///
337    /// - `id`: deleted object ID
338    #[inline]
339    fn delete_id(&self, _data: &mut Self::Data, _slf: &WlDisplayRef, id: u32) {
340        let _ = id;
341    }
342}
343
344impl WlDisplayEventHandler for private::NoOpEventHandler {
345    type Data = ();
346}
347
348// SAFETY: - INTERFACE is a valid wl_interface
349//         - mutable_type always returns the same value
350unsafe impl<H> EventHandler for private::EventHandler<H>
351where
352    H: WlDisplayEventHandler,
353{
354    const WL_INTERFACE: &'static wl_interface = &INTERFACE;
355
356    #[inline]
357    fn mutable_type() -> Option<(TypeId, &'static str)> {
358        let id = TypeId::of::<H::Data>();
359        let name = std::any::type_name::<H::Data>();
360        Some((id, name))
361    }
362
363    #[allow(unused_variables)]
364    unsafe fn handle_event(
365        &self,
366        queue: &Queue,
367        data: *mut u8,
368        slf: &UntypedBorrowedProxy,
369        opcode: u32,
370        args: *mut wl_argument,
371    ) {
372        // SAFETY: This function requires that slf has the interface INTERFACE
373        let slf = unsafe { proxy::low_level::from_untyped_borrowed::<WlDisplayRef>(slf) };
374        // SAFETY: This function requires that data is `&mut T` where `T`
375        //         has the type id returned by `Self::mutable_type`, i.e.,
376        //         `T = H::Data`.
377        let data: &mut H::Data = unsafe { &mut *data.cast() };
378        match opcode {
379            0 => {
380                // SAFETY: INTERFACE requires that there are 3 arguments
381                let args = unsafe { &*args.cast::<[wl_argument; 3]>() };
382                // SAFETY: - INTERFACE requires that args[0] contains an object
383                let arg0 = unsafe {
384                    if let Some(p) = NonNull::new(args[0].o.cast()) {
385                        Some(UntypedBorrowedProxy::new_immutable(queue.libwayland(), p))
386                    } else {
387                        None
388                    }
389                };
390                let arg0 = arg0.as_ref();
391                // SAFETY: - INTERFACE requires that args[1] contains a uint
392                let arg1 = unsafe { args[1].u };
393                // SAFETY: - INTERFACE requires that args[2] contains a string
394                //         - if the pointer is not null, then it is a c string
395                let arg2 = unsafe { convert_string_arg("wl_display", "message", args[2].s) };
396                self.0.error(data, slf, arg0, arg1, arg2);
397            }
398            1 => {
399                // SAFETY: INTERFACE requires that there are 1 arguments
400                let args = unsafe { &*args.cast::<[wl_argument; 1]>() };
401                // SAFETY: - INTERFACE requires that args[0] contains a uint
402                let arg0 = unsafe { args[0].u };
403                self.0.delete_id(data, slf, arg0);
404            }
405            _ => {
406                invalid_opcode("wl_display", opcode);
407            }
408        }
409    }
410}
411
412impl<H> CreateEventHandler<H> for private::ProxyApi
413where
414    H: WlDisplayEventHandler,
415{
416    type EventHandler = private::EventHandler<H>;
417
418    #[inline]
419    fn create_event_handler(handler: H) -> Self::EventHandler {
420        private::EventHandler(handler)
421    }
422}
423
424impl WlDisplay {
425    /// Since when the error.invalid_object enum variant is available.
426    #[allow(dead_code)]
427    pub const ENM__ERROR_INVALID_OBJECT__SINCE: u32 = 1;
428    /// Since when the error.invalid_method enum variant is available.
429    #[allow(dead_code)]
430    pub const ENM__ERROR_INVALID_METHOD__SINCE: u32 = 1;
431    /// Since when the error.no_memory enum variant is available.
432    #[allow(dead_code)]
433    pub const ENM__ERROR_NO_MEMORY__SINCE: u32 = 1;
434    /// Since when the error.implementation enum variant is available.
435    #[allow(dead_code)]
436    pub const ENM__ERROR_IMPLEMENTATION__SINCE: u32 = 1;
437}
438
439/// global error values
440///
441/// These errors are global and can be emitted in response to any
442/// server request.
443#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
444#[allow(dead_code)]
445pub struct WlDisplayError(pub u32);
446
447impl WlDisplayError {
448    /// server couldn't find object
449    #[allow(dead_code)]
450    pub const INVALID_OBJECT: Self = Self(0);
451
452    /// method doesn't exist on the specified interface or malformed request
453    #[allow(dead_code)]
454    pub const INVALID_METHOD: Self = Self(1);
455
456    /// server is out of memory
457    #[allow(dead_code)]
458    pub const NO_MEMORY: Self = Self(2);
459
460    /// implementation error in compositor
461    #[allow(dead_code)]
462    pub const IMPLEMENTATION: Self = Self(3);
463}
464
465impl Debug for WlDisplayError {
466    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
467        let name = match *self {
468            Self::INVALID_OBJECT => "INVALID_OBJECT",
469            Self::INVALID_METHOD => "INVALID_METHOD",
470            Self::NO_MEMORY => "NO_MEMORY",
471            Self::IMPLEMENTATION => "IMPLEMENTATION",
472            _ => return Debug::fmt(&self.0, f),
473        };
474        f.write_str(name)
475    }
476}
477
478/// Functional event handlers.
479pub mod event_handlers {
480    use super::*;
481
482    /// Event handler for error events.
483    pub struct Error<T, F>(F, PhantomData<fn(&mut T)>);
484    impl<T, F> WlDisplayEventHandler for Error<T, F>
485    where
486        T: 'static,
487        F: Fn(&mut T, &WlDisplayRef, Option<&UntypedBorrowedProxy>, u32, &str),
488    {
489        type Data = T;
490
491        #[inline]
492        fn error(
493            &self,
494            _data: &mut T,
495            _slf: &WlDisplayRef,
496            object_id: Option<&UntypedBorrowedProxy>,
497            code: u32,
498            message: &str,
499        ) {
500            self.0(_data, _slf, object_id, code, message)
501        }
502    }
503
504    /// Event handler for delete_id events.
505    pub struct DeleteId<T, F>(F, PhantomData<fn(&mut T)>);
506    impl<T, F> WlDisplayEventHandler for DeleteId<T, F>
507    where
508        T: 'static,
509        F: Fn(&mut T, &WlDisplayRef, u32),
510    {
511        type Data = T;
512
513        #[inline]
514        fn delete_id(&self, _data: &mut T, _slf: &WlDisplayRef, id: u32) {
515            self.0(_data, _slf, id)
516        }
517    }
518
519    impl WlDisplay {
520        /// Creates an event handler for error events.
521        ///
522        /// The event handler ignores all other events.
523        #[allow(dead_code)]
524        pub fn on_error<T, F>(f: F) -> Error<T, F>
525        where
526            T: 'static,
527            F: Fn(&mut T, &WlDisplayRef, Option<&UntypedBorrowedProxy>, u32, &str),
528        {
529            Error(f, PhantomData)
530        }
531
532        /// Creates an event handler for delete_id events.
533        ///
534        /// The event handler ignores all other events.
535        #[allow(dead_code)]
536        pub fn on_delete_id<T, F>(f: F) -> DeleteId<T, F>
537        where
538            T: 'static,
539            F: Fn(&mut T, &WlDisplayRef, u32),
540        {
541            DeleteId(f, PhantomData)
542        }
543    }
544}