snappers 0.1.0

Standalone Wayland screenshot tool with a niri-style selection UI
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
use std::f64::consts::{PI, TAU};

use anyhow::Result;
use cairo::{Context, Format, ImageSurface};
use pango::{Alignment, FontDescription};

use crate::geometry::{Point, Rect, Size};
use crate::theme::Theme;

pub const SELECTION_BORDER: i32 = 3;
pub const HANDLE_SIZE: i32 = 6;
const PADDING: i32 = 8;
const RADIUS: i32 = 16;
const BORDER: f64 = 1.0;
const CORNER_RADIUS: f64 = 8.0;
const FONT: &str = "sans 14px";

#[derive(Debug, Clone)]
pub struct PixelSurface {
    pub width: i32,
    pub height: i32,
    pub data: Vec<u8>,
}

#[derive(Debug, Clone)]
pub struct PanelAssets {
    pub show_pointer: PixelSurface,
    pub hide_pointer: PixelSurface,
}

impl PixelSurface {
    pub fn from_rgba_image(image: &image::DynamicImage) -> Self {
        let rgba = image.to_rgba8();
        let (width, height) = rgba.dimensions();
        let mut data = Vec::with_capacity((width * height * 4) as usize);
        for pixel in rgba.pixels() {
            let [r, g, b, a] = pixel.0;
            let alpha = a as u32;
            let premul = |channel: u8| ((channel as u32 * alpha + 127) / 255) as u8;
            data.push(premul(b));
            data.push(premul(g));
            data.push(premul(r));
            data.push(a);
        }

        Self {
            width: width as i32,
            height: height as i32,
            data,
        }
    }
}

pub fn build_panel_assets(theme: &Theme) -> Result<PanelAssets> {
    Ok(PanelAssets {
        show_pointer: render_panel(&panel_markup("show", theme), theme)?,
        hide_pointer: render_panel(&panel_markup("hide", theme), theme)?,
    })
}

fn panel_markup(pointer_verb: &str, theme: &Theme) -> String {
    let bg = theme.badge_bg.to_hex_rgb();
    let fg = theme.badge_text.to_hex_rgb();
    format!(
        "Press <span face='mono' bgcolor='{bg}' fgcolor='{fg}'> Space </span> to save the screenshot.\n\
         Press <span face='mono' bgcolor='{bg}' fgcolor='{fg}'> P </span> to {pointer_verb} the pointer."
    )
}

pub fn paint_background(cr: &Context, surface: &mut PixelSurface, target_size: Size) -> Result<()> {
    let mut image = ImageSurface::create(Format::ARgb32, surface.width, surface.height)?;
    {
        let mut data = image.data()?;
        data.copy_from_slice(&surface.data);
    }
    cr.save()?;
    cr.scale(
        target_size.width as f64 / surface.width as f64,
        target_size.height as f64 / surface.height as f64,
    );
    cr.set_source_surface(&image, 0.0, 0.0)?;
    cr.paint()?;
    cr.restore()?;
    Ok(())
}

pub fn paint_masks_and_border(
    cr: &Context,
    output_size: Size,
    selection: Option<Rect>,
    theme: &Theme,
) -> Result<()> {
    theme.dim_mask.set_source(cr);
    if let Some(rect) = selection {
        cr.rectangle(0.0, 0.0, output_size.width as f64, rect.y as f64);
        cr.fill()?;
        cr.rectangle(
            0.0,
            (rect.y + rect.height) as f64,
            output_size.width as f64,
            (output_size.height - rect.y - rect.height) as f64,
        );
        cr.fill()?;
        cr.rectangle(0.0, rect.y as f64, rect.x as f64, rect.height as f64);
        cr.fill()?;
        cr.rectangle(
            (rect.x + rect.width) as f64,
            rect.y as f64,
            (output_size.width - rect.x - rect.width) as f64,
            rect.height as f64,
        );
        cr.fill()?;

        theme.accent.set_source(cr);
        cr.set_line_width(SELECTION_BORDER as f64);
        cr.rectangle(
            rect.x as f64 - SELECTION_BORDER as f64 / 2.0,
            rect.y as f64 - SELECTION_BORDER as f64 / 2.0,
            rect.width as f64 + SELECTION_BORDER as f64,
            rect.height as f64 + SELECTION_BORDER as f64,
        );
        cr.stroke()?;

        let hs = HANDLE_SIZE as f64;
        let half = hs / 2.0;
        for (hx, hy) in [
            (rect.x as f64, rect.y as f64),
            ((rect.x + rect.width) as f64, rect.y as f64),
            (rect.x as f64, (rect.y + rect.height) as f64),
            ((rect.x + rect.width) as f64, (rect.y + rect.height) as f64),
        ] {
            cr.rectangle(hx - half, hy - half, hs, hs);
            cr.fill()?;
        }
    } else {
        cr.rectangle(
            0.0,
            0.0,
            output_size.width as f64,
            output_size.height as f64,
        );
        cr.fill()?;
    }
    Ok(())
}

pub fn paint_panel(
    cr: &Context,
    panel: &mut PixelSurface,
    output_size: Size,
    dragging_selection: bool,
) -> Result<Rect> {
    let location = panel_location(output_size, Size::new(panel.width, panel.height));
    let alpha = if dragging_selection { 0.3 } else { 0.9 };

    let mut surface = ImageSurface::create(Format::ARgb32, panel.width, panel.height)?;
    {
        let mut data = surface.data()?;
        data.copy_from_slice(&panel.data);
    }
    cr.save()?;
    cr.set_source_surface(&surface, location.x as f64, location.y as f64)?;
    cr.paint_with_alpha(alpha)?;
    cr.restore()?;

    Ok(Rect::new(location.x, location.y, panel.width, panel.height))
}

pub fn panel_location(output_size: Size, panel_size: Size) -> Point {
    let x = ((output_size.width - panel_size.width) / 2).max(0);
    let y = (output_size.height - panel_size.height - PADDING * 2).max(0);
    Point::new(x, y)
}

pub const DIMENSIONS_MAX_WIDTH: i32 = 256;
pub const DIMENSIONS_MAX_HEIGHT: i32 = 48;
const DIMENSIONS_FONT: &str = "mono 13px";
const DIMENSIONS_PADDING: i32 = 6;
const DIMENSIONS_CORNER: f64 = 6.0;
const DIMENSIONS_GAP: i32 = 8;

pub fn render_dimensions_label(width: i32, height: i32, theme: &Theme) -> Result<PixelSurface> {
    let text = format!("{width} \u{00d7} {height}");
    let mut font = FontDescription::from_string(DIMENSIONS_FONT);
    font.set_absolute_size((13 * pango::SCALE) as f64);

    let (tw, th) = {
        let surface = ImageSurface::create(Format::ARgb32, 0, 0)?;
        let cr = Context::new(&surface)?;
        let layout = pangocairo::functions::create_layout(&cr);
        layout.context().set_round_glyph_positions(false);
        layout.set_font_description(Some(&font));
        layout.set_text(&text);
        layout.pixel_size()
    };

    // Always render at MAX dimensions so the wgpu texture UV mapping is 1:1.
    // The visible pill is centered within the full surface.
    let pill_w = (tw + DIMENSIONS_PADDING * 2).min(DIMENSIONS_MAX_WIDTH);
    let pill_h = (th + DIMENSIONS_PADDING * 2).min(DIMENSIONS_MAX_HEIGHT);
    let ox = (DIMENSIONS_MAX_WIDTH - pill_w) / 2;
    let oy = (DIMENSIONS_MAX_HEIGHT - pill_h) / 2;

    let surface = ImageSurface::create(Format::ARgb32, DIMENSIONS_MAX_WIDTH, DIMENSIONS_MAX_HEIGHT)?;
    {
        let cr = Context::new(&surface)?;
        rounded_rect(
            &cr,
            ox as f64 + 0.5,
            oy as f64 + 0.5,
            pill_w as f64 - 1.0,
            pill_h as f64 - 1.0,
            DIMENSIONS_CORNER,
        );
        cr.save()?;
        cr.clip_preserve();
        theme.panel_bg.set_source(&cr);
        cr.paint()?;
        cr.restore()?;

        theme.panel_border.set_source(&cr);
        cr.set_line_width(1.0);
        cr.stroke()?;

        cr.move_to(
            f64::from(ox + DIMENSIONS_PADDING),
            f64::from(oy + DIMENSIONS_PADDING),
        );
        let layout = pangocairo::functions::create_layout(&cr);
        layout.context().set_round_glyph_positions(false);
        layout.set_font_description(Some(&font));
        layout.set_text(&text);
        theme.text_dim.set_source(&cr);
        pangocairo::functions::show_layout(&cr, &layout);
    }

    let data = surface.take_data()?;
    Ok(PixelSurface {
        width: DIMENSIONS_MAX_WIDTH,
        height: DIMENSIONS_MAX_HEIGHT,
        data: data.to_vec(),
    })
}

pub fn dimensions_label_position(selection: Rect, label_size: Size, output_size: Size) -> Point {
    let x = (selection.x + selection.width / 2 - label_size.width / 2)
        .max(0)
        .min(output_size.width - label_size.width);
    let above = selection.y - label_size.height - DIMENSIONS_GAP;
    let y = if above >= 0 {
        above
    } else {
        selection.y + selection.height + DIMENSIONS_GAP
    };
    Point::new(x, y.max(0).min(output_size.height - label_size.height))
}

pub fn paint_dimensions(
    cr: &Context,
    label: &PixelSurface,
    selection: Rect,
    output_size: Size,
) -> Result<()> {
    let pos = dimensions_label_position(
        selection,
        Size::new(label.width, label.height),
        output_size,
    );
    let mut surface = ImageSurface::create(Format::ARgb32, label.width, label.height)?;
    {
        let mut data = surface.data()?;
        data.copy_from_slice(&label.data);
    }
    cr.save()?;
    cr.set_source_surface(&surface, pos.x as f64, pos.y as f64)?;
    cr.paint()?;
    cr.restore()?;
    Ok(())
}

pub fn capture_button_hit(panel_rect: Rect, point: Point) -> bool {
    let radius = RADIUS - 2;
    let xc = panel_rect.x + PADDING + radius;
    let yc = panel_rect.y + panel_rect.height / 2;
    let dx = point.x - xc;
    let dy = point.y - yc;
    dx * dx + dy * dy <= radius * radius
}

fn render_panel(text: &str, theme: &Theme) -> Result<PixelSurface> {
    let mut font = FontDescription::from_string(FONT);
    font.set_absolute_size((14 * pango::SCALE) as f64);

    let (width, height) = {
        let surface = ImageSurface::create(Format::ARgb32, 0, 0)?;
        let cr = Context::new(&surface)?;
        let layout = pangocairo::functions::create_layout(&cr);
        layout.context().set_round_glyph_positions(false);
        layout.set_font_description(Some(&font));
        layout.set_alignment(Alignment::Left);
        layout.set_markup(text);
        layout.set_spacing(2 * 1024);

        let (mut width, mut height) = layout.pixel_size();
        width += PADDING + RADIUS * 2 + PADDING + PADDING;
        height = height.max(RADIUS * 2);
        height += PADDING * 2;
        (width, height)
    };

    let surface = ImageSurface::create(Format::ARgb32, width, height)?;
    {
        let cr = Context::new(&surface)?;

        // Rounded-rect background
        let inset = BORDER / 2.0;
        rounded_rect(&cr, inset, inset, width as f64 - BORDER, height as f64 - BORDER, CORNER_RADIUS);
        cr.save()?;
        cr.clip_preserve();
        theme.panel_bg.set_source(&cr);
        cr.paint()?;
        cr.restore()?;

        // Border stroke along the same path
        theme.panel_border.set_source(&cr);
        cr.set_line_width(BORDER);
        cr.stroke()?;

        // Capture button — single accent-filled circle
        let yc = f64::from(height / 2);
        let r = f64::from(RADIUS);
        cr.new_sub_path();
        cr.arc(f64::from(PADDING) + r, yc, r - 3.0, 0.0, TAU);
        theme.accent.set_source(&cr);
        cr.fill()?;

        // Panel text
        cr.move_to(
            f64::from(PADDING + RADIUS * 2 + PADDING),
            f64::from(PADDING),
        );
        let layout = pangocairo::functions::create_layout(&cr);
        layout.context().set_round_glyph_positions(false);
        layout.set_font_description(Some(&font));
        layout.set_alignment(Alignment::Left);
        layout.set_markup(text);
        layout.set_spacing(2 * 1024);

        theme.text.set_source(&cr);
        pangocairo::functions::show_layout(&cr, &layout);
    }

    let data = surface.take_data()?;
    Ok(PixelSurface {
        width,
        height,
        data: data.to_vec(),
    })
}

fn rounded_rect(cr: &Context, x: f64, y: f64, w: f64, h: f64, r: f64) {
    cr.new_sub_path();
    cr.arc(x + r, y + r, r, PI, 1.5 * PI);
    cr.arc(x + w - r, y + r, r, 1.5 * PI, 2.0 * PI);
    cr.arc(x + w - r, y + h - r, r, 0.0, 0.5 * PI);
    cr.arc(x + r, y + h - r, r, 0.5 * PI, PI);
    cr.close_path();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn build_panel_assets_renders_pixel_buffers() {
        let theme = Theme::default();
        let assets = build_panel_assets(&theme).expect("panel assets should render");
        assert!(assets.show_pointer.width > 0);
        assert!(assets.show_pointer.height > 0);
        assert!(!assets.show_pointer.data.is_empty());
        assert!(assets.hide_pointer.width > 0);
        assert!(assets.hide_pointer.height > 0);
        assert!(!assets.hide_pointer.data.is_empty());
    }

    #[test]
    fn final_overlay_surface_can_be_mapped_after_painting() {
        let theme = Theme::default();
        let output_size = Size::new(800, 600);
        let mut background = PixelSurface {
            width: 2,
            height: 2,
            data: vec![255; 2 * 2 * 4],
        };
        let assets = build_panel_assets(&theme).expect("panel assets should render");
        let mut panel = assets.show_pointer.clone();
        let mut surface =
            ImageSurface::create(Format::ARgb32, output_size.width, output_size.height)
                .expect("surface should allocate");

        {
            let cr = Context::new(&surface).expect("context should create");
            paint_background(&cr, &mut background, output_size).expect("background should paint");
            paint_masks_and_border(
                &cr,
                output_size,
                Some(Rect::new(100, 120, 200, 160)),
                &theme,
            )
            .expect("mask should paint");
            paint_panel(&cr, &mut panel, output_size, false).expect("panel should paint");
        }

        let data = surface
            .data()
            .expect("surface data should be accessible after painting");
        assert!(!data.is_empty());
    }

    #[test]
    fn dimensions_label_renders_non_empty() {
        let theme = Theme::default();
        let label = render_dimensions_label(1920, 1080, &theme).expect("label should render");
        assert!(label.width > 0);
        assert!(label.height > 0);
        assert!(label.width <= DIMENSIONS_MAX_WIDTH);
        assert!(label.height <= DIMENSIONS_MAX_HEIGHT);
        assert!(!label.data.is_empty());
    }

    #[test]
    fn dimensions_label_positioned_above_when_space() {
        let sel = Rect::new(100, 200, 400, 300);
        let label_size = Size::new(120, 30);
        let output_size = Size::new(1920, 1080);
        let pos = dimensions_label_position(sel, label_size, output_size);
        assert!(pos.y < sel.y);
    }

    #[test]
    fn dimensions_label_positioned_below_when_no_space_above() {
        let sel = Rect::new(100, 5, 400, 300);
        let label_size = Size::new(120, 30);
        let output_size = Size::new(1920, 1080);
        let pos = dimensions_label_position(sel, label_size, output_size);
        assert!(pos.y >= sel.y + sel.height);
    }
}