Skip to main content

mochi_protocol/
plugin.rs

1//! The conversation between mochid and a plugin backend.
2//!
3//! mochid starts the backend with one end of a socket pair as the file
4//! descriptor named by [`FD_ENV`], and the same JSON lines as the main
5//! socket go over it: mochid sends [`ToPlugin`], the backend sends
6//! [`FromPlugin`]. mochid speaks first, with `hello`; the backend answers
7//! with its own `hello`, then runs until mochid closes the socket.
8//!
9//! The messages mirror a builtin module's `ModuleCtx`, one message per
10//! call. The backend numbers its activities and bubbles itself, from 1, and
11//! events about them use its numbers. Requests that expect an answer carry
12//! an `id` the answer repeats.
13
14use std::path::PathBuf;
15
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use crate::Contribution;
20use crate::spec::{ActivitySpec, Args, BubbleSpec, CallError, EndReason};
21
22/// The environment variable holding the backend's end of the socket, as a
23/// file descriptor number: always `3`.
24pub const FD_ENV: &str = "MOCHI_PLUGIN_FD";
25
26/// The environment variable holding the plugin's directory, where its
27/// manifest is. The backend also starts there.
28pub const DIR_ENV: &str = "MOCHI_PLUGIN_DIR";
29
30/// Sent by mochid to a plugin backend.
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32#[serde(tag = "type", rename_all = "snake_case")]
33pub enum ToPlugin {
34    /// The first message. The backend answers with its own `hello`.
35    Hello {
36        api: u32,
37        /// mochid's version.
38        version: String,
39        /// The plugin's id.
40        module: String,
41        /// Its `[module.<id>]` table from config.toml, as JSON.
42        settings: Value,
43        /// See `ModuleCtx::data_dir`.
44        data_dir: PathBuf,
45        /// See `ModuleCtx::session_dir`.
46        session_dir: PathBuf,
47        compositor: CompositorState,
48    },
49    /// Runs one of its actions, with arguments already checked against the
50    /// manifest. Answer with `reply` and the same `id`.
51    Command { id: u64, action: String, args: Args },
52    /// A click on one of its activities that has no expanded view.
53    Clicked { activity: u64 },
54    /// The pointer came onto one of its activities on the island, or left.
55    Hovered { activity: u64, hovered: bool },
56    /// One of its activities is gone for good.
57    Ended { activity: u64, reason: EndReason },
58    /// A click on one of its bubbles.
59    BubbleClicked { bubble: u64 },
60    /// A module named in the manifest's `[uses] state` published state:
61    /// `null` when it stopped. Sent once at the start when it has some.
62    State { module: String, state: Value },
63    /// The compositor's state changed.
64    Compositor { state: CompositorState },
65    /// What the enabled modules offer this plugin: every contribution whose
66    /// `target` is its id. Sent at the start, then when a reload changes it.
67    Offers { offers: Vec<Contribution> },
68    /// The answer to a `call`.
69    CallResult {
70        id: u64,
71        #[serde(default, skip_serializing_if = "Option::is_none")]
72        error: Option<CallError>,
73        /// What the action answered with, like the output `mochi ipc`
74        /// prints.
75        #[serde(default, skip_serializing_if = "Option::is_none")]
76        output: Option<String>,
77    },
78    /// The answer to a compositor request: `windows` returns a list of
79    /// [`WindowInfo`], `pointer_output` a name or `null`.
80    CompositorResult {
81        id: u64,
82        #[serde(default)]
83        value: Value,
84        #[serde(default, skip_serializing_if = "Option::is_none")]
85        error: Option<String>,
86    },
87}
88
89/// Sent by a plugin backend to mochid.
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91#[serde(tag = "type", rename_all = "snake_case")]
92pub enum FromPlugin {
93    /// The answer to mochid's `hello`, with the protocol version the
94    /// backend speaks.
95    Hello {
96        api: u32,
97    },
98    /// Replaces its state, which the UI and other modules can read.
99    PublishState {
100        state: Value,
101    },
102    /// Submits an activity, numbered by the backend.
103    Present {
104        id: u64,
105        spec: ActivitySpec,
106    },
107    /// Replaces an activity's payload.
108    Update {
109        id: u64,
110        payload: Value,
111    },
112    Withdraw {
113        id: u64,
114    },
115    /// Shows a bubble, numbered by the backend, or replaces the one with the
116    /// same key.
117    ShowBubble {
118        id: u64,
119        spec: BubbleSpec,
120    },
121    UpdateBubble {
122        id: u64,
123        payload: Value,
124    },
125    HideBubble {
126        id: u64,
127    },
128    /// Answers a `command`: with `output` to print, or `error`, or neither
129    /// for plain success.
130    Reply {
131        id: u64,
132        #[serde(default, skip_serializing_if = "Option::is_none")]
133        output: Option<String>,
134        #[serde(default, skip_serializing_if = "Option::is_none")]
135        error: Option<String>,
136    },
137    /// Runs another module's action. Answered with `call_result`.
138    Call {
139        id: u64,
140        module: String,
141        action: String,
142        #[serde(default)]
143        args: Vec<String>,
144    },
145    /// Switches to a workspace. Answered with `compositor_result`.
146    ActivateWorkspace {
147        id: u64,
148        workspace: u32,
149    },
150    /// Asks for the windows on visible workspaces. Answered with
151    /// `compositor_result`.
152    Windows {
153        id: u64,
154    },
155    /// Asks which output the pointer is on. Answered with
156    /// `compositor_result`.
157    PointerOutput {
158        id: u64,
159    },
160}
161
162/// The compositor's state, as `ModuleCtx::compositor` gives builtins.
163#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
164pub struct CompositorState {
165    /// `wayland`, or `unsupported` without compositor information.
166    pub backend: String,
167    /// Sorted by name.
168    pub outputs: Vec<OutputInfo>,
169    /// Grouped by output, each output's in display order.
170    pub workspaces: Vec<WorkspaceInfo>,
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    /// The output with keyboard focus, by name, when the compositor says.
173    pub focused_output: Option<String>,
174    /// The app id of the window that had keyboard focus last.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub focused_app: Option<String>,
177    /// Something is capturing the screen.
178    #[serde(default)]
179    pub screencast: bool,
180    /// What is being captured, by monitor or window name.
181    #[serde(default)]
182    pub captured: Vec<String>,
183    /// The active keyboard layout's name, like `English (US)`, when the
184    /// compositor says.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub keyboard_layout: Option<String>,
187}
188
189/// A monitor.
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191pub struct OutputInfo {
192    /// The connector name, like `DP-3`.
193    pub name: String,
194    /// A human-readable name, often the monitor's model.
195    pub description: String,
196    /// Its mode in pixels, 0 until the compositor says.
197    pub width: u32,
198    /// See `width`.
199    pub height: u32,
200}
201
202/// A workspace.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct WorkspaceInfo {
205    /// Valid while the workspace exists; compositors may reuse it after.
206    pub id: u32,
207    /// Its name, like `1`.
208    pub name: String,
209    /// The output it's on, by name.
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub output: Option<String>,
212    /// Its position in the compositor's layout, when it has one.
213    #[serde(default)]
214    pub coordinates: Vec<u32>,
215    /// Shown on its output.
216    pub active: bool,
217    /// Something on it wants attention.
218    #[serde(default)]
219    pub urgent: bool,
220    /// The compositor hides it from workspace lists.
221    #[serde(default)]
222    pub hidden: bool,
223    /// Whether `activate_workspace` may switch to it.
224    #[serde(default)]
225    pub can_activate: bool,
226}
227
228/// A window on a visible workspace.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct WindowInfo {
231    /// Its title.
232    pub title: String,
233    /// Its app id, like `firefox`.
234    pub app_id: String,
235    /// Its position in the compositor's global layout, in logical pixels.
236    pub x: i32,
237    /// See `x`.
238    pub y: i32,
239    /// Its size, in logical pixels.
240    pub width: i32,
241    /// See `width`.
242    pub height: i32,
243    /// Floating rather than tiled.
244    pub floating: bool,
245}
246
247#[cfg(test)]
248mod tests {
249    use serde_json::json;
250
251    use super::*;
252    use crate::spec::ArgValue;
253    use crate::{decode, encode};
254
255    fn round_trip_to(message: ToPlugin) {
256        let line = encode(&message).unwrap();
257        let back: ToPlugin = decode(std::str::from_utf8(&line).unwrap()).unwrap();
258        assert_eq!(back, message);
259    }
260
261    fn round_trip_from(message: FromPlugin) {
262        let line = encode(&message).unwrap();
263        let back: FromPlugin = decode(std::str::from_utf8(&line).unwrap()).unwrap();
264        assert_eq!(back, message);
265    }
266
267    #[test]
268    fn every_message_to_a_plugin_round_trips() {
269        round_trip_to(ToPlugin::Hello {
270            api: 1,
271            version: "0.4.7".into(),
272            module: "pomodoro".into(),
273            settings: json!({ "minutes": 25 }),
274            data_dir: "/run/user/1000/mochi/data/pomodoro".into(),
275            session_dir: "/run/user/1000/mochi/session/pomodoro".into(),
276            compositor: CompositorState::default(),
277        });
278        round_trip_to(ToPlugin::Command {
279            id: 1,
280            action: "start".into(),
281            args: [("minutes".to_owned(), ArgValue::Int(5))]
282                .into_iter()
283                .collect(),
284        });
285        round_trip_to(ToPlugin::Clicked { activity: 2 });
286        round_trip_to(ToPlugin::Hovered {
287            activity: 2,
288            hovered: true,
289        });
290        round_trip_to(ToPlugin::Ended {
291            activity: 2,
292            reason: EndReason::Dismissed,
293        });
294        round_trip_to(ToPlugin::BubbleClicked { bubble: 3 });
295        round_trip_to(ToPlugin::State {
296            module: "media".into(),
297            state: json!({ "playing": true }),
298        });
299        round_trip_to(ToPlugin::Compositor {
300            state: CompositorState {
301                backend: "wayland".into(),
302                outputs: vec![OutputInfo {
303                    name: "DP-3".into(),
304                    description: "Some monitor".into(),
305                    width: 1920,
306                    height: 1080,
307                }],
308                workspaces: vec![WorkspaceInfo {
309                    id: 4,
310                    name: "1".into(),
311                    output: Some("DP-3".into()),
312                    coordinates: vec![0],
313                    active: true,
314                    urgent: false,
315                    hidden: false,
316                    can_activate: true,
317                }],
318                focused_output: Some("DP-3".into()),
319                focused_app: Some("kitty".into()),
320                screencast: false,
321                captured: Vec::new(),
322                keyboard_layout: Some("English (US)".into()),
323            },
324        });
325        round_trip_to(ToPlugin::CallResult {
326            id: 4,
327            error: None,
328            output: None,
329        });
330        round_trip_to(ToPlugin::CallResult {
331            id: 5,
332            error: Some(CallError::NotEnabled("media".into())),
333            output: None,
334        });
335        round_trip_to(ToPlugin::CallResult {
336            id: 6,
337            error: None,
338            output: Some("{\"title\": \"4\"}".into()),
339        });
340        round_trip_to(ToPlugin::Offers {
341            offers: vec![Contribution {
342                module: "emoji".into(),
343                target: "launcher".into(),
344                kind: "provider".into(),
345                id: "emoji".into(),
346                view: String::new(),
347                title: "Emoji".into(),
348                icon: None,
349                order: 0,
350                options: json!({ "prefix": ":" }),
351            }],
352        });
353        round_trip_to(ToPlugin::CompositorResult {
354            id: 6,
355            value: json!("DP-3"),
356            error: None,
357        });
358    }
359
360    #[test]
361    fn every_message_from_a_plugin_round_trips() {
362        round_trip_from(FromPlugin::Hello { api: 1 });
363        round_trip_from(FromPlugin::PublishState {
364            state: json!({ "left": 300 }),
365        });
366        round_trip_from(FromPlugin::Present {
367            id: 1,
368            spec: ActivitySpec::new("Timer").key("timer"),
369        });
370        round_trip_from(FromPlugin::Update {
371            id: 1,
372            payload: json!({ "left": 299 }),
373        });
374        round_trip_from(FromPlugin::Withdraw { id: 1 });
375        round_trip_from(FromPlugin::ShowBubble {
376            id: 2,
377            spec: BubbleSpec::new("Dot"),
378        });
379        round_trip_from(FromPlugin::UpdateBubble {
380            id: 2,
381            payload: json!(1),
382        });
383        round_trip_from(FromPlugin::HideBubble { id: 2 });
384        round_trip_from(FromPlugin::Reply {
385            id: 1,
386            output: Some("done".into()),
387            error: None,
388        });
389        round_trip_from(FromPlugin::Call {
390            id: 3,
391            module: "media".into(),
392            action: "toggle".into(),
393            args: Vec::new(),
394        });
395        round_trip_from(FromPlugin::ActivateWorkspace {
396            id: 4,
397            workspace: 2,
398        });
399        round_trip_from(FromPlugin::Windows { id: 5 });
400        round_trip_from(FromPlugin::PointerOutput { id: 6 });
401    }
402
403    /// Plugins in other languages write these by hand.
404    #[test]
405    fn short_forms_parse() {
406        let present: FromPlugin =
407            decode(r#"{"type":"present","id":1,"spec":{"compact":"Timer","timeout_ms":3000}}"#)
408                .unwrap();
409        let FromPlugin::Present { spec, .. } = present else {
410            panic!("not a present");
411        };
412        assert_eq!(spec.timeout, Some(std::time::Duration::from_secs(3)));
413
414        let reply: FromPlugin = decode(r#"{"type":"reply","id":1}"#).unwrap();
415        assert_eq!(
416            reply,
417            FromPlugin::Reply {
418                id: 1,
419                output: None,
420                error: None
421            }
422        );
423    }
424}