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