forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB64a9351Ivan Molodetskikh2 years ago1319 commits

client.rs459 lines, 16.1 KiBHistoryRawDownload
1use anyhow::{anyhow, bail, Context};
2use niri_ipc::{
3 Event, KeyboardLayouts, LogicalOutput, Mode, Output, OutputConfigChanged, Request, Response,
4 Socket, Transform,
5};
6use serde_json::json;
7
8use crate::cli::Msg;
9use crate::utils::version;
10
11pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
12 let request = match &msg {
13 Msg::Version => Request::Version,
14 Msg::Outputs => Request::Outputs,
15 Msg::FocusedWindow => Request::FocusedWindow,
16 Msg::FocusedOutput => Request::FocusedOutput,
17 Msg::Action { action } => Request::Action(action.clone()),
18 Msg::Output { output, action } => Request::Output {
19 output: output.clone(),
20 action: action.clone(),
21 },
22 Msg::Workspaces => Request::Workspaces,
23 Msg::Windows => Request::Windows,
24 Msg::KeyboardLayouts => Request::KeyboardLayouts,
25 Msg::EventStream => Request::EventStream,
26 Msg::RequestError => Request::ReturnError,
27 };
28
29 let socket = Socket::connect().context("error connecting to the niri socket")?;
30
31 let (reply, mut read_event) = socket
32 .send(request)
33 .context("error communicating with niri")?;
34
35 let compositor_version = match reply {
36 Err(_) if !matches!(msg, Msg::Version) => {
37 // If we got an error, it might be that the CLI is a different version from the running
38 // niri instance. Request the running instance version to compare and print a message.
39 Socket::connect()
40 .and_then(|socket| socket.send(Request::Version))
41 .ok()
42 .map(|(reply, _read_event)| reply)
43 }
44 _ => None,
45 };
46
47 // Default SIGPIPE so that our prints don't panic on stdout closing.
48 unsafe {
49 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
50 }
51
52 let response = reply.map_err(|err_msg| {
53 // Check for CLI-server version mismatch to add helpful context.
54 match compositor_version {
55 Some(Ok(Response::Version(compositor_version))) => {
56 let cli_version = version();
57 if cli_version != compositor_version {
58 eprintln!("Running niri compositor has a different version from the niri CLI:");
59 eprintln!("Compositor version: {compositor_version}");
60 eprintln!("CLI version: {cli_version}");
61 eprintln!("Did you forget to restart niri after an update?");
62 eprintln!();
63 }
64 }
65 Some(_) => {
66 eprintln!("Unable to get the running niri compositor version.");
67 eprintln!("Did you forget to restart niri after an update?");
68 eprintln!();
69 }
70 None => {
71 // Communication error, or the original request was already a version request.
72 // Don't add irrelevant context.
73 }
74 }
75
76 anyhow!(err_msg).context("niri returned an error")
77 })?;
78
79 match msg {
80 Msg::RequestError => {
81 bail!("unexpected response: expected an error, got {response:?}");
82 }
83 Msg::Version => {
84 let Response::Version(compositor_version) = response else {
85 bail!("unexpected response: expected Version, got {response:?}");
86 };
87
88 let cli_version = version();
89
90 if json {
91 println!(
92 "{}",
93 json!({
94 "compositor": compositor_version,
95 "cli": cli_version,
96 })
97 );
98 return Ok(());
99 }
100
101 if cli_version != compositor_version {
102 eprintln!("Running niri compositor has a different version from the niri CLI.");
103 eprintln!("Did you forget to restart niri after an update?");
104 eprintln!();
105 }
106
107 println!("Compositor version: {compositor_version}");
108 println!("CLI version: {cli_version}");
109 }
110 Msg::Outputs => {
111 let Response::Outputs(outputs) = response else {
112 bail!("unexpected response: expected Outputs, got {response:?}");
113 };
114
115 if json {
116 let output =
117 serde_json::to_string(&outputs).context("error formatting response")?;
118 println!("{output}");
119 return Ok(());
120 }
121
122 let mut outputs = outputs.into_iter().collect::<Vec<_>>();
123 outputs.sort_unstable_by(|a, b| a.0.cmp(&b.0));
124
125 for (connector, output) in outputs.into_iter() {
126 print_output(connector, output)?;
127 println!();
128 }
129 }
130 Msg::FocusedWindow => {
131 let Response::FocusedWindow(window) = response else {
132 bail!("unexpected response: expected FocusedWindow, got {response:?}");
133 };
134
135 if json {
136 let window = serde_json::to_string(&window).context("error formatting response")?;
137 println!("{window}");
138 return Ok(());
139 }
140
141 if let Some(window) = window {
142 println!("Focused window:");
143
144 if let Some(title) = window.title {
145 println!(" Title: \"{title}\"");
146 } else {
147 println!(" Title: (unset)");
148 }
149
150 if let Some(app_id) = window.app_id {
151 println!(" App ID: \"{app_id}\"");
152 } else {
153 println!(" App ID: (unset)");
154 }
155 } else {
156 println!("No window is focused.");
157 }
158 }
159 Msg::Windows => {
160 let Response::Windows(mut windows) = response else {
161 bail!("unexpected response: expected Windows, got {response:?}");
162 };
163
164 if json {
165 let windows =
166 serde_json::to_string(&windows).context("error formatting response")?;
167 println!("{windows}");
168 return Ok(());
169 }
170
171 windows.sort_unstable_by(|a, b| a.id.cmp(&b.id));
172
173 for window in windows {
174 let focused = if window.is_focused { " (focused)" } else { "" };
175 println!("Window ID {}:{focused}", window.id);
176
177 if let Some(title) = window.title {
178 println!(" Title: \"{title}\"");
179 } else {
180 println!(" Title: (unset)");
181 }
182
183 if let Some(app_id) = window.app_id {
184 println!(" App ID: \"{app_id}\"");
185 } else {
186 println!(" App ID: (unset)");
187 }
188
189 if let Some(workspace_id) = window.workspace_id {
190 println!(" Workspace ID: {workspace_id}");
191 } else {
192 println!(" Workspace ID: (none)");
193 }
194
195 println!();
196 }
197 }
198 Msg::FocusedOutput => {
199 let Response::FocusedOutput(output) = response else {
200 bail!("unexpected response: expected FocusedOutput, got {response:?}");
201 };
202
203 if json {
204 let output = serde_json::to_string(&output).context("error formatting response")?;
205 println!("{output}");
206 return Ok(());
207 }
208
209 if let Some(output) = output {
210 print_output(output.name.clone(), output)?;
211 } else {
212 println!("No output is focused.");
213 }
214 }
215 Msg::Action { .. } => {
216 let Response::Handled = response else {
217 bail!("unexpected response: expected Handled, got {response:?}");
218 };
219 }
220 Msg::Output { output, .. } => {
221 let Response::OutputConfigChanged(response) = response else {
222 bail!("unexpected response: expected OutputConfigChanged, got {response:?}");
223 };
224
225 if json {
226 let response =
227 serde_json::to_string(&response).context("error formatting response")?;
228 println!("{response}");
229 return Ok(());
230 }
231
232 if response == OutputConfigChanged::OutputWasMissing {
233 println!("Output \"{output}\" is not connected.");
234 println!("The change will apply when it is connected.");
235 }
236 }
237 Msg::Workspaces => {
238 let Response::Workspaces(mut response) = response else {
239 bail!("unexpected response: expected Workspaces, got {response:?}");
240 };
241
242 if json {
243 let response =
244 serde_json::to_string(&response).context("error formatting response")?;
245 println!("{response}");
246 return Ok(());
247 }
248
249 if response.is_empty() {
250 println!("No workspaces.");
251 return Ok(());
252 }
253
254 response.sort_by_key(|ws| ws.idx);
255 response.sort_by(|a, b| a.output.cmp(&b.output));
256
257 let mut current_output = if let Some(output) = response[0].output.as_deref() {
258 println!("Output \"{output}\":");
259 Some(output)
260 } else {
261 println!("No output:");
262 None
263 };
264
265 for ws in &response {
266 if ws.output.as_deref() != current_output {
267 let output = ws.output.as_deref().context(
268 "invalid response: workspace with no output \
269 following a workspace with an output",
270 )?;
271 current_output = Some(output);
272 println!("\nOutput \"{output}\":");
273 }
274
275 let is_active = if ws.is_active { " * " } else { " " };
276 let idx = ws.idx;
277 let name = if let Some(name) = ws.name.as_deref() {
278 format!(" \"{name}\"")
279 } else {
280 String::new()
281 };
282 println!("{is_active}{idx}{name}");
283 }
284 }
285 Msg::KeyboardLayouts => {
286 let Response::KeyboardLayouts(response) = response else {
287 bail!("unexpected response: expected KeyboardLayouts, got {response:?}");
288 };
289
290 if json {
291 let response =
292 serde_json::to_string(&response).context("error formatting response")?;
293 println!("{response}");
294 return Ok(());
295 }
296
297 let KeyboardLayouts { names, current_idx } = response;
298 let current_idx = usize::from(current_idx);
299
300 println!("Keyboard layouts:");
301 for (idx, name) in names.iter().enumerate() {
302 let is_active = if idx == current_idx { " * " } else { " " };
303 println!("{is_active}{idx} {name}");
304 }
305 }
306 Msg::EventStream => {
307 let Response::Handled = response else {
308 bail!("unexpected response: expected Handled, got {response:?}");
309 };
310
311 if !json {
312 println!("Started reading events.");
313 }
314
315 loop {
316 let event = read_event().context("error reading event from niri")?;
317
318 if json {
319 let event = serde_json::to_string(&event).context("error formatting event")?;
320 println!("{event}");
321 continue;
322 }
323
324 match event {
325 Event::WorkspacesChanged { workspaces } => {
326 println!("Workspaces changed: {workspaces:?}");
327 }
328 Event::WorkspaceActivated { id, focused } => {
329 let word = if focused { "focused" } else { "activated" };
330 println!("Workspace {word}: {id}");
331 }
332 Event::WorkspaceActiveWindowChanged {
333 workspace_id,
334 active_window_id,
335 } => {
336 println!(
337 "Workspace {workspace_id}: \
338 active window changed to {active_window_id:?}"
339 );
340 }
341 Event::WindowsChanged { windows } => {
342 println!("Windows changed: {windows:?}");
343 }
344 Event::WindowOpenedOrChanged { window } => {
345 println!("Window opened or changed: {window:?}");
346 }
347 Event::WindowClosed { id } => {
348 println!("Window closed: {id}");
349 }
350 Event::WindowFocusChanged { id } => {
351 println!("Window focus changed: {id:?}");
352 }
353 Event::KeyboardLayoutsChanged { keyboard_layouts } => {
354 println!("Keyboard layouts changed: {keyboard_layouts:?}");
355 }
356 Event::KeyboardLayoutSwitched { idx } => {
357 println!("Keyboard layout switched: {idx}");
358 }
359 }
360 }
361 }
362 }
363
364 Ok(())
365}
366
367fn print_output(connector: String, output: Output) -> anyhow::Result<()> {
368 let Output {
369 name,
370 make,
371 model,
372 physical_size,
373 modes,
374 current_mode,
375 vrr_supported,
376 vrr_enabled,
377 logical,
378 } = output;
379
380 println!(r#"Output "{connector}" ({make} - {model} - {name})"#);
381
382 if let Some(current) = current_mode {
383 let mode = *modes
384 .get(current)
385 .context("invalid response: current mode does not exist")?;
386 let Mode {
387 width,
388 height,
389 refresh_rate,
390 is_preferred,
391 } = mode;
392 let refresh = refresh_rate as f64 / 1000.;
393 let preferred = if is_preferred { " (preferred)" } else { "" };
394 println!(" Current mode: {width}x{height} @ {refresh:.3} Hz{preferred}");
395 } else {
396 println!(" Disabled");
397 }
398
399 if vrr_supported {
400 let enabled = if vrr_enabled { "enabled" } else { "disabled" };
401 println!(" Variable refresh rate: supported, {enabled}");
402 } else {
403 println!(" Variable refresh rate: not supported");
404 }
405
406 if let Some((width, height)) = physical_size {
407 println!(" Physical size: {width}x{height} mm");
408 } else {
409 println!(" Physical size: unknown");
410 }
411
412 if let Some(logical) = logical {
413 let LogicalOutput {
414 x,
415 y,
416 width,
417 height,
418 scale,
419 transform,
420 } = logical;
421 println!(" Logical position: {x}, {y}");
422 println!(" Logical size: {width}x{height}");
423 println!(" Scale: {scale}");
424
425 let transform = match transform {
426 Transform::Normal => "normal",
427 Transform::_90 => "90° counter-clockwise",
428 Transform::_180 => "180°",
429 Transform::_270 => "270° counter-clockwise",
430 Transform::Flipped => "flipped horizontally",
431 Transform::Flipped90 => "90° counter-clockwise, flipped horizontally",
432 Transform::Flipped180 => "flipped vertically",
433 Transform::Flipped270 => "270° counter-clockwise, flipped horizontally",
434 };
435 println!(" Transform: {transform}");
436 }
437
438 println!(" Available modes:");
439 for (idx, mode) in modes.into_iter().enumerate() {
440 let Mode {
441 width,
442 height,
443 refresh_rate,
444 is_preferred,
445 } = mode;
446 let refresh = refresh_rate as f64 / 1000.;
447
448 let is_current = Some(idx) == current_mode;
449 let qualifier = match (is_current, is_preferred) {
450 (true, true) => " (current, preferred)",
451 (true, false) => " (current)",
452 (false, true) => " (preferred)",
453 (false, false) => "",
454 };
455
456 println!(" {width}x{height}@{refresh:.3}{qualifier}");
457 }
458 Ok(())
459}