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