crabshell_services/
brightness.rs1#[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
23const MAX_DEVICES: usize = 32;
25const MAX_READ: u64 = 64;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct Backlight {
31 pub name: String,
34 pub brightness: u32,
36 pub max_brightness: u32,
38}
39
40#[derive(Clone)]
42pub struct Brightness {
43 service: Option<Rc<Service>>,
45 devices: ReadSignal<Vec<Backlight>>,
46}
47
48impl Brightness {
49 pub fn devices(&self) -> ReadSignal<Vec<Backlight>> {
51 self.devices
52 }
53
54 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
77pub(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
95pub(crate) struct Service {
97 shared: Rc<Shared>,
98 logind: Rc<logind::Service>,
99 state: RefCell<Option<State>>,
100 pending: RefCell<BTreeMap<String, u32>>,
102 logged: Cell<bool>,
104}
105
106struct State {
107 devices: Signal<Vec<Backlight>>,
108 names: Vec<String>,
110 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 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 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 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 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
226fn 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
249fn 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}