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/theme_service.h"
10 #include "base/location.h"
11 #include "base/memory/ref_counted_memory.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/sequenced_task_runner.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/thread_task_runner_handle.h"
18 #include "chrome/browser/chrome_notification_types.h"
19 #include "chrome/browser/extensions/extension_service.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/browser/themes/browser_theme_pack.h"
22 #include "chrome/browser/themes/custom_theme_supplier.h"
23 #include "chrome/browser/themes/theme_properties.h"
24 #include "chrome/browser/themes/theme_syncable_service.h"
25 #include "chrome/common/chrome_constants.h"
26 #include "chrome/common/pref_names.h"
27 #include "content/public/browser/notification_service.h"
28 #include "content/public/browser/user_metrics.h"
29 #include "extensions/browser/extension_prefs.h"
30 #include "extensions/browser/extension_registry.h"
31 #include "extensions/browser/extension_system.h"
32 #include "extensions/browser/uninstall_reason.h"
33 #include "extensions/common/extension.h"
34 #include "extensions/common/extension_set.h"
35 #include "grit/theme_resources.h"
36 #include "ui/base/layout.h"
37 #include "ui/base/resource/resource_bundle.h"
38 #include "ui/gfx/image/image_skia.h"
39 #include "ui/native_theme/common_theme.h"
40 #include "ui/native_theme/native_theme.h"
42 #if defined(ENABLE_EXTENSIONS)
43 #include "extensions/browser/extension_registry_observer.h"
46 #if defined(ENABLE_SUPERVISED_USERS)
47 #include "chrome/browser/supervised_user/supervised_user_theme.h"
51 #include "ui/base/win/shell.h"
54 using base::UserMetricsAction
;
55 using content::BrowserThread
;
56 using extensions::Extension
;
57 using extensions::UnloadedExtensionInfo
;
58 using ui::ResourceBundle
;
60 typedef ThemeProperties Properties
;
62 // The default theme if we haven't installed a theme yet or if we've clicked
63 // the "Use Classic" button.
64 const char* ThemeService::kDefaultThemeID
= "";
68 // The default theme if we've gone to the theme gallery and installed the
69 // "Default" theme. We have to detect this case specifically. (By the time we
70 // realize we've installed the default theme, we already have an extension
71 // unpacked on the filesystem.)
72 const char* kDefaultThemeGalleryID
= "hkacjpbfdknhflllbcmjibkdeoafencn";
74 // Wait this many seconds after startup to garbage collect unused themes.
75 // Removing unused themes is done after a delay because there is no
76 // reason to do it at startup.
77 // ExtensionService::GarbageCollectExtensions() does something similar.
78 const int kRemoveUnusedThemesStartupDelay
= 30;
80 SkColor
IncreaseLightness(SkColor color
, double percent
) {
81 color_utils::HSL result
;
82 color_utils::SkColorToHSL(color
, &result
);
83 result
.l
+= (1 - result
.l
) * percent
;
84 return color_utils::HSLToSkColor(result
, SkColorGetA(color
));
87 // Writes the theme pack to disk on a separate thread.
88 void WritePackToDiskCallback(BrowserThemePack
* pack
,
89 const base::FilePath
& path
) {
90 if (!pack
->WriteToDisk(path
))
91 NOTREACHED() << "Could not write theme pack to disk";
94 // Heuristic to determine if color is grayscale. This is used to decide whether
95 // to use the colorful or white logo, if a theme fails to specify which.
96 bool IsColorGrayscale(SkColor color
) {
97 const int kChannelTolerance
= 9;
98 int r
= SkColorGetR(color
);
99 int g
= SkColorGetG(color
);
100 int b
= SkColorGetB(color
);
101 int range
= std::max(r
, std::max(g
, b
)) - std::min(r
, std::min(g
, b
));
102 return range
< kChannelTolerance
;
107 #if defined(ENABLE_EXTENSIONS)
108 class ThemeService::ThemeObserver
109 : public extensions::ExtensionRegistryObserver
{
111 explicit ThemeObserver(ThemeService
* service
) : theme_service_(service
) {
112 extensions::ExtensionRegistry::Get(theme_service_
->profile_
)
116 ~ThemeObserver() override
{
117 extensions::ExtensionRegistry::Get(theme_service_
->profile_
)
118 ->RemoveObserver(this);
122 void OnExtensionWillBeInstalled(content::BrowserContext
* browser_context
,
123 const extensions::Extension
* extension
,
126 const std::string
& old_name
) override
{
127 if (extension
->is_theme()) {
128 // The theme may be initially disabled. Wait till it is loaded (if ever).
129 theme_service_
->installed_pending_load_id_
= extension
->id();
133 void OnExtensionLoaded(content::BrowserContext
* browser_context
,
134 const extensions::Extension
* extension
) override
{
135 if (extension
->is_theme() &&
136 theme_service_
->installed_pending_load_id_
!= kDefaultThemeID
&&
137 theme_service_
->installed_pending_load_id_
== extension
->id()) {
138 theme_service_
->SetTheme(extension
);
140 theme_service_
->installed_pending_load_id_
= kDefaultThemeID
;
143 void OnExtensionUnloaded(
144 content::BrowserContext
* browser_context
,
145 const extensions::Extension
* extension
,
146 extensions::UnloadedExtensionInfo::Reason reason
) override
{
147 if (reason
!= extensions::UnloadedExtensionInfo::REASON_UPDATE
&&
148 reason
!= extensions::UnloadedExtensionInfo::REASON_LOCK_ALL
&&
149 extension
->is_theme() &&
150 extension
->id() == theme_service_
->GetThemeID()) {
151 theme_service_
->UseDefaultTheme();
155 ThemeService
* theme_service_
;
157 #endif // defined(ENABLE_EXTENSIONS)
159 ThemeService::ThemeService()
161 rb_(ResourceBundle::GetSharedInstance()),
163 installed_pending_load_id_(kDefaultThemeID
),
164 number_of_infobars_(0),
165 weak_ptr_factory_(this) {
168 ThemeService::~ThemeService() {
169 FreePlatformCaches();
172 void ThemeService::Init(Profile
* profile
) {
173 DCHECK(CalledOnValidThread());
179 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
,
180 content::Source
<Profile
>(profile_
));
182 theme_syncable_service_
.reset(new ThemeSyncableService(profile_
, this));
185 gfx::Image
ThemeService::GetImageNamed(int id
) const {
186 DCHECK(CalledOnValidThread());
189 if (theme_supplier_
.get())
190 image
= theme_supplier_
->GetImageNamed(id
);
193 image
= rb_
.GetNativeImageNamed(id
);
198 bool ThemeService::IsSystemThemeDistinctFromDefaultTheme() const {
202 bool ThemeService::UsingSystemTheme() const {
203 return UsingDefaultTheme();
206 gfx::ImageSkia
* ThemeService::GetImageSkiaNamed(int id
) const {
207 gfx::Image image
= GetImageNamed(id
);
210 // TODO(pkotwicz): Remove this const cast. The gfx::Image interface returns
211 // its images const. GetImageSkiaNamed() also should but has many callsites.
212 return const_cast<gfx::ImageSkia
*>(image
.ToImageSkia());
215 SkColor
ThemeService::GetColor(int id
) const {
216 DCHECK(CalledOnValidThread());
218 if (theme_supplier_
.get() && theme_supplier_
->GetColor(id
, &color
))
221 // For backward compat with older themes, some newer colors are generated from
222 // older ones if they are missing.
224 case Properties::COLOR_NTP_SECTION_HEADER_TEXT
:
225 return IncreaseLightness(GetColor(Properties::COLOR_NTP_TEXT
), 0.30);
226 case Properties::COLOR_NTP_SECTION_HEADER_TEXT_HOVER
:
227 return GetColor(Properties::COLOR_NTP_TEXT
);
228 case Properties::COLOR_NTP_SECTION_HEADER_RULE
:
229 return IncreaseLightness(GetColor(Properties::COLOR_NTP_TEXT
), 0.70);
230 case Properties::COLOR_NTP_SECTION_HEADER_RULE_LIGHT
:
231 return IncreaseLightness(GetColor(Properties::COLOR_NTP_TEXT
), 0.86);
232 case Properties::COLOR_NTP_TEXT_LIGHT
:
233 return IncreaseLightness(GetColor(Properties::COLOR_NTP_TEXT
), 0.40);
234 case Properties::COLOR_THROBBER_SPINNING
:
235 case Properties::COLOR_THROBBER_WAITING
: {
237 bool found_color
= ui::CommonThemeGetSystemColor(
238 id
== Properties::COLOR_THROBBER_SPINNING
239 ? ui::NativeTheme::kColorId_ThrobberSpinningColor
240 : ui::NativeTheme::kColorId_ThrobberWaitingColor
,
243 color_utils::HSL hsl
= GetTint(Properties::TINT_BUTTONS
);
244 return color_utils::HSLShift(base_color
, hsl
);
246 #if defined(ENABLE_SUPERVISED_USERS)
247 case Properties::COLOR_SUPERVISED_USER_LABEL
:
248 return color_utils::GetReadableColor(
250 GetColor(Properties::COLOR_SUPERVISED_USER_LABEL_BACKGROUND
));
251 case Properties::COLOR_SUPERVISED_USER_LABEL_BACKGROUND
:
252 return color_utils::BlendTowardOppositeLuminance(
253 GetColor(Properties::COLOR_FRAME
), 0x80);
254 case Properties::COLOR_SUPERVISED_USER_LABEL_BORDER
:
255 return color_utils::AlphaBlend(
256 GetColor(Properties::COLOR_SUPERVISED_USER_LABEL_BACKGROUND
),
260 case Properties::COLOR_STATUS_BAR_TEXT
: {
261 // A long time ago, we blended the toolbar and the tab text together to
262 // get the status bar text because, at the time, our text rendering in
263 // views couldn't do alpha blending. Even though this is no longer the
264 // case, this blending decision is built into the majority of themes that
265 // exist, and we must keep doing it.
266 SkColor toolbar_color
= GetColor(Properties::COLOR_TOOLBAR
);
267 SkColor text_color
= GetColor(Properties::COLOR_TAB_TEXT
);
268 return SkColorSetARGB(
269 SkColorGetA(text_color
),
270 (SkColorGetR(text_color
) + SkColorGetR(toolbar_color
)) / 2,
271 (SkColorGetG(text_color
) + SkColorGetR(toolbar_color
)) / 2,
272 (SkColorGetB(text_color
) + SkColorGetR(toolbar_color
)) / 2);
276 return Properties::GetDefaultColor(id
);
279 int ThemeService::GetDisplayProperty(int id
) const {
281 if (theme_supplier_
.get() &&
282 theme_supplier_
->GetDisplayProperty(id
, &result
)) {
286 if (id
== Properties::NTP_LOGO_ALTERNATE
) {
287 if (UsingDefaultTheme() || UsingSystemTheme())
288 return 0; // Colorful logo.
290 if (HasCustomImage(IDR_THEME_NTP_BACKGROUND
))
291 return 1; // White logo.
293 SkColor background_color
= GetColor(Properties::COLOR_NTP_BACKGROUND
);
294 return IsColorGrayscale(background_color
) ? 0 : 1;
297 return Properties::GetDefaultDisplayProperty(id
);
300 bool ThemeService::ShouldUseNativeFrame() const {
301 if (HasCustomImage(IDR_THEME_FRAME
))
304 return ui::win::IsAeroGlassEnabled();
310 bool ThemeService::HasCustomImage(int id
) const {
311 return BrowserThemePack::IsPersistentImageID(id
) &&
312 theme_supplier_
&& theme_supplier_
->HasCustomImage(id
);
315 base::RefCountedMemory
* ThemeService::GetRawData(
317 ui::ScaleFactor scale_factor
) const {
318 // Check to see whether we should substitute some images.
319 int ntp_alternate
= GetDisplayProperty(Properties::NTP_LOGO_ALTERNATE
);
320 if (id
== IDR_PRODUCT_LOGO
&& ntp_alternate
!= 0)
321 id
= IDR_PRODUCT_LOGO_WHITE
;
323 base::RefCountedMemory
* data
= nullptr;
324 if (theme_supplier_
.get())
325 data
= theme_supplier_
->GetRawData(id
, scale_factor
);
327 data
= rb_
.LoadDataResourceBytesForScale(id
, ui::SCALE_FACTOR_100P
);
332 void ThemeService::Shutdown() {
333 #if defined(ENABLE_EXTENSIONS)
334 theme_observer_
.reset();
338 void ThemeService::Observe(int type
,
339 const content::NotificationSource
& source
,
340 const content::NotificationDetails
& details
) {
341 using content::Details
;
343 case extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
:
344 registrar_
.Remove(this,
345 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
,
346 content::Source
<Profile
>(profile_
));
347 OnExtensionServiceReady();
349 case extensions::NOTIFICATION_EXTENSION_ENABLED
: {
350 const Extension
* extension
= Details
<const Extension
>(details
).ptr();
351 if (extension
->is_theme())
360 void ThemeService::SetTheme(const Extension
* extension
) {
361 DCHECK(extension
->is_theme());
362 ExtensionService
* service
=
363 extensions::ExtensionSystem::Get(profile_
)->extension_service();
364 if (!service
->IsExtensionEnabled(extension
->id())) {
365 // |extension| is disabled when reverting to the previous theme via an
367 service
->EnableExtension(extension
->id());
368 // Enabling the extension will call back to SetTheme().
372 std::string previous_theme_id
= GetThemeID();
374 // Clear our image cache.
375 FreePlatformCaches();
377 BuildFromExtension(extension
);
378 SaveThemeID(extension
->id());
380 NotifyThemeChanged();
381 content::RecordAction(UserMetricsAction("Themes_Installed"));
383 if (previous_theme_id
!= kDefaultThemeID
&&
384 previous_theme_id
!= extension
->id()) {
385 // Disable the old theme.
386 service
->DisableExtension(previous_theme_id
,
387 extensions::Extension::DISABLE_USER_ACTION
);
391 void ThemeService::SetCustomDefaultTheme(
392 scoped_refptr
<CustomThemeSupplier
> theme_supplier
) {
394 SwapThemeSupplier(theme_supplier
);
395 NotifyThemeChanged();
398 bool ThemeService::ShouldInitWithSystemTheme() const {
402 void ThemeService::RemoveUnusedThemes(bool ignore_infobars
) {
403 // We do not want to garbage collect themes on startup (|ready_| is false).
404 // Themes will get garbage collected after |kRemoveUnusedThemesStartupDelay|.
405 if (!profile_
|| !ready_
)
407 if (!ignore_infobars
&& number_of_infobars_
!= 0)
410 ExtensionService
* service
=
411 extensions::ExtensionSystem::Get(profile_
)->extension_service();
415 std::string current_theme
= GetThemeID();
416 std::vector
<std::string
> remove_list
;
417 scoped_ptr
<const extensions::ExtensionSet
> extensions(
418 extensions::ExtensionRegistry::Get(profile_
)
419 ->GenerateInstalledExtensionsSet());
420 extensions::ExtensionPrefs
* prefs
= extensions::ExtensionPrefs::Get(profile_
);
421 for (extensions::ExtensionSet::const_iterator it
= extensions
->begin();
422 it
!= extensions
->end(); ++it
) {
423 const extensions::Extension
* extension
= it
->get();
424 if (extension
->is_theme() &&
425 extension
->id() != current_theme
) {
426 // Only uninstall themes which are not disabled or are disabled with
427 // reason DISABLE_USER_ACTION. We cannot blanket uninstall all disabled
428 // themes because externally installed themes are initially disabled.
429 int disable_reason
= prefs
->GetDisableReasons(extension
->id());
430 if (!prefs
->IsExtensionDisabled(extension
->id()) ||
431 disable_reason
== Extension::DISABLE_USER_ACTION
) {
432 remove_list
.push_back((*it
)->id());
436 // TODO: Garbage collect all unused themes. This method misses themes which
437 // are installed but not loaded because they are blacklisted by a management
440 for (size_t i
= 0; i
< remove_list
.size(); ++i
) {
441 service
->UninstallExtension(remove_list
[i
],
442 extensions::UNINSTALL_REASON_ORPHANED_THEME
,
443 base::Bind(&base::DoNothing
), nullptr);
447 void ThemeService::UseDefaultTheme() {
449 content::RecordAction(UserMetricsAction("Themes_Reset"));
450 #if defined(ENABLE_SUPERVISED_USERS)
451 if (IsSupervisedUser()) {
452 SetSupervisedUserTheme();
457 NotifyThemeChanged();
460 void ThemeService::UseSystemTheme() {
464 bool ThemeService::UsingDefaultTheme() const {
465 std::string id
= GetThemeID();
466 return id
== ThemeService::kDefaultThemeID
||
467 id
== kDefaultThemeGalleryID
;
470 std::string
ThemeService::GetThemeID() const {
471 return profile_
->GetPrefs()->GetString(prefs::kCurrentThemeID
);
474 color_utils::HSL
ThemeService::GetTint(int id
) const {
475 DCHECK(CalledOnValidThread());
477 color_utils::HSL hsl
;
478 if (theme_supplier_
.get() && theme_supplier_
->GetTint(id
, &hsl
))
481 return ThemeProperties::GetDefaultTint(id
);
484 void ThemeService::ClearAllThemeData() {
488 SwapThemeSupplier(nullptr);
490 // Clear our image cache.
491 FreePlatformCaches();
493 profile_
->GetPrefs()->ClearPref(prefs::kCurrentThemePackFilename
);
494 SaveThemeID(kDefaultThemeID
);
496 // There should be no more infobars. This may not be the case because of
497 // http://crbug.com/62154
498 // RemoveUnusedThemes is called on a task because ClearAllThemeData() may
499 // be called as a result of NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED.
500 base::ThreadTaskRunnerHandle::Get()->PostTask(
501 FROM_HERE
, base::Bind(&ThemeService::RemoveUnusedThemes
,
502 weak_ptr_factory_
.GetWeakPtr(), true));
505 void ThemeService::LoadThemePrefs() {
506 PrefService
* prefs
= profile_
->GetPrefs();
508 std::string current_id
= GetThemeID();
509 if (current_id
== kDefaultThemeID
) {
510 #if defined(ENABLE_SUPERVISED_USERS)
511 // Supervised users have a different default theme.
512 if (IsSupervisedUser()) {
513 SetSupervisedUserTheme();
518 if (ShouldInitWithSystemTheme())
526 bool loaded_pack
= false;
528 // If we don't have a file pack, we're updating from an old version.
529 base::FilePath path
= prefs
->GetFilePath(prefs::kCurrentThemePackFilename
);
530 if (path
!= base::FilePath()) {
531 SwapThemeSupplier(BrowserThemePack::BuildFromDataPack(path
, current_id
));
532 loaded_pack
= theme_supplier_
.get() != nullptr;
536 content::RecordAction(UserMetricsAction("Themes.Loaded"));
539 // Else: wait for the extension service to be ready so that the theme pack
540 // can be recreated from the extension.
543 void ThemeService::NotifyThemeChanged() {
547 DVLOG(1) << "Sending BROWSER_THEME_CHANGED";
549 content::NotificationService
* service
=
550 content::NotificationService::current();
551 service
->Notify(chrome::NOTIFICATION_BROWSER_THEME_CHANGED
,
552 content::Source
<ThemeService
>(this),
553 content::NotificationService::NoDetails());
554 #if defined(OS_MACOSX)
555 NotifyPlatformThemeChanged();
558 // Notify sync that theme has changed.
559 if (theme_syncable_service_
.get()) {
560 theme_syncable_service_
->OnThemeChange();
564 #if defined(USE_AURA)
565 void ThemeService::FreePlatformCaches() {
566 // Views (Skia) has no platform image cache to clear.
570 void ThemeService::OnExtensionServiceReady() {
572 // If the ThemeService is not ready yet, the custom theme data pack needs to
573 // be recreated from the extension.
577 // Send notification in case anyone requested data and cached it when the
578 // theme service was not ready yet.
579 NotifyThemeChanged();
582 #if defined(ENABLE_EXTENSIONS)
583 theme_observer_
.reset(new ThemeObserver(this));
587 extensions::NOTIFICATION_EXTENSION_ENABLED
,
588 content::Source
<Profile
>(profile_
));
590 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
591 FROM_HERE
, base::Bind(&ThemeService::RemoveUnusedThemes
,
592 weak_ptr_factory_
.GetWeakPtr(), false),
593 base::TimeDelta::FromSeconds(kRemoveUnusedThemesStartupDelay
));
596 void ThemeService::MigrateTheme() {
597 // TODO(erg): We need to pop up a dialog informing the user that their
598 // theme is being migrated.
599 ExtensionService
* service
=
600 extensions::ExtensionSystem::Get(profile_
)->extension_service();
601 const Extension
* extension
=
602 service
? service
->GetExtensionById(GetThemeID(), false) : nullptr;
604 DLOG(ERROR
) << "Migrating theme";
605 BuildFromExtension(extension
);
606 content::RecordAction(UserMetricsAction("Themes.Migrated"));
608 DLOG(ERROR
) << "Theme is mysteriously gone.";
610 content::RecordAction(UserMetricsAction("Themes.Gone"));
614 void ThemeService::SwapThemeSupplier(
615 scoped_refptr
<CustomThemeSupplier
> theme_supplier
) {
616 if (theme_supplier_
.get())
617 theme_supplier_
->StopUsingTheme();
618 theme_supplier_
= theme_supplier
;
619 if (theme_supplier_
.get())
620 theme_supplier_
->StartUsingTheme();
623 void ThemeService::SavePackName(const base::FilePath
& pack_path
) {
624 profile_
->GetPrefs()->SetFilePath(
625 prefs::kCurrentThemePackFilename
, pack_path
);
628 void ThemeService::SaveThemeID(const std::string
& id
) {
629 profile_
->GetPrefs()->SetString(prefs::kCurrentThemeID
, id
);
632 void ThemeService::BuildFromExtension(const Extension
* extension
) {
633 scoped_refptr
<BrowserThemePack
> pack(
634 BrowserThemePack::BuildFromExtension(extension
));
636 // TODO(erg): We've failed to install the theme; perhaps we should tell the
637 // user? http://crbug.com/34780
638 LOG(ERROR
) << "Could not load theme.";
642 ExtensionService
* service
=
643 extensions::ExtensionSystem::Get(profile_
)->extension_service();
647 // Write the packed file to disk.
648 base::FilePath pack_path
=
649 extension
->path().Append(chrome::kThemePackFilename
);
650 service
->GetFileTaskRunner()->PostTask(
652 base::Bind(&WritePackToDiskCallback
, pack
, pack_path
));
654 SavePackName(pack_path
);
655 SwapThemeSupplier(pack
);
658 #if defined(ENABLE_SUPERVISED_USERS)
659 bool ThemeService::IsSupervisedUser() const {
660 return profile_
->IsSupervised();
663 void ThemeService::SetSupervisedUserTheme() {
664 SetCustomDefaultTheme(new SupervisedUserTheme
);
668 void ThemeService::OnInfobarDisplayed() {
669 number_of_infobars_
++;
672 void ThemeService::OnInfobarDestroyed() {
673 number_of_infobars_
--;
675 if (number_of_infobars_
== 0)
676 RemoveUnusedThemes(false);
679 ThemeSyncableService
* ThemeService::GetThemeSyncableService() const {
680 return theme_syncable_service_
.get();