tauri_brightness_core/lib.rs
1//! Cross-platform display brightness control.
2//!
3//! This crate is the engine behind the
4//! [`tauri-plugin-brightness`](https://crates.io/crates/tauri-plugin-brightness)
5//! plugin, and it has no dependency on Tauri, so it can be used from any Rust
6//! program.
7//!
8//! Three backends are supported and are selected automatically:
9//!
10//! | Backend | Mechanism | Notes |
11//! | --- | --- | --- |
12//! | [`Backend::Ddc`] | DDC/CI over I2C, in process | Fast, no external tools |
13//! | [`Backend::Ddcutil`] | The `ddcutil` command line tool | NVIDIA, docks, USB-DDC |
14//! | [`Backend::Backlight`] | Linux `/sys/class/backlight` | Laptop internal panels |
15//!
16//! A display is addressed by a [`MonitorId`], whose textual form is stable for
17//! the lifetime of a boot, for example `ddc-0` or `backlight-intel_backlight`.
18//!
19//! # Example
20//!
21//! ```no_run
22//! use tauri_brightness_core::{list_monitors, set_brightness};
23//!
24//! for monitor in list_monitors() {
25//! println!("{} is at {}%", monitor.name, monitor.brightness_percent());
26//! set_brightness(&monitor.id, 50)?;
27//! }
28//! # Ok::<(), tauri_brightness_core::Error>(())
29//! ```
30//!
31//! # Permissions
32//!
33//! On Linux, external monitors reach DDC/CI through `/dev/i2c-*`, which requires
34//! the `i2c-dev` kernel module and usually membership of the `i2c` group.
35//! Internal panels are controlled without privileges through the `logind` D-Bus
36//! interface. When nothing is detected, [`diagnose`] reports which of these is
37//! missing.
38
39#![deny(missing_docs)]
40#![deny(unsafe_code)]
41#![cfg_attr(docsrs, feature(doc_cfg))]
42
43mod error;
44mod models;
45
46mod backends;
47
48pub use error::{Error, Result};
49pub use models::{percent, raw_from_percent, Backend, Diagnostics, MonitorId, MonitorInfo};
50
51use backends::{backlight, ddc, ddcutil, diagnostics};
52
53/// Enumerates every display whose brightness can be controlled.
54///
55/// The DDC/CI backend is tried first because it stays in process. The
56/// `ddcutil` backend is only consulted when the first one found nothing, since
57/// it shares the same protocol but costs a process per call. Kernel backlight
58/// devices are always appended, because laptop panels are not DDC/CI devices.
59///
60/// Returns an empty list, rather than an error, when no display is found:
61/// callers that want an explanation should use [`diagnose`].
62pub fn list_monitors() -> Vec<MonitorInfo> {
63 let mut monitors = ddc::enumerate();
64
65 if monitors.is_empty() {
66 log::info!("the in-process DDC/CI backend found no display, trying `ddcutil`");
67 monitors = ddcutil::enumerate();
68 if !monitors.is_empty() {
69 log::info!("`ddcutil` found {} display(s)", monitors.len());
70 }
71 }
72
73 monitors.extend(backlight::enumerate());
74
75 if monitors.is_empty() {
76 log::warn!("no display with brightness control was detected by any backend");
77 }
78
79 monitors
80}
81
82/// Reads the brightness of the display identified by `id`.
83///
84/// The value is on the display's own scale, which is `0..=255` for DDC/CI
85/// displays and `0..=100` for the others. Use [`MonitorInfo::brightness_percent`]
86/// for a value that is comparable across displays.
87///
88/// # Errors
89///
90/// Returns [`Error::InvalidId`] when `id` is malformed and
91/// [`Error::DisplayNotFound`] when no backend knows that display.
92pub fn get_brightness(id: &str) -> Result<u8> {
93 match MonitorId::parse(id)? {
94 parsed if parsed.backend() == Backend::Backlight => backlight::get(parsed.locator()),
95 parsed if parsed.backend() == Backend::Ddcutil => ddcutil::get(locator_index(&parsed)?),
96 parsed => ddc::get(locator_index(&parsed)?),
97 }
98}
99
100/// Sets the brightness of the display identified by `id`.
101///
102/// The value is interpreted on a `0..=100` scale for DDC/CI displays that
103/// report a maximum of `100`, and on their own scale otherwise, which matches
104/// what the DDC/CI protocol expects.
105///
106/// # Errors
107///
108/// Returns [`Error::InvalidId`] when `id` is malformed and
109/// [`Error::DisplayNotFound`] when no backend knows that display.
110pub fn set_brightness(id: &str, value: u8) -> Result<()> {
111 match MonitorId::parse(id)? {
112 parsed if parsed.backend() == Backend::Backlight => backlight::set(parsed.locator(), value),
113 parsed if parsed.backend() == Backend::Ddcutil => {
114 ddcutil::set(locator_index(&parsed)?, value)
115 }
116 parsed => ddc::set(locator_index(&parsed)?, value),
117 }
118}
119
120/// Probes the system and explains why a display may not have been detected.
121///
122/// Never fails: every check degrades to a `false` or an explanatory string.
123pub fn diagnose() -> Diagnostics {
124 diagnostics::run()
125}
126
127/// Extracts the numeric index out of a display identifier.
128fn locator_index(id: &MonitorId) -> Result<usize> {
129 id.index().ok_or_else(|| Error::InvalidId(id.to_string()))
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135
136 #[test]
137 fn a_malformed_id_is_rejected_before_any_backend_is_touched() {
138 assert!(matches!(
139 get_brightness("not-a-display"),
140 Err(Error::InvalidId(_))
141 ));
142 assert!(matches!(
143 set_brightness("also-wrong", 50),
144 Err(Error::InvalidId(_))
145 ));
146 }
147
148 #[test]
149 fn a_ddc_id_without_an_index_is_rejected() {
150 assert!(matches!(
151 get_brightness("ddc-abc"),
152 Err(Error::InvalidId(_))
153 ));
154 }
155
156 #[test]
157 fn listing_displays_never_fails() {
158 // The result depends on the machine, but the call must not panic or
159 // return an error on a host without any controllable display.
160 let monitors = list_monitors();
161 for monitor in monitors {
162 assert!(!monitor.id.is_empty());
163 assert!(monitor.max >= 1);
164 assert!(monitor.brightness <= monitor.max);
165 }
166 }
167
168 #[test]
169 fn diagnostics_never_fail() {
170 let diagnostics = diagnose();
171 let _ = diagnostics.suggestions.len();
172 }
173}