viuer 0.11.0

Display images in the terminal
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
use crate::config::Config;
use crate::error::{ViuError, ViuResult};
use crate::utils::terminal_size;
use crossterm::cursor::{MoveRight, MoveTo, MoveToPreviousLine};
use crossterm::execute;
use image::{DynamicImage, GenericImageView};
use std::io::Write;

#[cfg(feature = "print-file")]
use std::path::Path;

mod block;
pub use block::BlockPrinter;

mod kitty;
pub use kitty::{get_kitty_support, KittyPrinter, KittySupport};

#[cfg(all(feature = "sixel", not(windows)))]
mod sixel;
#[cfg(all(feature = "sixel", not(windows)))]
pub use self::sixel::SixelPrinter;

#[cfg(any(feature = "icy_sixel", all(feature = "sixel", windows)))]
mod icy_sixel;
#[cfg(any(feature = "icy_sixel", all(feature = "sixel", windows)))]
pub use self::icy_sixel::IcySixelPrinter;

#[cfg(any(feature = "sixel", feature = "icy_sixel"))]
mod sixel_util;
#[cfg(any(feature = "sixel", feature = "icy_sixel"))]
pub use self::sixel_util::is_sixel_supported;

mod iterm;

pub(crate) mod read_key;

pub use iterm::iTermPrinter;
pub use iterm::is_iterm_supported;
#[cfg(test)]
use read_key::test_utils::TestKeys;
use read_key::ReadKey;

pub trait Printer {
    // Print the given image in the terminal while respecting the options in the config struct.
    // Return the dimensions of the printed image in **terminal cells**.
    fn print(
        &self,
        // Terminal input which may be used to query for supported capabilities.
        stdin: &impl ReadKey,
        // Terminal output where the Printer should emit the image.
        stdout: &mut impl Write,
        img: &DynamicImage,
        config: &Config,
    ) -> ViuResult<(u32, u32)>;

    #[cfg(feature = "print-file")]
    fn print_from_file<P: AsRef<Path>>(
        &self,
        stdin: &impl ReadKey,
        stdout: &mut impl Write,
        filename: P,
        config: &Config,
    ) -> ViuResult<(u32, u32)> {
        let img = image::ImageReader::open(filename)?
            .with_guessed_format()?
            .decode()?;
        self.print(stdin, stdout, &img, config)
    }
}

#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Copy)]
pub enum PrinterType {
    Block,
    Kitty,
    iTerm,
    #[cfg(all(feature = "sixel", not(windows)))]
    Sixel,
    #[cfg(any(feature = "icy_sixel", all(feature = "sixel", windows)))]
    IcySixel,
}

impl Printer for PrinterType {
    fn print(
        &self,
        stdin: &impl ReadKey,
        stdout: &mut impl Write,
        img: &DynamicImage,
        config: &Config,
    ) -> ViuResult<(u32, u32)> {
        match self {
            PrinterType::Block => BlockPrinter.print(stdin, stdout, img, config),
            PrinterType::Kitty => KittyPrinter.print(stdin, stdout, img, config),
            PrinterType::iTerm => iTermPrinter.print(stdin, stdout, img, config),
            #[cfg(all(feature = "sixel", not(windows)))]
            PrinterType::Sixel => SixelPrinter.print(stdin, stdout, img, config),
            #[cfg(any(feature = "icy_sixel", all(feature = "sixel", windows)))]
            PrinterType::IcySixel => IcySixelPrinter.print(stdin, stdout, img, config),
        }
    }

    #[cfg(feature = "print-file")]
    fn print_from_file<P: AsRef<Path>>(
        &self,
        stdin: &impl ReadKey,
        stdout: &mut impl Write,
        filename: P,
        config: &Config,
    ) -> ViuResult<(u32, u32)> {
        match self {
            PrinterType::Block => BlockPrinter.print_from_file(stdin, stdout, filename, config),
            PrinterType::Kitty => KittyPrinter.print_from_file(stdin, stdout, filename, config),
            PrinterType::iTerm => iTermPrinter.print_from_file(stdin, stdout, filename, config),
            #[cfg(all(feature = "sixel", not(windows)))]
            PrinterType::Sixel => SixelPrinter.print_from_file(stdin, stdout, filename, config),
            #[cfg(any(feature = "icy_sixel", all(feature = "sixel", windows)))]
            PrinterType::IcySixel => {
                IcySixelPrinter.print_from_file(stdin, stdout, filename, config)
            }
        }
    }
}

/// Resize a [image::DynamicImage] so that it fits within optional width and height bounds.
/// If none are provided, terminal size is used instead.
pub fn resize(img: &DynamicImage, width: Option<u32>, height: Option<u32>) -> DynamicImage {
    let (w, h) = find_best_fit(img, width, height);

    // find_best_fit returns values in terminal cells. Hence, we multiply by two
    // because a 5x10 image can fit in 5x5 cells. However, a 5x9 image will also
    // fit in 5x5 and 1 is deducted in such cases.
    img.resize_exact(
        w,
        2 * h - img.height() % 2,
        image::imageops::FilterType::CatmullRom,
    )
}

/// Find the best dimensions for the printed image, based on user's input.
/// Returns the dimensions of how the image should be printed in **terminal cells**.
///
/// The behaviour is different based on the provided width and height:
/// - If both are None, the image will be resized to fit in the terminal. Aspect ratio is preserved.
/// - If only one is provided and the other is None, it will fit the image in the provided boundary. Aspect ratio is preserved.
/// - If both are provided, the image will be resized to match the new size. Aspect ratio is **not** preserved.
///
/// Example:
/// Use None for both dimensions to use terminal size (80x24) instead.
/// The image ratio is 2:1, the terminal can be split into 80x46 squares.
/// The best fit would be to use the whole width (80) and 40 vertical squares,
/// which is equivalent to 20 terminal cells.
///
/// let img = image::DynamicImage::ImageRgba8(image::RgbaImage::new(160, 80));
/// let (w, h) = find_best_fit(&img, None, None);
/// assert_eq!(w, 80);
/// assert_eq!(h, 20);
//TODO: it might make more sense to change signiture from img to (width, height)
fn find_best_fit(img: &DynamicImage, width: Option<u32>, height: Option<u32>) -> (u32, u32) {
    let (img_width, img_height) = img.dimensions();

    // Match user's width and height preferences
    match (width, height) {
        (None, None) => {
            let (term_w, term_h) = terminal_size();
            let (w, h) = fit_dimensions(img_width, img_height, term_w as u32, term_h as u32);

            // One less row because two reasons:
            // - the prompt after executing the command will take a line
            // - gifs flicker
            let h = if h == term_h as u32 { h - 1 } else { h };
            (w, h)
        }
        // Either width or height is specified, will fit and preserve aspect ratio.
        (Some(w), None) => fit_dimensions(img_width, img_height, w, img_height),
        (None, Some(h)) => fit_dimensions(img_width, img_height, img_width, h),

        // Both width and height are specified, will resize to match exactly
        (Some(w), Some(h)) => (w, h),
    }
}

/// Given width & height of an image, scale the size so that it can fit within given bounds
/// while preserving aspect ratio. Will only scale down - if dimensions are smaller than the
/// bounds, they will be returned unmodified.
///
/// Note: input bounds are meant to hold dimensions of a terminal, where the height of a cell is
/// twice it's width. It is best illustrated in an example:
///
/// Trying to fit a 100x100 image in 40x15 terminal cells. The best fit, while having an aspect
/// ratio of 1:1, would be to use all of the available height, 15, which is
/// equivalent in size to 30 vertical cells. Hence, the returned dimensions will be 30x15.
///
/// assert_eq!((30, 15), viuer::fit_dimensions(100, 100, 40, 15));
fn fit_dimensions(width: u32, height: u32, bound_width: u32, bound_height: u32) -> (u32, u32) {
    let bound_height = 2 * bound_height;

    if width <= bound_width && height <= bound_height {
        return (width, std::cmp::max(1, height / 2 + height % 2));
    }

    let ratio = width * bound_height;
    let nratio = bound_width * height;

    let use_width = nratio <= ratio;
    let intermediate = if use_width {
        height * bound_width / width
    } else {
        width * bound_height / height
    };

    if use_width {
        (bound_width, std::cmp::max(1, intermediate / 2))
    } else {
        (intermediate, std::cmp::max(1, bound_height / 2))
    }
}

// Move the cursor to a location from where it should start printing. Calculations are based on
// offsets from the config.
fn adjust_offset(stdout: &mut impl Write, config: &Config) -> ViuResult {
    if config.absolute_offset {
        if config.y >= 0 {
            // If absolute_offset, move to (x,y).
            execute!(stdout, MoveTo(config.x, config.y as u16))?;
        } else {
            //Negative values do not make sense.
            return Err(ViuError::InvalidConfiguration(
                "absolute_offset is true but y offset is negative".to_owned(),
            ));
        }
    } else {
        if config.y < 0 {
            // MoveUp if negative
            execute!(stdout, MoveToPreviousLine(-config.y as u16))?;
        } else {
            // Move down y lines
            for _ in 0..config.y {
                // writeln! is used instead of MoveDown to force scrolldown
                // observed when config.y > 0 and cursor is on the last terminal line
                writeln!(stdout)?;
            }
        }

        // Some terminals interpret 0 as 1, see MoveRight documentation
        if config.x > 0 {
            execute!(stdout, MoveRight(config.x))?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_adjust_offset_output(config: &Config, str: &str) {
        let mut vec = Vec::new();
        adjust_offset(&mut vec, config).unwrap();
        assert_eq!(std::str::from_utf8(&vec).unwrap(), str);
    }

    fn best_fit_large_test_image() -> DynamicImage {
        DynamicImage::ImageRgba8(image::RgbaImage::new(600, 499))
    }

    fn best_fit_small_test_image() -> DynamicImage {
        DynamicImage::ImageRgba8(image::RgbaImage::new(40, 25))
    }

    fn resize_get_large_test_image() -> DynamicImage {
        DynamicImage::ImageRgba8(image::RgbaImage::new(1000, 799))
    }

    fn resize_get_small_test_image() -> DynamicImage {
        DynamicImage::ImageRgba8(image::RgbaImage::new(20, 10))
    }

    // Resize tests

    #[test]
    fn test_resize_none() {
        let width = None;
        let height = None;

        let img = resize_get_large_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 60);
        assert_eq!(new_img.height(), 45);

        let img = resize_get_small_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 20);
        assert_eq!(new_img.height(), 10);
    }

    #[test]
    fn test_resize_some_none() {
        let width = Some(100);
        let height = None;

        let img = resize_get_large_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 100);
        assert_eq!(new_img.height(), 77);

        let img = resize_get_small_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 20);
        assert_eq!(new_img.height(), 10);
    }

    #[test]
    fn test_resize_none_some() {
        let width = None;
        let mut height = Some(90);

        let img = resize_get_large_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 225);
        assert_eq!(new_img.height(), 179);

        height = Some(4);
        let img = resize_get_small_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 16);
        assert_eq!(new_img.height(), 8);
    }

    #[test]
    fn test_resize_some_some() {
        let width = Some(15);
        let height = Some(9);

        let img = resize_get_large_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 15);
        assert_eq!(new_img.height(), 17);

        let img = resize_get_small_test_image();
        let new_img = resize(&img, width, height);
        assert_eq!(new_img.width(), 15);
        assert_eq!(new_img.height(), 18);
    }

    // Best fit tests

    #[test]
    fn find_best_fit_none() {
        let width = None;
        let height = None;

        let img = best_fit_large_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 57);
        assert_eq!(h, 23);

        let img = best_fit_small_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 40);
        assert_eq!(h, 13);

        let img = DynamicImage::ImageRgba8(image::RgbaImage::new(160, 80));
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 80);
        assert_eq!(h, 20);
    }

    #[test]
    fn find_best_fit_some_none() {
        let width = Some(100);
        let height = None;

        let img = best_fit_large_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 100);
        assert_eq!(h, 41);

        let img = best_fit_small_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 40);
        assert_eq!(h, 13);

        let width = Some(6);
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 6);
        assert_eq!(h, 1);

        let width = Some(3);
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 3);
        assert_eq!(h, 1);
    }

    #[test]
    fn find_best_fit_none_some() {
        let width = None;
        let height = Some(90);

        let img = best_fit_large_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 216);
        assert_eq!(h, 90);

        let height = Some(4);
        let img = best_fit_small_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 12);
        assert_eq!(h, 4);
    }

    #[test]
    fn find_best_fit_some_some() {
        let width = Some(15);
        let height = Some(9);

        let img = best_fit_large_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 15);
        assert_eq!(h, 9);

        let img = best_fit_small_test_image();
        let (w, h) = find_best_fit(&img, width, height);
        assert_eq!(w, 15);
        assert_eq!(h, 9);
    }

    #[test]
    fn test_fit_dimensions() {
        // ratio 1:1
        assert_eq!((40, 20), fit_dimensions(100, 100, 40, 50));
        assert_eq!((20, 10), fit_dimensions(100, 100, 40, 10));
        // ratio 3:2
        assert_eq!((30, 10), fit_dimensions(240, 160, 30, 100));
        // ratio 5:7
        assert_eq!((200, 140), fit_dimensions(300, 420, 320, 140));
    }

    #[test]
    fn test_fit_smaller_than_bounds() {
        assert_eq!((4, 2), fit_dimensions(4, 3, 80, 24));
        assert_eq!((4, 1), fit_dimensions(4, 1, 80, 24));
    }

    #[test]
    fn test_fit_equal_to_bounds() {
        assert_eq!((80, 12), fit_dimensions(80, 24, 80, 24));
    }

    #[test]
    fn test_zero_offset() {
        let config = Config {
            absolute_offset: false,
            x: 0,
            y: 0,
            ..Default::default()
        };
        // Should not move at all
        test_adjust_offset_output(&config, "");
    }

    #[test]
    fn test_adjust_offset_absolute() {
        let mut config = Config {
            absolute_offset: true,
            x: 3,
            y: 4,
            ..Default::default()
        };

        config.x = 3;
        config.y = 0;
        test_adjust_offset_output(&config, "\x1b[1;4H");

        config.x = 7;
        config.y = 4;
        test_adjust_offset_output(&config, "\x1b[5;8H");
    }

    #[test]
    fn test_adjust_offset_not_absolute() {
        let mut config = Config {
            absolute_offset: false,
            x: 3,
            y: 4,
            ..Default::default()
        };
        test_adjust_offset_output(&config, "\n\n\n\n\x1b[3C");

        config.x = 1;
        config.y = -2;
        test_adjust_offset_output(&config, "\x1b[2F\x1b[1C");
    }

    #[test]
    fn test_invalid_adjust_offset() {
        let config = Config {
            absolute_offset: true,
            y: -1,
            ..Default::default()
        };

        let mut vec = Vec::new();
        let err = adjust_offset(&mut vec, &config).unwrap_err();
        assert!(matches!(err, ViuError::InvalidConfiguration { .. }));
    }
}