forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

screenshot_ui.rs1263 lines, 39.1 KiBHistoryRawDownload
1use std::cell::RefCell;
2use std::cmp::{max, min};
3use std::collections::HashMap;
4use std::f64::consts::TAU;
5use std::iter::zip;
6use std::rc::Rc;
7
8use anyhow::Context;
9use arrayvec::ArrayVec;
10use niri_config::{Action, Bind, BoundAction, Config, Key, Modifiers, Trigger};
11use niri_ipc::SizeChange;
12use pango::{Alignment, FontDescription};
13use pangocairo::cairo::{self, ImageSurface};
14use smithay::backend::allocator::Fourcc;
15use smithay::backend::input::TouchSlot;
16use smithay::backend::renderer::element::utils::{Relocate, RelocateRenderElement};
17use smithay::backend::renderer::element::Kind;
18use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
19use smithay::backend::renderer::{ExportMem, Texture as _};
20use smithay::input::keyboard::Keysym;
21use smithay::output::{Output, WeakOutput};
22use smithay::utils::{Buffer, Physical, Point, Rectangle, Scale, Size, Transform};
23
24use crate::animation::{Animation, Clock};
25use crate::layout::floating::DIRECTIONAL_MOVE_PX;
26use crate::niri_render_elements;
27use crate::render_helpers::primary_gpu_texture::PrimaryGpuTextureRenderElement;
28use crate::render_helpers::solid_color::{SolidColorBuffer, SolidColorRenderElement};
29use crate::render_helpers::texture::{TextureBuffer, TextureRenderElement};
30use crate::render_helpers::{render_to_texture, RenderTarget};
31use crate::utils::to_physical_precise_round;
32
33const SELECTION_BORDER: i32 = 2;
34
35const PADDING: i32 = 8;
36const RADIUS: i32 = 16;
37const FONT: &str = "sans 14px";
38const BORDER: i32 = 4;
39const TEXT_HIDE_P: &str =
40 "Press <span face='mono' bgcolor='#2C2C2C'> Space </span> to save the screenshot.\n\
41 Press <span face='mono' bgcolor='#2C2C2C'> P </span> to hide the pointer.";
42const TEXT_SHOW_P: &str =
43 "Press <span face='mono' bgcolor='#2C2C2C'> Space </span> to save the screenshot.\n\
44 Press <span face='mono' bgcolor='#2C2C2C'> P </span> to show the pointer.";
45
46// Ideally the screenshot UI should support cross-output selections. However, that poses some
47// technical challenges when the outputs have different scales and such. So, this implementation
48// allows only single-output selections for now.
49//
50// As a consequence of this, selection coordinates are in output-local coordinate space.
51#[allow(clippy::large_enum_variant)]
52pub enum ScreenshotUi {
53 Closed {
54 last_selection: Option<(WeakOutput, Rectangle<i32, Physical>)>,
55 clock: Clock,
56 config: Rc<RefCell<Config>>,
57 },
58 Open {
59 selection: (Output, Point<i32, Physical>, Point<i32, Physical>),
60 output_data: HashMap<Output, OutputData>,
61 button: Button,
62 show_pointer: bool,
63 open_anim: Animation,
64 clock: Clock,
65 config: Rc<RefCell<Config>>,
66 path: Option<String>,
67 },
68}
69
70/// State for moving the selection (as opposed to just drawing).
71pub struct MoveState {
72 // Cursor offset from selection.1 when starting the move.
73 pointer_offset: Point<i32, Physical>,
74 // If the move is initiated by a touch, this is the slot. If `None`, the move was initiated by
75 // holding Space.
76 touch_slot: Option<TouchSlot>,
77}
78
79pub enum Button {
80 Up,
81 Down {
82 touch_slot: Option<TouchSlot>,
83 on_capture_button: bool,
84 last_pos: (Output, Point<i32, Physical>),
85 move_state: Option<MoveState>,
86 },
87}
88
89pub struct OutputData {
90 size: Size<i32, Physical>,
91 scale: f64,
92 transform: Transform,
93 // Output, screencast, screen capture.
94 screenshot: [OutputScreenshot; 3],
95 buffers: [SolidColorBuffer; 8],
96 locations: [Point<i32, Physical>; 8],
97 panel: Option<(TextureBuffer<GlesTexture>, TextureBuffer<GlesTexture>)>,
98}
99
100pub struct OutputScreenshot {
101 texture: GlesTexture,
102 buffer: PrimaryGpuTextureRenderElement,
103 pointer: Option<PrimaryGpuTextureRenderElement>,
104}
105
106niri_render_elements! {
107 ScreenshotUiRenderElement => {
108 Screenshot = PrimaryGpuTextureRenderElement,
109 SolidColor = SolidColorRenderElement,
110 }
111}
112
113impl Button {
114 fn is_down(&self) -> bool {
115 matches!(self, Self::Down { .. })
116 }
117
118 fn is_dragging_selection(&self) -> bool {
119 matches!(
120 self,
121 Self::Down {
122 on_capture_button: false,
123 ..
124 }
125 )
126 }
127}
128
129impl ScreenshotUi {
130 pub fn new(clock: Clock, config: Rc<RefCell<Config>>) -> Self {
131 Self::Closed {
132 last_selection: None,
133 clock,
134 config,
135 }
136 }
137
138 pub fn open(
139 &mut self,
140 renderer: &mut GlesRenderer,
141 // Output, screencast, screen capture.
142 screenshots: HashMap<Output, [OutputScreenshot; 3]>,
143 default_output: Output,
144 show_pointer: bool,
145 path: Option<String>,
146 ) -> bool {
147 if screenshots.is_empty() {
148 return false;
149 }
150
151 let Self::Closed {
152 last_selection,
153 clock,
154 config,
155 } = self
156 else {
157 return false;
158 };
159
160 let last_selection = last_selection
161 .take()
162 .and_then(|(weak, sel)| weak.upgrade().map(|output| (output, sel)));
163 let selection = match last_selection {
164 Some(selection) if screenshots.contains_key(&selection.0) => selection,
165 _ => {
166 let output = default_output;
167 let output_transform = output.current_transform();
168 let output_mode = output.current_mode().unwrap();
169 let size = output_transform.transform_size(output_mode.size);
170 (
171 output,
172 Rectangle::new(
173 Point::from((size.w / 4, size.h / 4)),
174 Size::from((size.w / 2, size.h / 2)),
175 ),
176 )
177 }
178 };
179
180 let selection = (
181 selection.0,
182 selection.1.loc,
183 selection.1.loc + selection.1.size - Size::from((1, 1)),
184 );
185
186 let output_data = screenshots
187 .into_iter()
188 .map(|(output, screenshot)| {
189 let transform = output.current_transform();
190 let output_mode = output.current_mode().unwrap();
191 let size = transform.transform_size(output_mode.size);
192 let scale = output.current_scale().fractional_scale();
193 let buffers = [
194 SolidColorBuffer::new((0., 0.), [1., 1., 1., 1.]),
195 SolidColorBuffer::new((0., 0.), [1., 1., 1., 1.]),
196 SolidColorBuffer::new((0., 0.), [1., 1., 1., 1.]),
197 SolidColorBuffer::new((0., 0.), [1., 1., 1., 1.]),
198 SolidColorBuffer::new((0., 0.), [0., 0., 0., 0.5]),
199 SolidColorBuffer::new((0., 0.), [0., 0., 0., 0.5]),
200 SolidColorBuffer::new((0., 0.), [0., 0., 0., 0.5]),
201 SolidColorBuffer::new((0., 0.), [0., 0., 0., 0.5]),
202 ];
203 let locations = [Default::default(); 8];
204
205 let mut render_panel_ = |text| {
206 render_panel(renderer, scale, text)
207 .map_err(|err| warn!("error rendering help panel: {err:?}"))
208 .ok()
209 };
210 let panel_show = render_panel_(TEXT_SHOW_P);
211 let panel_hide = render_panel_(TEXT_HIDE_P);
212 let panel = Option::zip(panel_show, panel_hide);
213
214 let data = OutputData {
215 size,
216 scale,
217 transform,
218 screenshot,
219 buffers,
220 locations,
221 panel,
222 };
223 (output, data)
224 })
225 .collect();
226
227 let open_anim = {
228 let c = config.borrow();
229 Animation::new(clock.clone(), 0., 1., 0., c.animations.screenshot_ui_open.0)
230 };
231
232 *self = Self::Open {
233 selection,
234 output_data,
235 button: Button::Up,
236 show_pointer,
237 open_anim,
238 clock: clock.clone(),
239 config: config.clone(),
240 path,
241 };
242
243 self.update_buffers();
244
245 true
246 }
247
248 pub fn close(&mut self) -> bool {
249 let Self::Open {
250 selection,
251 clock,
252 config,
253 ..
254 } = self
255 else {
256 return false;
257 };
258
259 let last_selection = Some((
260 selection.0.downgrade(),
261 rect_from_corner_points(selection.1, selection.2),
262 ));
263
264 *self = Self::Closed {
265 last_selection,
266 clock: clock.clone(),
267 config: config.clone(),
268 };
269
270 true
271 }
272
273 pub fn toggle_pointer(&mut self) {
274 if let Self::Open { show_pointer, .. } = self {
275 *show_pointer = !*show_pointer;
276 }
277 }
278
279 pub fn is_open(&self) -> bool {
280 matches!(self, ScreenshotUi::Open { .. })
281 }
282
283 pub fn set_space_down(&mut self, down: bool) {
284 if let Self::Open {
285 selection,
286 button:
287 Button::Down {
288 move_state,
289 last_pos,
290 ..
291 },
292 ..
293 } = self
294 {
295 if down {
296 if move_state.is_none() {
297 *move_state = Some(MoveState {
298 pointer_offset: last_pos.1 - selection.1,
299 touch_slot: None,
300 });
301 }
302 } else {
303 // Only clear if moving with Space.
304 if let Some(MoveState {
305 touch_slot: None, ..
306 }) = move_state
307 {
308 *move_state = None;
309 }
310 }
311 }
312 }
313
314 pub fn move_left(&mut self) {
315 let Self::Open {
316 selection: (output, a, b),
317 output_data,
318 ..
319 } = self
320 else {
321 return;
322 };
323
324 let data = &output_data[output];
325
326 let delta: i32 = to_physical_precise_round(data.scale, DIRECTIONAL_MOVE_PX);
327 let delta = min(delta, min(a.x, b.x));
328 a.x -= delta;
329 b.x -= delta;
330
331 self.update_buffers();
332 }
333
334 pub fn move_right(&mut self) {
335 let Self::Open {
336 selection: (output, a, b),
337 output_data,
338 ..
339 } = self
340 else {
341 return;
342 };
343
344 let data = &output_data[output];
345
346 let delta: i32 = to_physical_precise_round(data.scale, DIRECTIONAL_MOVE_PX);
347 let delta = min(delta, data.size.w - max(a.x, b.x) - 1);
348 a.x += delta;
349 b.x += delta;
350
351 self.update_buffers();
352 }
353
354 pub fn move_up(&mut self) {
355 let Self::Open {
356 selection: (output, a, b),
357 output_data,
358 ..
359 } = self
360 else {
361 return;
362 };
363
364 let data = &output_data[output];
365
366 let delta: i32 = to_physical_precise_round(data.scale, DIRECTIONAL_MOVE_PX);
367 let delta = min(delta, min(a.y, b.y));
368 a.y -= delta;
369 b.y -= delta;
370
371 self.update_buffers();
372 }
373
374 pub fn move_down(&mut self) {
375 let Self::Open {
376 selection: (output, a, b),
377 output_data,
378 ..
379 } = self
380 else {
381 return;
382 };
383
384 let data = &output_data[output];
385
386 let delta: i32 = to_physical_precise_round(data.scale, DIRECTIONAL_MOVE_PX);
387 let delta = min(delta, data.size.h - max(a.y, b.y) - 1);
388 a.y += delta;
389 b.y += delta;
390
391 self.update_buffers();
392 }
393
394 /// Moves the screenshot selection to a different output.
395 ///
396 /// This preserves the relative position while keeping logical size. It is (intentionally) very
397 /// similar to how floating windows move across monitors, but with one difference: floating
398 /// windows can go partially outside the view, while the screenshot selection cannot. So, we
399 /// clamp it to new output bounds, trying to preserve the size if possible.
400 pub fn move_to_output(&mut self, new_output: Output) {
401 let Self::Open {
402 selection,
403 output_data,
404 ..
405 } = self
406 else {
407 return;
408 };
409
410 let (current_output, current_a, current_b) = selection;
411
412 if current_output == &new_output {
413 return;
414 }
415
416 let Some(target_data) = output_data.get(&new_output) else {
417 return;
418 };
419
420 let current_data = &output_data[current_output];
421
422 let current_rect: Rectangle<_, Physical> = Rectangle::new(
423 Point::from((current_a.x.min(current_b.x), current_a.y.min(current_b.y))),
424 Size::from((
425 (current_a.x.max(current_b.x) - current_a.x.min(current_b.x) + 1),
426 (current_a.y.max(current_b.y) - current_a.y.min(current_b.y) + 1),
427 )),
428 );
429 let current_rect = current_rect.to_f64();
430
431 let rel_x = current_rect.loc.x / current_data.size.w as f64;
432 let rel_y = current_rect.loc.y / current_data.size.h as f64;
433
434 let factor = target_data.scale / current_data.scale;
435 let mut new_width = (current_rect.size.w * factor).round() as i32;
436 let mut new_height = (current_rect.size.h * factor).round() as i32;
437
438 new_width = new_width.clamp(1, target_data.size.w);
439 new_height = new_height.clamp(1, target_data.size.h);
440
441 let new_x = (rel_x * target_data.size.w as f64).round() as i32;
442 let new_y = (rel_y * target_data.size.h as f64).round() as i32;
443
444 let max_x = target_data.size.w - new_width;
445 let max_y = target_data.size.h - new_height;
446 let new_x = new_x.clamp(0, max_x);
447 let new_y = new_y.clamp(0, max_y);
448
449 let new_rect = Rectangle::new(
450 Point::from((new_x, new_y)),
451 Size::from((new_width, new_height)),
452 );
453
454 *selection = (
455 new_output,
456 new_rect.loc,
457 new_rect.loc + new_rect.size - Size::from((1, 1)),
458 );
459
460 self.update_buffers();
461 }
462
463 pub fn set_width(&mut self, change: SizeChange) {
464 let Self::Open {
465 selection: (output, a, b),
466 output_data,
467 ..
468 } = self
469 else {
470 return;
471 };
472
473 let data = &output_data[output];
474
475 let available_size = f64::from(data.size.w);
476 let current_size = max(a.x, b.x) + 1 - min(a.x, b.x);
477
478 let new_size = match change {
479 SizeChange::SetFixed(fixed) => to_physical_precise_round(data.scale, fixed),
480 SizeChange::SetProportion(prop) => {
481 let prop = (prop / 100.).clamp(0., 1.);
482 (available_size * prop).round() as i32
483 }
484 SizeChange::AdjustFixed(delta) => {
485 let delta = to_physical_precise_round(data.scale, delta);
486 current_size.saturating_add(delta)
487 }
488 SizeChange::AdjustProportion(delta) => {
489 let current_prop = f64::from(current_size) / available_size;
490 let prop = (current_prop + delta / 100.).clamp(0., 1.);
491 (available_size * prop).round() as i32
492 }
493 };
494 let new_size = new_size.clamp(1, data.size.w - min(a.x, b.x)) - 1;
495 a.x = min(a.x, b.x);
496 b.x = a.x + new_size;
497
498 self.update_buffers();
499 }
500
501 pub fn set_height(&mut self, change: SizeChange) {
502 let Self::Open {
503 selection: (output, a, b),
504 output_data,
505 ..
506 } = self
507 else {
508 return;
509 };
510
511 let data = &output_data[output];
512
513 let available_size = f64::from(data.size.h);
514 let current_size = max(a.y, b.y) + 1 - min(a.y, b.y);
515
516 let new_size = match change {
517 SizeChange::SetFixed(fixed) => to_physical_precise_round(data.scale, fixed),
518 SizeChange::SetProportion(prop) => {
519 let prop = (prop / 100.).clamp(0., 1.);
520 (available_size * prop).round() as i32
521 }
522 SizeChange::AdjustFixed(delta) => {
523 let delta = to_physical_precise_round(data.scale, delta);
524 current_size.saturating_add(delta)
525 }
526 SizeChange::AdjustProportion(delta) => {
527 let current_prop = f64::from(current_size) / available_size;
528 let prop = (current_prop + delta / 100.).clamp(0., 1.);
529 (available_size * prop).round() as i32
530 }
531 };
532 let new_size = new_size.clamp(1, data.size.h - min(a.y, b.y)) - 1;
533 a.y = min(a.y, b.y);
534 b.y = a.y + new_size;
535
536 self.update_buffers();
537 }
538
539 pub fn advance_animations(&mut self) {}
540
541 pub fn are_animations_ongoing(&self) -> bool {
542 let Self::Open { open_anim, .. } = self else {
543 return false;
544 };
545
546 !open_anim.is_done()
547 }
548
549 fn update_buffers(&mut self) {
550 let Self::Open {
551 selection,
552 output_data,
553 ..
554 } = self
555 else {
556 panic!("screenshot UI must be open to update buffers");
557 };
558
559 let (selection_output, a, b) = selection;
560 let mut rect = rect_from_corner_points(*a, *b);
561
562 for (output, data) in output_data {
563 let buffers = &mut data.buffers;
564 let locations = &mut data.locations;
565 let size = data.size;
566 let scale = data.scale;
567
568 if output == selection_output {
569 // Check if the selection is still valid. If not, reset it back to default.
570 if !Rectangle::from_size(size).contains_rect(rect) {
571 rect = Rectangle::new(
572 Point::from((size.w / 4, size.h / 4)),
573 Size::from((size.w / 2, size.h / 2)),
574 );
575 *a = rect.loc;
576 *b = rect.loc + rect.size - Size::from((1, 1));
577 }
578
579 let border = to_physical_precise_round(scale, SELECTION_BORDER);
580
581 let resize = move |buffer: &mut SolidColorBuffer, w: i32, h: i32| {
582 let size = Size::<_, Physical>::from((w, h));
583 buffer.resize(size.to_f64().to_logical(scale));
584 };
585
586 resize(&mut buffers[0], rect.size.w + border * 2, border);
587 resize(&mut buffers[1], rect.size.w + border * 2, border);
588 resize(&mut buffers[2], border, rect.size.h);
589 resize(&mut buffers[3], border, rect.size.h);
590
591 resize(&mut buffers[4], size.w, rect.loc.y);
592 resize(&mut buffers[5], size.w, size.h - rect.loc.y - rect.size.h);
593 resize(&mut buffers[6], rect.loc.x, rect.size.h);
594 resize(
595 &mut buffers[7],
596 size.w - rect.loc.x - rect.size.w,
597 rect.size.h,
598 );
599
600 locations[0] = Point::from((rect.loc.x - border, rect.loc.y - border));
601 locations[1] = Point::from((rect.loc.x - border, rect.loc.y + rect.size.h));
602 locations[2] = Point::from((rect.loc.x - border, rect.loc.y));
603 locations[3] = Point::from((rect.loc.x + rect.size.w, rect.loc.y));
604
605 locations[5] = Point::from((0, rect.loc.y + rect.size.h));
606 locations[6] = Point::from((0, rect.loc.y));
607 locations[7] = Point::from((rect.loc.x + rect.size.w, rect.loc.y));
608 } else {
609 buffers[0].resize((0., 0.));
610 buffers[1].resize((0., 0.));
611 buffers[2].resize((0., 0.));
612 buffers[3].resize((0., 0.));
613
614 buffers[4].resize(size.to_f64().to_logical(data.scale));
615 buffers[5].resize((0., 0.));
616 buffers[6].resize((0., 0.));
617 buffers[7].resize((0., 0.));
618 }
619 }
620 }
621
622 pub fn render_output(
623 &self,
624 output: &Output,
625 target: RenderTarget,
626 push: &mut dyn FnMut(ScreenshotUiRenderElement),
627 ) {
628 let _span = tracy_client::span!("ScreenshotUi::render_output");
629
630 let Self::Open {
631 output_data,
632 show_pointer,
633 button,
634 open_anim,
635 ..
636 } = self
637 else {
638 panic!("screenshot UI must be open to render it");
639 };
640
641 let Some(output_data) = output_data.get(output) else {
642 return;
643 };
644
645 let scale = output_data.scale;
646 let progress = open_anim.clamped_value().clamp(0., 1.) as f32;
647
648 // The help panel goes on top.
649 if let Some((show, hide)) = &output_data.panel {
650 let buffer = if *show_pointer { hide } else { show };
651 let alpha = if button.is_dragging_selection() {
652 0.3
653 } else {
654 0.9
655 };
656 let location = panel_location(output_data, buffer.texture().size())
657 .to_f64()
658 .to_logical(scale);
659
660 let elem = PrimaryGpuTextureRenderElement(TextureRenderElement::from_texture_buffer(
661 buffer.clone(),
662 location,
663 alpha * progress,
664 None,
665 None,
666 Kind::Unspecified,
667 ));
668 push(elem.into());
669 }
670
671 for (buffer, loc) in zip(&output_data.buffers, &output_data.locations) {
672 let elem = SolidColorRenderElement::from_buffer(
673 buffer,
674 loc.to_f64().to_logical(scale),
675 progress,
676 Kind::Unspecified,
677 );
678 push(elem.into());
679 }
680
681 // The screenshot itself goes last.
682 let index = match target {
683 RenderTarget::Output => 0,
684 RenderTarget::Screencast => 1,
685 RenderTarget::ScreenCapture => 2,
686 };
687 let screenshot = &output_data.screenshot[index];
688
689 if *show_pointer {
690 if let Some(pointer) = screenshot.pointer.clone() {
691 push(pointer.into());
692 }
693 }
694 push(screenshot.buffer.clone().into());
695 }
696
697 pub fn capture(
698 &self,
699 renderer: &mut GlesRenderer,
700 ) -> anyhow::Result<(Size<i32, Physical>, Vec<u8>)> {
701 let _span = tracy_client::span!("ScreenshotUi::capture");
702
703 let Self::Open {
704 selection,
705 output_data,
706 show_pointer,
707 ..
708 } = self
709 else {
710 panic!("screenshot UI must be open to capture");
711 };
712
713 let data = &output_data[&selection.0];
714 let rect = rect_from_corner_points(selection.1, selection.2);
715
716 let screenshot = &data.screenshot[0];
717
718 // Composite the pointer on top if needed.
719 let mut tex_rect = None;
720 if *show_pointer {
721 if let Some(pointer) = screenshot.pointer.clone() {
722 let scale = pointer.0.buffer().texture_scale();
723 let offset = rect.loc.upscale(-1);
724
725 let mut elements = ArrayVec::<_, 2>::new();
726 elements.push(pointer);
727 elements.push(screenshot.buffer.clone());
728 let elements = elements.iter().rev().map(|elem| {
729 RelocateRenderElement::from_element(elem, offset, Relocate::Relative)
730 });
731
732 let res = render_to_texture(
733 renderer,
734 rect.size,
735 scale,
736 Transform::Normal,
737 Fourcc::Abgr8888,
738 elements,
739 );
740 match res {
741 Ok((texture, _)) => {
742 tex_rect = Some((texture, Rectangle::from_size(rect.size)));
743 }
744 Err(err) => {
745 warn!("error compositing pointer onto screenshot: {err:?}");
746 }
747 }
748 }
749 }
750
751 let (texture, rect) = tex_rect.unwrap_or_else(|| (screenshot.texture.clone(), rect));
752 // The size doesn't actually matter because we're not transforming anything.
753 let buf_rect = rect
754 .to_logical(1)
755 .to_buffer(1, Transform::Normal, &Size::from((1, 1)));
756
757 let mapping = renderer
758 .copy_texture(&texture, buf_rect, Fourcc::Abgr8888)
759 .context("error copying texture")?;
760 let copy = renderer
761 .map_texture(&mapping)
762 .context("error mapping texture")?;
763
764 Ok((rect.size, copy.to_vec()))
765 }
766
767 pub fn binds(&self) -> impl Iterator<Item = &Bind> + Clone {
768 const fn bind(key: Key, action: Action) -> Bind {
769 Bind {
770 key,
771 action: BoundAction::Press(action),
772 repeat: false, // Not useful for these actions.
773 cooldown: None,
774 allow_when_locked: true,
775 allow_inhibiting: false,
776 hotkey_overlay_title: None,
777 }
778 }
779
780 const BINDS: &[Bind] = &[
781 bind(
782 Key {
783 trigger: Trigger::Keysym(Keysym::Escape),
784 modifiers: Modifiers::empty(),
785 },
786 Action::CancelScreenshot,
787 ),
788 bind(
789 Key {
790 trigger: Trigger::Keysym(Keysym::Return),
791 modifiers: Modifiers::empty(),
792 },
793 Action::ConfirmScreenshot {
794 write_to_disk: true,
795 },
796 ),
797 bind(
798 Key {
799 trigger: Trigger::Keysym(Keysym::c),
800 modifiers: Modifiers::CTRL,
801 },
802 Action::ConfirmScreenshot {
803 write_to_disk: false,
804 },
805 ),
806 bind(
807 Key {
808 trigger: Trigger::Keysym(Keysym::p),
809 modifiers: Modifiers::empty(),
810 },
811 Action::ScreenshotTogglePointer,
812 ),
813 ];
814
815 const SPACE: &[Bind] = &[bind(
816 Key {
817 trigger: Trigger::Keysym(Keysym::space),
818 modifiers: Modifiers::empty(),
819 },
820 Action::ConfirmScreenshot {
821 write_to_disk: true,
822 },
823 )];
824
825 // A bit of gymnastics to return an iterator over constant &Bind values.
826 let Self::Open { button, .. } = self else {
827 return [].iter().chain([].iter());
828 };
829
830 // Pressing Space while the button is down goes into origin moving rather than capture.
831 let space: &[Bind] = if matches!(button, Button::Down { .. }) {
832 &[]
833 } else {
834 SPACE
835 };
836
837 space.iter().chain(BINDS)
838 }
839
840 pub fn selection_output(&self) -> Option<&Output> {
841 if let Self::Open {
842 selection: (output, _, _),
843 ..
844 } = self
845 {
846 Some(output)
847 } else {
848 None
849 }
850 }
851
852 pub fn output_size(&self, output: &Output) -> Option<(Size<i32, Physical>, f64, Transform)> {
853 if let Self::Open { output_data, .. } = self {
854 let data = output_data.get(output)?;
855 Some((data.size, data.scale, data.transform))
856 } else {
857 None
858 }
859 }
860
861 /// The pointer has moved to `point` relative to the current selection output.
862 ///
863 /// The point may be outside output bounds.
864 pub fn pointer_motion(&mut self, point: Point<i32, Physical>, slot: Option<TouchSlot>) {
865 let Self::Open {
866 selection,
867 output_data,
868 button:
869 Button::Down {
870 touch_slot,
871 on_capture_button,
872 last_pos,
873 move_state,
874 },
875 ..
876 } = self
877 else {
878 return;
879 };
880
881 if *touch_slot != slot {
882 return;
883 }
884
885 last_pos.1 = point;
886
887 if *on_capture_button {
888 return;
889 }
890
891 if let Some(move_state) = move_state {
892 // The cursor offset is relative to selection.1.
893 let delta = point - (selection.1 + move_state.pointer_offset);
894
895 let desired = rect_from_corner_points(selection.1 + delta, selection.2 + delta);
896 let bounds = Rectangle::from_size(output_data[&selection.0].size - desired.size);
897 let clamped_loc = desired.loc.constrain(bounds);
898
899 let delta = clamped_loc - rect_from_corner_points(selection.1, selection.2).loc;
900 selection.1 += delta;
901 selection.2 += delta;
902 } else {
903 let size = output_data[&selection.0].size;
904 selection.2 = Point::new(point.x.clamp(0, size.w - 1), point.y.clamp(0, size.h - 1));
905 }
906
907 self.update_buffers();
908 }
909
910 pub fn pointer_down(
911 &mut self,
912 output: Output,
913 point: Point<i32, Physical>,
914 slot: Option<TouchSlot>,
915 move_existing: bool,
916 ) -> bool {
917 let Self::Open {
918 selection,
919 output_data,
920 show_pointer,
921 button,
922 ..
923 } = self
924 else {
925 return false;
926 };
927
928 // Check if this is a second touch (different slot) while already dragging.
929 if let Some(new_slot) = slot {
930 if let Button::Down {
931 on_capture_button: false,
932 move_state,
933 last_pos,
934 ..
935 } = button
936 {
937 if move_state.is_none() {
938 *move_state = Some(MoveState {
939 pointer_offset: last_pos.1 - selection.1,
940 touch_slot: Some(new_slot),
941 });
942 }
943 }
944 }
945
946 if button.is_down() {
947 return false;
948 }
949
950 if move_existing {
951 if output != selection.0 {
952 return false;
953 }
954
955 *button = Button::Down {
956 touch_slot: slot,
957 on_capture_button: false,
958 last_pos: (output, point),
959 move_state: Some(MoveState {
960 pointer_offset: point - selection.1,
961 touch_slot: slot,
962 }),
963 };
964 return true;
965 }
966
967 let Some(output_data) = output_data.get(&output) else {
968 return false;
969 };
970
971 if let Some((show, hide)) = &output_data.panel {
972 let buffer = if *show_pointer { hide } else { show };
973 let panel_size = buffer.texture().size();
974 let location = panel_location(output_data, panel_size);
975
976 if is_within_capture_button(output_data.scale, panel_size, point - location) {
977 *button = Button::Down {
978 touch_slot: slot,
979 on_capture_button: true,
980 last_pos: (output, point),
981 move_state: None,
982 };
983 return false;
984 }
985 }
986
987 *button = Button::Down {
988 touch_slot: slot,
989 on_capture_button: false,
990 last_pos: (output.clone(), point),
991 move_state: None,
992 };
993
994 let point = Point::new(
995 point.x.clamp(0, output_data.size.w - 1),
996 point.y.clamp(0, output_data.size.h - 1),
997 );
998 *selection = (output, point, point);
999
1000 self.update_buffers();
1001
1002 true
1003 }
1004
1005 pub fn pointer_up(&mut self, slot: Option<TouchSlot>) -> Option<bool> {
1006 let Self::Open {
1007 selection,
1008 output_data,
1009 button,
1010 show_pointer,
1011 ..
1012 } = self
1013 else {
1014 return None;
1015 };
1016
1017 let Button::Down {
1018 touch_slot,
1019 on_capture_button,
1020 ref last_pos,
1021 ref mut move_state,
1022 ..
1023 } = *button
1024 else {
1025 return None;
1026 };
1027
1028 if touch_slot != slot {
1029 // This is not our main touch, but it might be the move touch. If so, stop the move.
1030 if let Some(state) = move_state {
1031 if state.touch_slot.is_some_and(|m_slot| Some(m_slot) == slot) {
1032 *move_state = None;
1033 }
1034 };
1035
1036 return None;
1037 }
1038
1039 let last_pos = last_pos.clone();
1040 *button = Button::Up;
1041
1042 // Check if we released still on the capture button.
1043 if on_capture_button {
1044 let (output, point) = last_pos;
1045
1046 #[allow(clippy::question_mark)]
1047 let Some(output_data) = output_data.get(&output) else {
1048 return None;
1049 };
1050
1051 if let Some((show, hide)) = &output_data.panel {
1052 let buffer = if *show_pointer { hide } else { show };
1053 let panel_size = buffer.texture().size();
1054 let location = panel_location(output_data, panel_size);
1055
1056 if is_within_capture_button(output_data.scale, panel_size, point - location) {
1057 return Some(true);
1058 }
1059 }
1060 }
1061
1062 // Check if the resulting selection is zero-sized, and try to come up with a small
1063 // default rectangle.
1064 let (output, a, b) = selection;
1065 let mut rect = rect_from_corner_points(*a, *b);
1066 if rect.size.is_empty() || rect.size == Size::from((1, 1)) {
1067 let data = &output_data[output];
1068 rect = Rectangle::new(
1069 Point::from((rect.loc.x - 16, rect.loc.y - 16)),
1070 Size::from((32, 32)),
1071 )
1072 .intersection(Rectangle::from_size(data.size))
1073 .unwrap_or_default();
1074 *a = rect.loc;
1075 *b = rect.loc + rect.size - Size::from((1, 1));
1076 }
1077
1078 self.update_buffers();
1079
1080 Some(false)
1081 }
1082}
1083
1084impl OutputScreenshot {
1085 pub fn from_textures(
1086 renderer: &mut GlesRenderer,
1087 scale: Scale<f64>,
1088 texture: GlesTexture,
1089 pointer: Option<(GlesTexture, Rectangle<i32, Physical>)>,
1090 ) -> Self {
1091 let buffer = PrimaryGpuTextureRenderElement(TextureRenderElement::from_texture_buffer(
1092 TextureBuffer::from_texture(
1093 renderer,
1094 texture.clone(),
1095 scale,
1096 Transform::Normal,
1097 Vec::new(),
1098 ),
1099 (0., 0.),
1100 1.,
1101 None,
1102 None,
1103 Kind::Unspecified,
1104 ));
1105
1106 let pointer = pointer.map(|(texture, geo)| {
1107 PrimaryGpuTextureRenderElement(TextureRenderElement::from_texture_buffer(
1108 TextureBuffer::from_texture(
1109 renderer,
1110 texture,
1111 scale,
1112 Transform::Normal,
1113 Vec::new(),
1114 ),
1115 geo.to_f64().to_logical(scale).loc,
1116 1.,
1117 None,
1118 None,
1119 Kind::Unspecified,
1120 ))
1121 });
1122
1123 Self {
1124 texture,
1125 buffer,
1126 pointer,
1127 }
1128 }
1129}
1130
1131pub fn rect_from_corner_points(
1132 a: Point<i32, Physical>,
1133 b: Point<i32, Physical>,
1134) -> Rectangle<i32, Physical> {
1135 let x1 = min(a.x, b.x);
1136 let y1 = min(a.y, b.y);
1137 let x2 = max(a.x, b.x);
1138 let y2 = max(a.y, b.y);
1139 // We're adding + 1 because the pointer is clamped to output size - 1, so to get the full
1140 // screen worth of selection we must add back that + 1.
1141 Rectangle::from_extremities((x1, y1), (x2 + 1, y2 + 1))
1142}
1143
1144fn panel_location(output_data: &OutputData, panel_size: Size<i32, Buffer>) -> Point<i32, Physical> {
1145 let scale = output_data.scale;
1146 let padding: i32 = to_physical_precise_round(scale, PADDING);
1147 let x = max(0, (output_data.size.w - panel_size.w) / 2);
1148 let y = max(0, output_data.size.h - panel_size.h - padding * 2);
1149 Point::from((x, y))
1150}
1151
1152fn is_within_capture_button(
1153 scale: f64,
1154 panel_size: Size<i32, Buffer>,
1155 pos_within_panel: Point<i32, Physical>,
1156) -> bool {
1157 let padding: i32 = to_physical_precise_round(scale, PADDING);
1158 let radius = to_physical_precise_round::<i32>(scale, RADIUS) - 2;
1159
1160 let xc = padding + radius;
1161 let yc = panel_size.h / 2;
1162 let pos = pos_within_panel;
1163
1164 (pos.x - xc) * (pos.x - xc) + (pos.y - yc) * (pos.y - yc) <= radius * radius
1165}
1166
1167fn render_panel(
1168 renderer: &mut GlesRenderer,
1169 scale: f64,
1170 text: &str,
1171) -> anyhow::Result<TextureBuffer<GlesTexture>> {
1172 let _span = tracy_client::span!("screenshot_ui::render_panel");
1173
1174 let padding: i32 = to_physical_precise_round(scale, PADDING);
1175 // Keep the border width even to avoid blurry edges.
1176 let border_width = (f64::from(BORDER) / 2. * scale).round() * 2.;
1177 let half_border_width = (border_width / 2.) as i32;
1178 let radius: i32 = to_physical_precise_round(scale, RADIUS);
1179 let circle_stroke: f64 = to_physical_precise_round(scale, 2.);
1180
1181 // Add 2 px of spacing to separate the backgrounds of the "Space" and "P" keys.
1182 let spacing = to_physical_precise_round::<i32>(scale, 2) * 1024;
1183
1184 let mut font = FontDescription::from_string(FONT);
1185 font.set_absolute_size(to_physical_precise_round(scale, font.size()));
1186
1187 let surface = ImageSurface::create(cairo::Format::ARgb32, 0, 0)?;
1188 let cr = cairo::Context::new(&surface)?;
1189 let layout = pangocairo::functions::create_layout(&cr);
1190 layout.context().set_round_glyph_positions(false);
1191 layout.set_font_description(Some(&font));
1192 layout.set_alignment(Alignment::Left);
1193 layout.set_markup(text);
1194 layout.set_spacing(spacing);
1195
1196 let (mut width, mut height) = layout.pixel_size();
1197
1198 width += padding + radius * 2 + padding - half_border_width + padding;
1199 height = max(height, radius * 2);
1200 height += padding * 2;
1201
1202 let surface = ImageSurface::create(cairo::Format::ARgb32, width, height)?;
1203 let cr = cairo::Context::new(&surface)?;
1204 cr.set_source_rgb(0.1, 0.1, 0.1);
1205 cr.paint()?;
1206
1207 let padding = f64::from(padding);
1208 let half_border_width = f64::from(half_border_width);
1209 let r = f64::from(radius);
1210
1211 let yc = f64::from(height / 2);
1212
1213 cr.new_sub_path();
1214 cr.arc(padding + r, yc, r, 0., TAU);
1215 cr.set_source_rgb(1., 1., 1.);
1216 cr.fill()?;
1217
1218 cr.new_sub_path();
1219 cr.arc(padding + r, yc, r - circle_stroke, 0., TAU);
1220 cr.set_source_rgb(0.1, 0.1, 0.1);
1221 cr.fill()?;
1222
1223 cr.new_sub_path();
1224 cr.arc(padding + r, yc, r - circle_stroke * 2., 0., TAU);
1225 cr.set_source_rgb(1., 1., 1.);
1226 cr.fill()?;
1227
1228 cr.move_to(padding + r * 2. + padding - half_border_width, padding);
1229
1230 let layout = pangocairo::functions::create_layout(&cr);
1231 layout.context().set_round_glyph_positions(false);
1232 layout.set_font_description(Some(&font));
1233 layout.set_alignment(Alignment::Left);
1234 layout.set_markup(text);
1235 layout.set_spacing(spacing);
1236
1237 cr.set_source_rgb(1., 1., 1.);
1238 pangocairo::functions::show_layout(&cr, &layout);
1239
1240 cr.move_to(0., 0.);
1241 cr.line_to(width.into(), 0.);
1242 cr.line_to(width.into(), height.into());
1243 cr.line_to(0., height.into());
1244 cr.line_to(0., 0.);
1245 cr.set_source_rgb(0.3, 0.3, 0.3);
1246 cr.set_line_width(border_width);
1247 cr.stroke()?;
1248 drop(cr);
1249
1250 let data = surface.take_data().unwrap();
1251 let buffer = TextureBuffer::from_memory(
1252 renderer,
1253 &data,
1254 Fourcc::Argb8888,
1255 (width, height),
1256 false,
1257 scale,
1258 Transform::Normal,
1259 Vec::new(),
1260 )?;
1261
1262 Ok(buffer)
1263}