- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / gtk / omnibox / omnibox_popup_view_gtk.cc
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/gtk/omnibox/omnibox_popup_view_gtk.h"
6
7 #include <gtk/gtk.h>
8
9 #include <algorithm>
10 #include <string>
11
12 #include "base/basictypes.h"
13 #include "base/i18n/rtl.h"
14 #include "base/logging.h"
15 #include "base/stl_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/browser/autocomplete/autocomplete_match.h"
18 #include "chrome/browser/autocomplete/autocomplete_result.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/defaults.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/search_engines/template_url.h"
23 #include "chrome/browser/search_engines/template_url_service.h"
24 #include "chrome/browser/ui/gtk/gtk_theme_service.h"
25 #include "chrome/browser/ui/gtk/gtk_util.h"
26 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
27 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
28 #include "chrome/browser/ui/omnibox/omnibox_view.h"
29 #include "content/public/browser/notification_source.h"
30 #include "grit/theme_resources.h"
31 #include "ui/base/gtk/gtk_hig_constants.h"
32 #include "ui/base/gtk/gtk_screen_util.h"
33 #include "ui/base/gtk/gtk_windowing.h"
34 #include "ui/gfx/color_utils.h"
35 #include "ui/gfx/font.h"
36 #include "ui/gfx/gtk_compat.h"
37 #include "ui/gfx/gtk_util.h"
38 #include "ui/gfx/image/cairo_cached_surface.h"
39 #include "ui/gfx/image/image.h"
40 #include "ui/gfx/rect.h"
41 #include "ui/gfx/skia_utils_gtk.h"
42
43 namespace {
44
45 const GdkColor kBorderColor = GDK_COLOR_RGB(0xc7, 0xca, 0xce);
46 const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xff, 0xff, 0xff);
47 const GdkColor kSelectedBackgroundColor = GDK_COLOR_RGB(0xdf, 0xe6, 0xf6);
48 const GdkColor kHoveredBackgroundColor = GDK_COLOR_RGB(0xef, 0xf2, 0xfa);
49
50 const GdkColor kContentTextColor = GDK_COLOR_RGB(0x00, 0x00, 0x00);
51 const GdkColor kURLTextColor = GDK_COLOR_RGB(0x00, 0x88, 0x00);
52
53 // We have a 1 pixel border around the entire results popup.
54 const int kBorderThickness = 1;
55
56 // The vertical height of each result.
57 const int kHeightPerResult = 24;
58
59 // Width of the icons.
60 const int kIconWidth = 17;
61
62 // We want to vertically center the image in the result space.
63 const int kIconTopPadding = 2;
64
65 // Space between the left edge (including the border) and the text.
66 const int kIconLeftPadding = 3 + kBorderThickness;
67
68 // Space between the image and the text.
69 const int kIconRightPadding = 5;
70
71 // Space between the left edge (including the border) and the text.
72 const int kIconAreaWidth =
73     kIconLeftPadding + kIconWidth + kIconRightPadding;
74
75 // Space between the right edge (including the border) and the text.
76 const int kRightPadding = 3;
77
78 // When we have both a content and description string, we don't want the
79 // content to push the description off.  Limit the content to a percentage of
80 // the total width.
81 const float kContentWidthPercentage = 0.7;
82
83 // How much to offset the popup from the bottom of the location bar.
84 const int kVerticalOffset = 3;
85
86 // The size delta between the font used for the edit and the result rows. Passed
87 // to gfx::Font::DeriveFont.
88 const int kEditFontAdjust = -1;
89
90 // UTF-8 Left-to-right embedding.
91 const char* kLRE = "\xe2\x80\xaa";
92
93 // Return a Rect covering the whole area of |window|.
94 gfx::Rect GetWindowRect(GdkWindow* window) {
95   gint width = gdk_window_get_width(window);
96   gint height = gdk_window_get_height(window);
97   return gfx::Rect(width, height);
98 }
99
100 // TODO(deanm): Find some better home for this, and make it more efficient.
101 size_t GetUTF8Offset(const string16& text, size_t text_offset) {
102   return UTF16ToUTF8(text.substr(0, text_offset)).length();
103 }
104
105 // Generates the normal URL color, a green color used in unhighlighted URL
106 // text. It is a mix of |kURLTextColor| and the current text color.  Unlike the
107 // selected text color, it is more important to match the qualities of the
108 // foreground typeface color instead of taking the background into account.
109 GdkColor NormalURLColor(GdkColor foreground) {
110   color_utils::HSL fg_hsl;
111   color_utils::SkColorToHSL(gfx::GdkColorToSkColor(foreground), &fg_hsl);
112
113   color_utils::HSL hue_hsl;
114   color_utils::SkColorToHSL(gfx::GdkColorToSkColor(kURLTextColor), &hue_hsl);
115
116   // Only allow colors that have a fair amount of saturation in them (color vs
117   // white). This means that our output color will always be fairly green.
118   double s = std::max(0.5, fg_hsl.s);
119
120   // Make sure the luminance is at least as bright as the |kURLTextColor| green
121   // would be if we were to use that.
122   double l;
123   if (fg_hsl.l < hue_hsl.l)
124     l = hue_hsl.l;
125   else
126     l = (fg_hsl.l + hue_hsl.l) / 2;
127
128   color_utils::HSL output = { hue_hsl.h, s, l };
129   return gfx::SkColorToGdkColor(color_utils::HSLToSkColor(output, 255));
130 }
131
132 // Generates the selected URL color, a green color used on URL text in the
133 // currently highlighted entry in the autocomplete popup. It's a mix of
134 // |kURLTextColor|, the current text color, and the background color (the
135 // select highlight). It is more important to contrast with the background
136 // saturation than to look exactly like the foreground color.
137 GdkColor SelectedURLColor(GdkColor foreground, GdkColor background) {
138   color_utils::HSL fg_hsl;
139   color_utils::SkColorToHSL(gfx::GdkColorToSkColor(foreground), &fg_hsl);
140
141   color_utils::HSL bg_hsl;
142   color_utils::SkColorToHSL(gfx::GdkColorToSkColor(background), &bg_hsl);
143
144   color_utils::HSL hue_hsl;
145   color_utils::SkColorToHSL(gfx::GdkColorToSkColor(kURLTextColor), &hue_hsl);
146
147   // The saturation of the text should be opposite of the background, clamped
148   // to 0.2-0.8. We make sure it's greater than 0.2 so there's some color, but
149   // less than 0.8 so it's not the oversaturated neon-color.
150   double opposite_s = 1 - bg_hsl.s;
151   double s = std::max(0.2, std::min(0.8, opposite_s));
152
153   // The luminance should match the luminance of the foreground text.  Again,
154   // we clamp so as to have at some amount of color (green) in the text.
155   double opposite_l = fg_hsl.l;
156   double l = std::max(0.1, std::min(0.9, opposite_l));
157
158   color_utils::HSL output = { hue_hsl.h, s, l };
159   return gfx::SkColorToGdkColor(color_utils::HSLToSkColor(output, 255));
160 }
161 }  // namespace
162
163 OmniboxPopupViewGtk::OmniboxPopupViewGtk(const gfx::Font& font,
164                                          OmniboxView* omnibox_view,
165                                          OmniboxEditModel* edit_model,
166                                          GtkWidget* location_bar)
167     : omnibox_view_(omnibox_view),
168       location_bar_(location_bar),
169       window_(gtk_window_new(GTK_WINDOW_POPUP)),
170       layout_(NULL),
171       theme_service_(NULL),
172       font_(font.DeriveFont(kEditFontAdjust)),
173       ignore_mouse_drag_(false),
174       opened_(false) {
175   // edit_model may be NULL in unit tests.
176   if (edit_model) {
177     model_.reset(new OmniboxPopupModel(this, edit_model));
178     theme_service_ = GtkThemeService::GetFrom(edit_model->profile());
179   }
180 }
181
182 void OmniboxPopupViewGtk::Init() {
183   gtk_widget_set_can_focus(window_, FALSE);
184   // Don't allow the window to be resized.  This also forces the window to
185   // shrink down to the size of its child contents.
186   gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
187   gtk_widget_set_app_paintable(window_, TRUE);
188   // Have GTK double buffer around the expose signal.
189   gtk_widget_set_double_buffered(window_, TRUE);
190
191   // Cache the layout so we don't have to create it for every expose.  If we
192   // were a real widget we should handle changing directions, but we're not
193   // doing RTL or anything yet, so it shouldn't be important now.
194   layout_ = gtk_widget_create_pango_layout(window_, NULL);
195   // We don't want the layout of search results depending on their language.
196   pango_layout_set_auto_dir(layout_, FALSE);
197   // We always ellipsize when drawing our text runs.
198   pango_layout_set_ellipsize(layout_, PANGO_ELLIPSIZE_END);
199
200   gtk_widget_add_events(window_, GDK_BUTTON_MOTION_MASK |
201                                  GDK_POINTER_MOTION_MASK |
202                                  GDK_BUTTON_PRESS_MASK |
203                                  GDK_BUTTON_RELEASE_MASK);
204   g_signal_connect(window_, "motion-notify-event",
205                    G_CALLBACK(HandleMotionThunk), this);
206   g_signal_connect(window_, "button-press-event",
207                    G_CALLBACK(HandleButtonPressThunk), this);
208   g_signal_connect(window_, "button-release-event",
209                    G_CALLBACK(HandleButtonReleaseThunk), this);
210   g_signal_connect(window_, "expose-event",
211                    G_CALLBACK(HandleExposeThunk), this);
212
213   registrar_.Add(this,
214                  chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
215                  content::Source<ThemeService>(theme_service_));
216   theme_service_->InitThemesFor(this);
217
218   // TODO(erg): There appears to be a bug somewhere in something which shows
219   // itself when we're in NX. Previously, we called
220   // gtk_util::ActAsRoundedWindow() to make this popup have rounded
221   // corners. This worked on the standard xorg server (both locally and
222   // remotely), but broke over NX. My current hypothesis is that it can't
223   // handle shaping top-level windows during an expose event, but I'm not sure
224   // how else to get accurate shaping information.
225   //
226   // r25080 (the original patch that added rounded corners here) should
227   // eventually be cherry picked once I know what's going
228   // on. http://crbug.com/22015.
229 }
230
231 OmniboxPopupViewGtk::~OmniboxPopupViewGtk() {
232   // Explicitly destroy our model here, before we destroy our GTK widgets.
233   // This is because the model destructor can call back into us, and we need
234   // to make sure everything is still valid when it does.
235   model_.reset();
236   // layout_ may be NULL in unit tests.
237   if (layout_) {
238     g_object_unref(layout_);
239     gtk_widget_destroy(window_);
240   }
241 }
242
243 bool OmniboxPopupViewGtk::IsOpen() const {
244   return opened_;
245 }
246
247 void OmniboxPopupViewGtk::InvalidateLine(size_t line) {
248   if (line < GetHiddenMatchCount())
249     return;
250   // TODO(deanm): Is it possible to use some constant for the width, instead
251   // of having to query the width of the window?
252   GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window_));
253   GdkRectangle line_rect = GetRectForLine(
254       line, GetWindowRect(gdk_window).width()).ToGdkRectangle();
255   gdk_window_invalidate_rect(gdk_window, &line_rect, FALSE);
256 }
257
258 void OmniboxPopupViewGtk::UpdatePopupAppearance() {
259   const AutocompleteResult& result = GetResult();
260   const size_t hidden_matches = GetHiddenMatchCount();
261   if (result.size() <= hidden_matches) {
262     Hide();
263     return;
264   }
265
266   Show(result.size() - hidden_matches);
267   gtk_widget_queue_draw(window_);
268 }
269
270 gfx::Rect OmniboxPopupViewGtk::GetTargetBounds() {
271   if (!gtk_widget_get_realized(window_))
272     return gfx::Rect();
273
274   gfx::Rect retval = ui::GetWidgetScreenBounds(window_);
275
276   // The widget bounds don't update synchronously so may be out of sync with
277   // our last size request.
278   GtkRequisition req;
279   gtk_widget_size_request(window_, &req);
280   retval.set_width(req.width);
281   retval.set_height(req.height);
282
283   return retval;
284 }
285
286 void OmniboxPopupViewGtk::PaintUpdatesNow() {
287   // Paint our queued invalidations now, synchronously.
288   GdkWindow* gdk_window = gtk_widget_get_window(window_);
289   gdk_window_process_updates(gdk_window, FALSE);
290 }
291
292 void OmniboxPopupViewGtk::OnDragCanceled() {
293   ignore_mouse_drag_ = true;
294 }
295
296 void OmniboxPopupViewGtk::Observe(int type,
297                                   const content::NotificationSource& source,
298                                   const content::NotificationDetails& details) {
299   DCHECK(type == chrome::NOTIFICATION_BROWSER_THEME_CHANGED);
300
301   if (theme_service_->UsingNativeTheme()) {
302     gtk_util::UndoForceFontSize(window_);
303
304     border_color_ = theme_service_->GetBorderColor();
305
306     gtk_util::GetTextColors(
307         &background_color_, &selected_background_color_,
308         &content_text_color_, &selected_content_text_color_);
309
310     hovered_background_color_ = gtk_util::AverageColors(
311         background_color_, selected_background_color_);
312     url_text_color_ = NormalURLColor(content_text_color_);
313     url_selected_text_color_ = SelectedURLColor(selected_content_text_color_,
314                                                 selected_background_color_);
315   } else {
316     gtk_util::ForceFontSizePixels(window_, font_.GetFontSize());
317
318     border_color_ = kBorderColor;
319     background_color_ = kBackgroundColor;
320     selected_background_color_ = kSelectedBackgroundColor;
321     hovered_background_color_ = kHoveredBackgroundColor;
322
323     content_text_color_ = kContentTextColor;
324     selected_content_text_color_ = kContentTextColor;
325     url_text_color_ = kURLTextColor;
326     url_selected_text_color_ = kURLTextColor;
327   }
328
329   // Calculate dimmed colors.
330   content_dim_text_color_ =
331       gtk_util::AverageColors(content_text_color_,
332                               background_color_);
333   selected_content_dim_text_color_ =
334       gtk_util::AverageColors(selected_content_text_color_,
335                               selected_background_color_);
336
337   // Set the background color, so we don't need to paint it manually.
338   gtk_widget_modify_bg(window_, GTK_STATE_NORMAL, &background_color_);
339 }
340
341 size_t OmniboxPopupViewGtk::LineFromY(int y) const {
342   // model_ may be NULL in unit tests.
343   if (model_)
344     DCHECK_NE(0U, model_->result().size());
345   size_t line = std::max(y - kBorderThickness, 0) / kHeightPerResult;
346   return std::min(line + GetHiddenMatchCount(), GetResult().size() - 1);
347 }
348
349 gfx::Rect OmniboxPopupViewGtk::GetRectForLine(size_t line, int width) const {
350   size_t visible_line = line - GetHiddenMatchCount();
351   return gfx::Rect(kBorderThickness,
352                    (visible_line * kHeightPerResult) + kBorderThickness,
353                    width - (kBorderThickness * 2),
354                    kHeightPerResult);
355 }
356
357 size_t OmniboxPopupViewGtk::GetHiddenMatchCount() const {
358   return GetResult().ShouldHideTopMatch() ? 1 : 0;
359 }
360
361 const AutocompleteResult& OmniboxPopupViewGtk::GetResult() const {
362   return model_->result();
363 }
364
365 // static
366 void OmniboxPopupViewGtk::SetupLayoutForMatch(
367     PangoLayout* layout,
368     const string16& text,
369     const AutocompleteMatch::ACMatchClassifications& classifications,
370     const GdkColor* base_color,
371     const GdkColor* dim_color,
372     const GdkColor* url_color,
373     const std::string& prefix_text) {
374   // In RTL, mark text with left-to-right embedding mark if there is no strong
375   // RTL characters inside it, so the ending punctuation displays correctly
376   // and the eliding ellipsis displays correctly. We only mark the text with
377   // LRE. Wrapping it with LRE and PDF by calling AdjustStringForLocaleDirection
378   // or WrapStringWithLTRFormatting will render the elllipsis at the left of the
379   // elided pure LTR text.
380   bool marked_with_lre = false;
381   string16 localized_text = text;
382   // Pango is really easy to overflow and send into a computational death
383   // spiral that can corrupt the screen. Assume that we'll never have more than
384   // 2000 characters, which should be a safe assumption until we all get robot
385   // eyes. http://crbug.com/66576
386   if (localized_text.length() > 2000)
387     localized_text = localized_text.substr(0, 2000);
388   bool is_rtl = base::i18n::IsRTL();
389   if (is_rtl && !base::i18n::StringContainsStrongRTLChars(localized_text)) {
390     localized_text.insert(0, 1, base::i18n::kLeftToRightEmbeddingMark);
391     marked_with_lre = true;
392   }
393
394   // We can have a prefix, or insert additional characters while processing the
395   // classifications.  We need to take this in to account when we translate the
396   // UTF-16 offsets in the classification into text_utf8 byte offsets.
397   size_t additional_offset = prefix_text.length();  // Length in utf-8 bytes.
398   std::string text_utf8 = prefix_text + UTF16ToUTF8(localized_text);
399
400   PangoAttrList* attrs = pango_attr_list_new();
401
402   // TODO(deanm): This is a hack, just to handle coloring prefix_text.
403   // Hopefully I can clean up the match situation a bit and this will
404   // come out cleaner.  For now, apply the base color to the whole text
405   // so that our prefix will have the base color applied.
406   PangoAttribute* base_fg_attr = pango_attr_foreground_new(
407       base_color->red, base_color->green, base_color->blue);
408   pango_attr_list_insert(attrs, base_fg_attr);  // Ownership taken.
409
410   // Walk through the classifications, they are linear, in order, and should
411   // cover the entire text.  We create a bunch of overlapping attributes,
412   // extending from the offset to the end of the string.  The ones created
413   // later will override the previous ones, meaning we will still setup each
414   // portion correctly, we just don't need to compute the end offset.
415   for (ACMatchClassifications::const_iterator i = classifications.begin();
416        i != classifications.end(); ++i) {
417     size_t offset = GetUTF8Offset(localized_text, i->offset) +
418                     additional_offset;
419
420     // TODO(deanm): All the colors should probably blend based on whether this
421     // result is selected or not.  This would include the green URLs.  Right
422     // now the caller is left to blend only the base color.  Do we need to
423     // handle things like DIM urls?  Turns out DIM means something different
424     // than you'd think, all of the description text is not DIM, it is a
425     // special case that is not very common, but we should figure out and
426     // support it.
427     const GdkColor* color = base_color;
428     if (i->style & ACMatchClassification::URL) {
429       color = url_color;
430       // Insert a left to right embedding to make sure that URLs are shown LTR.
431       if (is_rtl && !marked_with_lre) {
432         std::string lre(kLRE);
433         text_utf8.insert(offset, lre);
434         additional_offset += lre.length();
435       }
436     }
437
438     if (i->style & ACMatchClassification::DIM)
439       color = dim_color;
440
441     PangoAttribute* fg_attr = pango_attr_foreground_new(
442         color->red, color->green, color->blue);
443     fg_attr->start_index = offset;
444     pango_attr_list_insert(attrs, fg_attr);  // Ownership taken.
445
446     // Matched portions are bold, otherwise use the normal weight.
447     PangoWeight weight = (i->style & ACMatchClassification::MATCH) ?
448         PANGO_WEIGHT_BOLD : PANGO_WEIGHT_NORMAL;
449     PangoAttribute* weight_attr = pango_attr_weight_new(weight);
450     weight_attr->start_index = offset;
451     pango_attr_list_insert(attrs, weight_attr);  // Ownership taken.
452   }
453
454   pango_layout_set_text(layout, text_utf8.data(), text_utf8.length());
455   pango_layout_set_attributes(layout, attrs);  // Ref taken.
456   pango_attr_list_unref(attrs);
457 }
458
459 void OmniboxPopupViewGtk::Show(size_t num_results) {
460   gint origin_x, origin_y;
461   GdkWindow* gdk_window = gtk_widget_get_window(location_bar_);
462   gdk_window_get_origin(gdk_window, &origin_x, &origin_y);
463   GtkAllocation allocation;
464   gtk_widget_get_allocation(location_bar_, &allocation);
465
466   int horizontal_offset = 1;
467   gtk_window_move(GTK_WINDOW(window_),
468       origin_x + allocation.x - kBorderThickness + horizontal_offset,
469       origin_y + allocation.y + allocation.height - kBorderThickness - 1 +
470           kVerticalOffset);
471   gtk_widget_set_size_request(window_,
472       allocation.width + (kBorderThickness * 2) - (horizontal_offset * 2),
473       (num_results * kHeightPerResult) + (kBorderThickness * 2));
474   gtk_widget_show(window_);
475   StackWindow();
476   opened_ = true;
477 }
478
479 void OmniboxPopupViewGtk::Hide() {
480   gtk_widget_hide(window_);
481   opened_ = false;
482 }
483
484 void OmniboxPopupViewGtk::StackWindow() {
485   gfx::NativeView omnibox_view = omnibox_view_->GetNativeView();
486   DCHECK(GTK_IS_WIDGET(omnibox_view));
487   GtkWidget* toplevel = gtk_widget_get_toplevel(omnibox_view);
488   DCHECK(gtk_widget_is_toplevel(toplevel));
489   ui::StackPopupWindow(window_, toplevel);
490 }
491
492 void OmniboxPopupViewGtk::AcceptLine(size_t line,
493                                      WindowOpenDisposition disposition) {
494   // OpenMatch() may close the popup, which will clear the result set and, by
495   // extension, |match| and its contents.  So copy the relevant match out to
496   // make sure it stays alive until the call completes.
497   AutocompleteMatch match = GetResult().match_at(line);
498   omnibox_view_->OpenMatch(match, disposition, GURL(), line);
499 }
500
501 gfx::Image OmniboxPopupViewGtk::IconForMatch(
502     const AutocompleteMatch& match,
503     bool selected,
504     bool is_selected_keyword) {
505   const gfx::Image image = model_->GetIconIfExtensionMatch(match);
506   if (!image.IsEmpty())
507     return image;
508
509   int icon;
510   if (is_selected_keyword)
511     icon = IDR_OMNIBOX_TTS;
512   else if (match.starred)
513     icon = IDR_OMNIBOX_STAR;
514   else
515     icon = AutocompleteMatch::TypeToIcon(match.type);
516
517   if (selected) {
518     switch (icon) {
519       case IDR_OMNIBOX_EXTENSION_APP:
520         icon = IDR_OMNIBOX_EXTENSION_APP_DARK;
521         break;
522       case IDR_OMNIBOX_HTTP:
523         icon = IDR_OMNIBOX_HTTP_DARK;
524         break;
525       case IDR_OMNIBOX_SEARCH:
526         icon = IDR_OMNIBOX_SEARCH_DARK;
527         break;
528       case IDR_OMNIBOX_STAR:
529         icon = IDR_OMNIBOX_STAR_DARK;
530         break;
531       case IDR_OMNIBOX_TTS:
532         icon = IDR_OMNIBOX_TTS_DARK;
533         break;
534       default:
535         NOTREACHED();
536         break;
537     }
538   }
539
540   return theme_service_->GetImageNamed(icon);
541 }
542
543 void OmniboxPopupViewGtk::GetVisibleMatchForInput(
544     size_t index,
545     const AutocompleteMatch** match,
546     bool* is_selected_keyword) {
547   const AutocompleteResult& result = GetResult();
548
549   if (result.match_at(index).associated_keyword.get() &&
550       model_->selected_line() == index &&
551       model_->selected_line_state() == OmniboxPopupModel::KEYWORD) {
552     *match = result.match_at(index).associated_keyword.get();
553     *is_selected_keyword = true;
554     return;
555   }
556
557   *match = &result.match_at(index);
558   *is_selected_keyword = false;
559 }
560
561 gboolean OmniboxPopupViewGtk::HandleMotion(GtkWidget* widget,
562                                            GdkEventMotion* event) {
563   if (!IsOpen())
564     return FALSE;
565
566   // TODO(deanm): Windows has a bunch of complicated logic here.
567   size_t line = LineFromY(static_cast<int>(event->y));
568   // There is both a hovered and selected line, hovered just means your mouse
569   // is over it, but selected is what's showing in the location edit.
570   model_->SetHoveredLine(line);
571   // Select the line if the user has the left mouse button down.
572   if (!ignore_mouse_drag_ && (event->state & GDK_BUTTON1_MASK))
573     model_->SetSelectedLine(line, false, false);
574   return TRUE;
575 }
576
577 gboolean OmniboxPopupViewGtk::HandleButtonPress(GtkWidget* widget,
578                                                 GdkEventButton* event) {
579   if (!IsOpen())
580     return FALSE;
581
582   ignore_mouse_drag_ = false;
583   // Very similar to HandleMotion.
584   size_t line = LineFromY(static_cast<int>(event->y));
585   model_->SetHoveredLine(line);
586   if (event->button == 1)
587     model_->SetSelectedLine(line, false, false);
588   return TRUE;
589 }
590
591 gboolean OmniboxPopupViewGtk::HandleButtonRelease(GtkWidget* widget,
592                                                   GdkEventButton* event) {
593   if (!IsOpen())
594     return FALSE;
595
596   if (ignore_mouse_drag_) {
597     // See header comment about this flag.
598     ignore_mouse_drag_ = false;
599     return TRUE;
600   }
601
602   size_t line = LineFromY(static_cast<int>(event->y));
603   switch (event->button) {
604     case 1:  // Left click.
605       AcceptLine(line, CURRENT_TAB);
606       break;
607     case 2:  // Middle click.
608       AcceptLine(line, NEW_BACKGROUND_TAB);
609       break;
610     default:
611       // Don't open the result.
612       break;
613   }
614   return TRUE;
615 }
616
617 gboolean OmniboxPopupViewGtk::HandleExpose(GtkWidget* widget,
618                                            GdkEventExpose* event) {
619   bool ltr = !base::i18n::IsRTL();
620   const AutocompleteResult& result = GetResult();
621
622   gfx::Rect window_rect = GetWindowRect(event->window);
623   gfx::Rect damage_rect = gfx::Rect(event->area);
624   // Handle when our window is super narrow.  A bunch of the calculations
625   // below would go negative, and really we're not going to fit anything
626   // useful in such a small window anyway.  Just don't paint anything.
627   // This means we won't draw the border, but, yeah, whatever.
628   // TODO(deanm): Make the code more robust and remove this check.
629   if (window_rect.width() < (kIconAreaWidth * 3))
630     return TRUE;
631
632   cairo_t* cr = gdk_cairo_create(gtk_widget_get_window(widget));
633   gdk_cairo_rectangle(cr, &event->area);
634   cairo_clip(cr);
635
636   // This assert is kinda ugly, but it would be more currently unneeded work
637   // to support painting a border that isn't 1 pixel thick.  There is no point
638   // in writing that code now, and explode if that day ever comes.
639   COMPILE_ASSERT(kBorderThickness == 1, border_1px_implied);
640   // Draw the 1px border around the entire window.
641   gdk_cairo_set_source_color(cr, &border_color_);
642   cairo_rectangle(cr, 0, 0, window_rect.width(), window_rect.height());
643   cairo_stroke(cr);
644
645   pango_layout_set_height(layout_, kHeightPerResult * PANGO_SCALE);
646
647   for (size_t i = GetHiddenMatchCount(); i < result.size(); ++i) {
648     gfx::Rect line_rect = GetRectForLine(i, window_rect.width());
649     // Only repaint and layout damaged lines.
650     if (!line_rect.Intersects(damage_rect))
651       continue;
652
653     const AutocompleteMatch* match = NULL;
654     bool is_selected_keyword = false;
655     GetVisibleMatchForInput(i, &match, &is_selected_keyword);
656     bool is_selected = (model_->selected_line() == i);
657     bool is_hovered = (model_->hovered_line() == i);
658     if (is_selected || is_hovered) {
659       gdk_cairo_set_source_color(cr, is_selected ? &selected_background_color_ :
660                                  &hovered_background_color_);
661       // This entry is selected or hovered, fill a rect with the color.
662       cairo_rectangle(cr, line_rect.x(), line_rect.y(),
663                       line_rect.width(), line_rect.height());
664       cairo_fill(cr);
665     }
666
667     int icon_start_x = ltr ? kIconLeftPadding :
668         (line_rect.width() - kIconLeftPadding - kIconWidth);
669     // Draw the icon for this result.
670     gtk_util::DrawFullImage(cr, widget,
671                             IconForMatch(*match, is_selected,
672                                          is_selected_keyword),
673                             icon_start_x, line_rect.y() + kIconTopPadding);
674
675     // Draw the results text vertically centered in the results space.
676     // First draw the contents / url, but don't let it take up the whole width
677     // if there is also a description to be shown.
678     bool has_description = !match->description.empty();
679     int text_width = window_rect.width() - (kIconAreaWidth + kRightPadding);
680     int allocated_content_width = has_description ?
681         static_cast<int>(text_width * kContentWidthPercentage) : text_width;
682     pango_layout_set_width(layout_, allocated_content_width * PANGO_SCALE);
683
684     // Note: We force to URL to LTR for all text directions.
685     SetupLayoutForMatch(layout_, match->contents, match->contents_class,
686                         is_selected ? &selected_content_text_color_ :
687                             &content_text_color_,
688                         is_selected ? &selected_content_dim_text_color_ :
689                             &content_dim_text_color_,
690                         is_selected ? &url_selected_text_color_ :
691                             &url_text_color_,
692                         std::string());
693
694     int actual_content_width, actual_content_height;
695     pango_layout_get_size(layout_,
696         &actual_content_width, &actual_content_height);
697     actual_content_width /= PANGO_SCALE;
698     actual_content_height /= PANGO_SCALE;
699
700     // DCHECK_LT(actual_content_height, kHeightPerResult);  // Font is too tall.
701     // Center the text within the line.
702     int content_y = std::max(line_rect.y(),
703         line_rect.y() + ((kHeightPerResult - actual_content_height) / 2));
704
705     cairo_save(cr);
706     cairo_move_to(cr,
707                   ltr ? kIconAreaWidth :
708                         (text_width - actual_content_width),
709                   content_y);
710     pango_cairo_show_layout(cr, layout_);
711     cairo_restore(cr);
712
713     if (has_description) {
714       pango_layout_set_width(layout_,
715           (text_width - actual_content_width) * PANGO_SCALE);
716
717       // In Windows, a boolean "force_dim" is passed as true for the
718       // description.  Here, we pass the dim text color for both normal and dim,
719       // to accomplish the same thing.
720       SetupLayoutForMatch(layout_, match->description, match->description_class,
721                           is_selected ? &selected_content_dim_text_color_ :
722                               &content_dim_text_color_,
723                           is_selected ? &selected_content_dim_text_color_ :
724                               &content_dim_text_color_,
725                           is_selected ? &url_selected_text_color_ :
726                               &url_text_color_,
727                           std::string(" - "));
728       gint actual_description_width;
729       pango_layout_get_size(layout_, &actual_description_width, NULL);
730
731       cairo_save(cr);
732       cairo_move_to(cr, ltr ?
733                     (kIconAreaWidth + actual_content_width) :
734                     (text_width - actual_content_width -
735                      (actual_description_width / PANGO_SCALE)),
736                     content_y);
737       pango_cairo_show_layout(cr, layout_);
738       cairo_restore(cr);
739     }
740
741     if (match->associated_keyword.get()) {
742       // If this entry has an associated keyword, draw the arrow at the extreme
743       // other side of the omnibox.
744       icon_start_x = ltr ? (line_rect.width() - kIconLeftPadding - kIconWidth) :
745           kIconLeftPadding;
746       // Draw the icon for this result.
747       gtk_util::DrawFullImage(cr, widget,
748                               theme_service_->GetImageNamed(
749                                   is_selected ? IDR_OMNIBOX_TTS_DARK :
750                                   IDR_OMNIBOX_TTS),
751                               icon_start_x, line_rect.y() + kIconTopPadding);
752     }
753   }
754
755   cairo_destroy(cr);
756   return TRUE;
757 }