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