Skip to main content

mochi_protocol/
lib.rs

1//! The Mochi protocol: messages exchanged over the daemon's Unix socket.
2//!
3//! Every message is one JSON object on one line. Clients send a
4//! [`ClientMessage`], the daemon sends a [`DaemonMessage`]. Each object has a
5//! `type` field naming the variant in snake_case. `docs/protocol.md` describes
6//! the conversation in full.
7//!
8//! The protocol only grows: new message types and new fields with defaults.
9//! Removing or renaming anything means a new [`API`] version.
10
11mod actions;
12mod bubbles;
13mod contributions;
14mod messages;
15pub mod plugin;
16pub mod spec;
17mod theme;
18pub mod version;
19
20pub use actions::{ActionSpec, ArgKind, ArgSpec, ModuleActions};
21pub use bubbles::{Area, AreaArrangement, Arrangement, Bubble, BubbleId, Overflow, Stacking};
22pub use contributions::Contribution;
23pub use messages::{
24    Activity, ActivityId, Click, ClientMessage, CompositorStatus, DaemonMessage, ErrorCode,
25    EventKind, PluginState, PluginStatus, Role, Scroll, Status,
26};
27pub use theme::{
28    Anchor, Appearance, Color, ColorError, Colors, Layout, Mode, Motion, Notch, Text, Theme,
29};
30
31/// The protocol version both sides announce in `hello`.
32pub const API: u32 = 1;
33
34/// The longest line a reader should accept, in bytes. Anything longer is a
35/// broken or hostile peer.
36pub const MAX_LINE: usize = 1 << 20;
37
38/// Overrides where clients look for the daemon's socket. The daemon also sets
39/// it for the Quickshell process it starts.
40pub const SOCKET_ENV: &str = "MOCHI_SOCKET";
41
42/// `$MOCHI_SOCKET`, or else `$XDG_RUNTIME_DIR/mochi/mochi.sock`.
43pub fn socket_path() -> Option<std::path::PathBuf> {
44    let set = |name| std::env::var_os(name).filter(|value| !value.is_empty());
45    if let Some(socket) = set(SOCKET_ENV) {
46        return Some(socket.into());
47    }
48    let runtime: std::path::PathBuf = set("XDG_RUNTIME_DIR")?.into();
49    Some(runtime.join("mochi").join("mochi.sock"))
50}
51
52/// Serializes a message as one line, including the trailing newline.
53pub fn encode<T: serde::Serialize>(message: &T) -> Result<Vec<u8>, serde_json::Error> {
54    let mut line = serde_json::to_vec(message)?;
55    line.push(b'\n');
56    Ok(line)
57}
58
59/// Parses one line, with or without its trailing newline.
60pub fn decode<'a, T: serde::Deserialize<'a>>(line: &'a str) -> Result<T, serde_json::Error> {
61    serde_json::from_str(line.trim_end_matches(['\n', '\r']))
62}
63
64/// Module ids that changed, old first. The old id still works in
65/// `config.toml`, in commands and in plugin manifests, with a warning.
66pub const RENAMED_MODULES: [(&str, &str); 1] = [("hub", "control-center")];
67
68/// The current id of a module, for one named by its old id.
69pub fn module_id(id: &str) -> &str {
70    RENAMED_MODULES
71        .iter()
72        .find(|(old, _)| *old == id)
73        .map_or(id, |(_, new)| new)
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn encode_ends_with_one_newline() {
82        let line = encode(&ClientMessage::Status).unwrap();
83        assert_eq!(line, b"{\"type\":\"status\"}\n");
84    }
85
86    #[test]
87    fn decode_accepts_the_trailing_newline() {
88        let message: ClientMessage = decode("{\"type\":\"reload\"}\r\n").unwrap();
89        assert_eq!(message, ClientMessage::Reload);
90    }
91}