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