Skip to main content

mochi_sdk/
lib.rs

1//! Write Mochi plugin backends in Rust.
2//!
3//! A plugin backend is a program mochid starts and talks to over a socket.
4//! This crate does the talking: [`ModuleCtx`] has the same calls as a
5//! builtin module's context in mochid, so a plugin can show activities on
6//! the island, bubbles, answer `mochi ipc` actions and publish state for
7//! its views, like any builtin.
8//!
9//! ```no_run
10//! use mochi_sdk::{ActivitySpec, ModuleCtx, ModuleEvent, json};
11//!
12//! fn main() -> std::process::ExitCode {
13//!     mochi_sdk::run(hello)
14//! }
15//!
16//! async fn hello(mut ctx: ModuleCtx) -> Result<(), mochi_sdk::Error> {
17//!     while let Some(event) = ctx.next_event().await {
18//!         if let ModuleEvent::Command(command) = event {
19//!             // `mochi ipc hello say`, declared in mochi-plugin.toml.
20//!             let spec = ActivitySpec::new("Hello").payload(json!({ "text": "Hi" }));
21//!             ctx.present(spec);
22//!             command.reply(Ok(()));
23//!         }
24//!     }
25//!     Ok(())
26//! }
27//! ```
28//!
29//! The backend runs until mochid closes the connection: then
30//! [`ModuleCtx::next_event`] returns `None`, and the plugin should return.
31
32#![warn(missing_docs)]
33
34use std::collections::HashMap;
35use std::future::Future;
36use std::os::fd::FromRawFd;
37use std::path::{Path, PathBuf};
38use std::process::ExitCode;
39use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
40use std::sync::{Arc, Mutex};
41
42/// The protocol's message types, for tests that play mochid's part: see
43/// [`ModuleCtx::over`].
44pub use mochi_protocol as protocol;
45pub use mochi_protocol::plugin::{CompositorState, OutputInfo, WindowInfo, WorkspaceInfo};
46pub use mochi_protocol::spec::{
47    ActivitySpec, ArgValue, Args, BubbleSpec, CallError, EndReason, Priority, SamePriority,
48};
49pub use mochi_protocol::{API, ActivityId, Area, BubbleId, Contribution};
50pub use serde_json::{Value, json};
51
52use mochi_protocol::plugin::{FD_ENV, FromPlugin, ToPlugin};
53use serde::de::DeserializeOwned;
54use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
55use tokio::net::UnixStream;
56use tokio::sync::{mpsc, oneshot, watch};
57
58/// Any error a plugin returns: `?` turns most errors into it, and
59/// `"text".into()` makes one from a message.
60pub type Error = Box<dyn std::error::Error + Send + Sync>;
61
62/// Connects to mochid, runs `plugin` until it returns, and turns its result
63/// into an exit code. Runs on a single-threaded tokio runtime; to pick
64/// another, use [`ModuleCtx::connect`] from your own.
65pub fn run<F, Fut>(plugin: F) -> ExitCode
66where
67    F: FnOnce(ModuleCtx) -> Fut,
68    Fut: Future<Output = Result<(), Error>>,
69{
70    let runtime = match tokio::runtime::Builder::new_current_thread()
71        .enable_all()
72        .build()
73    {
74        Ok(runtime) => runtime,
75        Err(error) => {
76            report(&format!("cannot start the async runtime: {error}"));
77            return ExitCode::FAILURE;
78        }
79    };
80    let result = runtime.block_on(async {
81        let ctx = ModuleCtx::connect().await?;
82        plugin(ctx).await
83    });
84    match result {
85        Ok(()) => ExitCode::SUCCESS,
86        Err(error) => {
87            report(&error.to_string());
88            ExitCode::FAILURE
89        }
90    }
91}
92
93/// mochid logs what a backend prints on stderr.
94#[allow(clippy::print_stderr)]
95fn report(message: &str) {
96    eprintln!("{message}");
97}
98
99/// What mochid tells the plugin.
100#[derive(Debug)]
101pub enum ModuleEvent {
102    /// `mochi ipc <plugin> <action>`, or a call from another module. Answer
103    /// it with [`ModuleCommand::reply`] or [`ModuleCommand::answer`].
104    Command(ModuleCommand),
105    /// A click on one of its activities that has no expanded view.
106    Clicked(ActivityId),
107    /// The pointer came onto one of its activities on the island, or left.
108    Hovered {
109        /// The id [`ModuleCtx::present`] returned.
110        activity: ActivityId,
111        /// Whether the pointer is on it now.
112        hovered: bool,
113    },
114    /// One of its activities is gone for good.
115    Ended {
116        /// The id [`ModuleCtx::present`] returned.
117        activity: ActivityId,
118        /// Why: it timed out, the user closed it, the plugin withdrew it,
119        /// another with its key replaced it, or a click outside closed it.
120        reason: EndReason,
121    },
122    /// A click on one of its bubbles.
123    BubbleClicked(BubbleId),
124    /// A module from `[uses] state` in the manifest published state:
125    /// `Value::Null` when it stopped. Sent once at the start when it has
126    /// some, then on every change.
127    State {
128        /// The module's id.
129        module: String,
130        /// Its whole state, as it published it.
131        state: Value,
132    },
133    /// What the enabled modules offer this plugin: every contribution whose
134    /// `target` is its id. Sent at the start, then when a reload changes it.
135    Offers(Vec<Contribution>),
136}
137
138/// An action to run, with arguments already checked against the manifest.
139/// Dropping it without an answer tells the caller it failed.
140#[derive(Debug)]
141pub struct ModuleCommand {
142    /// The action's name, from the manifest.
143    pub action: String,
144    /// Its arguments, parsed into the kinds the manifest declares: read
145    /// them with [`Args::str`], [`Args::int`], [`Args::float`] and
146    /// [`Args::bool`]. Optional ones that were left out are missing.
147    pub args: Args,
148    id: u64,
149    outgoing: Option<mpsc::UnboundedSender<FromPlugin>>,
150}
151
152impl ModuleCommand {
153    /// Answers: `Ok(())` for success, `Err` with a message `mochi ipc`
154    /// prints as the failure.
155    pub fn reply(mut self, result: Result<(), String>) {
156        self.send(None, result.err());
157    }
158
159    /// Replies with output, which `mochi ipc` prints.
160    pub fn answer(mut self, result: Result<String, String>) {
161        match result {
162            Ok(output) => self.send(Some(output), None),
163            Err(error) => self.send(None, Some(error)),
164        }
165    }
166
167    fn send(&mut self, output: Option<String>, error: Option<String>) {
168        if let Some(outgoing) = self.outgoing.take() {
169            let _ = outgoing.send(FromPlugin::Reply {
170                id: self.id,
171                output,
172                error,
173            });
174        }
175    }
176}
177
178impl Drop for ModuleCommand {
179    fn drop(&mut self) {
180        self.send(
181            None,
182            Some("the plugin dropped the command without answering".into()),
183        );
184    }
185}
186
187type Pending = Arc<Mutex<HashMap<u64, oneshot::Sender<ToPlugin>>>>;
188
189/// The plugin's connection to mochid. Every call is one message, and none
190/// waits for mochid unless it returns a future.
191#[derive(Debug)]
192pub struct ModuleCtx {
193    module: String,
194    version: String,
195    settings: Value,
196    data_dir: PathBuf,
197    session_dir: PathBuf,
198    ids: AtomicU64,
199    requests: AtomicU64,
200    outgoing: mpsc::UnboundedSender<FromPlugin>,
201    events: mpsc::UnboundedReceiver<ModuleEvent>,
202    pending: Pending,
203    compositor: watch::Receiver<CompositorState>,
204}
205
206impl ModuleCtx {
207    /// Connects through the socket mochid passes in `MOCHI_PLUGIN_FD` and
208    /// says hello. Fails when the program wasn't started by mochid.
209    pub async fn connect() -> Result<Self, Error> {
210        let fd: i32 = std::env::var(FD_ENV)
211            .map_err(|_| format!("{FD_ENV} isn't set: mochid starts plugin backends, not you"))?
212            .parse()
213            .map_err(|_| format!("{FD_ENV} isn't a file descriptor"))?;
214        static TAKEN: AtomicBool = AtomicBool::new(false);
215        if TAKEN.swap(true, Ordering::SeqCst) {
216            return Err("already connected to mochid".into());
217        }
218        // SAFETY: mochid opens this descriptor for the backend and nothing
219        // else in the process owns it; `TAKEN` makes sure it's wrapped once.
220        let stream = unsafe { std::os::unix::net::UnixStream::from_raw_fd(fd) };
221        stream.set_nonblocking(true)?;
222        Self::over(UnixStream::from_std(stream)?).await
223    }
224
225    /// Talks to mochid over `stream`: for tests, which play mochid's part
226    /// on the other end. mochid speaks first, with `hello`.
227    ///
228    /// ```
229    /// use mochi_sdk::protocol::plugin::{CompositorState, FromPlugin, ToPlugin};
230    /// use mochi_sdk::{ActivitySpec, ModuleCtx, json};
231    /// use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
232    /// use tokio::net::UnixStream;
233    ///
234    /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
235    /// let (mochid, plugin) = UnixStream::pair().unwrap();
236    /// let (reader, mut writer) = mochid.into_split();
237    /// let hello = ToPlugin::Hello {
238    ///     api: mochi_sdk::API,
239    ///     version: "test".into(),
240    ///     module: "timer".into(),
241    ///     settings: json!({ "minutes": 5 }),
242    ///     data_dir: "/tmp/timer".into(),
243    ///     session_dir: "/tmp/timer".into(),
244    ///     compositor: CompositorState::default(),
245    /// };
246    /// writer.write_all(&mochi_sdk::protocol::encode(&hello).unwrap()).await.unwrap();
247    ///
248    /// let ctx = ModuleCtx::over(plugin).await.unwrap();
249    /// ctx.present(ActivitySpec::new("Timer"));
250    ///
251    /// // What the plugin sent: its hello, then the activity.
252    /// let mut lines = BufReader::new(reader).lines();
253    /// let mut next = async || {
254    ///     let line = lines.next_line().await.unwrap().unwrap();
255    ///     mochi_sdk::protocol::decode::<FromPlugin>(&line).unwrap()
256    /// };
257    /// assert_eq!(next().await, FromPlugin::Hello { api: mochi_sdk::API });
258    /// assert!(matches!(next().await, FromPlugin::Present { id: 1, .. }));
259    /// # });
260    /// ```
261    pub async fn over(stream: UnixStream) -> Result<Self, Error> {
262        let (reader, mut writer) = stream.into_split();
263        let mut reader = BufReader::new(reader);
264        let mut line = String::new();
265        reader.read_line(&mut line).await?;
266        let ToPlugin::Hello {
267            api,
268            version,
269            module,
270            settings,
271            data_dir,
272            session_dir,
273            compositor,
274        } = mochi_protocol::decode(&line)?
275        else {
276            return Err("mochid didn't start with hello".into());
277        };
278        if api != API {
279            return Err(format!("mochid speaks api {api}, this plugin speaks {API}").into());
280        }
281        writer
282            .write_all(&mochi_protocol::encode(&FromPlugin::Hello { api: API })?)
283            .await?;
284
285        let (outgoing, mut to_write) = mpsc::unbounded_channel::<FromPlugin>();
286        tokio::spawn(async move {
287            while let Some(message) = to_write.recv().await {
288                let Ok(line) = mochi_protocol::encode(&message) else {
289                    continue;
290                };
291                if writer.write_all(&line).await.is_err() {
292                    break;
293                }
294            }
295        });
296
297        let (events, received) = mpsc::unbounded_channel();
298        let (compositor_sender, compositor) = watch::channel(compositor);
299        let pending = Pending::default();
300        tokio::spawn(read(
301            reader,
302            events,
303            compositor_sender,
304            pending.clone(),
305            outgoing.clone(),
306        ));
307
308        Ok(Self {
309            module,
310            version,
311            settings,
312            data_dir,
313            session_dir,
314            ids: AtomicU64::new(0),
315            requests: AtomicU64::new(0),
316            outgoing,
317            events: received,
318            pending,
319            compositor,
320        })
321    }
322
323    /// The plugin's id.
324    pub fn module(&self) -> &str {
325        &self.module
326    }
327
328    /// mochid's version.
329    pub fn version(&self) -> &str {
330        &self.version
331    }
332
333    /// The plugin's `[module.<id>]` table from config.toml. Fields missing
334    /// there take their `Default` values when `T` uses `#[serde(default)]`.
335    pub fn settings<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
336        let settings = match &self.settings {
337            Value::Null => Value::Object(serde_json::Map::new()),
338            other => other.clone(),
339        };
340        serde_json::from_value(settings)
341    }
342
343    /// A directory only this plugin writes to, emptied when mochid starts,
344    /// in the runtime directory: for files its views load.
345    pub fn data_dir(&self) -> &Path {
346        &self.data_dir
347    }
348
349    /// Like [`data_dir`](Self::data_dir), but kept across mochid restarts.
350    /// Created on first use.
351    pub fn session_dir(&self) -> &Path {
352        &self.session_dir
353    }
354
355    /// Replaces the plugin's state, which its views read as
356    /// `Daemon.state("<id>")` and other modules can watch.
357    pub fn publish_state(&self, state: Value) {
358        self.send(FromPlugin::PublishState { state });
359    }
360
361    /// Submits an activity to the island. Whether and when it shows is up
362    /// to the arbiter.
363    pub fn present(&self, spec: ActivitySpec) -> ActivityId {
364        let id = self.next_id();
365        self.send(FromPlugin::Present { id, spec });
366        ActivityId(id)
367    }
368
369    /// Replaces an activity's payload. Its view updates in place.
370    pub fn update(&self, id: ActivityId, payload: Value) {
371        self.send(FromPlugin::Update { id: id.0, payload });
372    }
373
374    /// Removes an activity, shown or waiting. It ends with
375    /// [`EndReason::Withdrawn`].
376    pub fn withdraw(&self, id: ActivityId) {
377        self.send(FromPlugin::Withdraw { id: id.0 });
378    }
379
380    /// Shows a bubble, or replaces the plugin's bubble with the same key.
381    pub fn show_bubble(&self, spec: BubbleSpec) -> BubbleId {
382        let id = self.next_id();
383        self.send(FromPlugin::ShowBubble { id, spec });
384        BubbleId(id)
385    }
386
387    /// Replaces a bubble's payload, keeping its place. Not news: see
388    /// [`BubbleSpec::news`].
389    pub fn update_bubble(&self, id: BubbleId, payload: Value) {
390        self.send(FromPlugin::UpdateBubble { id: id.0, payload });
391    }
392
393    /// Removes a bubble.
394    pub fn hide_bubble(&self, id: BubbleId) {
395        self.send(FromPlugin::HideBubble { id: id.0 });
396    }
397
398    /// Runs another module's action, with the same checks as `mochi ipc`.
399    /// [`CallError::NotEnabled`] means that module isn't enabled.
400    pub fn call(
401        &self,
402        module: &str,
403        action: &str,
404        args: &[&str],
405    ) -> impl Future<Output = Result<(), CallError>> + Send + 'static {
406        let answer = self.ask(module, action, args);
407        async move { answer.await.map(drop) }
408    }
409
410    /// Like [`ModuleCtx::call`], and returns what the action answered with,
411    /// like the output `mochi ipc` prints.
412    pub fn ask(
413        &self,
414        module: &str,
415        action: &str,
416        args: &[&str],
417    ) -> impl Future<Output = Result<Option<String>, CallError>> + Send + 'static {
418        let (id, answer) = self.request();
419        self.send(FromPlugin::Call {
420            id,
421            module: module.to_owned(),
422            action: action.to_owned(),
423            args: args.iter().map(|arg| (*arg).to_owned()).collect(),
424        });
425        async move {
426            match answer.await {
427                Ok(ToPlugin::CallResult {
428                    error: None,
429                    output,
430                    ..
431                }) => Ok(output),
432                Ok(ToPlugin::CallResult {
433                    error: Some(error), ..
434                }) => Err(error),
435                _ => Err(CallError::Failed("mochid stopped".into())),
436            }
437        }
438    }
439
440    /// The compositor's state as it is now.
441    pub fn compositor(&self) -> CompositorState {
442        self.compositor.borrow().clone()
443    }
444
445    /// Wakes on every new compositor state.
446    pub fn compositor_changes(&self) -> watch::Receiver<CompositorState> {
447        self.compositor.clone()
448    }
449
450    /// Switches to a workspace, by its id from [`CompositorState`].
451    pub fn activate_workspace(
452        &self,
453        workspace: u32,
454    ) -> impl Future<Output = Result<(), String>> + Send + 'static {
455        let (id, answer) = self.request();
456        self.send(FromPlugin::ActivateWorkspace { id, workspace });
457        async move { compositor_answer(answer).await.map(drop) }
458    }
459
460    /// The windows on visible workspaces, where the compositor says.
461    pub fn windows(
462        &self,
463    ) -> impl Future<Output = Result<Vec<WindowInfo>, String>> + Send + 'static {
464        let (id, answer) = self.request();
465        self.send(FromPlugin::Windows { id });
466        async move {
467            let value = compositor_answer(answer).await?;
468            serde_json::from_value(value).map_err(|error| error.to_string())
469        }
470    }
471
472    /// The output the pointer is on, when the compositor says.
473    pub fn pointer_output(
474        &self,
475    ) -> impl Future<Output = Result<Option<String>, String>> + Send + 'static {
476        let (id, answer) = self.request();
477        self.send(FromPlugin::PointerOutput { id });
478        async move {
479            let value = compositor_answer(answer).await?;
480            Ok(value.as_str().map(str::to_owned))
481        }
482    }
483
484    /// The next command or event. `None` once mochid closes the
485    /// connection: the plugin should finish then.
486    pub async fn next_event(&mut self) -> Option<ModuleEvent> {
487        self.events.recv().await
488    }
489
490    fn next_id(&self) -> u64 {
491        self.ids.fetch_add(1, Ordering::Relaxed) + 1
492    }
493
494    fn request(&self) -> (u64, oneshot::Receiver<ToPlugin>) {
495        let id = self.requests.fetch_add(1, Ordering::Relaxed) + 1;
496        let (sender, receiver) = oneshot::channel();
497        self.pending
498            .lock()
499            .unwrap_or_else(|poisoned| poisoned.into_inner())
500            .insert(id, sender);
501        (id, receiver)
502    }
503
504    fn send(&self, message: FromPlugin) {
505        // Fails only once mochid is gone, when nothing matters anymore.
506        let _ = self.outgoing.send(message);
507    }
508}
509
510async fn compositor_answer(answer: oneshot::Receiver<ToPlugin>) -> Result<Value, String> {
511    match answer.await {
512        Ok(ToPlugin::CompositorResult {
513            error: None, value, ..
514        }) => Ok(value),
515        Ok(ToPlugin::CompositorResult {
516            error: Some(error), ..
517        }) => Err(error),
518        _ => Err("mochid stopped".into()),
519    }
520}
521
522/// Reads mochid's messages until it closes the connection.
523async fn read(
524    mut reader: BufReader<tokio::net::unix::OwnedReadHalf>,
525    events: mpsc::UnboundedSender<ModuleEvent>,
526    compositor: watch::Sender<CompositorState>,
527    pending: Pending,
528    outgoing: mpsc::UnboundedSender<FromPlugin>,
529) {
530    let mut line = Vec::new();
531    loop {
532        line.clear();
533        let limit = mochi_protocol::MAX_LINE as u64 + 1;
534        match (&mut reader).take(limit).read_until(b'\n', &mut line).await {
535            Ok(0) | Err(_) => break,
536            Ok(_) if line.len() > mochi_protocol::MAX_LINE => break,
537            Ok(_) => {}
538        }
539        let Ok(message) = std::str::from_utf8(&line)
540            .map_err(|error| error.to_string())
541            .and_then(|text| {
542                mochi_protocol::decode::<ToPlugin>(text).map_err(|error| error.to_string())
543            })
544        else {
545            // A newer mochid may send messages this SDK doesn't know.
546            continue;
547        };
548        let event = match message {
549            ToPlugin::Command { id, action, args } => ModuleEvent::Command(ModuleCommand {
550                action,
551                args,
552                id,
553                outgoing: Some(outgoing.clone()),
554            }),
555            ToPlugin::Clicked { activity } => ModuleEvent::Clicked(ActivityId(activity)),
556            ToPlugin::Hovered { activity, hovered } => ModuleEvent::Hovered {
557                activity: ActivityId(activity),
558                hovered,
559            },
560            ToPlugin::Ended { activity, reason } => ModuleEvent::Ended {
561                activity: ActivityId(activity),
562                reason,
563            },
564            ToPlugin::BubbleClicked { bubble } => ModuleEvent::BubbleClicked(BubbleId(bubble)),
565            ToPlugin::State { module, state } => ModuleEvent::State { module, state },
566            ToPlugin::Offers { offers } => ModuleEvent::Offers(offers),
567            ToPlugin::Compositor { state } => {
568                compositor.send_replace(state);
569                continue;
570            }
571            answer @ (ToPlugin::CallResult { id, .. } | ToPlugin::CompositorResult { id, .. }) => {
572                let waiting = pending
573                    .lock()
574                    .unwrap_or_else(|poisoned| poisoned.into_inner())
575                    .remove(&id);
576                if let Some(waiting) = waiting {
577                    let _ = waiting.send(answer);
578                }
579                continue;
580            }
581            ToPlugin::Hello { .. } => continue,
582        };
583        if events.send(event).is_err() {
584            break;
585        }
586    }
587    // Waiting calls fail now that mochid is gone.
588    pending
589        .lock()
590        .unwrap_or_else(|poisoned| poisoned.into_inner())
591        .clear();
592}
593
594#[cfg(test)]
595mod tests {
596    use std::path::PathBuf;
597
598    use mochi_protocol::spec::ArgValue;
599    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
600
601    use super::*;
602
603    /// Plays mochid: says hello and hands back both ends of the talk.
604    async fn mochid() -> (
605        ModuleCtx,
606        BufReader<tokio::net::unix::OwnedReadHalf>,
607        tokio::net::unix::OwnedWriteHalf,
608    ) {
609        let (ours, theirs) = UnixStream::pair().unwrap();
610        let (reader, mut writer) = ours.into_split();
611        let hello = ToPlugin::Hello {
612            api: API,
613            version: "test".into(),
614            module: "timer".into(),
615            settings: json!({ "minutes": 5 }),
616            data_dir: PathBuf::from("/tmp/data"),
617            session_dir: PathBuf::from("/tmp/session"),
618            compositor: CompositorState::default(),
619        };
620        writer
621            .write_all(&mochi_protocol::encode(&hello).unwrap())
622            .await
623            .unwrap();
624        let ctx = ModuleCtx::over(theirs).await.unwrap();
625        let mut reader = BufReader::new(reader);
626        assert_eq!(receive(&mut reader).await, FromPlugin::Hello { api: API });
627        (ctx, reader, writer)
628    }
629
630    async fn receive(reader: &mut BufReader<tokio::net::unix::OwnedReadHalf>) -> FromPlugin {
631        let mut line = String::new();
632        reader.read_line(&mut line).await.unwrap();
633        mochi_protocol::decode(&line).unwrap()
634    }
635
636    async fn send(writer: &mut tokio::net::unix::OwnedWriteHalf, message: ToPlugin) {
637        writer
638            .write_all(&mochi_protocol::encode(&message).unwrap())
639            .await
640            .unwrap();
641    }
642
643    #[tokio::test]
644    async fn settings_and_requests() {
645        #[derive(serde::Deserialize, Default)]
646        #[serde(default)]
647        struct Settings {
648            minutes: u32,
649            label: String,
650        }
651        let (ctx, mut reader, _writer) = mochid().await;
652        let settings: Settings = ctx.settings().unwrap();
653        assert_eq!(settings.minutes, 5);
654        assert_eq!(settings.label, "");
655        assert_eq!(ctx.module(), "timer");
656
657        let first = ctx.present(ActivitySpec::new("Timer"));
658        let bubble = ctx.show_bubble(BubbleSpec::new("Dot"));
659        assert_eq!(first, ActivityId(1));
660        assert_eq!(bubble, BubbleId(2));
661        assert!(matches!(
662            receive(&mut reader).await,
663            FromPlugin::Present { id: 1, .. }
664        ));
665        assert!(matches!(
666            receive(&mut reader).await,
667            FromPlugin::ShowBubble { id: 2, .. }
668        ));
669    }
670
671    #[tokio::test]
672    async fn commands_are_answered_or_fail_when_dropped() {
673        let (mut ctx, mut reader, mut writer) = mochid().await;
674        let args: Args = [("minutes".to_owned(), ArgValue::Int(3))]
675            .into_iter()
676            .collect();
677        send(
678            &mut writer,
679            ToPlugin::Command {
680                id: 7,
681                action: "start".into(),
682                args,
683            },
684        )
685        .await;
686        send(
687            &mut writer,
688            ToPlugin::Command {
689                id: 8,
690                action: "stop".into(),
691                args: Args::default(),
692            },
693        )
694        .await;
695
696        let Some(ModuleEvent::Command(command)) = ctx.next_event().await else {
697            panic!("no command");
698        };
699        assert_eq!(command.args.int("minutes"), Some(3));
700        command.answer(Ok("started".into()));
701        let Some(ModuleEvent::Command(command)) = ctx.next_event().await else {
702            panic!("no command");
703        };
704        drop(command);
705
706        assert_eq!(
707            receive(&mut reader).await,
708            FromPlugin::Reply {
709                id: 7,
710                output: Some("started".into()),
711                error: None
712            }
713        );
714        assert!(matches!(
715            receive(&mut reader).await,
716            FromPlugin::Reply {
717                id: 8,
718                error: Some(_),
719                ..
720            }
721        ));
722    }
723
724    #[tokio::test]
725    async fn calls_get_their_answers() {
726        let (ctx, mut reader, mut writer) = mochid().await;
727        let call = ctx.call("media", "toggle", &[]);
728        let FromPlugin::Call { id, module, .. } = receive(&mut reader).await else {
729            panic!("no call");
730        };
731        assert_eq!(module, "media");
732        send(
733            &mut writer,
734            ToPlugin::CallResult {
735                id,
736                error: Some(CallError::NotEnabled("media".into())),
737                output: None,
738            },
739        )
740        .await;
741        assert_eq!(call.await, Err(CallError::NotEnabled("media".into())));
742
743        let ask = ctx.ask("launcher", "search", &["2+2"]);
744        let FromPlugin::Call { id, .. } = receive(&mut reader).await else {
745            panic!("no call");
746        };
747        send(
748            &mut writer,
749            ToPlugin::CallResult {
750                id,
751                error: None,
752                output: Some("4".into()),
753            },
754        )
755        .await;
756        assert_eq!(ask.await, Ok(Some("4".into())));
757
758        let pointer = ctx.pointer_output();
759        let FromPlugin::PointerOutput { id } = receive(&mut reader).await else {
760            panic!("no request");
761        };
762        send(
763            &mut writer,
764            ToPlugin::CompositorResult {
765                id,
766                value: json!("DP-3"),
767                error: None,
768            },
769        )
770        .await;
771        assert_eq!(pointer.await, Ok(Some("DP-3".into())));
772    }
773
774    #[tokio::test]
775    async fn the_end_of_the_connection_ends_events() {
776        let (mut ctx, reader, writer) = mochid().await;
777        let call = ctx.call("media", "toggle", &[]);
778        drop((reader, writer));
779        assert!(ctx.next_event().await.is_none());
780        assert!(call.await.is_err());
781    }
782}