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.
4
5#include "chrome/browser/ui/libgtk2ui/gtk2_ui.h"
6
7#include <set>
8
9#include <pango/pango.h>
10
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/stringprintf.h"
20#include "chrome/browser/themes/theme_properties.h"
21#include "chrome/browser/ui/libgtk2ui/app_indicator_icon.h"
22#include "chrome/browser/ui/libgtk2ui/chrome_gtk_frame.h"
23#include "chrome/browser/ui/libgtk2ui/gtk2_border.h"
24#include "chrome/browser/ui/libgtk2ui/gtk2_event_loop.h"
25#include "chrome/browser/ui/libgtk2ui/gtk2_key_bindings_handler.h"
26#include "chrome/browser/ui/libgtk2ui/gtk2_signal_registrar.h"
27#include "chrome/browser/ui/libgtk2ui/gtk2_status_icon.h"
28#include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
29#include "chrome/browser/ui/libgtk2ui/native_theme_gtk2.h"
30#include "chrome/browser/ui/libgtk2ui/print_dialog_gtk2.h"
31#include "chrome/browser/ui/libgtk2ui/printing_gtk2_util.h"
32#include "chrome/browser/ui/libgtk2ui/select_file_dialog_impl.h"
33#include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
34#include "chrome/browser/ui/libgtk2ui/unity_service.h"
35#include "chrome/browser/ui/libgtk2ui/x11_input_method_context_impl_gtk2.h"
36#include "grit/components_scaled_resources.h"
37#include "grit/theme_resources.h"
38#include "printing/printing_context_linux.h"
39#include "third_party/skia/include/core/SkBitmap.h"
40#include "third_party/skia/include/core/SkCanvas.h"
41#include "third_party/skia/include/core/SkColor.h"
42#include "third_party/skia/include/core/SkShader.h"
43#include "ui/base/resource/resource_bundle.h"
44#include "ui/gfx/canvas.h"
45#include "ui/gfx/image/image.h"
46#include "ui/gfx/pango_util.h"
47#include "ui/gfx/rect.h"
48#include "ui/gfx/size.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"
55
56#if defined(USE_GCONF)
57#include "chrome/browser/ui/libgtk2ui/gconf_listener.h"
58#endif
59
60// A minimized port of GtkThemeService into something that can provide colors
61// and images for aura.
62//
63// TODO(erg): There's still a lot that needs ported or done for the first time:
64//
65// - Render and inject the omnibox background.
66// - Make sure to test with a light on dark theme, too.
67
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>
74
75namespace libgtk2ui {
76
77namespace {
78
79struct GObjectDeleter {
80  void operator()(void* ptr) {
81    g_object_unref(ptr);
82  }
83};
84struct GtkIconInfoDeleter {
85  void operator()(GtkIconInfo* ptr) {
86    gtk_icon_info_free(ptr);
87  }
88};
89typedef scoped_ptr<GIcon, GObjectDeleter> ScopedGIcon;
90typedef scoped_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo;
91typedef scoped_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf;
92
93// Prefix for app indicator ids
94const char kAppIndicatorIdPrefix[] = "chrome_app_indicator_";
95
96// Number of app indicators used (used as part of app-indicator id).
97int indicators_count;
98
99// The unknown content type.
100const char* kUnknownContentType = "application/octet-stream";
101
102// The size of the rendered toolbar image.
103const int kToolbarImageWidth = 64;
104const int kToolbarImageHeight = 128;
105
106// How much to tint the GTK+ color lighter at the top of the window.
107const color_utils::HSL kGtkFrameShift = { -1, -1, 0.58 };
108
109// How much to tint the GTK+ color when an explicit frame color hasn't been
110// specified.
111const color_utils::HSL kDefaultFrameShift = { -1, -1, 0.4 };
112
113// Values used as the new luminance and saturation values in the inactive tab
114// text color.
115const double kDarkInactiveLuminance = 0.85;
116const double kLightInactiveLuminance = 0.15;
117const double kHeavyInactiveSaturation = 0.7;
118const double kLightInactiveSaturation = 0.3;
119
120// Default color for links on the NTP when the GTK+ theme doesn't define a
121// link color. Constant taken from gtklinkbutton.c.
122const GdkColor kDefaultLinkColor = { 0, 0, 0, 0xeeee };
123
124const int kSkiaToGDKMultiplier = 257;
125
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.
129//
130// Default tints.
131const color_utils::HSL kDefaultTintButtons = { -1, -1, -1 };
132const color_utils::HSL kDefaultTintFrame = { -1, -1, -1 };
133const color_utils::HSL kDefaultTintFrameInactive = { -1, -1, 0.75f };
134const color_utils::HSL kDefaultTintFrameIncognito = { -1, 0.2f, 0.35f };
135const color_utils::HSL kDefaultTintFrameIncognitoInactive = { -1, 0.3f, 0.6f };
136const color_utils::HSL kDefaultTintBackgroundTab = { -1, 0.5, 0.75 };
137
138// A list of images that we provide while in gtk mode.
139//
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.
144const 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,
156};
157
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.
163const 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,
173};
174
175// This table converts button ids into a pair of gtk-stock id and state.
176struct 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 },
183
184  { IDR_FORWARD,   GTK_STOCK_GO_FORWARD, GTK_STATE_NORMAL },
185  { IDR_FORWARD_D, GTK_STOCK_GO_FORWARD, GTK_STATE_INSENSITIVE },
186
187  { IDR_HOME,      GTK_STOCK_HOME,       GTK_STATE_NORMAL },
188
189  { IDR_RELOAD,    GTK_STOCK_REFRESH,    GTK_STATE_NORMAL },
190  { IDR_RELOAD_D,  GTK_STOCK_REFRESH,    GTK_STATE_INSENSITIVE },
191
192  { IDR_STOP,      GTK_STOCK_STOP,       GTK_STATE_NORMAL },
193  { IDR_STOP_D,    GTK_STOCK_STOP,       GTK_STATE_INSENSITIVE },
194};
195
196// The image resources that will be tinted by the 'button' tint value.
197const 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,
204
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
211};
212
213bool 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));
219
220    for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i)
221      images.insert(kGtkIcons[i].idr);
222
223    images.insert(kOtherToolbarButtonIDs,
224                  kOtherToolbarButtonIDs + arraysize(kOtherToolbarButtonIDs));
225  }
226
227  return images.count(id) > 0;
228}
229
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.
237void 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);
244
245  color_utils::HSL text_tint;
246  color_utils::SkColorToHSL(GdkColorToSkColor(text_color),
247                            &text_tint);
248
249  color_utils::HSL background_tint;
250  color_utils::SkColorToHSL(GdkColorToSkColor(background_color),
251                            &background_tint);
252
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;
268
269    // Use the saturation of the text.
270    tint->s = text_tint.s;
271
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;
281
282    // Don't modify the saturation; the amount of color doesn't matter.
283    tint->s = -1;
284
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;
295  }
296}
297
298// Applies an HSL shift to a GdkColor (instead of an SkColor)
299void GdkColorHSLShift(const color_utils::HSL& shift, GdkColor* frame_color) {
300  SkColor shifted = color_utils::HSLShift(
301      GdkColorToSkColor(*frame_color), shift);
302
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;
307}
308
309// Copied Default blah sections from ThemeService.
310color_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;
327  }
328}
329
330// Returns a FontRenderParams corresponding to GTK's configuration.
331gfx::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);
344
345  gfx::FontRenderParams params;
346  params.antialiasing = antialias != 0;
347
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;
359  }
360
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;
374  }
375
376  g_free(hint_style);
377  g_free(rgba);
378
379  return params;
380}
381
382views::LinuxUI::NonClientMiddleClickAction GetDefaultMiddleClickAction() {
383  scoped_ptr<base::Environment> env(base::Environment::Create());
384  switch (base::nix::GetDesktopEnvironment(env.get())) {
385    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
386      // Starting with KDE 4.4, windows' titlebars can be dragged with the
387      // middle mouse button to create tab groups. We don't support that in
388      // Chrome, but at least avoid lowering windows in response to middle
389      // clicks to avoid surprising users who expect the KDE behavior.
390      return views::LinuxUI::MIDDLE_CLICK_ACTION_NONE;
391    default:
392      return views::LinuxUI::MIDDLE_CLICK_ACTION_LOWER;
393  }
394}
395
396}  // namespace
397
398Gtk2UI::Gtk2UI() : middle_click_action_(GetDefaultMiddleClickAction()) {
399  GtkInitFromCommandLine(*CommandLine::ForCurrentProcess());
400}
401
402void Gtk2UI::Initialize() {
403  signals_.reset(new Gtk2SignalRegistrar);
404
405  // Create our fake widgets.
406  fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
407  fake_frame_ = chrome_gtk_frame_new();
408  fake_label_.Own(gtk_label_new(""));
409  fake_entry_.Own(gtk_entry_new());
410
411  // Only realized widgets receive style-set notifications, which we need to
412  // broadcast new theme images and colors. Only realized widgets have style
413  // properties, too, which we query for some colors.
414  gtk_widget_realize(fake_frame_);
415  gtk_widget_realize(fake_window_);
416
417  signals_->Connect(fake_frame_, "style-set",
418                    G_CALLBACK(&OnStyleSetThunk), this);
419
420  LoadGtkValues();
421
422  printing::PrintingContextLinux::SetCreatePrintDialogFunction(
423      &PrintDialogGtk2::CreatePrintDialog);
424  printing::PrintingContextLinux::SetPdfPaperSizeFunction(
425      &GetPdfPaperSizeDeviceUnitsGtk);
426
427#if defined(USE_GCONF)
428  // We must build this after GTK gets initialized.
429  gconf_listener_.reset(new GConfListener(this));
430#endif  // defined(USE_GCONF)
431
432  indicators_count = 0;
433
434  // Instantiate the singleton instance of Gtk2EventLoop.
435  Gtk2EventLoop::GetInstance();
436}
437
438Gtk2UI::~Gtk2UI() {
439  gtk_widget_destroy(fake_window_);
440  gtk_widget_destroy(fake_frame_);
441  fake_label_.Destroy();
442  fake_entry_.Destroy();
443
444  ClearAllThemeData();
445}
446
447gfx::Image Gtk2UI::GetThemeImageNamed(int id) const {
448  // Try to get our cached version:
449  ImageCache::const_iterator it = gtk_images_.find(id);
450  if (it != gtk_images_.end())
451    return it->second;
452
453  if (IsOverridableImage(id)) {
454    gfx::Image image = gfx::Image(
455        gfx::ImageSkia::CreateFrom1xBitmap(GenerateGtkThemeBitmap(id)));
456    gtk_images_[id] = image;
457    return image;
458  }
459
460  return gfx::Image();
461}
462
463bool Gtk2UI::GetColor(int id, SkColor* color) const {
464  ColorMap::const_iterator it = colors_.find(id);
465  if (it != colors_.end()) {
466    *color = it->second;
467    return true;
468  }
469
470  return false;
471}
472
473bool Gtk2UI::HasCustomImage(int id) const {
474  return IsOverridableImage(id);
475}
476
477SkColor Gtk2UI::GetFocusRingColor() const {
478  return focus_ring_color_;
479}
480
481SkColor Gtk2UI::GetThumbActiveColor() const {
482  return thumb_active_color_;
483}
484
485SkColor Gtk2UI::GetThumbInactiveColor() const {
486  return thumb_inactive_color_;
487}
488
489SkColor Gtk2UI::GetTrackColor() const {
490  return track_color_;
491}
492
493SkColor Gtk2UI::GetActiveSelectionBgColor() const {
494  return active_selection_bg_color_;
495}
496
497SkColor Gtk2UI::GetActiveSelectionFgColor() const {
498  return active_selection_fg_color_;
499}
500
501SkColor Gtk2UI::GetInactiveSelectionBgColor() const {
502  return inactive_selection_bg_color_;
503}
504
505SkColor Gtk2UI::GetInactiveSelectionFgColor() const {
506  return inactive_selection_fg_color_;
507}
508
509double Gtk2UI::GetCursorBlinkInterval() const {
510  // From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is
511  // the default value for gtk-cursor-blink-time.
512  static const gint kGtkDefaultCursorBlinkTime = 1200;
513
514  // Dividing GTK's cursor blink cycle time (in milliseconds) by this value
515  // yields an appropriate value for
516  // content::RendererPreferences::caret_blink_interval.  This matches the
517  // logic in the WebKit GTK port.
518  static const double kGtkCursorBlinkCycleFactor = 2000.0;
519
520  gint cursor_blink_time = kGtkDefaultCursorBlinkTime;
521  gboolean cursor_blink = TRUE;
522  g_object_get(gtk_settings_get_default(),
523               "gtk-cursor-blink-time", &cursor_blink_time,
524               "gtk-cursor-blink", &cursor_blink,
525               NULL);
526  return cursor_blink ? (cursor_blink_time / kGtkCursorBlinkCycleFactor) : 0.0;
527}
528
529ui::NativeTheme* Gtk2UI::GetNativeTheme(aura::Window* window) const {
530  ui::NativeTheme* native_theme_override = NULL;
531  if (!native_theme_overrider_.is_null())
532    native_theme_override = native_theme_overrider_.Run(window);
533
534  if (native_theme_override)
535    return native_theme_override;
536
537  return NativeThemeGtk2::instance();
538}
539
540void Gtk2UI::SetNativeThemeOverride(const NativeThemeGetter& callback) {
541  native_theme_overrider_ = callback;
542}
543
544bool Gtk2UI::GetDefaultUsesSystemTheme() const {
545  scoped_ptr<base::Environment> env(base::Environment::Create());
546
547  switch (base::nix::GetDesktopEnvironment(env.get())) {
548    case base::nix::DESKTOP_ENVIRONMENT_GNOME:
549    case base::nix::DESKTOP_ENVIRONMENT_UNITY:
550    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
551      return true;
552    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
553    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
554    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
555      return false;
556  }
557  // Unless GetDesktopEnvironment() badly misbehaves, this should never happen.
558  NOTREACHED();
559  return false;
560}
561
562void Gtk2UI::SetDownloadCount(int count) const {
563  if (unity::IsRunning())
564    unity::SetDownloadCount(count);
565}
566
567void Gtk2UI::SetProgressFraction(float percentage) const {
568  if (unity::IsRunning())
569    unity::SetProgressFraction(percentage);
570}
571
572bool Gtk2UI::IsStatusIconSupported() const {
573  return true;
574}
575
576scoped_ptr<views::StatusIconLinux> Gtk2UI::CreateLinuxStatusIcon(
577    const gfx::ImageSkia& image,
578    const base::string16& tool_tip) const {
579  if (AppIndicatorIcon::CouldOpen()) {
580    ++indicators_count;
581    return scoped_ptr<views::StatusIconLinux>(new AppIndicatorIcon(
582        base::StringPrintf("%s%d", kAppIndicatorIdPrefix, indicators_count),
583        image,
584        tool_tip));
585  } else {
586    return scoped_ptr<views::StatusIconLinux>(new Gtk2StatusIcon(
587        image, tool_tip));
588  }
589}
590
591gfx::Image Gtk2UI::GetIconForContentType(
592    const std::string& content_type,
593    int size) const {
594  // This call doesn't take a reference.
595  GtkIconTheme* theme = gtk_icon_theme_get_default();
596
597  std::string content_types[] = {
598    content_type, kUnknownContentType
599  };
600
601  for (size_t i = 0; i < arraysize(content_types); ++i) {
602    ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str()));
603    ScopedGtkIconInfo icon_info(
604        gtk_icon_theme_lookup_by_gicon(
605            theme, icon.get(), size,
606            static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE)));
607    if (!icon_info)
608      continue;
609    ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), NULL));
610    if (!pixbuf)
611      continue;
612
613    SkBitmap bitmap = GdkPixbufToImageSkia(pixbuf.get());
614    DCHECK_EQ(size, bitmap.width());
615    DCHECK_EQ(size, bitmap.height());
616    gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
617    image_skia.MakeThreadSafe();
618    return gfx::Image(image_skia);
619  }
620  return gfx::Image();
621}
622
623scoped_ptr<views::Border> Gtk2UI::CreateNativeBorder(
624    views::LabelButton* owning_button,
625    scoped_ptr<views::LabelButtonBorder> border) {
626  if (owning_button->GetNativeTheme() != NativeThemeGtk2::instance())
627    return border.PassAs<views::Border>();
628
629  return scoped_ptr<views::Border>(
630      new Gtk2Border(this, owning_button, border.Pass()));
631}
632
633void Gtk2UI::AddWindowButtonOrderObserver(
634    views::WindowButtonOrderObserver* observer) {
635  if (!leading_buttons_.empty() || !trailing_buttons_.empty()) {
636    observer->OnWindowButtonOrderingChange(leading_buttons_,
637                                           trailing_buttons_);
638  }
639
640  observer_list_.AddObserver(observer);
641}
642
643void Gtk2UI::RemoveWindowButtonOrderObserver(
644    views::WindowButtonOrderObserver* observer) {
645  observer_list_.RemoveObserver(observer);
646}
647
648void Gtk2UI::SetWindowButtonOrdering(
649    const std::vector<views::FrameButton>& leading_buttons,
650    const std::vector<views::FrameButton>& trailing_buttons) {
651  leading_buttons_ = leading_buttons;
652  trailing_buttons_ = trailing_buttons;
653
654  FOR_EACH_OBSERVER(views::WindowButtonOrderObserver, observer_list_,
655                    OnWindowButtonOrderingChange(leading_buttons_,
656                                                 trailing_buttons_));
657}
658
659void Gtk2UI::SetNonClientMiddleClickAction(NonClientMiddleClickAction action) {
660  middle_click_action_ = action;
661}
662
663scoped_ptr<ui::LinuxInputMethodContext> Gtk2UI::CreateInputMethodContext(
664    ui::LinuxInputMethodContextDelegate* delegate) const {
665  return scoped_ptr<ui::LinuxInputMethodContext>(
666      new X11InputMethodContextImplGtk2(delegate));
667}
668
669gfx::FontRenderParams Gtk2UI::GetDefaultFontRenderParams() const {
670  static gfx::FontRenderParams params = GetGtkFontRenderParams();
671  return params;
672}
673
674scoped_ptr<gfx::ScopedPangoFontDescription>
675Gtk2UI::GetDefaultPangoFontDescription() const {
676  return scoped_ptr<gfx::ScopedPangoFontDescription>(
677      new gfx::ScopedPangoFontDescription(
678          pango_font_description_copy(default_font_description_->get())));
679}
680
681double Gtk2UI::GetFontDPI() const {
682  GtkSettings* gtk_settings = gtk_settings_get_default();
683  CHECK(gtk_settings);
684  gint dpi = -1;
685  g_object_get(gtk_settings, "gtk-xft-dpi", &dpi, NULL);
686
687  // GTK multiplies the DPI by 1024 before storing it.
688  return (dpi > 0) ? dpi / 1024.0 : dpi;
689}
690
691ui::SelectFileDialog* Gtk2UI::CreateSelectFileDialog(
692    ui::SelectFileDialog::Listener* listener,
693    ui::SelectFilePolicy* policy) const {
694  return SelectFileDialogImpl::Create(listener, policy);
695}
696
697bool Gtk2UI::UnityIsRunning() {
698  return unity::IsRunning();
699}
700
701views::LinuxUI::NonClientMiddleClickAction
702Gtk2UI::GetNonClientMiddleClickAction() {
703  return middle_click_action_;
704}
705
706void Gtk2UI::NotifyWindowManagerStartupComplete() {
707  // TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO
708  // from http://standards.freedesktop.org/startup-notification-spec/ instead.
709  gdk_notify_startup_complete();
710}
711
712bool Gtk2UI::MatchEvent(const ui::Event& event,
713                        std::vector<ui::TextEditCommandAuraLinux>* commands) {
714  // Ensure that we have a keyboard handler.
715  if (!key_bindings_handler_)
716    key_bindings_handler_.reset(new Gtk2KeyBindingsHandler);
717
718  return key_bindings_handler_->MatchEvent(event, commands);
719}
720
721void Gtk2UI::GetScrollbarColors(GdkColor* thumb_active_color,
722                                GdkColor* thumb_inactive_color,
723                                GdkColor* track_color) {
724  GdkColor* theme_thumb_active = NULL;
725  GdkColor* theme_thumb_inactive = NULL;
726  GdkColor* theme_trough_color = NULL;
727  gtk_widget_style_get(GTK_WIDGET(fake_frame_),
728                       "scrollbar-slider-prelight-color", &theme_thumb_active,
729                       "scrollbar-slider-normal-color", &theme_thumb_inactive,
730                       "scrollbar-trough-color", &theme_trough_color,
731                       NULL);
732
733  // Ask the theme if the theme specifies all the scrollbar colors and short
734  // circuit the expensive painting/compositing if we have all of them.
735  if (theme_thumb_active && theme_thumb_inactive && theme_trough_color) {
736    *thumb_active_color = *theme_thumb_active;
737    *thumb_inactive_color = *theme_thumb_inactive;
738    *track_color = *theme_trough_color;
739
740    gdk_color_free(theme_thumb_active);
741    gdk_color_free(theme_thumb_inactive);
742    gdk_color_free(theme_trough_color);
743    return;
744  }
745
746  // Create window containing scrollbar elements
747  GtkWidget* window    = gtk_window_new(GTK_WINDOW_POPUP);
748  GtkWidget* fixed     = gtk_fixed_new();
749  GtkWidget* scrollbar = gtk_hscrollbar_new(NULL);
750  gtk_container_add(GTK_CONTAINER(window), fixed);
751  gtk_container_add(GTK_CONTAINER(fixed),  scrollbar);
752  gtk_widget_realize(window);
753  gtk_widget_realize(scrollbar);
754
755  // Draw scrollbar thumb part and track into offscreen image
756  const int kWidth  = 100;
757  const int kHeight = 20;
758  GtkStyle* style   = gtk_rc_get_style(scrollbar);
759  GdkWindow* gdk_window = gtk_widget_get_window(window);
760  GdkPixmap* pm     = gdk_pixmap_new(gdk_window, kWidth, kHeight, -1);
761  GdkRectangle rect = { 0, 0, kWidth, kHeight };
762  unsigned char data[3 * kWidth * kHeight];
763  for (int i = 0; i < 3; ++i) {
764    if (i < 2) {
765      // Thumb part
766      gtk_paint_slider(style, pm,
767                       i == 0 ? GTK_STATE_PRELIGHT : GTK_STATE_NORMAL,
768                       GTK_SHADOW_OUT, &rect, scrollbar, "slider", 0, 0,
769                       kWidth, kHeight, GTK_ORIENTATION_HORIZONTAL);
770    } else {
771      // Track
772      gtk_paint_box(style, pm, GTK_STATE_ACTIVE, GTK_SHADOW_IN, &rect,
773                    scrollbar, "trough-upper", 0, 0, kWidth, kHeight);
774    }
775    GdkPixbuf* pb = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB,
776                                             FALSE, 8, kWidth, kHeight,
777                                             3 * kWidth, 0, 0);
778    gdk_pixbuf_get_from_drawable(pb, pm, NULL, 0, 0, 0, 0, kWidth, kHeight);
779
780    // Sample pixels
781    int components[3] = { 0 };
782    for (int y = 2; y < kHeight - 2; ++y) {
783      for (int c = 0; c < 3; ++c) {
784        // Sample a vertical slice of pixels at about one-thirds from the
785        // left edge. This allows us to avoid any fixed graphics that might be
786        // located at the edges or in the center of the scrollbar.
787        // Each pixel is made up of a red, green, and blue component; taking up
788        // a total of three bytes.
789        components[c] += data[3 * (kWidth / 3 + y * kWidth) + c];
790      }
791    }
792    GdkColor* color = i == 0 ? thumb_active_color :
793                      i == 1 ? thumb_inactive_color :
794                               track_color;
795    color->pixel = 0;
796    // We sampled pixels across the full height of the image, ignoring a two
797    // pixel border. In some themes, the border has a completely different
798    // color which we do not want to factor into our average color computation.
799    //
800    // We now need to scale the colors from the 0..255 range, to the wider
801    // 0..65535 range, and we need to actually compute the average color; so,
802    // we divide by the total number of pixels in the sample.
803    color->red   = components[0] * 65535 / (255 * (kHeight - 4));
804    color->green = components[1] * 65535 / (255 * (kHeight - 4));
805    color->blue  = components[2] * 65535 / (255 * (kHeight - 4));
806
807    g_object_unref(pb);
808  }
809  g_object_unref(pm);
810
811  gtk_widget_destroy(window);
812
813  // Override any of the default colors with ones that were specified by the
814  // theme.
815  if (theme_thumb_active) {
816    *thumb_active_color = *theme_thumb_active;
817    gdk_color_free(theme_thumb_active);
818  }
819
820  if (theme_thumb_inactive) {
821    *thumb_inactive_color = *theme_thumb_inactive;
822    gdk_color_free(theme_thumb_inactive);
823  }
824
825  if (theme_trough_color) {
826    *track_color = *theme_trough_color;
827    gdk_color_free(theme_trough_color);
828  }
829}
830
831void Gtk2UI::LoadGtkValues() {
832  // TODO(erg): GtkThemeService had a comment here about having to muck with
833  // the raw Prefs object to remove prefs::kCurrentThemeImages or else we'd
834  // regress startup time. Figure out how to do that when we can't access the
835  // prefs system from here.
836
837  GtkStyle* frame_style = gtk_rc_get_style(fake_frame_);
838
839  GtkStyle* window_style = gtk_rc_get_style(fake_window_);
840  SetThemeColorFromGtk(ThemeProperties::COLOR_CONTROL_BACKGROUND,
841                       &window_style->bg[GTK_STATE_NORMAL]);
842
843  GdkColor toolbar_color = window_style->bg[GTK_STATE_NORMAL];
844  SetThemeColorFromGtk(ThemeProperties::COLOR_TOOLBAR, &toolbar_color);
845
846  GdkColor button_color = window_style->bg[GTK_STATE_SELECTED];
847  SetThemeTintFromGtk(ThemeProperties::TINT_BUTTONS, &button_color);
848
849  GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
850  GdkColor label_color = label_style->fg[GTK_STATE_NORMAL];
851  SetThemeColorFromGtk(ThemeProperties::COLOR_TAB_TEXT, &label_color);
852  SetThemeColorFromGtk(ThemeProperties::COLOR_BOOKMARK_TEXT, &label_color);
853  SetThemeColorFromGtk(ThemeProperties::COLOR_STATUS_BAR_TEXT, &label_color);
854
855  default_font_description_.reset(new gfx::ScopedPangoFontDescription(
856      pango_font_description_copy(label_style->font_desc)));
857
858  // Build the various icon tints.
859  GetNormalButtonTintHSL(&button_tint_);
860  GetNormalEntryForegroundHSL(&entry_tint_);
861  GetSelectedEntryForegroundHSL(&selected_entry_tint_);
862  GdkColor frame_color = BuildFrameColors(frame_style);
863
864  // The inactive frame color never occurs naturally in the theme, as it is a
865  // tinted version of |frame_color|. We generate another color based on the
866  // background tab color, with the lightness and saturation moved in the
867  // opposite direction. (We don't touch the hue, since there should be subtle
868  // hints of the color in the text.)
869  color_utils::HSL inactive_tab_text_hsl =
870      tints_[ThemeProperties::TINT_BACKGROUND_TAB];
871  if (inactive_tab_text_hsl.l < 0.5)
872    inactive_tab_text_hsl.l = kDarkInactiveLuminance;
873  else
874    inactive_tab_text_hsl.l = kLightInactiveLuminance;
875
876  if (inactive_tab_text_hsl.s < 0.5)
877    inactive_tab_text_hsl.s = kHeavyInactiveSaturation;
878  else
879    inactive_tab_text_hsl.s = kLightInactiveSaturation;
880
881  colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
882      color_utils::HSLToSkColor(inactive_tab_text_hsl, 255);
883
884  // We pick the text and background colors for the NTP out of the colors for a
885  // GtkEntry. We do this because GtkEntries background color is never the same
886  // as |toolbar_color|, is usually a white, and when it isn't a white,
887  // provides sufficient contrast to |toolbar_color|. Try this out with
888  // Darklooks, HighContrastInverse or ThinIce.
889  GtkStyle* entry_style = gtk_rc_get_style(fake_entry_.get());
890  GdkColor ntp_background = entry_style->base[GTK_STATE_NORMAL];
891  GdkColor ntp_foreground = entry_style->text[GTK_STATE_NORMAL];
892  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_BACKGROUND,
893                       &ntp_background);
894  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_TEXT,
895                       &ntp_foreground);
896
897  // The NTP header is the color that surrounds the current active thumbnail on
898  // the NTP, and acts as the border of the "Recent Links" box. It would be
899  // awesome if they were separated so we could use GetBorderColor() for the
900  // border around the "Recent Links" section, but matching the frame color is
901  // more important.
902  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_HEADER,
903                       &frame_color);
904  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION,
905                       &toolbar_color);
906  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_TEXT,
907                       &label_color);
908
909  // Override the link color if the theme provides it.
910  const GdkColor* link_color = NULL;
911  gtk_widget_style_get(GTK_WIDGET(fake_window_),
912                       "link-color", &link_color, NULL);
913
914  bool is_default_link_color = false;
915  if (!link_color) {
916    link_color = &kDefaultLinkColor;
917    is_default_link_color = true;
918  }
919
920  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK,
921                       link_color);
922  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_LINK_UNDERLINE,
923                       link_color);
924  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK,
925                       link_color);
926  SetThemeColorFromGtk(ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE,
927                       link_color);
928
929  if (!is_default_link_color)
930    gdk_color_free(const_cast<GdkColor*>(link_color));
931
932  // Generate the colors that we pass to WebKit.
933  focus_ring_color_ = GdkColorToSkColor(frame_color);
934
935  GdkColor thumb_active_color, thumb_inactive_color, track_color;
936  Gtk2UI::GetScrollbarColors(&thumb_active_color,
937                             &thumb_inactive_color,
938                             &track_color);
939  thumb_active_color_ = GdkColorToSkColor(thumb_active_color);
940  thumb_inactive_color_ = GdkColorToSkColor(thumb_inactive_color);
941  track_color_ = GdkColorToSkColor(track_color);
942
943  // Some GTK themes only define the text selection colors on the GtkEntry
944  // class, so we need to use that for getting selection colors.
945  active_selection_bg_color_ =
946      GdkColorToSkColor(entry_style->base[GTK_STATE_SELECTED]);
947  active_selection_fg_color_ =
948      GdkColorToSkColor(entry_style->text[GTK_STATE_SELECTED]);
949  inactive_selection_bg_color_ =
950      GdkColorToSkColor(entry_style->base[GTK_STATE_ACTIVE]);
951  inactive_selection_fg_color_ =
952      GdkColorToSkColor(entry_style->text[GTK_STATE_ACTIVE]);
953}
954
955GdkColor Gtk2UI::BuildFrameColors(GtkStyle* frame_style) {
956  GdkColor* theme_frame = NULL;
957  GdkColor* theme_inactive_frame = NULL;
958  GdkColor* theme_incognito_frame = NULL;
959  GdkColor* theme_incognito_inactive_frame = NULL;
960  gtk_widget_style_get(GTK_WIDGET(fake_frame_),
961                       "frame-color", &theme_frame,
962                       "inactive-frame-color", &theme_inactive_frame,
963                       "incognito-frame-color", &theme_incognito_frame,
964                       "incognito-inactive-frame-color",
965                       &theme_incognito_inactive_frame,
966                       NULL);
967
968  GdkColor frame_color = BuildAndSetFrameColor(
969      &frame_style->bg[GTK_STATE_SELECTED],
970      theme_frame,
971      kDefaultFrameShift,
972      ThemeProperties::COLOR_FRAME,
973      ThemeProperties::TINT_FRAME);
974  if (theme_frame)
975    gdk_color_free(theme_frame);
976  SetThemeTintFromGtk(ThemeProperties::TINT_BACKGROUND_TAB, &frame_color);
977
978  BuildAndSetFrameColor(
979      &frame_style->bg[GTK_STATE_INSENSITIVE],
980      theme_inactive_frame,
981      kDefaultFrameShift,
982      ThemeProperties::COLOR_FRAME_INACTIVE,
983      ThemeProperties::TINT_FRAME_INACTIVE);
984  if (theme_inactive_frame)
985    gdk_color_free(theme_inactive_frame);
986
987  BuildAndSetFrameColor(
988      &frame_color,
989      theme_incognito_frame,
990      GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO),
991      ThemeProperties::COLOR_FRAME_INCOGNITO,
992      ThemeProperties::TINT_FRAME_INCOGNITO);
993  if (theme_incognito_frame)
994    gdk_color_free(theme_incognito_frame);
995
996  BuildAndSetFrameColor(
997      &frame_color,
998      theme_incognito_inactive_frame,
999      GetDefaultTint(ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE),
1000      ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1001      ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE);
1002  if (theme_incognito_inactive_frame)
1003    gdk_color_free(theme_incognito_inactive_frame);
1004
1005  return frame_color;
1006}
1007
1008void Gtk2UI::SetThemeColorFromGtk(int id, const GdkColor* color) {
1009  colors_[id] = GdkColorToSkColor(*color);
1010}
1011
1012void Gtk2UI::SetThemeTintFromGtk(int id, const GdkColor* color) {
1013  color_utils::HSL default_tint = GetDefaultTint(id);
1014  color_utils::HSL hsl;
1015  color_utils::SkColorToHSL(GdkColorToSkColor(*color), &hsl);
1016
1017  if (default_tint.s != -1)
1018    hsl.s = default_tint.s;
1019
1020  if (default_tint.l != -1)
1021    hsl.l = default_tint.l;
1022
1023  tints_[id] = hsl;
1024}
1025
1026GdkColor Gtk2UI::BuildAndSetFrameColor(const GdkColor* base,
1027                                       const GdkColor* gtk_base,
1028                                       const color_utils::HSL& tint,
1029                                       int color_id,
1030                                       int tint_id) {
1031  GdkColor out_color = *base;
1032  if (gtk_base) {
1033    // The theme author specified a color to use, use it without modification.
1034    out_color = *gtk_base;
1035  } else {
1036    // Tint the basic color since this is a heuristic color instead of one
1037    // specified by the theme author.
1038    GdkColorHSLShift(tint, &out_color);
1039  }
1040  SetThemeColorFromGtk(color_id, &out_color);
1041  SetThemeTintFromGtk(tint_id, &out_color);
1042
1043  return out_color;
1044}
1045
1046SkBitmap Gtk2UI::GenerateGtkThemeBitmap(int id) const {
1047  switch (id) {
1048    case IDR_THEME_TOOLBAR: {
1049      GtkStyle* style = gtk_rc_get_style(fake_window_);
1050      GdkColor* color = &style->bg[GTK_STATE_NORMAL];
1051      SkBitmap bitmap;
1052      bitmap.allocN32Pixels(kToolbarImageWidth, kToolbarImageHeight);
1053      bitmap.eraseARGB(0xff, color->red >> 8, color->green >> 8,
1054                       color->blue >> 8);
1055      return bitmap;
1056    }
1057    case IDR_THEME_TAB_BACKGROUND:
1058    case IDR_THEME_TAB_BACKGROUND_DESKTOP:
1059      return GenerateTabImage(IDR_THEME_FRAME);
1060    case IDR_THEME_TAB_BACKGROUND_INCOGNITO:
1061    case IDR_THEME_TAB_BACKGROUND_INCOGNITO_DESKTOP:
1062      return GenerateTabImage(IDR_THEME_FRAME_INCOGNITO);
1063    case IDR_FRAME:
1064    case IDR_THEME_FRAME:
1065      return GenerateFrameImage(ThemeProperties::COLOR_FRAME,
1066                                "frame-gradient-color");
1067    case IDR_FRAME_INACTIVE:
1068    case IDR_THEME_FRAME_INACTIVE:
1069      return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INACTIVE,
1070                                "inactive-frame-gradient-color");
1071    case IDR_THEME_FRAME_INCOGNITO:
1072      return GenerateFrameImage(ThemeProperties::COLOR_FRAME_INCOGNITO,
1073                                "incognito-frame-gradient-color");
1074    case IDR_THEME_FRAME_INCOGNITO_INACTIVE: {
1075      return GenerateFrameImage(
1076          ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE,
1077          "incognito-inactive-frame-gradient-color");
1078    }
1079    // Icons that sit inside the omnibox shouldn't receive TINT_BUTTONS and
1080    // instead should tint based on the foreground text entry color in GTK+
1081    // mode because some themes that try to be dark *and* light have very
1082    // different colors between the omnibox and the normal background area.
1083    // TODO(erg): Decide what to do about other icons that appear in the
1084    // omnibox, e.g. content settings icons.
1085    case IDR_OMNIBOX_EXTENSION_APP:
1086    case IDR_OMNIBOX_HTTP:
1087    case IDR_OMNIBOX_SEARCH:
1088    case IDR_OMNIBOX_STAR:
1089    case IDR_OMNIBOX_TTS: {
1090      return GenerateTintedIcon(id, entry_tint_);
1091    }
1092    // In GTK mode, the dark versions of the omnibox icons only ever appear in
1093    // the autocomplete popup and only against the current theme's GtkEntry
1094    // base[GTK_STATE_SELECTED] color, so tint the icons so they won't collide
1095    // with the selected color.
1096    case IDR_OMNIBOX_EXTENSION_APP_DARK:
1097    case IDR_OMNIBOX_HTTP_DARK:
1098    case IDR_OMNIBOX_SEARCH_DARK:
1099    case IDR_OMNIBOX_STAR_DARK:
1100    case IDR_OMNIBOX_TTS_DARK: {
1101      return GenerateTintedIcon(id, selected_entry_tint_);
1102    }
1103    // In GTK mode, we need to manually render several icons.
1104    case IDR_BACK:
1105    case IDR_BACK_D:
1106    case IDR_FORWARD:
1107    case IDR_FORWARD_D:
1108    case IDR_HOME:
1109    case IDR_RELOAD:
1110    case IDR_RELOAD_D:
1111    case IDR_STOP:
1112    case IDR_STOP_D: {
1113      return GenerateGTKIcon(id);
1114    }
1115    case IDR_TOOLBAR_BEZEL_HOVER:
1116      return GenerateToolbarBezel(GTK_STATE_PRELIGHT, IDR_TOOLBAR_BEZEL_HOVER);
1117    case IDR_TOOLBAR_BEZEL_PRESSED:
1118      return GenerateToolbarBezel(GTK_STATE_ACTIVE, IDR_TOOLBAR_BEZEL_PRESSED);
1119    default: {
1120      return GenerateTintedIcon(id, button_tint_);
1121    }
1122  }
1123
1124  return SkBitmap();
1125}
1126
1127SkBitmap Gtk2UI::GenerateFrameImage(
1128    int color_id,
1129    const char* gradient_name) const {
1130  // We use two colors: the main color (passed in) and a lightened version of
1131  // that color (which is supposed to match the light gradient at the top of
1132  // several GTK+ themes, such as Ambiance, Clearlooks or Bluebird).
1133  ColorMap::const_iterator it = colors_.find(color_id);
1134  DCHECK(it != colors_.end());
1135  SkColor base = it->second;
1136
1137  gfx::Canvas canvas(gfx::Size(kToolbarImageWidth, kToolbarImageHeight),
1138      1.0f, true);
1139
1140  int gradient_size;
1141  GdkColor* gradient_top_color = NULL;
1142  gtk_widget_style_get(GTK_WIDGET(fake_frame_),
1143                       "frame-gradient-size", &gradient_size,
1144                       gradient_name, &gradient_top_color,
1145                       NULL);
1146  if (gradient_size) {
1147    SkColor lighter = gradient_top_color ?
1148        GdkColorToSkColor(*gradient_top_color) :
1149        color_utils::HSLShift(base, kGtkFrameShift);
1150    if (gradient_top_color)
1151      gdk_color_free(gradient_top_color);
1152    skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1153        0, gradient_size, lighter, base);
1154    SkPaint paint;
1155    paint.setStyle(SkPaint::kFill_Style);
1156    paint.setAntiAlias(true);
1157    paint.setShader(shader.get());
1158
1159    canvas.DrawRect(gfx::Rect(0, 0, kToolbarImageWidth, gradient_size), paint);
1160  }
1161
1162  canvas.FillRect(gfx::Rect(0, gradient_size, kToolbarImageWidth,
1163                            kToolbarImageHeight - gradient_size), base);
1164  return canvas.ExtractImageRep().sk_bitmap();
1165}
1166
1167SkBitmap Gtk2UI::GenerateTabImage(int base_id) const {
1168  const SkBitmap* base_image = GetThemeImageNamed(base_id).ToSkBitmap();
1169  SkBitmap bg_tint = SkBitmapOperations::CreateHSLShiftedBitmap(
1170      *base_image, GetDefaultTint(ThemeProperties::TINT_BACKGROUND_TAB));
1171  return SkBitmapOperations::CreateTiledBitmap(
1172      bg_tint, 0, 0, bg_tint.width(), bg_tint.height());
1173}
1174
1175SkBitmap Gtk2UI::GenerateTintedIcon(
1176    int base_id,
1177    const color_utils::HSL& tint) const {
1178  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1179  return SkBitmapOperations::CreateHSLShiftedBitmap(
1180      rb.GetImageNamed(base_id).AsBitmap(), tint);
1181}
1182
1183SkBitmap Gtk2UI::GenerateGTKIcon(int base_id) const {
1184  const char* stock_id = NULL;
1185  GtkStateType gtk_state = GTK_STATE_NORMAL;
1186  for (unsigned int i = 0; i < arraysize(kGtkIcons); ++i) {
1187    if (kGtkIcons[i].idr == base_id) {
1188      stock_id = kGtkIcons[i].stock_id;
1189      gtk_state = kGtkIcons[i].gtk_state;
1190      break;
1191    }
1192  }
1193  DCHECK(stock_id);
1194
1195  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1196  SkBitmap default_bitmap = rb.GetImageNamed(base_id).AsBitmap();
1197
1198  gtk_widget_ensure_style(fake_frame_);
1199  GtkStyle* style = gtk_widget_get_style(fake_frame_);
1200  GtkIconSet* icon_set = gtk_style_lookup_icon_set(style, stock_id);
1201  if (!icon_set)
1202    return default_bitmap;
1203
1204  // Ask GTK to render the icon to a buffer, which we will steal from.
1205  GdkPixbuf* gdk_icon = gtk_icon_set_render_icon(
1206      icon_set,
1207      style,
1208      base::i18n::IsRTL() ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR,
1209      gtk_state,
1210      GTK_ICON_SIZE_SMALL_TOOLBAR,
1211      fake_frame_,
1212      NULL);
1213
1214  if (!gdk_icon) {
1215    // This can theoretically happen if an icon theme doesn't provide a
1216    // specific image. This should realistically never happen, but I bet there
1217    // are some theme authors who don't reliably provide all icons.
1218    return default_bitmap;
1219  }
1220
1221  SkBitmap retval;
1222  retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1223  retval.eraseColor(0);
1224
1225  const SkBitmap icon = GdkPixbufToImageSkia(gdk_icon);
1226  g_object_unref(gdk_icon);
1227
1228  SkCanvas canvas(retval);
1229
1230  if (gtk_state == GTK_STATE_ACTIVE || gtk_state == GTK_STATE_PRELIGHT) {
1231    SkBitmap border = DrawGtkButtonBorder(gtk_state,
1232                                          false,
1233                                          false,
1234                                          default_bitmap.width(),
1235                                          default_bitmap.height());
1236    canvas.drawBitmap(border, 0, 0);
1237  }
1238
1239  canvas.drawBitmap(icon,
1240                    (default_bitmap.width() / 2) - (icon.width() / 2),
1241                    (default_bitmap.height() / 2) - (icon.height() / 2));
1242
1243  return retval;
1244}
1245
1246SkBitmap Gtk2UI::GenerateToolbarBezel(int gtk_state, int sizing_idr) const {
1247  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1248  SkBitmap default_bitmap =
1249      rb.GetImageNamed(sizing_idr).AsBitmap();
1250
1251  SkBitmap retval;
1252  retval.allocN32Pixels(default_bitmap.width(), default_bitmap.height());
1253  retval.eraseColor(0);
1254
1255  SkCanvas canvas(retval);
1256  SkBitmap border = DrawGtkButtonBorder(
1257      gtk_state,
1258      false,
1259      false,
1260      default_bitmap.width(),
1261      default_bitmap.height());
1262  canvas.drawBitmap(border, 0, 0);
1263
1264  return retval;
1265}
1266
1267void Gtk2UI::GetNormalButtonTintHSL(color_utils::HSL* tint) const {
1268  GtkStyle* window_style = gtk_rc_get_style(fake_window_);
1269  const GdkColor accent_gdk_color = window_style->bg[GTK_STATE_SELECTED];
1270  const GdkColor base_color = window_style->base[GTK_STATE_NORMAL];
1271
1272  GtkStyle* label_style = gtk_rc_get_style(fake_label_.get());
1273  const GdkColor text_color = label_style->fg[GTK_STATE_NORMAL];
1274
1275  PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1276}
1277
1278void Gtk2UI::GetNormalEntryForegroundHSL(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
1282  GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1283  const GdkColor text_color = style->text[GTK_STATE_NORMAL];
1284  const GdkColor base_color = style->base[GTK_STATE_NORMAL];
1285
1286  PickButtonTintFromColors(accent_gdk_color, text_color, base_color, tint);
1287}
1288
1289void Gtk2UI::GetSelectedEntryForegroundHSL(color_utils::HSL* tint) const {
1290  // The simplest of all the tints. We just use the selected text in the entry
1291  // since the icons tinted this way will only be displayed against
1292  // base[GTK_STATE_SELECTED].
1293  GtkStyle* style = gtk_rc_get_style(fake_entry_.get());
1294  const GdkColor color = style->text[GTK_STATE_SELECTED];
1295  color_utils::SkColorToHSL(GdkColorToSkColor(color), tint);
1296}
1297
1298SkBitmap Gtk2UI::DrawGtkButtonBorder(int gtk_state,
1299                                     bool focused,
1300                                     bool call_to_action,
1301                                     int width,
1302                                     int height) const {
1303  // Create a temporary GTK button to snapshot
1304  GtkWidget* window = gtk_offscreen_window_new();
1305  GtkWidget* button = gtk_button_new();
1306  gtk_widget_set_size_request(button, width, height);
1307  gtk_container_add(GTK_CONTAINER(window), button);
1308  gtk_widget_realize(window);
1309  gtk_widget_realize(button);
1310  gtk_widget_show(button);
1311  gtk_widget_show(window);
1312
1313  if (call_to_action)
1314    GTK_WIDGET_SET_FLAGS(button, GTK_HAS_DEFAULT);
1315
1316  if (focused) {
1317    // We can't just use gtk_widget_grab_focus() here because that sets
1318    // gtk_widget_is_focus(), but not gtk_widget_has_focus(), which is what the
1319    // GtkButton's paint checks.
1320    GTK_WIDGET_SET_FLAGS(button, GTK_HAS_FOCUS);
1321  }
1322
1323  gtk_widget_set_state(button, static_cast<GtkStateType>(gtk_state));
1324
1325  GdkPixmap* pixmap;
1326  {
1327    // http://crbug.com/346740
1328    ANNOTATE_SCOPED_MEMORY_LEAK;
1329    pixmap = gtk_widget_get_snapshot(button, NULL);
1330  }
1331  int w, h;
1332  gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &w, &h);
1333  DCHECK_EQ(w, width);
1334  DCHECK_EQ(h, height);
1335
1336  // We render the Pixmap to a Pixbuf. This can be slow, as we're scrapping
1337  // bits from X.
1338  GdkColormap* colormap = gdk_drawable_get_colormap(pixmap);
1339  GdkPixbuf* pixbuf = gdk_pixbuf_get_from_drawable(NULL,
1340                                                   GDK_DRAWABLE(pixmap),
1341                                                   colormap,
1342                                                   0, 0, 0, 0, w, h);
1343
1344  // Finally, we convert our pixbuf into a type we can use.
1345  SkBitmap border = GdkPixbufToImageSkia(pixbuf);
1346  g_object_unref(pixbuf);
1347  g_object_unref(pixmap);
1348  gtk_widget_destroy(window);
1349
1350  return border;
1351}
1352
1353void Gtk2UI::ClearAllThemeData() {
1354  gtk_images_.clear();
1355}
1356
1357void Gtk2UI::OnStyleSet(GtkWidget* widget, GtkStyle* previous_style) {
1358  ClearAllThemeData();
1359  LoadGtkValues();
1360  NativeThemeGtk2::instance()->NotifyObservers();
1361}
1362
1363}  // namespace libgtk2ui
1364
1365views::LinuxUI* BuildGtk2UI() {
1366  return new libgtk2ui::Gtk2UI;
1367}
1368