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