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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
use super::arithmetic::{ops::CheckedSub, Round};
use super::img::{self, Image};
use super::types::{self, Point, Rect, Size};
use super::{arithmetic, debug, error, imageops};
use std::cmp::Ordering;
use std::path::PathBuf;

#[derive(Clone, Copy, Debug)]
pub struct Options {
    pub transparent_component_threshold: u32,
    pub alpha_threshold: f64,
}

impl Default for Options {
    #[inline]
    fn default() -> Self {
        Self {
            transparent_component_threshold: 8,
            alpha_threshold: 0.95,
        }
    }
}

pub enum Kind {
    #[cfg(feature = "builtin")]
    Builtin(super::builtin::Builtin),
    Custom(Border),
}

impl From<Border> for Kind {
    fn from(border: Border) -> Self {
        Kind::Custom(border)
    }
}
impl From<Border> for Option<Kind> {
    fn from(border: Border) -> Self {
        Some(Kind::Custom(border))
    }
}

#[cfg(feature = "builtin")]
impl From<super::builtin::Builtin> for Kind {
    fn from(builtin: super::builtin::Builtin) -> Self {
        Kind::Builtin(builtin)
    }
}

#[cfg(feature = "builtin")]
impl From<super::builtin::Builtin> for Option<Kind> {
    fn from(builtin: super::builtin::Builtin) -> Self {
        Some(Kind::Builtin(builtin))
    }
}

impl Kind {
    #[inline]
    pub fn into_border(self) -> Result<Border, Error> {
        match self {
            #[cfg(feature = "builtin")]
            Self::Builtin(builtin) => builtin.into_border(),
            Self::Custom(border) => Ok(border),
        }
    }
}

impl std::fmt::Debug for Kind {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            #[cfg(feature = "builtin")]
            Kind::Builtin(builtin) => write!(f, "Builtin({:?})", builtin),
            Kind::Custom(_) => write!(f, "Custom"),
        }
    }
}

#[derive(Clone)]
pub struct Border {
    inner: Image,
    options: Option<Options>,
    transparent_components: Vec<Rect>,
}

impl std::ops::Deref for Border {
    type Target = Image;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl std::ops::DerefMut for Border {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl Border {
    #[inline]
    pub fn from_reader<R: std::io::BufRead + std::io::Seek>(
        reader: R,
        options: Option<Options>,
    ) -> Result<Self, Error> {
        let image = Image::from_reader(reader).map_err(img::Error::from)?;
        Self::from_image(image, options).map_err(Error::from)
    }

    #[inline]
    pub fn open(path: impl Into<PathBuf>, options: Option<Options>) -> Result<Self, Error> {
        let image = Image::open(path.into()).map_err(img::Error::from)?;
        Self::from_image(image, options).map_err(Error::from)
    }

    #[inline]
    pub fn from_image(
        inner: Image,
        options: Option<Options>,
    ) -> Result<Self, TransparentComponentsError> {
        let mut border = Self {
            inner,
            options,
            transparent_components: Vec::new(),
        };
        border.compute_transparent_components(options)?;
        Ok(border)
    }

    #[inline]
    pub fn custom(
        mut border: Self,
        content_size: Size,
        stich_direction: Option<types::Orientation>,
    ) -> Result<Self, Error> {
        use arithmetic::{
            ops::{CheckedAdd, CheckedDiv, CheckedMul},
            Cast,
        };

        let components = border.transparent_components().clone();
        if components.len() != 1 {
            return Err(Error::Invalid(InvalidTransparentComponentsError {
                required: (Ordering::Equal, 1),
                components,
            }));
        }
        // by default, use the longer dimension to stich
        let stich_direction = stich_direction.unwrap_or(types::Orientation::Portrait);
        border.rotate_to_orientation(stich_direction)?;
        let original_orientation = content_size.orientation();
        let content_size = content_size.rotate_to_orientation(stich_direction);
        debug!(&content_size);

        let border_size = border.size_for(types::BoundedSize {
            width: Some(content_size.width),
            height: None,
        })?;
        debug!(&border_size);
        border.resize_and_crop(border_size, types::ResizeMode::Cover)?;

        // border is portrait now, we stich vertically
        // todo: find optimal overlay patches somehow
        let (top_patch_rect, _) =
            compute_patch_rect(border_size, 0.0, 0.25).map_err(|err| error::Arithmetic {
                msg: "failed to compute top patch".into(),
                source: err,
            })?;

        let (bottom_patch_rect, bottom_patch_size) = compute_patch_rect(border_size, 0.75, 1.0)
            .map_err(|err| error::Arithmetic {
                msg: "failed to compute bottom patch".into(),
                source: err,
            })?;

        let (_, overlay_patch_size) =
            compute_patch_rect(border_size, 0.3, 0.7).map_err(|err| error::Arithmetic {
                msg: "failed to compute overlay patch rect".into(),
                source: err,
            })?;

        // create buffer for the new border
        let border_content_size = border.content_size()?;
        debug!(&border_content_size);

        let border_padding = border_size
            .checked_sub(border_content_size)
            .map_err(|err| error::Arithmetic {
                msg: "failed to compute border padding".to_string(),
                source: err.into(),
            })?;
        debug!(&border_padding);

        let new_border_size =
            content_size
                .checked_add(border_padding)
                .map_err(|err| error::Arithmetic {
                    msg: "failed to compute new border size".to_string(),
                    source: err.into(),
                })?;

        let mut new_border = Image::with_size(new_border_size);
        debug!(&new_border.size());

        #[cfg(feature = "debug")]
        {
            let green = types::Color::rgba(0, 255, 0, 255);
            let clear = types::Color::clear();
            new_border
                .fill(green, imageops::FillMode::Set)
                .map_err(img::Error::from)?;

            let content_rect = border.content_rect()?;
            debug!(&content_rect);

            let new_border_content_rect = (|| {
                let bottom_right_padding =
                    Point::from(border.size()).checked_sub(content_rect.bottom_right())?;
                let new_border_content_rect_bottom_right =
                    Point::from(new_border_size).checked_sub(bottom_right_padding)?;

                let rect = Rect::from_points(
                    content_rect.top_left(),
                    new_border_content_rect_bottom_right,
                );
                Ok::<_, arithmetic::Error>(rect)
            })();
            let new_border_content_rect =
                new_border_content_rect.map_err(|err| error::Arithmetic {
                    msg: "failed to compute new border content rect".into(),
                    source: err,
                })?;

            new_border
                .fill_rect(clear, &new_border_content_rect, imageops::FillMode::Set)
                .map_err(img::Error::from)?;
        }

        // draw top patch
        let mut border_top: Image = border.inner.clone();
        #[cfg(feature = "debug")]
        border_top
            .clip_alpha(&border_top.size().into(), 0, 200)
            .map_err(img::Error::from)?;
        border_top
            .crop(&top_patch_rect)
            .map_err(img::CropError::from)
            .map_err(img::Error::from)?;

        new_border.overlay(&border_top, Point::origin());

        // draw bottom patch
        let mut border_bottom = border.inner.clone();
        #[cfg(feature = "debug")]
        border_bottom
            .clip_alpha(&border_bottom.size().into(), 0, 200)
            .map_err(img::Error::from)?;
        border_bottom
            .crop(&bottom_patch_rect)
            .map_err(img::CropError::from)
            .map_err(img::Error::from)?;

        let bottom_patch_top_left = Point::from(new_border_size)
            .checked_sub(bottom_patch_size.into())
            .map_err(|err| error::Arithmetic {
                msg: "failed to compute bottom patch top left".to_string(),
                source: err.into(),
            })?;
        new_border.overlay(&border_bottom, bottom_patch_top_left);

        // draw patches in between
        let fill_height = (|| {
            let mut height = i64::from(new_border_size.height);
            height = CheckedSub::checked_sub(height, bottom_patch_rect.height())?;
            height = CheckedSub::checked_sub(height, top_patch_rect.height())?;
            let height = height.cast::<u32>()?;
            Ok::<_, arithmetic::Error>(height)
        })();
        let fill_height: u32 = fill_height.map_err(|err| error::Arithmetic {
            msg: "failed to compute fill height".to_string(),
            source: err,
        })?;
        debug!(&fill_height);
        debug!(&overlay_patch_size.height);

        let fade_height = (|| {
            let height = f64::from(overlay_patch_size.height)
                .checked_mul(0.2)?
                .ceil()
                .cast::<u32>()?;
            Ok::<_, arithmetic::Error>(height)
        })();
        let fade_height = fade_height.map_err(|err| error::Arithmetic {
            msg: "failed to compute fade height".to_string(),
            source: err,
        })?;
        debug!(&fade_height);

        let safe_patch_height = (|| {
            let total_fade_height = CheckedMul::checked_mul(fade_height, 2)?;
            let height = CheckedSub::checked_sub(overlay_patch_size.height, total_fade_height)?;
            Ok::<_, arithmetic::Error>(height)
        })();
        let safe_patch_height = safe_patch_height.map_err(|err| error::Arithmetic {
            msg: "failed to compute safe patch height".to_string(),
            source: err,
        })?;
        debug!(&safe_patch_height);

        let num_patches = (|| {
            let patches = f64::from(fill_height)
                .checked_div(f64::from(safe_patch_height))?
                .ceil()
                .cast::<u32>()?;
            Ok::<_, arithmetic::Error>(patches)
        })();
        let num_patches = num_patches.map_err(|err| error::Arithmetic {
            msg: "failed to compute number of patches".to_string(),
            source: err,
        })?;
        debug!(&num_patches);

        let new_safe_patch_height = (|| {
            let height = f64::from(fill_height)
                .checked_div(f64::from(num_patches))?
                .ceil()
                .cast::<u32>()?;
            Ok::<_, arithmetic::Error>(height)
        })();
        let new_safe_patch_height = new_safe_patch_height.map_err(|err| error::Arithmetic {
            msg: "failed to compute new safe patch height".to_string(),
            source: err,
        })?;
        debug!(&new_safe_patch_height);

        let patch_height = (|| {
            let total_fade_height = CheckedMul::checked_mul(fade_height, 2)?;
            let height = CheckedAdd::checked_add(new_safe_patch_height, total_fade_height)?;
            Ok::<_, arithmetic::Error>(height)
        })();
        let patch_height = patch_height.map_err(|err| error::Arithmetic {
            msg: "failed to compute patch height".to_string(),
            source: err,
        })?;
        debug!(&patch_height);

        let patch_size = Size {
            width: overlay_patch_size.width,
            height: patch_height,
        };

        for i in 0..num_patches {
            let patch_top_left = (|| {
                let mut patch_offset_y =
                    CheckedMul::checked_mul(i64::from(i), i64::from(new_safe_patch_height))?;
                patch_offset_y = CheckedSub::checked_sub(patch_offset_y, i64::from(fade_height))?;

                let top_left = top_patch_rect.bottom_left().checked_add(Point {
                    x: 0,
                    y: patch_offset_y,
                })?;
                Ok::<_, arithmetic::Error>(top_left)
            })();

            let patch_top_left = patch_top_left.map_err(|err| error::Arithmetic {
                msg: "failed to compute patch top left".to_string(),
                source: err,
            })?;

            overlay_and_fade_patch(
                &mut new_border,
                border.inner.clone(),
                patch_top_left,
                patch_size,
                fade_height,
            )?;
        }

        let mut new_border = Self::from_image(new_border, border.options)?;
        new_border.rotate_to_orientation(original_orientation)?;
        Ok(new_border)
    }

    #[inline]
    fn compute_transparent_components(
        &mut self,
        options: Option<Options>,
    ) -> Result<(), TransparentComponentsError> {
        let options = options.unwrap_or_default();
        self.transparent_components = imageops::find_transparent_components(
            &self.inner,
            options.alpha_threshold,
            options.transparent_component_threshold,
        )?;

        if self.transparent_components.is_empty() {
            return Err(TransparentComponentsError::Invalid(
                InvalidTransparentComponentsError {
                    required: (Ordering::Greater, 0),
                    components: self.transparent_components.clone(),
                },
            ));
        }
        self.transparent_components
            .sort_by_key(|b| std::cmp::Reverse(b.pixel_count().unwrap_or(0)));
        Ok(())
    }

    #[inline]
    pub fn resize_and_crop(
        &mut self,
        container: Size,
        resize_mode: types::ResizeMode,
    ) -> Result<(), Error> {
        let crop_mode = super::CropMode::Center;
        self.inner
            .resize_and_crop(container, resize_mode, crop_mode)
            .map_err(img::Error::from)?;
        self.compute_transparent_components(self.options)?;
        Ok(())
    }

    #[inline]
    pub fn rotate(&mut self, angle: &types::Rotation) -> Result<(), Error> {
        self.inner.rotate(angle);
        self.compute_transparent_components(self.options)?;
        Ok(())
    }

    #[inline]
    pub fn rotate_to_orientation(&mut self, orientation: types::Orientation) -> Result<(), Error> {
        self.inner.rotate_to_orientation(orientation);
        self.compute_transparent_components(self.options)?;
        Ok(())
    }

    #[inline]
    pub fn content_rect(&self) -> Result<&Rect, TransparentComponentsError> {
        self.transparent_components.first().ok_or_else(|| {
            TransparentComponentsError::Invalid(InvalidTransparentComponentsError {
                required: (Ordering::Greater, 0),
                components: self.transparent_components.clone(),
            })
        })
    }

    #[inline]
    pub fn content_size(&self) -> Result<Size, Error> {
        let rect = self.content_rect()?;
        let size = rect.size().map_err(|err| error::Arithmetic {
            msg: "failed to compute size of content rect".to_string(),
            source: err.into(),
        })?;
        Ok(size)
    }

    #[inline]
    pub fn size_for(
        &self,
        target_content_size: impl Into<types::BoundedSize>,
    ) -> Result<Size, Error> {
        use types::ResizeMode;

        let border_content_size = self.content_size()?;
        let target_content_size = target_content_size.into();
        debug!(&self.size());
        debug!(&border_content_size);
        debug!(&target_content_size);

        // scale down if larger than target content size
        let contain_content_size = border_content_size
            .scale_to_bounds(target_content_size, ResizeMode::Contain)
            .map_err(|err| error::Arithmetic {
                msg: "failed to scale border content size".into(),
                source: err.into(),
            })?;
        debug!(&contain_content_size);

        // scale up as little as possible to cover target content size
        let cover_content_size = contain_content_size
            .scale_to_bounds(target_content_size, ResizeMode::Cover)
            .map_err(|err| error::Arithmetic {
                msg: "failed to scale border content size".into(),
                source: err.into(),
            })?;
        debug!(&cover_content_size);

        let border_scale_factor = border_content_size
            .scale_factor(cover_content_size, ResizeMode::Cover)
            .map_err(|err| error::Arithmetic {
                msg: "failed to compute scale factor for border".into(),
                source: err.into(),
            })?;

        debug!(&border_scale_factor);

        let scaled_border_size = self
            .size()
            .scale_by::<_, Round>(border_scale_factor.0)
            .map_err(|err| error::Arithmetic {
                msg: "failed to compute scaled border size".into(),
                source: err.into(),
            })?;

        debug!(&scaled_border_size);
        Ok(scaled_border_size)
    }

    #[inline]
    #[must_use]
    pub fn transparent_components(&self) -> &Vec<Rect> {
        &self.transparent_components
    }
}

fn compute_patch_rect(
    size: Size,
    top_percent: f64,
    bottom_percent: f64,
) -> Result<(Rect, Size), arithmetic::Error> {
    use arithmetic::{ops::CheckedMul, Cast};

    let top_left = Point {
        x: 0,
        y: f64::from(size.height)
            .checked_mul(top_percent)?
            .cast::<i64>()?,
    };
    let bottom_right = Point {
        x: i64::from(size.width),
        y: f64::from(size.height)
            .checked_mul(bottom_percent)?
            .cast::<i64>()?,
    };
    let rect = Rect::from_points(top_left, bottom_right);
    let size = rect.size()?;
    Ok((rect, size))
}

fn overlay_and_fade_patch(
    image: &mut img::Image,
    mut patch: img::Image,
    top_left: Point,
    patch_size: Size,
    fade_height: u32,
) -> Result<(), Error> {
    patch
        .crop_to_fit(patch_size, types::CropMode::Center)
        .map_err(img::CropError::from)
        .map_err(img::Error::from)?;

    #[cfg(feature = "debug")]
    patch
        .clip_alpha(&patch.size().into(), 0, 200)
        .map_err(img::Error::from)?;

    let axis = types::Axis::Y;
    // fade out to top
    let fade_start = Point {
        x: i64::from(patch_size.width),
        y: i64::from(fade_height),
    };
    let fade_end = Point::origin();
    patch
        .fade_out(fade_start, fade_end, axis)
        .map_err(img::Error::from)?;

    // fade out to bottom
    let fade_start = Point::from(patch_size)
        .checked_sub(fade_start)
        .map_err(|err| error::Arithmetic {
            msg: "failed to compute fade start point for bottom patch".into(),
            source: err.into(),
        })?;

    let fade_end = Point::from(patch_size);
    patch
        .fade_out(fade_start, fade_end, axis)
        .map_err(img::Error::from)?;
    image.overlay(&patch, top_left);
    Ok(())
}

#[derive(thiserror::Error, PartialEq, Clone, Debug)]
pub enum TransparentComponentsError {
    #[error(transparent)]
    TransparentComponents(#[from] imageops::TransparentComponentsError),

    #[error("invalid transparent components")]
    Invalid(
        #[from]
        #[source]
        InvalidTransparentComponentsError,
    ),
}

#[derive(thiserror::Error, PartialEq, Eq, Clone, Debug)]
pub struct InvalidTransparentComponentsError {
    required: (Ordering, usize),
    components: Vec<Rect>,
}

impl std::fmt::Display for InvalidTransparentComponentsError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let (predicate, required) = self.required;
        let (predicate_string, required) = match predicate {
            Ordering::Less => ("at most", required - 1),
            Ordering::Equal => ("exactly", required),
            Ordering::Greater => ("at least", required + 1),
        };
        write!(
            f,
            "have {} components ({:?}), but {} {} are required",
            self.components.len(),
            self.components,
            predicate_string,
            required
        )
    }
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("missing border")]
    Missing,

    #[error("invalid transparent components")]
    Invalid(
        #[from]
        #[source]
        InvalidTransparentComponentsError,
    ),

    #[error(transparent)]
    TransparentComponents(#[from] TransparentComponentsError),

    #[error(transparent)]
    Image(#[from] img::Error),

    #[error(transparent)]
    Arithmetic(#[from] error::Arithmetic),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{img::Image, types};
    use anyhow::Result;
    use std::path::{Path, PathBuf};

    fn draw_transparent_components(
        mut border: Image,
        components: &Vec<types::Rect>,
        output: impl AsRef<Path>,
    ) -> Result<()> {
        use imageops::FillMode;

        let red = types::Color::rgba(255, 0, 0, 125);
        for c in components {
            let top_left = Point {
                y: c.top,
                x: c.left,
            };
            let bottom_right = Point {
                y: c.bottom,
                x: c.right,
            };
            border.fill_rect(
                red,
                &Rect::from_points(top_left, bottom_right),
                FillMode::Blend,
            )?;
        }
        border.save_with_filename(output.as_ref(), None)?;
        Ok(())
    }

    macro_rules! transparent_areas_tests {
        ($($name:ident: $values:expr,)*) => {
            $(
                #[test]
                fn $name() -> Result<()> {
                    let (border_path, expected_components) = $values;
                    let repo: PathBuf = env!("CARGO_MANIFEST_DIR").into();
                    let border_file = repo.join(&border_path);
                    let options = Options::default();
                    let img = Image::open(&border_file)?;
                    let border = Border::from_image(img.clone(), Some(options));
                    let components = match border {
                        Err(TransparentComponentsError::Invalid(InvalidTransparentComponentsError { components, .. })) => Ok(components),
                        Err(err) => Err(err),
                        Ok(border) => {
                            Ok(border.transparent_components().to_vec())
                        }
                    }?;

                    // debug components
                    let output = repo.join(
                        format!("testing/{}.png", stringify!($name)));
                    draw_transparent_components(img, &components, &output)?;
                    println!("components: {:?}", components);

                    assert_eq!(components.len(), expected_components);
                    Ok(())
                }
            )*
        }
    }

    transparent_areas_tests! {
        test_transparent_areas_3_vertical: (
            "samples/borders/border_3_areas_vertical.png", 3),
        test_transparent_areas_3_horizontal: (
            "samples/borders/border_3_areas_horizontal.png", 3),
        test_transparent_areas_1_vertical: (
            "samples/borders/border_1_areas_vertical.png", 1),
        test_transparent_areas_1_horizontal: (
            "samples/borders/border_1_areas_horizontal.png", 1),
    }

    #[test]
    fn test_transparent_areas_3_rotate() -> Result<()> {
        use types::Rotation;

        let repo: PathBuf = env!("CARGO_MANIFEST_DIR").into();
        let border_file = repo.join("samples/borders/border_3_areas_vertical.png");
        let options = Options {
            transparent_component_threshold: 8,
            alpha_threshold: 0.95,
        };
        let img = Image::open(&border_file)?;
        let border = Border::from_image(img, Some(options))?;

        for rotation in &[
            Rotation::Rotate0,
            Rotation::Rotate90,
            Rotation::Rotate180,
            Rotation::Rotate270,
        ] {
            let mut rotated = border.clone();
            rotated.rotate(rotation)?;
            let output = repo.join(format!(
                "testing/border_3_areas_vertical_{:?}.png",
                rotation
            ));
            let components = rotated.transparent_components().clone();
            println!("sorted components: {:?}", &components);
            draw_transparent_components(rotated.inner, &components, &output)?;
            assert_eq!(components.len(), 3);
        }
        Ok(())
    }
}