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