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
use winapi::um::winnt::HANDLE;
use winapi::um::winuser::IMAGE_BITMAP;
use crate::win32::resources_helper as rh;
use crate::{OemBitmap, OemImage, NwgError};
use std::ptr;

#[cfg(feature = "embed-resource")]
use super::EmbedResource;

/** 
A wrapper over a bitmap file (*.bmp)

Note that Bitmap object are only used as display resources (ie: it's impossible to read pixels or resized it).
If those features are needed, see the `image-decoder` feature.

To display a bitmap in an application, see the `ImageFrame` control.

By default, bitmap resources do not support transparency BUT if `image-decoder` is enabled, bitmaps can be loaded
from any file type supported by NWG (JPEG, PNG, BMP, ICO, DDS, TIFF).

Bitmaps can be converted to icons using the "copy_as_icon" function.


**Builder parameters:**
  * `source_file`:      The source of the bitmap if it is a file.
  * `source_bin`:       The source of the bitmap if it is a binary blob. For example using `include_bytes!("my_icon.bmp")`.
  * `source_system`:    The source of the bitmap if it is a system resource (see OemBitmap)
  * `source_embed`:     The source of the bitmap if it is stored in an embedded file
  * `source_embed_id`:  The number identifier of the icon in the embedded file
  * `source_embed_str`: The string identifier of the icon in the embedded file
  * `size`:             Optional. Resize the image to this size.
  * `strict`:           Use a system placeholder instead of panicking if the image source do no exists.

Example:

```rust
use native_windows_gui as nwg;

fn load_bitmap() -> nwg::Bitmap {
    let mut bitmap = nwg::Bitmap::default();

    nwg::Bitmap::builder()
        .source_file(Some("Hello.bmp"))
        .strict(true)
        .build(&mut bitmap);

    bitmap
}

```

*/
#[allow(unused)]
pub struct Bitmap {
    pub handle: HANDLE,
    pub(crate) owned: bool
}

impl Bitmap {

    pub fn builder<'a>() -> BitmapBuilder<'a> {
        BitmapBuilder {
            source_text: None,
            source_bin: None,
            source_system: None,

            #[cfg(feature = "embed-resource")]
            source_embed: None,

            #[cfg(feature = "embed-resource")]
            source_embed_id: 0,

            #[cfg(feature = "embed-resource")]
            source_embed_str: None,

            size: None,
            strict: false
        }
    }

    pub fn from_system(cursor: OemBitmap) -> Bitmap {
        let mut out = Self::default();

        // Default cursor creation cannot fail

        Self::builder()
            .source_system(Some(cursor))
            .build(&mut out)
            .unwrap();

        out
    }

    /**
        Creates a new icon from the bitmap data. The bitmap must have been initialized
    */
    pub fn copy_as_icon(&self) -> crate::Icon {
        use winapi::um::winuser::CreateIconIndirect;
        use winapi::um::winuser::ICONINFO;

        if self.handle.is_null() {
            panic!("Bitmap was not initialized");
        }

        let mut icon_info = ICONINFO {
            fIcon: 1,
            xHotspot: 0,
            yHotspot: 0,
            hbmMask: self.handle as _,
            hbmColor: self.handle as _
        };

        let icon = unsafe { CreateIconIndirect(&mut icon_info) };

        crate::Icon {
            handle: icon as _,
            owned: true
        }
    }

}

pub struct BitmapBuilder<'a> {
    source_text: Option<&'a str>,
    source_bin: Option<&'a [u8]>,
    source_system: Option<OemBitmap>,

    #[cfg(feature = "embed-resource")]
    source_embed: Option<&'a EmbedResource>,

    #[cfg(feature = "embed-resource")]
    source_embed_id: usize,

    #[cfg(feature = "embed-resource")]
    source_embed_str: Option<&'a str>,
    
    size: Option<(u32, u32)>,
    strict: bool,
}

impl<'a> BitmapBuilder<'a> {

    pub fn source_file(mut self, t: Option<&'a str>) -> BitmapBuilder<'a> {
        self.source_text = t;
        self
    }

    pub fn source_bin(mut self, t: Option<&'a [u8]>) -> BitmapBuilder<'a> {
        self.source_bin = t;
        self
    }

    pub fn source_system(mut self, t: Option<OemBitmap>) -> BitmapBuilder<'a> {
        self.source_system = t;
        self
    }

    #[cfg(feature = "embed-resource")]
    pub fn source_embed(mut self, em: Option<&'a EmbedResource>) -> BitmapBuilder<'a> {
        self.source_embed = em;
        self
    }

    #[cfg(feature = "embed-resource")]
    pub fn source_embed_id(mut self, id: usize) -> BitmapBuilder<'a> {
        self.source_embed_id = id;
        self
    }

    #[cfg(feature = "embed-resource")]
    pub fn source_embed_str(mut self, id: Option<&'a str>) -> BitmapBuilder<'a> {
        self.source_embed_str = id;
        self
    }

    pub fn size(mut self, s: Option<(u32, u32)>) -> BitmapBuilder<'a> {
        self.size = s;
        self
    }

    pub fn strict(mut self, s: bool) -> BitmapBuilder<'a> {
        self.strict = s;
        self
    }

    pub fn build(self, b: &mut Bitmap) -> Result<(), NwgError> {
        if let Some(src) = self.source_text {
            let handle = unsafe { 
                #[cfg(feature="image-decoder")]
                let handle = rh::build_image_decoder(src, self.size, self.strict, IMAGE_BITMAP);

                #[cfg(not(feature="image-decoder"))]
                let handle = rh::build_image(src, self.size, self.strict, IMAGE_BITMAP);

                handle?
            };

            *b = Bitmap { handle, owned: true };
        } else if let Some(src) = self.source_system {
            let handle = unsafe { rh::build_oem_image(OemImage::Bitmap(src), self.size)? };
            *b = Bitmap { handle, owned: true };
        } else if let Some(src) = self.source_bin { 
            let handle = unsafe { rh::bitmap_from_memory(src)? };

            *b = Bitmap { handle, owned: true };
        } else {
            #[cfg(all(feature = "embed-resource", feature="image-decoder"))]
            fn build_embed(builder: BitmapBuilder) -> Result<Bitmap, NwgError> {
                match builder.source_embed {
                    Some(embed) => {
                        match builder.source_embed_str {
                            Some(src) => embed.image_str(src, builder.size)
                                .ok_or_else(|| NwgError::resource_create(format!("No bitmap in embed resource identified by {}", src))),
                            None => embed.image(builder.source_embed_id, builder.size)
                                .ok_or_else(|| NwgError::resource_create(format!("No bitmap in embed resource identified by {}", builder.source_embed_id)))
                        }
                    },
                    None => Err(NwgError::resource_create("No source provided for Bitmap"))
                }
            }

            #[cfg(feature = "embed-resource")]
            #[cfg(not(feature = "image-decoder"))]
            fn build_embed(builder: BitmapBuilder) -> Result<Bitmap, NwgError> {
                match builder.source_embed {
                    Some(embed) => {
                        match builder.source_embed_str {
                            Some(src) => embed.bitmap_str(src, builder.size)
                                .ok_or_else(|| NwgError::resource_create(format!("No bitmap in embed resource identified by {}", src))),
                            None => embed.bitmap(builder.source_embed_id, builder.size)
                                .ok_or_else(|| NwgError::resource_create(format!("No bitmap in embed resource identified by {}", builder.source_embed_id)))
                        }
                    },
                    None => Err(NwgError::resource_create("No source provided for Bitmap"))
                }
            }

            #[cfg(not(feature = "embed-resource"))]
            fn build_embed(_builder: BitmapBuilder) -> Result<Bitmap, NwgError> {
                Err(NwgError::resource_create("No source provided for Bitmap"))
            }

            *b = build_embed(self)?;
        }
    
        Ok(())
    }

}


impl Default for Bitmap {

    fn default() -> Bitmap {
        Bitmap {
            handle: ptr::null_mut(),
            owned: false
        }
    }

}

impl PartialEq for Bitmap {

    fn eq(&self, other: &Self) -> bool {
        self.handle == other.handle
    }

}

impl Drop for Bitmap {

    fn drop(&mut self) {
        use winapi::um::wingdi::DeleteObject;
        if self.owned {
            unsafe { DeleteObject(self.handle); }
        }
    }

}