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