forge
Explore
Log in

Don't you dare go Hollow

Support color picker functionality

Browse files at this commit

7210045b2a058c4be7bef6fd2059f337bf53b1ecnnyyxxxxParent: ed20822
  • feat
    • support color picker functionality
Show full message
feat: support color picker functionality

chore: format code

refactor: improve quality

feat: implement gnomes PickColor method

refactor: minor code extraction

misc: fix reviews

fixes
niri-ipc/src/lib.rsmodified+12 -0
@@ -65,6 +65,8 @@ pub enum Request {
65 FocusedWindow,65 FocusedWindow,
66 /// Request picking a window and get its information.66 /// Request picking a window and get its information.
67 PickWindow,67 PickWindow,
68+ /// Request picking a color from the screen.
69+ PickColor,
68 /// Perform an action.70 /// Perform an action.
69 Action(Action),71 Action(Action),
70 /// Change output configuration temporarily.72 /// Change output configuration temporarily.
@@ -133,10 +135,20 @@ pub enum Response {
133 FocusedWindow(Option<Window>),135 FocusedWindow(Option<Window>),
134 /// Information about the picked window.136 /// Information about the picked window.
135 PickedWindow(Option<Window>),137 PickedWindow(Option<Window>),
138+ /// Information about the picked color.
139+ PickedColor(Option<PickedColor>),
136 /// Output configuration change result.140 /// Output configuration change result.
137 OutputConfigChanged(OutputConfigChanged),141 OutputConfigChanged(OutputConfigChanged),
138 }142 }
139 143
144+/// Color picked from the screen.
145+#[derive(Serialize, Deserialize, Debug, Clone)]
146+#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
147+pub struct PickedColor {
148+ /// Color values as red, green, blue, each ranging from 0.0 to 1.0.
149+ pub rgb: [f64; 3],
150+}
151+
140 /// Actions that niri can perform.152 /// Actions that niri can perform.
141 // Variants in this enum should match the spelling of the ones in niri-config. Most, but not all,153 // Variants in this enum should match the spelling of the ones in niri-config. Most, but not all,
142 // variants from niri-config should be present here.154 // variants from niri-config should be present here.
src/cli.rsmodified+2 -0
@@ -77,6 +77,8 @@ pub enum Msg {
77 FocusedWindow,77 FocusedWindow,
78 /// Pick a window with the mouse and print information about it.78 /// Pick a window with the mouse and print information about it.
79 PickWindow,79 PickWindow,
80+ /// Pick a color from the screen with the mouse.
81+ PickColor,
80 /// Perform an action.82 /// Perform an action.
81 Action {83 Action {
82 #[command(subcommand)]84 #[command(subcommand)]
src/dbus/gnome_shell_screenshot.rsmodified+32 -0
@@ -1,7 +1,10 @@
1+use std::collections::HashMap;
1 use std::path::PathBuf;2 use std::path::PathBuf;
2 3
4+use niri_ipc::PickedColor;
3 use zbus::fdo::{self, RequestNameFlags};5 use zbus::fdo::{self, RequestNameFlags};
4 use zbus::interface;6 use zbus::interface;
7+use zbus::zvariant::OwnedValue;
5 8
6 use super::Start;9 use super::Start;
7 10
@@ -12,6 +15,7 @@ pub struct Screenshot {
12 15
13 pub enum ScreenshotToNiri {16 pub enum ScreenshotToNiri {
14 TakeScreenshot { include_cursor: bool },17 TakeScreenshot { include_cursor: bool },
18+ PickColor(async_channel::Sender<Option<PickedColor>>),
15 }19 }
16 20
17 pub enum NiriToScreenshot {21 pub enum NiriToScreenshot {
@@ -47,6 +51,34 @@ impl Screenshot {
47 51
48 Ok((true, filename))52 Ok((true, filename))
49 }53 }
54+
55+ async fn pick_color(&self) -> fdo::Result<HashMap<String, OwnedValue>> {
56+ let (tx, rx) = async_channel::bounded(1);
57+ if let Err(err) = self.to_niri.send(ScreenshotToNiri::PickColor(tx)) {
58+ warn!("error sending pick color message to niri: {err:?}");
59+ return Err(fdo::Error::Failed("internal error".to_owned()));
60+ }
61+
62+ let color = match rx.recv().await {
63+ Ok(Some(color)) => color,
64+ Ok(None) => {
65+ return Err(fdo::Error::Failed("no color picked".to_owned()));
66+ }
67+ Err(err) => {
68+ warn!("error receiving message from niri: {err:?}");
69+ return Err(fdo::Error::Failed("internal error".to_owned()));
70+ }
71+ };
72+
73+ let mut result = HashMap::new();
74+ let rgb_slice: &[f64] = &color.rgb;
75+ result.insert(
76+ "color".to_string(),
77+ zbus::zvariant::Value::from(rgb_slice).try_into().unwrap(),
78+ );
79+
80+ Ok(result)
81+ }
50 }82 }
51 83
52 impl Screenshot {84 impl Screenshot {
src/input/mod.rsmodified+5 -1
@@ -48,6 +48,7 @@ use crate::utils::{center, get_monotonic_time, ResizeEdge};
48 48
49 pub mod backend_ext;49 pub mod backend_ext;
50 pub mod move_grab;50 pub mod move_grab;
51+pub mod pick_color_grab;
51 pub mod pick_window_grab;52 pub mod pick_window_grab;
52 pub mod resize_grab;53 pub mod resize_grab;
53 pub mod scroll_tracker;54 pub mod scroll_tracker;
@@ -377,7 +378,10 @@ impl State {
377 }378 }
378 }379 }
379 380
380- if pressed && raw == Some(Keysym::Escape) && this.niri.pick_window.is_some() {381+ if pressed
382+ && raw == Some(Keysym::Escape)
383+ && (this.niri.pick_window.is_some() || this.niri.pick_color.is_some())
384+ {
381 // We window picking state so the pick window grab must be active.385 // We window picking state so the pick window grab must be active.
382 // Unsetting it cancels window picking.386 // Unsetting it cancels window picking.
383 this.niri387 this.niri
src/input/pick_color_grab.rsadded+223 -0
@@ -0,0 +1,223 @@
1+use niri_ipc::PickedColor;
2+use smithay::backend::allocator::Fourcc;
3+use smithay::backend::input::ButtonState;
4+use smithay::backend::renderer::element::utils::{Relocate, RelocateRenderElement};
5+use smithay::input::pointer::{
6+ AxisFrame, ButtonEvent, CursorImageStatus, GestureHoldBeginEvent, GestureHoldEndEvent,
7+ GesturePinchBeginEvent, GesturePinchEndEvent, GesturePinchUpdateEvent, GestureSwipeBeginEvent,
8+ GestureSwipeEndEvent, GestureSwipeUpdateEvent, GrabStartData as PointerGrabStartData,
9+ MotionEvent, PointerGrab, PointerInnerHandle, RelativeMotionEvent,
10+};
11+use smithay::input::SeatHandler;
12+use smithay::utils::{Logical, Physical, Point, Scale, Size, Transform};
13+
14+use crate::niri::State;
15+use crate::render_helpers::render_to_vec;
16+
17+pub struct PickColorGrab {
18+ start_data: PointerGrabStartData<State>,
19+}
20+
21+impl PickColorGrab {
22+ pub fn new(start_data: PointerGrabStartData<State>) -> Self {
23+ Self { start_data }
24+ }
25+
26+ fn on_ungrab(&mut self, state: &mut State) {
27+ if let Some(tx) = state.niri.pick_color.take() {
28+ let _ = tx.send_blocking(None);
29+ }
30+ state
31+ .niri
32+ .cursor_manager
33+ .set_cursor_image(CursorImageStatus::default_named());
34+ state.niri.queue_redraw_all();
35+ }
36+
37+ fn pick_color_at_point(location: Point<f64, Logical>, data: &mut State) -> Option<PickedColor> {
38+ let (output, pos_within_output) = data.niri.output_under(location)?;
39+ let output = output.clone();
40+
41+ data.backend
42+ .with_primary_renderer(|renderer| {
43+ data.niri.update_render_elements(Some(&output));
44+
45+ let scale = Scale::from(output.current_scale().fractional_scale());
46+ // FIXME: perhaps replace floor with round once we figure out the pointer behavior
47+ // at the bottom/right edges of the monitors.
48+ let pos = pos_within_output.to_physical_precise_floor(scale);
49+ let size = Size::<i32, Physical>::from((1, 1));
50+
51+ let elements = data.niri.render(
52+ renderer,
53+ &output,
54+ false,
55+ crate::render_helpers::RenderTarget::ScreenCapture,
56+ );
57+
58+ let pixels = match render_to_vec(
59+ renderer,
60+ size,
61+ scale,
62+ Transform::Normal,
63+ Fourcc::Abgr8888,
64+ elements.iter().rev().map(|elem| {
65+ let offset = pos.upscale(-1);
66+ RelocateRenderElement::from_element(elem, offset, Relocate::Relative)
67+ }),
68+ ) {
69+ Ok(pixels) => pixels,
70+ Err(_) => return None,
71+ };
72+
73+ if pixels.len() == 4 {
74+ let rgb = [
75+ f64::from(pixels[0]) / 255.0,
76+ f64::from(pixels[1]) / 255.0,
77+ f64::from(pixels[2]) / 255.0,
78+ ];
79+ Some(PickedColor { rgb })
80+ } else {
81+ error!(
82+ "unexpected pixel data length: {} (expected 4)",
83+ pixels.len()
84+ );
85+ None
86+ }
87+ })
88+ .flatten()
89+ }
90+}
91+
92+impl PointerGrab<State> for PickColorGrab {
93+ fn motion(
94+ &mut self,
95+ data: &mut State,
96+ handle: &mut PointerInnerHandle<'_, State>,
97+ _focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
98+ event: &MotionEvent,
99+ ) {
100+ handle.motion(data, None, event);
101+ }
102+
103+ fn relative_motion(
104+ &mut self,
105+ data: &mut State,
106+ handle: &mut PointerInnerHandle<'_, State>,
107+ _focus: Option<(<State as SeatHandler>::PointerFocus, Point<f64, Logical>)>,
108+ event: &RelativeMotionEvent,
109+ ) {
110+ handle.relative_motion(data, None, event);
111+ }
112+
113+ fn button(
114+ &mut self,
115+ data: &mut State,
116+ handle: &mut PointerInnerHandle<'_, State>,
117+ event: &ButtonEvent,
118+ ) {
119+ if event.state != ButtonState::Pressed {
120+ return;
121+ }
122+
123+ if let Some(tx) = data.niri.pick_color.take() {
124+ let color = Self::pick_color_at_point(handle.current_location(), data);
125+ let _ = tx.send_blocking(color);
126+ }
127+
128+ handle.unset_grab(self, data, event.serial, event.time, true);
129+ }
130+
131+ fn axis(
132+ &mut self,
133+ data: &mut State,
134+ handle: &mut PointerInnerHandle<'_, State>,
135+ details: AxisFrame,
136+ ) {
137+ handle.axis(data, details);
138+ }
139+
140+ fn frame(&mut self, data: &mut State, handle: &mut PointerInnerHandle<'_, State>) {
141+ handle.frame(data);
142+ }
143+
144+ fn gesture_swipe_begin(
145+ &mut self,
146+ data: &mut State,
147+ handle: &mut PointerInnerHandle<'_, State>,
148+ event: &GestureSwipeBeginEvent,
149+ ) {
150+ handle.gesture_swipe_begin(data, event);
151+ }
152+
153+ fn gesture_swipe_update(
154+ &mut self,
155+ data: &mut State,
156+ handle: &mut PointerInnerHandle<'_, State>,
157+ event: &GestureSwipeUpdateEvent,
158+ ) {
159+ handle.gesture_swipe_update(data, event);
160+ }
161+
162+ fn gesture_swipe_end(
163+ &mut self,
164+ data: &mut State,
165+ handle: &mut PointerInnerHandle<'_, State>,
166+ event: &GestureSwipeEndEvent,
167+ ) {
168+ handle.gesture_swipe_end(data, event);
169+ }
170+
171+ fn gesture_pinch_begin(
172+ &mut self,
173+ data: &mut State,
174+ handle: &mut PointerInnerHandle<'_, State>,
175+ event: &GesturePinchBeginEvent,
176+ ) {
177+ handle.gesture_pinch_begin(data, event);
178+ }
179+
180+ fn gesture_pinch_update(
181+ &mut self,
182+ data: &mut State,
183+ handle: &mut PointerInnerHandle<'_, State>,
184+ event: &GesturePinchUpdateEvent,
185+ ) {
186+ handle.gesture_pinch_update(data, event);
187+ }
188+
189+ fn gesture_pinch_end(
190+ &mut self,
191+ data: &mut State,
192+ handle: &mut PointerInnerHandle<'_, State>,
193+ event: &GesturePinchEndEvent,
194+ ) {
195+ handle.gesture_pinch_end(data, event);
196+ }
197+
198+ fn gesture_hold_begin(
199+ &mut self,
200+ data: &mut State,
201+ handle: &mut PointerInnerHandle<'_, State>,
202+ event: &GestureHoldBeginEvent,
203+ ) {
204+ handle.gesture_hold_begin(data, event);
205+ }
206+
207+ fn gesture_hold_end(
208+ &mut self,
209+ data: &mut State,
210+ handle: &mut PointerInnerHandle<'_, State>,
211+ event: &GestureHoldEndEvent,
212+ ) {
213+ handle.gesture_hold_end(data, event);
214+ }
215+
216+ fn start_data(&self) -> &PointerGrabStartData<State> {
217+ &self.start_data
218+ }
219+
220+ fn unset(&mut self, data: &mut State) {
221+ self.on_ungrab(data);
222+ }
223+}
src/ipc/client.rsmodified+21 -0
@@ -20,6 +20,7 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
20 Msg::FocusedWindow => Request::FocusedWindow,20 Msg::FocusedWindow => Request::FocusedWindow,
21 Msg::FocusedOutput => Request::FocusedOutput,21 Msg::FocusedOutput => Request::FocusedOutput,
22 Msg::PickWindow => Request::PickWindow,22 Msg::PickWindow => Request::PickWindow,
23+ Msg::PickColor => Request::PickColor,
23 Msg::Action { action } => Request::Action(action.clone()),24 Msg::Action { action } => Request::Action(action.clone()),
24 Msg::Output { output, action } => Request::Output {25 Msg::Output { output, action } => Request::Output {
25 output: output.clone(),26 output: output.clone(),
@@ -270,6 +271,26 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
270 println!("No window selected.");271 println!("No window selected.");
271 }272 }
272 }273 }
274+ Msg::PickColor => {
275+ let Response::PickedColor(color) = response else {
276+ bail!("unexpected response: expected PickedColor, got {response:?}");
277+ };
278+
279+ if json {
280+ let color = serde_json::to_string(&color).context("error formatting response")?;
281+ println!("{color}");
282+ return Ok(());
283+ }
284+
285+ if let Some(color) = color {
286+ let [r, g, b] = color.rgb.map(|v| (v.clamp(0., 1.) * 255.).round() as u8);
287+
288+ println!("Picked color: rgb({r}, {g}, {b})",);
289+ println!("Hex: #{:02x}{:02x}{:02x}", r, g, b);
290+ } else {
291+ println!("No color was picked.");
292+ }
293+ }
273 Msg::Action { .. } => {294 Msg::Action { .. } => {
274 let Response::Handled = response else {295 let Response::Handled = response else {
275 bail!("unexpected response: expected Handled, got {response:?}");296 bail!("unexpected response: expected Handled, got {response:?}");
src/ipc/server.rsmodified+9 -0
@@ -356,6 +356,15 @@ async fn process(ctx: &ClientCtx, request: Request) -> Reply {
356 });356 });
357 Response::PickedWindow(window)357 Response::PickedWindow(window)
358 }358 }
359+ Request::PickColor => {
360+ let (tx, rx) = async_channel::bounded(1);
361+ ctx.event_loop.insert_idle(move |state| {
362+ state.handle_pick_color(tx);
363+ });
364+ let result = rx.recv().await;
365+ let color = result.map_err(|_| String::from("error getting picked color"))?;
366+ Response::PickedColor(color)
367+ }
359 Request::Action(action) => {368 Request::Action(action) => {
360 let (tx, rx) = async_channel::bounded(1);369 let (tx, rx) = async_channel::bounded(1);
361 370
src/niri.rsmodified+39 -2
@@ -45,7 +45,10 @@ use smithay::desktop::{
45 PopupUngrabStrategy, Space, Window, WindowSurfaceType,45 PopupUngrabStrategy, Space, Window, WindowSurfaceType,
46 };46 };
47 use smithay::input::keyboard::Layout as KeyboardLayout;47 use smithay::input::keyboard::Layout as KeyboardLayout;
48-use smithay::input::pointer::{CursorIcon, CursorImageStatus, CursorImageSurfaceData, MotionEvent};48+use smithay::input::pointer::{
49+ CursorIcon, CursorImageStatus, CursorImageSurfaceData, Focus,
50+ GrabStartData as PointerGrabStartData, MotionEvent,
51+};
49 use smithay::input::{Seat, SeatState};52 use smithay::input::{Seat, SeatState};
50 use smithay::output::{self, Output, OutputModeSource, PhysicalProperties, Subpixel, WeakOutput};53 use smithay::output::{self, Output, OutputModeSource, PhysicalProperties, Subpixel, WeakOutput};
51 use smithay::reexports::calloop::generic::Generic;54 use smithay::reexports::calloop::generic::Generic;
@@ -118,6 +121,7 @@ use crate::dbus::gnome_shell_screenshot::{NiriToScreenshot, ScreenshotToNiri};
118 use crate::dbus::mutter_screen_cast::{self, ScreenCastToNiri};121 use crate::dbus::mutter_screen_cast::{self, ScreenCastToNiri};
119 use crate::frame_clock::FrameClock;122 use crate::frame_clock::FrameClock;
120 use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};123 use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};
124+use crate::input::pick_color_grab::PickColorGrab;
121 use crate::input::scroll_tracker::ScrollTracker;125 use crate::input::scroll_tracker::ScrollTracker;
122 use crate::input::{126 use crate::input::{
123 apply_libinput_settings, mods_with_finger_scroll_binds, mods_with_mouse_binds,127 apply_libinput_settings, mods_with_finger_scroll_binds, mods_with_mouse_binds,
@@ -358,6 +362,7 @@ pub struct Niri {
358 pub exit_confirm_dialog: Option<ExitConfirmDialog>,362 pub exit_confirm_dialog: Option<ExitConfirmDialog>,
359 363
360 pub pick_window: Option<async_channel::Sender<Option<MappedId>>>,364 pub pick_window: Option<async_channel::Sender<Option<MappedId>>>,
365+ pub pick_color: Option<async_channel::Sender<Option<niri_ipc::PickedColor>>>,
361 366
362 pub debug_draw_opaque_regions: bool,367 pub debug_draw_opaque_regions: bool,
363 pub debug_draw_damage: bool,368 pub debug_draw_damage: bool,
@@ -1612,6 +1617,22 @@ impl State {
1612 self.niri.queue_redraw_all();1617 self.niri.queue_redraw_all();
1613 }1618 }
1614 1619
1620+ pub fn handle_pick_color(&mut self, tx: async_channel::Sender<Option<niri_ipc::PickedColor>>) {
1621+ let pointer = self.niri.seat.get_pointer().unwrap();
1622+ let start_data = PointerGrabStartData {
1623+ focus: None,
1624+ button: 0,
1625+ location: pointer.current_location(),
1626+ };
1627+ let grab = PickColorGrab::new(start_data);
1628+ pointer.set_grab(self, grab, SERIAL_COUNTER.next_serial(), Focus::Clear);
1629+ self.niri.pick_color = Some(tx);
1630+ self.niri
1631+ .cursor_manager
1632+ .set_cursor_image(CursorImageStatus::Named(CursorIcon::Crosshair));
1633+ self.niri.queue_redraw_all();
1634+ }
1635+
1615 #[cfg(feature = "xdp-gnome-screencast")]1636 #[cfg(feature = "xdp-gnome-screencast")]
1616 pub fn on_pw_msg(&mut self, msg: PwToNiri) {1637 pub fn on_pw_msg(&mut self, msg: PwToNiri) {
1617 match msg {1638 match msg {
@@ -1903,7 +1924,22 @@ impl State {
1903 to_screenshot: &async_channel::Sender<NiriToScreenshot>,1924 to_screenshot: &async_channel::Sender<NiriToScreenshot>,
1904 msg: ScreenshotToNiri,1925 msg: ScreenshotToNiri,
1905 ) {1926 ) {
1906- let ScreenshotToNiri::TakeScreenshot { include_cursor } = msg;1927+ match msg {
1928+ ScreenshotToNiri::TakeScreenshot { include_cursor } => {
1929+ self.handle_take_screenshot(to_screenshot, include_cursor);
1930+ }
1931+ ScreenshotToNiri::PickColor(tx) => {
1932+ self.handle_pick_color(tx);
1933+ }
1934+ }
1935+ }
1936+
1937+ #[cfg(feature = "dbus")]
1938+ fn handle_take_screenshot(
1939+ &mut self,
1940+ to_screenshot: &async_channel::Sender<NiriToScreenshot>,
1941+ include_cursor: bool,
1942+ ) {
1907 let _span = tracy_client::span!("TakeScreenshot");1943 let _span = tracy_client::span!("TakeScreenshot");
1908 1944
1909 let rv = self.backend.with_primary_renderer(|renderer| {1945 let rv = self.backend.with_primary_renderer(|renderer| {
@@ -2351,6 +2387,7 @@ impl Niri {
2351 exit_confirm_dialog,2387 exit_confirm_dialog,
2352 2388
2353 pick_window: None,2389 pick_window: None,
2390+ pick_color: None,
2354 2391
2355 debug_draw_opaque_regions: false,2392 debug_draw_opaque_regions: false,
2356 debug_draw_damage: false,2393 debug_draw_damage: false,