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, a polkit agent and HTTP GET.
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 a11y;
19mod activation;
20mod audio;
21mod bluetooth;
22mod brightness;
23mod clock;
24mod dbus;
25mod desktop_entries;
26mod file;
27mod folder;
28mod greetd;
29mod http;
30mod hyprland;
31mod lines;
32mod locale;
33mod logind;
34mod mpris;
35mod network;
36mod niri;
37mod notifications;
38mod pam;
39mod pipewire;
40mod polkit;
41mod power;
42mod process;
43mod socket;
44mod socket_server;
45mod spawn;
46mod stats;
47mod sway;
48#[cfg(test)]
49mod testing;
50mod tray;
51mod watch;
52
53use std::cell::{Cell, OnceCell, RefCell};
54use std::future::{Future, poll_fn};
55use std::os::fd::OwnedFd;
56use std::path::PathBuf;
57use std::pin::pin;
58use std::rc::Rc;
59use std::sync::Arc;
60use std::task::{Poll, Waker};
61use std::time::{Duration, Instant};
62
63use calloop::channel::Channel;
64use calloop::futures::{Executor, Scheduler};
65use calloop::generic::Generic;
66use calloop::timer::{TimeoutAction, Timer};
67use calloop::{Interest, LoopHandle, Mode, PostAction, RegistrationToken};
68use crabshell_reactive::{Owner, ReadSignal, Signal};
69use crabshell_ui::{Cx, IntoProp};
70
71#[doc(hidden)]
72pub use a11y::follow_accessibility;
73pub use audio::{Audio, AudioChannel, AudioNode, AudioStream, PeakTarget, Sink};
74pub use bluetooth::{
75  Bluetooth, BluetoothAdapter, BluetoothAdapterState, BluetoothAgent, BluetoothDevice,
76  BluetoothDeviceState, PairingKind, PairingRequest,
77};
78pub use brightness::{Backlight, Brightness};
79pub use clock::Precision;
80pub use desktop_entries::{DesktopAction, DesktopEntries, DesktopEntry};
81pub use file::{FileError, FileErrorKind, FileView};
82pub use folder::{FolderEntry, FolderView};
83pub use greetd::{GreetMessage, GreetState, Greetd};
84pub use http::{Http, HttpError, HttpErrorKind};
85pub use hyprland::{Hyprland, HyprlandEvent, HyprlandMonitor, HyprlandToplevel, HyprlandWorkspace};
86pub use locale::Locale;
87pub use logind::Logind;
88pub use mpris::{LoopStatus, Mpris, PlaybackStatus, Player};
89pub use network::Scanner;
90pub use network::{
91  ConnectionFailReason, Connectivity, Network, NetworkDevice, NetworkKind, NetworkState,
92  SavedConnection, WifiMode, WifiNetwork, WifiSecurity,
93};
94pub use niri::{Niri, NiriKeyboardLayouts, NiriWindow, NiriWorkspace};
95pub use notifications::{CloseReason, Notification, Notifications, Timeout, Urgency};
96pub use pam::{Pam, PamError, PamMessage, PamResult, PamState};
97pub use pipewire::{PipeWire, PwLink, PwLinkGroup, PwLinkState, PwNode};
98pub use polkit::{AuthRequest, AuthState, PolkitAgent};
99pub use power::{
100  BatteryState, DeviceKind, PerformanceDegradation, PowerDevice, PowerProfile, PowerProfiles,
101  UPower,
102};
103pub use process::{IntoCommand, Process};
104pub use socket::Socket;
105pub use socket_server::SocketServer;
106#[doc(hidden)]
107pub use spawn::{FIRST_START, shell_tunables};
108pub use stats::{SystemStats, Temperature};
109pub use sway::{Sway, SwayEvent, SwayEventKind, SwayOutput, Workspace};
110pub use tray::{
111  MenuEntry, MenuToggle, Tray, TrayCategory, TrayHost, TrayItem, TrayMenu, TrayStatus,
112};
113
114/// Makes the services reachable from `cx` and every context made from it.
115/// The shell calls this once, with its root context and its event loop.
116///
117/// Nothing starts here: each service starts when a config first asks for
118/// it. The loop is kept weakly, so it and the compositor connection still
119/// go when the shell drops.
120pub fn provide<D: 'static>(cx: &Cx, handle: &LoopHandle<'static, D>) {
121  provide_with(cx, handle, Config::system());
122}
123
124/// [`provide`] with the system's parts swapped for a test's.
125fn provide_with<D: 'static>(cx: &Cx, handle: &LoopHandle<'static, D>, config: Config) {
126  let shared = Rc::new(Shared::new(cx.owner(), handle, config));
127  cx.provide(Alone(Rc::clone(&shared)));
128  cx.provide(clock::Clocks::new(Rc::clone(&shared)));
129  cx.provide(sway::Service::new(Rc::clone(&shared)));
130  cx.provide(hyprland::Service::new(Rc::clone(&shared)));
131  cx.provide(niri::Service::new(Rc::clone(&shared)));
132  cx.provide(pipewire::Service::new(Rc::clone(&shared)));
133  cx.provide(audio::AudioService::new(Rc::clone(&shared)));
134  cx.provide(tray::Service::new(Rc::clone(&shared)));
135  cx.provide(power::UPowerService::new(Rc::clone(&shared)));
136  cx.provide(power::ProfilesService::new(Rc::clone(&shared)));
137  let agent = cx.provide(bluetooth::agent::Service::new(Rc::clone(&shared)));
138  cx.provide(bluetooth::BluetoothService::new(Rc::clone(&shared), agent));
139  cx.provide(notifications::Service::new(Rc::clone(&shared)));
140  cx.provide(mpris::Service::new(Rc::clone(&shared)));
141  cx.provide(network::NetworkService::new(Rc::clone(&shared)));
142  cx.provide(socket::Sockets(Rc::clone(&shared)));
143  cx.provide(process::Processes::new(Rc::clone(&shared)));
144  cx.provide(desktop_entries::Service::new(Rc::clone(&shared)));
145  cx.provide(file::Files(Rc::clone(&shared)));
146  cx.provide(http::Service::new(Rc::clone(&shared)));
147  cx.provide(stats::Service::new(Rc::clone(&shared)));
148  cx.provide(greetd::Service::new(Rc::clone(&shared)));
149  cx.provide(pam::Service(Rc::clone(&shared)));
150  cx.provide(polkit::Service::new(Rc::clone(&shared)));
151  let logind = cx.provide(logind::Service::new(Rc::clone(&shared)));
152  cx.provide(brightness::Service::new(Rc::clone(&shared), logind));
153  cx.provide(a11y::Service::new(Rc::clone(&shared)));
154}
155
156/// Lets the services ask the compositor for activation tokens for the
157/// programs they start, so it may focus them: `request` asks for one for
158/// a program with the app id given, if any, and hands it to the callback.
159/// The shell calls this once, when the compositor offers tokens; without
160/// it programs start at once with none.
161#[doc(hidden)]
162pub fn provide_activation_tokens(
163  cx: &Cx,
164  request: impl Fn(Option<&str>, Box<dyn FnOnce(String)>) + 'static,
165) {
166  if let Some(processes) = cx.service::<process::Processes>() {
167    let _ = processes.shared.activation.set(Box::new(request));
168  }
169}
170
171/// Stops every program a config started with `cx.process` and every curl
172/// `cx.http_get` and `cx.cover_art` run, and starts every program still
173/// waiting for its activation token, without it. The
174/// shell calls this before it exits, since `std::process::exit` skips the
175/// drops that would stop them, each program has a process group of its
176/// own, and no token or timer comes after the exit.
177#[doc(hidden)]
178pub fn stop_programs(cx: &Cx) {
179  if let Some(processes) = cx.service::<process::Processes>() {
180    activation::start_waiting(&processes.shared);
181  }
182  process::stop_all(cx);
183  http::stop_all(cx);
184}
185
186/// What the services keep across a reload, for the shell to save: the
187/// notifications kept. `None` when no service has anything to keep.
188#[doc(hidden)]
189pub fn save_state(cx: &Cx) -> Option<serde_json::Value> {
190  let notifications = cx.service::<notifications::Service>()?.save()?;
191  Some(serde_json::json!({ "notifications": notifications }))
192}
193
194/// Whether the notification server is still taking over from the shell
195/// before a reload, which the shell waits for before it says `ready`, so
196/// the old shell isn't told to exit before it handed its notifications
197/// over.
198#[doc(hidden)]
199pub fn taking_over(cx: &Cx) -> bool {
200  cx.service::<notifications::Service>()
201    .is_some_and(|service| service.taking_over())
202}
203
204/// Says whether the shell runs alone. A shell a reload starts beside the
205/// old one isn't, until the old one has exited: meanwhile what only one
206/// process can hold, the polkit agent and socket servers, waits, and
207/// starts when this turns true. A shell is alone until told otherwise.
208#[doc(hidden)]
209pub fn set_alone(cx: &Cx, alone: bool) {
210  let Some(handle) = cx.service::<Alone>() else {
211    return;
212  };
213  let shared = &handle.0;
214  shared.alone.set(alone);
215  if alone {
216    // Taken first: a start may add another.
217    let waiting = shared.until_alone.take();
218    for start in waiting {
219      start();
220    }
221  }
222}
223
224/// Hands the services what [`save_state`] gave the shell before a reload.
225/// The shell calls it before the root closure runs.
226#[doc(hidden)]
227pub fn restore_state(cx: &Cx, state: serde_json::Value) {
228  let Some(service) = cx.service::<notifications::Service>() else {
229    return;
230  };
231  if let serde_json::Value::Object(mut state) = state
232    && let Some(notifications) = state.remove("notifications")
233  {
234    service.restore(notifications);
235  }
236}
237
238/// The name of user `uid` through NSS, so a user from LDAP or
239/// systemd-homed counts as one in `/etc/passwd` does. `None` for no such
240/// user; a lookup that fails is logged.
241pub(crate) fn user_name(uid: u32) -> Option<String> {
242  match nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid)) {
243    Ok(user) => user.map(|user| user.name).filter(|name| !name.is_empty()),
244    Err(error) => {
245      tracing::warn!(%error, uid, "couldn't look the user up");
246      None
247    }
248  }
249}
250
251/// The services a context hands out.
252pub trait ServicesExt {
253  /// The time, truncated to `precision`: it changes on each whole second
254  /// or minute and holds the one just passed, in the system time zone.
255  /// Every caller asking for the same precision gets the same signal.
256  ///
257  /// A minute clock wakes the shell once a minute and at no other time.
258  /// After a suspend, and when timedated changes the time zone, it is
259  /// right again at once. A zone changed any other way shows from the
260  /// next tick.
261  fn clock(&self, precision: Precision) -> ReadSignal<jiff::Zoned>;
262
263  /// The month and day names of the user's locale for dates: `LC_ALL`,
264  /// else `LC_TIME`, else `LANG`. English until glibc's names for it are
265  /// read, once per shell, by running `locale -k LC_TIME` on a thread;
266  /// that wakes the shell once. C, POSIX, unset, or a locale that isn't
267  /// installed stays English.
268  fn locale(&self) -> ReadSignal<Locale>;
269
270  /// Sway's workspaces, outputs, commands and events, over the IPC socket
271  /// at `$SWAYSOCK`, as Quickshell's `I3`. Every caller shares one
272  /// connection, made on the first call.
273  ///
274  /// The lists are empty while Sway isn't there. When `SWAYSOCK` is unset
275  /// or the first connect fails, they stay empty and the service never
276  /// wakes the shell. When a working connection closes, they are empty
277  /// until a reconnect, tried every 2 s, works. While connected, it wakes
278  /// the shell only for a workspace event, an output event once a config
279  /// asked for the outputs, and the kinds of event a handler asked for.
280  fn sway(&self) -> Sway;
281
282  /// Hyprland's workspaces, monitors and windows, over its IPC sockets
283  /// in `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/`. Every
284  /// caller shares one event connection, made on the first call.
285  ///
286  /// The lists are empty while Hyprland isn't there: when the signature
287  /// is unset or its sockets are missing, they stay empty, which is
288  /// logged once, and the service never wakes the shell. When Hyprland
289  /// closes its event socket, the lists empty and nothing reconnects.
290  /// While connected, it wakes the shell only when Hyprland sends
291  /// something.
292  fn hyprland(&self) -> Hyprland;
293
294  /// niri's workspaces, windows, keyboard layouts and overview, from its
295  /// event stream on the IPC socket at `$NIRI_SOCKET`. Every caller
296  /// shares one connection, made on the first call.
297  ///
298  /// The lists are empty while niri isn't there: when `NIRI_SOCKET` is
299  /// unset or the socket is missing, they stay empty, which is logged
300  /// once, and the service never wakes the shell. When niri closes the
301  /// stream while its socket is still there, the shell connects once
302  /// again; otherwise the lists empty and nothing reconnects. While
303  /// connected, it wakes the shell only when niri sends something.
304  fn niri(&self) -> Niri;
305
306  /// PipeWire's nodes and the links between them, over its native
307  /// protocol on `pipewire-0` in `$PIPEWIRE_RUNTIME_DIR`, else
308  /// `$XDG_RUNTIME_DIR`. Every caller shares one connection, made on the
309  /// first call, so a shell that never asks pays nothing.
310  ///
311  /// The lists are empty while PipeWire isn't there, which is logged
312  /// once, and the service never wakes the shell. When PipeWire closes
313  /// the connection while its socket is still there, the shell connects
314  /// once again; otherwise the lists empty and nothing reconnects. While
315  /// connected, it wakes the shell only when the graph changes.
316  fn pipewire(&self) -> PipeWire;
317
318  /// The audio server's default sink, with its volume and mute. Every
319  /// caller shares one connection, which starts on the loop's next turn
320  /// and never waits for the server. It wakes the shell only when the
321  /// server reports a change, and while a peak meter from
322  /// [`Audio::peaks`] records.
323  ///
324  /// With no server, the sink is `None` and the service tries again
325  /// every 2 s, for up to a minute after startup and after each drop of
326  /// a working connection. Then it stops, logs that once and never wakes
327  /// the shell again; a restart tries again.
328  fn audio(&self) -> Audio;
329
330  /// The system tray: every app's StatusNotifierItem on the session bus.
331  /// Every caller shares one connection, which starts on the loop's next
332  /// turn and never waits for the bus.
333  ///
334  /// The shell runs the StatusNotifierWatcher while no other program
335  /// does, and otherwise reads the list from the one that runs, taking
336  /// over when it leaves. With no session bus the list stays empty and
337  /// the service never wakes the shell. It wakes the shell only when
338  /// something arrives on the bus for it.
339  fn tray(&self) -> TrayHost;
340
341  /// UPower's batteries and power supplies, on the system bus. Every
342  /// caller shares one connection, which starts on the loop's next turn.
343  ///
344  /// While UPower isn't running the lists are empty, and they fill when
345  /// it starts. With no system bus they stay empty and the service never
346  /// wakes the shell. It wakes the shell only when UPower says something
347  /// changed.
348  fn upower(&self) -> UPower;
349
350  /// The power profile, from power-profiles-daemon on the system bus.
351  /// Every caller shares one connection. It behaves as
352  /// [`upower`](Self::upower) does while the daemon isn't there.
353  fn power_profiles(&self) -> PowerProfiles;
354
355  /// Bluetooth adapters and devices, from BlueZ on the system bus. Every
356  /// caller shares one connection. It behaves as [`upower`](Self::upower)
357  /// does while BlueZ isn't there, and wakes the shell only when BlueZ
358  /// says something changed.
359  fn bluetooth(&self) -> Bluetooth;
360
361  /// The shell's Bluetooth pairing agent: when BlueZ needs a PIN, a
362  /// passkey or a yes to pair a device, it asks the shell, and a config
363  /// shows the prompt. The first call registers the agent with BlueZ on
364  /// the system bus, as `KeyboardDisplay`, again whenever BlueZ starts
365  /// again; a shell that never calls it never answers BlueZ. Every caller
366  /// shares the one agent, which wakes the shell only when BlueZ calls.
367  fn bluetooth_agent(&self) -> BluetoothAgent;
368
369  /// The notification server on the session bus: what apps sent, and
370  /// the popups still showing. Every caller shares one connection, which
371  /// starts on the loop's next turn and never waits for the bus.
372  ///
373  /// The shell serves while no other program does. While another daemon
374  /// has the name, the shell waits for it to leave, and keeps what it was
375  /// sent if one takes the name over. With no session bus the lists stay
376  /// empty and the service never wakes the shell. It wakes the shell only
377  /// when an app calls and when a popup expires.
378  fn notifications(&self) -> Notifications;
379
380  /// The media players on the session bus, over MPRIS, such as a music
381  /// player or a browser playing a video. Every caller shares one
382  /// connection, which starts on the loop's next turn and never waits
383  /// for the bus.
384  ///
385  /// With no session bus the list stays empty and the service never
386  /// wakes the shell. It wakes the shell only when a player says
387  /// something changed. MPRIS doesn't say when the position moves, so a
388  /// bar works it out with [`Player::position_at`].
389  fn mpris(&self) -> Mpris;
390
391  /// Network devices and Wi-Fi networks, from NetworkManager on the
392  /// system bus. Every caller shares one connection. It behaves as
393  /// [`upower`](Self::upower) does while NetworkManager isn't there, and
394  /// wakes the shell only when NetworkManager says something changed.
395  fn network(&self) -> Network;
396
397  /// A connection to the Unix socket at `path`, made at once, as
398  /// Quickshell's `Socket`. Each call opens its own, which closes when
399  /// this context goes. It wakes the shell only when the other end sends
400  /// something or takes what was written.
401  fn socket(&self, path: impl Into<PathBuf>) -> Socket;
402
403  /// A server on the Unix socket at `path`, as Quickshell's
404  /// `SocketServer`: it listens at once, and each client that connects
405  /// becomes a [`Socket`] for [`SocketServer::on_connection`]. Each call
406  /// makes its own, which stops when this context goes, closing its
407  /// connections and removing its socket file. It wakes the shell only
408  /// when a client connects, sends something or takes what was written.
409  fn socket_server(&self, path: impl Into<PathBuf>) -> SocketServer;
410
411  /// Runs the program `command` builds, as Quickshell's `Process`, and
412  /// keeps what it prints and how it ended. `command` returns a
413  /// [`Command`](std::process::Command) or a list such as
414  /// `["uptime", "-p"]`. It starts on the loop's next turn, and again
415  /// whenever a signal `command` read changes or [`Process::restart`] is
416  /// called, stopping the run before. It is stopped when this context
417  /// goes. It wakes the shell only when the program prints, takes input
418  /// or ends.
419  fn process<C: IntoCommand>(&self, command: impl Fn() -> C + 'static) -> Process;
420
421  /// Starts `command` and lets it run on its own, as a launcher does:
422  /// its input and outputs are empty, it has a process group of its own,
423  /// and it is reaped when it ends. A failure to start is logged. When
424  /// the compositor hands out activation tokens, it starts once one comes,
425  /// or after 100 ms without one, with the token in
426  /// `XDG_ACTIVATION_TOKEN` and `DESKTOP_STARTUP_ID`, so the compositor
427  /// may focus its window.
428  fn exec_detached(&self, command: impl IntoCommand);
429
430  /// The text file at `path`, as Quickshell's `FileView`: read now, and
431  /// again when it changes on disk. Each call reads its own, which goes
432  /// with this context. It is read on the main thread, so a file on a
433  /// slow disk delays the frame.
434  fn file_view(&self, path: impl Into<PathBuf>) -> FileView;
435
436  /// The folder at `path`, as Qt's `FolderListModel`: its entries, read
437  /// at the next flush and again 50 ms after a change in it, so a burst
438  /// of changes reads it once, and followed as `file_view` follows a
439  /// file when the folder is made later, removed or replaced.
440  /// `path` takes a value or a closure; a new path follows the new
441  /// folder, and a panic in the closure is logged and empties the view
442  /// until the next change. Each call reads its own, which goes with
443  /// this context. It is read on the main thread, and wakes the shell
444  /// only when the folder changes.
445  fn folder_view(&self, path: impl IntoProp<PathBuf>) -> FolderView;
446
447  /// CPU, memory and temperature stats, sampled at once and then every
448  /// `period`, at least 250 ms, from `/proc` and `/sys/class/hwmon`. Each
449  /// call samples on its own timer, which goes with this context, so
450  /// stats wake the shell only while a context that shows them lives.
451  /// Call it once, above `per_output`, and share the signal. The signal
452  /// starts empty and fills when the first sample, asked for at once,
453  /// comes back from the thread the reads run on, so a slow sensor never
454  /// holds up a frame. A tick while a read still runs is skipped. Each
455  /// sample wakes the shell twice: at the tick and when the answer comes.
456  fn system_stats(&self, period: Duration) -> ReadSignal<SystemStats>;
457
458  /// greetd, for a greeter: makes a session for a user, answers its
459  /// questions and starts it, over the socket `GREETD_SOCK` names. One
460  /// connection per shell, made at the first request; it wakes the shell
461  /// only when greetd answers.
462  fn greetd(&self) -> Greetd;
463
464  /// A value kept in the JSON file at `path`, as Quickshell's
465  /// `JsonAdapter`: `default` until the file is read, the file's value
466  /// once it is, and the file rewritten whenever the config sets another.
467  /// A missing file, and its directory, is made at the first set. A file
468  /// that isn't `T`'s
469  /// JSON is logged and left alone, and the value stays.
470  fn json_file<T>(&self, path: impl Into<PathBuf>, default: T) -> Signal<T>
471  where
472    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + 'static;
473
474  /// Fetches `url` with an HTTP GET through `curl`, in a process of its
475  /// own, so nothing waits on the network. A closure fetches again when a
476  /// signal it read changes the URL. It stops when this context goes, and
477  /// wakes the shell only while curl runs.
478  fn http_get(&self, url: impl IntoProp<String>) -> Http;
479
480  /// The local file for the cover art at `url`, for an `Image`: a
481  /// `file://` URL's file, or an `http:` or `https:` URL's picture
482  /// downloaded through `curl` into `$XDG_CACHE_HOME/crabshell/art`.
483  /// `None` while it downloads, and for anything else or a failure, which
484  /// is logged once per URL.
485  fn cover_art(&self, url: impl IntoProp<String>) -> ReadSignal<Option<PathBuf>>;
486
487  /// The installed applications, from the desktop entries in the XDG
488  /// data directories: what a launcher lists and starts, and where a
489  /// window's app id finds its icon. Every caller shares one list, read
490  /// on the loop's next turn after the first call.
491  ///
492  /// The directories are watched, and the list is read again once the
493  /// files have been still for 100 ms after a change. It wakes the shell
494  /// at no other time.
495  fn desktop_entries(&self) -> DesktopEntries;
496
497  /// Authentication through the PAM service `service`, the name of a
498  /// file in `/etc/pam.d`, as a lock screen asks for the user's
499  /// password. Each call has its own, which goes with this context.
500  ///
501  /// Nothing runs until [`Pam::start`]. Each attempt runs on a thread of
502  /// its own, since libpam blocks, and wakes the shell only when PAM asks
503  /// or says something, or the attempt ends. After a success PAM's
504  /// account step runs too, which clears `pam_faillock`'s count of past
505  /// failures; its refusal is only logged. An attempt ended while PAM
506  /// waits for an answer counts as a failure, as [`Pam::start`] says.
507  fn pam(&self, service: &str) -> Pam;
508
509  /// The shell's polkit authentication agent, as Quickshell's
510  /// `PolkitAgent`: when a program asks polkit for something only some
511  /// users may do, its request shows here for the config's dialog. The
512  /// first call registers the agent with polkit on the system bus for
513  /// this session; a shell that never calls it never reaches polkit.
514  ///
515  /// A refused registration is logged and no requests arrive. It wakes
516  /// the shell only when polkit calls and while a request is answered.
517  fn polkit_agent(&self) -> PolkitAgent;
518
519  /// logind on the system bus: when the machine is about to sleep, a
520  /// delay so a config can get ready first, as a lock screen locks, and
521  /// the power actions. Every caller shares one connection, which starts
522  /// on the loop's next turn. It behaves as [`upower`](Self::upower)
523  /// does while logind isn't there, and wakes the shell only for
524  /// `PrepareForSleep`.
525  fn logind(&self) -> Logind;
526
527  /// The screen backlights in `/sys/class/backlight`, read on the first
528  /// call and followed with inotify, and set through logind, which
529  /// starts with it. Every caller shares one list. It wakes the shell
530  /// only when the kernel says a brightness changed; a backlight added
531  /// later shows after a restart.
532  fn brightness(&self) -> Brightness;
533}
534
535impl ServicesExt for Cx {
536  fn clock(&self, precision: Precision) -> ReadSignal<jiff::Zoned> {
537    clock::clock(self, precision)
538  }
539
540  fn locale(&self) -> ReadSignal<Locale> {
541    locale::locale(self)
542  }
543
544  fn sway(&self) -> Sway {
545    sway::sway(self)
546  }
547
548  fn hyprland(&self) -> Hyprland {
549    hyprland::hyprland(self)
550  }
551
552  fn niri(&self) -> Niri {
553    niri::niri(self)
554  }
555
556  fn pipewire(&self) -> PipeWire {
557    pipewire::pipewire(self)
558  }
559
560  fn audio(&self) -> Audio {
561    audio::audio(self)
562  }
563
564  fn tray(&self) -> TrayHost {
565    tray::tray(self)
566  }
567
568  fn upower(&self) -> UPower {
569    power::upower(self)
570  }
571
572  fn power_profiles(&self) -> PowerProfiles {
573    power::power_profiles(self)
574  }
575
576  fn bluetooth(&self) -> Bluetooth {
577    bluetooth::bluetooth(self)
578  }
579
580  fn bluetooth_agent(&self) -> BluetoothAgent {
581    bluetooth::agent::bluetooth_agent(self)
582  }
583
584  fn notifications(&self) -> Notifications {
585    notifications::notifications(self)
586  }
587
588  fn mpris(&self) -> Mpris {
589    mpris::mpris(self)
590  }
591
592  fn network(&self) -> Network {
593    network::network(self)
594  }
595
596  fn socket(&self, path: impl Into<PathBuf>) -> Socket {
597    socket::socket(self, path.into())
598  }
599
600  fn socket_server(&self, path: impl Into<PathBuf>) -> SocketServer {
601    socket_server::socket_server(self, path.into())
602  }
603
604  #[track_caller]
605  fn process<C: IntoCommand>(&self, command: impl Fn() -> C + 'static) -> Process {
606    process::process(self, command)
607  }
608
609  fn exec_detached(&self, command: impl IntoCommand) {
610    process::exec_detached(self, command);
611  }
612
613  fn file_view(&self, path: impl Into<PathBuf>) -> FileView {
614    file::file_view(self, path.into())
615  }
616
617  #[track_caller]
618  fn folder_view(&self, path: impl IntoProp<PathBuf>) -> FolderView {
619    folder::folder_view(self, path, std::panic::Location::caller())
620  }
621
622  fn system_stats(&self, period: Duration) -> ReadSignal<SystemStats> {
623    stats::system_stats(self, period)
624  }
625
626  fn greetd(&self) -> Greetd {
627    greetd::greetd(self)
628  }
629
630  fn json_file<T>(&self, path: impl Into<PathBuf>, default: T) -> Signal<T>
631  where
632    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + 'static,
633  {
634    file::json_file(self, path.into(), default)
635  }
636
637  #[track_caller]
638  fn http_get(&self, url: impl IntoProp<String>) -> Http {
639    http::http_get(self, url)
640  }
641
642  #[track_caller]
643  fn cover_art(&self, url: impl IntoProp<String>) -> ReadSignal<Option<PathBuf>> {
644    http::art::cover_art(self, url)
645  }
646
647  fn desktop_entries(&self) -> DesktopEntries {
648    desktop_entries::desktop_entries(self)
649  }
650
651  fn pam(&self, service: &str) -> Pam {
652    pam::pam(self, service)
653  }
654
655  fn polkit_agent(&self) -> PolkitAgent {
656    polkit::polkit_agent(self)
657  }
658
659  fn logind(&self) -> Logind {
660    logind::logind(self)
661  }
662
663  fn brightness(&self) -> Brightness {
664    brightness::brightness(self)
665  }
666}
667
668/// What every service of one shell starts from.
669struct Shared {
670  /// The root context's owner. Services create their signals under it,
671  /// so bars on every output share them and they go with the shell.
672  root: Owner,
673  /// The event loop, held weakly. Services' timers and futures live in
674  /// the loop and hold the services, so a strong handle here would be an
675  /// `Rc` cycle that keeps the loop and the compositor connection alive
676  /// after the shell drops. calloop's weak handle has no type we can
677  /// name, so a closure keeps it.
678  event_loop: Box<dyn Fn() -> Option<Box<dyn EventLoop>>>,
679  /// The one futures executor every service's D-Bus calls run on, added
680  /// to the loop on first use. `None` if that failed.
681  executor: OnceCell<Option<Scheduler<()>>>,
682  /// The one inotify instance, made for the first directory watched.
683  watcher: watch::Watcher,
684  /// How to ask for an activation token, once the shell gives it.
685  activation: OnceCell<activation::Request>,
686  /// The programs waiting for their activation token.
687  waiting: activation::Waiting,
688  config: Config,
689  /// Whether the shell runs alone; see [`set_alone`].
690  alone: Cell<bool>,
691  /// What starts once it does.
692  until_alone: RefCell<Vec<Box<dyn FnOnce()>>>,
693}
694
695/// The services' [`Shared`], for [`set_alone`].
696struct Alone(Rc<Shared>);
697
698impl Shared {
699  fn new<D: 'static>(root: Owner, handle: &LoopHandle<'static, D>, config: Config) -> Shared {
700    let weak = handle.downgrade();
701    Shared {
702      root,
703      event_loop: Box::new(move || {
704        weak
705          .upgrade()
706          .map(|handle| Box::new(handle) as Box<dyn EventLoop>)
707      }),
708      executor: OnceCell::new(),
709      watcher: watch::Watcher::default(),
710      activation: OnceCell::new(),
711      waiting: activation::Waiting::default(),
712      config,
713      alone: Cell::new(true),
714      until_alone: RefCell::default(),
715    }
716  }
717
718  /// Runs `start` now if the shell runs alone, else once it does.
719  fn when_alone(&self, start: impl FnOnce() + 'static) {
720    if self.alone.get() {
721      start();
722    } else {
723      self.until_alone.borrow_mut().push(Box::new(start));
724    }
725  }
726
727  /// The event loop, while it is still there.
728  fn event_loop(&self) -> Option<Box<dyn EventLoop>> {
729    (self.event_loop)()
730  }
731
732  /// Runs `future` on the main thread, between the loop's other sources,
733  /// so no D-Bus call delays a frame.
734  fn spawn(&self, future: impl Future<Output = ()> + 'static) {
735    let scheduler = self.executor.get_or_init(|| {
736      let (executor, scheduler) = calloop::futures::executor()
737        .inspect_err(|error| tracing::error!(%error, "no executor for the services"))
738        .ok()?;
739      self
740        .event_loop()?
741        .insert_executor(executor)
742        .then_some(scheduler)
743    });
744    if let Some(scheduler) = scheduler
745      && let Err(error) = scheduler.schedule(future)
746    {
747      tracing::error!(%error, "a service's future couldn't start");
748    }
749  }
750}
751
752impl Shared {
753  /// Awaits `call`, or gives up after `limit` with a timed-out error. The
754  /// timer is the loop's and goes as soon as the call ends. zbus's own
755  /// timeout left its timer behind, which woke zbus's thread once, `limit`
756  /// after every call, while nothing changed.
757  async fn timeout<T>(
758    &self,
759    limit: Duration,
760    call: impl Future<Output = zbus::Result<T>>,
761  ) -> zbus::Result<T> {
762    let fired = Rc::new(Cell::new(false));
763    let waker: Rc<RefCell<Option<Waker>>> = Rc::default();
764    let tick = {
765      let (fired, waker) = (Rc::clone(&fired), Rc::clone(&waker));
766      Box::new(move || {
767        fired.set(true);
768        if let Some(waker) = waker.take() {
769          waker.wake();
770        }
771        TimeoutAction::Drop
772      })
773    };
774    let token = self
775      .event_loop()
776      .and_then(|event_loop| event_loop.insert_timer(Instant::now() + limit, tick));
777    let _timer = RemoveOnDrop(self, token);
778    let mut call = pin!(call);
779    poll_fn(|context| {
780      if let Poll::Ready(result) = call.as_mut().poll(context) {
781        return Poll::Ready(result);
782      }
783      if fired.get() {
784        let error = std::io::Error::new(std::io::ErrorKind::TimedOut, "no answer in time");
785        return Poll::Ready(Err(zbus::Error::InputOutput(error.into())));
786      }
787      waker.replace(Some(context.waker().clone()));
788      Poll::Pending
789    })
790    .await
791  }
792}
793
794/// Removes a loop source when dropped, as a call that ends removes its
795/// timer.
796struct RemoveOnDrop<'a>(&'a Shared, Option<RegistrationToken>);
797
798impl Drop for RemoveOnDrop<'_> {
799  fn drop(&mut self) {
800    if let (Some(token), Some(event_loop)) = (self.1, self.0.event_loop()) {
801      event_loop.remove(token);
802    }
803  }
804}
805
806/// The parts of the event loop services use. It hides the loop's data
807/// type, since one services map serves any shell.
808trait EventLoop {
809  /// Calls `tick` at `deadline`, then again at whatever it returns.
810  /// `None`, logged, if the loop refused it.
811  fn insert_timer(
812    &self,
813    deadline: Instant,
814    tick: Box<dyn FnMut() -> TimeoutAction>,
815  ) -> Option<RegistrationToken>;
816
817  /// Calls `ready` whenever `fd` is ready for `interest`. The loop owns
818  /// `fd` and closes it when the source is removed. `None`, logged, if
819  /// the loop refused it.
820  fn insert_fd(
821    &self,
822    fd: OwnedFd,
823    interest: Interest,
824    ready: Box<dyn FnMut()>,
825  ) -> Option<RegistrationToken>;
826
827  /// Removes a source. One that is already gone is ignored.
828  fn remove(&self, token: RegistrationToken);
829
830  /// Adds the services' executor. `false`, logged, if the loop refused it.
831  fn insert_executor(&self, executor: Executor<()>) -> bool;
832
833  /// Calls `on_message` with each message libpulse's thread sends on
834  /// `channel`. `false`, logged, if the loop refused it.
835  fn insert_audio_channel(
836    &self,
837    channel: Channel<audio::Message>,
838    on_message: Box<dyn FnMut(audio::Message)>,
839  ) -> bool;
840
841  /// Calls `on_event` with each event a PAM attempt's thread sends on
842  /// `channel`, and with `Closed` once the thread is gone. `None`, logged,
843  /// if the loop refused it.
844  fn insert_pam_channel(
845    &self,
846    channel: Channel<pam::Event>,
847    on_event: Box<dyn FnMut(calloop::channel::Event<pam::Event>)>,
848  ) -> Option<RegistrationToken>;
849
850  /// Adds the channel a user lookup's thread sends names on.
851  fn insert_users_channel(
852    &self,
853    channel: Channel<polkit::Found>,
854    on_event: Box<dyn FnMut(calloop::channel::Event<polkit::Found>)>,
855  ) -> Option<RegistrationToken>;
856
857  /// Calls `on_answer` with each sample the stats' thread sends on
858  /// `channel`. `None`, logged, if the loop refused it.
859  fn insert_stats_channel(
860    &self,
861    channel: Channel<stats::Answer>,
862    on_answer: Box<dyn FnMut(stats::Answer)>,
863  ) -> Option<RegistrationToken>;
864}
865
866impl<D: 'static> EventLoop for LoopHandle<'static, D> {
867  fn insert_timer(
868    &self,
869    deadline: Instant,
870    mut tick: Box<dyn FnMut() -> TimeoutAction>,
871  ) -> Option<RegistrationToken> {
872    self
873      .insert_source(Timer::from_deadline(deadline), move |_, _, _| tick())
874      .inspect_err(|error| tracing::error!(%error, "a service's timer couldn't be added"))
875      .ok()
876  }
877
878  fn insert_fd(
879    &self,
880    fd: OwnedFd,
881    interest: Interest,
882    mut ready: Box<dyn FnMut()>,
883  ) -> Option<RegistrationToken> {
884    let source = Generic::new(fd, interest, Mode::Level);
885    self
886      .insert_source(source, move |_, _, _| {
887        ready();
888        Ok(PostAction::Continue)
889      })
890      .inspect_err(|error| tracing::error!(%error, "a service's socket couldn't be added"))
891      .ok()
892  }
893
894  fn remove(&self, token: RegistrationToken) {
895    LoopHandle::remove(self, token);
896  }
897
898  fn insert_executor(&self, executor: Executor<()>) -> bool {
899    self
900      .insert_source(executor, |(), _, _| {})
901      .inspect_err(|error| tracing::error!(%error, "the services' executor couldn't be added"))
902      .is_ok()
903  }
904
905  fn insert_audio_channel(
906    &self,
907    channel: Channel<audio::Message>,
908    mut on_message: Box<dyn FnMut(audio::Message)>,
909  ) -> bool {
910    self
911      .insert_source(channel, move |event, _, _| {
912        if let calloop::channel::Event::Msg(message) = event {
913          on_message(message);
914        }
915      })
916      .inspect_err(|error| tracing::error!(%error, "the audio channel couldn't be added"))
917      .is_ok()
918  }
919
920  fn insert_pam_channel(
921    &self,
922    channel: Channel<pam::Event>,
923    mut on_event: Box<dyn FnMut(calloop::channel::Event<pam::Event>)>,
924  ) -> Option<RegistrationToken> {
925    self
926      .insert_source(channel, move |event, _, _| on_event(event))
927      .inspect_err(|error| tracing::error!(%error, "a PAM attempt's channel couldn't be added"))
928      .ok()
929  }
930
931  fn insert_users_channel(
932    &self,
933    channel: Channel<polkit::Found>,
934    mut on_event: Box<dyn FnMut(calloop::channel::Event<polkit::Found>)>,
935  ) -> Option<RegistrationToken> {
936    self
937      .insert_source(channel, move |event, _, _| on_event(event))
938      .inspect_err(|error| tracing::error!(%error, "a user lookup's channel couldn't be added"))
939      .ok()
940  }
941
942  fn insert_stats_channel(
943    &self,
944    channel: Channel<stats::Answer>,
945    mut on_answer: Box<dyn FnMut(stats::Answer)>,
946  ) -> Option<RegistrationToken> {
947    self
948      .insert_source(channel, move |event, _, _| {
949        if let calloop::channel::Event::Msg(answer) = event {
950          on_answer(answer);
951        }
952      })
953      .inspect_err(|error| tracing::error!(%error, "the stats' channel couldn't be added"))
954      .ok()
955  }
956}
957
958/// Where the services find the system. Tests point it at their own files
959/// and a private bus.
960struct Config {
961  /// The link that names the system time zone, `/etc/localtime`. `None`
962  /// when `TZ` is set, since it names the zone then, as it does for libc.
963  localtime: Option<PathBuf>,
964  /// The system bus, where logind, timedated, UPower,
965  /// power-profiles-daemon, BlueZ, NetworkManager and polkit are. `None`
966  /// for none.
967  system_bus: Option<zbus::Address>,
968  /// The session bus, where tray items, notifying apps and media
969  /// players are. `None` for none.
970  session_bus: Option<zbus::Address>,
971  /// Sway's IPC socket, from `SWAYSOCK`. `None` when that is unset.
972  sway: Option<sway::Socket>,
973  /// `NO_AT_BRIDGE=1`, the user's word that no screen reader reads the
974  /// shell, as GTK and Qt take it.
975  no_at_bridge: bool,
976  /// The accessibility bus from `AT_SPI_BUS_ADDRESS`, used instead of
977  /// asking the launcher, as libatspi and Qt do.
978  at_spi_bus: Option<String>,
979  /// The directory of Hyprland's sockets,
980  /// `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE`. `None` when
981  /// either is unset.
982  hyprland: Option<PathBuf>,
983  /// niri's IPC socket, from `NIRI_SOCKET`. `None` when that is unset.
984  niri: Option<PathBuf>,
985  /// PipeWire's socket, `pipewire-0` in `PIPEWIRE_RUNTIME_DIR`, else
986  /// `XDG_RUNTIME_DIR`. `None` when both are unset.
987  pipewire: Option<PathBuf>,
988  /// The audio server. `None` for none, so a test never reaches the
989  /// user's.
990  audio: Option<audio::Server>,
991  /// How long a popup shows when its app leaves that to the server: 5 s,
992  /// and less in tests.
993  popup_timeout: Duration,
994  /// greetd's socket, from `GREETD_SOCK`. `None` when that is unset.
995  greetd: Option<PathBuf>,
996  /// Where the desktop entries are. Tests give directories of their own.
997  desktop_entries: desktop_entries::Sources,
998  /// What `cx.pam` authenticates with: libpam, and a script in tests, so
999  /// no test counts toward locking a real account.
1000  pam: Arc<dyn pam::Backend>,
1001  /// Where polkit's setuid helper, which checks answers with PAM, may be;
1002  /// the first that exists runs. Tests give a script of their own.
1003  polkit_helpers: Vec<PathBuf>,
1004  /// polkit's socket for its helper, tried before `polkit_helpers`.
1005  polkit_socket: PathBuf,
1006  /// How polkit's identities are named: through NSS, and in tests a
1007  /// lookup as slow as they like. It runs off the loop's thread.
1008  polkit_users: Arc<dyn Fn(u32) -> Option<String> + Send + Sync>,
1009  /// How long a request waits for its identities' names before it goes on
1010  /// with those found.
1011  polkit_users_limit: Duration,
1012  /// The `curl` that `cx.http_get` and `cx.cover_art` run.
1013  curl: PathBuf,
1014  /// Where `cx.cover_art` keeps what it downloads. `None` for no cache.
1015  art_cache: Option<PathBuf>,
1016  /// Where the backlights are, `/sys/class/backlight`.
1017  backlight: PathBuf,
1018  /// Where procfs and sysfs are, `/proc` and `/sys`, for the stats.
1019  proc: PathBuf,
1020  sys: PathBuf,
1021  /// A pause before each stats read, so tests can make sensors slow.
1022  #[cfg(test)]
1023  stats_delay: Duration,
1024  /// Whether the first stats read panics, as a bug would.
1025  #[cfg(test)]
1026  stats_panic: bool,
1027}
1028
1029impl Config {
1030  fn system() -> Config {
1031    Config {
1032      localtime: std::env::var_os("TZ")
1033        .is_none()
1034        .then(|| PathBuf::from("/etc/localtime")),
1035      system_bus: zbus::Address::system()
1036        .inspect_err(|error| tracing::warn!(%error, "no system bus address"))
1037        .ok(),
1038      session_bus: zbus::Address::session()
1039        .inspect_err(|error| tracing::warn!(%error, "no session bus address"))
1040        .ok(),
1041      no_at_bridge: std::env::var_os("NO_AT_BRIDGE").is_some_and(|value| value == "1"),
1042      at_spi_bus: std::env::var("AT_SPI_BUS_ADDRESS")
1043        .ok()
1044        .filter(|address| !address.is_empty()),
1045      sway: std::env::var_os("SWAYSOCK")
1046        .filter(|path| !path.is_empty())
1047        .map(|path| sway::Socket {
1048          path: path.into(),
1049          retry: sway::RETRY,
1050        }),
1051      hyprland: std::env::var_os("XDG_RUNTIME_DIR")
1052        .filter(|dir| !dir.is_empty())
1053        .zip(std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").filter(|sig| !sig.is_empty()))
1054        .map(|(dir, signature)| PathBuf::from(dir).join("hypr").join(signature)),
1055      niri: std::env::var_os("NIRI_SOCKET")
1056        .filter(|path| !path.is_empty())
1057        .map(PathBuf::from),
1058      pipewire: ["PIPEWIRE_RUNTIME_DIR", "XDG_RUNTIME_DIR"]
1059        .into_iter()
1060        .find_map(|name| std::env::var_os(name).filter(|dir| !dir.is_empty()))
1061        .map(|dir| PathBuf::from(dir).join("pipewire-0")),
1062      audio: Some(audio::Server {
1063        address: None,
1064        retry: audio::RETRY,
1065        retry_for: audio::RETRY_FOR,
1066      }),
1067      popup_timeout: notifications::POPUP_TIMEOUT,
1068      greetd: std::env::var_os("GREETD_SOCK")
1069        .filter(|path| !path.is_empty())
1070        .map(PathBuf::from),
1071      desktop_entries: desktop_entries::Sources::system(),
1072      pam: Arc::new(pam::LibPam),
1073      polkit_helpers: polkit::HELPERS.map(PathBuf::from).to_vec(),
1074      polkit_socket: PathBuf::from(polkit::HELPER_SOCKET),
1075      polkit_users: Arc::new(user_name),
1076      polkit_users_limit: polkit::USERS_LIMIT,
1077      curl: PathBuf::from("curl"),
1078      art_cache: http::art::cache_dir(),
1079      backlight: PathBuf::from("/sys/class/backlight"),
1080      proc: PathBuf::from("/proc"),
1081      sys: PathBuf::from("/sys"),
1082      #[cfg(test)]
1083      stats_delay: Duration::ZERO,
1084      #[cfg(test)]
1085      stats_panic: false,
1086    }
1087  }
1088}