Skip to main content

jump_core/
launcher.rs

1// Copyright 2026 entro314-labs
2// SPDX-License-Identifier: MPL-2.0
3
4//! Async bridge to the `pop-launcher` IPC service.
5//!
6//! `pop-launcher` is a long-lived child process speaking newline-delimited JSON
7//! on stdin/stdout. Keeping one instance alive for the lifetime of the daemon
8//! matters: measured on a warm cache a query round-trips in 0.5–1.5 ms, but the
9//! first query after spawn pays for plugin discovery and desktop-entry indexing.
10//! Respawning per invocation would put that cost on the keypress that opens the
11//! launcher, which is the one frame the user actually judges.
12//!
13//! ## Staleness
14//!
15//! The protocol carries no request id, so a response cannot be matched to the
16//! query that caused it. The service does cancel an in-flight search when a new
17//! `Search` arrives, so responses are effectively last-write-wins. Rather than
18//! guess at correlation, every emitted [`Event::Update`] is stamped with the
19//! query text that was most recently sent. The frontend compares that against
20//! the current input and, when they differ, keeps rendering the previous results
21//! instead of flashing an empty list — the behaviour Spotlight has.
22
23use std::process::Stdio;
24use std::sync::Arc;
25use std::sync::atomic::{AtomicU64, Ordering};
26
27use pop_launcher::{GpuPreference, Indice, Request, Response};
28use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
29use tokio::process::{Child, Command};
30use tokio::sync::{Mutex, mpsc};
31
32use crate::model::Item;
33
34/// Why the service could not be started.
35#[derive(Debug, thiserror::Error)]
36pub enum Error {
37    /// `pop-launcher` could not be executed — usually not installed.
38    #[error("failed to spawn the pop-launcher service")]
39    Spawn(#[source] std::io::Error),
40    /// The child started but its stdin or stdout was not piped back to us.
41    #[error("pop-launcher stdin/stdout was not captured")]
42    MissingPipe,
43}
44
45/// Something the launcher service told us.
46#[derive(Debug, Clone)]
47pub enum Event {
48    /// A new result set. `query` is the search text that was most recently
49    /// sent, not necessarily the one the user has typed by now.
50    Update {
51        /// Monotonic query generation, to discard responses overtaken by a
52        /// newer keystroke.
53        seq: u64,
54        /// The search text this set answers.
55        query: String,
56        /// The results, in the order the service returned them.
57        items: Vec<Item>,
58    },
59    /// The service wants the input box replaced (tab completion).
60    Fill(String),
61    /// A desktop entry the frontend is responsible for launching.
62    DesktopEntry {
63        /// Path to the `.desktop` file to launch.
64        path: std::path::PathBuf,
65        /// Whether the entry asked for the discrete GPU.
66        gpu_preference: GpuPreference,
67        /// A named desktop action to run instead of the default `Exec`.
68        action_name: Option<String>,
69    },
70    /// Context menu options for a result.
71    Context {
72        /// The result the options belong to.
73        id: Indice,
74        /// The options themselves, to be shown as secondary actions.
75        options: Vec<pop_launcher::ContextOption>,
76    },
77    /// The service considers the interaction finished; dismiss the UI.
78    Close,
79    /// The service died. The frontend should degrade rather than hang.
80    Disconnected,
81}
82
83/// Write half of the connection. Cheap to clone and share across tasks.
84#[derive(Clone, Debug)]
85pub struct Launcher {
86    tx: mpsc::UnboundedSender<Request>,
87    /// Mirrors the most recently sent search text so the reader task can stamp
88    /// updates without inventing a correlation id.
89    last_query: Arc<Mutex<String>>,
90    seq: Arc<AtomicU64>,
91}
92
93impl Launcher {
94    /// Spawn the service and start pumping both directions.
95    ///
96    /// Returns the write handle and the stream of events. The child is killed
97    /// when the returned [`LauncherGuard`] drops.
98    ///
99    /// # Errors
100    ///
101    /// [`Error::Spawn`] if `pop-launcher` is not on `PATH` or cannot be
102    /// executed, and [`Error::MissingPipe`] if its stdio was not captured.
103    pub fn spawn() -> Result<(Self, mpsc::UnboundedReceiver<Event>, LauncherGuard), Error> {
104        let mut child = Command::new("pop-launcher")
105            .stdin(Stdio::piped())
106            .stdout(Stdio::piped())
107            // The service logs to stderr; forwarding it to ours keeps plugin
108            // errors visible under RUST_LOG without corrupting the JSON stream.
109            .stderr(Stdio::inherit())
110            .kill_on_drop(true)
111            .spawn()
112            .map_err(Error::Spawn)?;
113
114        let mut stdin = child.stdin.take().ok_or(Error::MissingPipe)?;
115        let stdout = child.stdout.take().ok_or(Error::MissingPipe)?;
116
117        let (request_tx, mut request_rx) = mpsc::unbounded_channel::<Request>();
118        let (event_tx, event_rx) = mpsc::unbounded_channel::<Event>();
119
120        let last_query = Arc::new(Mutex::new(String::new()));
121        let seq = Arc::new(AtomicU64::new(0));
122
123        // Writer: serialise requests onto the child's stdin.
124        tokio::spawn(async move {
125            while let Some(request) = request_rx.recv().await {
126                let Ok(mut line) = serde_json::to_vec(&request) else {
127                    tracing::error!(?request, "failed to serialise launcher request");
128                    continue;
129                };
130                line.push(b'\n');
131                if let Err(error) = stdin.write_all(&line).await {
132                    tracing::warn!(%error, "pop-launcher stdin closed");
133                    break;
134                }
135                if let Err(error) = stdin.flush().await {
136                    tracing::warn!(%error, "failed to flush pop-launcher stdin");
137                    break;
138                }
139            }
140        });
141
142        // Reader: decode responses and translate them into frontend events.
143        let reader_query = Arc::clone(&last_query);
144        let reader_seq = Arc::clone(&seq);
145        tokio::spawn(async move {
146            let mut lines = BufReader::new(stdout).lines();
147            loop {
148                match lines.next_line().await {
149                    Ok(Some(line)) => {
150                        let response: Response = match serde_json::from_str(&line) {
151                            Ok(response) => response,
152                            Err(error) => {
153                                tracing::warn!(%error, %line, "undecodable launcher response");
154                                continue;
155                            }
156                        };
157
158                        let event = match response {
159                            Response::Update(results) => {
160                                let query = reader_query.lock().await.clone();
161                                Event::Update {
162                                    seq: reader_seq.load(Ordering::Relaxed),
163                                    query,
164                                    items: results
165                                        .into_iter()
166                                        .map(Item::from_search_result)
167                                        .collect(),
168                                }
169                            }
170                            Response::Fill(text) => Event::Fill(text),
171                            Response::DesktopEntry {
172                                path,
173                                gpu_preference,
174                                action_name,
175                            } => Event::DesktopEntry {
176                                path,
177                                gpu_preference,
178                                action_name,
179                            },
180                            Response::Context { id, options } => Event::Context { id, options },
181                            Response::Close => Event::Close,
182                        };
183
184                        if event_tx.send(event).is_err() {
185                            break;
186                        }
187                    }
188                    Ok(None) => {
189                        let _ = event_tx.send(Event::Disconnected);
190                        break;
191                    }
192                    Err(error) => {
193                        tracing::warn!(%error, "pop-launcher stdout read failed");
194                        let _ = event_tx.send(Event::Disconnected);
195                        break;
196                    }
197                }
198            }
199        });
200
201        let launcher = Self {
202            tx: request_tx,
203            last_query,
204            seq,
205        };
206
207        Ok((launcher, event_rx, LauncherGuard { child }))
208    }
209
210    /// Run a search. Returns the generation assigned to it.
211    ///
212    /// Sent unconditionally on every keystroke rather than debounced: at ~1 ms
213    /// round-trip a debounce would only add latency without saving work, and
214    /// the service already cancels the previous search when a new one arrives.
215    pub fn search(&self, query: impl Into<String>) -> u64 {
216        let query = query.into();
217        let seq = self.seq.fetch_add(1, Ordering::Relaxed) + 1;
218
219        let last_query = Arc::clone(&self.last_query);
220        let text = query.clone();
221        tokio::spawn(async move {
222            *last_query.lock().await = text;
223        });
224
225        self.send(Request::Search(query));
226        seq
227    }
228
229    /// Run a result's primary action.
230    pub fn activate(&self, id: Indice) {
231        self.send(Request::Activate(id));
232    }
233
234    /// Ask for tab completion of a result; answered with [`Event::Fill`].
235    pub fn complete(&self, id: Indice) {
236        self.send(Request::Complete(id));
237    }
238
239    /// Ask for a result's context options; answered with [`Event::Context`].
240    pub fn context(&self, id: Indice) {
241        self.send(Request::Context(id));
242    }
243
244    /// Run one of the context options previously returned for `id`.
245    pub fn activate_context(&self, id: Indice, context: Indice) {
246        self.send(Request::ActivateContext { id, context });
247    }
248
249    /// Ask the service to close a window result (used by the switcher).
250    pub fn quit(&self, id: Indice) {
251        self.send(Request::Quit(id));
252    }
253
254    /// Tell the service the frontend was dismissed so it can release resources.
255    /// Deliberately *not* `Exit` — we keep the process warm for the next open.
256    pub fn dismissed(&self) {
257        self.send(Request::Close);
258    }
259
260    /// Cancel the in-flight search without dismissing the session.
261    pub fn interrupt(&self) {
262        self.send(Request::Interrupt);
263    }
264
265    fn send(&self, request: Request) {
266        if self.tx.send(request).is_err() {
267            tracing::warn!("pop-launcher request channel closed");
268        }
269    }
270}
271
272/// Owns the child process. Dropping it terminates the service.
273pub struct LauncherGuard {
274    child: Child,
275}
276
277impl LauncherGuard {
278    /// Ask the service to exit and reap it.
279    pub async fn shutdown(mut self) {
280        let _ = self.child.kill().await;
281    }
282}