Home | History | Annotate | Download | only in themes
      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 "chrome/browser/themes/browser_theme_pack.h"
      6 
      7 #include <limits>
      8 
      9 #include "base/files/file.h"
     10 #include "base/memory/ref_counted_memory.h"
     11 #include "base/memory/scoped_ptr.h"
     12 #include "base/stl_util.h"
     13 #include "base/strings/string_number_conversions.h"
     14 #include "base/strings/string_util.h"
     15 #include "base/strings/utf_string_conversions.h"
     16 #include "base/threading/sequenced_worker_pool.h"
     17 #include "base/threading/thread_restrictions.h"
     18 #include "base/values.h"
     19 #include "chrome/browser/themes/theme_properties.h"
     20 #include "chrome/common/extensions/manifest_handlers/theme_handler.h"
     21 #include "content/public/browser/browser_thread.h"
     22 #include "extensions/common/id_util.h"
     23 #include "grit/theme_resources.h"
     24 #include "grit/ui_resources.h"
     25 #include "third_party/skia/include/core/SkCanvas.h"
     26 #include "ui/base/resource/data_pack.h"
     27 #include "ui/base/resource/resource_bundle.h"
     28 #include "ui/gfx/canvas.h"
     29 #include "ui/gfx/codec/png_codec.h"
     30 #include "ui/gfx/image/canvas_image_source.h"
     31 #include "ui/gfx/image/image.h"
     32 #include "ui/gfx/image/image_skia.h"
     33 #include "ui/gfx/image/image_skia_operations.h"
     34 #include "ui/gfx/screen.h"
     35 #include "ui/gfx/size_conversions.h"
     36 #include "ui/gfx/skia_util.h"
     37 
     38 using content::BrowserThread;
     39 using extensions::Extension;
     40 
     41 namespace {
     42 
     43 // Version number of the current theme pack. We just throw out and rebuild
     44 // theme packs that aren't int-equal to this. Increment this number if you
     45 // change default theme assets.
     46 const int kThemePackVersion = 34;
     47 
     48 // IDs that are in the DataPack won't clash with the positive integer
     49 // uint16. kHeaderID should always have the maximum value because we want the
     50 // "header" to be written last. That way we can detect whether the pack was
     51 // successfully written and ignore and regenerate if it was only partially
     52 // written (i.e. chrome crashed on a different thread while writing the pack).
     53 const int kMaxID = 0x0000FFFF;  // Max unsigned 16-bit int.
     54 const int kHeaderID = kMaxID - 1;
     55 const int kTintsID = kMaxID - 2;
     56 const int kColorsID = kMaxID - 3;
     57 const int kDisplayPropertiesID = kMaxID - 4;
     58 const int kSourceImagesID = kMaxID - 5;
     59 const int kScaleFactorsID = kMaxID - 6;
     60 
     61 // The sum of kFrameBorderThickness and kNonClientRestoredExtraThickness from
     62 // OpaqueBrowserFrameView.
     63 const int kRestoredTabVerticalOffset = 15;
     64 
     65 // Persistent constants for the main images that we need. These have the same
     66 // names as their IDR_* counterparts but these values will always stay the
     67 // same.
     68 const int PRS_THEME_FRAME = 1;
     69 const int PRS_THEME_FRAME_INACTIVE = 2;
     70 const int PRS_THEME_FRAME_INCOGNITO = 3;
     71 const int PRS_THEME_FRAME_INCOGNITO_INACTIVE = 4;
     72 const int PRS_THEME_TOOLBAR = 5;
     73 const int PRS_THEME_TAB_BACKGROUND = 6;
     74 const int PRS_THEME_TAB_BACKGROUND_INCOGNITO = 7;
     75 const int PRS_THEME_TAB_BACKGROUND_V = 8;
     76 const int PRS_THEME_NTP_BACKGROUND = 9;
     77 const int PRS_THEME_FRAME_OVERLAY = 10;
     78 const int PRS_THEME_FRAME_OVERLAY_INACTIVE = 11;
     79 const int PRS_THEME_BUTTON_BACKGROUND = 12;
     80 const int PRS_THEME_NTP_ATTRIBUTION = 13;
     81 const int PRS_THEME_WINDOW_CONTROL_BACKGROUND = 14;
     82 
     83 struct PersistingImagesTable {
     84   // A non-changing integer ID meant to be saved in theme packs. This ID must
     85   // not change between versions of chrome.
     86   int persistent_id;
     87 
     88   // The IDR that depends on the whims of GRIT and therefore changes whenever
     89   // someone adds a new resource.
     90   int idr_id;
     91 
     92   // String to check for when parsing theme manifests or NULL if this isn't
     93   // supposed to be changeable by the user.
     94   const char* key;
     95 };
     96 
     97 // IDR_* resource names change whenever new resources are added; use persistent
     98 // IDs when storing to a cached pack.
     99 PersistingImagesTable kPersistingImages[] = {
    100   { PRS_THEME_FRAME, IDR_THEME_FRAME,
    101     "theme_frame" },
    102   { PRS_THEME_FRAME_INACTIVE, IDR_THEME_FRAME_INACTIVE,
    103     "theme_frame_inactive" },
    104   { PRS_THEME_FRAME_INCOGNITO, IDR_THEME_FRAME_INCOGNITO,
    105     "theme_frame_incognito" },
    106   { PRS_THEME_FRAME_INCOGNITO_INACTIVE, IDR_THEME_FRAME_INCOGNITO_INACTIVE,
    107     "theme_frame_incognito_inactive" },
    108   { PRS_THEME_TOOLBAR, IDR_THEME_TOOLBAR,
    109     "theme_toolbar" },
    110   { PRS_THEME_TAB_BACKGROUND, IDR_THEME_TAB_BACKGROUND,
    111     "theme_tab_background" },
    112   { PRS_THEME_TAB_BACKGROUND_INCOGNITO, IDR_THEME_TAB_BACKGROUND_INCOGNITO,
    113     "theme_tab_background_incognito" },
    114   { PRS_THEME_TAB_BACKGROUND_V, IDR_THEME_TAB_BACKGROUND_V,
    115     "theme_tab_background_v"},
    116   { PRS_THEME_NTP_BACKGROUND, IDR_THEME_NTP_BACKGROUND,
    117     "theme_ntp_background" },
    118   { PRS_THEME_FRAME_OVERLAY, IDR_THEME_FRAME_OVERLAY,
    119     "theme_frame_overlay" },
    120   { PRS_THEME_FRAME_OVERLAY_INACTIVE, IDR_THEME_FRAME_OVERLAY_INACTIVE,
    121     "theme_frame_overlay_inactive" },
    122   { PRS_THEME_BUTTON_BACKGROUND, IDR_THEME_BUTTON_BACKGROUND,
    123     "theme_button_background" },
    124   { PRS_THEME_NTP_ATTRIBUTION, IDR_THEME_NTP_ATTRIBUTION,
    125     "theme_ntp_attribution" },
    126   { PRS_THEME_WINDOW_CONTROL_BACKGROUND, IDR_THEME_WINDOW_CONTROL_BACKGROUND,
    127     "theme_window_control_background"},
    128 
    129   // The rest of these entries have no key because they can't be overridden
    130   // from the json manifest.
    131   { 15, IDR_BACK, NULL },
    132   { 16, IDR_BACK_D, NULL },
    133   { 17, IDR_BACK_H, NULL },
    134   { 18, IDR_BACK_P, NULL },
    135   { 19, IDR_FORWARD, NULL },
    136   { 20, IDR_FORWARD_D, NULL },
    137   { 21, IDR_FORWARD_H, NULL },
    138   { 22, IDR_FORWARD_P, NULL },
    139   { 23, IDR_HOME, NULL },
    140   { 24, IDR_HOME_H, NULL },
    141   { 25, IDR_HOME_P, NULL },
    142   { 26, IDR_RELOAD, NULL },
    143   { 27, IDR_RELOAD_H, NULL },
    144   { 28, IDR_RELOAD_P, NULL },
    145   { 29, IDR_STOP, NULL },
    146   { 30, IDR_STOP_D, NULL },
    147   { 31, IDR_STOP_H, NULL },
    148   { 32, IDR_STOP_P, NULL },
    149   { 33, IDR_BROWSER_ACTIONS_OVERFLOW, NULL },
    150   { 34, IDR_BROWSER_ACTIONS_OVERFLOW_H, NULL },
    151   { 35, IDR_BROWSER_ACTIONS_OVERFLOW_P, NULL },
    152   { 36, IDR_TOOLS, NULL },
    153   { 37, IDR_TOOLS_H, NULL },
    154   { 38, IDR_TOOLS_P, NULL },
    155   { 39, IDR_MENU_DROPARROW, NULL },
    156   { 40, IDR_THROBBER, NULL },
    157   { 41, IDR_THROBBER_WAITING, NULL },
    158   { 42, IDR_THROBBER_LIGHT, NULL },
    159   { 43, IDR_TOOLBAR_BEZEL_HOVER, NULL },
    160   { 44, IDR_TOOLBAR_BEZEL_PRESSED, NULL },
    161   { 45, IDR_TOOLS_BAR, NULL },
    162 };
    163 const size_t kPersistingImagesLength = arraysize(kPersistingImages);
    164 
    165 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
    166 // Persistent theme ids for Windows.
    167 const int PRS_THEME_FRAME_DESKTOP = 100;
    168 const int PRS_THEME_FRAME_INACTIVE_DESKTOP = 101;
    169 const int PRS_THEME_FRAME_INCOGNITO_DESKTOP = 102;
    170 const int PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP = 103;
    171 const int PRS_THEME_TOOLBAR_DESKTOP = 104;
    172 const int PRS_THEME_TAB_BACKGROUND_DESKTOP = 105;
    173 const int PRS_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP = 106;
    174 
    175 // Persistent theme to resource id mapping for Windows AURA.
    176 PersistingImagesTable kPersistingImagesDesktopAura[] = {
    177   { PRS_THEME_FRAME_DESKTOP, IDR_THEME_FRAME_DESKTOP,
    178     "theme_frame" },
    179   { PRS_THEME_FRAME_INACTIVE_DESKTOP, IDR_THEME_FRAME_INACTIVE_DESKTOP,
    180     "theme_frame_inactive" },
    181   { PRS_THEME_FRAME_INCOGNITO_DESKTOP, IDR_THEME_FRAME_INCOGNITO_DESKTOP,
    182     "theme_frame_incognito" },
    183   { PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP,
    184     IDR_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP,
    185     "theme_frame_incognito_inactive" },
    186   { PRS_THEME_TOOLBAR_DESKTOP, IDR_THEME_TOOLBAR_DESKTOP,
    187     "theme_toolbar" },
    188   { PRS_THEME_TAB_BACKGROUND_DESKTOP, IDR_THEME_TAB_BACKGROUND_DESKTOP,
    189     "theme_tab_background" },
    190   { PRS_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
    191     IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
    192     "theme_tab_background_incognito" },
    193 };
    194 const size_t kPersistingImagesDesktopAuraLength =
    195     arraysize(kPersistingImagesDesktopAura);
    196 #endif
    197 
    198 int GetPersistentIDByNameHelper(const std::string& key,
    199                                 const PersistingImagesTable* image_table,
    200                                 size_t image_table_size) {
    201   for (size_t i = 0; i < image_table_size; ++i) {
    202     if (image_table[i].key != NULL &&
    203         base::strcasecmp(key.c_str(), image_table[i].key) == 0) {
    204       return image_table[i].persistent_id;
    205     }
    206   }
    207   return -1;
    208 }
    209 
    210 int GetPersistentIDByName(const std::string& key) {
    211   return GetPersistentIDByNameHelper(key,
    212                                      kPersistingImages,
    213                                      kPersistingImagesLength);
    214 }
    215 
    216 int GetPersistentIDByIDR(int idr) {
    217   static std::map<int,int>* lookup_table = new std::map<int,int>();
    218   if (lookup_table->empty()) {
    219     for (size_t i = 0; i < kPersistingImagesLength; ++i) {
    220       int idr = kPersistingImages[i].idr_id;
    221       int prs_id = kPersistingImages[i].persistent_id;
    222       (*lookup_table)[idr] = prs_id;
    223     }
    224 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
    225     for (size_t i = 0; i < kPersistingImagesDesktopAuraLength; ++i) {
    226       int idr = kPersistingImagesDesktopAura[i].idr_id;
    227       int prs_id = kPersistingImagesDesktopAura[i].persistent_id;
    228       (*lookup_table)[idr] = prs_id;
    229     }
    230 #endif
    231   }
    232   std::map<int,int>::iterator it = lookup_table->find(idr);
    233   return (it == lookup_table->end()) ? -1 : it->second;
    234 }
    235 
    236 // Returns true if the scales in |input| match those in |expected|.
    237 // The order must match as the index is used in determining the raw id.
    238 bool InputScalesValid(const base::StringPiece& input,
    239                       const std::vector<ui::ScaleFactor>& expected) {
    240   size_t scales_size = static_cast<size_t>(input.size() / sizeof(float));
    241   if (scales_size != expected.size())
    242     return false;
    243   scoped_ptr<float[]> scales(new float[scales_size]);
    244   // Do a memcpy to avoid misaligned memory access.
    245   memcpy(scales.get(), input.data(), input.size());
    246   for (size_t index = 0; index < scales_size; ++index) {
    247     if (scales[index] != ui::GetScaleForScaleFactor(expected[index]))
    248       return false;
    249   }
    250   return true;
    251 }
    252 
    253 // Returns |scale_factors| as a string to be written to disk.
    254 std::string GetScaleFactorsAsString(
    255     const std::vector<ui::ScaleFactor>& scale_factors) {
    256   scoped_ptr<float[]> scales(new float[scale_factors.size()]);
    257   for (size_t i = 0; i < scale_factors.size(); ++i)
    258     scales[i] = ui::GetScaleForScaleFactor(scale_factors[i]);
    259   std::string out_string = std::string(
    260       reinterpret_cast<const char*>(scales.get()),
    261       scale_factors.size() * sizeof(float));
    262   return out_string;
    263 }
    264 
    265 struct StringToIntTable {
    266   const char* key;
    267   ThemeProperties::OverwritableByUserThemeProperty id;
    268 };
    269 
    270 // Strings used by themes to identify tints in the JSON.
    271 StringToIntTable kTintTable[] = {
    272   { "buttons", ThemeProperties::TINT_BUTTONS },
    273   { "frame", ThemeProperties::TINT_FRAME },
    274   { "frame_inactive", ThemeProperties::TINT_FRAME_INACTIVE },
    275   { "frame_incognito", ThemeProperties::TINT_FRAME_INCOGNITO },
    276   { "frame_incognito_inactive",
    277     ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE },
    278   { "background_tab", ThemeProperties::TINT_BACKGROUND_TAB },
    279 };
    280 const size_t kTintTableLength = arraysize(kTintTable);
    281 
    282 // Strings used by themes to identify colors in the JSON.
    283 StringToIntTable kColorTable[] = {
    284   { "frame", ThemeProperties::COLOR_FRAME },
    285   { "frame_inactive", ThemeProperties::COLOR_FRAME_INACTIVE },
    286   { "frame_incognito", ThemeProperties::COLOR_FRAME_INCOGNITO },
    287   { "frame_incognito_inactive",
    288     ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE },
    289   { "toolbar", ThemeProperties::COLOR_TOOLBAR },
    290   { "tab_text", ThemeProperties::COLOR_TAB_TEXT },
    291   { "tab_background_text", ThemeProperties::COLOR_BACKGROUND_TAB_TEXT },
    292   { "bookmark_text", ThemeProperties::COLOR_BOOKMARK_TEXT },
    293   { "ntp_background", ThemeProperties::COLOR_NTP_BACKGROUND },
    294   { "ntp_text", ThemeProperties::COLOR_NTP_TEXT },
    295   { "ntp_link", ThemeProperties::COLOR_NTP_LINK },
    296   { "ntp_link_underline", ThemeProperties::COLOR_NTP_LINK_UNDERLINE },
    297   { "ntp_header", ThemeProperties::COLOR_NTP_HEADER },
    298   { "ntp_section", ThemeProperties::COLOR_NTP_SECTION },
    299   { "ntp_section_text", ThemeProperties::COLOR_NTP_SECTION_TEXT },
    300   { "ntp_section_link", ThemeProperties::COLOR_NTP_SECTION_LINK },
    301   { "ntp_section_link_underline",
    302     ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE },
    303   { "button_background", ThemeProperties::COLOR_BUTTON_BACKGROUND },
    304 };
    305 const size_t kColorTableLength = arraysize(kColorTable);
    306 
    307 // Strings used by themes to identify display properties keys in JSON.
    308 StringToIntTable kDisplayProperties[] = {
    309   { "ntp_background_alignment",
    310     ThemeProperties::NTP_BACKGROUND_ALIGNMENT },
    311   { "ntp_background_repeat", ThemeProperties::NTP_BACKGROUND_TILING },
    312   { "ntp_logo_alternate", ThemeProperties::NTP_LOGO_ALTERNATE },
    313 };
    314 const size_t kDisplayPropertiesSize = arraysize(kDisplayProperties);
    315 
    316 int GetIntForString(const std::string& key,
    317                     StringToIntTable* table,
    318                     size_t table_length) {
    319   for (size_t i = 0; i < table_length; ++i) {
    320     if (base::strcasecmp(key.c_str(), table[i].key) == 0) {
    321       return table[i].id;
    322     }
    323   }
    324 
    325   return -1;
    326 }
    327 
    328 struct IntToIntTable {
    329   int key;
    330   int value;
    331 };
    332 
    333 // Mapping used in CreateFrameImages() to associate frame images with the
    334 // tint ID that should maybe be applied to it.
    335 IntToIntTable kFrameTintMap[] = {
    336   { PRS_THEME_FRAME, ThemeProperties::TINT_FRAME },
    337   { PRS_THEME_FRAME_INACTIVE, ThemeProperties::TINT_FRAME_INACTIVE },
    338   { PRS_THEME_FRAME_OVERLAY, ThemeProperties::TINT_FRAME },
    339   { PRS_THEME_FRAME_OVERLAY_INACTIVE,
    340     ThemeProperties::TINT_FRAME_INACTIVE },
    341   { PRS_THEME_FRAME_INCOGNITO, ThemeProperties::TINT_FRAME_INCOGNITO },
    342   { PRS_THEME_FRAME_INCOGNITO_INACTIVE,
    343     ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE },
    344 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
    345   { PRS_THEME_FRAME_DESKTOP, ThemeProperties::TINT_FRAME },
    346   { PRS_THEME_FRAME_INACTIVE_DESKTOP, ThemeProperties::TINT_FRAME_INACTIVE },
    347   { PRS_THEME_FRAME_INCOGNITO_DESKTOP, ThemeProperties::TINT_FRAME_INCOGNITO },
    348   { PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP,
    349     ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE },
    350 #endif
    351 };
    352 
    353 // Mapping used in GenerateTabBackgroundImages() to associate what frame image
    354 // goes with which tab background.
    355 IntToIntTable kTabBackgroundMap[] = {
    356   { PRS_THEME_TAB_BACKGROUND, PRS_THEME_FRAME },
    357   { PRS_THEME_TAB_BACKGROUND_INCOGNITO, PRS_THEME_FRAME_INCOGNITO },
    358 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
    359   { PRS_THEME_TAB_BACKGROUND_DESKTOP, PRS_THEME_FRAME_DESKTOP },
    360   { PRS_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
    361     PRS_THEME_FRAME_INCOGNITO_DESKTOP },
    362 #endif
    363 };
    364 
    365 struct CropEntry {
    366   int prs_id;
    367 
    368   // The maximum useful height of the image at |prs_id|.
    369   int max_height;
    370 
    371   // Whether cropping the image at |prs_id| should be skipped on OSes which
    372   // have a frame border to the left and right of the web contents.
    373   // This should be true for images which can be used to decorate the border to
    374   // the left and the right of the web contents.
    375   bool skip_if_frame_border;
    376 };
    377 
    378 // The images which should be cropped before being saved to the data pack. The
    379 // maximum heights are meant to be conservative as to give room for the UI to
    380 // change without the maximum heights having to be modified.
    381 // |kThemePackVersion| must be incremented if any of the maximum heights below
    382 // are modified.
    383 struct CropEntry kImagesToCrop[] = {
    384   { PRS_THEME_FRAME, 120, true },
    385   { PRS_THEME_FRAME_INACTIVE, 120, true },
    386   { PRS_THEME_FRAME_INCOGNITO, 120, true },
    387   { PRS_THEME_FRAME_INCOGNITO_INACTIVE, 120, true },
    388   { PRS_THEME_FRAME_OVERLAY, 120, true },
    389   { PRS_THEME_FRAME_OVERLAY_INACTIVE, 120, true },
    390   { PRS_THEME_TOOLBAR, 200, false },
    391   { PRS_THEME_BUTTON_BACKGROUND, 60, false },
    392   { PRS_THEME_WINDOW_CONTROL_BACKGROUND, 50, false },
    393 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
    394   { PRS_THEME_TOOLBAR_DESKTOP, 200, false }
    395 #endif
    396 };
    397 
    398 
    399 // A list of images that don't need tinting or any other modification and can
    400 // be byte-copied directly into the finished DataPack. This should contain the
    401 // persistent IDs for all themeable image IDs that aren't in kFrameTintMap,
    402 // kTabBackgroundMap or kImagesToCrop.
    403 const int kPreloadIDs[] = {
    404   PRS_THEME_NTP_BACKGROUND,
    405   PRS_THEME_NTP_ATTRIBUTION,
    406 };
    407 
    408 // Returns true if this OS uses a browser frame which has a non zero width to
    409 // the left and the right of the web contents.
    410 bool HasFrameBorder() {
    411 #if defined(OS_CHROMEOS) || defined(OS_MACOSX)
    412   return false;
    413 #else
    414   return true;
    415 #endif
    416 }
    417 
    418 // Returns a piece of memory with the contents of the file |path|.
    419 base::RefCountedMemory* ReadFileData(const base::FilePath& path) {
    420   if (!path.empty()) {
    421     base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ);
    422     if (file.IsValid()) {
    423       int64 length = file.GetLength();
    424       if (length > 0 && length < INT_MAX) {
    425         int size = static_cast<int>(length);
    426         std::vector<unsigned char> raw_data;
    427         raw_data.resize(size);
    428         char* data = reinterpret_cast<char*>(&(raw_data.front()));
    429         if (file.ReadAtCurrentPos(data, size) == length)
    430           return base::RefCountedBytes::TakeVector(&raw_data);
    431       }
    432     }
    433   }
    434 
    435   return NULL;
    436 }
    437 
    438 // Shifts an image's HSL values. The caller is responsible for deleting
    439 // the returned image.
    440 gfx::Image CreateHSLShiftedImage(const gfx::Image& image,
    441                                  const color_utils::HSL& hsl_shift) {
    442   const gfx::ImageSkia* src_image = image.ToImageSkia();
    443   return gfx::Image(gfx::ImageSkiaOperations::CreateHSLShiftedImage(
    444       *src_image, hsl_shift));
    445 }
    446 
    447 // Computes a bitmap at one scale from a bitmap at a different scale.
    448 SkBitmap CreateLowQualityResizedBitmap(const SkBitmap& source_bitmap,
    449                                        ui::ScaleFactor source_scale_factor,
    450                                        ui::ScaleFactor desired_scale_factor) {
    451   gfx::Size scaled_size = gfx::ToCeiledSize(
    452       gfx::ScaleSize(gfx::Size(source_bitmap.width(),
    453                                source_bitmap.height()),
    454                      ui::GetScaleForScaleFactor(desired_scale_factor) /
    455                      ui::GetScaleForScaleFactor(source_scale_factor)));
    456   SkBitmap scaled_bitmap;
    457   scaled_bitmap.setConfig(SkBitmap::kARGB_8888_Config,
    458                           scaled_size.width(),
    459                           scaled_size.height());
    460   if (!scaled_bitmap.allocPixels())
    461     SK_CRASH();
    462   scaled_bitmap.eraseARGB(0, 0, 0, 0);
    463   SkCanvas canvas(scaled_bitmap);
    464   SkRect scaled_bounds = RectToSkRect(gfx::Rect(scaled_size));
    465   // Note(oshima): The following scaling code doesn't work with
    466   // a mask image.
    467   canvas.drawBitmapRect(source_bitmap, NULL, scaled_bounds);
    468   return scaled_bitmap;
    469 }
    470 
    471 // A ImageSkiaSource that scales 100P image to the target scale factor
    472 // if the ImageSkiaRep for the target scale factor isn't available.
    473 class ThemeImageSource: public gfx::ImageSkiaSource {
    474  public:
    475   explicit ThemeImageSource(const gfx::ImageSkia& source) : source_(source) {
    476   }
    477   virtual ~ThemeImageSource() {}
    478 
    479   virtual gfx::ImageSkiaRep GetImageForScale(float scale) OVERRIDE {
    480     if (source_.HasRepresentation(scale))
    481       return source_.GetRepresentation(scale);
    482     const gfx::ImageSkiaRep& rep_100p = source_.GetRepresentation(1.0f);
    483     SkBitmap scaled_bitmap = CreateLowQualityResizedBitmap(
    484         rep_100p.sk_bitmap(),
    485         ui::SCALE_FACTOR_100P,
    486         ui::GetSupportedScaleFactor(scale));
    487     return gfx::ImageSkiaRep(scaled_bitmap, scale);
    488   }
    489 
    490  private:
    491   const gfx::ImageSkia source_;
    492 
    493   DISALLOW_COPY_AND_ASSIGN(ThemeImageSource);
    494 };
    495 
    496 // An ImageSkiaSource that delays decoding PNG data into bitmaps until
    497 // needed. Missing data for a scale factor is computed by scaling data for an
    498 // available scale factor. Computed bitmaps are stored for future look up.
    499 class ThemeImagePngSource : public gfx::ImageSkiaSource {
    500  public:
    501   typedef std::map<ui::ScaleFactor,
    502                    scoped_refptr<base::RefCountedMemory> > PngMap;
    503 
    504   explicit ThemeImagePngSource(const PngMap& png_map) : png_map_(png_map) {}
    505 
    506   virtual ~ThemeImagePngSource() {}
    507 
    508  private:
    509   virtual gfx::ImageSkiaRep GetImageForScale(float scale) OVERRIDE {
    510     ui::ScaleFactor scale_factor = ui::GetSupportedScaleFactor(scale);
    511     // Look up the bitmap for |scale factor| in the bitmap map. If found
    512     // return it.
    513     BitmapMap::const_iterator exact_bitmap_it = bitmap_map_.find(scale_factor);
    514     if (exact_bitmap_it != bitmap_map_.end())
    515       return gfx::ImageSkiaRep(exact_bitmap_it->second, scale);
    516 
    517     // Look up the raw PNG data for |scale_factor| in the png map. If found,
    518     // decode it, store the result in the bitmap map and return it.
    519     PngMap::const_iterator exact_png_it = png_map_.find(scale_factor);
    520     if (exact_png_it != png_map_.end()) {
    521       SkBitmap bitmap;
    522       if (!gfx::PNGCodec::Decode(exact_png_it->second->front(),
    523                                  exact_png_it->second->size(),
    524                                  &bitmap)) {
    525         NOTREACHED();
    526         return gfx::ImageSkiaRep();
    527       }
    528       bitmap_map_[scale_factor] = bitmap;
    529       return gfx::ImageSkiaRep(bitmap, scale);
    530     }
    531 
    532     // Find an available PNG for another scale factor. We want to use the
    533     // highest available scale factor.
    534     PngMap::const_iterator available_png_it = png_map_.end();
    535     for (PngMap::const_iterator png_it = png_map_.begin();
    536          png_it != png_map_.end(); ++png_it) {
    537       if (available_png_it == png_map_.end() ||
    538           ui::GetScaleForScaleFactor(png_it->first) >
    539           ui::GetScaleForScaleFactor(available_png_it->first)) {
    540         available_png_it = png_it;
    541       }
    542     }
    543     if (available_png_it == png_map_.end())
    544       return gfx::ImageSkiaRep();
    545     ui::ScaleFactor available_scale_factor = available_png_it->first;
    546 
    547     // Look up the bitmap for |available_scale_factor| in the bitmap map.
    548     // If not found, decode the corresponging png data, store the result
    549     // in the bitmap map.
    550     BitmapMap::const_iterator available_bitmap_it =
    551         bitmap_map_.find(available_scale_factor);
    552     if (available_bitmap_it == bitmap_map_.end()) {
    553       SkBitmap available_bitmap;
    554       if (!gfx::PNGCodec::Decode(available_png_it->second->front(),
    555                                  available_png_it->second->size(),
    556                                  &available_bitmap)) {
    557         NOTREACHED();
    558         return gfx::ImageSkiaRep();
    559       }
    560       bitmap_map_[available_scale_factor] = available_bitmap;
    561       available_bitmap_it = bitmap_map_.find(available_scale_factor);
    562     }
    563 
    564     // Scale the available bitmap to the desired scale factor, store the result
    565     // in the bitmap map and return it.
    566     SkBitmap scaled_bitmap = CreateLowQualityResizedBitmap(
    567         available_bitmap_it->second,
    568         available_scale_factor,
    569         scale_factor);
    570     bitmap_map_[scale_factor] = scaled_bitmap;
    571     return gfx::ImageSkiaRep(scaled_bitmap, scale);
    572   }
    573 
    574   PngMap png_map_;
    575 
    576   typedef std::map<ui::ScaleFactor, SkBitmap> BitmapMap;
    577   BitmapMap bitmap_map_;
    578 
    579   DISALLOW_COPY_AND_ASSIGN(ThemeImagePngSource);
    580 };
    581 
    582 class TabBackgroundImageSource: public gfx::CanvasImageSource {
    583  public:
    584   TabBackgroundImageSource(const gfx::ImageSkia& image_to_tint,
    585                            const gfx::ImageSkia& overlay,
    586                            const color_utils::HSL& hsl_shift,
    587                            int vertical_offset)
    588       : gfx::CanvasImageSource(image_to_tint.size(), false),
    589         image_to_tint_(image_to_tint),
    590         overlay_(overlay),
    591         hsl_shift_(hsl_shift),
    592         vertical_offset_(vertical_offset) {
    593   }
    594 
    595   virtual ~TabBackgroundImageSource() {
    596   }
    597 
    598   // Overridden from CanvasImageSource:
    599   virtual void Draw(gfx::Canvas* canvas) OVERRIDE {
    600     gfx::ImageSkia bg_tint =
    601         gfx::ImageSkiaOperations::CreateHSLShiftedImage(image_to_tint_,
    602             hsl_shift_);
    603     canvas->TileImageInt(bg_tint, 0, vertical_offset_, 0, 0,
    604         size().width(), size().height());
    605 
    606     // If they've provided a custom image, overlay it.
    607     if (!overlay_.isNull()) {
    608       canvas->TileImageInt(overlay_, 0, 0, size().width(),
    609                            overlay_.height());
    610     }
    611   }
    612 
    613  private:
    614   const gfx::ImageSkia image_to_tint_;
    615   const gfx::ImageSkia overlay_;
    616   const color_utils::HSL hsl_shift_;
    617   const int vertical_offset_;
    618 
    619   DISALLOW_COPY_AND_ASSIGN(TabBackgroundImageSource);
    620 };
    621 
    622 }  // namespace
    623 
    624 BrowserThemePack::~BrowserThemePack() {
    625   if (!data_pack_.get()) {
    626     delete header_;
    627     delete [] tints_;
    628     delete [] colors_;
    629     delete [] display_properties_;
    630     delete [] source_images_;
    631   }
    632 }
    633 
    634 // static
    635 scoped_refptr<BrowserThemePack> BrowserThemePack::BuildFromExtension(
    636     const Extension* extension) {
    637   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    638   DCHECK(extension);
    639   DCHECK(extension->is_theme());
    640 
    641   scoped_refptr<BrowserThemePack> pack(new BrowserThemePack);
    642   pack->BuildHeader(extension);
    643   pack->BuildTintsFromJSON(extensions::ThemeInfo::GetTints(extension));
    644   pack->BuildColorsFromJSON(extensions::ThemeInfo::GetColors(extension));
    645   pack->BuildDisplayPropertiesFromJSON(
    646       extensions::ThemeInfo::GetDisplayProperties(extension));
    647 
    648   // Builds the images. (Image building is dependent on tints).
    649   FilePathMap file_paths;
    650   pack->ParseImageNamesFromJSON(
    651       extensions::ThemeInfo::GetImages(extension),
    652       extension->path(),
    653       &file_paths);
    654   pack->BuildSourceImagesArray(file_paths);
    655 
    656   if (!pack->LoadRawBitmapsTo(file_paths, &pack->images_on_ui_thread_))
    657     return NULL;
    658 
    659   pack->CreateImages(&pack->images_on_ui_thread_);
    660 
    661   // Make sure the |images_on_file_thread_| has bitmaps for supported
    662   // scale factors before passing to FILE thread.
    663   pack->images_on_file_thread_ = pack->images_on_ui_thread_;
    664   for (ImageCache::iterator it = pack->images_on_file_thread_.begin();
    665        it != pack->images_on_file_thread_.end(); ++it) {
    666     gfx::ImageSkia* image_skia =
    667         const_cast<gfx::ImageSkia*>(it->second.ToImageSkia());
    668     image_skia->MakeThreadSafe();
    669   }
    670 
    671   // Set ThemeImageSource on |images_on_ui_thread_| to resample the source
    672   // image if a caller of BrowserThemePack::GetImageNamed() requests an
    673   // ImageSkiaRep for a scale factor not specified by the theme author.
    674   // Callers of BrowserThemePack::GetImageNamed() to be able to retrieve
    675   // ImageSkiaReps for all supported scale factors.
    676   for (ImageCache::iterator it = pack->images_on_ui_thread_.begin();
    677        it != pack->images_on_ui_thread_.end(); ++it) {
    678     const gfx::ImageSkia source_image_skia = it->second.AsImageSkia();
    679     ThemeImageSource* source = new ThemeImageSource(source_image_skia);
    680     // image_skia takes ownership of source.
    681     gfx::ImageSkia image_skia(source, source_image_skia.size());
    682     it->second = gfx::Image(image_skia);
    683   }
    684 
    685   // Generate raw images (for new-tab-page attribution and background) for
    686   // any missing scale from an available scale image.
    687   for (size_t i = 0; i < arraysize(kPreloadIDs); ++i) {
    688     pack->GenerateRawImageForAllSupportedScales(kPreloadIDs[i]);
    689   }
    690 
    691   // The BrowserThemePack is now in a consistent state.
    692   return pack;
    693 }
    694 
    695 // static
    696 scoped_refptr<BrowserThemePack> BrowserThemePack::BuildFromDataPack(
    697     const base::FilePath& path, const std::string& expected_id) {
    698   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    699   // Allow IO on UI thread due to deep-seated theme design issues.
    700   // (see http://crbug.com/80206)
    701   base::ThreadRestrictions::ScopedAllowIO allow_io;
    702   scoped_refptr<BrowserThemePack> pack(new BrowserThemePack);
    703   // Scale factor parameter is moot as data pack has image resources for all
    704   // supported scale factors.
    705   pack->data_pack_.reset(
    706       new ui::DataPack(ui::SCALE_FACTOR_NONE));
    707 
    708   if (!pack->data_pack_->LoadFromPath(path)) {
    709     LOG(ERROR) << "Failed to load theme data pack.";
    710     return NULL;
    711   }
    712 
    713   base::StringPiece pointer;
    714   if (!pack->data_pack_->GetStringPiece(kHeaderID, &pointer))
    715     return NULL;
    716   pack->header_ = reinterpret_cast<BrowserThemePackHeader*>(const_cast<char*>(
    717       pointer.data()));
    718 
    719   if (pack->header_->version != kThemePackVersion) {
    720     DLOG(ERROR) << "BuildFromDataPack failure! Version mismatch!";
    721     return NULL;
    722   }
    723   // TODO(erg): Check endianess once DataPack works on the other endian.
    724   std::string theme_id(reinterpret_cast<char*>(pack->header_->theme_id),
    725                        extensions::id_util::kIdSize);
    726   std::string truncated_id =
    727       expected_id.substr(0, extensions::id_util::kIdSize);
    728   if (theme_id != truncated_id) {
    729     DLOG(ERROR) << "Wrong id: " << theme_id << " vs " << expected_id;
    730     return NULL;
    731   }
    732 
    733   if (!pack->data_pack_->GetStringPiece(kTintsID, &pointer))
    734     return NULL;
    735   pack->tints_ = reinterpret_cast<TintEntry*>(const_cast<char*>(
    736       pointer.data()));
    737 
    738   if (!pack->data_pack_->GetStringPiece(kColorsID, &pointer))
    739     return NULL;
    740   pack->colors_ =
    741       reinterpret_cast<ColorPair*>(const_cast<char*>(pointer.data()));
    742 
    743   if (!pack->data_pack_->GetStringPiece(kDisplayPropertiesID, &pointer))
    744     return NULL;
    745   pack->display_properties_ = reinterpret_cast<DisplayPropertyPair*>(
    746       const_cast<char*>(pointer.data()));
    747 
    748   if (!pack->data_pack_->GetStringPiece(kSourceImagesID, &pointer))
    749     return NULL;
    750   pack->source_images_ = reinterpret_cast<int*>(
    751       const_cast<char*>(pointer.data()));
    752 
    753   if (!pack->data_pack_->GetStringPiece(kScaleFactorsID, &pointer))
    754     return NULL;
    755 
    756   if (!InputScalesValid(pointer, pack->scale_factors_)) {
    757     DLOG(ERROR) << "BuildFromDataPack failure! The pack scale factors differ "
    758                 << "from those supported by platform.";
    759     return NULL;
    760   }
    761   return pack;
    762 }
    763 
    764 // static
    765 void BrowserThemePack::GetThemeableImageIDRs(std::set<int>* result) {
    766   if (!result)
    767     return;
    768 
    769   result->clear();
    770   for (size_t i = 0; i < kPersistingImagesLength; ++i)
    771     result->insert(kPersistingImages[i].idr_id);
    772 
    773 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
    774   for (size_t i = 0; i < kPersistingImagesDesktopAuraLength; ++i)
    775     result->insert(kPersistingImagesDesktopAura[i].idr_id);
    776 #endif
    777 }
    778 
    779 bool BrowserThemePack::WriteToDisk(const base::FilePath& path) const {
    780   // Add resources for each of the property arrays.
    781   RawDataForWriting resources;
    782   resources[kHeaderID] = base::StringPiece(
    783       reinterpret_cast<const char*>(header_), sizeof(BrowserThemePackHeader));
    784   resources[kTintsID] = base::StringPiece(
    785       reinterpret_cast<const char*>(tints_),
    786       sizeof(TintEntry[kTintTableLength]));
    787   resources[kColorsID] = base::StringPiece(
    788       reinterpret_cast<const char*>(colors_),
    789       sizeof(ColorPair[kColorTableLength]));
    790   resources[kDisplayPropertiesID] = base::StringPiece(
    791       reinterpret_cast<const char*>(display_properties_),
    792       sizeof(DisplayPropertyPair[kDisplayPropertiesSize]));
    793 
    794   int source_count = 1;
    795   int* end = source_images_;
    796   for (; *end != -1 ; end++)
    797     source_count++;
    798   resources[kSourceImagesID] = base::StringPiece(
    799       reinterpret_cast<const char*>(source_images_),
    800       source_count * sizeof(*source_images_));
    801 
    802   // Store results of GetScaleFactorsAsString() in std::string as
    803   // base::StringPiece does not copy data in constructor.
    804   std::string scale_factors_string = GetScaleFactorsAsString(scale_factors_);
    805   resources[kScaleFactorsID] = scale_factors_string;
    806 
    807   AddRawImagesTo(image_memory_, &resources);
    808 
    809   RawImages reencoded_images;
    810   RepackImages(images_on_file_thread_, &reencoded_images);
    811   AddRawImagesTo(reencoded_images, &resources);
    812 
    813   return ui::DataPack::WritePack(path, resources, ui::DataPack::BINARY);
    814 }
    815 
    816 bool BrowserThemePack::GetTint(int id, color_utils::HSL* hsl) const {
    817   if (tints_) {
    818     for (size_t i = 0; i < kTintTableLength; ++i) {
    819       if (tints_[i].id == id) {
    820         hsl->h = tints_[i].h;
    821         hsl->s = tints_[i].s;
    822         hsl->l = tints_[i].l;
    823         return true;
    824       }
    825     }
    826   }
    827 
    828   return false;
    829 }
    830 
    831 bool BrowserThemePack::GetColor(int id, SkColor* color) const {
    832   if (colors_) {
    833     for (size_t i = 0; i < kColorTableLength; ++i) {
    834       if (colors_[i].id == id) {
    835         *color = colors_[i].color;
    836         return true;
    837       }
    838     }
    839   }
    840 
    841   return false;
    842 }
    843 
    844 bool BrowserThemePack::GetDisplayProperty(int id, int* result) const {
    845   if (display_properties_) {
    846     for (size_t i = 0; i < kDisplayPropertiesSize; ++i) {
    847       if (display_properties_[i].id == id) {
    848         *result = display_properties_[i].property;
    849         return true;
    850       }
    851     }
    852   }
    853 
    854   return false;
    855 }
    856 
    857 gfx::Image BrowserThemePack::GetImageNamed(int idr_id) {
    858   int prs_id = GetPersistentIDByIDR(idr_id);
    859   if (prs_id == -1)
    860     return gfx::Image();
    861 
    862   // Check if the image is cached.
    863   ImageCache::const_iterator image_iter = images_on_ui_thread_.find(prs_id);
    864   if (image_iter != images_on_ui_thread_.end())
    865     return image_iter->second;
    866 
    867   ThemeImagePngSource::PngMap png_map;
    868   for (size_t i = 0; i < scale_factors_.size(); ++i) {
    869     scoped_refptr<base::RefCountedMemory> memory =
    870         GetRawData(idr_id, scale_factors_[i]);
    871     if (memory.get())
    872       png_map[scale_factors_[i]] = memory;
    873   }
    874   if (!png_map.empty()) {
    875     gfx::ImageSkia image_skia(new ThemeImagePngSource(png_map), 1.0f);
    876     // |image_skia| takes ownership of ThemeImagePngSource.
    877     gfx::Image ret = gfx::Image(image_skia);
    878     images_on_ui_thread_[prs_id] = ret;
    879     return ret;
    880   }
    881 
    882   return gfx::Image();
    883 }
    884 
    885 base::RefCountedMemory* BrowserThemePack::GetRawData(
    886     int idr_id,
    887     ui::ScaleFactor scale_factor) const {
    888   base::RefCountedMemory* memory = NULL;
    889   int prs_id = GetPersistentIDByIDR(idr_id);
    890   int raw_id = GetRawIDByPersistentID(prs_id, scale_factor);
    891 
    892   if (raw_id != -1) {
    893     if (data_pack_.get()) {
    894       memory = data_pack_->GetStaticMemory(raw_id);
    895     } else {
    896       RawImages::const_iterator it = image_memory_.find(raw_id);
    897       if (it != image_memory_.end()) {
    898         memory = it->second.get();
    899       }
    900     }
    901   }
    902 
    903   return memory;
    904 }
    905 
    906 bool BrowserThemePack::HasCustomImage(int idr_id) const {
    907   int prs_id = GetPersistentIDByIDR(idr_id);
    908   if (prs_id == -1)
    909     return false;
    910 
    911   int* img = source_images_;
    912   for (; *img != -1; ++img) {
    913     if (*img == prs_id)
    914       return true;
    915   }
    916 
    917   return false;
    918 }
    919 
    920 // private:
    921 
    922 BrowserThemePack::BrowserThemePack()
    923     : CustomThemeSupplier(EXTENSION),
    924       header_(NULL),
    925       tints_(NULL),
    926       colors_(NULL),
    927       display_properties_(NULL),
    928       source_images_(NULL) {
    929   scale_factors_ = ui::GetSupportedScaleFactors();
    930   // On Windows HiDPI SCALE_FACTOR_100P may not be supported by default.
    931   if (std::find(scale_factors_.begin(), scale_factors_.end(),
    932                 ui::SCALE_FACTOR_100P) == scale_factors_.end()) {
    933     scale_factors_.push_back(ui::SCALE_FACTOR_100P);
    934   }
    935 }
    936 
    937 void BrowserThemePack::BuildHeader(const Extension* extension) {
    938   header_ = new BrowserThemePackHeader;
    939   header_->version = kThemePackVersion;
    940 
    941   // TODO(erg): Need to make this endian safe on other computers. Prerequisite
    942   // is that ui::DataPack removes this same check.
    943 #if defined(__BYTE_ORDER)
    944   // Linux check
    945   COMPILE_ASSERT(__BYTE_ORDER == __LITTLE_ENDIAN,
    946                  datapack_assumes_little_endian);
    947 #elif defined(__BIG_ENDIAN__)
    948   // Mac check
    949   #error DataPack assumes little endian
    950 #endif
    951   header_->little_endian = 1;
    952 
    953   const std::string& id = extension->id();
    954   memcpy(header_->theme_id, id.c_str(), extensions::id_util::kIdSize);
    955 }
    956 
    957 void BrowserThemePack::BuildTintsFromJSON(
    958     const base::DictionaryValue* tints_value) {
    959   tints_ = new TintEntry[kTintTableLength];
    960   for (size_t i = 0; i < kTintTableLength; ++i) {
    961     tints_[i].id = -1;
    962     tints_[i].h = -1;
    963     tints_[i].s = -1;
    964     tints_[i].l = -1;
    965   }
    966 
    967   if (!tints_value)
    968     return;
    969 
    970   // Parse the incoming data from |tints_value| into an intermediary structure.
    971   std::map<int, color_utils::HSL> temp_tints;
    972   for (base::DictionaryValue::Iterator iter(*tints_value); !iter.IsAtEnd();
    973        iter.Advance()) {
    974     const base::ListValue* tint_list;
    975     if (iter.value().GetAsList(&tint_list) &&
    976         (tint_list->GetSize() == 3)) {
    977       color_utils::HSL hsl = { -1, -1, -1 };
    978 
    979       if (tint_list->GetDouble(0, &hsl.h) &&
    980           tint_list->GetDouble(1, &hsl.s) &&
    981           tint_list->GetDouble(2, &hsl.l)) {
    982         int id = GetIntForString(iter.key(), kTintTable, kTintTableLength);
    983         if (id != -1) {
    984           temp_tints[id] = hsl;
    985         }
    986       }
    987     }
    988   }
    989 
    990   // Copy data from the intermediary data structure to the array.
    991   size_t count = 0;
    992   for (std::map<int, color_utils::HSL>::const_iterator it =
    993            temp_tints.begin();
    994        it != temp_tints.end() && count < kTintTableLength;
    995        ++it, ++count) {
    996     tints_[count].id = it->first;
    997     tints_[count].h = it->second.h;
    998     tints_[count].s = it->second.s;
    999     tints_[count].l = it->second.l;
   1000   }
   1001 }
   1002 
   1003 void BrowserThemePack::BuildColorsFromJSON(
   1004     const base::DictionaryValue* colors_value) {
   1005   colors_ = new ColorPair[kColorTableLength];
   1006   for (size_t i = 0; i < kColorTableLength; ++i) {
   1007     colors_[i].id = -1;
   1008     colors_[i].color = SkColorSetRGB(0, 0, 0);
   1009   }
   1010 
   1011   std::map<int, SkColor> temp_colors;
   1012   if (colors_value)
   1013     ReadColorsFromJSON(colors_value, &temp_colors);
   1014   GenerateMissingColors(&temp_colors);
   1015 
   1016   // Copy data from the intermediary data structure to the array.
   1017   size_t count = 0;
   1018   for (std::map<int, SkColor>::const_iterator it = temp_colors.begin();
   1019        it != temp_colors.end() && count < kColorTableLength; ++it, ++count) {
   1020     colors_[count].id = it->first;
   1021     colors_[count].color = it->second;
   1022   }
   1023 }
   1024 
   1025 void BrowserThemePack::ReadColorsFromJSON(
   1026     const base::DictionaryValue* colors_value,
   1027     std::map<int, SkColor>* temp_colors) {
   1028   // Parse the incoming data from |colors_value| into an intermediary structure.
   1029   for (base::DictionaryValue::Iterator iter(*colors_value); !iter.IsAtEnd();
   1030        iter.Advance()) {
   1031     const base::ListValue* color_list;
   1032     if (iter.value().GetAsList(&color_list) &&
   1033         ((color_list->GetSize() == 3) || (color_list->GetSize() == 4))) {
   1034       SkColor color = SK_ColorWHITE;
   1035       int r, g, b;
   1036       if (color_list->GetInteger(0, &r) &&
   1037           color_list->GetInteger(1, &g) &&
   1038           color_list->GetInteger(2, &b)) {
   1039         if (color_list->GetSize() == 4) {
   1040           double alpha;
   1041           int alpha_int;
   1042           if (color_list->GetDouble(3, &alpha)) {
   1043             color = SkColorSetARGB(static_cast<int>(alpha * 255), r, g, b);
   1044           } else if (color_list->GetInteger(3, &alpha_int) &&
   1045                      (alpha_int == 0 || alpha_int == 1)) {
   1046             color = SkColorSetARGB(alpha_int ? 255 : 0, r, g, b);
   1047           } else {
   1048             // Invalid entry for part 4.
   1049             continue;
   1050           }
   1051         } else {
   1052           color = SkColorSetRGB(r, g, b);
   1053         }
   1054 
   1055         int id = GetIntForString(iter.key(), kColorTable, kColorTableLength);
   1056         if (id != -1) {
   1057           (*temp_colors)[id] = color;
   1058         }
   1059       }
   1060     }
   1061   }
   1062 }
   1063 
   1064 void BrowserThemePack::GenerateMissingColors(
   1065     std::map<int, SkColor>* colors) {
   1066   // Generate link colors, if missing. (See GetColor()).
   1067   if (!colors->count(ThemeProperties::COLOR_NTP_HEADER) &&
   1068       colors->count(ThemeProperties::COLOR_NTP_SECTION)) {
   1069     (*colors)[ThemeProperties::COLOR_NTP_HEADER] =
   1070         (*colors)[ThemeProperties::COLOR_NTP_SECTION];
   1071   }
   1072 
   1073   if (!colors->count(ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE) &&
   1074       colors->count(ThemeProperties::COLOR_NTP_SECTION_LINK)) {
   1075     SkColor color_section_link =
   1076         (*colors)[ThemeProperties::COLOR_NTP_SECTION_LINK];
   1077     (*colors)[ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE] =
   1078         SkColorSetA(color_section_link, SkColorGetA(color_section_link) / 3);
   1079   }
   1080 
   1081   if (!colors->count(ThemeProperties::COLOR_NTP_LINK_UNDERLINE) &&
   1082       colors->count(ThemeProperties::COLOR_NTP_LINK)) {
   1083     SkColor color_link = (*colors)[ThemeProperties::COLOR_NTP_LINK];
   1084     (*colors)[ThemeProperties::COLOR_NTP_LINK_UNDERLINE] =
   1085         SkColorSetA(color_link, SkColorGetA(color_link) / 3);
   1086   }
   1087 
   1088   // Generate frame colors, if missing. (See GenerateFrameColors()).
   1089   SkColor frame;
   1090   std::map<int, SkColor>::const_iterator it =
   1091       colors->find(ThemeProperties::COLOR_FRAME);
   1092   if (it != colors->end()) {
   1093     frame = it->second;
   1094   } else {
   1095     frame = ThemeProperties::GetDefaultColor(
   1096         ThemeProperties::COLOR_FRAME);
   1097   }
   1098 
   1099   if (!colors->count(ThemeProperties::COLOR_FRAME)) {
   1100     (*colors)[ThemeProperties::COLOR_FRAME] =
   1101         HSLShift(frame, GetTintInternal(ThemeProperties::TINT_FRAME));
   1102   }
   1103   if (!colors->count(ThemeProperties::COLOR_FRAME_INACTIVE)) {
   1104     (*colors)[ThemeProperties::COLOR_FRAME_INACTIVE] =
   1105         HSLShift(frame, GetTintInternal(
   1106             ThemeProperties::TINT_FRAME_INACTIVE));
   1107   }
   1108   if (!colors->count(ThemeProperties::COLOR_FRAME_INCOGNITO)) {
   1109     (*colors)[ThemeProperties::COLOR_FRAME_INCOGNITO] =
   1110         HSLShift(frame, GetTintInternal(
   1111             ThemeProperties::TINT_FRAME_INCOGNITO));
   1112   }
   1113   if (!colors->count(ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE)) {
   1114     (*colors)[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] =
   1115         HSLShift(frame, GetTintInternal(
   1116             ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE));
   1117   }
   1118 }
   1119 
   1120 void BrowserThemePack::BuildDisplayPropertiesFromJSON(
   1121     const base::DictionaryValue* display_properties_value) {
   1122   display_properties_ = new DisplayPropertyPair[kDisplayPropertiesSize];
   1123   for (size_t i = 0; i < kDisplayPropertiesSize; ++i) {
   1124     display_properties_[i].id = -1;
   1125     display_properties_[i].property = 0;
   1126   }
   1127 
   1128   if (!display_properties_value)
   1129     return;
   1130 
   1131   std::map<int, int> temp_properties;
   1132   for (base::DictionaryValue::Iterator iter(*display_properties_value);
   1133        !iter.IsAtEnd(); iter.Advance()) {
   1134     int property_id = GetIntForString(iter.key(), kDisplayProperties,
   1135                                       kDisplayPropertiesSize);
   1136     switch (property_id) {
   1137       case ThemeProperties::NTP_BACKGROUND_ALIGNMENT: {
   1138         std::string val;
   1139         if (iter.value().GetAsString(&val)) {
   1140           temp_properties[ThemeProperties::NTP_BACKGROUND_ALIGNMENT] =
   1141               ThemeProperties::StringToAlignment(val);
   1142         }
   1143         break;
   1144       }
   1145       case ThemeProperties::NTP_BACKGROUND_TILING: {
   1146         std::string val;
   1147         if (iter.value().GetAsString(&val)) {
   1148           temp_properties[ThemeProperties::NTP_BACKGROUND_TILING] =
   1149               ThemeProperties::StringToTiling(val);
   1150         }
   1151         break;
   1152       }
   1153       case ThemeProperties::NTP_LOGO_ALTERNATE: {
   1154         int val = 0;
   1155         if (iter.value().GetAsInteger(&val))
   1156           temp_properties[ThemeProperties::NTP_LOGO_ALTERNATE] = val;
   1157         break;
   1158       }
   1159     }
   1160   }
   1161 
   1162   // Copy data from the intermediary data structure to the array.
   1163   size_t count = 0;
   1164   for (std::map<int, int>::const_iterator it = temp_properties.begin();
   1165        it != temp_properties.end() && count < kDisplayPropertiesSize;
   1166        ++it, ++count) {
   1167     display_properties_[count].id = it->first;
   1168     display_properties_[count].property = it->second;
   1169   }
   1170 }
   1171 
   1172 void BrowserThemePack::ParseImageNamesFromJSON(
   1173     const base::DictionaryValue* images_value,
   1174     const base::FilePath& images_path,
   1175     FilePathMap* file_paths) const {
   1176   if (!images_value)
   1177     return;
   1178 
   1179   for (base::DictionaryValue::Iterator iter(*images_value); !iter.IsAtEnd();
   1180        iter.Advance()) {
   1181     if (iter.value().IsType(base::Value::TYPE_DICTIONARY)) {
   1182       const base::DictionaryValue* inner_value = NULL;
   1183       if (iter.value().GetAsDictionary(&inner_value)) {
   1184         for (base::DictionaryValue::Iterator inner_iter(*inner_value);
   1185              !inner_iter.IsAtEnd();
   1186              inner_iter.Advance()) {
   1187           std::string name;
   1188           ui::ScaleFactor scale_factor = ui::SCALE_FACTOR_NONE;
   1189           if (GetScaleFactorFromManifestKey(inner_iter.key(), &scale_factor) &&
   1190               inner_iter.value().IsType(base::Value::TYPE_STRING) &&
   1191               inner_iter.value().GetAsString(&name)) {
   1192             AddFileAtScaleToMap(iter.key(),
   1193                                 scale_factor,
   1194                                 images_path.AppendASCII(name),
   1195                                 file_paths);
   1196           }
   1197         }
   1198       }
   1199     } else if (iter.value().IsType(base::Value::TYPE_STRING)) {
   1200       std::string name;
   1201       if (iter.value().GetAsString(&name)) {
   1202         AddFileAtScaleToMap(iter.key(),
   1203                             ui::SCALE_FACTOR_100P,
   1204                             images_path.AppendASCII(name),
   1205                             file_paths);
   1206       }
   1207     }
   1208   }
   1209 }
   1210 
   1211 void BrowserThemePack::AddFileAtScaleToMap(const std::string& image_name,
   1212                                            ui::ScaleFactor scale_factor,
   1213                                            const base::FilePath& image_path,
   1214                                            FilePathMap* file_paths) const {
   1215   int id = GetPersistentIDByName(image_name);
   1216   if (id != -1)
   1217     (*file_paths)[id][scale_factor] = image_path;
   1218 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
   1219   id = GetPersistentIDByNameHelper(image_name,
   1220                                    kPersistingImagesDesktopAura,
   1221                                    kPersistingImagesDesktopAuraLength);
   1222   if (id != -1)
   1223     (*file_paths)[id][scale_factor] = image_path;
   1224 #endif
   1225 }
   1226 
   1227 void BrowserThemePack::BuildSourceImagesArray(const FilePathMap& file_paths) {
   1228   std::vector<int> ids;
   1229   for (FilePathMap::const_iterator it = file_paths.begin();
   1230        it != file_paths.end(); ++it) {
   1231     ids.push_back(it->first);
   1232   }
   1233 
   1234   source_images_ = new int[ids.size() + 1];
   1235   std::copy(ids.begin(), ids.end(), source_images_);
   1236   source_images_[ids.size()] = -1;
   1237 }
   1238 
   1239 bool BrowserThemePack::LoadRawBitmapsTo(
   1240     const FilePathMap& file_paths,
   1241     ImageCache* image_cache) {
   1242   // Themes should be loaded on the file thread, not the UI thread.
   1243   // http://crbug.com/61838
   1244   base::ThreadRestrictions::ScopedAllowIO allow_io;
   1245 
   1246   for (FilePathMap::const_iterator it = file_paths.begin();
   1247        it != file_paths.end(); ++it) {
   1248     int prs_id = it->first;
   1249     // Some images need to go directly into |image_memory_|. No modification is
   1250     // necessary or desirable.
   1251     bool is_copyable = false;
   1252     for (size_t i = 0; i < arraysize(kPreloadIDs); ++i) {
   1253       if (kPreloadIDs[i] == prs_id) {
   1254         is_copyable = true;
   1255         break;
   1256       }
   1257     }
   1258     gfx::ImageSkia image_skia;
   1259     for (int pass = 0; pass < 2; ++pass) {
   1260       // Two passes: In the first pass, we process only scale factor
   1261       // 100% and in the second pass all other scale factors. We
   1262       // process scale factor 100% first because the first image added
   1263       // in image_skia.AddRepresentation() determines the DIP size for
   1264       // all representations.
   1265       for (ScaleFactorToFileMap::const_iterator s2f = it->second.begin();
   1266            s2f != it->second.end(); ++s2f) {
   1267         ui::ScaleFactor scale_factor = s2f->first;
   1268         if ((pass == 0 && scale_factor != ui::SCALE_FACTOR_100P) ||
   1269             (pass == 1 && scale_factor == ui::SCALE_FACTOR_100P)) {
   1270           continue;
   1271         }
   1272         scoped_refptr<base::RefCountedMemory> raw_data(
   1273             ReadFileData(s2f->second));
   1274         if (!raw_data.get() || !raw_data->size()) {
   1275           LOG(ERROR) << "Could not load theme image"
   1276                      << " prs_id=" << prs_id
   1277                      << " scale_factor_enum=" << scale_factor
   1278                      << " file=" << s2f->second.value()
   1279                      << (raw_data.get() ? " (zero size)" : " (read error)");
   1280           return false;
   1281         }
   1282         if (is_copyable) {
   1283           int raw_id = GetRawIDByPersistentID(prs_id, scale_factor);
   1284           image_memory_[raw_id] = raw_data;
   1285         } else {
   1286           SkBitmap bitmap;
   1287           if (gfx::PNGCodec::Decode(raw_data->front(), raw_data->size(),
   1288                                     &bitmap)) {
   1289             image_skia.AddRepresentation(
   1290                 gfx::ImageSkiaRep(bitmap,
   1291                                   ui::GetScaleForScaleFactor(scale_factor)));
   1292           } else {
   1293             NOTREACHED() << "Unable to decode theme image resource "
   1294                          << it->first;
   1295           }
   1296         }
   1297       }
   1298     }
   1299     if (!is_copyable && !image_skia.isNull())
   1300       (*image_cache)[prs_id] = gfx::Image(image_skia);
   1301   }
   1302 
   1303   return true;
   1304 }
   1305 
   1306 void BrowserThemePack::CreateImages(ImageCache* images) const {
   1307   CropImages(images);
   1308   CreateFrameImages(images);
   1309   CreateTintedButtons(GetTintInternal(ThemeProperties::TINT_BUTTONS), images);
   1310   CreateTabBackgroundImages(images);
   1311 }
   1312 
   1313 void BrowserThemePack::CropImages(ImageCache* images) const {
   1314   bool has_frame_border = HasFrameBorder();
   1315   for (size_t i = 0; i < arraysize(kImagesToCrop); ++i) {
   1316     if (has_frame_border && kImagesToCrop[i].skip_if_frame_border)
   1317       continue;
   1318 
   1319     int prs_id = kImagesToCrop[i].prs_id;
   1320     ImageCache::iterator it = images->find(prs_id);
   1321     if (it == images->end())
   1322       continue;
   1323 
   1324     int crop_height = kImagesToCrop[i].max_height;
   1325     gfx::ImageSkia image_skia = it->second.AsImageSkia();
   1326     (*images)[prs_id] = gfx::Image(gfx::ImageSkiaOperations::ExtractSubset(
   1327         image_skia, gfx::Rect(0, 0, image_skia.width(), crop_height)));
   1328   }
   1329 }
   1330 
   1331 void BrowserThemePack::CreateFrameImages(ImageCache* images) const {
   1332   ResourceBundle& rb = ResourceBundle::GetSharedInstance();
   1333 
   1334   // Create all the output images in a separate cache and move them back into
   1335   // the input images because there can be name collisions.
   1336   ImageCache temp_output;
   1337 
   1338   for (size_t i = 0; i < arraysize(kFrameTintMap); ++i) {
   1339     int prs_id = kFrameTintMap[i].key;
   1340     gfx::Image frame;
   1341     // If there's no frame image provided for the specified id, then load
   1342     // the default provided frame. If that's not provided, skip this whole
   1343     // thing and just use the default images.
   1344     int prs_base_id = 0;
   1345 
   1346 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
   1347     if (prs_id == PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP) {
   1348       prs_base_id = images->count(PRS_THEME_FRAME_INCOGNITO_DESKTOP) ?
   1349                     PRS_THEME_FRAME_INCOGNITO_DESKTOP : PRS_THEME_FRAME_DESKTOP;
   1350     } else if (prs_id == PRS_THEME_FRAME_INACTIVE_DESKTOP) {
   1351       prs_base_id = PRS_THEME_FRAME_DESKTOP;
   1352     } else if (prs_id == PRS_THEME_FRAME_INCOGNITO_DESKTOP &&
   1353                 !images->count(PRS_THEME_FRAME_INCOGNITO_DESKTOP)) {
   1354       prs_base_id = PRS_THEME_FRAME_DESKTOP;
   1355     }
   1356 #endif
   1357     if (!prs_base_id) {
   1358       if (prs_id == PRS_THEME_FRAME_INCOGNITO_INACTIVE) {
   1359         prs_base_id = images->count(PRS_THEME_FRAME_INCOGNITO) ?
   1360                       PRS_THEME_FRAME_INCOGNITO : PRS_THEME_FRAME;
   1361       } else if (prs_id == PRS_THEME_FRAME_OVERLAY_INACTIVE) {
   1362         prs_base_id = PRS_THEME_FRAME_OVERLAY;
   1363       } else if (prs_id == PRS_THEME_FRAME_INACTIVE) {
   1364         prs_base_id = PRS_THEME_FRAME;
   1365       } else if (prs_id == PRS_THEME_FRAME_INCOGNITO &&
   1366                  !images->count(PRS_THEME_FRAME_INCOGNITO)) {
   1367         prs_base_id = PRS_THEME_FRAME;
   1368       } else {
   1369         prs_base_id = prs_id;
   1370       }
   1371     }
   1372     if (images->count(prs_id)) {
   1373       frame = (*images)[prs_id];
   1374     } else if (prs_base_id != prs_id && images->count(prs_base_id)) {
   1375       frame = (*images)[prs_base_id];
   1376     } else if (prs_base_id == PRS_THEME_FRAME_OVERLAY) {
   1377 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
   1378       if (images->count(PRS_THEME_FRAME_DESKTOP)) {
   1379 #else
   1380       if (images->count(PRS_THEME_FRAME)) {
   1381 #endif
   1382         // If there is no theme overlay, don't tint the default frame,
   1383         // because it will overwrite the custom frame image when we cache and
   1384         // reload from disk.
   1385         frame = gfx::Image();
   1386       }
   1387     } else {
   1388       // If the theme doesn't specify an image, then apply the tint to
   1389       // the default frame.
   1390       frame = rb.GetImageNamed(IDR_THEME_FRAME);
   1391 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
   1392       if (prs_id >= PRS_THEME_FRAME_DESKTOP &&
   1393           prs_id <= PRS_THEME_FRAME_INCOGNITO_INACTIVE_DESKTOP) {
   1394         frame = rb.GetImageNamed(IDR_THEME_FRAME_DESKTOP);
   1395       }
   1396 #endif
   1397     }
   1398     if (!frame.IsEmpty()) {
   1399       temp_output[prs_id] = CreateHSLShiftedImage(
   1400           frame, GetTintInternal(kFrameTintMap[i].value));
   1401     }
   1402   }
   1403   MergeImageCaches(temp_output, images);
   1404 }
   1405 
   1406 void BrowserThemePack::CreateTintedButtons(
   1407     const color_utils::HSL& button_tint,
   1408     ImageCache* processed_images) const {
   1409   if (button_tint.h != -1 || button_tint.s != -1 || button_tint.l != -1) {
   1410     ResourceBundle& rb = ResourceBundle::GetSharedInstance();
   1411     const std::set<int>& idr_ids =
   1412         ThemeProperties::GetTintableToolbarButtons();
   1413     for (std::set<int>::const_iterator it = idr_ids.begin();
   1414          it != idr_ids.end(); ++it) {
   1415       int prs_id = GetPersistentIDByIDR(*it);
   1416       DCHECK(prs_id > 0);
   1417 
   1418       // Fetch the image by IDR...
   1419       gfx::Image& button = rb.GetImageNamed(*it);
   1420 
   1421       // but save a version with the persistent ID.
   1422       (*processed_images)[prs_id] =
   1423           CreateHSLShiftedImage(button, button_tint);
   1424     }
   1425   }
   1426 }
   1427 
   1428 void BrowserThemePack::CreateTabBackgroundImages(ImageCache* images) const {
   1429   ImageCache temp_output;
   1430   for (size_t i = 0; i < arraysize(kTabBackgroundMap); ++i) {
   1431     int prs_id = kTabBackgroundMap[i].key;
   1432     int prs_base_id = kTabBackgroundMap[i].value;
   1433 
   1434     // We only need to generate the background tab images if we were provided
   1435     // with a PRS_THEME_FRAME.
   1436     ImageCache::const_iterator it = images->find(prs_base_id);
   1437     if (it != images->end()) {
   1438       gfx::ImageSkia image_to_tint = (it->second).AsImageSkia();
   1439       color_utils::HSL hsl_shift = GetTintInternal(
   1440           ThemeProperties::TINT_BACKGROUND_TAB);
   1441       int vertical_offset = images->count(prs_id)
   1442                             ? kRestoredTabVerticalOffset : 0;
   1443 
   1444       gfx::ImageSkia overlay;
   1445       ImageCache::const_iterator overlay_it = images->find(prs_id);
   1446       if (overlay_it != images->end())
   1447         overlay = overlay_it->second.AsImageSkia();
   1448 
   1449       gfx::ImageSkiaSource* source = new TabBackgroundImageSource(
   1450           image_to_tint, overlay, hsl_shift, vertical_offset);
   1451       // ImageSkia takes ownership of |source|.
   1452       temp_output[prs_id] = gfx::Image(gfx::ImageSkia(source,
   1453           image_to_tint.size()));
   1454     }
   1455   }
   1456   MergeImageCaches(temp_output, images);
   1457 }
   1458 
   1459 void BrowserThemePack::RepackImages(const ImageCache& images,
   1460                                     RawImages* reencoded_images) const {
   1461   for (ImageCache::const_iterator it = images.begin();
   1462        it != images.end(); ++it) {
   1463     gfx::ImageSkia image_skia = *it->second.ToImageSkia();
   1464 
   1465     typedef std::vector<gfx::ImageSkiaRep> ImageSkiaReps;
   1466     ImageSkiaReps image_reps = image_skia.image_reps();
   1467     if (image_reps.empty()) {
   1468       NOTREACHED() << "No image reps for resource " << it->first << ".";
   1469     }
   1470     for (ImageSkiaReps::iterator rep_it = image_reps.begin();
   1471          rep_it != image_reps.end(); ++rep_it) {
   1472       std::vector<unsigned char> bitmap_data;
   1473       if (!gfx::PNGCodec::EncodeBGRASkBitmap(rep_it->sk_bitmap(), false,
   1474                                              &bitmap_data)) {
   1475         NOTREACHED() << "Image file for resource " << it->first
   1476                      << " could not be encoded.";
   1477       }
   1478       int raw_id = GetRawIDByPersistentID(
   1479           it->first,
   1480           ui::GetSupportedScaleFactor(rep_it->scale()));
   1481       (*reencoded_images)[raw_id] =
   1482           base::RefCountedBytes::TakeVector(&bitmap_data);
   1483     }
   1484   }
   1485 }
   1486 
   1487 void BrowserThemePack::MergeImageCaches(
   1488     const ImageCache& source, ImageCache* destination) const {
   1489   for (ImageCache::const_iterator it = source.begin(); it != source.end();
   1490        ++it) {
   1491     (*destination)[it->first] = it->second;
   1492   }
   1493 }
   1494 
   1495 void BrowserThemePack::AddRawImagesTo(const RawImages& images,
   1496                                       RawDataForWriting* out) const {
   1497   for (RawImages::const_iterator it = images.begin(); it != images.end();
   1498        ++it) {
   1499     (*out)[it->first] = base::StringPiece(
   1500         it->second->front_as<char>(), it->second->size());
   1501   }
   1502 }
   1503 
   1504 color_utils::HSL BrowserThemePack::GetTintInternal(int id) const {
   1505   if (tints_) {
   1506     for (size_t i = 0; i < kTintTableLength; ++i) {
   1507       if (tints_[i].id == id) {
   1508         color_utils::HSL hsl;
   1509         hsl.h = tints_[i].h;
   1510         hsl.s = tints_[i].s;
   1511         hsl.l = tints_[i].l;
   1512         return hsl;
   1513       }
   1514     }
   1515   }
   1516 
   1517   return ThemeProperties::GetDefaultTint(id);
   1518 }
   1519 
   1520 int BrowserThemePack::GetRawIDByPersistentID(
   1521     int prs_id,
   1522     ui::ScaleFactor scale_factor) const {
   1523   if (prs_id < 0)
   1524     return -1;
   1525 
   1526   for (size_t i = 0; i < scale_factors_.size(); ++i) {
   1527     if (scale_factors_[i] == scale_factor)
   1528       return static_cast<int>(kPersistingImagesLength * i) + prs_id;
   1529   }
   1530   return -1;
   1531 }
   1532 
   1533 bool BrowserThemePack::GetScaleFactorFromManifestKey(
   1534     const std::string& key,
   1535     ui::ScaleFactor* scale_factor) const {
   1536   int percent = 0;
   1537   if (base::StringToInt(key, &percent)) {
   1538     float scale = static_cast<float>(percent) / 100.0f;
   1539     for (size_t i = 0; i < scale_factors_.size(); ++i) {
   1540       if (fabs(ui::GetScaleForScaleFactor(scale_factors_[i]) - scale)
   1541               < 0.001) {
   1542         *scale_factor = scale_factors_[i];
   1543         return true;
   1544       }
   1545     }
   1546   }
   1547   return false;
   1548 }
   1549 
   1550 void BrowserThemePack::GenerateRawImageForAllSupportedScales(int prs_id) {
   1551   // Compute (by scaling) bitmaps for |prs_id| for any scale factors
   1552   // for which the theme author did not provide a bitmap. We compute
   1553   // the bitmaps using the highest scale factor that theme author
   1554   // provided.
   1555   // Note: We use only supported scale factors. For example, if scale
   1556   // factor 2x is supported by the current system, but 1.8x is not and
   1557   // if the theme author did not provide an image for 2x but one for
   1558   // 1.8x, we will not use the 1.8x image here. Here we will only use
   1559   // images provided for scale factors supported by the current system.
   1560 
   1561   // See if any image is missing. If not, we're done.
   1562   bool image_missing = false;
   1563   for (size_t i = 0; i < scale_factors_.size(); ++i) {
   1564     int raw_id = GetRawIDByPersistentID(prs_id, scale_factors_[i]);
   1565     if (image_memory_.find(raw_id) == image_memory_.end()) {
   1566       image_missing = true;
   1567       break;
   1568     }
   1569   }
   1570   if (!image_missing)
   1571     return;
   1572 
   1573   // Find available scale factor with highest scale.
   1574   ui::ScaleFactor available_scale_factor = ui::SCALE_FACTOR_NONE;
   1575   for (size_t i = 0; i < scale_factors_.size(); ++i) {
   1576     int raw_id = GetRawIDByPersistentID(prs_id, scale_factors_[i]);
   1577     if ((available_scale_factor == ui::SCALE_FACTOR_NONE ||
   1578          (ui::GetScaleForScaleFactor(scale_factors_[i]) >
   1579           ui::GetScaleForScaleFactor(available_scale_factor))) &&
   1580         image_memory_.find(raw_id) != image_memory_.end()) {
   1581       available_scale_factor = scale_factors_[i];
   1582     }
   1583   }
   1584   // If no scale factor is available, we're done.
   1585   if (available_scale_factor == ui::SCALE_FACTOR_NONE)
   1586     return;
   1587 
   1588   // Get bitmap for the available scale factor.
   1589   int available_raw_id = GetRawIDByPersistentID(prs_id, available_scale_factor);
   1590   RawImages::const_iterator it = image_memory_.find(available_raw_id);
   1591   SkBitmap available_bitmap;
   1592   if (!gfx::PNGCodec::Decode(it->second->front(),
   1593                              it->second->size(),
   1594                              &available_bitmap)) {
   1595     NOTREACHED() << "Unable to decode theme image for prs_id="
   1596                  << prs_id << " for scale_factor=" << available_scale_factor;
   1597     return;
   1598   }
   1599 
   1600   // Fill in all missing scale factors by scaling the available bitmap.
   1601   for (size_t i = 0; i < scale_factors_.size(); ++i) {
   1602     int scaled_raw_id = GetRawIDByPersistentID(prs_id, scale_factors_[i]);
   1603     if (image_memory_.find(scaled_raw_id) != image_memory_.end())
   1604       continue;
   1605     SkBitmap scaled_bitmap =
   1606         CreateLowQualityResizedBitmap(available_bitmap,
   1607                                       available_scale_factor,
   1608                                       scale_factors_[i]);
   1609     std::vector<unsigned char> bitmap_data;
   1610     if (!gfx::PNGCodec::EncodeBGRASkBitmap(scaled_bitmap,
   1611                                            false,
   1612                                            &bitmap_data)) {
   1613       NOTREACHED() << "Unable to encode theme image for prs_id="
   1614                    << prs_id << " for scale_factor=" << scale_factors_[i];
   1615       break;
   1616     }
   1617     image_memory_[scaled_raw_id] =
   1618         base::RefCountedBytes::TakeVector(&bitmap_data);
   1619   }
   1620 }
   1621