wallswitch 0.55.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
mod awww;
mod backends;
mod config;
mod dependencies;
mod desktop;
mod dimension;
mod environment;
mod error;
mod fileinfo;
mod list;
mod monitors;
mod orientation;
mod pids;
mod state;
mod traits;
mod walkdir;

pub use self::{
    awww::*, backends::*, config::*, dependencies::*, desktop::*, dimension::*, environment::*,
    error::*, fileinfo::*, list::*, monitors::*, orientation::*, pids::*, state::*, traits::*,
    walkdir::*,
};

// https://blog.rust-lang.org/2026/04/16/Rust-1.95.0/
cfg_select! {
    feature = "args_v2" => {
        mod args_v2;
        pub use args_v2::*;
    }
    _ => {
        // default: "clap"
        mod args_v1;
        pub use args_v1::*;
    }
}

// use rayon::prelude::*;
use std::{
    env,
    hash::{BuildHasher, Hasher, RandomState},
    thread,
};

/// Show initial messages
pub fn show_initial_msgs(config: &Config) -> WallSwitchResult<()> {
    let pkg_name = ENVIRON.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)";
    let dependencies = [depend1, depend2];

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

    config.print()?;

    Ok(())
}

/// 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();
        let error = WallSwitchError::NoImages { paths: directories };
        eprintln!("{error}");
        std::process::exit(1);
    }

    // Filtra as imagens que já estão no histórico recente
    let mut pool: Vec<FileInfo> = images
        .iter()
        .filter(|img| !state.history.contains(&img.path))
        .cloned()
        .collect();

    let nimages: usize = pool.len();

    // Se o pool esgotou (todas já foram vistas), recicla o histórico
    if nimages < config.monitors.len() {
        if config.verbose {
            println!("Image pool exhausted. Resetting history cycle.");
        }
        state.history.clear();
        pool = images.clone();
    }

    pool.update_number();

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

    Ok(pool)
}

/// Gather the files with Smart Caching and Visual Deduplication
pub fn gather_files(config: &Config, state: &mut State) -> WallSwitchResult<Vec<FileInfo>> {
    // 1. Limpa entradas de cache de arquivos deletados
    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();

    // 2. Smart Cache Check (Tamanho + Tempo de Modificação)
    for mut file in raw_files {
        if let Some(cache) = state.hashes.get(&file.path) {
            // Se o arquivo não mudou, usamos o hash em O(1) (Leitura instantânea)
            if cache.size == file.size && cache.mtime == file.mtime {
                file.hash = cache.hash.clone();
                cached_files.push(file);
                continue;
            }
        }
        needs_hash.push(file);
    }

    // 3. Processa em Paralelo (apenas para arquivos NOVOS ou MODIFICADOS)
    if !needs_hash.is_empty() {
        if config.verbose {
            println!(
                "Calculating deep BLAKE3 hashes for {} new/modified files...",
                needs_hash.len()
            );
        }
        needs_hash.update_hash()?;
    }

    // 4. Salva os novos hashes computados no estado
    for file in &needs_hash {
        state.hashes.insert(
            file.path.clone(),
            CacheEntry {
                size: file.size,
                mtime: file.mtime,
                hash: file.hash.clone(),
            },
        );
    }

    // 5. Unifica arquivos e previne Duplicatas Visuais (arquivos com nomes diferentes mas mesmo hash)
    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)
}

/**
Shuffle the vector in place with the Fisher-Yates algorithm.

```
    use wallswitch::shuffle;

    let mut strings = vec!["abc", "foo", "bar", "baz", "mm nn", "zzz"];

    shuffle(&mut strings);

    println!("strings: {:?}", strings);

    let mut integers: Vec<u32> = (1..=20).collect();

    shuffle(&mut integers);

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

<https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle>

<https://stackoverflow.com/questions/26033976/how-do-i-create-a-vec-from-a-range-and-shuffle-it>

*/
pub fn shuffle<T>(vec: &mut [T]) {
    let n: usize = vec.len();
    for i in 0..(n - 1) {
        // Generate random index j, such that: i <= j < n
        // The remainder (`%`) after division is always less than the divisor.
        let j = (rand() as usize) % (n - i) + i;
        vec.swap(i, j);
    }
}

/// Generate a random integer value in the given range (min, max) inclusive.
pub fn get_random_integer(min: u64, max: u64) -> u64 {
    min + rand() % (max - min + 1)
}

/// Generate a random integer value in the given range (min, max) inclusive.
///
/// Return error if `min > max``
pub fn get_random_integer_v2(min: u64, max: u64) -> WallSwitchResult<u64> {
    if min > max {
        Err(WallSwitchError::MinMax { min, max })
    } else {
        // The remainder (`%`) after division is always less than the divisor.
        Ok(min + rand() % (max - min + 1))
    }
}

/// Generate random numbers without external dependencies
pub fn rand() -> u64 {
    RandomState::new().build_hasher().finish()
}

/// 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

Parallelize the computation using std::thread::scope

<https://stackoverflow.com/questions/74590440/how-do-i-change-the-structure-in-the-thread>
*/
pub fn update_images(files: &[FileInfo], config: &Config) -> Vec<FileInfo> {
    let mut owned_files: Vec<FileInfo> = files.to_vec();

    thread::scope(|scope| {
        for file in &mut owned_files {
            scope.spawn(move || -> WallSwitchResult<()> {
                //let id = thread::current().id();
                //println!("identifier thread: {id:?}");
                file.update_info(config)
            });
        }
    });

    owned_files
}

/*
pub fn update_images_v2(
    files: &[FileInfo],
    config: &Config,
) -> Vec<FileInfo> {
    let mut owned_files: Vec<FileInfo> = files.to_vec();

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

        for file in &mut owned_files {
            threads.push(scope.spawn(move || -> WallSwitchResult<()> {
                //let id = thread::current().id();
                //println!("identifier thread: {id:?}");
                file.update_info(config)
            }));
        }

        for thread in threads {
            let _result = thread.join();
        }
    });

    owned_files
}

pub fn update_images_v3(
    files: &[FileInfo],
    config: &Config,
) -> WallSwitchResult<Vec<FileInfo>> {
    files
        .iter() // Sequential computing
        //.par_iter() // Parallelize the computation using rayon
        .cloned()
        .map(|mut file| -> WallSwitchResult<FileInfo> {
            //let thread = rayon::current_thread_index();
            //println!("rayon thread id {:?}", thread);
            file.update_info(config)?;
            Ok(file)
        })
        .collect()
}
*/

#[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();
        shuffle(&mut vec);

        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_v2(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_v2(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_v2(21, 20).map_err(|err| {
            eprintln!("{err}");
            err
        });
        assert!(result.is_err());

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

        Ok(())
    }
}