Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(83)

Side by Side Diff: app/gfx/icon_util.cc

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

Powered by Google App Engine
This is Rietveld 408576698