Add ability to gather metrics to BubbleManager.
[chromium-blink-merge.git] / chrome / browser / ui / libgtk2ui / gtk2_ui.cc
blob21e7ce31e942bf51bac8b875fe5febf76ec7592b
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/ui/libgtk2ui/gtk2_ui.h"
7 #include <math.h>
8 #include <set>
10 #include <pango/pango.h>
12 #include "base/command_line.h"
13 #include "base/debug/leak_annotations.h"
14 #include "base/environment.h"
15 #include "base/i18n/rtl.h"
16 #include "base/logging.h"
17 #include "base/nix/mime_util_xdg.h"
18 #include "base/nix/xdg_util.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/stringprintf.h"
22 #include "chrome/browser/themes/theme_properties.h"
23 #include "chrome/browser/ui/libgtk2ui/app_indicator_icon.h"
24 #include "chrome/browser/ui/libgtk2ui/chrome_gtk_frame.h"
25 #include "chrome/browser/ui/libgtk2ui/gtk2_border.h"
26 #include "chrome/browser/ui/libgtk2ui/gtk2_event_loop.h"
27 #include "chrome/browser/ui/libgtk2ui/gtk2_key_bindings_handler.h"
28 #include "chrome/browser/ui/libgtk2ui/gtk2_signal_registrar.h"
29 #include "chrome/browser/ui/libgtk2ui/gtk2_status_icon.h"
30 #include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
31 #include "chrome/browser/ui/libgtk2ui/native_theme_gtk2.h"
32 #include "chrome/browser/ui/libgtk2ui/print_dialog_gtk2.h"
33 #include "chrome/browser/ui/libgtk2ui/printing_gtk2_util.h"
34 #include "chrome/browser/ui/libgtk2ui/select_file_dialog_impl.h"
35 #include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
36 #include "chrome/browser/ui/libgtk2ui/unity_service.h"
37 #include "chrome/browser/ui/libgtk2ui/x11_input_method_context_impl_gtk2.h"
38 #include "grit/components_scaled_resources.h"
39 #include "grit/theme_resources.h"
40 #include "printing/printing_context_linux.h"
41 #include "third_party/skia/include/core/SkBitmap.h"
42 #include "third_party/skia/include/core/SkCanvas.h"
43 #include "third_party/skia/include/core/SkColor.h"
44 #include "third_party/skia/include/core/SkShader.h"
45 #include "ui/base/resource/resource_bundle.h"
46 #include "ui/gfx/canvas.h"
47 #include "ui/gfx/display.h"
48 #include "ui/gfx/geometry/rect.h"
49 #include "ui/gfx/geometry/size.h"
50 #include "ui/gfx/image/image.h"
51 #include "ui/gfx/skbitmap_operations.h"
52 #include "ui/gfx/skia_util.h"
53 #include "ui/native_theme/native_theme.h"
54 #include "ui/resources/grit/ui_resources.h"
55 #include "ui/views/controls/button/label_button.h"
56 #include "ui/views/controls/button/label_button_border.h"
57 #include "ui/views/linux_ui/window_button_order_observer.h"
58 #include "ui/views/resources/grit/views_resources.h"
60 #if defined(USE_GCONF)
61 #include "chrome/browser/ui/libgtk2ui/gconf_listener.h"
62 #endif
64 // A minimized port of GtkThemeService into something that can provide colors
65 // and images for aura.
67 // TODO(erg): There's still a lot that needs ported or done for the first time:
69 // - Render and inject the omnibox background.
70 // - Make sure to test with a light on dark theme, too.
72 // Work around a header bug:
73 // linux/debian_wheezy_i386-sysroot/usr/include/linux/stddef.h redefines NULL
74 // to 0, which breaks -Wsentinel. Get back the normal definition of NULL.
75 // TODO(thakis): Remove this once we update sysroots.
76 #define __need_NULL
77 #include <stddef.h>
79 namespace libgtk2ui {
81 namespace {
83 struct GObjectDeleter {
84 void operator()(void* ptr) {
85 g_object_unref(ptr);
88 struct GtkIconInfoDeleter {
89 void operator()(GtkIconInfo* ptr) {
90 gtk_icon_info_free(ptr);
93 typedef scoped_ptr<GIcon, GObjectDeleter> ScopedGIcon;
94 typedef scoped_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo;
95 typedef scoped_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf;
97 // Prefix for app indicator ids
98 const char kAppIndicatorIdPrefix[] = "chrome_app_indicator_";
100 // Number of app indicators used (used as part of app-indicator id).
101 int indicators_count;
103 // The unknown content type.
104 const char* kUnknownContentType = "application/octet-stream";
106 // The size of the rendered toolbar image.
107 const int kToolbarImageWidth = 64;
108 const int kToolbarImageHeight = 128;
110 // How much to tint the GTK+ color lighter at the top of the window.
111 const color_utils::HSL kGtkFrameShift = { -1, -1, 0.58 };
113 // How much to tint the GTK+ color when an explicit frame color hasn't been
114 // specified.
115 const color_utils::HSL kDefaultFrameShift = { -1, -1, 0.4 };
117 // Values used as the new luminance and saturation values in the inactive tab
118 // text color.
119 const double kDarkInactiveLuminance = 0.85;
120 const double kLightInactiveLuminance = 0.15;
121 const double kHeavyInactiveSaturation = 0.7;
122 const double kLightInactiveSaturation = 0.3;
124 // Default color for links on the NTP when the GTK+ theme doesn't define a
125 // link color. Constant taken from gtklinkbutton.c.
126 const GdkColor kDefaultLinkColor = { 0, 0, 0, 0xeeee };
128 const int kSkiaToGDKMultiplier = 257;
130 // TODO(erg): ThemeService has a whole interface just for reading default
131 // constants. Figure out what to do with that more long term; for now, just
132 // copy the constants themselves here.
134 // Default tints.
135 const color_utils::HSL kDefaultTintButtons = { -1, -1, -1 };
136 const color_utils::HSL kDefaultTintFrame = { -1, -1, -1 };
137 const color_utils::HSL kDefaultTintFrameInactive = { -1, -1, 0.75f };
138 const color_utils::HSL kDefaultTintFrameIncognito = { -1, 0.2f, 0.35f };
139 const color_utils::HSL kDefaultTintFrameIncognitoInactive = { -1, 0.3f, 0.6f };
140 const color_utils::HSL kDefaultTintBackgroundTab = { -1, 0.5, 0.75 };
142 // A list of images that we provide while in gtk mode.
144 // TODO(erg): We list both the normal and *_DESKTOP versions of some of these
145 // images because in some contexts, we don't go through the
146 // chrome::MapThemeImage interface. That should be fixed, but tracking that
147 // down is Hard.
148 const int kThemeImages[] = {
149 IDR_THEME_TOOLBAR,
150 IDR_THEME_TAB_BACKGROUND,
151 IDR_THEME_TAB_BACKGROUND_DESKTOP,
152 IDR_THEME_TAB_BACKGROUND_INCOGNITO,
153 IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
154 IDR_FRAME,
155 IDR_FRAME_INACTIVE,
156 IDR_THEME_FRAME,
157 IDR_THEME_FRAME_INACTIVE,
158 IDR_THEME_FRAME_INCOGNITO,
159 IDR_THEME_FRAME_INCOGNITO_INACTIVE,
162 // A list of icons used in the autocomplete view that should be tinted to the
163 // current gtk theme selection color so they stand out against the GtkEntry's
164 // base color.
165 // TODO(erg): Decide what to do about other icons that appear in the omnibox,
166 // e.g. content settings icons.
167 const int kAutocompleteImages[] = {
168 IDR_OMNIBOX_CALCULATOR,
169 IDR_OMNIBOX_EXTENSION_APP,
170 IDR_OMNIBOX_HTTP,
171 IDR_OMNIBOX_HTTP_DARK,
172 IDR_OMNIBOX_SEARCH,
173 IDR_OMNIBOX_SEARCH_DARK,
174 IDR_OMNIBOX_STAR,
175 IDR_OMNIBOX_STAR_DARK,
176 IDR_OMNIBOX_TTS,
177 IDR_OMNIBOX_TTS_DARK,
180 // This table converts button ids into a pair of gtk-stock id and state.
181 struct IDRGtkMapping {
182 int idr;
183 const char* stock_id;
184 GtkStateType gtk_state;
185 } const kGtkIcons[] = {
186 { IDR_BACK, GTK_STOCK_GO_BACK, GTK_STATE_NORMAL },
187 { IDR_BACK_D, GTK_STOCK_GO_BACK, GTK_STATE_INSENSITIVE },
189 { IDR_FORWARD, GTK_STOCK_GO_FORWARD, GTK_STATE_NORMAL },
190 { IDR_FORWARD_D, GTK_STOCK_GO_FORWARD, GTK_STATE_INSENSITIVE },
192 { IDR_HOME, GTK_STOCK_HOME, GTK_STATE_NORMAL },
194 { IDR_RELOAD, GTK_STOCK_REFRESH, GTK_STATE_NORMAL },
195 { IDR_RELOAD_D, GTK_STOCK_REFRESH, GTK_STATE_INSENSITIVE },
197 { IDR_STOP, GTK_STOCK_STOP, GTK_STATE_NORMAL },
198 { IDR_STOP_D, GTK_STOCK_STOP, GTK_STATE_INSENSITIVE },
201 // The image resources that will be tinted by the 'button' tint value.
202 const int kOtherToolbarButtonIDs[] = {
203 IDR_TOOLBAR_BEZEL_HOVER,
204 IDR_TOOLBAR_BEZEL_PRESSED,
205 IDR_BROWSER_ACTIONS_OVERFLOW,
207 // TODO(erg): The dropdown arrow should be tinted because we're injecting
208 // various background GTK colors, but the code that accesses them needs to be
209 // modified so that they ask their ui::ThemeProvider instead of the
210 // ResourceBundle. (i.e. in a light on dark theme, the dropdown arrow will be
211 // dark on dark)
212 IDR_MENU_DROPARROW
215 bool IsOverridableImage(int id) {
216 CR_DEFINE_STATIC_LOCAL(std::set<int>, images, ());
217 if (images.empty()) {
218 images.insert(kThemeImages, kThemeImages + arraysize(kThemeImages));
219 images.insert(kAutocompleteImages,
220 kAutocompleteImages + arraysize(kAutocompleteImages));
222 for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i)
223 images.insert(kGtkIcons[i].idr);
225 images.insert(kOtherToolbarButtonIDs,
226 kOtherToolbarButtonIDs + arraysize(kOtherToolbarButtonIDs));
229 return images.count(id) > 0;
232 // Picks a button tint from a set of background colors. While
233 // |accent_gdk_color| will usually be the same color through a theme, this
234 // function will get called with the normal GtkLabel |text_color|/GtkWindow
235 // |background_color| pair and the GtkEntry |text_color|/|background_color|
236 // pair. While 3/4 of the time the resulting tint will be the same, themes that
237 // have a dark window background (with light text) and a light text entry (with
238 // dark text) will get better icons with this separated out.
239 void PickButtonTintFromColors(const GdkColor& accent_gdk_color,
240 const GdkColor& text_color,
241 const GdkColor& background_color,
242 color_utils::HSL* tint) {
243 SkColor accent_color = GdkColorToSkColor(accent_gdk_color);
244 color_utils::HSL accent_tint;
245 color_utils::SkColorToHSL(accent_color, &accent_tint);
247 color_utils::HSL text_tint;
248 color_utils::SkColorToHSL(GdkColorToSkColor(text_color),
249 &text_tint);
251 color_utils::HSL background_tint;
252 color_utils::SkColorToHSL(GdkColorToSkColor(background_color),
253 &background_tint);
255 // If the accent color is gray, then our normal HSL tomfoolery will bring out
256 // whatever color is oddly dominant (for example, in rgb space [125, 128,
257 // 125] will tint green instead of gray). Slight differences (+/-10 (4%) to
258 // all color components) should be interpreted as this color being gray and
259 // we should switch into a special grayscale mode.
260 int rb_diff = abs(static_cast<int>(SkColorGetR(accent_color)) -
261 static_cast<int>(SkColorGetB(accent_color)));
262 int rg_diff = abs(static_cast<int>(SkColorGetR(accent_color)) -
263 static_cast<int>(SkColorGetG(accent_color)));
264 int bg_diff = abs(static_cast<int>(SkColorGetB(accent_color)) -
265 static_cast<int>(SkColorGetG(accent_color)));
266 if (rb_diff < 10 && rg_diff < 10 && bg_diff < 10) {
267 // Our accent is white/gray/black. Only the luminance of the accent color
268 // matters.
269 tint->h = -1;
271 // Use the saturation of the text.
272 tint->s = text_tint.s;
274 // Use the luminance of the accent color UNLESS there isn't enough
275 // luminance contrast between the accent color and the base color.
276 if (fabs(accent_tint.l - background_tint.l) > 0.3)
277 tint->l = accent_tint.l;
278 else
279 tint->l = text_tint.l;
280 } else {
281 // Our accent is a color.
282 tint->h = accent_tint.h;
284 // Don't modify the saturation; the amount of color doesn't matter.
285 tint->s = -1;
287 // If the text wants us to darken the icon, don't change the luminance (the
288 // icons are already dark enough). Otherwise, lighten the icon by no more
289 // than 0.9 since we don't want a pure-white icon even if the text is pure
290 // white.
291 if (text_tint.l < 0.5)
292 tint->l = -1;
293 else if (text_tint.l <= 0.9)
294 tint->l = text_tint.l;
295 else
296 tint->l = 0.9;
300 // Applies an HSL shift to a GdkColor (instead of an SkColor)
301 void GdkColorHSLShift(const color_utils::HSL& shift, GdkColor* frame_color) {
302 SkColor shifted = color_utils::HSLShift(
303 GdkColorToSkColor(*frame_color), shift);
305 frame_color->pixel = 0;
306 frame_color->red = SkColorGetR(shifted) * kSkiaToGDKMultiplier;
307 frame_color->green = SkColorGetG(shifted) * kSkiaToGDKMultiplier;
308 frame_color->blue = SkColorGetB(shifted) * kSkiaToGDKMultiplier;
311 // Copied Default blah sections from ThemeService.
312 color_utils::HSL GetDefaultTint(int id) {
313 switch (id) {
314 case ThemeProperties::TINT_FRAME:
315 return kDefaultTintFrame;
316 case ThemeProperties::TINT_FRAME_INACTIVE:
317 return kDefaultTintFrameInactive;
318 case ThemeProperties::TINT_FRAME_INCOGNITO:
319 return kDefaultTintFrameIncognito;
320 case ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE:
321 return kDefaultTintFrameIncognitoInactive;
322 case ThemeProperties::TINT_BUTTONS:
323 return kDefaultTintButtons;
324 case ThemeProperties::TINT_BACKGROUND_TAB:
325 return kDefaultTintBackgroundTab;
326 default:
327 color_utils::HSL result = {-1, -1, -1};
328 return result;
332 // Returns a gfx::FontRenderParams corresponding to GTK's configuration.
333 gfx::FontRenderParams GetGtkFontRenderParams() {
334 GtkSettings* gtk_settings = gtk_settings_get_default();
335 CHECK(gtk_settings);
336 gint antialias = 0;
337 gint hinting = 0;
338 gchar* hint_style = NULL;
339 gchar* rgba = NULL;
340 g_object_get(gtk_settings,
341 "gtk-xft-antialias", &antialias,
342 "gtk-xft-hinting", &hinting,
343 "gtk-xft-hintstyle", &hint_style,
344 "gtk-xft-rgba", &rgba,
345 NULL);
347 gfx::FontRenderParams params;
348 params.antialiasing = antialias != 0;
350 if (hinting == 0 || !hint_style || strcmp(hint_style, "hintnone") == 0) {
351 params.hinting = gfx::FontRenderParams::HINTING_NONE;
352 } else if (strcmp(hint_style, "hintslight") == 0) {
353 params.hinting = gfx::FontRenderParams::HINTING_SLIGHT;
354 } else if (strcmp(hint_style, "hintmedium") == 0) {
355 params.hinting = gfx::FontRenderParams::HINTING_MEDIUM;
356 } else if (strcmp(hint_style, "hintfull") == 0) {
357 params.hinting = gfx::FontRenderParams::HINTING_FULL;
358 } else {
359 LOG(WARNING) << "Unexpected gtk-xft-hintstyle \"" << hint_style << "\"";
360 params.hinting = gfx::FontRenderParams::HINTING_NONE;
363 if (!rgba || strcmp(rgba, "none") == 0) {
364 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
365 } else if (strcmp(rgba, "rgb") == 0) {
366 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB;
367 } else if (strcmp(rgba, "bgr") == 0) {
368 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR;
369 } else if (strcmp(rgba, "vrgb") == 0) {
370 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB;
371 } else if (strcmp(rgba, "vbgr") == 0) {
372 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR;
373 } else {
374 LOG(WARNING) << "Unexpected gtk-xft-rgba \"" << rgba << "\"";
375 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
378 g_free(hint_style);
379 g_free(rgba);
381 return params;
384 double GetDPI() {
385 GtkSettings* gtk_settings = gtk_settings_get_default();
386 CHECK(gtk_settings);
387 gint gtk_dpi = -1;
388 g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, NULL);
390 // GTK multiplies the DPI by 1024 before storing it.
391 return (gtk_dpi > 0) ? gtk_dpi / 1024.0 : 96.0;
394 // Queries GTK for its font DPI setting and returns the number of pixels in a
395 // point.
396 double GetPixelsInPoint(float device_scale_factor) {
397 double dpi = GetDPI();
399 // Take device_scale_factor into account — if Chrome already scales the
400 // entire UI up by 2x, we should not also scale up.
401 dpi /= device_scale_factor;
403 // There are 72 points in an inch.
404 return dpi / 72.0;
407 views::LinuxUI::NonClientMiddleClickAction GetDefaultMiddleClickAction() {
408 scoped_ptr<base::Environment> env(base::Environment::Create());
409 switch (base::nix::GetDesktopEnvironment(env.get())) {
410 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
411 // Starting with KDE 4.4, windows' titlebars can be dragged with the
412 // middle mouse button to create tab groups. We don't support that in
413 // Chrome, but at least avoid lowering windows in response to middle
414 // clicks to avoid surprising users who expect the KDE behavior.
415 return views::LinuxUI::MIDDLE_CLICK_ACTION_NONE;
416 default:
417 return views::LinuxUI::MIDDLE_CLICK_ACTION_LOWER;
421 } // namespace
423 Gtk2UI::Gtk2UI()
424 : default_font_size_pixels_(0),
425 default_font_style_(gfx::Font::NORMAL),
426 middle_click_action_(GetDefaultMiddleClickAction()),
427 device_scale_factor_(1.0) {
428 GtkInitFromCommandLine(*base::CommandLine::ForCurrentProcess());
431 void Gtk2UI::Initialize() {
432 signals_.reset(new Gtk2SignalRegistrar);
434 // Create our fake widgets.
435 fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
436 fake_frame_ = chrome_gtk_frame_new();
437 fake_label_.Own(gtk_label_new(""));
438 fake_entry_.Own(gtk_entry_new());
440 // Only realized widgets receive style-set notifications, which we need to
441 // broadcast new theme images and colors. Only realized widgets have style
442 // properties, too, which we query for some colors.
443 gtk_widget_realize(fake_frame_);
444 gtk_widget_realize(fake_window_);
446 signals_->Connect(fake_frame_, "style-set",
447 G_CALLBACK(&OnStyleSetThunk), this);
449 LoadGtkValues();
451 printing::PrintingContextLinux::SetCreatePrintDialogFunction(
452 &PrintDialogGtk2::CreatePrintDialog);
453 printing::PrintingContextLinux::SetPdfPaperSizeFunction(
454 &GetPdfPaperSizeDeviceUnitsGtk);
456 #if defined(USE_GCONF)
457 // We must build this after GTK gets initialized.
458 gconf_listener_.reset(new GConfListener(this));
459 #endif // defined(USE_GCONF)
461 indicators_count = 0;
463 // Instantiate the singleton instance of Gtk2EventLoop.
464 Gtk2EventLoop::GetInstance();
467 Gtk2UI::~Gtk2UI() {
468 gtk_widget_destroy(fake_window_);
469 gtk_widget_destroy(fake_frame_);
470 fake_label_.Destroy();
471 fake_entry_.Destroy();
473 ClearAllThemeData();
476 gfx::Image Gtk2UI::GetThemeImageNamed(int id) const {
477 // Try to get our cached version:
478 ImageCache::const_iterator it = gtk_images_.find(id);
479 if (it != gtk_images_.end())
480 return it->second;
482 if (IsOverridableImage(id)) {
483 gfx::Image image = gfx::Image(
484 gfx::ImageSkia::CreateFrom1xBitmap(GenerateGtkThemeBitmap(id)));
485 gtk_images_[id] = image;
486 return image;
489 return gfx::Image();
492 bool Gtk2UI::GetColor(int id, SkColor* color) const {
493 ColorMap::const_iterator it = colors_.find(id);
494 if (it != colors_.end()) {
495 *color = it->second;
496 return true;
499 return false;
502 bool Gtk2UI::HasCustomImage(int id) const {
503 return IsOverridableImage(id);
506 SkColor Gtk2UI::GetFocusRingColor() const {
507 return focus_ring_color_;
510 SkColor Gtk2UI::GetThumbActiveColor() const {
511 return thumb_active_color_;
514 SkColor Gtk2UI::GetThumbInactiveColor() const {
515 return thumb_inactive_color_;
518 SkColor Gtk2UI::GetTrackColor() const {
519 return track_color_;
522 SkColor Gtk2UI::GetActiveSelectionBgColor() const {
523 return active_selection_bg_color_;
526 SkColor Gtk2UI::GetActiveSelectionFgColor() const {
527 return active_selection_fg_color_;
530 SkColor Gtk2UI::GetInactiveSelectionBgColor() const {
531 return inactive_selection_bg_color_;
534 SkColor Gtk2UI::GetInactiveSelectionFgColor() const {
535 return inactive_selection_fg_color_;
538 double Gtk2UI::GetCursorBlinkInterval() const {
539 // From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is
540 // the default value for gtk-cursor-blink-time.
541 static const gint kGtkDefaultCursorBlinkTime = 1200;
543 // Dividing GTK's cursor blink cycle time (in milliseconds) by this value
544 // yields an appropriate value for
545 // content::RendererPreferences::caret_blink_interval. This matches the
546 // logic in the WebKit GTK port.
547 static const double kGtkCursorBlinkCycleFactor = 2000.0;
549 gint cursor_blink_time = kGtkDefaultCursorBlinkTime;
550 gboolean cursor_blink = TRUE;
551 g_object_get(gtk_settings_get_default(),
552 "gtk-cursor-blink-time", &cursor_blink_time,
553 "gtk-cursor-blink", &cursor_blink,
554 NULL);
555 return cursor_blink ? (cursor_blink_time / kGtkCursorBlinkCycleFactor) : 0.0;
558 ui::NativeTheme* Gtk2UI::GetNativeTheme(aura::Window* window) const {
559 ui::NativeTheme* native_theme_override = NULL;
560 if (!native_theme_overrider_.is_null())
561 native_theme_override = native_theme_overrider_.Run(window);
563 if (native_theme_override)
564 return native_theme_override;
566 return NativeThemeGtk2::instance();
569 void Gtk2UI::SetNativeThemeOverride(const NativeThemeGetter& callback) {
570 native_theme_overrider_ = callback;
573 bool Gtk2UI::GetDefaultUsesSystemTheme() const {
574 scoped_ptr<base::Environment> env(base::Environment::Create());
576 switch (base::nix::GetDesktopEnvironment(env.get())) {
577 case base::nix::DESKTOP_ENVIRONMENT_GNOME:
578 case base::nix::DESKTOP_ENVIRONMENT_UNITY:
579 case base::nix::DESKTOP_ENVIRONMENT_XFCE:
580 return true;
581 case base::nix::DESKTOP_ENVIRONMENT_KDE3:
582 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
583 case base::nix::DESKTOP_ENVIRONMENT_OTHER:
584 return false;
586 // Unless GetDesktopEnvironment() badly misbehaves, this should never happen.
587 NOTREACHED();
588 return false;
591 void Gtk2UI::SetDownloadCount(int count) const {
592 if (unity::IsRunning())
593 unity::SetDownloadCount(count);
596 void Gtk2UI::SetProgressFraction(float percentage) const {
597 if (unity::IsRunning())
598 unity::SetProgressFraction(percentage);
601 bool Gtk2UI::IsStatusIconSupported() const {
602 return true;
605 scoped_ptr<views::StatusIconLinux> Gtk2UI::CreateLinuxStatusIcon(
606 const gfx::ImageSkia& image,
607 const base::string16& tool_tip) const {
608 if (AppIndicatorIcon::CouldOpen()) {
609 ++indicators_count;
610 return scoped_ptr<views::StatusIconLinux>(new AppIndicatorIcon(
611 base::StringPrintf("%s%d", kAppIndicatorIdPrefix, indicators_count),
612 image,
613 tool_tip));
614 } else {
615 return scoped_ptr<views::StatusIconLinux>(new Gtk2StatusIcon(
616 image, tool_tip));
620 gfx::Image Gtk2UI::GetIconForContentType(
621 const std::string& content_type,
622 int size) const {
623 // This call doesn't take a reference.
624 GtkIconTheme* theme = gtk_icon_theme_get_default();
626 std::string content_types[] = {
627 content_type, kUnknownContentType
630 for (size_t i = 0; i < arraysize(content_types); ++i) {
631 ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str()));
632 ScopedGtkIconInfo icon_info(
633 gtk_icon_theme_lookup_by_gicon(
634 theme, icon.get(), size,
635 static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE)));
636 if (!icon_info)
637 continue;
638 ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), NULL));
639 if (!pixbuf)
640 continue;
642 SkBitmap bitmap = GdkPixbufToImageSkia(pixbuf.get());
643 DCHECK_EQ(size, bitmap.width());
644 DCHECK_EQ(size, bitmap.height());
645 gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
646 image_skia.MakeThreadSafe();
647 return gfx::Image(image_skia);
649 return gfx::Image();
652 scoped_ptr<views::Border> Gtk2UI::CreateNativeBorder(
653 views::LabelButton* owning_button,
654 scoped_ptr<views::LabelButtonBorder> border) {
655 if (owning_button->GetNativeTheme() != NativeThemeGtk2::instance())
656 return border.Pass();
658 return make_scoped_ptr(new Gtk2Border(this, owning_button, border.Pass()));
661 void Gtk2UI::AddWindowButtonOrderObserver(
662 views::WindowButtonOrderObserver* observer) {
663 if (!leading_buttons_.empty() || !trailing_buttons_.empty()) {
664 observer->OnWindowButtonOrderingChange(leading_buttons_,
665 trailing_buttons_);
668 observer_list_.AddObserver(observer);
671 void Gtk2UI::RemoveWindowButtonOrderObserver(
672 views::WindowButtonOrderObserver* observer) {
673 observer_list_.RemoveObserver(observer);
676 void Gtk2UI::SetWindowButtonOrdering(
677 const std::vector<views::FrameButton>& leading_buttons,
678 const std::vector<views::FrameButton>& trailing_buttons) {
679 leading_buttons_ = leading_buttons;
680 trailing_buttons_ = trailing_buttons;
682 FOR_EACH_OBSERVER(views::WindowButtonOrderObserver, observer_list_,
683 OnWindowButtonOrderingChange(leading_buttons_,
684 trailing_buttons_));
687 void Gtk2UI::SetNonClientMiddleClickAction(NonClientMiddleClickAction action) {
688 middle_click_action_ = action;
691 scoped_ptr<ui::LinuxInputMethodContext> Gtk2UI::CreateInputMethodContext(
692 ui::LinuxInputMethodContextDelegate* delegate,
693 bool is_simple) const {
694 return scoped_ptr<ui::LinuxInputMethodContext>(
695 new X11InputMethodContextImplGtk2(delegate, is_simple));
698 gfx::FontRenderParams Gtk2UI::GetDefaultFontRenderParams() const {
699 static gfx::FontRenderParams params = GetGtkFontRenderParams();
700 return params;
703 void Gtk2UI::GetDefaultFontDescription(
704 std::string* family_out,
705 int* size_pixels_out,
706 int* style_out,
707 gfx::FontRenderParams* params_out) const {
708 *family_out = default_font_family_;
709 *size_pixels_out = default_font_size_pixels_;
710 *style_out = default_font_style_;
711 *params_out = default_font_render_params_;
714 ui::SelectFileDialog* Gtk2UI::CreateSelectFileDialog(
715 ui::SelectFileDialog::Listener* listener,
716 ui::SelectFilePolicy* policy) const {
717 return SelectFileDialogImpl::Create(listener, policy);
720 bool Gtk2UI::UnityIsRunning() {
721 return unity::IsRunning();
724 views::LinuxUI::NonClientMiddleClickAction
725 Gtk2UI::GetNonClientMiddleClickAction() {
726 return middle_click_action_;
729 void Gtk2UI::NotifyWindowManagerStartupComplete() {
730 // TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO
731 // from http://standards.freedesktop.org/startup-notification-spec/ instead.
732 gdk_notify_startup_complete();
735 bool Gtk2UI::MatchEvent(const ui::Event& event,
736 std::vector<ui::TextEditCommandAuraLinux>* commands) {
737 // Ensure that we have a keyboard handler.
738 if (!key_bindings_handler_)
739 key_bindings_handler_.reset(new Gtk2KeyBindingsHandler);
741 return key_bindings_handler_->MatchEvent(event, commands);
744 void Gtk2UI::GetScrollbarColors(GdkColor* thumb_active_color,
745 GdkColor* thumb_inactive_color,
746 GdkColor* track_color) {
747 GdkColor* theme_thumb_active = NULL;
748 GdkColor* theme_thumb_inactive = NULL;
749 GdkColor* theme_trough_color = NULL;
750 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
751 "scrollbar-slider-prelight-color", &theme_thumb_active,
752 "scrollbar-slider-normal-color", &theme_thumb_inactive,
753 "scrollbar-trough-color", &theme_trough_color,
754 NULL);
756 // Ask the theme if the theme specifies all the scrollbar colors and short
757 // circuit the expensive painting/compositing if we have all of them.
758 if (theme_thumb_active && theme_thumb_inactive && theme_trough_color) {
759 *thumb_active_color = *theme_thumb_active;
760 *thumb_inactive_color = *theme_thumb_inactive;
761 *track_color = *theme_trough_color;
763 gdk_color_free(theme_thumb_active);
764 gdk_color_free(theme_thumb_inactive);
765 gdk_color_free(theme_trough_color);
766 return;
769 // Create window containing scrollbar elements
770 GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);
771 GtkWidget* fixed = gtk_fixed_new();
772 GtkWidget* scrollbar = gtk_hscrollbar_new(NULL);
773 gtk_container_add(GTK_CONTAINER(window), fixed);
774 gtk_container_add(GTK_CONTAINER(fixed), scrollbar);
775 gtk_widget_realize(window);
776 gtk_widget_realize(scrollbar);
778 // Draw scrollbar thumb part and track into offscreen image
779 const int kWidth = 100;
780 const int kHeight = 20;
781 GtkStyle* style = gtk_rc_get_style(scrollbar);
782 GdkWindow* gdk_window = gtk_widget_get_window(window);
783 GdkPixmap* pm = gdk_pixmap_new(gdk_window, kWidth, kHeight, -1);
784 GdkRectangle rect = { 0, 0, kWidth, kHeight };
785 unsigned char data[3 * kWidth * kHeight];
786 for (int i = 0; i < 3; ++i) {
787 if (i < 2) {
788 // Thumb part
789 gtk_paint_slider(style, pm,
790 i == 0 ? GTK_STATE_PRELIGHT : GTK_STATE_NORMAL,
791 GTK_SHADOW_OUT, &rect, scrollbar, "slider", 0, 0,
792 kWidth, kHeight, GTK_ORIENTATION_HORIZONTAL);
793 } else {
794 // Track
795 gtk_paint_box(style, pm, GTK_STATE_ACTIVE, GTK_SHADOW_IN, &rect,
796 scrollbar, "trough-upper", 0, 0, kWidth, kHeight);
798 GdkPixbuf* pb = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB,
799 FALSE, 8, kWidth, kHeight,
800 3 * kWidth, 0, 0);
801 gdk_pixbuf_get_from_drawable(pb, pm, NULL, 0, 0, 0, 0, kWidth, kHeight);
803 // Sample pixels
804 int components[3] = { 0 };
805 for (int y = 2; y < kHeight - 2; ++y) {
806 for (int c = 0; c < 3; ++c) {
807 // Sample a vertical slice of pixels at about one-thirds from the
808 // left edge. This allows us to avoid any fixed graphics that might be
809 // located at the edges or in the center of the scrollbar.
810 // Each pixel is made up of a red, green, and blue component; taking up
811 // a total of three bytes.
812 components[c] += data[3 * (kWidth / 3 + y * kWidth) + c];
815 GdkColor* color = i == 0 ? thumb_active_color :
816 i == 1 ? thumb_inactive_color :
817 track_color;
818 color->pixel = 0;
819 // We sampled pixels across the full height of the image, ignoring a two
820 // pixel border. In some themes, the border has a completely different
821 // color which we do not want to factor into our average color computation.
823 // We now need to scale the colors from the 0..255 range, to the wider
824 // 0..65535 range, and we need to actually compute the average color; so,
825 // we divide by the total number of pixels in the sample.
826 color->red = components[0] * 65535 / (255 * (kHeight - 4));
827 color->green = components[1] * 65535 / (255 * (kHeight - 4));
828 color->blue = components[2] * 65535 / (255 * (kHeight - 4));
830 g_object_unref(pb);
832 g_object_unref(pm);
834 gtk_widget_destroy(window);
836 // Override any of the default colors with ones that were specified by the
837 // theme.
838 if (theme_thumb_active) {
839 *thumb_active_color = *theme_thumb_active;
840 gdk_color_free(theme_thumb_active);
843 if (theme_thumb_inactive) {
844 *thumb_inactive_color = *theme_thumb_inactive;
845 gdk_color_free(theme_thumb_inactive);
848 if (theme_trough_color) {
849 *track_color = *theme_trough_color;
850 gdk_color_free(theme_trough_color);
854 void Gtk2UI::LoadGtkValues() {
855 // TODO(erg): GtkThemeService had a comment here about having to muck with
856 // the raw Prefs object to remove prefs::kCurrentThemeImages or else we'd
857 // regress startup time. Figure out how to do that when we can't access the
858 // prefs system from here.
860 GtkStyle* frame_style = gtk_rc_get_style(fake_frame_);
862 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
863 SetThemeColorFromGtk(ThemeProperties::COLOR_CONTROL_BACKGROUND,
864 &window_style->bg[GTK_STATE_NORMAL]);
866 GdkColor toolbar_color = window_style->bg[GTK_STATE_NORMAL];
867 SetThemeColorFromGtk(ThemeProperties::COLOR_TOOLBAR, &toolbar_color);
869 GdkColor button_color = window_style->bg[GTK_STATE_SELECTED];
870 SetThemeTintFromGtk(ThemeProperties::TINT_BUTTONS, &button_color);
872 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
873 GdkColor label_color = label_style->fg[GTK_STATE_NORMAL];
874 SetThemeColorFromGtk(ThemeProperties::COLOR_TAB_TEXT, &label_color);
875 SetThemeColorFromGtk(ThemeProperties::COLOR_BOOKMARK_TEXT, &label_color);
876 SetThemeColorFromGtk(ThemeProperties::COLOR_STATUS_BAR_TEXT, &label_color);
878 UpdateDefaultFont(label_style->font_desc);
880 // Build the various icon tints.
881 GetNormalButtonTintHSL(&button_tint_);
882 GetNormalEntryForegroundHSL(&entry_tint_);
883 GetSelectedEntryForegroundHSL(&selected_entry_tint_);
884 GdkColor frame_color = BuildFrameColors(frame_style);
886 // The inactive frame color never occurs naturally in the theme, as it is a
887 // tinted version of |frame_color|. We generate another color based on the
888 // background tab color, with the lightness and saturation moved in the
889 // opposite direction. (We don't touch the hue, since there should be subtle
890 // hints of the color in the text.)
891 color_utils::HSL inactive_tab_text_hsl =
892 tints_[ThemeProperties::TINT_BACKGROUND_TAB];
893 if (inactive_tab_text_hsl.l < 0.5)
894 inactive_tab_text_hsl.l = kDarkInactiveLuminance;
895 else
896 inactive_tab_text_hsl.l = kLightInactiveLuminance;
898 if (inactive_tab_text_hsl.s < 0.5)
899 inactive_tab_text_hsl.s = kHeavyInactiveSaturation;
900 else
901 inactive_tab_text_hsl.s = kLightInactiveSaturation;
903 colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
904 color_utils::HSLToSkColor(inactive_tab_text_hsl, 255);
906 // We pick the text and background colors for the NTP out of the colors for a
907 // GtkEntry. We do this because GtkEntries background color is never the same
908 // as |toolbar_color|, is usually a white, and when it isn't a white,
909 // provides sufficient contrast to |toolbar_color|. Try this out with
910 // Darklooks, HighContrastInverse or ThinIce.
911 GtkStyle* entry_style = gtk_rc_get_style(fake_entry_.get());
912 GdkColor ntp_background = entry_style->base[GTK_STATE_NORMAL];
913 GdkColor ntp_foreground = entry_style->text[GTK_STATE_NORMAL];
914 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_BACKGROUND,
915 &ntp_background);
916 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_TEXT,
917 &ntp_foreground);
919 // The NTP header is the color that surrounds the current active thumbnail on
920 // the NTP, and acts as the border of the "Recent Links" box. It would be
921 // awesome if they were separated so we could use GetBorderColor() for the
922 // border around the "Recent Links" section, but matching the frame color is
923 // more important.
924 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_HEADER,
925 &frame_color);
926 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION,
927 &toolbar_color);
928 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_TEXT,
929 &label_color);
931 // Override the link color if the theme provides it.
932 const GdkColor* link_color = NULL;
933 gtk_widget_style_get(GTK_WIDGET(fake_window_),
934 "link-color", &link_color, NULL);
936 bool is_default_link_color = false;
937 if (!link_color) {
938 link_color = &kDefaultLinkColor;
939 is_default_link_color = true;
942 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK,
943 link_color);
944 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK_UNDERLINE,
945 link_color);
946 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK,
947 link_color);
948 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE,
949 link_color);
951 if (!is_default_link_color)
952 gdk_color_free(const_cast<GdkColor*>(link_color));
954 // Generate the colors that we pass to WebKit.
955 focus_ring_color_ = GdkColorToSkColor(frame_color);
957 GdkColor thumb_active_color, thumb_inactive_color, track_color;
958 Gtk2UI::GetScrollbarColors(&thumb_active_color,
959 &thumb_inactive_color,
960 &track_color);
961 thumb_active_color_ = GdkColorToSkColor(thumb_active_color);
962 thumb_inactive_color_ = GdkColorToSkColor(thumb_inactive_color);
963 track_color_ = GdkColorToSkColor(track_color);
965 // Some GTK themes only define the text selection colors on the GtkEntry
966 // class, so we need to use that for getting selection colors.
967 active_selection_bg_color_ =
968 GdkColorToSkColor(entry_style->base[GTK_STATE_SELECTED]);
969 active_selection_fg_color_ =
970 GdkColorToSkColor(entry_style->text[GTK_STATE_SELECTED]);
971 inactive_selection_bg_color_ =
972 GdkColorToSkColor(entry_style->base[GTK_STATE_ACTIVE]);
973 inactive_selection_fg_color_ =
974 GdkColorToSkColor(entry_style->text[GTK_STATE_ACTIVE]);
976 colors_[ThemeProperties::COLOR_THROBBER_SPINNING] =
977 NativeThemeGtk2::instance()->GetSystemColor(
978 ui::NativeTheme::kColorId_ThrobberSpinningColor);
979 colors_[ThemeProperties::COLOR_THROBBER_WAITING] =
980 NativeThemeGtk2::instance()->GetSystemColor(
981 ui::NativeTheme::kColorId_ThrobberWaitingColor);
984 GdkColor Gtk2UI::BuildFrameColors(GtkStyle* frame_style) {
985 GdkColor* theme_frame = NULL;
986 GdkColor* theme_inactive_frame = NULL;
987 GdkColor* theme_incognito_frame = NULL;
988 GdkColor* theme_incognito_inactive_frame = NULL;
989 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
990 "frame-color", &theme_frame,
991 "inactive-frame-color", &theme_inactive_frame,
992 "incognito-frame-color", &theme_incognito_frame,
993 "incognito-inactive-frame-color",
994 &theme_incognito_inactive_frame,
995 NULL);
997 GdkColor frame_color = BuildAndSetFrameColor(
998 &frame_style->bg[GTK_STATE_SELECTED],
999 theme_frame,
1000 kDefaultFrameShift,
1001 ThemeProperties::COLOR_FRAME,
1002 ThemeProperties::TINT_FRAME);
1003 if (theme_frame)
1004 gdk_color_free(theme_frame);
1005 SetThemeTintFromGtk(ThemeProperties::TINT_BACKGROUND_TAB, &frame_color);
1007 BuildAndSetFrameColor(
1008 &frame_style->bg[GTK_STATE_INSENSITIVE],
1009 theme_inactive_frame,
1010 kDefaultFrameShift,
1011 ThemeProperties::COLOR_FRAME_INACTIVE,
1012 ThemeProperties::TINT_FRAME_INACTIVE);
1013 if (theme_inactive_frame)
1014 gdk_color_free(theme_inactive_frame);
1016 BuildAndSetFrameColor(
1017 &frame_color,
1018 theme_incognito_frame,
1019 GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO),
1020 ThemeProperties::COLOR_FRAME_INCOGNITO,
1021 ThemeProperties::TINT_FRAME_INCOGNITO);
1022 if (theme_incognito_frame)
1023 gdk_color_free(theme_incognito_frame);
1025 BuildAndSetFrameColor(
1026 &frame_color,
1027 theme_incognito_inactive_frame,
1028 GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE),
1029 ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1030 ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE);
1031 if (theme_incognito_inactive_frame)
1032 gdk_color_free(theme_incognito_inactive_frame);
1034 return frame_color;
1037 void Gtk2UI::SetThemeColorFromGtk(int id, const GdkColor* color) {
1038 colors_[id] = GdkColorToSkColor(*color);
1041 void Gtk2UI::SetThemeTintFromGtk(int id, const GdkColor* color) {
1042 color_utils::HSL default_tint = GetDefaultTint(id);
1043 color_utils::HSL hsl;
1044 color_utils::SkColorToHSL(GdkColorToSkColor(*color), &hsl);
1046 if (default_tint.s != -1)
1047 hsl.s = default_tint.s;
1049 if (default_tint.l != -1)
1050 hsl.l = default_tint.l;
1052 tints_[id] = hsl;
1055 GdkColor Gtk2UI::BuildAndSetFrameColor(const GdkColor* base,
1056 const GdkColor* gtk_base,
1057 const color_utils::HSL& tint,
1058 int color_id,
1059 int tint_id) {
1060 GdkColor out_color = *base;
1061 if (gtk_base) {
1062 // The theme author specified a color to use, use it without modification.
1063 out_color = *gtk_base;
1064 } else {
1065 // Tint the basic color since this is a heuristic color instead of one
1066 // specified by the theme author.
1067 GdkColorHSLShift(tint, &out_color);
1069 SetThemeColorFromGtk(color_id, &out_color);
1070 SetThemeTintFromGtk(tint_id, &out_color);
1072 return out_color;
1075 SkBitmap Gtk2UI::GenerateGtkThemeBitmap(int id) const {
1076 switch (id) {
1077 case IDR_THEME_TOOLBAR: {
1078 GtkStyle* style = gtk_rc_get_style(fake_window_);
1079 GdkColor* color = &style->bg[GTK_STATE_NORMAL];
1080 SkBitmap bitmap;
1081 bitmap.allocN32Pixels(kToolbarImageWidth, kToolbarImageHeight);
1082 bitmap.eraseARGB(0xff, color->red >> 8, color->green >> 8,
1083 color->blue >> 8);
1084 return bitmap;
1086 case IDR_THEME_TAB_BACKGROUND:
1087 case IDR_THEME_TAB_BACKGROUND_DESKTOP:
1088 return GenerateTabImage(IDR_THEME_FRAME);
1089 case IDR_THEME_TAB_BACKGROUND_INCOGNITO:
1090 case IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP:
1091 return GenerateTabImage(IDR_THEME_FRAME_INCOGNITO);
1092 case IDR_FRAME:
1093 case IDR_THEME_FRAME:
1094 return GenerateFrameImage(ThemeProperties::COLOR_FRAME,
1095 "frame-gradient-color");
1096 case IDR_FRAME_INACTIVE:
1097 case IDR_THEME_FRAME_INACTIVE:
1098 return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INACTIVE,
1099 "inactive-frame-gradient-color");
1100 case IDR_THEME_FRAME_INCOGNITO:
1101 return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INCOGNITO,
1102 "incognito-frame-gradient-color");
1103 case IDR_THEME_FRAME_INCOGNITO_INACTIVE: {
1104 return GenerateFrameImage(
1105 ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1106 "incognito-inactive-frame-gradient-color");
1108 // Icons that sit inside the omnibox shouldn't receive TINT_BUTTONS and
1109 // instead should tint based on the foreground text entry color in GTK+
1110 // mode because some themes that try to be dark *and* light have very
1111 // different colors between the omnibox and the normal background area.
1112 // TODO(erg): Decide what to do about other icons that appear in the
1113 // omnibox, e.g. content settings icons.
1114 case IDR_OMNIBOX_CALCULATOR:
1115 case IDR_OMNIBOX_EXTENSION_APP:
1116 case IDR_OMNIBOX_HTTP:
1117 case IDR_OMNIBOX_SEARCH:
1118 case IDR_OMNIBOX_STAR:
1119 case IDR_OMNIBOX_TTS: {
1120 return GenerateTintedIcon(id, entry_tint_);
1122 // In GTK mode, the dark versions of the omnibox icons only ever appear in
1123 // the autocomplete popup and only against the current theme's GtkEntry
1124 // base[GTK_STATE_SELECTED] color, so tint the icons so they won't collide
1125 // with the selected color.
1126 case IDR_OMNIBOX_EXTENSION_APP_DARK:
1127 case IDR_OMNIBOX_HTTP_DARK:
1128 case IDR_OMNIBOX_SEARCH_DARK:
1129 case IDR_OMNIBOX_STAR_DARK:
1130 case IDR_OMNIBOX_TTS_DARK: {
1131 return GenerateTintedIcon(id, selected_entry_tint_);
1133 // In GTK mode, we need to manually render several icons.
1134 case IDR_BACK:
1135 case IDR_BACK_D:
1136 case IDR_FORWARD:
1137 case IDR_FORWARD_D:
1138 case IDR_HOME:
1139 case IDR_RELOAD:
1140 case IDR_RELOAD_D:
1141 case IDR_STOP:
1142 case IDR_STOP_D: {
1143 return GenerateGTKIcon(id);
1145 case IDR_TOOLBAR_BEZEL_HOVER:
1146 return GenerateToolbarBezel(GTK_STATE_PRELIGHT, IDR_TOOLBAR_BEZEL_HOVER);
1147 case IDR_TOOLBAR_BEZEL_PRESSED:
1148 return GenerateToolbarBezel(GTK_STATE_ACTIVE, IDR_TOOLBAR_BEZEL_PRESSED);
1149 default: {
1150 return GenerateTintedIcon(id, button_tint_);
1154 return SkBitmap();
1157 SkBitmap Gtk2UI::GenerateFrameImage(
1158 int color_id,
1159 const char* gradient_name) const {
1160 // We use two colors: the main color (passed in) and a lightened version of
1161 // that color (which is supposed to match the light gradient at the top of
1162 // several GTK+ themes, such as Ambiance, Clearlooks or Bluebird).
1163 ColorMap::const_iterator it = colors_.find(color_id);
1164 DCHECK(it != colors_.end());
1165 SkColor base = it->second;
1167 gfx::Canvas canvas(gfx::Size(kToolbarImageWidth, kToolbarImageHeight),
1168 1.0f, true);
1170 int gradient_size;
1171 GdkColor* gradient_top_color = NULL;
1172 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
1173 "frame-gradient-size", &gradient_size,
1174 gradient_name, &gradient_top_color,
1175 NULL);
1176 if (gradient_size) {
1177 SkColor lighter = gradient_top_color ?
1178 GdkColorToSkColor(*gradient_top_color) :
1179 color_utils::HSLShift(base, kGtkFrameShift);
1180 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1181 0, gradient_size, lighter, base);
1182 SkPaint paint;
1183 paint.setStyle(SkPaint::kFill_Style);
1184 paint.setAntiAlias(true);
1185 paint.setShader(shader.get());
1187 canvas.DrawRect(gfx::Rect(0, 0, kToolbarImageWidth, gradient_size), paint);
1190 if (gradient_top_color)
1191 gdk_color_free(gradient_top_color);
1193 canvas.FillRect(gfx::Rect(0, gradient_size, kToolbarImageWidth,
1194 kToolbarImageHeight - gradient_size), base);
1195 return canvas.ExtractImageRep().sk_bitmap();
1198 SkBitmap Gtk2UI::GenerateTabImage(int base_id) const {
1199 const SkBitmap* base_image = GetThemeImageNamed(base_id).ToSkBitmap();
1200 SkBitmap bg_tint = SkBitmapOperations::CreateHSLShiftedBitmap(
1201 *base_image, GetDefaultTint(ThemeProperties::TINT_BACKGROUND_TAB));
1202 return SkBitmapOperations::CreateTiledBitmap(
1203 bg_tint, 0, 0, bg_tint.width(), bg_tint.height());
1206 SkBitmap Gtk2UI::GenerateTintedIcon(
1207 int base_id,
1208 const color_utils::HSL& tint) const {
1209 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1210 return SkBitmapOperations::CreateHSLShiftedBitmap(
1211 rb.GetImageNamed(base_id).AsBitmap(), tint);
1214 SkBitmap Gtk2UI::GenerateGTKIcon(int base_id) const {
1215 const char* stock_id = NULL;
1216 GtkStateType gtk_state = GTK_STATE_NORMAL;
1217 for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i) {
1218 if (kGtkIcons[i].idr == base_id) {
1219 stock_id = kGtkIcons[i].stock_id;
1220 gtk_state = kGtkIcons[i].gtk_state;
1221 break;
1224 DCHECK(stock_id);
1226 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1227 SkBitmap default_bitmap = rb.GetImageNamed(base_id).AsBitmap();
1229 gtk_widget_ensure_style(fake_frame_);
1230 GtkStyle* style = gtk_widget_get_style(fake_frame_);
1231 GtkIconSet* icon_set = gtk_style_lookup_icon_set(style, stock_id);
1232 if (!icon_set)
1233 return default_bitmap;
1235 // Ask GTK to render the icon to a buffer, which we will steal from.
1236 GdkPixbuf* gdk_icon = gtk_icon_set_render_icon(
1237 icon_set,
1238 style,
1239 base::i18n::IsRTL() ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR,
1240 gtk_state,
1241 GTK_ICON_SIZE_SMALL_TOOLBAR,
1242 fake_frame_,
1243 NULL);
1245 if (!gdk_icon) {
1246 // This can theoretically happen if an icon theme doesn't provide a
1247 // specific image. This should realistically never happen, but I bet there
1248 // are some theme authors who don't reliably provide all icons.
1249 return default_bitmap;
1252 SkBitmap retval;
1253 retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1254 retval.eraseColor(0);
1256 const SkBitmap icon = GdkPixbufToImageSkia(gdk_icon);
1257 g_object_unref(gdk_icon);
1259 SkCanvas canvas(retval);
1261 if (gtk_state == GTK_STATE_ACTIVE || gtk_state == GTK_STATE_PRELIGHT) {
1262 SkBitmap border = DrawGtkButtonBorder(gtk_state,
1263 false,
1264 false,
1265 default_bitmap.width(),
1266 default_bitmap.height());
1267 canvas.drawBitmap(border, 0, 0);
1270 canvas.drawBitmap(icon,
1271 (default_bitmap.width() / 2) - (icon.width() / 2),
1272 (default_bitmap.height() / 2) - (icon.height() / 2));
1274 return retval;
1277 SkBitmap Gtk2UI::GenerateToolbarBezel(int gtk_state, int sizing_idr) const {
1278 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1279 SkBitmap default_bitmap =
1280 rb.GetImageNamed(sizing_idr).AsBitmap();
1282 SkBitmap retval;
1283 retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1284 retval.eraseColor(0);
1286 SkCanvas canvas(retval);
1287 SkBitmap border = DrawGtkButtonBorder(
1288 gtk_state,
1289 false,
1290 false,
1291 default_bitmap.width(),
1292 default_bitmap.height());
1293 canvas.drawBitmap(border, 0, 0);
1295 return retval;
1298 void Gtk2UI::GetNormalButtonTintHSL(color_utils::HSL* tint) const {
1299 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
1300 const GdkColor accent_gdk_color = window_style->bg[GTK_STATE_SELECTED];
1301 const GdkColor base_color = window_style->base[GTK_STATE_NORMAL];
1303 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
1304 const GdkColor text_color = label_style->fg[GTK_STATE_NORMAL];
1306 PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1309 void Gtk2UI::GetNormalEntryForegroundHSL(color_utils::HSL* tint) const {
1310 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
1311 const GdkColor accent_gdk_color = window_style->bg[GTK_STATE_SELECTED];
1313 GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1314 const GdkColor text_color = style->text[GTK_STATE_NORMAL];
1315 const GdkColor base_color = style->base[GTK_STATE_NORMAL];
1317 PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1320 void Gtk2UI::GetSelectedEntryForegroundHSL(color_utils::HSL* tint) const {
1321 // The simplest of all the tints. We just use the selected text in the entry
1322 // since the icons tinted this way will only be displayed against
1323 // base[GTK_STATE_SELECTED].
1324 GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1325 const GdkColor color = style->text[GTK_STATE_SELECTED];
1326 color_utils::SkColorToHSL(GdkColorToSkColor(color), tint);
1329 SkBitmap Gtk2UI::DrawGtkButtonBorder(int gtk_state,
1330 bool focused,
1331 bool call_to_action,
1332 int width,
1333 int height) const {
1334 // Create a temporary GTK button to snapshot
1335 GtkWidget* window = gtk_offscreen_window_new();
1336 GtkWidget* button = gtk_button_new();
1337 gtk_widget_set_size_request(button, width, height);
1338 gtk_container_add(GTK_CONTAINER(window), button);
1339 gtk_widget_realize(window);
1340 gtk_widget_realize(button);
1341 gtk_widget_show(button);
1342 gtk_widget_show(window);
1344 if (call_to_action)
1345 GTK_WIDGET_SET_FLAGS(button, GTK_HAS_DEFAULT);
1347 if (focused) {
1348 // We can't just use gtk_widget_grab_focus() here because that sets
1349 // gtk_widget_is_focus(), but not gtk_widget_has_focus(), which is what the
1350 // GtkButton's paint checks.
1351 GTK_WIDGET_SET_FLAGS(button, GTK_HAS_FOCUS);
1354 gtk_widget_set_state(button, static_cast<GtkStateType>(gtk_state));
1356 GdkPixmap* pixmap;
1358 // http://crbug.com/346740
1359 ANNOTATE_SCOPED_MEMORY_LEAK;
1360 pixmap = gtk_widget_get_snapshot(button, NULL);
1362 int w, h;
1363 gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &w, &h);
1364 DCHECK_EQ(w, width);
1365 DCHECK_EQ(h, height);
1367 // We render the Pixmap to a Pixbuf. This can be slow, as we're scrapping
1368 // bits from X.
1369 GdkColormap* colormap = gdk_drawable_get_colormap(pixmap);
1370 GdkPixbuf* pixbuf = gdk_pixbuf_get_from_drawable(NULL,
1371 GDK_DRAWABLE(pixmap),
1372 colormap,
1373 0, 0, 0, 0, w, h);
1375 // Finally, we convert our pixbuf into a type we can use.
1376 SkBitmap border = GdkPixbufToImageSkia(pixbuf);
1377 g_object_unref(pixbuf);
1378 g_object_unref(pixmap);
1379 gtk_widget_destroy(window);
1381 return border;
1384 void Gtk2UI::ClearAllThemeData() {
1385 gtk_images_.clear();
1388 void Gtk2UI::UpdateDefaultFont(const PangoFontDescription* desc) {
1389 // Use gfx::FontRenderParams to select a family and determine the rendering
1390 // settings.
1391 gfx::FontRenderParamsQuery query;
1392 query.families = base::SplitString(pango_font_description_get_family(desc),
1393 ",", base::TRIM_WHITESPACE,
1394 base::SPLIT_WANT_ALL);
1396 if (pango_font_description_get_size_is_absolute(desc)) {
1397 // If the size is absolute, it's specified in Pango units. There are
1398 // PANGO_SCALE Pango units in a device unit (pixel).
1399 const int size_pixels = pango_font_description_get_size(desc) / PANGO_SCALE;
1400 default_font_size_pixels_ = size_pixels;
1401 query.pixel_size = size_pixels;
1402 } else {
1403 // Non-absolute sizes are in points (again scaled by PANGO_SIZE).
1404 // Round the value when converting to pixels to match GTK's logic.
1405 const double size_points = pango_font_description_get_size(desc) /
1406 static_cast<double>(PANGO_SCALE);
1407 default_font_size_pixels_ = static_cast<int>(
1408 GetPixelsInPoint(device_scale_factor_) * size_points + 0.5);
1409 query.point_size = static_cast<int>(size_points);
1412 query.style = gfx::Font::NORMAL;
1413 // TODO(davemoore): Support weights other than bold?
1414 if (pango_font_description_get_weight(desc) == PANGO_WEIGHT_BOLD)
1415 query.style |= gfx::Font::BOLD;
1416 // TODO(davemoore): What about PANGO_STYLE_OBLIQUE?
1417 if (pango_font_description_get_style(desc) == PANGO_STYLE_ITALIC)
1418 query.style |= gfx::Font::ITALIC;
1420 default_font_render_params_ =
1421 gfx::GetFontRenderParams(query, &default_font_family_);
1422 default_font_style_ = query.style;
1425 void Gtk2UI::OnStyleSet(GtkWidget* widget, GtkStyle* previous_style) {
1426 ClearAllThemeData();
1427 LoadGtkValues();
1428 NativeThemeGtk2::instance()->NotifyObservers();
1431 void Gtk2UI::UpdateDeviceScaleFactor(float device_scale_factor) {
1432 device_scale_factor_ = device_scale_factor;
1433 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
1434 UpdateDefaultFont(label_style->font_desc);
1437 float Gtk2UI::GetDeviceScaleFactor() const {
1438 if (gfx::Display::HasForceDeviceScaleFactor())
1439 return gfx::Display::GetForcedDeviceScaleFactor();
1440 const int kCSSDefaultDPI = 96;
1441 const float scale = GetDPI() / kCSSDefaultDPI;
1442 // Round to 1 decimal, e.g. to 1.4.
1443 const float rounded = roundf(scale * 10) / 10;
1444 // See crbug.com/484400
1445 return rounded < 1.3 ? 1.0 : rounded;
1448 } // namespace libgtk2ui
1450 views::LinuxUI* BuildGtk2UI() {
1451 return new libgtk2ui::Gtk2UI;