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
//! Types and traits for the xdg shell.

use std::{collections::VecDeque, num::NonZeroU32};

use derivative::Derivative;
use runa_core::provide_any::Demand;
use runa_wayland_protocols::stable::xdg_shell::{
    xdg_surface::v5 as xdg_surface, xdg_toplevel::v5 as xdg_toplevel,
};
use runa_wayland_types::NewId;

use super::Shell;
use crate::utils::geometry::{coords, Extent, Point, Rectangle};

/// Surface layout
///
/// A surface layout is where the surface is positioned on the screen, and its
/// screen space size.
#[derive(Debug, Default, Clone, Copy)]
pub struct Layout {
    /// The position of the surface on the screen.
    pub position: Option<Point<i32, coords::Screen>>,
    /// The size of the surface on the screen.
    pub extent:   Option<Extent<u32, coords::Screen>>,
}

/// Extension of [`super::Shell`] to provide xdg shell specific informations.
pub trait XdgShell: Shell {
    /// Ask the shell to calculate the layout of the given surface.
    fn layout(&self, _key: Self::Token) -> Layout {
        Layout::default()
    }
}

/// The xdg_surface "role"
///
/// This is not technically a role, since the surface can be assigned either a
/// top-level or a popup role after this "role" is attached to it. But we still
/// use the role interface because it's convenient.
#[derive(Debug, Clone)]
pub struct Surface {
    active:                      bool,
    geometry:                    Option<Rectangle<i32, coords::Surface>>,
    pub(crate) pending_geometry: Option<Rectangle<i32, coords::Surface>>,
    /// Pending configure events that haven't been ACK'd, associated with a
    /// oneshot channel which will be notified once the client ACK the
    /// configure event.
    pub(crate) pending_serial:   VecDeque<NonZeroU32>,
    /// The serial in the last ack_configure request.
    pub(crate) last_ack:         Option<NonZeroU32>,
    pub(crate) serial:           NonZeroU32,
    pub(crate) object_id:        u32,
}

impl Surface {
    #[inline]
    pub(crate) fn new(object_id: NewId) -> Self {
        Self {
            active:           false,
            geometry:         None,
            pending_geometry: None,
            pending_serial:   VecDeque::new(),
            last_ack:         None,
            serial:           NonZeroU32::new(1).unwrap(),
            object_id:        object_id.0,
        }
    }

    fn commit<S: XdgShell>(
        &mut self,
        shell: &mut S,
        surface: &super::surface::Surface<S>,
        _object_id: u32,
    ) -> Result<(), &'static str> {
        tracing::debug!("Committing xdg_surface");
        if surface.pending(shell).buffer().is_some() && self.last_ack.is_none() {
            return Err("Cannot attach buffer before the initial configure sequence is completed")
        }
        if self.pending_serial.is_empty() && self.last_ack.is_none() {
            // We haven't sent out the first configure event yet.
            // notify the configure listener which will send out the configure event.
            tracing::debug!("sending initial configure event");
            surface.notify_layout_changed(shell.layout(surface.current_key()));
        }
        self.geometry = self.pending_geometry;

        Ok(())
    }
}

impl<S: Shell> super::surface::Role<S> for Surface {
    fn name(&self) -> &'static str {
        xdg_surface::NAME
    }

    fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
        demand.provide_ref(self);
    }

    fn provide_mut<'a>(&'a mut self, demand: &mut Demand<'a>) {
        demand.provide_mut(self);
    }

    fn deactivate(&mut self, _shell: &mut S) {
        if !self.active {
            return
        }
        self.active = false;
    }

    fn is_active(&self) -> bool {
        self.active
    }
}

#[derive(Default, Debug, Clone, Copy)]
pub(crate) struct TopLevelState {
    pub(crate) min_size: Option<Extent<i32, coords::Surface>>,
    pub(crate) max_size: Option<Extent<i32, coords::Surface>>,
}

/// The xdg_toplevel role
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
pub struct TopLevel {
    pub(crate) base:      Surface,
    is_active:            bool,
    pub(crate) app_id:    Option<String>,
    pub(crate) title:     Option<String>,
    pub(crate) current:   TopLevelState,
    pub(crate) pending:   TopLevelState,
    pub(crate) object_id: u32,
}

impl TopLevel {
    pub(crate) fn new(base: Surface, object_id: u32) -> Self {
        Self {
            base,
            is_active: true,
            app_id: None,
            title: None,
            current: TopLevelState::default(),
            pending: TopLevelState::default(),
            object_id,
        }
    }

    /// Geometry of the surface, as defined by the xdg_toplevel role.
    pub fn geometry(&self) -> Option<Rectangle<i32, coords::Surface>> {
        self.base.geometry
    }
}

impl<S: XdgShell> super::surface::Role<S> for TopLevel {
    fn name(&self) -> &'static str {
        xdg_toplevel::NAME
    }

    fn deactivate(&mut self, _shell: &mut S) {
        if !self.is_active {
            return
        }
        self.is_active = false;
    }

    fn is_active(&self) -> bool {
        self.is_active
    }

    fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
        demand.provide_ref(self).provide_ref(&self.base);
    }

    fn provide_mut<'a>(&'a mut self, demand: &mut Demand<'a>) {
        if let Some(mut receiver) = demand.maybe_provide_mut() {
            receiver.provide(self);
        } else if let Some(mut receiver) = demand.maybe_provide_mut() {
            receiver.provide(&mut self.base);
        }
    }

    fn pre_commit(
        &mut self,
        shell: &mut S,
        surface: &super::surface::Surface<S>,
    ) -> Result<(), &'static str> {
        tracing::debug!("Committing xdg_toplevel");
        let object_id = self.object_id;
        self.current = self.pending;

        self.base.commit(shell, surface, object_id)?;
        Ok(())
    }
}

/// The xdg_popup role
///
/// TODO: not implemented yet
#[derive(Clone, Debug, Copy)]
pub struct Popup;