exhibit 0.2.0

A small Rust library for controlling the display of any Displayable type
Documentation
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
use std::fmt;

use cfg_if::cfg_if;

use crate::{
    moves::{move_down, move_right},
    write_utils::{writeln_truncated, writeln_untruncated},
};

/// A wrapper around a [`Display`](std::fmt::Display)able type.
///
/// This is created by the [`exhibit`](crate::ExhibitExt::exhibit) method.
/// It allows you to control, among other things,
/// the rectangular area of the screen,
/// as well as the upper-left corner position,
/// where an object is to be displayed.
///
/// # Examples
///
/// ```rust
/// use exhibit::ExhibitExt;
///
/// // This will print to the given position on the screen.
/// print!("{}", "Hello, world!".exhibit().pos(5, 5));
///
/// // This will crop the text to fit the given size.
/// print!("{}", "Hello, world!".exhibit().size(10, 10));
/// ```
#[derive(Clone, Copy)]
pub struct Exhibit<'t, T: ?Sized> {
    /// Inner [`Display`](std::fmt::Display)able object.
    inner: &'t T,

    /// Horizontal position in terminal cells
    /// with respect to the current column.
    x: Option<u16>,
    /// Vertical position in terminal cells
    /// with respect to the current line.
    y: Option<u16>,
    /// Maximum width in terminal cells.
    width: Option<u16>,
    /// Maximum height in terminal cells.
    height: Option<u16>,

    /// Whether to redact the contents
    /// of the [`Display`](std::fmt::Display)able object.
    redact: bool,

    #[cfg(feature = "ansi")]
    /// Whether
    /// [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code)
    /// are to be stripped from the rendered output.
    strip_ansi: bool,

    #[cfg(feature = "unicode")]
    /// Whether wide Unicode characters are to be shaded
    /// in the rendered output.
    shade_wide: bool,
}

impl<'t, T> Exhibit<'t, T> {
    pub(super) fn new(inner: &'t T) -> Self {
        Self {
            inner,

            x: None,
            y: None,
            width: None,
            height: None,

            redact: false,

            #[cfg(feature = "ansi")]
            strip_ansi: false,

            #[cfg(feature = "unicode")]
            shade_wide: false,
        }
    }

    /// Set the horizontal position in terminal cells.
    ///
    /// The position is relative to the current column,
    /// so that you can better control the position of the output
    /// in the context of terminal user interfaces.
    #[must_use]
    pub fn x(&mut self, x: u16) -> &mut Self {
        self.x = Some(x);
        self
    }

    /// Set the vertical position in terminal cells.
    ///
    /// The position is relative to the current line,
    /// so that you can better control the position of the output
    /// in the context of terminal user interfaces.
    #[must_use]
    pub fn y(&mut self, y: u16) -> &mut Self {
        self.y = Some(y);
        self
    }

    /// Convenience method for setting the
    /// [`x`](Self::x) and [`y`](Self::y) positions
    /// at the same time.
    #[must_use]
    pub fn pos(&mut self, x: u16, y: u16) -> &mut Self {
        self.x(x).y(y)
    }

    /// Set the maximum width in terminal cells.
    #[must_use]
    pub fn width(&mut self, width: u16) -> &mut Self {
        self.width = Some(width);
        self
    }

    /// Set the maximum height in terminal cells.
    #[must_use]
    pub fn height(&mut self, height: u16) -> &mut Self {
        self.height = Some(height);
        self
    }

    /// Convenience method for setting the
    /// [`width`](Self::width) and [`height`](Self::height) dimensions
    /// at the same time.
    #[must_use]
    pub fn size(&mut self, width: u16, height: u16) -> &mut Self {
        self.width(width).height(height)
    }

    /// Redact the contents of the [`Display`](std::fmt::Display)able object
    /// by replacing most of its characters with blocks.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use exhibit::ExhibitExt;
    /// let text = "Hello, world!";
    /// assert_eq!(
    ///     text.exhibit().redact(true).to_string(),
    ///     "▆▅▆▆▅, ▅▅▅▆▆!\n",
    /// );
    /// ```
    #[must_use]
    pub fn redact(&mut self, redact: bool) -> &mut Self {
        self.redact = redact;
        self
    }

    /// Strip
    /// [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code)
    /// from the rendered output.
    ///
    /// Useful in situations where the output is to be displayed
    /// in a terminal that does not support ANSI escape sequences,
    /// or if you pretend to style the output yourself
    /// and want to avoid possible conflicts.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use exhibit::ExhibitExt;
    /// let text = "\x1b[31mHello, world!\x1b[0m";
    /// assert_eq!(
    ///     text.exhibit().strip_ansi(true).to_string(),
    ///     "Hello, world!\n",
    /// );
    /// ```
    #[cfg(feature = "ansi")]
    #[must_use]
    pub fn strip_ansi(&mut self, strip_ansi: bool) -> &mut Self {
        self.strip_ansi = strip_ansi;
        self
    }

    /// Shade wide Unicode characters in the rendered output.
    ///
    /// Useful in situations where you plan to display something
    /// on top of the output, and you want
    /// to avoid chopping off wide characters underneath.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use exhibit::ExhibitExt;
    /// let text = "Hello, 🌎!";
    /// assert_eq!(
    ///     text.exhibit().shade_wide(true).to_string(),
    ///     "Hello, ░░!\n",
    /// );
    /// ```
    #[cfg(feature = "unicode")]
    #[must_use]
    pub fn shade_wide(&mut self, shade_wide: bool) -> &mut Self {
        self.shade_wide = shade_wide;
        self
    }
}

impl<T> fmt::Display for Exhibit<'_, T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(y) = self.y {
            move_down(f, y)?;
        }

        cfg_if! {
            if #[cfg(feature = "ansi")] {
                let strip_ansi = self.strip_ansi;
            } else {
                let strip_ansi = false;
            }
        }
        cfg_if! {
            if #[cfg(feature = "unicode")] {
                let shade_wide = self.shade_wide;
            } else {
                let shade_wide = false;
            }
        }

        match (self.height, self.width) {
            (None, None) if self.x.is_none() && !self.redact && !strip_ansi && !shade_wide => {
                self.inner.fmt(f)
            }
            (None, None) => self.inner.to_string().lines().try_for_each(|line| {
                if let Some(x) = self.x {
                    move_right(f, x)?;
                }
                writeln_untruncated(f, line, self.redact, strip_ansi, shade_wide)
            }),

            (Some(height), None) => self
                .inner
                .to_string()
                .lines()
                .take(height as usize)
                .try_for_each(|line| {
                    if let Some(x) = self.x {
                        move_right(f, x)?;
                    }
                    writeln_untruncated(f, line, self.redact, strip_ansi, shade_wide)
                }),

            (None, Some(width)) => self.inner.to_string().lines().try_for_each(|line| {
                if let Some(x) = self.x {
                    move_right(f, x)?;
                }
                writeln_truncated(f, line, self.redact, strip_ansi, shade_wide, width as usize)
            }),

            (Some(height), Some(width)) => self
                .inner
                .to_string()
                .lines()
                .take(height as usize)
                .try_for_each(|line| {
                    if let Some(x) = self.x {
                        move_right(f, x)?;
                    }
                    writeln_truncated(f, line, self.redact, strip_ansi, shade_wide, width as usize)
                }),
        }
    }
}

#[cfg(test)]
mod tests {
    use cfg_if::cfg_if;
    #[cfg(feature = "ansi")]
    use console::style;
    use insta::assert_display_snapshot;

    use crate::ExhibitExt;

    #[test]
    fn ascii() {
        let text = "Hello, world!\nThis is a test!";

        assert_eq!(text.exhibit().to_string(), text);

        assert_display_snapshot!(text.exhibit().height(1), @r###"
        Hello, world!
        "###);

        assert_display_snapshot!(text.exhibit().width(4), @r###"
        Hell
        This
        "###);

        assert_display_snapshot!(text.exhibit().size(5, 1), @r###"
        Hello
        "###);
    }

    #[cfg(feature = "unicode")]
    #[test]
    fn redact() {
        let text = "你好世界!\nThis is a test!";

        assert_ne!(text.exhibit().redact(true).to_string(), text);

        assert_display_snapshot!(text.exhibit().redact(true).height(1), @r###"
        ▇▇▇▇▇▇▇▇!
        "###);

        assert_display_snapshot!(text.exhibit().redact(true).width(4), @r###"
        ▇▇▇▇
        ▆▆▆▅
        "###);

        assert_display_snapshot!(text.exhibit().redact(true).size(5, 1), @r###"
        ▇▇▇▇
        "###);
    }

    #[cfg(all(feature = "ansi", feature = "unicode"))]
    #[test]
    fn redact_ansi() {
        let text = format!(
            "{}\n{}",
            style(format!("{}世界!", style("你好").bold())).cyan(),
            style(format!("Th{} a test!", style("is is").italic())).blue()
        );

        assert_ne!(text.exhibit().redact(true).to_string(), text);

        assert_display_snapshot!(text.exhibit().redact(true).height(1), @r###"
        ▇▇▇▇▇▇▇▇!
        "###);

        assert_display_snapshot!(text.exhibit().redact(true).width(4), @r###"
        ▇▇▇▇
        ▆▆▆▅
        "###);

        assert_display_snapshot!(text.exhibit().redact(true).size(5, 1), @r###"
        ▇▇▇▇
        "###);
    }

    #[cfg(feature = "ansi")]
    #[test]
    fn ansi() {
        let text = format!(
            "{}\n{}",
            style(format!("{}, world!", style("Hello").bold())).cyan(),
            style(format!("Th{} a test!", style("is is").italic())).blue()
        );

        assert_eq!(text.exhibit().to_string(), text);

        assert_display_snapshot!(text.exhibit().height(1), @r###"
        Hello, world!
        "###);

        assert_display_snapshot!(text.exhibit().width(4), @r###"
        Hell
        This
        "###);

        assert_display_snapshot!(text.exhibit().size(5, 1), @r###"
        Hello
        "###);
    }

    #[cfg(feature = "ansi")]
    #[test]
    fn strip_ansi() {
        let text = format!(
            "{}\n{}",
            style(format!("{}, world!", style("Hello").bold())).cyan(),
            style(format!("Th{} a test!", style("is is").italic())).blue()
        );

        assert_ne!(text.exhibit().strip_ansi(true).to_string(), text);

        assert_display_snapshot!(text.exhibit().strip_ansi(true).height(1), @r###"
        Hello, world!
        "###);

        assert_display_snapshot!(text.exhibit().strip_ansi(true).width(4), @r###"
        Hell
        This
        "###);

        assert_display_snapshot!(text.exhibit().strip_ansi(true).size(5, 1), @r###"
        Hello
        "###);
    }

    #[cfg(feature = "unicode")]
    #[test]
    fn unicode() {
        let text = "你好世界!\nThis is a test!";

        assert_eq!(text.exhibit().to_string(), text);

        assert_display_snapshot!(text.exhibit().height(1), @r###"
        你好世界!
        "###);

        assert_display_snapshot!(text.exhibit().width(11), @r###"
        你好世界!
        This i
        "###);

        assert_display_snapshot!(text.exhibit().size(11, 1), @r###"
        你好世界!
        "###);
    }

    #[cfg(feature = "unicode")]
    #[test]
    fn shade_wide() {
        let text = "你好世界!\nThis is a test!";

        assert_ne!(text.exhibit().shade_wide(true).to_string(), text);

        assert_display_snapshot!(text.exhibit()
            .shade_wide(true).height(1), @r###"
        ░░░░░░░░!
        "###);

        assert_display_snapshot!(text.exhibit()
            .shade_wide(true).width(11), @r###"
        ░░░░░░░░!
        ░░░░░░░░ ░░
        "###);

        assert_display_snapshot!(text.exhibit()
            .shade_wide(true).size(11, 1), @r###"
        ░░░░░░░░!
        "###);
    }

    #[cfg(all(feature = "ansi", feature = "unicode"))]
    #[test]
    fn ansi_with_unicode() {
        let text = format!(
            "{}\n{}",
            style(format!("{}, world!", style("Hello").bold())).cyan(),
            style(format!("Th{} a test!", style("is is").italic())).blue()
        );

        assert_eq!(text.exhibit().to_string(), text);

        assert_display_snapshot!(text.exhibit().height(1), @r###"
        Hello, world!
        "###);

        assert_display_snapshot!(text.exhibit().width(9), @r###"
        Hell
        This 
        "###);

        assert_display_snapshot!(text.exhibit().size(10, 1), @r###"
        Hello
        "###);
    }

    #[test]
    fn position() {
        let text = "Hello, world!\nThis is a test!";

        cfg_if! {
            if #[cfg(any(feature = "cursor-crossterm", feature = "cursor-termion"))] {
                let expected = "\rHello, world!\n\rThis is a test!\n";
            } else {
                let expected = r###"

 Hello, world!
 This is a test!
"###;
            }
        }
        assert_eq!(text.exhibit().pos(1, 2).to_string(), expected);
    }
}