wallswitch 0.62.4

randomly selects wallpapers for multiple monitors
Documentation
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use crate::{
    Arguments, Complex, Desktop, Environment, Monitor, Orientation, ProceduralEffect, U8Extension,
    WallSwitchError, WallSwitchResult, get_feh_path, get_monitors,
};
use serde::{Deserialize, Serialize};
use std::{
    fs::{self, File},
    io::{BufReader, BufWriter, Write},
    path::{Path, PathBuf},
};

/// Configurable parameters and custom presets for procedural mathematical overlays.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectsConfig {
    /// If true, append custom config presets to the default hardcoded presets.
    ///
    /// If false, use only the presets specified in the config file.
    #[serde(default = "default_true")]
    pub add_presets: bool,
    /// Minimum iteration limit for escape-time fractal calculations.
    #[serde(default = "default_min_iterations")]
    pub min_iterations: u32,
    /// Maximum iteration limit for escape-time fractal calculations.
    #[serde(default = "default_max_iterations")]
    pub max_iterations: u32,
    /// User-defined Julia Set presets.
    #[serde(default)]
    pub julia: Vec<CustomFractalPreset>,
    /// User-defined Mandelbrot Set presets.
    #[serde(default)]
    pub mandelbrot: Vec<CustomFractalPreset>,
    /// User-defined Newton-Raphson Basin presets.
    #[serde(default)]
    pub newton: Vec<CustomNewtonPreset>,
    /// User-defined Nova Julia presets.
    #[serde(default)]
    pub nova: Vec<CustomNovaPreset>,
}

impl Default for EffectsConfig {
    /// Initialises default configuration parameters and seeds the configuration with
    /// two distinct presets for each mathematical generator to provide immediate visual variety.
    fn default() -> Self {
        Self {
            add_presets: default_true(),
            min_iterations: default_min_iterations(),
            max_iterations: default_max_iterations(),
            julia: vec![
                CustomFractalPreset {
                    center: Complex { re: -0.8, im: 0.18 },
                    fractal_name: "Stardust spiral galaxy arms".to_string(),
                },
                CustomFractalPreset {
                    center: Complex {
                        re: 0.285,
                        im: 0.535,
                    },
                    fractal_name: "Pinwheel orbital clouds".to_string(),
                },
            ],
            mandelbrot: vec![
                CustomFractalPreset {
                    center: Complex {
                        re: -0.74,
                        im: 0.24,
                    },
                    fractal_name: "custom v1".to_string(),
                },
                CustomFractalPreset {
                    center: Complex {
                        re: -0.088,
                        im: 0.655,
                    },
                    fractal_name: "custom v2".to_string(),
                },
            ],
            newton: vec![
                CustomNewtonPreset {
                    power: 7,
                    lambda: Complex { re: 0.95, im: 0.55 },
                    name: "Aetheric prismatic vortex".to_string(),
                },
                CustomNewtonPreset {
                    power: 3,
                    lambda: Complex { re: 1.50, im: 0.25 },
                    name: "Over-relaxed geometric crown".to_string(),
                },
            ],
            nova: vec![
                CustomNovaPreset {
                    power: 4,
                    c: Complex {
                        re: -0.15,
                        im: -0.35,
                    },
                    r: Complex { re: 1.10, im: 0.20 },
                    name: "Bioluminescent plasma plumes".to_string(),
                },
                CustomNovaPreset {
                    power: 6,
                    c: Complex { re: 0.25, im: 0.40 },
                    r: Complex {
                        re: 0.85,
                        im: -0.15,
                    },
                    name: "Astral jellyfish lattice".to_string(),
                },
            ],
        }
    }
}

/// Helper function providing a default true value for Serde deserialisation.
fn default_true() -> bool {
    true
}

fn default_min_iterations() -> u32 {
    600
}

fn default_max_iterations() -> u32 {
    1200
}

/// A serialized custom Julia/Mandelbrot preset representing the focal point.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomFractalPreset {
    pub center: Complex,
    pub fractal_name: String,
}

/// A serialized custom Newton preset representing root-finding convergence fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomNewtonPreset {
    pub power: u32,
    pub lambda: Complex,
    pub name: String,
}

/// A serialized custom Nova preset representing dynamic fluid-like plumes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomNovaPreset {
    pub power: u32,
    pub c: Complex,
    pub r: Complex,
    pub name: String,
}

/// Configuration variables
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    /// Desktops: gnome, xfce, openbox, ...
    pub desktop: Desktop,
    /// Directories containing image files
    pub directories: Vec<PathBuf>,
    /// Image file extension (identify -list format)
    pub extensions: Vec<String>,
    /// Interval (in seconds) between each wallpaper displayed
    pub interval: u64,
    /// Minimum dimension
    pub min_dimension: u64,
    /// Maximum dimension
    pub max_dimension: u64,
    /// Minimum file size
    pub min_size: u64,
    /// Maximum file size
    pub max_size: u64,
    /// Monitor properties
    pub monitors: Vec<Monitor>,
    /// Attach images to monitors in the Horizontal or Vertical orientation
    pub monitor_orientation: Orientation,

    /// Run a single wallpaper update cycle and exit
    #[serde(skip)]
    pub once: bool,

    /// feh binary path
    pub path_feh: PathBuf,
    /// Sort the images found
    pub sort: bool,
    /// Selected procedural overlay effect (none, fractal, star, random)
    pub effect: ProceduralEffect,
    /// Configurable parameters and custom presets for mathematical overlays
    #[serde(default)]
    pub effects: EffectsConfig,
    /// Wallpaper file path used by gnome desktop
    pub wallpaper: PathBuf,

    /// Run without actually applying wallpapers (Simulation mode)
    #[serde(skip)]
    pub dry_run: bool,

    /// Animation transition type for awww daemon
    pub transition_type: String,
    /// Duration of awww transition in seconds
    pub transition_duration: u16,
    /// Framerate of the awww transition animation
    pub transition_fps: u16,
    /// Angle for wipe/wave transitions
    pub transition_angle: u16,
    /// Starting position for center/outer transitions
    pub transition_pos: String,

    /// Show intermediate runtime messages
    #[serde(skip)]
    pub verbose: bool,
}

impl Default for Config {
    fn default() -> Self {
        // Set image extensions (identify -list format)
        let extensions: Vec<String> = ["avif", "jpg", "jpeg", "png", "tif", "webp"]
            .iter()
            .map(ToString::to_string)
            .collect();

        // Interval: 30 * 60 = 1800 seconds (30 minutes)
        let interval: u64 = 30 * 60;

        // Dimension.height >= min_dimension && dimension.width >= min_dimension
        let min_dimension: u64 = 600;

        // Dimension.height <= max_dimension && dimension.width <= max_dimension
        let max_dimension: u64 = 128_000;

        Config {
            desktop: Desktop::detect(),
            min_dimension,
            max_dimension,
            min_size: u64::pow(1024, 1), // 1024 ^ 1 = 1kb
            max_size: u64::pow(1024, 3), // 1024 ^ 3 = 1Gb
            directories: get_directories().unwrap_or_default(),
            effect: ProceduralEffect::None,
            effects: EffectsConfig::default(),
            extensions,
            interval,
            monitors: get_monitors(2),
            monitor_orientation: Orientation::Horizontal,
            once: false,
            path_feh: PathBuf::from("/usr/bin/feh"),
            sort: false,
            verbose: false,
            wallpaper: get_wallpaper_path().unwrap_or_default(),
            dry_run: false,
            transition_type: "random".to_string(),
            transition_duration: 2,
            transition_fps: 60,
            transition_angle: 45,
            transition_pos: "center".to_string(),
        }
    }
}

// Set boundary config values
fn config_boundary() -> Config {
    Config {
        interval: 5,
        min_dimension: 10,
        min_size: 1,
        monitors: vec![Monitor::default()],
        ..Config::default()
    }
}

impl Config {
    /// Merges settings from the JSON file with parsed command-line arguments.
    ///
    /// Priority: 1. CLI Args -> 2. Config File -> 3. Defaults.
    pub fn new(args: &Arguments) -> WallSwitchResult<Self> {
        let mut read_default_config = false;
        let config_path: PathBuf = get_config_path()?;

        // Attempt to read the existing JSON file; fallback to Default if missing
        let config: Config = match read_config_file(&config_path) {
            Ok(configuration) => configuration,
            Err(_) => {
                read_default_config = true;
                Self::default()
            }
        }
        // Apply CLI overrides, validate values, and sync the JSON file back to disk
        .set_command_line_arguments(args)?
        .validate_config()?
        .write_config_file(&config_path, read_default_config)?;

        Ok(config)
    }

    /// Check if the value is in the range
    pub fn in_range(&self, value: u64) -> bool {
        self.min_dimension <= value && value <= self.max_dimension
    }

    /// Print Config
    pub fn print(&self) -> WallSwitchResult<()> {
        let json: String = serde_json::to_string_pretty(self)?;
        println!("Config:\n{json}\n");

        Ok(())
    }

    /// Set command-line arguments for configuration
    ///
    /// Update self: Config values
    fn set_command_line_arguments(mut self, args: &Arguments) -> WallSwitchResult<Self> {
        if let Some(min_dimension) = args.min_dimension {
            self.min_dimension = min_dimension;
        }

        if let Some(max_dimension) = args.max_dimension {
            self.max_dimension = max_dimension;
        }

        if let Some(min_size) = args.min_size {
            self.min_size = min_size;
        }

        if let Some(max_size) = args.max_size {
            self.max_size = max_size;
        }

        if let Some(interval) = args.interval {
            self.interval = interval;
        }

        if let Some(monitor) = args.monitor {
            self.monitors = get_monitors(monitor.into());
        }

        if let Some(orientation) = &args.monitor_orientation {
            self.monitor_orientation = orientation.clone();
        }

        if let Some(pictures_per_monitor) = args.pictures_per_monitor {
            for monitor in &mut self.monitors {
                monitor.pictures_per_monitor = pictures_per_monitor;
            }
        }

        self.once = args.once;

        if args.dry_run {
            self.dry_run = true;
            self.once = true; // Force a single execution cycle and exit on dry-run
        }
        if let Some(ref t) = args.transition_type {
            self.transition_type = t.clone();
        }
        if let Some(d) = args.transition_duration {
            self.transition_duration = d;
        }
        if let Some(f) = args.transition_fps {
            self.transition_fps = f;
        }
        if let Some(a) = args.transition_angle {
            self.transition_angle = a;
        }
        if let Some(ref p) = args.transition_pos {
            self.transition_pos = p.clone();
        }

        if let Some(effect) = args.effect {
            self.effect = effect;
        }

        // Apply CLI overrides for procedural mathematical overlay details (EffectsConfig)
        if let Some(effects_add_presets) = args.effects_add_presets {
            self.effects.add_presets = effects_add_presets;
        }

        if let Some(effects_min_iterations) = args.effects_min_iterations {
            self.effects.min_iterations = effects_min_iterations;
        }

        if let Some(effects_max_iterations) = args.effects_max_iterations {
            self.effects.max_iterations = effects_max_iterations;
        }

        if args.sort {
            self.sort = !self.sort;
        }

        if args.verbose {
            self.verbose = !self.verbose;
        }

        self.desktop = Desktop::detect(); // Update desktop

        Ok(self)
    }

    /// Validate configuration
    pub fn validate_config(mut self) -> WallSwitchResult<Self> {
        let boundary: Config = config_boundary();

        // Note: Multiple pictures per monitor (-p) is now fully supported on all desktops!

        if self.interval < boundary.interval {
            let value = self.interval.to_string();
            return Err(WallSwitchError::AtLeastValue {
                arg: "--interval".to_string(),
                value,
                num: boundary.interval,
            });
        }

        if !self.path_feh.is_file() {
            self.path_feh = get_feh_path(true)?;
        }

        if self.min_dimension < boundary.min_dimension {
            let value = self.min_dimension.to_string();
            return Err(WallSwitchError::AtLeastValue {
                arg: "--min_dimension".to_string(),
                value,
                num: boundary.min_dimension,
            });
        }

        if self.min_size < boundary.min_size {
            let value = self.min_size.to_string();
            return Err(WallSwitchError::AtLeastValue {
                arg: "--min_size".to_string(),
                value,
                num: boundary.min_size,
            });
        }

        if self.monitors.is_empty() {
            let value = self.monitors.len().to_string();
            return Err(WallSwitchError::AtLeastValue {
                arg: "--interval".to_string(),
                value,
                num: 1,
            });
        }

        for monitor in &self.monitors {
            if monitor.pictures_per_monitor < 1 {
                let value = monitor.pictures_per_monitor.to_string();
                return Err(WallSwitchError::AtLeastValue {
                    arg: "--picture".to_string(),
                    value,
                    num: 1,
                });
            }
        }

        if let Some(parent) = self.wallpaper.parent()
            && !parent.exists()
        {
            // Ensure the directory exists
            fs::create_dir_all(parent)?;
        }

        // Validate basic boundary pairs
        for (min, max) in [
            (self.min_dimension, self.max_dimension),
            (self.min_size, self.max_size),
        ] {
            if min > max {
                return Err(WallSwitchError::MinMax { min, max });
            }
        }

        // Validate that min_iterations does not exceed max_iterations
        if self.effects.min_iterations > self.effects.max_iterations {
            return Err(WallSwitchError::MinMax {
                min: self.effects.min_iterations as u64,
                max: self.effects.max_iterations as u64,
            });
        }

        Ok(self)
    }

    /// Write config file path:: "/home/user_name/.config/wallswitch/wallswitch.json"
    pub fn write_config_file(
        self,
        path: &PathBuf,
        read_default_config: bool,
    ) -> WallSwitchResult<Self> {
        if read_default_config {
            eprintln!("Create the configuration file: {path:?}\n");
        }

        // Recursively create a directory and all of its parent components if they are missing
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?
        };

        let file: File = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
            .map_err(|io_error| WallSwitchError::IOError {
                path: path.to_path_buf(),
                io_error,
            })?;

        let mut writer = BufWriter::new(file);
        serde_json::to_writer_pretty(&mut writer, &self)?;
        writer.flush()?;

        Ok(self)
    }

    /// Get the number of images per cycle
    pub fn get_number_of_images(&self) -> usize {
        self.monitors
            .iter()
            .map(|monitor| monitor.pictures_per_monitor.to_usize())
            .sum()
    }
}

/// Default wallpaper path: "/home/user_name/wallswitch.jpg"
pub fn get_wallpaper_path() -> WallSwitchResult<PathBuf> {
    let env = Environment::new()?;
    let home = env.get_home();
    let pkg_name = env.get_pkg_name();

    let mut wallpaper_path: PathBuf = [home, pkg_name].iter().collect();
    wallpaper_path.set_extension("jpg");

    Ok(wallpaper_path)
}

/// Default directories to search for images
pub fn get_directories() -> WallSwitchResult<Vec<PathBuf>> {
    let env = Environment::new()?;
    let home = env.get_home();

    let images = ["Figures", "Images", "Pictures", "Wallpapers", "Imagens"];

    // Create a vector of image directories under the home directory
    let directories_home: Vec<PathBuf> = images
        .into_iter()
        .map(|image| Path::new(home).join(image))
        .collect();

    // Use std::path::MAIN_SEPARATOR directly
    let sep = std::path::MAIN_SEPARATOR.to_string();

    // Add default system backgrounds directories
    let path1: PathBuf = [&sep, "usr", "share", "wallpapers"].iter().collect();
    let path2: PathBuf = [&sep, "usr", "share", "backgrounds"].iter().collect();

    // Create a vector of additional image directories
    let directories_others: Vec<PathBuf> = vec![path1, path2];

    // Combine the two vectors and return
    Ok(directories_home
        .into_iter()
        .chain(directories_others)
        .collect())
}

/// Config file path: "/home/user_name/.config/wallswitch/wallswitch.json"
pub fn get_config_path() -> WallSwitchResult<PathBuf> {
    let env = Environment::new()?;
    let home = env.get_home();
    let pkg_name = env.get_pkg_name();
    let hidden_dir = ".config";

    let mut config_path: PathBuf = [home, hidden_dir, pkg_name, pkg_name].iter().collect();
    config_path.set_extension("json");

    Ok(config_path)
}

/// Read config file path: "/home/user_name/.config/wallswitch/wallswitch.json"
pub fn read_config_file<P>(path: P) -> WallSwitchResult<Config>
where
    P: AsRef<Path>,
{
    // Open the file in read-only mode with buffer
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    // Read the JSON contents of the file as an instance of `Config`
    let config: Config = serde_json::from_reader(reader)?;

    Ok(config)
}