druid-shell 0.8.3

Platform abstracting application shell used for Druid toolkit.
Documentation
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
// Copyright 2022 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use wayland_client as wlc;
use wayland_protocols::wlr::unstable::layer_shell::v1::client as layershell;
use wayland_protocols::xdg_shell::client::xdg_surface;

use crate::kurbo;
use crate::window;

use super::super::error;
use super::super::outputs;
use super::surface;
use super::Compositor;
use super::CompositorHandle;
use super::Handle;
use super::Outputs;
use super::Popup;

#[derive(Default)]
struct Output {
    preferred: Option<String>,
    current: Option<outputs::Meta>,
}

struct Inner {
    config: Config,
    wl_surface: std::cell::RefCell<surface::Surface>,
    ls_surface:
        std::cell::RefCell<wlc::Main<layershell::zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>>,
    requires_initialization: std::cell::RefCell<bool>,
    available: std::cell::RefCell<bool>,
    output: std::cell::RefCell<Output>,
}

impl Inner {
    fn popup<'a>(
        &self,
        surface: &'a wlc::Main<xdg_surface::XdgSurface>,
        pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>,
    ) -> wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup> {
        let popup = surface.get_popup(None, pos);
        self.ls_surface.borrow().get_popup(&popup);
        popup
    }
}

impl Popup for Inner {
    fn surface<'a>(
        &self,
        surface: &'a wlc::Main<xdg_surface::XdgSurface>,
        pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>,
    ) -> Result<wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup>, error::Error>
    {
        Ok(self.popup(surface, pos))
    }
}

impl Drop for Inner {
    fn drop(&mut self) {
        self.ls_surface.borrow().destroy();
    }
}

impl From<Inner> for std::sync::Arc<surface::Data> {
    fn from(s: Inner) -> std::sync::Arc<surface::Data> {
        std::sync::Arc::<surface::Data>::from(s.wl_surface.borrow().clone())
    }
}

#[derive(Clone, Debug)]
pub struct Margin {
    top: i32,
    right: i32,
    bottom: i32,
    left: i32,
}

impl Default for Margin {
    fn default() -> Self {
        Margin::from((0, 0, 0, 0))
    }
}

impl Margin {
    pub fn new(m: impl Into<Margin>) -> Self {
        m.into()
    }

    pub fn uniform(m: i32) -> Self {
        Margin::from((m, m, m, m))
    }
}

impl From<(i32, i32, i32, i32)> for Margin {
    fn from(margins: (i32, i32, i32, i32)) -> Self {
        Self {
            top: margins.0,
            left: margins.1,
            bottom: margins.2,
            right: margins.3,
        }
    }
}

impl From<i32> for Margin {
    fn from(m: i32) -> Self {
        Margin::from((m, m, m, m))
    }
}

impl From<(i32, i32)> for Margin {
    fn from(m: (i32, i32)) -> Self {
        Margin::from((m.0, m.1, m.0, m.1))
    }
}

#[derive(Clone)]
pub struct Config {
    pub initial_size: kurbo::Size,
    pub layer: layershell::zwlr_layer_shell_v1::Layer,
    pub keyboard_interactivity: layershell::zwlr_layer_surface_v1::KeyboardInteractivity,
    pub anchor: layershell::zwlr_layer_surface_v1::Anchor,
    pub exclusive_zone: i32,
    pub margin: Margin,
    pub namespace: &'static str,
    pub app_id: &'static str,
}

impl Config {
    pub fn keyboard_interactivity(
        mut self,
        mode: layershell::zwlr_layer_surface_v1::KeyboardInteractivity,
    ) -> Self {
        self.keyboard_interactivity = mode;
        self
    }

    pub fn layer(mut self, layer: layershell::zwlr_layer_shell_v1::Layer) -> Self {
        self.layer = layer;
        self
    }

    pub fn anchor(mut self, anchor: layershell::zwlr_layer_surface_v1::Anchor) -> Self {
        self.anchor = anchor;
        self
    }

    pub fn margin(mut self, m: impl Into<Margin>) -> Self {
        self.margin = m.into();
        self
    }

    fn apply(&self, surface: &Surface) {
        let ls = surface.inner.ls_surface.borrow();
        ls.set_exclusive_zone(self.exclusive_zone);
        ls.set_anchor(self.anchor);
        ls.set_keyboard_interactivity(self.keyboard_interactivity);
        ls.set_margin(
            self.margin.top,
            self.margin.right,
            self.margin.bottom,
            self.margin.left,
        );
        ls.set_size(
            self.initial_size.width as u32,
            self.initial_size.height as u32,
        );
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            layer: layershell::zwlr_layer_shell_v1::Layer::Overlay,
            initial_size: kurbo::Size::ZERO,
            keyboard_interactivity: layershell::zwlr_layer_surface_v1::KeyboardInteractivity::None,
            anchor: layershell::zwlr_layer_surface_v1::Anchor::all(),
            exclusive_zone: 0,
            margin: Margin::default(),
            namespace: "druid",
            app_id: "",
        }
    }
}

#[derive(Clone)]
pub struct Surface {
    inner: std::sync::Arc<Inner>,
}

impl Surface {
    pub fn new(
        c: impl Into<CompositorHandle>,
        handler: Box<dyn window::WinHandler>,
        config: Config,
    ) -> Self {
        let compositor = CompositorHandle::new(c);
        let wl_surface = surface::Surface::new(compositor.clone(), handler, kurbo::Size::ZERO);
        let ls_surface = compositor.zwlr_layershell_v1().unwrap().get_layer_surface(
            &wl_surface.inner.wl_surface.borrow(),
            None,
            config.layer,
            config.namespace.to_string(),
        );

        let handle = Self {
            inner: std::sync::Arc::new(Inner {
                config,
                wl_surface: std::cell::RefCell::new(wl_surface),
                ls_surface: std::cell::RefCell::new(ls_surface),
                requires_initialization: std::cell::RefCell::new(true),
                available: std::cell::RefCell::new(false),
                output: std::cell::RefCell::new(Default::default()),
            }),
        };

        Surface::initialize(&handle);
        handle
    }

    pub(crate) fn with_handler<T, F: FnOnce(&mut dyn window::WinHandler) -> T>(
        &self,
        f: F,
    ) -> Option<T> {
        std::sync::Arc::<surface::Data>::from(self).with_handler(f)
    }

    fn initialize(handle: &Surface) {
        handle.inner.requires_initialization.replace(false);
        tracing::debug!("attempting to initialize layershell");

        handle.inner.ls_surface.borrow().quick_assign({
            let handle = handle.clone();
            move |a1, event, a2| {
                tracing::debug!("consuming event {:?} {:?} {:?}", a1, event, a2);
                Surface::consume_layershell_event(&handle, &a1, &event, &a2);
            }
        });

        handle.inner.config.apply(handle);
        handle.inner.wl_surface.borrow().commit();
    }

    fn consume_layershell_event(
        handle: &Surface,
        a1: &wlc::Main<layershell::zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>,
        event: &layershell::zwlr_layer_surface_v1::Event,
        data: &wlc::DispatchData,
    ) {
        match *event {
            layershell::zwlr_layer_surface_v1::Event::Configure {
                serial,
                width,
                height,
            } => {
                let mut dim = handle.inner.config.initial_size;
                // compositor is deferring to the client for determining the size
                // when values are zero.
                if width != 0 && height != 0 {
                    dim = kurbo::Size::new(width as f64, height as f64);
                }

                let ls = handle.inner.ls_surface.borrow();
                ls.ack_configure(serial);
                ls.set_size(dim.width as u32, dim.height as u32);
                handle.inner.wl_surface.borrow().update_dimensions(dim);
                handle.inner.wl_surface.borrow().request_paint();
                handle.inner.available.replace(true);
            }
            layershell::zwlr_layer_surface_v1::Event::Closed => {
                if let Some(o) = handle.inner.wl_surface.borrow().output() {
                    handle
                        .inner
                        .output
                        .borrow_mut()
                        .preferred
                        .get_or_insert(o.name.clone());
                    handle.inner.output.borrow_mut().current.get_or_insert(o);
                }
                handle.inner.ls_surface.borrow().destroy();
                handle.inner.available.replace(false);
                handle.inner.requires_initialization.replace(true);
            }
            _ => tracing::warn!("unimplemented event {:?} {:?} {:?}", a1, event, data),
        }
    }
}

impl Outputs for Surface {
    fn removed(&self, o: &outputs::Meta) {
        self.inner.wl_surface.borrow().removed(o);
        self.inner.output.borrow_mut().current.take();
    }

    fn inserted(&self, o: &outputs::Meta) {
        let old = String::from(
            self.inner
                .output
                .borrow()
                .preferred
                .as_ref()
                .map_or("", |name| name),
        );

        let reinitialize = *self.inner.requires_initialization.borrow();
        let reinitialize = old == o.name || reinitialize;
        if !reinitialize {
            tracing::debug!(
                "skipping reinitialization output for layershell {:?} {:?} == {:?} || {:?} -> {:?}",
                o.id(),
                o.name,
                old,
                *self.inner.requires_initialization.borrow(),
                reinitialize,
            );
            return;
        }

        tracing::debug!(
            "reinitializing output for layershell {:?} {:?} == {:?} || {:?} -> {:?}",
            o.id(),
            o.name,
            old,
            *self.inner.requires_initialization.borrow(),
            reinitialize,
        );

        let sdata = self.inner.wl_surface.borrow().inner.clone();
        self.inner
            .wl_surface
            .replace(surface::Surface::replace(&sdata));
        let sdata = self.inner.wl_surface.borrow().inner.clone();
        let replacedlayershell = self.inner.ls_surface.replace(
            sdata
                .compositor
                .zwlr_layershell_v1()
                .unwrap()
                .get_layer_surface(
                    &self.inner.wl_surface.borrow().inner.wl_surface.borrow(),
                    o.output.as_ref(),
                    self.inner.config.layer,
                    self.inner.config.namespace.to_string(),
                ),
        );

        Surface::initialize(self);

        replacedlayershell.destroy();
    }
}

impl Popup for Surface {
    fn surface<'a>(
        &self,
        popup: &'a wlc::Main<xdg_surface::XdgSurface>,
        pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>,
    ) -> Result<wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup>, error::Error>
    {
        Ok(self.inner.popup(popup, pos))
    }
}

impl Handle for Surface {
    fn get_size(&self) -> kurbo::Size {
        return self.inner.wl_surface.borrow().get_size();
    }

    fn set_size(&self, dim: kurbo::Size) {
        return self.inner.wl_surface.borrow().set_size(dim);
    }

    fn request_anim_frame(&self) {
        if *self.inner.available.borrow() {
            self.inner.wl_surface.borrow().request_anim_frame()
        }
    }

    fn invalidate(&self) {
        return self.inner.wl_surface.borrow().invalidate();
    }

    fn invalidate_rect(&self, rect: kurbo::Rect) {
        return self.inner.wl_surface.borrow().invalidate_rect(rect);
    }

    fn remove_text_field(&self, token: crate::TextFieldToken) {
        return self.inner.wl_surface.borrow().remove_text_field(token);
    }

    fn set_focused_text_field(&self, active_field: Option<crate::TextFieldToken>) {
        return self
            .inner
            .wl_surface
            .borrow()
            .set_focused_text_field(active_field);
    }

    fn set_input_region(&self, region: Option<crate::Region>) {
        self.inner.wl_surface.borrow().set_input_region(region);
    }

    fn get_idle_handle(&self) -> super::idle::Handle {
        return self.inner.wl_surface.borrow().get_idle_handle();
    }

    fn get_scale(&self) -> crate::Scale {
        return self.inner.wl_surface.borrow().get_scale();
    }

    fn run_idle(&self) {
        if *self.inner.available.borrow() {
            self.inner.wl_surface.borrow().run_idle();
        }
    }

    fn release(&self) {
        self.inner.wl_surface.borrow().release()
    }

    fn data(&self) -> Option<std::sync::Arc<surface::Data>> {
        self.inner.wl_surface.borrow().data()
    }
}

impl From<&Surface> for std::sync::Arc<surface::Data> {
    fn from(s: &Surface) -> std::sync::Arc<surface::Data> {
        std::sync::Arc::<surface::Data>::from(s.inner.wl_surface.borrow().clone())
    }
}

impl From<Surface> for std::sync::Arc<surface::Data> {
    fn from(s: Surface) -> std::sync::Arc<surface::Data> {
        std::sync::Arc::<surface::Data>::from(s.inner.wl_surface.borrow().clone())
    }
}

impl From<Surface> for Box<dyn Handle> {
    fn from(s: Surface) -> Box<dyn Handle> {
        Box::new(s) as Box<dyn Handle>
    }
}

impl From<Surface> for Box<dyn Outputs> {
    fn from(s: Surface) -> Box<dyn Outputs> {
        Box::new(s) as Box<dyn Outputs>
    }
}

impl From<Surface> for Box<dyn Popup> {
    fn from(s: Surface) -> Self {
        Box::new(s) as Box<dyn Popup>
    }
}