1 // Copyright (c) 2011 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/theme_service.h"
6
7 #include <gdk-pixbuf/gdk-pixbuf.h>
8
9 #include "base/i18n/rtl.h"
10 #include "base/logging.h"
11 #include "third_party/skia/include/core/SkBitmap.h"
12 #include "ui/gfx/gtk_util.h"
13
GetPixbufNamed(int id) const14 GdkPixbuf* ThemeService::GetPixbufNamed(int id) const {
15 return GetPixbufImpl(id, false);
16 }
17
GetRTLEnabledPixbufNamed(int id) const18 GdkPixbuf* ThemeService::GetRTLEnabledPixbufNamed(int id) const {
19 return GetPixbufImpl(id, true);
20 }
21
GetPixbufImpl(int id,bool rtl_enabled) const22 GdkPixbuf* ThemeService::GetPixbufImpl(int id, bool rtl_enabled) const {
23 DCHECK(CalledOnValidThread());
24 // Use the negative |resource_id| for the key for BIDI-aware images.
25 int key = rtl_enabled ? -id : id;
26
27 // Check to see if we already have the pixbuf in the cache.
28 GdkPixbufMap::const_iterator pixbufs_iter = gdk_pixbufs_.find(key);
29 if (pixbufs_iter != gdk_pixbufs_.end())
30 return pixbufs_iter->second;
31
32 SkBitmap* bitmap = GetBitmapNamed(id);
33 GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(bitmap);
34
35 // We loaded successfully. Cache the pixbuf.
36 if (pixbuf) {
37 if (base::i18n::IsRTL() && rtl_enabled) {
38 GdkPixbuf* original_pixbuf = pixbuf;
39 pixbuf = gdk_pixbuf_flip(pixbuf, TRUE);
40 g_object_unref(original_pixbuf);
41 }
42
43 gdk_pixbufs_[key] = pixbuf;
44 return pixbuf;
45 }
46
47 // We failed to retrieve the bitmap, show a debugging red square.
48 LOG(WARNING) << "Unable to load GdkPixbuf with id " << id;
49 NOTREACHED(); // Want to assert in debug mode.
50
51 static GdkPixbuf* empty_bitmap = NULL;
52 if (!empty_bitmap) {
53 // The placeholder bitmap is bright red so people notice the problem.
54 // This bitmap will be leaked, but this code should never be hit.
55 scoped_ptr<SkBitmap> skia_bitmap(new SkBitmap());
56 skia_bitmap->setConfig(SkBitmap::kARGB_8888_Config, 32, 32);
57 skia_bitmap->allocPixels();
58 skia_bitmap->eraseARGB(255, 255, 0, 0);
59 empty_bitmap = gfx::GdkPixbufFromSkBitmap(skia_bitmap.get());
60 }
61 return empty_bitmap;
62 }
63
FreePlatformCaches()64 void ThemeService::FreePlatformCaches() {
65 DCHECK(CalledOnValidThread());
66
67 // Free GdkPixbufs.
68 for (GdkPixbufMap::iterator i = gdk_pixbufs_.begin();
69 i != gdk_pixbufs_.end(); i++) {
70 g_object_unref(i->second);
71 }
72 gdk_pixbufs_.clear();
73 }
74