wallswitch 0.54.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
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
use crate::{
    Colors, Config, Desktop, FileInfo,
    Orientation::{Horizontal, Vertical},
    U8Extension, WallSwitchError, WallSwitchResult,
};
use std::{
    // cmp::Ordering,
    path::PathBuf,
    process::{Command, Output, Stdio},
};

/// Set desktop wallpaper based on the detected Desktop Environment.
pub fn set_wallpaper(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    match config.desktop {
        Desktop::Gnome => set_gnome_wallpaper(images, config)?,
        Desktop::Xfce => set_xfce_wallpaper(images, config)?,
        Desktop::Hyprland => set_hyprland_wallpaper(images, config)?,
        Desktop::Niri => set_niri_wallpaper(images, config)?,
        Desktop::Openbox => set_openbox_wallpaper(images, config)?,
    }

    println!();
    Ok(())
}

/// Helper to check if a command exists in the system PATH.
/// It also logs the check if verbose is enabled.
fn is_installed(binary: &str, verbose: bool) -> bool {
    let mut cmd = Command::new("which");
    cmd.arg(binary);

    if verbose {
        println!("\n[CHECK] Checking if '{binary}' is installed...");
        println!("program: {:?}", cmd.get_program());
        println!("arguments: {:#?}", cmd.get_args().collect::<Vec<_>>());
    }

    let status = cmd
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);

    if verbose {
        println!(
            "Result: {}",
            if status {
                "Found".green()
            } else {
                "Not Found".red()
            }
        );
    }

    status
}

/// Generic error message for missing Wayland wallpaper tools with installation instructions.
fn missing_tools_error() -> WallSwitchError {
    let msg = "Neither 'swaybg' nor 'hyprpaper' was found on your system.\n\n\
        To fix this, please install at least one of them:\n\
        - Manjaro/Arch: sudo pacman -S swaybg hyprpaper\n\
        - Fedora: sudo dnf install swaybg hyprpaper\n\
        - Debian/Ubuntu: sudo apt install swaybg hyprpaper"
        .to_string();
    WallSwitchError::UnableToFind(msg)
}

/// Logic for applying wallpaper using swaybg.
/// This includes the verbose logging requested.
fn apply_swaybg_wallpaper(
    images: &[FileInfo],
    monitors: &[String],
    config: &Config,
) -> WallSwitchResult<()> {
    // 1. Kill previous instances to avoid multiple swaybg processes
    let _ = Command::new("pkill").arg("swaybg").output();

    // 2. Construct the command
    let mut cmd = Command::new("swaybg");
    for (image, monitor) in images.iter().zip(monitors) {
        let path_str = image.path.to_str().unwrap_or_default();
        cmd.arg("-o")
            .arg(monitor)
            .arg("-i")
            .arg(path_str)
            .arg("-m")
            .arg("fill");
    }

    // 3. Verbose Logging (Mimics the style of your exec_cmd)
    if config.verbose {
        let program = cmd.get_program();
        let arguments: Vec<_> = cmd.get_args().collect::<Vec<_>>();
        println!("\nprogram: {program:?}");
        println!("arguments: {arguments:#?}");
    }

    // 4. Spawn the process (Background execution)
    cmd.stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(WallSwitchError::Io)?;

    Ok(())
}

/// Native Hyprland logic using hyprctl and hyprpaper daemon
fn set_hyprland_wallpaper(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    let monitors = get_hyprland_monitors(config)?;

    // 1. Check if daemon is alive
    let mut check_cmd = Command::new("hyprctl");
    check_cmd.args(["hyprpaper", "listloaded"]);

    if config.verbose {
        println!("\nprogram: {:?}", check_cmd.get_program());
        println!("arguments: {:#?}", check_cmd.get_args().collect::<Vec<_>>());
    }

    let loaded_str = match check_cmd.output() {
        Ok(out) => String::from_utf8_lossy(&out.stdout).to_string(),
        Err(_) => {
            return Err(WallSwitchError::UnableToFind(
                "hyprpaper daemon not running".into(),
            ));
        }
    };

    // 2. Preload and Wallpaper loop
    for (image, monitor) in images.iter().zip(&monitors) {
        let path_str = image.path.to_str().unwrap_or_default();

        if !loaded_str.contains(path_str) {
            let mut preload_cmd = Command::new("hyprctl");
            preload_cmd.args(["hyprpaper", "preload", path_str]);

            if config.verbose {
                println!("\nprogram: {:?}", preload_cmd.get_program());
                println!(
                    "arguments: {:#?}",
                    preload_cmd.get_args().collect::<Vec<_>>()
                );
            }
            let _ = preload_cmd.output();
        }

        let mut wall_cmd = Command::new("hyprctl");
        let wall_arg = format!("{monitor},{path_str}");
        wall_cmd.args(["hyprpaper", "wallpaper", &wall_arg]);

        // exec_cmd already handles its own verbose logging
        exec_cmd(
            &mut wall_cmd,
            config.verbose,
            &format!("Apply wallpaper on {monitor}"),
        )?;
    }

    // 3. Cleanup
    let mut unload_cmd = Command::new("hyprctl");
    unload_cmd.args(["hyprpaper", "unload", "unused"]);
    if config.verbose {
        println!("\nprogram: {:?}", unload_cmd.get_program());
        println!(
            "arguments: {:#?}",
            unload_cmd.get_args().collect::<Vec<_>>()
        );
    }
    let _ = unload_cmd.output();

    Ok(())
}

/// Retrieves active monitor names (e.g., DP-1, HDMI-A-1) from hyprctl monitors.
fn get_hyprland_monitors(config: &Config) -> WallSwitchResult<Vec<String>> {
    let mut cmd = Command::new("hyprctl");
    cmd.arg("monitors");

    // Execute hyprctl to get the current hardware state.
    let output = exec_cmd(&mut cmd, config.verbose, "get_hyprland_monitors")?;
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Parse output to extract monitor names from lines starting with "Monitor".
    let monitors: Vec<String> = stdout
        .lines()
        .filter(|line| line.starts_with("Monitor"))
        .filter_map(|line| line.split_whitespace().nth(1).map(|s| s.to_string()))
        .collect();

    if monitors.is_empty() {
        return Err(WallSwitchError::NoMonitors("hyprctl".to_string()));
    }

    Ok(monitors)
}

/// Set wallpaper for Niri with fallback logic (swaybg -> hyprpaper)
fn set_niri_wallpaper(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    let monitors = get_niri_monitors(config)?;

    if is_installed("swaybg", config.verbose) {
        apply_swaybg_wallpaper(images, &monitors, config)
    } else if is_installed("hyprpaper", config.verbose) {
        // Uses hyprland logic as fallback for hyprpaper
        set_hyprland_wallpaper(images, config)
    } else {
        Err(missing_tools_error())
    }
}

/// Get monitor names from Niri (e.g., DP-1, DP-2) using 'niri msg outputs'
fn get_niri_monitors(config: &Config) -> WallSwitchResult<Vec<String>> {
    let mut cmd = Command::new("niri");
    cmd.args(["msg", "outputs"]);

    let output = exec_cmd(&mut cmd, config.verbose, "get_niri_monitors")?;
    let stdout = String::from_utf8_lossy(&output.stdout);

    // New parsing logic:
    // 1. Filter lines starting with "Output"
    // 2. Find the content inside the LAST set of parentheses
    let monitors: Vec<String> = stdout
        .lines()
        .filter(|line| line.starts_with("Output"))
        .filter_map(|line| {
            let start = line.rfind('(')?; // Find last '('
            let end = line.rfind(')')?; // Find last ')'
            if start < end {
                Some(line[start + 1..end].to_string())
            } else {
                None
            }
        })
        .collect();

    if monitors.is_empty() {
        return Err(WallSwitchError::NoMonitors("niri msg".to_string()));
    }

    Ok(monitors)
}

fn set_xfce_wallpaper(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    let monitors = get_xfce_monitors(config)?;

    if config.verbose {
        println!("monitors:\n{monitors:#?}");
    }

    for (image, monitor) in images.iter().zip(monitors) {
        apply_xfconf(&image.path, &monitor, config)?;
    }

    Ok(())
}

/**
    Get xfce monitors

    Example:
    ```
    // xfconf-query -c xfce4-desktop -p /backdrop -l | grep last-image
    // xfconf-query -c xfce4-desktop -p /backdrop -l | grep 'workspace0/last-image'

    let monitors = [
        "/backdrop/screen0/monitorDP-0/workspace0/last-image",
        "/backdrop/screen0/monitorDP-2/workspace0/last-image",
    ];
    ```
*/
fn get_xfce_monitors(config: &Config) -> WallSwitchResult<Vec<String>> {
    // Filter standard output that contains all these words
    let words = ["screen0", "workspace0", "last-image"];

    let mut cmd = Command::new("xfconf-query");
    let xfconf_cmd = cmd.args([
        "--channel",
        "xfce4-desktop",
        "--property",
        "/backdrop",
        "--list",
    ]);

    let xfconf_out: Output = exec_cmd(xfconf_cmd, config.verbose, "get_xfce_monitors: xfconf")?;

    let std_output: String = String::from_utf8(xfconf_out.stdout)?;

    let outputs: Vec<String> = std_output
        .trim()
        .split(['\n', ' '])
        .filter(|&output| words.into_iter().all(|word| output.contains(word)))
        .map(ToString::to_string)
        .collect();

    Ok(outputs)
}

fn apply_xfconf(path: &PathBuf, monitor: &str, config: &Config) -> WallSwitchResult<()> {
    let mut cmd = Command::new("xfconf-query");
    let xfconf = cmd
        .args(["--channel", "xfce4-desktop", "--property", monitor, "--set"])
        .arg(path);

    let msg = format!("apply_xfconf: xfconf {monitor}");

    exec_cmd(xfconf, config.verbose, &msg)?;

    Ok(())
}

fn set_openbox_wallpaper(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    let mut feh_cmd = Command::new(&config.path_feh);

    for image in images {
        feh_cmd.arg("--bg-fill").arg(&image.path);
    }

    exec_cmd(&mut feh_cmd, config.verbose, "feh")?;

    Ok(())
}

/// Create a wallpaper file and set it as your desktop background image.
fn set_gnome_wallpaper(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    // Create a wallpaper file with magick command line (ImageMagick).
    create_background_image(images, config)?;

    // gsettings set org.gnome.desktop.background picture-uri      '/home/use_name/wallswitch.jpg'
    // gsettings set org.gnome.desktop.background picture-uri-dark '/home/use_name/wallswitch.jpg'

    for picture in ["picture-uri", "picture-uri-dark"] {
        let mut cmd = Command::new("gsettings");
        let gsettings = cmd
            .args(["set", "org.gnome.desktop.background", picture])
            .arg(&config.wallpaper);

        let msg = format!("gsettings {picture}");

        exec_cmd(gsettings, config.verbose, &msg)?;
    }

    // gsettings set org.gnome.desktop.background picture-options spanned

    let mut cmd = Command::new("gsettings");
    let spanned = cmd.args([
        "set",
        "org.gnome.desktop.background",
        "picture-options",
        "spanned",
    ]);

    exec_cmd(spanned, config.verbose, "spanned")?;

    Ok(())
}

/**
Create custom background image

To join images horizontally: +append
To join images vertically: -append
To see gravity options: magick -list gravity

### Example.
Consider 3 images in the directory: "fig01.webp", "fig02.avif" and "fig03.jpg".

Two distinct cases:

- case 1. N Monitors with the same resolution (3840x2160):

magick fig0* -gravity Center -resize 3840x2160^ -extent 3840x2160 +append wallpaper.jpg

or with aspect ratio: 16:9

magick fig0* -gravity Center -resize 3840x2160^ -extent 16:9 +append wallpaper.jpg

- case 2. 3 Monitors with different resolutions (3840x2160, 1920x1080 and 3840x2160):

magick fig01* -gravity Center -resize 3840x2160^ -extent 3840x2160 wallpaper_01.jpg \
magick fig02* -gravity Center -resize 1920x1080^ -extent 1920x1080 wallpaper_02.jpg \
magick fig03* -gravity Center -resize 3840x2160^ -extent 3840x2160 wallpaper_03.jpg \
magick -gravity South wallpaper_0*.jpg +append wallpaper.jpg

ImageMagick can run multiple operations on separate instances in a single command:

magick -gravity Center \
\( fig01* -resize 3840x2160^ -extent 3840x2160 \) \
\( fig02* -resize 1920x1080^ -extent 1920x1080 \) \
\( fig03* -resize 3840x2160^ -extent 3840x2160 \) \
-gravity South +append wallpaper.jpg

<https://www.imagemagick.org/script/command-line-processing.php>
*/
fn create_background_image(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    let mut magick_cmd = Command::new(&config.path_magick);

    get_partitions_iter(images, config)
        .zip(&config.monitors)
        .try_for_each(|(images, monitor)| -> WallSwitchResult<()> {
            let mut width: u64 = monitor.resolution.width;
            let mut height: u64 = monitor.resolution.height;

            let pictures_per_monitor = monitor.pictures_per_monitor.to_u64();

            let remainder_w: usize = (width % pictures_per_monitor).try_into()?;
            let remainder_h: usize = (height % pictures_per_monitor).try_into()?;

            match monitor.picture_orientation {
                Horizontal => height /= pictures_per_monitor,
                Vertical => width /= pictures_per_monitor,
            }

            magick_cmd.args(["(", "-gravity", "Center"]);

            images.iter().enumerate().for_each(|(index, image)| {
                let mut w = width;
                let mut h = height;

                // Add extra row or column to adjust image composition to resolution.
                match monitor.picture_orientation {
                    Horizontal => {
                        if index < remainder_h {
                            h += 1; // Add extra row if necessary
                        }
                    }
                    Vertical => {
                        if index < remainder_w {
                            w += 1; // Add extra column if necessary
                        }
                    }
                }

                let resize = format!("{w}x{h}^");
                let extent = format!("{w}x{h}");

                magick_cmd
                    .arg("(")
                    .arg(&image.path)
                    .args(["-resize", &resize])
                    .args(["-extent", &extent])
                    .arg(")");
            });

            // Indicates how the images are combined
            match monitor.picture_orientation {
                Horizontal => {
                    magick_cmd.args(["-gravity", "South", "-append", ")"]);
                }
                Vertical => {
                    magick_cmd.args(["-gravity", "South", "+append", ")"]);
                }
            }

            Ok(())
        })?;

    match config.monitor_orientation {
        Horizontal => {
            magick_cmd.arg("+append").arg(&config.wallpaper);
        }
        Vertical => {
            magick_cmd.arg("-append").arg(&config.wallpaper);
        }
    }

    exec_cmd(&mut magick_cmd, config.verbose, "magick")?;

    Ok(())
}

/// Get partitions from a Slice
#[allow(dead_code)]
fn get_partitions_slice<'a>(mut images: &'a [FileInfo], config: &'a Config) -> Vec<&'a [FileInfo]> {
    let mut partition = Vec::new();

    config.monitors.iter().for_each(|monitor| {
        let (head, tail) = images.split_at(monitor.pictures_per_monitor.into());
        images = tail;
        partition.push(head);
    });

    partition
}

/// Returns an iterator over partitions of images based on monitor settings.
///
/// Arguments:
///
/// * `images`: A reference to a slice of `FileInfo` objects, representing the images to be partitioned.
/// * `config`: A reference to a `Config` object, containing information about the monitors and their settings.
fn get_partitions_iter<'a>(
    mut images: &'a [FileInfo],
    config: &'a Config,
) -> impl Iterator<Item = &'a [FileInfo]> {
    // Create an iterator over the monitor configurations
    config.monitors.iter().map(move |monitor| {
        let (head, tail) = images.split_at(monitor.pictures_per_monitor.into());
        images = tail;
        head
    })
}

/// Executes the command as a child process,
/// waiting for it to finish and collecting all of its output.
pub fn exec_cmd(cmd: &mut Command, verbose: bool, msg: &str) -> WallSwitchResult<Output> {
    let output: Output = cmd.output().inspect_err(|error| {
        eprintln!("fn exec_cmd()");
        eprintln!("cmd: {cmd:?}");
        eprintln!("Error: {error}");
    })?;

    if !output.status.success() || verbose {
        let program = cmd.get_program();
        let arguments: Vec<_> = cmd.get_args().collect();

        println!("\nprogram: {program:?}");
        println!("arguments: {arguments:#?}");

        let stdout = String::from_utf8_lossy(&output.stdout);

        if !stdout.trim().is_empty() {
            println!("stdout:'{}'\n", stdout.trim());
        }
    }

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let status = output.status;

        eprintln!("{msg} status: {status}");
        eprintln!("{msg} stderr: {stderr}");

        panic!("{stderr:?}");
    }

    Ok(output)
}