Skip to main content

viewer/
viewer.rs

1//! A picture viewer: a folder's pictures as a thumbnail strip along the bottom, the selected
2//! one large above it, zoomed and panned by dragging. It shows every format the library reads:
3//! PNG, JPEG, GIF (animated), WebP, BMP, ICO, and SVG (sharp at any size).
4//!   cargo run -p taut --example viewer [-- <folder>]
5//! Keys: Left and Right step through pictures, Home and End to the first and last; Ctrl+Up and
6//! Ctrl+Down zoom (as do the wheel and two fingers), F fits the picture to the window, 1 shows
7//! it at its own size.
8#![windows_subsystem = "windows"]
9use std::path::{Path, PathBuf};
10use taut::{Align, Animation, Color, Drawing, Flow, Icon, Key, Length, Mods, Picture, Role, Ui, Window};
11
12const SMALLER: Icon = Icon::line("M3.5 8h9");
13const LARGER: Icon = Icon::line("M8 3.5v9M3.5 8h9");
14/// The endings of the files that are shown.
15const ENDINGS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "svg"];
16/// How far one step zooms, and the least and the most it may be.
17const STEP: f32 = 1.25;
18const ZOOMS: (f32, f32) = (0.05, 32.0);
19
20/// What a picture is shown with: a still one, one that moves, or a drawing.
21#[derive(Clone, Copy)]
22enum Shown {
23    Still(Picture),
24    Moving(Animation),
25    Drawn(Drawing),
26}
27
28/// One picture of the folder: its name, its kind, how many pixels wide and high it is of
29/// itself, and what shows it.
30pub struct Shot {
31    name: String,
32    kind: &'static str,
33    size: (f32, f32),
34    shown: Shown,
35}
36
37/// Everything the viewer keeps.
38pub struct Viewer {
39    folder: PathBuf,
40    /// The files that are still to be read: they are read into the interface at its first
41    /// run, which is where pictures are kept.
42    files: Vec<PathBuf>,
43    shots: Vec<Shot>,
44    /// The picture shown.
45    current: usize,
46    /// How large the picture is shown (1: a pixel of it to a unit), or none while it fits
47    /// the window; and how far it has been moved from the middle.
48    zoom: Option<f32>,
49    moved: (f32, f32),
50    /// The zoom the picture fits the room it has at (but for a small one, never larger than
51    /// it is).
52    fitted: f32,
53}
54
55impl Viewer {
56    /// A viewer of the pictures in `folder`, in the order of their names.
57    pub fn new(folder: PathBuf) -> Viewer {
58        let known = |path: &PathBuf| path.extension().and_then(|ending| ending.to_str()).is_some_and(|ending| ENDINGS.contains(&ending.to_lowercase().as_str()));
59        let mut files: Vec<PathBuf> = std::fs::read_dir(&folder).into_iter().flatten().flatten().map(|entry| entry.path()).filter(known).collect();
60        files.sort();
61        Viewer { folder, files, shots: Vec::new(), current: 0, zoom: None, moved: (0.0, 0.0), fitted: 1.0 }
62    }
63
64    /// Goes to another picture, fitted to the window.
65    fn go_to(&mut self, index: usize) {
66        (self.current, self.zoom, self.moved) = (index.min(self.shots.len().saturating_sub(1)), None, (0.0, 0.0));
67    }
68}
69
70/// Reads a picture file into the interface, and asks it how large the picture is. Nothing,
71/// for a file that is none it can read.
72fn read(path: &Path, ui: &mut Ui) -> Option<Shot> {
73    let bytes = std::fs::read(path).ok()?;
74    let name = path.file_name()?.to_string_lossy().into_owned();
75    // (What kind it is, to say so: as its first bytes have it.)
76    let kind = match bytes.as_slice() {
77        [0xFF, 0xD8, ..] => "JPEG",
78        [b'R', b'I', b'F', b'F', ..] => "WebP",
79        [b'B', b'M', ..] => "BMP",
80        [0, 0, 1, 0, ..] => "ICO",
81        [0x89, b'P', b'N', b'G', ..] => "PNG",
82        [b'G', b'I', b'F', ..] => "GIF",
83        _ => "SVG",
84    };
85    let shown = match kind {
86        "GIF" => Shown::Moving(ui.add_animation(&bytes)?),
87        "SVG" => Shown::Drawn(ui.add_drawing(std::str::from_utf8(&bytes).ok()?)?),
88        _ => Shown::Still(ui.add_picture_file(&bytes)?),
89    };
90    let size = match shown {
91        Shown::Still(picture) => ui.picture_size(picture).map(|(wide, high)| [wide as f32, high as f32]),
92        Shown::Moving(animation) => ui.animation_size(animation).map(|(wide, high)| [wide as f32, high as f32]),
93        Shown::Drawn(drawing) => ui.drawing_size(drawing),
94    }?;
95    Some(Shot { name, kind, size: (size[0], size[1]), shown })
96}
97
98/// A box that shows a picture, at the size it is said to have.
99fn picture_box(ui: &mut Ui, shown: Shown, color: taut::Color) -> taut::El<'_> {
100    match shown {
101        Shown::Still(picture) => ui.el().picture(picture),
102        Shown::Moving(animation) => ui.el().animation(animation),
103        Shown::Drawn(drawing) => ui.el().drawing(drawing, color),
104    }
105}
106
107pub fn describe(app: &mut Viewer, ui: &mut Ui) {
108    let t = ui.theme;
109    for file in std::mem::take(&mut app.files) {
110        app.shots.extend(read(&file, ui));
111    }
112    keys(app, ui);
113    ui.column().grow().open();
114    bar(app, ui);
115
116    // The picture that is selected, in the middle of the room, as large as it is zoomed to, and
117    // moved by as much as it has been dragged. While it fits, it is as large as fits (the
118    // room it has is this run's, as it comes out of layout). The wheel and two fingers zoom.
119    let view = ui.el().flow(Flow::Stack).grow().clip().fill(Color::BLACK.lerp(t.bg, 0.6)).sense().open();
120    let room = ui.available_size();
121    if let Some((size, shown)) = app.shots.get(app.current).map(|shot| (shot.size, shot.shown)) {
122        app.fitted = (room.w / size.0).min(room.h / size.1).min(1.0);
123        if let Some([_, down]) = ui.wheel_delta(&view) {
124            zoom_by(app, if down < 0.0 { STEP } else { 1.0 / STEP });
125        }
126        if let Some(zoom) = ui.zoom(&view) {
127            zoom_by(app, zoom.factor);
128        }
129        let zoom = app.zoom.unwrap_or(app.fitted);
130        let (wide, high) = (size.0 * zoom, size.1 * zoom);
131        if let Some((gone, caught)) = ui.drag_delta(&view, [app.moved.0, app.moved.1, 0.0, 0.0]) {
132            app.moved = (caught[0] + gone.x, caught[1] + gone.y);
133        }
134        picture_box(ui, shown, t.text).place(Align::Center).offset(app.moved.0, app.moved.1).size(wide, high).show();
135    } else {
136        ui.row().place(Align::Center).open();
137        ui.text(&format!("There are no pictures in {}", app.folder.display()), t.font, t.text_faint);
138        ui.close();
139    }
140    ui.close();
141    strip(app, ui);
142    ui.close();
143}
144
145/// The bar over the picture: its name, kind and size, and how large it is shown.
146fn bar(app: &mut Viewer, ui: &mut Ui) {
147    let t = ui.theme;
148    ui.row().pad((10.0, 6.0)).gap(8.0).fill(t.panel).align(Align::Start, Align::Center).open();
149    if let Some(shot) = app.shots.get(app.current) {
150        ui.text(&shot.name, t.font.bold(), t.text);
151        ui.note(&format!("{}, {} by {}", shot.kind, shot.size.0, shot.size.1));
152    }
153    ui.spacer();
154    let zoom = app.zoom.map_or("Fitted".to_string(), |zoom| format!("{:.0}%", zoom * 100.0));
155    ui.note(&zoom);
156    if ui.icon_button(SMALLER, "Smaller").clicked {
157        zoom_by(app, 1.0 / STEP);
158    }
159    if ui.icon_button(LARGER, "Larger").clicked {
160        zoom_by(app, STEP);
161    }
162    if ui.button("Fit").clicked {
163        app.go_to(app.current);
164    }
165    if ui.button("1:1").clicked {
166        app.zoom = Some(1.0);
167    }
168    ui.close();
169}
170
171/// Zooms by a step, from what shows now: about the middle of the room.
172fn zoom_by(app: &mut Viewer, by: f32) {
173    // (While it fits, it shows at the zoom it fits at; the last run said what that was.)
174    let now = app.zoom.unwrap_or(app.fitted);
175    app.zoom = Some((now * by).clamp(ZOOMS.0, ZOOMS.1));
176    app.moved = (app.moved.0 * by, app.moved.1 * by);
177}
178
179/// The strip of small pictures along the bottom. A click on one selects it.
180fn strip(app: &mut Viewer, ui: &mut Ui) {
181    let t = ui.theme;
182    ui.row().h(Length::Px(92.0)).pad(8.0).gap(6.0).fill(t.panel).scroll_x().open();
183    let mut clicked = None;
184    for (number, shot) in app.shots.iter().enumerate() {
185        let selected = number == app.current;
186        let edge = if selected { t.accent } else { t.line };
187        let small = ui.el().key(&shot.name).size(72.0, 72.0).flow(Flow::Stack).border(edge, 2.0).radius(4.0).sense().focusable().open();
188        picture_box(ui, shot.shown, t.text).place(Align::Center).size(64.0, 64.0).keep_aspect().show();
189        ui.close();
190        ui.tell(&small, Role::Row, Some(selected), &shot.name);
191        clicked = clicked.or(small.clicked.then_some(number));
192    }
193    ui.close();
194    if let Some(number) = clicked {
195        app.go_to(number);
196    }
197}
198
199/// The keys of the viewer.
200fn keys(app: &mut Viewer, ui: &mut Ui) {
201    let last = app.shots.len().saturating_sub(1);
202    let to = match () {
203        _ if ui.key(Key::Right, Mods::NONE) => Some((app.current + 1).min(last)),
204        _ if ui.key(Key::Left, Mods::NONE) => Some(app.current.saturating_sub(1)),
205        _ if ui.key(Key::Home, Mods::NONE) => Some(0),
206        _ if ui.key(Key::End, Mods::NONE) => Some(last),
207        _ => None,
208    };
209    if let Some(to) = to {
210        app.go_to(to);
211    }
212    if ui.keys("Ctrl+Up") {
213        zoom_by(app, STEP);
214    }
215    if ui.keys("Ctrl+Down") {
216        zoom_by(app, 1.0 / STEP);
217    }
218    if ui.keys("F") {
219        app.go_to(app.current);
220    }
221    if ui.keys("1") {
222        app.zoom = Some(1.0);
223    }
224}
225
226fn main() {
227    let folder = std::env::args_os().nth(1).map(PathBuf::from).or_else(|| std::env::current_dir().ok()).unwrap_or_default();
228    let mut app = Viewer::new(folder);
229    let window = Window { title: "Pictures", width: 900.0, height: 640.0, min_width: 360.0, min_height: 280.0, ..Default::default() };
230    taut::run(window, move |ui| describe(&mut app, ui));
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236    use taut::testing::Trial;
237
238    /// A folder with a picture of each kind the library reads, and a file that is none.
239    fn made() -> PathBuf {
240        let folder = std::env::temp_dir().join(format!("taut-viewer-{}", std::process::id()));
241        _ = std::fs::remove_dir_all(&folder);
242        std::fs::create_dir_all(&folder).unwrap();
243        let pictures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests").join("pictures");
244        for (from, to) in [
245            ("inks.jpg", "a-inks.jpg"),
246            ("moving.gif", "b-moving.gif"),
247            ("logo.svg", "c-logo.svg"),
248            ("lossy.webp", "d-lossy.webp"),
249            ("bmp-24.bmp", "e-bmp.bmp"),
250            ("icon.ico", "f-icon.ico"),
251            ("passes.png", "g-passes.png"),
252        ] {
253            std::fs::copy(pictures.join(from), folder.join(to)).unwrap();
254        }
255        std::fs::write(folder.join("notes.txt"), "not a picture").unwrap();
256        folder
257    }
258
259    #[test]
260    fn pictures_of_every_kind_are_shown_picked_zoomed_and_moved() {
261        let folder = made();
262        let mut trial = Trial::new(Viewer::new(folder.clone()), describe);
263        trial.resize(640.0, 420.0, 1.0);
264        let kinds: Vec<&str> = trial.app.shots.iter().map(|shot| shot.kind).collect();
265        assert_eq!(kinds, ["JPEG", "GIF", "SVG", "WebP", "BMP", "ICO", "PNG"], "every picture, and nothing else");
266        assert!(trial.has(Role::Text, "a-inks.jpg") && trial.has(Role::Row, "g-passes.png"));
267        trial.looks_like("tests/looks/viewer.png");
268
269        // Picked from the strip, and by the keys.
270        trial.press(Role::Row, "c-logo.svg");
271        assert_eq!(trial.app.current, 2);
272        trial.key("Right");
273        trial.key("Right");
274        assert!(trial.has(Role::Text, "e-bmp.bmp") && trial.find(Role::Row, "e-bmp.bmp").on == Some(true));
275        trial.key("End");
276        assert_eq!(trial.app.current, 6);
277        trial.key("Home");
278
279        // Zoomed in by a step from where it fits, then shown at its own size; dragged about;
280        // and fitted again, back in the middle.
281        let fitted = trial.app.fitted;
282        trial.press(Role::Button, "Larger");
283        assert_eq!(trial.app.zoom, Some(fitted * STEP));
284        // The wheel zooms too, over the picture: in, and out again.
285        let middle = trial.center_of(Role::Text, "a-inks.jpg");
286        let over = taut::geom::pt(middle.x + 200.0, 200.0);
287        trial.wheel(over, 0.0, -48.0);
288        assert_eq!(trial.app.zoom, Some(fitted * STEP * STEP));
289        trial.wheel(over, 0.0, 48.0);
290        assert_eq!(trial.app.zoom, Some(fitted * STEP));
291        trial.key("1");
292        assert!(trial.has(Role::Text, "100%"));
293        let middle = trial.center_of(Role::Text, "a-inks.jpg");
294        let at = taut::geom::pt(middle.x + 200.0, 200.0);
295        trial.drag(at, taut::geom::pt(at.x - 60.0, at.y + 30.0));
296        assert_eq!(trial.app.moved, (-60.0, 30.0));
297        trial.press(Role::Button, "Fit");
298        assert!(trial.app.zoom.is_none() && trial.app.moved == (0.0, 0.0) && trial.has(Role::Text, "Fitted"));
299
300        // The moving one moves: its picture changes as time passes.
301        trial.press(Role::Row, "b-moving.gif");
302        let before = trial.screen.pixels.clone();
303        trial.wait(std::time::Duration::from_millis(500));
304        assert!(trial.screen.pixels != before, "the film went on");
305        _ = std::fs::remove_dir_all(&folder);
306    }
307}