MacViews: Use Mac's "Constrained Window Button" style for Button::STYLE_BUTTON LabelB...
[chromium-blink-merge.git] / chrome / browser / ui / libgtk2ui / gtk2_ui.cc
blob3bf8fa54623530fa729798228d5d32db47e2ba9f
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>
11 #include <X11/Xlib.h>
12 #include <gio/gio.h>
14 #include "base/command_line.h"
15 #include "base/debug/leak_annotations.h"
16 #include "base/environment.h"
17 #include "base/i18n/rtl.h"
18 #include "base/logging.h"
19 #include "base/nix/mime_util_xdg.h"
20 #include "base/nix/xdg_util.h"
21 #include "base/stl_util.h"
22 #include "base/strings/string_split.h"
23 #include "base/strings/stringprintf.h"
24 #include "chrome/browser/themes/theme_properties.h"
25 #include "chrome/browser/ui/libgtk2ui/app_indicator_icon.h"
26 #include "chrome/browser/ui/libgtk2ui/chrome_gtk_frame.h"
27 #include "chrome/browser/ui/libgtk2ui/gtk2_border.h"
28 #include "chrome/browser/ui/libgtk2ui/gtk2_event_loop.h"
29 #include "chrome/browser/ui/libgtk2ui/gtk2_key_bindings_handler.h"
30 #include "chrome/browser/ui/libgtk2ui/gtk2_signal_registrar.h"
31 #include "chrome/browser/ui/libgtk2ui/gtk2_status_icon.h"
32 #include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
33 #include "chrome/browser/ui/libgtk2ui/native_theme_gtk2.h"
34 #include "chrome/browser/ui/libgtk2ui/print_dialog_gtk2.h"
35 #include "chrome/browser/ui/libgtk2ui/printing_gtk2_util.h"
36 #include "chrome/browser/ui/libgtk2ui/select_file_dialog_impl.h"
37 #include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
38 #include "chrome/browser/ui/libgtk2ui/unity_service.h"
39 #include "chrome/browser/ui/libgtk2ui/x11_input_method_context_impl_gtk2.h"
40 #include "grit/components_scaled_resources.h"
41 #include "grit/theme_resources.h"
42 #include "printing/printing_context_linux.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "third_party/skia/include/core/SkCanvas.h"
45 #include "third_party/skia/include/core/SkColor.h"
46 #include "third_party/skia/include/core/SkShader.h"
47 #include "ui/base/resource/resource_bundle.h"
48 #include "ui/gfx/canvas.h"
49 #include "ui/gfx/display.h"
50 #include "ui/gfx/geometry/rect.h"
51 #include "ui/gfx/geometry/size.h"
52 #include "ui/gfx/image/image.h"
53 #include "ui/gfx/skbitmap_operations.h"
54 #include "ui/gfx/skia_util.h"
55 #include "ui/gfx/x/x11_types.h"
56 #include "ui/resources/grit/ui_resources.h"
57 #include "ui/views/controls/button/label_button.h"
58 #include "ui/views/controls/button/label_button_border.h"
59 #include "ui/views/linux_ui/window_button_order_observer.h"
60 #include "ui/views/resources/grit/views_resources.h"
62 #if defined(USE_GCONF)
63 #include "chrome/browser/ui/libgtk2ui/gconf_listener.h"
64 #endif
66 // A minimized port of GtkThemeService into something that can provide colors
67 // and images for aura.
69 // TODO(erg): There's still a lot that needs ported or done for the first time:
71 // - Render and inject the omnibox background.
72 // - Make sure to test with a light on dark theme, too.
74 // Work around a header bug:
75 // linux/debian_wheezy_i386-sysroot/usr/include/linux/stddef.h redefines NULL
76 // to 0, which breaks -Wsentinel. Get back the normal definition of NULL.
77 // TODO(thakis): Remove this once we update sysroots.
78 #define __need_NULL
79 #include <stddef.h>
81 namespace libgtk2ui {
83 namespace {
85 struct GObjectDeleter {
86 void operator()(void* ptr) {
87 g_object_unref(ptr);
90 struct GtkIconInfoDeleter {
91 void operator()(GtkIconInfo* ptr) {
92 gtk_icon_info_free(ptr);
95 typedef scoped_ptr<GIcon, GObjectDeleter> ScopedGIcon;
96 typedef scoped_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo;
97 typedef scoped_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf;
99 // Prefix for app indicator ids
100 const char kAppIndicatorIdPrefix[] = "chrome_app_indicator_";
102 // Number of app indicators used (used as part of app-indicator id).
103 int indicators_count;
105 // The unknown content type.
106 const char* kUnknownContentType = "application/octet-stream";
108 // The size of the rendered toolbar image.
109 const int kToolbarImageWidth = 64;
110 const int kToolbarImageHeight = 128;
112 // How much to tint the GTK+ color lighter at the top of the window.
113 const color_utils::HSL kGtkFrameShift = { -1, -1, 0.58 };
115 // How much to tint the GTK+ color when an explicit frame color hasn't been
116 // specified.
117 const color_utils::HSL kDefaultFrameShift = { -1, -1, 0.4 };
119 // Values used as the new luminance and saturation values in the inactive tab
120 // text color.
121 const double kDarkInactiveLuminance = 0.85;
122 const double kLightInactiveLuminance = 0.15;
123 const double kHeavyInactiveSaturation = 0.7;
124 const double kLightInactiveSaturation = 0.3;
126 // Default color for links on the NTP when the GTK+ theme doesn't define a
127 // link color. Constant taken from gtklinkbutton.c.
128 const GdkColor kDefaultLinkColor = { 0, 0, 0, 0xeeee };
130 const int kSkiaToGDKMultiplier = 257;
132 // TODO(erg): ThemeService has a whole interface just for reading default
133 // constants. Figure out what to do with that more long term; for now, just
134 // copy the constants themselves here.
136 // Default tints.
137 const color_utils::HSL kDefaultTintButtons = { -1, -1, -1 };
138 const color_utils::HSL kDefaultTintFrame = { -1, -1, -1 };
139 const color_utils::HSL kDefaultTintFrameInactive = { -1, -1, 0.75f };
140 const color_utils::HSL kDefaultTintFrameIncognito = { -1, 0.2f, 0.35f };
141 const color_utils::HSL kDefaultTintFrameIncognitoInactive = { -1, 0.3f, 0.6f };
142 const color_utils::HSL kDefaultTintBackgroundTab = { -1, 0.5, 0.75 };
144 // A list of images that we provide while in gtk mode.
146 // TODO(erg): We list both the normal and *_DESKTOP versions of some of these
147 // images because in some contexts, we don't go through the
148 // chrome::MapThemeImage interface. That should be fixed, but tracking that
149 // down is Hard.
150 const int kThemeImages[] = {
151 IDR_THEME_TOOLBAR,
152 IDR_THEME_TAB_BACKGROUND,
153 IDR_THEME_TAB_BACKGROUND_DESKTOP,
154 IDR_THEME_TAB_BACKGROUND_INCOGNITO,
155 IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
156 IDR_FRAME,
157 IDR_FRAME_INACTIVE,
158 IDR_THEME_FRAME,
159 IDR_THEME_FRAME_INACTIVE,
160 IDR_THEME_FRAME_INCOGNITO,
161 IDR_THEME_FRAME_INCOGNITO_INACTIVE,
164 // A list of icons used in the autocomplete view that should be tinted to the
165 // current gtk theme selection color so they stand out against the GtkEntry's
166 // base color.
167 // TODO(erg): Decide what to do about other icons that appear in the omnibox,
168 // e.g. content settings icons.
169 const int kAutocompleteImages[] = {
170 IDR_OMNIBOX_CALCULATOR,
171 IDR_OMNIBOX_EXTENSION_APP,
172 IDR_OMNIBOX_HTTP,
173 IDR_OMNIBOX_HTTP_DARK,
174 IDR_OMNIBOX_SEARCH,
175 IDR_OMNIBOX_SEARCH_DARK,
176 IDR_OMNIBOX_STAR,
177 IDR_OMNIBOX_STAR_DARK,
178 IDR_OMNIBOX_TTS,
179 IDR_OMNIBOX_TTS_DARK,
182 // This table converts button ids into a pair of gtk-stock id and state.
183 struct IDRGtkMapping {
184 int idr;
185 const char* stock_id;
186 GtkStateType gtk_state;
187 } const kGtkIcons[] = {
188 { IDR_BACK, GTK_STOCK_GO_BACK, GTK_STATE_NORMAL },
189 { IDR_BACK_D, GTK_STOCK_GO_BACK, GTK_STATE_INSENSITIVE },
191 { IDR_FORWARD, GTK_STOCK_GO_FORWARD, GTK_STATE_NORMAL },
192 { IDR_FORWARD_D, GTK_STOCK_GO_FORWARD, GTK_STATE_INSENSITIVE },
194 { IDR_HOME, GTK_STOCK_HOME, GTK_STATE_NORMAL },
196 { IDR_RELOAD, GTK_STOCK_REFRESH, GTK_STATE_NORMAL },
197 { IDR_RELOAD_D, GTK_STOCK_REFRESH, GTK_STATE_INSENSITIVE },
199 { IDR_STOP, GTK_STOCK_STOP, GTK_STATE_NORMAL },
200 { IDR_STOP_D, GTK_STOCK_STOP, GTK_STATE_INSENSITIVE },
203 // The image resources that will be tinted by the 'button' tint value.
204 const int kOtherToolbarButtonIDs[] = {
205 IDR_TOOLBAR_BEZEL_HOVER,
206 IDR_TOOLBAR_BEZEL_PRESSED,
207 IDR_BROWSER_ACTIONS_OVERFLOW,
209 // TODO(erg): The dropdown arrow should be tinted because we're injecting
210 // various background GTK colors, but the code that accesses them needs to be
211 // modified so that they ask their ui::ThemeProvider instead of the
212 // ResourceBundle. (i.e. in a light on dark theme, the dropdown arrow will be
213 // dark on dark)
214 IDR_MENU_DROPARROW
217 bool IsOverridableImage(int id) {
218 CR_DEFINE_STATIC_LOCAL(std::set<int>, images, ());
219 if (images.empty()) {
220 images.insert(kThemeImages, kThemeImages + arraysize(kThemeImages));
221 images.insert(kAutocompleteImages,
222 kAutocompleteImages + arraysize(kAutocompleteImages));
224 for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i)
225 images.insert(kGtkIcons[i].idr);
227 images.insert(kOtherToolbarButtonIDs,
228 kOtherToolbarButtonIDs + arraysize(kOtherToolbarButtonIDs));
231 return images.count(id) > 0;
234 // Picks a button tint from a set of background colors. While
235 // |accent_gdk_color| will usually be the same color through a theme, this
236 // function will get called with the normal GtkLabel |text_color|/GtkWindow
237 // |background_color| pair and the GtkEntry |text_color|/|background_color|
238 // pair. While 3/4 of the time the resulting tint will be the same, themes that
239 // have a dark window background (with light text) and a light text entry (with
240 // dark text) will get better icons with this separated out.
241 void PickButtonTintFromColors(const GdkColor& accent_gdk_color,
242 const GdkColor& text_color,
243 const GdkColor& background_color,
244 color_utils::HSL* tint) {
245 SkColor accent_color = GdkColorToSkColor(accent_gdk_color);
246 color_utils::HSL accent_tint;
247 color_utils::SkColorToHSL(accent_color, &accent_tint);
249 color_utils::HSL text_tint;
250 color_utils::SkColorToHSL(GdkColorToSkColor(text_color),
251 &text_tint);
253 color_utils::HSL background_tint;
254 color_utils::SkColorToHSL(GdkColorToSkColor(background_color),
255 &background_tint);
257 // If the accent color is gray, then our normal HSL tomfoolery will bring out
258 // whatever color is oddly dominant (for example, in rgb space [125, 128,
259 // 125] will tint green instead of gray). Slight differences (+/-10 (4%) to
260 // all color components) should be interpreted as this color being gray and
261 // we should switch into a special grayscale mode.
262 int rb_diff = abs(static_cast<int>(SkColorGetR(accent_color)) -
263 static_cast<int>(SkColorGetB(accent_color)));
264 int rg_diff = abs(static_cast<int>(SkColorGetR(accent_color)) -
265 static_cast<int>(SkColorGetG(accent_color)));
266 int bg_diff = abs(static_cast<int>(SkColorGetB(accent_color)) -
267 static_cast<int>(SkColorGetG(accent_color)));
268 if (rb_diff < 10 && rg_diff < 10 && bg_diff < 10) {
269 // Our accent is white/gray/black. Only the luminance of the accent color
270 // matters.
271 tint->h = -1;
273 // Use the saturation of the text.
274 tint->s = text_tint.s;
276 // Use the luminance of the accent color UNLESS there isn't enough
277 // luminance contrast between the accent color and the base color.
278 if (fabs(accent_tint.l - background_tint.l) > 0.3)
279 tint->l = accent_tint.l;
280 else
281 tint->l = text_tint.l;
282 } else {
283 // Our accent is a color.
284 tint->h = accent_tint.h;
286 // Don't modify the saturation; the amount of color doesn't matter.
287 tint->s = -1;
289 // If the text wants us to darken the icon, don't change the luminance (the
290 // icons are already dark enough). Otherwise, lighten the icon by no more
291 // than 0.9 since we don't want a pure-white icon even if the text is pure
292 // white.
293 if (text_tint.l < 0.5)
294 tint->l = -1;
295 else if (text_tint.l <= 0.9)
296 tint->l = text_tint.l;
297 else
298 tint->l = 0.9;
302 // Applies an HSL shift to a GdkColor (instead of an SkColor)
303 void GdkColorHSLShift(const color_utils::HSL& shift, GdkColor* frame_color) {
304 SkColor shifted = color_utils::HSLShift(
305 GdkColorToSkColor(*frame_color), shift);
307 frame_color->pixel = 0;
308 frame_color->red = SkColorGetR(shifted) * kSkiaToGDKMultiplier;
309 frame_color->green = SkColorGetG(shifted) * kSkiaToGDKMultiplier;
310 frame_color->blue = SkColorGetB(shifted) * kSkiaToGDKMultiplier;
313 // Copied Default blah sections from ThemeService.
314 color_utils::HSL GetDefaultTint(int id) {
315 switch (id) {
316 case ThemeProperties::TINT_FRAME:
317 return kDefaultTintFrame;
318 case ThemeProperties::TINT_FRAME_INACTIVE:
319 return kDefaultTintFrameInactive;
320 case ThemeProperties::TINT_FRAME_INCOGNITO:
321 return kDefaultTintFrameIncognito;
322 case ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE:
323 return kDefaultTintFrameIncognitoInactive;
324 case ThemeProperties::TINT_BUTTONS:
325 return kDefaultTintButtons;
326 case ThemeProperties::TINT_BACKGROUND_TAB:
327 return kDefaultTintBackgroundTab;
328 default:
329 color_utils::HSL result = {-1, -1, -1};
330 return result;
334 // Returns a gfx::FontRenderParams corresponding to GTK's configuration.
335 gfx::FontRenderParams GetGtkFontRenderParams() {
336 GtkSettings* gtk_settings = gtk_settings_get_default();
337 CHECK(gtk_settings);
338 gint antialias = 0;
339 gint hinting = 0;
340 gchar* hint_style = NULL;
341 gchar* rgba = NULL;
342 g_object_get(gtk_settings,
343 "gtk-xft-antialias", &antialias,
344 "gtk-xft-hinting", &hinting,
345 "gtk-xft-hintstyle", &hint_style,
346 "gtk-xft-rgba", &rgba,
347 NULL);
349 gfx::FontRenderParams params;
350 params.antialiasing = antialias != 0;
352 if (hinting == 0 || !hint_style || strcmp(hint_style, "hintnone") == 0) {
353 params.hinting = gfx::FontRenderParams::HINTING_NONE;
354 } else if (strcmp(hint_style, "hintslight") == 0) {
355 params.hinting = gfx::FontRenderParams::HINTING_SLIGHT;
356 } else if (strcmp(hint_style, "hintmedium") == 0) {
357 params.hinting = gfx::FontRenderParams::HINTING_MEDIUM;
358 } else if (strcmp(hint_style, "hintfull") == 0) {
359 params.hinting = gfx::FontRenderParams::HINTING_FULL;
360 } else {
361 LOG(WARNING) << "Unexpected gtk-xft-hintstyle \"" << hint_style << "\"";
362 params.hinting = gfx::FontRenderParams::HINTING_NONE;
365 if (!rgba || strcmp(rgba, "none") == 0) {
366 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
367 } else if (strcmp(rgba, "rgb") == 0) {
368 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB;
369 } else if (strcmp(rgba, "bgr") == 0) {
370 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR;
371 } else if (strcmp(rgba, "vrgb") == 0) {
372 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB;
373 } else if (strcmp(rgba, "vbgr") == 0) {
374 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR;
375 } else {
376 LOG(WARNING) << "Unexpected gtk-xft-rgba \"" << rgba << "\"";
377 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
380 g_free(hint_style);
381 g_free(rgba);
383 return params;
386 double GetBaseDPI() {
387 XDisplay* xdisplay = gfx::GetXDisplay();
388 int xscreen = DefaultScreen(xdisplay);
389 return (DisplayHeight(xdisplay, xscreen) * 25.4) /
390 DisplayHeightMM(xdisplay, xscreen);
393 double GetFontDPI() {
394 GtkSettings* gtk_settings = gtk_settings_get_default();
395 CHECK(gtk_settings);
396 gint gtk_dpi = -1;
397 g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, NULL);
399 // GTK multiplies the DPI by 1024 before storing it.
400 return (gtk_dpi > 0) ? gtk_dpi / 1024.0 : GetBaseDPI();
403 // Queries GTK for its font DPI setting and returns the number of pixels in a
404 // point.
405 double GetPixelsInPoint(float device_scale_factor) {
406 double dpi = GetFontDPI();
408 // Take device_scale_factor into account — if Chrome already scales the
409 // entire UI up by 2x, we should not also scale up.
410 dpi /= device_scale_factor;
412 // There are 72 points in an inch.
413 return dpi / 72.0;
416 views::LinuxUI::NonClientMiddleClickAction GetDefaultMiddleClickAction() {
417 scoped_ptr<base::Environment> env(base::Environment::Create());
418 switch (base::nix::GetDesktopEnvironment(env.get())) {
419 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
420 // Starting with KDE 4.4, windows' titlebars can be dragged with the
421 // middle mouse button to create tab groups. We don't support that in
422 // Chrome, but at least avoid lowering windows in response to middle
423 // clicks to avoid surprising users who expect the KDE behavior.
424 return views::LinuxUI::MIDDLE_CLICK_ACTION_NONE;
425 default:
426 return views::LinuxUI::MIDDLE_CLICK_ACTION_LOWER;
430 double GetGnomeTextScalingFactor() {
431 const char kDesktopInterfaceSchema[] = "org.gnome.desktop.interface";
432 for (const gchar* const* schemas = g_settings_list_schemas(); *schemas;
433 schemas++) {
434 if (!strcmp(kDesktopInterfaceSchema, static_cast<const char*>(*schemas))) {
435 GSettings* settings = g_settings_new(kDesktopInterfaceSchema);
436 double scale = g_settings_get_double(settings, "text-scaling-factor");
437 g_object_unref(settings);
438 return scale;
441 // Fallback if the schema does not exist.
442 return GetFontDPI() / GetBaseDPI();
445 } // namespace
447 Gtk2UI::Gtk2UI()
448 : default_font_size_pixels_(0),
449 default_font_style_(gfx::Font::NORMAL),
450 middle_click_action_(GetDefaultMiddleClickAction()),
451 device_scale_factor_(1.0) {
452 GtkInitFromCommandLine(*base::CommandLine::ForCurrentProcess());
455 void Gtk2UI::Initialize() {
456 signals_.reset(new Gtk2SignalRegistrar);
458 // Create our fake widgets.
459 fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
460 fake_frame_ = chrome_gtk_frame_new();
461 fake_label_.Own(gtk_label_new(""));
462 fake_entry_.Own(gtk_entry_new());
464 // Only realized widgets receive style-set notifications, which we need to
465 // broadcast new theme images and colors. Only realized widgets have style
466 // properties, too, which we query for some colors.
467 gtk_widget_realize(fake_frame_);
468 gtk_widget_realize(fake_window_);
470 signals_->Connect(fake_frame_, "style-set",
471 G_CALLBACK(&OnStyleSetThunk), this);
473 LoadGtkValues();
475 printing::PrintingContextLinux::SetCreatePrintDialogFunction(
476 &PrintDialogGtk2::CreatePrintDialog);
477 printing::PrintingContextLinux::SetPdfPaperSizeFunction(
478 &GetPdfPaperSizeDeviceUnitsGtk);
480 #if defined(USE_GCONF)
481 // We must build this after GTK gets initialized.
482 gconf_listener_.reset(new GConfListener(this));
483 #endif // defined(USE_GCONF)
485 indicators_count = 0;
487 // Instantiate the singleton instance of Gtk2EventLoop.
488 Gtk2EventLoop::GetInstance();
491 Gtk2UI::~Gtk2UI() {
492 gtk_widget_destroy(fake_window_);
493 gtk_widget_destroy(fake_frame_);
494 fake_label_.Destroy();
495 fake_entry_.Destroy();
497 ClearAllThemeData();
500 gfx::Image Gtk2UI::GetThemeImageNamed(int id) const {
501 // Try to get our cached version:
502 ImageCache::const_iterator it = gtk_images_.find(id);
503 if (it != gtk_images_.end())
504 return it->second;
506 if (IsOverridableImage(id)) {
507 gfx::Image image = gfx::Image(
508 gfx::ImageSkia::CreateFrom1xBitmap(GenerateGtkThemeBitmap(id)));
509 gtk_images_[id] = image;
510 return image;
513 return gfx::Image();
516 bool Gtk2UI::GetColor(int id, SkColor* color) const {
517 ColorMap::const_iterator it = colors_.find(id);
518 if (it != colors_.end()) {
519 *color = it->second;
520 return true;
523 return false;
526 bool Gtk2UI::HasCustomImage(int id) const {
527 return IsOverridableImage(id);
530 SkColor Gtk2UI::GetFocusRingColor() const {
531 return focus_ring_color_;
534 SkColor Gtk2UI::GetThumbActiveColor() const {
535 return thumb_active_color_;
538 SkColor Gtk2UI::GetThumbInactiveColor() const {
539 return thumb_inactive_color_;
542 SkColor Gtk2UI::GetTrackColor() const {
543 return track_color_;
546 SkColor Gtk2UI::GetActiveSelectionBgColor() const {
547 return active_selection_bg_color_;
550 SkColor Gtk2UI::GetActiveSelectionFgColor() const {
551 return active_selection_fg_color_;
554 SkColor Gtk2UI::GetInactiveSelectionBgColor() const {
555 return inactive_selection_bg_color_;
558 SkColor Gtk2UI::GetInactiveSelectionFgColor() const {
559 return inactive_selection_fg_color_;
562 double Gtk2UI::GetCursorBlinkInterval() const {
563 // From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is
564 // the default value for gtk-cursor-blink-time.
565 static const gint kGtkDefaultCursorBlinkTime = 1200;
567 // Dividing GTK's cursor blink cycle time (in milliseconds) by this value
568 // yields an appropriate value for
569 // content::RendererPreferences::caret_blink_interval. This matches the
570 // logic in the WebKit GTK port.
571 static const double kGtkCursorBlinkCycleFactor = 2000.0;
573 gint cursor_blink_time = kGtkDefaultCursorBlinkTime;
574 gboolean cursor_blink = TRUE;
575 g_object_get(gtk_settings_get_default(),
576 "gtk-cursor-blink-time", &cursor_blink_time,
577 "gtk-cursor-blink", &cursor_blink,
578 NULL);
579 return cursor_blink ? (cursor_blink_time / kGtkCursorBlinkCycleFactor) : 0.0;
582 ui::NativeTheme* Gtk2UI::GetNativeTheme(aura::Window* window) const {
583 ui::NativeTheme* native_theme_override = NULL;
584 if (!native_theme_overrider_.is_null())
585 native_theme_override = native_theme_overrider_.Run(window);
587 if (native_theme_override)
588 return native_theme_override;
590 return NativeThemeGtk2::instance();
593 void Gtk2UI::SetNativeThemeOverride(const NativeThemeGetter& callback) {
594 native_theme_overrider_ = callback;
597 bool Gtk2UI::GetDefaultUsesSystemTheme() const {
598 scoped_ptr<base::Environment> env(base::Environment::Create());
600 switch (base::nix::GetDesktopEnvironment(env.get())) {
601 case base::nix::DESKTOP_ENVIRONMENT_GNOME:
602 case base::nix::DESKTOP_ENVIRONMENT_UNITY:
603 case base::nix::DESKTOP_ENVIRONMENT_XFCE:
604 return true;
605 case base::nix::DESKTOP_ENVIRONMENT_KDE3:
606 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
607 case base::nix::DESKTOP_ENVIRONMENT_OTHER:
608 return false;
610 // Unless GetDesktopEnvironment() badly misbehaves, this should never happen.
611 NOTREACHED();
612 return false;
615 void Gtk2UI::SetDownloadCount(int count) const {
616 if (unity::IsRunning())
617 unity::SetDownloadCount(count);
620 void Gtk2UI::SetProgressFraction(float percentage) const {
621 if (unity::IsRunning())
622 unity::SetProgressFraction(percentage);
625 bool Gtk2UI::IsStatusIconSupported() const {
626 return true;
629 scoped_ptr<views::StatusIconLinux> Gtk2UI::CreateLinuxStatusIcon(
630 const gfx::ImageSkia& image,
631 const base::string16& tool_tip) const {
632 if (AppIndicatorIcon::CouldOpen()) {
633 ++indicators_count;
634 return scoped_ptr<views::StatusIconLinux>(new AppIndicatorIcon(
635 base::StringPrintf("%s%d", kAppIndicatorIdPrefix, indicators_count),
636 image,
637 tool_tip));
638 } else {
639 return scoped_ptr<views::StatusIconLinux>(new Gtk2StatusIcon(
640 image, tool_tip));
644 gfx::Image Gtk2UI::GetIconForContentType(
645 const std::string& content_type,
646 int size) const {
647 // This call doesn't take a reference.
648 GtkIconTheme* theme = gtk_icon_theme_get_default();
650 std::string content_types[] = {
651 content_type, kUnknownContentType
654 for (size_t i = 0; i < arraysize(content_types); ++i) {
655 ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str()));
656 ScopedGtkIconInfo icon_info(
657 gtk_icon_theme_lookup_by_gicon(
658 theme, icon.get(), size,
659 static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE)));
660 if (!icon_info)
661 continue;
662 ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), NULL));
663 if (!pixbuf)
664 continue;
666 SkBitmap bitmap = GdkPixbufToImageSkia(pixbuf.get());
667 DCHECK_EQ(size, bitmap.width());
668 DCHECK_EQ(size, bitmap.height());
669 gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
670 image_skia.MakeThreadSafe();
671 return gfx::Image(image_skia);
673 return gfx::Image();
676 scoped_ptr<views::Border> Gtk2UI::CreateNativeBorder(
677 views::LabelButton* owning_button,
678 scoped_ptr<views::LabelButtonBorder> border) {
679 if (owning_button->GetNativeTheme() != NativeThemeGtk2::instance())
680 return border.Pass();
682 return make_scoped_ptr(new Gtk2Border(this, owning_button, border.Pass()));
685 void Gtk2UI::AddWindowButtonOrderObserver(
686 views::WindowButtonOrderObserver* observer) {
687 if (!leading_buttons_.empty() || !trailing_buttons_.empty()) {
688 observer->OnWindowButtonOrderingChange(leading_buttons_,
689 trailing_buttons_);
692 observer_list_.AddObserver(observer);
695 void Gtk2UI::RemoveWindowButtonOrderObserver(
696 views::WindowButtonOrderObserver* observer) {
697 observer_list_.RemoveObserver(observer);
700 void Gtk2UI::SetWindowButtonOrdering(
701 const std::vector<views::FrameButton>& leading_buttons,
702 const std::vector<views::FrameButton>& trailing_buttons) {
703 leading_buttons_ = leading_buttons;
704 trailing_buttons_ = trailing_buttons;
706 FOR_EACH_OBSERVER(views::WindowButtonOrderObserver, observer_list_,
707 OnWindowButtonOrderingChange(leading_buttons_,
708 trailing_buttons_));
711 void Gtk2UI::SetNonClientMiddleClickAction(NonClientMiddleClickAction action) {
712 middle_click_action_ = action;
715 scoped_ptr<ui::LinuxInputMethodContext> Gtk2UI::CreateInputMethodContext(
716 ui::LinuxInputMethodContextDelegate* delegate,
717 bool is_simple) const {
718 return scoped_ptr<ui::LinuxInputMethodContext>(
719 new X11InputMethodContextImplGtk2(delegate, is_simple));
722 gfx::FontRenderParams Gtk2UI::GetDefaultFontRenderParams() const {
723 static gfx::FontRenderParams params = GetGtkFontRenderParams();
724 return params;
727 void Gtk2UI::GetDefaultFontDescription(
728 std::string* family_out,
729 int* size_pixels_out,
730 int* style_out,
731 gfx::FontRenderParams* params_out) const {
732 *family_out = default_font_family_;
733 *size_pixels_out = default_font_size_pixels_;
734 *style_out = default_font_style_;
735 *params_out = default_font_render_params_;
738 ui::SelectFileDialog* Gtk2UI::CreateSelectFileDialog(
739 ui::SelectFileDialog::Listener* listener,
740 ui::SelectFilePolicy* policy) const {
741 return SelectFileDialogImpl::Create(listener, policy);
744 bool Gtk2UI::UnityIsRunning() {
745 return unity::IsRunning();
748 views::LinuxUI::NonClientMiddleClickAction
749 Gtk2UI::GetNonClientMiddleClickAction() {
750 return middle_click_action_;
753 void Gtk2UI::NotifyWindowManagerStartupComplete() {
754 // TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO
755 // from http://standards.freedesktop.org/startup-notification-spec/ instead.
756 gdk_notify_startup_complete();
759 bool Gtk2UI::MatchEvent(const ui::Event& event,
760 std::vector<ui::TextEditCommandAuraLinux>* commands) {
761 // Ensure that we have a keyboard handler.
762 if (!key_bindings_handler_)
763 key_bindings_handler_.reset(new Gtk2KeyBindingsHandler);
765 return key_bindings_handler_->MatchEvent(event, commands);
768 void Gtk2UI::GetScrollbarColors(GdkColor* thumb_active_color,
769 GdkColor* thumb_inactive_color,
770 GdkColor* track_color) {
771 GdkColor* theme_thumb_active = NULL;
772 GdkColor* theme_thumb_inactive = NULL;
773 GdkColor* theme_trough_color = NULL;
774 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
775 "scrollbar-slider-prelight-color", &theme_thumb_active,
776 "scrollbar-slider-normal-color", &theme_thumb_inactive,
777 "scrollbar-trough-color", &theme_trough_color,
778 NULL);
780 // Ask the theme if the theme specifies all the scrollbar colors and short
781 // circuit the expensive painting/compositing if we have all of them.
782 if (theme_thumb_active && theme_thumb_inactive && theme_trough_color) {
783 *thumb_active_color = *theme_thumb_active;
784 *thumb_inactive_color = *theme_thumb_inactive;
785 *track_color = *theme_trough_color;
787 gdk_color_free(theme_thumb_active);
788 gdk_color_free(theme_thumb_inactive);
789 gdk_color_free(theme_trough_color);
790 return;
793 // Create window containing scrollbar elements
794 GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);
795 GtkWidget* fixed = gtk_fixed_new();
796 GtkWidget* scrollbar = gtk_hscrollbar_new(NULL);
797 gtk_container_add(GTK_CONTAINER(window), fixed);
798 gtk_container_add(GTK_CONTAINER(fixed), scrollbar);
799 gtk_widget_realize(window);
800 gtk_widget_realize(scrollbar);
802 // Draw scrollbar thumb part and track into offscreen image
803 const int kWidth = 100;
804 const int kHeight = 20;
805 GtkStyle* style = gtk_rc_get_style(scrollbar);
806 GdkWindow* gdk_window = gtk_widget_get_window(window);
807 GdkPixmap* pm = gdk_pixmap_new(gdk_window, kWidth, kHeight, -1);
808 GdkRectangle rect = { 0, 0, kWidth, kHeight };
809 unsigned char data[3 * kWidth * kHeight];
810 for (int i = 0; i < 3; ++i) {
811 if (i < 2) {
812 // Thumb part
813 gtk_paint_slider(style, pm,
814 i == 0 ? GTK_STATE_PRELIGHT : GTK_STATE_NORMAL,
815 GTK_SHADOW_OUT, &rect, scrollbar, "slider", 0, 0,
816 kWidth, kHeight, GTK_ORIENTATION_HORIZONTAL);
817 } else {
818 // Track
819 gtk_paint_box(style, pm, GTK_STATE_ACTIVE, GTK_SHADOW_IN, &rect,
820 scrollbar, "trough-upper", 0, 0, kWidth, kHeight);
822 GdkPixbuf* pb = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB,
823 FALSE, 8, kWidth, kHeight,
824 3 * kWidth, 0, 0);
825 gdk_pixbuf_get_from_drawable(pb, pm, NULL, 0, 0, 0, 0, kWidth, kHeight);
827 // Sample pixels
828 int components[3] = { 0 };
829 for (int y = 2; y < kHeight - 2; ++y) {
830 for (int c = 0; c < 3; ++c) {
831 // Sample a vertical slice of pixels at about one-thirds from the
832 // left edge. This allows us to avoid any fixed graphics that might be
833 // located at the edges or in the center of the scrollbar.
834 // Each pixel is made up of a red, green, and blue component; taking up
835 // a total of three bytes.
836 components[c] += data[3 * (kWidth / 3 + y * kWidth) + c];
839 GdkColor* color = i == 0 ? thumb_active_color :
840 i == 1 ? thumb_inactive_color :
841 track_color;
842 color->pixel = 0;
843 // We sampled pixels across the full height of the image, ignoring a two
844 // pixel border. In some themes, the border has a completely different
845 // color which we do not want to factor into our average color computation.
847 // We now need to scale the colors from the 0..255 range, to the wider
848 // 0..65535 range, and we need to actually compute the average color; so,
849 // we divide by the total number of pixels in the sample.
850 color->red = components[0] * 65535 / (255 * (kHeight - 4));
851 color->green = components[1] * 65535 / (255 * (kHeight - 4));
852 color->blue = components[2] * 65535 / (255 * (kHeight - 4));
854 g_object_unref(pb);
856 g_object_unref(pm);
858 gtk_widget_destroy(window);
860 // Override any of the default colors with ones that were specified by the
861 // theme.
862 if (theme_thumb_active) {
863 *thumb_active_color = *theme_thumb_active;
864 gdk_color_free(theme_thumb_active);
867 if (theme_thumb_inactive) {
868 *thumb_inactive_color = *theme_thumb_inactive;
869 gdk_color_free(theme_thumb_inactive);
872 if (theme_trough_color) {
873 *track_color = *theme_trough_color;
874 gdk_color_free(theme_trough_color);
878 void Gtk2UI::LoadGtkValues() {
879 // TODO(erg): GtkThemeService had a comment here about having to muck with
880 // the raw Prefs object to remove prefs::kCurrentThemeImages or else we'd
881 // regress startup time. Figure out how to do that when we can't access the
882 // prefs system from here.
884 GtkStyle* frame_style = gtk_rc_get_style(fake_frame_);
886 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
887 SetThemeColorFromGtk(ThemeProperties::COLOR_CONTROL_BACKGROUND,
888 &window_style->bg[GTK_STATE_NORMAL]);
890 GdkColor toolbar_color = window_style->bg[GTK_STATE_NORMAL];
891 SetThemeColorFromGtk(ThemeProperties::COLOR_TOOLBAR, &toolbar_color);
893 GdkColor button_color = window_style->bg[GTK_STATE_SELECTED];
894 SetThemeTintFromGtk(ThemeProperties::TINT_BUTTONS, &button_color);
896 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
897 GdkColor label_color = label_style->fg[GTK_STATE_NORMAL];
898 SetThemeColorFromGtk(ThemeProperties::COLOR_TAB_TEXT, &label_color);
899 SetThemeColorFromGtk(ThemeProperties::COLOR_BOOKMARK_TEXT, &label_color);
900 SetThemeColorFromGtk(ThemeProperties::COLOR_STATUS_BAR_TEXT, &label_color);
902 UpdateDefaultFont(label_style->font_desc);
904 // Build the various icon tints.
905 GetNormalButtonTintHSL(&button_tint_);
906 GetNormalEntryForegroundHSL(&entry_tint_);
907 GetSelectedEntryForegroundHSL(&selected_entry_tint_);
908 GdkColor frame_color = BuildFrameColors(frame_style);
910 // The inactive frame color never occurs naturally in the theme, as it is a
911 // tinted version of |frame_color|. We generate another color based on the
912 // background tab color, with the lightness and saturation moved in the
913 // opposite direction. (We don't touch the hue, since there should be subtle
914 // hints of the color in the text.)
915 color_utils::HSL inactive_tab_text_hsl =
916 tints_[ThemeProperties::TINT_BACKGROUND_TAB];
917 if (inactive_tab_text_hsl.l < 0.5)
918 inactive_tab_text_hsl.l = kDarkInactiveLuminance;
919 else
920 inactive_tab_text_hsl.l = kLightInactiveLuminance;
922 if (inactive_tab_text_hsl.s < 0.5)
923 inactive_tab_text_hsl.s = kHeavyInactiveSaturation;
924 else
925 inactive_tab_text_hsl.s = kLightInactiveSaturation;
927 colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
928 color_utils::HSLToSkColor(inactive_tab_text_hsl, 255);
930 // We pick the text and background colors for the NTP out of the colors for a
931 // GtkEntry. We do this because GtkEntries background color is never the same
932 // as |toolbar_color|, is usually a white, and when it isn't a white,
933 // provides sufficient contrast to |toolbar_color|. Try this out with
934 // Darklooks, HighContrastInverse or ThinIce.
935 GtkStyle* entry_style = gtk_rc_get_style(fake_entry_.get());
936 GdkColor ntp_background = entry_style->base[GTK_STATE_NORMAL];
937 GdkColor ntp_foreground = entry_style->text[GTK_STATE_NORMAL];
938 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_BACKGROUND,
939 &ntp_background);
940 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_TEXT,
941 &ntp_foreground);
943 // The NTP header is the color that surrounds the current active thumbnail on
944 // the NTP, and acts as the border of the "Recent Links" box. It would be
945 // awesome if they were separated so we could use GetBorderColor() for the
946 // border around the "Recent Links" section, but matching the frame color is
947 // more important.
948 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_HEADER,
949 &frame_color);
950 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION,
951 &toolbar_color);
952 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_TEXT,
953 &label_color);
955 // Override the link color if the theme provides it.
956 const GdkColor* link_color = NULL;
957 gtk_widget_style_get(GTK_WIDGET(fake_window_),
958 "link-color", &link_color, NULL);
960 bool is_default_link_color = false;
961 if (!link_color) {
962 link_color = &kDefaultLinkColor;
963 is_default_link_color = true;
966 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK,
967 link_color);
968 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK_UNDERLINE,
969 link_color);
970 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK,
971 link_color);
972 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE,
973 link_color);
975 if (!is_default_link_color)
976 gdk_color_free(const_cast<GdkColor*>(link_color));
978 // Generate the colors that we pass to WebKit.
979 focus_ring_color_ = GdkColorToSkColor(frame_color);
981 GdkColor thumb_active_color, thumb_inactive_color, track_color;
982 Gtk2UI::GetScrollbarColors(&thumb_active_color,
983 &thumb_inactive_color,
984 &track_color);
985 thumb_active_color_ = GdkColorToSkColor(thumb_active_color);
986 thumb_inactive_color_ = GdkColorToSkColor(thumb_inactive_color);
987 track_color_ = GdkColorToSkColor(track_color);
989 // Some GTK themes only define the text selection colors on the GtkEntry
990 // class, so we need to use that for getting selection colors.
991 active_selection_bg_color_ =
992 GdkColorToSkColor(entry_style->base[GTK_STATE_SELECTED]);
993 active_selection_fg_color_ =
994 GdkColorToSkColor(entry_style->text[GTK_STATE_SELECTED]);
995 inactive_selection_bg_color_ =
996 GdkColorToSkColor(entry_style->base[GTK_STATE_ACTIVE]);
997 inactive_selection_fg_color_ =
998 GdkColorToSkColor(entry_style->text[GTK_STATE_ACTIVE]);
1001 GdkColor Gtk2UI::BuildFrameColors(GtkStyle* frame_style) {
1002 GdkColor* theme_frame = NULL;
1003 GdkColor* theme_inactive_frame = NULL;
1004 GdkColor* theme_incognito_frame = NULL;
1005 GdkColor* theme_incognito_inactive_frame = NULL;
1006 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
1007 "frame-color", &theme_frame,
1008 "inactive-frame-color", &theme_inactive_frame,
1009 "incognito-frame-color", &theme_incognito_frame,
1010 "incognito-inactive-frame-color",
1011 &theme_incognito_inactive_frame,
1012 NULL);
1014 GdkColor frame_color = BuildAndSetFrameColor(
1015 &frame_style->bg[GTK_STATE_SELECTED],
1016 theme_frame,
1017 kDefaultFrameShift,
1018 ThemeProperties::COLOR_FRAME,
1019 ThemeProperties::TINT_FRAME);
1020 if (theme_frame)
1021 gdk_color_free(theme_frame);
1022 SetThemeTintFromGtk(ThemeProperties::TINT_BACKGROUND_TAB, &frame_color);
1024 BuildAndSetFrameColor(
1025 &frame_style->bg[GTK_STATE_INSENSITIVE],
1026 theme_inactive_frame,
1027 kDefaultFrameShift,
1028 ThemeProperties::COLOR_FRAME_INACTIVE,
1029 ThemeProperties::TINT_FRAME_INACTIVE);
1030 if (theme_inactive_frame)
1031 gdk_color_free(theme_inactive_frame);
1033 BuildAndSetFrameColor(
1034 &frame_color,
1035 theme_incognito_frame,
1036 GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO),
1037 ThemeProperties::COLOR_FRAME_INCOGNITO,
1038 ThemeProperties::TINT_FRAME_INCOGNITO);
1039 if (theme_incognito_frame)
1040 gdk_color_free(theme_incognito_frame);
1042 BuildAndSetFrameColor(
1043 &frame_color,
1044 theme_incognito_inactive_frame,
1045 GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE),
1046 ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1047 ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE);
1048 if (theme_incognito_inactive_frame)
1049 gdk_color_free(theme_incognito_inactive_frame);
1051 return frame_color;
1054 void Gtk2UI::SetThemeColorFromGtk(int id, const GdkColor* color) {
1055 colors_[id] = GdkColorToSkColor(*color);
1058 void Gtk2UI::SetThemeTintFromGtk(int id, const GdkColor* color) {
1059 color_utils::HSL default_tint = GetDefaultTint(id);
1060 color_utils::HSL hsl;
1061 color_utils::SkColorToHSL(GdkColorToSkColor(*color), &hsl);
1063 if (default_tint.s != -1)
1064 hsl.s = default_tint.s;
1066 if (default_tint.l != -1)
1067 hsl.l = default_tint.l;
1069 tints_[id] = hsl;
1072 GdkColor Gtk2UI::BuildAndSetFrameColor(const GdkColor* base,
1073 const GdkColor* gtk_base,
1074 const color_utils::HSL& tint,
1075 int color_id,
1076 int tint_id) {
1077 GdkColor out_color = *base;
1078 if (gtk_base) {
1079 // The theme author specified a color to use, use it without modification.
1080 out_color = *gtk_base;
1081 } else {
1082 // Tint the basic color since this is a heuristic color instead of one
1083 // specified by the theme author.
1084 GdkColorHSLShift(tint, &out_color);
1086 SetThemeColorFromGtk(color_id, &out_color);
1087 SetThemeTintFromGtk(tint_id, &out_color);
1089 return out_color;
1092 SkBitmap Gtk2UI::GenerateGtkThemeBitmap(int id) const {
1093 switch (id) {
1094 case IDR_THEME_TOOLBAR: {
1095 GtkStyle* style = gtk_rc_get_style(fake_window_);
1096 GdkColor* color = &style->bg[GTK_STATE_NORMAL];
1097 SkBitmap bitmap;
1098 bitmap.allocN32Pixels(kToolbarImageWidth, kToolbarImageHeight);
1099 bitmap.eraseARGB(0xff, color->red >> 8, color->green >> 8,
1100 color->blue >> 8);
1101 return bitmap;
1103 case IDR_THEME_TAB_BACKGROUND:
1104 case IDR_THEME_TAB_BACKGROUND_DESKTOP:
1105 return GenerateTabImage(IDR_THEME_FRAME);
1106 case IDR_THEME_TAB_BACKGROUND_INCOGNITO:
1107 case IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP:
1108 return GenerateTabImage(IDR_THEME_FRAME_INCOGNITO);
1109 case IDR_FRAME:
1110 case IDR_THEME_FRAME:
1111 return GenerateFrameImage(ThemeProperties::COLOR_FRAME,
1112 "frame-gradient-color");
1113 case IDR_FRAME_INACTIVE:
1114 case IDR_THEME_FRAME_INACTIVE:
1115 return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INACTIVE,
1116 "inactive-frame-gradient-color");
1117 case IDR_THEME_FRAME_INCOGNITO:
1118 return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INCOGNITO,
1119 "incognito-frame-gradient-color");
1120 case IDR_THEME_FRAME_INCOGNITO_INACTIVE: {
1121 return GenerateFrameImage(
1122 ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1123 "incognito-inactive-frame-gradient-color");
1125 // Icons that sit inside the omnibox shouldn't receive TINT_BUTTONS and
1126 // instead should tint based on the foreground text entry color in GTK+
1127 // mode because some themes that try to be dark *and* light have very
1128 // different colors between the omnibox and the normal background area.
1129 // TODO(erg): Decide what to do about other icons that appear in the
1130 // omnibox, e.g. content settings icons.
1131 case IDR_OMNIBOX_CALCULATOR:
1132 case IDR_OMNIBOX_EXTENSION_APP:
1133 case IDR_OMNIBOX_HTTP:
1134 case IDR_OMNIBOX_SEARCH:
1135 case IDR_OMNIBOX_STAR:
1136 case IDR_OMNIBOX_TTS: {
1137 return GenerateTintedIcon(id, entry_tint_);
1139 // In GTK mode, the dark versions of the omnibox icons only ever appear in
1140 // the autocomplete popup and only against the current theme's GtkEntry
1141 // base[GTK_STATE_SELECTED] color, so tint the icons so they won't collide
1142 // with the selected color.
1143 case IDR_OMNIBOX_EXTENSION_APP_DARK:
1144 case IDR_OMNIBOX_HTTP_DARK:
1145 case IDR_OMNIBOX_SEARCH_DARK:
1146 case IDR_OMNIBOX_STAR_DARK:
1147 case IDR_OMNIBOX_TTS_DARK: {
1148 return GenerateTintedIcon(id, selected_entry_tint_);
1150 // In GTK mode, we need to manually render several icons.
1151 case IDR_BACK:
1152 case IDR_BACK_D:
1153 case IDR_FORWARD:
1154 case IDR_FORWARD_D:
1155 case IDR_HOME:
1156 case IDR_RELOAD:
1157 case IDR_RELOAD_D:
1158 case IDR_STOP:
1159 case IDR_STOP_D: {
1160 return GenerateGTKIcon(id);
1162 case IDR_TOOLBAR_BEZEL_HOVER:
1163 return GenerateToolbarBezel(GTK_STATE_PRELIGHT, IDR_TOOLBAR_BEZEL_HOVER);
1164 case IDR_TOOLBAR_BEZEL_PRESSED:
1165 return GenerateToolbarBezel(GTK_STATE_ACTIVE, IDR_TOOLBAR_BEZEL_PRESSED);
1166 default: {
1167 return GenerateTintedIcon(id, button_tint_);
1171 return SkBitmap();
1174 SkBitmap Gtk2UI::GenerateFrameImage(
1175 int color_id,
1176 const char* gradient_name) const {
1177 // We use two colors: the main color (passed in) and a lightened version of
1178 // that color (which is supposed to match the light gradient at the top of
1179 // several GTK+ themes, such as Ambiance, Clearlooks or Bluebird).
1180 ColorMap::const_iterator it = colors_.find(color_id);
1181 DCHECK(it != colors_.end());
1182 SkColor base = it->second;
1184 gfx::Canvas canvas(gfx::Size(kToolbarImageWidth, kToolbarImageHeight),
1185 1.0f, true);
1187 int gradient_size;
1188 GdkColor* gradient_top_color = NULL;
1189 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
1190 "frame-gradient-size", &gradient_size,
1191 gradient_name, &gradient_top_color,
1192 NULL);
1193 if (gradient_size) {
1194 SkColor lighter = gradient_top_color ?
1195 GdkColorToSkColor(*gradient_top_color) :
1196 color_utils::HSLShift(base, kGtkFrameShift);
1197 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1198 0, gradient_size, lighter, base);
1199 SkPaint paint;
1200 paint.setStyle(SkPaint::kFill_Style);
1201 paint.setAntiAlias(true);
1202 paint.setShader(shader.get());
1204 canvas.DrawRect(gfx::Rect(0, 0, kToolbarImageWidth, gradient_size), paint);
1207 if (gradient_top_color)
1208 gdk_color_free(gradient_top_color);
1210 canvas.FillRect(gfx::Rect(0, gradient_size, kToolbarImageWidth,
1211 kToolbarImageHeight - gradient_size), base);
1212 return canvas.ExtractImageRep().sk_bitmap();
1215 SkBitmap Gtk2UI::GenerateTabImage(int base_id) const {
1216 const SkBitmap* base_image = GetThemeImageNamed(base_id).ToSkBitmap();
1217 SkBitmap bg_tint = SkBitmapOperations::CreateHSLShiftedBitmap(
1218 *base_image, GetDefaultTint(ThemeProperties::TINT_BACKGROUND_TAB));
1219 return SkBitmapOperations::CreateTiledBitmap(
1220 bg_tint, 0, 0, bg_tint.width(), bg_tint.height());
1223 SkBitmap Gtk2UI::GenerateTintedIcon(
1224 int base_id,
1225 const color_utils::HSL& tint) const {
1226 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1227 return SkBitmapOperations::CreateHSLShiftedBitmap(
1228 rb.GetImageNamed(base_id).AsBitmap(), tint);
1231 SkBitmap Gtk2UI::GenerateGTKIcon(int base_id) const {
1232 const char* stock_id = NULL;
1233 GtkStateType gtk_state = GTK_STATE_NORMAL;
1234 for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i) {
1235 if (kGtkIcons[i].idr == base_id) {
1236 stock_id = kGtkIcons[i].stock_id;
1237 gtk_state = kGtkIcons[i].gtk_state;
1238 break;
1241 DCHECK(stock_id);
1243 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1244 SkBitmap default_bitmap = rb.GetImageNamed(base_id).AsBitmap();
1246 gtk_widget_ensure_style(fake_frame_);
1247 GtkStyle* style = gtk_widget_get_style(fake_frame_);
1248 GtkIconSet* icon_set = gtk_style_lookup_icon_set(style, stock_id);
1249 if (!icon_set)
1250 return default_bitmap;
1252 // Ask GTK to render the icon to a buffer, which we will steal from.
1253 GdkPixbuf* gdk_icon = gtk_icon_set_render_icon(
1254 icon_set,
1255 style,
1256 base::i18n::IsRTL() ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR,
1257 gtk_state,
1258 GTK_ICON_SIZE_SMALL_TOOLBAR,
1259 fake_frame_,
1260 NULL);
1262 if (!gdk_icon) {
1263 // This can theoretically happen if an icon theme doesn't provide a
1264 // specific image. This should realistically never happen, but I bet there
1265 // are some theme authors who don't reliably provide all icons.
1266 return default_bitmap;
1269 SkBitmap retval;
1270 retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1271 retval.eraseColor(0);
1273 const SkBitmap icon = GdkPixbufToImageSkia(gdk_icon);
1274 g_object_unref(gdk_icon);
1276 SkCanvas canvas(retval);
1278 if (gtk_state == GTK_STATE_ACTIVE || gtk_state == GTK_STATE_PRELIGHT) {
1279 SkBitmap border = DrawGtkButtonBorder(gtk_state,
1280 false,
1281 false,
1282 default_bitmap.width(),
1283 default_bitmap.height());
1284 canvas.drawBitmap(border, 0, 0);
1287 canvas.drawBitmap(icon,
1288 (default_bitmap.width() / 2) - (icon.width() / 2),
1289 (default_bitmap.height() / 2) - (icon.height() / 2));
1291 return retval;
1294 SkBitmap Gtk2UI::GenerateToolbarBezel(int gtk_state, int sizing_idr) const {
1295 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1296 SkBitmap default_bitmap =
1297 rb.GetImageNamed(sizing_idr).AsBitmap();
1299 SkBitmap retval;
1300 retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1301 retval.eraseColor(0);
1303 SkCanvas canvas(retval);
1304 SkBitmap border = DrawGtkButtonBorder(
1305 gtk_state,
1306 false,
1307 false,
1308 default_bitmap.width(),
1309 default_bitmap.height());
1310 canvas.drawBitmap(border, 0, 0);
1312 return retval;
1315 void Gtk2UI::GetNormalButtonTintHSL(color_utils::HSL* tint) const {
1316 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
1317 const GdkColor accent_gdk_color = window_style->bg[GTK_STATE_SELECTED];
1318 const GdkColor base_color = window_style->base[GTK_STATE_NORMAL];
1320 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
1321 const GdkColor text_color = label_style->fg[GTK_STATE_NORMAL];
1323 PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1326 void Gtk2UI::GetNormalEntryForegroundHSL(color_utils::HSL* tint) const {
1327 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
1328 const GdkColor accent_gdk_color = window_style->bg[GTK_STATE_SELECTED];
1330 GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1331 const GdkColor text_color = style->text[GTK_STATE_NORMAL];
1332 const GdkColor base_color = style->base[GTK_STATE_NORMAL];
1334 PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1337 void Gtk2UI::GetSelectedEntryForegroundHSL(color_utils::HSL* tint) const {
1338 // The simplest of all the tints. We just use the selected text in the entry
1339 // since the icons tinted this way will only be displayed against
1340 // base[GTK_STATE_SELECTED].
1341 GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1342 const GdkColor color = style->text[GTK_STATE_SELECTED];
1343 color_utils::SkColorToHSL(GdkColorToSkColor(color), tint);
1346 SkBitmap Gtk2UI::DrawGtkButtonBorder(int gtk_state,
1347 bool focused,
1348 bool call_to_action,
1349 int width,
1350 int height) const {
1351 // Create a temporary GTK button to snapshot
1352 GtkWidget* window = gtk_offscreen_window_new();
1353 GtkWidget* button = gtk_button_new();
1354 gtk_widget_set_size_request(button, width, height);
1355 gtk_container_add(GTK_CONTAINER(window), button);
1356 gtk_widget_realize(window);
1357 gtk_widget_realize(button);
1358 gtk_widget_show(button);
1359 gtk_widget_show(window);
1361 if (call_to_action)
1362 GTK_WIDGET_SET_FLAGS(button, GTK_HAS_DEFAULT);
1364 if (focused) {
1365 // We can't just use gtk_widget_grab_focus() here because that sets
1366 // gtk_widget_is_focus(), but not gtk_widget_has_focus(), which is what the
1367 // GtkButton's paint checks.
1368 GTK_WIDGET_SET_FLAGS(button, GTK_HAS_FOCUS);
1371 gtk_widget_set_state(button, static_cast<GtkStateType>(gtk_state));
1373 GdkPixmap* pixmap;
1375 // http://crbug.com/346740
1376 ANNOTATE_SCOPED_MEMORY_LEAK;
1377 pixmap = gtk_widget_get_snapshot(button, NULL);
1379 int w, h;
1380 gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &w, &h);
1381 DCHECK_EQ(w, width);
1382 DCHECK_EQ(h, height);
1384 // We render the Pixmap to a Pixbuf. This can be slow, as we're scrapping
1385 // bits from X.
1386 GdkColormap* colormap = gdk_drawable_get_colormap(pixmap);
1387 GdkPixbuf* pixbuf = gdk_pixbuf_get_from_drawable(NULL,
1388 GDK_DRAWABLE(pixmap),
1389 colormap,
1390 0, 0, 0, 0, w, h);
1392 // Finally, we convert our pixbuf into a type we can use.
1393 SkBitmap border = GdkPixbufToImageSkia(pixbuf);
1394 g_object_unref(pixbuf);
1395 g_object_unref(pixmap);
1396 gtk_widget_destroy(window);
1398 return border;
1401 void Gtk2UI::ClearAllThemeData() {
1402 gtk_images_.clear();
1405 void Gtk2UI::UpdateDefaultFont(const PangoFontDescription* desc) {
1406 // Use gfx::FontRenderParams to select a family and determine the rendering
1407 // settings.
1408 gfx::FontRenderParamsQuery query;
1409 query.families = base::SplitString(pango_font_description_get_family(desc),
1410 ",", base::TRIM_WHITESPACE,
1411 base::SPLIT_WANT_ALL);
1413 if (pango_font_description_get_size_is_absolute(desc)) {
1414 // If the size is absolute, it's specified in Pango units. There are
1415 // PANGO_SCALE Pango units in a device unit (pixel).
1416 const int size_pixels = pango_font_description_get_size(desc) / PANGO_SCALE;
1417 default_font_size_pixels_ = size_pixels;
1418 query.pixel_size = size_pixels;
1419 } else {
1420 // Non-absolute sizes are in points (again scaled by PANGO_SIZE).
1421 // Round the value when converting to pixels to match GTK's logic.
1422 const double size_points = pango_font_description_get_size(desc) /
1423 static_cast<double>(PANGO_SCALE);
1424 default_font_size_pixels_ = static_cast<int>(
1425 GetPixelsInPoint(device_scale_factor_) * size_points + 0.5);
1426 query.point_size = static_cast<int>(size_points);
1429 query.style = gfx::Font::NORMAL;
1430 // TODO(davemoore): Support weights other than bold?
1431 if (pango_font_description_get_weight(desc) == PANGO_WEIGHT_BOLD)
1432 query.style |= gfx::Font::BOLD;
1433 // TODO(davemoore): What about PANGO_STYLE_OBLIQUE?
1434 if (pango_font_description_get_style(desc) == PANGO_STYLE_ITALIC)
1435 query.style |= gfx::Font::ITALIC;
1437 default_font_render_params_ =
1438 gfx::GetFontRenderParams(query, &default_font_family_);
1439 default_font_style_ = query.style;
1442 void Gtk2UI::OnStyleSet(GtkWidget* widget, GtkStyle* previous_style) {
1443 ClearAllThemeData();
1444 LoadGtkValues();
1445 NativeThemeGtk2::instance()->NotifyObservers();
1448 void Gtk2UI::UpdateDeviceScaleFactor(float device_scale_factor) {
1449 device_scale_factor_ = device_scale_factor;
1450 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
1451 UpdateDefaultFont(label_style->font_desc);
1454 float Gtk2UI::GetDeviceScaleFactor() const {
1455 if (gfx::Display::HasForceDeviceScaleFactor())
1456 return gfx::Display::GetForcedDeviceScaleFactor();
1457 // Linux chrome does not support dynamnic scale factor change. Use the
1458 // value obtanied during startup. The value is rounded to 1 decimal, e.g.
1459 // to 1.4, for safety.
1460 static float device_scale_factor =
1461 roundf(GetGnomeTextScalingFactor() * 10) / 10;
1462 return device_scale_factor;
1465 } // namespace libgtk2ui
1467 views::LinuxUI* BuildGtk2UI() {
1468 return new libgtk2ui::Gtk2UI;