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