Skip to main content

mochi_protocol/
messages.rs

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/// Identifies one activity for its whole life, across the daemon and the UI.
11#[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/// Who is on the other end of a connection. It decides which messages the
22/// daemon accepts from it.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum Role {
26    /// The Quickshell UI.
27    Ui,
28    /// The `mochi` CLI or any other control client.
29    Ctl,
30}
31
32/// Sent to the daemon.
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34#[serde(tag = "type", rename_all = "snake_case")]
35pub enum ClientMessage {
36    /// Must be the first message on every connection.
37    Hello { api: u32, role: Role },
38    /// Runs a module action. Answered with `ok` or `error`.
39    Command {
40        module: String,
41        action: String,
42        #[serde(default)]
43        args: Vec<String>,
44    },
45    /// Something happened to the island. UI only, never answered.
46    Event {
47        activity: ActivityId,
48        kind: EventKind,
49        /// The monitor whose island it happened on, when the UI knows.
50        #[serde(default, skip_serializing_if = "Option::is_none")]
51        output: Option<String>,
52        /// For `outside`: the click that closed it, which the daemon passes
53        /// on to the window under it once the island lets go.
54        #[serde(default, skip_serializing_if = "Option::is_none")]
55        click: Option<Click>,
56    },
57    /// A scroll the island caught that belongs to the window under it, once
58    /// the island lets go there. UI only, never answered.
59    PassOn { click: Click },
60    /// A click on a bubble. UI only, never answered.
61    BubbleClick { bubble: BubbleId },
62    /// A click on an area's "+N", for the bubbles it leaves out. The daemon
63    /// lists them in the island. UI only, never answered.
64    OverflowClick { area: Area },
65    /// Answered with `status`.
66    Status,
67    /// Reloads config and theme. Answered with `ok` or `error`.
68    Reload,
69    /// Closes what the island shows, as a right click on it does. For a
70    /// keybind: notices that don't take the keyboard can't hear Escape.
71    /// Answered with `ok`, also when nothing shows.
72    Dismiss,
73    /// Answered with `actions`, for one module or all of them.
74    ListActions {
75        #[serde(default, skip_serializing_if = "Option::is_none")]
76        module: Option<String>,
77    },
78    /// Asks the daemon to give the session to the daemon with process
79    /// `pid`, as `mochid --dev` does: it stops its shell and its modules,
80    /// waits for that process to end, then starts again. Answered with `ok`
81    /// before it stops.
82    StepAside { pid: u32 },
83    /// Records what mochid, Quickshell and the programs they start cost
84    /// for `seconds`, with a flame graph of mochid, and writes a report.
85    /// Answered with `output`, the report's path, once it's written.
86    Profile { seconds: u32 },
87    /// How many frames a window of the UI drew in the last second, while
88    /// the daemon profiles: `surface` is `island` or `desktop`. UI only,
89    /// never answered.
90    Frames {
91        output: String,
92        surface: String,
93        frames: u32,
94    },
95}
96
97/// Sent by the daemon.
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99#[serde(tag = "type", rename_all = "snake_case")]
100pub enum DaemonMessage {
101    /// Answer to the client's `hello`.
102    Hello { api: u32, version: String },
103    /// The enabled modules. Sent to the UI after `hello` and when the list
104    /// changes.
105    Modules { modules: Vec<String> },
106    /// What modules offer each other, from every enabled module. Sent to the
107    /// UI after `hello`.
108    Contributions { contributions: Vec<Contribution> },
109    /// The latest state a module published. Sent to the UI after `hello` for
110    /// every module, then whenever it changes.
111    State { module: String, state: Value },
112    /// A passing value a module sends many times a second, like an audio
113    /// meter's level. The daemon doesn't keep it or send it again.
114    Live { module: String, value: Value },
115    /// What the island shows now. `None` when no activity exists at all.
116    Present {
117        activity: Option<Activity>,
118        /// What islands on other monitors show while `activity` is meant
119        /// for one monitor: the idle island, when it runs. Only without
120        /// `output`.
121        #[serde(default, skip_serializing_if = "Option::is_none")]
122        resting: Option<Activity>,
123        /// The monitor whose island shows `activity`; every monitor's
124        /// without it. Each monitor has an island of its own.
125        #[serde(default, skip_serializing_if = "Option::is_none")]
126        output: Option<String>,
127    },
128    /// Every bubble, in drawing order. Sent to the UI after `hello` and on
129    /// every change.
130    Bubbles {
131        bubbles: Vec<Bubble>,
132        #[serde(default, skip_serializing_if = "Vec::is_empty")]
133        overflow: Vec<Overflow>,
134        /// How stacked areas behave, when any area stacks.
135        #[serde(default, skip_serializing_if = "Option::is_none")]
136        stack: Option<Stacking>,
137        /// The areas that merge or stack their bubbles; the others lay them
138        /// apart.
139        #[serde(default, skip_serializing_if = "Vec::is_empty")]
140        arrangements: Vec<AreaArrangement>,
141        /// How long the pointer rests on a bubble before its tooltip shows;
142        /// none means never.
143        #[serde(default, skip_serializing_if = "Option::is_none")]
144        tooltip_ms: Option<u64>,
145    },
146    /// Design tokens. Sent to the UI after `hello` and on reload.
147    Theme { theme: Box<Theme> },
148    /// A request succeeded.
149    Ok,
150    /// A command succeeded with something to say: a choice the user made,
151    /// for example. `mochi ipc` prints it.
152    Output { output: String },
153    /// Answer to `status`.
154    Status { status: Status },
155    /// Answer to `list_actions`.
156    Actions { modules: Vec<ModuleActions> },
157    /// A request failed, or a message could not be handled.
158    Error { code: ErrorCode, message: String },
159    /// Whether the daemon profiles now: while it does, the UI counts the
160    /// frames each window draws and sends `frames` every second. Sent to
161    /// the UI after `hello` and whenever it changes. UI only.
162    Profiling { on: bool },
163    /// The outputs a fullscreen window covers, by name: their island and
164    /// desktop can't be seen, so views there stop moving. Sent to the UI
165    /// after `hello` and whenever it changes. UI only.
166    Covered {
167        outputs: Vec<String>,
168        /// The monitors whose desktop windows hide, which covers the
169        /// desktop widgets there but not the island.
170        #[serde(default)]
171        desktops: Vec<String>,
172    },
173    /// Reload the views in place, keeping the windows: the shell directory
174    /// has a module it didn't have. The UI says hello again once it has.
175    /// UI only.
176    ReloadViews,
177}
178
179/// The activity the island shows.
180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181pub struct Activity {
182    pub id: ActivityId,
183    pub module: String,
184    /// The view to load: `modules/<module>/<view>.qml`.
185    pub view: String,
186    pub payload: Value,
187    /// Whether `view` is the expanded view.
188    pub expanded: bool,
189    /// Whether a click toggles between a compact and an expanded view.
190    pub expandable: bool,
191    /// The module's replacement key. A new activity with the same module, key
192    /// and view continues the previous one: the UI updates the payload in
193    /// place instead of switching views.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub key: Option<String>,
196    /// Takes the keyboard while shown, and a click anywhere outside the island
197    /// dismisses it. For views you type into, like a launcher.
198    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
199    pub modal: bool,
200    /// A full-screen view, `modules/<module>/<overlay>.qml`, drawn under the
201    /// island on every monitor while the activity shows. For picking
202    /// something on screen, like a region to capture. Implies `modal`.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub overlay: Option<String>,
205    /// The monitor a modal activity shows on, by name. The islands on other
206    /// monitors keep what they showed. Without one, every island shows it.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub output: Option<String>,
209    /// A click outside the island closes it, which means the UI catches
210    /// every click while it shows. Implied by `modal`.
211    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
212    pub outside: bool,
213    /// Shows over a fullscreen window, which hides the island otherwise. A
214    /// modal activity shows there without it.
215    #[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    /// The user closed the activity, for example with a swipe or a close
226    /// button.
227    Dismiss,
228    /// The user clicked outside the island while the activity was shown.
229    Outside,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233pub struct Status {
234    /// The daemon's version.
235    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    /// The plugins in plugins.toml.
242    #[serde(default, skip_serializing_if = "Vec::is_empty")]
243    pub plugins: Vec<PluginStatus>,
244    /// Why the island can't answer password prompts, when a connection
245    /// that said it's the UI isn't the Quickshell mochid started.
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub foreign_ui: Option<String>,
248}
249
250/// One plugin from plugins.toml, as the daemon sees it.
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct PluginStatus {
253    pub id: String,
254    pub state: PluginState,
255    /// Why it's missing or failed.
256    #[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    /// Enabled and running.
264    Running,
265    /// Installed, but not in `modules`.
266    Disabled,
267    /// Listed but not installed, or its manifest has an error.
268    Missing,
269    /// Its backend kept crashing and was stopped until the next reload.
270    Failed,
271}
272
273/// What the daemon knows about the compositor.
274#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
275pub struct CompositorStatus {
276    /// `wayland`, or `unsupported` when no compositor information is
277    /// available.
278    pub backend: String,
279    /// Output names.
280    pub outputs: Vec<String>,
281    pub workspaces: usize,
282    /// The output with focus, when the compositor says.
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub focused: Option<String>,
285    /// The active keyboard layout, when the compositor says.
286    #[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    /// The line was not a valid message.
294    BadMessage,
295    /// Something other than `hello` arrived first.
296    HelloFirst,
297    UnsupportedApi,
298    /// The connection's role may not send this message.
299    NotAllowed,
300    UnknownModule,
301    UnknownAction,
302    InvalidArgs,
303    /// The module accepted the command but it failed.
304    ModuleFailed,
305    /// `reload` found an error in a config file.
306    InvalidConfig,
307    Internal,
308}
309
310/// A click outside the island, where it happened, to pass on.
311#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
312pub struct Click {
313    /// The monitor it happened on.
314    pub output: String,
315    /// Where, in that monitor's logical pixels, out of `width` by `height`.
316    pub x: f64,
317    pub y: f64,
318    pub width: f64,
319    pub height: f64,
320    /// Qt's button: 1 left, 2 right, 4 middle; 0 for a scroll.
321    pub button: u32,
322    /// A scroll instead of a click: Qt's wheel angles, 120 a notch,
323    /// positive away from the user and to the right.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub scroll: Option<Scroll>,
326}
327
328/// A wheel or touchpad scroll, as Qt reports it.
329#[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    /// The UI parses these by hand, so their exact shape is part of the API.
581    #[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}