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.
5 #include "chrome/browser/themes/browser_theme_pack.h"
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"
38 using content::BrowserThread;
39 using extensions::Extension;
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;
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;
61 // The sum of kFrameBorderThickness and kNonClientRestoredExtraThickness from
62 // OpaqueBrowserFrameView.
63 const int kRestoredTabVerticalOffset = 15;
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
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;
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.
88 // The IDR that depends on the whims of GRIT and therefore changes whenever
89 // someone adds a new resource.
92 // String to check for when parsing theme manifests or NULL if this isn't
93 // supposed to be changeable by the user.
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,
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,
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"},
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 },
163 const size_t kPersistingImagesLength = arraysize(kPersistingImages);
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;
175 // Persistent theme to resource id mapping for Windows AURA.
176 PersistingImagesTable kPersistingImagesWinDesktopAura[] = {
177 { PRS_THEME_FRAME_WIN, IDR_THEME_FRAME_WIN,
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,
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" },
194 const size_t kPersistingImagesWinDesktopAuraLength =
195 arraysize(kPersistingImagesWinDesktopAura);
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;
210 int GetPersistentIDByName(const std::string& key) {
211 return GetPersistentIDByNameHelper(key,
213 kPersistingImagesLength);
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;
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;
232 std::map<int,int>::iterator it = lookup_table->find(idr);
233 return (it == lookup_table->end()) ? -1 : it->second;
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())
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]))
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));
265 struct StringToIntTable {
267 ThemeProperties::OverwritableByUserThemeProperty id;
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 },
280 const size_t kTintTableLength = arraysize(kTintTable);
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 },
305 const size_t kColorTableLength = arraysize(kColorTable);
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 },
314 const size_t kDisplayPropertiesSize = arraysize(kDisplayProperties);
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) {
328 struct IntToIntTable {
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 },
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 },
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 },
359 { PRS_THEME_TAB_BACKGROUND_WIN, PRS_THEME_FRAME_WIN },
360 { PRS_THEME_TAB_BACKGROUND_INCOGNITO_WIN, PRS_THEME_FRAME_INCOGNITO_WIN },
367 // The maximum useful height of the image at |prs_id|.
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;
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
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 },
393 { PRS_THEME_TOOLBAR_WIN, 200, false }
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,
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)
417 // Returns a piece of memory with the contents of the file |path|.
418 base::RefCountedMemory* ReadFileData(const base::FilePath& path) {
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);
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));
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,
458 scaled_size.height());
459 if (!scaled_bitmap.allocPixels())
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
466 canvas.drawBitmapRect(source_bitmap, NULL, scaled_bounds);
467 return scaled_bitmap;
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 {
474 explicit ThemeImageSource(const gfx::ImageSkia& source) : source_(source) {
476 virtual ~ThemeImageSource() {}
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);
490 const gfx::ImageSkia source_;
492 DISALLOW_COPY_AND_ASSIGN(ThemeImageSource);
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 {
500 typedef std::map<ui::ScaleFactor,
501 scoped_refptr<base::RefCountedMemory> > PngMap;
503 explicit ThemeImagePngSource(const PngMap& png_map) : png_map_(png_map) {}
505 virtual ~ThemeImagePngSource() {}
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
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);
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()) {
521 if (!gfx::PNGCodec::Decode(exact_png_it->second->front(),
522 exact_png_it->second->size(),
525 return gfx::ImageSkiaRep();
527 bitmap_map_[scale_factor] = bitmap;
528 return gfx::ImageSkiaRep(bitmap, scale);
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;
542 if (available_png_it == png_map_.end())
543 return gfx::ImageSkiaRep();
544 ui::ScaleFactor available_scale_factor = available_png_it->first;
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)) {
557 return gfx::ImageSkiaRep();
559 bitmap_map_[available_scale_factor] = available_bitmap;
560 available_bitmap_it = bitmap_map_.find(available_scale_factor);
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,
569 bitmap_map_[scale_factor] = scaled_bitmap;
570 return gfx::ImageSkiaRep(scaled_bitmap, scale);
575 typedef std::map<ui::ScaleFactor, SkBitmap> BitmapMap;
576 BitmapMap bitmap_map_;
578 DISALLOW_COPY_AND_ASSIGN(ThemeImagePngSource);
581 class TabBackgroundImageSource: public gfx::CanvasImageSource {
583 TabBackgroundImageSource(const gfx::ImageSkia& image_to_tint,
584 const gfx::ImageSkia& overlay,
585 const color_utils::HSL& hsl_shift,
587 : gfx::CanvasImageSource(image_to_tint.size(), false),
588 image_to_tint_(image_to_tint),
590 hsl_shift_(hsl_shift),
591 vertical_offset_(vertical_offset) {
594 virtual ~TabBackgroundImageSource() {
597 // Overridden from CanvasImageSource:
598 virtual void Draw(gfx::Canvas* canvas) OVERRIDE {
599 gfx::ImageSkia bg_tint =
600 gfx::ImageSkiaOperations::CreateHSLShiftedImage(image_to_tint_,
602 canvas->TileImageInt(bg_tint, 0, vertical_offset_, 0, 0,
603 size().width(), size().height());
605 // If they've provided a custom image, overlay it.
606 if (!overlay_.isNull()) {
607 canvas->TileImageInt(overlay_, 0, 0, size().width(),
613 const gfx::ImageSkia image_to_tint_;
614 const gfx::ImageSkia overlay_;
615 const color_utils::HSL hsl_shift_;
616 const int vertical_offset_;
618 DISALLOW_COPY_AND_ASSIGN(TabBackgroundImageSource);
623 BrowserThemePack::~BrowserThemePack() {
624 if (!data_pack_.get()) {
628 delete [] display_properties_;
629 delete [] source_images_;
634 scoped_refptr<BrowserThemePack> BrowserThemePack::BuildFromExtension(
635 const Extension* extension) {
636 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
638 DCHECK(extension->is_theme());
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));
647 // Builds the images. (Image building is dependent on tints).
648 FilePathMap file_paths;
649 pack->ParseImageNamesFromJSON(
650 extensions::ThemeInfo::GetImages(extension),
653 pack->BuildSourceImagesArray(file_paths);
655 if (!pack->LoadRawBitmapsTo(file_paths, &pack->images_on_ui_thread_))
658 pack->CreateImages(&pack->images_on_ui_thread_);
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();
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);
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]);
690 // The BrowserThemePack is now in a consistent state.
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));
707 if (!pack->data_pack_->LoadFromPath(path)) {
708 LOG(ERROR) << "Failed to load theme data pack.";
712 base::StringPiece pointer;
713 if (!pack->data_pack_->GetStringPiece(kHeaderID, &pointer))
715 pack->header_ = reinterpret_cast<BrowserThemePackHeader*>(const_cast<char*>(
718 if (pack->header_->version != kThemePackVersion) {
719 DLOG(ERROR) << "BuildFromDataPack failure! Version mismatch!";
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;
732 if (!pack->data_pack_->GetStringPiece(kTintsID, &pointer))
734 pack->tints_ = reinterpret_cast<TintEntry*>(const_cast<char*>(
737 if (!pack->data_pack_->GetStringPiece(kColorsID, &pointer))
740 reinterpret_cast<ColorPair*>(const_cast<char*>(pointer.data()));
742 if (!pack->data_pack_->GetStringPiece(kDisplayPropertiesID, &pointer))
744 pack->display_properties_ = reinterpret_cast<DisplayPropertyPair*>(
745 const_cast<char*>(pointer.data()));
747 if (!pack->data_pack_->GetStringPiece(kSourceImagesID, &pointer))
749 pack->source_images_ = reinterpret_cast<int*>(
750 const_cast<char*>(pointer.data()));
752 if (!pack->data_pack_->GetStringPiece(kScaleFactorsID, &pointer))
755 if (!InputScalesValid(pointer, pack->scale_factors_)) {
756 DLOG(ERROR) << "BuildFromDataPack failure! The pack scale factors differ "
757 << "from those supported by platform.";
763 void BrowserThemePack::GetThemeableImageIDRs(std::set<int>* result) {
768 for (size_t i = 0; i < kPersistingImagesLength; ++i)
769 result->insert(kPersistingImages[i].idr_id);
772 for (size_t i = 0; i < kPersistingImagesWinDesktopAuraLength; ++i)
773 result->insert(kPersistingImagesWinDesktopAura[i].idr_id);
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]));
792 int source_count = 1;
793 int* end = source_images_;
794 for (; *end != -1 ; end++)
796 resources[kSourceImagesID] = base::StringPiece(
797 reinterpret_cast<const char*>(source_images_),
798 source_count * sizeof(*source_images_));
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;
805 AddRawImagesTo(image_memory_, &resources);
807 RawImages reencoded_images;
808 RepackImages(images_on_file_thread_, &reencoded_images);
809 AddRawImagesTo(reencoded_images, &resources);
811 return ui::DataPack::WritePack(path, resources, ui::DataPack::BINARY);
814 bool BrowserThemePack::GetTint(int id, color_utils::HSL* hsl) const {
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;
829 bool BrowserThemePack::GetColor(int id, SkColor* color) const {
831 for (size_t i = 0; i < kColorTableLength; ++i) {
832 if (colors_[i].id == id) {
833 *color = colors_[i].color;
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;
855 gfx::Image BrowserThemePack::GetImageNamed(int idr_id) {
856 int prs_id = GetPersistentIDByIDR(idr_id);
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;
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]);
870 png_map[scale_factors_[i]] = memory;
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;
884 base::RefCountedMemory* BrowserThemePack::GetRawData(
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);
892 if (data_pack_.get()) {
893 memory = data_pack_->GetStaticMemory(raw_id);
895 RawImages::const_iterator it = image_memory_.find(raw_id);
896 if (it != image_memory_.end()) {
897 memory = it->second.get();
905 bool BrowserThemePack::HasCustomImage(int idr_id) const {
906 int prs_id = GetPersistentIDByIDR(idr_id);
910 int* img = source_images_;
911 for (; *img != -1; ++img) {
921 BrowserThemePack::BrowserThemePack()
922 : CustomThemeSupplier(EXTENSION),
926 display_properties_(NULL),
927 source_images_(NULL) {
928 scale_factors_ = ui::GetSupportedScaleFactors();
931 void BrowserThemePack::BuildHeader(const Extension* extension) {
932 header_ = new BrowserThemePackHeader;
933 header_->version = kThemePackVersion;
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)
939 COMPILE_ASSERT(__BYTE_ORDER == __LITTLE_ENDIAN,
940 datapack_assumes_little_endian);
941 #elif defined(__BIG_ENDIAN__)
943 #error DataPack assumes little endian
945 header_->little_endian = 1;
947 const std::string& id = extension->id();
948 memcpy(header_->theme_id, id.c_str(), extensions::id_util::kIdSize);
951 void BrowserThemePack::BuildTintsFromJSON(
952 const base::DictionaryValue* tints_value) {
953 tints_ = new TintEntry[kTintTableLength];
954 for (size_t i = 0; i < kTintTableLength; ++i) {
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();
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 };
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);
978 temp_tints[id] = hsl;
984 // Copy data from the intermediary data structure to the array.
986 for (std::map<int, color_utils::HSL>::const_iterator it =
988 it != temp_tints.end() && count < kTintTableLength;
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;
997 void BrowserThemePack::BuildColorsFromJSON(
998 const base::DictionaryValue* colors_value) {
999 colors_ = new ColorPair[kColorTableLength];
1000 for (size_t i = 0; i < kColorTableLength; ++i) {
1002 colors_[i].color = SkColorSetRGB(0, 0, 0);
1005 std::map<int, SkColor> temp_colors;
1007 ReadColorsFromJSON(colors_value, &temp_colors);
1008 GenerateMissingColors(&temp_colors);
1010 // Copy data from the intermediary data structure to the array.
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;
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();
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;
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) {
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);
1042 // Invalid entry for part 4.
1046 color = SkColorSetRGB(r, g, b);
1049 int id = GetIntForString(iter.key(), kColorTable, kColorTableLength);
1051 (*temp_colors)[id] = color;
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];
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);
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);
1082 // Generate frame colors, if missing. (See GenerateFrameColors()).
1084 std::map<int, SkColor>::const_iterator it =
1085 colors->find(ThemeProperties::COLOR_FRAME);
1086 if (it != colors->end()) {
1089 frame = ThemeProperties::GetDefaultColor(
1090 ThemeProperties::COLOR_FRAME);
1093 if (!colors->count(ThemeProperties::COLOR_FRAME)) {
1094 (*colors)[ThemeProperties::COLOR_FRAME] =
1095 HSLShift(frame, GetTintInternal(ThemeProperties::TINT_FRAME));
1097 if (!colors->count(ThemeProperties::COLOR_FRAME_INACTIVE)) {
1098 (*colors)[ThemeProperties::COLOR_FRAME_INACTIVE] =
1099 HSLShift(frame, GetTintInternal(
1100 ThemeProperties::TINT_FRAME_INACTIVE));
1102 if (!colors->count(ThemeProperties::COLOR_FRAME_INCOGNITO)) {
1103 (*colors)[ThemeProperties::COLOR_FRAME_INCOGNITO] =
1104 HSLShift(frame, GetTintInternal(
1105 ThemeProperties::TINT_FRAME_INCOGNITO));
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));
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;
1122 if (!display_properties_value)
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: {
1133 if (iter.value().GetAsString(&val)) {
1134 temp_properties[ThemeProperties::NTP_BACKGROUND_ALIGNMENT] =
1135 ThemeProperties::StringToAlignment(val);
1139 case ThemeProperties::NTP_BACKGROUND_TILING: {
1141 if (iter.value().GetAsString(&val)) {
1142 temp_properties[ThemeProperties::NTP_BACKGROUND_TILING] =
1143 ThemeProperties::StringToTiling(val);
1147 case ThemeProperties::NTP_LOGO_ALTERNATE: {
1149 if (iter.value().GetAsInteger(&val))
1150 temp_properties[ThemeProperties::NTP_LOGO_ALTERNATE] = val;
1156 // Copy data from the intermediary data structure to the array.
1158 for (std::map<int, int>::const_iterator it = temp_properties.begin();
1159 it != temp_properties.end() && count < kDisplayPropertiesSize;
1161 display_properties_[count].id = it->first;
1162 display_properties_[count].property = it->second;
1166 void BrowserThemePack::ParseImageNamesFromJSON(
1167 const base::DictionaryValue* images_value,
1168 const base::FilePath& images_path,
1169 FilePathMap* file_paths) const {
1173 for (base::DictionaryValue::Iterator iter(*images_value); !iter.IsAtEnd();
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()) {
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(),
1188 images_path.AppendASCII(name),
1193 } else if (iter.value().IsType(base::Value::TYPE_STRING)) {
1195 if (iter.value().GetAsString(&name)) {
1196 AddFileAtScaleToMap(iter.key(),
1197 ui::SCALE_FACTOR_100P,
1198 images_path.AppendASCII(name),
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);
1211 (*file_paths)[id][scale_factor] = image_path;
1213 id = GetPersistentIDByNameHelper(image_name,
1214 kPersistingImagesWinDesktopAura,
1215 kPersistingImagesWinDesktopAuraLength);
1217 (*file_paths)[id][scale_factor] = image_path;
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);
1228 source_images_ = new int[ids.size() + 1];
1229 std::copy(ids.begin(), ids.end(), source_images_);
1230 source_images_[ids.size()] = -1;
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;
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) {
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)) {
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)");
1277 int raw_id = GetRawIDByPersistentID(prs_id, scale_factor);
1278 image_memory_[raw_id] = raw_data;
1281 if (gfx::PNGCodec::Decode(raw_data->front(), raw_data->size(),
1283 image_skia.AddRepresentation(
1284 gfx::ImageSkiaRep(bitmap,
1285 ui::GetImageScale(scale_factor)));
1287 NOTREACHED() << "Unable to decode theme image resource "
1293 if (!is_copyable && !image_skia.isNull())
1294 (*image_cache)[prs_id] = gfx::Image(image_skia);
1300 void BrowserThemePack::CreateImages(ImageCache* images) const {
1302 CreateFrameImages(images);
1303 CreateTintedButtons(GetTintInternal(ThemeProperties::TINT_BUTTONS), images);
1304 CreateTabBackgroundImages(images);
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)
1313 int prs_id = kImagesToCrop[i].prs_id;
1314 ImageCache::iterator it = images->find(prs_id);
1315 if (it == images->end())
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)));
1325 void BrowserThemePack::CreateFrameImages(ImageCache* images) const {
1326 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
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;
1332 for (size_t i = 0; i < arraysize(kFrameTintMap); ++i) {
1333 int prs_id = kFrameTintMap[i].key;
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;
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;
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;
1363 prs_base_id = prs_id;
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) {
1372 if (images->count(PRS_THEME_FRAME_WIN)) {
1374 if (images->count(PRS_THEME_FRAME)) {
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();
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);
1392 if (!frame.IsEmpty()) {
1393 temp_output[prs_id] = CreateHSLShiftedImage(
1394 frame, GetTintInternal(kFrameTintMap[i].value));
1397 MergeImageCaches(temp_output, images);
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);
1412 // Fetch the image by IDR...
1413 gfx::Image& button = rb.GetImageNamed(*it);
1415 // but save a version with the persistent ID.
1416 (*processed_images)[prs_id] =
1417 CreateHSLShiftedImage(button, button_tint);
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;
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;
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();
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()));
1450 MergeImageCaches(temp_output, images);
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();
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 << ".";
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,
1470 NOTREACHED() << "Image file for resource " << it->first
1471 << " could not be encoded.";
1473 int raw_id = GetRawIDByPersistentID(
1475 ui::GetSupportedScaleFactor(rep_it->scale()));
1476 (*reencoded_images)[raw_id] =
1477 base::RefCountedBytes::TakeVector(&bitmap_data);
1482 void BrowserThemePack::MergeImageCaches(
1483 const ImageCache& source, ImageCache* destination) const {
1484 for (ImageCache::const_iterator it = source.begin(); it != source.end();
1486 (*destination)[it->first] = it->second;
1490 void BrowserThemePack::AddRawImagesTo(const RawImages& images,
1491 RawDataForWriting* out) const {
1492 for (RawImages::const_iterator it = images.begin(); it != images.end();
1494 (*out)[it->first] = base::StringPiece(
1495 it->second->front_as<char>(), it->second->size());
1499 color_utils::HSL BrowserThemePack::GetTintInternal(int id) const {
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;
1512 return ThemeProperties::GetDefaultTint(id);
1515 int BrowserThemePack::GetRawIDByPersistentID(
1517 ui::ScaleFactor scale_factor) const {
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;
1528 bool BrowserThemePack::GetScaleFactorFromManifestKey(
1529 const std::string& key,
1530 ui::ScaleFactor* scale_factor) const {
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];
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
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.
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;
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];
1578 // If no scale factor is available, we're done.
1579 if (available_scale_factor == ui::SCALE_FACTOR_NONE)
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(),
1588 &available_bitmap)) {
1589 NOTREACHED() << "Unable to decode theme image for prs_id="
1590 << prs_id << " for scale_factor=" << available_scale_factor;
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())
1599 SkBitmap scaled_bitmap =
1600 CreateLowQualityResizedBitmap(available_bitmap,
1601 available_scale_factor,
1603 std::vector<unsigned char> bitmap_data;
1604 if (!gfx::PNGCodec::EncodeBGRASkBitmap(scaled_bitmap,
1607 NOTREACHED() << "Unable to encode theme image for prs_id="
1608 << prs_id << " for scale_factor=" << scale_factors_[i];
1611 image_memory_[scaled_raw_id] =
1612 base::RefCountedBytes::TakeVector(&bitmap_data);