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 {
6565 FocusedWindow,
6666 /// Request picking a window and get its information.
6767 PickWindow,
68+ /// Request picking a color from the screen.
69+ PickColor,
6870 /// Perform an action.
6971 Action(Action),
7072 /// Change output configuration temporarily.
@@ -133,10 +135,20 @@ pub enum Response {
133135 FocusedWindow(Option<Window>),
134136 /// Information about the picked window.
135137 PickedWindow(Option<Window>),
138+ /// Information about the picked color.
139+ PickedColor(Option<PickedColor>),
136140 /// Output configuration change result.
137141 OutputConfigChanged(OutputConfigChanged),
138142 }
139143
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+
140152 /// Actions that niri can perform.
141153 // Variants in this enum should match the spelling of the ones in niri-config. Most, but not all,
142154 // variants from niri-config should be present here.
src/cli.rsmodified+2 -0
@@ -77,6 +77,8 @@ pub enum Msg {
7777 FocusedWindow,
7878 /// Pick a window with the mouse and print information about it.
7979 PickWindow,
80+ /// Pick a color from the screen with the mouse.
81+ PickColor,
8082 /// Perform an action.
8183 Action {
8284 #[command(subcommand)]
src/dbus/gnome_shell_screenshot.rsmodified+32 -0
@@ -1,7 +1,10 @@
1+use std::collections::HashMap;
12 use std::path::PathBuf;
23
4+use niri_ipc::PickedColor;
35 use zbus::fdo::{self, RequestNameFlags};
46 use zbus::interface;
7+use zbus::zvariant::OwnedValue;
58
69 use super::Start;
710
@@ -12,6 +15,7 @@ pub struct Screenshot {
1215
1316 pub enum ScreenshotToNiri {
1417 TakeScreenshot { include_cursor: bool },
18+ PickColor(async_channel::Sender<Option<PickedColor>>),
1519 }
1620
1721 pub enum NiriToScreenshot {
@@ -47,6 +51,34 @@ impl Screenshot {
4751
4852 Ok((true, filename))
4953 }
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+ }
5082 }
5183
5284 impl Screenshot {
src/input/mod.rsmodified+5 -1
@@ -48,6 +48,7 @@ use crate::utils::{center, get_monotonic_time, ResizeEdge};
4848
4949 pub mod backend_ext;
5050 pub mod move_grab;
51+pub mod pick_color_grab;
5152 pub mod pick_window_grab;
5253 pub mod resize_grab;
5354 pub mod scroll_tracker;
@@ -377,7 +378,10 @@ impl State {
377378 }
378379 }
379380
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+ {
381385 // We window picking state so the pick window grab must be active.
382386 // Unsetting it cancels window picking.
383387 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<()> {
2020 Msg::FocusedWindow => Request::FocusedWindow,
2121 Msg::FocusedOutput => Request::FocusedOutput,
2222 Msg::PickWindow => Request::PickWindow,
23+ Msg::PickColor => Request::PickColor,
2324 Msg::Action { action } => Request::Action(action.clone()),
2425 Msg::Output { output, action } => Request::Output {
2526 output: output.clone(),
@@ -270,6 +271,26 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
270271 println!("No window selected.");
271272 }
272273 }
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+ }
273294 Msg::Action { .. } => {
274295 let Response::Handled = response else {
275296 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 {
356356 });
357357 Response::PickedWindow(window)
358358 }
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+ }
359368 Request::Action(action) => {
360369 let (tx, rx) = async_channel::bounded(1);
361370
src/niri.rsmodified+39 -2
@@ -45,7 +45,10 @@ use smithay::desktop::{
4545 PopupUngrabStrategy, Space, Window, WindowSurfaceType,
4646 };
4747 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+};
4952 use smithay::input::{Seat, SeatState};
5053 use smithay::output::{self, Output, OutputModeSource, PhysicalProperties, Subpixel, WeakOutput};
5154 use smithay::reexports::calloop::generic::Generic;
@@ -118,6 +121,7 @@ use crate::dbus::gnome_shell_screenshot::{NiriToScreenshot, ScreenshotToNiri};
118121 use crate::dbus::mutter_screen_cast::{self, ScreenCastToNiri};
119122 use crate::frame_clock::FrameClock;
120123 use crate::handlers::{configure_lock_surface, XDG_ACTIVATION_TOKEN_TIMEOUT};
124+use crate::input::pick_color_grab::PickColorGrab;
121125 use crate::input::scroll_tracker::ScrollTracker;
122126 use crate::input::{
123127 apply_libinput_settings, mods_with_finger_scroll_binds, mods_with_mouse_binds,
@@ -358,6 +362,7 @@ pub struct Niri {
358362 pub exit_confirm_dialog: Option<ExitConfirmDialog>,
359363
360364 pub pick_window: Option<async_channel::Sender<Option<MappedId>>>,
365+ pub pick_color: Option<async_channel::Sender<Option<niri_ipc::PickedColor>>>,
361366
362367 pub debug_draw_opaque_regions: bool,
363368 pub debug_draw_damage: bool,
@@ -1612,6 +1617,22 @@ impl State {
16121617 self.niri.queue_redraw_all();
16131618 }
16141619
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+
16151636 #[cfg(feature = "xdp-gnome-screencast")]
16161637 pub fn on_pw_msg(&mut self, msg: PwToNiri) {
16171638 match msg {
@@ -1903,7 +1924,22 @@ impl State {
19031924 to_screenshot: &async_channel::Sender<NiriToScreenshot>,
19041925 msg: ScreenshotToNiri,
19051926 ) {
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+ ) {
19071943 let _span = tracy_client::span!("TakeScreenshot");
19081944
19091945 let rv = self.backend.with_primary_renderer(|renderer| {
@@ -2351,6 +2387,7 @@ impl Niri {
23512387 exit_confirm_dialog,
23522388
23532389 pick_window: None,
2390+ pick_color: None,
23542391
23552392 debug_draw_opaque_regions: false,
23562393 debug_draw_damage: false,