Skip to main content

clairlune_platform/
lib.rs

1//! Platform layer: finding the monitors and setting the desktop wallpaper.
2//!
3//! The OS wallpaper APIs only set static images (PLAN.md section 2). A
4//! [`WallpaperHost`] wraps one OS's API: list the monitors with stable ids and
5//! physical sizes, read and set each monitor's wallpaper. [`detect`] picks the
6//! host for the running system. [`StillStore`] writes each still under a new
7//! file name, because some systems don't reload an unchanged path.
8//!
9//! Windows (`IDesktopWallpaper`, per monitor) and Linux (GNOME, Cinnamon,
10//! MATE, KDE Plasma, XFCE, Sway; one image for all monitors) are implemented;
11
12#[cfg(target_os = "linux")]
13mod linux;
14mod login;
15/// macOS: the wallpaper per screen, and Space changes.
16#[cfg(target_os = "macos")]
17pub mod macos;
18mod power;
19mod store;
20/// What this process uses (CPU time, memory), for the log.
21pub mod usage;
22#[cfg(windows)]
23mod windows;
24/// Live wallpaper windows in the desktop layer (Windows).
25#[cfg(windows)]
26pub mod windows_live;
27/// Compositors with wlr layer-shell: our own background surfaces.
28#[cfg(target_os = "linux")]
29pub mod wlr;
30
31pub use login::BACKGROUND_ARG;
32pub use power::on_battery;
33pub use store::{Snapshot, StillStore};
34
35/// Linux: the whole desktop as the one monitor wallpapers are made for (its
36/// largest output's size), without a wallpaper host (window managers with
37/// none can still play live).
38#[cfg(target_os = "linux")]
39pub fn linux_desktop_monitor() -> Monitor {
40    linux::desktop_monitor()
41}
42
43use std::fmt;
44use std::path::{Path, PathBuf};
45
46/// One monitor, in physical pixels.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct Monitor {
49    /// Stable id that survives reboots and re-plugging: the device path on
50    /// Windows. Per-monitor seeds and saved scenes key on it (PLAN.md 2.1).
51    pub id: String,
52    /// Position on the virtual screen (the origin can be negative).
53    pub x: i32,
54    pub y: i32,
55    pub width: u32,
56    pub height: u32,
57    pub primary: bool,
58}
59
60/// What a host can do.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct Capabilities {
63    /// A different image per monitor.
64    pub per_monitor: bool,
65    /// An animated host behind the desktop icons (later milestone).
66    pub live: bool,
67}
68
69#[derive(Debug)]
70pub enum PlatformError {
71    /// No host for this system yet, with a reason for the user.
72    Unsupported(String),
73    /// The OS call failed.
74    Os(String),
75    Io(std::io::Error),
76    /// The monitor id is not (or no longer) connected.
77    NoSuchMonitor(String),
78}
79
80impl fmt::Display for PlatformError {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        match self {
83            PlatformError::Unsupported(why) => write!(f, "not supported here: {why}"),
84            PlatformError::Os(e) => write!(f, "system call failed: {e}"),
85            PlatformError::Io(e) => write!(f, "{e}"),
86            PlatformError::NoSuchMonitor(id) => write!(f, "no connected monitor `{id}`"),
87        }
88    }
89}
90
91impl std::error::Error for PlatformError {}
92
93impl From<std::io::Error> for PlatformError {
94    fn from(e: std::io::Error) -> Self {
95        PlatformError::Io(e)
96    }
97}
98
99/// One system's wallpaper API.
100pub trait WallpaperHost {
101    /// Short name for logs and the settings screen, e.g. `windows-desktop-wallpaper`.
102    fn name(&self) -> &'static str;
103    fn capabilities(&self) -> Capabilities;
104    /// Connected monitors, primary first.
105    fn monitors(&self) -> Result<Vec<Monitor>, PlatformError>;
106    /// The image currently set on a monitor, if any (a solid colour has none).
107    fn current(&self, monitor: &Monitor) -> Result<Option<PathBuf>, PlatformError>;
108    /// Sets a still image on one monitor. The path must be absolute, and the
109    /// image should already be the monitor's size.
110    fn set_static(&self, monitor: &Monitor, path: &Path) -> Result<(), PlatformError>;
111    /// Everything needed to put the current wallpaper back later.
112    fn snapshot(&self) -> Result<Snapshot, PlatformError>;
113    /// Puts a snapshot back. Monitors that are gone are skipped.
114    fn restore(&self, snapshot: &Snapshot) -> Result<(), PlatformError>;
115}
116
117/// The host for the running system.
118pub fn detect() -> Result<Box<dyn WallpaperHost>, PlatformError> {
119    #[cfg(windows)]
120    {
121        Ok(Box::new(windows::WindowsHost::new()?))
122    }
123    #[cfg(target_os = "linux")]
124    {
125        Ok(Box::new(linux::LinuxHost::new()?))
126    }
127    #[cfg(target_os = "macos")]
128    {
129        Ok(Box::new(macos::MacHost::new()?))
130    }
131    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
132    {
133        Err(PlatformError::Unsupported(format!(
134            "setting the wallpaper on {} arrives in a later milestone",
135            std::env::consts::OS
136        )))
137    }
138}
139
140/// The per-user local data directory: Local AppData on Windows,
141/// `~/Library/Application Support` on macOS, `$XDG_DATA_HOME` (or
142/// `~/.local/share`) elsewhere.
143pub fn local_data_dir() -> Option<PathBuf> {
144    #[cfg(windows)]
145    {
146        windows::local_app_data()
147    }
148    #[cfg(target_os = "macos")]
149    {
150        home_dir().map(|h| h.join("Library").join("Application Support"))
151    }
152    #[cfg(all(unix, not(target_os = "macos")))]
153    {
154        std::env::var_os("XDG_DATA_HOME")
155            .map(PathBuf::from)
156            .filter(|p| p.is_absolute())
157            .or_else(|| home_dir().map(|h| h.join(".local").join("share")))
158    }
159}
160
161/// The per-user configuration directory: Roaming AppData on Windows,
162/// `~/Library/Application Support` on macOS, `$XDG_CONFIG_HOME` (or
163/// `~/.config`) elsewhere.
164pub fn config_dir() -> Option<PathBuf> {
165    #[cfg(windows)]
166    {
167        windows::roaming_app_data()
168    }
169    #[cfg(target_os = "macos")]
170    {
171        home_dir().map(|h| h.join("Library").join("Application Support"))
172    }
173    #[cfg(all(unix, not(target_os = "macos")))]
174    {
175        std::env::var_os("XDG_CONFIG_HOME")
176            .map(PathBuf::from)
177            .filter(|p| p.is_absolute())
178            .or_else(|| home_dir().map(|h| h.join(".config")))
179    }
180}
181
182/// The user's Pictures folder (exports go to `Pictures/Clairlune`).
183pub fn pictures_dir() -> Option<PathBuf> {
184    #[cfg(windows)]
185    {
186        windows::pictures()
187    }
188    #[cfg(unix)]
189    {
190        home_dir().map(|h| h.join("Pictures"))
191    }
192}
193
194/// Clairlune's data directory (stills, archive, logs): `<local data>/clairlune`.
195pub fn app_data_dir() -> Option<PathBuf> {
196    local_data_dir().map(|d| d.join(clairlune_scene::ident::APP_ID))
197}
198
199/// Clairlune's configuration directory: `<config>/clairlune`.
200pub fn app_config_dir() -> Option<PathBuf> {
201    config_dir().map(|d| d.join(clairlune_scene::ident::APP_ID))
202}
203
204/// The command line that starts `exe` at login, quietly.
205#[cfg_attr(not(windows), allow(dead_code))]
206fn login_command(exe: &Path) -> String {
207    format!("\"{}\" {BACKGROUND_ARG}", exe.display())
208}
209
210/// The command 0.12 and older registered: no background argument.
211#[cfg_attr(not(windows), allow(dead_code))]
212fn old_login_command(exe: &Path) -> String {
213    format!("\"{}\"", exe.display())
214}
215
216/// Whether `exe` is registered to start at login; `None` where this build
217/// can't manage login items.
218pub fn start_at_login(exe: &Path) -> Option<bool> {
219    #[cfg(windows)]
220    {
221        let (want, old) = (login_command(exe), old_login_command(exe));
222        Some(
223            windows::start_at_login_command()
224                .is_some_and(|c| c.eq_ignore_ascii_case(&want) || c.eq_ignore_ascii_case(&old)),
225        )
226    }
227    #[cfg(any(target_os = "linux", target_os = "macos"))]
228    {
229        Some(login::registered(exe))
230    }
231    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
232    {
233        let _ = exe;
234        None
235    }
236}
237
238/// Whether the login entry for `exe` is one from 0.12 or older (Windows),
239/// which starts it without [`BACKGROUND_ARG`].
240pub fn login_entry_outdated(exe: &Path) -> bool {
241    #[cfg(windows)]
242    {
243        windows::start_at_login_command()
244            .is_some_and(|c| c.eq_ignore_ascii_case(&old_login_command(exe)))
245    }
246    #[cfg(not(windows))]
247    {
248        let _ = exe;
249        false
250    }
251}
252
253/// Registers or removes `exe` as a login item (per user, no admin rights),
254/// started with [`BACKGROUND_ARG`].
255pub fn set_start_at_login(exe: &Path, enable: bool) -> Result<(), PlatformError> {
256    #[cfg(windows)]
257    {
258        let cmd = login_command(exe);
259        windows::set_start_at_login_command(enable.then_some(cmd.as_str()))
260    }
261    #[cfg(any(target_os = "linux", target_os = "macos"))]
262    {
263        login::set(exe, enable)
264    }
265    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
266    {
267        let _ = (exe, enable);
268        Err(PlatformError::Unsupported(
269            "starting at login isn't supported on this system".into(),
270        ))
271    }
272}
273
274/// Whether the system asks apps for a dark appearance, when that is known.
275pub fn system_prefers_dark() -> Option<bool> {
276    #[cfg(windows)]
277    {
278        windows::apps_use_dark_theme()
279    }
280    #[cfg(not(windows))]
281    {
282        None
283    }
284}
285
286#[cfg(unix)]
287fn home_dir() -> Option<PathBuf> {
288    std::env::var_os("HOME")
289        .filter(|h| !h.is_empty())
290        .map(PathBuf::from)
291}
292
293/// Makes the process aware of each monitor's DPI so sizes come back in physical
294/// pixels. Call once, before any window or monitor query. A no-op where it
295/// does not apply.
296pub fn init_dpi_awareness() {
297    #[cfg(windows)]
298    windows::init_dpi_awareness();
299}
300
301/// Lets a GUI-built exe print to the terminal it was started from (Windows;
302/// elsewhere the process already shares it).
303#[cfg(windows)]
304pub fn attach_parent_console() {
305    windows::attach_parent_console();
306}
307
308/// Sorts monitors primary first, then left to right, top to bottom, so the
309/// order is the same on every run.
310#[cfg(any(windows, target_os = "macos", test))]
311pub(crate) fn sort_monitors(monitors: &mut [Monitor]) {
312    monitors.sort_by_key(|m| (!m.primary, m.x, m.y));
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    fn m(id: &str, x: i32, primary: bool) -> Monitor {
320        Monitor {
321            id: id.into(),
322            x,
323            y: 0,
324            width: 1920,
325            height: 1080,
326            primary,
327        }
328    }
329
330    #[test]
331    fn primary_first_then_left_to_right() {
332        let mut v = vec![m("c", 1920, false), m("b", -1920, false), m("a", 0, true)];
333        sort_monitors(&mut v);
334        let ids: Vec<&str> = v.iter().map(|m| m.id.as_str()).collect();
335        assert_eq!(ids, ["a", "b", "c"]);
336    }
337}