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 macOS (`NSWorkspace`, per
10//! screen) are implemented. Elsewhere [`detect`] says the wallpaper isn't
11//! set here: the scenes still render (`clairlune-cli render`, `gif`).
12
13mod login;
14/// macOS: the wallpaper per screen, and Space changes.
15#[cfg(target_os = "macos")]
16pub mod macos;
17mod power;
18mod store;
19/// What this process uses (CPU time, memory), for the log.
20pub mod usage;
21#[cfg(windows)]
22mod windows;
23/// Live wallpaper windows in the desktop layer (Windows).
24#[cfg(windows)]
25pub mod windows_live;
26
27pub use login::BACKGROUND_ARG;
28pub use power::on_battery;
29pub use store::{Snapshot, StillStore};
30
31use std::fmt;
32use std::path::{Path, PathBuf};
33
34/// One monitor, in physical pixels.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct Monitor {
37    /// Stable id that survives reboots and re-plugging: the device path on
38    /// Windows. Per-monitor seeds and saved scenes key on it (PLAN.md 2.1).
39    pub id: String,
40    /// Position on the virtual screen (the origin can be negative).
41    pub x: i32,
42    pub y: i32,
43    pub width: u32,
44    pub height: u32,
45    pub primary: bool,
46}
47
48/// What a host can do.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub struct Capabilities {
51    /// A different image per monitor.
52    pub per_monitor: bool,
53    /// An animated host behind the desktop icons (later milestone).
54    pub live: bool,
55}
56
57#[derive(Debug)]
58pub enum PlatformError {
59    /// No host for this system yet, with a reason for the user.
60    Unsupported(String),
61    /// The OS call failed.
62    Os(String),
63    Io(std::io::Error),
64    /// The monitor id is not (or no longer) connected.
65    NoSuchMonitor(String),
66}
67
68impl fmt::Display for PlatformError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self {
71            PlatformError::Unsupported(why) => write!(f, "not supported here: {why}"),
72            PlatformError::Os(e) => write!(f, "system call failed: {e}"),
73            PlatformError::Io(e) => write!(f, "{e}"),
74            PlatformError::NoSuchMonitor(id) => write!(f, "no connected monitor `{id}`"),
75        }
76    }
77}
78
79impl std::error::Error for PlatformError {}
80
81impl From<std::io::Error> for PlatformError {
82    fn from(e: std::io::Error) -> Self {
83        PlatformError::Io(e)
84    }
85}
86
87/// One system's wallpaper API.
88pub trait WallpaperHost {
89    /// Short name for logs and the settings screen, e.g. `windows-desktop-wallpaper`.
90    fn name(&self) -> &'static str;
91    fn capabilities(&self) -> Capabilities;
92    /// Connected monitors, primary first.
93    fn monitors(&self) -> Result<Vec<Monitor>, PlatformError>;
94    /// The image currently set on a monitor, if any (a solid colour has none).
95    fn current(&self, monitor: &Monitor) -> Result<Option<PathBuf>, PlatformError>;
96    /// Sets a still image on one monitor. The path must be absolute, and the
97    /// image should already be the monitor's size.
98    fn set_static(&self, monitor: &Monitor, path: &Path) -> Result<(), PlatformError>;
99    /// Everything needed to put the current wallpaper back later.
100    fn snapshot(&self) -> Result<Snapshot, PlatformError>;
101    /// Puts a snapshot back. Monitors that are gone are skipped.
102    fn restore(&self, snapshot: &Snapshot) -> Result<(), PlatformError>;
103}
104
105/// The host for the running system.
106pub fn detect() -> Result<Box<dyn WallpaperHost>, PlatformError> {
107    #[cfg(windows)]
108    {
109        Ok(Box::new(windows::WindowsHost::new()?))
110    }
111    #[cfg(target_os = "macos")]
112    {
113        Ok(Box::new(macos::MacHost::new()?))
114    }
115    #[cfg(not(any(windows, target_os = "macos")))]
116    {
117        Err(PlatformError::Unsupported(format!(
118            "Clairlune sets the wallpaper on Windows and macOS, not on {}; `render` and `gif` make the images",
119            std::env::consts::OS
120        )))
121    }
122}
123
124/// The per-user local data directory: Local AppData on Windows,
125/// `~/Library/Application Support` on macOS, `$XDG_DATA_HOME` (or
126/// `~/.local/share`) elsewhere.
127pub fn local_data_dir() -> Option<PathBuf> {
128    #[cfg(windows)]
129    {
130        windows::local_app_data()
131    }
132    #[cfg(target_os = "macos")]
133    {
134        home_dir().map(|h| h.join("Library").join("Application Support"))
135    }
136    #[cfg(all(unix, not(target_os = "macos")))]
137    {
138        std::env::var_os("XDG_DATA_HOME")
139            .map(PathBuf::from)
140            .filter(|p| p.is_absolute())
141            .or_else(|| home_dir().map(|h| h.join(".local").join("share")))
142    }
143}
144
145/// The per-user configuration directory: Roaming AppData on Windows,
146/// `~/Library/Application Support` on macOS, `$XDG_CONFIG_HOME` (or
147/// `~/.config`) elsewhere.
148pub fn config_dir() -> Option<PathBuf> {
149    #[cfg(windows)]
150    {
151        windows::roaming_app_data()
152    }
153    #[cfg(target_os = "macos")]
154    {
155        home_dir().map(|h| h.join("Library").join("Application Support"))
156    }
157    #[cfg(all(unix, not(target_os = "macos")))]
158    {
159        std::env::var_os("XDG_CONFIG_HOME")
160            .map(PathBuf::from)
161            .filter(|p| p.is_absolute())
162            .or_else(|| home_dir().map(|h| h.join(".config")))
163    }
164}
165
166/// The user's Pictures folder (exports go to `Pictures/Clairlune`).
167pub fn pictures_dir() -> Option<PathBuf> {
168    #[cfg(windows)]
169    {
170        windows::pictures()
171    }
172    #[cfg(unix)]
173    {
174        home_dir().map(|h| h.join("Pictures"))
175    }
176}
177
178/// Clairlune's data directory (stills, archive, logs): `<local data>/clairlune`.
179pub fn app_data_dir() -> Option<PathBuf> {
180    local_data_dir().map(|d| d.join(clairlune_scene::ident::APP_ID))
181}
182
183/// Clairlune's configuration directory: `<config>/clairlune`.
184pub fn app_config_dir() -> Option<PathBuf> {
185    config_dir().map(|d| d.join(clairlune_scene::ident::APP_ID))
186}
187
188/// The command line that starts `exe` at login, quietly.
189#[cfg_attr(not(windows), allow(dead_code))]
190fn login_command(exe: &Path) -> String {
191    format!("\"{}\" {BACKGROUND_ARG}", exe.display())
192}
193
194/// The command 0.12 and older registered: no background argument.
195#[cfg_attr(not(windows), allow(dead_code))]
196fn old_login_command(exe: &Path) -> String {
197    format!("\"{}\"", exe.display())
198}
199
200/// Whether `exe` is registered to start at login; `None` where this build
201/// can't manage login items.
202pub fn start_at_login(exe: &Path) -> Option<bool> {
203    #[cfg(windows)]
204    {
205        let (want, old) = (login_command(exe), old_login_command(exe));
206        Some(
207            windows::start_at_login_command()
208                .is_some_and(|c| c.eq_ignore_ascii_case(&want) || c.eq_ignore_ascii_case(&old)),
209        )
210    }
211    #[cfg(target_os = "macos")]
212    {
213        Some(login::registered(exe))
214    }
215    #[cfg(not(any(windows, target_os = "macos")))]
216    {
217        let _ = exe;
218        None
219    }
220}
221
222/// Whether the login entry for `exe` is one from 0.12 or older (Windows),
223/// which starts it without [`BACKGROUND_ARG`].
224pub fn login_entry_outdated(exe: &Path) -> bool {
225    #[cfg(windows)]
226    {
227        windows::start_at_login_command()
228            .is_some_and(|c| c.eq_ignore_ascii_case(&old_login_command(exe)))
229    }
230    #[cfg(not(windows))]
231    {
232        let _ = exe;
233        false
234    }
235}
236
237/// Start at login is registered but switched off where only the user can
238/// switch it on: macOS's System Settings > General > Login Items, or
239/// Windows' Settings > Apps > Startup. `false` elsewhere.
240pub fn start_at_login_needs_approval(exe: &Path) -> bool {
241    #[cfg(target_os = "macos")]
242    {
243        login::needs_approval(exe)
244    }
245    #[cfg(windows)]
246    {
247        let _ = exe;
248        windows::startup_switched_off()
249    }
250    #[cfg(not(any(target_os = "macos", windows)))]
251    {
252        let _ = exe;
253        false
254    }
255}
256
257/// Opens where the user switches start at login on: System Settings >
258/// General > Login Items (macOS), Settings > Apps > Startup (Windows).
259/// Nothing elsewhere.
260pub fn open_login_items_settings() {
261    #[cfg(target_os = "macos")]
262    login::open_login_items();
263    #[cfg(windows)]
264    let _ = windows::open_url("ms-settings:startupapps");
265}
266
267/// Registers or removes `exe` as a login item (per user, no admin rights),
268/// started with [`BACKGROUND_ARG`].
269pub fn set_start_at_login(exe: &Path, enable: bool) -> Result<(), PlatformError> {
270    #[cfg(windows)]
271    {
272        let cmd = login_command(exe);
273        windows::set_start_at_login_command(enable.then_some(cmd.as_str()))
274    }
275    #[cfg(target_os = "macos")]
276    {
277        login::set(exe, enable)
278    }
279    #[cfg(not(any(windows, target_os = "macos")))]
280    {
281        let _ = (exe, enable);
282        Err(PlatformError::Unsupported(
283            "starting at login isn't supported on this system".into(),
284        ))
285    }
286}
287
288/// Whether the taskbar (where the tray icon sits) is light, when that is
289/// known: Windows only (macOS tints a template icon itself).
290pub fn taskbar_is_light() -> Option<bool> {
291    #[cfg(windows)]
292    {
293        windows::taskbar_is_light()
294    }
295    #[cfg(not(windows))]
296    {
297        None
298    }
299}
300
301/// Whether the system asks apps for a dark appearance, when that is known.
302pub fn system_prefers_dark() -> Option<bool> {
303    #[cfg(windows)]
304    {
305        windows::apps_use_dark_theme()
306    }
307    #[cfg(not(windows))]
308    {
309        None
310    }
311}
312
313#[cfg(unix)]
314fn home_dir() -> Option<PathBuf> {
315    std::env::var_os("HOME")
316        .filter(|h| !h.is_empty())
317        .map(PathBuf::from)
318}
319
320/// Makes the process aware of each monitor's DPI so sizes come back in physical
321/// pixels. Call once, before any window or monitor query. A no-op where it
322/// does not apply.
323pub fn init_dpi_awareness() {
324    #[cfg(windows)]
325    windows::init_dpi_awareness();
326}
327
328/// Opens a web page in the default browser (`&` and `%` in it are safe).
329pub fn open_url(url: &str) -> Result<(), String> {
330    #[cfg(windows)]
331    {
332        windows::open_url(url)
333    }
334    #[cfg(not(windows))]
335    {
336        let opener = if cfg!(target_os = "macos") {
337            "open"
338        } else {
339            "xdg-open"
340        };
341        std::process::Command::new(opener)
342            .arg(url)
343            .spawn()
344            .map(|_| ())
345            .map_err(|e| e.to_string())
346    }
347}
348
349/// Lets a GUI-built exe print to the terminal it was started from (Windows;
350/// elsewhere the process already shares it).
351#[cfg(windows)]
352pub fn attach_parent_console() {
353    windows::attach_parent_console();
354}
355
356/// Sorts monitors primary first, then left to right, top to bottom, so the
357/// order is the same on every run.
358#[cfg(any(windows, target_os = "macos", test))]
359pub(crate) fn sort_monitors(monitors: &mut [Monitor]) {
360    monitors.sort_by_key(|m| (!m.primary, m.x, m.y));
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    fn m(id: &str, x: i32, primary: bool) -> Monitor {
368        Monitor {
369            id: id.into(),
370            x,
371            y: 0,
372            width: 1920,
373            height: 1080,
374            primary,
375        }
376    }
377
378    #[test]
379    fn primary_first_then_left_to_right() {
380        let mut v = vec![m("c", 1920, false), m("b", -1920, false), m("a", 0, true)];
381        sort_monitors(&mut v);
382        let ids: Vec<&str> = v.iter().map(|m| m.id.as_str()).collect();
383        assert_eq!(ids, ["a", "b", "c"]);
384    }
385}