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
use crate::{compositor::Surface, error::GlobalError, globals::GlobalData, registry::GlobalProxy};
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Weak,
};
use wayland_client::{
    globals::GlobalList,
    protocol::{wl_output, wl_surface},
    Connection, Dispatch, Proxy, QueueHandle,
};
use wayland_protocols::ext::session_lock::v1::client::{
    ext_session_lock_manager_v1, ext_session_lock_surface_v1, ext_session_lock_v1,
};

mod dispatch;

/// Handler trait for session lock protocol.
pub trait SessionLockHandler: Sized {
    /// The session lock is active, and the client may create lock surfaces.
    fn locked(&mut self, conn: &Connection, qh: &QueueHandle<Self>, session_lock: SessionLock);

    /// Session lock is not active and should be destroyed.
    ///
    /// This may be sent immediately if the compositor denys the requires to create a lock,
    /// or may be sent some time after `lock`.
    fn finished(&mut self, conn: &Connection, qh: &QueueHandle<Self>, session_lock: SessionLock);

    /// Compositor has requested size for surface.
    fn configure(
        &mut self,
        conn: &Connection,
        qh: &QueueHandle<Self>,
        surface: SessionLockSurface,
        configure: SessionLockSurfaceConfigure,
        serial: u32,
    );
}

#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct SessionLockSurfaceConfigure {
    pub new_size: (u32, u32),
}

#[derive(Debug)]
struct SessionLockSurfaceInner {
    surface: Surface,
    session_lock_surface: ext_session_lock_surface_v1::ExtSessionLockSurfaceV1,
}

impl Drop for SessionLockSurfaceInner {
    fn drop(&mut self) {
        self.session_lock_surface.destroy();
    }
}

#[must_use]
#[derive(Debug, Clone)]
pub struct SessionLockSurface(Arc<SessionLockSurfaceInner>);

impl SessionLockSurface {
    pub fn from_ext_session_lock_surface(
        surface: &ext_session_lock_surface_v1::ExtSessionLockSurfaceV1,
    ) -> Option<Self> {
        surface.data::<SessionLockSurfaceData>().and_then(|data| data.inner.upgrade()).map(Self)
    }

    pub fn wl_surface(&self) -> &wl_surface::WlSurface {
        self.0.surface.wl_surface()
    }
}

#[derive(Debug)]
pub struct SessionLockSurfaceData {
    inner: Weak<SessionLockSurfaceInner>,
}

impl SessionLockSurfaceData {
    pub fn session_lock_surface(&self) -> Option<SessionLockSurface> {
        self.inner.upgrade().map(SessionLockSurface)
    }
}

#[derive(Debug)]
pub struct SessionLockInner {
    session_lock: ext_session_lock_v1::ExtSessionLockV1,
    locked: AtomicBool,
}

impl Drop for SessionLockInner {
    fn drop(&mut self) {
        if self.locked.load(Ordering::SeqCst) {
            self.session_lock.unlock_and_destroy();
        } else {
            self.session_lock.destroy();
        }
    }
}

/// A session lock
///
/// The lock is destroyed on drop, which must be done after `locked` or `finished`
/// is received.
#[must_use]
#[derive(Debug, Clone)]
pub struct SessionLock(Arc<SessionLockInner>);

impl SessionLock {
    pub fn from_ext_session_lock(surface: &ext_session_lock_v1::ExtSessionLockV1) -> Option<Self> {
        surface.data::<SessionLockData>().and_then(|data| data.inner.upgrade()).map(Self)
    }

    pub fn is_locked(&self) -> bool {
        self.0.locked.load(Ordering::SeqCst)
    }
}

#[derive(Debug)]
pub struct SessionLockData {
    inner: Weak<SessionLockInner>,
}

impl SessionLock {
    pub fn create_lock_surface<D>(
        &self,
        surface: impl Into<Surface>,
        output: &wl_output::WlOutput,
        qh: &QueueHandle<D>,
    ) -> SessionLockSurface
    where
        D: Dispatch<ext_session_lock_surface_v1::ExtSessionLockSurfaceV1, SessionLockSurfaceData>
            + 'static,
    {
        // Freeze the queue during the creation of the Arc to avoid a race between events on the
        // new objects being processed and the Weak in the SessionLockSurfaceData becoming usable.
        let freeze = qh.freeze();
        let surface = surface.into();

        let inner = Arc::new_cyclic(|weak| {
            let session_lock_surface = self.0.session_lock.get_lock_surface(
                surface.wl_surface(),
                output,
                qh,
                SessionLockSurfaceData { inner: weak.clone() },
            );

            SessionLockSurfaceInner { surface, session_lock_surface }
        });
        drop(freeze);

        SessionLockSurface(inner)
    }
}

/// A handler for [`ext_session_lock_manager_v1::ExtSessionLockManagerV1`]
#[derive(Debug)]
pub struct SessionLockState {
    session_lock_manager: GlobalProxy<ext_session_lock_manager_v1::ExtSessionLockManagerV1>,
}

impl SessionLockState {
    pub fn new<D>(globals: &GlobalList, qh: &QueueHandle<D>) -> Self
    where
        D: Dispatch<ext_session_lock_manager_v1::ExtSessionLockManagerV1, GlobalData> + 'static,
    {
        let session_lock_manager = GlobalProxy::from(globals.bind(qh, 1..=1, GlobalData));
        Self { session_lock_manager }
    }

    pub fn lock<D>(&self, qh: &QueueHandle<D>) -> Result<SessionLock, GlobalError>
    where
        D: Dispatch<ext_session_lock_v1::ExtSessionLockV1, SessionLockData> + 'static,
    {
        let session_lock_manager = self.session_lock_manager.get()?;

        // Freeze the queue during the creation of the Arc to avoid a race between events on the
        // new objects being processed and the Weak in the SessionLockData becoming usable.
        let freeze = qh.freeze();

        let inner = Arc::new_cyclic(|weak| {
            let session_lock =
                session_lock_manager.lock(qh, SessionLockData { inner: weak.clone() });

            SessionLockInner { session_lock, locked: AtomicBool::new(false) }
        });
        drop(freeze);

        Ok(SessionLock(inner))
    }
}

#[macro_export]
macro_rules! delegate_session_lock {
    ($(@<$( $lt:tt $( : $clt:tt $(+ $dlt:tt )* )? ),+>)? $ty: ty) => {
        $crate::reexports::client::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty:
            [
                $crate::reexports::protocols::ext::session_lock::v1::client::ext_session_lock_manager_v1::ExtSessionLockManagerV1: $crate::globals::GlobalData
            ] => $crate::session_lock::SessionLockState
        );
        $crate::reexports::client::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty:
            [
                $crate::reexports::protocols::ext::session_lock::v1::client::ext_session_lock_v1::ExtSessionLockV1: $crate::session_lock::SessionLockData
            ] => $crate::session_lock::SessionLockState
        );
        $crate::reexports::client::delegate_dispatch!($(@< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $ty:
            [
                $crate::reexports::protocols::ext::session_lock::v1::client::ext_session_lock_surface_v1::ExtSessionLockSurfaceV1: $crate::session_lock::SessionLockSurfaceData
            ] => $crate::session_lock::SessionLockState
        );
    };
}