#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod apply;
mod archive;
mod diagnostics;
mod icon;
mod ipc;
mod library;
mod live;
mod settings;
mod sun;
mod timefmt;
mod timeline;
mod tokens;
mod tray;
mod ui;
use apply::{Done, Job};
use clairlune_scene::{APP_NAME, Theme};
use settings::Settings;
use std::hash::BuildHasher;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant, SystemTime};
use winit::application::ApplicationHandler;
use winit::event::{StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy};
use winit::window::WindowId;
const CHECK_EVERY: Duration = Duration::from_secs(20);
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
struct PoolState {
#[serde(default)]
positions: std::collections::BTreeMap<String, usize>,
#[serde(default)]
last: std::collections::BTreeMap<String, String>,
}
type MonitorKey = (Option<String>, i32, i32, u32, u32);
fn monitor_layout(event_loop: &ActiveEventLoop) -> Vec<MonitorKey> {
let mut v: Vec<MonitorKey> = event_loop
.available_monitors()
.map(|m| {
let (p, s) = (m.position(), m.size());
(m.name(), p.x, p.y, s.width, s.height)
})
.collect();
v.sort();
v
}
const TIMELINE_LEAD: jiff::SignedDuration = jiff::SignedDuration::from_secs(4);
const MONITOR_SETTLE: Duration = Duration::from_millis(1500);
const MONITOR_POLL: Duration = Duration::from_secs(5);
enum AppEvent {
Menu(tray_icon::menu::MenuEvent),
Done(Done),
OpenSettings,
LiveFrame,
}
struct App {
settings: Settings,
settings_path: PathBuf,
settings_stamp: Option<SystemTime>,
data_dir: PathBuf,
jobs: mpsc::Sender<Job>,
busy: bool,
next_change: Option<Instant>,
next_check: Instant,
shown_theme: Option<Theme>,
shown_journey: bool,
scrolling_ok: bool,
renew: Option<(String, u64)>,
current: Option<PathBuf>,
current_theme: Option<Theme>,
current_buddy: Option<bool>,
status: ui::view::Status,
tray: Option<tray::Tray>,
live: live::Live,
metronome: Arc<AtomicU64>,
#[cfg(windows)]
watcher: Option<clairlune_platform::windows_live::SystemWatcher>,
#[cfg(target_os = "macos")]
spaces: clairlune_platform::macos::SpaceWatcher,
monitor_layout: Option<Vec<MonitorKey>>,
monitors_changed_at: Option<Instant>,
next_monitor_poll: Instant,
timeline: timeline::Timeline,
timeline_path: PathBuf,
timeline_stamp: Option<SystemTime>,
timeline_since: Option<jiff::Timestamp>,
timeline_applied: Option<timeline::Slot>,
timeline_next: Option<jiff::Timestamp>,
timeline_generate: bool,
manual_until: Option<jiff::Timestamp>,
apply_at: Option<Instant>,
pools: PoolState,
settings_window: Option<ui::UiWindow>,
library_window: Option<ui::UiWindow>,
timeline_window: Option<ui::UiWindow>,
archive_window: Option<ui::UiWindow>,
archive_items: Vec<archive::Entry>,
library_items: Vec<library::Item>,
library_uses: std::collections::BTreeMap<String, Vec<String>>,
last_section: ui::view::Section,
ui_test: Option<UiTest>,
}
struct UiTest {
out: PathBuf,
steps: Vec<(Duration, UiStep)>,
started: Instant,
next: usize,
}
#[derive(Clone, Copy)]
enum UiStep {
Open(Theme, ui::view::Section),
OpenLibrary,
OpenTimeline(Theme, usize, usize),
CloseTimeline,
OpenArchive,
CloseArchive,
Screenshot(&'static str),
Close,
CloseLibrary,
Exit,
}
impl UiTest {
fn new(out: PathBuf) -> Self {
use ui::view::Section;
let ms = Duration::from_millis;
let mut steps = Vec::new();
let cycles = [
(Theme::Dark, Section::Rotation, "settings-dark-rotation.png"),
(Theme::Light, Section::Buddy, "settings-light-buddy.png"),
(Theme::Dark, Section::Live, "settings-dark-live.png"),
(Theme::Dark, Section::Content, "settings-dark-content.png"),
];
for (i, (theme, section, shot)) in cycles.into_iter().enumerate() {
let t0 = 1500 * i as u64;
steps.push((ms(t0), UiStep::Open(theme, section)));
steps.push((ms(t0 + 700), UiStep::Screenshot(shot)));
steps.push((ms(t0 + 1200), UiStep::Close));
}
steps.push((ms(6300), UiStep::OpenLibrary));
steps.push((ms(7100), UiStep::Screenshot("library.png")));
steps.push((ms(7600), UiStep::CloseLibrary));
let timelines = [
(Theme::Dark, 0, 1, "timeline-dark.png"),
(Theme::Light, 0, 4, "timeline-light.png"),
];
for (i, (theme, day, index, shot)) in timelines.into_iter().enumerate() {
let t0 = 8100 + 1700 * i as u64;
steps.push((ms(t0), UiStep::OpenTimeline(theme, day, index)));
steps.push((ms(t0 + 900), UiStep::Screenshot(shot)));
steps.push((ms(t0 + 1400), UiStep::CloseTimeline));
}
steps.push((ms(11600), UiStep::OpenArchive));
steps.push((ms(12400), UiStep::Screenshot("archive.png")));
steps.push((ms(12900), UiStep::CloseArchive));
steps.push((ms(13400), UiStep::Open(Theme::Light, Section::Theme)));
steps.push((ms(14100), UiStep::Screenshot("settings-light-theme.png")));
steps.push((ms(14600), UiStep::Close));
steps.push((ms(15100), UiStep::Exit));
UiTest {
out,
steps,
started: Instant::now(),
next: 0,
}
}
fn due(&mut self) -> Option<UiStep> {
let (at, step) = *self.steps.get(self.next)?;
(self.started.elapsed() >= at).then(|| {
self.next += 1;
step
})
}
fn wake(&self) -> Option<Instant> {
self.steps.get(self.next).map(|(at, _)| self.started + *at)
}
}
fn capitalise_first(s: &str) -> String {
let mut c = s.chars();
c.next()
.map(|f| f.to_uppercase().chain(c).collect())
.unwrap_or_default()
}
fn random_seed() -> u64 {
std::collections::hash_map::RandomState::new().hash_one(0x5EED_u64)
}
fn file_stamp(path: &Path) -> Option<SystemTime> {
std::fs::metadata(path).and_then(|m| m.modified()).ok()
}
fn open(path: &Path, text: bool) {
#[cfg(windows)]
let mut cmd = std::process::Command::new(if text { "notepad.exe" } else { "explorer.exe" });
#[cfg(target_os = "macos")]
let mut cmd = {
let mut c = std::process::Command::new("open");
if text {
c.arg("-t");
}
c
};
#[cfg(all(unix, not(target_os = "macos")))]
let mut cmd = {
let _ = text;
std::process::Command::new("xdg-open")
};
if let Err(e) = cmd.arg(path).spawn() {
tracing::warn!(target: "clairlune", path = %path.display(), error = %e, "could not open");
}
}
impl App {
fn timeline_mode(&self) -> bool {
self.settings.rotation.mode == settings::RotationMode::Timeline && !self.timeline.is_empty()
}
fn interval(&self) -> Option<Duration> {
if self.timeline_mode() && !self.timeline_generate {
return None;
}
let m = self.settings.schedule.change_every_minutes;
(m > 0 && !self.settings.schedule.paused).then(|| Duration::from_secs(u64::from(m) * 60))
}
fn reschedule(&mut self) {
self.next_change = self.interval().map(|d| Instant::now() + d);
}
fn submit(&mut self, job: Job) {
let export = matches!(job, Job::Export { .. } | Job::ExportGif { .. });
if self.busy && !export {
return;
}
if !export {
self.busy = true;
if let Some(t) = &self.tray {
t.set_busy(true);
}
}
if self.jobs.send(job).is_err() {
tracing::error!(target: "clairlune", "worker thread is gone");
}
}
fn set_metronome(&self, playing: bool) {
let us = if playing {
self.live.frame_interval().as_micros() as u64
} else {
0
};
self.metronome.store(us, Ordering::Relaxed);
}
fn new_wallpaper(&mut self) {
self.current_theme = None;
self.current_buddy = None;
let seed = random_seed();
let at = self.apply_at.take();
let scrolling = self.live.scrolling_ok();
self.submit(Job::New {
seed,
settings: Box::new(self.settings.clone()),
at,
scrolling,
});
}
fn archive(&self) -> Option<archive::Archive> {
archive::Archive::open(self.data_dir.join("archive")).ok()
}
fn reapply(&mut self, previous: bool) {
let Some(archive) = self.archive() else {
return;
};
let (dir, theme, buddy) = if previous {
let current_name = self
.current
.as_ref()
.filter(|p| p.starts_with(archive.dir()))
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned());
let entry = match current_name {
Some(n) => archive.before(&n),
None => archive.latest(),
};
let Some(entry) = entry else {
return;
};
self.current_theme = None;
self.current_buddy = None;
(archive.dir().join(entry.name), None, None)
} else {
let Some(dir) = self.current.clone() else {
return;
};
(dir, self.current_theme, self.current_buddy)
};
self.apply_folder(dir, theme, buddy, previous);
}
fn new_wallpaper_on(&mut self, monitor: String) {
let Some(dir) = self.current.clone() else {
return self.new_wallpaper_by_hand();
};
self.current_theme = None;
self.current_buddy = None;
self.renew = Some((monitor, random_seed()));
self.apply_folder(dir, None, None, true);
}
fn apply_folder(
&mut self,
dir: PathBuf,
theme: Option<Theme>,
buddy: Option<bool>,
archive: bool,
) {
let recipes = std::fs::read_to_string(dir.join("recipe.json"))
.map_err(|e| e.to_string())
.and_then(|t| serde_json::from_str(&t).map_err(|e| e.to_string()));
let at = self.apply_at.take();
let renew = self.renew.take();
let scrolling = self.live.scrolling_ok();
match recipes {
Ok(recipes) => self.submit(Job::Recipes {
at,
recipes: Box::new(recipes),
source: Some(dir),
theme,
buddy,
settings: Box::new(self.settings.clone()),
archive,
renew,
scrolling,
}),
Err(e) => {
tracing::warn!(target: "clairlune", dir = %dir.display(), error = %e, "unreadable saved scene")
}
}
}
fn save_settings(&mut self) {
if let Err(e) = self.settings.save(&self.settings_path) {
tracing::warn!(target: "clairlune", error = %e, "could not save settings");
}
self.settings_stamp = file_stamp(&self.settings_path);
}
fn save_pools(&self) {
if let Ok(json) = serde_json::to_string_pretty(&self.pools) {
let _ = std::fs::write(self.data_dir.join("state.json"), json);
}
}
fn check_timeline(&mut self) {
if !self.timeline_mode() {
if self.timeline_since.take().is_some() {
self.timeline_generate = false;
self.reschedule();
}
return;
}
let now = jiff::Timestamp::now();
let tz = jiff::tz::TimeZone::system();
let Some(active) = timeline::resolve(&self.timeline, &tz, now) else {
return;
};
self.timeline_next = Some(active.next);
if self.ui_test.is_some() {
return; }
if self.settings.schedule.paused {
return;
}
if !self.busy && self.timeline_since != Some(active.next) {
let ahead = active.next.duration_since(now);
if ahead > jiff::SignedDuration::ZERO
&& ahead <= TIMELINE_LEAD
&& let Some(up) = timeline::resolve(&self.timeline, &tz, active.next)
&& up.since == active.next
&& let Ok(wait) = std::time::Duration::try_from(ahead)
{
tracing::info!(target: "clairlune", seconds = wait.as_secs_f32(), "timeline: preparing the next slot");
self.manual_until = None;
self.timeline_since = Some(up.since);
self.apply_at = Some(Instant::now() + wait);
self.apply_pick(up.pick, up.since);
self.apply_at = None;
return;
}
}
if self.timeline_since.is_some_and(|s| s > now) {
return;
}
if let Some(until) = self.manual_until {
if now < until {
return;
}
self.manual_until = None;
}
if self.timeline_since == Some(active.since) || self.busy {
return;
}
self.timeline_since = Some(active.since);
self.apply_pick(active.pick, active.since);
}
fn apply_pick(&mut self, pick: timeline::Pick, since: jiff::Timestamp) {
match pick {
timeline::Pick::Generate => {
tracing::info!(target: "clairlune", "timeline: empty day, generating");
self.timeline_applied = None;
self.timeline_generate = true;
self.new_wallpaper();
self.reschedule();
}
timeline::Pick::Slot { weekday, index } => {
self.timeline_applied = self.timeline.day(weekday).get(index).cloned();
self.timeline_generate = false;
self.next_change = None;
self.apply_slot(weekday, index, since.as_second() as u64);
}
}
}
fn apply_slot(&mut self, weekday: jiff::civil::Weekday, index: usize, seed: u64) {
let Some(slot) = self.timeline.day(weekday).get(index).cloned() else {
return;
};
let key = format!(
"{}-{index}",
timeline::day_name(timeline::weekday_index(weekday))
);
tracing::info!(target: "clairlune", slot = %key, start = %timeline::format_time(slot.start), "timeline slot");
match slot.content {
timeline::Content::Item { id } => self.show_library_item(&id, slot.theme, slot.buddy),
timeline::Content::Pool { ids, tag, order } => {
let items = self.library().map(|l| l.items()).unwrap_or_default();
let mut candidates: Vec<String> = ids
.into_iter()
.filter(|id| items.iter().any(|i| &i.id == id))
.collect();
if let Some(tag) = tag {
for i in items.iter().filter(|i| i.tags.contains(&tag)) {
if !candidates.contains(&i.id) {
candidates.push(i.id.clone());
}
}
}
let last = self.pools.last.get(&key).cloned();
let position = self.pools.positions.entry(key.clone()).or_default();
match timeline::pick_from_pool(&candidates, order, seed, last.as_deref(), position)
{
Some(id) => {
self.pools.last.insert(key, id.clone());
self.save_pools();
self.show_library_item(&id, slot.theme, slot.buddy);
}
None => {
tracing::warn!(target: "clairlune", "timeline pool is empty; generating");
self.new_wallpaper();
}
}
}
timeline::Content::Random {
archetypes,
activities,
weather,
} => {
let mut s = self.settings.clone();
if !archetypes.is_empty() {
s.content.archetypes = archetypes;
}
if !activities.is_empty() {
s.content.activities = activities;
}
if !weather.is_empty() {
s.content.weather = weather;
}
match slot.theme {
library::ThemeChoice::Light => s.theme.mode = settings::ThemeMode::Light,
library::ThemeChoice::Dark => s.theme.mode = settings::ThemeMode::Dark,
library::ThemeChoice::Follow => {}
}
match slot.buddy {
library::BuddyChoice::On => s.buddy.show = true,
library::BuddyChoice::Off => s.buddy.show = false,
library::BuddyChoice::Follow => {}
}
self.current_theme = None;
self.current_buddy = None;
let at = self.apply_at.take();
let scrolling = self.live.scrolling_ok();
self.submit(Job::New {
seed: random_seed(),
settings: Box::new(s),
at,
scrolling,
});
}
}
}
fn show_library_item(
&mut self,
id: &str,
slot_theme: library::ThemeChoice,
slot_buddy: library::BuddyChoice,
) {
let Some(lib) = self.library() else {
return;
};
let Some(mut item) = lib.get(id) else {
tracing::warn!(target: "clairlune", id, "timeline item is gone; generating");
self.new_wallpaper();
return;
};
if slot_theme != library::ThemeChoice::Follow {
item.theme = slot_theme;
}
if slot_buddy != library::BuddyChoice::Follow {
item.buddy = slot_buddy;
}
let (theme, buddy) = Self::library_choices(&item, &self.settings);
self.current_theme = theme;
self.current_buddy = buddy;
self.apply_folder(lib.item_dir(id), theme, buddy, false);
}
fn timeline_replanned(&mut self) {
let active = timeline::resolve(
&self.timeline,
&jiff::tz::TimeZone::system(),
jiff::Timestamp::now(),
);
let Some(active) = active else {
self.timeline_since = None;
return;
};
let same = match (&active.pick, &self.timeline_applied) {
(timeline::Pick::Slot { weekday, index }, Some(applied)) => self
.timeline
.day(*weekday)
.get(*index)
.is_some_and(|s| s.shows_same(applied)),
(timeline::Pick::Generate, None) => self.timeline_generate,
_ => false,
};
if same && self.timeline_since.is_some() {
self.timeline_since = Some(active.since);
self.timeline_next = Some(active.next);
} else {
self.timeline_since = None;
}
}
fn timeline_edited(&mut self) {
if let Err(e) = self.timeline.save(&self.timeline_path) {
tracing::warn!(target: "clairlune", error = %e, "could not save the timeline");
self.status.note = Some(format!("Couldn't save the timeline: {e}"));
}
self.timeline_stamp = file_stamp(&self.timeline_path);
self.timeline_replanned();
self.check_timeline();
self.refresh_library();
}
fn open_timeline(&mut self, event_loop: &ActiveEventLoop) {
self.refresh_library();
if self.timeline_window.is_some() {
return;
}
let theme = apply::resolve_theme(&self.settings.theme);
match ui::UiWindow::open(event_loop, ui::Kind::Timeline, theme, self.last_section) {
Ok(w) => self.timeline_window = Some(w),
Err(e) => {
tracing::warn!(target: "clairlune", error = %e, "no timeline window; opening the file");
if !self.timeline_path.exists() {
let _ = self.timeline.save(&self.timeline_path);
}
open(&self.timeline_path, true);
}
}
}
fn new_wallpaper_by_hand(&mut self) {
if self.timeline_mode() && !self.timeline_generate {
self.manual_until = self.timeline_next;
}
self.new_wallpaper();
self.reschedule();
}
fn check(&mut self) {
let until = self.settings.general.detailed_logging_until;
if until != 0 && until <= timefmt::now_unix() {
self.settings.general.detailed_logging_until = 0;
diagnostics::set_detailed(false);
tracing::info!(target: "clairlune", "detailed logging ended");
self.save_settings();
}
let tl_stamp = file_stamp(&self.timeline_path);
if tl_stamp != self.timeline_stamp {
self.timeline_stamp = tl_stamp;
match timeline::Timeline::load(&self.timeline_path) {
Ok(t) => {
if t != self.timeline {
tracing::info!(target: "clairlune", "timeline changed");
self.timeline = t;
self.timeline_replanned();
self.refresh_library();
}
}
Err(e) => {
tracing::warn!(target: "clairlune", error = %e, "timeline.toml did not load");
self.status.note = Some(format!("The timeline file has an error: {e}"));
}
}
}
if let Some(w) = &self.timeline_window {
w.request_redraw();
}
let stamp = file_stamp(&self.settings_path);
if stamp != self.settings_stamp {
self.settings_stamp = stamp;
let new = Settings::load(&self.settings_path);
if new != self.settings {
tracing::info!(target: "clairlune", "settings changed on disk");
let schedule_changed = new.schedule != self.settings.schedule;
self.settings = new;
if let Some(t) = &self.tray {
t.show_theme(self.settings.theme.mode);
t.show_paused(self.settings.schedule.paused);
}
if schedule_changed {
self.reschedule();
}
}
}
let scrolling = self.live.scrolling_ok();
if scrolling != self.scrolling_ok {
self.scrolling_ok = scrolling;
if !scrolling && self.shown_journey && !self.busy && self.current_theme.is_none() {
tracing::info!(target: "clairlune", "live frame rate too low to scroll; replacing the journey");
self.reapply(false);
return;
}
}
let theme = apply::resolve_theme(&self.settings.theme);
if self.current_theme.is_none()
&& self.shown_theme.is_some_and(|t| t != theme)
&& !self.busy
{
tracing::info!(target: "clairlune", theme = theme.as_str(), "theme changed; re-rendering");
self.reapply(false);
}
self.check_timeline();
}
fn on_action(&mut self, action: tray::Action, event_loop: &ActiveEventLoop) {
use tray::Action;
match action {
Action::NewWallpaper => self.new_wallpaper_by_hand(),
Action::NewWallpaperOn(i) => {
if let Some(id) = self.tray.as_ref().and_then(|t| t.monitor_id(i)) {
self.new_wallpaper_on(id);
}
}
Action::Previous => self.reapply(true),
Action::Theme(mode) => {
self.settings.theme.mode = mode;
if let Some(t) = &self.tray {
t.show_theme(mode);
}
self.save_settings();
self.check();
}
Action::ToggleLive => {
self.settings.display.mode = match self.settings.display.mode {
settings::WallpaperMode::Live => settings::WallpaperMode::Still,
settings::WallpaperMode::Still => settings::WallpaperMode::Live,
};
self.save_settings();
self.follow_display_settings();
self.redraw_windows();
}
Action::TogglePause => {
self.settings.schedule.paused = !self.settings.schedule.paused;
if let Some(t) = &self.tray {
t.show_paused(self.settings.schedule.paused);
}
self.save_settings();
self.reschedule();
}
Action::SavePng => {
let dest = self.export_dir();
self.submit(Job::Export { dest, source: None });
}
Action::SaveGif => self.export_gif(),
Action::SaveToLibrary => self.save_to_library(),
Action::OpenLibrary => self.open_library(event_loop),
Action::OpenTimeline => self.open_timeline(event_loop),
Action::OpenArchive => self.open_archive(event_loop),
Action::OpenSettings => self.open_settings(event_loop, None),
Action::Quit => event_loop.exit(),
}
}
fn open_settings(&mut self, event_loop: &ActiveEventLoop, theme: Option<Theme>) {
if let Some(w) = &self.settings_window {
w.request_redraw();
return;
}
let theme = theme.unwrap_or_else(|| apply::resolve_theme(&self.settings.theme));
self.status.start_at_login = std::env::current_exe()
.ok()
.and_then(|exe| clairlune_platform::start_at_login(&exe));
self.status.note = None;
match ui::UiWindow::open(event_loop, ui::Kind::Settings, theme, self.last_section) {
Ok(w) => {
self.settings_window = Some(w);
self.refresh_window_thumb();
}
Err(e) => {
tracing::warn!(target: "clairlune", error = %e, "no settings window; opening the file");
if !self.settings_path.exists() {
self.save_settings();
}
open(&self.settings_path, true);
}
}
}
fn library(&self) -> Option<library::Library> {
library::Library::open(self.data_dir.join("library")).ok()
}
fn refresh_library(&mut self) {
self.library_items = self.library().map(|l| l.items()).unwrap_or_default();
self.library_uses = self
.library_items
.iter()
.map(|i| (i.id.clone(), self.timeline.uses(&i.id)))
.filter(|(_, u)| !u.is_empty())
.collect();
self.redraw_windows();
}
fn redraw_windows(&self) {
for w in [
&self.settings_window,
&self.library_window,
&self.timeline_window,
&self.archive_window,
]
.into_iter()
.flatten()
{
w.request_redraw();
}
}
fn open_library(&mut self, event_loop: &ActiveEventLoop) {
self.refresh_library();
if self.library_window.is_some() {
return;
}
let theme = apply::resolve_theme(&self.settings.theme);
match ui::UiWindow::open(event_loop, ui::Kind::Library, theme, self.last_section) {
Ok(w) => self.library_window = Some(w),
Err(e) => tracing::warn!(target: "clairlune", error = %e, "no library window"),
}
}
fn save_to_library(&mut self) {
let dir = self.current.clone();
self.save_dir_to_library(dir);
}
fn save_dir_to_library(&mut self, dir: Option<PathBuf>) {
let note = (|| {
let dir = dir.ok_or("There's no wallpaper to save yet.")?;
let lib = self
.library()
.ok_or("The library folder can't be opened.")?;
if dir.starts_with(lib.dir()) {
return Err("This wallpaper is already in the library.");
}
let archive = self.archive().ok_or("The archive can't be opened.")?;
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned());
let entry = name
.and_then(|n| archive.get(&n))
.ok_or("This wallpaper is no longer in the archive.")?;
lib.save_entry(&dir, &entry, timefmt::now_unix())
.map(|item| item.name)
.map_err(|_| "Saving to the library failed; see the logs.")
})();
self.status.note = Some(match note {
Ok(name) => format!("Saved to the library as {name}."),
Err(e) => e.to_string(),
});
self.refresh_library();
}
fn refresh_archive(&mut self) {
self.archive_items = self.archive().map(|a| a.entries()).unwrap_or_default();
if let Some(w) = &self.archive_window {
w.request_redraw();
}
}
fn open_archive(&mut self, event_loop: &ActiveEventLoop) {
self.refresh_archive();
if self.archive_window.is_some() {
return;
}
let theme = apply::resolve_theme(&self.settings.theme);
match ui::UiWindow::open(event_loop, ui::Kind::Archive, theme, self.last_section) {
Ok(w) => self.archive_window = Some(w),
Err(e) => {
tracing::warn!(target: "clairlune", error = %e, "no archive window; opening the folder");
open(&self.data_dir.join("archive"), false);
}
}
}
fn on_archive_action(&mut self, action: ui::view::UiAction) {
use ui::view::UiAction;
let Some(archive) = self.archive() else {
return;
};
let dir_of = |name: &str| archive.dir().join(name);
match action {
UiAction::ApplyArchive(name) => {
self.current_theme = None;
self.current_buddy = None;
self.apply_folder(dir_of(&name), None, None, false);
}
UiAction::PinArchive { name, pinned } => {
if let Err(e) = archive.set_pinned(&name, pinned) {
self.status.note = Some(format!("Couldn't pin it: {e}"));
}
}
UiAction::SaveArchiveToLibrary(name) => {
self.save_dir_to_library(Some(dir_of(&name)));
}
UiAction::ExportArchive { name, gif } => {
let dest = self.export_dir();
let source = Some(dir_of(&name));
if gif {
self.submit(Job::ExportGif {
dest,
source,
theme: apply::resolve_theme(&self.settings.theme),
buddy: self.settings.buddy.show,
});
} else {
self.submit(Job::Export { dest, source });
}
}
UiAction::DeleteArchive(name) => {
let dir = dir_of(&name);
if self.current.as_deref() == Some(dir.as_path()) {
self.current = None;
}
self.status.note = Some(match archive.delete(&name) {
Ok(()) => "Deleted from the archive.".to_string(),
Err(e) => format!("Couldn't delete it: {e}"),
});
}
_ => {}
}
self.refresh_archive();
}
fn library_choices(item: &library::Item, settings: &Settings) -> (Option<Theme>, Option<bool>) {
let theme = match item.theme {
library::ThemeChoice::Follow => None,
library::ThemeChoice::Light => Some(Theme::Light),
library::ThemeChoice::Dark => Some(Theme::Dark),
};
let buddy = match item.buddy {
library::BuddyChoice::Follow => None,
library::BuddyChoice::On => Some(true),
library::BuddyChoice::Off => Some(false),
};
let _ = settings;
(theme, buddy)
}
fn on_library_action(&mut self, action: ui::view::UiAction) {
use ui::view::UiAction;
let Some(lib) = self.library() else {
return;
};
match action {
UiAction::ApplyLibrary(id) => {
if let Some(item) = lib.get(&id) {
let (theme, buddy) = Self::library_choices(&item, &self.settings);
self.current_theme = theme;
self.current_buddy = buddy;
self.apply_folder(lib.item_dir(&id), theme, buddy, false);
}
}
UiAction::UpdateLibrary(item) => {
if let Err(e) = lib.update(&item) {
self.status.note = Some(format!("Couldn't save the change: {e}"));
}
if self.current.as_deref() == Some(lib.item_dir(&item.id).as_path()) {
let (theme, buddy) = Self::library_choices(&item, &self.settings);
self.current_theme = theme;
self.current_buddy = buddy;
self.reapply(false);
}
}
UiAction::DeleteLibrary { id, forget } => {
if self.current.as_deref() == Some(lib.item_dir(&id).as_path()) {
self.current = None;
}
if !self.timeline.uses(&id).is_empty() {
self.timeline.forget_item(&id, forget);
if let Err(e) = self.timeline.save(&self.timeline_path) {
tracing::warn!(target: "clairlune", error = %e, "could not save the timeline");
}
self.timeline_stamp = file_stamp(&self.timeline_path);
self.timeline_replanned();
}
self.status.note = Some(match lib.delete(&id) {
Ok(()) => "Deleted from the library.".to_string(),
Err(e) => format!("Couldn't delete it: {e}"),
});
}
UiAction::ExportLibrary { id, gif } => {
let dest = self.export_dir();
let source = Some(lib.item_dir(&id));
if gif {
let item = lib.get(&id);
let (theme, buddy) = item
.map(|i| Self::library_choices(&i, &self.settings))
.unwrap_or((None, None));
self.submit(Job::ExportGif {
dest,
source,
theme: theme.unwrap_or_else(|| apply::resolve_theme(&self.settings.theme)),
buddy: buddy.unwrap_or(self.settings.buddy.show),
});
} else {
self.submit(Job::Export { dest, source });
}
}
_ => {}
}
self.refresh_library();
}
fn refresh_window_thumb(&mut self) {
let (Some(w), Some(dir)) = (&mut self.settings_window, &self.current) else {
return;
};
let path = dir.join("thumb.png");
if let Some((size, rgba)) = std::fs::read(&path)
.ok()
.and_then(|b| ui::decode_png_rgba(&b))
{
w.set_thumb(size, &rgba);
}
}
fn timeline_prepare_at(&self) -> Option<Instant> {
if !self.timeline_mode() || self.ui_test.is_some() {
return None;
}
let next = self.timeline_next?;
if self.timeline_since == Some(next) {
return None;
}
let ahead = next.duration_since(jiff::Timestamp::now()) - TIMELINE_LEAD;
let wait = std::time::Duration::try_from(ahead).unwrap_or(Duration::ZERO);
Some(Instant::now() + wait)
}
fn watch_monitors(&mut self, event_loop: &ActiveEventLoop, now: Instant) {
let mut noticed = false;
#[cfg(windows)]
if let Some(w) = &self.watcher {
noticed = w.take_displays_changed();
if w.take_taskbar_created() {
tracing::info!(target: "clairlune", "Explorer restarted");
self.live.refresh();
}
if w.take_clock_changed() {
tracing::info!(target: "clairlune", "the clock changed or the computer woke; checking the timeline");
self.check_timeline();
}
}
#[cfg(target_os = "macos")]
if self.spaces.take_changed() && !self.busy {
self.live.reset_stills();
}
if !cfg!(windows) && now >= self.next_monitor_poll {
self.next_monitor_poll = now + MONITOR_POLL;
noticed = self.monitor_layout.as_ref() != Some(&monitor_layout(event_loop));
}
if self.monitor_layout.is_none() {
self.monitor_layout = Some(monitor_layout(event_loop));
}
if noticed {
self.monitors_changed_at = Some(now);
}
let Some(at) = self.monitors_changed_at else {
return;
};
if now < at + MONITOR_SETTLE || self.busy || self.ui_test.is_some() {
return;
}
self.monitors_changed_at = None;
let layout = monitor_layout(event_loop);
if self.monitor_layout.as_ref() == Some(&layout) {
tracing::debug!(target: "clairlune", "display change settled; same monitors");
return;
}
tracing::info!(target: "clairlune", monitors = layout.len(), "monitors changed; making the wallpaper again");
self.monitor_layout = Some(layout);
if self.current.is_some() {
self.reapply(false);
} else {
self.new_wallpaper();
}
}
fn follow_display_settings(&mut self) {
let live = self.settings.display.mode == settings::WallpaperMode::Live;
self.live.set_fps(self.settings.live.smoothness_fps);
self.live.set_battery_policy(
self.settings.live.battery_saver_on_battery,
self.settings.live.pause_on_battery,
);
self.live
.set_cover_pause(self.settings.live.pause_when_covered);
self.live.set_enabled(live);
if let Some(t) = &self.tray {
t.show_live(live && live::supported().is_ok());
}
}
fn status(&self) -> ui::view::Status {
let mut s = self.status.clone();
s.crash_reports = diagnostics::crash_reports(&self.data_dir).len();
let until = self.settings.general.detailed_logging_until;
s.detailed_until = (until > timefmt::now_unix()).then(|| {
jiff::Timestamp::from_second(until as i64)
.map(timeline::local_hhmm)
.unwrap_or_default()
});
s.live = self.live.status.clone();
s.live_supported = live::supported().err();
s.timeline_next = self
.timeline_next
.filter(|_| self.timeline_mode())
.map(|t| format!("Next slot at {}", timeline::local_hhmm(t)));
s.timeline_problems = match self.library() {
Some(lib) => self.timeline.problems(&|id| lib.get(id).is_some()),
None => Vec::new(),
};
s.busy = self.busy;
s.next_in_minutes = self
.next_change
.map(|t| t.saturating_duration_since(Instant::now()).as_secs() / 60);
s
}
fn on_ui_action(&mut self, action: ui::view::UiAction, event_loop: &ActiveEventLoop) {
use ui::view::UiAction;
match action {
UiAction::SettingsChanged => {
self.save_settings();
if let Some(t) = &self.tray {
t.show_theme(self.settings.theme.mode);
t.show_paused(self.settings.schedule.paused);
}
self.follow_display_settings();
self.reschedule();
let theme = apply::resolve_theme(&self.settings.theme);
for w in [
&mut self.settings_window,
&mut self.library_window,
&mut self.timeline_window,
&mut self.archive_window,
]
.into_iter()
.flatten()
{
w.set_theme(theme);
}
self.check();
}
UiAction::NewWallpaper => self.new_wallpaper_by_hand(),
UiAction::EditTimeline => self.open_timeline(event_loop),
UiAction::TimelineChanged => self.timeline_edited(),
UiAction::Previous => self.reapply(true),
UiAction::OpenArchive => self.open_archive(event_loop),
UiAction::OpenArchiveFolder => open(&self.data_dir.join("archive"), false),
a @ (UiAction::ApplyArchive(_)
| UiAction::PinArchive { .. }
| UiAction::SaveArchiveToLibrary(_)
| UiAction::ExportArchive { .. }
| UiAction::DeleteArchive(_)) => self.on_archive_action(a),
UiAction::OpenLogs => open(&self.data_dir.join("logs"), false),
UiAction::OpenCrashReports => open(&self.data_dir.join("crashes"), false),
UiAction::SetDetailedLogging(on) => {
self.settings.general.detailed_logging_until = if on {
timefmt::now_unix() + diagnostics::DETAILED_SECS
} else {
0
};
diagnostics::set_detailed(on);
tracing::info!(target: "clairlune", on, "detailed logging");
self.save_settings();
}
UiAction::ExportDiagnostics => {
let info = diagnostics::SystemInfo {
monitors: self
.monitor_layout
.iter()
.flatten()
.map(|(name, x, y, w, h)| {
format!("{w}x{h} at ({x}, {y}) {}", name.as_deref().unwrap_or(""))
})
.collect(),
live: self.live.status.clone(),
};
let config_dir = self
.settings_path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| self.data_dir.clone());
let dest = self.export_dir();
self.status.note = Some(
match diagnostics::export_bundle(
&self.data_dir,
&config_dir,
self.current.as_deref(),
&info,
&dest,
) {
Ok(path) => {
open(&dest, false);
format!("Saved {}", path.display())
}
Err(e) => format!("Couldn't export diagnostics: {e}"),
},
);
}
UiAction::SavePng => {
let dest = self.export_dir();
self.submit(Job::Export { dest, source: None });
}
UiAction::SaveToLibrary => self.save_to_library(),
UiAction::OpenLibrary => self.open_library(event_loop),
a @ (UiAction::ApplyLibrary(_)
| UiAction::UpdateLibrary(_)
| UiAction::DeleteLibrary { .. }
| UiAction::ExportLibrary { .. }) => self.on_library_action(a),
UiAction::SaveGif => {
self.status.note = Some("Making the GIF...".to_string());
self.export_gif();
}
UiAction::SetStartAtLogin(on) => {
let result = std::env::current_exe()
.map_err(|e| e.to_string())
.and_then(|exe| {
clairlune_platform::set_start_at_login(&exe, on)
.map_err(|e| e.to_string())
.map(|()| clairlune_platform::start_at_login(&exe))
});
match result {
Ok(state) => self.status.start_at_login = state,
Err(e) => {
self.status.note = Some(format!("Couldn't change start at login: {e}"))
}
}
}
UiAction::RestoreWallpaper => {
self.settings.schedule.paused = true;
self.save_settings();
self.reschedule();
if let Some(t) = &self.tray {
t.show_paused(true);
}
self.submit(Job::Restore);
}
}
if let Some(w) = &self.settings_window {
w.request_redraw();
}
let _ = event_loop;
}
fn run_ui_test(&mut self, event_loop: &ActiveEventLoop) {
while let Some(step) = self.ui_test.as_mut().and_then(UiTest::due) {
match step {
UiStep::Open(theme, section) => {
let opened = Instant::now();
self.open_settings(event_loop, Some(theme));
if let Some(w) = &mut self.settings_window {
w.set_section(section);
if section == ui::view::Section::Buddy {
w.toast("Clawd skips the next wallpaper");
}
}
tracing::info!(target: "clairlune", ms = opened.elapsed().as_millis() as u64, memory_mb = memory_mb(), "ui test: settings opened");
}
UiStep::Screenshot(name) => {
let out = self.ui_test.as_ref().map(|t| t.out.join(name));
let target = [
&mut self.archive_window,
&mut self.timeline_window,
&mut self.library_window,
&mut self.settings_window,
]
.into_iter()
.flatten()
.next();
if let (Some(w), Some(out)) = (target, out) {
w.screenshot_to = Some(out);
w.request_redraw();
}
}
UiStep::OpenLibrary => {
self.open_library(event_loop);
if let (Some(w), Some(first)) =
(&mut self.library_window, self.library_items.first())
{
w.select_item(first);
}
tracing::info!(target: "clairlune", items = self.library_items.len(), memory_mb = memory_mb(), "ui test: library opened");
}
UiStep::CloseLibrary => {
self.library_window = None;
self.trim_if_idle();
tracing::info!(target: "clairlune", memory_mb = memory_mb(), "ui test: library closed");
}
UiStep::OpenTimeline(theme, day, index) => {
self.open_timeline(event_loop);
if let Some(w) = &mut self.timeline_window {
w.set_theme(theme);
w.select_slot(day, index);
}
tracing::info!(target: "clairlune", memory_mb = memory_mb(), "ui test: timeline opened");
}
UiStep::CloseTimeline => {
self.timeline_window = None;
self.trim_if_idle();
tracing::info!(target: "clairlune", memory_mb = memory_mb(), "ui test: timeline closed");
}
UiStep::OpenArchive => {
self.open_archive(event_loop);
let pick = self.archive_items.get(1).map(|e| e.name.clone());
if let (Some(w), Some(name)) = (&mut self.archive_window, pick) {
w.select_entry(&name);
}
tracing::info!(target: "clairlune", entries = self.archive_items.len(), memory_mb = memory_mb(), "ui test: archive opened");
}
UiStep::CloseArchive => {
self.archive_window = None;
self.trim_if_idle();
tracing::info!(target: "clairlune", memory_mb = memory_mb(), "ui test: archive closed");
}
UiStep::Close => {
self.settings_window = None;
self.trim_if_idle();
tracing::info!(target: "clairlune", memory_mb = memory_mb(), "ui test: settings closed");
}
UiStep::Exit => {
tracing::info!(target: "clairlune", "ui test passed: settings opened and closed 3 times on one loop");
event_loop.exit();
}
}
}
}
fn trim_if_idle(&self) {
let open = [
&self.settings_window,
&self.library_window,
&self.timeline_window,
&self.archive_window,
]
.iter()
.any(|w| w.is_some());
if !open {
#[cfg(windows)]
clairlune_platform::windows_live::trim_memory();
}
}
fn has_tray(&self) -> bool {
self.tray.is_some()
}
fn export_gif(&mut self) {
let dest = self.export_dir();
let theme = self
.shown_theme
.unwrap_or_else(|| apply::resolve_theme(&self.settings.theme));
self.submit(Job::ExportGif {
dest,
source: None,
theme,
buddy: self.settings.buddy.show,
});
}
fn export_dir(&self) -> PathBuf {
if self.settings.export.folder.trim().is_empty() {
clairlune_platform::pictures_dir()
.unwrap_or_else(|| self.data_dir.clone())
.join(APP_NAME)
} else {
PathBuf::from(self.settings.export.folder.trim())
}
}
fn on_done(&mut self, done: Done) {
match done {
Done::Applied {
source,
seed,
theme,
archetype,
activity,
monitors,
ms,
live,
} => {
self.busy = false;
self.current = source;
diagnostics::set_current(self.current.clone());
self.shown_theme = Some(theme);
self.shown_journey = live.iter().any(|s| s.package.recipe.is_journey());
if let Some(t) = &self.tray {
let span = live.iter().any(|s| s.view.is_some());
let screens: Vec<_> = if span {
Vec::new()
} else {
live.iter().map(|s| s.monitor.clone()).collect()
};
t.set_monitors(&screens);
}
self.live.show(live);
self.refresh_archive();
self.trim_if_idle();
let what = match activity {
Some(a) => {
format!("{} in {}", a.replace('_', " "), archetype.replace('_', " "))
}
None => archetype.replace('_', " "),
};
let mut text = format!("{APP_NAME}: {what} (seed {seed})");
if self.timeline_mode()
&& let Some(next) = self.timeline_next
{
text.push_str(&format!(", next at {}", timeline::local_hhmm(next)));
}
tracing::debug!(target: "clairlune", monitors, ms, "{text}");
self.status.what = what;
self.status.seed = Some(seed);
self.status.theme = Some(theme);
self.refresh_window_thumb();
if let Some(t) = &self.tray {
t.set_busy(false);
t.set_tooltip(&text);
}
}
Done::Exported(path) => {
tracing::info!(target: "clairlune", path = %path.display(), "saved");
self.status.note = Some(format!("Saved {}", path.display()));
if let Some(dir) = path.parent() {
open(dir, false);
}
}
Done::NoHost(why) => {
self.status.note = Some(why);
if let Some(w) = &self.settings_window {
w.request_redraw();
}
}
Done::Restored => {
self.busy = false;
self.current = None;
self.status.what.clear();
self.status.seed = None;
self.status.theme = None;
self.status.note =
Some("Your wallpaper is back. The schedule is paused.".to_string());
if let Some(w) = &mut self.settings_window {
w.clear_thumb();
}
if let Some(t) = &self.tray {
t.set_busy(false);
t.set_tooltip(APP_NAME);
}
}
Done::Failed(e) => {
self.busy = false;
tracing::debug!(target: "clairlune", error = %e, "shown in the tray tooltip");
self.status.note = Some(capitalise_first(&e));
if let Some(t) = &self.tray {
t.set_busy(false);
t.set_tooltip(&format!("{APP_NAME}: {e}"));
}
}
}
}
}
impl ApplicationHandler<AppEvent> for App {
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
if cause != StartCause::Init {
return;
}
match tray::Tray::new(
self.settings.theme.mode,
self.settings.schedule.paused,
self.settings.display.mode == settings::WallpaperMode::Live
&& live::supported().is_ok(),
) {
Ok(t) => {
self.tray = Some(t);
tracing::debug!(target: "clairlune", memory_mb = memory_mb(), "tray ready");
}
Err(e) => tracing::error!(target: "clairlune", error = %e, "no tray icon"),
}
if let Some(report) = diagnostics::new_crash_report(&self.data_dir) {
tracing::warn!(target: "clairlune", report = %report.display(), "Clairlune stopped unexpectedly last time");
self.status.note = Some(
"Clairlune stopped unexpectedly last time. The crash report is under General, Crash reports."
.into(),
);
}
if !self.has_tray() && self.ui_test.is_none() {
self.open_settings(event_loop, None);
}
let latest = self.archive().and_then(|a| a.latest());
self.current = latest
.as_ref()
.and_then(|e| self.archive().map(|a| a.dir().join(&e.name)));
if let Some(e) = &latest {
self.status.what = match &e.activity {
Some(a) => format!(
"{} in {}",
a.replace('_', " "),
e.archetype.replace('_', " ")
),
None => e.archetype.replace('_', " "),
};
self.status.seed = Some(e.seed);
}
if self.ui_test.is_some() {
self.check_timeline();
return;
}
self.shown_theme = latest.and_then(|e| match e.theme.as_str() {
"light" => Some(Theme::Light),
"dark" => Some(Theme::Dark),
_ => None,
});
if self.timeline_mode() {
self.check_timeline();
} else if self.settings.schedule.change_at_login || self.current.is_none() {
self.new_wallpaper();
} else if self.settings.display.mode == settings::WallpaperMode::Live {
self.reapply(false);
}
self.reschedule();
}
fn resumed(&mut self, _event_loop: &ActiveEventLoop) {}
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
let status = self.status();
let mut actions = Vec::new();
let before = self.settings.clone();
let library_dir = self.data_dir.join("library");
let archive_dir = self.data_dir.join("archive");
let current_entry = self
.current
.as_ref()
.filter(|p| p.starts_with(&archive_dir))
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned());
let Some(w) = [
&mut self.settings_window,
&mut self.library_window,
&mut self.timeline_window,
&mut self.archive_window,
]
.into_iter()
.flatten()
.find(|w| w.id() == id) else {
return;
};
let mut model = ui::Model {
settings: &mut self.settings,
status: &status,
library: &self.library_items,
library_dir: &library_dir,
uses: &self.library_uses,
timeline: &mut self.timeline,
archive: &self.archive_items,
archive_dir: &archive_dir,
current_entry: current_entry.as_deref(),
};
let outcome = w.on_event(&event, &mut model, &mut actions);
let kind = w.kind();
if kind == ui::Kind::Settings {
self.last_section = w.section();
}
if let ui::Outcome::Close = outcome {
match kind {
ui::Kind::Settings => {
self.settings_window = None;
tracing::debug!(target: "clairlune", "settings closed");
if !self.has_tray()
&& self.ui_test.is_none()
&& self.library_window.is_none()
&& self.timeline_window.is_none()
&& self.archive_window.is_none()
{
event_loop.exit();
}
}
ui::Kind::Library => self.library_window = None,
ui::Kind::Timeline => self.timeline_window = None,
ui::Kind::Archive => self.archive_window = None,
}
self.trim_if_idle();
}
if self.settings == before {
actions.retain(|a| *a != ui::view::UiAction::SettingsChanged);
}
for a in actions {
self.on_ui_action(a, event_loop);
}
}
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: AppEvent) {
match event {
AppEvent::Menu(e) => {
if let Some(action) = self.tray.as_ref().and_then(|t| t.action(e.id())) {
tracing::debug!(target: "clairlune", ?action, "menu");
self.on_action(action, event_loop);
}
}
AppEvent::Done(d) => self.on_done(d),
AppEvent::OpenSettings => self.open_settings(event_loop, None),
AppEvent::LiveFrame => {
let next = self.live.tick(Instant::now());
self.set_metronome(next.is_some());
}
}
let _ = event_loop;
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
self.run_ui_test(event_loop);
let now = Instant::now();
self.watch_monitors(event_loop, now);
if self.next_change.is_some_and(|t| now >= t) && !self.busy {
self.new_wallpaper();
self.reschedule();
}
if now >= self.next_check {
self.check();
self.next_check = now + CHECK_EVERY;
}
let live_next = self.live.tick(Instant::now());
self.set_metronome(live_next.is_some());
let mut wake = match self.next_change {
Some(t) => t.min(self.next_check),
None => self.next_check,
};
if let Some(t) = live_next {
wake = wake.min(t);
}
if let Some(t) = self.monitors_changed_at {
wake = wake.min(t + MONITOR_SETTLE);
}
if let Some(t) = self.timeline_prepare_at() {
if Instant::now() >= t {
if !self.busy {
self.check_timeline();
}
} else {
wake = wake.min(t);
}
}
if !cfg!(windows) {
wake = wake.min(self.next_monitor_poll);
}
if let Some(t) = self.ui_test.as_ref().and_then(|t| t.wake()) {
wake = wake.min(t);
}
event_loop.set_control_flow(ControlFlow::WaitUntil(wake));
}
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
tracing::info!(target: "clairlune", "quitting");
}
}
pub(crate) fn memory_mb() -> u64 {
#[cfg(windows)]
{
clairlune_platform::windows_live::process_memory() >> 20
}
#[cfg(not(windows))]
{
0
}
}
fn init_logging(data_dir: &Path) -> Option<tracing_appender::non_blocking::WorkerGuard> {
use tracing_subscriber::fmt;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let filter = diagnostics::filter_layer(false);
let _ = std::fs::create_dir_all(data_dir.join("logs"));
diagnostics::prune_logs(&data_dir.join("logs"), diagnostics::LOG_CAP_BYTES);
let appender = tracing_appender::rolling::Builder::new()
.rotation(tracing_appender::rolling::Rotation::DAILY)
.filename_prefix("clairlune")
.filename_suffix("log")
.max_log_files(7)
.build(data_dir.join("logs"));
let (file_layer, guard) = match appender {
Ok(a) => {
let (writer, guard) = tracing_appender::non_blocking(a);
(
Some(fmt::layer().with_writer(writer).with_ansi(false)),
Some(guard),
)
}
Err(_) => (None, None),
};
let stderr_layer = cfg!(debug_assertions).then(|| fmt::layer().with_writer(std::io::stderr));
tracing_subscriber::registry()
.with(filter)
.with(diagnostics::Tail)
.with(file_layer)
.with(stderr_layer)
.init();
diagnostics::install_crash_reports(data_dir);
guard
}
fn single_instance(data_dir: &Path) -> Result<std::fs::File, String> {
let path = data_dir.join("instance.lock");
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(|e| format!("{}: {e}", path.display()))?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(std::fs::TryLockError::WouldBlock) => Err("already running".into()),
Err(std::fs::TryLockError::Error(e)) => Err(e.to_string()),
}
}
fn seed_ui_test(data_dir: &Path) -> Result<(), String> {
use clairlune_scene::{Aspect, ContentContext, compose};
let archive = archive::Archive::open(data_dir.join("archive")).map_err(|e| e.to_string())?;
let lib = library::Library::open(data_dir.join("library")).map_err(|e| e.to_string())?;
let mut saved = Vec::new();
for (i, seed) in [3u64, 7, 42].into_iter().enumerate() {
let recipe = compose(seed, Aspect::from_size(16, 9), &ContentContext::default());
let pkg = clairlune_render::ScenePackage::capture(&recipe, 960, 540)
.map_err(|e| e.to_string())?;
let theme = pkg.themes()[0];
let (img, palette) = pkg.still(theme, true).ok_or("no frame")?;
let png = apply::png_of(&img, palette)?;
let thumb = apply::png_of(&apply::shrink(&img, 480), palette)?;
let entry = archive
.add(&archive::NewEntry {
created: 1_000 + i as u64,
recipes: archive::EntryRecipes {
base_seed: seed,
theme: theme.as_str().into(),
monitors: vec![archive::MonitorScene {
monitor: "ui-test".into(),
width: 960,
height: 540,
recipe,
}],
},
pngs: vec![png],
thumb_png: thumb,
packages: vec![std::sync::Arc::new(pkg)],
})
.map_err(|e| e.to_string())?;
if i < 2 {
let item = lib
.save_entry(&archive.dir().join(&entry.name), &entry, 2_000 + i as u64)
.map_err(|e| e.to_string())?;
saved.push(item.id);
}
}
let [a, b] = [&saved[0], &saved[1]];
let tl = format!(
r#"layout = "weekly"
[[day.monday.slot]]
start = "00:00"
content = {{ type = "random", archetypes = ["night_sky", "cave"] }}
theme = "dark"
[[day.monday.slot]]
start = "07:00"
content = {{ type = "item", id = "{a}" }}
theme = "light"
[[day.monday.slot]]
start = "12:30"
content = {{ type = "pool", ids = ["{a}", "{b}"], order = "shuffle" }}
[[day.monday.slot]]
start = "18:15"
content = {{ type = "item", id = "{b}" }}
[[day.monday.slot]]
start = "22:00"
content = {{ type = "random", archetypes = ["night_sky"], activities = ["stargaze"] }}
theme = "dark"
[[day.wednesday.slot]]
start = "08:00"
content = {{ type = "item", id = "{b}" }}
[[day.wednesday.slot]]
start = "17:45"
content = {{ type = "random" }}
[[day.friday.slot]]
start = "06:30"
content = {{ type = "item", id = "{a}" }}
[[day.friday.slot]]
start = "20:00"
content = {{ type = "item", id = "lib_gone" }}
[[day.saturday.slot]]
start = "09:00"
content = {{ type = "pool", ids = ["{b}", "{a}"], order = "sequential" }}
[[day.sunday.slot]]
start = "10:00"
content = {{ type = "random", archetypes = ["shore", "forest"] }}
"#
);
std::fs::write(data_dir.join("timeline.toml"), tl).map_err(|e| e.to_string())?;
std::fs::write(
data_dir.join("settings.toml"),
"[rotation]\nmode = \"timeline\"\n\n[theme]\nmode = \"schedule\"\nfollow_sun = true\nlocation = \"40.71, -74.01\"\n",
)
.map_err(|e| e.to_string())?;
Ok(())
}
fn spawn_worker(
rx: mpsc::Receiver<Job>,
proxy: EventLoopProxy<AppEvent>,
archive_dir: PathBuf,
) -> std::io::Result<()> {
std::thread::Builder::new()
.name("clairlune-worker".into())
.spawn(move || {
apply::worker(
rx,
move |d| {
let _ = proxy.send_event(AppEvent::Done(d));
},
archive_dir,
)
})
.map(|_| ())
}
fn command_line_answer(args: &[String]) -> Option<String> {
let first = args.get(1).map(String::as_str)?;
match first {
"--version" | "-V" => Some(format!("{APP_NAME} {}", env!("CARGO_PKG_VERSION"))),
"--help" | "-h" => Some(format!(
"{APP_NAME} {}: procedural, animated ASCII-art wallpapers.\n\n\
Run it without arguments: it lives in the notification area (the menu bar on macOS).\n\
Options:\n --version print the version and exit\n --help print this and exit",
env!("CARGO_PKG_VERSION")
)),
_ => None,
}
}
fn main() {
let args: Vec<String> = std::env::args().collect();
if let Some(text) = command_line_answer(&args) {
#[cfg(windows)]
clairlune_platform::attach_parent_console();
println!("{text}");
return;
}
clairlune_platform::init_dpi_awareness();
let ui_test_out = args
.iter()
.position(|a| a == "--ui-test")
.map(|i| PathBuf::from(args.get(i + 1).cloned().unwrap_or_else(|| ".".into())));
let data_dir = match &ui_test_out {
Some(out) => Some(out.join("data")),
None => clairlune_platform::app_data_dir(),
};
let Some(data_dir) = data_dir else {
eprintln!("{APP_NAME}: no data directory");
return;
};
let _ = std::fs::create_dir_all(&data_dir);
let _log = init_logging(&data_dir);
if ui_test_out.is_some()
&& let Err(e) = seed_ui_test(&data_dir)
{
tracing::warn!(target: "clairlune", error = %e, "ui test content");
}
let _instance = match single_instance(&data_dir) {
Ok(f) => f,
Err(e) => {
let asked = ipc::ask_running_copy(&data_dir);
tracing::info!(target: "clairlune", reason = %e, asked, "another copy is running; asked it to open Settings");
return;
}
};
let settings_path = match &ui_test_out {
Some(_) => data_dir.join("settings.toml"),
None => clairlune_platform::app_config_dir()
.unwrap_or_else(|| data_dir.clone())
.join("settings.toml"),
};
let settings = Settings::load(&settings_path);
let timeline_path = settings_path.with_file_name("timeline.toml");
if settings.general.detailed_logging_until > timefmt::now_unix() {
diagnostics::set_detailed(true);
}
tracing::info!(
target: "clairlune",
version = env!("CARGO_PKG_VERSION"),
generator_version = clairlune_scene::GENERATOR_VERSION,
os = std::env::consts::OS,
settings = %settings_path.display(),
data = %data_dir.display(),
memory_mb = memory_mb(),
"starting"
);
let event_loop = match EventLoop::<AppEvent>::with_user_event().build() {
Ok(l) => l,
Err(e) => {
tracing::error!(target: "clairlune", error = %e, "no event loop");
return;
}
};
let proxy: EventLoopProxy<AppEvent> = event_loop.create_proxy();
{
let p = proxy.clone();
tray_icon::menu::MenuEvent::set_event_handler(Some(move |e| {
let _ = p.send_event(AppEvent::Menu(e));
}));
let p = proxy.clone();
tray_icon::TrayIconEvent::set_event_handler(Some(move |e| {
if let tray_icon::TrayIconEvent::DoubleClick {
button: tray_icon::MouseButton::Left,
..
} = e
{
let _ = p.send_event(AppEvent::OpenSettings);
}
}));
}
if ui_test_out.is_none() {
let p = proxy.clone();
if let Err(e) = ipc::serve(&data_dir, move || {
let _ = p.send_event(AppEvent::OpenSettings);
}) {
tracing::warn!(target: "clairlune", error = %e, "no single-instance channel; a second launch won't open Settings");
}
}
let metronome_proxy = proxy.clone();
let (jobs, rx) = mpsc::channel();
let archive_dir = data_dir.join("archive");
let worker = if ui_test_out.is_some() {
drop(rx);
Ok(())
} else {
spawn_worker(rx, proxy, archive_dir)
};
if let Err(e) = worker {
tracing::error!(target: "clairlune", error = %e, "no worker thread");
return;
}
let pools: PoolState = std::fs::read_to_string(data_dir.join("state.json"))
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_default();
let mut live = live::Live::new(
settings.display.mode == settings::WallpaperMode::Live,
settings.live.smoothness_fps,
);
live.set_battery_policy(
settings.live.battery_saver_on_battery,
settings.live.pause_on_battery,
);
live.set_cover_pause(settings.live.pause_when_covered);
#[cfg(windows)]
let watcher = match clairlune_platform::windows_live::SystemWatcher::new() {
Ok(w) => Some(w),
Err(e) => {
tracing::warn!(target: "clairlune", error = %e, "no display-change watcher");
None
}
};
let metronome = Arc::new(AtomicU64::new(0));
{
let (m, p) = (metronome.clone(), metronome_proxy);
let _ = std::thread::Builder::new()
.name("clairlune-live-metronome".into())
.spawn(move || {
loop {
let us = m.load(Ordering::Relaxed);
if us == 0 {
std::thread::sleep(Duration::from_millis(200));
continue;
}
std::thread::sleep(Duration::from_micros(us));
if p.send_event(AppEvent::LiveFrame).is_err() {
return; }
}
});
}
let mut app = App {
live,
metronome,
#[cfg(windows)]
watcher,
#[cfg(target_os = "macos")]
spaces: clairlune_platform::macos::SpaceWatcher::new(),
monitor_layout: None,
monitors_changed_at: None,
next_monitor_poll: Instant::now(),
settings_stamp: file_stamp(&settings_path),
settings,
settings_path,
data_dir,
jobs,
busy: false,
next_change: None,
next_check: Instant::now() + CHECK_EVERY,
shown_theme: None,
shown_journey: false,
scrolling_ok: true,
renew: None,
current: None,
current_theme: None,
current_buddy: None,
tray: None,
timeline: timeline::Timeline::load(&timeline_path).unwrap_or_default(),
timeline_stamp: file_stamp(&timeline_path),
timeline_path,
timeline_since: None,
timeline_applied: None,
timeline_next: None,
timeline_generate: false,
manual_until: None,
apply_at: None,
pools,
settings_window: None,
library_window: None,
timeline_window: None,
archive_window: None,
archive_items: Vec::new(),
library_items: Vec::new(),
library_uses: std::collections::BTreeMap::new(),
last_section: ui::view::Section::Rotation,
status: ui::view::Status::default(),
ui_test: ui_test_out.map(UiTest::new),
};
if let Err(e) = event_loop.run_app(&mut app) {
tracing::error!(target: "clairlune", error = %e, "event loop ended with an error");
}
}
#[cfg(test)]
mod tests {
use super::*;
use settings::ThemeMode;
#[test]
fn version_and_help_answer_without_starting() {
let args = |a: &[&str]| -> Vec<String> {
std::iter::once("clairlune")
.chain(a.iter().copied())
.map(String::from)
.collect()
};
let v = command_line_answer(&args(&["--version"])).unwrap();
assert_eq!(v, format!("{APP_NAME} {}", env!("CARGO_PKG_VERSION")));
assert_eq!(command_line_answer(&args(&["-V"])), Some(v));
assert!(
command_line_answer(&args(&["--help"]))
.unwrap()
.contains("--version")
);
assert_eq!(command_line_answer(&args(&[])), None);
assert_eq!(command_line_answer(&args(&["--ui-test", "x"])), None);
}
#[test]
fn theme_mode_resolves() {
let with = |mode| settings::ThemeSettings {
mode,
..Default::default()
};
assert_eq!(apply::resolve_theme(&with(ThemeMode::Light)), Theme::Light);
assert_eq!(apply::resolve_theme(&with(ThemeMode::Dark)), Theme::Dark);
let _ = apply::resolve_theme(&with(ThemeMode::FollowSystem));
}
#[test]
fn a_theme_schedule_follows_the_clock_or_the_sun() {
use jiff::civil::date;
let ny = jiff::tz::TimeZone::get("America/New_York").unwrap();
let at = |h: i8, m: i8| {
date(2026, 6, 21)
.at(h, m, 0, 0)
.to_zoned_datetime(ny.clone())
.unwrap()
};
let mut t = settings::ThemeSettings {
mode: ThemeMode::Schedule,
..Default::default()
};
assert_eq!(apply::resolve_theme_at(&t, &at(18, 59)), Theme::Light);
assert_eq!(apply::resolve_theme_at(&t, &at(19, 0)), Theme::Dark);
assert_eq!(apply::resolve_theme_at(&t, &at(2, 0)), Theme::Dark);
assert_eq!(apply::resolve_theme_at(&t, &at(7, 0)), Theme::Light);
(t.dark_from, t.light_from) = ("13:00".into(), "14:30".into());
assert_eq!(apply::resolve_theme_at(&t, &at(12, 59)), Theme::Light);
assert_eq!(apply::resolve_theme_at(&t, &at(14, 0)), Theme::Dark);
assert_eq!(apply::resolve_theme_at(&t, &at(14, 30)), Theme::Light);
t.follow_sun = true;
t.location = "40.71, -74.01".into();
assert_eq!(apply::resolve_theme_at(&t, &at(5, 10)), Theme::Dark);
assert_eq!(apply::resolve_theme_at(&t, &at(13, 30)), Theme::Light);
assert_eq!(apply::resolve_theme_at(&t, &at(20, 20)), Theme::Light);
assert_eq!(apply::resolve_theme_at(&t, &at(20, 45)), Theme::Dark);
t.location = "somewhere".into();
assert_eq!(apply::resolve_theme_at(&t, &at(13, 30)), Theme::Dark);
}
#[test]
fn a_second_instance_is_refused() {
let dir = std::env::temp_dir().join(format!("clairlune-instance-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let first = single_instance(&dir).unwrap();
assert!(single_instance(&dir).is_err());
drop(first);
assert!(single_instance(&dir).is_ok());
let _ = std::fs::remove_dir_all(&dir);
}
}