libwaysip 0.6.1

Wayland native (zwlr_layer_shell) area selection client lib
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
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
512
513
514
515
516
use std::{cell::OnceCell, os::fd::AsFd};

use wayland_client::{
    QueueHandle,
    protocol::{
        wl_buffer::WlBuffer,
        wl_output::WlOutput,
        wl_shm::{self, WlShm},
        wl_surface::WlSurface,
    },
};
use wayland_cursor::CursorImageBuffer;
use wayland_protocols::{
    wp::cursor_shape::v1::client::wp_cursor_shape_manager_v1::WpCursorShapeManagerV1,
    xdg::xdg_output::zv1::client::zxdg_output_v1,
};
use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_surface_v1::ZwlrLayerSurfaceV1;

use crate::{
    Position, Size, Style,
    error::BoxInfoError,
    render::{self, UiInit},
};

/// You are allow to choose three actions of waysip, include area selection, point selection, and
/// select screen
#[derive(Debug, Clone, Copy, Default)]
pub enum SelectionType {
    #[default]
    Area,
    Point,
    Screen,
    PredefinedBoxes,
    /// Combined mode: single click behaves like output selection, drag behaves like dimensions
    DimensionsOrOutput,
}

#[derive(Debug, Clone)]
pub struct ZXdgOutputInfo {
    pub zxdg_output: zxdg_output_v1::ZxdgOutputV1,
    pub size: Size,
    pub start_position: Position,
    pub name: String,
    pub description: String,
}

impl ZXdgOutputInfo {
    pub fn new(zxdgoutput: zxdg_output_v1::ZxdgOutputV1) -> Self {
        Self {
            zxdg_output: zxdgoutput,
            size: Size {
                width: 0,
                height: 0,
            },
            start_position: Position { x: 0, y: 0 },
            name: "".to_string(),
            description: "".to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct WlOutputInfo {
    pub output: WlOutput,
    pub description: String,
    pub name: String,
    pub size: Size,
    pub xdg_output_info: OnceCell<ZXdgOutputInfo>,
}

impl WlOutputInfo {
    pub(crate) fn xdg_output_info_mut(&mut self) -> &mut ZXdgOutputInfo {
        self.xdg_output_info.get_mut().expect("should inited")
    }
    pub(crate) fn xdg_output_info(&self) -> &ZXdgOutputInfo {
        self.xdg_output_info.get().expect("should inited")
    }
    pub(crate) fn zxdg_output(&self) -> &zxdg_output_v1::ZxdgOutputV1 {
        &self
            .xdg_output_info
            .get()
            .expect("should inited")
            .zxdg_output
    }
    pub fn new(output: WlOutput) -> Self {
        Self {
            output,
            description: "".to_string(),
            name: "".to_string(),
            size: Size {
                width: 0,
                height: 0,
            },
            xdg_output_info: OnceCell::new(),
        }
    }
    pub fn get_screen_info(&self) -> ScreenInfo {
        let xdg_output_info = self.xdg_output_info();
        ScreenInfo {
            name: self.name.clone(),
            description: self.description.clone(),
            position: xdg_output_info.start_position,
            output_size: self.size,
            wl_output: self.output.clone(),
            screen_size: xdg_output_info.size,
        }
    }
    pub fn get_output(&self) -> &WlOutput {
        &self.output
    }

    pub fn get_size(&self) -> Size {
        self.size
    }

    pub fn get_name(&self) -> &str {
        &self.name
    }

    pub fn get_description(&self) -> &str {
        &self.description
    }
}

/// tell the screen info, include description, size and the name. and include the current wloutput
/// binded by the screen
#[derive(Debug)]
pub struct ScreenInfo {
    pub position: Position,
    pub screen_size: Size,
    pub wl_output: WlOutput,
    pub output_size: Size,
    pub name: String,
    pub description: String,
}

impl ScreenInfo {
    /// get the binding output
    pub fn get_wloutput(&self) -> &WlOutput {
        &self.wl_output
    }

    /// get the logical size of the wloutput
    pub fn get_wloutput_size(&self) -> Size {
        self.output_size
    }

    /// get the logical size of the screen
    pub fn get_size(&self) -> Size {
        self.screen_size
    }

    /// get the name of the screen
    pub fn get_name(&self) -> &str {
        &self.name
    }

    /// get the description of the screen
    pub fn get_description(&self) -> &str {
        &self.description
    }

    /// get the logical position of the screen
    pub fn get_position(&self) -> Position {
        self.position
    }
}

#[derive(Debug)]
pub struct WaysipState {
    pub wloutput_infos: Vec<WlOutputInfo>,
    pub running: bool,
    pub selection_type: SelectionType,
    pub wl_surfaces: Vec<LayerSurfaceInfo>,
    pub current_pos: Position<f64>,
    pub start_pos: Option<Position<f64>>,
    pub end_pos: Option<Position<f64>>,
    pub current_screen: usize,
    pub cursor_manager: Option<WpCursorShapeManagerV1>,
    pub shm: Option<WlShm>,
    pub qh: Option<QueueHandle<Self>>,
    pub predefined_boxes: Option<Vec<BoxInfo>>,
    pub aspect_ratio: Option<(f64, f64)>,
    pub last_redraw: std::time::Instant,
    /// Tracks actual effective selection type for DimensionsOrOutput mode
    pub effective_selection_type: Option<SelectionType>,
    /// Time when mouse was pressed down
    pub mouse_press_time: Option<std::time::Instant>,
}

impl WaysipState {
    pub fn new(selection_type: SelectionType) -> Self {
        WaysipState {
            wloutput_infos: Vec::new(),
            running: true,
            selection_type,
            wl_surfaces: Vec::new(),
            current_pos: Position { x: 0., y: 0. },
            start_pos: None,
            end_pos: None,
            current_screen: 0,
            cursor_manager: None,
            qh: None,
            shm: None,
            predefined_boxes: None,
            aspect_ratio: None,
            last_redraw: std::time::Instant::now() - std::time::Duration::from_secs(1),
            effective_selection_type: None,
            mouse_press_time: None,
        }
    }

    pub fn is_area(&self) -> bool {
        matches!(self.selection_type, SelectionType::Area)
    }

    pub fn is_screen(&self) -> bool {
        matches!(self.selection_type, SelectionType::Screen)
    }

    pub fn is_predefined_boxes(&self) -> bool {
        matches!(self.selection_type, SelectionType::PredefinedBoxes)
    }

    pub fn is_dimensions_or_output(&self) -> bool {
        matches!(self.selection_type, SelectionType::DimensionsOrOutput)
    }

    /// Get the effective selection type, considering DimensionsOrOutput mode
    pub fn effective_selection_type(&self) -> SelectionType {
        self.effective_selection_type.unwrap_or(self.selection_type)
    }

    /// Check if we should behave like area selection (for effective type)
    pub fn is_effective_area(&self) -> bool {
        matches!(self.effective_selection_type(), SelectionType::Area)
    }

    /// Check if we should behave like screen selection (for effective type)
    pub fn is_effective_screen(&self) -> bool {
        matches!(self.effective_selection_type(), SelectionType::Screen)
    }

    pub fn set_boxes(&mut self, boxes: Vec<BoxInfo>) {
        self.predefined_boxes = Some(boxes);
    }

    pub fn ensure_buffer(&mut self, surface: &ZwlrLayerSurfaceV1, (width, height): (u32, u32)) {
        let Some(surface_info) = self
            .wl_surfaces
            .iter_mut()
            .find(|info| info.layer == *surface)
        else {
            return;
        };
        if surface_info.buffer_busy {
            return;
        }
        let mut file = tempfile::tempfile().unwrap();
        let qh = self.qh.as_ref().unwrap();
        let width = width as i32;
        let height = height as i32;
        let UiInit {
            context: cairo_t,
            stride,
        } = render::draw_ui(
            &mut file,
            (width, width),
            surface_info.style.background_color,
        );
        let pool = self
            .shm
            .as_ref()
            .unwrap()
            .create_pool(file.as_fd(), width * height * 4, qh, ());

        let buffer = pool.create_buffer(0, width, height, stride, wl_shm::Format::Argb8888, qh, ());

        let old_buffer = std::mem::replace(&mut surface_info.buffer, buffer);
        let old_cairo_t = std::mem::replace(&mut surface_info.cairo_t, cairo_t);
        old_buffer.destroy();
        drop(old_cairo_t);

        surface_info.buffer_busy = true;
        surface_info.inited = false;
    }

    pub fn ensure_init(&mut self, surface: &ZwlrLayerSurfaceV1) {
        let Some(surface_info) = self
            .wl_surfaces
            .iter_mut()
            .find(|info| info.layer == *surface)
        else {
            return;
        };
        if surface_info.inited {
            return;
        }
        surface_info.init_commit();
        surface_info.inited = true;
    }

    pub fn commit(&self) {
        let qh = self.qh.as_ref().unwrap();
        for (idx, surface) in self.wl_surfaces.iter().enumerate() {
            surface.wl_surface.frame(qh, idx);
            surface.wl_surface.commit();
        }
    }

    pub fn redraw_current_surface(&self) {
        let surface_info = &self.wl_surfaces[self.current_screen];
        self.redraw(&surface_info.layer);
    }

    pub fn redraw_all_surface(&self) {
        for surface_info in &self.wl_surfaces {
            self.redraw(&surface_info.layer);
        }
    }

    pub fn redraw(&self, surface: &ZwlrLayerSurfaceV1) {
        let Some(screen_index) = self
            .wl_surfaces
            .iter()
            .position(|info| info.layer == *surface)
        else {
            return;
        };

        let info = &self.wl_surfaces[screen_index];
        let ZXdgOutputInfo {
            size,
            start_position,
            name,
            description,
            ..
        } = self.wloutput_infos[screen_index].xdg_output_info();

        if self.is_screen()
            || self.is_effective_screen()
            // NOTE: if is DimensionsOrOutput, and no end_pos, show like window select,
            // else dimension select
            || (self.is_dimensions_or_output() && self.start_pos.is_none())
        {
            for (idx, info) in self
                .wl_surfaces
                .iter()
                .enumerate()
                .filter(|(_, i)| i.inited)
            {
                let ZXdgOutputInfo {
                    size,
                    start_position,
                    ..
                } = &self.wloutput_infos[idx].xdg_output_info();
                info.redraw_select_screen(
                    idx == self.current_screen,
                    *size,
                    *start_position,
                    name,
                    description,
                );
            }
        } else {
            if self.start_pos.is_none() {
                return;
            }
            info.redraw(
                self.start_pos.unwrap(),
                self.end_pos,
                *start_position,
                *size,
                self.is_area() || self.is_effective_area() || self.is_dimensions_or_output(),
                self.predefined_boxes.as_ref(),
            );
        }
    }

    pub fn area_info(&self) -> Option<AreaInfo> {
        if self.start_pos.is_none() || self.end_pos.is_none() {
            return None;
        }
        let Position {
            x: start_x,
            y: start_y,
        } = self.start_pos.unwrap();
        let Position { x: end_x, y: end_y } = self.end_pos.unwrap();
        let output = self.wloutput_infos[self.current_screen].clone();
        Some(AreaInfo {
            box_info: BoxInfo {
                start_x,
                start_y,
                end_x,
                end_y,
            },
            screen_info: output.get_screen_info(),
            effective_selection_type: self.effective_selection_type,
        })
    }
}

#[derive(Debug)]
pub struct LayerSurfaceInfo {
    pub layer: ZwlrLayerSurfaceV1,
    pub wl_surface: WlSurface,
    pub cursor_surface: WlSurface,
    pub buffer: WlBuffer,
    pub cursor_buffer: Option<CursorImageBuffer>,
    pub cairo_t: cairo::Context,
    pub stride: i32,
    pub inited: bool,
    pub buffer_busy: bool,
    pub style: Style,
    pub pango_layout: std::cell::OnceCell<pango::Layout>,
    pub font_desc_bold: std::cell::OnceCell<pango::FontDescription>,
    pub font_desc_normal: std::cell::OnceCell<pango::FontDescription>,
}

/// coordinates of box
#[derive(Debug)]
pub struct BoxInfo {
    pub start_x: f64,
    pub start_y: f64,
    pub end_x: f64,
    pub end_y: f64,
}

impl BoxInfo {
    pub fn get_box_from_str(box_string: &str) -> Result<Self, BoxInfoError> {
        let (coords, size) = box_string
            .split_once(' ')
            .ok_or(BoxInfoError::InvalidBoxString(box_string.to_string()))?;
        let (start_x, start_y) = coords
            .split_once(',')
            .ok_or(BoxInfoError::InvalidBoxCoordsString(coords.to_string()))?;
        let (width, height) = size
            .split_once('x')
            .ok_or(BoxInfoError::InvalidBoxSizeString(size.to_string()))?;
        let start_x = start_x
            .parse::<f64>()
            .map_err(BoxInfoError::ParseFloatError)?;
        let start_y = start_y
            .parse::<f64>()
            .map_err(BoxInfoError::ParseFloatError)?;
        let width = width
            .parse::<f64>()
            .map_err(BoxInfoError::ParseFloatError)?;
        let height = height
            .parse::<f64>()
            .map_err(BoxInfoError::ParseFloatError)?;
        Ok(BoxInfo {
            start_x,
            start_y,
            end_x: start_x + width,
            end_y: start_y + height,
        })
    }
}

/// describe the information of the area
#[derive(Debug)]
pub struct AreaInfo {
    pub box_info: BoxInfo,
    pub screen_info: ScreenInfo,
    pub effective_selection_type: Option<SelectionType>,
}

impl AreaInfo {
    /// provide the width of the area as f64
    pub fn width_f64(&self) -> f64 {
        (self.box_info.end_x - self.box_info.start_x).abs()
    }

    pub fn size(&self) -> Size {
        Size {
            width: self.width(),
            height: self.height(),
        }
    }

    pub fn size_f(&self) -> Size<f64> {
        Size {
            width: self.height_f64(),
            height: self.width_f64(),
        }
    }

    /// provide the width of the area as i32
    pub fn width(&self) -> i32 {
        self.width_f64() as i32
    }

    /// provide the height of the area as f64
    pub fn height_f64(&self) -> f64 {
        (self.box_info.end_y - self.box_info.start_y).abs()
    }

    /// provide the width of the area as i32
    pub fn height(&self) -> i32 {
        self.height_f64() as i32
    }

    /// calculate the real start position
    pub fn left_top_point(&self) -> Position {
        Position {
            x: self.box_info.start_x.min(self.box_info.end_x) as i32,
            y: (self.box_info.start_y.min(self.box_info.end_y)) as i32,
        }
    }

    /// you can get the info of the chosen screen
    pub fn selected_screen_info(&self) -> &ScreenInfo {
        &self.screen_info
    }
}