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
extern crate ico;

use crate::{Icon, SourceImage, Entry, Error, STD_CAPACITY};
use std::{result, io::{self, Write}, fmt::{self, Debug, Formatter}};
use image::{DynamicImage, GenericImageView};

const MIN_ICO_SIZE: u32 = 1;
const MAX_ICO_SIZE: u32 = 256;

/// A collection of entries stored in a single `.ico` file.
#[derive(Clone)]
pub struct Ico {
    icon_dir: ico::IconDir,
    entries: Vec<u32>
}

impl Icon<Entry> for Ico {
    fn new() -> Self {
        Ico {
            icon_dir: ico::IconDir::new(ico::ResourceType::Icon),
            entries: Vec::with_capacity(STD_CAPACITY)
        }
    }

    fn add_entry<F: FnMut(&SourceImage, u32) -> DynamicImage>(
        &mut self,
        mut filter: F,
        source: &SourceImage,
        entry: Entry
    ) -> Result<(), Error<Entry>> {
        if entry.0 < MIN_ICO_SIZE || entry.0 > MAX_ICO_SIZE {
            return Err(Error::InvalidSize(entry.0));
        }

        if self.entries.contains(&entry.0) {
            return Err(Error::AlreadyIncluded(entry));
        }

        let icon = filter(source, entry.0);
        let (icon_w, icon_h) = icon.dimensions();
        if icon_w != entry.0 || icon_h != entry.0 {
            return Err(Error::InvalidDimensions(entry.0, (icon_w, icon_h)));
        }

        let size = icon.width();
        let data = icon.to_rgba().into_vec();
        let image = ico::IconImage::from_rgba_data(size, size, data);

        let entry = ico::IconDirEntry::encode(&image)?;
        self.icon_dir.add_entry(entry);

        Ok(())
    }

    fn write<W: Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.icon_dir.write(w)
    }
}

impl Debug for Ico {
    fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> {
        let n_entries = self.icon_dir.entries().len();
        let mut entries_str = String::with_capacity(42 * n_entries);

        for _ in 0..n_entries {
            entries_str.push_str("ico::IconDirEntry {{ /* fields omitted */ }}, ");
        }

        let icon_dir= format!(
            "ico::IconDir {{ restype: ico::ResourceType::Icon, entries: [{:?}] }}",
            entries_str
        );

        write!(f, "iconwriter::Ico {{ icon_dir: {} }} ", icon_dir)
    }
}