|
1 | 1 | use rand::Rng; |
2 | 2 | use std::{ |
3 | | - fs::{read_dir, read_to_string}, |
| 3 | + fs::{read_dir, read_to_string, DirEntry}, |
4 | 4 | path::PathBuf, |
5 | 5 | process::Command, |
6 | 6 | }; |
@@ -41,6 +41,11 @@ pub fn get_current_wallpaper() -> Result<File> { |
41 | 41 | File::try_from(wallpaper).map_err(|msg| anyhow!("failed to get current wallpaper: {msg}")) |
42 | 42 | } |
43 | 43 |
|
| 44 | +fn get_random_file(files: Vec<&DirEntry>) -> PathBuf { |
| 45 | + let random_number = rand::rng().random_range(0..files.len()); |
| 46 | + files.get(random_number).unwrap().path() |
| 47 | +} |
| 48 | + |
44 | 49 | /// Gets a random wallpaper from the wallpaper directory. |
45 | 50 | /// It can also return a folder, which will be handled by the caller. |
46 | 51 | /// Hidden files will be ignored. |
@@ -68,28 +73,22 @@ pub fn get_random_wallpaper(settings: &Settings) -> Result<File> { |
68 | 73 | return Err(anyhow!("no wallpapers in the wallpaper directory")); |
69 | 74 | } |
70 | 75 |
|
71 | | - let get_path_str = |path: &PathBuf| -> Result<String> { |
72 | | - path.to_str() |
73 | | - .ok_or(anyhow!("failed to convert path to str")) |
74 | | - .map(|path_str| path_str.to_owned()) |
75 | | - }; |
76 | | - |
77 | 76 | let path = if let Ok(current_wallpaper) = get_current_wallpaper() { |
78 | 77 | let current_wallpaper_str = current_wallpaper.to_string(); |
79 | 78 | let files = files |
80 | 79 | .iter() |
81 | 80 | .filter(|entry| { |
82 | | - let entry_path = entry.path(); |
83 | | - let entry_path_str = get_path_str(&entry_path).unwrap(); |
| 81 | + let entry_path_str = entry |
| 82 | + .path() |
| 83 | + .to_str() |
| 84 | + .expect("failed to convert path to str") |
| 85 | + .to_string(); |
84 | 86 | entry_path_str != current_wallpaper_str |
85 | 87 | }) |
86 | 88 | .collect::<Vec<_>>(); |
87 | | - |
88 | | - let random_number = rand::rng().random_range(0..files.len()); |
89 | | - files.get(random_number).unwrap().path() |
| 89 | + get_random_file(files) |
90 | 90 | } else { |
91 | | - let random_number = rand::rng().random_range(0..files.len()); |
92 | | - files.get(random_number).unwrap().path() |
| 91 | + get_random_file(files.iter().collect()) |
93 | 92 | }; |
94 | 93 |
|
95 | 94 | File::new(path).ok_or(anyhow!("failed to get random wallpaper")) |
|
0 commit comments