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