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