forge
Explore
Log in

Don't you dare go Hollow

Implement area selection screenshots

Browse files at this commit

073b52c3e62e5c11528c7a8ad644e4a71edada53Ivan MolodetskikhParent: 31f6b32
resources/default-config.kdlmodified+2 -1
@@ -213,7 +213,8 @@ binds {
213213 Mod+Minus { set-column-width "-10%"; }
214214 Mod+Equal { set-column-width "+10%"; }
215215
216- Print { screenshot-screen; }
216+ Print { screenshot; }
217+ Ctrl+Print { screenshot-screen; }
217218 Alt+Print { screenshot-window; }
218219
219220 Mod+Shift+E { quit; }
src/config.rsmodified+5 -0
@@ -236,6 +236,11 @@ pub enum Action {
236236 PowerOffMonitors,
237237 ToggleDebugTint,
238238 Spawn(#[knuffel(arguments)] Vec<String>),
239+ #[knuffel(skip)]
240+ ConfirmScreenshot,
241+ #[knuffel(skip)]
242+ CancelScreenshot,
243+ Screenshot,
239244 ScreenshotScreen,
240245 ScreenshotWindow,
241246 CloseWindow,
src/input.rsmodified+105 -1
@@ -19,6 +19,7 @@ use smithay::wayland::tablet_manager::{TabletDescriptor, TabletSeatTrait};
1919
2020 use crate::config::{Action, Binds, Modifiers};
2121 use crate::niri::State;
22+use crate::screenshot_ui::ScreenshotUi;
2223 use crate::utils::{center, get_monotonic_time, spawn};
2324
2425 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -70,6 +71,7 @@ impl State {
7071 raw,
7172 pressed,
7273 *mods,
74+ &this.niri.screenshot_ui,
7375 )
7476 },
7577 ) else {
@@ -129,6 +131,32 @@ impl State {
129131 }
130132 }
131133 }
134+ Action::ConfirmScreenshot => {
135+ if let Some(renderer) = self.backend.renderer() {
136+ match self.niri.screenshot_ui.capture(renderer) {
137+ Ok((size, pixels)) => {
138+ if let Err(err) = self.niri.save_screenshot(size, pixels) {
139+ warn!("error saving screenshot: {err:?}");
140+ }
141+ }
142+ Err(err) => {
143+ warn!("error capturing screenshot: {err:?}");
144+ }
145+ }
146+ }
147+
148+ self.niri.screenshot_ui.close();
149+ self.niri.queue_redraw_all();
150+ }
151+ Action::CancelScreenshot => {
152+ self.niri.screenshot_ui.close();
153+ self.niri.queue_redraw_all();
154+ }
155+ Action::Screenshot => {
156+ if let Some(renderer) = self.backend.renderer() {
157+ self.niri.open_screenshot_ui(renderer);
158+ }
159+ }
132160 Action::ScreenshotWindow => {
133161 let active = self.niri.layout.active_window();
134162 if let Some((window, output)) = active {
@@ -335,6 +363,21 @@ impl State {
335363 }
336364 }
337365
366+ if let Some(output) = self.niri.screenshot_ui.selection_output() {
367+ let geom = self.niri.global_space.output_geometry(output).unwrap();
368+ let mut point = new_pos;
369+ point.x = point
370+ .x
371+ .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
372+ point.y = point
373+ .y
374+ .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
375+ let point = (point - geom.loc.to_f64())
376+ .to_physical(output.current_scale().fractional_scale())
377+ .to_i32_round();
378+ self.niri.screenshot_ui.pointer_motion(point);
379+ }
380+
338381 let under = self.niri.surface_under_and_global_space(new_pos);
339382 self.niri.pointer_focus = under.clone();
340383 let under = under.map(|u| u.surface);
@@ -378,6 +421,21 @@ impl State {
378421
379422 let pointer = self.niri.seat.get_pointer().unwrap();
380423
424+ if let Some(output) = self.niri.screenshot_ui.selection_output() {
425+ let geom = self.niri.global_space.output_geometry(output).unwrap();
426+ let mut point = pos;
427+ point.x = point
428+ .x
429+ .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
430+ point.y = point
431+ .y
432+ .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
433+ let point = (point - geom.loc.to_f64())
434+ .to_physical(output.current_scale().fractional_scale())
435+ .to_i32_round();
436+ self.niri.screenshot_ui.pointer_motion(point);
437+ }
438+
381439 let under = self.niri.surface_under_and_global_space(pos);
382440 self.niri.pointer_focus = under.clone();
383441 let under = under.map(|u| u.surface);
@@ -418,6 +476,34 @@ impl State {
418476
419477 self.update_pointer_focus();
420478
479+ if let Some(button) = event.button() {
480+ let pos = pointer.current_location();
481+ if let Some((output, _)) = self.niri.output_under(pos) {
482+ let output = output.clone();
483+ let geom = self.niri.global_space.output_geometry(&output).unwrap();
484+ let mut point = pos;
485+ // Re-clamp as pointer can be within 0.5 from the limit which will round up
486+ // to a wrong value.
487+ point.x = point
488+ .x
489+ .clamp(geom.loc.x as f64, (geom.loc.x + geom.size.w - 1) as f64);
490+ point.y = point
491+ .y
492+ .clamp(geom.loc.y as f64, (geom.loc.y + geom.size.h - 1) as f64);
493+ let point = (point - geom.loc.to_f64())
494+ .to_physical(output.current_scale().fractional_scale())
495+ .to_i32_round();
496+ if self.niri.screenshot_ui.pointer_button(
497+ output,
498+ point,
499+ button,
500+ button_state,
501+ ) {
502+ self.niri.queue_redraw_all();
503+ }
504+ }
505+ }
506+
421507 pointer.button(
422508 self,
423509 &ButtonEvent {
@@ -842,6 +928,7 @@ fn should_intercept_key(
842928 raw: Option<Keysym>,
843929 pressed: bool,
844930 mods: ModifiersState,
931+ screenshot_ui: &ScreenshotUi,
845932 ) -> FilterResult<Option<Action>> {
846933 // Actions are only triggered on presses, release of the key
847934 // shouldn't try to intercept anything unless we have marked
@@ -850,7 +937,20 @@ fn should_intercept_key(
850937 return FilterResult::Forward;
851938 }
852939
853- match (action(bindings, comp_mod, modified, raw, mods), pressed) {
940+ let mut final_action = action(bindings, comp_mod, modified, raw, mods);
941+ if screenshot_ui.is_open()
942+ // Allow only a subset of compositor actions while the screenshot UI is open,
943+ // since the user cannot see the screen.
944+ && !matches!(
945+ final_action,
946+ Some(Action::Quit | Action::ChangeVt(_) | Action::Suspend | Action::PowerOffMonitors)
947+ )
948+ {
949+ // Otherwise, use the screenshot UI action.
950+ final_action = screenshot_ui.action(raw, mods);
951+ }
952+
953+ match (final_action, pressed) {
854954 (Some(action), true) => {
855955 suppressed_keys.insert(key_code);
856956 FilterResult::Intercept(Some(action))
@@ -965,6 +1065,8 @@ mod tests {
9651065 let comp_mod = CompositorMod::Super;
9661066 let mut suppressed_keys = HashSet::new();
9671067
1068+ let screenshot_ui = ScreenshotUi::new();
1069+
9681070 // The key_code we pick is arbitrary, the only thing
9691071 // that matters is that they are different between cases.
9701072
@@ -979,6 +1081,7 @@ mod tests {
9791081 Some(close_keysym),
9801082 pressed,
9811083 mods,
1084+ &screenshot_ui,
9821085 )
9831086 };
9841087
@@ -993,6 +1096,7 @@ mod tests {
9931096 Some(Keysym::l),
9941097 pressed,
9951098 mods,
1099+ &screenshot_ui,
9961100 )
9971101 };
9981102
src/main.rsmodified+1 -0
@@ -12,6 +12,7 @@ mod handlers;
1212 mod input;
1313 mod layout;
1414 mod niri;
15+mod screenshot_ui;
1516 mod utils;
1617 mod watcher;
1718
src/niri.rsmodified+103 -14
@@ -20,6 +20,7 @@ use smithay::backend::renderer::element::{
2020 RenderElementStates,
2121 };
2222 use smithay::backend::renderer::gles::{GlesMapping, GlesRenderer, GlesTexture};
23+use smithay::backend::renderer::sync::SyncPoint;
2324 use smithay::backend::renderer::{Bind, ExportMem, Frame, ImportAll, Offscreen, Renderer};
2425 use smithay::desktop::utils::{
2526 bbox_from_surface_tree, output_update, send_dmabuf_feedback_surface_tree,
@@ -85,6 +86,7 @@ use crate::frame_clock::FrameClock;
8586 use crate::handlers::configure_lock_surface;
8687 use crate::layout::{output_size, Layout, MonitorRenderElement};
8788 use crate::pw_utils::{Cast, PipeWire};
89+use crate::screenshot_ui::{ScreenshotUi, ScreenshotUiRenderElement};
8890 use crate::utils::{center, get_monotonic_time, make_screenshot_path, write_png_rgba8};
8991
9092 const CLEAR_COLOR: [f32; 4] = [0.2, 0.2, 0.2, 1.];
@@ -150,6 +152,8 @@ pub struct Niri {
150152
151153 pub lock_state: LockState,
152154
155+ pub screenshot_ui: ScreenshotUi,
156+
153157 #[cfg(feature = "dbus")]
154158 pub dbus: Option<crate::dbus::DBusServers>,
155159 #[cfg(feature = "dbus")]
@@ -310,7 +314,7 @@ impl State {
310314 let pointer = &self.niri.seat.get_pointer().unwrap();
311315 let location = pointer.current_location();
312316
313- if !self.niri.is_locked() {
317+ if !self.niri.is_locked() && !self.niri.screenshot_ui.is_open() {
314318 // Don't refresh cursor focus during transitions.
315319 if let Some((output, _)) = self.niri.output_under(location) {
316320 let monitor = self.niri.layout.monitor_for_output(output).unwrap();
@@ -366,6 +370,8 @@ impl State {
366370 pub fn update_focus(&mut self) {
367371 let focus = if self.niri.is_locked() {
368372 self.niri.lock_surface_focus()
373+ } else if self.niri.screenshot_ui.is_open() {
374+ None
369375 } else {
370376 self.niri.layer_surface_focus().or_else(|| {
371377 self.niri
@@ -580,6 +586,8 @@ impl Niri {
580586 let cursor_manager =
581587 CursorManager::new(&config_.cursor.xcursor_theme, config_.cursor.xcursor_size);
582588
589+ let screenshot_ui = ScreenshotUi::new();
590+
583591 let socket_source = ListeningSocketSource::new_auto().unwrap();
584592 let socket_name = socket_source.socket_name().to_os_string();
585593 event_loop
@@ -657,6 +665,8 @@ impl Niri {
657665
658666 lock_state: LockState::Unlocked,
659667
668+ screenshot_ui,
669+
660670 #[cfg(feature = "dbus")]
661671 dbus: None,
662672 #[cfg(feature = "dbus")]
@@ -832,6 +842,10 @@ impl Niri {
832842 }
833843 lock_state => self.lock_state = lock_state,
834844 }
845+
846+ if self.screenshot_ui.close() {
847+ self.queue_redraw_all();
848+ }
835849 }
836850
837851 pub fn output_resized(&mut self, output: Output) {
@@ -852,6 +866,18 @@ impl Niri {
852866 }
853867 }
854868
869+ // If the output size changed with an open screenshot UI, close the screenshot UI.
870+ if let Some(old_size) = self.screenshot_ui.output_size(&output) {
871+ let output_transform = output.current_transform();
872+ let output_mode = output.current_mode().unwrap();
873+ let size = output_transform.transform_size(output_mode.size);
874+ if old_size != size {
875+ self.screenshot_ui.close();
876+ self.queue_redraw_all();
877+ return;
878+ }
879+ }
880+
855881 self.queue_redraw(output);
856882 }
857883
@@ -889,7 +915,7 @@ impl Niri {
889915 }
890916
891917 pub fn window_under_cursor(&self) -> Option<&Window> {
892- if self.is_locked() {
918+ if self.is_locked() || self.screenshot_ui.is_open() {
893919 return None;
894920 }
895921
@@ -928,6 +954,10 @@ impl Niri {
928954 });
929955 }
930956
957+ if self.screenshot_ui.is_open() {
958+ return None;
959+ }
960+
931961 let (window, win_pos_within_output) =
932962 self.layout.window_under(&output, pos_within_output)?;
933963
@@ -1321,6 +1351,32 @@ impl Niri {
13211351 return elements;
13221352 }
13231353
1354+ // Prepare the background element.
1355+ let state = self.output_state.get(output).unwrap();
1356+ let background = SolidColorRenderElement::from_buffer(
1357+ &state.background_buffer,
1358+ (0, 0),
1359+ output_scale,
1360+ 1.,
1361+ Kind::Unspecified,
1362+ )
1363+ .into();
1364+
1365+ // If the screenshot UI is open, draw it.
1366+ if self.screenshot_ui.is_open() {
1367+ elements.extend(
1368+ self.screenshot_ui
1369+ .render_output(output)
1370+ .into_iter()
1371+ .map(OutputRenderElements::from),
1372+ );
1373+
1374+ // Add the background for outputs that were connected while the screenshot UI was open.
1375+ elements.push(background);
1376+
1377+ return elements;
1378+ }
1379+
13241380 // Get monitor elements.
13251381 let mon = self.layout.monitor_for_output(output).unwrap();
13261382 let monitor_elements = mon.render_elements(renderer);
@@ -1363,17 +1419,7 @@ impl Niri {
13631419 extend_from_layer(&mut elements, Layer::Background);
13641420
13651421 // Then the background.
1366- let state = self.output_state.get(output).unwrap();
1367- elements.push(
1368- SolidColorRenderElement::from_buffer(
1369- &state.background_buffer,
1370- (0, 0),
1371- output_scale,
1372- 1.,
1373- Kind::Unspecified,
1374- )
1375- .into(),
1376- );
1422+ elements.push(background);
13771423
13781424 elements
13791425 }
@@ -1879,6 +1925,42 @@ impl Niri {
18791925 }
18801926 }
18811927
1928+ pub fn open_screenshot_ui(&mut self, renderer: &mut GlesRenderer) {
1929+ if self.is_locked() || self.screenshot_ui.is_open() {
1930+ return;
1931+ }
1932+
1933+ let Some(default_output) = self.output_under_cursor() else {
1934+ return;
1935+ };
1936+
1937+ let screenshots = self
1938+ .global_space
1939+ .outputs()
1940+ .cloned()
1941+ .filter_map(|output| {
1942+ let size = output.current_mode().unwrap().size;
1943+ let scale = Scale::from(output.current_scale().fractional_scale());
1944+ let elements = self.render(renderer, &output, true);
1945+
1946+ let res = render_to_texture(renderer, size, scale, Fourcc::Abgr8888, &elements);
1947+ let screenshot = match res {
1948+ Ok((texture, _)) => texture,
1949+ Err(err) => {
1950+ warn!("error rendering output {}: {err:?}", output.name());
1951+ return None;
1952+ }
1953+ };
1954+
1955+ Some((output, screenshot))
1956+ })
1957+ .collect();
1958+
1959+ self.screenshot_ui
1960+ .open(renderer, screenshots, default_output);
1961+ self.queue_redraw_all();
1962+ }
1963+
18821964 pub fn screenshot(&self, renderer: &mut GlesRenderer, output: &Output) -> anyhow::Result<()> {
18831965 let _span = tracy_client::span!("Niri::screenshot");
18841966
@@ -1916,7 +1998,11 @@ impl Niri {
19161998 .context("error saving screenshot")
19171999 }
19182000
1919- fn save_screenshot(&self, size: Size<i32, Physical>, pixels: Vec<u8>) -> anyhow::Result<()> {
2001+ pub fn save_screenshot(
2002+ &self,
2003+ size: Size<i32, Physical>,
2004+ pixels: Vec<u8>,
2005+ ) -> anyhow::Result<()> {
19202006 let path = make_screenshot_path().context("error making screenshot path")?;
19212007 debug!("saving screenshot to {path:?}");
19222008
@@ -2029,6 +2115,8 @@ impl Niri {
20292115 pub fn lock(&mut self, confirmation: SessionLocker) {
20302116 info!("locking session");
20312117
2118+ self.screenshot_ui.close();
2119+
20322120 self.lock_state = LockState::Locking(confirmation);
20332121 self.queue_redraw_all();
20342122 }
@@ -2065,6 +2153,7 @@ render_elements! {
20652153 Wayland = WaylandSurfaceRenderElement<R>,
20662154 NamedPointer = TextureRenderElement<<R as Renderer>::TextureId>,
20672155 SolidColor = SolidColorRenderElement,
2156+ ScreenshotUi = ScreenshotUiRenderElement<R>,
20682157 }
20692158
20702159 #[derive(Default)]
src/screenshot_ui.rsadded+448 -0
@@ -0,0 +1,448 @@
1+use std::cmp::{max, min};
2+use std::collections::HashMap;
3+use std::iter::zip;
4+use std::mem;
5+
6+use anyhow::Context;
7+use arrayvec::ArrayVec;
8+use smithay::backend::allocator::Fourcc;
9+use smithay::backend::input::{ButtonState, MouseButton};
10+use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
11+use smithay::backend::renderer::element::texture::{TextureBuffer, TextureRenderElement};
12+use smithay::backend::renderer::element::Kind;
13+use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
14+use smithay::backend::renderer::ExportMem;
15+use smithay::input::keyboard::{Keysym, ModifiersState};
16+use smithay::output::{Output, WeakOutput};
17+use smithay::render_elements;
18+use smithay::utils::{Physical, Point, Rectangle, Size, Transform};
19+
20+use crate::config::Action;
21+
22+const BORDER: i32 = 2;
23+
24+// Ideally the screenshot UI should support cross-output selections. However, that poses some
25+// technical challenges when the outputs have different scales and such. So, this implementation
26+// allows only single-output selections for now.
27+//
28+// As a consequence of this, selection coordinates are in output-local coordinate space.
29+pub enum ScreenshotUi {
30+ Closed {
31+ last_selection: Option<(WeakOutput, Rectangle<i32, Physical>)>,
32+ },
33+ Open {
34+ selection: (Output, Point<i32, Physical>, Point<i32, Physical>),
35+ output_data: HashMap<Output, OutputData>,
36+ mouse_down: bool,
37+ },
38+}
39+
40+pub struct OutputData {
41+ size: Size<i32, Physical>,
42+ texture: GlesTexture,
43+ texture_buffer: TextureBuffer<GlesTexture>,
44+ buffers: [SolidColorBuffer; 8],
45+ locations: [Point<i32, Physical>; 8],
46+}
47+
48+render_elements! {
49+ #[derive(Debug)]
50+ pub ScreenshotUiRenderElement<R>;
51+ Screenshot = TextureRenderElement<R::TextureId>,
52+ SolidColor = SolidColorRenderElement,
53+}
54+
55+impl ScreenshotUi {
56+ pub fn new() -> Self {
57+ Self::Closed {
58+ last_selection: None,
59+ }
60+ }
61+
62+ pub fn open(
63+ &mut self,
64+ renderer: &GlesRenderer,
65+ screenshots: HashMap<Output, GlesTexture>,
66+ default_output: Output,
67+ ) -> bool {
68+ if screenshots.is_empty() {
69+ return false;
70+ }
71+
72+ let Self::Closed { last_selection } = self else {
73+ return false;
74+ };
75+
76+ let last_selection = last_selection
77+ .take()
78+ .and_then(|(weak, sel)| weak.upgrade().map(|output| (output, sel)));
79+ let selection = match last_selection {
80+ Some(selection) if screenshots.contains_key(&selection.0) => selection,
81+ _ => {
82+ let output = default_output;
83+ let output_transform = output.current_transform();
84+ let output_mode = output.current_mode().unwrap();
85+ let size = output_transform.transform_size(output_mode.size);
86+ (
87+ output,
88+ Rectangle::from_loc_and_size(
89+ (size.w / 4, size.h / 4),
90+ (size.w / 2, size.h / 2),
91+ ),
92+ )
93+ }
94+ };
95+ let scale = selection.0.current_scale().integer_scale();
96+ let selection = (
97+ selection.0,
98+ selection.1.loc,
99+ selection.1.loc + selection.1.size - Size::from((scale, scale)),
100+ );
101+
102+ let output_data = screenshots
103+ .into_iter()
104+ .map(|(output, texture)| {
105+ let output_transform = output.current_transform();
106+ let output_mode = output.current_mode().unwrap();
107+ let size = output_transform.transform_size(output_mode.size);
108+ let texture_buffer = TextureBuffer::from_texture(
109+ renderer,
110+ texture.clone(),
111+ output.current_scale().integer_scale(),
112+ Transform::Normal,
113+ None,
114+ );
115+ let buffers = [
116+ SolidColorBuffer::new((0, 0), [1., 1., 1., 1.]),
117+ SolidColorBuffer::new((0, 0), [1., 1., 1., 1.]),
118+ SolidColorBuffer::new((0, 0), [1., 1., 1., 1.]),
119+ SolidColorBuffer::new((0, 0), [1., 1., 1., 1.]),
120+ SolidColorBuffer::new((0, 0), [0., 0., 0., 0.5]),
121+ SolidColorBuffer::new((0, 0), [0., 0., 0., 0.5]),
122+ SolidColorBuffer::new((0, 0), [0., 0., 0., 0.5]),
123+ SolidColorBuffer::new((0, 0), [0., 0., 0., 0.5]),
124+ ];
125+ let locations = [Default::default(); 8];
126+ let data = OutputData {
127+ size,
128+ texture,
129+ texture_buffer,
130+ buffers,
131+ locations,
132+ };
133+ (output, data)
134+ })
135+ .collect();
136+
137+ *self = Self::Open {
138+ selection,
139+ output_data,
140+ mouse_down: false,
141+ };
142+
143+ self.update_buffers();
144+
145+ true
146+ }
147+
148+ pub fn close(&mut self) -> bool {
149+ let selection = match mem::take(self) {
150+ Self::Open { selection, .. } => selection,
151+ closed @ Self::Closed { .. } => {
152+ // Put it back.
153+ *self = closed;
154+ return false;
155+ }
156+ };
157+
158+ let scale = selection.0.current_scale().integer_scale();
159+ let last_selection = Some((
160+ selection.0.downgrade(),
161+ rect_from_corner_points(selection.1, selection.2, scale),
162+ ));
163+
164+ *self = Self::Closed { last_selection };
165+
166+ true
167+ }
168+
169+ pub fn is_open(&self) -> bool {
170+ matches!(self, ScreenshotUi::Open { .. })
171+ }
172+
173+ fn update_buffers(&mut self) {
174+ let Self::Open {
175+ selection,
176+ output_data,
177+ ..
178+ } = self
179+ else {
180+ panic!("screenshot UI must be open to update buffers");
181+ };
182+
183+ let (selection_output, a, b) = selection;
184+ let scale = selection_output.current_scale().integer_scale();
185+ let mut rect = rect_from_corner_points(*a, *b, scale);
186+
187+ for (output, data) in output_data {
188+ let buffers = &mut data.buffers;
189+ let locations = &mut data.locations;
190+ let size = data.size;
191+
192+ if output == selection_output {
193+ let scale = output.current_scale().integer_scale();
194+
195+ // Check if the selection is still valid. If not, reset it back to default.
196+ if !Rectangle::from_loc_and_size((0, 0), size).contains_rect(rect) {
197+ rect = Rectangle::from_loc_and_size(
198+ (size.w / 4, size.h / 4),
199+ (size.w / 2, size.h / 2),
200+ );
201+ *a = rect.loc;
202+ *b = rect.loc + rect.size - Size::from((scale, scale));
203+ }
204+
205+ let border = BORDER * scale;
206+
207+ buffers[0].resize((rect.size.w + border * 2, border));
208+ buffers[1].resize((rect.size.w + border * 2, border));
209+ buffers[2].resize((border, rect.size.h));
210+ buffers[3].resize((border, rect.size.h));
211+
212+ buffers[4].resize((size.w, rect.loc.y));
213+ buffers[5].resize((size.w, size.h - rect.loc.y - rect.size.h));
214+ buffers[6].resize((rect.loc.x, rect.size.h));
215+ buffers[7].resize((size.w - rect.loc.x - rect.size.w, rect.size.h));
216+
217+ locations[0] = Point::from((rect.loc.x - border, rect.loc.y - border));
218+ locations[1] = Point::from((rect.loc.x - border, rect.loc.y + rect.size.h));
219+ locations[2] = Point::from((rect.loc.x - border, rect.loc.y));
220+ locations[3] = Point::from((rect.loc.x + rect.size.w, rect.loc.y));
221+
222+ locations[5] = Point::from((0, rect.loc.y + rect.size.h));
223+ locations[6] = Point::from((0, rect.loc.y));
224+ locations[7] = Point::from((rect.loc.x + rect.size.w, rect.loc.y));
225+ } else {
226+ buffers[0].resize((0, 0));
227+ buffers[1].resize((0, 0));
228+ buffers[2].resize((0, 0));
229+ buffers[3].resize((0, 0));
230+
231+ buffers[4].resize(size.to_logical(1));
232+ buffers[5].resize((0, 0));
233+ buffers[6].resize((0, 0));
234+ buffers[7].resize((0, 0));
235+ }
236+ }
237+ }
238+
239+ pub fn render_output(
240+ &self,
241+ output: &Output,
242+ ) -> ArrayVec<ScreenshotUiRenderElement<GlesRenderer>, 9> {
243+ let _span = tracy_client::span!("ScreenshotUi::render_output");
244+
245+ let Self::Open { output_data, .. } = self else {
246+ panic!("screenshot UI must be open to render it");
247+ };
248+
249+ let mut elements = ArrayVec::new();
250+
251+ let Some(output_data) = output_data.get(output) else {
252+ return elements;
253+ };
254+
255+ let buf_loc = zip(&output_data.buffers, &output_data.locations);
256+ elements.extend(buf_loc.map(|(buffer, loc)| {
257+ SolidColorRenderElement::from_buffer(
258+ buffer,
259+ *loc,
260+ 1., // We treat these as physical coordinates.
261+ 1.,
262+ Kind::Unspecified,
263+ )
264+ .into()
265+ }));
266+
267+ // The screenshot itself goes last.
268+ elements.push(
269+ TextureRenderElement::from_texture_buffer(
270+ (0., 0.),
271+ &output_data.texture_buffer,
272+ None,
273+ None,
274+ None,
275+ Kind::Unspecified,
276+ )
277+ .into(),
278+ );
279+
280+ elements
281+ }
282+
283+ pub fn capture(
284+ &self,
285+ renderer: &mut GlesRenderer,
286+ ) -> anyhow::Result<(Size<i32, Physical>, Vec<u8>)> {
287+ let _span = tracy_client::span!("ScreenshotUi::capture");
288+
289+ let Self::Open {
290+ selection,
291+ output_data,
292+ ..
293+ } = self
294+ else {
295+ panic!("screenshot UI must be open to capture");
296+ };
297+
298+ let data = &output_data[&selection.0];
299+ let scale = selection.0.current_scale().integer_scale();
300+ let rect = rect_from_corner_points(selection.1, selection.2, scale);
301+ let buf_rect = rect
302+ .to_logical(1)
303+ .to_buffer(1, Transform::Normal, &data.size.to_logical(1));
304+
305+ let mapping = renderer
306+ .copy_texture(&data.texture, buf_rect, Fourcc::Abgr8888)
307+ .context("error copying texture")?;
308+ let copy = renderer
309+ .map_texture(&mapping)
310+ .context("error mapping texture")?;
311+
312+ Ok((rect.size, copy.to_vec()))
313+ }
314+
315+ pub fn action(&self, raw: Option<Keysym>, mods: ModifiersState) -> Option<Action> {
316+ if !matches!(self, Self::Open { .. }) {
317+ return None;
318+ }
319+
320+ action(raw?, mods)
321+ }
322+
323+ pub fn selection_output(&self) -> Option<&Output> {
324+ if let Self::Open {
325+ selection: (output, _, _),
326+ ..
327+ } = self
328+ {
329+ Some(output)
330+ } else {
331+ None
332+ }
333+ }
334+
335+ pub fn output_size(&self, output: &Output) -> Option<Size<i32, Physical>> {
336+ if let Self::Open { output_data, .. } = self {
337+ Some(output_data.get(output)?.size)
338+ } else {
339+ None
340+ }
341+ }
342+
343+ /// The pointer has moved to `point` relative to the current selection output.
344+ pub fn pointer_motion(&mut self, point: Point<i32, Physical>) {
345+ let Self::Open {
346+ selection,
347+ mouse_down: true,
348+ ..
349+ } = self
350+ else {
351+ return;
352+ };
353+
354+ selection.2 = point;
355+ self.update_buffers();
356+ }
357+
358+ pub fn pointer_button(
359+ &mut self,
360+ output: Output,
361+ point: Point<i32, Physical>,
362+ button: MouseButton,
363+ state: ButtonState,
364+ ) -> bool {
365+ let Self::Open {
366+ selection,
367+ output_data,
368+ mouse_down,
369+ } = self
370+ else {
371+ return false;
372+ };
373+
374+ if button != MouseButton::Left {
375+ return false;
376+ }
377+
378+ let down = state == ButtonState::Pressed;
379+ if *mouse_down == down {
380+ return false;
381+ }
382+
383+ if !output_data.contains_key(&output) {
384+ return false;
385+ }
386+
387+ *mouse_down = down;
388+
389+ if down {
390+ *selection = (output, point, point);
391+ } else {
392+ // Check if the resulting selection is zero-sized, and try to come up with a small
393+ // default rectangle.
394+ let (output, a, b) = selection;
395+ let scale = output.current_scale().integer_scale();
396+ let mut rect = rect_from_corner_points(*a, *b, scale);
397+ if rect.size.is_empty() || rect.size == Size::from((scale, scale)) {
398+ let data = &output_data[output];
399+ rect = Rectangle::from_loc_and_size((rect.loc.x - 16, rect.loc.y - 16), (32, 32))
400+ .intersection(Rectangle::from_loc_and_size((0, 0), data.size))
401+ .unwrap_or_default();
402+ let scale = output.current_scale().integer_scale();
403+ *a = rect.loc;
404+ *b = rect.loc + rect.size - Size::from((scale, scale));
405+ }
406+ }
407+
408+ self.update_buffers();
409+
410+ true
411+ }
412+}
413+
414+impl Default for ScreenshotUi {
415+ fn default() -> Self {
416+ Self::new()
417+ }
418+}
419+
420+fn action(raw: Keysym, mods: ModifiersState) -> Option<Action> {
421+ if raw == Keysym::Escape {
422+ return Some(Action::CancelScreenshot);
423+ }
424+
425+ if mods.alt || mods.shift {
426+ return None;
427+ }
428+
429+ if (mods.ctrl && raw == Keysym::c)
430+ || (!mods.ctrl && (raw == Keysym::space || raw == Keysym::Return))
431+ {
432+ return Some(Action::ConfirmScreenshot);
433+ }
434+
435+ None
436+}
437+
438+pub fn rect_from_corner_points(
439+ a: Point<i32, Physical>,
440+ b: Point<i32, Physical>,
441+ scale: i32,
442+) -> Rectangle<i32, Physical> {
443+ let x1 = min(a.x, b.x);
444+ let y1 = min(a.y, b.y);
445+ let x2 = max(a.x, b.x);
446+ let y2 = max(a.y, b.y);
447+ Rectangle::from_extemities((x1, y1), (x2 + scale, y2 + scale))
448+}