Skip to main content

crabshell_services/
brightness.rs

1//! Screen brightness: the backlights in sysfs, set through logind so no
2//! root is needed.
3
4#[cfg(test)]
5mod tests;
6
7use std::cell::{Cell, RefCell};
8use std::collections::{BTreeMap, HashSet};
9use std::io::Read;
10use std::path::Path;
11use std::rc::{Rc, Weak};
12use std::sync::Once;
13
14use crabshell_reactive::{ReadSignal, Signal, untrack};
15use crabshell_ui::Cx;
16use inotify::WatchMask;
17
18use crate::Shared;
19use crate::dbus::set_changed;
20use crate::logind;
21use crate::watch::{self, Watch};
22
23/// The most backlights kept.
24const MAX_DEVICES: usize = 32;
25/// The most bytes read from one sysfs file: a number and a newline.
26const MAX_READ: u64 = 64;
27
28/// A backlight in `/sys/class/backlight`.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct Backlight {
31  /// Its sysfs name, such as `intel_backlight`, which
32  /// [`Brightness::set`] takes.
33  pub name: String,
34  /// How bright it is, from 0 to `max_brightness`.
35  pub brightness: u32,
36  /// The brightest it goes.
37  pub max_brightness: u32,
38}
39
40/// Screen brightness, from `cx.brightness()`. Cloning it is cheap.
41#[derive(Clone)]
42pub struct Brightness {
43  /// `None` when the shell provided no services.
44  service: Option<Rc<Service>>,
45  devices: ReadSignal<Vec<Backlight>>,
46}
47
48impl Brightness {
49  /// Every backlight, by name. Empty on a machine with none.
50  pub fn devices(&self) -> ReadSignal<Vec<Backlight>> {
51    self.devices
52  }
53
54  /// Asks logind to set the backlight `name` to `value`, held to its
55  /// `max_brightness`. It shows in [`devices`](Self::devices) once the
56  /// kernel has it. Before logind is reached, as from the root closure,
57  /// the latest value for each backlight waits and is sent once it is.
58  /// An unknown name or a refusal is logged, and so, once, is a value
59  /// waiting for a logind that isn't there.
60  pub fn set(&self, name: &str, value: u32) {
61    let Some(service) = &self.service else {
62      return;
63    };
64    let max = untrack(|| {
65      self.devices.try_with(|devices| {
66        let device = devices.iter().find(|device| device.name == name)?;
67        Some(device.max_brightness)
68      })
69    });
70    match max.flatten() {
71      Some(max) => service.set(name, value.min(max)),
72      None => tracing::warn!(name, "no such backlight, so its brightness wasn't set"),
73    }
74  }
75}
76
77/// `cx.brightness()`.
78pub(crate) fn brightness(cx: &Cx) -> Brightness {
79  let Some(service) = cx.service::<Service>() else {
80    static LOGGED: Once = Once::new();
81    LOGGED.call_once(|| {
82      tracing::warn!("cx.brightness() needs the services the shell provides; it stays empty");
83    });
84    return Brightness {
85      service: None,
86      devices: cx.signal(Vec::new()).read_only(),
87    };
88  };
89  Brightness {
90    devices: service.start(),
91    service: Some(service),
92  }
93}
94
95/// The backlights for one shell, read from the first ask.
96pub(crate) struct Service {
97  shared: Rc<Shared>,
98  logind: Rc<logind::Service>,
99  state: RefCell<Option<State>>,
100  /// The latest value asked for each backlight before logind is reached.
101  pending: RefCell<BTreeMap<String, u32>>,
102  /// Whether a value that couldn't go yet was logged.
103  logged: Cell<bool>,
104}
105
106struct State {
107  devices: Signal<Vec<Backlight>>,
108  /// The backlights' names, as listed at the start.
109  names: Vec<String>,
110  /// Those whose files were logged as unreadable, so each logs once.
111  logged: HashSet<String>,
112  _watches: Vec<Watch>,
113}
114
115impl Service {
116  pub(crate) fn new(shared: Rc<Shared>, logind: Rc<logind::Service>) -> Service {
117    Service {
118      shared,
119      logind,
120      state: RefCell::new(None),
121      pending: RefCell::default(),
122      logged: Cell::new(false),
123    }
124  }
125
126  /// Sends `value` for the backlight `name`, or keeps it until logind is
127  /// reached.
128  fn set(&self, name: &str, value: u32) {
129    if self.logind.connection().is_some() {
130      return self.logind.set_brightness(name, value);
131    }
132    if self.shared.config.system_bus.is_none() {
133      if !self.logged.replace(true) {
134        tracing::info!("no system bus, so logind can't set a brightness");
135      }
136      return;
137    }
138    self.pending.borrow_mut().insert(name.to_owned(), value);
139    if !self.logged.replace(true) {
140      tracing::info!("logind isn't reached yet, so the brightness is set once it is");
141    }
142  }
143
144  fn start(self: &Rc<Self>) -> ReadSignal<Vec<Backlight>> {
145    if let Some(state) = &*self.state.borrow() {
146      return state.devices.read_only();
147    }
148    // For `set`, so logind is reached before a config asks.
149    self.logind.start();
150    if let Some(connected) = self.logind.connected() {
151      let service = Rc::downgrade(self);
152      self.shared.root.effect(move || {
153        if connected.get()
154          && let Some(service) = Weak::upgrade(&service)
155        {
156          for (name, value) in service.pending.take() {
157            service.logind.set_brightness(&name, value);
158          }
159        }
160      });
161    }
162    let root = &self.shared.config.backlight;
163    let names = names(root);
164    let watches = names
165      .iter()
166      .filter_map(|name| {
167        // The kernel says a brightness changed here, whether a program
168        // wrote `brightness` or the firmware moved it on a key.
169        let path = root.join(name).join("actual_brightness");
170        let service = Rc::downgrade(self);
171        let on_change = move |_: &watch::Change| {
172          if let Some(service) = Weak::upgrade(&service) {
173            service.read();
174          }
175        };
176        watch::watch(&self.shared, &path, WatchMask::MODIFY, on_change)
177          .inspect_err(|error| {
178            tracing::warn!(%error, path = %path.display(), "can't follow this backlight");
179          })
180          .ok()
181      })
182      .collect();
183    let devices = self.shared.root.signal(Vec::new());
184    *self.state.borrow_mut() = Some(State {
185      devices,
186      names,
187      logged: HashSet::new(),
188      _watches: watches,
189    });
190    self.read();
191    devices.read_only()
192  }
193
194  /// Reads every backlight again and shows what changed.
195  fn read(&self) {
196    let root = &self.shared.config.backlight;
197    let read = {
198      let mut state = self.state.borrow_mut();
199      let Some(state) = state.as_mut() else {
200        return;
201      };
202      let mut devices = Vec::new();
203      for name in &state.names {
204        let dir = root.join(name);
205        let read = read_value(&dir.join("brightness"))
206          .and_then(|brightness| Ok((brightness, read_value(&dir.join("max_brightness"))?)));
207        match read {
208          Ok((brightness, max_brightness)) => devices.push(Backlight {
209            name: name.clone(),
210            brightness: brightness.min(max_brightness),
211            max_brightness,
212          }),
213          Err(error) => {
214            if state.logged.insert(name.clone()) {
215              tracing::warn!(name, %error, "can't read this backlight, so it isn't listed");
216            }
217          }
218        }
219      }
220      (state.devices, devices)
221    };
222    set_changed(read.0, read.1);
223  }
224}
225
226/// The backlights' names under `root`, sorted, at most [`MAX_DEVICES`].
227fn names(root: &Path) -> Vec<String> {
228  let entries = match std::fs::read_dir(root) {
229    Ok(entries) => entries,
230    Err(error) => {
231      tracing::info!(%error, root = %root.display(), "no backlights");
232      return Vec::new();
233    }
234  };
235  let mut names: Vec<String> = entries
236    .filter_map(|entry| entry.ok()?.file_name().into_string().ok())
237    .collect();
238  names.sort();
239  if names.len() > MAX_DEVICES {
240    tracing::warn!(
241      count = names.len(),
242      "more backlights than {MAX_DEVICES}; the rest aren't listed"
243    );
244    names.truncate(MAX_DEVICES);
245  }
246  names
247}
248
249/// The number in the sysfs file at `path`.
250fn read_value(path: &Path) -> std::io::Result<u32> {
251  let mut text = String::new();
252  std::fs::File::open(path)?
253    .take(MAX_READ + 1)
254    .read_to_string(&mut text)?;
255  if text.len() as u64 > MAX_READ {
256    return Err(std::io::Error::other(format!(
257      "{} is over {MAX_READ} bytes",
258      path.display()
259    )));
260  }
261  text
262    .trim()
263    .parse()
264    .map_err(|error| std::io::Error::other(format!("{} holds {text:?}: {error}", path.display())))
265}