diff options
author | ben@chromium.org <ben@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-05-06 02:23:31 +0000 |
---|---|---|
committer | ben@chromium.org <ben@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-05-06 02:23:31 +0000 |
commit | 3712621396b5ffa5572bc5c0728a63efe9f7476e (patch) | |
tree | a55fc85f01bafbe1ae86e43c5f1ce9638db5b621 /app/gfx | |
parent | af9a8c86fc50e8d789bf795347302e6c94ad6854 (diff) | |
download | chromium_src-3712621396b5ffa5572bc5c0728a63efe9f7476e.zip chromium_src-3712621396b5ffa5572bc5c0728a63efe9f7476e.tar.gz chromium_src-3712621396b5ffa5572bc5c0728a63efe9f7476e.tar.bz2 |
Move: drag_drop_types, favicon_size, icon_util, insets, path, message_box_flags, os_exchange_data to src/app
http://crbug.com/11387
Review URL: http://codereview.chromium.org/115012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@15371 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'app/gfx')
-rw-r--r-- | app/gfx/favicon_size.h | 33 | ||||
-rw-r--r-- | app/gfx/icon_util.cc | 477 | ||||
-rw-r--r-- | app/gfx/icon_util.h | 193 | ||||
-rw-r--r-- | app/gfx/icon_util_unittest.cc | 264 | ||||
-rw-r--r-- | app/gfx/insets.h | 69 | ||||
-rw-r--r-- | app/gfx/path.h | 40 | ||||
-rw-r--r-- | app/gfx/path_gtk.cc | 27 | ||||
-rw-r--r-- | app/gfx/path_win.cc | 24 |
8 files changed, 1127 insertions, 0 deletions
diff --git a/app/gfx/favicon_size.h b/app/gfx/favicon_size.h new file mode 100644 index 0000000..fb66411 --- /dev/null +++ b/app/gfx/favicon_size.h @@ -0,0 +1,33 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef APP_GFX_FAVICON_SIZE_H_ +#define APP_GFX_FAVICON_SIZE_H_ + +#include "base/compiler_specific.h" + +// Size (along each axis) of the favicon. +const int kFavIconSize = 16; + +// If the width or height is bigger than the favicon size, a new width/height +// is calculated and returned in width/height that maintains the aspect +// ratio of the supplied values. +static void calc_favicon_target_size(int* width, int* height) ALLOW_UNUSED; + +// static +void calc_favicon_target_size(int* width, int* height) { + if (*width > kFavIconSize || *height > kFavIconSize) { + // Too big, resize it maintaining the aspect ratio. + float aspect_ratio = static_cast<float>(*width) / + static_cast<float>(*height); + *height = kFavIconSize; + *width = static_cast<int>(aspect_ratio * *height); + if (*width > kFavIconSize) { + *width = kFavIconSize; + *height = static_cast<int>(*width / aspect_ratio); + } + } +} + +#endif // APP_GFX_FAVICON_SIZE_H_ diff --git a/app/gfx/icon_util.cc b/app/gfx/icon_util.cc new file mode 100644 index 0000000..1e9e3c9 --- /dev/null +++ b/app/gfx/icon_util.cc @@ -0,0 +1,477 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "app/gfx/icon_util.h" + +#include "base/file_util.h" +#include "base/gfx/size.h" +#include "base/logging.h" +#include "chrome/common/win_util.h" +#include "skia/ext/image_operations.h" +#include "skia/include/SkBitmap.h" + +// Defining the dimensions for the icon images. We store only one value because +// we always resize to a square image; that is, the value 48 means that we are +// going to resize the given bitmap to a 48 by 48 pixels bitmap. +// +// The icon images appear in the icon file in same order in which their +// corresponding dimensions appear in the |icon_dimensions_| array, so it is +// important to keep this array sorted. Also note that the maximum icon image +// size we can handle is 255 by 255. +const int IconUtil::icon_dimensions_[] = { + 8, // Recommended by the MSDN as a nice to have icon size. + 10, // Used by the Shell (e.g. for shortcuts). + 14, // Recommended by the MSDN as a nice to have icon size. + 16, // Toolbar, Application and Shell icon sizes. + 22, // Recommended by the MSDN as a nice to have icon size. + 24, // Used by the Shell (e.g. for shortcuts). + 32, // Toolbar, Dialog and Wizard icon size. + 40, // Quick Launch. + 48, // Alt+Tab icon size. + 64, // Recommended by the MSDN as a nice to have icon size. + 96, // Recommended by the MSDN as a nice to have icon size. + 128 // Used by the Shell (e.g. for shortcuts). +}; + +HICON IconUtil::CreateHICONFromSkBitmap(const SkBitmap& bitmap) { + // Only 32 bit ARGB bitmaps are supported. We also try to perform as many + // validations as we can on the bitmap. + SkAutoLockPixels bitmap_lock(bitmap); + if ((bitmap.getConfig() != SkBitmap::kARGB_8888_Config) || + (bitmap.width() <= 0) || (bitmap.height() <= 0) || + (bitmap.getPixels() == NULL)) { + return NULL; + } + + // We start by creating a DIB which we'll use later on in order to create + // the HICON. We use BITMAPV5HEADER since the bitmap we are about to convert + // may contain an alpha channel and the V5 header allows us to specify the + // alpha mask for the DIB. + BITMAPV5HEADER bitmap_header; + InitializeBitmapHeader(&bitmap_header, bitmap.width(), bitmap.height()); + void* bits; + HDC hdc = ::GetDC(NULL); + HBITMAP dib; + dib = ::CreateDIBSection(hdc, reinterpret_cast<BITMAPINFO*>(&bitmap_header), + DIB_RGB_COLORS, &bits, NULL, 0); + DCHECK(dib); + ::ReleaseDC(NULL, hdc); + memcpy(bits, bitmap.getPixels(), bitmap.width() * bitmap.height() * 4); + + // Icons are generally created using an AND and XOR masks where the AND + // specifies boolean transparency (the pixel is either opaque or + // transparent) and the XOR mask contains the actual image pixels. However, + // since our bitmap has an alpha channel, the AND monochrome bitmap won't + // actually be used for computing the pixel transparency. Since every icon + // must have an AND mask bitmap, we go ahead and create one so that we can + // associate it with the ICONINFO structure we'll later pass to + // ::CreateIconIndirect(). The monochrome bitmap is created such that all the + // pixels are opaque. + HBITMAP mono_bitmap = ::CreateBitmap(bitmap.width(), bitmap.height(), + 1, 1, NULL); + DCHECK(mono_bitmap); + ICONINFO icon_info; + icon_info.fIcon = TRUE; + icon_info.xHotspot = 0; + icon_info.yHotspot = 0; + icon_info.hbmMask = mono_bitmap; + icon_info.hbmColor = dib; + HICON icon = ::CreateIconIndirect(&icon_info); + ::DeleteObject(dib); + ::DeleteObject(mono_bitmap); + return icon; +} + +SkBitmap* IconUtil::CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s) { + // We start with validating parameters. + ICONINFO icon_info; + if (!icon || !(::GetIconInfo(icon, &icon_info)) || + !icon_info.fIcon || (s.width() <= 0) || (s.height() <= 0)) { + return NULL; + } + + // Allocating memory for the SkBitmap object. We are going to create an ARGB + // bitmap so we should set the configuration appropriately. + SkBitmap* bitmap = new SkBitmap; + DCHECK(bitmap); + bitmap->setConfig(SkBitmap::kARGB_8888_Config, s.width(), s.height()); + bitmap->allocPixels(); + SkAutoLockPixels bitmap_lock(*bitmap); + + // Now we should create a DIB so that we can use ::DrawIconEx in order to + // obtain the icon's image. + BITMAPV5HEADER h; + InitializeBitmapHeader(&h, s.width(), s.height()); + HDC dc = ::GetDC(NULL); + unsigned int* bits; + HBITMAP dib = ::CreateDIBSection(dc, + reinterpret_cast<BITMAPINFO*>(&h), + DIB_RGB_COLORS, + reinterpret_cast<void**>(&bits), + NULL, + 0); + DCHECK(dib); + HDC dib_dc = CreateCompatibleDC(dc); + DCHECK(dib_dc); + ::SelectObject(dib_dc, dib); + + // Windows icons are defined using two different masks. The XOR mask, which + // represents the icon image and an AND mask which is a monochrome bitmap + // which indicates the transparency of each pixel. + // + // To make things more complex, the icon image itself can be an ARGB bitmap + // and therefore contain an alpha channel which specifies the transparency + // for each pixel. Unfortunately, there is no easy way to determine whether + // or not a bitmap has an alpha channel and therefore constructing the bitmap + // for the icon is nothing but straightforward. + // + // The idea is to read the AND mask but use it only if we know for sure that + // the icon image does not have an alpha channel. The only way to tell if the + // bitmap has an alpha channel is by looking through the pixels and checking + // whether there are non-zero alpha bytes. + // + // We start by drawing the AND mask into our DIB. + memset(bits, 0, s.width() * s.height() * 4); + ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_MASK); + + // Capture boolean opacity. We may not use it if we find out the bitmap has + // an alpha channel. + bool* opaque = new bool[s.width() * s.height()]; + DCHECK(opaque); + int x, y; + for (y = 0; y < s.height(); ++y) { + for (x = 0; x < s.width(); ++x) + opaque[(y * s.width()) + x] = !bits[(y * s.width()) + x]; + } + + // Then draw the image itself which is really the XOR mask. + memset(bits, 0, s.width() * s.height() * 4); + ::DrawIconEx(dib_dc, 0, 0, icon, s.width(), s.height(), 0, NULL, DI_NORMAL); + memcpy(bitmap->getPixels(), + static_cast<void*>(bits), + s.width() * s.height() * 4); + + // Finding out whether the bitmap has an alpha channel. + bool bitmap_has_alpha_channel = false; + unsigned int* p = static_cast<unsigned int*>(bitmap->getPixels()); + for (y = 0; y < s.height(); ++y) { + for (x = 0; x < s.width(); ++x) { + if ((*p & 0xff000000) != 0) { + bitmap_has_alpha_channel = true; + break; + } + p++; + } + + if (bitmap_has_alpha_channel) { + break; + } + } + + // If the bitmap does not have an alpha channel, we need to build it using + // the previously captured AND mask. Otherwise, we are done. + if (!bitmap_has_alpha_channel) { + p = static_cast<unsigned int*>(bitmap->getPixels()); + for (y = 0; y < s.height(); ++y) { + for (x = 0; x < s.width(); ++x) { + DCHECK_EQ((*p & 0xff000000), 0); + if (opaque[(y * s.width()) + x]) { + *p |= 0xff000000; + } else { + *p &= 0x00ffffff; + } + p++; + } + } + } + + delete [] opaque; + ::DeleteDC(dib_dc); + ::DeleteObject(dib); + ::ReleaseDC(NULL, dc); + + return bitmap; +} + +bool IconUtil::CreateIconFileFromSkBitmap(const SkBitmap& bitmap, + const std::wstring& icon_file_name) { + // Only 32 bit ARGB bitmaps are supported. We also make sure the bitmap has + // been properly initialized. + SkAutoLockPixels bitmap_lock(bitmap); + if ((bitmap.getConfig() != SkBitmap::kARGB_8888_Config) || + (bitmap.height() <= 0) || (bitmap.width() <= 0) || + (bitmap.getPixels() == NULL)) { + return false; + } + + // We start by creating the file. + win_util::ScopedHandle icon_file(::CreateFile(icon_file_name.c_str(), + GENERIC_WRITE, + 0, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL)); + + if (icon_file.Get() == INVALID_HANDLE_VALUE) { + return false; + } + + // Creating a set of bitmaps corresponding to the icon images we'll end up + // storing in the icon file. Each bitmap is created by resizing the given + // bitmap to the desired size. + std::vector<SkBitmap> bitmaps; + CreateResizedBitmapSet(bitmap, &bitmaps); + int bitmap_count = static_cast<int>(bitmaps.size()); + DCHECK_GT(bitmap_count, 0); + + // Computing the total size of the buffer we need in order to store the + // images in the desired icon format. + int buffer_size = ComputeIconFileBufferSize(bitmaps); + unsigned char* buffer = new unsigned char[buffer_size]; + DCHECK_NE(buffer, static_cast<unsigned char*>(NULL)); + memset(buffer, 0, buffer_size); + + // Setting the information in the structures residing within the buffer. + // First, we set the information which doesn't require iterating through the + // bitmap set and then we set the bitmap specific structures. In the latter + // step we also copy the actual bits. + ICONDIR* icon_dir = reinterpret_cast<ICONDIR*>(buffer); + icon_dir->idType = kResourceTypeIcon; + icon_dir->idCount = bitmap_count; + int icon_dir_count = bitmap_count - 1; + int offset = sizeof(ICONDIR) + (sizeof(ICONDIRENTRY) * icon_dir_count); + for (int i = 0; i < bitmap_count; i++) { + ICONIMAGE* image = reinterpret_cast<ICONIMAGE*>(buffer + offset); + DCHECK_LT(offset, buffer_size); + int icon_image_size = 0; + SetSingleIconImageInformation(bitmaps[i], + i, + icon_dir, + image, + offset, + &icon_image_size); + DCHECK_GT(icon_image_size, 0); + offset += icon_image_size; + } + DCHECK_EQ(offset, buffer_size); + + // Finally, writing the data info the file. + DWORD bytes_written; + bool delete_file = false; + if (!WriteFile(icon_file.Get(), buffer, buffer_size, &bytes_written, NULL) || + bytes_written != buffer_size) { + delete_file = true; + } + + ::CloseHandle(icon_file.Take()); + delete [] buffer; + if (delete_file) { + bool success = file_util::Delete(icon_file_name, false); + DCHECK(success); + } + + return !delete_file; +} + +int IconUtil::GetIconDimensionCount() { + return sizeof(icon_dimensions_) / sizeof(icon_dimensions_[0]); +} + +void IconUtil::InitializeBitmapHeader(BITMAPV5HEADER* header, int width, + int height) { + DCHECK(header); + memset(header, 0, sizeof(BITMAPV5HEADER)); + header->bV5Size = sizeof(BITMAPV5HEADER); + + // Note that icons are created using top-down DIBs so we must negate the + // value used for the icon's height. + header->bV5Width = width; + header->bV5Height = -height; + header->bV5Planes = 1; + header->bV5Compression = BI_RGB; + + // Initializing the bitmap format to 32 bit ARGB. + header->bV5BitCount = 32; + header->bV5RedMask = 0x00FF0000; + header->bV5GreenMask = 0x0000FF00; + header->bV5BlueMask = 0x000000FF; + header->bV5AlphaMask = 0xFF000000; + + // Use the system color space. The default value is LCS_CALIBRATED_RGB, which + // causes us to crash if we don't specify the approprite gammas, etc. See + // <http://msdn.microsoft.com/en-us/library/ms536531(VS.85).aspx> and + // <http://b/1283121>. + header->bV5CSType = LCS_WINDOWS_COLOR_SPACE; +} + +void IconUtil::SetSingleIconImageInformation(const SkBitmap& bitmap, + int index, + ICONDIR* icon_dir, + ICONIMAGE* icon_image, + int image_offset, + int* image_byte_count) { + DCHECK_GE(index, 0); + DCHECK_NE(icon_dir, static_cast<ICONDIR*>(NULL)); + DCHECK_NE(icon_image, static_cast<ICONIMAGE*>(NULL)); + DCHECK_GT(image_offset, 0); + DCHECK_NE(image_byte_count, static_cast<int*>(NULL)); + + // We start by computing certain image values we'll use later on. + int xor_mask_size; + int and_mask_size; + int bytes_in_resource; + ComputeBitmapSizeComponents(bitmap, + &xor_mask_size, + &and_mask_size, + &bytes_in_resource); + + icon_dir->idEntries[index].bWidth = static_cast<BYTE>(bitmap.width()); + icon_dir->idEntries[index].bHeight = static_cast<BYTE>(bitmap.height()); + icon_dir->idEntries[index].wPlanes = 1; + icon_dir->idEntries[index].wBitCount = 32; + icon_dir->idEntries[index].dwBytesInRes = bytes_in_resource; + icon_dir->idEntries[index].dwImageOffset = image_offset; + icon_image->icHeader.biSize = sizeof(BITMAPINFOHEADER); + + // The width field in the BITMAPINFOHEADER structure accounts for the height + // of both the AND mask and the XOR mask so we need to multiply the bitmap's + // height by 2. The same does NOT apply to the width field. + icon_image->icHeader.biHeight = bitmap.height() * 2; + icon_image->icHeader.biWidth = bitmap.width(); + icon_image->icHeader.biPlanes = 1; + icon_image->icHeader.biBitCount = 32; + + // We use a helper function for copying to actual bits from the SkBitmap + // object into the appropriate space in the buffer. We use a helper function + // (rather than just copying the bits) because there is no way to specify the + // orientation (bottom-up vs. top-down) of a bitmap residing in a .ico file. + // Thus, if we just copy the bits, we'll end up with a bottom up bitmap in + // the .ico file which will result in the icon being displayed upside down. + // The helper function copies the image into the buffer one scanline at a + // time. + // + // Note that we don't need to initialize the AND mask since the memory + // allocated for the icon data buffer was initialized to zero. The icon we + // create will therefore use an AND mask containing only zeros, which is OK + // because the underlying image has an alpha channel. An AND mask containing + // only zeros essentially means we'll initially treat all the pixels as + // opaque. + unsigned char* image_addr = reinterpret_cast<unsigned char*>(icon_image); + unsigned char* xor_mask_addr = image_addr + sizeof(BITMAPINFOHEADER); + CopySkBitmapBitsIntoIconBuffer(bitmap, xor_mask_addr, xor_mask_size); + *image_byte_count = bytes_in_resource; +} + +void IconUtil::CopySkBitmapBitsIntoIconBuffer(const SkBitmap& bitmap, + unsigned char* buffer, + int buffer_size) { + SkAutoLockPixels bitmap_lock(bitmap); + unsigned char* bitmap_ptr = static_cast<unsigned char*>(bitmap.getPixels()); + int bitmap_size = bitmap.height() * bitmap.width() * 4; + DCHECK_EQ(buffer_size, bitmap_size); + for (int i = 0; i < bitmap_size; i += bitmap.width() * 4) { + memcpy(buffer + bitmap_size - bitmap.width() * 4 - i, + bitmap_ptr + i, + bitmap.width() * 4); + } +} + +void IconUtil::CreateResizedBitmapSet(const SkBitmap& bitmap_to_resize, + std::vector<SkBitmap>* bitmaps) { + DCHECK_NE(bitmaps, static_cast<std::vector<SkBitmap>* >(NULL)); + DCHECK_EQ(static_cast<int>(bitmaps->size()), 0); + + bool inserted_original_bitmap = false; + for (int i = 0; i < GetIconDimensionCount(); i++) { + // If the dimensions of the bitmap we are resizing are the same as the + // current dimensions, then we should insert the bitmap and not a resized + // bitmap. If the bitmap's dimensions are smaller, we insert our bitmap + // first so that the bitmaps we return in the vector are sorted based on + // their dimensions. + if (!inserted_original_bitmap) { + if ((bitmap_to_resize.width() == icon_dimensions_[i]) && + (bitmap_to_resize.height() == icon_dimensions_[i])) { + bitmaps->push_back(bitmap_to_resize); + inserted_original_bitmap = true; + continue; + } + + if ((bitmap_to_resize.width() < icon_dimensions_[i]) && + (bitmap_to_resize.height() < icon_dimensions_[i])) { + bitmaps->push_back(bitmap_to_resize); + inserted_original_bitmap = true; + } + } + bitmaps->push_back(skia::ImageOperations::Resize( + bitmap_to_resize, skia::ImageOperations::RESIZE_LANCZOS3, + icon_dimensions_[i], icon_dimensions_[i])); + } + + if (!inserted_original_bitmap) { + bitmaps->push_back(bitmap_to_resize); + } +} + +int IconUtil::ComputeIconFileBufferSize(const std::vector<SkBitmap>& set) { + // We start by counting the bytes for the structures that don't depend on the + // number of icon images. Note that sizeof(ICONDIR) already accounts for a + // single ICONDIRENTRY structure, which is why we subtract one from the + // number of bitmaps. + int total_buffer_size = 0; + total_buffer_size += sizeof(ICONDIR); + int bitmap_count = static_cast<int>(set.size()); + total_buffer_size += sizeof(ICONDIRENTRY) * (bitmap_count - 1); + int dimension_count = GetIconDimensionCount(); + DCHECK_GE(bitmap_count, dimension_count); + + // Add the bitmap specific structure sizes. + for (int i = 0; i < bitmap_count; i++) { + int xor_mask_size; + int and_mask_size; + int bytes_in_resource; + ComputeBitmapSizeComponents(set[i], + &xor_mask_size, + &and_mask_size, + &bytes_in_resource); + total_buffer_size += bytes_in_resource; + } + return total_buffer_size; +} + +void IconUtil::ComputeBitmapSizeComponents(const SkBitmap& bitmap, + int* xor_mask_size, + int* and_mask_size, + int* bytes_in_resource) { + // The XOR mask size is easy to calculate since we only deal with 32bpp + // images. + *xor_mask_size = bitmap.width() * bitmap.height() * 4; + + // Computing the AND mask is a little trickier since it is a monochrome + // bitmap (regardless of the number of bits per pixels used in the XOR mask). + // There are two things we must make sure we do when computing the AND mask + // size: + // + // 1. Make sure the right number of bytes is allocated for each AND mask + // scan line in case the number of pixels in the image is not divisible by + // 8. For example, in a 15X15 image, 15 / 8 is one byte short of + // containing the number of bits we need in order to describe a single + // image scan line so we need to add a byte. Thus, we need 2 bytes instead + // of 1 for each scan line. + // + // 2. Make sure each scan line in the AND mask is 4 byte aligned (so that the + // total icon image has a 4 byte alignment). In the 15X15 image example + // above, we can not use 2 bytes so we increase it to the next multiple of + // 4 which is 4. + // + // Once we compute the size for a singe AND mask scan line, we multiply that + // number by the image height in order to get the total number of bytes for + // the AND mask. Thus, for a 15X15 image, we need 15 * 4 which is 60 bytes + // for the monochrome bitmap representing the AND mask. + int and_line_length = (bitmap.width() + 7) >> 3; + and_line_length = (and_line_length + 3) & ~3; + *and_mask_size = and_line_length * bitmap.height(); + int masks_size = *xor_mask_size + *and_mask_size; + *bytes_in_resource = masks_size + sizeof(BITMAPINFOHEADER); +} diff --git a/app/gfx/icon_util.h b/app/gfx/icon_util.h new file mode 100644 index 0000000..9066df9 --- /dev/null +++ b/app/gfx/icon_util.h @@ -0,0 +1,193 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_COMMON_ICON_UTIL_H__ +#define CHROME_COMMON_ICON_UTIL_H__ + +#include <windows.h> +#include <string> +#include <vector> +#include "base/basictypes.h" + +namespace gfx { + class Size; +} +class SkBitmap; + +/////////////////////////////////////////////////////////////////////////////// +// +// The IconUtil class contains helper functions for manipulating Windows icons. +// The class interface contains methods for converting an HICON handle into an +// SkBitmap object and vice versa. The class can also create a .ico file given +// a PNG image contained in an SkBitmap object. The following code snippet +// shows an example usage of IconUtil::CreateHICONFromSkBitmap(): +// +// SkBitmap bitmap; +// +// // Fill |bitmap| with valid data +// bitmap.setConfig(...); +// bitmap.allocPixels(); +// +// ... +// +// // Convert the bitmap into a Windows HICON +// HICON icon = IconUtil::CreateHICONFromSkBitmap(bitmap); +// if (icon == NULL) { +// // Handle error +// ... +// } +// +// // Use the icon with a WM_SETICON message +// ::SendMessage(hwnd, WM_SETICON, static_cast<WPARAM>(ICON_BIG), +// reinterpret_cast<LPARAM>(icon)); +// +// // Destroy the icon when we are done +// ::DestroyIcon(icon); +// +/////////////////////////////////////////////////////////////////////////////// +class IconUtil { + public: + // Given an SkBitmap object, the function converts the bitmap to a Windows + // icon and returns the corresponding HICON handle. If the function can not + // convert the bitmap, NULL is returned. + // + // The client is responsible for destroying the icon when it is no longer + // needed by calling ::DestroyIcon(). + static HICON CreateHICONFromSkBitmap(const SkBitmap& bitmap); + + // Given a valid HICON handle representing an icon, this function converts + // the icon into an SkBitmap object containing an ARGB bitmap using the + // dimensions specified in |s|. |s| must specify valid dimensions (both + // width() an height() must be greater than zero). If the function can + // convert the icon to a bitmap (most probably due to an invalid parameter), + // the return value is NULL. + // + // The client owns the returned bitmap object and is responsible for deleting + // it when it is no longer needed. + static SkBitmap* CreateSkBitmapFromHICON(HICON icon, const gfx::Size& s); + + // Given an initialized SkBitmap object and a file name, this function + // creates a .ico file with the given name using the provided bitmap. The + // icon file is created with multiple icon images of varying predefined + // dimensions because Windows uses different image sizes when loading icons, + // depending on where the icon is drawn (ALT+TAB window, desktop shortcut, + // Quick Launch, etc.). |icon_file_name| needs to specify the full path for + // the desired .ico file. + // + // The function returns true on success and false otherwise. + static bool CreateIconFileFromSkBitmap(const SkBitmap& bitmap, + const std::wstring& icon_file_name); + + private: + // The icon format is published in the MSDN but there is no definition of + // the icon file structures in any of the Windows header files so we need to + // define these structure within the class. We must make sure we use 2 byte + // packing so that the structures are layed out properly within the file. +#pragma pack(push) +#pragma pack(2) + + // ICONDIRENTRY contains meta data for an individual icon image within a + // .ico file. + struct ICONDIRENTRY { + BYTE bWidth; + BYTE bHeight; + BYTE bColorCount; + BYTE bReserved; + WORD wPlanes; + WORD wBitCount; + DWORD dwBytesInRes; + DWORD dwImageOffset; + }; + + // ICONDIR Contains information about all the icon images contained within a + // single .ico file. + struct ICONDIR { + WORD idReserved; + WORD idType; + WORD idCount; + ICONDIRENTRY idEntries[1]; + }; + + // Contains the actual icon image. + struct ICONIMAGE { + BITMAPINFOHEADER icHeader; + RGBQUAD icColors[1]; + BYTE icXOR[1]; + BYTE icAND[1]; + }; +#pragma pack(pop) + + // Used for indicating that the .ico contains an icon (rather than a cursor) + // image. This value is set in the |idType| field of the ICONDIR structure. + static const int kResourceTypeIcon = 1; + + // The dimensions of the icon images we insert into the .ico file. + static const int icon_dimensions_[]; + + // Returns how many icon dimensions are defined. + static int GetIconDimensionCount(); + + // A helper function that initializes a BITMAPV5HEADER structure with a set + // of values. + static void InitializeBitmapHeader(BITMAPV5HEADER* header, int width, + int height); + + // Given a single SkBitmap object and pointers to the corresponding icon + // structures within the icon data buffer, this function sets the image + // information (dimensions, color depth, etc.) in the icon structures and + // also copies the underlying icon image into the appropriate location. + // + // The function will set the data pointed to by |image_byte_count| with the + // number of image bytes written to the buffer. Note that the number of bytes + // includes only the image data written into the memory pointed to by + // |icon_image|. + static void SetSingleIconImageInformation(const SkBitmap& bitmap, + int index, + ICONDIR* icon_dir, + ICONIMAGE* icon_image, + int image_offset, + int* image_byte_count); + + // Copies the bits of an SkBitmap object into a buffer holding the bits of + // the corresponding image for an icon within the .ico file. + static void CopySkBitmapBitsIntoIconBuffer(const SkBitmap& bitmap, + unsigned char* buffer, + int buffer_size); + + // Given a single bitmap, this function creates a set of bitmaps with + // specific dimensions by resizing the given bitmap to the appropriate sizes. + static void CreateResizedBitmapSet(const SkBitmap& bitmap_to_resize, + std::vector<SkBitmap>* bitmaps); + + // Given a set of bitmaps with varying dimensions, this function computes + // the amount of memory needed in order to store the bitmaps as image icons + // in a .ico file. + static int ComputeIconFileBufferSize(const std::vector<SkBitmap>& set); + + // A helper function for computing various size components of a given bitmap. + // The different sizes can be used within the various .ico file structures. + // + // |xor_mask_size| - the size, in bytes, of the XOR mask in the ICONIMAGE + // structure. + // |and_mask_size| - the size, in bytes, of the AND mask in the ICONIMAGE + // structure. + // |bytes_in_resource| - the total number of bytes set in the ICONIMAGE + // structure. This value is equal to the sum of the + // bytes in the AND mask and the XOR mask plus the size + // of the BITMAPINFOHEADER structure. Note that since + // only 32bpp are handled by the IconUtil class, the + // icColors field in the ICONIMAGE structure is ignored + // and is not accounted for when computing the + // different size components. + static void ComputeBitmapSizeComponents(const SkBitmap& bitmap, + int* xor_mask_size, + int* and_mask_size, + int* bytes_in_resource); + + // Prevent clients from instantiating objects of that class by declaring the + // ctor/dtor as private. + DISALLOW_IMPLICIT_CONSTRUCTORS(IconUtil); +}; + +#endif // CHROME_COMMON_ICON_UTIL_H__ diff --git a/app/gfx/icon_util_unittest.cc b/app/gfx/icon_util_unittest.cc new file mode 100644 index 0000000..0b9c200 --- /dev/null +++ b/app/gfx/icon_util_unittest.cc @@ -0,0 +1,264 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <atlbase.h> +#include <atlapp.h> +#include <atlmisc.h> + +#include "app/gfx/icon_util.h" +#include "base/gfx/size.h" +#include "base/scoped_ptr.h" +#include "base/file_util.h" +#include "base/path_service.h" +#include "chrome/common/chrome_paths.h" +#include "skia/include/SkBitmap.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + + static const wchar_t* const kSmallIconName = L"icon_util\\16_X_16_icon.ico"; + static const wchar_t* const kLargeIconName = L"icon_util\\128_X_128_icon.ico"; + static const wchar_t* const kTempIconFilename = L"temp_test_icon.ico"; + + class IconUtilTest : public testing::Test { + public: + IconUtilTest() { + PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory_); + } + ~IconUtilTest() {} + + static const int kSmallIconWidth = 16; + static const int kSmallIconHeight = 16; + static const int kLargeIconWidth = 128; + static const int kLargeIconHeight = 128; + + // Given a file name for an .ico file and an image dimentions, this + // function loads the icon and returns an HICON handle. + HICON LoadIconFromFile(const std::wstring& filename, + int width, + int height) { + HICON icon = + static_cast<HICON>(LoadImage(NULL, + filename.c_str(), + IMAGE_ICON, + width, + height, + LR_LOADTRANSPARENT | LR_LOADFROMFILE)); + return icon; + } + + protected: + // The root directory for test files. + std::wstring test_data_directory_; + + private: + DISALLOW_EVIL_CONSTRUCTORS(IconUtilTest); + }; +}; + +// The following test case makes sure IconUtil::SkBitmapFromHICON fails +// gracefully when called with invalid input parameters. +TEST_F(IconUtilTest, TestIconToBitmapInvalidParameters) { + std::wstring icon_filename(test_data_directory_); + file_util::AppendToPath(&icon_filename, kSmallIconName); + gfx::Size icon_size(kSmallIconWidth, kSmallIconHeight); + HICON icon = LoadIconFromFile(icon_filename, + icon_size.width(), + icon_size.height()); + ASSERT_TRUE(icon != NULL); + + // Invalid size parameter. + gfx::Size invalid_icon_size(kSmallIconHeight, 0); + EXPECT_EQ(IconUtil::CreateSkBitmapFromHICON(icon, invalid_icon_size), + static_cast<SkBitmap*>(NULL)); + + // Invalid icon. + EXPECT_EQ(IconUtil::CreateSkBitmapFromHICON(NULL, icon_size), + static_cast<SkBitmap*>(NULL)); + + // The following code should succeed. + scoped_ptr<SkBitmap> bitmap; + bitmap.reset(IconUtil::CreateSkBitmapFromHICON(icon, icon_size)); + EXPECT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + ::DestroyIcon(icon); +} + +// The following test case makes sure IconUtil::CreateHICONFromSkBitmap fails +// gracefully when called with invalid input parameters. +TEST_F(IconUtilTest, TestBitmapToIconInvalidParameters) { + HICON icon = NULL; + scoped_ptr<SkBitmap> bitmap; + + // Wrong bitmap format. + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kA8_Config, kSmallIconWidth, kSmallIconHeight); + icon = IconUtil::CreateHICONFromSkBitmap(*bitmap); + EXPECT_EQ(icon, static_cast<HICON>(NULL)); + + // Invalid bitmap size. + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kARGB_8888_Config, 0, 0); + icon = IconUtil::CreateHICONFromSkBitmap(*bitmap); + EXPECT_EQ(icon, static_cast<HICON>(NULL)); + + // Valid bitmap configuration but no pixels allocated. + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kARGB_8888_Config, + kSmallIconWidth, + kSmallIconHeight); + icon = IconUtil::CreateHICONFromSkBitmap(*bitmap); + EXPECT_TRUE(icon == NULL); +} + +// The following test case makes sure IconUtil::CreateIconFileFromSkBitmap +// fails gracefully when called with invalid input parameters. +TEST_F(IconUtilTest, TestCreateIconFileInvalidParameters) { + scoped_ptr<SkBitmap> bitmap; + std::wstring valid_icon_filename(test_data_directory_); + file_util::AppendToPath(&valid_icon_filename, kSmallIconName); + std::wstring invalid_icon_filename(L"C:\\<>?.ico"); + + // Wrong bitmap format. + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kA8_Config, kSmallIconWidth, kSmallIconHeight); + EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap, + valid_icon_filename)); + + // Invalid bitmap size. + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kARGB_8888_Config, 0, 0); + EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap, + valid_icon_filename)); + + // Bitmap with no allocated pixels. + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kARGB_8888_Config, + kSmallIconWidth, + kSmallIconHeight); + EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap, + valid_icon_filename)); + + // Invalid file name. + bitmap->allocPixels(); + // Setting the pixels to black. + memset(bitmap->getPixels(), 0, bitmap->width() * bitmap->height() * 4); + EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap, + invalid_icon_filename)); +} + +// This test case makes sure that when we load an icon from disk and convert +// the HICON into a bitmap, the bitmap has the expected format and dimentions. +TEST_F(IconUtilTest, TestCreateSkBitmapFromHICON) { + scoped_ptr<SkBitmap> bitmap; + std::wstring small_icon_filename(test_data_directory_); + file_util::AppendToPath(&small_icon_filename, kSmallIconName); + gfx::Size small_icon_size(kSmallIconWidth, kSmallIconHeight); + HICON small_icon = LoadIconFromFile(small_icon_filename, + small_icon_size.width(), + small_icon_size.height()); + ASSERT_NE(small_icon, static_cast<HICON>(NULL)); + bitmap.reset(IconUtil::CreateSkBitmapFromHICON(small_icon, small_icon_size)); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + EXPECT_EQ(bitmap->width(), small_icon_size.width()); + EXPECT_EQ(bitmap->height(), small_icon_size.height()); + EXPECT_EQ(bitmap->config(), SkBitmap::kARGB_8888_Config); + ::DestroyIcon(small_icon); + + std::wstring large_icon_filename(test_data_directory_); + file_util::AppendToPath(&large_icon_filename, kLargeIconName); + gfx::Size large_icon_size(kLargeIconWidth, kLargeIconHeight); + HICON large_icon = LoadIconFromFile(large_icon_filename, + large_icon_size.width(), + large_icon_size.height()); + ASSERT_NE(large_icon, static_cast<HICON>(NULL)); + bitmap.reset(IconUtil::CreateSkBitmapFromHICON(large_icon, large_icon_size)); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + EXPECT_EQ(bitmap->width(), large_icon_size.width()); + EXPECT_EQ(bitmap->height(), large_icon_size.height()); + EXPECT_EQ(bitmap->config(), SkBitmap::kARGB_8888_Config); + ::DestroyIcon(large_icon); +} + +// This test case makes sure that when an HICON is created from an SkBitmap, +// the returned handle is valid and refers to an icon with the expected +// dimentions color depth etc. +TEST_F(IconUtilTest, TestBasicCreateHICONFromSkBitmap) { + scoped_ptr<SkBitmap> bitmap; + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kARGB_8888_Config, + kSmallIconWidth, + kSmallIconHeight); + bitmap->allocPixels(); + HICON icon = IconUtil::CreateHICONFromSkBitmap(*bitmap); + EXPECT_NE(icon, static_cast<HICON>(NULL)); + ICONINFO icon_info; + ASSERT_TRUE(::GetIconInfo(icon, &icon_info)); + EXPECT_TRUE(icon_info.fIcon); + + // Now that have the icon information, we should obtain the specification of + // the icon's bitmap and make sure it matches the specification of the + // SkBitmap we started with. + // + // The bitmap handle contained in the icon information is a handle to a + // compatible bitmap so we need to call ::GetDIBits() in order to retrieve + // the bitmap's header information. + BITMAPINFO bitmap_info; + ::ZeroMemory(&bitmap_info, sizeof(BITMAPINFO)); + bitmap_info.bmiHeader.biSize = sizeof(BITMAPINFO); + HDC hdc = ::GetDC(NULL); + int result = ::GetDIBits(hdc, + icon_info.hbmColor, + 0, + kSmallIconWidth, + NULL, + &bitmap_info, + DIB_RGB_COLORS); + ASSERT_GT(result, 0); + EXPECT_EQ(bitmap_info.bmiHeader.biWidth, kSmallIconWidth); + EXPECT_EQ(bitmap_info.bmiHeader.biHeight, kSmallIconHeight); + EXPECT_EQ(bitmap_info.bmiHeader.biPlanes, 1); + EXPECT_EQ(bitmap_info.bmiHeader.biBitCount, 32); + ::ReleaseDC(NULL, hdc); + ::DestroyIcon(icon); +} + +// The following test case makes sure IconUtil::CreateIconFileFromSkBitmap +// creates a valid .ico file given an SkBitmap. +TEST_F(IconUtilTest, TestCreateIconFile) { + scoped_ptr<SkBitmap> bitmap; + std::wstring icon_filename(test_data_directory_); + file_util::AppendToPath(&icon_filename, kTempIconFilename); + + // Allocating the bitmap. + bitmap.reset(new SkBitmap); + ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL)); + bitmap->setConfig(SkBitmap::kARGB_8888_Config, + kSmallIconWidth, + kSmallIconHeight); + bitmap->allocPixels(); + + // Setting the pixels to black. + memset(bitmap->getPixels(), 0, bitmap->width() * bitmap->height() * 4); + + EXPECT_TRUE(IconUtil::CreateIconFileFromSkBitmap(*bitmap, + icon_filename)); + + // We are currently only testing that it is possible to load an icon from + // the .ico file we just created. We don't really check the additional icon + // images created by IconUtil::CreateIconFileFromSkBitmap. + HICON icon = LoadIconFromFile(icon_filename, + kSmallIconWidth, + kSmallIconHeight); + EXPECT_NE(icon, static_cast<HICON>(NULL)); + if (icon != NULL) { + ::DestroyIcon(icon); + } +} diff --git a/app/gfx/insets.h b/app/gfx/insets.h new file mode 100644 index 0000000..741de3a2 --- /dev/null +++ b/app/gfx/insets.h @@ -0,0 +1,69 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_COMMON_GFX_INSETS_H__ +#define CHROME_COMMON_GFX_INSETS_H__ + +namespace gfx { + +// +// An insets represents the borders of a container (the space the container must +// leave at each of its edges). +// + +class Insets { + public: + Insets() : top_(0), left_(0), bottom_(0), right_(0) {} + Insets(int top, int left, int bottom, int right) + : top_(top), left_(left), bottom_(bottom), right_(right) { } + + ~Insets() {} + + int top() const { return top_; } + int left() const { return left_; } + int bottom() const { return bottom_; } + int right() const { return right_; } + + // Returns the total width taken up by the insets, which is the sum of the + // left and right insets. + int width() const { return left_ + right_; } + + // Returns the total height taken up by the insets, which is the sum of the + // top and bottom insets. + int height() const { return top_ + bottom_; } + + void Set(int top, int left, int bottom, int right) { + top_ = top; + left_ = left; + bottom_ = bottom; + right_ = right; + } + + bool operator==(const Insets& insets) const { + return top_ == insets.top_ && left_ == insets.left_ && + bottom_ == insets.bottom_ && right_ == insets.right_; + } + + bool operator!=(const Insets& insets) const { + return !(*this == insets); + } + + Insets& operator+=(const Insets& insets) { + top_ += insets.top_; + left_ += insets.left_; + bottom_ += insets.bottom_; + right_ += insets.right_; + return *this; + } + + private: + int top_; + int left_; + int bottom_; + int right_; +}; + +} // namespace + +#endif // CHROME_COMMON_GFX_INSETS_H__ diff --git a/app/gfx/path.h b/app/gfx/path.h new file mode 100644 index 0000000..ac7537c --- /dev/null +++ b/app/gfx/path.h @@ -0,0 +1,40 @@ +// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_COMMON_GFX_CHROME_PATH_H_ +#define CHROME_COMMON_GFX_CHROME_PATH_H_ + +#include "base/basictypes.h" + +#if defined(OS_WIN) +#include <windows.h> +#elif defined(OS_LINUX) +typedef struct _GdkRegion GdkRegion; +#endif + +#include "SkPath.h" + +namespace gfx { + +class Path : public SkPath { + public: + Path() : SkPath() { moveTo(0, 0); } + +#if defined(OS_WIN) + // Creates a HRGN from the path. The caller is responsible for freeing + // resources used by this region. This only supports polygon paths. + HRGN CreateHRGN() const; +#elif defined(OS_LINUX) + // Creates a Gdkregion from the path. The caller is responsible for freeing + // resources used by this region. This only supports polygon paths. + GdkRegion* CreateGdkRegion() const; +#endif + + private: + DISALLOW_COPY_AND_ASSIGN(Path); +}; + +} + +#endif // #ifndef CHROME_COMMON_GFX_CHROME_PATH_H_ diff --git a/app/gfx/path_gtk.cc b/app/gfx/path_gtk.cc new file mode 100644 index 0000000..bc35857 --- /dev/null +++ b/app/gfx/path_gtk.cc @@ -0,0 +1,27 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "app/gfx/path.h" + +#include <gdk/gdk.h> + +#include "base/scoped_ptr.h" + +namespace gfx { + +GdkRegion* Path::CreateGdkRegion() const { + int point_count = getPoints(NULL, 0); + scoped_array<SkPoint> points(new SkPoint[point_count]); + getPoints(points.get(), point_count); + + scoped_array<GdkPoint> gdk_points(new GdkPoint[point_count]); + for (int i = 0; i < point_count; ++i) { + gdk_points[i].x = SkScalarRound(points[i].fX); + gdk_points[i].y = SkScalarRound(points[i].fY); + } + + return gdk_region_polygon(gdk_points.get(), point_count, GDK_EVEN_ODD_RULE); +} + +} // namespace gfx diff --git a/app/gfx/path_win.cc b/app/gfx/path_win.cc new file mode 100644 index 0000000..72fce71 --- /dev/null +++ b/app/gfx/path_win.cc @@ -0,0 +1,24 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "app/gfx/path.h" + +#include "base/scoped_ptr.h" + +namespace gfx { + +HRGN Path::CreateHRGN() const { + int point_count = getPoints(NULL, 0); + scoped_array<SkPoint> points(new SkPoint[point_count]); + getPoints(points.get(), point_count); + scoped_array<POINT> windows_points(new POINT[point_count]); + for (int i = 0; i < point_count; ++i) { + windows_points[i].x = SkScalarRound(points[i].fX); + windows_points[i].y = SkScalarRound(points[i].fY); + } + + return ::CreatePolygonRgn(windows_points.get(), point_count, ALTERNATE); +} + +} // namespace gfx |