wallswitch 0.66.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
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
use crate::{
    AwwwBackend, Colors, CommandExt, Config, Desktop, Dimension, Environment, FileInfo,
    HyprlandBackend, Monitor,
    Orientation::{Horizontal, Vertical},
    ProceduralEffect, SwaybgBackend, U8Extension, WALLPAPER_A, WALLPAPER_B, WallSwitchError,
    WallSwitchResult, detect_monitors, is_installed,
};
use image::{RgbImage, imageops::FilterType};
use rayon::prelude::*; // Required for parallel iterators
use std::{
    io::Error,
    path::{Path, PathBuf},
    process::Command,
};

/// Core trait defining the wallpaper application logic across disparate desktop environments.
///
/// Follows the "Functional Core, Imperative Shell" architectural pattern:
/// - `build_commands`: Pure command construction logic.
/// - `apply`: Execution coordinator that dispatches constructed commands to the OS.
pub trait WallpaperBackend {
    /// Pure function: Constructs the required system commands for the target desktop environment.
    fn build_commands(_images: &[FileInfo], _config: &Config) -> WallSwitchResult<Vec<Command>> {
        Ok(vec![])
    }

    /// Impure function: Executes the constructed system commands.
    ///
    /// Iterates over commands generated by [`build_commands`](WallpaperBackend::build_commands)
    /// and runs them using [`CommandExt::run_with_config`]. Can be overridden by compositors
    /// requiring custom lifecycle logic (e.g., GNOME double-buffering, Hyprland preloading).
    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();
            // Using the new CommandExt trait for unified execution
            cmd.run_with_config(config, &format!("Executing {program_name}"))?;
        }
        Ok(())
    }
}

/// Orchestrates wallpaper generation and dispatches to the active desktop environment backend.
///
/// # Workflow
/// 1. Pre-renders, scales, and stitches monitor canvases in parallel into cache partitions.
/// 2. Dispatches compiled image files to the detected [`Desktop`] backend provider.
///
/// # Errors
/// Returns [`WallSwitchError::MissingWaylandTools`] if no supported Wayland utility is present.
pub fn set_wallpaper(
    images: &[FileInfo],
    config: &Config,
    env: &Environment,
) -> WallSwitchResult<()> {
    // 1. Pre-render and compile unique monitor canvases concurrently
    let compiled_images = compile_wallpapers_for_monitors(images, config, env)?;

    // 2. Clean, single-line dispatcher per desktop environment
    match config.desktop {
        Desktop::Gnome => GnomeBackend::apply(&compiled_images, config)?,
        Desktop::Xfce => XfceBackend::apply(&compiled_images, config)?,

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

        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 {
                return Err(WallSwitchError::MissingWaylandTools);
            }
        }

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

    Ok(())
}

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

/// GNOME Desktop backend provider utilizing GSettings and Ping-Pong double buffering.
pub struct GnomeBackend;

impl GnomeBackend {
    /// Builds `gsettings` commands targeting an explicit wallpaper file path.
    ///
    /// Adheres to the DRY principle by configuring both light (`picture-uri`)
    /// and dark (`picture-uri-dark`) schemas, alongside the `spanned` layout option.
    pub fn build_commands_for_path(wallpaper_path: &Path) -> Vec<Command> {
        let wallpaper_uri = format!("file://{}", wallpaper_path.display());
        let mut commands = Vec::with_capacity(3);

        // Configure URI across both light and dark GNOME appearance styles
        for key in ["picture-uri", "picture-uri-dark"] {
            let mut cmd = Command::new("gsettings");
            cmd.args(["set", "org.gnome.desktop.background", key, &wallpaper_uri]);
            commands.push(cmd);
        }

        // Set picture-options layout to span multi-monitor setups seamlessly
        let mut span_cmd = Command::new("gsettings");
        span_cmd.args([
            "set",
            "org.gnome.desktop.background",
            "picture-options",
            "spanned",
        ]);
        commands.push(span_cmd);

        commands
    }
}

impl WallpaperBackend for GnomeBackend {
    /// Satisfies the trait contract by constructing commands for the resolved ping-pong target.
    fn build_commands(_images: &[FileInfo], config: &Config) -> WallSwitchResult<Vec<Command>> {
        let target_path = toggle_ping_pong_path(&config.wallpaper);
        Ok(Self::build_commands_for_path(&target_path))
    }

    fn apply(images: &[FileInfo], config: &Config) -> WallSwitchResult<()> {
        // 1. Alterna para o próximo buffer em memória (A -> B ou B -> A)
        let target_path = toggle_ping_pong_path(&config.wallpaper);

        if config.dry_run {
            println!(
                "[DRY-RUN] Would stitch and save final spanned wallpaper to: {:?}",
                target_path
            );
        } else {
            // 2. Monta o canvas final e salva no buffer de destino
            let final_wallpaper = assemble_final_wallpaper(images, config)?;
            final_wallpaper
                .save(&target_path)
                .map_err(|e| WallSwitchError::Io(Error::other(e)))?;

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

        // 3. Aplica os comandos apontando para a nova URI
        let mut commands = Self::build_commands_for_path(&target_path);
        for cmd in commands.iter_mut() {
            cmd.run_with_config(config, "Executing gsettings")?;
        }

        Ok(())
    }
}

/// XFCE Desktop backend provider using `xfconf-query`.
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)
    }
}

/// Openbox and standalone X11 Window Manager backend provider using `feh`.
pub struct OpenboxBackend;

impl WallpaperBackend for OpenboxBackend {
    /// Builds the execution command for X11 / Openbox environments using `feh`.
    ///
    /// # Protocol Guard & Didactic Rationale
    /// `feh` relies directly on the legacy X11 protocol and requires a valid `$DISPLAY`
    /// to connect to the X Server root window. When running inside a pure Wayland session
    /// (e.g., Mutter, Hyprland, Sway), invoking `feh` results in an immediate display
    /// connection failure (`feh ERROR: Can't open X display`).
    ///
    /// This guard guarantees fail-fast execution and prevents unnecessary process spawns
    /// by ensuring `feh` is exclusively executed under native X11 sessions.
    fn build_commands(images: &[FileInfo], config: &Config) -> WallSwitchResult<Vec<Command>> {
        // Defensive check: Prevent executing X11 tools within modern Wayland sessions
        if config.desktop.is_wayland() {
            return Err(WallSwitchError::CommandFailed {
                program: "feh".to_string(),
                status: "skipped".to_string(),
                stderr: "feh cannot run inside a Wayland session. Use a Wayland backend (awww, swaybg, hyprpaper) or native DE tools (GNOME/XFCE).".to_string(),
            });
        }

        // Construct the multi-monitor wallpaper assignment command for X11
        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])
    }
}

// ==============================================================================
// PURE & ISOLATED UTILITY HELPERS
// ==============================================================================

/// Toggles the ping-pong double buffer path in-memory ([`WALLPAPER_A`] <-> [`WALLPAPER_B`]).
///
/// # Lifecycle & Self-Healing Logic
/// 1. If the current wallpaper does not exist on disk yet (1st run ever),
///    it guarantees the target is [`WALLPAPER_A`].
/// 2. If it already exists, it toggles in-memory with zero heap allocations:
///    - `_a.png` -> `_b.png`
///    - `_b.png` -> `_a.png`
pub fn toggle_ping_pong_path(current_path: &Path) -> PathBuf {
    // Caso especial: se o arquivo não existe no disco (1ª execução), o alvo DEVE ser o _a!
    if !current_path.exists() {
        return current_path.with_file_name(WALLPAPER_A);
    }

    let is_wallpaper_a = current_path
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|name| name.eq_ignore_ascii_case(WALLPAPER_A));

    if is_wallpaper_a {
        current_path.with_file_name(WALLPAPER_B)
    } else {
        current_path.with_file_name(WALLPAPER_A)
    }
}

// ==============================================================================
// 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: &Monitor) -> Result<Self, std::num::TryFromIntError> {
        let mut width = monitor.resolution.width.max(1);
        let mut height = monitor.resolution.height.max(1);
        let pics_per_monitor = monitor.pictures_per_monitor.to_u64().max(1);

        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.max(1),
            base_h: height.max(1),
            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,
) -> WallSwitchResult<()> {
    if config.effect == ProceduralEffect::None {
        return Ok(());
    }

    // 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 (propagates Err if any)
    if let Some(renderer) = resolved.get_renderer(monitor, config)? {
        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);
    }

    Ok(())
}

/// 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: &Monitor,
    config: &Config,
    env: &Environment,
    index: usize,
) -> WallSwitchResult<FileInfo> {
    let cache_dir = env.get_app_cache_dir();

    // Ensure the cache directory exists before writing to it
    if !config.dry_run {
        std::fs::create_dir_all(&cache_dir).map_err(WallSwitchError::Io)?;
    }

    let output_path = cache_dir.join(format!("wallswitch_monitor_{index}.png"));

    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
            );
        }
    } 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(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,
    env: &Environment,
) -> 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 ...");
        }
    }

    // 1. First, collect the partitions into a Vec so we can use Rayon's parallel iterator.
    let partitions: Vec<&[FileInfo]> = get_partitions_iter(images, config).collect();

    // 2. Use Rayon to process the partitions in parallel.
    let compiled_files = partitions
        .into_par_iter()
        .zip(&config.monitors)
        .enumerate()
        .map(|(index, (partition, monitor))| {
            compile_single_monitor_background(partition, monitor, config, env, index)
        })
        .collect::<WallSwitchResult<Vec<_>>>()?;

    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: &Monitor,
) -> WallSwitchResult<RgbImage> {
    let canvas_w = (monitor.resolution.width as u32).max(1);
    let canvas_h = (monitor.resolution.height as u32).max(1);

    let mut monitor_canvas = RgbImage::new(canvas_w, canvas_h);
    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;
                }
            }
        }

        // Memory optimization: Load, resize, and convert inside a nested block to drop
        // the heavy uncompressed DynamicImage (`img`) immediately before drawing.
        let resized = {
            // 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
            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(
    compiled_images: &[FileInfo],
    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).max(1), (total_h as u32).max(1));
    let mut current_x = 0;
    let mut current_y = 0;

    for (idx, img_info) in compiled_images.iter().enumerate() {
        // Load, convert to RGB8, draw, and immediately drop to keep memory consumption low
        let img = image::open(&img_info.path)
            .map_err(|e| {
                WallSwitchError::UnableToFind(format!(
                    "Failed to load compiled monitor canvas: {e}"
                ))
            })?
            .to_rgb8();

        image::imageops::overlay(&mut final_canvas, &img, current_x as i64, current_y as i64);

        if let Some(mon) = config.monitors.get(idx) {
            match config.monitor_orientation {
                Horizontal => {
                    current_x += mon.resolution.width;
                }
                Vertical => {
                    current_y += mon.resolution.height;
                }
            }
        }
    }

    Ok(final_canvas)
}

/// Partitions a flat slice of images into sub-slices for each configured monitor.
///
/// Each monitor consumes a specified number of pictures (`pictures_per_monitor`).
/// The iterator lazily advances through the `images` slice, dividing it into chunks
/// corresponding to each monitor's requirements.
///
/// # Safety & Panic-Freedom
///
/// Uses [`slice::split_at_checked`] instead of `split_at` to eliminate runtime panics
/// if fewer images are available than the monitor configuration requests.
///
/// - If `count <= images.len()`, the slice is split into `[0..count]` (head) and `[count..]` (tail).
/// - If `count > images.len()`, it gracefully falls back to yielding all remaining images
///   in `head` and leaves `tail` as an empty slice (`&[]`).
fn get_partitions_iter<'a>(
    mut images: &'a [FileInfo],
    config: &'a Config,
) -> impl Iterator<Item = &'a [FileInfo]> {
    config.monitors.iter().map(move |monitor| {
        let count = monitor.pictures_per_monitor as usize;

        // Perform safe boundary splitting:
        // If there are not enough images remaining, consume what is left
        // and set the remaining tail to an empty slice (&[]).
        let (head, tail) = images.split_at_checked(count).unwrap_or((images, &[]));

        // Advance the internal cursor to the unassigned remainder of the slice
        images = tail;

        // Return the chunk allocated for the current monitor
        head
    })
}

//----------------------------------------------------------------------------//
//                                   Tests                                    //
//----------------------------------------------------------------------------//

/// cargo test -- --show-output tests_wallpaper
#[cfg(test)]
mod tests_wallpaper {
    use super::*;
    use crate::{Dimension, Orientation};
    use std::fs;

    #[test]
    fn test_toggle_ping_pong_path() {
        let temp_dir = std::env::temp_dir().join("wallswitch_toggle_test");
        let _ = fs::create_dir_all(&temp_dir);

        let path_a = temp_dir.join(WALLPAPER_A);
        let path_b = temp_dir.join(WALLPAPER_B);

        let _ = fs::remove_file(&path_a);
        let _ = fs::remove_file(&path_b);

        // 1. Arquivo não existe no disco (1ª execução) -> DEVE retornar _A
        assert_eq!(toggle_ping_pong_path(&path_a), path_a);

        // 2. Arquivo _A existe no disco -> DEVE alternar para _B
        fs::write(&path_a, b"buffer A").unwrap();
        assert_eq!(toggle_ping_pong_path(&path_a), path_b);

        // 3. Arquivo _B existe no disco -> DEVE alternar para _A
        fs::write(&path_b, b"buffer B").unwrap();
        assert_eq!(toggle_ping_pong_path(&path_b), path_a);

        let _ = fs::remove_dir_all(&temp_dir);
    }

    /// Verifies that GNOME backend constructs all 3 required GSettings commands:
    /// light mode URI, dark mode URI, and spanned layout options.
    #[test]
    fn test_gnome_build_commands_for_path() {
        let target = Path::new("/tmp/wallswitch_a.png");
        let commands = GnomeBackend::build_commands_for_path(target);

        assert_eq!(commands.len(), 3, "Expected exactly 3 GSettings directives");

        for cmd in &commands {
            assert_eq!(
                cmd.get_program(),
                "gsettings",
                "Target binary must be gsettings"
            );
        }

        let expected_uri = "file:///tmp/wallswitch_a.png";

        let has_light_uri = commands.iter().any(|cmd| {
            let args: Vec<_> = cmd.get_args().map(|a| a.to_string_lossy()).collect();
            args.contains(&"picture-uri".into()) && args.contains(&expected_uri.into())
        });

        let has_dark_uri = commands.iter().any(|cmd| {
            let args: Vec<_> = cmd.get_args().map(|a| a.to_string_lossy()).collect();
            args.contains(&"picture-uri-dark".into()) && args.contains(&expected_uri.into())
        });

        let has_spanned = commands.iter().any(|cmd| {
            let args: Vec<_> = cmd.get_args().map(|a| a.to_string_lossy()).collect();
            args.contains(&"picture-options".into()) && args.contains(&"spanned".into())
        });

        assert!(
            has_light_uri,
            "GSettings picture-uri command missing or malformed"
        );
        assert!(
            has_dark_uri,
            "GSettings picture-uri-dark command missing or malformed"
        );
        assert!(
            has_spanned,
            "GSettings spanned layout command missing or malformed"
        );
    }

    /// Verifies that OpenboxBackend fails fast and rejects execution under Wayland sessions.
    #[test]
    fn test_openbox_backend_wayland_guard() {
        let config = Config {
            desktop: Desktop::Wayland,
            ..Config::default()
        };

        let images = vec![];
        let result = OpenboxBackend::build_commands(&images, &config);

        assert!(
            result.is_err(),
            "OpenboxBackend must fail fast when running inside a Wayland compositor"
        );
    }

    /// Verifies mathematical coordinate slicing for multi-picture horizontal splitting.
    #[test]
    fn test_layout_target_calculation() {
        let monitor = Monitor {
            picture_orientation: Orientation::Horizontal,
            pictures_per_monitor: 2,
            resolution: Dimension {
                width: 3840,
                height: 2160,
            },
        };

        let target = LayoutTarget::calculate(&monitor).expect("Layout geometry calculation failed");
        assert_eq!(target.base_w, 3840);
        assert_eq!(
            target.base_h, 1080,
            "Height should be bisected into two 1080p partitions"
        );
        assert_eq!(target.rem_h, 0);
        assert_eq!(target.rem_w, 0);
    }

    /// Verifies safe, panic-free iterator partitioning across configured monitors.
    #[test]
    fn test_get_partitions_iter_safety() {
        let monitor1 = Monitor {
            pictures_per_monitor: 2,
            ..Monitor::default()
        };
        let monitor2 = Monitor {
            pictures_per_monitor: 1,
            ..Monitor::default()
        };
        let config = Config {
            monitors: vec![monitor1, monitor2],
            ..Config::default()
        };

        let dummy_images = vec![
            FileInfo {
                number: 1,
                ..FileInfo::default()
            },
            FileInfo {
                number: 2,
                ..FileInfo::default()
            },
            FileInfo {
                number: 3,
                ..FileInfo::default()
            },
        ];

        let partitions: Vec<_> = get_partitions_iter(&dummy_images, &config).collect();
        assert_eq!(partitions.len(), 2, "Expected 2 monitor partitions");
        assert_eq!(partitions[0].len(), 2, "Monitor 1 expects 2 images");
        assert_eq!(partitions[1].len(), 1, "Monitor 2 expects 1 image");
    }
}