Skip to main content

crabshell_services/
logind.rs

1//! logind on the system bus: when the machine goes to sleep, holding
2//! sleep off until a config is ready for it, and the power actions.
3
4#[cfg(test)]
5mod tests;
6
7use std::cell::{Cell, RefCell};
8use std::os::fd::OwnedFd;
9use std::panic::Location;
10use std::rc::Rc;
11use std::sync::Once;
12
13use crabshell_reactive::{Owner, ReadSignal, Signal};
14use crabshell_ui::{Cx, IntoProp};
15use zbus::{Connection, Message};
16
17use crate::Shared;
18use crate::dbus::{self, CALL_TIMEOUT, Daemon, PROPERTIES, set_changed};
19
20pub(crate) const LOGIND: &str = "org.freedesktop.login1";
21const PATH: &str = "/org/freedesktop/login1";
22const MANAGER: &str = "org.freedesktop.login1.Manager";
23/// The shell's own session, whichever it is.
24const SESSION_PATH: &str = "/org/freedesktop/login1/session/auto";
25const SESSION: &str = "org.freedesktop.login1.Session";
26
27/// logind, from `cx.logind()`. Cloning it is cheap.
28#[derive(Clone)]
29pub struct Logind {
30  /// `None` when the shell provided no services.
31  service: Option<Rc<Service>>,
32  sleeping: ReadSignal<bool>,
33  /// The asking context's owner, which a delay lives as long as.
34  owner: Owner,
35}
36
37impl Logind {
38  /// Whether the machine is about to sleep: `true` from logind's
39  /// `PrepareForSleep(true)` until its `PrepareForSleep(false)` after
40  /// the resume. `false` while logind isn't running.
41  pub fn preparing_for_sleep(&self) -> ReadSignal<bool> {
42    self.sleeping
43  }
44
45  /// Holds sleep off until `ready` reads `true`, as a lock screen locks
46  /// before the machine sleeps. While the asking context lives, the
47  /// shell holds a logind delay inhibitor. When the machine is about to
48  /// sleep, it lets go as soon as `ready` reads `true`, and takes a new
49  /// one after the resume. logind's `InhibitDelayMaxSec`, 5 s by
50  /// default, bounds the wait. Each call holds its own. An inhibitor
51  /// logind refuses is logged and asked for again only after the next
52  /// resume or when logind starts again.
53  ///
54  /// `ready` is read only while the machine is about to sleep. If it
55  /// panics, that is logged and the inhibitor goes.
56  #[track_caller]
57  pub fn delay_sleep_until(&self, ready: impl IntoProp<bool>) {
58    let at = Location::caller();
59    if self.owner.is_disposed() {
60      return tracing::warn!(
61        "Logind::delay_sleep_until (called at {at}) on a context that is gone does nothing"
62      );
63    }
64    let Some(service) = &self.service else {
65      return;
66    };
67    let Some((sleeping, connected)) = service.signals() else {
68      return;
69    };
70    let ready = ready.into_prop().shared();
71    let hold = Rc::new(Hold {
72      fd: RefCell::new(None),
73      asking: Cell::new(None),
74      arrived: self.owner.signal(0),
75    });
76    let service = Rc::clone(service);
77    // The effect owns the hold, so the inhibitor goes with the context,
78    // or when a panic in `ready` disables the effect.
79    self
80      .owner
81      .effect(move || {
82        if !connected.get() {
83          hold.release();
84        } else if !sleeping.get() {
85          hold.take(&service);
86        } else {
87          // Read too when an inhibitor asked for before arrives late.
88          hold.arrived.get();
89          if ready() {
90            hold.release();
91          }
92        }
93      })
94      .named(format!("Logind::delay_sleep_until (called at {at})"));
95  }
96
97  /// Turns the machine off, as logind's `PowerOff`. polkit may ask the
98  /// user first. A refusal is logged, and so is a call made before
99  /// logind is reached, which is dropped; the same holds for the other
100  /// power actions.
101  pub fn power_off(&self) {
102    self.manager("PowerOff");
103  }
104
105  /// Restarts the machine, as logind's `Reboot`.
106  pub fn reboot(&self) {
107    self.manager("Reboot");
108  }
109
110  /// Sends the machine to sleep, as logind's `Suspend`.
111  pub fn suspend(&self) {
112    self.manager("Suspend");
113  }
114
115  /// Hibernates the machine, as logind's `Hibernate`.
116  pub fn hibernate(&self) {
117    self.manager("Hibernate");
118  }
119
120  /// Calls the manager's `method` with `interactive` true.
121  fn manager(&self, method: &'static str) {
122    if let Some(service) = &self.service {
123      service.call(PATH, MANAGER, method, true);
124    }
125  }
126}
127
128/// One `delay_sleep_until`'s inhibitor.
129struct Hold {
130  /// The descriptor logind watches: closing it lets go.
131  fd: RefCell<Option<OwnedFd>>,
132  /// The generation of logind an `Inhibit` call under way went to.
133  asking: Cell<Option<u64>>,
134  /// Bumped when an inhibitor arrives, so one that arrives while the
135  /// machine is about to sleep is let go as `ready` says.
136  arrived: Signal<u32>,
137}
138
139impl Hold {
140  /// Asks logind for an inhibitor, unless one is held or asked of the
141  /// logind running now.
142  fn take(self: &Rc<Self>, service: &Rc<Service>) {
143    let Some((connection, generation)) = service.connection() else {
144      return;
145    };
146    if self.fd.borrow().is_some() || self.asking.get() == Some(generation) {
147      return;
148    }
149    self.asking.set(Some(generation));
150    let (hold, service) = (Rc::downgrade(self), Rc::clone(service));
151    let shared = Rc::clone(&service.shared);
152    shared.spawn(async move {
153      let why = "The shell gets ready for sleep";
154      let body = ("sleep", "crabshell", why, "delay");
155      let call = connection.call_method(Some(LOGIND), PATH, Some(MANAGER), "Inhibit", &body);
156      let fd = service
157        .shared
158        .timeout(CALL_TIMEOUT, call)
159        .await
160        .and_then(|reply| reply.body().deserialize::<zbus::OwnedFd>());
161      // Gone with its context, asked again of a logind that restarted,
162      // or from one that went: the descriptor closes here.
163      let Some(hold) = hold.upgrade() else {
164        return;
165      };
166      if hold.asking.get() != Some(generation) {
167        return;
168      }
169      hold.asking.set(None);
170      if service.connection().map(|(_, now)| now) != Some(generation) {
171        return;
172      }
173      match fd {
174        Ok(fd) => {
175          hold.fd.replace(Some(fd.into()));
176          hold
177            .arrived
178            .try_update(|count| *count = count.wrapping_add(1));
179        }
180        Err(error) => tracing::warn!(%error, "logind gave no inhibitor, so sleep won't wait"),
181      }
182    });
183  }
184
185  /// Lets go of the inhibitor, if one is held.
186  fn release(&self) {
187    drop(self.fd.take());
188  }
189}
190
191/// `cx.logind()`.
192pub(crate) fn logind(cx: &Cx) -> Logind {
193  match cx.service::<Service>() {
194    Some(service) => Logind {
195      sleeping: service.start(),
196      service: Some(service),
197      owner: cx.owner(),
198    },
199    None => {
200      static LOGGED: Once = Once::new();
201      LOGGED.call_once(|| {
202        tracing::warn!("cx.logind() needs the services the shell provides; it does nothing");
203      });
204      Logind {
205        service: None,
206        sleeping: cx.signal(false).read_only(),
207        owner: cx.owner(),
208      }
209    }
210  }
211}
212
213/// logind for one shell, followed from the first ask.
214pub(crate) struct Service {
215  shared: Rc<Shared>,
216  state: RefCell<Option<State>>,
217}
218
219struct State {
220  sleeping: Signal<bool>,
221  /// The bus, while logind runs, for its methods.
222  connection: Option<Connection>,
223  /// Whether `connection` is there, for the delays waiting on it.
224  connected: Signal<bool>,
225  generation: u64,
226}
227
228impl Service {
229  pub(crate) fn new(shared: Rc<Shared>) -> Service {
230    Service {
231      shared,
232      state: RefCell::new(None),
233    }
234  }
235
236  /// Starts following logind, once, and returns `preparing_for_sleep`.
237  pub(crate) fn start(self: &Rc<Self>) -> ReadSignal<bool> {
238    if let Some(state) = &*self.state.borrow() {
239      return state.sleeping.read_only();
240    }
241    let sleeping = self.shared.root.signal(false);
242    *self.state.borrow_mut() = Some(State {
243      sleeping,
244      connection: None,
245      connected: self.shared.root.signal(false),
246      generation: 0,
247    });
248    match self.shared.config.system_bus.clone() {
249      Some(address) => {
250        let follow = dbus::follow(Rc::clone(&self.shared), Rc::clone(self), address);
251        self.shared.spawn(follow);
252      }
253      None => tracing::info!("no system bus, so logind can't be reached"),
254    }
255    sleeping.read_only()
256  }
257
258  /// Whether logind is reached, for what waits to call it.
259  pub(crate) fn connected(&self) -> Option<Signal<bool>> {
260    Some(self.signals()?.1)
261  }
262
263  fn signals(&self) -> Option<(Signal<bool>, Signal<bool>)> {
264    let state = self.state.borrow();
265    state
266      .as_ref()
267      .map(|state| (state.sleeping, state.connected))
268  }
269
270  /// The bus while logind runs, with the generation it runs in.
271  pub(crate) fn connection(&self) -> Option<(Connection, u64)> {
272    let state = self.state.borrow();
273    let state = state.as_ref()?;
274    Some((state.connection.clone()?, state.generation))
275  }
276
277  /// Calls logind's `method` on `interface` at `path` with `body`, and
278  /// logs a failure.
279  pub(crate) fn call<B>(&self, path: &'static str, interface: &'static str, method: &str, body: B)
280  where
281    B: serde::Serialize + zbus::DynamicType + 'static,
282  {
283    let Some((connection, _)) = self.connection() else {
284      return tracing::info!(method, "logind isn't running, so nothing was asked of it");
285    };
286    let (shared, method) = (Rc::clone(&self.shared), method.to_owned());
287    self.shared.spawn(async move {
288      let call = connection.call_method(Some(LOGIND), path, Some(interface), &*method, &body);
289      if let Err(error) = shared.timeout(CALL_TIMEOUT, call).await {
290        tracing::warn!(%error, method, "logind refused");
291      }
292    });
293  }
294
295  /// Sets the backlight `name` to `value`, through the shell's session.
296  pub(crate) fn set_brightness(&self, name: &str, value: u32) {
297    let body = ("backlight".to_owned(), name.to_owned(), value);
298    self.call(SESSION_PATH, SESSION, "SetBrightness", body);
299  }
300
301  fn publish(&self, sleeping: bool, connected: bool) {
302    if let Some((sleeping_now, connected_now)) = self.signals() {
303      set_changed(sleeping_now, sleeping);
304      set_changed(connected_now, connected);
305    }
306  }
307}
308
309impl Daemon for Service {
310  const NAME: &'static str = LOGIND;
311
312  fn alive(&self) -> bool {
313    let state = self.state.borrow();
314    state
315      .as_ref()
316      .is_some_and(|state| state.sleeping.try_with(|_| ()).is_some())
317  }
318
319  fn clear(&self) -> u64 {
320    let generation = {
321      let mut state = self.state.borrow_mut();
322      let Some(state) = state.as_mut() else {
323        return 0;
324      };
325      state.connection = None;
326      state.generation += 1;
327      state.generation
328    };
329    self.publish(false, false);
330    generation
331  }
332
333  async fn read(self: Rc<Self>, connection: Connection, generation: u64) {
334    let body = (MANAGER, "PreparingForSleep");
335    let call = connection.call_method(Some(LOGIND), PATH, Some(PROPERTIES), "Get", &body);
336    let sleeping = self
337      .shared
338      .timeout(CALL_TIMEOUT, call)
339      .await
340      .and_then(|reply| bool::try_from(&reply.body().deserialize::<zbus::OwnedVariant>()?));
341    let sleeping = sleeping.unwrap_or_else(|error| {
342      tracing::warn!(%error, "couldn't read whether logind prepares for sleep");
343      false
344    });
345    {
346      let mut state = self.state.borrow_mut();
347      let Some(state) = state
348        .as_mut()
349        .filter(|state| state.generation == generation)
350      else {
351        return;
352      };
353      state.connection = Some(connection);
354    }
355    self.publish(sleeping, true);
356  }
357
358  fn signal(self: &Rc<Self>, _: &Connection, message: &Message) {
359    if message.header().member().map(|member| member.as_str()) != Some("PrepareForSleep") {
360      return;
361    }
362    match message.body().deserialize::<bool>() {
363      Ok(sleeping) => {
364        if let Some((signal, _)) = self.signals() {
365          set_changed(signal, sleeping);
366        }
367      }
368      Err(error) => tracing::warn!(%error, "a bad PrepareForSleep from logind"),
369    }
370  }
371
372  /// `PrepareForSleep` only: logind broadcasts every session and user
373  /// that comes and goes.
374  fn rules() -> Vec<String> {
375    vec![format!(
376      "type='signal',sender='{LOGIND}',path='{PATH}',interface='{MANAGER}',member='PrepareForSleep'"
377    )]
378  }
379}