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