forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBad3847fIvan Molodetskikh1 year ago2457 commits

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