wallswitch 0.57.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
use crate::*;
use std::process;

// use rayon::prelude::*;
use std::{
    env,
    io::{self, Write},                     // For real-time terminal flushing
    sync::atomic::{AtomicUsize, Ordering}, // For thread-safe counting
    thread,
};

/// Core application logic: coordinates arguments, state, and execution cycles.
pub fn run() -> WallSwitchResult<()> {
    // 1. Parse command-line arguments as the primary source of intent
    let args = Arguments::build()?;

    // 2. Load persistent state (History and BLAKE3 hash cache) from disk
    let mut state = State::load();

    // 3. Initialize configuration by merging JSON file settings with CLI overrides
    let config = Config::new(&args)?;

    // 4. Handle listing requests
    if let Some(criteria) = args.list {
        match criteria {
            // If the user wants raw JSON state output
            SortCriteria::Processed | SortCriteria::Unprocessed | SortCriteria::Cache => {
                list_json_cache(&state, criteria)?;
            }
            // Standard table listing
            _ => {
                let mut images = gather_files(&config, &mut state)?;

                // This will now show the "Probing image [x/y] : path"
                // if dimensions are missing from wallswitch-state.json
                images = update_images(&images, &config, &mut state);

                list_all_images(images, criteria)?;
            }
        }
        process::exit(0);
    }

    // 5. Normal operation: Show startup info and clean up previous processes
    show_initial_msgs(&config)?;
    kill_other_instances(&config)?;

    // 6. Execute either a single switch or start the infinite loop
    if config.once {
        try_run_cycle(&config, &mut state)
    } else {
        loop {
            try_run_cycle(&config, &mut state)?;
        }
    }
}

/// Gather the files with Smart Caching and Visual Deduplication
pub fn gather_files(config: &Config, state: &mut State) -> WallSwitchResult<Vec<FileInfo>> {
    state.garbage_collect();

    let mut raw_files = Vec::new();
    for dir in &config.directories {
        raw_files.extend(get_files_from_directory(dir, config)?);
    }

    let mut needs_hash = Vec::new();
    let mut cached_files = Vec::new();

    for mut file in raw_files {
        if let Some(cache) = state.hashes.get(&file.path)
            && cache.size == file.size
            && cache.mtime == file.mtime
        {
            file.hash = cache.hash.clone();
            // Idiomatically assigning the Option<Dimension>
            file.dimension = cache.dimension.clone();
            cached_files.push(file);
            continue;
        }
        needs_hash.push(file);
    }

    if !needs_hash.is_empty() {
        if config.verbose {
            println!(
                "Calculating deep BLAKE3 hashes for {} new/modified files...",
                needs_hash.len()
            );
        }
        needs_hash.update_hash()?;
    }

    for file in &needs_hash {
        state.hashes.insert(
            file.path.clone(),
            CacheEntry {
                size: file.size,
                mtime: file.mtime,
                hash: file.hash.clone(),
                dimension: file.dimension.clone(),
            },
        );
    }

    let all_files = cached_files.into_iter().chain(needs_hash);
    let mut files = Vec::new();
    let mut seen_hashes = std::collections::HashSet::new();

    for file in all_files {
        if seen_hashes.insert(file.hash.clone()) {
            files.push(file);
        } else if config.verbose {
            println!("Visual duplicate ignored: {:?}", file.path);
        }
    }

    Ok(files)
}

/// Show initial messages
pub fn show_initial_msgs(config: &Config) -> WallSwitchResult<()> {
    let env = Environment::new()?;
    let pkg_name = env.get_pkg_name();

    let pkg_desc = env!("CARGO_PKG_DESCRIPTION");
    let pkg_version = env!("CARGO_PKG_VERSION");
    let interval = config.interval;
    let info = format!("Interval between each wallpaper: {interval} seconds.");
    let author = "Claudio Fernandes de Souza Rodrigues (claudiofsrodrigues@gmail.com)";

    println!("{pkg_name} {pkg_desc}\n{info}\n{author}");
    println!("version: {pkg_version}\n");

    let depend1 = "imagemagick (image viewing/manipulation program)";
    let depend2 = "feh (fast and light image viewer for X11/Openbox)";
    let depend3 = "awww (animated Wayland wallpaper daemon)";
    let depend4 = "swaybg (wallpaper utility for Wayland compositors)";
    let depend5 = "hyprpaper (wallpaper utility for Hyprland)";

    let dependencies = [depend1, depend2, depend3, depend4, depend5];

    println!("Dependencies:");
    dependencies.print_with_spaces(" ");
    println!();

    config.print()?;

    Ok(())
}

/// Encapsulates logic for a single wallpaper selection and application cycle.
///
/// Implements a "Strict Quorum" logic with hardware-aware concurrency:
/// 1. It pulls candidates from the unseen pool (shuffled).
/// 2. It determines the optimal batch size using the ConcurrencyExt trait.
/// 3. It probes batches in parallel based on actual logical CPU cores.
/// 4. If the pool of valid images cannot satisfy the requirement (needed),
///    it triggers self-healing by clearing the history and retrying once.
fn try_run_cycle(config: &Config, state: &mut State) -> WallSwitchResult<()> {
    let candidates = get_images(config, state)?;
    let needed = config.get_number_of_images();

    // If verbose is enabled, print the full list of candidates found in the directories.
    // This happens after shuffling but before probing dimensions.
    if config.verbose {
        display_files(&candidates, config);
    }

    // Utilize your trait to get the hardware-aware optimal core count.
    // Since ConcurrencyExt is implemented for any slice [T], we call it on candidates.
    // Determine the optimal batch size based on logical CPU cores
    let batch_size = candidates.get_optimal_cores();

    let mut valid_pool: Vec<FileInfo> = Vec::new();
    let mut candidate_iter = candidates.into_iter();

    // PHASE 1: Accumulate valid images until the quorum (needed) is met.
    // We iterate in batches to maximize parallel execution of 'identify' commands.
    while valid_pool.len() < needed {
        let mut batch = Vec::new();

        // Fill the batch using the hardware-optimal size
        for _ in 0..batch_size {
            if let Some(img) = candidate_iter.next() {
                batch.push(img);
            }
        }

        // If no more candidates are found in the directories, break the loop
        if batch.is_empty() {
            break;
        }

        // Parallel update and validation of the current batch
        let probed_batch = update_images(&batch, config, state);

        // Only collect images that successfully passed dimension and size filters
        valid_pool.extend(
            probed_batch
                .into_iter()
                .filter(|f| f.is_valid == Some(true)),
        );
    }

    // PHASE 2: Quorum Validation.
    if valid_pool.len() >= needed {
        // Success: Extract exactly the number of images required.
        let cycle_images: Vec<FileInfo> = valid_pool.drain(0..needed).collect();

        if config.verbose {
            println!(
                "Quorum satisfied: {} valid images found using {} parallel threads.",
                cycle_images.len(),
                batch_size
            );
        }

        print!("{}", SliceDisplay(&cycle_images));
        println!();

        // Apply wallpaper using the configured backend (Gnome, XFCE, Wayland, etc.)
        set_wallpaper(&cycle_images, config)?;

        // Update history and persist state to disk
        for fig in &cycle_images {
            state.history.push(fig.path.clone());
        }
        state.save()?;

        if config.once {
            return Ok(());
        }

        // Wait for the defined interval and recurse for the next cycle
        std::thread::sleep(std::time::Duration::from_secs(config.interval));
        return try_run_cycle(config, state);
    }

    // PHASE 3: Self-Healing.
    // If the pool wasn't satisfied, clear history and retry once to find valid images.
    if !state.history.is_empty() {
        if config.verbose {
            println!(
                "\nQuorum failed: Needed {}, but found only {}. Resetting history for a full disk search...",
                needed,
                valid_pool.len()
            );
        }
        state.history.clear();
        state.save()?;

        // Restart the cycle with a clean history
        return try_run_cycle(config, state);
    }

    // Critical failure: No valid images found even with an empty history.
    Err(WallSwitchError::InsufficientNumber)
}

/// Get unique and random images filtering against history
pub fn get_images(config: &Config, state: &mut State) -> WallSwitchResult<Vec<FileInfo>> {
    let images: Vec<FileInfo> = gather_files(config, state)?;

    if images.is_empty() {
        let directories = config.directories.clone();
        return Err(WallSwitchError::NoImages { paths: directories });
    }

    // Filter out images that are already in the recent history
    let mut pool: Vec<FileInfo> = images
        .iter()
        .filter(|img| !state.history.contains(&img.path))
        .cloned()
        .collect();

    // The required number of images for ONE complete cycle
    let needed_images = config.get_number_of_images();

    // If the pool is too small to even start a cycle, reset the history immediately
    if pool.len() < needed_images {
        if config.verbose {
            println!(
                "Image pool exhausted (less than {needed_images} unseen images). Resetting history cycle."
            );
        }
        state.history.clear();
        pool = images.clone();
    }

    pool.update_number();

    if !config.sort {
        pool.shuffle();
    }

    Ok(pool)
}

/// Display found images
pub fn display_files(files: &[FileInfo], config: &Config) {
    let nfiles = files.len();
    if nfiles == 0 {
        return;
    }

    let ndigits = nfiles.to_string().len();

    if config.sort {
        println!(
            "\n{} images were found (sorted):",
            nfiles.to_string().green().bold()
        );
    } else {
        println!(
            "\n{} images were found (shuffled):",
            nfiles.to_string().green().bold()
        );
    }

    for file in files {
        println!(
            "images[{n:0ndigits$}/{t}]: {p:?}",
            n = file.number,
            p = file.path,
            t = file.total,
        );
    }
    println!();
}

/**
Update FileInfo images with dimension information safely and concurrently.

This implementation follows the DRY principle by utilizing the Smart Cache:
1. It filters only images that lack dimension data (Option is None).
2. It uses ConcurrencyExt to limit parallel 'identify' processes to CPU core count.
3. It saves the results back to the persistent state, ensuring future calls are O(1).
*/
pub fn update_images(files: &[FileInfo], config: &Config, state: &mut State) -> Vec<FileInfo> {
    let mut owned_files: Vec<FileInfo> = files.to_vec();

    // 1. Functional approach: select only files needing probe OR validation
    let mut needs_update: Vec<&mut FileInfo> = owned_files
        .iter_mut()
        .filter(|file| file.dimension.is_none() || file.is_valid.is_none())
        .collect();

    if !needs_update.is_empty() {
        // Count only those that actually need the heavy "identify" command
        let total_to_probe = needs_update
            .iter()
            .filter(|f| f.dimension.is_none())
            .count();
        let counter = AtomicUsize::new(0);

        if config.verbose && total_to_probe > 0 {
            println!("Probing dimensions for {} new files...", total_to_probe);
        }

        let chunk_size = needs_update.get_chunk_size(needs_update.len());

        thread::scope(|scope| {
            for chunk in needs_update.chunks_mut(chunk_size) {
                scope.spawn(|| {
                    // Functional evaluation inside the thread
                    chunk.iter_mut().for_each(|file| {
                        // Step A: Probe dimension if missing
                        if file.dimension.is_none() && file.update_info(config).is_ok() {
                            let current = counter.fetch_add(1, Ordering::SeqCst) + 1;
                            let file_name =
                                file.path.file_name().unwrap_or_default().to_string_lossy();
                            let msg = format!(
                                "Probing image [{current: >4}/{total_to_probe}] : {file_name}"
                            )
                            .to_line_start();
                            print!("{msg}");
                            let _ = io::stdout().flush();
                        }

                        // Step B: Validate based on current runtime Config
                        let dim_valid = file
                            .dimension
                            .as_ref()
                            .map(|d| d.is_valid(config))
                            .unwrap_or(false);
                        let size_valid = file.size_is_valid(config);
                        let name_valid = file.name_is_valid(config);

                        file.is_valid = Some(dim_valid && size_valid && name_valid);
                    });
                });
            }
        });

        if config.verbose && total_to_probe > 0 {
            println!("\nProbing completed.\n");
        }

        // Step C: Sync probed dimensions with the state cache
        let mut state_changed = false;
        for file in &owned_files {
            if let Some(dim) = &file.dimension
                && let Some(entry) = state.hashes.get_mut(&file.path)
                && entry.dimension.is_none()
            {
                entry.dimension = Some(dim.clone());
                state_changed = true;
            }
        }

        if state_changed {
            let _ = state.save();
        }
    }

    owned_files
}

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

/// Run tests with:
/// cargo test -- --show-output tests_lib
#[cfg(test)]
mod test_lib {
    use crate::*;

    #[test]
    /// `cargo test -- --show-output vec_shuffle`
    fn vec_shuffle() {
        let mut vec: Vec<u32> = (1..=100).collect();
        vec.shuffle();

        println!("vec: {vec:?}");
        assert_eq!(vec.len(), 100);
    }

    #[test]
    /// `cargo test -- --show-output random_integers_v1`
    ///
    /// <https://stackoverflow.com/questions/48218459/how-do-i-generate-a-vector-of-random-numbers-in-a-range>
    fn random_integers_v1() {
        // Example: Get a random integer value in the range 1 to 20:
        let value: u64 = get_random_integer(1, 20);

        println!("integer: {value:?}");

        // Generate a vector of 100 64-bit integer values in the range from 1 to 20,
        // allowing duplicates:

        let integers: Vec<u64> = (0..100).map(|_| get_random_integer(1, 20)).collect();

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

        let condition_a = integers.iter().min() >= Some(&1);
        let condition_b = integers.iter().max() <= Some(&20);

        assert!(condition_a);
        assert!(condition_b);
        assert_eq!(integers.len(), 100);
    }

    #[test]
    /// `cargo test -- --show-output random_integers_v2`
    ///
    /// <https://stackoverflow.com/questions/48218459/how-do-i-generate-a-vector-of-random-numbers-in-a-range>
    fn random_integers_v2() -> WallSwitchResult<()> {
        // Example: Get a random integer value in the range 1 to 20:
        let value: u64 = get_random_integer_safe(1, 20)?;

        println!("integer: {value:?}");

        // Generate a vector of 100 64-bit integer values in the range from 1 to 20,
        // allowing duplicates:

        let integers: Vec<u64> = (0..100)
            .map(|_| get_random_integer_safe(1, 20))
            .collect::<Result<Vec<u64>, _>>()?;

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

        let condition_a = integers.iter().min() >= Some(&1);
        let condition_b = integers.iter().max() <= Some(&20);

        assert!(condition_a);
        assert!(condition_b);
        assert_eq!(integers.len(), 100);

        Ok(())
    }

    #[test]
    /// `cargo test -- --show-output random_integers_v3`
    fn random_integers_v3() -> WallSwitchResult<()> {
        let result = get_random_integer_safe(21, 20).map_err(|err| {
            eprintln!("{err}");
            err
        });
        assert!(result.is_err());

        let error = result.unwrap_err();
        eprintln!("error: {error:?}");

        Ok(())
    }
}