icon_util.cc revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
1// Copyright (c) 2012 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 "ui/gfx/icon_util.h"
6
7#include "base/file_util.h"
8#include "base/logging.h"
9#include "base/memory/scoped_ptr.h"
10#include "base/win/resource_util.h"
11#include "base/win/scoped_gdi_object.h"
12#include "base/win/scoped_handle.h"
13#include "base/win/scoped_hdc.h"
14#include "skia/ext/image_operations.h"
15#include "third_party/skia/include/core/SkBitmap.h"
16#include "ui/gfx/gdi_util.h"
17#include "ui/gfx/image/image.h"
18#include "ui/gfx/image/image_family.h"
19#include "ui/gfx/size.h"
20
21namespace {
22
23struct ScopedICONINFO : ICONINFO {
24  ScopedICONINFO() {
25    hbmColor = NULL;
26    hbmMask = NULL;
27  }
28
29  ~ScopedICONINFO() {
30    if (hbmColor)
31      ::DeleteObject(hbmColor);
32    if (hbmMask)
33      ::DeleteObject(hbmMask);
34  }
35};
36
37// Creates a new ImageFamily, |resized_image_family|, based on the images in
38// |image_family|, but containing images of specific dimensions desirable for
39// Windows icons. For each desired image dimension, it chooses the most
40// appropriate image for that size, and resizes it to the desired size.
41// Returns true on success, false on failure. Failure can occur if
42// |image_family| is empty, all images in the family have size 0x0, or an image
43// has no allocated pixel data.
44// |resized_image_family| must be empty.
45bool BuildResizedImageFamily(const gfx::ImageFamily& image_family,
46                             gfx::ImageFamily* resized_image_family) {
47  DCHECK(resized_image_family);
48  DCHECK(resized_image_family->empty());
49
50  for (size_t i = 0; i < IconUtil::kNumIconDimensions; ++i) {
51    int dimension = IconUtil::kIconDimensions[i];
52    gfx::Size size(dimension, dimension);
53    const gfx::Image* best = image_family.GetBest(size);
54    if (!best || best->IsEmpty()) {
55      // Either |image_family| is empty, or all images have size 0x0.
56      return false;
57    }
58
59    // Optimize for the "Large icons" view in Windows Vista+. This view displays
60    // icons at full size if only if there is a 256x256 (kLargeIconSize) image
61    // in the .ico file. Otherwise, it shrinks icons to 48x48 (kMediumIconSize).
62    if (dimension > IconUtil::kMediumIconSize &&
63        best->Width() <= IconUtil::kMediumIconSize &&
64        best->Height() <= IconUtil::kMediumIconSize) {
65      // There is no source icon larger than 48x48, so do not create any
66      // images larger than 48x48. kIconDimensions is sorted in ascending
67      // order, so it is safe to break here.
68      break;
69    }
70
71    if (best->Size() == size) {
72      resized_image_family->Add(*best);
73    } else {
74      // There is no |dimension|x|dimension| source image.
75      // Resize this one to the desired size, and insert it.
76      SkBitmap best_bitmap = best->AsBitmap();
77      // If a gfx::Image was created from a SkBitmap with no allocated pixels,
78      // AsBitmap will return a null bitmap instead. This bitmap will have no
79      // config and a size of 0x0. Check this and fail early, to avoid having
80      // 0x0-sized bitmaps in our resized image family.
81      if (best_bitmap.config() == SkBitmap::kNo_Config)
82        return false;
83      SkBitmap resized_bitmap = skia::ImageOperations::Resize(
84          best_bitmap, skia::ImageOperations::RESIZE_LANCZOS3,
85          dimension, dimension);
86      resized_image_family->Add(gfx::Image::CreateFrom1xBitmap(resized_bitmap));
87    }
88  }
89  return true;
90}
91
92// Creates a set of bitmaps from an image family.
93// All images smaller than 256x256 are converted to SkBitmaps, and inserted into
94// |bitmaps| in order of aspect ratio (thinnest to widest), and then ascending
95// size order. If an image of exactly 256x256 is specified, it is converted into
96// PNG format and stored in |png_bytes|. Images with width or height larger than
97// 256 are ignored.
98// |bitmaps| must be an empty vector, and not NULL.
99// Returns true on success, false on failure. This fails if any image in
100// |image_family| is not a 32-bit ARGB image, or is otherwise invalid.
101bool ConvertImageFamilyToBitmaps(
102    const gfx::ImageFamily& image_family,
103    std::vector<SkBitmap>* bitmaps,
104    scoped_refptr<base::RefCountedMemory>* png_bytes) {
105  DCHECK(bitmaps != NULL);
106  DCHECK(bitmaps->empty());
107
108  for (gfx::ImageFamily::const_iterator it = image_family.begin();
109       it != image_family.end(); ++it) {
110    const gfx::Image& image = *it;
111
112    // All images should have one of the kIconDimensions sizes.
113    DCHECK_GT(image.Width(), 0);
114    DCHECK_LE(image.Width(), IconUtil::kLargeIconSize);
115    DCHECK_GT(image.Height(), 0);
116    DCHECK_LE(image.Height(), IconUtil::kLargeIconSize);
117
118    SkBitmap bitmap = image.AsBitmap();
119
120    // Only 32 bit ARGB bitmaps are supported. We also make sure the bitmap has
121    // been properly initialized.
122    SkAutoLockPixels bitmap_lock(bitmap);
123    if ((bitmap.config() != SkBitmap::kARGB_8888_Config) ||
124        (bitmap.getPixels() == NULL)) {
125      return false;
126    }
127
128    // Special case: Icons exactly 256x256 are stored in PNG format.
129    if (image.Width() == IconUtil::kLargeIconSize &&
130        image.Height() == IconUtil::kLargeIconSize) {
131      *png_bytes = image.As1xPNGBytes();
132    } else {
133      bitmaps->push_back(bitmap);
134    }
135  }
136
137  return true;
138}
139
140}  // namespace
141
142// The icon images appear in the icon file in same order in which their
143// corresponding dimensions appear in this array, so it is important to keep
144// this array sorted. Also note that the maximum icon image size we can handle
145// is 256 by 256. See:
146// http://msdn.microsoft.com/en-us/library/windows/desktop/aa511280.aspx#size
147const int IconUtil::kIconDimensions[] = {
148  8,    // Recommended by the MSDN as a nice to have icon size.
149  10,   // Used by the Shell (e.g. for shortcuts).
150  14,   // Recommended by the MSDN as a nice to have icon size.
151  16,   // Toolbar, Application and Shell icon sizes.
152  22,   // Recommended by the MSDN as a nice to have icon size.
153  24,   // Used by the Shell (e.g. for shortcuts).
154  32,   // Toolbar, Dialog and Wizard icon size.
155  40,   // Quick Launch.
156  48,   // Alt+Tab icon size.
157  64,   // Recommended by the MSDN as a nice to have icon size.
158  96,   // Recommended by the MSDN as a nice to have icon size.
159  128,  // Used by the Shell (e.g. for shortcuts).
160  256   // Used by Vista onwards for large icons.
161};
162
163const size_t IconUtil::kNumIconDimensions = arraysize(kIconDimensions);
164const size_t IconUtil::kNumIconDimensionsUpToMediumSize = 9;
165
166HICON IconUtil::CreateHICONFromSkBitmap(const SkBitmap& bitmap) {
167  // Only 32 bit ARGB bitmaps are supported. We also try to perform as many
168  // validations as we can on the bitmap.
169  SkAutoLockPixels bitmap_lock(bitmap);
170  if ((bitmap.config() != SkBitmap::kARGB_8888_Config) ||
171      (bitmap.width() <= 0) || (bitmap.height() <= 0) ||
172      (bitmap.getPixels() == NULL))
173    return NULL;
174
175  // We start by creating a DIB which we'll use later on in order to create
176  // the HICON. We use BITMAPV5HEADER since the bitmap we are about to convert
177  // may contain an alpha channel and the V5 header allows us to specify the
178  // alpha mask for the DIB.
179  BITMAPV5HEADER bitmap_header;
180  InitializeBitmapHeader(&bitmap_header, bitmap.width(), bitmap.height());
181  void* bits;
182  HDC hdc = ::GetDC(NULL);
183  HBITMAP dib;
184  dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&bitmap_header),
185                           DIB_RGB_COLORS, &bits, NULL, 0);
186  DCHECK(dib);
187  ::ReleaseDC(NULL, hdc);
188  memcpy(bits, bitmap.getPixels(), bitmap.width() * bitmap.height() * 4);
189
190  // Icons are generally created using an AND and XOR masks where the AND
191  // specifies boolean transparency (the pixel is either opaque or
192  // transparent) and the XOR mask contains the actual image pixels. If the XOR
193  // mask bitmap has an alpha channel, the AND monochrome bitmap won't
194  // actually be used for computing the pixel transparency. Even though all our
195  // bitmap has an alpha channel, Windows might not agree when all alpha values
196  // are zero. So the monochrome bitmap is created with all pixels transparent
197  // for this case. Otherwise, it is created with all pixels opaque.
198  bool bitmap_has_alpha_channel = PixelsHaveAlpha(
199      static_cast<const uint32*>(bitmap.getPixels()),
200      bitmap.width() * bitmap.height());
201
202  scoped_ptr<uint8[]> mask_bits;
203  if (!bitmap_has_alpha_channel) {
204    // Bytes per line with paddings to make it word alignment.
205    size_t bytes_per_line = (bitmap.width() + 0xF) / 16 * 2;
206    size_t mask_bits_size = bytes_per_line * bitmap.height();
207
208    mask_bits.reset(new uint8[mask_bits_size]);
209    DCHECK(mask_bits.get());
210
211    // Make all pixels transparent.
212    memset(mask_bits.get(), 0xFF, mask_bits_size);
213  }
214
215  HBITMAP mono_bitmap = ::CreateBitmap(bitmap.width(), bitmap.height(), 1, 1,
216      reinterpret_cast<LPVOID>(mask_bits.get()));
217  DCHECK(mono_bitmap);
218
219  ICONINFO icon_info;
220  icon_info.fIcon = TRUE;
221  icon_info.xHotspot = 0;
222  icon_info.yHotspot = 0;
223  icon_info.hbmMask = mono_bitmap;
224  icon_info.hbmColor = dib;
225  HICON icon = ::CreateIconIndirect(&icon_info);
226  ::DeleteObject(dib);
227  ::DeleteObject(mono_bitmap);
228  return icon;
229}
230
231SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s) {
232  // We start with validating parameters.
233  if (!icon || s.IsEmpty())
234    return NULL;
235  ScopedICONINFO icon_info;
236  if (!::GetIconInfo(icon, &icon_info))
237    return NULL;
238  if (!icon_info.fIcon)
239    return NULL;
240  return new SkBitmap(CreateSkBitmapFromHICONHelper(icon, s));
241}
242
243scoped_ptr<SkBitmap> IconUtil::CreateSkBitmapFromIconResource(HMODULE module,
244                                                              int resource_id,
245                                                              int size) {
246  DCHECK_LE(size, kLargeIconSize);
247
248  // For everything except the Vista+ 256x256 icons, use |LoadImage()|.
249  if (size != kLargeIconSize) {
250    HICON icon_handle =
251        static_cast<HICON>(LoadImage(module, MAKEINTRESOURCE(resource_id),
252                                     IMAGE_ICON, size, size,
253                                     LR_DEFAULTCOLOR | LR_DEFAULTSIZE));
254    scoped_ptr<SkBitmap> bitmap(IconUtil::CreateSkBitmapFromHICON(icon_handle));
255    DestroyIcon(icon_handle);
256    return bitmap.Pass();
257  }
258
259  // For Vista+ 256x256 PNG icons, read the resource directly and find
260  // the corresponding icon entry to get its PNG bytes.
261  void* icon_dir_data = NULL;
262  size_t icon_dir_size = 0;
263  if (!base::win::GetResourceFromModule(module, resource_id, RT_GROUP_ICON,
264                                        &icon_dir_data, &icon_dir_size)) {
265    return scoped_ptr<SkBitmap>();
266  }
267  DCHECK(icon_dir_data);
268  DCHECK_GE(icon_dir_size, sizeof(GRPICONDIR));
269
270  const GRPICONDIR* icon_dir =
271      reinterpret_cast<const GRPICONDIR*>(icon_dir_data);
272  const GRPICONDIRENTRY* large_icon_entry = NULL;
273  for (size_t i = 0; i < icon_dir->idCount; ++i) {
274    const GRPICONDIRENTRY* entry = &icon_dir->idEntries[i];
275    // 256x256 icons are stored with width and height set to 0.
276    // See: http://en.wikipedia.org/wiki/ICO_(file_format)
277    if (entry->bWidth == 0 && entry->bHeight == 0) {
278      large_icon_entry = entry;
279      break;
280    }
281  }
282  if (!large_icon_entry)
283    return scoped_ptr<SkBitmap>();
284
285  void* png_data = NULL;
286  size_t png_size = 0;
287  if (!base::win::GetResourceFromModule(module, large_icon_entry->nID, RT_ICON,
288                                        &png_data, &png_size)) {
289    return scoped_ptr<SkBitmap>();
290  }
291  DCHECK(png_data);
292  DCHECK_EQ(png_size, large_icon_entry->dwBytesInRes);
293
294  const unsigned char* png_bytes =
295      reinterpret_cast<const unsigned char*>(png_data);
296  gfx::Image image = gfx::Image::CreateFrom1xPNGBytes(png_bytes, png_size);
297  return scoped_ptr<SkBitmap>(new SkBitmap(image.AsBitmap()));
298}
299
300SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon) {
301  // We start with validating parameters.
302  if (!icon)
303    return NULL;
304
305  ScopedICONINFO icon_info;
306  BITMAP bitmap_info = { 0 };
307
308  if (!::GetIconInfo(icon, &icon_info))
309    return NULL;
310
311  if (!::GetObject(icon_info.hbmMask, sizeof(bitmap_info), &bitmap_info))
312    return NULL;
313
314  gfx::Size icon_size(bitmap_info.bmWidth, bitmap_info.bmHeight);
315  return new SkBitmap(CreateSkBitmapFromHICONHelper(icon, icon_size));
316}
317
318HICON IconUtil::CreateCursorFromDIB(const gfx::Size& icon_size,
319                                    const gfx::Point& hotspot,
320                                    const void* dib_bits,
321                                    size_t dib_size) {
322  BITMAPINFO icon_bitmap_info = {0};
323  gfx::CreateBitmapHeader(
324      icon_size.width(),
325      icon_size.height(),
326      reinterpret_cast<BITMAPINFOHEADER*>(&icon_bitmap_info));
327
328  base::win::ScopedGetDC dc(NULL);
329  base::win::ScopedCreateDC working_dc(CreateCompatibleDC(dc));
330  base::win::ScopedGDIObject<HBITMAP> bitmap_handle(
331      CreateDIBSection(dc,
332                       &icon_bitmap_info,
333                       DIB_RGB_COLORS,
334                       0,
335                       0,
336                       0));
337  if (dib_size > 0) {
338    SetDIBits(0,
339              bitmap_handle,
340              0,
341              icon_size.height(),
342              dib_bits,
343              &icon_bitmap_info,
344              DIB_RGB_COLORS);
345  }
346
347  HBITMAP old_bitmap = reinterpret_cast<HBITMAP>(
348      SelectObject(working_dc, bitmap_handle));
349  SetBkMode(working_dc, TRANSPARENT);
350  SelectObject(working_dc, old_bitmap);
351
352  base::win::ScopedGDIObject<HBITMAP> mask(
353      CreateBitmap(icon_size.width(),
354                   icon_size.height(),
355                   1,
356                   1,
357                   NULL));
358  ICONINFO ii = {0};
359  ii.fIcon = FALSE;
360  ii.xHotspot = hotspot.x();
361  ii.yHotspot = hotspot.y();
362  ii.hbmMask = mask;
363  ii.hbmColor = bitmap_handle;
364
365  return CreateIconIndirect(&ii);
366}
367
368SkBitmap IconUtil::CreateSkBitmapFromHICONHelper(HICON icon,
369                                                 const gfx::Size& s) {
370  DCHECK(icon);
371  DCHECK(!s.IsEmpty());
372
373  // Allocating memory for the SkBitmap object. We are going to create an ARGB
374  // bitmap so we should set the configuration appropriately.
375  SkBitmap bitmap;
376  bitmap.setConfig(SkBitmap::kARGB_8888_Config, s.width(), s.height());
377  bitmap.allocPixels();
378  bitmap.eraseARGB(0, 0, 0, 0);
379  SkAutoLockPixels bitmap_lock(bitmap);
380
381  // Now we should create a DIB so that we can use ::DrawIconEx in order to
382  // obtain the icon's image.
383  BITMAPV5HEADER h;
384  InitializeBitmapHeader(&h, s.width(), s.height());
385  HDC hdc = ::GetDC(NULL);
386  uint32* bits;
387  HBITMAP dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&h),
388      DIB_RGB_COLORS, reinterpret_cast<void**>(&bits), NULL, 0);
389  DCHECK(dib);
390  HDC dib_dc = CreateCompatibleDC(hdc);
391  ::ReleaseDC(NULL, hdc);
392  DCHECK(dib_dc);
393  HGDIOBJ old_obj = ::SelectObject(dib_dc, dib);
394
395  // Windows icons are defined using two different masks. The XOR mask, which
396  // represents the icon image and an AND mask which is a monochrome bitmap
397  // which indicates the transparency of each pixel.
398  //
399  // To make things more complex, the icon image itself can be an ARGB bitmap
400  // and therefore contain an alpha channel which specifies the transparency
401  // for each pixel. Unfortunately, there is no easy way to determine whether
402  // or not a bitmap has an alpha channel and therefore constructing the bitmap
403  // for the icon is nothing but straightforward.
404  //
405  // The idea is to read the AND mask but use it only if we know for sure that
406  // the icon image does not have an alpha channel. The only way to tell if the
407  // bitmap has an alpha channel is by looking through the pixels and checking
408  // whether there are non-zero alpha bytes.
409  //
410  // We start by drawing the AND mask into our DIB.
411  size_t num_pixels = s.GetArea();
412  memset(bits, 0, num_pixels * 4);
413  ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_MASK);
414
415  // Capture boolean opacity. We may not use it if we find out the bitmap has
416  // an alpha channel.
417  scoped_ptr<bool[]> opaque(new bool[num_pixels]);
418  for (size_t i = 0; i < num_pixels; ++i)
419    opaque[i] = !bits[i];
420
421  // Then draw the image itself which is really the XOR mask.
422  memset(bits, 0, num_pixels * 4);
423  ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_NORMAL);
424  memcpy(bitmap.getPixels(), static_cast<void*>(bits), num_pixels * 4);
425
426  // Finding out whether the bitmap has an alpha channel.
427  bool bitmap_has_alpha_channel = PixelsHaveAlpha(
428      static_cast<const uint32*>(bitmap.getPixels()), num_pixels);
429
430  // If the bitmap does not have an alpha channel, we need to build it using
431  // the previously captured AND mask. Otherwise, we are done.
432  if (!bitmap_has_alpha_channel) {
433    uint32* p = static_cast<uint32*>(bitmap.getPixels());
434    for (size_t i = 0; i < num_pixels; ++p, ++i) {
435      DCHECK_EQ((*p & 0xff000000), 0u);
436      if (opaque[i])
437        *p |= 0xff000000;
438      else
439        *p &= 0x00ffffff;
440    }
441  }
442
443  ::SelectObject(dib_dc, old_obj);
444  ::DeleteObject(dib);
445  ::DeleteDC(dib_dc);
446
447  return bitmap;
448}
449
450// static
451bool IconUtil::CreateIconFileFromImageFamily(
452    const gfx::ImageFamily& image_family,
453    const base::FilePath& icon_path) {
454  // Creating a set of bitmaps corresponding to the icon images we'll end up
455  // storing in the icon file. Each bitmap is created by resizing the most
456  // appropriate image from |image_family| to the desired size.
457  gfx::ImageFamily resized_image_family;
458  if (!BuildResizedImageFamily(image_family, &resized_image_family))
459    return false;
460
461  std::vector<SkBitmap> bitmaps;
462  scoped_refptr<base::RefCountedMemory> png_bytes;
463  if (!ConvertImageFamilyToBitmaps(resized_image_family, &bitmaps, &png_bytes))
464    return false;
465
466  // Guaranteed true because BuildResizedImageFamily will provide at least one
467  // image < 256x256.
468  DCHECK(!bitmaps.empty());
469  size_t bitmap_count = bitmaps.size();  // Not including PNG image.
470  // Including PNG image, if any.
471  size_t image_count = bitmap_count + (png_bytes.get() ? 1 : 0);
472
473  // Now that basic checks are done, we can create the file.
474  base::win::ScopedHandle icon_file(::CreateFile(icon_path.value().c_str(),
475       GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL));
476
477  if (!icon_file.IsValid())
478    return false;
479
480  // Computing the total size of the buffer we need in order to store the
481  // images in the desired icon format.
482  size_t buffer_size = ComputeIconFileBufferSize(bitmaps);
483  // Account for the bytes needed for the PNG entry.
484  if (png_bytes.get())
485    buffer_size += sizeof(ICONDIRENTRY) + png_bytes->size();
486
487  // Setting the information in the structures residing within the buffer.
488  // First, we set the information which doesn't require iterating through the
489  // bitmap set and then we set the bitmap specific structures. In the latter
490  // step we also copy the actual bits.
491  std::vector<uint8> buffer(buffer_size);
492  ICONDIR* icon_dir = reinterpret_cast<ICONDIR*>(&buffer[0]);
493  icon_dir->idType = kResourceTypeIcon;
494  icon_dir->idCount = static_cast<WORD>(image_count);
495  // - 1 because there is already one ICONDIRENTRY in ICONDIR.
496  size_t icon_dir_count = image_count - 1;
497
498  size_t offset = sizeof(ICONDIR) + (sizeof(ICONDIRENTRY) * icon_dir_count);
499  for (size_t i = 0; i < bitmap_count; i++) {
500    ICONIMAGE* image = reinterpret_cast<ICONIMAGE*>(&buffer[offset]);
501    DCHECK_LT(offset, buffer_size);
502    size_t icon_image_size = 0;
503    SetSingleIconImageInformation(bitmaps[i], i, icon_dir, image, offset,
504                                  &icon_image_size);
505    DCHECK_GT(icon_image_size, 0U);
506    offset += icon_image_size;
507  }
508
509  // Add the PNG entry, if necessary.
510  if (png_bytes.get()) {
511    ICONDIRENTRY* entry = &icon_dir->idEntries[bitmap_count];
512    entry->bWidth = 0;
513    entry->bHeight = 0;
514    entry->wPlanes = 1;
515    entry->wBitCount = 32;
516    entry->dwBytesInRes = static_cast<DWORD>(png_bytes->size());
517    entry->dwImageOffset = static_cast<DWORD>(offset);
518    memcpy(&buffer[offset], png_bytes->front(), png_bytes->size());
519    offset += png_bytes->size();
520  }
521
522  DCHECK_EQ(offset, buffer_size);
523
524  // Finally, write the data to the file.
525  DWORD bytes_written;
526  bool delete_file = false;
527  if (!WriteFile(icon_file.Get(), &buffer[0], buffer_size, &bytes_written,
528                 NULL) ||
529      bytes_written != buffer_size) {
530    delete_file = true;
531  }
532
533  ::CloseHandle(icon_file.Take());
534  if (delete_file) {
535    bool success = file_util::Delete(icon_path, false);
536    DCHECK(success);
537  }
538
539  return !delete_file;
540}
541
542bool IconUtil::PixelsHaveAlpha(const uint32* pixels, size_t num_pixels) {
543  for (const uint32* end = pixels + num_pixels; pixels != end; ++pixels) {
544    if ((*pixels & 0xff000000) != 0)
545      return true;
546  }
547
548  return false;
549}
550
551void IconUtil::InitializeBitmapHeader(BITMAPV5HEADER* header, int width,
552                                      int height) {
553  DCHECK(header);
554  memset(header, 0, sizeof(BITMAPV5HEADER));
555  header->bV5Size = sizeof(BITMAPV5HEADER);
556
557  // Note that icons are created using top-down DIBs so we must negate the
558  // value used for the icon's height.
559  header->bV5Width = width;
560  header->bV5Height = -height;
561  header->bV5Planes = 1;
562  header->bV5Compression = BI_RGB;
563
564  // Initializing the bitmap format to 32 bit ARGB.
565  header->bV5BitCount = 32;
566  header->bV5RedMask = 0x00FF0000;
567  header->bV5GreenMask = 0x0000FF00;
568  header->bV5BlueMask = 0x000000FF;
569  header->bV5AlphaMask = 0xFF000000;
570
571  // Use the system color space.  The default value is LCS_CALIBRATED_RGB, which
572  // causes us to crash if we don't specify the approprite gammas, etc.  See
573  // <http://msdn.microsoft.com/en-us/library/ms536531(VS.85).aspx> and
574  // <http://b/1283121>.
575  header->bV5CSType = LCS_WINDOWS_COLOR_SPACE;
576
577  // Use a valid value for bV5Intent as 0 is not a valid one.
578  // <http://msdn.microsoft.com/en-us/library/dd183381(VS.85).aspx>
579  header->bV5Intent = LCS_GM_IMAGES;
580}
581
582void IconUtil::SetSingleIconImageInformation(const SkBitmap& bitmap,
583                                             size_t index,
584                                             ICONDIR* icon_dir,
585                                             ICONIMAGE* icon_image,
586                                             size_t image_offset,
587                                             size_t* image_byte_count) {
588  DCHECK(icon_dir != NULL);
589  DCHECK(icon_image != NULL);
590  DCHECK_GT(image_offset, 0U);
591  DCHECK(image_byte_count != NULL);
592  DCHECK_LT(bitmap.width(), kLargeIconSize);
593  DCHECK_LT(bitmap.height(), kLargeIconSize);
594
595  // We start by computing certain image values we'll use later on.
596  size_t xor_mask_size, bytes_in_resource;
597  ComputeBitmapSizeComponents(bitmap,
598                              &xor_mask_size,
599                              &bytes_in_resource);
600
601  icon_dir->idEntries[index].bWidth = static_cast<BYTE>(bitmap.width());
602  icon_dir->idEntries[index].bHeight = static_cast<BYTE>(bitmap.height());
603  icon_dir->idEntries[index].wPlanes = 1;
604  icon_dir->idEntries[index].wBitCount = 32;
605  icon_dir->idEntries[index].dwBytesInRes = bytes_in_resource;
606  icon_dir->idEntries[index].dwImageOffset = image_offset;
607  icon_image->icHeader.biSize = sizeof(BITMAPINFOHEADER);
608
609  // The width field in the BITMAPINFOHEADER structure accounts for the height
610  // of both the AND mask and the XOR mask so we need to multiply the bitmap's
611  // height by 2. The same does NOT apply to the width field.
612  icon_image->icHeader.biHeight = bitmap.height() * 2;
613  icon_image->icHeader.biWidth = bitmap.width();
614  icon_image->icHeader.biPlanes = 1;
615  icon_image->icHeader.biBitCount = 32;
616
617  // We use a helper function for copying to actual bits from the SkBitmap
618  // object into the appropriate space in the buffer. We use a helper function
619  // (rather than just copying the bits) because there is no way to specify the
620  // orientation (bottom-up vs. top-down) of a bitmap residing in a .ico file.
621  // Thus, if we just copy the bits, we'll end up with a bottom up bitmap in
622  // the .ico file which will result in the icon being displayed upside down.
623  // The helper function copies the image into the buffer one scanline at a
624  // time.
625  //
626  // Note that we don't need to initialize the AND mask since the memory
627  // allocated for the icon data buffer was initialized to zero. The icon we
628  // create will therefore use an AND mask containing only zeros, which is OK
629  // because the underlying image has an alpha channel. An AND mask containing
630  // only zeros essentially means we'll initially treat all the pixels as
631  // opaque.
632  unsigned char* image_addr = reinterpret_cast<unsigned char*>(icon_image);
633  unsigned char* xor_mask_addr = image_addr + sizeof(BITMAPINFOHEADER);
634  CopySkBitmapBitsIntoIconBuffer(bitmap, xor_mask_addr, xor_mask_size);
635  *image_byte_count = bytes_in_resource;
636}
637
638void IconUtil::CopySkBitmapBitsIntoIconBuffer(const SkBitmap& bitmap,
639                                              unsigned char* buffer,
640                                              size_t buffer_size) {
641  SkAutoLockPixels bitmap_lock(bitmap);
642  unsigned char* bitmap_ptr = static_cast<unsigned char*>(bitmap.getPixels());
643  size_t bitmap_size = bitmap.height() * bitmap.width() * 4;
644  DCHECK_EQ(buffer_size, bitmap_size);
645  for (size_t i = 0; i < bitmap_size; i += bitmap.width() * 4) {
646    memcpy(buffer + bitmap_size - bitmap.width() * 4 - i,
647           bitmap_ptr + i,
648           bitmap.width() * 4);
649  }
650}
651
652size_t IconUtil::ComputeIconFileBufferSize(const std::vector<SkBitmap>& set) {
653  DCHECK(!set.empty());
654
655  // We start by counting the bytes for the structures that don't depend on the
656  // number of icon images. Note that sizeof(ICONDIR) already accounts for a
657  // single ICONDIRENTRY structure, which is why we subtract one from the
658  // number of bitmaps.
659  size_t total_buffer_size = sizeof(ICONDIR);
660  size_t bitmap_count = set.size();
661  total_buffer_size += sizeof(ICONDIRENTRY) * (bitmap_count - 1);
662  // May not have all icon sizes, but must have at least up to medium icon size.
663  DCHECK_GE(bitmap_count, kNumIconDimensionsUpToMediumSize);
664
665  // Add the bitmap specific structure sizes.
666  for (size_t i = 0; i < bitmap_count; i++) {
667    size_t xor_mask_size, bytes_in_resource;
668    ComputeBitmapSizeComponents(set[i],
669                                &xor_mask_size,
670                                &bytes_in_resource);
671    total_buffer_size += bytes_in_resource;
672  }
673  return total_buffer_size;
674}
675
676void IconUtil::ComputeBitmapSizeComponents(const SkBitmap& bitmap,
677                                           size_t* xor_mask_size,
678                                           size_t* bytes_in_resource) {
679  // The XOR mask size is easy to calculate since we only deal with 32bpp
680  // images.
681  *xor_mask_size = bitmap.width() * bitmap.height() * 4;
682
683  // Computing the AND mask is a little trickier since it is a monochrome
684  // bitmap (regardless of the number of bits per pixels used in the XOR mask).
685  // There are two things we must make sure we do when computing the AND mask
686  // size:
687  //
688  // 1. Make sure the right number of bytes is allocated for each AND mask
689  //    scan line in case the number of pixels in the image is not divisible by
690  //    8. For example, in a 15X15 image, 15 / 8 is one byte short of
691  //    containing the number of bits we need in order to describe a single
692  //    image scan line so we need to add a byte. Thus, we need 2 bytes instead
693  //    of 1 for each scan line.
694  //
695  // 2. Make sure each scan line in the AND mask is 4 byte aligned (so that the
696  //    total icon image has a 4 byte alignment). In the 15X15 image example
697  //    above, we can not use 2 bytes so we increase it to the next multiple of
698  //    4 which is 4.
699  //
700  // Once we compute the size for a singe AND mask scan line, we multiply that
701  // number by the image height in order to get the total number of bytes for
702  // the AND mask. Thus, for a 15X15 image, we need 15 * 4 which is 60 bytes
703  // for the monochrome bitmap representing the AND mask.
704  size_t and_line_length = (bitmap.width() + 7) >> 3;
705  and_line_length = (and_line_length + 3) & ~3;
706  size_t and_mask_size = and_line_length * bitmap.height();
707  size_t masks_size = *xor_mask_size + and_mask_size;
708  *bytes_in_resource = masks_size + sizeof(BITMAPINFOHEADER);
709}
710