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