Skip to main content

crabshell_services/
lib.rs

1//! The services a Crabshell bar reads: the clock, Sway's and Hyprland's
2//! workspaces, audio, the tray, power, notifications, the installed
3//! applications, PAM, greetd and a polkit agent.
4//!
5//! The shell calls [`provide`] once, with its root context and event loop.
6//! After that, any context hands out services through [`ServicesExt`],
7//! such as `cx.clock(Precision::Minute)`. Each service starts the first
8//! time a config asks for it and is shared by every caller, so two outputs
9//! never mean two connections. Its signals belong to the root context's
10//! owner: bars on every output share them, and they go when the shell does.
11//!
12//! Asked for on a context the shell didn't set up, as in a ui test, a
13//! service logs once and hands out a value that never changes.
14
15#![forbid(unsafe_code)]
16#![warn(missing_docs)]
17
18mod activation;
19mod audio;
20mod bluetooth;
21mod clock;
22mod dbus;
23mod desktop_entries;
24mod file;
25mod greetd;
26mod hyprland;
27mod lines;
28mod mpris;
29mod network;
30mod notifications;
31mod pam;
32mod polkit;
33mod power;
34mod process;
35mod socket;
36mod socket_server;
37mod spawn;
38mod sway;
39#[cfg(test)]
40mod testing;
41mod tray;
42mod watch;
43
44use std::cell::{Cell, OnceCell, RefCell};
45use std::future::{Future, poll_fn};
46use std::os::fd::OwnedFd;
47use std::path::PathBuf;
48use std::pin::pin;
49use std::rc::Rc;
50use std::sync::Arc;
51use std::task::{Poll, Waker};
52use std::time::{Duration, Instant};
53
54use calloop::channel::Channel;
55use calloop::futures::{Executor, Scheduler};
56use calloop::generic::Generic;
57use calloop::timer::{TimeoutAction, Timer};
58use calloop::{Interest, LoopHandle, Mode, PostAction, RegistrationToken};
59use crabshell_reactive::{Owner, ReadSignal, Signal};
60use crabshell_ui::Cx;
61
62pub use audio::{Audio, AudioChannel, AudioNode, AudioStream, PeakTarget, Sink};
63pub use bluetooth::{
64  Bluetooth, BluetoothAdapter, BluetoothAdapterState, BluetoothAgent, BluetoothDevice,
65  BluetoothDeviceState, PairingKind, PairingRequest,
66};
67pub use clock::Precision;
68pub use desktop_entries::{DesktopAction, DesktopEntries, DesktopEntry};
69pub use file::{FileError, FileErrorKind, FileView};
70pub use greetd::{GreetMessage, GreetState, Greetd};
71pub use hyprland::{Hyprland, HyprlandEvent, HyprlandMonitor, HyprlandToplevel, HyprlandWorkspace};
72pub use mpris::{LoopStatus, Mpris, PlaybackStatus, Player};
73pub use network::{
74  ConnectionFailReason, Connectivity, Network, NetworkDevice, NetworkKind, NetworkState,
75  SavedConnection, WifiMode, WifiNetwork, WifiSecurity,
76};
77pub use notifications::{CloseReason, Notification, Notifications, Timeout, Urgency};
78pub use pam::{Pam, PamError, PamMessage, PamResult, PamState};
79pub use polkit::{AuthRequest, AuthState, PolkitAgent};
80pub use power::{
81  BatteryState, DeviceKind, PerformanceDegradation, PowerDevice, PowerProfile, PowerProfiles,
82  UPower,
83};
84pub use process::{IntoCommand, Process};
85pub use socket::Socket;
86pub use socket_server::SocketServer;
87#[doc(hidden)]
88pub use spawn::{FIRST_START, shell_tunables};
89pub use sway::{Sway, SwayEvent, SwayEventKind, SwayOutput, Workspace};
90pub use tray::{
91  MenuEntry, MenuToggle, Tray, TrayCategory, TrayHost, TrayItem, TrayMenu, TrayStatus,
92};
93
94/// Makes the services reachable from `cx` and every context made from it.
95/// The shell calls this once, with its root context and its event loop.
96///
97/// Nothing starts here: each service starts when a config first asks for
98/// it. The loop is kept weakly, so it and the compositor connection still
99/// go when the shell drops.
100pub fn provide<D: 'static>(cx: &Cx, handle: &LoopHandle<'static, D>) {
101  provide_with(cx, handle, Config::system());
102}
103
104/// [`provide`] with the system's parts swapped for a test's.
105fn provide_with<D: 'static>(cx: &Cx, handle: &LoopHandle<'static, D>, config: Config) {
106  let shared = Rc::new(Shared::new(cx.owner(), handle, config));
107  cx.provide(clock::Clocks::new(Rc::clone(&shared)));
108  cx.provide(sway::Service::new(Rc::clone(&shared)));
109  cx.provide(hyprland::Service::new(Rc::clone(&shared)));
110  cx.provide(audio::AudioService::new(Rc::clone(&shared)));
111  cx.provide(tray::Service::new(Rc::clone(&shared)));
112  cx.provide(power::UPowerService::new(Rc::clone(&shared)));
113  cx.provide(power::ProfilesService::new(Rc::clone(&shared)));
114  let agent = cx.provide(bluetooth::agent::Service::new(Rc::clone(&shared)));
115  cx.provide(bluetooth::BluetoothService::new(Rc::clone(&shared), agent));
116  cx.provide(notifications::Service::new(Rc::clone(&shared)));
117  cx.provide(mpris::Service::new(Rc::clone(&shared)));
118  cx.provide(network::NetworkService::new(Rc::clone(&shared)));
119  cx.provide(socket::Sockets(Rc::clone(&shared)));
120  cx.provide(process::Processes::new(Rc::clone(&shared)));
121  cx.provide(desktop_entries::Service::new(Rc::clone(&shared)));
122  cx.provide(file::Files(Rc::clone(&shared)));
123  cx.provide(greetd::Service::new(Rc::clone(&shared)));
124  cx.provide(pam::Service(Rc::clone(&shared)));
125  cx.provide(polkit::Service::new(Rc::clone(&shared)));
126}
127
128/// Lets the services ask the compositor for activation tokens for the
129/// programs they start, so it may focus them: `request` asks for one for
130/// a program with the app id given, if any, and hands it to the callback.
131/// The shell calls this once, when the compositor offers tokens; without
132/// it programs start at once with none.
133#[doc(hidden)]
134pub fn provide_activation_tokens(
135  cx: &Cx,
136  request: impl Fn(Option<&str>, Box<dyn FnOnce(String)>) + 'static,
137) {
138  if let Some(processes) = cx.service::<process::Processes>() {
139    let _ = processes.shared.activation.set(Box::new(request));
140  }
141}
142
143/// Stops every program a config started with `cx.process`, and starts
144/// every one still waiting for its activation token, without it. The
145/// shell calls this before it exits, since `std::process::exit` skips the
146/// drops that would stop them, each program has a process group of its
147/// own, and no token or timer comes after the exit.
148#[doc(hidden)]
149pub fn stop_programs(cx: &Cx) {
150  if let Some(processes) = cx.service::<process::Processes>() {
151    activation::start_waiting(&processes.shared);
152  }
153  process::stop_all(cx);
154}
155
156/// What the services keep across a reload, for the shell to save: the
157/// notifications kept. `None` when no service has anything to keep.
158#[doc(hidden)]
159pub fn save_state(cx: &Cx) -> Option<serde_json::Value> {
160  let notifications = cx.service::<notifications::Service>()?.save()?;
161  Some(serde_json::json!({ "notifications": notifications }))
162}
163
164/// Hands the services what [`save_state`] gave the shell before a reload.
165/// The shell calls it before the root closure runs.
166#[doc(hidden)]
167pub fn restore_state(cx: &Cx, state: serde_json::Value) {
168  let Some(service) = cx.service::<notifications::Service>() else {
169    return;
170  };
171  if let serde_json::Value::Object(mut state) = state
172    && let Some(notifications) = state.remove("notifications")
173  {
174    service.restore(notifications);
175  }
176}
177
178/// The name of user `uid` through NSS, so a user from LDAP or
179/// systemd-homed counts as one in `/etc/passwd` does. `None` for no such
180/// user; a lookup that fails is logged.
181pub(crate) fn user_name(uid: u32) -> Option<String> {
182  match nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid)) {
183    Ok(user) => user.map(|user| user.name).filter(|name| !name.is_empty()),
184    Err(error) => {
185      tracing::warn!(%error, uid, "couldn't look the user up");
186      None
187    }
188  }
189}
190
191/// The services a context hands out.
192pub trait ServicesExt {
193  /// The time, truncated to `precision`: it changes on each whole second
194  /// or minute and holds the one just passed, in the system time zone.
195  /// Every caller asking for the same precision gets the same signal.
196  ///
197  /// A minute clock wakes the shell once a minute and at no other time.
198  /// After a suspend, and when timedated changes the time zone, it is
199  /// right again at once. A zone changed any other way shows from the
200  /// next tick.
201  fn clock(&self, precision: Precision) -> ReadSignal<jiff::Zoned>;
202
203  /// Sway's workspaces, outputs, commands and events, over the IPC socket
204  /// at `$SWAYSOCK`, as Quickshell's `I3`. Every caller shares one
205  /// connection, made on the first call.
206  ///
207  /// The lists are empty while Sway isn't there. When `SWAYSOCK` is unset
208  /// or the first connect fails, they stay empty and the service never
209  /// wakes the shell. When a working connection closes, they are empty
210  /// until a reconnect, tried every 2 s, works. While connected, it wakes
211  /// the shell only for a workspace event, an output event once a config
212  /// asked for the outputs, and the kinds of event a handler asked for.
213  fn sway(&self) -> Sway;
214
215  /// Hyprland's workspaces, monitors and windows, over its IPC sockets
216  /// in `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/`. Every
217  /// caller shares one event connection, made on the first call.
218  ///
219  /// The lists are empty while Hyprland isn't there: when the signature
220  /// is unset or its sockets are missing, they stay empty, which is
221  /// logged once, and the service never wakes the shell. When Hyprland
222  /// closes its event socket, the lists empty and nothing reconnects.
223  /// While connected, it wakes the shell only when Hyprland sends
224  /// something.
225  fn hyprland(&self) -> Hyprland;
226
227  /// The audio server's default sink, with its volume and mute. Every
228  /// caller shares one connection, which starts on the loop's next turn
229  /// and never waits for the server. It wakes the shell only when the
230  /// server reports a change, and while a peak meter from
231  /// [`Audio::peaks`] records.
232  ///
233  /// With no server, the sink is `None` and the service tries again
234  /// every 2 s, for up to a minute after startup and after each drop of
235  /// a working connection. Then it stops, logs that once and never wakes
236  /// the shell again; a restart tries again.
237  fn audio(&self) -> Audio;
238
239  /// The system tray: every app's StatusNotifierItem on the session bus.
240  /// Every caller shares one connection, which starts on the loop's next
241  /// turn and never waits for the bus.
242  ///
243  /// The shell runs the StatusNotifierWatcher while no other program
244  /// does, and otherwise reads the list from the one that runs, taking
245  /// over when it leaves. With no session bus the list stays empty and
246  /// the service never wakes the shell. It wakes the shell only when
247  /// something arrives on the bus for it.
248  fn tray(&self) -> TrayHost;
249
250  /// UPower's batteries and power supplies, on the system bus. Every
251  /// caller shares one connection, which starts on the loop's next turn.
252  ///
253  /// While UPower isn't running the lists are empty, and they fill when
254  /// it starts. With no system bus they stay empty and the service never
255  /// wakes the shell. It wakes the shell only when UPower says something
256  /// changed.
257  fn upower(&self) -> UPower;
258
259  /// The power profile, from power-profiles-daemon on the system bus.
260  /// Every caller shares one connection. It behaves as
261  /// [`upower`](Self::upower) does while the daemon isn't there.
262  fn power_profiles(&self) -> PowerProfiles;
263
264  /// Bluetooth adapters and devices, from BlueZ on the system bus. Every
265  /// caller shares one connection. It behaves as [`upower`](Self::upower)
266  /// does while BlueZ isn't there, and wakes the shell only when BlueZ
267  /// says something changed.
268  fn bluetooth(&self) -> Bluetooth;
269
270  /// The shell's Bluetooth pairing agent: when BlueZ needs a PIN, a
271  /// passkey or a yes to pair a device, it asks the shell, and a config
272  /// shows the prompt. The first call registers the agent with BlueZ on
273  /// the system bus, as `KeyboardDisplay`, again whenever BlueZ starts
274  /// again; a shell that never calls it never answers BlueZ. Every caller
275  /// shares the one agent, which wakes the shell only when BlueZ calls.
276  fn bluetooth_agent(&self) -> BluetoothAgent;
277
278  /// The notification server on the session bus: what apps sent, and
279  /// the popups still showing. Every caller shares one connection, which
280  /// starts on the loop's next turn and never waits for the bus.
281  ///
282  /// The shell serves while no other program does. While another daemon
283  /// has the name, the shell waits for it to leave, and keeps what it was
284  /// sent if one takes the name over. With no session bus the lists stay
285  /// empty and the service never wakes the shell. It wakes the shell only
286  /// when an app calls and when a popup expires.
287  fn notifications(&self) -> Notifications;
288
289  /// The media players on the session bus, over MPRIS, such as a music
290  /// player or a browser playing a video. Every caller shares one
291  /// connection, which starts on the loop's next turn and never waits
292  /// for the bus.
293  ///
294  /// With no session bus the list stays empty and the service never
295  /// wakes the shell. It wakes the shell only when a player says
296  /// something changed. MPRIS doesn't say when the position moves, so a
297  /// bar works it out with [`Player::position_at`].
298  fn mpris(&self) -> Mpris;
299
300  /// Network devices and Wi-Fi networks, from NetworkManager on the
301  /// system bus. Every caller shares one connection. It behaves as
302  /// [`upower`](Self::upower) does while NetworkManager isn't there, and
303  /// wakes the shell only when NetworkManager says something changed.
304  fn network(&self) -> Network;
305
306  /// A connection to the Unix socket at `path`, made at once, as
307  /// Quickshell's `Socket`. Each call opens its own, which closes when
308  /// this context goes. It wakes the shell only when the other end sends
309  /// something or takes what was written.
310  fn socket(&self, path: impl Into<PathBuf>) -> Socket;
311
312  /// A server on the Unix socket at `path`, as Quickshell's
313  /// `SocketServer`: it listens at once, and each client that connects
314  /// becomes a [`Socket`] for [`SocketServer::on_connection`]. Each call
315  /// makes its own, which stops when this context goes, closing its
316  /// connections and removing its socket file. It wakes the shell only
317  /// when a client connects, sends something or takes what was written.
318  fn socket_server(&self, path: impl Into<PathBuf>) -> SocketServer;
319
320  /// Runs the program `command` builds, as Quickshell's `Process`, and
321  /// keeps what it prints and how it ended. `command` returns a
322  /// [`Command`](std::process::Command) or a list such as
323  /// `["uptime", "-p"]`. It starts on the loop's next turn, and again
324  /// whenever a signal `command` read changes or [`Process::restart`] is
325  /// called, stopping the run before. It is stopped when this context
326  /// goes. It wakes the shell only when the program prints, takes input
327  /// or ends.
328  fn process<C: IntoCommand>(&self, command: impl Fn() -> C + 'static) -> Process;
329
330  /// Starts `command` and lets it run on its own, as a launcher does:
331  /// its input and outputs are empty, it has a process group of its own,
332  /// and it is reaped when it ends. A failure to start is logged. When
333  /// the compositor hands out activation tokens, it starts once one comes,
334  /// or after 100 ms without one, with the token in
335  /// `XDG_ACTIVATION_TOKEN` and `DESKTOP_STARTUP_ID`, so the compositor
336  /// may focus its window.
337  fn exec_detached(&self, command: impl IntoCommand);
338
339  /// The text file at `path`, as Quickshell's `FileView`: read now, and
340  /// again when it changes on disk. Each call reads its own, which goes
341  /// with this context. It is read on the main thread, so a file on a
342  /// slow disk delays the frame.
343  fn file_view(&self, path: impl Into<PathBuf>) -> FileView;
344
345  /// greetd, for a greeter: makes a session for a user, answers its
346  /// questions and starts it, over the socket `GREETD_SOCK` names. One
347  /// connection per shell, made at the first request; it wakes the shell
348  /// only when greetd answers.
349  fn greetd(&self) -> Greetd;
350
351  /// A value kept in the JSON file at `path`, as Quickshell's
352  /// `JsonAdapter`: `default` until the file is read, the file's value
353  /// once it is, and the file rewritten whenever the config sets another.
354  /// A missing file, and its directory, is made at the first set. A file
355  /// that isn't `T`'s
356  /// JSON is logged and left alone, and the value stays.
357  fn json_file<T>(&self, path: impl Into<PathBuf>, default: T) -> Signal<T>
358  where
359    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + 'static;
360
361  /// The installed applications, from the desktop entries in the XDG
362  /// data directories: what a launcher lists and starts, and where a
363  /// window's app id finds its icon. Every caller shares one list, read
364  /// on the loop's next turn after the first call.
365  ///
366  /// The directories are watched, and the list is read again once the
367  /// files have been still for 100 ms after a change. It wakes the shell
368  /// at no other time.
369  fn desktop_entries(&self) -> DesktopEntries;
370
371  /// Authentication through the PAM service `service`, the name of a
372  /// file in `/etc/pam.d`, as a lock screen asks for the user's
373  /// password. Each call has its own, which goes with this context.
374  ///
375  /// Nothing runs until [`Pam::start`]. Each attempt runs on a thread of
376  /// its own, since libpam blocks, and wakes the shell only when PAM asks
377  /// or says something, or the attempt ends. After a success PAM's
378  /// account step runs too, which clears `pam_faillock`'s count of past
379  /// failures; its refusal is only logged. An attempt ended while PAM
380  /// waits for an answer counts as a failure, as [`Pam::start`] says.
381  fn pam(&self, service: &str) -> Pam;
382
383  /// The shell's polkit authentication agent, as Quickshell's
384  /// `PolkitAgent`: when a program asks polkit for something only some
385  /// users may do, its request shows here for the config's dialog. The
386  /// first call registers the agent with polkit on the system bus for
387  /// this session; a shell that never calls it never reaches polkit.
388  ///
389  /// A refused registration is logged and no requests arrive. It wakes
390  /// the shell only when polkit calls and while a request is answered.
391  fn polkit_agent(&self) -> PolkitAgent;
392}
393
394impl ServicesExt for Cx {
395  fn clock(&self, precision: Precision) -> ReadSignal<jiff::Zoned> {
396    clock::clock(self, precision)
397  }
398
399  fn sway(&self) -> Sway {
400    sway::sway(self)
401  }
402
403  fn hyprland(&self) -> Hyprland {
404    hyprland::hyprland(self)
405  }
406
407  fn audio(&self) -> Audio {
408    audio::audio(self)
409  }
410
411  fn tray(&self) -> TrayHost {
412    tray::tray(self)
413  }
414
415  fn upower(&self) -> UPower {
416    power::upower(self)
417  }
418
419  fn power_profiles(&self) -> PowerProfiles {
420    power::power_profiles(self)
421  }
422
423  fn bluetooth(&self) -> Bluetooth {
424    bluetooth::bluetooth(self)
425  }
426
427  fn bluetooth_agent(&self) -> BluetoothAgent {
428    bluetooth::agent::bluetooth_agent(self)
429  }
430
431  fn notifications(&self) -> Notifications {
432    notifications::notifications(self)
433  }
434
435  fn mpris(&self) -> Mpris {
436    mpris::mpris(self)
437  }
438
439  fn network(&self) -> Network {
440    network::network(self)
441  }
442
443  fn socket(&self, path: impl Into<PathBuf>) -> Socket {
444    socket::socket(self, path.into())
445  }
446
447  fn socket_server(&self, path: impl Into<PathBuf>) -> SocketServer {
448    socket_server::socket_server(self, path.into())
449  }
450
451  #[track_caller]
452  fn process<C: IntoCommand>(&self, command: impl Fn() -> C + 'static) -> Process {
453    process::process(self, command)
454  }
455
456  fn exec_detached(&self, command: impl IntoCommand) {
457    process::exec_detached(self, command);
458  }
459
460  fn file_view(&self, path: impl Into<PathBuf>) -> FileView {
461    file::file_view(self, path.into())
462  }
463
464  fn greetd(&self) -> Greetd {
465    greetd::greetd(self)
466  }
467
468  fn json_file<T>(&self, path: impl Into<PathBuf>, default: T) -> Signal<T>
469  where
470    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + 'static,
471  {
472    file::json_file(self, path.into(), default)
473  }
474
475  fn desktop_entries(&self) -> DesktopEntries {
476    desktop_entries::desktop_entries(self)
477  }
478
479  fn pam(&self, service: &str) -> Pam {
480    pam::pam(self, service)
481  }
482
483  fn polkit_agent(&self) -> PolkitAgent {
484    polkit::polkit_agent(self)
485  }
486}
487
488/// What every service of one shell starts from.
489struct Shared {
490  /// The root context's owner. Services create their signals under it,
491  /// so bars on every output share them and they go with the shell.
492  root: Owner,
493  /// The event loop, held weakly. Services' timers and futures live in
494  /// the loop and hold the services, so a strong handle here would be an
495  /// `Rc` cycle that keeps the loop and the compositor connection alive
496  /// after the shell drops. calloop's weak handle has no type we can
497  /// name, so a closure keeps it.
498  event_loop: Box<dyn Fn() -> Option<Box<dyn EventLoop>>>,
499  /// The one futures executor every service's D-Bus calls run on, added
500  /// to the loop on first use. `None` if that failed.
501  executor: OnceCell<Option<Scheduler<()>>>,
502  /// The one inotify instance, made for the first directory watched.
503  watcher: watch::Watcher,
504  /// How to ask for an activation token, once the shell gives it.
505  activation: OnceCell<activation::Request>,
506  /// The programs waiting for their activation token.
507  waiting: activation::Waiting,
508  config: Config,
509}
510
511impl Shared {
512  fn new<D: 'static>(root: Owner, handle: &LoopHandle<'static, D>, config: Config) -> Shared {
513    let weak = handle.downgrade();
514    Shared {
515      root,
516      event_loop: Box::new(move || {
517        weak
518          .upgrade()
519          .map(|handle| Box::new(handle) as Box<dyn EventLoop>)
520      }),
521      executor: OnceCell::new(),
522      watcher: watch::Watcher::default(),
523      activation: OnceCell::new(),
524      waiting: activation::Waiting::default(),
525      config,
526    }
527  }
528
529  /// The event loop, while it is still there.
530  fn event_loop(&self) -> Option<Box<dyn EventLoop>> {
531    (self.event_loop)()
532  }
533
534  /// Runs `future` on the main thread, between the loop's other sources,
535  /// so no D-Bus call delays a frame.
536  fn spawn(&self, future: impl Future<Output = ()> + 'static) {
537    let scheduler = self.executor.get_or_init(|| {
538      let (executor, scheduler) = calloop::futures::executor()
539        .inspect_err(|error| tracing::error!(%error, "no executor for the services"))
540        .ok()?;
541      self
542        .event_loop()?
543        .insert_executor(executor)
544        .then_some(scheduler)
545    });
546    if let Some(scheduler) = scheduler
547      && let Err(error) = scheduler.schedule(future)
548    {
549      tracing::error!(%error, "a service's future couldn't start");
550    }
551  }
552}
553
554impl Shared {
555  /// Awaits `call`, or gives up after `limit` with a timed-out error. The
556  /// timer is the loop's and goes as soon as the call ends. zbus's own
557  /// timeout left its timer behind, which woke zbus's thread once, `limit`
558  /// after every call, while nothing changed.
559  async fn timeout<T>(
560    &self,
561    limit: Duration,
562    call: impl Future<Output = zbus::Result<T>>,
563  ) -> zbus::Result<T> {
564    let fired = Rc::new(Cell::new(false));
565    let waker: Rc<RefCell<Option<Waker>>> = Rc::default();
566    let tick = {
567      let (fired, waker) = (Rc::clone(&fired), Rc::clone(&waker));
568      Box::new(move || {
569        fired.set(true);
570        if let Some(waker) = waker.take() {
571          waker.wake();
572        }
573        TimeoutAction::Drop
574      })
575    };
576    let token = self
577      .event_loop()
578      .and_then(|event_loop| event_loop.insert_timer(Instant::now() + limit, tick));
579    let _timer = RemoveOnDrop(self, token);
580    let mut call = pin!(call);
581    poll_fn(|context| {
582      if let Poll::Ready(result) = call.as_mut().poll(context) {
583        return Poll::Ready(result);
584      }
585      if fired.get() {
586        let error = std::io::Error::new(std::io::ErrorKind::TimedOut, "no answer in time");
587        return Poll::Ready(Err(zbus::Error::InputOutput(error.into())));
588      }
589      waker.replace(Some(context.waker().clone()));
590      Poll::Pending
591    })
592    .await
593  }
594}
595
596/// Removes a loop source when dropped, as a call that ends removes its
597/// timer.
598struct RemoveOnDrop<'a>(&'a Shared, Option<RegistrationToken>);
599
600impl Drop for RemoveOnDrop<'_> {
601  fn drop(&mut self) {
602    if let (Some(token), Some(event_loop)) = (self.1, self.0.event_loop()) {
603      event_loop.remove(token);
604    }
605  }
606}
607
608/// The parts of the event loop services use. It hides the loop's data
609/// type, since one services map serves any shell.
610trait EventLoop {
611  /// Calls `tick` at `deadline`, then again at whatever it returns.
612  /// `None`, logged, if the loop refused it.
613  fn insert_timer(
614    &self,
615    deadline: Instant,
616    tick: Box<dyn FnMut() -> TimeoutAction>,
617  ) -> Option<RegistrationToken>;
618
619  /// Calls `ready` whenever `fd` is ready for `interest`. The loop owns
620  /// `fd` and closes it when the source is removed. `None`, logged, if
621  /// the loop refused it.
622  fn insert_fd(
623    &self,
624    fd: OwnedFd,
625    interest: Interest,
626    ready: Box<dyn FnMut()>,
627  ) -> Option<RegistrationToken>;
628
629  /// Removes a source. One that is already gone is ignored.
630  fn remove(&self, token: RegistrationToken);
631
632  /// Adds the services' executor. `false`, logged, if the loop refused it.
633  fn insert_executor(&self, executor: Executor<()>) -> bool;
634
635  /// Calls `on_message` with each message libpulse's thread sends on
636  /// `channel`. `false`, logged, if the loop refused it.
637  fn insert_audio_channel(
638    &self,
639    channel: Channel<audio::Message>,
640    on_message: Box<dyn FnMut(audio::Message)>,
641  ) -> bool;
642
643  /// Calls `on_event` with each event a PAM attempt's thread sends on
644  /// `channel`, and with `Closed` once the thread is gone. `None`, logged,
645  /// if the loop refused it.
646  fn insert_pam_channel(
647    &self,
648    channel: Channel<pam::Event>,
649    on_event: Box<dyn FnMut(calloop::channel::Event<pam::Event>)>,
650  ) -> Option<RegistrationToken>;
651
652  /// Adds the channel a user lookup's thread sends names on.
653  fn insert_users_channel(
654    &self,
655    channel: Channel<polkit::Found>,
656    on_event: Box<dyn FnMut(calloop::channel::Event<polkit::Found>)>,
657  ) -> Option<RegistrationToken>;
658}
659
660impl<D: 'static> EventLoop for LoopHandle<'static, D> {
661  fn insert_timer(
662    &self,
663    deadline: Instant,
664    mut tick: Box<dyn FnMut() -> TimeoutAction>,
665  ) -> Option<RegistrationToken> {
666    self
667      .insert_source(Timer::from_deadline(deadline), move |_, _, _| tick())
668      .inspect_err(|error| tracing::error!(%error, "a service's timer couldn't be added"))
669      .ok()
670  }
671
672  fn insert_fd(
673    &self,
674    fd: OwnedFd,
675    interest: Interest,
676    mut ready: Box<dyn FnMut()>,
677  ) -> Option<RegistrationToken> {
678    let source = Generic::new(fd, interest, Mode::Level);
679    self
680      .insert_source(source, move |_, _, _| {
681        ready();
682        Ok(PostAction::Continue)
683      })
684      .inspect_err(|error| tracing::error!(%error, "a service's socket couldn't be added"))
685      .ok()
686  }
687
688  fn remove(&self, token: RegistrationToken) {
689    LoopHandle::remove(self, token);
690  }
691
692  fn insert_executor(&self, executor: Executor<()>) -> bool {
693    self
694      .insert_source(executor, |(), _, _| {})
695      .inspect_err(|error| tracing::error!(%error, "the services' executor couldn't be added"))
696      .is_ok()
697  }
698
699  fn insert_audio_channel(
700    &self,
701    channel: Channel<audio::Message>,
702    mut on_message: Box<dyn FnMut(audio::Message)>,
703  ) -> bool {
704    self
705      .insert_source(channel, move |event, _, _| {
706        if let calloop::channel::Event::Msg(message) = event {
707          on_message(message);
708        }
709      })
710      .inspect_err(|error| tracing::error!(%error, "the audio channel couldn't be added"))
711      .is_ok()
712  }
713
714  fn insert_pam_channel(
715    &self,
716    channel: Channel<pam::Event>,
717    mut on_event: Box<dyn FnMut(calloop::channel::Event<pam::Event>)>,
718  ) -> Option<RegistrationToken> {
719    self
720      .insert_source(channel, move |event, _, _| on_event(event))
721      .inspect_err(|error| tracing::error!(%error, "a PAM attempt's channel couldn't be added"))
722      .ok()
723  }
724
725  fn insert_users_channel(
726    &self,
727    channel: Channel<polkit::Found>,
728    mut on_event: Box<dyn FnMut(calloop::channel::Event<polkit::Found>)>,
729  ) -> Option<RegistrationToken> {
730    self
731      .insert_source(channel, move |event, _, _| on_event(event))
732      .inspect_err(|error| tracing::error!(%error, "a user lookup's channel couldn't be added"))
733      .ok()
734  }
735}
736
737/// Where the services find the system. Tests point it at their own files
738/// and a private bus.
739struct Config {
740  /// The link that names the system time zone, `/etc/localtime`. `None`
741  /// when `TZ` is set, since it names the zone then, as it does for libc.
742  localtime: Option<PathBuf>,
743  /// The system bus, where logind, timedated, UPower,
744  /// power-profiles-daemon, BlueZ, NetworkManager and polkit are. `None`
745  /// for none.
746  system_bus: Option<zbus::Address>,
747  /// The session bus, where tray items, notifying apps and media
748  /// players are. `None` for none.
749  session_bus: Option<zbus::Address>,
750  /// Sway's IPC socket, from `SWAYSOCK`. `None` when that is unset.
751  sway: Option<sway::Socket>,
752  /// The directory of Hyprland's sockets,
753  /// `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE`. `None` when
754  /// either is unset.
755  hyprland: Option<PathBuf>,
756  /// The audio server. `None` for none, so a test never reaches the
757  /// user's.
758  audio: Option<audio::Server>,
759  /// How long a popup shows when its app leaves that to the server: 5 s,
760  /// and less in tests.
761  popup_timeout: Duration,
762  /// greetd's socket, from `GREETD_SOCK`. `None` when that is unset.
763  greetd: Option<PathBuf>,
764  /// Where the desktop entries are. Tests give directories of their own.
765  desktop_entries: desktop_entries::Sources,
766  /// What `cx.pam` authenticates with: libpam, and a script in tests, so
767  /// no test counts toward locking a real account.
768  pam: Arc<dyn pam::Backend>,
769  /// Where polkit's setuid helper, which checks answers with PAM, may be;
770  /// the first that exists runs. Tests give a script of their own.
771  polkit_helpers: Vec<PathBuf>,
772  /// polkit's socket for its helper, tried before `polkit_helpers`.
773  polkit_socket: PathBuf,
774  /// How polkit's identities are named: through NSS, and in tests a
775  /// lookup as slow as they like. It runs off the loop's thread.
776  polkit_users: Arc<dyn Fn(u32) -> Option<String> + Send + Sync>,
777  /// How long a request waits for its identities' names before it goes on
778  /// with those found.
779  polkit_users_limit: Duration,
780}
781
782impl Config {
783  fn system() -> Config {
784    Config {
785      localtime: std::env::var_os("TZ")
786        .is_none()
787        .then(|| PathBuf::from("/etc/localtime")),
788      system_bus: zbus::Address::system()
789        .inspect_err(|error| tracing::warn!(%error, "no system bus address"))
790        .ok(),
791      session_bus: zbus::Address::session()
792        .inspect_err(|error| tracing::warn!(%error, "no session bus address"))
793        .ok(),
794      sway: std::env::var_os("SWAYSOCK")
795        .filter(|path| !path.is_empty())
796        .map(|path| sway::Socket {
797          path: path.into(),
798          retry: sway::RETRY,
799        }),
800      hyprland: std::env::var_os("XDG_RUNTIME_DIR")
801        .filter(|dir| !dir.is_empty())
802        .zip(std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").filter(|sig| !sig.is_empty()))
803        .map(|(dir, signature)| PathBuf::from(dir).join("hypr").join(signature)),
804      audio: Some(audio::Server {
805        address: None,
806        retry: audio::RETRY,
807        retry_for: audio::RETRY_FOR,
808      }),
809      popup_timeout: notifications::POPUP_TIMEOUT,
810      greetd: std::env::var_os("GREETD_SOCK")
811        .filter(|path| !path.is_empty())
812        .map(PathBuf::from),
813      desktop_entries: desktop_entries::Sources::system(),
814      pam: Arc::new(pam::LibPam),
815      polkit_helpers: polkit::HELPERS.map(PathBuf::from).to_vec(),
816      polkit_socket: PathBuf::from(polkit::HELPER_SOCKET),
817      polkit_users: Arc::new(user_name),
818      polkit_users_limit: polkit::USERS_LIMIT,
819    }
820  }
821}