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

Side by Side Diff: chrome/common/gfx/icon_util.cc

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

Powered by Google App Engine
This is Rietveld 408576698