ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / ui / libgtk2ui / gtk2_ui.cc
blob5405a718ef1f540515ff20cf0e15580cd44a3d20
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 <set>
9 #include <pango/pango.h>
11 #include "base/command_line.h"
12 #include "base/debug/leak_annotations.h"
13 #include "base/environment.h"
14 #include "base/i18n/rtl.h"
15 #include "base/logging.h"
16 #include "base/nix/mime_util_xdg.h"
17 #include "base/nix/xdg_util.h"
18 #include "base/stl_util.h"
19 #include "base/strings/string_split.h"
20 #include "base/strings/stringprintf.h"
21 #include "chrome/browser/themes/theme_properties.h"
22 #include "chrome/browser/ui/libgtk2ui/app_indicator_icon.h"
23 #include "chrome/browser/ui/libgtk2ui/chrome_gtk_frame.h"
24 #include "chrome/browser/ui/libgtk2ui/gtk2_border.h"
25 #include "chrome/browser/ui/libgtk2ui/gtk2_event_loop.h"
26 #include "chrome/browser/ui/libgtk2ui/gtk2_key_bindings_handler.h"
27 #include "chrome/browser/ui/libgtk2ui/gtk2_signal_registrar.h"
28 #include "chrome/browser/ui/libgtk2ui/gtk2_status_icon.h"
29 #include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
30 #include "chrome/browser/ui/libgtk2ui/native_theme_gtk2.h"
31 #include "chrome/browser/ui/libgtk2ui/print_dialog_gtk2.h"
32 #include "chrome/browser/ui/libgtk2ui/printing_gtk2_util.h"
33 #include "chrome/browser/ui/libgtk2ui/select_file_dialog_impl.h"
34 #include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
35 #include "chrome/browser/ui/libgtk2ui/unity_service.h"
36 #include "chrome/browser/ui/libgtk2ui/x11_input_method_context_impl_gtk2.h"
37 #include "grit/components_scaled_resources.h"
38 #include "grit/theme_resources.h"
39 #include "printing/printing_context_linux.h"
40 #include "third_party/skia/include/core/SkBitmap.h"
41 #include "third_party/skia/include/core/SkCanvas.h"
42 #include "third_party/skia/include/core/SkColor.h"
43 #include "third_party/skia/include/core/SkShader.h"
44 #include "ui/base/resource/resource_bundle.h"
45 #include "ui/gfx/canvas.h"
46 #include "ui/gfx/geometry/rect.h"
47 #include "ui/gfx/geometry/size.h"
48 #include "ui/gfx/image/image.h"
49 #include "ui/gfx/skbitmap_operations.h"
50 #include "ui/gfx/skia_util.h"
51 #include "ui/resources/grit/ui_resources.h"
52 #include "ui/views/controls/button/label_button.h"
53 #include "ui/views/controls/button/label_button_border.h"
54 #include "ui/views/linux_ui/window_button_order_observer.h"
56 #if defined(USE_GCONF)
57 #include "chrome/browser/ui/libgtk2ui/gconf_listener.h"
58 #endif
60 // A minimized port of GtkThemeService into something that can provide colors
61 // and images for aura.
63 // TODO(erg): There's still a lot that needs ported or done for the first time:
65 // - Render and inject the omnibox background.
66 // - Make sure to test with a light on dark theme, too.
68 // Work around a header bug:
69 // linux/debian_wheezy_i386-sysroot/usr/include/linux/stddef.h redefines NULL
70 // to 0, which breaks -Wsentinel. Get back the normal definition of NULL.
71 // TODO(thakis): Remove this once we update sysroots.
72 #define __need_NULL
73 #include <stddef.h>
75 namespace libgtk2ui {
77 namespace {
79 struct GObjectDeleter {
80 void operator()(void* ptr) {
81 g_object_unref(ptr);
84 struct GtkIconInfoDeleter {
85 void operator()(GtkIconInfo* ptr) {
86 gtk_icon_info_free(ptr);
89 typedef scoped_ptr<GIcon, GObjectDeleter> ScopedGIcon;
90 typedef scoped_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo;
91 typedef scoped_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf;
93 // Prefix for app indicator ids
94 const char kAppIndicatorIdPrefix[] = "chrome_app_indicator_";
96 // Number of app indicators used (used as part of app-indicator id).
97 int indicators_count;
99 // The unknown content type.
100 const char* kUnknownContentType = "application/octet-stream";
102 // The size of the rendered toolbar image.
103 const int kToolbarImageWidth = 64;
104 const int kToolbarImageHeight = 128;
106 // How much to tint the GTK+ color lighter at the top of the window.
107 const color_utils::HSL kGtkFrameShift = { -1, -1, 0.58 };
109 // How much to tint the GTK+ color when an explicit frame color hasn't been
110 // specified.
111 const color_utils::HSL kDefaultFrameShift = { -1, -1, 0.4 };
113 // Values used as the new luminance and saturation values in the inactive tab
114 // text color.
115 const double kDarkInactiveLuminance = 0.85;
116 const double kLightInactiveLuminance = 0.15;
117 const double kHeavyInactiveSaturation = 0.7;
118 const double kLightInactiveSaturation = 0.3;
120 // Default color for links on the NTP when the GTK+ theme doesn't define a
121 // link color. Constant taken from gtklinkbutton.c.
122 const GdkColor kDefaultLinkColor = { 0, 0, 0, 0xeeee };
124 const int kSkiaToGDKMultiplier = 257;
126 // TODO(erg): ThemeService has a whole interface just for reading default
127 // constants. Figure out what to do with that more long term; for now, just
128 // copy the constants themselves here.
130 // Default tints.
131 const color_utils::HSL kDefaultTintButtons = { -1, -1, -1 };
132 const color_utils::HSL kDefaultTintFrame = { -1, -1, -1 };
133 const color_utils::HSL kDefaultTintFrameInactive = { -1, -1, 0.75f };
134 const color_utils::HSL kDefaultTintFrameIncognito = { -1, 0.2f, 0.35f };
135 const color_utils::HSL kDefaultTintFrameIncognitoInactive = { -1, 0.3f, 0.6f };
136 const color_utils::HSL kDefaultTintBackgroundTab = { -1, 0.5, 0.75 };
138 // A list of images that we provide while in gtk mode.
140 // TODO(erg): We list both the normal and *_DESKTOP versions of some of these
141 // images because in some contexts, we don't go through the
142 // chrome::MapThemeImage interface. That should be fixed, but tracking that
143 // down is Hard.
144 const int kThemeImages[] = {
145 IDR_THEME_TOOLBAR,
146 IDR_THEME_TAB_BACKGROUND,
147 IDR_THEME_TAB_BACKGROUND_DESKTOP,
148 IDR_THEME_TAB_BACKGROUND_INCOGNITO,
149 IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP,
150 IDR_FRAME,
151 IDR_FRAME_INACTIVE,
152 IDR_THEME_FRAME,
153 IDR_THEME_FRAME_INACTIVE,
154 IDR_THEME_FRAME_INCOGNITO,
155 IDR_THEME_FRAME_INCOGNITO_INACTIVE,
158 // A list of icons used in the autocomplete view that should be tinted to the
159 // current gtk theme selection color so they stand out against the GtkEntry's
160 // base color.
161 // TODO(erg): Decide what to do about other icons that appear in the omnibox,
162 // e.g. content settings icons.
163 const int kAutocompleteImages[] = {
164 IDR_OMNIBOX_EXTENSION_APP,
165 IDR_OMNIBOX_HTTP,
166 IDR_OMNIBOX_HTTP_DARK,
167 IDR_OMNIBOX_SEARCH,
168 IDR_OMNIBOX_SEARCH_DARK,
169 IDR_OMNIBOX_STAR,
170 IDR_OMNIBOX_STAR_DARK,
171 IDR_OMNIBOX_TTS,
172 IDR_OMNIBOX_TTS_DARK,
175 // This table converts button ids into a pair of gtk-stock id and state.
176 struct IDRGtkMapping {
177 int idr;
178 const char* stock_id;
179 GtkStateType gtk_state;
180 } const kGtkIcons[] = {
181 { IDR_BACK, GTK_STOCK_GO_BACK, GTK_STATE_NORMAL },
182 { IDR_BACK_D, GTK_STOCK_GO_BACK, GTK_STATE_INSENSITIVE },
184 { IDR_FORWARD, GTK_STOCK_GO_FORWARD, GTK_STATE_NORMAL },
185 { IDR_FORWARD_D, GTK_STOCK_GO_FORWARD, GTK_STATE_INSENSITIVE },
187 { IDR_HOME, GTK_STOCK_HOME, GTK_STATE_NORMAL },
189 { IDR_RELOAD, GTK_STOCK_REFRESH, GTK_STATE_NORMAL },
190 { IDR_RELOAD_D, GTK_STOCK_REFRESH, GTK_STATE_INSENSITIVE },
192 { IDR_STOP, GTK_STOCK_STOP, GTK_STATE_NORMAL },
193 { IDR_STOP_D, GTK_STOCK_STOP, GTK_STATE_INSENSITIVE },
196 // The image resources that will be tinted by the 'button' tint value.
197 const int kOtherToolbarButtonIDs[] = {
198 IDR_TOOLBAR_BEZEL_HOVER,
199 IDR_TOOLBAR_BEZEL_PRESSED,
200 IDR_BROWSER_ACTIONS_OVERFLOW,
201 IDR_THROBBER,
202 IDR_THROBBER_WAITING,
203 IDR_THROBBER_LIGHT,
205 // TODO(erg): The dropdown arrow should be tinted because we're injecting
206 // various background GTK colors, but the code that accesses them needs to be
207 // modified so that they ask their ui::ThemeProvider instead of the
208 // ResourceBundle. (i.e. in a light on dark theme, the dropdown arrow will be
209 // dark on dark)
210 IDR_MENU_DROPARROW
213 bool IsOverridableImage(int id) {
214 CR_DEFINE_STATIC_LOCAL(std::set<int>, images, ());
215 if (images.empty()) {
216 images.insert(kThemeImages, kThemeImages + arraysize(kThemeImages));
217 images.insert(kAutocompleteImages,
218 kAutocompleteImages + arraysize(kAutocompleteImages));
220 for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i)
221 images.insert(kGtkIcons[i].idr);
223 images.insert(kOtherToolbarButtonIDs,
224 kOtherToolbarButtonIDs + arraysize(kOtherToolbarButtonIDs));
227 return images.count(id) > 0;
230 // Picks a button tint from a set of background colors. While
231 // |accent_gdk_color| will usually be the same color through a theme, this
232 // function will get called with the normal GtkLabel |text_color|/GtkWindow
233 // |background_color| pair and the GtkEntry |text_color|/|background_color|
234 // pair. While 3/4 of the time the resulting tint will be the same, themes that
235 // have a dark window background (with light text) and a light text entry (with
236 // dark text) will get better icons with this separated out.
237 void PickButtonTintFromColors(const GdkColor& accent_gdk_color,
238 const GdkColor& text_color,
239 const GdkColor& background_color,
240 color_utils::HSL* tint) {
241 SkColor accent_color = GdkColorToSkColor(accent_gdk_color);
242 color_utils::HSL accent_tint;
243 color_utils::SkColorToHSL(accent_color, &accent_tint);
245 color_utils::HSL text_tint;
246 color_utils::SkColorToHSL(GdkColorToSkColor(text_color),
247 &text_tint);
249 color_utils::HSL background_tint;
250 color_utils::SkColorToHSL(GdkColorToSkColor(background_color),
251 &background_tint);
253 // If the accent color is gray, then our normal HSL tomfoolery will bring out
254 // whatever color is oddly dominant (for example, in rgb space [125, 128,
255 // 125] will tint green instead of gray). Slight differences (+/-10 (4%) to
256 // all color components) should be interpreted as this color being gray and
257 // we should switch into a special grayscale mode.
258 int rb_diff = abs(static_cast<int>(SkColorGetR(accent_color)) -
259 static_cast<int>(SkColorGetB(accent_color)));
260 int rg_diff = abs(static_cast<int>(SkColorGetR(accent_color)) -
261 static_cast<int>(SkColorGetG(accent_color)));
262 int bg_diff = abs(static_cast<int>(SkColorGetB(accent_color)) -
263 static_cast<int>(SkColorGetG(accent_color)));
264 if (rb_diff < 10 && rg_diff < 10 && bg_diff < 10) {
265 // Our accent is white/gray/black. Only the luminance of the accent color
266 // matters.
267 tint->h = -1;
269 // Use the saturation of the text.
270 tint->s = text_tint.s;
272 // Use the luminance of the accent color UNLESS there isn't enough
273 // luminance contrast between the accent color and the base color.
274 if (fabs(accent_tint.l - background_tint.l) > 0.3)
275 tint->l = accent_tint.l;
276 else
277 tint->l = text_tint.l;
278 } else {
279 // Our accent is a color.
280 tint->h = accent_tint.h;
282 // Don't modify the saturation; the amount of color doesn't matter.
283 tint->s = -1;
285 // If the text wants us to darken the icon, don't change the luminance (the
286 // icons are already dark enough). Otherwise, lighten the icon by no more
287 // than 0.9 since we don't want a pure-white icon even if the text is pure
288 // white.
289 if (text_tint.l < 0.5)
290 tint->l = -1;
291 else if (text_tint.l <= 0.9)
292 tint->l = text_tint.l;
293 else
294 tint->l = 0.9;
298 // Applies an HSL shift to a GdkColor (instead of an SkColor)
299 void GdkColorHSLShift(const color_utils::HSL& shift, GdkColor* frame_color) {
300 SkColor shifted = color_utils::HSLShift(
301 GdkColorToSkColor(*frame_color), shift);
303 frame_color->pixel = 0;
304 frame_color->red = SkColorGetR(shifted) * kSkiaToGDKMultiplier;
305 frame_color->green = SkColorGetG(shifted) * kSkiaToGDKMultiplier;
306 frame_color->blue = SkColorGetB(shifted) * kSkiaToGDKMultiplier;
309 // Copied Default blah sections from ThemeService.
310 color_utils::HSL GetDefaultTint(int id) {
311 switch (id) {
312 case ThemeProperties::TINT_FRAME:
313 return kDefaultTintFrame;
314 case ThemeProperties::TINT_FRAME_INACTIVE:
315 return kDefaultTintFrameInactive;
316 case ThemeProperties::TINT_FRAME_INCOGNITO:
317 return kDefaultTintFrameIncognito;
318 case ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE:
319 return kDefaultTintFrameIncognitoInactive;
320 case ThemeProperties::TINT_BUTTONS:
321 return kDefaultTintButtons;
322 case ThemeProperties::TINT_BACKGROUND_TAB:
323 return kDefaultTintBackgroundTab;
324 default:
325 color_utils::HSL result = {-1, -1, -1};
326 return result;
330 // Returns a gfx::FontRenderParams corresponding to GTK's configuration.
331 gfx::FontRenderParams GetGtkFontRenderParams() {
332 GtkSettings* gtk_settings = gtk_settings_get_default();
333 CHECK(gtk_settings);
334 gint antialias = 0;
335 gint hinting = 0;
336 gchar* hint_style = NULL;
337 gchar* rgba = NULL;
338 g_object_get(gtk_settings,
339 "gtk-xft-antialias", &antialias,
340 "gtk-xft-hinting", &hinting,
341 "gtk-xft-hintstyle", &hint_style,
342 "gtk-xft-rgba", &rgba,
343 NULL);
345 gfx::FontRenderParams params;
346 params.antialiasing = antialias != 0;
348 if (hinting == 0 || !hint_style || strcmp(hint_style, "hintnone") == 0) {
349 params.hinting = gfx::FontRenderParams::HINTING_NONE;
350 } else if (strcmp(hint_style, "hintslight") == 0) {
351 params.hinting = gfx::FontRenderParams::HINTING_SLIGHT;
352 } else if (strcmp(hint_style, "hintmedium") == 0) {
353 params.hinting = gfx::FontRenderParams::HINTING_MEDIUM;
354 } else if (strcmp(hint_style, "hintfull") == 0) {
355 params.hinting = gfx::FontRenderParams::HINTING_FULL;
356 } else {
357 LOG(WARNING) << "Unexpected gtk-xft-hintstyle \"" << hint_style << "\"";
358 params.hinting = gfx::FontRenderParams::HINTING_NONE;
361 if (!rgba || strcmp(rgba, "none") == 0) {
362 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
363 } else if (strcmp(rgba, "rgb") == 0) {
364 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB;
365 } else if (strcmp(rgba, "bgr") == 0) {
366 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR;
367 } else if (strcmp(rgba, "vrgb") == 0) {
368 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB;
369 } else if (strcmp(rgba, "vbgr") == 0) {
370 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR;
371 } else {
372 LOG(WARNING) << "Unexpected gtk-xft-rgba \"" << rgba << "\"";
373 params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
376 g_free(hint_style);
377 g_free(rgba);
379 return params;
382 // Queries GTK for its font DPI setting and returns the number of pixels in a
383 // point.
384 double GetPixelsInPoint() {
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 double dpi = (gtk_dpi > 0) ? gtk_dpi / 1024.0 : 96.0;
393 // There are 72 points in an inch.
394 return dpi / 72.0;
397 views::LinuxUI::NonClientMiddleClickAction GetDefaultMiddleClickAction() {
398 scoped_ptr<base::Environment> env(base::Environment::Create());
399 switch (base::nix::GetDesktopEnvironment(env.get())) {
400 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
401 // Starting with KDE 4.4, windows' titlebars can be dragged with the
402 // middle mouse button to create tab groups. We don't support that in
403 // Chrome, but at least avoid lowering windows in response to middle
404 // clicks to avoid surprising users who expect the KDE behavior.
405 return views::LinuxUI::MIDDLE_CLICK_ACTION_NONE;
406 default:
407 return views::LinuxUI::MIDDLE_CLICK_ACTION_LOWER;
411 } // namespace
413 Gtk2UI::Gtk2UI()
414 : default_font_size_pixels_(0),
415 default_font_style_(gfx::Font::NORMAL),
416 middle_click_action_(GetDefaultMiddleClickAction()) {
417 GtkInitFromCommandLine(*base::CommandLine::ForCurrentProcess());
420 void Gtk2UI::Initialize() {
421 signals_.reset(new Gtk2SignalRegistrar);
423 // Create our fake widgets.
424 fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
425 fake_frame_ = chrome_gtk_frame_new();
426 fake_label_.Own(gtk_label_new(""));
427 fake_entry_.Own(gtk_entry_new());
429 // Only realized widgets receive style-set notifications, which we need to
430 // broadcast new theme images and colors. Only realized widgets have style
431 // properties, too, which we query for some colors.
432 gtk_widget_realize(fake_frame_);
433 gtk_widget_realize(fake_window_);
435 signals_->Connect(fake_frame_, "style-set",
436 G_CALLBACK(&OnStyleSetThunk), this);
438 LoadGtkValues();
440 printing::PrintingContextLinux::SetCreatePrintDialogFunction(
441 &PrintDialogGtk2::CreatePrintDialog);
442 printing::PrintingContextLinux::SetPdfPaperSizeFunction(
443 &GetPdfPaperSizeDeviceUnitsGtk);
445 #if defined(USE_GCONF)
446 // We must build this after GTK gets initialized.
447 gconf_listener_.reset(new GConfListener(this));
448 #endif // defined(USE_GCONF)
450 indicators_count = 0;
452 // Instantiate the singleton instance of Gtk2EventLoop.
453 Gtk2EventLoop::GetInstance();
456 Gtk2UI::~Gtk2UI() {
457 gtk_widget_destroy(fake_window_);
458 gtk_widget_destroy(fake_frame_);
459 fake_label_.Destroy();
460 fake_entry_.Destroy();
462 ClearAllThemeData();
465 gfx::Image Gtk2UI::GetThemeImageNamed(int id) const {
466 // Try to get our cached version:
467 ImageCache::const_iterator it = gtk_images_.find(id);
468 if (it != gtk_images_.end())
469 return it->second;
471 if (IsOverridableImage(id)) {
472 gfx::Image image = gfx::Image(
473 gfx::ImageSkia::CreateFrom1xBitmap(GenerateGtkThemeBitmap(id)));
474 gtk_images_[id] = image;
475 return image;
478 return gfx::Image();
481 bool Gtk2UI::GetColor(int id, SkColor* color) const {
482 ColorMap::const_iterator it = colors_.find(id);
483 if (it != colors_.end()) {
484 *color = it->second;
485 return true;
488 return false;
491 bool Gtk2UI::HasCustomImage(int id) const {
492 return IsOverridableImage(id);
495 SkColor Gtk2UI::GetFocusRingColor() const {
496 return focus_ring_color_;
499 SkColor Gtk2UI::GetThumbActiveColor() const {
500 return thumb_active_color_;
503 SkColor Gtk2UI::GetThumbInactiveColor() const {
504 return thumb_inactive_color_;
507 SkColor Gtk2UI::GetTrackColor() const {
508 return track_color_;
511 SkColor Gtk2UI::GetActiveSelectionBgColor() const {
512 return active_selection_bg_color_;
515 SkColor Gtk2UI::GetActiveSelectionFgColor() const {
516 return active_selection_fg_color_;
519 SkColor Gtk2UI::GetInactiveSelectionBgColor() const {
520 return inactive_selection_bg_color_;
523 SkColor Gtk2UI::GetInactiveSelectionFgColor() const {
524 return inactive_selection_fg_color_;
527 double Gtk2UI::GetCursorBlinkInterval() const {
528 // From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is
529 // the default value for gtk-cursor-blink-time.
530 static const gint kGtkDefaultCursorBlinkTime = 1200;
532 // Dividing GTK's cursor blink cycle time (in milliseconds) by this value
533 // yields an appropriate value for
534 // content::RendererPreferences::caret_blink_interval. This matches the
535 // logic in the WebKit GTK port.
536 static const double kGtkCursorBlinkCycleFactor = 2000.0;
538 gint cursor_blink_time = kGtkDefaultCursorBlinkTime;
539 gboolean cursor_blink = TRUE;
540 g_object_get(gtk_settings_get_default(),
541 "gtk-cursor-blink-time", &cursor_blink_time,
542 "gtk-cursor-blink", &cursor_blink,
543 NULL);
544 return cursor_blink ? (cursor_blink_time / kGtkCursorBlinkCycleFactor) : 0.0;
547 ui::NativeTheme* Gtk2UI::GetNativeTheme(aura::Window* window) const {
548 ui::NativeTheme* native_theme_override = NULL;
549 if (!native_theme_overrider_.is_null())
550 native_theme_override = native_theme_overrider_.Run(window);
552 if (native_theme_override)
553 return native_theme_override;
555 return NativeThemeGtk2::instance();
558 void Gtk2UI::SetNativeThemeOverride(const NativeThemeGetter& callback) {
559 native_theme_overrider_ = callback;
562 bool Gtk2UI::GetDefaultUsesSystemTheme() const {
563 scoped_ptr<base::Environment> env(base::Environment::Create());
565 switch (base::nix::GetDesktopEnvironment(env.get())) {
566 case base::nix::DESKTOP_ENVIRONMENT_GNOME:
567 case base::nix::DESKTOP_ENVIRONMENT_UNITY:
568 case base::nix::DESKTOP_ENVIRONMENT_XFCE:
569 return true;
570 case base::nix::DESKTOP_ENVIRONMENT_KDE3:
571 case base::nix::DESKTOP_ENVIRONMENT_KDE4:
572 case base::nix::DESKTOP_ENVIRONMENT_OTHER:
573 return false;
575 // Unless GetDesktopEnvironment() badly misbehaves, this should never happen.
576 NOTREACHED();
577 return false;
580 void Gtk2UI::SetDownloadCount(int count) const {
581 if (unity::IsRunning())
582 unity::SetDownloadCount(count);
585 void Gtk2UI::SetProgressFraction(float percentage) const {
586 if (unity::IsRunning())
587 unity::SetProgressFraction(percentage);
590 bool Gtk2UI::IsStatusIconSupported() const {
591 return true;
594 scoped_ptr<views::StatusIconLinux> Gtk2UI::CreateLinuxStatusIcon(
595 const gfx::ImageSkia& image,
596 const base::string16& tool_tip) const {
597 if (AppIndicatorIcon::CouldOpen()) {
598 ++indicators_count;
599 return scoped_ptr<views::StatusIconLinux>(new AppIndicatorIcon(
600 base::StringPrintf("%s%d", kAppIndicatorIdPrefix, indicators_count),
601 image,
602 tool_tip));
603 } else {
604 return scoped_ptr<views::StatusIconLinux>(new Gtk2StatusIcon(
605 image, tool_tip));
609 gfx::Image Gtk2UI::GetIconForContentType(
610 const std::string& content_type,
611 int size) const {
612 // This call doesn't take a reference.
613 GtkIconTheme* theme = gtk_icon_theme_get_default();
615 std::string content_types[] = {
616 content_type, kUnknownContentType
619 for (size_t i = 0; i < arraysize(content_types); ++i) {
620 ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str()));
621 ScopedGtkIconInfo icon_info(
622 gtk_icon_theme_lookup_by_gicon(
623 theme, icon.get(), size,
624 static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE)));
625 if (!icon_info)
626 continue;
627 ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), NULL));
628 if (!pixbuf)
629 continue;
631 SkBitmap bitmap = GdkPixbufToImageSkia(pixbuf.get());
632 DCHECK_EQ(size, bitmap.width());
633 DCHECK_EQ(size, bitmap.height());
634 gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
635 image_skia.MakeThreadSafe();
636 return gfx::Image(image_skia);
638 return gfx::Image();
641 scoped_ptr<views::Border> Gtk2UI::CreateNativeBorder(
642 views::LabelButton* owning_button,
643 scoped_ptr<views::LabelButtonBorder> border) {
644 if (owning_button->GetNativeTheme() != NativeThemeGtk2::instance())
645 return border.Pass();
647 return make_scoped_ptr(new Gtk2Border(this, owning_button, border.Pass()));
650 void Gtk2UI::AddWindowButtonOrderObserver(
651 views::WindowButtonOrderObserver* observer) {
652 if (!leading_buttons_.empty() || !trailing_buttons_.empty()) {
653 observer->OnWindowButtonOrderingChange(leading_buttons_,
654 trailing_buttons_);
657 observer_list_.AddObserver(observer);
660 void Gtk2UI::RemoveWindowButtonOrderObserver(
661 views::WindowButtonOrderObserver* observer) {
662 observer_list_.RemoveObserver(observer);
665 void Gtk2UI::SetWindowButtonOrdering(
666 const std::vector<views::FrameButton>& leading_buttons,
667 const std::vector<views::FrameButton>& trailing_buttons) {
668 leading_buttons_ = leading_buttons;
669 trailing_buttons_ = trailing_buttons;
671 FOR_EACH_OBSERVER(views::WindowButtonOrderObserver, observer_list_,
672 OnWindowButtonOrderingChange(leading_buttons_,
673 trailing_buttons_));
676 void Gtk2UI::SetNonClientMiddleClickAction(NonClientMiddleClickAction action) {
677 middle_click_action_ = action;
680 scoped_ptr<ui::LinuxInputMethodContext> Gtk2UI::CreateInputMethodContext(
681 ui::LinuxInputMethodContextDelegate* delegate) const {
682 return scoped_ptr<ui::LinuxInputMethodContext>(
683 new X11InputMethodContextImplGtk2(delegate));
686 gfx::FontRenderParams Gtk2UI::GetDefaultFontRenderParams() const {
687 static gfx::FontRenderParams params = GetGtkFontRenderParams();
688 return params;
691 void Gtk2UI::GetDefaultFontDescription(
692 std::string* family_out,
693 int* size_pixels_out,
694 int* style_out,
695 gfx::FontRenderParams* params_out) const {
696 *family_out = default_font_family_;
697 *size_pixels_out = default_font_size_pixels_;
698 *style_out = default_font_style_;
699 *params_out = default_font_render_params_;
702 ui::SelectFileDialog* Gtk2UI::CreateSelectFileDialog(
703 ui::SelectFileDialog::Listener* listener,
704 ui::SelectFilePolicy* policy) const {
705 return SelectFileDialogImpl::Create(listener, policy);
708 bool Gtk2UI::UnityIsRunning() {
709 return unity::IsRunning();
712 views::LinuxUI::NonClientMiddleClickAction
713 Gtk2UI::GetNonClientMiddleClickAction() {
714 return middle_click_action_;
717 void Gtk2UI::NotifyWindowManagerStartupComplete() {
718 // TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO
719 // from http://standards.freedesktop.org/startup-notification-spec/ instead.
720 gdk_notify_startup_complete();
723 bool Gtk2UI::MatchEvent(const ui::Event& event,
724 std::vector<ui::TextEditCommandAuraLinux>* commands) {
725 // Ensure that we have a keyboard handler.
726 if (!key_bindings_handler_)
727 key_bindings_handler_.reset(new Gtk2KeyBindingsHandler);
729 return key_bindings_handler_->MatchEvent(event, commands);
732 void Gtk2UI::GetScrollbarColors(GdkColor* thumb_active_color,
733 GdkColor* thumb_inactive_color,
734 GdkColor* track_color) {
735 GdkColor* theme_thumb_active = NULL;
736 GdkColor* theme_thumb_inactive = NULL;
737 GdkColor* theme_trough_color = NULL;
738 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
739 "scrollbar-slider-prelight-color", &theme_thumb_active,
740 "scrollbar-slider-normal-color", &theme_thumb_inactive,
741 "scrollbar-trough-color", &theme_trough_color,
742 NULL);
744 // Ask the theme if the theme specifies all the scrollbar colors and short
745 // circuit the expensive painting/compositing if we have all of them.
746 if (theme_thumb_active && theme_thumb_inactive && theme_trough_color) {
747 *thumb_active_color = *theme_thumb_active;
748 *thumb_inactive_color = *theme_thumb_inactive;
749 *track_color = *theme_trough_color;
751 gdk_color_free(theme_thumb_active);
752 gdk_color_free(theme_thumb_inactive);
753 gdk_color_free(theme_trough_color);
754 return;
757 // Create window containing scrollbar elements
758 GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);
759 GtkWidget* fixed = gtk_fixed_new();
760 GtkWidget* scrollbar = gtk_hscrollbar_new(NULL);
761 gtk_container_add(GTK_CONTAINER(window), fixed);
762 gtk_container_add(GTK_CONTAINER(fixed), scrollbar);
763 gtk_widget_realize(window);
764 gtk_widget_realize(scrollbar);
766 // Draw scrollbar thumb part and track into offscreen image
767 const int kWidth = 100;
768 const int kHeight = 20;
769 GtkStyle* style = gtk_rc_get_style(scrollbar);
770 GdkWindow* gdk_window = gtk_widget_get_window(window);
771 GdkPixmap* pm = gdk_pixmap_new(gdk_window, kWidth, kHeight, -1);
772 GdkRectangle rect = { 0, 0, kWidth, kHeight };
773 unsigned char data[3 * kWidth * kHeight];
774 for (int i = 0; i < 3; ++i) {
775 if (i < 2) {
776 // Thumb part
777 gtk_paint_slider(style, pm,
778 i == 0 ? GTK_STATE_PRELIGHT : GTK_STATE_NORMAL,
779 GTK_SHADOW_OUT, &rect, scrollbar, "slider", 0, 0,
780 kWidth, kHeight, GTK_ORIENTATION_HORIZONTAL);
781 } else {
782 // Track
783 gtk_paint_box(style, pm, GTK_STATE_ACTIVE, GTK_SHADOW_IN, &rect,
784 scrollbar, "trough-upper", 0, 0, kWidth, kHeight);
786 GdkPixbuf* pb = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB,
787 FALSE, 8, kWidth, kHeight,
788 3 * kWidth, 0, 0);
789 gdk_pixbuf_get_from_drawable(pb, pm, NULL, 0, 0, 0, 0, kWidth, kHeight);
791 // Sample pixels
792 int components[3] = { 0 };
793 for (int y = 2; y < kHeight - 2; ++y) {
794 for (int c = 0; c < 3; ++c) {
795 // Sample a vertical slice of pixels at about one-thirds from the
796 // left edge. This allows us to avoid any fixed graphics that might be
797 // located at the edges or in the center of the scrollbar.
798 // Each pixel is made up of a red, green, and blue component; taking up
799 // a total of three bytes.
800 components[c] += data[3 * (kWidth / 3 + y * kWidth) + c];
803 GdkColor* color = i == 0 ? thumb_active_color :
804 i == 1 ? thumb_inactive_color :
805 track_color;
806 color->pixel = 0;
807 // We sampled pixels across the full height of the image, ignoring a two
808 // pixel border. In some themes, the border has a completely different
809 // color which we do not want to factor into our average color computation.
811 // We now need to scale the colors from the 0..255 range, to the wider
812 // 0..65535 range, and we need to actually compute the average color; so,
813 // we divide by the total number of pixels in the sample.
814 color->red = components[0] * 65535 / (255 * (kHeight - 4));
815 color->green = components[1] * 65535 / (255 * (kHeight - 4));
816 color->blue = components[2] * 65535 / (255 * (kHeight - 4));
818 g_object_unref(pb);
820 g_object_unref(pm);
822 gtk_widget_destroy(window);
824 // Override any of the default colors with ones that were specified by the
825 // theme.
826 if (theme_thumb_active) {
827 *thumb_active_color = *theme_thumb_active;
828 gdk_color_free(theme_thumb_active);
831 if (theme_thumb_inactive) {
832 *thumb_inactive_color = *theme_thumb_inactive;
833 gdk_color_free(theme_thumb_inactive);
836 if (theme_trough_color) {
837 *track_color = *theme_trough_color;
838 gdk_color_free(theme_trough_color);
842 void Gtk2UI::LoadGtkValues() {
843 // TODO(erg): GtkThemeService had a comment here about having to muck with
844 // the raw Prefs object to remove prefs::kCurrentThemeImages or else we'd
845 // regress startup time. Figure out how to do that when we can't access the
846 // prefs system from here.
848 GtkStyle* frame_style = gtk_rc_get_style(fake_frame_);
850 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
851 SetThemeColorFromGtk(ThemeProperties::COLOR_CONTROL_BACKGROUND,
852 &window_style->bg[GTK_STATE_NORMAL]);
854 GdkColor toolbar_color = window_style->bg[GTK_STATE_NORMAL];
855 SetThemeColorFromGtk(ThemeProperties::COLOR_TOOLBAR, &toolbar_color);
857 GdkColor button_color = window_style->bg[GTK_STATE_SELECTED];
858 SetThemeTintFromGtk(ThemeProperties::TINT_BUTTONS, &button_color);
860 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
861 GdkColor label_color = label_style->fg[GTK_STATE_NORMAL];
862 SetThemeColorFromGtk(ThemeProperties::COLOR_TAB_TEXT, &label_color);
863 SetThemeColorFromGtk(ThemeProperties::COLOR_BOOKMARK_TEXT, &label_color);
864 SetThemeColorFromGtk(ThemeProperties::COLOR_STATUS_BAR_TEXT, &label_color);
866 UpdateDefaultFont(label_style->font_desc);
868 // Build the various icon tints.
869 GetNormalButtonTintHSL(&button_tint_);
870 GetNormalEntryForegroundHSL(&entry_tint_);
871 GetSelectedEntryForegroundHSL(&selected_entry_tint_);
872 GdkColor frame_color = BuildFrameColors(frame_style);
874 // The inactive frame color never occurs naturally in the theme, as it is a
875 // tinted version of |frame_color|. We generate another color based on the
876 // background tab color, with the lightness and saturation moved in the
877 // opposite direction. (We don't touch the hue, since there should be subtle
878 // hints of the color in the text.)
879 color_utils::HSL inactive_tab_text_hsl =
880 tints_[ThemeProperties::TINT_BACKGROUND_TAB];
881 if (inactive_tab_text_hsl.l < 0.5)
882 inactive_tab_text_hsl.l = kDarkInactiveLuminance;
883 else
884 inactive_tab_text_hsl.l = kLightInactiveLuminance;
886 if (inactive_tab_text_hsl.s < 0.5)
887 inactive_tab_text_hsl.s = kHeavyInactiveSaturation;
888 else
889 inactive_tab_text_hsl.s = kLightInactiveSaturation;
891 colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
892 color_utils::HSLToSkColor(inactive_tab_text_hsl, 255);
894 // We pick the text and background colors for the NTP out of the colors for a
895 // GtkEntry. We do this because GtkEntries background color is never the same
896 // as |toolbar_color|, is usually a white, and when it isn't a white,
897 // provides sufficient contrast to |toolbar_color|. Try this out with
898 // Darklooks, HighContrastInverse or ThinIce.
899 GtkStyle* entry_style = gtk_rc_get_style(fake_entry_.get());
900 GdkColor ntp_background = entry_style->base[GTK_STATE_NORMAL];
901 GdkColor ntp_foreground = entry_style->text[GTK_STATE_NORMAL];
902 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_BACKGROUND,
903 &ntp_background);
904 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_TEXT,
905 &ntp_foreground);
907 // The NTP header is the color that surrounds the current active thumbnail on
908 // the NTP, and acts as the border of the "Recent Links" box. It would be
909 // awesome if they were separated so we could use GetBorderColor() for the
910 // border around the "Recent Links" section, but matching the frame color is
911 // more important.
912 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_HEADER,
913 &frame_color);
914 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION,
915 &toolbar_color);
916 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_TEXT,
917 &label_color);
919 // Override the link color if the theme provides it.
920 const GdkColor* link_color = NULL;
921 gtk_widget_style_get(GTK_WIDGET(fake_window_),
922 "link-color", &link_color, NULL);
924 bool is_default_link_color = false;
925 if (!link_color) {
926 link_color = &kDefaultLinkColor;
927 is_default_link_color = true;
930 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK,
931 link_color);
932 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK_UNDERLINE,
933 link_color);
934 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK,
935 link_color);
936 SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE,
937 link_color);
939 if (!is_default_link_color)
940 gdk_color_free(const_cast<GdkColor*>(link_color));
942 // Generate the colors that we pass to WebKit.
943 focus_ring_color_ = GdkColorToSkColor(frame_color);
945 GdkColor thumb_active_color, thumb_inactive_color, track_color;
946 Gtk2UI::GetScrollbarColors(&thumb_active_color,
947 &thumb_inactive_color,
948 &track_color);
949 thumb_active_color_ = GdkColorToSkColor(thumb_active_color);
950 thumb_inactive_color_ = GdkColorToSkColor(thumb_inactive_color);
951 track_color_ = GdkColorToSkColor(track_color);
953 // Some GTK themes only define the text selection colors on the GtkEntry
954 // class, so we need to use that for getting selection colors.
955 active_selection_bg_color_ =
956 GdkColorToSkColor(entry_style->base[GTK_STATE_SELECTED]);
957 active_selection_fg_color_ =
958 GdkColorToSkColor(entry_style->text[GTK_STATE_SELECTED]);
959 inactive_selection_bg_color_ =
960 GdkColorToSkColor(entry_style->base[GTK_STATE_ACTIVE]);
961 inactive_selection_fg_color_ =
962 GdkColorToSkColor(entry_style->text[GTK_STATE_ACTIVE]);
965 GdkColor Gtk2UI::BuildFrameColors(GtkStyle* frame_style) {
966 GdkColor* theme_frame = NULL;
967 GdkColor* theme_inactive_frame = NULL;
968 GdkColor* theme_incognito_frame = NULL;
969 GdkColor* theme_incognito_inactive_frame = NULL;
970 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
971 "frame-color", &theme_frame,
972 "inactive-frame-color", &theme_inactive_frame,
973 "incognito-frame-color", &theme_incognito_frame,
974 "incognito-inactive-frame-color",
975 &theme_incognito_inactive_frame,
976 NULL);
978 GdkColor frame_color = BuildAndSetFrameColor(
979 &frame_style->bg[GTK_STATE_SELECTED],
980 theme_frame,
981 kDefaultFrameShift,
982 ThemeProperties::COLOR_FRAME,
983 ThemeProperties::TINT_FRAME);
984 if (theme_frame)
985 gdk_color_free(theme_frame);
986 SetThemeTintFromGtk(ThemeProperties::TINT_BACKGROUND_TAB, &frame_color);
988 BuildAndSetFrameColor(
989 &frame_style->bg[GTK_STATE_INSENSITIVE],
990 theme_inactive_frame,
991 kDefaultFrameShift,
992 ThemeProperties::COLOR_FRAME_INACTIVE,
993 ThemeProperties::TINT_FRAME_INACTIVE);
994 if (theme_inactive_frame)
995 gdk_color_free(theme_inactive_frame);
997 BuildAndSetFrameColor(
998 &frame_color,
999 theme_incognito_frame,
1000 GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO),
1001 ThemeProperties::COLOR_FRAME_INCOGNITO,
1002 ThemeProperties::TINT_FRAME_INCOGNITO);
1003 if (theme_incognito_frame)
1004 gdk_color_free(theme_incognito_frame);
1006 BuildAndSetFrameColor(
1007 &frame_color,
1008 theme_incognito_inactive_frame,
1009 GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE),
1010 ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1011 ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE);
1012 if (theme_incognito_inactive_frame)
1013 gdk_color_free(theme_incognito_inactive_frame);
1015 return frame_color;
1018 void Gtk2UI::SetThemeColorFromGtk(int id, const GdkColor* color) {
1019 colors_[id] = GdkColorToSkColor(*color);
1022 void Gtk2UI::SetThemeTintFromGtk(int id, const GdkColor* color) {
1023 color_utils::HSL default_tint = GetDefaultTint(id);
1024 color_utils::HSL hsl;
1025 color_utils::SkColorToHSL(GdkColorToSkColor(*color), &hsl);
1027 if (default_tint.s != -1)
1028 hsl.s = default_tint.s;
1030 if (default_tint.l != -1)
1031 hsl.l = default_tint.l;
1033 tints_[id] = hsl;
1036 GdkColor Gtk2UI::BuildAndSetFrameColor(const GdkColor* base,
1037 const GdkColor* gtk_base,
1038 const color_utils::HSL& tint,
1039 int color_id,
1040 int tint_id) {
1041 GdkColor out_color = *base;
1042 if (gtk_base) {
1043 // The theme author specified a color to use, use it without modification.
1044 out_color = *gtk_base;
1045 } else {
1046 // Tint the basic color since this is a heuristic color instead of one
1047 // specified by the theme author.
1048 GdkColorHSLShift(tint, &out_color);
1050 SetThemeColorFromGtk(color_id, &out_color);
1051 SetThemeTintFromGtk(tint_id, &out_color);
1053 return out_color;
1056 SkBitmap Gtk2UI::GenerateGtkThemeBitmap(int id) const {
1057 switch (id) {
1058 case IDR_THEME_TOOLBAR: {
1059 GtkStyle* style = gtk_rc_get_style(fake_window_);
1060 GdkColor* color = &style->bg[GTK_STATE_NORMAL];
1061 SkBitmap bitmap;
1062 bitmap.allocN32Pixels(kToolbarImageWidth, kToolbarImageHeight);
1063 bitmap.eraseARGB(0xff, color->red >> 8, color->green >> 8,
1064 color->blue >> 8);
1065 return bitmap;
1067 case IDR_THEME_TAB_BACKGROUND:
1068 case IDR_THEME_TAB_BACKGROUND_DESKTOP:
1069 return GenerateTabImage(IDR_THEME_FRAME);
1070 case IDR_THEME_TAB_BACKGROUND_INCOGNITO:
1071 case IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP:
1072 return GenerateTabImage(IDR_THEME_FRAME_INCOGNITO);
1073 case IDR_FRAME:
1074 case IDR_THEME_FRAME:
1075 return GenerateFrameImage(ThemeProperties::COLOR_FRAME,
1076 "frame-gradient-color");
1077 case IDR_FRAME_INACTIVE:
1078 case IDR_THEME_FRAME_INACTIVE:
1079 return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INACTIVE,
1080 "inactive-frame-gradient-color");
1081 case IDR_THEME_FRAME_INCOGNITO:
1082 return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INCOGNITO,
1083 "incognito-frame-gradient-color");
1084 case IDR_THEME_FRAME_INCOGNITO_INACTIVE: {
1085 return GenerateFrameImage(
1086 ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1087 "incognito-inactive-frame-gradient-color");
1089 // Icons that sit inside the omnibox shouldn't receive TINT_BUTTONS and
1090 // instead should tint based on the foreground text entry color in GTK+
1091 // mode because some themes that try to be dark *and* light have very
1092 // different colors between the omnibox and the normal background area.
1093 // TODO(erg): Decide what to do about other icons that appear in the
1094 // omnibox, e.g. content settings icons.
1095 case IDR_OMNIBOX_EXTENSION_APP:
1096 case IDR_OMNIBOX_HTTP:
1097 case IDR_OMNIBOX_SEARCH:
1098 case IDR_OMNIBOX_STAR:
1099 case IDR_OMNIBOX_TTS: {
1100 return GenerateTintedIcon(id, entry_tint_);
1102 // In GTK mode, the dark versions of the omnibox icons only ever appear in
1103 // the autocomplete popup and only against the current theme's GtkEntry
1104 // base[GTK_STATE_SELECTED] color, so tint the icons so they won't collide
1105 // with the selected color.
1106 case IDR_OMNIBOX_EXTENSION_APP_DARK:
1107 case IDR_OMNIBOX_HTTP_DARK:
1108 case IDR_OMNIBOX_SEARCH_DARK:
1109 case IDR_OMNIBOX_STAR_DARK:
1110 case IDR_OMNIBOX_TTS_DARK: {
1111 return GenerateTintedIcon(id, selected_entry_tint_);
1113 // In GTK mode, we need to manually render several icons.
1114 case IDR_BACK:
1115 case IDR_BACK_D:
1116 case IDR_FORWARD:
1117 case IDR_FORWARD_D:
1118 case IDR_HOME:
1119 case IDR_RELOAD:
1120 case IDR_RELOAD_D:
1121 case IDR_STOP:
1122 case IDR_STOP_D: {
1123 return GenerateGTKIcon(id);
1125 case IDR_TOOLBAR_BEZEL_HOVER:
1126 return GenerateToolbarBezel(GTK_STATE_PRELIGHT, IDR_TOOLBAR_BEZEL_HOVER);
1127 case IDR_TOOLBAR_BEZEL_PRESSED:
1128 return GenerateToolbarBezel(GTK_STATE_ACTIVE, IDR_TOOLBAR_BEZEL_PRESSED);
1129 default: {
1130 return GenerateTintedIcon(id, button_tint_);
1134 return SkBitmap();
1137 SkBitmap Gtk2UI::GenerateFrameImage(
1138 int color_id,
1139 const char* gradient_name) const {
1140 // We use two colors: the main color (passed in) and a lightened version of
1141 // that color (which is supposed to match the light gradient at the top of
1142 // several GTK+ themes, such as Ambiance, Clearlooks or Bluebird).
1143 ColorMap::const_iterator it = colors_.find(color_id);
1144 DCHECK(it != colors_.end());
1145 SkColor base = it->second;
1147 gfx::Canvas canvas(gfx::Size(kToolbarImageWidth, kToolbarImageHeight),
1148 1.0f, true);
1150 int gradient_size;
1151 GdkColor* gradient_top_color = NULL;
1152 gtk_widget_style_get(GTK_WIDGET(fake_frame_),
1153 "frame-gradient-size", &gradient_size,
1154 gradient_name, &gradient_top_color,
1155 NULL);
1156 if (gradient_size) {
1157 SkColor lighter = gradient_top_color ?
1158 GdkColorToSkColor(*gradient_top_color) :
1159 color_utils::HSLShift(base, kGtkFrameShift);
1160 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1161 0, gradient_size, lighter, base);
1162 SkPaint paint;
1163 paint.setStyle(SkPaint::kFill_Style);
1164 paint.setAntiAlias(true);
1165 paint.setShader(shader.get());
1167 canvas.DrawRect(gfx::Rect(0, 0, kToolbarImageWidth, gradient_size), paint);
1170 if (gradient_top_color)
1171 gdk_color_free(gradient_top_color);
1173 canvas.FillRect(gfx::Rect(0, gradient_size, kToolbarImageWidth,
1174 kToolbarImageHeight - gradient_size), base);
1175 return canvas.ExtractImageRep().sk_bitmap();
1178 SkBitmap Gtk2UI::GenerateTabImage(int base_id) const {
1179 const SkBitmap* base_image = GetThemeImageNamed(base_id).ToSkBitmap();
1180 SkBitmap bg_tint = SkBitmapOperations::CreateHSLShiftedBitmap(
1181 *base_image, GetDefaultTint(ThemeProperties::TINT_BACKGROUND_TAB));
1182 return SkBitmapOperations::CreateTiledBitmap(
1183 bg_tint, 0, 0, bg_tint.width(), bg_tint.height());
1186 SkBitmap Gtk2UI::GenerateTintedIcon(
1187 int base_id,
1188 const color_utils::HSL& tint) const {
1189 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1190 return SkBitmapOperations::CreateHSLShiftedBitmap(
1191 rb.GetImageNamed(base_id).AsBitmap(), tint);
1194 SkBitmap Gtk2UI::GenerateGTKIcon(int base_id) const {
1195 const char* stock_id = NULL;
1196 GtkStateType gtk_state = GTK_STATE_NORMAL;
1197 for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i) {
1198 if (kGtkIcons[i].idr == base_id) {
1199 stock_id = kGtkIcons[i].stock_id;
1200 gtk_state = kGtkIcons[i].gtk_state;
1201 break;
1204 DCHECK(stock_id);
1206 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1207 SkBitmap default_bitmap = rb.GetImageNamed(base_id).AsBitmap();
1209 gtk_widget_ensure_style(fake_frame_);
1210 GtkStyle* style = gtk_widget_get_style(fake_frame_);
1211 GtkIconSet* icon_set = gtk_style_lookup_icon_set(style, stock_id);
1212 if (!icon_set)
1213 return default_bitmap;
1215 // Ask GTK to render the icon to a buffer, which we will steal from.
1216 GdkPixbuf* gdk_icon = gtk_icon_set_render_icon(
1217 icon_set,
1218 style,
1219 base::i18n::IsRTL() ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR,
1220 gtk_state,
1221 GTK_ICON_SIZE_SMALL_TOOLBAR,
1222 fake_frame_,
1223 NULL);
1225 if (!gdk_icon) {
1226 // This can theoretically happen if an icon theme doesn't provide a
1227 // specific image. This should realistically never happen, but I bet there
1228 // are some theme authors who don't reliably provide all icons.
1229 return default_bitmap;
1232 SkBitmap retval;
1233 retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1234 retval.eraseColor(0);
1236 const SkBitmap icon = GdkPixbufToImageSkia(gdk_icon);
1237 g_object_unref(gdk_icon);
1239 SkCanvas canvas(retval);
1241 if (gtk_state == GTK_STATE_ACTIVE || gtk_state == GTK_STATE_PRELIGHT) {
1242 SkBitmap border = DrawGtkButtonBorder(gtk_state,
1243 false,
1244 false,
1245 default_bitmap.width(),
1246 default_bitmap.height());
1247 canvas.drawBitmap(border, 0, 0);
1250 canvas.drawBitmap(icon,
1251 (default_bitmap.width() / 2) - (icon.width() / 2),
1252 (default_bitmap.height() / 2) - (icon.height() / 2));
1254 return retval;
1257 SkBitmap Gtk2UI::GenerateToolbarBezel(int gtk_state, int sizing_idr) const {
1258 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1259 SkBitmap default_bitmap =
1260 rb.GetImageNamed(sizing_idr).AsBitmap();
1262 SkBitmap retval;
1263 retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1264 retval.eraseColor(0);
1266 SkCanvas canvas(retval);
1267 SkBitmap border = DrawGtkButtonBorder(
1268 gtk_state,
1269 false,
1270 false,
1271 default_bitmap.width(),
1272 default_bitmap.height());
1273 canvas.drawBitmap(border, 0, 0);
1275 return retval;
1278 void Gtk2UI::GetNormalButtonTintHSL(color_utils::HSL* tint) const {
1279 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
1280 const GdkColor accent_gdk_color = window_style->bg[GTK_STATE_SELECTED];
1281 const GdkColor base_color = window_style->base[GTK_STATE_NORMAL];
1283 GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
1284 const GdkColor text_color = label_style->fg[GTK_STATE_NORMAL];
1286 PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1289 void Gtk2UI::GetNormalEntryForegroundHSL(color_utils::HSL* tint) const {
1290 GtkStyle* window_style = gtk_rc_get_style(fake_window_);
1291 const GdkColor accent_gdk_color = window_style->bg[GTK_STATE_SELECTED];
1293 GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1294 const GdkColor text_color = style->text[GTK_STATE_NORMAL];
1295 const GdkColor base_color = style->base[GTK_STATE_NORMAL];
1297 PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1300 void Gtk2UI::GetSelectedEntryForegroundHSL(color_utils::HSL* tint) const {
1301 // The simplest of all the tints. We just use the selected text in the entry
1302 // since the icons tinted this way will only be displayed against
1303 // base[GTK_STATE_SELECTED].
1304 GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1305 const GdkColor color = style->text[GTK_STATE_SELECTED];
1306 color_utils::SkColorToHSL(GdkColorToSkColor(color), tint);
1309 SkBitmap Gtk2UI::DrawGtkButtonBorder(int gtk_state,
1310 bool focused,
1311 bool call_to_action,
1312 int width,
1313 int height) const {
1314 // Create a temporary GTK button to snapshot
1315 GtkWidget* window = gtk_offscreen_window_new();
1316 GtkWidget* button = gtk_button_new();
1317 gtk_widget_set_size_request(button, width, height);
1318 gtk_container_add(GTK_CONTAINER(window), button);
1319 gtk_widget_realize(window);
1320 gtk_widget_realize(button);
1321 gtk_widget_show(button);
1322 gtk_widget_show(window);
1324 if (call_to_action)
1325 GTK_WIDGET_SET_FLAGS(button, GTK_HAS_DEFAULT);
1327 if (focused) {
1328 // We can't just use gtk_widget_grab_focus() here because that sets
1329 // gtk_widget_is_focus(), but not gtk_widget_has_focus(), which is what the
1330 // GtkButton's paint checks.
1331 GTK_WIDGET_SET_FLAGS(button, GTK_HAS_FOCUS);
1334 gtk_widget_set_state(button, static_cast<GtkStateType>(gtk_state));
1336 GdkPixmap* pixmap;
1338 // http://crbug.com/346740
1339 ANNOTATE_SCOPED_MEMORY_LEAK;
1340 pixmap = gtk_widget_get_snapshot(button, NULL);
1342 int w, h;
1343 gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &w, &h);
1344 DCHECK_EQ(w, width);
1345 DCHECK_EQ(h, height);
1347 // We render the Pixmap to a Pixbuf. This can be slow, as we're scrapping
1348 // bits from X.
1349 GdkColormap* colormap = gdk_drawable_get_colormap(pixmap);
1350 GdkPixbuf* pixbuf = gdk_pixbuf_get_from_drawable(NULL,
1351 GDK_DRAWABLE(pixmap),
1352 colormap,
1353 0, 0, 0, 0, w, h);
1355 // Finally, we convert our pixbuf into a type we can use.
1356 SkBitmap border = GdkPixbufToImageSkia(pixbuf);
1357 g_object_unref(pixbuf);
1358 g_object_unref(pixmap);
1359 gtk_widget_destroy(window);
1361 return border;
1364 void Gtk2UI::ClearAllThemeData() {
1365 gtk_images_.clear();
1368 void Gtk2UI::UpdateDefaultFont(const PangoFontDescription* desc) {
1369 // Use gfx::FontRenderParams to select a family and determine the rendering
1370 // settings.
1371 gfx::FontRenderParamsQuery query(false /* for_web_contents */);
1372 base::SplitString(pango_font_description_get_family(desc), ',',
1373 &query.families);
1375 if (pango_font_description_get_size_is_absolute(desc)) {
1376 // If the size is absolute, it's specified in Pango units. There are
1377 // PANGO_SCALE Pango units in a device unit (pixel).
1378 const int size_pixels = pango_font_description_get_size(desc) / PANGO_SCALE;
1379 default_font_size_pixels_ = size_pixels;
1380 query.pixel_size = size_pixels;
1381 } else {
1382 // Non-absolute sizes are in points (again scaled by PANGO_SIZE).
1383 // Round the value when converting to pixels to match GTK's logic.
1384 const double size_points = pango_font_description_get_size(desc) /
1385 static_cast<double>(PANGO_SCALE);
1386 default_font_size_pixels_ = static_cast<int>(
1387 GetPixelsInPoint() * size_points + 0.5);
1388 query.point_size = static_cast<int>(size_points);
1391 query.style = gfx::Font::NORMAL;
1392 // TODO(davemoore): Support weights other than bold?
1393 if (pango_font_description_get_weight(desc) == PANGO_WEIGHT_BOLD)
1394 query.style |= gfx::Font::BOLD;
1395 // TODO(davemoore): What about PANGO_STYLE_OBLIQUE?
1396 if (pango_font_description_get_style(desc) == PANGO_STYLE_ITALIC)
1397 query.style |= gfx::Font::ITALIC;
1399 default_font_render_params_ =
1400 gfx::GetFontRenderParams(query, &default_font_family_);
1401 default_font_style_ = query.style;
1404 void Gtk2UI::OnStyleSet(GtkWidget* widget, GtkStyle* previous_style) {
1405 ClearAllThemeData();
1406 LoadGtkValues();
1407 NativeThemeGtk2::instance()->NotifyObservers();
1410 } // namespace libgtk2ui
1412 views::LinuxUI* BuildGtk2UI() {
1413 return new libgtk2ui::Gtk2UI;