1#![warn(missing_docs)]
6
7use std::time::Duration;
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::Area;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16#[serde(transparent)]
17pub struct Priority(pub u8);
18
19impl Priority {
20 pub const IDLE: Self = Self(0);
22 pub const LOW: Self = Self(25);
24 pub const NORMAL: Self = Self(50);
26 pub const HIGH: Self = Self(75);
28 pub const URGENT: Self = Self(100);
30 pub const TOP: Self = Self(u8::MAX);
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum SamePriority {
40 #[default]
42 Queue,
43 Stack,
45}
46
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52#[serde(default)]
53pub struct ActivitySpec {
54 pub key: Option<String>,
56 pub compact: String,
58 pub expanded: Option<String>,
60 #[serde(
62 rename = "expand_for_ms",
63 with = "millis",
64 skip_serializing_if = "Option::is_none"
65 )]
66 pub expand_for: Option<Duration>,
67 pub payload: Value,
69 pub priority: Priority,
71 #[serde(
73 rename = "timeout_ms",
74 with = "millis",
75 skip_serializing_if = "Option::is_none"
76 )]
77 pub timeout: Option<Duration>,
78 pub interruptible: bool,
81 pub same_priority: SamePriority,
83 pub modal: bool,
86 pub overlay: Option<String>,
88 pub passive: bool,
91 pub fleeting: bool,
94 pub over_fullscreen: bool,
98 pub output: Option<String>,
101}
102
103impl Default for ActivitySpec {
104 fn default() -> Self {
105 Self::new("")
106 }
107}
108
109impl ActivitySpec {
110 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 pub fn key(mut self, key: impl Into<String>) -> Self {
135 self.key = Some(key.into());
136 self
137 }
138
139 pub fn expanded(mut self, view: impl Into<String>) -> Self {
142 self.expanded = Some(view.into());
143 self
144 }
145
146 pub fn expand_for(mut self, duration: Duration) -> Self {
150 self.expand_for = Some(duration);
151 self
152 }
153
154 pub fn payload(mut self, payload: Value) -> Self {
156 self.payload = payload;
157 self
158 }
159
160 pub fn priority(mut self, priority: Priority) -> Self {
162 self.priority = priority;
163 self
164 }
165
166 pub fn timeout(mut self, timeout: Duration) -> Self {
169 self.timeout = Some(timeout);
170 self
171 }
172
173 pub fn uninterruptible(mut self) -> Self {
175 self.interruptible = false;
176 self
177 }
178
179 pub fn modal(mut self) -> Self {
181 self.modal = true;
182 self
183 }
184
185 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 pub fn passive(mut self) -> Self {
198 self.passive = true;
199 self
200 }
201
202 pub fn fleeting(mut self) -> Self {
204 self.fleeting = true;
205 self
206 }
207
208 pub fn over_fullscreen(mut self) -> Self {
210 self.over_fullscreen = true;
211 self
212 }
213
214 pub fn output(mut self, output: impl Into<String>) -> Self {
218 self.output = Some(output.into());
219 self
220 }
221
222 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")]
231pub enum EndReason {
233 Expired,
235 Dismissed,
237 Withdrawn,
239 Replaced,
241 Outside,
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
250pub struct BubbleHome {
251 pub area: Area,
253 pub group: Option<&'static str>,
255 pub order: i32,
257 pub wide: bool,
259}
260
261impl BubbleHome {
262 pub const fn new(area: Area) -> Self {
264 Self {
265 area,
266 group: None,
267 order: 0,
268 wide: false,
269 }
270 }
271
272 pub const fn group(mut self, group: &'static str) -> Self {
274 self.group = Some(group);
275 self
276 }
277
278 pub const fn order(mut self, order: i32) -> Self {
280 self.order = order;
281 self
282 }
283
284 pub const fn wide(mut self) -> Self {
286 self.wide = true;
287 self
288 }
289}
290
291#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
295#[serde(default)]
296pub struct BubbleSpec {
297 pub key: Option<String>,
300 pub view: String,
303 pub wide: Option<String>,
306 pub payload: Value,
308 pub area: Area,
310 pub group: Option<String>,
312 pub order: i32,
314 pub priority: Priority,
317 pub news: bool,
320 #[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 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 pub fn tooltip(mut self, text: impl Into<String>) -> Self {
351 self.tooltip = Some(text.into());
352 self
353 }
354
355 pub fn key(mut self, key: impl Into<String>) -> Self {
357 self.key = Some(key.into());
358 self
359 }
360
361 pub fn wide(mut self, view: impl Into<String>) -> Self {
363 self.wide = Some(view.into());
364 self
365 }
366
367 pub fn payload(mut self, payload: Value) -> Self {
369 self.payload = payload;
370 self
371 }
372
373 pub fn area(mut self, area: Area) -> Self {
375 self.area = area;
376 self
377 }
378
379 pub fn group(mut self, group: impl Into<String>) -> Self {
381 self.group = Some(group.into());
382 self
383 }
384
385 pub fn order(mut self, order: i32) -> Self {
387 self.order = order;
388 self
389 }
390
391 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 pub fn priority(mut self, priority: Priority) -> Self {
403 self.priority = priority;
404 self
405 }
406
407 pub fn news(mut self) -> Self {
409 self.news = true;
410 self
411 }
412}
413
414#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
416#[serde(untagged)]
417pub enum ArgValue {
418 String(String),
420 Int(i64),
422 Float(f64),
424 Bool(bool),
426}
427
428#[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 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
484#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
485pub enum CallError {
486 #[error("module {0:?} is not enabled")]
488 NotEnabled(String),
489 #[error("a module cannot call itself")]
490 Itself,
492 #[error("{module} has no action {action:?}")]
493 UnknownAction {
495 module: String,
497 action: String,
499 },
500 #[error("{0}")]
501 InvalidArgs(String),
503 #[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 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
540mod 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}