brushkit-preview 0.2.2

Tip bitmaps for .abr, .brush and .brushset files: sampled tips, synthesized computed tips, Procreate Shape.png and contact sheets
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
//! Tip bitmaps for every brush file this workspace reads.
//!
//! `preview_abr`, `preview_brush` and `preview_brushset` each take the whole
//! file as bytes and return one [`PreviewEntry`] per brush in file order,
//! available or not. A brush whose tip cannot be rendered is reported with a
//! reason rather than dropped, so a caller can lay out a complete grid. Each
//! has a `_first_available` twin that returns only the first `n` available
//! entries and builds no entry after them.
//!
//! Every function here is pure over `&[u8]`: no filesystem, no threads, so the
//! crate builds for `wasm32-unknown-unknown`.

pub mod procreate;

mod bitmap;
#[cfg(feature = "text")]
mod sheet;
mod synth;

pub use bitmap::*;
#[cfg(feature = "text")]
pub use sheet::*;
pub use synth::*;

use brushkit_abr::{parse_abr_deferred_without_patterns, DeferredPack, ShapeTipFamily};
use std::io::Cursor;
use std::num::NonZeroU32;

#[derive(Debug, Clone, Copy)]
pub struct PreviewOptions {
    /// Larger side of every returned tip is at most this many pixels (>= 1).
    pub max_cell: u32,
}

#[derive(Debug, Clone)]
pub struct PreviewSet {
    pub set_name: Option<String>,
    pub entries: Vec<PreviewEntry>,
}

/// File-declared raster dimensions, independent of the returned preview size.
/// A readable header does not guarantee valid pixels or a safe allocation size.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct SourceDimensions {
    width: NonZeroU32,
    height: NonZeroU32,
}

impl SourceDimensions {
    pub fn new(width: u32, height: u32) -> Option<Self> {
        Some(Self {
            width: NonZeroU32::new(width)?,
            height: NonZeroU32::new(height)?,
        })
    }

    pub fn width(self) -> u32 {
        self.width.get()
    }
    pub fn height(self) -> u32 {
        self.height.get()
    }
}

#[derive(Debug, Clone)]
pub struct PreviewEntry {
    pub index: usize,
    pub name: String,
    pub tip: TipPreview,
    /// None when the brush has no source raster or its dimensions cannot be read.
    pub source_dimensions: Option<SourceDimensions>,
}

#[derive(Debug, Clone)]
pub enum TipPreview {
    Available(GrayscaleBitmap),
    Unavailable(UnavailableReason),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnavailableReason {
    NoShapePng,
    UnsupportedTipKind(String),
    Corrupt(String),
    TooLarge { width: u32, height: u32 },
}

#[derive(Debug)]
pub struct PreviewError(pub String);

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

impl std::error::Error for PreviewError {}

fn check_max_cell(opts: PreviewOptions) -> Result<u32, PreviewError> {
    if opts.max_cell == 0 {
        return Err(PreviewError("max_cell must be at least 1".to_string()));
    }
    Ok(opts.max_cell)
}

/// Which entries a preview returns.
#[derive(Clone, Copy)]
enum Take {
    All,
    /// The first `n` entries whose tip is available. This stops pulling after
    /// the `n`th; it saves work only because callers pass a lazy iterator.
    FirstAvailable(usize),
}

impl Take {
    fn collect(self, entries: impl Iterator<Item = PreviewEntry>) -> Vec<PreviewEntry> {
        match self {
            Take::All => entries.collect(),
            Take::FirstAvailable(n) => entries
                .filter(|entry| matches!(entry.tip, TipPreview::Available(_)))
                .take(n)
                .collect(),
        }
    }
}

/// Where an `.abr` preview row came from: an index into `brushes`,
/// `computed_presets` or `unsupported_tip_presets` of the parsed pack. The
/// derived order, variant first and then index, orders rows that share a
/// preset ordinal: sampled first, then computed, then unsupported, each in
/// file order.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Source {
    Sampled(usize),
    Computed(usize),
    Unsupported(usize),
}

struct Row {
    /// The preset ordinal from the descriptor, `usize::MAX` when unknown.
    key: usize,
    source: Source,
}

/// Tips for a Photoshop `.abr` pack.
///
/// Sampled tips are decoded one at a time and downsampled immediately, so the
/// peak footprint holds one full-size tip rather than the whole pack. Computed
/// presets are synthesized from their geometry; a preset that declares neither
/// is reported as an unsupported tip kind.
///
/// Embedded pattern payloads are neither copied nor decoded.
pub fn preview_abr(bytes: &[u8], opts: PreviewOptions) -> Result<PreviewSet, PreviewError> {
    abr(bytes, opts, Take::All)
}

/// The first `n` entries of [`preview_abr`] whose tip is available, in the
/// same order and with the same `index` they have there, so indices may skip.
/// Unavailable entries do not count toward `n`, and entries after the `n`th
/// available one are not built, so their tips are not decoded or downsampled.
///
/// The whole pack is still parsed, and the parser decodes some tips itself:
/// every tip of a v1 or v2 pack, and in newer packs the tips that a preset
/// uses as its dual brush (see [`brushkit_abr::DeferredPack`]).
pub fn preview_abr_first_available(
    bytes: &[u8],
    opts: PreviewOptions,
    n: usize,
) -> Result<PreviewSet, PreviewError> {
    abr(bytes, opts, Take::FirstAvailable(n))
}

fn abr(bytes: &[u8], opts: PreviewOptions, take: Take) -> Result<PreviewSet, PreviewError> {
    let max_cell = check_max_cell(opts)?;

    let deferred =
        parse_abr_deferred_without_patterns(bytes).map_err(|e| PreviewError(e.to_string()))?;
    let pack = &deferred.pack;

    let mut rows: Vec<Row> = Vec::new();
    rows.extend(pack.brushes.iter().enumerate().map(|(i, brush)| Row {
        key: brush.preset_index.unwrap_or(usize::MAX),
        source: Source::Sampled(i),
    }));
    rows.extend(
        pack.computed_presets
            .iter()
            .enumerate()
            .map(|(i, preset)| Row {
                key: preset.preset_index.unwrap_or(usize::MAX),
                source: Source::Computed(i),
            }),
    );
    rows.extend(
        pack.unsupported_tip_presets
            .iter()
            .enumerate()
            .map(|(i, preset)| Row {
                key: preset.preset_index,
                source: Source::Unsupported(i),
            }),
    );

    rows.sort_by_key(|row| (row.key, row.source));

    let entries = rows
        .into_iter()
        .enumerate()
        .map(|(index, row)| abr_entry(&deferred, index, row.source, max_cell));

    Ok(PreviewSet {
        set_name: None,
        entries: take.collect(entries),
    })
}

/// Render one `.abr` row. A sampled tip is decoded and downsampled here, so
/// only the rows a caller takes are decoded.
fn abr_entry(deferred: &DeferredPack, index: usize, source: Source, max_cell: u32) -> PreviewEntry {
    #[cfg(test)]
    tests::record_entry();
    let pack = &deferred.pack;
    let (name, tip, source_dimensions) = match source {
        Source::Sampled(i) => {
            let brush = &pack.brushes[i];
            let name = if brush.name.is_empty() {
                brush.id.clone()
            } else {
                brush.name.clone()
            };
            let tip = match deferred.decode_tip(i) {
                Ok(tip) => TipPreview::Available(downsample(&to_grayscale(&tip), max_cell)),
                Err(e) => TipPreview::Unavailable(UnavailableReason::Corrupt(e.to_string())),
            };
            (
                name,
                tip,
                SourceDimensions::new(brush.tip.width, brush.tip.height),
            )
        }
        Source::Computed(i) => {
            let preset = &pack.computed_presets[i];
            let tip = match preset
                .descriptor
                .computed
                .as_ref()
                .filter(|geom| can_synthesize(geom))
                .and_then(synthesize_computed_tip)
            {
                Some(bitmap) => TipPreview::Available(downsample(&bitmap, max_cell)),
                None => TipPreview::Unavailable(UnavailableReason::UnsupportedTipKind(
                    "computed".to_string(),
                )),
            };
            (preset.name.clone(), tip, None)
        }
        Source::Unsupported(i) => {
            let preset = &pack.unsupported_tip_presets[i];
            let kind = match (&preset.tip_shape, &preset.shape_tip_family) {
                (Some(shape), _) => format!("{shape:?}"),
                (None, Some(ShapeTipFamily::Bristle)) => "bristle".to_string(),
                (None, Some(ShapeTipFamily::Erodible)) => "erodible".to_string(),
                (None, None) => "shape tip".to_string(),
            };
            (
                preset.name.clone(),
                TipPreview::Unavailable(UnavailableReason::UnsupportedTipKind(kind)),
                None,
            )
        }
    };
    PreviewEntry {
        index,
        name,
        tip,
        source_dimensions,
    }
}

/// Tips for a Procreate `.brushset`.
///
/// With a `brushset.plist` the set name and the member order come from it;
/// without one the members are the top-level directories that hold a
/// `Brush.archive`, in zip order, and the set has no name.
pub fn preview_brushset(bytes: &[u8], opts: PreviewOptions) -> Result<PreviewSet, PreviewError> {
    brushset(bytes, opts, Take::All)
}

/// The first `n` entries of [`preview_brushset`] whose tip is available, in
/// the same order and with the same `index` they have there, so indices may
/// skip. Unavailable entries do not count toward `n`, and members after the
/// `n`th available one are not read.
pub fn preview_brushset_first_available(
    bytes: &[u8],
    opts: PreviewOptions,
    n: usize,
) -> Result<PreviewSet, PreviewError> {
    brushset(bytes, opts, Take::FirstAvailable(n))
}

fn brushset(bytes: &[u8], opts: PreviewOptions, take: Take) -> Result<PreviewSet, PreviewError> {
    let max_cell = check_max_cell(opts)?;
    let mut zip = open_zip(bytes)?;

    let (set_name, prefixes) = if zip.by_name("brushset.plist").is_ok() {
        let buf = procreate::read_zip_entry(&mut zip, "brushset.plist").map_err(PreviewError)?;
        let (name, uuids) = procreate::parse_brushset_plist(&buf).map_err(PreviewError)?;
        (name, uuids.into_iter().map(|u| format!("{u}/")).collect())
    } else {
        let members: Vec<String> = procreate::members_in_zip_order(&mut zip)
            .into_iter()
            .map(|d| format!("{d}/"))
            .collect();
        if members.is_empty() {
            return Err(PreviewError("no brushes found".to_string()));
        }
        (None, members)
    };

    let entries = prefixes
        .iter()
        .enumerate()
        .map(|(index, prefix)| member_entry(&mut zip, index, prefix, max_cell));

    Ok(PreviewSet {
        set_name,
        entries: take.collect(entries),
    })
}

/// The tip of a single Procreate `.brush`: one entry at index 0, read from the
/// archive's root rather than from a member directory.
pub fn preview_brush(bytes: &[u8], opts: PreviewOptions) -> Result<PreviewSet, PreviewError> {
    brush(bytes, opts, Take::All)
}

/// [`preview_brush`] limited to available tips: its single entry when the tip
/// is available and `n >= 1`, otherwise no entries. With `n == 0` the tip is
/// not decoded.
pub fn preview_brush_first_available(
    bytes: &[u8],
    opts: PreviewOptions,
    n: usize,
) -> Result<PreviewSet, PreviewError> {
    brush(bytes, opts, Take::FirstAvailable(n))
}

fn brush(bytes: &[u8], opts: PreviewOptions, take: Take) -> Result<PreviewSet, PreviewError> {
    let max_cell = check_max_cell(opts)?;
    let mut zip = open_zip(bytes)?;

    if zip.by_name("Brush.archive").is_err() {
        return Err(PreviewError("Brush.archive not found".to_string()));
    }

    let entry = std::iter::once_with(|| member_entry(&mut zip, 0, "", max_cell));
    Ok(PreviewSet {
        set_name: None,
        entries: take.collect(entry),
    })
}

fn open_zip(bytes: &[u8]) -> Result<zip::ZipArchive<Cursor<&[u8]>>, PreviewError> {
    zip::ZipArchive::new(Cursor::new(bytes))
        .map_err(|e| PreviewError(format!("failed to open zip: {e}")))
}

/// One member of a Procreate archive. `prefix` is `"{uuid}/"` for a
/// `.brushset` member and `""` for a root-layout `.brush`.
///
/// A member is always an entry: an archive that cannot be read names the entry
/// after its directory and reports why, rather than shifting every index after
/// it. A readable `Shape.png` reports its size either way.
fn member_entry(
    zip: &mut zip::ZipArchive<Cursor<&[u8]>>,
    index: usize,
    prefix: &str,
    max_cell: u32,
) -> PreviewEntry {
    #[cfg(test)]
    tests::record_entry();
    let fallback_name = if prefix.is_empty() {
        "Brush".to_string()
    } else {
        prefix.trim_end_matches('/').to_string()
    };

    let archive = procreate::read_zip_entry(zip, &format!("{prefix}Brush.archive"))
        .and_then(|buf| procreate::brush_name(&buf));

    let shape_path = format!("{prefix}Shape.png");
    let shape = if zip.by_name(&shape_path).is_ok() {
        Some(procreate::read_zip_entry(zip, &shape_path))
    } else {
        None
    };
    let source_dimensions = match &shape {
        Some(Ok(png)) => procreate::header_dimensions(png)
            .and_then(|(width, height)| SourceDimensions::new(width, height)),
        _ => None,
    };

    let (name, tip) = match archive {
        Ok(name) => (name.unwrap_or(fallback_name), shape_tip(shape, max_cell)),
        Err(msg) => (
            fallback_name,
            TipPreview::Unavailable(UnavailableReason::Corrupt(msg)),
        ),
    };

    PreviewEntry {
        index,
        name,
        tip,
        source_dimensions,
    }
}

/// The tip for a member's `Shape.png`: `None` when the member has no shape,
/// otherwise the read result.
fn shape_tip(shape: Option<Result<Vec<u8>, String>>, max_cell: u32) -> TipPreview {
    let png = match shape {
        None => return TipPreview::Unavailable(UnavailableReason::NoShapePng),
        Some(Err(msg)) => return TipPreview::Unavailable(UnavailableReason::Corrupt(msg)),
        Some(Ok(png)) => png,
    };
    match procreate::decode_tip_png(&png) {
        Ok(bitmap) => TipPreview::Available(downsample(&bitmap, max_cell)),
        Err(procreate::ShapePngError::TooLarge { width, height }) => {
            TipPreview::Unavailable(UnavailableReason::TooLarge { width, height })
        }
        Err(procreate::ShapePngError::Corrupt(msg)) => {
            TipPreview::Unavailable(UnavailableReason::Corrupt(msg))
        }
    }
}

// The integration tests' fixture builders, shared with the unit tests below.
#[cfg(test)]
#[path = "../tests/common/mod.rs"]
mod common;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::{brush_archive, brushset_plist, gray_png, samp_abr, zip_with, SampTip};
    use std::cell::Cell;

    thread_local! {
        // Thread-local because cargo runs unit tests on parallel threads.
        static ENTRIES: Cell<usize> = const { Cell::new(0) };
    }

    /// Called once per entry built, before any of its tip is read or decoded.
    pub(super) fn record_entry() {
        ENTRIES.with(|count| count.set(count.get() + 1));
    }

    /// Entries built by `f` on this thread.
    fn entries_built<T>(f: impl FnOnce() -> T) -> usize {
        ENTRIES.with(|count| count.set(0));
        f();
        ENTRIES.with(Cell::get)
    }

    const OPTS: PreviewOptions = PreviewOptions { max_cell: 8 };

    fn tip(corrupt: bool) -> SampTip {
        SampTip {
            width: 4,
            height: 4,
            fill: 0x80,
            corrupt,
        }
    }

    #[test]
    fn abr_builds_only_the_entries_it_returns() {
        let bytes = samp_abr(&[
            tip(false),
            tip(false),
            tip(false),
            tip(false),
            tip(false),
            tip(false),
        ]);
        assert_eq!(
            entries_built(|| preview_abr_first_available(&bytes, OPTS, 2).unwrap()),
            2
        );
        assert_eq!(
            entries_built(|| preview_abr_first_available(&bytes, OPTS, 0).unwrap()),
            0
        );
        assert_eq!(entries_built(|| preview_abr(&bytes, OPTS).unwrap()), 6);
    }

    #[test]
    fn abr_failed_decode_does_not_count_toward_n() {
        let bytes = samp_abr(&[tip(false), tip(false), tip(true)]);
        assert!(matches!(
            preview_abr(&bytes, OPTS).unwrap().entries[0].tip,
            TipPreview::Unavailable(UnavailableReason::Corrupt(_))
        ));
        let mut set = None;
        assert_eq!(
            entries_built(|| set = Some(preview_abr_first_available(&bytes, OPTS, 1).unwrap())),
            2
        );
        let entries = set.unwrap().entries;
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].index, 1);
    }

    #[test]
    fn brushset_reads_only_the_members_it_returns() {
        let archive = brush_archive("Tip");
        let shape = gray_png(4, 4, 200);
        let plist = brushset_plist("Set", &["a", "b", "c", "d"]);
        let mut files: Vec<(String, &[u8])> = vec![("brushset.plist".into(), &plist)];
        for member in ["a", "b", "c", "d"] {
            files.push((format!("{member}/Brush.archive"), &archive));
            files.push((format!("{member}/Shape.png"), &shape));
        }
        let files: Vec<(&str, &[u8])> = files.iter().map(|(p, b)| (p.as_str(), *b)).collect();
        let bytes = zip_with(&files);
        assert_eq!(
            entries_built(|| preview_brushset_first_available(&bytes, OPTS, 1).unwrap()),
            1
        );
        assert_eq!(entries_built(|| preview_brushset(&bytes, OPTS).unwrap()), 4);
    }
}