photograph 0.4.1

Native desktop photo browser and non-destructive editor for RAW images and color grading
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
use std::{
    collections::{HashMap, HashSet},
    path::PathBuf,
    sync::mpsc,
};

use crate::locations::{self, Location};

const CELL: f32 = 170.0;
const FILMSTRIP_CELL: f32 = 64.0;
const MAX_THUMB_JOBS: usize = 4;

enum ThumbState {
    Loading,
    Ready(egui::TextureHandle),
    Failed,
}

struct ThumbResult {
    path: PathBuf,
    rgba: Option<(Vec<u8>, usize, usize)>,
}

/// File browser state for directory navigation and thumbnail selection.
pub struct Browser {
    pub current_dir: PathBuf,
    subdirs: Vec<(PathBuf, String)>,
    pub images: Vec<(PathBuf, String)>,
    pending_nav: Option<PathBuf>,
    thumbnails: HashMap<PathBuf, ThumbState>,
    tx: mpsc::SyncSender<ThumbResult>,
    rx: mpsc::Receiver<ThumbResult>,
    /// The focused/open photo — drives the Edit target and highlight.
    pub selected: Option<PathBuf>,
    /// Anchor for shift-click range selection — the last plain- or Ctrl-clicked item.
    select_anchor: Option<PathBuf>,
    /// Working set built via Ctrl-click (toggle) or Shift-click (range); shown as
    /// checkboxes, drives the filmstrip, and is what Render targets.
    pub selection: HashSet<PathBuf>,
    path_edit: String,
    /// Set when the path bar holds text that isn't a navigable path.
    path_error: Option<String>,
    /// Photo to focus once a pending navigation lands (path bar given a file).
    pending_select: Option<PathBuf>,
    storage_locations: Vec<Location>,
    network_locations: Vec<Location>,
    scan_error: Option<String>,
}

impl Browser {
    /// Creates a browser rooted at `initial_dir` or a reasonable fallback directory.
    pub fn new(initial_dir: Option<PathBuf>) -> Self {
        let dir = initial_dir.filter(|p| p.is_dir()).unwrap_or_else(|| {
            let pictures = dirs::picture_dir()
                .or_else(|| dirs::home_dir().map(|h| h.join("Pictures")))
                .filter(|p| p.is_dir());
            pictures.unwrap_or_else(|| dirs::home_dir().unwrap_or_else(|| PathBuf::from("/")))
        });
        let (tx, rx) = mpsc::sync_channel(64);
        let mut b = Self {
            path_edit: dir.display().to_string(),
            current_dir: dir,
            subdirs: Vec::new(),
            images: Vec::new(),
            pending_nav: None,
            thumbnails: HashMap::new(),
            tx,
            rx,
            selected: None,
            select_anchor: None,
            selection: HashSet::new(),
            path_error: None,
            pending_select: None,
            storage_locations: Vec::new(),
            network_locations: Vec::new(),
            scan_error: None,
        };
        b.scan_locations();
        b.scan();
        b
    }

    fn scan(&mut self) {
        self.subdirs.clear();
        self.images.clear();
        self.thumbnails.clear();
        self.scan_error = None;

        let rd = match std::fs::read_dir(&self.current_dir) {
            Ok(rd) => rd,
            Err(e) => {
                let msg = if e.kind() == std::io::ErrorKind::PermissionDenied {
                    "Cannot read this directory: permission denied".to_string()
                } else {
                    format!("Cannot read this directory: {e}")
                };
                self.scan_error = Some(msg);
                return;
            }
        };

        for entry in rd.flatten() {
            let path = entry.path();
            let name = entry.file_name().to_string_lossy().into_owned();
            if name.starts_with('.') {
                continue;
            }
            if path.is_dir() {
                self.subdirs.push((path, name));
            } else if is_image(&path) {
                self.images.push((path, name));
            }
        }

        self.subdirs.sort_by(|a, b| a.1.cmp(&b.1));
        self.images.sort_by(|a, b| a.1.cmp(&b.1));
    }

    fn scan_locations(&mut self) {
        let home = dirs::home_dir();
        let (storage, mut network) = locations::mounted_locations(home.as_deref());
        network.extend(locations::gvfs_locations());
        self.storage_locations = storage;
        self.network_locations = network;
    }

    fn navigate(&mut self, dir: PathBuf) {
        self.pending_nav = Some(dir);
    }

    /// Toggles whether `path` is in the working selection (checkbox, filmstrip,
    /// Render target).
    pub fn toggle_selection(&mut self, path: PathBuf) {
        if !self.selection.remove(&path) {
            self.selection.insert(path);
        }
    }

    /// Paths currently in the working selection.
    pub fn selected_paths(&self) -> Vec<PathBuf> {
        self.selection.iter().cloned().collect()
    }

    /// Number of paths currently in the working selection.
    pub fn selection_count(&self) -> usize {
        self.selection.len()
    }

    /// Whether `path` is currently in the working selection.
    pub fn is_selected(&self, path: &std::path::Path) -> bool {
        self.selection.contains(path)
    }

    fn queue_pending_thumbs(&mut self, ctx: &egui::Context) {
        let in_flight = self
            .thumbnails
            .values()
            .filter(|state| matches!(state, ThumbState::Loading))
            .count();
        if in_flight >= MAX_THUMB_JOBS {
            return;
        }
        let slots = MAX_THUMB_JOBS - in_flight;

        let to_queue: Vec<PathBuf> = self
            .images
            .iter()
            .filter(|(p, _)| !self.thumbnails.contains_key(p))
            .take(slots)
            .map(|(p, _)| p.clone())
            .collect();

        for path in to_queue {
            self.thumbnails.insert(path.clone(), ThumbState::Loading);
            let tx = self.tx.clone();
            let ctx2 = ctx.clone();
            let cache_dir = self.current_dir.join(".thumbnails");
            std::thread::spawn(move || {
                let result = generate_thumb(&path, &cache_dir);
                let _ = tx.send(ThumbResult { path, rgba: result });
                ctx2.request_repaint();
            });
        }
    }

    fn drain_channel(&mut self, ctx: &egui::Context) {
        while let Ok(ThumbResult { path, rgba }) = self.rx.try_recv() {
            let state = match rgba {
                Some((data, w, h)) => {
                    let img = egui::ColorImage::from_rgba_unmultiplied([w, h], &data);
                    let tex = ctx.load_texture(
                        path.to_string_lossy().as_ref(),
                        img,
                        egui::TextureOptions::LINEAR,
                    );
                    ThumbState::Ready(tex)
                }
                None => ThumbState::Failed,
            };
            self.thumbnails.insert(path, state);
        }
    }

    /// Drain thumbnail results and queue pending thumbnails.
    /// Call every frame before rendering windows.
    pub fn poll(&mut self, ctx: &egui::Context) {
        if let Some(nav) = self.pending_nav.take() {
            self.current_dir = nav;
            self.path_edit = self.current_dir.display().to_string();
            self.path_error = None;
            self.selected = None;
            self.select_anchor = None;
            self.selection.clear();
            self.scan_locations();
            self.scan();
            if let Some(file) = self.pending_select.take() {
                if self.images.iter().any(|(p, _)| *p == file) {
                    self.select_anchor = Some(file.clone());
                    self.selected = Some(file);
                }
            }
        }

        self.drain_channel(ctx);
        self.queue_pending_thumbs(ctx);
    }

    /// Renders the left-hand navigation sidebar: locations, then the current
    /// directory's subfolders, as vertical lists.
    pub fn show_sidebar(&mut self, ui: &mut egui::Ui) {
        let mut nav_to: Option<PathBuf> = None;

        ui.label(egui::RichText::new("LOCATIONS").weak().small());
        let mut places: Vec<(PathBuf, &str, &str)> = Vec::new();
        if let Some(home) = dirs::home_dir() {
            places.push((home, "\u{1F3E0}", "Home"));
        }
        places.push((PathBuf::from("/"), "\u{1F4BB}", "Computer"));
        for (path, icon, label) in places {
            let is_current = path == self.current_dir;
            if ui
                .selectable_label(is_current, format!("{icon} {label}"))
                .on_hover_text(path.display().to_string())
                .clicked()
            {
                nav_to = Some(path);
            }
        }
        ui.add_space(8.0);

        for (heading, icon, list) in [
            ("STORAGE", "\u{1F4BE}", &self.storage_locations),
            ("NETWORK", "\u{1F310}", &self.network_locations),
        ] {
            if list.is_empty() {
                continue;
            }
            ui.label(egui::RichText::new(heading).weak().small());
            for loc in list {
                let is_current = loc.path == self.current_dir;
                if ui
                    .selectable_label(is_current, format!("{icon} {}", loc.label))
                    .on_hover_text(&loc.detail)
                    .clicked()
                {
                    nav_to = Some(loc.path.clone());
                }
            }
            ui.add_space(8.0);
        }

        ui.separator();
        ui.add_space(4.0);

        // Editable path bar + up button
        ui.horizontal(|ui| {
            let has_parent = self.current_dir.parent().is_some();
            if ui
                .add_enabled(has_parent, egui::Button::new("\u{2B06}"))
                .on_hover_text("Parent directory")
                .clicked()
            {
                if let Some(p) = self.current_dir.parent() {
                    nav_to = Some(p.to_path_buf());
                }
            }

            let resp = ui.add(
                egui::TextEdit::singleline(&mut self.path_edit)
                    .desired_width(ui.available_width())
                    .font(egui::TextStyle::Monospace),
            );
            if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
                let candidate =
                    locations::expand_typed_path(&self.path_edit, dirs::home_dir().as_deref());
                if candidate.is_dir() {
                    nav_to = Some(candidate);
                } else if candidate.is_file() {
                    // A photo path: open its folder with the photo focused.
                    if let Some(parent) = candidate.parent() {
                        nav_to = Some(parent.to_path_buf());
                        self.pending_select = Some(candidate);
                    }
                } else {
                    // Keep the typed text so it can be corrected.
                    self.path_error = Some(format!("No such folder: {}", candidate.display()));
                }
            }
            if resp.changed() {
                self.path_error = None;
            }
        });
        if let Some(err) = &self.path_error {
            ui.colored_label(ui.visuals().error_fg_color, err);
        }

        ui.add_space(4.0);
        ui.separator();

        if !self.subdirs.is_empty() {
            ui.add_space(4.0);
            ui.label(egui::RichText::new("FOLDERS").weak().small());
            egui::ScrollArea::vertical()
                .auto_shrink([false, true])
                .show(ui, |ui| {
                    for (path, name) in &self.subdirs {
                        if ui.button(format!("\u{1F4C1} {}", name)).clicked() {
                            nav_to = Some(path.clone());
                        }
                    }
                });
        }

        if let Some(nav) = nav_to {
            self.navigate(nav);
        }
    }

    /// Renders the thumbnail grid (Library mode central panel content).
    /// Plain click focuses a photo and resets the selection to just that one;
    /// Ctrl/Cmd-click toggles a photo in/out of the selection (and moves the
    /// range anchor there); Shift-click range-selects from the anchor. The
    /// selection drives the checkbox badge, the filmstrip, and Render's
    /// target set. Double-click opens the photo fullscreen — the returned
    /// path, if any, is that open request.
    pub fn show_contents(&mut self, ui: &mut egui::Ui, _ctx: &egui::Context) -> Option<PathBuf> {
        let mut plain_click: Option<PathBuf> = None;
        let mut ctrl_click: Option<PathBuf> = None;
        let mut shift_click: Option<PathBuf> = None;
        let mut open_request: Option<PathBuf> = None;

        if let Some(err) = &self.scan_error {
            ui.centered_and_justified(|ui| {
                ui.label(err.as_str());
            });
        } else if self.images.is_empty() && self.subdirs.is_empty() {
            ui.centered_and_justified(|ui| {
                ui.label("No images in this directory");
            });
        } else {
            let avail_w = ui.available_width();
            let cols = ((avail_w / (CELL + 8.0)) as usize).max(1);

            egui::ScrollArea::vertical()
                .auto_shrink([false, false])
                .show(ui, |ui| {
                    egui::Grid::new("image_grid")
                        .num_columns(cols)
                        .spacing([8.0, 8.0])
                        .show(ui, |ui| {
                            for (i, (path, name)) in self.images.iter().enumerate() {
                                let is_focused = self.selected.as_ref() == Some(path);
                                let is_checked = self.selection.contains(path);
                                let thumb = match self.thumbnails.get(path) {
                                    Some(ThumbState::Ready(tex)) => {
                                        Some((tex.id(), tex.size_vec2()))
                                    }
                                    _ => None,
                                };

                                let resp = draw_thumb_cell(
                                    ui,
                                    name,
                                    thumb,
                                    is_focused,
                                    is_checked,
                                    CELL,
                                    true,
                                );
                                if resp.double_clicked() {
                                    open_request = Some(path.clone());
                                } else if resp.clicked() {
                                    let shift_held = ui.input(|i| i.modifiers.shift);
                                    let ctrl_held =
                                        ui.input(|i| i.modifiers.ctrl || i.modifiers.mac_cmd);
                                    if ctrl_held {
                                        ctrl_click = Some(path.clone());
                                    } else if shift_held {
                                        shift_click = Some(path.clone());
                                    } else {
                                        plain_click = Some(path.clone());
                                    }
                                }

                                if (i + 1) % cols == 0 {
                                    ui.end_row();
                                }
                            }
                        });
                });
        }

        if let Some(path) = plain_click {
            self.selected = Some(path.clone());
            self.select_anchor = Some(path.clone());
            self.selection.clear();
            self.selection.insert(path);
        }
        if let Some(path) = ctrl_click {
            self.selected = Some(path.clone());
            self.select_anchor = Some(path.clone());
            self.toggle_selection(path);
        }
        if let Some(path) = shift_click {
            self.extend_selection_to(path);
        }

        open_request
    }

    /// Extends the range selection from `select_anchor` (or `selected` if no
    /// anchor yet) up to `path`, inclusive, in folder order.
    fn extend_selection_to(&mut self, path: PathBuf) {
        let anchor = self
            .select_anchor
            .clone()
            .or_else(|| self.selected.clone());
        let Some(anchor) = anchor else {
            self.selected = Some(path.clone());
            self.select_anchor = Some(path.clone());
            self.selection.clear();
            self.selection.insert(path);
            return;
        };
        let anchor_idx = self.images.iter().position(|(p, _)| *p == anchor);
        let click_idx = self.images.iter().position(|(p, _)| *p == path);
        if let (Some(a), Some(c)) = (anchor_idx, click_idx) {
            let (lo, hi) = if a <= c { (a, c) } else { (c, a) };
            self.selection = self.images[lo..=hi]
                .iter()
                .map(|(p, _)| p.clone())
                .collect();
        }
        self.selected = Some(path);
    }

    /// Renders a horizontal filmstrip of the current selection at a smaller
    /// size, reusing the same thumbnail cache as the grid. Returns the
    /// clicked path, if any, so the caller can switch the active photo.
    pub fn show_filmstrip(&mut self, ui: &mut egui::Ui, active: Option<&std::path::Path>) -> Option<PathBuf> {
        let mut clicked_path = None;
        let selection: Vec<(PathBuf, String)> = self
            .images
            .iter()
            .filter(|(p, _)| self.selection.contains(p))
            .cloned()
            .collect();
        egui::ScrollArea::horizontal()
            .auto_shrink([false, false])
            .show(ui, |ui| {
                ui.horizontal(|ui| {
                    for (path, name) in &selection {
                        let is_active = active == Some(path.as_path());
                        let is_checked = self.selection.contains(path);
                        let thumb = match self.thumbnails.get(path) {
                            Some(ThumbState::Ready(tex)) => Some((tex.id(), tex.size_vec2())),
                            _ => None,
                        };
                        if draw_thumb_cell(
                            ui,
                            name,
                            thumb,
                            is_active,
                            is_checked,
                            FILMSTRIP_CELL,
                            false,
                        )
                        .clicked()
                        {
                            clicked_path = Some(path.clone());
                        }
                    }
                });
            });
        clicked_path
    }
}

fn draw_thumb_cell(
    ui: &mut egui::Ui,
    name: &str,
    thumb: Option<(egui::TextureId, egui::Vec2)>,
    selected: bool,
    marked: bool,
    cell: f32,
    show_label: bool,
) -> egui::Response {
    let cell_height = if show_label { cell + 22.0 } else { cell };
    let (resp, painter) = ui.allocate_painter(egui::vec2(cell, cell_height), egui::Sense::click());
    let rect = resp.rect;

    // Background
    if selected {
        painter.rect_filled(rect, 4.0, ui.visuals().selection.bg_fill);
    } else if resp.hovered() {
        painter.rect_filled(rect, 4.0, ui.visuals().widgets.hovered.bg_fill);
    }

    // Image area
    let img_rect = egui::Rect::from_min_size(rect.min, egui::vec2(cell, cell));
    match thumb {
        Some((tex_id, tex_size)) => {
            let scale = (cell / tex_size.x).min(cell / tex_size.y);
            let display = tex_size * scale;
            let offset = (egui::vec2(cell, cell) - display) * 0.5;
            let draw_rect = egui::Rect::from_min_size(img_rect.min + offset, display);
            painter.image(
                tex_id,
                draw_rect,
                egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
                egui::Color32::WHITE,
            );
        }
        None => {
            painter.rect_filled(img_rect, 4.0, egui::Color32::from_gray(40));
            painter.text(
                img_rect.center(),
                egui::Align2::CENTER_CENTER,
                "\u{2026}",
                egui::FontId::proportional(22.0),
                egui::Color32::GRAY,
            );
        }
    }

    // Marked-for-export badge
    if marked {
        let badge_center = img_rect.right_top() + egui::vec2(-10.0, 10.0);
        painter.circle_filled(badge_center, 8.0, ui.visuals().selection.bg_fill);
        painter.text(
            badge_center,
            egui::Align2::CENTER_CENTER,
            "\u{2713}",
            egui::FontId::proportional(10.0),
            egui::Color32::WHITE,
        );
    }

    // Filename label
    if show_label {
        let label_pos = egui::pos2(rect.center().x, img_rect.max.y + 11.0);
        let name_short = if name.len() > 24 { &name[..24] } else { name };
        painter.text(
            label_pos,
            egui::Align2::CENTER_CENTER,
            name_short,
            egui::FontId::proportional(11.0),
            ui.visuals().text_color(),
        );
    }

    resp
}

fn generate_thumb(path: &PathBuf, cache_dir: &PathBuf) -> Option<(Vec<u8>, usize, usize)> {
    let thumb_path = crate::thumbnail::cache_path(path, cache_dir);

    let img = if thumb_path.exists() {
        image::open(&thumb_path).ok()?
    } else {
        let full = crate::thumbnail::open_image_for_preview(path).ok()?;
        let t = full.thumbnail(crate::thumbnail::THUMB_SIZE, crate::thumbnail::THUMB_SIZE);
        let _ = std::fs::create_dir_all(cache_dir);
        let _ = t.save(&thumb_path);
        t
    };

    let rgba = img.to_rgba8();
    let w = rgba.width() as usize;
    let h = rgba.height() as usize;
    Some((rgba.into_raw(), w, h))
}

fn is_image(path: &std::path::Path) -> bool {
    crate::thumbnail::is_supported_image(path)
}