tilo-winit 0.5.2

winit 0.30.13 (https://github.com/rust-windowing/winit) with the additions the Tilo SDK uses: synthetic key events, Wayland drag sources and swipe gestures, a macOS quit request. Tilo's fork; see TILO-FORK.md.
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! # Wayland
//!
//! **Note:** Windows don't appear on Wayland until you draw/present to them.
//!
//! By default, Winit loads system libraries using `dlopen`. This can be
//! disabled by disabling the `"wayland-dlopen"` cargo feature.
//!
//! ## Client-side decorations
//!
//! Winit provides client-side decorations by default, but the behaviour can
//! be controlled with the following feature flags:
//!
//! * `wayland-csd-adwaita` (default).
//! * `wayland-csd-adwaita-crossfont`.
//! * `wayland-csd-adwaita-notitle`.

use std::ffi::c_void;
use std::ptr::NonNull;

use crate::dpi::PhysicalSize;
use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder};
use crate::monitor::MonitorHandle;
use crate::window::{Window, WindowAttributes};

pub use crate::window::Theme;

/// Additional methods on [`ActiveEventLoop`] that are specific to Wayland.
pub trait ActiveEventLoopExtWayland {
    /// True if the [`ActiveEventLoop`] uses Wayland.
    fn is_wayland(&self) -> bool;
}

impl ActiveEventLoopExtWayland for ActiveEventLoop {
    #[inline]
    fn is_wayland(&self) -> bool {
        self.p.is_wayland()
    }
}

/// Additional methods on [`EventLoop`] that are specific to Wayland.
pub trait EventLoopExtWayland {
    /// True if the [`EventLoop`] uses Wayland.
    fn is_wayland(&self) -> bool;
}

impl<T: 'static> EventLoopExtWayland for EventLoop<T> {
    #[inline]
    fn is_wayland(&self) -> bool {
        self.event_loop.is_wayland()
    }
}

/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland.
pub trait EventLoopBuilderExtWayland {
    /// Force using Wayland.
    fn with_wayland(&mut self) -> &mut Self;

    /// Whether to allow the event loop to be created off of the main thread.
    ///
    /// By default, the window is only allowed to be created on the main
    /// thread, to make platform compatibility easier.
    fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
}

impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
    #[inline]
    fn with_wayland(&mut self) -> &mut Self {
        self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::Wayland);
        self
    }

    #[inline]
    fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
        self.platform_specific.any_thread = any_thread;
        self
    }
}

/// Outcome of the exact surface commit observed through `wp_presentation`.
/// Times use the clock advertised by the compositor, never callback receipt time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WaylandPresentation {
    Presented {
        clock_id: u32,
        timestamp: std::time::Duration,
        refresh: std::time::Duration,
        sequence: u64,
        flags: u32,
    },
    Discarded,
}

impl WaylandPresentation {
    #[doc(hidden)]
    pub fn from_protocol(
        clock_id: Option<u32>,
        time: (u32, u32, u32),
        refresh: u32,
        sequence: (u32, u32),
        flags: Option<u32>,
    ) -> Self {
        match (clock_id, flags) {
            (Some(clock_id), Some(flags)) if time.2 < 1_000_000_000 => Self::Presented {
                clock_id,
                timestamp: std::time::Duration::new(
                    (u64::from(time.0) << 32) | u64::from(time.1),
                    time.2,
                ),
                refresh: std::time::Duration::from_nanos(u64::from(refresh)),
                sequence: (u64::from(sequence.0) << 32) | u64::from(sequence.1),
                flags,
            },
            _ => Self::Discarded,
        }
    }
}

/// One-shot observation of the next surface commit. No pixels or input text.
pub type WaylandPresentationObserver = Box<dyn FnOnce(WaylandPresentation) + Send + 'static>;

/// A field's `zwp_text_input_v3` content type: the `content_hint` bits and
/// the `content_purpose` value, as the protocol defines them. Unknown hint
/// bits are dropped and an unknown purpose is sent as `normal`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ImeContentType {
    pub hint: u32,
    pub purpose: u32,
}

/// Additional methods on [`Window`] that are specific to Wayland.
///
/// [`Window`]: crate::window::Window
pub trait WindowExtWayland {
    /// Send this content type to the input method instead of the one
    /// [`Window::set_ime_purpose`](crate::window::Window::set_ime_purpose)
    /// stands for; `None` goes back to the purpose's.
    fn set_ime_content_type(&self, content: Option<ImeContentType>);
    /// Publish a private, ephemeral equality stamp for the original editable field.
    /// An empty stamp disables admission. Does not grant microphone or IME ownership.
    fn private_text_input(&self, snapshot: Option<[u8; 32]>) -> bool;
    /// Resolve the exact original request after its actual renderer result.
    /// Outcome is accepted (0), known rejection (1), or unknown delivery (2).
    fn acknowledge_private_text_input(&self, serial: u32, outcome: u32);

    /// Present a frame of `size` pixels that `present` commits (a swapchain
    /// present), observing it with the standard presentation protocol when
    /// `observer` is given. The surface takes the logical size that frame was
    /// drawn for in the same commit, so a frame is never shown stretched to
    /// a size configured after it was drawn. Holds the native window state
    /// lock across `present` so an IME/configure commit cannot take the
    /// feedback or the size for an unrelated buffer. Always calls `present`;
    /// returns whether the presentation is observed. A frame callback or
    /// client submission never completes this observer.
    fn present_frame(
        &self,
        size: PhysicalSize<u32>,
        observer: Option<WaylandPresentationObserver>,
        present: impl FnOnce(),
    ) -> bool;

    /// Whether a frame [`Self::present_frame`] presents may be drawn in the top-left corner of a
    /// larger buffer: the surface shows only the frame's own pixels, so a swapchain can keep
    /// its buffers while the window's size changes under them.
    fn crops_frames(&self) -> bool;

    /// Returns `xdg_toplevel` of the window or [`None`] if the window is X11 window.
    fn xdg_toplevel(&self) -> Option<NonNull<c_void>>;

    /// Start a drag-and-drop from this window, offering `offers` as
    /// mime type → content: bytes, or a file that is read only when a
    /// receiver asks for it, on the thread that writes the pipe
    /// ([`DragData::File`]).
    ///
    /// Call it while a pointer button is held — the compositor validates
    /// the drag against that implicit grab, so a drag started without one
    /// is ignored. The receiving application asks for whichever offered
    /// mime type it understands and is handed those bytes.
    ///
    /// Bytes rather than a file path, because the receiver may be a
    /// sandboxed app in its own mount namespace where a path from this
    /// process does not resolve. Offer a `text/uri-list` too if the
    /// receiver may want a name, but never offer only that.
    ///
    /// Returns whether the drag was started: `false` on X11, when no
    /// pointer is on the seat, when the compositor has no
    /// `wl_data_device_manager`, or when `offers` is empty.
    fn start_drag(&self, offers: Vec<(String, DragData)>) -> bool;

    /// Whether the compositor draws this window's decorations, as settled by
    /// `xdg-decoration` in the last configure. `None` before the first
    /// configure. An X11 window manager always decorates.
    fn server_side_decorations(&self) -> Option<bool>;

    /// The (fourcc, modifier) pairs the compositor takes as dma-bufs; empty
    /// on X11 or before the compositor announced them (Tilo).
    fn client_buffer_formats(&self) -> Vec<(u32, u64)>;

    /// A `wl_buffer` of pixels another process drew (Tilo's render
    /// service), calling `on_release` whenever the compositor releases it.
    /// `None` on X11, or for a buffer the compositor does not take.
    #[cfg(wayland_platform)]
    fn create_client_buffer(
        &self,
        source: ClientBufferSource<'_>,
        on_release: Box<dyn Fn() + Send + Sync>,
    ) -> Option<ClientBuffer>;

    /// Attach `buffer` to this window's surface with `damage` (buffer
    /// pixels: x, y, width, height; empty damages all of it) and commit,
    /// observing the commit's presentation with `observer`. Returns whether
    /// the presentation is observed (Tilo).
    #[cfg(wayland_platform)]
    fn attach_client_buffer(
        &self,
        buffer: &ClientBuffer,
        damage: &[(i32, i32, i32, i32)],
        observer: Option<WaylandPresentationObserver>,
    ) -> bool;

    /// Whether this window is the session's lock screen and the compositor
    /// confirmed the lock: it has its surface, sized to the output, and
    /// every input is its. Before that it draws nothing.
    fn is_session_lock_up(&self) -> bool;

    /// End the session's lock this window holds, after it established that
    /// the person may: the session's desktop shows again. A window that is
    /// not the lock screen does nothing.
    fn unlock_session(&self);
}

#[cfg(wayland_platform)]
pub use crate::platform_impl::wayland::{
    Anchor, ClientBuffer, ClientBufferSource, DragData, KeyboardInteractivity, Layer,
    LayerSurfaceAttributes,
};

impl WindowExtWayland for Window {
    fn set_ime_content_type(&self, content: Option<ImeContentType>) {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => (),
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.set_ime_content_type(content),
        }
    }
    fn private_text_input(&self, snapshot: Option<[u8; 32]>) -> bool {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => false,
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.private_text_input(snapshot),
        }
    }
    fn acknowledge_private_text_input(&self, serial: u32, outcome: u32) {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => (),
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => {
                window.acknowledge_private_text_input(serial, outcome)
            }
        }
    }

    fn present_frame(
        &self,
        size: PhysicalSize<u32>,
        observer: Option<WaylandPresentationObserver>,
        present: impl FnOnce(),
    ) -> bool {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => {
                let _ = (size, observer);
                present();
                false
            }
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => {
                window.present_frame(size, observer, present)
            }
        }
    }

    fn crops_frames(&self) -> bool {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => false,
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.crops_frames(),
        }
    }

    #[inline]
    fn xdg_toplevel(&self) -> Option<NonNull<c_void>> {
        #[allow(clippy::single_match)]
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => None,
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.xdg_toplevel(),
        }
    }

    /// Whether this window is the session's lock screen and the compositor
    /// confirmed the lock: it has its surface, sized to the output, and
    /// every input is its. Before that it draws nothing.
    fn is_session_lock_up(&self) -> bool {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => false,
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.is_session_lock_up(),
        }
    }

    /// End the session's lock this window holds. The session's desktop
    /// shows again. A window that is not the lock screen does nothing.
    fn unlock_session(&self) {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => (),
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.unlock_session(),
        }
    }

    #[inline]
    fn start_drag(&self, offers: Vec<(String, DragData)>) -> bool {
        #[allow(clippy::single_match)]
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => false,
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.start_drag(offers),
        }
    }

    #[inline]
    fn server_side_decorations(&self) -> Option<bool> {
        #[allow(clippy::single_match)]
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => Some(true),
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.server_side_decorations(),
        }
    }

    fn client_buffer_formats(&self) -> Vec<(u32, u64)> {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => Vec::new(),
            #[cfg(wayland_platform)]
            crate::platform_impl::Window::Wayland(window) => window.client_buffer_formats(),
        }
    }

    #[cfg(wayland_platform)]
    fn create_client_buffer(
        &self,
        source: ClientBufferSource<'_>,
        on_release: Box<dyn Fn() + Send + Sync>,
    ) -> Option<ClientBuffer> {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => None,
            crate::platform_impl::Window::Wayland(window) => {
                window.create_client_buffer(source, on_release)
            }
        }
    }

    #[cfg(wayland_platform)]
    fn attach_client_buffer(
        &self,
        buffer: &ClientBuffer,
        damage: &[(i32, i32, i32, i32)],
        observer: Option<WaylandPresentationObserver>,
    ) -> bool {
        match &self.window {
            #[cfg(x11_platform)]
            crate::platform_impl::Window::X(_) => false,
            crate::platform_impl::Window::Wayland(window) => {
                window.attach_client_buffer(buffer, damage, observer)
            }
        }
    }
}

/// The compositor's serial of the newest input event (a key, a pointer button, a touch going
/// down or up) this process's event loop has handed the application, or that it dropped for
/// having no window: every input the compositor sent before it has been handed over too. Input
/// that reaches the application by another way (a desktop's bar telling it a button of its
/// own was pressed) names the serial it came after, and waits until this one reaches it.
/// `None` until the first.
pub fn delivered_input_serial() -> Option<u32> {
    #[cfg(wayland_platform)]
    {
        crate::platform_impl::wayland::delivered_input_serial()
    }
    #[cfg(not(wayland_platform))]
    {
        None
    }
}

/// Content-free identity of a key delivered by the Wayland compositor.
/// The timestamp is the protocol's wrapping millisecond clock, not an
/// assumed Unix/monotonic epoch. Repeats and synthesized keys have no stamp.
pub trait KeyEventExtWayland {
    fn wayland_serial_time(&self) -> Option<(u32, u32)>;
}

impl KeyEventExtWayland for crate::event::KeyEvent {
    fn wayland_serial_time(&self) -> Option<(u32, u32)> {
        self.platform_specific.wayland_stamp
    }
}

/// Additional methods on [`WindowAttributes`] that are specific to Wayland.
pub trait WindowAttributesExtWayland {
    /// Build window with the given name.
    ///
    /// The `general` name sets an application ID, which should match the `.desktop`
    /// file distributed with your program. The `instance` is a `no-op`.
    ///
    /// For details about application ID conventions, see the
    /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
    fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self;

    /// Make this window a surface on a layer of its output instead of a
    /// toplevel the desktop places.
    ///
    /// A session's own surfaces — a bar, a desk, a panel, a quick settings
    /// sheet — say where they go themselves: which layer, which edges they
    /// are anchored to, how much of the edge they reserve for the desktop
    /// to keep windows out of. The compositor composites them like any
    /// other client's surface.
    ///
    /// The attributes that only a toplevel has (a title, client side
    /// decorations, minimizing, maximizing, fullscreen, moving, a window
    /// menu) are ignored. The surface is configured with the size its
    /// anchors give it, like any layer surface.
    fn with_layer_surface(self, attributes: LayerSurfaceAttributes) -> Self;

    /// Make this window the session's lock screen instead of a toplevel
    /// the desktop places.
    ///
    /// The window asks the compositor for the session's lock when it is
    /// created: once every output shows it and nothing else draws, the
    /// window gets its surface, sized to the output, and every input goes
    /// to it. Leaving the lock is the window's own request
    /// ([`WindowExtWayland::unlock_session`]), after it established that the
    /// person may.
    ///
    /// The attributes that only a toplevel has (a title, client side
    /// decorations, minimizing, maximizing, fullscreen, moving, a window
    /// menu) are ignored.
    fn with_session_lock(self) -> Self;
}

impl WindowAttributesExtWayland for WindowAttributes {
    #[inline]
    fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
        self.platform_specific.name = Some(crate::platform_impl::ApplicationName::new(
            general.into(),
            instance.into(),
        ));
        self
    }

    #[inline]
    fn with_layer_surface(mut self, attributes: LayerSurfaceAttributes) -> Self {
        self.platform_specific.layer = Some(attributes);
        self
    }

    #[inline]
    fn with_session_lock(mut self) -> Self {
        self.platform_specific.session_lock = true;
        self
    }
}

/// Additional methods on `MonitorHandle` that are specific to Wayland.
pub trait MonitorHandleExtWayland {
    /// Returns the inner identifier of the monitor.
    fn native_id(&self) -> u32;

    /// The display's physical size in millimetres, when the compositor
    /// reports one. Lets a client tell a 14" panel from a 65" television
    /// that happen to share a resolution.
    fn physical_size_mm(&self) -> Option<(u32, u32)>;
}

impl MonitorHandleExtWayland for MonitorHandle {
    #[inline]
    fn native_id(&self) -> u32 {
        self.inner.native_identifier()
    }

    #[inline]
    fn physical_size_mm(&self) -> Option<(u32, u32)> {
        self.inner.physical_size_mm()
    }
}

#[doc(hidden)]
#[cfg(wayland_platform)]
pub use crate::platform_impl::wayland::private_text_input_protocol;