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
use crate::{
Colors, Config, Environment, Orientation, ProceduralEffect, SortCriteria, WallSwitchResult,
get_config_path, read_config_file,
};
use clap::{
CommandFactory, Parser,
builder::{
BoolishValueParser,
styling::{AnsiColor, Effects, Styles},
},
}; // command-line arguments
use clap_complete::{Generator, Shell, generate};
/// Custom Clap styling to mimic a beautiful colored help menu.
fn get_styles() -> Styles {
Styles::styled()
.header(AnsiColor::Yellow.on_default() | Effects::BOLD)
.usage(AnsiColor::Yellow.on_default() | Effects::BOLD)
.literal(AnsiColor::Green.on_default())
.placeholder(AnsiColor::Cyan.on_default())
}
/// Dynamically builds the extra help menu section with named colors
/// and injects the actual system path of the config file.
fn get_after_help() -> String {
// Resolve path using a safe compile-time fallback environment for clap initialization
let env = Environment::new().unwrap_or_else(|_| Environment::fallback());
// Safely attempt to get the configuration path, defaulting to a generic string on failure
let config_path = get_config_path(&env)
.map(|p| p.display().to_string())
.unwrap_or_else(|_| "~/.config/wallswitch/wallswitch.json".to_string());
// 1. Initialize the base string with the configuration file path
let mut help_text = format!(
"{}\n {}\n\n",
"Config file:".yellow().bold(),
config_path.blue().bold(),
);
// 2. Add detailed section about EffectsConfig and configuration adjustments
help_text.push_str(&format!(
"{}\n {}\n\n\
• {}: Add custom presets to defaults (default: true).\n\
• {}: Minimum iteration limit for escape-time calculations.\n\
• {}: Maximum iteration limit for escape-time calculations.\n\
• {} / {} / {} / {}: Custom arrays of mathematical presets.\n\n",
"Effects Configuration (EffectsConfig):".yellow().bold(),
"Alter these parameters inside your 'wallswitch.json' or override them via CLI:".dimmed(),
"add-presets".green().bold(),
"min-iterations".green().bold(),
"max-iterations".green().bold(),
"julia".green().bold(),
"mandelbrot".green().bold(),
"newton".green().bold(),
"nova".green().bold()
));
// 3. Add Examples heading
help_text.push_str(&format!("{}\n", "Examples:".yellow().bold()));
// 4. Define examples as an Array of structured Tuples ("Comment", "Command")
let examples = [
(
"# Start the automatic background loop using default settings",
"wallswitch",
),
(
"# Run a single wallpaper update cycle and exit (useful for cron jobs)",
"wallswitch --once",
),
(
"# Change wallpaper every 10 minutes (600 seconds)",
"wallswitch --interval 600",
),
(
"# Set 3 different wallpapers per monitor (Gnome desktop only)",
"wallswitch --pictures-per-monitor 3",
),
(
"# Filter images by dimension (min 1080px) and file size (max 5MB)",
"wallswitch --min-dimension 1080 --max-size 5242880",
),
(
"# Apply a specific Julia Sets fractal overlay on wallpapers",
"wallswitch --effect julia",
),
(
"# Override the preset behavior and iterations for fractal calculations",
"wallswitch --effect julia --effects-add-presets false --effects-min-iterations 1200",
),
(
"# Apply random fractal overlays [julia, mandelbrot]",
"wallswitch --effect fractal",
),
(
"# Apply randomized procedural overlays (fractal, star, aurora) on wallpapers",
"wallswitch --effect random",
),
(
"# Dry run mode to see what would be executed without applying changes",
"wallswitch --dry-run --verbose",
),
(
"# Wayland (awww): Use specific transition effects and duration",
"wallswitch --transition-type wave --transition-duration 3",
),
(
"# List all found images sorted by file size",
"wallswitch --list size",
),
(
"# Display all processed images (with dimensions) in JSON format",
"wallswitch --list processed",
),
(
"# Display all images that haven't been probed yet",
"wallswitch --list unprocessed",
),
(
"# Count processed images using jq",
"wallswitch -l processed | jq 'length'",
),
(
"# Limit CPU processing to 20% of total logical cores during rendering",
"wallswitch --max-threads-percent 20",
),
];
// 5. Iterate over the list, applying colors centrally and idiomatically
for (comment, cmd) in examples {
help_text.push_str(&format!(
" {}\n {}\n\n",
comment.dimmed(),
cmd.green().bold()
));
}
// Remove trailing newlines at the end of the string
help_text.trim_end().to_string()
}
const APPLET_TEMPLATE: &str = "\
{before-help}
{about}
{usage-heading} {usage}
{all-args}
{after-help}";
/// Command line arguments
#[derive(Parser, Debug, Clone)]
#[command(
// Read from `Cargo.toml`
author, version, about,
long_about = None,
next_line_help = true,
help_template = APPLET_TEMPLATE,
styles = get_styles(),
after_help = get_after_help(),
)]
pub struct Arguments {
/// 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
#[arg(
short('b'), long("min-size"),
required = false,
default_value = None,
hide_default_value = true,
)]
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
#[arg(
short('B'), long("max-size"),
required = false,
default_value = None,
hide_default_value = true
)]
pub max_size: Option<u64>,
/// Read the configuration file and exit the program.
#[arg(short('c'), long("config"), default_value_t = false)]
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.
#[arg(
short('d'), long("min-dimension"),
required = false,
default_value = None,
hide_default_value = true,
value_parser = clap::value_parser!(u64).range(10..)
)]
pub min_dimension: Option<u64>,
/// Set the maximum dimension that the height and width must satisfy.
///
/// width <= max_dimension && height <= max_dimension
#[arg(
short('D'), long("max-dimension"),
required = false,
default_value = None,
hide_default_value = true
)]
pub max_dimension: Option<u64>,
/// Apply a procedural overlay effect to the selected wallpapers before displaying.
#[arg(
short('e'),
long("effect"),
value_enum,
required = false,
default_value = None,
hide_default_value = true,
)]
pub effect: Option<ProceduralEffect>,
/// Whether custom presets are appended to default ones (true) or replace them (false).
#[arg(
long("effects-add-presets"),
value_name = "BOOL",
required = false,
value_parser = BoolishValueParser::new(),
)]
pub effects_add_presets: Option<bool>,
/// Set a custom minimum iteration limit for escape-time fractal calculations.
#[arg(
short('n'),
long("effects-min-iterations"),
value_name = "MIN_ITERATIONS",
required = false,
value_parser = clap::value_parser!(u32).range(10..=100_000),
)]
pub effects_min_iterations: Option<u32>,
/// Set a custom maximum iteration limit for escape-time fractal calculations.
#[arg(
short('N'),
long("effects-max-iterations"),
value_name = "MAX_ITERATIONS",
required = false,
value_parser = clap::value_parser!(u32).range(10..=100_000),
)]
pub effects_max_iterations: Option<u32>,
/**
Generate shell completions and exit the program.
### How to generate shell completions for Z-shell:
#### Example 1 (as a regular user):
Generate completion_derive.zsh file with:
```console
wallswitch --generate=zsh > completion_derive.zsh
```
Append the contents of the completion_derive.zsh file to the end of completion zsh file.
ZSH completions are commonly stored in any directory listed in your `$fpath` variable.
On Linux, view `$fpath` variable with:
```console
echo $fpath | perl -nE 'say for split /\s+/'
```
And then, execute:
```console
compinit && zsh
```
#### Example 2 (as a regular user):
Generate completions to rustup and wallswitch.
Visible to only the regular user.
```console
mkdir -p ~/.oh-my-zsh/functions
rustup completions zsh > ~/.oh-my-zsh/functions/_rustup
wallswitch --generate=zsh > ~/.oh-my-zsh/functions/_wallswitch
compinit && zsh
```
#### Example 3 (as root):
Generate completions to rustup, cargo and wallswitch.
Visible to all system users.
```console
mkdir -p /usr/local/share/zsh/site-functions
rustup completions zsh > /usr/local/share/zsh/site-functions/_rustup
rustup completions zsh cargo > /usr/local/share/zsh/site-functions/_cargo
wallswitch --generate=zsh > /usr/local/share/zsh/site-functions/_wallswitch
compinit && zsh
```
See `rustup completions` for detailed help.
<https://github.com/clap-rs/clap/blob/master/clap_complete/examples/completion-derive.rs>
*/
#[arg(short('g'), long("generate"), value_enum)]
pub generator: Option<Shell>,
/// Set the interval (in seconds) between each wallpaper displayed.
///
/// Default value: interval = 30 * 60 = 1800 seconds (30 minutes).
#[arg(
short('i'), long("interval"),
required = false,
default_value = None,
hide_default_value = true,
value_parser = clap::value_parser!(u64).range(5..)
)]
pub interval: Option<u64>,
/// List all found images and exit.
///
/// Sort criteria: [path, size, sizedesc, name, extension, width, height, area, ratio, time, processed, unprocessed, cache]
#[arg(short('l'), long("list"), value_name = "CRITERIA")]
pub list: Option<SortCriteria>,
/// Set the number of monitors [default: 2]
#[arg(
short('m'), long("monitor"),
required = false,
default_value = None,
hide_default_value = true,
value_parser = clap::value_parser!(u8).range(1..)
)]
pub monitor: Option<u8>,
/// Inform monitor orientation: Horizontal (side-by-side) or Vertical (stacked).
///
/// Orientation: [Horizontal, Vertical]
///
/// Default orientation: Horizontal.
#[arg(
short('o'),
long("orientation"),
required = false,
default_value = None,
hide_default_value = true,
)]
pub monitor_orientation: Option<Orientation>,
/// Run a single wallpaper update cycle and exit.
#[arg(short('1'), long("once"), default_value_t = false)]
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
#[arg(
short('p'), long("pictures-per-monitor"),
required = false,
default_value = None,
hide_default_value = true,
value_parser = clap::value_parser!(u8).range(1..=256)
)]
pub pictures_per_monitor: Option<u8>,
/// Sort the images found.
#[arg(short('s'), long("sort"), default_value_t = false)]
pub sort: bool,
/// Run without applying the wallpapers (simulation mode).
#[arg(short('r'), long("dry-run"), default_value_t = false)]
pub dry_run: bool,
/// Transition type for Wayland compositors using awww (e.g. wipe, wave, fade, random).
#[arg(long("transition-type"), required = false)]
pub transition_type: Option<String>,
/// Duration of the transition animation in seconds.
#[arg(long("transition-duration"), required = false)]
pub transition_duration: Option<u16>,
/// Frames per second for transition smoothness.
#[arg(long("transition-fps"), required = false)]
pub transition_fps: Option<u16>,
/// Angle used by directional transitions (wipe, wave).
#[arg(long("transition-angle"), required = false)]
pub transition_angle: Option<u16>,
/// Origin position used by grow/outer transitions (e.g. center, top).
#[arg(long("transition-pos"), required = false)]
pub transition_pos: Option<String>,
/// Limit the maximum execution threads used by parallel tasks.
///
/// Expressed as a percentage of the total logical CPU cores (between 10% and 100%).
///
/// For example, 25% on an 16-core CPU restricts execution to 4 concurrent threads.
///
/// [default: 50]
#[arg(
short('t'),
long("max-threads-percent"),
value_name = "PERCENT",
required = false,
value_parser = clap::value_parser!(u8).range(10..=100)
)]
pub max_threads_percent: Option<u8>,
/// Show intermediate runtime messages.
///
/// Show found images.
///
/// Show pid numbers of previous running program.
#[arg(short('v'), long("verbose"), default_value_t = false)]
pub verbose: bool,
}
impl Arguments {
/// Build Arguments struct
pub fn build(env: &Environment) -> WallSwitchResult<Arguments> {
let args: Arguments = Arguments::parse();
if let Some(generator) = args.generator {
args.print_completions(generator);
}
if args.config {
let config_path = get_config_path(env)?;
let config = match read_config_file(&config_path) {
Ok(cfg) => cfg,
Err(_) => {
// Fall back to creating, writing, and returning the default configuration
let default_config = Config::default_with_env(env);
default_config.write_config_file(&config_path, true)?
}
};
let json: String = serde_json::to_string_pretty(&config)?;
println!("{json}");
std::process::exit(0);
}
Ok(args)
}
/// Print shell completions to standard output
fn print_completions<G>(&self, r#gen: G)
where
G: Generator + std::fmt::Debug,
{
let mut cmd = Arguments::command();
let cmd_name = cmd.get_name().to_string();
let mut stdout = std::io::stdout();
eprintln!("Generating completion file for {gen:?}...");
generate(r#gen, &mut cmd, cmd_name, &mut stdout);
std::process::exit(1);
}
}