rs-rich-micro 0.0.10

Micro assets for rs-rich: emoji-sized inline images, packages, a layered registry and :micro: markup
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
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
//! The asset model (#566, #579, #585): what a micro asset is, independent of
//! where it was loaded from or how a terminal will draw it.

use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;

use rich::cells::cell_len;

use crate::error::MicroError;
use crate::name::check_name;

/// The widest asset, in cells. Micro assets are emoji-sized; anything wider
/// is an image, not an inline icon.
pub const MAX_COLS: u16 = 4;
/// The tallest asset, in rows (#711). A one-row asset sits in a line of
/// text; a two-row one (a 2×2 icon, a 3×2 animation) reserves the row below
/// the line it sits on. Anything taller is an image, not an inline icon.
pub const MAX_ROWS: u16 = 2;
/// The longest alt text, in characters.
pub const MAX_ALT_CHARS: usize = 200;

/// Whether an asset is a still image or moves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AssetKind {
    #[default]
    Static,
    Animated,
}

impl AssetKind {
    pub fn as_str(self) -> &'static str {
        match self {
            AssetKind::Static => "static",
            AssetKind::Animated => "animated",
        }
    }
}

impl FromStr for AssetKind {
    type Err = MicroError;
    fn from_str(value: &str) -> Result<Self, MicroError> {
        match value {
            "static" => Ok(AssetKind::Static),
            "animated" => Ok(AssetKind::Animated),
            other => Err(MicroError::Manifest(format!(
                "unknown kind {other:?}: use \"static\" or \"animated\""
            ))),
        }
    }
}

/// An asset's footprint in terminal cells: columns × rows. The default is
/// 2×1, the footprint of an emoji (a cell is about twice as tall as it is
/// wide). Any size from 1×1 to [`MAX_COLS`] × [`MAX_ROWS`] (4×2) is allowed:
/// 1 to 4 columns, 1 or 2 rows. A two-row asset (a 2×2 icon, a 3×2
/// animation) reserves the row below the line it sits on; see
/// [`MicroRows`](crate::MicroRows).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct CellSize {
    cols: u16,
    rows: u16,
}

impl Default for CellSize {
    fn default() -> Self {
        CellSize { cols: 2, rows: 1 }
    }
}

impl CellSize {
    /// `cols` × `rows`, checked: 1..=[`MAX_COLS`] columns and
    /// 1..=[`MAX_ROWS`] rows.
    pub fn new(cols: u16, rows: u16) -> Result<Self, MicroError> {
        if cols == 0 || rows == 0 {
            return Err(MicroError::InvalidSize(format!(
                "micro asset size {cols}x{rows}: columns and rows must be at least 1"
            )));
        }
        if cols > MAX_COLS || rows > MAX_ROWS {
            return Err(MicroError::InvalidSize(format!(
                "micro asset size {cols}x{rows}: at most {MAX_COLS} columns and {MAX_ROWS} \
                 rows ({MAX_COLS}x{MAX_ROWS}); anything larger is an image, not a micro asset"
            )));
        }
        Ok(CellSize { cols, rows })
    }

    pub fn cols(self) -> usize {
        self.cols as usize
    }

    pub fn rows(self) -> usize {
        self.rows as usize
    }

    /// Whether it takes more than one row: such an asset reserves the rows
    /// below the line it sits on.
    pub fn is_multi_row(self) -> bool {
        self.rows > 1
    }
}

impl fmt::Display for CellSize {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}x{}", self.cols, self.rows)
    }
}

impl FromStr for CellSize {
    type Err = MicroError;
    /// `"2x1"`, `"1x1"`, `"2x2"`, `"3x2"`.
    fn from_str(value: &str) -> Result<Self, MicroError> {
        let bad = || {
            MicroError::InvalidSize(format!(
                "micro asset size {value:?}: write columns x rows, like \"2x1\""
            ))
        };
        let (cols, rows) = value.split_once(['x', 'X']).ok_or_else(bad)?;
        let parse = |part: &str| {
            if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) {
                Err(bad())
            } else {
                part.parse::<u16>().map_err(|_| bad())
            }
        };
        CellSize::new(parse(cols)?, parse(rows)?)
    }
}

/// An image file format a package may hold.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageFormat {
    Png,
    /// Animated PNG: a PNG with an `acTL` chunk.
    Apng,
    Gif,
    WebP,
}

impl ImageFormat {
    pub fn as_str(self) -> &'static str {
        match self {
            ImageFormat::Png => "png",
            ImageFormat::Apng => "apng",
            ImageFormat::Gif => "gif",
            ImageFormat::WebP => "webp",
        }
    }
}

/// What an image's header says, read without decoding it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ImageInfo {
    pub format: ImageFormat,
    pub width: u32,
    pub height: u32,
    /// 1 for a still image.
    pub frames: u32,
}

impl ImageInfo {
    /// The bytes it takes decoded, as RGBA, every frame at canvas size.
    pub fn decoded_bytes(&self) -> u64 {
        self.width as u64 * self.height as u64 * 4 * self.frames.max(1) as u64
    }
}

/// One image in a package: its path inside the package, its header and its
/// size on disk. The bytes are read on demand
/// ([`MicroAsset::read_variant`]), never kept.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ImageRef {
    pub path: String,
    pub info: ImageInfo,
    pub bytes: u64,
}

/// The images an asset can be drawn from. An asset built in code may have
/// none and render only its fallback.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Variants {
    /// The still image; also the static frame of an animation.
    pub static_image: Option<ImageRef>,
    /// A GIF, APNG or WebP animation.
    pub animation: Option<ImageRef>,
    /// An animation as a sequence of still images.
    pub frames: Vec<ImageRef>,
}

impl Variants {
    pub fn is_empty(&self) -> bool {
        self.static_image.is_none() && self.animation.is_none() && self.frames.is_empty()
    }

    /// Every image, static first.
    pub fn iter(&self) -> impl Iterator<Item = &ImageRef> {
        self.static_image
            .iter()
            .chain(self.animation.iter())
            .chain(self.frames.iter())
    }
}

/// What to show where no image can be drawn: an emoji, a short text, or both.
/// Each must fit the asset's columns and hold no whitespace or control
/// characters. With neither, the alt text is used, cut to fit.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Fallback {
    pub emoji: Option<String>,
    pub text: Option<String>,
}

/// A registry layer, in ascending precedence: a later layer wins.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Layer {
    /// Shipped with the library.
    BuiltIn,
    /// The user's own assets (`~/.config/rich/micro/`).
    User,
    /// A trusted project's assets (`.rich/micro/`).
    Project,
    /// Added in code.
    Inline,
}

impl Layer {
    pub const ALL: [Layer; 4] = [Layer::BuiltIn, Layer::User, Layer::Project, Layer::Inline];

    pub fn as_str(self) -> &'static str {
        match self {
            Layer::BuiltIn => "built-in",
            Layer::User => "user",
            Layer::Project => "project",
            Layer::Inline => "inline",
        }
    }

    pub(crate) fn index(self) -> usize {
        self as usize
    }
}

impl fmt::Display for Layer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Where a package's files live, so its images can be read later.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum PackageLocation {
    /// A package directory.
    Directory(PathBuf),
    /// A zip archive, and the package's folder inside it (`""` at its root).
    Archive { path: PathBuf, prefix: String },
    /// The library's own built-in set, compiled in: the package's folder in
    /// it (`status/success`).
    BuiltIn(String),
}

/// Where an asset came from.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Origin {
    pub layer: Layer,
    /// The pack it was installed with, if any.
    pub pack: Option<String>,
    /// Its package, when it was loaded from one.
    pub location: Option<PackageLocation>,
}

impl Default for Origin {
    fn default() -> Self {
        Origin {
            layer: Layer::Inline,
            pack: None,
            location: None,
        }
    }
}

impl fmt::Display for Origin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.layer.as_str())?;
        if let Some(pack) = &self.pack {
            write!(f, " pack {pack}")?;
        }
        match &self.location {
            Some(PackageLocation::Directory(path)) => write!(f, " ({})", path.display()),
            Some(PackageLocation::Archive { path, prefix }) if prefix.is_empty() => {
                write!(f, " ({})", path.display())
            }
            Some(PackageLocation::Archive { path, prefix }) => {
                write!(f, " ({}!{prefix})", path.display())
            }
            Some(PackageLocation::BuiltIn(prefix)) => write!(f, " (builtin:{prefix})"),
            None => Ok(()),
        }
    }
}

/// An emoji-sized inline image or animation.
///
/// ```
/// use rich_micro::{CellSize, MicroAsset};
///
/// let asset = MicroAsset::new("status/ok", "green check mark")?
///     .with_emoji("✅")?
///     .with_text("OK")?;
/// assert_eq!(asset.size(), CellSize::default()); // 2x1
/// assert!(MicroAsset::new("status/ok", "check")?.with_size(CellSize::new(1, 1)?)?.with_emoji("✅").is_err());
/// # Ok::<(), rich_micro::MicroError>(())
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MicroAsset {
    name: String,
    kind: AssetKind,
    size: CellSize,
    variants: Variants,
    alt: String,
    fallback: Fallback,
    aliases: Vec<String>,
    origin: Origin,
    version: Option<String>,
    license: Option<String>,
    author: Option<String>,
}

impl MicroAsset {
    /// A static 2×1 asset with no images, in the inline layer. `alt` is
    /// mandatory: it is what screen readers, logs and plain exports show.
    pub fn new(name: &str, alt: &str) -> Result<Self, MicroError> {
        check_name(name)?;
        check_alt(alt)?;
        Ok(MicroAsset {
            name: name.to_string(),
            kind: AssetKind::Static,
            size: CellSize::default(),
            variants: Variants::default(),
            alt: alt.trim().to_string(),
            fallback: Fallback::default(),
            aliases: Vec::new(),
            origin: Origin::default(),
            version: None,
            license: None,
            author: None,
        })
    }

    /// Change the size; the fallbacks set so far must still fit.
    pub fn with_size(mut self, size: CellSize) -> Result<Self, MicroError> {
        for value in [&self.fallback.emoji, &self.fallback.text]
            .into_iter()
            .flatten()
        {
            check_fallback(value, size)?;
        }
        self.size = size;
        Ok(self)
    }

    /// An emoji to show where no image can be drawn.
    pub fn with_emoji(mut self, emoji: &str) -> Result<Self, MicroError> {
        check_fallback(emoji, self.size)?;
        self.fallback.emoji = Some(emoji.to_string());
        Ok(self)
    }

    /// A short text to show where neither an image nor emoji can be.
    pub fn with_text(mut self, text: &str) -> Result<Self, MicroError> {
        check_fallback(text, self.size)?;
        self.fallback.text = Some(text.to_string());
        Ok(self)
    }

    #[must_use]
    pub fn with_kind(mut self, kind: AssetKind) -> Self {
        self.kind = kind;
        self
    }

    #[must_use]
    pub fn with_variants(mut self, variants: Variants) -> Self {
        self.variants = variants;
        self
    }

    /// Another name for this asset, resolved within its layer.
    pub fn with_alias(mut self, alias: &str) -> Result<Self, MicroError> {
        check_name(alias)?;
        if alias != self.name && !self.aliases.iter().any(|a| a == alias) {
            self.aliases.push(alias.to_string());
        }
        Ok(self)
    }

    #[must_use]
    pub fn with_origin(mut self, origin: Origin) -> Self {
        self.origin = origin;
        self
    }

    #[must_use]
    pub fn with_version(mut self, version: &str) -> Self {
        self.version = Some(version.to_string());
        self
    }

    #[must_use]
    pub fn with_license(mut self, license: &str) -> Self {
        self.license = Some(license.to_string());
        self
    }

    #[must_use]
    pub fn with_author(mut self, author: &str) -> Self {
        self.author = Some(author.to_string());
        self
    }

    /// Check what the builder methods cannot check one at a time: an animated
    /// asset needs an animation or frames.
    pub fn validate(&self) -> Result<(), MicroError> {
        if self.kind == AssetKind::Animated
            && self.variants.animation.is_none()
            && self.variants.frames.is_empty()
        {
            return Err(MicroError::Manifest(format!(
                "micro asset {:?} is animated but has no animation or frames",
                self.name
            )));
        }
        Ok(())
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn kind(&self) -> AssetKind {
        self.kind
    }

    pub fn size(&self) -> CellSize {
        self.size
    }

    /// Its width in cells: what it always measures, however it is drawn.
    pub fn cols(&self) -> usize {
        self.size.cols()
    }

    /// Its height in rows: 1, or 2 for an asset that reserves the row below
    /// its line.
    pub fn rows(&self) -> usize {
        self.size.rows()
    }

    pub fn variants(&self) -> &Variants {
        &self.variants
    }

    pub fn alt(&self) -> &str {
        &self.alt
    }

    pub fn fallback(&self) -> &Fallback {
        &self.fallback
    }

    pub fn aliases(&self) -> &[String] {
        &self.aliases
    }

    pub fn origin(&self) -> &Origin {
        &self.origin
    }

    pub fn version(&self) -> Option<&str> {
        self.version.as_deref()
    }

    pub fn license(&self) -> Option<&str> {
        self.license.as_deref()
    }

    pub fn author(&self) -> Option<&str> {
        self.author.as_deref()
    }

    /// Read one of this asset's images from its package, under `limits`.
    /// Errors when the asset has no package or the file changed and now
    /// breaks a limit.
    pub fn read_variant(
        &self,
        image: &ImageRef,
        limits: &crate::Limits,
    ) -> Result<Vec<u8>, MicroError> {
        let location =
            self.origin.location.as_ref().ok_or_else(|| {
                MicroError::Io(format!("micro asset {:?} has no package", self.name))
            })?;
        crate::package::read_file(location, &image.path, limits)
    }
}

fn check_alt(alt: &str) -> Result<(), MicroError> {
    let trimmed = alt.trim();
    if trimmed.is_empty() {
        return Err(MicroError::InvalidAlt(
            "micro asset alt text is required".to_string(),
        ));
    }
    if trimmed.chars().any(char::is_control) {
        return Err(MicroError::InvalidAlt(format!(
            "micro asset alt text {trimmed:?} holds control characters"
        )));
    }
    if trimmed.chars().count() > MAX_ALT_CHARS {
        return Err(MicroError::InvalidAlt(format!(
            "micro asset alt text is longer than {MAX_ALT_CHARS} characters"
        )));
    }
    Ok(())
}

/// A fallback must be non-empty, fit `size`, and hold no whitespace (it would
/// let wrapping split the asset) or control characters.
pub(crate) fn check_fallback(value: &str, size: CellSize) -> Result<(), MicroError> {
    if value.is_empty() {
        return Err(MicroError::InvalidFallback(
            "micro asset fallback is empty".to_string(),
        ));
    }
    if value
        .chars()
        .any(|c| c.is_whitespace() || c.is_control() || crate::render::is_sentinel(c))
    {
        return Err(MicroError::InvalidFallback(format!(
            "micro asset fallback {value:?} holds whitespace or control characters"
        )));
    }
    let width = cell_len(value);
    if width == 0 || width > size.cols() {
        return Err(MicroError::InvalidFallback(format!(
            "micro asset fallback {value:?} is {width} cells wide; it must fit {} columns",
            size.cols()
        )));
    }
    Ok(())
}

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

    #[test]
    fn sizes() {
        assert_eq!("2x1".parse::<CellSize>().unwrap(), CellSize::default());
        assert_eq!("1x1".parse::<CellSize>().unwrap().cols(), 1);
        // Two rows (#711): every width up to four columns.
        for cols in 1..=MAX_COLS {
            let size: CellSize = format!("{cols}x2").parse().unwrap();
            assert_eq!((size.cols(), size.rows()), (cols as usize, 2));
            assert!(size.is_multi_row());
        }
        assert!(!CellSize::default().is_multi_row());
        assert_eq!("3X2".parse::<CellSize>().unwrap().to_string(), "3x2");
        for refused in ["2x3", "1x3", "5x2", "4x9"] {
            let err = refused.parse::<CellSize>().unwrap_err().to_string();
            assert!(err.contains("at most 4 columns and 2 rows (4x2)"), "{err}");
        }
        assert!(matches!(
            CellSize::new(2, 3),
            Err(MicroError::InvalidSize(_))
        ));
        assert!("0x1".parse::<CellSize>().is_err());
        assert!("2x0".parse::<CellSize>().is_err());
        assert!("5x1".parse::<CellSize>().is_err());
        assert!("x1".parse::<CellSize>().is_err());
        assert!("+2x1".parse::<CellSize>().is_err());
        assert!("99999x1".parse::<CellSize>().is_err());
    }

    #[test]
    fn alt_is_mandatory() {
        assert!(matches!(
            MicroAsset::new("a", "  "),
            Err(MicroError::InvalidAlt(_))
        ));
        assert!(MicroAsset::new("a", "bell\u{7}").is_err());
        assert!(MicroAsset::new("A", "x").is_err());
    }

    #[test]
    fn fallbacks_must_fit() {
        let one = CellSize::new(1, 1).unwrap();
        let asset = MicroAsset::new("a", "alt").unwrap();
        assert!(asset.clone().with_emoji("🚀").is_ok());
        assert!(asset.clone().with_text("OK").is_ok());
        assert!(asset.clone().with_text("OKAY").is_err());
        assert!(asset.clone().with_text("o k").is_err());
        assert!(asset.clone().with_text("").is_err());
        assert!(asset.clone().with_text("\u{1b}[31m").is_err());
        let rocket = asset.clone().with_emoji("🚀").unwrap();
        assert!(rocket.with_size(one).is_err());
        assert!(asset.with_size(one).unwrap().with_text("*").is_ok());
    }

    #[test]
    fn animated_needs_motion() {
        let asset = MicroAsset::new("a", "alt")
            .unwrap()
            .with_kind(AssetKind::Animated);
        assert!(asset.validate().is_err());
    }
}