flowcull 0.1.0

Fast photo culling with raw/JPEG pair support
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

mod catalog;
mod decode;
mod ops;
mod theme;

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver, Sender};

use eframe::egui::{self, Color32, ColorImage, Key, TextureHandle, TextureOptions};
use rayon::prelude::*;

use catalog::{Label, Photo};
use ops::{ExportKind, OnConflict, RemoveMode};
use theme::{
    apply_style, card, count_dot, key_cap, label_chip, label_color, label_glyph, paint_label_chip,
    BG, PANEL,
};

/// Previews kept decoded around the current photo.
const PREFETCH: usize = 2;
const PREVIEW_CACHE: usize = 12;
const THUMB_HEIGHT: f32 = 110.0;
const SIDE_WIDTH: f32 = 250.0;
/// Vertical drag distance that commits a label.
const SWIPE_PX: f32 = 80.0;
/// Horizontal drag distance that commits navigation; a faster fling needs less.
const NAV_PX: f32 = 60.0;
/// Release speed (px/s) that commits navigation regardless of distance.
const FLING_PX_S: f32 = 500.0;

enum Msg {
    /// Decoded thumbnail (`None` when the file could not be decoded), tagged with the folder
    /// generation it belongs to so results from a previously opened folder are dropped.
    Thumb(u64, String, Option<ColorImage>),
    Preview(u64, String, ColorImage),
    Removed(anyhow::Result<usize>),
    Status(String),
}

struct App {
    dir: Option<PathBuf>,
    photos: Vec<Photo>,
    cur: usize,
    thumbs: HashMap<String, TextureHandle>,
    previews: HashMap<String, TextureHandle>,
    preview_lru: VecDeque<String>,
    pending: HashSet<String>,
    thumbs_done: usize,
    /// Bumped on every folder open; background results carry the generation they were started in.
    generation: u64,
    /// Longest edge of decoded previews, sized to the screen on the first frame.
    preview_size: u32,
    tx: Sender<Msg>,
    rx: Receiver<Msg>,
    preview_pool: rayon::ThreadPool,
    export_kind: ExportKind,
    on_conflict: OnConflict,
    remove_mode: RemoveMode,
    confirm_remove: bool,
    /// Accumulated drag on the main photo; committed as a swipe on release.
    swipe: egui::Vec2,
    /// Photo the filmstrip was last centered on; it re-centres only when `cur` changes.
    centered: Option<usize>,
    /// Axis locked in for the current drag, decided after the first few pixels.
    swipe_vertical: Option<bool>,
    fullscreen: bool,
    status: String,
}

impl App {
    fn new() -> Self {
        let (tx, rx) = mpsc::channel();
        Self {
            dir: None,
            photos: Vec::new(),
            cur: 0,
            thumbs: HashMap::new(),
            previews: HashMap::new(),
            preview_lru: VecDeque::new(),
            pending: HashSet::new(),
            thumbs_done: 0,
            generation: 0,
            preview_size: 0,
            tx,
            rx,
            preview_pool: rayon::ThreadPoolBuilder::new()
                .num_threads(3)
                .build()
                .unwrap(),
            export_kind: ExportKind::Both,
            on_conflict: OnConflict::Rename,
            remove_mode: RemoveMode::RecycleBin,
            confirm_remove: false,
            swipe: egui::Vec2::ZERO,
            centered: None,
            swipe_vertical: None,
            fullscreen: false,
            status: "Open a folder to start culling".into(),
        }
    }

    fn open_folder(&mut self, ctx: &egui::Context) {
        if let Some(dir) = rfd::FileDialog::new().pick_folder() {
            self.load_dir(dir, ctx);
        }
    }

    fn load_dir(&mut self, dir: PathBuf, ctx: &egui::Context) {
        match catalog::scan(&dir) {
            Ok(photos) => {
                self.photos = photos;
                self.dir = Some(dir);
                self.cur = 0;
                self.thumbs.clear();
                self.previews.clear();
                self.preview_lru.clear();
                self.pending.clear();
                self.thumbs_done = 0;
                self.generation += 1;
                self.status = format!("{} photos", self.photos.len());
                self.build_thumbs(ctx.clone());
            }
            Err(e) => self.status = format!("Error: {e:#}"),
        }
    }

    fn build_thumbs(&self, ctx: egui::Context) {
        let jobs: Vec<(String, PathBuf)> = self
            .photos
            .iter()
            .map(|p| (p.stem.clone(), p.display_path().to_path_buf()))
            .collect();
        let (tx, generation) = (self.tx.clone(), self.generation);
        std::thread::spawn(move || {
            jobs.into_par_iter().for_each(|(stem, path)| {
                let img = decode::load(&path, decode::THUMB_SIZE).ok();
                let _ = tx.send(Msg::Thumb(
                    generation,
                    stem,
                    img.as_ref().map(to_color_image),
                ));
                ctx.request_repaint();
            });
        });
    }

    fn request_previews(&mut self, ctx: &egui::Context) {
        if self.photos.is_empty() {
            return;
        }
        let lo = self.cur.saturating_sub(PREFETCH);
        let hi = (self.cur + PREFETCH).min(self.photos.len() - 1);
        for i in (lo..=hi).rev() {
            let photo = &self.photos[i];
            if self.previews.contains_key(&photo.stem) || self.pending.contains(&photo.stem) {
                continue;
            }
            self.pending.insert(photo.stem.clone());
            let (stem, path, tx, ctx) = (
                photo.stem.clone(),
                photo.display_path().to_path_buf(),
                self.tx.clone(),
                ctx.clone(),
            );
            let (generation, size) = (self.generation, self.preview_size);
            self.preview_pool.spawn(move || {
                match decode::load(&path, size) {
                    Ok(img) => {
                        let _ = tx.send(Msg::Preview(generation, stem, to_color_image(&img)));
                    }
                    Err(e) => {
                        let _ = tx.send(Msg::Status(format!("{}: {e:#}", path.display())));
                    }
                }
                ctx.request_repaint();
            });
        }
    }

    fn drain_messages(&mut self, ctx: &egui::Context) {
        while let Ok(msg) = self.rx.try_recv() {
            match msg {
                Msg::Thumb(generation, _, _) | Msg::Preview(generation, _, _)
                    if generation != self.generation => {}
                Msg::Thumb(_, stem, img) => {
                    if let Some(img) = img {
                        self.thumbs
                            .insert(stem, ctx.load_texture("thumb", img, TextureOptions::LINEAR));
                    }
                    self.thumbs_done += 1;
                }
                Msg::Preview(_, stem, img) => {
                    self.pending.remove(&stem);
                    self.previews.insert(
                        stem.clone(),
                        ctx.load_texture("preview", img, TextureOptions::LINEAR),
                    );
                    self.preview_lru.push_back(stem);
                    while self.preview_lru.len() > PREVIEW_CACHE {
                        if let Some(old) = self.preview_lru.pop_front() {
                            self.previews.remove(&old);
                        }
                    }
                }
                Msg::Removed(result) => {
                    self.status = match result {
                        Ok(n) => format!("Removed {n} files"),
                        Err(e) => format!("Remove failed: {e:#}"),
                    };
                    self.prune_missing_files();
                }
                Msg::Status(s) => self.status = s,
            }
        }
    }

    fn handle_keys(&mut self, ctx: &egui::Context) {
        let (label, step) = ctx.input(|i| {
            let label = if i.key_pressed(Key::P) {
                Some(Label::Pick)
            } else if i.key_pressed(Key::X) {
                Some(Label::Reject)
            } else if i.key_pressed(Key::U) {
                Some(Label::Unlabeled)
            } else {
                None
            };
            let step = if i.key_pressed(Key::ArrowRight) {
                1
            } else if i.key_pressed(Key::ArrowLeft) {
                -1
            } else if i.key_pressed(Key::Home) {
                -(self.cur as isize)
            } else if i.key_pressed(Key::End) {
                self.photos.len() as isize
            } else {
                0
            };
            (label, step)
        });
        if ctx.input(|i| i.modifiers.command && i.key_pressed(Key::O)) {
            self.open_folder(ctx);
        }
        let toggle_fs = ctx.input(|i| i.key_pressed(Key::F));
        let escape = ctx.input(|i| i.key_pressed(Key::Escape));
        if toggle_fs || (escape && self.fullscreen) {
            self.fullscreen = !self.fullscreen;
            ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(self.fullscreen));
        }
        if let Some(label) = label {
            self.set_label(label);
        }
        self.step(step);
    }

    fn set_label(&mut self, label: Label) {
        if let Some(photo) = self.photos.get_mut(self.cur) {
            photo.label = label;
            self.save_labels();
        }
    }

    fn step(&mut self, step: isize) {
        if step != 0 && !self.photos.is_empty() {
            self.cur = (self.cur as isize + step).clamp(0, self.photos.len() as isize - 1) as usize;
        }
    }

    fn save_labels(&mut self) {
        if let Some(dir) = &self.dir {
            if let Err(e) = catalog::save_labels(dir, &self.photos) {
                self.status = format!("Could not save labels: {e:#}");
            }
        }
    }

    fn export(&mut self) {
        let Some(dest) = rfd::FileDialog::new().pick_folder() else {
            return;
        };
        let (photos, kind, on_conflict, tx) = (
            self.photos.clone(),
            self.export_kind,
            self.on_conflict,
            self.tx.clone(),
        );
        self.status = "Exporting...".into();
        std::thread::spawn(move || {
            let msg = match ops::export_picks(&photos, kind, on_conflict, &dest) {
                Ok(r) => {
                    let mut msg = format!("Exported {} files to {}", r.copied, dest.display());
                    if r.skipped > 0 {
                        msg += &format!(", skipped {} existing", r.skipped);
                    }
                    if let Some(err) = r.first_error {
                        msg += &format!(", {} failed ({err})", r.failed);
                    }
                    msg
                }
                Err(e) => format!("Export failed: {e:#}"),
            };
            let _ = tx.send(Msg::Status(msg));
        });
    }

    fn remove_rejects(&mut self) {
        let (photos, mode, tx) = (self.photos.clone(), self.remove_mode, self.tx.clone());
        self.status = "Removing...".into();
        std::thread::spawn(move || {
            let _ = tx.send(Msg::Removed(ops::remove_rejects(&photos, mode)));
        });
    }

    /// Drop photos whose files are gone from disk; the list follows disk truth after a removal,
    /// whether it fully succeeded, partially failed, or labels changed while it ran.
    fn prune_missing_files(&mut self) {
        for p in &mut self.photos {
            p.jpeg = p.jpeg.take().filter(|f| f.exists());
            p.raw = p.raw.take().filter(|f| f.exists());
        }
        self.photos.retain(|p| p.jpeg.is_some() || p.raw.is_some());
        self.cur = self.cur.min(self.photos.len().saturating_sub(1));
        self.save_labels();
    }

    fn count(&self, label: Label) -> usize {
        self.photos.iter().filter(|p| p.label == label).count()
    }

    fn side_panel(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
        ui.spacing_mut().item_spacing.y = 10.0;

        let folder = self.dir.as_ref().map(|d| {
            d.file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned()
        });
        let (done, total) = (self.thumbs_done, self.photos.len());
        let w = ui.available_width() - 24.0;
        let mut open = false;
        card(ui, "Source", |ui| {
            match folder {
                Some(name) => {
                    ui.add(egui::Label::new(egui::RichText::new(name).strong()).truncate());
                    if done < total {
                        ui.horizontal(|ui| {
                            ui.spinner();
                            ui.weak(format!("Loading thumbnails {done}/{total}"));
                        });
                    } else {
                        ui.weak(format!("{total} photos"));
                    }
                }
                None => {
                    ui.weak("No folder open");
                }
            }
            open = ui
                .add_sized([w, 30.0], egui::Button::new("Open folder…"))
                .clicked();
        });
        if open {
            self.open_folder(ctx);
        }

        if let Some(photo) = self.photos.get(self.cur) {
            let (index, label) = (self.cur + 1, photo.label);
            let name = photo
                .display_path()
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned();
            let kind = match (&photo.jpeg, &photo.raw) {
                (Some(_), Some(_)) => "RAW + JPEG pair".to_string(),
                (None, Some(raw)) => format!("RAW · {}", ext_upper(raw)),
                _ => "JPEG".to_string(),
            };
            card(ui, "Photo", |ui| {
                ui.horizontal(|ui| {
                    ui.scope(|ui| {
                        // Leave room for the index so a long name truncates instead of overlapping.
                        ui.set_max_width(w - 56.0);
                        ui.add(egui::Label::new(egui::RichText::new(name).strong()).truncate());
                    });
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        ui.weak(format!("{index}/{total}"));
                    });
                });
                ui.weak(kind);
                ui.add_space(2.0);
                label_chip(ui, label);
            });
        }

        let rows = [
            (
                label_color(Label::Pick),
                self.count(Label::Pick),
                "picked",
                "P",
            ),
            (
                label_color(Label::Reject),
                self.count(Label::Reject),
                "rejected",
                "X",
            ),
            (
                Color32::GRAY,
                self.count(Label::Unlabeled),
                "unlabeled",
                "U",
            ),
        ];
        card(ui, "Cull", |ui| {
            ui.spacing_mut().item_spacing.y = 6.0;
            for (color, n, what, key) in rows {
                ui.horizontal(|ui| {
                    count_dot(ui, color, n, what);
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        key_cap(ui, key);
                    });
                });
            }
            ui.horizontal(|ui| {
                ui.weak("navigate");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    key_cap(ui, "→");
                    key_cap(ui, "←");
                });
            });
        });

        let mut export = false;
        card(ui, "Export picks", |ui| {
            egui::ComboBox::from_id_salt("export_kind")
                .width(w)
                .selected_text(match self.export_kind {
                    ExportKind::Both => "Raw + JPEG",
                    ExportKind::Raw => "Raw only",
                    ExportKind::Jpeg => "JPEG only",
                })
                .show_ui(ui, |ui| {
                    ui.selectable_value(&mut self.export_kind, ExportKind::Both, "Raw + JPEG");
                    ui.selectable_value(&mut self.export_kind, ExportKind::Raw, "Raw only");
                    ui.selectable_value(&mut self.export_kind, ExportKind::Jpeg, "JPEG only");
                });
            egui::ComboBox::from_id_salt("on_conflict")
                .width(w)
                .selected_text(match self.on_conflict {
                    OnConflict::Rename => "Existing: rename new",
                    OnConflict::Skip => "Existing: skip",
                })
                .show_ui(ui, |ui| {
                    ui.selectable_value(
                        &mut self.on_conflict,
                        OnConflict::Rename,
                        "Existing: rename new",
                    );
                    ui.selectable_value(&mut self.on_conflict, OnConflict::Skip, "Existing: skip");
                });
            export = ui
                .add_sized([w, 30.0], egui::Button::new("Export to folder…"))
                .clicked();
        });
        if export {
            self.export();
        }

        let mut remove = false;
        card(ui, "Clean up rejects", |ui| {
            egui::ComboBox::from_id_salt("remove_mode")
                .width(w)
                .selected_text(match self.remove_mode {
                    RemoveMode::RecycleBin => "Recycle bin",
                    RemoveMode::Delete => "Delete permanently",
                })
                .show_ui(ui, |ui| {
                    ui.selectable_value(
                        &mut self.remove_mode,
                        RemoveMode::RecycleBin,
                        "Recycle bin",
                    );
                    ui.selectable_value(
                        &mut self.remove_mode,
                        RemoveMode::Delete,
                        "Delete permanently",
                    );
                });
            remove = ui
                .add_sized([w, 30.0], egui::Button::new("Remove rejects…"))
                .clicked();
        });
        if remove && self.count(Label::Reject) > 0 {
            self.confirm_remove = true;
        }

        ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| {
            ui.spacing_mut().item_spacing.y = 6.0;
            ui.horizontal(|ui| {
                key_cap(ui, "F");
                ui.weak("fullscreen");
                ui.add_space(8.0);
                key_cap(ui, "Ctrl+O");
                ui.weak("open");
            });
            ui.add(egui::Label::new(egui::RichText::new(&self.status).weak()).wrap());
        });
    }

    fn confirm_dialog(&mut self, ctx: &egui::Context) {
        if !self.confirm_remove {
            return;
        }
        let n = self.count(Label::Reject);
        let verb = match self.remove_mode {
            RemoveMode::RecycleBin => "move to the recycle bin",
            RemoveMode::Delete => "permanently delete",
        };
        egui::Window::new("Remove rejects")
            .collapsible(false)
            .resizable(false)
            .show(ctx, |ui| {
                ui.label(format!("{verb} all files of {n} rejected photos?"));
                ui.horizontal(|ui| {
                    if ui.button("Yes").clicked() {
                        self.confirm_remove = false;
                        self.remove_rejects();
                    }
                    if ui.button("Cancel").clicked() {
                        self.confirm_remove = false;
                    }
                });
            });
    }

    /// Texture to show for photo `i` and whether it is the thumbnail stand-in.
    fn texture_for(&self, i: usize) -> Option<(&TextureHandle, bool)> {
        let photo = self.photos.get(i)?;
        match self.previews.get(&photo.stem) {
            Some(p) => Some((p, false)),
            None => self.thumbs.get(&photo.stem).map(|t| (t, true)),
        }
    }

    /// Draw photo `i` fitted inside `area`, shifted by `offset`. Returns the drawn rect.
    fn draw_photo(
        &self,
        ui: &mut egui::Ui,
        i: usize,
        area: egui::Rect,
        offset: egui::Vec2,
    ) -> Option<egui::Rect> {
        let (tex, loading) = self.texture_for(i)?;
        let [w, h] = tex.size();
        let label = self.photos[i].label;
        let scale = (area.width() / w as f32).min(area.height() / h as f32);
        let scale = if loading { scale } else { scale.min(1.0) };
        let size = egui::vec2(w as f32 * scale, h as f32 * scale);
        let rect = egui::Rect::from_center_size(area.center() + offset, size);

        egui::Image::new(tex).corner_radius(3).paint_at(ui, rect);
        if loading {
            ui.painter()
                .rect_filled(rect, 3, Color32::from_black_alpha(90));
            let chip = egui::Rect::from_center_size(
                rect.center_bottom() - egui::vec2(0.0, 32.0),
                egui::vec2(120.0, 32.0),
            );
            ui.painter()
                .rect_filled(chip, 16, Color32::from_black_alpha(200));
            ui.put(
                egui::Rect::from_center_size(
                    chip.left_center() + egui::vec2(20.0, 0.0),
                    egui::vec2(16.0, 16.0),
                ),
                egui::Spinner::new().size(14.0),
            );
            ui.painter().text(
                chip.center() + egui::vec2(10.0, 0.0),
                egui::Align2::CENTER_CENTER,
                "Loading…",
                egui::FontId::proportional(13.0),
                Color32::WHITE,
            );
        }
        if label != Label::Unlabeled {
            // Drawn inside the image so it stays visible in fullscreen, where there is no margin.
            ui.painter().rect_stroke(
                rect,
                3,
                egui::Stroke::new(3.0, label_color(label)),
                egui::StrokeKind::Inside,
            );
            if self.fullscreen && i == self.cur {
                let chip = egui::Rect::from_min_size(
                    rect.left_top() + egui::vec2(16.0, 16.0),
                    egui::vec2(110.0, 28.0),
                );
                paint_label_chip(ui.painter(), chip, label);
            }
        }
        Some(rect)
    }

    fn main_view(&mut self, ui: &mut egui::Ui) {
        if self.photos.is_empty() {
            ui.centered_and_justified(|ui| ui.label("No photos"));
            return;
        }
        if self.texture_for(self.cur).is_none() {
            ui.centered_and_justified(|ui| ui.spinner());
            return;
        }
        let area = ui.max_rect();
        let resp = ui.interact(area, ui.scope_id().with("swipe"), egui::Sense::drag());
        if resp.dragged() {
            self.swipe += resp.drag_delta();
            if self.swipe_vertical.is_none() && self.swipe.length() > 12.0 {
                self.swipe_vertical = Some(self.swipe.y.abs() > self.swipe.x.abs());
            }
        } else if self.swipe != egui::Vec2::ZERO {
            // Ease the remaining offset back to rest.
            let dt = ui.input(|i| i.stable_dt).min(0.1);
            self.swipe *= (-dt * 9.0).exp();
            if self.swipe.length() < 0.5 {
                self.swipe = egui::Vec2::ZERO;
            }
            ui.ctx().request_repaint();
        }
        let swipe = self.swipe;
        let vertical = self.swipe_vertical.unwrap_or(false);
        // Neighbors sit one panel width apart so they are off-screen at rest.
        let stride = area.width() + 24.0;
        // Swiping up picks, down rejects; swiping the same way again undoes the label.
        let verdict = {
            let swiped = if swipe.y < 0.0 {
                Label::Pick
            } else {
                Label::Reject
            };
            if self.photos[self.cur].label == swiped {
                Label::Unlabeled
            } else {
                swiped
            }
        };

        if vertical {
            let offset = egui::vec2(0.0, swipe.y.clamp(-SWIPE_PX, SWIPE_PX));
            let rect = self.draw_photo(ui, self.cur, area, offset);
            if let (Some(rect), true) = (rect, swipe.y.abs() > 10.0) {
                let strength = (swipe.y.abs() / SWIPE_PX).min(1.0);
                let color = match verdict {
                    Label::Unlabeled => Color32::GRAY,
                    label => label_color(label),
                };
                ui.painter()
                    .rect_filled(rect, 3, color.gamma_multiply(0.35 * strength));
                if swipe.y.abs() >= SWIPE_PX {
                    let text = match verdict {
                        Label::Pick => "PICK",
                        Label::Reject => "REJECT",
                        Label::Unlabeled => "UNLABEL",
                    };
                    let pill = egui::Rect::from_center_size(rect.center(), egui::vec2(180.0, 56.0));
                    ui.painter().rect_filled(pill, 28, color);
                    ui.painter().text(
                        pill.center(),
                        egui::Align2::CENTER_CENTER,
                        text,
                        egui::FontId::proportional(24.0),
                        Color32::WHITE,
                    );
                }
            }
        } else {
            self.draw_photo(ui, self.cur, area, egui::vec2(swipe.x, 0.0));
            if swipe.x > 0.0 && self.cur > 0 {
                self.draw_photo(ui, self.cur - 1, area, egui::vec2(swipe.x - stride, 0.0));
            } else if swipe.x < 0.0 && self.cur + 1 < self.photos.len() {
                self.draw_photo(ui, self.cur + 1, area, egui::vec2(swipe.x + stride, 0.0));
            }
        }

        if resp.drag_stopped() {
            if vertical {
                if swipe.y.abs() >= SWIPE_PX {
                    self.set_label(verdict);
                }
                self.swipe = egui::Vec2::ZERO;
            } else {
                let vx = ui.input(|i| i.pointer.velocity().x);
                let flung = vx.abs() > FLING_PX_S && vx.signum() == swipe.x.signum();
                let before = self.cur;
                if swipe.x.abs() >= NAV_PX || flung {
                    self.step(if swipe.x < 0.0 { 1 } else { -1 });
                }
                if self.cur != before {
                    // The new photo keeps sliding in from where the finger left it.
                    self.swipe.x -= stride.copysign(swipe.x);
                }
            }
            self.swipe.y = 0.0;
            self.swipe_vertical = None;
        }
    }

    fn filmstrip(&mut self, ui: &mut egui::Ui) {
        let mut clicked = None;
        let mut recentered = None;
        egui::ScrollArea::horizontal().show(ui, |ui| {
            ui.horizontal(|ui| {
                for (i, photo) in self.photos.iter().enumerate() {
                    let size = match self.thumbs.get(&photo.stem) {
                        Some(tex) => {
                            let [w, h] = tex.size();
                            egui::vec2(THUMB_HEIGHT * w as f32 / h as f32, THUMB_HEIGHT)
                        }
                        None => egui::vec2(THUMB_HEIGHT * 1.5, THUMB_HEIGHT),
                    };
                    let (rect, resp) = ui.allocate_exact_size(size, egui::Sense::click());
                    let is_cur = i == self.cur;
                    if is_cur && self.centered != Some(i) {
                        ui.scroll_to_rect(rect, Some(egui::Align::Center));
                        recentered = Some(i);
                    }
                    if resp.clicked() {
                        clicked = Some(i);
                    }
                    if !ui.is_rect_visible(rect) {
                        continue;
                    }
                    let painter = ui.painter();
                    match self.thumbs.get(&photo.stem) {
                        Some(tex) => {
                            egui::Image::new(tex).corner_radius(4).paint_at(ui, rect);
                        }
                        None => {
                            painter.rect_filled(rect, 4, Color32::from_rgb(40, 40, 40));
                        }
                    }
                    if !is_cur && !resp.hovered() {
                        let dim = if photo.label == Label::Reject {
                            140
                        } else {
                            70
                        };
                        painter.rect_filled(rect, 4, Color32::from_black_alpha(dim));
                    }
                    if photo.label != Label::Unlabeled {
                        let color = label_color(photo.label);
                        painter.rect_stroke(
                            rect,
                            4,
                            egui::Stroke::new(2.0, color),
                            egui::StrokeKind::Inside,
                        );
                        let badge = egui::Rect::from_min_size(
                            rect.left_top() + egui::vec2(6.0, 6.0),
                            egui::vec2(20.0, 20.0),
                        );
                        painter.rect_filled(badge, 4, color);
                        painter.text(
                            badge.center(),
                            egui::Align2::CENTER_CENTER,
                            label_glyph(photo.label),
                            egui::FontId::proportional(13.0),
                            Color32::WHITE,
                        );
                    }
                    if is_cur {
                        painter.rect_stroke(
                            rect.expand(3.0),
                            6,
                            egui::Stroke::new(2.0, Color32::WHITE),
                            egui::StrokeKind::Inside,
                        );
                    }
                }
            });
        });
        if recentered.is_some() {
            self.centered = recentered;
        }
        if let Some(i) = clicked {
            self.cur = i;
        }
    }
}

impl eframe::App for App {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        let ctx = &ui.ctx().clone();
        if self.preview_size == 0 {
            // Decode previews to the monitor's pixel size: sharp on 4K, no wasted work on 1080p.
            let px = ctx.input(|i| {
                i.viewport()
                    .monitor_size
                    .map(|m| m.max_elem() * i.pixels_per_point)
            });
            self.preview_size = px.map_or(decode::PREVIEW_SIZE, |p| (p as u32).clamp(1920, 4096));
        }
        self.drain_messages(ctx);
        self.handle_keys(ctx);
        self.request_previews(ctx);

        if !self.fullscreen {
            egui::Panel::left("side")
                .frame(
                    egui::Frame::new()
                        .fill(PANEL)
                        .inner_margin(egui::Margin::same(14)),
                )
                .size_range(SIDE_WIDTH..=SIDE_WIDTH)
                .resizable(false)
                .show_separator_line(false)
                .show(ui, |ui| self.side_panel(ui, ctx));
            egui::Panel::bottom("filmstrip")
                .frame(
                    egui::Frame::new()
                        .fill(Color32::from_rgb(24, 24, 24))
                        .inner_margin(egui::Margin::symmetric(8, 8)),
                )
                .show_separator_line(false)
                .show(ui, |ui| self.filmstrip(ui));
        }
        let margin = if self.fullscreen { 0 } else { 8 };
        egui::CentralPanel::default()
            .frame(
                egui::Frame::new()
                    .fill(BG)
                    .inner_margin(egui::Margin::same(margin)),
            )
            .show(ui, |ui| self.main_view(ui));
        self.confirm_dialog(ctx);
    }
}

fn ext_upper(path: &std::path::Path) -> String {
    path.extension()
        .map(|e| e.to_string_lossy().to_ascii_uppercase())
        .unwrap_or_default()
}

fn to_color_image(img: &image::RgbImage) -> ColorImage {
    ColorImage::from_rgb([img.width() as usize, img.height() as usize], img.as_raw())
}

fn main() -> eframe::Result {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_title("FlowCull")
            .with_inner_size([1400.0, 900.0])
            .with_icon(window_icon()),
        ..Default::default()
    };
    let dir = std::env::args().nth(1).map(PathBuf::from);
    eframe::run_native(
        "FlowCull",
        options,
        Box::new(move |cc| {
            apply_style(&cc.egui_ctx);
            let mut app = App::new();
            if let Some(dir) = dir {
                app.load_dir(dir, &cc.egui_ctx);
            }
            Ok(Box::new(app))
        }),
    )
}

/// Window and taskbar icon, embedded so the binary stays self-contained.
fn window_icon() -> egui::IconData {
    let img = image::load_from_memory(include_bytes!("../assets/icon-256.png"))
        .expect("embedded icon is a valid PNG")
        .into_rgba8();
    egui::IconData {
        width: img.width(),
        height: img.height(),
        rgba: img.into_raw(),
    }
}