wallswitch 0.60.5

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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use crate::{
    AwwwBackend, Colors, Config, Desktop, FileInfo, Monitor,
    Orientation::{Horizontal, Vertical},
    ProceduralEffect, U8Extension, WallSwitchError, WallSwitchResult, detect_monitors,
    is_installed,
};
use image::{RgbImage, imageops::FilterType};
use std::{
    io::Error,
    process::{Command, Output},
};

/// Core trait defining the wallpaper application logic.
/// Follows the "Functional Core, Imperative Shell" pattern.
pub trait WallpaperBackend {
    /// PURE FUNCTION: Only constructs the required system commands.
    /// Does NOT execute them. This makes the logic highly testable and predictable.
    fn build_commands(images: &[FileInfo], config: &Config) -> WallSwitchResult<Vec<Command>>;

    /// IMPURE FUNCTION: Executes the built commands.
    /// It defaults to sequentially running `build_commands`, but can be
    /// overridden by compositors that require complex state checks
    /// (e.g., Hyprland preloading, Swaybg daemon spawning).
    fn apply(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
        let mut commands = Self::build_commands(images, config)?;
        for cmd in commands.iter_mut() {
            let program_name = cmd.get_program().to_string_lossy().to_string();
            if config.dry_run {
                println!("[DRY-RUN] Would execute: {:?}", cmd);
            } else {
                exec_cmd(cmd, config.verbose, &format!("Executing {program_name}"))?;
            }
        }
        Ok(())
    }
}

/// Set desktop wallpaper based on the detected Desktop Environment.
pub fn set_wallpaper(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
    // 1. Determine if compilation is needed (if effect is active, or Gnome, or P > 1)
    let needs_compilation = config.desktop == Desktop::Gnome
        || config.effect != ProceduralEffect::None
        || config.monitors.iter().any(|m| m.pictures_per_monitor > 1);

    let compiled_images = if needs_compilation {
        compile_wallpapers_for_monitors(images, config)?
    } else {
        images.to_vec()
    };

    // 2. Dispatch to the appropriate backend using the compiled single-image-per-monitor files
    match config.desktop {
        Desktop::Gnome => {
            // Gnome requires stitching the compiled monitor images together into a single spanned file
            if config.dry_run {
                println!(
                    "[DRY-RUN] Would stitch compiled monitor canvases together to generate final spanned wallpaper."
                );
            } else {
                let mut monitor_canvases = Vec::new();
                for img_info in &compiled_images {
                    let img = image::open(&img_info.path)
                        .map_err(|e| {
                            WallSwitchError::UnableToFind(format!(
                                "Failed to load compiled monitor canvas: {e}"
                            ))
                        })?
                        .to_rgb8();
                    monitor_canvases.push(img);
                }
                let final_wallpaper = assemble_final_wallpaper(&monitor_canvases, config)?;
                final_wallpaper
                    .save(&config.wallpaper)
                    .map_err(|e| WallSwitchError::Io(Error::other(e)))?;

                if config.verbose {
                    println!("Stitched wallpaper saved to Gnome: {:?}", config.wallpaper);
                }
            }

            GnomeBackend::apply(&compiled_images, config)?;
        }
        Desktop::Xfce => XfceBackend::apply(&compiled_images, config)?,
        Desktop::Hyprland => HyprlandBackend::apply(&compiled_images, config)?,

        Desktop::Niri | Desktop::Labwc | Desktop::Mango | Desktop::Wayland => {
            if is_installed("awww") {
                AwwwBackend::apply(&compiled_images, config)?;
            } else if is_installed("swaybg") {
                SwaybgBackend::apply(&compiled_images, config)?;
            } else if is_installed("hyprpaper") {
                HyprlandBackend::apply(&compiled_images, config)?;
            } else {
                return Err(WallSwitchError::MissingWaylandTools);
            }
        }

        Desktop::Openbox => OpenboxBackend::apply(&compiled_images, config)?,
    }

    Ok(())
}

// ==============================================================================
// BACKEND IMPLEMENTATIONS
// ==============================================================================

pub struct GnomeBackend;

impl WallpaperBackend for GnomeBackend {
    fn build_commands(_images: &[FileInfo], config: &Config) -> WallSwitchResult<Vec<Command>> {
        let mut commands = Vec::new();

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

        // GSettings command to set the picture options to spanned
        let mut cmd = Command::new("gsettings");
        cmd.args([
            "set",
            "org.gnome.desktop.background",
            "picture-options",
            "spanned",
        ]);
        commands.push(cmd);

        Ok(commands)
    }
}

pub struct XfceBackend;

impl WallpaperBackend for XfceBackend {
    fn build_commands(images: &[FileInfo], config: &Config) -> WallSwitchResult<Vec<Command>> {
        let mut commands = Vec::new();
        let monitors = detect_monitors(config)?;

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

        // Cycle through compiled single-image-per-monitor backgrounds
        for (image, monitor) in images.iter().cycle().zip(monitors) {
            let mut cmd = Command::new("xfconf-query");
            cmd.args([
                "--channel",
                "xfce4-desktop",
                "--property",
                &monitor,
                "--create",
                "--type",
                "string",
                "--set",
            ])
            .arg(&image.path);

            commands.push(cmd);
        }

        Ok(commands)
    }
}

pub struct OpenboxBackend;

impl WallpaperBackend for OpenboxBackend {
    fn build_commands(images: &[FileInfo], config: &Config) -> WallSwitchResult<Vec<Command>> {
        let mut feh_cmd = Command::new(&config.path_feh);

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

        Ok(vec![feh_cmd])
    }
}

pub struct SwaybgBackend;

impl WallpaperBackend for SwaybgBackend {
    fn build_commands(_images: &[FileInfo], _config: &Config) -> WallSwitchResult<Vec<Command>> {
        Ok(vec![])
    }

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

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

        if config.dry_run {
            println!("[DRY-RUN] Would execute: pkill swaybg");
        } else {
            let _ = Command::new("pkill").arg("swaybg").output();
        }

        let mut cmd = Command::new("swaybg");
        for (image, monitor) in images.iter().cycle().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");
        }

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

        if config.dry_run {
            println!("[DRY-RUN] Would spawn swaybg daemon: {:?}", cmd);
        } else {
            cmd.stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
                .map_err(WallSwitchError::Io)?;
        }

        Ok(())
    }
}

pub struct HyprlandBackend;

impl WallpaperBackend for HyprlandBackend {
    fn build_commands(_images: &[FileInfo], _config: &Config) -> WallSwitchResult<Vec<Command>> {
        Ok(vec![])
    }

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

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

        let mut check_cmd = Command::new("hyprctl");
        check_cmd.args(["hyprpaper", "listloaded"]);

        let loaded_str = match check_cmd.output() {
            Ok(out) => String::from_utf8_lossy(&out.stdout).to_string(),
            Err(_) => {
                if config.dry_run {
                    "[DRY-RUN] hyprpaper daemon is offline".to_string()
                } else {
                    return Err(WallSwitchError::UnableToFind(
                        "hyprpaper daemon not running".into(),
                    ));
                }
            }
        };

        for (image, monitor) in images.iter().cycle().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<_>>()
                    );
                }
                if config.dry_run {
                    println!("[DRY-RUN] Would execute: {:?}", preload_cmd);
                } else {
                    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]);

            if config.dry_run {
                println!("[DRY-RUN] Would execute: {:?}", wall_cmd);
            } else {
                exec_cmd(
                    &mut wall_cmd,
                    config.verbose,
                    &format!("Apply wallpaper on {monitor}"),
                )?;
            }
        }

        let mut unload_cmd = Command::new("hyprctl");
        unload_cmd.args(["hyprpaper", "unload", "unused"]);
        if config.dry_run {
            println!("[DRY-RUN] Would execute: {:?}", unload_cmd);
        } else {
            let _ = unload_cmd.output();
        }

        Ok(())
    }
}

// ==============================================================================
// STRUCTURAL & MATHEMATICAL GEOMETRY COMPUTATIONS (Pure Helpers)
// ==============================================================================

struct LayoutTarget {
    base_w: u64,
    base_h: u64,
    rem_w: usize,
    rem_h: usize,
}

impl LayoutTarget {
    fn calculate(monitor: &crate::Monitor) -> Result<Self, std::num::TryFromIntError> {
        let mut width = monitor.resolution.width;
        let mut height = monitor.resolution.height;
        let pics_per_monitor = monitor.pictures_per_monitor.to_u64();

        let rem_w = (width % pics_per_monitor).try_into()?;
        let rem_h = (height % pics_per_monitor).try_into()?;

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

        Ok(Self {
            base_w: width,
            base_h: height,
            rem_w,
            rem_h,
        })
    }
}

/// Helper function to select and apply procedural overlays in-memory.
fn apply_selected_effect(canvas: &mut RgbImage, monitor: &Monitor, config: &Config, index: usize) {
    if config.effect == ProceduralEffect::None {
        return;
    }

    // 1. Resolve the effect once to prevent non-deterministic double-evaluation bugs
    let resolved = config.effect.resolve();

    // 2. Factory builds the resolved dynamic effect polymorphically
    if let Some(renderer) = resolved.get_renderer(monitor) {
        if config.verbose {
            let idx = index.to_string().bold().cyan();
            let name = resolved.get_name().bold().blue();

            // Dynamic dispatch prints the customized info of each concrete struct
            println!("Applying to Monitor {idx} {name} {}", renderer.info());
        }

        // Execute the render logic in-memory
        renderer.apply(canvas);
    }
}

/// Compiles a single monitor canvas, applies overlays, saves the output to disk, and builds its FileInfo metadata.
fn compile_single_monitor_background(
    partition: &[FileInfo],
    monitor: &crate::Monitor,
    config: &Config,
    index: usize,
) -> WallSwitchResult<FileInfo> {
    let output_path = std::env::temp_dir().join(format!("wallswitch_monitor_{index}.jpg"));

    if config.dry_run {
        if config.verbose {
            println!(
                "[DRY-RUN] Would compile backgrounds for Monitor {index} at resolution {}x{}",
                monitor.resolution.width, monitor.resolution.height
            );
            if config.effect != ProceduralEffect::None {
                println!(
                    "[DRY-RUN] Would apply randomized overlay effect: {:?}",
                    config.effect
                );
            }
        }
    } else {
        // 1. Assemble separate pictures into a single composite monitor background in-memory
        let mut monitor_canvas = assemble_monitor_canvas(partition, monitor)?;

        // 2. Overlay dynamic procedural adjustments if any are requested
        if config.effect != ProceduralEffect::None {
            apply_selected_effect(&mut monitor_canvas, monitor, config, index);
        }

        // 3. Save compiled monitor canvas to disk
        monitor_canvas
            .save(&output_path)
            .map_err(|e| WallSwitchError::Io(Error::other(e)))?;

        if config.verbose {
            println!("Monitor {index} background assembled: {:?}", output_path);
        }
    }

    // 4. Construct structural metadata representing the updated target file
    Ok(FileInfo {
        path: output_path,
        size: 0,
        mtime: 0,
        hash: String::new(),
        dimension: Some(crate::Dimension {
            width: monitor.resolution.width,
            height: monitor.resolution.height,
        }),
        is_valid: Some(true),
        number: index + 1,
        total: config.monitors.len(),
    })
}

/// Pre-processes and compiles separate multi-picture composite backgrounds in parallel for each monitor.
pub fn compile_wallpapers_for_monitors(
    images: &[FileInfo],
    config: &Config,
) -> WallSwitchResult<Vec<FileInfo>> {
    if config.verbose {
        if config.dry_run {
            println!("[DRY-RUN] Would assemble multi-monitor wallpaper in pure Rust ...");
        } else {
            println!("Assembling multi-monitor wallpaper in pure Rust ...");
        }
    }

    let partitions: Vec<_> = get_partitions_iter(images, config).collect();
    let mut compiled_files = Vec::new();

    std::thread::scope(|scope| {
        let mut threads = Vec::new();

        for (index, (partition, monitor)) in
            partitions.into_iter().zip(&config.monitors).enumerate()
        {
            // Spawn separate tasks for each physical display to optimize hardware efficiency
            let thread_handle = scope.spawn(move || -> WallSwitchResult<FileInfo> {
                compile_single_monitor_background(partition, monitor, config, index)
            });
            threads.push(thread_handle);
        }

        for handle in threads {
            let file_info = handle.join().unwrap()?;
            compiled_files.push(file_info);
        }

        Ok::<(), crate::WallSwitchError>(())
    })?;

    Ok(compiled_files)
}

/// Assembles multiple sub-images into a single cohesive canvas for a given monitor in-memory.
fn assemble_monitor_canvas(
    partition: &[FileInfo],
    monitor: &crate::Monitor,
) -> WallSwitchResult<RgbImage> {
    let mut monitor_canvas = RgbImage::new(
        monitor.resolution.width as u32,
        monitor.resolution.height as u32,
    );
    let target = LayoutTarget::calculate(monitor)?;

    let mut current_x = 0;
    let mut current_y = 0;

    for (p_idx, image_info) in partition.iter().enumerate() {
        let mut w = target.base_w;
        let mut h = target.base_h;

        match monitor.picture_orientation {
            Horizontal => {
                if p_idx < target.rem_h {
                    h += 1;
                }
            }
            Vertical => {
                if p_idx < target.rem_w {
                    w += 1;
                }
            }
        }

        // Load the image using the image crate
        let img = image::open(&image_info.path).map_err(|err| WallSwitchError::CorruptImage {
            path: image_info.path.clone(),
            source: err,
        })?;

        // Center crop and scale preserving aspect ratio (mimics magick -resize WxH^ -extent WxH)
        let resized = img
            .resize_to_fill(w as u32, h as u32, FilterType::Triangle)
            .to_rgb8();

        // Draw sub-image onto the monitor canvas
        image::imageops::overlay(
            &mut monitor_canvas,
            &resized,
            current_x as i64,
            current_y as i64,
        );

        // Adjust coordinates for the next image in the layout
        match monitor.picture_orientation {
            Horizontal => {
                current_y += h;
            }
            Vertical => {
                current_x += w;
            }
        }
    }

    Ok(monitor_canvas)
}

/// Stitches all compiled monitor canvases together to generate the final spanned multi-monitor wallpaper in-memory.
fn assemble_final_wallpaper(
    monitor_images: &[RgbImage],
    config: &Config,
) -> WallSwitchResult<RgbImage> {
    let mut total_w = 0;
    let mut total_h = 0;

    for monitor in &config.monitors {
        match config.monitor_orientation {
            Horizontal => {
                total_w += monitor.resolution.width;
                total_h = total_h.max(monitor.resolution.height);
            }
            Vertical => {
                total_w = total_w.max(monitor.resolution.width);
                total_h += monitor.resolution.height;
            }
        }
    }

    let mut final_canvas = RgbImage::new(total_w as u32, total_h as u32);
    let mut current_x = 0;
    let mut current_y = 0;

    for (idx, img) in monitor_images.iter().enumerate() {
        image::imageops::overlay(&mut final_canvas, img, current_x as i64, current_y as i64);

        match config.monitor_orientation {
            Horizontal => {
                current_x += config.monitors[idx].resolution.width;
            }
            Vertical => {
                current_y += config.monitors[idx].resolution.height;
            }
        }
    }

    Ok(final_canvas)
}

fn get_partitions_iter<'a>(
    mut images: &'a [FileInfo],
    config: &'a Config,
) -> impl Iterator<Item = &'a [FileInfo]> {
    config.monitors.iter().map(move |monitor| {
        let (head, tail) = images.split_at(monitor.pictures_per_monitor.into());
        images = tail;
        head
    })
}

pub fn exec_cmd(cmd: &mut Command, verbose: bool, msg: &str) -> WallSwitchResult<Output> {
    let output: Output = cmd.output().map_err(|e| {
        eprintln!("Failed to execute command: {:?}", cmd.get_program());
        WallSwitchError::Io(e)
    })?;

    let program = cmd.get_program();
    let arguments: Vec<_> = cmd.get_args().collect();

    if !output.status.success() || verbose {
        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}");

        return Err(WallSwitchError::CommandFailed {
            program: format!("{:?}", cmd.get_program()),
            status: output.status.to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        });
    }

    Ok(output)
}