forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB66583cdIvan Molodetskikh1 year ago2489 commits

client.rs741 lines, 25.4 KiBHistoryRawDownload
1use std::io::ErrorKind;
2use std::iter::Peekable;
3use std::path::Path;
4use std::{env, slice};
5
6use anyhow::{anyhow, bail, Context};
7use niri_config::OutputName;
8use niri_ipc::socket::Socket;
9use niri_ipc::{
10 Action, Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Overview,
11 Request, Response, Transform, Window, WindowLayout,
12};
13use serde_json::json;
14
15use crate::cli::Msg;
16use crate::utils::version;
17
18pub fn handle_msg(mut msg: Msg, json: bool) -> anyhow::Result<()> {
19 // For actions taking paths, prepend the niri CLI's working directory.
20 if let Msg::Action {
21 action:
22 Action::Screenshot { path, .. }
23 | Action::ScreenshotScreen { path, .. }
24 | Action::ScreenshotWindow { path, .. },
25 } = &mut msg
26 {
27 if let Some(path) = path {
28 ensure_absolute_path(path).context("error making the path absolute")?;
29 }
30 }
31
32 let request = match &msg {
33 Msg::Version => Request::Version,
34 Msg::Outputs => Request::Outputs,
35 Msg::FocusedWindow => Request::FocusedWindow,
36 Msg::FocusedOutput => Request::FocusedOutput,
37 Msg::PickWindow => Request::PickWindow,
38 Msg::PickColor => Request::PickColor,
39 Msg::Action { action } => Request::Action(action.clone()),
40 Msg::Output { output, action } => Request::Output {
41 output: output.clone(),
42 action: action.clone(),
43 },
44 Msg::Workspaces => Request::Workspaces,
45 Msg::Windows => Request::Windows,
46 Msg::Layers => Request::Layers,
47 Msg::KeyboardLayouts => Request::KeyboardLayouts,
48 Msg::EventStream => Request::EventStream,
49 Msg::RequestError => Request::ReturnError,
50 Msg::OverviewState => Request::OverviewState,
51 };
52
53 let mut socket = Socket::connect().context("error connecting to the niri socket")?;
54
55 let result = socket.send(request);
56
57 // For errors that can be caused by a version mismatch between the running niri instance and
58 // the niri msg CLI, we will try to fetch and compare the versions.
59 let check_compositor_version = match &result {
60 Err(err) => {
61 // Response JSON parsing errors.
62 matches!(
63 err.kind(),
64 ErrorKind::InvalidData | ErrorKind::UnexpectedEof
65 )
66 }
67 // Error returned from niri.
68 Ok(Err(_)) => true,
69 _ => false,
70 };
71
72 let compositor_version = if check_compositor_version && !matches!(msg, Msg::Version) {
73 // Reconnect to support older niri versions with one request per connection.
74 Socket::connect()
75 .and_then(|mut socket| socket.send(Request::Version))
76 .ok()
77 } else {
78 None
79 };
80
81 // Default SIGPIPE so that our prints don't panic on stdout closing.
82 unsafe {
83 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
84 }
85
86 // Check for CLI-server version mismatch to add helpful context.
87 match compositor_version {
88 Some(Ok(Response::Version(compositor_version))) => {
89 let cli_version = version();
90 if cli_version != compositor_version {
91 eprintln!("Running niri compositor has a different version from the niri CLI:");
92 eprintln!("Compositor version: {compositor_version}");
93 eprintln!("CLI version: {cli_version}");
94 eprintln!("Did you forget to restart niri after an update?");
95 eprintln!();
96 }
97 }
98 Some(_) => {
99 eprintln!("Unable to get the running niri compositor version.");
100 eprintln!("Did you forget to restart niri after an update?");
101 eprintln!();
102 }
103 None => {
104 // Communication error, or the original request was already a version request, or the
105 // original request had succeeded. Don't add irrelevant context.
106 }
107 }
108
109 let reply = result.context("error communicating with niri")?;
110 let response = reply.map_err(|err_msg| anyhow!(err_msg).context("niri returned an error"))?;
111
112 match msg {
113 Msg::RequestError => {
114 bail!("unexpected response: expected an error, got {response:?}");
115 }
116 Msg::Version => {
117 let Response::Version(compositor_version) = response else {
118 bail!("unexpected response: expected Version, got {response:?}");
119 };
120
121 let cli_version = version();
122
123 if json {
124 println!(
125 "{}",
126 json!({
127 "compositor": compositor_version,
128 "cli": cli_version,
129 })
130 );
131 return Ok(());
132 }
133
134 if cli_version != compositor_version {
135 eprintln!("Running niri compositor has a different version from the niri CLI.");
136 eprintln!("Did you forget to restart niri after an update?");
137 eprintln!();
138 }
139
140 println!("Compositor version: {compositor_version}");
141 println!("CLI version: {cli_version}");
142 }
143 Msg::Outputs => {
144 let Response::Outputs(outputs) = response else {
145 bail!("unexpected response: expected Outputs, got {response:?}");
146 };
147
148 if json {
149 let output =
150 serde_json::to_string(&outputs).context("error formatting response")?;
151 println!("{output}");
152 return Ok(());
153 }
154
155 let mut outputs = outputs
156 .into_values()
157 .map(|out| (OutputName::from_ipc_output(&out), out))
158 .collect::<Vec<_>>();
159 outputs.sort_unstable_by(|a, b| a.0.compare(&b.0));
160
161 for (_name, output) in outputs.into_iter() {
162 print_output(output)?;
163 println!();
164 }
165 }
166 Msg::FocusedWindow => {
167 let Response::FocusedWindow(window) = response else {
168 bail!("unexpected response: expected FocusedWindow, got {response:?}");
169 };
170
171 if json {
172 let window = serde_json::to_string(&window).context("error formatting response")?;
173 println!("{window}");
174 return Ok(());
175 }
176
177 if let Some(window) = window {
178 print_window(&window);
179 } else {
180 println!("No window is focused.");
181 }
182 }
183 Msg::Windows => {
184 let Response::Windows(mut windows) = response else {
185 bail!("unexpected response: expected Windows, got {response:?}");
186 };
187
188 if json {
189 let windows =
190 serde_json::to_string(&windows).context("error formatting response")?;
191 println!("{windows}");
192 return Ok(());
193 }
194
195 windows.sort_unstable_by(|a, b| a.id.cmp(&b.id));
196
197 for window in windows {
198 print_window(&window);
199 println!();
200 }
201 }
202 Msg::Layers => {
203 let Response::Layers(mut layers) = response else {
204 bail!("unexpected response: expected Layers, got {response:?}");
205 };
206
207 if json {
208 let layers = serde_json::to_string(&layers).context("error formatting response")?;
209 println!("{layers}");
210 return Ok(());
211 }
212
213 layers.sort_by(|a, b| {
214 Ord::cmp(&a.output, &b.output)
215 .then_with(|| Ord::cmp(&a.layer, &b.layer))
216 .then_with(|| Ord::cmp(&a.namespace, &b.namespace))
217 });
218 let mut iter = layers.iter().peekable();
219
220 let print = |surface: &niri_ipc::LayerSurface| {
221 println!(" Surface:");
222 println!(" Namespace: \"{}\"", &surface.namespace);
223
224 let interactivity = match surface.keyboard_interactivity {
225 niri_ipc::LayerSurfaceKeyboardInteractivity::None => "none",
226 niri_ipc::LayerSurfaceKeyboardInteractivity::Exclusive => "exclusive",
227 niri_ipc::LayerSurfaceKeyboardInteractivity::OnDemand => "on-demand",
228 };
229 println!(" Keyboard interactivity: {interactivity}");
230 };
231
232 let print_layer = |iter: &mut Peekable<slice::Iter<niri_ipc::LayerSurface>>,
233 output: &str,
234 layer| {
235 let mut empty = true;
236 while let Some(surface) = iter.next_if(|s| s.output == output && s.layer == layer) {
237 empty = false;
238 println!();
239 print(surface);
240 }
241 if empty {
242 println!(" (empty)\n");
243 } else {
244 println!();
245 }
246 };
247
248 while let Some(surface) = iter.peek() {
249 let output = &surface.output;
250 println!("Output \"{output}\":");
251
252 print!(" Background layer:");
253 print_layer(&mut iter, output, niri_ipc::Layer::Background);
254
255 print!(" Bottom layer:");
256 print_layer(&mut iter, output, niri_ipc::Layer::Bottom);
257
258 print!(" Top layer:");
259 print_layer(&mut iter, output, niri_ipc::Layer::Top);
260
261 print!(" Overlay layer:");
262 print_layer(&mut iter, output, niri_ipc::Layer::Overlay);
263 }
264 }
265 Msg::FocusedOutput => {
266 let Response::FocusedOutput(output) = response else {
267 bail!("unexpected response: expected FocusedOutput, got {response:?}");
268 };
269
270 if json {
271 let output = serde_json::to_string(&output).context("error formatting response")?;
272 println!("{output}");
273 return Ok(());
274 }
275
276 if let Some(output) = output {
277 print_output(output)?;
278 } else {
279 println!("No output is focused.");
280 }
281 }
282 Msg::PickWindow => {
283 let Response::PickedWindow(window) = response else {
284 bail!("unexpected response: expected PickedWindow, got {response:?}");
285 };
286
287 if json {
288 let window = serde_json::to_string(&window).context("error formatting response")?;
289 println!("{window}");
290 return Ok(());
291 }
292
293 if let Some(window) = window {
294 print_window(&window);
295 } else {
296 println!("No window selected.");
297 }
298 }
299 Msg::PickColor => {
300 let Response::PickedColor(color) = response else {
301 bail!("unexpected response: expected PickedColor, got {response:?}");
302 };
303
304 if json {
305 let color = serde_json::to_string(&color).context("error formatting response")?;
306 println!("{color}");
307 return Ok(());
308 }
309
310 if let Some(color) = color {
311 let [r, g, b] = color.rgb.map(|v| (v.clamp(0., 1.) * 255.).round() as u8);
312
313 println!("Picked color: rgb({r}, {g}, {b})",);
314 println!("Hex: #{r:02x}{g:02x}{b:02x}");
315 } else {
316 println!("No color was picked.");
317 }
318 }
319 Msg::Action { .. } => {
320 let Response::Handled = response else {
321 bail!("unexpected response: expected Handled, got {response:?}");
322 };
323 }
324 Msg::Output { output, .. } => {
325 let Response::OutputConfigChanged(response) = response else {
326 bail!("unexpected response: expected OutputConfigChanged, got {response:?}");
327 };
328
329 if json {
330 let response =
331 serde_json::to_string(&response).context("error formatting response")?;
332 println!("{response}");
333 return Ok(());
334 }
335
336 if response == OutputConfigChanged::OutputWasMissing {
337 println!("Output \"{output}\" is not connected.");
338 println!("The change will apply when it is connected.");
339 }
340 }
341 Msg::Workspaces => {
342 let Response::Workspaces(mut response) = response else {
343 bail!("unexpected response: expected Workspaces, got {response:?}");
344 };
345
346 if json {
347 let response =
348 serde_json::to_string(&response).context("error formatting response")?;
349 println!("{response}");
350 return Ok(());
351 }
352
353 if response.is_empty() {
354 println!("No workspaces.");
355 return Ok(());
356 }
357
358 response.sort_by_key(|ws| ws.idx);
359 response.sort_by(|a, b| a.output.cmp(&b.output));
360
361 let mut current_output = if let Some(output) = response[0].output.as_deref() {
362 println!("Output \"{output}\":");
363 Some(output)
364 } else {
365 println!("No output:");
366 None
367 };
368
369 for ws in &response {
370 if ws.output.as_deref() != current_output {
371 let output = ws.output.as_deref().context(
372 "invalid response: workspace with no output \
373 following a workspace with an output",
374 )?;
375 current_output = Some(output);
376 println!("\nOutput \"{output}\":");
377 }
378
379 let is_active = if ws.is_active { " * " } else { " " };
380 let idx = ws.idx;
381 let name = if let Some(name) = ws.name.as_deref() {
382 format!(" \"{name}\"")
383 } else {
384 String::new()
385 };
386 println!("{is_active}{idx}{name}");
387 }
388 }
389 Msg::KeyboardLayouts => {
390 let Response::KeyboardLayouts(response) = response else {
391 bail!("unexpected response: expected KeyboardLayouts, got {response:?}");
392 };
393
394 if json {
395 let response =
396 serde_json::to_string(&response).context("error formatting response")?;
397 println!("{response}");
398 return Ok(());
399 }
400
401 let KeyboardLayouts { names, current_idx } = response;
402 let current_idx = usize::from(current_idx);
403
404 println!("Keyboard layouts:");
405 for (idx, name) in names.iter().enumerate() {
406 let is_active = if idx == current_idx { " * " } else { " " };
407 println!("{is_active}{idx} {name}");
408 }
409 }
410 Msg::EventStream => {
411 let Response::Handled = response else {
412 bail!("unexpected response: expected Handled, got {response:?}");
413 };
414
415 if !json {
416 println!("Started reading events.");
417 }
418
419 let mut read_event = socket.read_events();
420 loop {
421 let event = read_event().context("error reading event from niri")?;
422
423 if json {
424 let event = serde_json::to_string(&event).context("error formatting event")?;
425 println!("{event}");
426 continue;
427 }
428
429 match event {
430 Event::WorkspacesChanged { workspaces } => {
431 println!("Workspaces changed: {workspaces:?}");
432 }
433 Event::WorkspaceUrgencyChanged { id, urgent } => {
434 println!("Workspace {id}: urgency changed to {urgent}");
435 }
436 Event::WorkspaceActivated { id, focused } => {
437 let word = if focused { "focused" } else { "activated" };
438 println!("Workspace {word}: {id}");
439 }
440 Event::WorkspaceActiveWindowChanged {
441 workspace_id,
442 active_window_id,
443 } => {
444 println!(
445 "Workspace {workspace_id}: \
446 active window changed to {active_window_id:?}"
447 );
448 }
449 Event::WindowsChanged { windows } => {
450 println!("Windows changed: {windows:?}");
451 }
452 Event::WindowOpenedOrChanged { window } => {
453 println!("Window opened or changed: {window:?}");
454 }
455 Event::WindowClosed { id } => {
456 println!("Window closed: {id}");
457 }
458 Event::WindowFocusChanged { id } => {
459 println!("Window focus changed: {id:?}");
460 }
461 Event::WindowUrgencyChanged { id, urgent } => {
462 println!("Window {id}: urgency changed to {urgent}");
463 }
464 Event::WindowLayoutsChanged { changes } => {
465 println!("Window layouts changed: {changes:?}");
466 }
467 Event::KeyboardLayoutsChanged { keyboard_layouts } => {
468 println!("Keyboard layouts changed: {keyboard_layouts:?}");
469 }
470 Event::KeyboardLayoutSwitched { idx } => {
471 println!("Keyboard layout switched: {idx}");
472 }
473 Event::OverviewOpenedOrClosed { is_open: opened } => {
474 println!("Overview toggled: {opened}");
475 }
476 Event::ConfigLoaded { failed } => {
477 let status = if failed {
478 "with an error"
479 } else {
480 "successfully"
481 };
482 println!("Config loaded {status}");
483 }
484 Event::ScreenshotCaptured { path } => {
485 let mut parts = vec![];
486 parts.push("copied to clipboard".to_string());
487 if let Some(path) = &path {
488 parts.push(format!("saved to {path}"));
489 }
490 let description = parts.join(" and ");
491 println!("Screenshot captured: {description}");
492 }
493 }
494 }
495 }
496 Msg::OverviewState => {
497 let Response::OverviewState(response) = response else {
498 bail!("unexpected response: expected Overview, got {response:?}");
499 };
500
501 if json {
502 let response =
503 serde_json::to_string(&response).context("error formatting response")?;
504 println!("{response}");
505 return Ok(());
506 }
507
508 let Overview { is_open } = response;
509 if is_open {
510 println!("Overview is open.");
511 } else {
512 println!("Overview is closed.");
513 }
514 }
515 }
516
517 Ok(())
518}
519
520fn print_output(output: Output) -> anyhow::Result<()> {
521 let Output {
522 name,
523 make,
524 model,
525 serial,
526 physical_size,
527 modes,
528 current_mode,
529 is_custom_mode,
530 vrr_supported,
531 vrr_enabled,
532 logical,
533 } = output;
534
535 let serial = serial.as_deref().unwrap_or("Unknown");
536 println!(r#"Output "{make} {model} {serial}" ({name})"#);
537
538 let print_qualifier = |is_preferred: bool, is_current: bool, is_custom_mode: bool| {
539 let mut qualifier = Vec::new();
540 if is_current {
541 qualifier.push("current");
542 if is_custom_mode {
543 qualifier.push("custom");
544 };
545 };
546
547 if is_preferred {
548 qualifier.push("preferred");
549 };
550
551 if qualifier.is_empty() {
552 String::new()
553 } else {
554 format!(" ({})", qualifier.join(", "))
555 }
556 };
557
558 if let Some(current) = current_mode {
559 let mode = *modes
560 .get(current)
561 .context("invalid response: current mode does not exist")?;
562 let Mode {
563 width,
564 height,
565 refresh_rate,
566 is_preferred,
567 } = mode;
568 let refresh = refresh_rate as f64 / 1000.;
569
570 // This is technically the current mode, but the println below already specifies that.
571 let qualifier = print_qualifier(is_preferred, false, is_custom_mode);
572 println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{qualifier}");
573 } else {
574 println!(" Disabled");
575 }
576
577 if vrr_supported {
578 let enabled = if vrr_enabled { "enabled" } else { "disabled" };
579 println!(" Variable refresh rate: supported, {enabled}");
580 } else {
581 println!(" Variable refresh rate: not supported");
582 }
583
584 if let Some((width, height)) = physical_size {
585 println!(" Physical size: {width}x{height} mm");
586 } else {
587 println!(" Physical size: unknown");
588 }
589
590 if let Some(logical) = logical {
591 let LogicalOutput {
592 x,
593 y,
594 width,
595 height,
596 scale,
597 transform,
598 } = logical;
599 println!(" Logical position: {x}, {y}");
600 println!(" Logical size: {width}x{height}");
601 println!(" Scale: {scale}");
602
603 let transform = match transform {
604 Transform::Normal => "normal",
605 Transform::_90 => "90° counter-clockwise",
606 Transform::_180 => "180°",
607 Transform::_270 => "270° counter-clockwise",
608 Transform::Flipped => "flipped horizontally",
609 Transform::Flipped90 => "90° counter-clockwise, flipped horizontally",
610 Transform::Flipped180 => "flipped vertically",
611 Transform::Flipped270 => "270° counter-clockwise, flipped horizontally",
612 };
613 println!(" Transform: {transform}");
614 }
615
616 println!(" Available modes:");
617 for (idx, mode) in modes.into_iter().enumerate() {
618 let Mode {
619 width,
620 height,
621 refresh_rate,
622 is_preferred,
623 } = mode;
624 let refresh = refresh_rate as f64 / 1000.;
625
626 let is_current = Some(idx) == current_mode;
627 let qualifier = print_qualifier(is_preferred, is_current, is_custom_mode);
628
629 println!(" {width}x{height}@{refresh:.3}{qualifier}");
630 }
631 Ok(())
632}
633
634fn print_window(window: &Window) {
635 let focused = if window.is_focused { " (focused)" } else { "" };
636 let urgent = if window.is_urgent { " (urgent)" } else { "" };
637 println!("Window ID {}:{focused}{urgent}", window.id);
638
639 if let Some(title) = &window.title {
640 println!(" Title: \"{title}\"");
641 } else {
642 println!(" Title: (unset)");
643 }
644
645 if let Some(app_id) = &window.app_id {
646 println!(" App ID: \"{app_id}\"");
647 } else {
648 println!(" App ID: (unset)");
649 }
650
651 println!(
652 " Is floating: {}",
653 if window.is_floating { "yes" } else { "no" }
654 );
655
656 if let Some(pid) = window.pid {
657 println!(" PID: {pid}");
658 } else {
659 println!(" PID: (unknown)");
660 }
661
662 if let Some(workspace_id) = window.workspace_id {
663 println!(" Workspace ID: {workspace_id}");
664 } else {
665 println!(" Workspace ID: (none)");
666 }
667
668 let WindowLayout {
669 pos_in_scrolling_layout,
670 tile_size,
671 window_size,
672 tile_pos_in_workspace_view,
673 window_offset_in_tile,
674 } = window.layout;
675
676 println!(" Layout:");
677 println!(
678 " Tile size: {} x {}",
679 fmt_rounded(tile_size.0),
680 fmt_rounded(tile_size.1)
681 );
682
683 if let Some(pos) = pos_in_scrolling_layout {
684 println!(" Scrolling position: column {}, tile {}", pos.0, pos.1);
685 }
686
687 if let Some(pos) = tile_pos_in_workspace_view {
688 println!(
689 " Workspace-view position: {}, {}",
690 fmt_rounded(pos.0),
691 fmt_rounded(pos.1)
692 );
693 }
694
695 println!(" Window size: {} x {}", window_size.0, window_size.1);
696 println!(
697 " Window offset in tile: {} x {}",
698 fmt_rounded(window_offset_in_tile.0),
699 fmt_rounded(window_offset_in_tile.1)
700 );
701}
702
703fn fmt_rounded(x: f64) -> String {
704 let r = x.round();
705 if (r - x).abs() <= 0.005 {
706 format!("{r}")
707 } else {
708 format!("{x:.2}")
709 }
710}
711
712fn ensure_absolute_path(path: &mut String) -> anyhow::Result<()> {
713 let p = Path::new(path);
714 if p.is_relative() {
715 let mut cwd = env::current_dir().context("error getting current working directory")?;
716 cwd.push(p);
717 match cwd.into_os_string().into_string() {
718 Ok(absolute) => *path = absolute,
719 Err(cwd) => bail!("couldn't convert absolute path to string: {cwd:?}"),
720 }
721 }
722 Ok(())
723}
724
725#[cfg(test)]
726mod tests {
727 use insta::assert_snapshot;
728
729 use super::*;
730
731 #[test]
732 fn test_fmt_rounded() {
733 assert_snapshot!(fmt_rounded(1.9), @"1.90");
734 assert_snapshot!(fmt_rounded(1.994), @"1.99");
735 assert_snapshot!(fmt_rounded(1.996), @"2");
736 assert_snapshot!(fmt_rounded(2.0), @"2");
737 assert_snapshot!(fmt_rounded(2.004), @"2");
738 assert_snapshot!(fmt_rounded(2.006), @"2.01");
739 assert_snapshot!(fmt_rounded(2.1), @"2.10");
740 }
741}