1use 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
22pub const FD_ENV: &str = "MOCHI_PLUGIN_FD";
25
26pub const DIR_ENV: &str = "MOCHI_PLUGIN_DIR";
29
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32#[serde(tag = "type", rename_all = "snake_case")]
33pub enum ToPlugin {
34 Hello {
36 api: u32,
37 version: String,
39 module: String,
41 settings: Value,
43 data_dir: PathBuf,
45 session_dir: PathBuf,
47 compositor: CompositorState,
48 },
49 Command { id: u64, action: String, args: Args },
52 Clicked { activity: u64 },
54 Hovered { activity: u64, hovered: bool },
56 Ended { activity: u64, reason: EndReason },
58 BubbleClicked { bubble: u64 },
60 State { module: String, state: Value },
63 Compositor { state: CompositorState },
65 Offers { offers: Vec<Contribution> },
68 CallResult {
70 id: u64,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 error: Option<CallError>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
76 output: Option<String>,
77 },
78 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91#[serde(tag = "type", rename_all = "snake_case")]
92pub enum FromPlugin {
93 Hello {
96 api: u32,
97 },
98 PublishState {
100 state: Value,
101 },
102 Present {
104 id: u64,
105 spec: ActivitySpec,
106 },
107 Update {
109 id: u64,
110 payload: Value,
111 },
112 Withdraw {
113 id: u64,
114 },
115 ShowBubble {
118 id: u64,
119 spec: BubbleSpec,
120 },
121 UpdateBubble {
122 id: u64,
123 payload: Value,
124 },
125 HideBubble {
126 id: u64,
127 },
128 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 Call {
139 id: u64,
140 module: String,
141 action: String,
142 #[serde(default)]
143 args: Vec<String>,
144 },
145 ActivateWorkspace {
147 id: u64,
148 workspace: u32,
149 },
150 Windows {
153 id: u64,
154 },
155 PointerOutput {
158 id: u64,
159 },
160}
161
162#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
164pub struct CompositorState {
165 pub backend: String,
167 pub outputs: Vec<OutputInfo>,
169 pub workspaces: Vec<WorkspaceInfo>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub focused_output: Option<String>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub focused_app: Option<String>,
177 #[serde(default)]
179 pub screencast: bool,
180 #[serde(default)]
182 pub captured: Vec<String>,
183 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub keyboard_layout: Option<String>,
187}
188
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191pub struct OutputInfo {
192 pub name: String,
194 pub description: String,
196 pub width: u32,
198 pub height: u32,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct WorkspaceInfo {
205 pub id: u32,
207 pub name: String,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
211 pub output: Option<String>,
212 #[serde(default)]
214 pub coordinates: Vec<u32>,
215 pub active: bool,
217 #[serde(default)]
219 pub urgent: bool,
220 #[serde(default)]
222 pub hidden: bool,
223 #[serde(default)]
225 pub can_activate: bool,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct WindowInfo {
231 pub title: String,
233 pub app_id: String,
235 pub x: i32,
237 pub y: i32,
239 pub width: i32,
241 pub height: i32,
243 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 #[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}