1#![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
42pub 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
58pub type Error = Box<dyn std::error::Error + Send + Sync>;
61
62pub 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#[allow(clippy::print_stderr)]
95fn report(message: &str) {
96 eprintln!("{message}");
97}
98
99#[derive(Debug)]
101pub enum ModuleEvent {
102 Command(ModuleCommand),
105 Clicked(ActivityId),
107 Hovered {
109 activity: ActivityId,
111 hovered: bool,
113 },
114 Ended {
116 activity: ActivityId,
118 reason: EndReason,
121 },
122 BubbleClicked(BubbleId),
124 State {
128 module: String,
130 state: Value,
132 },
133 Offers(Vec<Contribution>),
136}
137
138#[derive(Debug)]
141pub struct ModuleCommand {
142 pub action: String,
144 pub args: Args,
148 id: u64,
149 outgoing: Option<mpsc::UnboundedSender<FromPlugin>>,
150}
151
152impl ModuleCommand {
153 pub fn reply(mut self, result: Result<(), String>) {
156 self.send(None, result.err());
157 }
158
159 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#[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 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 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 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 pub fn module(&self) -> &str {
325 &self.module
326 }
327
328 pub fn version(&self) -> &str {
330 &self.version
331 }
332
333 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 pub fn data_dir(&self) -> &Path {
346 &self.data_dir
347 }
348
349 pub fn session_dir(&self) -> &Path {
352 &self.session_dir
353 }
354
355 pub fn publish_state(&self, state: Value) {
358 self.send(FromPlugin::PublishState { state });
359 }
360
361 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 pub fn update(&self, id: ActivityId, payload: Value) {
371 self.send(FromPlugin::Update { id: id.0, payload });
372 }
373
374 pub fn withdraw(&self, id: ActivityId) {
377 self.send(FromPlugin::Withdraw { id: id.0 });
378 }
379
380 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 pub fn update_bubble(&self, id: BubbleId, payload: Value) {
390 self.send(FromPlugin::UpdateBubble { id: id.0, payload });
391 }
392
393 pub fn hide_bubble(&self, id: BubbleId) {
395 self.send(FromPlugin::HideBubble { id: id.0 });
396 }
397
398 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 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 pub fn compositor(&self) -> CompositorState {
442 self.compositor.borrow().clone()
443 }
444
445 pub fn compositor_changes(&self) -> watch::Receiver<CompositorState> {
447 self.compositor.clone()
448 }
449
450 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 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 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 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 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
522async 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 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 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 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}