1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::{
7 Area, AreaArrangement, Bubble, BubbleId, Contribution, ModuleActions, Overflow, Stacking, Theme,
8};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct ActivityId(pub u64);
14
15impl fmt::Display for ActivityId {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 write!(f, "{}", self.0)
18 }
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum Role {
26 Ui,
28 Ctl,
30}
31
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34#[serde(tag = "type", rename_all = "snake_case")]
35pub enum ClientMessage {
36 Hello { api: u32, role: Role },
38 Command {
40 module: String,
41 action: String,
42 #[serde(default)]
43 args: Vec<String>,
44 },
45 Event {
47 activity: ActivityId,
48 kind: EventKind,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 output: Option<String>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
55 click: Option<Click>,
56 },
57 PassOn { click: Click },
60 BubbleClick { bubble: BubbleId },
62 OverflowClick { area: Area },
65 Status,
67 Reload,
69 Dismiss,
73 ListActions {
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 module: Option<String>,
77 },
78 StepAside { pid: u32 },
83 Profile { seconds: u32 },
87 Frames {
91 output: String,
92 surface: String,
93 frames: u32,
94 },
95}
96
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99#[serde(tag = "type", rename_all = "snake_case")]
100pub enum DaemonMessage {
101 Hello { api: u32, version: String },
103 Modules { modules: Vec<String> },
106 Contributions { contributions: Vec<Contribution> },
109 State { module: String, state: Value },
112 Live { module: String, value: Value },
115 Present {
117 activity: Option<Activity>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
122 resting: Option<Activity>,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
126 output: Option<String>,
127 },
128 Bubbles {
131 bubbles: Vec<Bubble>,
132 #[serde(default, skip_serializing_if = "Vec::is_empty")]
133 overflow: Vec<Overflow>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
136 stack: Option<Stacking>,
137 #[serde(default, skip_serializing_if = "Vec::is_empty")]
140 arrangements: Vec<AreaArrangement>,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
144 tooltip_ms: Option<u64>,
145 },
146 Theme { theme: Box<Theme> },
148 Ok,
150 Output { output: String },
153 Status { status: Status },
155 Actions { modules: Vec<ModuleActions> },
157 Error { code: ErrorCode, message: String },
159 Profiling { on: bool },
163 Covered {
167 outputs: Vec<String>,
168 #[serde(default)]
171 desktops: Vec<String>,
172 },
173 ReloadViews,
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181pub struct Activity {
182 pub id: ActivityId,
183 pub module: String,
184 pub view: String,
186 pub payload: Value,
187 pub expanded: bool,
189 pub expandable: bool,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub key: Option<String>,
196 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
199 pub modal: bool,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub overlay: Option<String>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub output: Option<String>,
209 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
212 pub outside: bool,
213 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
216 pub over_fullscreen: bool,
217}
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum EventKind {
222 Click,
223 HoverEnter,
224 HoverLeave,
225 Dismiss,
228 Outside,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233pub struct Status {
234 pub version: String,
236 pub api: u32,
237 pub ui_connected: bool,
238 pub modules: Vec<String>,
239 #[serde(default)]
240 pub compositor: CompositorStatus,
241 #[serde(default, skip_serializing_if = "Vec::is_empty")]
243 pub plugins: Vec<PluginStatus>,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub foreign_ui: Option<String>,
248}
249
250#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct PluginStatus {
253 pub id: String,
254 pub state: PluginState,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub message: Option<String>,
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
261#[serde(rename_all = "snake_case")]
262pub enum PluginState {
263 Running,
265 Disabled,
267 Missing,
269 Failed,
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
275pub struct CompositorStatus {
276 pub backend: String,
279 pub outputs: Vec<String>,
281 pub workspaces: usize,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
284 pub focused: Option<String>,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub keyboard_layout: Option<String>,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(rename_all = "snake_case")]
292pub enum ErrorCode {
293 BadMessage,
295 HelloFirst,
297 UnsupportedApi,
298 NotAllowed,
300 UnknownModule,
301 UnknownAction,
302 InvalidArgs,
303 ModuleFailed,
305 InvalidConfig,
307 Internal,
308}
309
310#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
312pub struct Click {
313 pub output: String,
315 pub x: f64,
317 pub y: f64,
318 pub width: f64,
319 pub height: f64,
320 pub button: u32,
322 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub scroll: Option<Scroll>,
326}
327
328#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
330pub struct Scroll {
331 pub x: f64,
332 pub y: f64,
333}
334
335#[cfg(test)]
336mod tests {
337 use serde_json::json;
338
339 use super::*;
340 use crate::{ActionSpec, ArgSpec, decode, encode};
341
342 fn round_trip_client(message: ClientMessage) {
343 let line = encode(&message).unwrap();
344 let back: ClientMessage = decode(std::str::from_utf8(&line).unwrap()).unwrap();
345 assert_eq!(back, message);
346 }
347
348 fn round_trip_daemon(message: DaemonMessage) {
349 let line = encode(&message).unwrap();
350 let back: DaemonMessage = decode(std::str::from_utf8(&line).unwrap()).unwrap();
351 assert_eq!(back, message);
352 }
353
354 fn activity() -> Activity {
355 Activity {
356 id: ActivityId(7),
357 module: "notifications".into(),
358 view: "Compact".into(),
359 payload: json!({ "title": "Hello" }),
360 expanded: false,
361 expandable: true,
362 modal: false,
363 overlay: None,
364 output: None,
365 outside: false,
366 over_fullscreen: false,
367 key: None,
368 }
369 }
370
371 #[test]
372 fn every_client_message_round_trips() {
373 round_trip_client(ClientMessage::Hello {
374 api: 1,
375 role: Role::Ui,
376 });
377 round_trip_client(ClientMessage::Command {
378 module: "launcher".into(),
379 action: "toggle".into(),
380 args: vec!["--fast".into()],
381 });
382 round_trip_client(ClientMessage::Event {
383 activity: ActivityId(3),
384 kind: EventKind::HoverLeave,
385 output: None,
386 click: None,
387 });
388 round_trip_client(ClientMessage::Event {
389 activity: ActivityId(3),
390 kind: EventKind::Click,
391 output: Some("DP-3".into()),
392 click: None,
393 });
394 round_trip_client(ClientMessage::Event {
395 activity: ActivityId(3),
396 kind: EventKind::Outside,
397 output: Some("DP-3".into()),
398 click: Some(Click {
399 output: "HDMI-A-1".into(),
400 x: 640.5,
401 y: 300.0,
402 width: 1920.0,
403 height: 1080.0,
404 button: 1,
405 scroll: None,
406 }),
407 });
408 round_trip_client(ClientMessage::PassOn {
409 click: Click {
410 output: "DP-3".into(),
411 x: 10.0,
412 y: 20.0,
413 width: 1920.0,
414 height: 1080.0,
415 button: 0,
416 scroll: Some(Scroll { x: 0.0, y: -120.0 }),
417 },
418 });
419 round_trip_client(ClientMessage::BubbleClick {
420 bubble: BubbleId(3),
421 });
422 round_trip_client(ClientMessage::OverflowClick { area: Area::Right });
423 round_trip_client(ClientMessage::Status);
424 round_trip_client(ClientMessage::Reload);
425 round_trip_client(ClientMessage::Dismiss);
426 round_trip_client(ClientMessage::ListActions { module: None });
427 round_trip_client(ClientMessage::ListActions {
428 module: Some("osd".into()),
429 });
430 }
431
432 #[test]
433 fn every_daemon_message_round_trips() {
434 round_trip_daemon(DaemonMessage::Hello {
435 api: 1,
436 version: "0.4.7".into(),
437 });
438 round_trip_daemon(DaemonMessage::Modules {
439 modules: vec!["idle".into()],
440 });
441 round_trip_daemon(DaemonMessage::State {
442 module: "idle".into(),
443 state: json!({ "unread": 2 }),
444 });
445 round_trip_daemon(DaemonMessage::Live {
446 module: "audio".into(),
447 value: json!({ "output": 0.5 }),
448 });
449 round_trip_daemon(DaemonMessage::Present {
450 activity: Some(activity()),
451 resting: None,
452 output: None,
453 });
454 round_trip_daemon(DaemonMessage::Present {
455 activity: Some(Activity {
456 output: Some("DP-3".into()),
457 ..activity()
458 }),
459 resting: Some(activity()),
460 output: None,
461 });
462 round_trip_daemon(DaemonMessage::Present {
463 activity: Some(Activity {
464 modal: true,
465 overlay: Some("Overlay".into()),
466 ..activity()
467 }),
468 resting: None,
469 output: None,
470 });
471 round_trip_daemon(DaemonMessage::Present {
472 activity: Some(Activity {
473 over_fullscreen: true,
474 ..activity()
475 }),
476 resting: None,
477 output: None,
478 });
479 round_trip_daemon(DaemonMessage::Present {
480 activity: Some(Activity {
481 modal: true,
482 output: Some("DP-3".into()),
483 ..activity()
484 }),
485 resting: None,
486 output: None,
487 });
488 round_trip_daemon(DaemonMessage::Present {
489 activity: None,
490 resting: None,
491 output: None,
492 });
493 round_trip_daemon(DaemonMessage::Present {
494 activity: Some(activity()),
495 resting: None,
496 output: Some("HDMI-A-1".into()),
497 });
498 round_trip_daemon(DaemonMessage::Output {
499 output: "[SELECTION]/screen:DP-3".into(),
500 });
501 round_trip_daemon(DaemonMessage::Contributions {
502 contributions: vec![Contribution {
503 module: "media".into(),
504 target: "control-center".into(),
505 kind: "card".into(),
506 id: "now-playing".into(),
507 view: "Card".into(),
508 title: "Now playing".into(),
509 icon: None,
510 order: 10,
511 options: json!({ "span": 2 }),
512 }],
513 });
514 round_trip_daemon(DaemonMessage::Bubbles {
515 bubbles: vec![Bubble {
516 id: BubbleId(4),
517 module: "media".into(),
518 key: Some("now".into()),
519 view: "Bubble".into(),
520 wide: true,
521 payload: json!({ "title": "Song" }),
522 area: Area::CenterLeft,
523 group: Some("status".into()),
524 priority: 50,
525 news: 3,
526 tooltip: Some("Song ยท Artist".into()),
527 apart: true,
528 }],
529 overflow: vec![Overflow {
530 area: Area::Right,
531 hidden: 2,
532 }],
533 stack: Some(Stacking { news_ms: 4000 }),
534 arrangements: vec![AreaArrangement {
535 area: Area::CenterLeft,
536 arrangement: crate::Arrangement::Island,
537 }],
538 tooltip_ms: Some(600),
539 });
540 round_trip_daemon(DaemonMessage::Theme {
541 theme: Box::default(),
542 });
543 round_trip_daemon(DaemonMessage::Ok);
544 round_trip_daemon(DaemonMessage::Status {
545 status: Status {
546 version: "0.4.7".into(),
547 api: 1,
548 ui_connected: true,
549 modules: vec!["idle".into()],
550 compositor: CompositorStatus {
551 backend: "wayland".into(),
552 outputs: vec!["DP-3".into()],
553 workspaces: 4,
554 focused: Some("DP-3".into()),
555 keyboard_layout: Some("English (UK)".into()),
556 },
557 plugins: vec![PluginStatus {
558 id: "pomodoro".into(),
559 state: PluginState::Failed,
560 message: Some("it crashed 5 times in a minute".into()),
561 }],
562 foreign_ui: Some("process 7 isn't the Quickshell mochid started".into()),
563 },
564 });
565 round_trip_daemon(DaemonMessage::Actions {
566 modules: vec![ModuleActions {
567 module: "osd".into(),
568 actions: vec![
569 ActionSpec::new("volume", "Change the volume")
570 .arg(ArgSpec::int("delta", "Percent to add or remove")),
571 ],
572 }],
573 });
574 round_trip_daemon(DaemonMessage::Error {
575 code: ErrorCode::UnknownAction,
576 message: "osd has no action nope".into(),
577 });
578 }
579
580 #[test]
582 fn ui_facing_messages_keep_their_wire_format() {
583 let present = DaemonMessage::Present {
584 activity: Some(activity()),
585 resting: None,
586 output: None,
587 };
588 assert_eq!(
589 serde_json::to_value(&present).unwrap(),
590 json!({
591 "type": "present",
592 "activity": {
593 "id": 7,
594 "module": "notifications",
595 "view": "Compact",
596 "payload": { "title": "Hello" },
597 "expanded": false,
598 "expandable": true
599 }
600 })
601 );
602
603 let event: ClientMessage =
604 decode(r#"{"type":"event","activity":7,"kind":"hover_enter"}"#).unwrap();
605 assert_eq!(
606 event,
607 ClientMessage::Event {
608 activity: ActivityId(7),
609 kind: EventKind::HoverEnter,
610 output: None,
611 click: None,
612 }
613 );
614
615 let overflow: ClientMessage =
616 decode(r#"{"type":"overflow_click","area":"center-right"}"#).unwrap();
617 assert_eq!(
618 overflow,
619 ClientMessage::OverflowClick {
620 area: Area::CenterRight
621 }
622 );
623 }
624
625 #[test]
626 fn the_key_is_only_sent_when_set() {
627 let keyed = Activity {
628 key: Some("osd".into()),
629 ..activity()
630 };
631 let json = serde_json::to_value(&keyed).unwrap();
632 assert_eq!(json["key"], "osd");
633
634 let back: Activity = serde_json::from_value(json).unwrap();
635 assert_eq!(back, keyed);
636
637 let without: Activity = serde_json::from_str(
638 r#"{"id":1,"module":"idle","view":"Pill","payload":{},"expanded":false,"expandable":false}"#,
639 )
640 .unwrap();
641 assert_eq!(without.key, None);
642 }
643
644 #[test]
645 fn optional_fields_may_be_left_out() {
646 let command: ClientMessage =
647 decode(r#"{"type":"command","module":"idle","action":"show"}"#).unwrap();
648 assert!(matches!(command, ClientMessage::Command { args, .. } if args.is_empty()));
649
650 let list: ClientMessage = decode(r#"{"type":"list_actions"}"#).unwrap();
651 assert_eq!(list, ClientMessage::ListActions { module: None });
652 }
653
654 #[test]
655 fn unknown_message_types_are_rejected() {
656 assert!(decode::<ClientMessage>(r#"{"type":"teleport"}"#).is_err());
657 assert!(decode::<ClientMessage>(r#"{"api":1}"#).is_err());
658 }
659}