OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #include "gfx/icon_util.h" | |
6 | |
7 #include "base/file_util.h" | |
8 #include "base/logging.h" | |
9 #include "base/scoped_ptr.h" | |
10 #include "base/win/scoped_handle.h" | |
11 #include "gfx/size.h" | |
12 #include "skia/ext/image_operations.h" | |
13 #include "third_party/skia/include/core/SkBitmap.h" | |
14 | |
15 // Defining the dimensions for the icon images. We store only one value because | |
16 // we always resize to a square image; that is, the value 48 means that we are | |
17 // going to resize the given bitmap to a 48 by 48 pixels bitmap. | |
18 // | |
19 // The icon images appear in the icon file in same order in which their | |
20 // corresponding dimensions appear in the |icon_dimensions_| array, so it is | |
21 // important to keep this array sorted. Also note that the maximum icon image | |
22 // size we can handle is 255 by 255. | |
23 const int IconUtil::icon_dimensions_[] = { | |
24 8, // Recommended by the MSDN as a nice to have icon size. | |
25 10, // Used by the Shell (e.g. for shortcuts). | |
26 14, // Recommended by the MSDN as a nice to have icon size. | |
27 16, // Toolbar, Application and Shell icon sizes. | |
28 22, // Recommended by the MSDN as a nice to have icon size. | |
29 24, // Used by the Shell (e.g. for shortcuts). | |
30 32, // Toolbar, Dialog and Wizard icon size. | |
31 40, // Quick Launch. | |
32 48, // Alt+Tab icon size. | |
33 64, // Recommended by the MSDN as a nice to have icon size. | |
34 96, // Recommended by the MSDN as a nice to have icon size. | |
35 128 // Used by the Shell (e.g. for shortcuts). | |
36 }; | |
37 | |
38 HICON IconUtil::CreateHICONFromSkBitmap(const SkBitmap& bitmap) { | |
39 // Only 32 bit ARGB bitmaps are supported. We also try to perform as many | |
40 // validations as we can on the bitmap. | |
41 SkAutoLockPixels bitmap_lock(bitmap); | |
42 if ((bitmap.getConfig() != SkBitmap::kARGB_8888_Config) || | |
43 (bitmap.width() <= 0) || (bitmap.height() <= 0) || | |
44 (bitmap.getPixels() == NULL)) | |
45 return NULL; | |
46 | |
47 // We start by creating a DIB which we'll use later on in order to create | |
48 // the HICON. We use BITMAPV5HEADER since the bitmap we are about to convert | |
49 // may contain an alpha channel and the V5 header allows us to specify the | |
50 // alpha mask for the DIB. | |
51 BITMAPV5HEADER bitmap_header; | |
52 InitializeBitmapHeader(&bitmap_header, bitmap.width(), bitmap.height()); | |
53 void* bits; | |
54 HDC hdc = ::GetDC(NULL); | |
55 HBITMAP dib; | |
56 dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&bitmap_header), | |
57 DIB_RGB_COLORS, &bits, NULL, 0); | |
58 DCHECK(dib); | |
59 ::ReleaseDC(NULL, hdc); | |
60 memcpy(bits, bitmap.getPixels(), bitmap.width() * bitmap.height() * 4); | |
61 | |
62 // Icons are generally created using an AND and XOR masks where the AND | |
63 // specifies boolean transparency (the pixel is either opaque or | |
64 // transparent) and the XOR mask contains the actual image pixels. If the XOR | |
65 // mask bitmap has an alpha channel, the AND monochrome bitmap won't | |
66 // actually be used for computing the pixel transparency. Even though all our | |
67 // bitmap has an alpha channel, Windows might not agree when all alpha values | |
68 // are zero. So the monochrome bitmap is created with all pixels transparent | |
69 // for this case. Otherwise, it is created with all pixels opaque. | |
70 bool bitmap_has_alpha_channel = PixelsHaveAlpha( | |
71 static_cast<const uint32*>(bitmap.getPixels()), | |
72 bitmap.width() * bitmap.height()); | |
73 | |
74 scoped_array<uint8> mask_bits; | |
75 if (!bitmap_has_alpha_channel) { | |
76 // Bytes per line with paddings to make it word alignment. | |
77 size_t bytes_per_line = (bitmap.width() + 0xF) / 16 * 2; | |
78 size_t mask_bits_size = bytes_per_line * bitmap.height(); | |
79 | |
80 mask_bits.reset(new uint8[mask_bits_size]); | |
81 DCHECK(mask_bits.get()); | |
82 | |
83 // Make all pixels transparent. | |
84 memset(mask_bits.get(), 0xFF, mask_bits_size); | |
85 } | |
86 | |
87 HBITMAP mono_bitmap = ::CreateBitmap(bitmap.width(), bitmap.height(), 1, 1, | |
88 reinterpret_cast<LPVOID>(mask_bits.get())); | |
89 DCHECK(mono_bitmap); | |
90 | |
91 ICONINFO icon_info; | |
92 icon_info.fIcon = TRUE; | |
93 icon_info.xHotspot = 0; | |
94 icon_info.yHotspot = 0; | |
95 icon_info.hbmMask = mono_bitmap; | |
96 icon_info.hbmColor = dib; | |
97 HICON icon = ::CreateIconIndirect(&icon_info); | |
98 ::DeleteObject(dib); | |
99 ::DeleteObject(mono_bitmap); | |
100 return icon; | |
101 } | |
102 | |
103 SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s) { | |
104 // We start with validating parameters. | |
105 ICONINFO icon_info; | |
106 if (!icon || !(::GetIconInfo(icon, &icon_info)) || | |
107 !icon_info.fIcon || s.IsEmpty()) | |
108 return NULL; | |
109 | |
110 // Allocating memory for the SkBitmap object. We are going to create an ARGB | |
111 // bitmap so we should set the configuration appropriately. | |
112 SkBitmap* bitmap = new SkBitmap; | |
113 DCHECK(bitmap); | |
114 bitmap->setConfig(SkBitmap::kARGB_8888_Config, s.width(), s.height()); | |
115 bitmap->allocPixels(); | |
116 bitmap->eraseARGB(0, 0, 0, 0); | |
117 SkAutoLockPixels bitmap_lock(*bitmap); | |
118 | |
119 // Now we should create a DIB so that we can use ::DrawIconEx in order to | |
120 // obtain the icon's image. | |
121 BITMAPV5HEADER h; | |
122 InitializeBitmapHeader(&h, s.width(), s.height()); | |
123 HDC dc = ::GetDC(NULL); | |
124 uint32* bits; | |
125 HBITMAP dib = ::CreateDIBSection(dc, reinterpret_cast<BITMAPINFO*>(&h), | |
126 DIB_RGB_COLORS, reinterpret_cast<void**>(&bits), NULL, 0); | |
127 DCHECK(dib); | |
128 HDC dib_dc = CreateCompatibleDC(dc); | |
129 DCHECK(dib_dc); | |
130 ::SelectObject(dib_dc, dib); | |
131 | |
132 // Windows icons are defined using two different masks. The XOR mask, which | |
133 // represents the icon image and an AND mask which is a monochrome bitmap | |
134 // which indicates the transparency of each pixel. | |
135 // | |
136 // To make things more complex, the icon image itself can be an ARGB bitmap | |
137 // and therefore contain an alpha channel which specifies the transparency | |
138 // for each pixel. Unfortunately, there is no easy way to determine whether | |
139 // or not a bitmap has an alpha channel and therefore constructing the bitmap | |
140 // for the icon is nothing but straightforward. | |
141 // | |
142 // The idea is to read the AND mask but use it only if we know for sure that | |
143 // the icon image does not have an alpha channel. The only way to tell if the | |
144 // bitmap has an alpha channel is by looking through the pixels and checking | |
145 // whether there are non-zero alpha bytes. | |
146 // | |
147 // We start by drawing the AND mask into our DIB. | |
148 size_t num_pixels = s.GetArea(); | |
149 memset(bits, 0, num_pixels * 4); | |
150 ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_MASK); | |
151 | |
152 // Capture boolean opacity. We may not use it if we find out the bitmap has | |
153 // an alpha channel. | |
154 bool* opaque = new bool[num_pixels]; | |
155 DCHECK(opaque); | |
156 for (size_t i = 0; i < num_pixels; ++i) | |
157 opaque[i] = !bits[i]; | |
158 | |
159 // Then draw the image itself which is really the XOR mask. | |
160 memset(bits, 0, num_pixels * 4); | |
161 ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_NORMAL); | |
162 memcpy(bitmap->getPixels(), static_cast<void*>(bits), num_pixels * 4); | |
163 | |
164 // Finding out whether the bitmap has an alpha channel. | |
165 bool bitmap_has_alpha_channel = PixelsHaveAlpha( | |
166 static_cast<const uint32*>(bitmap->getPixels()), num_pixels); | |
167 | |
168 // If the bitmap does not have an alpha channel, we need to build it using | |
169 // the previously captured AND mask. Otherwise, we are done. | |
170 if (!bitmap_has_alpha_channel) { | |
171 uint32* p = static_cast<uint32*>(bitmap->getPixels()); | |
172 for (size_t i = 0; i < num_pixels; ++p, ++i) { | |
173 DCHECK_EQ((*p & 0xff000000), 0u); | |
174 if (opaque[i]) | |
175 *p |= 0xff000000; | |
176 else | |
177 *p &= 0x00ffffff; | |
178 } | |
179 } | |
180 | |
181 delete [] opaque; | |
182 ::DeleteDC(dib_dc); | |
183 ::DeleteObject(dib); | |
184 ::ReleaseDC(NULL, dc); | |
185 | |
186 return bitmap; | |
187 } | |
188 | |
189 bool IconUtil::CreateIconFileFromSkBitmap(const SkBitmap& bitmap, | |
190 const FilePath& icon_path) { | |
191 // Only 32 bit ARGB bitmaps are supported. We also make sure the bitmap has | |
192 // been properly initialized. | |
193 SkAutoLockPixels bitmap_lock(bitmap); | |
194 if ((bitmap.getConfig() != SkBitmap::kARGB_8888_Config) || | |
195 (bitmap.height() <= 0) || (bitmap.width() <= 0) || | |
196 (bitmap.getPixels() == NULL)) | |
197 return false; | |
198 | |
199 // We start by creating the file. | |
200 base::win::ScopedHandle icon_file(::CreateFile(icon_path.value().c_str(), | |
201 GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)); | |
202 | |
203 if (icon_file.Get() == INVALID_HANDLE_VALUE) | |
204 return false; | |
205 | |
206 // Creating a set of bitmaps corresponding to the icon images we'll end up | |
207 // storing in the icon file. Each bitmap is created by resizing the given | |
208 // bitmap to the desired size. | |
209 std::vector<SkBitmap> bitmaps; | |
210 CreateResizedBitmapSet(bitmap, &bitmaps); | |
211 DCHECK(!bitmaps.empty()); | |
212 size_t bitmap_count = bitmaps.size(); | |
213 | |
214 // Computing the total size of the buffer we need in order to store the | |
215 // images in the desired icon format. | |
216 size_t buffer_size = ComputeIconFileBufferSize(bitmaps); | |
217 unsigned char* buffer = new unsigned char[buffer_size]; | |
218 DCHECK(buffer != NULL); | |
219 memset(buffer, 0, buffer_size); | |
220 | |
221 // Setting the information in the structures residing within the buffer. | |
222 // First, we set the information which doesn't require iterating through the | |
223 // bitmap set and then we set the bitmap specific structures. In the latter | |
224 // step we also copy the actual bits. | |
225 ICONDIR* icon_dir = reinterpret_cast<ICONDIR*>(buffer); | |
226 icon_dir->idType = kResourceTypeIcon; | |
227 icon_dir->idCount = bitmap_count; | |
228 size_t icon_dir_count = bitmap_count - 1; // Note DCHECK(!bitmaps.empty())! | |
229 size_t offset = sizeof(ICONDIR) + (sizeof(ICONDIRENTRY) * icon_dir_count); | |
230 for (size_t i = 0; i < bitmap_count; i++) { | |
231 ICONIMAGE* image = reinterpret_cast<ICONIMAGE*>(buffer + offset); | |
232 DCHECK_LT(offset, buffer_size); | |
233 size_t icon_image_size = 0; | |
234 SetSingleIconImageInformation(bitmaps[i], i, icon_dir, image, offset, | |
235 &icon_image_size); | |
236 DCHECK_GT(icon_image_size, 0U); | |
237 offset += icon_image_size; | |
238 } | |
239 DCHECK_EQ(offset, buffer_size); | |
240 | |
241 // Finally, writing the data info the file. | |
242 DWORD bytes_written; | |
243 bool delete_file = false; | |
244 if (!WriteFile(icon_file.Get(), buffer, buffer_size, &bytes_written, NULL) || | |
245 bytes_written != buffer_size) | |
246 delete_file = true; | |
247 | |
248 ::CloseHandle(icon_file.Take()); | |
249 delete [] buffer; | |
250 if (delete_file) { | |
251 bool success = file_util::Delete(icon_path, false); | |
252 DCHECK(success); | |
253 } | |
254 | |
255 return !delete_file; | |
256 } | |
257 | |
258 bool IconUtil::PixelsHaveAlpha(const uint32* pixels, size_t num_pixels) { | |
259 for (const uint32* end = pixels + num_pixels; pixels != end; ++pixels) { | |
260 if ((*pixels & 0xff000000) != 0) | |
261 return true; | |
262 } | |
263 | |
264 return false; | |
265 } | |
266 | |
267 void IconUtil::InitializeBitmapHeader(BITMAPV5HEADER* header, int width, | |
268 int height) { | |
269 DCHECK(header); | |
270 memset(header, 0, sizeof(BITMAPV5HEADER)); | |
271 header->bV5Size = sizeof(BITMAPV5HEADER); | |
272 | |
273 // Note that icons are created using top-down DIBs so we must negate the | |
274 // value used for the icon's height. | |
275 header->bV5Width = width; | |
276 header->bV5Height = -height; | |
277 header->bV5Planes = 1; | |
278 header->bV5Compression = BI_RGB; | |
279 | |
280 // Initializing the bitmap format to 32 bit ARGB. | |
281 header->bV5BitCount = 32; | |
282 header->bV5RedMask = 0x00FF0000; | |
283 header->bV5GreenMask = 0x0000FF00; | |
284 header->bV5BlueMask = 0x000000FF; | |
285 header->bV5AlphaMask = 0xFF000000; | |
286 | |
287 // Use the system color space. The default value is LCS_CALIBRATED_RGB, which | |
288 // causes us to crash if we don't specify the approprite gammas, etc. See | |
289 // <http://msdn.microsoft.com/en-us/library/ms536531(VS.85).aspx> and | |
290 // <http://b/1283121>. | |
291 header->bV5CSType = LCS_WINDOWS_COLOR_SPACE; | |
292 | |
293 // Use a valid value for bV5Intent as 0 is not a valid one. | |
294 // <http://msdn.microsoft.com/en-us/library/dd183381(VS.85).aspx> | |
295 header->bV5Intent = LCS_GM_IMAGES; | |
296 } | |
297 | |
298 void IconUtil::SetSingleIconImageInformation(const SkBitmap& bitmap, | |
299 size_t index, | |
300 ICONDIR* icon_dir, | |
301 ICONIMAGE* icon_image, | |
302 size_t image_offset, | |
303 size_t* image_byte_count) { | |
304 DCHECK(icon_dir != NULL); | |
305 DCHECK(icon_image != NULL); | |
306 DCHECK_GT(image_offset, 0U); | |
307 DCHECK(image_byte_count != NULL); | |
308 | |
309 // We start by computing certain image values we'll use later on. | |
310 size_t xor_mask_size, bytes_in_resource; | |
311 ComputeBitmapSizeComponents(bitmap, | |
312 &xor_mask_size, | |
313 &bytes_in_resource); | |
314 | |
315 icon_dir->idEntries[index].bWidth = static_cast<BYTE>(bitmap.width()); | |
316 icon_dir->idEntries[index].bHeight = static_cast<BYTE>(bitmap.height()); | |
317 icon_dir->idEntries[index].wPlanes = 1; | |
318 icon_dir->idEntries[index].wBitCount = 32; | |
319 icon_dir->idEntries[index].dwBytesInRes = bytes_in_resource; | |
320 icon_dir->idEntries[index].dwImageOffset = image_offset; | |
321 icon_image->icHeader.biSize = sizeof(BITMAPINFOHEADER); | |
322 | |
323 // The width field in the BITMAPINFOHEADER structure accounts for the height | |
324 // of both the AND mask and the XOR mask so we need to multiply the bitmap's | |
325 // height by 2. The same does NOT apply to the width field. | |
326 icon_image->icHeader.biHeight = bitmap.height() * 2; | |
327 icon_image->icHeader.biWidth = bitmap.width(); | |
328 icon_image->icHeader.biPlanes = 1; | |
329 icon_image->icHeader.biBitCount = 32; | |
330 | |
331 // We use a helper function for copying to actual bits from the SkBitmap | |
332 // object into the appropriate space in the buffer. We use a helper function | |
333 // (rather than just copying the bits) because there is no way to specify the | |
334 // orientation (bottom-up vs. top-down) of a bitmap residing in a .ico file. | |
335 // Thus, if we just copy the bits, we'll end up with a bottom up bitmap in | |
336 // the .ico file which will result in the icon being displayed upside down. | |
337 // The helper function copies the image into the buffer one scanline at a | |
338 // time. | |
339 // | |
340 // Note that we don't need to initialize the AND mask since the memory | |
341 // allocated for the icon data buffer was initialized to zero. The icon we | |
342 // create will therefore use an AND mask containing only zeros, which is OK | |
343 // because the underlying image has an alpha channel. An AND mask containing | |
344 // only zeros essentially means we'll initially treat all the pixels as | |
345 // opaque. | |
346 unsigned char* image_addr = reinterpret_cast<unsigned char*>(icon_image); | |
347 unsigned char* xor_mask_addr = image_addr + sizeof(BITMAPINFOHEADER); | |
348 CopySkBitmapBitsIntoIconBuffer(bitmap, xor_mask_addr, xor_mask_size); | |
349 *image_byte_count = bytes_in_resource; | |
350 } | |
351 | |
352 void IconUtil::CopySkBitmapBitsIntoIconBuffer(const SkBitmap& bitmap, | |
353 unsigned char* buffer, | |
354 size_t buffer_size) { | |
355 SkAutoLockPixels bitmap_lock(bitmap); | |
356 unsigned char* bitmap_ptr = static_cast<unsigned char*>(bitmap.getPixels()); | |
357 size_t bitmap_size = bitmap.height() * bitmap.width() * 4; | |
358 DCHECK_EQ(buffer_size, bitmap_size); | |
359 for (size_t i = 0; i < bitmap_size; i += bitmap.width() * 4) { | |
360 memcpy(buffer + bitmap_size - bitmap.width() * 4 - i, | |
361 bitmap_ptr + i, | |
362 bitmap.width() * 4); | |
363 } | |
364 } | |
365 | |
366 void IconUtil::CreateResizedBitmapSet(const SkBitmap& bitmap_to_resize, | |
367 std::vector<SkBitmap>* bitmaps) { | |
368 DCHECK(bitmaps != NULL); | |
369 DCHECK(bitmaps->empty()); | |
370 | |
371 bool inserted_original_bitmap = false; | |
372 for (size_t i = 0; i < arraysize(icon_dimensions_); i++) { | |
373 // If the dimensions of the bitmap we are resizing are the same as the | |
374 // current dimensions, then we should insert the bitmap and not a resized | |
375 // bitmap. If the bitmap's dimensions are smaller, we insert our bitmap | |
376 // first so that the bitmaps we return in the vector are sorted based on | |
377 // their dimensions. | |
378 if (!inserted_original_bitmap) { | |
379 if ((bitmap_to_resize.width() == icon_dimensions_[i]) && | |
380 (bitmap_to_resize.height() == icon_dimensions_[i])) { | |
381 bitmaps->push_back(bitmap_to_resize); | |
382 inserted_original_bitmap = true; | |
383 continue; | |
384 } | |
385 | |
386 if ((bitmap_to_resize.width() < icon_dimensions_[i]) && | |
387 (bitmap_to_resize.height() < icon_dimensions_[i])) { | |
388 bitmaps->push_back(bitmap_to_resize); | |
389 inserted_original_bitmap = true; | |
390 } | |
391 } | |
392 bitmaps->push_back(skia::ImageOperations::Resize( | |
393 bitmap_to_resize, skia::ImageOperations::RESIZE_LANCZOS3, | |
394 icon_dimensions_[i], icon_dimensions_[i])); | |
395 } | |
396 | |
397 if (!inserted_original_bitmap) | |
398 bitmaps->push_back(bitmap_to_resize); | |
399 } | |
400 | |
401 size_t IconUtil::ComputeIconFileBufferSize(const std::vector<SkBitmap>& set) { | |
402 DCHECK(!set.empty()); | |
403 | |
404 // We start by counting the bytes for the structures that don't depend on the | |
405 // number of icon images. Note that sizeof(ICONDIR) already accounts for a | |
406 // single ICONDIRENTRY structure, which is why we subtract one from the | |
407 // number of bitmaps. | |
408 size_t total_buffer_size = sizeof(ICONDIR); | |
409 size_t bitmap_count = set.size(); | |
410 total_buffer_size += sizeof(ICONDIRENTRY) * (bitmap_count - 1); | |
411 DCHECK_GE(bitmap_count, arraysize(icon_dimensions_)); | |
412 | |
413 // Add the bitmap specific structure sizes. | |
414 for (size_t i = 0; i < bitmap_count; i++) { | |
415 size_t xor_mask_size, bytes_in_resource; | |
416 ComputeBitmapSizeComponents(set[i], | |
417 &xor_mask_size, | |
418 &bytes_in_resource); | |
419 total_buffer_size += bytes_in_resource; | |
420 } | |
421 return total_buffer_size; | |
422 } | |
423 | |
424 void IconUtil::ComputeBitmapSizeComponents(const SkBitmap& bitmap, | |
425 size_t* xor_mask_size, | |
426 size_t* bytes_in_resource) { | |
427 // The XOR mask size is easy to calculate since we only deal with 32bpp | |
428 // images. | |
429 *xor_mask_size = bitmap.width() * bitmap.height() * 4; | |
430 | |
431 // Computing the AND mask is a little trickier since it is a monochrome | |
432 // bitmap (regardless of the number of bits per pixels used in the XOR mask). | |
433 // There are two things we must make sure we do when computing the AND mask | |
434 // size: | |
435 // | |
436 // 1. Make sure the right number of bytes is allocated for each AND mask | |
437 // scan line in case the number of pixels in the image is not divisible by | |
438 // 8. For example, in a 15X15 image, 15 / 8 is one byte short of | |
439 // containing the number of bits we need in order to describe a single | |
440 // image scan line so we need to add a byte. Thus, we need 2 bytes instead | |
441 // of 1 for each scan line. | |
442 // | |
443 // 2. Make sure each scan line in the AND mask is 4 byte aligned (so that the | |
444 // total icon image has a 4 byte alignment). In the 15X15 image example | |
445 // above, we can not use 2 bytes so we increase it to the next multiple of | |
446 // 4 which is 4. | |
447 // | |
448 // Once we compute the size for a singe AND mask scan line, we multiply that | |
449 // number by the image height in order to get the total number of bytes for | |
450 // the AND mask. Thus, for a 15X15 image, we need 15 * 4 which is 60 bytes | |
451 // for the monochrome bitmap representing the AND mask. | |
452 size_t and_line_length = (bitmap.width() + 7) >> 3; | |
453 and_line_length = (and_line_length + 3) & ~3; | |
454 size_t and_mask_size = and_line_length * bitmap.height(); | |
455 size_t masks_size = *xor_mask_size + and_mask_size; | |
456 *bytes_in_resource = masks_size + sizeof(BITMAPINFOHEADER); | |
457 } | |
OLD | NEW |