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
pub use ikon::{encode::{Encode, Save, EncodingError}, Image};
use ikon::{image::DynamicImage, AsSize};
use std::{
    io::{self, BufWriter, Write}, 
    path::{Path, PathBuf},
    fs::{self, File, DirBuilder}, 
    fmt::{self, Display, Formatter},
    collections::HashMap
};

/// A collection of commonly used resampling filters.
pub mod resample {
    pub use ikon::resample::{ResampleError, cubic, linear, nearest};
}

#[cfg(test)]
mod test;

/// The maximum size for an icon.
const MAX_SIZE: u32 = std::u16::MAX as u32 + 1;

macro_rules! path_buf {
    ($path:expr) => (PathBuf::from($path));
    ($($x:expr),*) => (PathBuf::from(format!($($x),*)));
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// A comprehensive Freedesktop Icon Theme encoder.
pub struct IconTheme {
    name: String,
    comment: String,
    icons: HashMap<Dir, HashMap<String, ImageBuffer>>
}

impl IconTheme {
    /// Creates a new, empty `IconTheme`.
    pub fn new(name: String, comment: String) -> Self {
        Self::with_capacity(name, comment, 0)
    }

    /// Creates a new `IconTheme`, allocating space for `capacity` icons.
    pub fn with_capacity(
        name: String, 
        comment: String, 
        capacity: usize
    ) -> Self {
        Self { name, comment, icons: HashMap::with_capacity(capacity) }
    }
}

impl Encode for IconTheme {
    type Key = Icon;

    #[inline]
    fn len(&self) -> usize {
        self.icons.len()
    }

    fn add_entry<
        F: FnMut(&DynamicImage, (u32, u32)) -> io::Result<DynamicImage>
    >(
        &mut self,
        filter: F,
        source: &Image,
        key: Icon
    ) -> Result<&mut Self, EncodingError<Icon>> {
        // TODO: Preallocate the default value of `self.icons.entry(key.dir)`.
        let dir = self.icons.entry(key.dir).or_insert(HashMap::new());

        if let None = dir.get(&key.name) {
            match source {
                Image::Raster(img) => {
                    let (x, y) = key.as_size();
                    let img = ikon::resample::apply(filter, img, (x, y))?;
                    
                    // TODO: Preallocate this properly.
                    let mut buff = Vec::with_capacity(x as usize * y as usize);

                    ikon::encode::png(&img, &mut buff)?;
                    let _ = dir.insert(key.name, ImageBuffer::Png(buff));
                },
                Image::Svg(svg) => {
                    // TODO: Preallocate this buffer.
                    let mut buff = Vec::new();
                    
                    ikon::encode::svg(svg, &mut buff)?;
                    let _ = dir.insert(key.name, ImageBuffer::Svg(buff));
                }
            }

            Ok(self)
        } else {
            Err(EncodingError::AlreadyIncluded(key))
        }
    }
}

impl Save for IconTheme {
    fn save<P: AsRef<Path>>(&mut self, path: &P) -> io::Result<&mut Self> {
        let mut builder = DirBuilder::new();
        builder.recursive(true);

        if !path.as_ref().exists() {
            builder.create(&path)?;
        }

        let mut index = BufWriter::new(
            File::create(path.as_ref().join("index.theme"))?
        );
        
        write!(
            &mut index, 
            "[Icon Theme]\nName={}\nComment={}\nDirectories=",
            self.name, self.comment
        )?;
       
        // Gegister all direcotories in the `Directories`field.
        let mut dirs = self.icons.keys();

        if let Some(first) = dirs.next() {
            write!(&mut index, "{}", first.path().display())?;

            while let Some(dir) = dirs.next() {
                write!(&mut index, ",{}", dir.path().display())?;
            }
        }

        write!(&mut index, "\n\n")?;

        // Write the information to the sub folders.
        for (dir, names) in &self.icons {
            let dir_path = dir.path();
            
            write!(
                &mut index, 
                "[{}]\nContext={}\n", 
                dir_path.display(), 
                dir.context
            )?;
            
            dir.size.write(&mut index)?;
            
            if dir.scale != 1 {
                write!(&mut index, "Scale={}\n", dir.scale)?;
            }

            write!(&mut index, "\n")?;
            
            for (name, buff) in names {
                let absolute_dir_path = path.as_ref().join(&dir_path);
                
                if !absolute_dir_path.exists() {
                    builder.create(&absolute_dir_path)?;
                }

                match buff {
                    ImageBuffer::Png(raw) => {
                        fs::write(
                            absolute_dir_path.join(format!("{}.png", name)), 
                            raw
                        )?;
                    },
                    ImageBuffer::Svg(raw) => {
                        fs::write(
                            absolute_dir_path.join(format!("{}.svg", name)), 
                            raw
                        )?;
                    }
                }

            }
        }

        Ok(self)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
/// Matadata about a particular icon in a `IconTheme`.
pub struct Icon {
    pub name: String,
    pub(crate) dir: Dir
}

impl Icon {
    #[inline]
    /// Application icons.
    pub fn application(name: String, size: Size, scale: usize) -> Self {
        Self { 
            name, 
            dir: Dir { size, scale, context: Context::Apps } 
        } 
    }
    
    #[inline]
    /// Icons representing MIME types.
    pub fn mime_type(name: String, size: Size, scale: usize) -> Self {
        Self { 
            name, 
            dir: Dir { size, scale, context: Context::Apps } 
        } 
    }
}

impl AsSize for Icon {
    #[inline]
    fn as_size(&self) -> (u32, u32) {
        let size = match self.dir.size {
            Size::Fixed(size) => size,
            Size::Scalable { size, .. } => size,
            Size::Threshold(size, _) => size
        };
        
        let size = size_to_u32(size);
        (size, size)
    }
}

/// A Directory entry.
#[derive(Copy, Clone, Debug, Hash)]
struct Dir {
    pub(crate) size: Size,
    pub(crate) context: Context,
    pub(crate) scale: usize
}

impl Dir {
    /// Returns the path to such directory.
    pub(crate) fn path(&self) -> PathBuf {
        let c = self.context.path();

        match self.size {
            Size::Fixed(size) if self.scale == 1 => {
                path_buf!("{0}x{0}/{1}", size, c)
            },
            Size::Fixed(size) => {
                path_buf!("{0}x{0}@{1}/{2}", size, self.scale, c)
            },
            Size::Scalable { .. } => path_buf!("scalable/{0}", c),
            Size::Threshold(_size, _t) => todo!()
        }
    }
}

impl PartialEq for Dir {
    fn eq(&self, other: &Self) -> bool {
        self.size == other.size
    }
}

impl Eq for Dir {}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
/// The dimensions of an `Icon`.
pub enum Size {
    /// A fixed size `Icon`.
    Fixed(u16),
    /// A scalable `Icon`, ranging between `max` and `min` pixels.
    Scalable { size: u16, max: u16, min: u16},
    /// An `Icon` whose size differ at most this much from the desired 
    /// (unscaled) size.
    Threshold(u16, i16)
}

impl Size {
    /// Helper function for formatting `index.theme`.
    pub(crate) fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
        match self {
            Self::Fixed(size) => {
                write!(w, "Size={}\nType=Fixed\n", size_to_u32(*size))
            },
            Self::Scalable { size, min, max, .. } => {
                write!(
                    w, 
                    "Size={}\nMinSize={}\nMaxSize={}\nType=Scalable\n",
                    size_to_u32(*size), min, max
                )
            },
            Self::Threshold(size, t) => {
                write!(w, "Size={}\nType=Threshold\n", size_to_u32(*size))?;

                if *t != 2 {
                    write!(w, "Threshold={}\n", t)?;
                }

                Ok(())
            }
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
/// The `Context` allows the designer to group icons on a conceptual level. It 
/// doesn't act as a namespace in the file system, such that icons can have 
/// identical names, but allows implementations to categorize and sort by it.
enum Context {
    /// Application icons.
    Apps,
    /// Icons representing MIME types.
    MimeTypes
}

impl Context {
    pub(crate) fn path(&self) -> &'static str {
        match self {
            Self::Apps => "apps",
            Self::MimeTypes => "mime_types"
        }
    }
}

impl Display for Context {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Self::Apps => write!(f, "Applications"),
            Self::MimeTypes => write!(f, "MimeTypes")
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
/// A compressed image buffer.
enum ImageBuffer {
    Png(Vec<u8>),
    Svg(Vec<u8>)
}

#[inline]
/// Helper function to convert from Size to regular pixel units.
fn size_to_u32(size: u16) -> u32 {
    if size == 0 {
        MAX_SIZE
    } else {
        size as u32
    }
}