wallswitch 0.55.0

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
// use args_v2
// cargo b -r && cargo install --path=. --features args_v2

use serde::{Deserialize, Serialize};
use std::{
    fmt::Debug,
    str::{self, FromStr},
};

use crate::{
    ENVIRON, Orientation, SortCriteria, WallSwitchError::{self, *}, WallSwitchResult, get_config_path, read_config_file
};

#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct Arguments {
    // see config::config_boundary() values
    /// Set a minimum file size (in bytes) for searching image files.
    ///
    /// keep files whose size is greater than or equal to a minimum value.
    ///
    /// size >= min_size
    pub min_size: Option<u64>,

    /// Set a maximum file size (in bytes) for searching image files.
    ///
    /// keep files whose size is less than or equal to a maximum value.
    ///
    /// size <= max_size
    pub max_size: Option<u64>,

    /// Read the configuration file and exit the program.
    pub config: bool,

    /// Set the minimum dimension that the height and width must satisfy.
    ///
    /// width >= min_dimension && height >= min_dimension
    ///
    /// Default value: min_dimension = 600.
    pub min_dimension: Option<u64>,

    /// Set the maximum dimension that the height and width must satisfy.
    ///
    /// width <= max_dimension && height <= max_dimension
    pub max_dimension: Option<u64>,

    /// Print help (see more with '--help')
    pub help: bool,

    /// Set the interval (in seconds) between each wallpaper displayed.
    ///
    /// Default value: interval = 30 * 60 = 1800 seconds (30 minutes).
    pub interval: Option<u64>,

    /// List all found images and exit. 
    ///
    /// Sort criteria: [path, size, name, extension]
    pub list: Option<SortCriteria>,

    /// Set the number of monitors [default: 2]
    pub monitor: Option<u8>,

    /// Inform monitor orientation: Horizontal (side-by-side) or Vertical (stacked).
    ///
    /// Orientation: [Horizontal, Vertical]
    ///
    /// Default orientation: Horizontal.
    pub monitor_orientation: Option<Orientation>,

    /// Run a single wallpaper update cycle and exit.
    pub once: bool,

    /// Set number of pictures (or images) per monitor [default: 1]
    ///
    /// Each monitor can have a diferent number of pictures (or images)
    ///
    /// Gnome desktop only
    pub pictures_per_monitor: Option<u8>,

    /// Sort the images found.
    pub sort: bool,

    /// Run without applying the wallpapers (simulation mode).
    pub dry_run: bool,

    /// Transition type for Wayland compositors using awww (e.g. wipe, wave, fade, random).
    pub transition_type: Option<String>,

    /// Duration of the transition animation in seconds.
    pub transition_duration: Option<u16>,

    /// Frames per second for transition smoothness.
    pub transition_fps: Option<u16>,

    /// Angle used by directional transitions (wipe, wave).
    pub transition_angle: Option<u16>,

    /// Origin position used by grow/outer transitions (e.g. center, top).
    pub transition_pos: Option<String>,

    /// Show intermediate runtime messages.
    ///
    /// Show found images.
    ///
    /// Show pid numbers of previous running program.
    pub verbose: bool,

    // Print version
    pub version: bool,
}

impl Arguments {
    /// Parses command-line arguments and builds an `Arguments` struct.
    pub fn build() -> WallSwitchResult<Arguments> {
        let args = Arguments::parse(std::env::args())?;

        if args.config {
            let config_path = get_config_path()?;
            let config = read_config_file(&config_path)?;
            let json: String = serde_json::to_string_pretty(&config)?;
            println!("{json}");
            std::process::exit(0);
        }

        Ok(args)
    }

    /// Parses command-line arguments into an `Arguments` struct.
    ///
    /// <https://stackoverflow.com/questions/51119143/how-do-i-check-the-second-element-of-the-command-line-arguments>
    fn parse(args: impl Iterator<Item = String>) -> WallSwitchResult<Self> {
        let mut arguments = Arguments::default();

        let args: Vec<String> = get_formatted_args(args);
        // println!("args: {args:?}");

        if args.is_empty() {
            return Ok(arguments);
        }

        let mut iter = args.into_iter();

        while let Some(current) = iter.next() {
            match current.as_ref() {
                "--min_size" | "-b" => {
                    let min_size: u64 = parse_value(iter.next(), "--min_size", 0)?;
                    arguments.min_size = Some(min_size)
                }
                "--max_size" | "-B" => {
                    let max_size: u64 = parse_value(iter.next(), "--max_size", 0)?;
                    arguments.max_size = Some(max_size)
                }
                "--min_dimension" | "-d" => {
                    let dimension: u64 = parse_value(iter.next(), "--min_dimension", 10)?;
                    arguments.min_dimension = Some(dimension)
                }
                "--max_dimension" | "-D" => {
                    let dimension: u64 = parse_value(iter.next(), "--max_dimension", 0)?;
                    arguments.max_dimension = Some(dimension)
                }
                "--interval" | "-i" => {
                    let interval: u64 = parse_value(iter.next(), "--interval", 5)?;
                    arguments.interval = Some(interval)
                }
                "--list" | "-l" => {
                    let criteria = parse_criteria(iter.next(), "--list")?;
                    arguments.list = Some(criteria);
                }
                "--monitor" | "-m" => {
                    let value: u64 = parse_value(iter.next(), "--monitor", 1)?;
                    let monitor: u8 = value.try_into().map_err(WallSwitchError::from)?;
                    arguments.monitor = Some(monitor)
                }
                "--orientation" | "-o" => {
                    let orientation = parse_orientation(iter.next(), "--orientation")?;
                    arguments.monitor_orientation = Some(orientation)
                }
                "--pictures_per_monitor" | "-p" => {
                    let value: u64 = parse_value(iter.next(), "--pictures_per_monitor", 1)?;
                    let pictures_per_monitor: u8 =
                        value.try_into().map_err(WallSwitchError::from)?;
                    arguments.pictures_per_monitor = Some(pictures_per_monitor)
                }
                "--config" | "-c" => arguments.config = true,
                "--help" | "-h" => show_help_summary(),
                "--sort" | "-s" => arguments.sort = true,
                "--once" => arguments.once = true,

                "--dry-run" => arguments.dry_run = true,
                "--transition-type" => arguments.transition_type = iter.next(),
                "--transition-duration" => {
                    let v = parse_value(iter.next(), "--transition-duration", 0)?;
                    arguments.transition_duration = Some(v as u16);
                }
                "--transition-fps" => {
                    let v = parse_value(iter.next(), "--transition-fps", 1)?;
                    arguments.transition_fps = Some(v as u16);
                }
                "--transition-angle" => {
                    let v = parse_value(iter.next(), "--transition-angle", 0)?;
                    arguments.transition_angle = Some(v as u16);
                }
                "--transition-pos" => arguments.transition_pos = iter.next(),

                "--verbose" | "-v" => arguments.verbose = true,
                "--Version" | "-V" => show_version(),
                _ => return Err(UnexpectedArg { arg: current }),
            }
        }

        Ok(arguments)
    }
}

// Helper para o parser manual:
fn parse_criteria(opt_s: Option<String>, name: &'static str) -> WallSwitchResult<SortCriteria> {
    if let Some(s) = opt_s {
        SortCriteria::from_str(&s).map_err(|e| WallSwitchError::InvalidValue { arg: name.to_string(), value: e })
    } else {
        Err(WallSwitchError::MissingValue { arg: name.to_string() })
    }
}

/// Formats command-line arguments to separate flags and values
fn get_formatted_args(args: impl Iterator<Item = String>) -> Vec<String> {
    args.skip(1) // skip program name
        // Split "--arg===12345" to "--arg 12345"
        .flat_map(|arg: String| {
            arg.split('=')
                .map(ToString::to_string)
                .collect::<Vec<String>>()
        })
        // Splits inclusive on the first digit: "--arg12345" to "--arg 12345"
        .flat_map(|arg: String| {
            if let Some(index) = arg.find(|c: char| c.is_ascii_digit()) {
                vec![arg[..index].to_string(), arg[index..].to_string()]
            } else {
                vec![arg]
            }
        })
        .map(|arg: String| arg.trim().to_string())
        .filter(|arg| !arg.is_empty())
        .collect()
}

/// Parse `Option<String>` to u64
///
/// Minimum dimension should be at least 10
///
/// Minimum interval should be at least 5 seconds
///
/// Monitor number should be at least 1
fn parse_value(opt_value: Option<String>, name: &'static str, min: u64) -> WallSwitchResult<u64> {
    if let Some(value) = opt_value {
        // println!("value: {value}");
        match value.parse::<u64>() {
            // num value should be at least min: num >= min
            Ok(num) if num >= min => Ok(num),
            Ok(_) => Err(AtLeastValue {
                arg: name.to_string(),
                value,
                num: min,
            }),
            Err(_) => Err(InvalidValue {
                arg: name.to_string(),
                value,
            }),
        }
    } else {
        Err(MissingValue {
            arg: name.to_string(),
        })
    }
}

/// Parse `Option<String>` to Orientation
fn parse_orientation(
    opt_string: Option<String>,
    name: &'static str,
) -> WallSwitchResult<Orientation> {
    if let Some(string) = opt_string {
        Orientation::from_str(&string)
    } else {
        Err(MissingValue {
            arg: name.to_string(),
        })
    }
}

/// Display help information with descriptions
fn show_help_summary() {
    let pkg_name = ENVIRON.get_pkg_name();
    let pkg_descr = env!("CARGO_PKG_DESCRIPTION");
    println!("{pkg_descr}");
    println!("\nUsage: {pkg_name} [OPTIONS]\n");
    println!("Options:\n");
    println!(
        "-b, --min_size <MIN_SIZE>\n\tSet a minimum file size (in bytes) for searching image files"
    );
    println!(
        "-B, --max_size <MAX_SIZE>\n\tSet a maximum file size (in bytes) for searching image files"
    );
    println!("-c, --config\n\tRead the configuration file and exit the program");
    println!(
        "-d, --min_dimension <MIN_DIMENSION>\n\tSet the minimum dimension that the height and width must satisfy"
    );
    println!(
        "-D, --max_dimension <MAX_DIMENSION>\n\tSet the maximum dimension that the height and width must satisfy"
    );
    println!("-h, --help\n\tPrint help");
    println!(
        "-i, --interval <INTERVAL>\n\tSet the interval (in seconds) between each wallpaper displayed"
    );
    println!("-l, --list <Criteria> (path, size, name, extension)\n\tList all images and exit");
    println!("-m, --monitor <MONITOR_NUMBER>\n\tSet the number of monitors [default: 2]");
    println!(
        "-o, --orientation <ORIENTATION>\n\tInform monitor orientation: Horizontal (side-by-side) or Vertical (stacked)."
    );
    println!("--once\n\tRun a single wallpaper update cycle and exit");
    println!(
        "-p, --pictures_per_monitor <PICTURE>\n\tSet number of pictures (or images) per monitor [default: 1]"
    );
    println!("-s, --sort\n\tSort the images found");

    println!("\nWayland/Awww Options:");
    println!("  --dry-run                    Don't apply wallpaper, just test");
    println!("  --transition-type <TYPE>     wipe, wave, fade, simple, random");
    println!("  --transition-duration <SEC>  Duration of animation");
    println!("  --transition-fps <FPS>       Smoothness of animation");
    println!("  --transition-angle <DEG>     Angle for wipe/wave");
    println!("  --transition-pos <POS>       Position for grow/outer (default: center)");

    println!("-v, --verbose\n\tShow intermediate runtime messages");
    println!("-V, --version\n\tPrint version");
    std::process::exit(0);
}

fn show_version() {
    let pkg_name = ENVIRON.get_pkg_name();
    let pkg_version = env!("CARGO_PKG_VERSION");
    println!("{pkg_name} {pkg_version}");
    std::process::exit(0);
}

#[cfg(test)]
mod test_args_v2 {
    use crate::{Arguments, Orientation, WallSwitchResult};

    // cargo test -- --help
    // cargo test -- --nocapture get_arguments
    // cargo test -- --show-output filter_unique

    #[test]
    /// `cargo test --features args_v2 -- --show-output get_arguments`    
    fn get_arguments() -> WallSwitchResult<()> {
        let entries = [
            "program_name",
            "-i",
            "60",
            " -d === ",
            "200",
            "--config",
            "--monitor=",
            "3",
            "-m==5",
            "-c",
            "-p",
            "3",
            "--orientation",
            "horiZontal",
        ];

        println!("entries: {entries:?}");

        //let args = std::env::args();
        let args: Vec<String> = entries.iter().map(ToString::to_string).collect();

        let arguments = Arguments::parse(args.into_iter())?;
        println!("arguments: {arguments:#?}");

        let json: String = serde_json::to_string_pretty(&arguments)?;
        println!("arguments: {json}");

        assert_eq!(
            arguments,
            Arguments {
                config: true,
                monitor_orientation: Some(Orientation::Horizontal),
                min_dimension: Some(200),
                max_dimension: None,
                min_size: None,
                max_size: None,
                help: false,
                interval: Some(60),
                list: None, 
                monitor: Some(5),
                once: false,
                pictures_per_monitor: Some(3),
                sort: false,
                dry_run: false,              
                transition_type: None,       
                transition_duration: None,   
                transition_fps: None,        
                transition_angle: None,      
                transition_pos: None,        
                verbose: false,
                version: false,
            }
        );

        Ok(())
    }

    #[test]
    /// `cargo test --features args_v2 -- --show-output split_arg_equal`
    fn split_arg_equal() -> WallSwitchResult<()> {
        let arg = "Löwe 老虎 Léo=öpard Gepa12345虎==rdi".to_string();
        println!("arg: {arg}");

        let result1: Vec<String> = if let Some(index) = arg.find('=') {
            vec![arg[..index].to_string(), arg[index + 1..].to_string()]
        } else {
            vec![arg.clone()]
        };

        let result2: Vec<&str> = arg
            .split_once('=')
            .into_iter()
            .flat_map(|(a, b)| vec![a, b])
            .collect();

        println!("result1: {result1:?}");

        assert_eq!(result1, ["Löwe 老虎 Léo", "öpard Gepa12345虎==rdi"]);
        assert_eq!(result1, result2);

        Ok(())
    }

    #[test]
    /// `cargo test --features args_v2 -- --show-output split_arg_digit`
    fn split_arg_digit() -> WallSwitchResult<()> {
        let arg = "Löwe 老虎 Léo=pard Gepa12345虎rdi".to_string();
        println!("arg: {arg}");

        let result = if let Some(index) = arg.find(|c: char| c.is_ascii_digit()) {
            //if let Some(index) = arg.chars().position(|c| c.is_ascii_digit()) {
            vec![arg[..index].to_string(), arg[index..].to_string()]
        } else {
            vec![arg]
        };

        println!("result: {result:?}");

        assert_eq!(result, ["Löwe 老虎 Léo=pard Gepa", "12345虎rdi"]);

        Ok(())
    }
}