Skip to main content

smithay_client_toolkit/shell/xdg/
dialog.rs

1use crate::reexports::client::{protocol::wl_compositor::WlCompositor, Proxy, QueueHandle};
2use crate::reexports::client::{protocol::wl_surface, Connection, Dispatch};
3use crate::reexports::protocols::xdg::decoration::zv1::client::zxdg_decoration_manager_v1::ZxdgDecorationManagerV1;
4use crate::shell::xdg::window::inner::{
5    determine_decoration_mode, determine_window_state, determine_wm_capabilities, WindowInner,
6};
7use crate::shell::xdg::window::WindowConfigure;
8use crate::shell::xdg::Dispatch2;
9use crate::shell::xdg::WindowDecorations;
10use crate::shell::WaylandSurface;
11use crate::{
12    compositor::{Surface, SurfaceData},
13    globals::ProvidesBoundGlobal,
14};
15use crate::{error::GlobalError, shell::xdg::XdgShellSurface};
16use std::num::NonZeroU32;
17use std::sync::{Arc, Mutex, Weak};
18use wayland_protocols::xdg::{
19    decoration::zv1::client::zxdg_toplevel_decoration_v1,
20    dialog::v1::client::xdg_dialog_v1::XdgDialogV1, shell::client::xdg_wm_base,
21};
22use wayland_protocols::xdg::{dialog::v1::client::xdg_dialog_v1, shell::client::xdg_surface};
23use wayland_protocols::xdg::{dialog::v1::client::xdg_wm_dialog_v1, shell::client::xdg_toplevel};
24
25/// Handler for toplevel operations on a [`Dialog`]
26pub trait DialogHandler: Sized {
27    /// Request to close a dialog.
28    ///
29    /// This request does not destroy the dialog. You must drop all [`Dialog`] handles to destroy the dialog.
30    /// This request may be sent either by the compositor or by some other mechanism (such as client side decorations).
31    fn request_close(&mut self, conn: &Connection, qh: &QueueHandle<Self>, window: &Dialog);
32
33    /// Apply a suggested surface change.
34    ///
35    /// When this function is called, the compositor is requesting the window's size or state to change.
36    ///
37    /// Internally this function is called when the underlying `xdg_surface` is configured. Any extension
38    /// protocols that interface with xdg-shell are able to be notified that the surface's configure sequence
39    /// is complete by using this function.
40    ///
41    /// # Double buffering
42    ///
43    /// Configure events in Wayland are considered to be double buffered and the state of the window does not
44    /// change until committed.
45    fn configure(
46        &mut self,
47        conn: &Connection,
48        qh: &QueueHandle<Self>,
49        window: &Dialog,
50        configure: WindowConfigure,
51        serial: u32,
52    );
53}
54
55#[derive(Debug, Clone)]
56pub struct Dialog {
57    inner: Arc<DialogInner>,
58}
59
60#[derive(Debug)]
61pub struct DialogData(pub(crate) Weak<DialogInner>);
62
63#[derive(Debug)]
64pub(crate) struct DialogInner {
65    pub xdg_dialog: XdgDialogV1,
66    pub window: WindowInner,
67}
68
69impl Dialog {
70    pub fn new<D, GLOBAL>(
71        parent: &xdg_toplevel::XdgToplevel,
72        qh: &QueueHandle<D>,
73        // TODO: is 6 correct?
74        compositor: &impl ProvidesBoundGlobal<WlCompositor, 6>,
75        wm: &GLOBAL,
76        decoration_manager: Option<&ZxdgDecorationManagerV1>,
77        decorations: WindowDecorations,
78    ) -> Result<Self, GlobalError>
79    where
80        D: Dispatch<wl_surface::WlSurface, SurfaceData<()>>
81            + Dispatch<xdg_surface::XdgSurface, DialogData>
82            + Dispatch<xdg_dialog_v1::XdgDialogV1, DialogData>
83            + Dispatch<xdg_toplevel::XdgToplevel, DialogData>
84            + Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, DialogData>
85            + 'static,
86        GLOBAL: ProvidesBoundGlobal<xdg_wm_dialog_v1::XdgWmDialogV1, 1>
87            + ProvidesBoundGlobal<xdg_wm_base::XdgWmBase, 5>,
88    {
89        let surface = Surface::new(compositor, qh)?;
90        let dialog = Self::from_surface(surface, parent, qh, wm, decoration_manager, decorations)?;
91        dialog.wl_surface().commit();
92        Ok(dialog)
93    }
94
95    pub fn from_surface<D, GLOBAL>(
96        surface: impl Into<Surface>,
97        parent: &xdg_toplevel::XdgToplevel,
98        qh: &QueueHandle<D>,
99        wm_base: &GLOBAL,
100        decoration_manager: Option<&ZxdgDecorationManagerV1>,
101        decorations: WindowDecorations,
102    ) -> Result<Self, GlobalError>
103    where
104        D: Dispatch<xdg_surface::XdgSurface, DialogData>
105            + Dispatch<xdg_dialog_v1::XdgDialogV1, DialogData>
106            + Dispatch<xdg_toplevel::XdgToplevel, DialogData>
107            + Dispatch<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, DialogData>
108            + 'static,
109        GLOBAL: ProvidesBoundGlobal<xdg_wm_dialog_v1::XdgWmDialogV1, 1>
110            + ProvidesBoundGlobal<xdg_wm_base::XdgWmBase, 5>,
111    {
112        let surface = surface.into();
113        let wm_dialog: xdg_wm_dialog_v1::XdgWmDialogV1 = wm_base.bound_global()?;
114        let wm_base: xdg_wm_base::XdgWmBase = wm_base.bound_global()?;
115
116        // Freeze the queue during the creation of the Arc to avoid a race between events on the
117        // new objects being processed and the Weak in the DialogData becoming usable.
118        let freeze = qh.freeze();
119
120        let inner = Arc::new_cyclic(|weak| {
121            let xdg_surface =
122                wm_base.get_xdg_surface(surface.wl_surface(), qh, DialogData(weak.clone()));
123            let surface = XdgShellSurface { surface, xdg_surface };
124            let xdg_toplevel = surface.xdg_surface.get_toplevel(qh, DialogData(weak.clone()));
125            xdg_toplevel.set_parent(Some(parent));
126            let xdg_dialog = wm_dialog.get_xdg_dialog(&xdg_toplevel, qh, DialogData(weak.clone()));
127
128            let toplevel_decoration = crate::shell::xdg::XdgShell::toplevel_decoration(
129                decoration_manager,
130                &xdg_toplevel,
131                decorations,
132                DialogData(weak.clone()),
133                qh,
134            );
135
136            DialogInner {
137                xdg_dialog,
138                window: WindowInner {
139                    xdg_surface: surface,
140                    xdg_toplevel,
141                    toplevel_decoration,
142                    pending_configure: Mutex::new(Default::default()),
143                },
144            }
145        });
146        drop(freeze);
147        let dialog = Dialog { inner };
148        Ok(dialog)
149    }
150
151    pub fn from_xdg_toplevel(toplevel: &xdg_toplevel::XdgToplevel) -> Option<Dialog> {
152        toplevel.data::<DialogData>().and_then(|data| data.dialog())
153    }
154
155    pub fn from_xdg_surface(surface: &xdg_surface::XdgSurface) -> Option<Dialog> {
156        surface.data::<DialogData>().and_then(|data| data.dialog())
157    }
158
159    pub fn from_toplevel_decoration(
160        decoration: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
161    ) -> Option<Dialog> {
162        decoration.data::<DialogData>().and_then(|data| data.dialog())
163    }
164
165    pub fn xdg_dialog(&self) -> &XdgDialogV1 {
166        &self.inner.xdg_dialog
167    }
168
169    pub fn xdg_shell_surface(&self) -> &XdgShellSurface {
170        &self.inner.window.xdg_surface
171    }
172
173    pub fn xdg_toplevel(&self) -> &xdg_toplevel::XdgToplevel {
174        &self.inner.window.xdg_toplevel
175    }
176
177    pub fn xdg_surface(&self) -> &xdg_surface::XdgSurface {
178        self.inner.window.xdg_surface.xdg_surface()
179    }
180
181    pub fn wl_surface(&self) -> &wl_surface::WlSurface {
182        self.inner.window.xdg_surface.wl_surface()
183    }
184
185    pub fn set_modal(&self, modal: bool) {
186        if modal {
187            self.inner.xdg_dialog.set_modal();
188        } else {
189            self.inner.xdg_dialog.unset_modal();
190        }
191    }
192}
193
194impl WaylandSurface for Dialog {
195    fn wl_surface(&self) -> &wl_surface::WlSurface {
196        self.wl_surface()
197    }
198}
199
200impl PartialEq for Dialog {
201    fn eq(&self, other: &Self) -> bool {
202        Arc::ptr_eq(&self.inner, &other.inner)
203    }
204}
205
206impl DialogData {
207    /// Get a new handle to the Dialog
208    ///
209    /// This returns `None` if the dialog has been destroyed.
210    pub fn dialog(&self) -> Option<Dialog> {
211        let inner = self.0.upgrade()?;
212        Some(Dialog { inner })
213    }
214}
215
216impl Drop for DialogInner {
217    fn drop(&mut self) {
218        self.xdg_dialog.destroy();
219    }
220}
221
222impl<D: DialogHandler> Dispatch2<xdg_surface::XdgSurface, D> for DialogData {
223    fn event(
224        &self,
225        data: &mut D,
226        xdg_surface: &xdg_surface::XdgSurface,
227        event: <xdg_surface::XdgSurface as wayland_client::Proxy>::Event,
228        conn: &Connection,
229        qhandle: &QueueHandle<D>,
230    ) {
231        if let Some(dialog) = Dialog::from_xdg_surface(xdg_surface) {
232            match event {
233                xdg_surface::Event::Configure { serial } => {
234                    xdg_surface.ack_configure(serial);
235
236                    let configure = dialog.inner.window.pending_configure.lock().unwrap().clone();
237                    DialogHandler::configure(data, conn, qhandle, &dialog, configure, serial)
238                }
239                _ => unreachable!(),
240            }
241        }
242    }
243}
244
245impl<D> Dispatch2<XdgDialogV1, D> for DialogData {
246    fn event(
247        &self,
248        _state: &mut D,
249        _proxy: &XdgDialogV1,
250        _event: <XdgDialogV1 as wayland_client::Proxy>::Event,
251        _conn: &Connection,
252        _qhandle: &QueueHandle<D>,
253    ) {
254    }
255}
256
257impl<D: DialogHandler> Dispatch2<xdg_toplevel::XdgToplevel, D> for DialogData {
258    fn event(
259        &self,
260        data: &mut D,
261        toplevel: &xdg_toplevel::XdgToplevel,
262        event: <xdg_toplevel::XdgToplevel as wayland_client::Proxy>::Event,
263        conn: &Connection,
264        qhandle: &QueueHandle<D>,
265    ) {
266        let Some(dialog) = Dialog::from_xdg_toplevel(toplevel) else {
267            return;
268        };
269
270        match event {
271            xdg_toplevel::Event::Configure { width, height, states } => {
272                let new_state = determine_window_state(&states);
273
274                // XXX we do explicit convertion and sanity checking because compositor
275                // could pass negative values which we should ignore all together.
276                let width = u32::try_from(width).ok().and_then(NonZeroU32::new);
277                let height = u32::try_from(height).ok().and_then(NonZeroU32::new);
278
279                let pending_configure = &mut dialog.inner.window.pending_configure.lock().unwrap();
280                pending_configure.new_size = (width, height);
281                pending_configure.state = new_state;
282            }
283            xdg_toplevel::Event::Close => {
284                data.request_close(conn, qhandle, &dialog);
285            }
286
287            xdg_toplevel::Event::ConfigureBounds { width, height } => {
288                let pending_configure = &mut dialog.inner.window.pending_configure.lock().unwrap();
289                if width == 0 && height == 0 {
290                    pending_configure.suggested_bounds = None;
291                } else {
292                    pending_configure.suggested_bounds = Some((width as u32, height as u32));
293                }
294            }
295            xdg_toplevel::Event::WmCapabilities { capabilities } => {
296                let pending_configure = &mut dialog.inner.window.pending_configure.lock().unwrap();
297                pending_configure.capabilities = determine_wm_capabilities(&capabilities)
298            }
299            _ => unreachable!(),
300        }
301    }
302}
303
304impl<D> Dispatch2<zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1, D> for DialogData
305where
306    D: DialogHandler,
307{
308    fn event(
309        &self,
310        _: &mut D,
311        decoration: &zxdg_toplevel_decoration_v1::ZxdgToplevelDecorationV1,
312        event: zxdg_toplevel_decoration_v1::Event,
313        _: &Connection,
314        _: &QueueHandle<D>,
315    ) {
316        if let Some(dialog) = Dialog::from_toplevel_decoration(decoration) {
317            match event {
318                zxdg_toplevel_decoration_v1::Event::Configure { mode } => match mode {
319                    wayland_client::WEnum::Value(mode) => {
320                        let mode = determine_decoration_mode(mode);
321                        dialog.inner.window.pending_configure.lock().unwrap().decoration_mode =
322                            mode;
323                    }
324
325                    wayland_client::WEnum::Unknown(unknown) => {
326                        log::error!(target: "sctk", "unknown decoration mode 0x{:x}", unknown);
327                    }
328                },
329
330                _ => unreachable!(),
331            }
332        }
333    }
334}