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