views: Add support for OS and Chrome themes (fixes #3610, fixes #3671)

Controls now respect OS and Chrome themes by default for both Alloy
and Chrome runtimes. Chrome themes (mode and colors) can be configured
using the new CefRequestContext::SetChromeColorScheme method. Individual
theme colors can be overridden using the new CefWindowDelegate::
OnThemeColorsChanged and CefWindow::SetThemeColor methods.

The `--force-light-mode` and `--force-dark-mode` command-line flags are
now respected on all platforms as an override for the OS theme.

The current Chrome theme, if any, will take precedence over the OS theme
when determining light/dark status. On Windows and MacOS the titlebar
color will also be updated to match the light/dark theme.

Testable as follows:
- Run: `cefclient --enable-chrome-runtime` OR
       `cefclient --use-views --persist-user-preferences --cache-path=...`
  - App launches with default OS light/dark theme colors.
  - Change OS dark/light theme under system settings. Notice that theme
    colors change as expected.
  - Right click, select items from the new Theme sub-menu. Notice that
    theme colors behave as expected.
  - Exit and relaunch the app. Notice that the last-used theme colors are
    applied on app restart.
- Add `--background-color=green` to above command-line.
  - Perform the same actions as above. Notice that all controls start
    and remain green throughout (except some icons with Chrome runtime).
- Add `--force-light-mode` or `--force-dark-mode` to above command-line.
  - Perform the same actions as above. Notice that OS dark/light theme
    changes are ignored, but Chrome theme changes work as expected.
This commit is contained in:
Marshall Greenblatt
2024-03-29 12:48:33 -04:00
parent 8a9a766d6d
commit 759cdc7584
97 changed files with 2975 additions and 206 deletions

View File

@@ -384,7 +384,7 @@ index 2f0fe9d22667c..f50fe7bf75df3 100644
+#endif
}
diff --git chrome/browser/chrome_content_browser_client.cc chrome/browser/chrome_content_browser_client.cc
index 011ffe3477b67..7bc473463374c 100644
index 011ffe3477b67..e56c0581ab844 100644
--- chrome/browser/chrome_content_browser_client.cc
+++ chrome/browser/chrome_content_browser_client.cc
@@ -47,6 +47,7 @@
@@ -416,7 +416,33 @@ index 011ffe3477b67..7bc473463374c 100644
// static
void ChromeContentBrowserClient::RegisterLocalStatePrefs(
PrefRegistrySimple* registry) {
@@ -4360,9 +4368,11 @@ void ChromeContentBrowserClient::BrowserURLHandlerCreated(
@@ -3612,9 +3620,24 @@ bool UpdatePreferredColorScheme(WebPreferences* web_prefs,
: blink::mojom::PreferredColorScheme::kLight;
}
#else
+ auto preferred_color_scheme = native_theme->GetPreferredColorScheme();
+
+ auto* profile = Profile::FromBrowserContext(
+ web_contents->GetBrowserContext());
+ const auto* theme_service = ThemeServiceFactory::GetForProfile(profile);
+
+ const auto browser_color_scheme = theme_service->GetBrowserColorScheme();
+ if (browser_color_scheme != ThemeService::BrowserColorScheme::kSystem) {
+ // Override the native theme.
+ preferred_color_scheme =
+ browser_color_scheme == ThemeService::BrowserColorScheme::kLight
+ ? ui::NativeTheme::PreferredColorScheme::kLight
+ : ui::NativeTheme::PreferredColorScheme::kDark;
+ }
+
// Update based on native theme scheme.
web_prefs->preferred_color_scheme =
- ToBlinkPreferredColorScheme(native_theme->GetPreferredColorScheme());
+ ToBlinkPreferredColorScheme(preferred_color_scheme);
#endif // BUILDFLAG(IS_ANDROID)
// Reauth WebUI doesn't support dark mode yet because it shares the dialog
@@ -4360,9 +4383,11 @@ void ChromeContentBrowserClient::BrowserURLHandlerCreated(
&search::HandleNewTabURLReverseRewrite);
#endif // BUILDFLAG(IS_ANDROID)
@@ -428,7 +454,7 @@ index 011ffe3477b67..7bc473463374c 100644
}
base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
@@ -6469,7 +6479,7 @@ void ChromeContentBrowserClient::OnNetworkServiceCreated(
@@ -6469,7 +6494,7 @@ void ChromeContentBrowserClient::OnNetworkServiceCreated(
#endif
}
@@ -437,7 +463,7 @@ index 011ffe3477b67..7bc473463374c 100644
content::BrowserContext* context,
bool in_memory,
const base::FilePath& relative_partition_path,
@@ -6487,6 +6497,8 @@ void ChromeContentBrowserClient::ConfigureNetworkContextParams(
@@ -6487,6 +6512,8 @@ void ChromeContentBrowserClient::ConfigureNetworkContextParams(
network_context_params->user_agent = GetUserAgentBasedOnPolicy(context);
network_context_params->accept_language = GetApplicationLocale();
}
@@ -446,7 +472,7 @@ index 011ffe3477b67..7bc473463374c 100644
}
std::vector<base::FilePath>
@@ -7612,10 +7624,10 @@ void ChromeContentBrowserClient::OnKeepaliveRequestStarted(
@@ -7612,10 +7639,10 @@ void ChromeContentBrowserClient::OnKeepaliveRequestStarted(
const auto now = base::TimeTicks::Now();
const auto timeout = GetKeepaliveTimerTimeout(context);
keepalive_deadline_ = std::max(keepalive_deadline_, now + timeout);
@@ -459,7 +485,7 @@ index 011ffe3477b67..7bc473463374c 100644
FROM_HERE, keepalive_deadline_ - now,
base::BindOnce(
&ChromeContentBrowserClient::OnKeepaliveTimerFired,
@@ -7634,7 +7646,8 @@ void ChromeContentBrowserClient::OnKeepaliveRequestFinished() {
@@ -7634,7 +7661,8 @@ void ChromeContentBrowserClient::OnKeepaliveRequestFinished() {
--num_keepalive_requests_;
if (num_keepalive_requests_ == 0) {
DVLOG(1) << "Stopping the keepalive timer";
@@ -469,7 +495,7 @@ index 011ffe3477b67..7bc473463374c 100644
// This deletes the keep alive handle attached to the timer function and
// unblock the shutdown sequence.
}
@@ -7774,7 +7787,7 @@ void ChromeContentBrowserClient::OnKeepaliveTimerFired(
@@ -7774,7 +7802,7 @@ void ChromeContentBrowserClient::OnKeepaliveTimerFired(
const auto now = base::TimeTicks::Now();
const auto then = keepalive_deadline_;
if (now < then) {

View File

@@ -233,7 +233,7 @@ index 0ccfe39eb5696..c9424316b6d14 100644
return gfx::Rect();
}
diff --git chrome/browser/ui/views/frame/browser_frame.cc chrome/browser/ui/views/frame/browser_frame.cc
index cce1835d35be3..5ac27ca62876a 100644
index cce1835d35be3..75f8aae063ada 100644
--- chrome/browser/ui/views/frame/browser_frame.cc
+++ chrome/browser/ui/views/frame/browser_frame.cc
@@ -114,15 +114,23 @@ ui::ColorProviderKey::SchemeVariant GetSchemeVariant(
@@ -341,7 +341,21 @@ index cce1835d35be3..5ac27ca62876a 100644
key.app_controller = browser_view_->browser()->app_controller();
@@ -637,5 +671,8 @@ bool BrowserFrame::RegenerateFrameOnThemeChange(
@@ -572,6 +606,13 @@ void BrowserFrame::SelectNativeTheme() {
return;
}
+ // Always use the NativeTheme for forced color modes.
+ if (ui::NativeTheme::IsForcedDarkMode() ||
+ ui::NativeTheme::IsForcedLightMode()) {
+ SetNativeTheme(native_theme);
+ return;
+ }
+
// Ignore the system theme for web apps with window-controls-overlay as the
// display_override so the web contents can blend with the overlay by using
// the developer-provided theme color for a better experience. Context:
@@ -637,5 +678,8 @@ bool BrowserFrame::RegenerateFrameOnThemeChange(
}
bool BrowserFrame::IsIncognitoBrowser() const {
@@ -351,7 +365,7 @@ index cce1835d35be3..5ac27ca62876a 100644
return browser_view_->browser()->profile()->IsIncognitoProfile();
}
diff --git chrome/browser/ui/views/frame/browser_frame.h chrome/browser/ui/views/frame/browser_frame.h
index 2e973c9e279b0..12b62efb8071f 100644
index 2e973c9e279b0..8662f9cf14b17 100644
--- chrome/browser/ui/views/frame/browser_frame.h
+++ chrome/browser/ui/views/frame/browser_frame.h
@@ -58,7 +58,9 @@ enum class TabDragKind {
@@ -364,6 +378,38 @@ index 2e973c9e279b0..12b62efb8071f 100644
BrowserFrame(const BrowserFrame&) = delete;
BrowserFrame& operator=(const BrowserFrame&) = delete;
@@ -137,7 +139,7 @@ class BrowserFrame : public views::Widget, public views::ContextMenuController {
// ThemeService calls this when a user has changed their theme, indicating
// that it's time to redraw everything.
- void UserChangedTheme(BrowserThemeChangeType theme_change_type);
+ virtual void UserChangedTheme(BrowserThemeChangeType theme_change_type);
// views::Widget:
views::internal::RootView* CreateRootView() override;
@@ -175,17 +177,17 @@ class BrowserFrame : public views::Widget, public views::ContextMenuController {
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
ui::ColorProviderKey GetColorProviderKey() const override;
+ // Select a native theme that is appropriate for the current context. This is
+ // currently only needed for Linux to switch between the regular NativeTheme
+ // and the GTK NativeTheme instance.
+ void SelectNativeTheme();
+
private:
void OnTouchUiChanged();
// Callback for MenuRunner.
void OnMenuClosed();
- // Select a native theme that is appropriate for the current context. This is
- // currently only needed for Linux to switch between the regular NativeTheme
- // and the GTK NativeTheme instance.
- void SelectNativeTheme();
-
// Regenerate the frame on theme change if necessary. Returns true if
// regenerated.
bool RegenerateFrameOnThemeChange(BrowserThemeChangeType theme_change_type);
diff --git chrome/browser/ui/views/frame/browser_view.cc chrome/browser/ui/views/frame/browser_view.cc
index f764d5edc704c..b7d5ee188736e 100644
--- chrome/browser/ui/views/frame/browser_view.cc

View File

@@ -0,0 +1,104 @@
diff --git ui/color/color_provider_manager.cc ui/color/color_provider_manager.cc
index a0933fab35037..7a381e24a8816 100644
--- ui/color/color_provider_manager.cc
+++ ui/color/color_provider_manager.cc
@@ -46,6 +46,15 @@ std::optional<GlobalManager>& GetGlobalManager() {
} // namespace
+void ColorProviderManager::AddObserver(ColorProviderManagerObserver* observer) {
+ observers_.AddObserver(observer);
+}
+
+void ColorProviderManager::RemoveObserver(
+ ColorProviderManagerObserver* observer) {
+ observers_.RemoveObserver(observer);
+}
+
ColorProviderManager::ColorProviderManager() {
ResetColorProviderInitializerList();
}
@@ -86,8 +95,19 @@ void ColorProviderManager::ResetColorProviderInitializerList() {
}
void ColorProviderManager::ResetColorProviderCache() {
- if (!color_providers_.empty())
+ if (!color_providers_.empty()) {
color_providers_.clear();
+
+ for (ColorProviderManagerObserver& observer : observers_) {
+ observer.OnColorProviderCacheReset();
+ }
+ }
+}
+
+void ColorProviderManager::AfterNativeThemeUpdated() {
+ for (ColorProviderManagerObserver& observer : observers_) {
+ observer.OnAfterNativeThemeUpdated();
+ }
}
void ColorProviderManager::AppendColorProviderInitializer(
diff --git ui/color/color_provider_manager.h ui/color/color_provider_manager.h
index 67341dd5fc3d6..ee70de7f7fd44 100644
--- ui/color/color_provider_manager.h
+++ ui/color/color_provider_manager.h
@@ -15,6 +15,7 @@
#include "base/containers/flat_map.h"
#include "base/functional/callback.h"
#include "base/memory/weak_ptr.h"
+#include "base/observer_list.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/color/color_provider_key.h"
#include "ui/color/system_theme.h"
@@ -24,6 +25,19 @@ namespace ui {
class ColorProvider;
+// Observers which are notified when the color provider manager changes.
+class COMPONENT_EXPORT(COLOR) ColorProviderManagerObserver {
+ public:
+ // Called when the color provider cache is reset.
+ virtual void OnColorProviderCacheReset() {}
+
+ // Called after NativeTheme sends OnNativeThemeUpdated notifications.
+ virtual void OnAfterNativeThemeUpdated() {}
+
+ protected:
+ virtual ~ColorProviderManagerObserver() = default;
+};
+
// Manages and provides color providers.
//
// In most cases, use ColorProviderManager::Get() to obtain an instance to the
@@ -48,6 +62,9 @@ class COMPONENT_EXPORT(COLOR) ColorProviderManager {
// Clears the ColorProviders stored in `color_providers_`.
void ResetColorProviderCache();
+ // Called after NativeTheme sends OnNativeThemeUpdated notifications.
+ void AfterNativeThemeUpdated();
+
// Appends `initializer` to the end of the current `initializer_list_`.
void AppendColorProviderInitializer(
ColorProviderInitializerList::CallbackType Initializer);
@@ -59,6 +76,10 @@ class COMPONENT_EXPORT(COLOR) ColorProviderManager {
return num_providers_initialized_;
}
+ // Add or remove observers.
+ void AddObserver(ColorProviderManagerObserver* observer);
+ void RemoveObserver(ColorProviderManagerObserver* observer);
+
protected:
ColorProviderManager();
virtual ~ColorProviderManager();
@@ -76,6 +97,9 @@ class COMPONENT_EXPORT(COLOR) ColorProviderManager {
// Tracks the number of ColorProviders constructed and initialized by the
// manager for metrics purposes.
size_t num_providers_initialized_ = 0;
+
+ base::ObserverList<ColorProviderManagerObserver>::UncheckedAndDanglingUntriaged
+ observers_;
};
} // namespace ui

View File

@@ -31,25 +31,86 @@ index 73d6ad5e9bb36..6c450e79c0f94 100644
auto& dark_mode_support = GetDarkModeSupport();
return (dark_mode_support.allow_dark_mode_for_app ||
dark_mode_support.set_preferred_app_mode) &&
diff --git ui/native_theme/native_theme_mac.mm ui/native_theme/native_theme_mac.mm
index d8ff86972911d..0fbafdef0fc26 100644
--- ui/native_theme/native_theme_mac.mm
+++ ui/native_theme/native_theme_mac.mm
@@ -51,6 +51,13 @@ bool InvertedColors() {
return NSWorkspace.sharedWorkspace.accessibilityDisplayShouldInvertColors;
diff --git chrome/browser/ui/views/chrome_browser_main_extra_parts_views_linux.cc chrome/browser/ui/views/chrome_browser_main_extra_parts_views_linux.cc
index 23d0611fdb2b5..81fd1055e926e 100644
--- chrome/browser/ui/views/chrome_browser_main_extra_parts_views_linux.cc
+++ chrome/browser/ui/views/chrome_browser_main_extra_parts_views_linux.cc
@@ -61,7 +61,10 @@ void ChromeBrowserMainExtraPartsViewsLinux::ToolkitInitialized() {
linux_ui_theme->GetNativeTheme()->system_theme());
}
#if defined(USE_DBUS)
- dark_mode_manager_ = std::make_unique<ui::DarkModeManagerLinux>();
+ if (!ui::NativeTheme::IsForcedDarkMode() &&
+ !ui::NativeTheme::IsForcedLightMode()) {
+ dark_mode_manager_ = std::make_unique<ui::DarkModeManagerLinux>();
+ }
#endif
}
+bool IsForcedLightMode() {
diff --git ui/gtk/native_theme_gtk.cc ui/gtk/native_theme_gtk.cc
index d69b17b004120..5175ea3a785a3 100644
--- ui/gtk/native_theme_gtk.cc
+++ ui/gtk/native_theme_gtk.cc
@@ -164,9 +164,11 @@ void NativeThemeGtk::OnThemeChanged(GtkSettings* settings,
// have a light variant and aren't affected by the setting. Because of this,
// experimentally check if the theme is dark by checking if the window
// background color is dark.
- const SkColor window_bg_color = GetBgColor("");
- set_use_dark_colors(IsForcedDarkMode() ||
- color_utils::IsDark(window_bg_color));
+ if (!IsForcedLightMode()) {
+ const SkColor window_bg_color = GetBgColor("");
+ set_use_dark_colors(IsForcedDarkMode() ||
+ color_utils::IsDark(window_bg_color));
+ }
set_preferred_color_scheme(CalculatePreferredColorScheme());
// GTK doesn't have a native high contrast setting. Rather, it's implied by
diff --git ui/native_theme/native_theme.cc ui/native_theme/native_theme.cc
index d466e72df7e2c..d0a58289ca291 100644
--- ui/native_theme/native_theme.cc
+++ ui/native_theme/native_theme.cc
@@ -143,6 +143,7 @@ void NativeTheme::NotifyOnNativeThemeUpdated() {
color_provider_manager.ResetColorProviderCache();
for (NativeThemeObserver& observer : native_theme_observers_)
observer.OnNativeThemeUpdated(this);
+ color_provider_manager.AfterNativeThemeUpdated();
RecordNumColorProvidersInitializedDuringOnNativeThemeUpdated(
color_provider_manager.num_providers_initialized() -
@@ -276,6 +277,13 @@ bool NativeTheme::IsForcedDarkMode() {
return kIsForcedDarkMode;
}
+bool NativeTheme::IsForcedLightMode() {
+ static bool kIsForcedLightMode =
+ base::CommandLine::ForCurrentProcess()->HasSwitch(
+ "force-light-mode");
+ return kIsForcedLightMode;
+}
+
} // namespace
bool NativeTheme::IsForcedHighContrast() {
static bool kIsForcedHighContrast =
base::CommandLine::ForCurrentProcess()->HasSwitch(
diff --git ui/native_theme/native_theme.h ui/native_theme/native_theme.h
index 3385e9e9d5690..54b69691383bf 100644
--- ui/native_theme/native_theme.h
+++ ui/native_theme/native_theme.h
@@ -603,6 +603,9 @@ class NATIVE_THEME_EXPORT NativeTheme {
// Whether dark mode is forced via command-line flag.
static bool IsForcedDarkMode();
// Helper object to respond to light mode/dark mode changeovers.
@@ -585,11 +592,15 @@ void NativeThemeMac::PaintSelectedMenuItem(
+ // Whether light mode is forced via command-line flag.
+ static bool IsForcedLightMode();
+
protected:
explicit NativeTheme(
bool should_only_use_dark_colors,
diff --git ui/native_theme/native_theme_mac.mm ui/native_theme/native_theme_mac.mm
index d8ff86972911d..c6cc9c70741c9 100644
--- ui/native_theme/native_theme_mac.mm
+++ ui/native_theme/native_theme_mac.mm
@@ -585,11 +585,15 @@ void NativeThemeMac::PaintSelectedMenuItem(
void NativeThemeMac::InitializeDarkModeStateAndObserver() {
__block auto theme = this;

View File

@@ -0,0 +1,90 @@
diff --git ui/gtk/gtk_ui.cc ui/gtk/gtk_ui.cc
index ab8f0d6b545b2..c4bd035f1cec4 100644
--- ui/gtk/gtk_ui.cc
+++ ui/gtk/gtk_ui.cc
@@ -26,6 +26,7 @@
#include "base/numerics/safe_conversions.h"
#include "base/observer_list.h"
#include "base/strings/string_split.h"
+#include "cef/libcef/features/features.h"
#include "chrome/browser/themes/theme_properties.h" // nogncheck
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
@@ -238,10 +239,15 @@ bool GtkUi::Initialize() {
};
GtkSettings* settings = gtk_settings_get_default();
+ // Disable GTK theme change notifications because they are extremely slow.
+ // Light/dark theme changes will still be detected via DarkModeManagerLinux.
+ // See https://issues.chromium.org/issues/40280130#comment7
+#if !BUILDFLAG(ENABLE_CEF)
connect(settings, "notify::gtk-theme-name", &GtkUi::OnThemeChanged);
connect(settings, "notify::gtk-icon-theme-name", &GtkUi::OnThemeChanged);
connect(settings, "notify::gtk-application-prefer-dark-theme",
&GtkUi::OnThemeChanged);
+#endif
connect(settings, "notify::gtk-cursor-theme-name",
&GtkUi::OnCursorThemeNameChanged);
connect(settings, "notify::gtk-cursor-theme-size",
diff --git ui/ozone/platform/x11/ozone_platform_x11.cc ui/ozone/platform/x11/ozone_platform_x11.cc
index 94012aae5f38d..852d736136faf 100644
--- ui/ozone/platform/x11/ozone_platform_x11.cc
+++ ui/ozone/platform/x11/ozone_platform_x11.cc
@@ -64,6 +64,8 @@ namespace ui {
namespace {
+bool g_multi_threaded_message_loop = false;
+
// Singleton OzonePlatform implementation for X11 platform.
class OzonePlatformX11 : public OzonePlatform,
public OSExchangeDataProviderFactoryOzone {
@@ -260,7 +262,15 @@ class OzonePlatformX11 : public OzonePlatform,
TouchFactory::SetTouchDeviceListFromCommandLine();
#if BUILDFLAG(USE_GTK)
- linux_ui_delegate_ = std::make_unique<LinuxUiDelegateX11>();
+ // Not creating the LinuxUiDelegateX11 will disable creation of GtkUi
+ // (interface to GTK desktop features) and cause ui::GetDefaultLinuxUi()
+ // (and related functions) to return nullptr. We can't use GtkUi in
+ // combination with multi-threaded-message-loop because Chromium's GTK
+ // implementation doesn't use GDK threads. Light/dark theme changes will
+ // still be detected via DarkModeManagerLinux.
+ if (!g_multi_threaded_message_loop) {
+ linux_ui_delegate_ = std::make_unique<LinuxUiDelegateX11>();
+ }
#endif
menu_utils_ = std::make_unique<X11MenuUtils>();
@@ -355,4 +365,8 @@ OzonePlatform* CreateOzonePlatformX11() {
return new OzonePlatformX11;
}
+void SetMultiThreadedMessageLoopX11() {
+ g_multi_threaded_message_loop = true;
+}
+
} // namespace ui
diff --git ui/ozone/platform/x11/ozone_platform_x11.h ui/ozone/platform/x11/ozone_platform_x11.h
index fd71ca6c81b7a..f1b7464b71e9d 100644
--- ui/ozone/platform/x11/ozone_platform_x11.h
+++ ui/ozone/platform/x11/ozone_platform_x11.h
@@ -5,6 +5,8 @@
#ifndef UI_OZONE_PLATFORM_X11_OZONE_PLATFORM_X11_H_
#define UI_OZONE_PLATFORM_X11_OZONE_PLATFORM_X11_H_
+#include "base/component_export.h"
+
namespace ui {
class OzonePlatform;
@@ -12,6 +14,9 @@ class OzonePlatform;
// Constructor hook for use in ozone_platform_list.cc
OzonePlatform* CreateOzonePlatformX11();
+// Indicate that CEF is using multi-threaded-message-loop.
+COMPONENT_EXPORT(OZONE) void SetMultiThreadedMessageLoopX11();
+
} // namespace ui
#endif // UI_OZONE_PLATFORM_X11_OZONE_PLATFORM_X11_H_