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