clairlune 0.17.6

Procedural, animated ASCII-art desktop wallpapers. Local, seeded and deterministic; no AI, no network.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! The tray (menu-bar) icon and its menu (PLAN.md section 10): the
//! notification area on Windows, the menu bar on macOS, a StatusNotifierItem
//! over D-Bus on Linux (ksni; desktops without a tray host, such as stock
//! GNOME, fall back to the Settings window).

use crate::settings::ThemeMode;
use clairlune_platform::Monitor;
use std::cell::{Cell, RefCell};
use tray_icon::menu::{CheckMenuItem, Menu, MenuId, MenuItem, PredefinedMenuItem, Submenu};
use tray_icon::{Icon, TrayIcon, TrayIconBuilder};

/// What a menu click asks for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
    NewWallpaper,
    /// A new scene on one monitor (its place in the submenu).
    NewWallpaperOn(usize),
    Previous,
    Theme(ThemeMode),
    ToggleLive,
    TogglePause,
    SavePng,
    SaveGif,
    SaveToLibrary,
    OpenLibrary,
    OpenTimeline,
    OpenArchive,
    OpenSettings,
    /// The newer version: install it, or open its release page.
    OpenUpdate,
    /// macOS: start the screen saver, which locks the Mac with the scene
    /// playing.
    LockScreen,
    Quit,
}

pub struct Tray {
    _icon: TrayIcon,
    menu: Menu,
    new: MenuItem,
    /// "New wallpaper on": one item per monitor, shown with two or more.
    on_monitor: Submenu,
    monitors: RefCell<Vec<(MenuItem, String)>>,
    on_monitor_shown: Cell<bool>,
    previous: MenuItem,
    follow: CheckMenuItem,
    light: CheckMenuItem,
    dark: CheckMenuItem,
    scheduled: CheckMenuItem,
    live: CheckMenuItem,
    pause: CheckMenuItem,
    save: MenuItem,
    save_gif: MenuItem,
    save_lib: MenuItem,
    library: MenuItem,
    timeline: MenuItem,
    archive: MenuItem,
    settings: MenuItem,
    quit: MenuItem,
    /// "Update available": at the top of the menu while there is one.
    update: MenuItem,
    update_shown: Cell<bool>,
    /// macOS: "Lock Screen" (with the screen saver), above Settings while
    /// the screen saver is on.
    lock: MenuItem,
    lock_shown: Cell<bool>,
}

/// The colour of the mark: macOS gets black, as a template it tints itself
/// (white on a dark menu bar); elsewhere white, or black on a light taskbar,
/// where white wouldn't show.
fn mark_colour() -> [u8; 3] {
    if cfg!(target_os = "macos") || clairlune_platform::taskbar_is_light() == Some(true) {
        [0, 0, 0]
    } else {
        [255, 255, 255]
    }
}

/// The tray mark at the size the system shows it sharp at: 36 on macOS (an
/// 18-point menu bar icon at 2x), 32 elsewhere.
fn mark() -> Result<Icon, String> {
    let size = if cfg!(target_os = "macos") { 36 } else { 32 };
    Icon::from_rgba(crate::icon::tray_rgba(size, mark_colour()), size, size)
        .map_err(|e| e.to_string())
}

impl Tray {
    pub fn new(mode: ThemeMode, paused: bool, live_on: bool) -> Result<Tray, String> {
        let new = MenuItem::new("New wallpaper", true, None);
        let on_monitor = Submenu::new("New wallpaper on", true);
        let previous = MenuItem::new("Previous wallpaper", true, None);
        let follow =
            CheckMenuItem::new("Follow system", true, mode == ThemeMode::FollowSystem, None);
        let light = CheckMenuItem::new("Light", true, mode == ThemeMode::Light, None);
        let dark = CheckMenuItem::new("Dark", true, mode == ThemeMode::Dark, None);
        let scheduled = CheckMenuItem::new("Schedule", true, mode == ThemeMode::Schedule, None);
        let theme = Submenu::new("Theme", true);
        theme
            .append_items(&[&follow, &light, &dark, &scheduled])
            .map_err(|e| e.to_string())?;
        let live = CheckMenuItem::new(
            "Live wallpaper",
            crate::live::supported().is_ok(),
            live_on,
            None,
        );
        let pause = CheckMenuItem::new("Pause changes", true, paused, None);
        let save = MenuItem::new("Save current as PNG", true, None);
        let save_gif = MenuItem::new("Save current as GIF", true, None);
        let save_lib = MenuItem::new("Save to library", true, None);
        let library = MenuItem::new("Library\u{2026}", true, None);
        let timeline = MenuItem::new("Timeline\u{2026}", true, None);
        let archive = MenuItem::new("Archive\u{2026}", true, None);
        let settings = MenuItem::new("Settings\u{2026}", true, None);
        let quit = MenuItem::new("Quit Clairlune", true, None);
        let update = MenuItem::new("Update available\u{2026}", true, None);
        let lock = MenuItem::new("Lock Screen", true, None);
        let menu = Menu::new();
        menu.append_items(&[
            &new,
            &previous,
            &PredefinedMenuItem::separator(),
            &theme,
            &live,
            &pause,
            &PredefinedMenuItem::separator(),
            &save,
            &save_gif,
            &save_lib,
            &library,
            &timeline,
            &archive,
            &settings,
            &PredefinedMenuItem::separator(),
            &quit,
        ])
        .map_err(|e| e.to_string())?;
        let builder = TrayIconBuilder::new()
            .with_menu(Box::new(menu.clone()))
            // Windows: a double click opens the app, so a single left click
            // mustn't pop the menu up first; the menu is on the right button.
            .with_menu_on_left_click(cfg!(not(windows)))
            .with_tooltip(clairlune_scene::APP_NAME);
        // macOS tints a template icon to suit the menu bar.
        #[cfg(target_os = "macos")]
        let builder = builder.with_icon_templated(mark()?);
        #[cfg(not(target_os = "macos"))]
        let builder = builder.with_icon(mark()?);
        let tray = builder.build().map_err(|e| e.to_string())?;
        Ok(Tray {
            _icon: tray,
            menu,
            new,
            on_monitor,
            monitors: RefCell::new(Vec::new()),
            on_monitor_shown: Cell::new(false),
            previous,
            follow,
            light,
            dark,
            scheduled,
            live,
            pause,
            save,
            save_gif,
            save_lib,
            library,
            timeline,
            archive,
            settings,
            quit,
            update,
            update_shown: Cell::new(false),
            lock,
            lock_shown: Cell::new(false),
        })
    }

    pub fn action(&self, id: &MenuId) -> Option<Action> {
        let pairs = [
            (self.new.id(), Action::NewWallpaper),
            (self.previous.id(), Action::Previous),
            (self.follow.id(), Action::Theme(ThemeMode::FollowSystem)),
            (self.light.id(), Action::Theme(ThemeMode::Light)),
            (self.dark.id(), Action::Theme(ThemeMode::Dark)),
            (self.scheduled.id(), Action::Theme(ThemeMode::Schedule)),
            (self.live.id(), Action::ToggleLive),
            (self.pause.id(), Action::TogglePause),
            (self.save.id(), Action::SavePng),
            (self.save_gif.id(), Action::SaveGif),
            (self.save_lib.id(), Action::SaveToLibrary),
            (self.library.id(), Action::OpenLibrary),
            (self.timeline.id(), Action::OpenTimeline),
            (self.archive.id(), Action::OpenArchive),
            (self.settings.id(), Action::OpenSettings),
            (self.update.id(), Action::OpenUpdate),
            (self.lock.id(), Action::LockScreen),
            (self.quit.id(), Action::Quit),
        ];
        if let Some(a) = pairs.into_iter().find(|(i, _)| *i == id).map(|(_, a)| a) {
            return Some(a);
        }
        self.monitors
            .borrow()
            .iter()
            .position(|(item, _)| item.id() == id)
            .map(Action::NewWallpaperOn)
    }

    /// The monitor id behind a "New wallpaper on" item.
    pub fn monitor_id(&self, i: usize) -> Option<String> {
        self.monitors.borrow().get(i).map(|(_, id)| id.clone())
    }

    /// The monitors that can each get a new scene: the submenu lists them
    /// with two or more, and is hidden otherwise.
    pub fn set_monitors(&self, monitors: &[Monitor]) {
        let mut items = self.monitors.borrow_mut();
        for (item, _) in items.drain(..) {
            let _ = self.on_monitor.remove(&item);
        }
        if monitors.len() < 2 {
            if self.on_monitor_shown.replace(false) {
                let _ = self.menu.remove(&self.on_monitor);
            }
            return;
        }
        for (m, label) in monitors.iter().zip(monitor_labels(monitors)) {
            let item = MenuItem::new(label, true, None);
            if self.on_monitor.append(&item).is_ok() {
                items.push((item, m.id.clone()));
            }
        }
        if !self.on_monitor_shown.replace(true) {
            let _ = self.menu.insert(&self.on_monitor, 1);
        }
    }

    /// Shows the newer version at the top of the menu ("Update to 0.16.0"
    /// where a click installs it, "Clairlune 0.16.0 is out" where it opens
    /// the release page), or takes it away (`None`).
    pub fn show_update(&self, version: Option<&str>, in_place: bool) {
        match version {
            Some(v) => {
                self.update.set_text(if in_place {
                    format!("Update to {v}\u{2026}")
                } else {
                    format!("Clairlune {v} is out\u{2026}")
                });
                if !self.update_shown.get() {
                    let _ = self.menu.insert(&self.update, 0);
                    self.update_shown.set(true);
                }
            }
            None => {
                if self.update_shown.get() {
                    let _ = self.menu.remove(&self.update);
                    self.update_shown.set(false);
                }
            }
        }
    }

    /// Draws the mark again for the taskbar's colour now (Windows: the
    /// taskbar turned light or dark).
    pub fn refresh_mark(&self) {
        if let Ok(icon) = mark() {
            #[cfg(target_os = "macos")]
            let _ = self._icon.set_icon_templated(Some(icon));
            #[cfg(not(target_os = "macos"))]
            let _ = self._icon.set_icon(Some(icon));
        }
    }

    /// macOS: shows "Lock Screen" above Settings, or takes it away.
    pub fn show_lock(&self, on: bool) {
        if on == self.lock_shown.get() {
            return;
        }
        if on {
            let at = self
                .menu
                .items()
                .iter()
                .position(|i| i.id() == self.settings.id())
                .unwrap_or(0);
            let _ = self.menu.insert(&self.lock, at);
        } else {
            let _ = self.menu.remove(&self.lock);
        }
        self.lock_shown.set(on);
    }

    /// Shows the theme mode as a radio group (check items toggle themselves on
    /// click, so the state is always set from the settings).
    pub fn show_theme(&self, mode: ThemeMode) {
        self.follow.set_checked(mode == ThemeMode::FollowSystem);
        self.light.set_checked(mode == ThemeMode::Light);
        self.dark.set_checked(mode == ThemeMode::Dark);
        self.scheduled.set_checked(mode == ThemeMode::Schedule);
    }

    /// Check items toggle themselves on click; the setting decides.
    pub fn show_live(&self, on: bool) {
        self.live.set_checked(on);
    }

    pub fn show_paused(&self, paused: bool) {
        self.pause.set_checked(paused);
    }

    pub fn set_tooltip(&self, text: &str) {
        let _ = self._icon.set_tooltip(Some(text));
    }

    /// Grey out the generating actions while a job runs.
    pub fn set_busy(&self, busy: bool) {
        self.new.set_enabled(!busy);
        self.on_monitor.set_enabled(!busy);
        self.previous.set_enabled(!busy);
    }
}

/// Names for monitors in a menu, by where they are: two side by side are
/// Left and Right (or Top and Bottom), more are numbered left to right;
/// each with its size, and the main one marked.
pub fn monitor_labels(monitors: &[Monitor]) -> Vec<String> {
    let mut order: Vec<usize> = (0..monitors.len()).collect();
    order.sort_by_key(|&i| (monitors[i].x, monitors[i].y));
    let stacked = monitors.len() == 2 && {
        let (a, b) = (&monitors[order[0]], &monitors[order[1]]);
        b.x < a.x + a.width as i32 && a.x < b.x + b.width as i32
    };
    if stacked {
        order.sort_by_key(|&i| (monitors[i].y, monitors[i].x));
    }
    let mut labels = vec![String::new(); monitors.len()];
    for (rank, &i) in order.iter().enumerate() {
        let m = &monitors[i];
        let place = match (monitors.len(), stacked, rank) {
            (2, false, 0) => "Left".to_string(),
            (2, false, _) => "Right".to_string(),
            (2, true, 0) => "Top".to_string(),
            (2, true, _) => "Bottom".to_string(),
            _ => format!("Monitor {}", rank + 1),
        };
        let main = if m.primary { ", main" } else { "" };
        labels[i] = format!("{place} ({}\u{d7}{}{main})", m.width, m.height);
    }
    labels
}

#[cfg(test)]
mod tests {
    use super::*;

    fn m(id: &str, x: i32, y: i32, w: u32, h: u32, primary: bool) -> Monitor {
        Monitor {
            id: id.into(),
            x,
            y,
            width: w,
            height: h,
            primary,
        }
    }

    #[test]
    fn monitors_are_named_by_where_they_are() {
        let side = [
            m("b", 2560, 0, 1920, 1080, false),
            m("a", 0, 0, 2560, 1440, true),
        ];
        assert_eq!(
            monitor_labels(&side),
            ["Right (1920\u{d7}1080)", "Left (2560\u{d7}1440, main)"]
        );
        // The second one on the left of the main one (negative x).
        let left = [
            m("a", 0, 0, 1920, 1080, true),
            m("b", -1920, 0, 1920, 1080, false),
        ];
        assert_eq!(monitor_labels(&left)[1], "Left (1920\u{d7}1080)");
        let stacked = [
            m("a", 0, 1080, 1920, 1080, true),
            m("b", 0, 0, 1920, 1080, false),
        ];
        assert_eq!(
            monitor_labels(&stacked),
            ["Bottom (1920\u{d7}1080, main)", "Top (1920\u{d7}1080)"]
        );
        let three = [
            m("c", 3840, 0, 1920, 1080, false),
            m("a", 0, 0, 1920, 1080, false),
            m("b", 1920, 0, 1920, 1080, true),
        ];
        assert_eq!(
            monitor_labels(&three),
            [
                "Monitor 3 (1920\u{d7}1080)",
                "Monitor 1 (1920\u{d7}1080)",
                "Monitor 2 (1920\u{d7}1080, main)"
            ]
        );
    }
}