mihari 0.1.5

Keyboard-driven image viewer and sorter
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
use std::{
    io,
    ops::Range,
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

use eframe::egui::{
    self, Align2, Color32, Context, FontId, Painter, Rect, TextureHandle, ViewportCommand,
    WindowLevel, pos2, vec2,
};

use crate::{
    album::{ARCHIVE_EXTENSIONS, Album, EXTENSIONS, Page},
    config::{Config, Direction},
    input::Action,
    loader::Loader,
};

const BACKGROUND: Color32 = Color32::from_gray(18);
const TEXT: Color32 = Color32::from_gray(216);

struct Slideshow {
    deadline: Option<Instant>,
    on_top: bool,
}

struct NextArchivePrompt {
    path: PathBuf,
    shown_at: Option<u64>,
}

pub(crate) struct Viewer {
    album: Album,
    loader: Loader,
    config: Config,
    spread: bool,
    direction: Direction,
    fullscreen: bool,
    manual_top: bool,
    slideshow: Option<Slideshow>,
    g_pending: bool,
    help: bool,
    next_archive: Option<NextArchivePrompt>,
    sort_help: String,
    notice: Option<String>,
    status: String,
}

impl Viewer {
    pub(crate) fn new(ctx: Context, album: Album, config: Config) -> io::Result<Self> {
        let sort_help = if config.move_keys.is_empty() {
            "No sort keys configured  /  u  undo".to_owned()
        } else {
            let keys: Vec<_> = config.move_keys.keys().map(char::to_string).collect();
            format!("{}  move selected  /  u  undo", keys.join(", "))
        };
        let mut viewer = Self {
            album,
            loader: Loader::new(ctx.clone())?,
            spread: config.spread,
            direction: config.direction,
            config,
            fullscreen: false,
            manual_top: false,
            slideshow: None,
            g_pending: false,
            help: false,
            next_archive: None,
            sort_help,
            notice: None,
            status: String::new(),
        };
        viewer.refresh_status(&ctx);
        Ok(viewer)
    }

    fn visible(&self) -> Range<usize> {
        self.album.visible(self.spread, self.config.cover)
    }

    fn on_top(&self) -> bool {
        self.slideshow
            .as_ref()
            .map_or(self.manual_top, |slide| slide.on_top)
    }

    fn apply_top(&self, ctx: &Context) {
        ctx.send_viewport_cmd(ViewportCommand::WindowLevel(if self.on_top() {
            WindowLevel::AlwaysOnTop
        } else {
            WindowLevel::Normal
        }));
    }

    fn stop_slideshow(&mut self, ctx: &Context) {
        if self.slideshow.take().is_some() {
            self.apply_top(ctx);
        }
    }

    fn refresh_status(&mut self, ctx: &Context) {
        use std::fmt::Write as _;

        self.status.clear();
        let total = self.album.pages().len();
        let active = self.album.active();
        if let Some(page) = self.album.pages().get(active) {
            let name = page.path.file_name().unwrap_or(page.path.as_os_str());
            ctx.send_viewport_cmd(ViewportCommand::Title(format!(
                "Mihari — {}/{} — {}",
                active + 1,
                total,
                name.to_string_lossy()
            )));
            let _ = write!(&mut self.status, "{} / {}  ·  ", active + 1, total);
        } else {
            ctx.send_viewport_cmd(ViewportCommand::Title("Mihari".to_owned()));
        }
        self.status.push_str(match (self.spread, self.direction) {
            (false, _) => "Single",
            (true, Direction::Rtl) => "Spread RTL",
            (true, Direction::Ltr) => "Spread LTR",
        });
        if self.slideshow.is_some() {
            self.status.push_str("  ·  Slideshow");
        }
        if self.on_top() {
            self.status.push_str("  ·  On top");
        }
        self.status.push_str("  ·  ? help");
    }

    fn open(&mut self, ctx: &Context, frame: &eframe::Frame, folder: bool) -> io::Result<()> {
        self.stop_slideshow(ctx);
        let mut dialog = rfd::FileDialog::new().set_parent(frame);
        if let Some(dir) = self.album.current_directory() {
            dialog = dialog.set_directory(dir);
        }
        let path = if folder {
            dialog.set_title("Open image folder").pick_folder()
        } else {
            let extensions: Vec<_> = EXTENSIONS
                .iter()
                .chain(ARCHIVE_EXTENSIONS)
                .copied()
                .collect();
            dialog
                .set_title("Open image or comic archive")
                .add_filter("Images and ZIP/CBZ archives", &extensions)
                .pick_file()
        };
        if let Some(path) = path {
            self.open_path(&path)?;
        }
        Ok(())
    }

    fn open_path(&mut self, path: &Path) -> io::Result<()> {
        self.album = Album::open(path, self.config.recurse)?;
        self.loader.clear();
        Ok(())
    }

    fn show_next_archive_prompt(&mut self, ctx: &Context) {
        let Some(prompt) = &mut self.next_archive else {
            return;
        };
        let frame = ctx.cumulative_frame_nr();
        let ready = *prompt.shown_at.get_or_insert(frame) != frame;
        ctx.input_mut(|input| {
            // egui also uses these key presses to activate focused buttons.
            input.events.retain(|event| {
                !matches!(
                    event,
                    egui::Event::Key {
                        key: egui::Key::Enter | egui::Key::Space,
                        pressed: true,
                        repeat,
                        ..
                    } if !ready || *repeat
                )
            });
        });
        let name = prompt.path.file_name().unwrap_or(prompt.path.as_os_str());
        let modal = egui::Modal::new(egui::Id::new("next_archive")).show(ctx, |ui| {
            ui.set_max_width(320.);
            ui.heading("End of archive");
            ui.label("Open the next file?");
            ui.label(name.to_string_lossy());
            ui.horizontal(|ui| {
                let open = ui.button("Open next file");
                let cancel = ui.button("Cancel");
                if cancel.clicked() {
                    ui.close();
                }
                ready
                    && (open.clicked()
                        || (!open.has_focus()
                            && !cancel.has_focus()
                            && ui.input_mut(|input| {
                                input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)
                            })))
            })
            .inner
        });
        if modal.should_close() {
            self.next_archive = None;
        } else if modal.inner
            && let Some(prompt) = self.next_archive.take()
        {
            self.stop_slideshow(ctx);
            if let Err(error) = self.open_path(&prompt.path) {
                self.notice = Some(format!("Open failed: {error}"));
            }
            self.refresh_status(ctx);
        } else {
            return;
        }
        ctx.request_repaint();
    }

    fn key(&mut self, action: Action, repeat: bool, ctx: &Context, frame: &eframe::Frame) -> bool {
        let g_pending = std::mem::take(&mut self.g_pending);
        match action {
            Action::Quit => {
                ctx.send_viewport_cmd(ViewportCommand::Close);
                return false;
            }
            Action::Help | Action::Escape if self.help => {
                self.help = false;
                return false;
            }
            _ if self.help => return false,
            Action::FirstPrefix if !g_pending => {
                self.g_pending = true;
                return false;
            }
            Action::Move(key) if !self.config.move_keys.contains_key(&key) => return false,
            Action::Unbound => return false,
            _ => {}
        }
        self.notice = None;
        if let Some(slide) = &mut self.slideshow {
            slide.deadline = None;
        }
        let visible = self.visible();
        match action {
            Action::Previous if visible.start > 0 => {
                self.album.select(visible.start - 1);
                self.album.select(self.visible().start);
            }
            Action::Next if visible.end < self.album.pages().len() => {
                self.album.select(visible.end)
            }
            Action::Next if !repeat => {
                match self.album.next_archive() {
                    Ok(path) => {
                        self.next_archive = path.map(|path| NextArchivePrompt {
                            path,
                            shown_at: None,
                        });
                    }
                    Err(error) => {
                        self.notice = Some(format!("Finding next archive failed: {error}"))
                    }
                }
                return false;
            }
            Action::ShiftSpreadBackward | Action::ShiftSpreadForward if self.spread => {
                return self.album.shift_spread(
                    self.config.cover,
                    matches!(action, Action::ShiftSpreadForward),
                );
            }
            Action::FirstPrefix => self.album.select(0),
            Action::Last => self
                .album
                .select(self.album.pages().len().saturating_sub(1)),
            Action::OpenFile | Action::OpenFolder => {
                if let Err(error) = self.open(ctx, frame, matches!(action, Action::OpenFolder)) {
                    self.notice = Some(format!("Open failed: {error}"));
                }
            }
            Action::Spread => self.spread = !self.spread,
            Action::Direction => {
                self.direction = match self.direction {
                    Direction::Rtl => Direction::Ltr,
                    Direction::Ltr => Direction::Rtl,
                };
            }
            Action::SelectOther if visible.len() == 2 => {
                self.album.select(if self.album.active() == visible.start {
                    visible.start + 1
                } else {
                    visible.start
                });
            }
            Action::Move(key) => {
                self.stop_slideshow(ctx);
                if let Some(page) = self.album.pages().get(self.album.active()) {
                    let id = page.id;
                    match self.album.move_active(&self.config.move_keys[&key]) {
                        Ok(()) => {
                            self.loader.invalidate(id);
                            self.notice = Some("Moved  ·  u to undo".to_owned());
                        }
                        Err(error) => self.notice = Some(format!("Move failed: {error}")),
                    }
                }
            }
            Action::Undo => {
                self.stop_slideshow(ctx);
                match self.album.undo() {
                    Ok(()) => {
                        self.loader
                            .invalidate(self.album.pages()[self.album.active()].id);
                        self.notice = Some("Move undone".to_owned());
                    }
                    Err(error) => self.notice = Some(format!("Undo: {error}")),
                }
            }
            Action::Slideshow if self.slideshow.is_some() => self.stop_slideshow(ctx),
            Action::Slideshow if !visible.is_empty() => {
                self.slideshow = Some(Slideshow {
                    deadline: None,
                    on_top: self.manual_top || self.config.slideshow_always_on_top,
                });
                self.apply_top(ctx);
            }
            Action::Top => {
                if let Some(slide) = &mut self.slideshow {
                    slide.on_top = !slide.on_top;
                } else {
                    self.manual_top = !self.manual_top;
                }
                self.apply_top(ctx);
            }
            Action::Fullscreen => self.set_fullscreen(ctx, !self.fullscreen),
            Action::Help => self.help = true,
            Action::Escape if self.fullscreen => self.set_fullscreen(ctx, false),
            Action::Escape => self.stop_slideshow(ctx),
            _ => return false,
        }
        true
    }

    fn set_fullscreen(&mut self, ctx: &Context, fullscreen: bool) {
        self.fullscreen = fullscreen;
        ctx.send_viewport_cmd(ViewportCommand::Fullscreen(fullscreen));
    }

    fn tick(&mut self, ctx: &Context, visible: Range<usize>) -> bool {
        let Some(slide) = &mut self.slideshow else {
            return false;
        };
        let pages = self.album.pages();
        if self.help
            || self.next_archive.is_some()
            || visible.len() == pages.len()
            || pages[visible.clone()]
                .iter()
                .any(|page| self.loader.get(page.id).is_none())
        {
            return false;
        }
        let now = Instant::now();
        let deadline = *slide
            .deadline
            .get_or_insert_with(|| now + Duration::from_secs(self.config.slideshow_seconds));
        if deadline > now {
            ctx.request_repaint_after(deadline - now);
            return false;
        }
        slide.deadline = None;
        self.album.select(if visible.end < pages.len() {
            visible.end
        } else {
            0
        });
        ctx.request_repaint();
        true
    }

    fn paint_canvas(&self, painter: &Painter, canvas: Rect, pages: &[Page]) {
        painter.rect_filled(canvas, 0., BACKGROUND);
        if self.help {
            self.paint_help(painter, canvas);
            return;
        }
        match pages {
            [] => centered(
                painter,
                canvas,
                "No images  ·  o to open a file  ·  O to open a folder",
            ),
            [page] => Self::paint_page(painter, canvas, self.loader.get(page.id)),
            [first, second] => {
                let (left, right) = match self.direction {
                    Direction::Rtl => (second, first),
                    Direction::Ltr => (first, second),
                };
                let left_image = self.loader.get(left.id);
                let right_image = self.loader.get(right.id);
                let (left_rect, right_rect) = spread_rects(canvas, left_image, right_image);
                Self::paint_page(painter, left_rect, left_image);
                Self::paint_page(painter, right_rect, right_image);
            }
            _ => unreachable!("a spread has at most two pages"),
        }
    }

    fn paint_page(painter: &Painter, bounds: Rect, image: CachedImage<'_>) {
        match image {
            Some(Ok(texture)) => {
                let size = texture.size_vec2();
                let scale = (bounds.width() / size.x).min(bounds.height() / size.y);
                let rect = Rect::from_center_size(bounds.center(), size * scale);
                painter.image(
                    texture.id(),
                    rect,
                    Rect::from_min_max(pos2(0., 0.), pos2(1., 1.)),
                    Color32::WHITE,
                );
            }
            Some(Err(error)) => {
                let clipped = painter.with_clip_rect(bounds);
                centered(&clipped, bounds, error);
            }
            None => centered(painter, bounds, "Loading…"),
        }
    }

    fn paint_help(&self, painter: &Painter, canvas: Rect) {
        let lines = [
            "h / k  previous    j / l  next    gg / G  first / last",
            "o  open image / archive    O  open folder",
            "v  spread    r  reading direction    Tab  select page",
            "[ / ]  shift spread back / forward by one page",
            &self.sort_help,
            "s  slideshow    t  always on top    f  fullscreen",
            "? / F1 / Esc  close help    q  quit",
        ];
        let height = 21.;
        let start = canvas.center().y - height * (lines.len() - 1) as f32 / 2.;
        for (index, line) in lines.into_iter().enumerate() {
            painter.text(
                pos2(canvas.center().x, start + index as f32 * height),
                Align2::CENTER_CENTER,
                line,
                FontId::proportional(14.),
                TEXT,
            );
        }
    }
}

impl eframe::App for Viewer {
    fn logic(&mut self, ctx: &Context, frame: &mut eframe::Frame) {
        let mut changed = false;
        if self.next_archive.is_none() {
            let actions: Vec<_> =
                ctx.input(|input| input.events.iter().filter_map(Action::from_event).collect());
            for (action, repeat) in actions {
                changed |= self.key(action, repeat, ctx, frame);
                if self.next_archive.is_some() {
                    break;
                }
            }
        }
        let visible = self.visible();
        self.loader
            .update(ctx, &self.album, visible.clone(), self.config.preload);
        changed |= self.tick(ctx, visible);
        if changed {
            self.refresh_status(ctx);
        }
    }

    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        self.show_next_archive_prompt(ui.ctx());
        let rect = ui.max_rect();
        let bottom = (rect.bottom() - 26.).max(rect.top());
        let canvas = Rect::from_min_max(rect.min, pos2(rect.right(), bottom));
        let footer = Rect::from_min_max(pos2(rect.left(), bottom), rect.max);
        let visible = self.visible();
        self.paint_canvas(
            &ui.painter_at(canvas),
            canvas,
            &self.album.pages()[visible.start..visible.end],
        );
        let painter = ui.painter_at(footer);
        painter.rect_filled(footer, 0., Color32::from_gray(29));
        let font = FontId::proportional(13.);
        let center_y = footer.center().y;
        let status = painter.layout_no_wrap(
            self.notice.as_deref().unwrap_or(&self.status).to_owned(),
            font.clone(),
            TEXT,
        );
        let mut status_clip = footer;
        if !self.help && visible.len() == 2 {
            let right = match self.direction {
                Direction::Rtl => visible.start,
                Direction::Ltr => visible.start + 1,
            };
            let selection = painter.layout_no_wrap(
                if self.album.active() == right {
                    "Selected: right"
                } else {
                    "Selected: left"
                }
                .to_owned(),
                font,
                TEXT,
            );
            let label = Align2::RIGHT_CENTER
                .anchor_size(pos2(footer.right() - 9., center_y), selection.size());
            let status_right = label.left() - 9.;
            if self.notice.is_none() || footer.left() + 9. + status.size().x <= status_right {
                painter.galley(label.min, selection, TEXT);
                status_clip.max.x = status_right;
            }
        }
        let status_position = Align2::LEFT_CENTER
            .anchor_size(pos2(footer.left() + 9., center_y), status.size())
            .min;
        painter
            .with_clip_rect(status_clip)
            .galley(status_position, status, TEXT);
    }
}

type CachedImage<'a> = Option<Result<&'a TextureHandle, &'a str>>;

fn spread_rects(canvas: Rect, left: CachedImage<'_>, right: CachedImage<'_>) -> (Rect, Rect) {
    let (bounds, split) = if let (Some(Ok(left)), Some(Ok(right))) = (left, right) {
        let left_size = left.size_vec2();
        let right_size = right.size_vec2();
        let left_ratio = left_size.x / left_size.y;
        let ratio = left_ratio + right_size.x / right_size.y;
        let height = canvas.height().min(canvas.width() / ratio);
        let bounds = Rect::from_center_size(canvas.center(), vec2(ratio * height, height));
        (bounds, bounds.left() + left_ratio * height)
    } else {
        (canvas, canvas.center().x)
    };
    (
        Rect::from_min_max(bounds.min, pos2(split, bounds.bottom())),
        Rect::from_min_max(pos2(split, bounds.top()), bounds.max),
    )
}

fn centered(painter: &Painter, rect: Rect, message: &str) {
    painter.text(
        rect.center(),
        Align2::CENTER_CENTER,
        message,
        FontId::proportional(14.),
        TEXT,
    );
}