1use std::collections::BTreeMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5use std::sync::mpsc;
6
7use eframe::egui;
8
9use crate::cache;
10use crate::cli::Args;
11use crate::error::{BackgroundPickerError, Result};
12use crate::scanner::{self, ImageInfo};
13use crate::thumbnail;
14
15const DEFAULT_PRELOAD_COUNT: usize = 8;
16const CHUNK_SIZE: usize = 100;
17const MIN_THREAD_COUNT: usize = 4;
18const PROGRESS_THRESHOLD: usize = 50;
19
20pub struct BackgroundPickerApp {
21 pub args: Args,
22 pub images: Vec<ImageInfo>,
23 pub folder_tree: BTreeMap<String, Vec<usize>>,
24 pub loading: bool,
25 pub thumbnail_sender: mpsc::Sender<(usize, egui::ColorImage)>,
26 pub thumbnail_receiver: mpsc::Receiver<(usize, egui::ColorImage)>,
27 pub thread_pool: rayon::ThreadPool,
28 pub cache_dir: PathBuf,
29}
30
31impl BackgroundPickerApp {
32 pub fn new(_cc: &eframe::CreationContext<'_>, args: Args) -> Result<Self> {
37 let cache_dir = cache::thumbnail_cache_dir()?;
38 if args.debug {
39 println!("Using thumbnail cache directory: {}", cache_dir.display());
40 }
41
42 let mut app = Self::with_state(args, Vec::new(), cache_dir)?;
43 app.scan_images();
44
45 if app.args.pregenerate {
46 app.pregenerate_all_thumbnails();
47 std::process::exit(0);
48 }
49
50 Ok(app)
51 }
52
53 pub fn with_state(args: Args, images: Vec<ImageInfo>, cache_dir: PathBuf) -> Result<Self> {
61 let (thumbnail_sender, thumbnail_receiver) = mpsc::channel();
62 Ok(Self {
63 args,
64 images,
65 folder_tree: BTreeMap::new(),
66 loading: false,
67 thumbnail_sender,
68 thumbnail_receiver,
69 thread_pool: Self::build_thread_pool()?,
70 cache_dir,
71 })
72 }
73
74 fn build_thread_pool() -> Result<rayon::ThreadPool> {
75 let num_threads = std::thread::available_parallelism()
76 .map_or(MIN_THREAD_COUNT, |n| n.get().max(MIN_THREAD_COUNT));
77 Ok(rayon::ThreadPoolBuilder::new()
78 .num_threads(num_threads)
79 .build()?)
80 }
81
82 pub fn scan_images(&mut self) {
83 if self.args.debug {
84 println!("Scanning directory: {}", self.args.directory.display());
85 }
86
87 let scanner::ScanResult {
88 images,
89 folder_tree,
90 } = scanner::scan(&self.args.directory);
91
92 if self.args.debug {
93 println!(
94 "Found {} images in {} folders",
95 images.len(),
96 folder_tree.len()
97 );
98 }
99
100 self.images = images;
101 self.folder_tree = folder_tree;
102 self.loading = false;
103 }
104
105 pub fn pregenerate_all_thumbnails(&mut self) {
106 let total_images = self.images.len();
107 if total_images == 0 {
108 if self.args.debug {
109 println!("No images found to pregenerate thumbnails for");
110 }
111 return;
112 }
113
114 if self.args.debug {
115 println!("Pre-generating thumbnails for {total_images} images...");
116 } else {
117 println!("Generating thumbnails for {total_images} images...");
118 }
119
120 let start_time = std::time::Instant::now();
121 let cache_dir = self.cache_dir.clone();
122 let size = self.args.thumbnail_size;
123 let debug = self.args.debug;
124 let paths: Vec<PathBuf> = self.images.iter().map(|image| image.path.clone()).collect();
125
126 let (cached_count, generated_count) =
127 Self::generate_thumbnails_in_parallel(&paths, size, &cache_dir, debug);
128
129 let elapsed = start_time.elapsed();
130
131 if self.args.debug {
132 println!("Thumbnail pregeneration complete:");
133 println!(" - {cached_count} thumbnails found in cache");
134 println!(" - {generated_count} thumbnails generated");
135 println!(
136 " - {} thumbnails failed",
137 total_images - cached_count - generated_count
138 );
139 println!(" - Time elapsed: {:.2}s", elapsed.as_secs_f64());
140 } else {
141 println!(
142 "Thumbnail generation complete: {cached_count} cached, {generated_count} generated ({:.1}s)",
143 elapsed.as_secs_f64()
144 );
145 }
146 }
147
148 fn generate_thumbnails_in_parallel(
149 paths: &[PathBuf],
150 size: u32,
151 cache_dir: &Path,
152 debug: bool,
153 ) -> (usize, usize) {
154 use rayon::prelude::*;
155
156 let total = paths.len();
157 let results: Vec<(bool, bool)> = (0..total)
158 .collect::<Vec<_>>()
159 .par_chunks(CHUNK_SIZE)
160 .enumerate()
161 .flat_map(|(chunk_idx, chunk)| {
162 let chunk_results: Vec<(bool, bool)> = chunk
163 .par_iter()
164 .map(|&index| {
165 Self::generate_one_thumbnail(&paths[index], index, size, cache_dir, debug)
166 })
167 .collect();
168
169 if !debug && total > PROGRESS_THRESHOLD {
170 let completed = (chunk_idx + 1) * CHUNK_SIZE.min(total);
171 print!("\rProgress: {completed}/{total} images processed");
172 let _ = std::io::Write::flush(&mut std::io::stdout());
173 }
174
175 chunk_results
176 })
177 .collect();
178
179 if !debug && total > PROGRESS_THRESHOLD {
180 println!();
181 }
182
183 let cached_count = results.iter().filter(|(was_cached, _)| *was_cached).count();
184 let generated_count = results
185 .iter()
186 .filter(|(_, was_generated)| *was_generated)
187 .count();
188 (cached_count, generated_count)
189 }
190
191 #[allow(clippy::option_if_let_else)] fn generate_one_thumbnail(
194 path: &Path,
195 index: usize,
196 size: u32,
197 cache_dir: &Path,
198 debug: bool,
199 ) -> (bool, bool) {
200 let abs_path = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
201 let file_name = path.file_name().unwrap_or_default();
202
203 if let Some(existing) = cache::find_existing_thumbnail(&abs_path) {
204 if thumbnail::load_cached(&existing, size).is_some() {
205 if debug {
206 println!(" [{}] Found existing thumbnail: {file_name:?}", index + 1);
207 }
208 return (true, false);
209 }
210 }
211
212 let cache_path = cache::cached_thumbnail_path(&abs_path, cache_dir);
213 if cache::is_cache_valid(&abs_path, &cache_path)
214 && thumbnail::load_cached(&cache_path, size).is_some()
215 {
216 if debug {
217 println!(" [{}] Found cached thumbnail: {file_name:?}", index + 1);
218 }
219 return (true, false);
220 }
221
222 if let Some(color_image) = thumbnail::generate(&abs_path, size) {
223 thumbnail::save_to_cache(&color_image, &cache_path, &abs_path);
224 if debug {
225 println!(" [{}] Generated thumbnail: {file_name:?}", index + 1);
226 }
227 (false, true)
228 } else {
229 if debug {
230 println!(
231 " [{}] Failed to generate thumbnail: {file_name:?}",
232 index + 1
233 );
234 }
235 (false, false)
236 }
237 }
238
239 pub fn load_thumbnail(&mut self, ctx: &egui::Context, index: usize) {
243 let Some(image) = self.images.get_mut(index) else {
244 return;
245 };
246 if image.thumbnail.is_some() || image.loading {
247 return;
248 }
249 image.loading = true;
250 let path = image.path.clone();
251
252 self.spawn_thumbnail_load(ctx, index, path);
253 }
254
255 pub fn preload_batch(&mut self, ctx: &egui::Context, indices: &[usize]) {
258 for &index in indices.iter().take(DEFAULT_PRELOAD_COUNT) {
259 let Some(image) = self.images.get_mut(index) else {
260 continue;
261 };
262 if image.thumbnail.is_some() || image.loading {
263 continue;
264 }
265 image.loading = true;
266 let path = image.path.clone();
267
268 self.spawn_thumbnail_load(ctx, index, path);
269 }
270 }
271
272 fn spawn_thumbnail_load(&self, ctx: &egui::Context, index: usize, path: PathBuf) {
273 let sender = self.thumbnail_sender.clone();
274 let size = self.args.thumbnail_size;
275 let cache_dir = self.cache_dir.clone();
276 let debug = self.args.debug;
277 let ctx = ctx.clone();
278
279 self.thread_pool.spawn(move || {
280 if let Some(color_image) = thumbnail::load_or_generate(&path, size, &cache_dir, debug) {
281 if sender.send((index, color_image)).is_ok() {
282 ctx.request_repaint();
283 }
284 }
285 });
286 }
287
288 pub fn process_thumbnail_results(&mut self, ctx: &egui::Context) {
289 while let Ok((index, color_image)) = self.thumbnail_receiver.try_recv() {
290 let texture = ctx.load_texture(
291 format!("thumbnail_{index}"),
292 color_image,
293 egui::TextureOptions::default(),
294 );
295
296 if let Some(image) = self.images.get_mut(index) {
297 image.thumbnail = Some(texture);
298 image.loading = false;
299 }
300 }
301 }
302
303 pub fn set_background(&self, path: &Path) -> Result<()> {
308 let mut command_parts = self.args.command.split_whitespace();
309 let program = command_parts
310 .next()
311 .ok_or_else(|| BackgroundPickerError::CommandExecution("Empty command".to_owned()))?;
312
313 let output = Command::new(program)
314 .args(command_parts)
315 .arg(path)
316 .output()
317 .map_err(|e| BackgroundPickerError::CommandExecution(e.to_string()))?;
318
319 if !output.status.success() {
320 let error_msg = String::from_utf8_lossy(&output.stderr).into_owned();
321 return Err(BackgroundPickerError::CommandExecution(error_msg));
322 }
323
324 Ok(())
325 }
326
327 pub fn save_selected_image(&self, path: &Path) -> Result<()> {
332 if let Some(parent) = self.args.selected_image_file.parent() {
333 fs::create_dir_all(parent).map_err(BackgroundPickerError::SaveSelectedImage)?;
334 }
335
336 fs::write(
337 &self.args.selected_image_file,
338 path.to_string_lossy().as_bytes(),
339 )
340 .map_err(BackgroundPickerError::SaveSelectedImage)
341 }
342}
343
344impl eframe::App for BackgroundPickerApp {
345 fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
346 let ctx = ui.ctx().clone();
347 self.process_thumbnail_results(&ctx);
348
349 egui::CentralPanel::default().show(ui, |ui| {
350 if self.loading {
351 ui.centered_and_justified(|ui| {
352 ui.label("Scanning for images...");
353 });
354 return;
355 }
356
357 ui.heading("Background Picker");
358 ui.separator();
359
360 egui::ScrollArea::vertical().show(ui, |ui| {
361 let folder_tree = std::mem::take(&mut self.folder_tree);
365
366 for (folder, image_indices) in &folder_tree {
367 let folder_label = if folder.is_empty() {
368 format!("Root ({} images)", image_indices.len())
369 } else {
370 format!("{folder} ({} images)", image_indices.len())
371 };
372
373 let header_response = egui::CollapsingHeader::new(folder_label)
374 .default_open(false)
375 .show(ui, |ui| {
376 ui.horizontal_wrapped(|ui| {
377 for &index in image_indices {
378 self.load_thumbnail(&ctx, index);
379 self.show_thumbnail(ui, index);
380 }
381 });
382 });
383
384 if header_response
385 .body_response
386 .is_some_and(|r| r.rect.height() > 0.0)
387 {
388 self.preload_batch(&ctx, image_indices);
389 }
390 }
391
392 self.folder_tree = folder_tree;
393 });
394 });
395 }
396}
397
398impl BackgroundPickerApp {
399 #[allow(clippy::cast_precision_loss)] fn show_thumbnail(&self, ui: &mut egui::Ui, index: usize) {
401 let Some(image) = self.images.get(index) else {
402 return;
403 };
404
405 if let Some(texture) = image.thumbnail.as_ref() {
406 let response = ui.add(egui::Image::new(texture).sense(egui::Sense::click()));
407 if response.clicked() {
408 let path = image.path.clone();
409 if let Err(e) = self.set_background(&path) {
410 eprintln!("Failed to set background: {e}");
411 } else {
412 let _ = self.save_selected_image(&path);
413 ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
414 }
415 }
416 response.on_hover_text(&image.relative_path);
417 } else {
418 let loading = image.loading;
419 let relative_path = image.relative_path.clone();
420 let size = self.args.thumbnail_size as f32;
421
422 let (rect, response) =
423 ui.allocate_exact_size(egui::Vec2::splat(size), egui::Sense::hover());
424 ui.painter()
425 .rect_filled(rect, 5.0_f32, egui::Color32::LIGHT_GRAY);
426
427 let loading_text = if loading {
428 "Loading..."
429 } else {
430 "Click to load"
431 };
432 ui.painter().text(
433 rect.center(),
434 egui::Align2::CENTER_CENTER,
435 loading_text,
436 egui::FontId::default(),
437 egui::Color32::DARK_GRAY,
438 );
439 response.on_hover_text(&relative_path);
440 }
441 }
442}