Skip to main content

mochi_protocol/
spec.rs

1//! What modules hand the daemon: activities for the island, bubbles, and
2//! the parsed arguments of their actions. Builtin modules use these types
3//! directly; plugin backends send them as JSON, so they serialize too.
4
5#![warn(missing_docs)]
6
7use std::time::Duration;
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::Area;
13
14/// Higher values win. The named levels leave room for anything in between.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16#[serde(transparent)]
17pub struct Priority(pub u8);
18
19impl Priority {
20    /// The idle island. Everything else interrupts it.
21    pub const IDLE: Self = Self(0);
22    /// Background news, like a finished download.
23    pub const LOW: Self = Self(25);
24    /// The default.
25    pub const NORMAL: Self = Self(50);
26    /// Worth interrupting for, like a call or a low battery.
27    pub const HIGH: Self = Self(75);
28    /// Needs attention now, like a critical battery.
29    pub const URGENT: Self = Self(100);
30    /// Interrupts anything, even uninterruptible activities, and nothing
31    /// interrupts it. For capturing the screen as it is: a screenshot of the
32    /// open launcher has to open over it.
33    pub const TOP: Self = Self(u8::MAX);
34}
35
36/// What a new activity does when the shown one has the same priority.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum SamePriority {
40    /// Wait until the shown activity ends.
41    #[default]
42    Queue,
43    /// Interrupt it. It comes back afterwards.
44    Stack,
45}
46
47/// Everything a module says about an activity it wants to show.
48///
49/// As JSON, only `compact` is required, and durations are milliseconds:
50/// `{"compact": "Timer", "timeout_ms": 4000}`.
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52#[serde(default)]
53pub struct ActivitySpec {
54    /// Replaces the module's existing activity with the same key.
55    pub key: Option<String>,
56    /// View shown by default: `modules/<module>/<compact>.qml`.
57    pub compact: String,
58    /// View shown after a click. Without one, clicks go to the module.
59    pub expanded: Option<String>,
60    /// Opens on the expanded view for this long, then collapses.
61    #[serde(
62        rename = "expand_for_ms",
63        with = "millis",
64        skip_serializing_if = "Option::is_none"
65    )]
66    pub expand_for: Option<Duration>,
67    /// What the views get as `payload`.
68    pub payload: Value,
69    /// Who shows first, and who interrupts whom.
70    pub priority: Priority,
71    /// Time on screen before the activity ends. `None` never times out.
72    #[serde(
73        rename = "timeout_ms",
74        with = "millis",
75        skip_serializing_if = "Option::is_none"
76    )]
77    pub timeout: Option<Duration>,
78    /// Whether a higher priority may interrupt it. [`Priority::TOP`]
79    /// interrupts anything.
80    pub interruptible: bool,
81    /// What it does when the shown activity has the same priority.
82    pub same_priority: SamePriority,
83    /// Takes the keyboard while shown; a click outside the island dismisses
84    /// it.
85    pub modal: bool,
86    /// A full-screen view under the island on every monitor.
87    pub overlay: Option<String>,
88    /// Never closes on a click outside, for feedback like the volume OSD
89    /// that shows while the user is busy elsewhere.
90    pub passive: bool,
91    /// Shown at once or not at all, never queued or suspended: feedback
92    /// like the volume OSD is stale by the time it would come back.
93    pub fleeting: bool,
94    /// Shows over a fullscreen window, like a game, which hides the island
95    /// otherwise. A modal activity shows there without it. For feedback on
96    /// something the user just did, like a screenshot or a volume key.
97    pub over_fullscreen: bool,
98    /// The monitor a modal activity shows on. The daemon picks one from
99    /// `[island] panels` when the module leaves it out.
100    pub output: Option<String>,
101}
102
103impl Default for ActivitySpec {
104    fn default() -> Self {
105        Self::new("")
106    }
107}
108
109impl ActivitySpec {
110    /// A normal-priority, interruptible activity with no timeout.
111    pub fn new(compact: impl Into<String>) -> Self {
112        Self {
113            key: None,
114            compact: compact.into(),
115            expanded: None,
116            expand_for: None,
117            payload: Value::Null,
118            priority: Priority::NORMAL,
119            timeout: None,
120            interruptible: true,
121            same_priority: SamePriority::Queue,
122            modal: false,
123            overlay: None,
124            output: None,
125            passive: false,
126            fleeting: false,
127            over_fullscreen: false,
128        }
129    }
130
131    /// Replaces the module's activity with the same key, wherever it is,
132    /// instead of adding one. With the same view too, the view updates in
133    /// place.
134    pub fn key(mut self, key: impl Into<String>) -> Self {
135        self.key = Some(key.into());
136        self
137    }
138
139    /// The view a click opens. Without one, clicks go to the module as
140    /// `Clicked`.
141    pub fn expanded(mut self, view: impl Into<String>) -> Self {
142        self.expanded = Some(view.into());
143        self
144    }
145
146    /// Opens on the expanded view, which needs one, and collapses after
147    /// `duration` on screen. A keyed replacement that sets it again opens it
148    /// again.
149    pub fn expand_for(mut self, duration: Duration) -> Self {
150        self.expand_for = Some(duration);
151        self
152    }
153
154    /// What the views get as `payload`.
155    pub fn payload(mut self, payload: Value) -> Self {
156        self.payload = payload;
157        self
158    }
159
160    /// See [`Priority`]; [`Priority::NORMAL`] by default.
161    pub fn priority(mut self, priority: Priority) -> Self {
162        self.priority = priority;
163        self
164    }
165
166    /// Ends it after this long on screen. The time only runs while it's
167    /// shown, not hovered and not expanded.
168    pub fn timeout(mut self, timeout: Duration) -> Self {
169        self.timeout = Some(timeout);
170        self
171    }
172
173    /// Nothing below [`Priority::TOP`] interrupts it.
174    pub fn uninterruptible(mut self) -> Self {
175        self.interruptible = false;
176        self
177    }
178
179    /// For views that take typing, like a launcher.
180    pub fn modal(mut self) -> Self {
181        self.modal = true;
182        self
183    }
184
185    /// Draws `view` over every monitor, under the island, while the activity
186    /// shows: `modules/<module>/<view>.qml`, which gets the payload and its
187    /// `screen`. Makes the activity modal. The island waits to show the
188    /// activity until the overlay's `ready` property is true, so an overlay
189    /// can capture the screen before the island changes.
190    pub fn overlay(mut self, view: impl Into<String>) -> Self {
191        self.overlay = Some(view.into());
192        self.modal = true;
193        self
194    }
195
196    /// Never closes on a click outside: see [`ActivitySpec::passive`].
197    pub fn passive(mut self) -> Self {
198        self.passive = true;
199        self
200    }
201
202    /// Never waits behind another activity: see [`ActivitySpec::fleeting`].
203    pub fn fleeting(mut self) -> Self {
204        self.fleeting = true;
205        self
206    }
207
208    /// Shows over a fullscreen window: see [`ActivitySpec::over_fullscreen`].
209    pub fn over_fullscreen(mut self) -> Self {
210        self.over_fullscreen = true;
211        self
212    }
213
214    /// Shows the activity on this monitor's island only, whatever
215    /// `[island] panels` or `notices` say. Each monitor has an island of
216    /// its own, so it waits only behind what that one shows.
217    pub fn output(mut self, output: impl Into<String>) -> Self {
218        self.output = Some(output.into());
219        self
220    }
221
222    /// [`SamePriority::Queue`] by default.
223    pub fn same_priority(mut self, rule: SamePriority) -> Self {
224        self.same_priority = rule;
225        self
226    }
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "snake_case")]
231/// Why an activity ended.
232pub enum EndReason {
233    /// Its timeout ran out.
234    Expired,
235    /// The user closed it.
236    Dismissed,
237    /// Its module withdrew it.
238    Withdrawn,
239    /// A newer activity with the same key took its place.
240    Replaced,
241    /// The user clicked outside the island, without having opened it: less
242    /// than a dismissal, more like its time running out early.
243    Outside,
244}
245
246/// Where a module's bubbles go unless the user moves them, for the
247/// settings panel's bubble editor. The module builds its specs from it
248/// with [`BubbleSpec::at`], so the editor and the bubbles agree.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
250pub struct BubbleHome {
251    /// The area they go in.
252    pub area: Area,
253    /// Bubbles with the same group next to each other share a pill.
254    pub group: Option<&'static str>,
255    /// Lower goes further left.
256    pub order: i32,
257    /// It has a wide view with text, which `wide = true` shows.
258    pub wide: bool,
259}
260
261impl BubbleHome {
262    /// In `area`, on their own, with no wide view.
263    pub const fn new(area: Area) -> Self {
264        Self {
265            area,
266            group: None,
267            order: 0,
268            wide: false,
269        }
270    }
271
272    /// Shares a pill with the bubbles of the same group.
273    pub const fn group(mut self, group: &'static str) -> Self {
274        self.group = Some(group);
275        self
276    }
277
278    /// Lower goes further left.
279    pub const fn order(mut self, order: i32) -> Self {
280        self.order = order;
281        self
282    }
283
284    /// Has a wide view with text.
285    pub const fn wide(mut self) -> Self {
286        self.wide = true;
287        self
288    }
289}
290
291/// Everything a module says about a bubble it wants to show.
292///
293/// As JSON, only `view` is required.
294#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
295#[serde(default)]
296pub struct BubbleSpec {
297    /// Replaces the module's existing bubble with the same key, keeping its
298    /// place.
299    pub key: Option<String>,
300    /// `modules/<module>/<view>.qml`: a small view that fits a round bubble,
301    /// an icon or a cover.
302    pub view: String,
303    /// A wider view with text, shown in a pill when the user asks for it
304    /// with `wide = true`.
305    pub wide: Option<String>,
306    /// What the views get as `payload`.
307    pub payload: Value,
308    /// Where it goes; the user's `[bubbles.<module>]` settings win.
309    pub area: Area,
310    /// Bubbles with the same group in the same area share one pill.
311    pub group: Option<String>,
312    /// Lower goes further left.
313    pub order: i32,
314    /// Breaks ties in `order`, decides who is left out when an area is
315    /// full, and who is in front of a stack.
316    pub priority: Priority,
317    /// Showing it again over the one with the same key is news: a stack
318    /// brings it to the front for a while. A new bubble always is.
319    pub news: bool,
320    /// What the pointer resting on it shows beside it. A view can say more
321    /// with a `tooltip` property, worked out from its payload.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub tooltip: Option<String>,
324}
325
326impl Default for BubbleSpec {
327    fn default() -> Self {
328        Self::new("")
329    }
330}
331
332impl BubbleSpec {
333    /// A normal-priority bubble on its own, right of the center.
334    pub fn new(view: impl Into<String>) -> Self {
335        Self {
336            key: None,
337            view: view.into(),
338            wide: None,
339            payload: Value::Null,
340            area: Area::CenterRight,
341            group: None,
342            order: 0,
343            priority: Priority::NORMAL,
344            news: false,
345            tooltip: None,
346        }
347    }
348
349    /// What the pointer resting on it shows beside it.
350    pub fn tooltip(mut self, text: impl Into<String>) -> Self {
351        self.tooltip = Some(text.into());
352        self
353    }
354
355    /// Replaces the module's bubble with the same key in place.
356    pub fn key(mut self, key: impl Into<String>) -> Self {
357        self.key = Some(key.into());
358        self
359    }
360
361    /// The wider view with text, for users who set `wide = true`.
362    pub fn wide(mut self, view: impl Into<String>) -> Self {
363        self.wide = Some(view.into());
364        self
365    }
366
367    /// What the views get as `payload`.
368    pub fn payload(mut self, payload: Value) -> Self {
369        self.payload = payload;
370        self
371    }
372
373    /// [`Area::CenterRight`] by default.
374    pub fn area(mut self, area: Area) -> Self {
375        self.area = area;
376        self
377    }
378
379    /// Bubbles with the same group next to each other share a pill.
380    pub fn group(mut self, group: impl Into<String>) -> Self {
381        self.group = Some(group.into());
382        self
383    }
384
385    /// Lower goes further left.
386    pub fn order(mut self, order: i32) -> Self {
387        self.order = order;
388        self
389    }
390
391    /// Where its module's bubbles go by default: `home`'s area, group and
392    /// order.
393    pub fn at(mut self, home: &BubbleHome) -> Self {
394        self.area = home.area;
395        self.group = home.group.map(str::to_owned);
396        self.order = home.order;
397        self
398    }
399
400    /// Breaks ties in `order`, picks who stays when an area is full and
401    /// who is in front of a stack.
402    pub fn priority(mut self, priority: Priority) -> Self {
403        self.priority = priority;
404        self
405    }
406
407    /// Marks this showing as news: see [`BubbleSpec::news`].
408    pub fn news(mut self) -> Self {
409        self.news = true;
410        self
411    }
412}
413
414/// One parsed argument, of the kind its action declares.
415#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
416#[serde(untagged)]
417pub enum ArgValue {
418    /// A `string` or `choice` argument, or `rest`.
419    String(String),
420    /// An `int` argument.
421    Int(i64),
422    /// A `float` argument.
423    Float(f64),
424    /// A `bool` argument.
425    Bool(bool),
426}
427
428/// Parsed arguments, looked up by name.
429///
430/// As JSON, an object from names to values: `{"minutes": 25}`.
431#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
432#[serde(
433    from = "serde_json::Map<String, Value>",
434    into = "serde_json::Map<String, Value>"
435)]
436pub struct Args(Vec<(String, ArgValue)>);
437
438impl Args {
439    /// An argument by name, whatever its kind.
440    pub fn get(&self, name: &str) -> Option<&ArgValue> {
441        self.0
442            .iter()
443            .find(|(arg, _)| arg == name)
444            .map(|(_, value)| value)
445    }
446
447    /// The value of a `string`, `choice` or `rest` argument.
448    pub fn str(&self, name: &str) -> Option<&str> {
449        match self.get(name)? {
450            ArgValue::String(value) => Some(value),
451            _ => None,
452        }
453    }
454
455    /// The value of an `int` argument.
456    pub fn int(&self, name: &str) -> Option<i64> {
457        match self.get(name)? {
458            ArgValue::Int(value) => Some(*value),
459            _ => None,
460        }
461    }
462
463    /// The value of a `float` argument.
464    pub fn float(&self, name: &str) -> Option<f64> {
465        match self.get(name)? {
466            ArgValue::Float(value) => Some(*value),
467            _ => None,
468        }
469    }
470
471    /// The value of a `bool` argument.
472    pub fn bool(&self, name: &str) -> Option<bool> {
473        match self.get(name)? {
474            ArgValue::Bool(value) => Some(*value),
475            _ => None,
476        }
477    }
478}
479
480/// Why calling another module's action failed.
481///
482/// As JSON: `{"kind": "not_enabled", "detail": "media"}`.
483#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
484#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
485pub enum CallError {
486    /// The module isn't enabled: the usual case for a soft dependency.
487    #[error("module {0:?} is not enabled")]
488    NotEnabled(String),
489    #[error("a module cannot call itself")]
490    /// A module called its own action.
491    Itself,
492    #[error("{module} has no action {action:?}")]
493    /// That module has no such action.
494    UnknownAction {
495        /// The module called.
496        module: String,
497        /// The action it doesn't have.
498        action: String,
499    },
500    #[error("{0}")]
501    /// The arguments don't fit the action; the message has its usage.
502    InvalidArgs(String),
503    /// The module ran the action and reported a failure, or isn't running.
504    #[error("{0}")]
505    Failed(String),
506}
507
508impl FromIterator<(String, ArgValue)> for Args {
509    fn from_iter<I: IntoIterator<Item = (String, ArgValue)>>(pairs: I) -> Self {
510        Self(pairs.into_iter().collect())
511    }
512}
513
514impl From<serde_json::Map<String, Value>> for Args {
515    /// Values that aren't strings, numbers or booleans are left out.
516    fn from(map: serde_json::Map<String, Value>) -> Self {
517        map.into_iter()
518            .filter_map(|(name, value)| Some((name, serde_json::from_value(value).ok()?)))
519            .collect()
520    }
521}
522
523impl From<Args> for serde_json::Map<String, Value> {
524    fn from(args: Args) -> Self {
525        args.0
526            .into_iter()
527            .map(|(name, value)| {
528                let value = match value {
529                    ArgValue::String(value) => Value::from(value),
530                    ArgValue::Int(value) => Value::from(value),
531                    ArgValue::Float(value) => Value::from(value),
532                    ArgValue::Bool(value) => Value::from(value),
533                };
534                (name, value)
535            })
536            .collect()
537    }
538}
539
540/// Durations as whole milliseconds.
541mod millis {
542    use std::time::Duration;
543
544    use serde::{Deserialize, Deserializer, Serializer};
545
546    pub fn serialize<S: Serializer>(
547        value: &Option<Duration>,
548        serializer: S,
549    ) -> Result<S::Ok, S::Error> {
550        match value {
551            Some(duration) => {
552                serializer.serialize_some(&u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
553            }
554            None => serializer.serialize_none(),
555        }
556    }
557
558    pub fn deserialize<'de, D: Deserializer<'de>>(
559        deserializer: D,
560    ) -> Result<Option<Duration>, D::Error> {
561        Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_millis))
562    }
563}
564
565#[cfg(test)]
566mod tests {
567    use serde_json::json;
568
569    use super::*;
570
571    #[test]
572    fn an_activity_needs_only_its_view() {
573        let spec: ActivitySpec = serde_json::from_value(json!({ "compact": "Timer" })).unwrap();
574        assert_eq!(spec, ActivitySpec::new("Timer"));
575    }
576
577    #[test]
578    fn activities_round_trip_with_durations_in_milliseconds() {
579        let spec = ActivitySpec::new("Timer")
580            .expanded("Big")
581            .timeout(Duration::from_millis(1500))
582            .priority(Priority::HIGH)
583            .same_priority(SamePriority::Stack)
584            .uninterruptible();
585        let json = serde_json::to_value(&spec).unwrap();
586        assert_eq!(json["timeout_ms"], 1500);
587        assert_eq!(json["priority"], 75);
588        assert_eq!(json["same_priority"], "stack");
589        assert_eq!(serde_json::from_value::<ActivitySpec>(json).unwrap(), spec);
590    }
591
592    #[test]
593    fn bubbles_round_trip() {
594        let spec = BubbleSpec::new("Dot")
595            .key("timer")
596            .area(Area::Right)
597            .priority(Priority::LOW)
598            .news();
599        let json = serde_json::to_value(&spec).unwrap();
600        assert_eq!(json["area"], "right");
601        assert_eq!(serde_json::from_value::<BubbleSpec>(json).unwrap(), spec);
602        let short: BubbleSpec = serde_json::from_value(json!({ "view": "Dot" })).unwrap();
603        assert_eq!(short, BubbleSpec::new("Dot"));
604    }
605
606    #[test]
607    fn args_are_an_object() {
608        let args: Args = [
609            ("minutes".to_owned(), ArgValue::Int(25)),
610            ("label".to_owned(), ArgValue::String("Write".into())),
611            ("ratio".to_owned(), ArgValue::Float(0.5)),
612            ("loud".to_owned(), ArgValue::Bool(true)),
613        ]
614        .into_iter()
615        .collect();
616        let json = serde_json::to_value(&args).unwrap();
617        assert_eq!(
618            json,
619            json!({ "minutes": 25, "label": "Write", "ratio": 0.5, "loud": true })
620        );
621        let back: Args = serde_json::from_value(json).unwrap();
622        assert_eq!(back.int("minutes"), Some(25));
623        assert_eq!(back.str("label"), Some("Write"));
624        assert_eq!(back.float("ratio"), Some(0.5));
625        assert_eq!(back.bool("loud"), Some(true));
626    }
627}