forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9ff2f83Ivan Molodetskikh1 year ago2099 commits

client.rs574 lines, 19.9 KiBHistoryRawDownload
1use std::iter::Peekable;
2use std::slice;
3
4use anyhow::{anyhow, bail, Context};
5use niri_config::OutputName;
6use niri_ipc::socket::Socket;
7use niri_ipc::{
8 Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Request, Response,
9 Transform, Window,
10};
11use serde_json::json;
12
13use crate::cli::Msg;
14use crate::utils::version;
15
16pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
17 let request = match &msg {
18 Msg::Version => Request::Version,
19 Msg::Outputs => Request::Outputs,
20 Msg::FocusedWindow => Request::FocusedWindow,
21 Msg::FocusedOutput => Request::FocusedOutput,
22 Msg::PickWindow => Request::PickWindow,
23 Msg::PickColor => Request::PickColor,
24 Msg::Action { action } => Request::Action(action.clone()),
25 Msg::Output { output, action } => Request::Output {
26 output: output.clone(),
27 action: action.clone(),
28 },
29 Msg::Workspaces => Request::Workspaces,
30 Msg::Windows => Request::Windows,
31 Msg::Layers => Request::Layers,
32 Msg::KeyboardLayouts => Request::KeyboardLayouts,
33 Msg::EventStream => Request::EventStream,
34 Msg::RequestError => Request::ReturnError,
35 };
36
37 let socket = Socket::connect().context("error connecting to the niri socket")?;
38
39 let (reply, mut read_event) = socket
40 .send(request)
41 .context("error communicating with niri")?;
42
43 let compositor_version = match reply {
44 Err(_) if !matches!(msg, Msg::Version) => {
45 // If we got an error, it might be that the CLI is a different version from the running
46 // niri instance. Request the running instance version to compare and print a message.
47 Socket::connect()
48 .and_then(|socket| socket.send(Request::Version))
49 .ok()
50 .map(|(reply, _read_event)| reply)
51 }
52 _ => None,
53 };
54
55 // Default SIGPIPE so that our prints don't panic on stdout closing.
56 unsafe {
57 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
58 }
59
60 let response = reply.map_err(|err_msg| {
61 // Check for CLI-server version mismatch to add helpful context.
62 match compositor_version {
63 Some(Ok(Response::Version(compositor_version))) => {
64 let cli_version = version();
65 if cli_version != compositor_version {
66 eprintln!("Running niri compositor has a different version from the niri CLI:");
67 eprintln!("Compositor version: {compositor_version}");
68 eprintln!("CLI version: {cli_version}");
69 eprintln!("Did you forget to restart niri after an update?");
70 eprintln!();
71 }
72 }
73 Some(_) => {
74 eprintln!("Unable to get the running niri compositor version.");
75 eprintln!("Did you forget to restart niri after an update?");
76 eprintln!();
77 }
78 None => {
79 // Communication error, or the original request was already a version request.
80 // Don't add irrelevant context.
81 }
82 }
83
84 anyhow!(err_msg).context("niri returned an error")
85 })?;
86
87 match msg {
88 Msg::RequestError => {
89 bail!("unexpected response: expected an error, got {response:?}");
90 }
91 Msg::Version => {
92 let Response::Version(compositor_version) = response else {
93 bail!("unexpected response: expected Version, got {response:?}");
94 };
95
96 let cli_version = version();
97
98 if json {
99 println!(
100 "{}",
101 json!({
102 "compositor": compositor_version,
103 "cli": cli_version,
104 })
105 );
106 return Ok(());
107 }
108
109 if cli_version != compositor_version {
110 eprintln!("Running niri compositor has a different version from the niri CLI.");
111 eprintln!("Did you forget to restart niri after an update?");
112 eprintln!();
113 }
114
115 println!("Compositor version: {compositor_version}");
116 println!("CLI version: {cli_version}");
117 }
118 Msg::Outputs => {
119 let Response::Outputs(outputs) = response else {
120 bail!("unexpected response: expected Outputs, got {response:?}");
121 };
122
123 if json {
124 let output =
125 serde_json::to_string(&outputs).context("error formatting response")?;
126 println!("{output}");
127 return Ok(());
128 }
129
130 let mut outputs = outputs
131 .into_values()
132 .map(|out| (OutputName::from_ipc_output(&out), out))
133 .collect::<Vec<_>>();
134 outputs.sort_unstable_by(|a, b| a.0.compare(&b.0));
135
136 for (_name, output) in outputs.into_iter() {
137 print_output(output)?;
138 println!();
139 }
140 }
141 Msg::FocusedWindow => {
142 let Response::FocusedWindow(window) = response else {
143 bail!("unexpected response: expected FocusedWindow, got {response:?}");
144 };
145
146 if json {
147 let window = serde_json::to_string(&window).context("error formatting response")?;
148 println!("{window}");
149 return Ok(());
150 }
151
152 if let Some(window) = window {
153 print_window(&window);
154 } else {
155 println!("No window is focused.");
156 }
157 }
158 Msg::Windows => {
159 let Response::Windows(mut windows) = response else {
160 bail!("unexpected response: expected Windows, got {response:?}");
161 };
162
163 if json {
164 let windows =
165 serde_json::to_string(&windows).context("error formatting response")?;
166 println!("{windows}");
167 return Ok(());
168 }
169
170 windows.sort_unstable_by(|a, b| a.id.cmp(&b.id));
171
172 for window in windows {
173 print_window(&window);
174 println!();
175 }
176 }
177 Msg::Layers => {
178 let Response::Layers(mut layers) = response else {
179 bail!("unexpected response: expected Layers, got {response:?}");
180 };
181
182 if json {
183 let layers = serde_json::to_string(&layers).context("error formatting response")?;
184 println!("{layers}");
185 return Ok(());
186 }
187
188 layers.sort_by(|a, b| {
189 Ord::cmp(&a.output, &b.output)
190 .then_with(|| Ord::cmp(&a.layer, &b.layer))
191 .then_with(|| Ord::cmp(&a.namespace, &b.namespace))
192 });
193 let mut iter = layers.iter().peekable();
194
195 let print = |surface: &niri_ipc::LayerSurface| {
196 println!(" Surface:");
197 println!(" Namespace: \"{}\"", &surface.namespace);
198
199 let interactivity = match surface.keyboard_interactivity {
200 niri_ipc::LayerSurfaceKeyboardInteractivity::None => "none",
201 niri_ipc::LayerSurfaceKeyboardInteractivity::Exclusive => "exclusive",
202 niri_ipc::LayerSurfaceKeyboardInteractivity::OnDemand => "on-demand",
203 };
204 println!(" Keyboard interactivity: {interactivity}");
205 };
206
207 let print_layer = |iter: &mut Peekable<slice::Iter<niri_ipc::LayerSurface>>,
208 output: &str,
209 layer| {
210 let mut empty = true;
211 while let Some(surface) = iter.next_if(|s| s.output == output && s.layer == layer) {
212 empty = false;
213 println!();
214 print(surface);
215 }
216 if empty {
217 println!(" (empty)\n");
218 } else {
219 println!();
220 }
221 };
222
223 while let Some(surface) = iter.peek() {
224 let output = &surface.output;
225 println!("Output \"{output}\":");
226
227 print!(" Background layer:");
228 print_layer(&mut iter, output, niri_ipc::Layer::Background);
229
230 print!(" Bottom layer:");
231 print_layer(&mut iter, output, niri_ipc::Layer::Bottom);
232
233 print!(" Top layer:");
234 print_layer(&mut iter, output, niri_ipc::Layer::Top);
235
236 print!(" Overlay layer:");
237 print_layer(&mut iter, output, niri_ipc::Layer::Overlay);
238 }
239 }
240 Msg::FocusedOutput => {
241 let Response::FocusedOutput(output) = response else {
242 bail!("unexpected response: expected FocusedOutput, got {response:?}");
243 };
244
245 if json {
246 let output = serde_json::to_string(&output).context("error formatting response")?;
247 println!("{output}");
248 return Ok(());
249 }
250
251 if let Some(output) = output {
252 print_output(output)?;
253 } else {
254 println!("No output is focused.");
255 }
256 }
257 Msg::PickWindow => {
258 let Response::PickedWindow(window) = response else {
259 bail!("unexpected response: expected PickedWindow, got {response:?}");
260 };
261
262 if json {
263 let window = serde_json::to_string(&window).context("error formatting response")?;
264 println!("{window}");
265 return Ok(());
266 }
267
268 if let Some(window) = window {
269 print_window(&window);
270 } else {
271 println!("No window selected.");
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 }
294 Msg::Action { .. } => {
295 let Response::Handled = response else {
296 bail!("unexpected response: expected Handled, got {response:?}");
297 };
298 }
299 Msg::Output { output, .. } => {
300 let Response::OutputConfigChanged(response) = response else {
301 bail!("unexpected response: expected OutputConfigChanged, got {response:?}");
302 };
303
304 if json {
305 let response =
306 serde_json::to_string(&response).context("error formatting response")?;
307 println!("{response}");
308 return Ok(());
309 }
310
311 if response == OutputConfigChanged::OutputWasMissing {
312 println!("Output \"{output}\" is not connected.");
313 println!("The change will apply when it is connected.");
314 }
315 }
316 Msg::Workspaces => {
317 let Response::Workspaces(mut response) = response else {
318 bail!("unexpected response: expected Workspaces, got {response:?}");
319 };
320
321 if json {
322 let response =
323 serde_json::to_string(&response).context("error formatting response")?;
324 println!("{response}");
325 return Ok(());
326 }
327
328 if response.is_empty() {
329 println!("No workspaces.");
330 return Ok(());
331 }
332
333 response.sort_by_key(|ws| ws.idx);
334 response.sort_by(|a, b| a.output.cmp(&b.output));
335
336 let mut current_output = if let Some(output) = response[0].output.as_deref() {
337 println!("Output \"{output}\":");
338 Some(output)
339 } else {
340 println!("No output:");
341 None
342 };
343
344 for ws in &response {
345 if ws.output.as_deref() != current_output {
346 let output = ws.output.as_deref().context(
347 "invalid response: workspace with no output \
348 following a workspace with an output",
349 )?;
350 current_output = Some(output);
351 println!("\nOutput \"{output}\":");
352 }
353
354 let is_active = if ws.is_active { " * " } else { " " };
355 let idx = ws.idx;
356 let name = if let Some(name) = ws.name.as_deref() {
357 format!(" \"{name}\"")
358 } else {
359 String::new()
360 };
361 println!("{is_active}{idx}{name}");
362 }
363 }
364 Msg::KeyboardLayouts => {
365 let Response::KeyboardLayouts(response) = response else {
366 bail!("unexpected response: expected KeyboardLayouts, got {response:?}");
367 };
368
369 if json {
370 let response =
371 serde_json::to_string(&response).context("error formatting response")?;
372 println!("{response}");
373 return Ok(());
374 }
375
376 let KeyboardLayouts { names, current_idx } = response;
377 let current_idx = usize::from(current_idx);
378
379 println!("Keyboard layouts:");
380 for (idx, name) in names.iter().enumerate() {
381 let is_active = if idx == current_idx { " * " } else { " " };
382 println!("{is_active}{idx} {name}");
383 }
384 }
385 Msg::EventStream => {
386 let Response::Handled = response else {
387 bail!("unexpected response: expected Handled, got {response:?}");
388 };
389
390 if !json {
391 println!("Started reading events.");
392 }
393
394 loop {
395 let event = read_event().context("error reading event from niri")?;
396
397 if json {
398 let event = serde_json::to_string(&event).context("error formatting event")?;
399 println!("{event}");
400 continue;
401 }
402
403 match event {
404 Event::WorkspacesChanged { workspaces } => {
405 println!("Workspaces changed: {workspaces:?}");
406 }
407 Event::WorkspaceActivated { id, focused } => {
408 let word = if focused { "focused" } else { "activated" };
409 println!("Workspace {word}: {id}");
410 }
411 Event::WorkspaceActiveWindowChanged {
412 workspace_id,
413 active_window_id,
414 } => {
415 println!(
416 "Workspace {workspace_id}: \
417 active window changed to {active_window_id:?}"
418 );
419 }
420 Event::WindowsChanged { windows } => {
421 println!("Windows changed: {windows:?}");
422 }
423 Event::WindowOpenedOrChanged { window } => {
424 println!("Window opened or changed: {window:?}");
425 }
426 Event::WindowClosed { id } => {
427 println!("Window closed: {id}");
428 }
429 Event::WindowFocusChanged { id } => {
430 println!("Window focus changed: {id:?}");
431 }
432 Event::KeyboardLayoutsChanged { keyboard_layouts } => {
433 println!("Keyboard layouts changed: {keyboard_layouts:?}");
434 }
435 Event::KeyboardLayoutSwitched { idx } => {
436 println!("Keyboard layout switched: {idx}");
437 }
438 }
439 }
440 }
441 }
442
443 Ok(())
444}
445
446fn print_output(output: Output) -> anyhow::Result<()> {
447 let Output {
448 name,
449 make,
450 model,
451 serial,
452 physical_size,
453 modes,
454 current_mode,
455 vrr_supported,
456 vrr_enabled,
457 logical,
458 } = output;
459
460 let serial = serial.as_deref().unwrap_or("Unknown");
461 println!(r#"Output "{make} {model} {serial}" ({name})"#);
462
463 if let Some(current) = current_mode {
464 let mode = *modes
465 .get(current)
466 .context("invalid response: current mode does not exist")?;
467 let Mode {
468 width,
469 height,
470 refresh_rate,
471 is_preferred,
472 } = mode;
473 let refresh = refresh_rate as f64 / 1000.;
474 let preferred = if is_preferred { " (preferred)" } else { "" };
475 println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{preferred}");
476 } else {
477 println!(" Disabled");
478 }
479
480 if vrr_supported {
481 let enabled = if vrr_enabled { "enabled" } else { "disabled" };
482 println!(" Variable refresh rate: supported, {enabled}");
483 } else {
484 println!(" Variable refresh rate: not supported");
485 }
486
487 if let Some((width, height)) = physical_size {
488 println!(" Physical size: {width}x{height} mm");
489 } else {
490 println!(" Physical size: unknown");
491 }
492
493 if let Some(logical) = logical {
494 let LogicalOutput {
495 x,
496 y,
497 width,
498 height,
499 scale,
500 transform,
501 } = logical;
502 println!(" Logical position: {x}, {y}");
503 println!(" Logical size: {width}x{height}");
504 println!(" Scale: {scale}");
505
506 let transform = match transform {
507 Transform::Normal => "normal",
508 Transform::_90 => "90° counter-clockwise",
509 Transform::_180 => "180°",
510 Transform::_270 => "270° counter-clockwise",
511 Transform::Flipped => "flipped horizontally",
512 Transform::Flipped90 => "90° counter-clockwise, flipped horizontally",
513 Transform::Flipped180 => "flipped vertically",
514 Transform::Flipped270 => "270° counter-clockwise, flipped horizontally",
515 };
516 println!(" Transform: {transform}");
517 }
518
519 println!(" Available modes:");
520 for (idx, mode) in modes.into_iter().enumerate() {
521 let Mode {
522 width,
523 height,
524 refresh_rate,
525 is_preferred,
526 } = mode;
527 let refresh = refresh_rate as f64 / 1000.;
528
529 let is_current = Some(idx) == current_mode;
530 let qualifier = match (is_current, is_preferred) {
531 (true, true) => " (current, preferred)",
532 (true, false) => " (current)",
533 (false, true) => " (preferred)",
534 (false, false) => "",
535 };
536
537 println!(" {width}x{height}@{refresh:.3}{qualifier}");
538 }
539 Ok(())
540}
541
542fn print_window(window: &Window) {
543 let focused = if window.is_focused { " (focused)" } else { "" };
544 println!("Window ID {}:{focused}", window.id);
545
546 if let Some(title) = &window.title {
547 println!(" Title: \"{title}\"");
548 } else {
549 println!(" Title: (unset)");
550 }
551
552 if let Some(app_id) = &window.app_id {
553 println!(" App ID: \"{app_id}\"");
554 } else {
555 println!(" App ID: (unset)");
556 }
557
558 println!(
559 " Is floating: {}",
560 if window.is_floating { "yes" } else { "no" }
561 );
562
563 if let Some(pid) = window.pid {
564 println!(" PID: {pid}");
565 } else {
566 println!(" PID: (unknown)");
567 }
568
569 if let Some(workspace_id) = window.workspace_id {
570 println!(" Workspace ID: {workspace_id}");
571 } else {
572 println!(" Workspace ID: (none)");
573 }
574}