- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / gtk / find_bar_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/find_bar_gtk.h"
6
7 #include <gdk/gdkkeysyms.h>
8
9 #include <algorithm>
10 #include <string>
11 #include <vector>
12
13 #include "base/debug/trace_event.h"
14 #include "base/i18n/rtl.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "chrome/browser/chrome_notification_types.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/browser/themes/theme_properties.h"
21 #include "chrome/browser/ui/browser.h"
22 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
23 #include "chrome/browser/ui/find_bar/find_bar_state.h"
24 #include "chrome/browser/ui/find_bar/find_bar_state_factory.h"
25 #include "chrome/browser/ui/find_bar/find_notification_details.h"
26 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
27 #include "chrome/browser/ui/gtk/browser_window_gtk.h"
28 #include "chrome/browser/ui/gtk/custom_button.h"
29 #include "chrome/browser/ui/gtk/gtk_theme_service.h"
30 #include "chrome/browser/ui/gtk/gtk_util.h"
31 #include "chrome/browser/ui/gtk/nine_box.h"
32 #include "chrome/browser/ui/gtk/slide_animator_gtk.h"
33 #include "chrome/browser/ui/gtk/tab_contents_container_gtk.h"
34 #include "chrome/browser/ui/gtk/tabs/tab_strip_gtk.h"
35 #include "chrome/browser/ui/gtk/view_id_util.h"
36 #include "content/public/browser/native_web_keyboard_event.h"
37 #include "content/public/browser/notification_source.h"
38 #include "content/public/browser/render_view_host.h"
39 #include "content/public/browser/web_contents.h"
40 #include "content/public/browser/web_contents_view.h"
41 #include "grit/generated_resources.h"
42 #include "grit/theme_resources.h"
43 #include "grit/ui_resources.h"
44 #include "ui/base/gtk/gtk_floating_container.h"
45 #include "ui/base/gtk/gtk_hig_constants.h"
46 #include "ui/base/l10n/l10n_util.h"
47 #include "ui/base/resource/resource_bundle.h"
48 #include "ui/gfx/image/cairo_cached_surface.h"
49 #include "ui/gfx/image/image.h"
50
51 using content::NativeWebKeyboardEvent;
52
53 namespace {
54
55 // Used as the color of the text in the entry box and the text for the results
56 // label for failure searches.
57 const GdkColor& kEntryTextColor = ui::kGdkBlack;
58
59 // Used as the color of the background of the entry box and the background of
60 // the find label for successful searches.
61 const GdkColor& kEntryBackgroundColor = ui::kGdkWhite;
62 const GdkColor kFindFailureBackgroundColor = GDK_COLOR_RGB(255, 102, 102);
63 const GdkColor kFindSuccessTextColor = GDK_COLOR_RGB(178, 178, 178);
64
65 // Padding around the container.
66 const int kBarPaddingTop = 2;
67 const int kBarPaddingBottom = 3;
68 const int kEntryPaddingLeft = 6;
69 const int kCloseButtonPadding = 3;
70 const int kBarPaddingRight = 4;
71
72 // The height of the findbar dialog, as dictated by the size of the background
73 // images.
74 const int kFindBarHeight = 32;
75
76 // The default width of the findbar dialog. It may get smaller if the window
77 // is narrow.
78 const int kFindBarWidth = 303;
79
80 // The size of the "rounded" corners.
81 const int kCornerSize = 3;
82
83 enum FrameType {
84   FRAME_MASK,
85   FRAME_STROKE,
86 };
87
88 // Returns a list of points that either form the outline of the status bubble
89 // (|type| == FRAME_MASK) or form the inner border around the inner edge
90 // (|type| == FRAME_STROKE).
91 std::vector<GdkPoint> MakeFramePolygonPoints(int width,
92                                              int height,
93                                              FrameType type) {
94   using gtk_util::MakeBidiGdkPoint;
95   std::vector<GdkPoint> points;
96
97   bool ltr = !base::i18n::IsRTL();
98   // If we have a stroke, we have to offset some of our points by 1 pixel.
99   // We have to inset by 1 pixel when we draw horizontal lines that are on the
100   // bottom or when we draw vertical lines that are closer to the end (end is
101   // right for ltr).
102   int y_off = (type == FRAME_MASK) ? 0 : -1;
103   // We use this one for LTR.
104   int x_off_l = ltr ? y_off : 0;
105   // We use this one for RTL.
106   int x_off_r = !ltr ? -y_off : 0;
107
108   // Top left corner
109   points.push_back(MakeBidiGdkPoint(x_off_r, 0, width, ltr));
110   points.push_back(MakeBidiGdkPoint(
111       kCornerSize + x_off_r, kCornerSize, width, ltr));
112
113   // Bottom left corner
114   points.push_back(MakeBidiGdkPoint(
115       kCornerSize + x_off_r, height - kCornerSize, width, ltr));
116   points.push_back(MakeBidiGdkPoint(
117       (2 * kCornerSize) + x_off_l, height + y_off,
118       width, ltr));
119
120   // Bottom right corner
121   points.push_back(MakeBidiGdkPoint(
122       width - (2 * kCornerSize) + x_off_r, height + y_off,
123       width, ltr));
124   points.push_back(MakeBidiGdkPoint(
125       width - kCornerSize + x_off_l, height - kCornerSize, width, ltr));
126
127   // Top right corner
128   points.push_back(MakeBidiGdkPoint(
129       width - kCornerSize + x_off_l, kCornerSize, width, ltr));
130   points.push_back(MakeBidiGdkPoint(width + x_off_l, 0, width, ltr));
131
132   return points;
133 }
134
135 // Give the findbar dialog its unique shape using images.
136 void SetDialogShape(GtkWidget* widget) {
137   static NineBox* dialog_shape = NULL;
138   if (!dialog_shape) {
139     dialog_shape = new NineBox(
140       IDR_FIND_DLG_LEFT_BACKGROUND,
141       IDR_FIND_DLG_MIDDLE_BACKGROUND,
142       IDR_FIND_DLG_RIGHT_BACKGROUND,
143       0, 0, 0, 0, 0, 0);
144   }
145
146   dialog_shape->ContourWidget(widget);
147 }
148
149 // Return a ninebox that will paint the border of the findbar dialog. This is
150 // shared across all instances of the findbar. Do not free the returned pointer.
151 const NineBox* GetDialogBorder() {
152   static NineBox* dialog_border = NULL;
153   if (!dialog_border) {
154     dialog_border = new NineBox(
155       IDR_FIND_DIALOG_LEFT,
156       IDR_FIND_DIALOG_MIDDLE,
157       IDR_FIND_DIALOG_RIGHT,
158       0, 0, 0, 0, 0, 0);
159   }
160
161   return dialog_border;
162 }
163
164 // Like gtk_util::CreateGtkBorderBin, but allows control over the alignment and
165 // returns both the event box and the alignment so we can modify it during its
166 // lifetime (i.e. during a theme change).
167 void BuildBorder(GtkWidget* child,
168                  int padding_top, int padding_bottom, int padding_left,
169                  int padding_right,
170                  GtkWidget** ebox, GtkWidget** alignment) {
171   *ebox = gtk_event_box_new();
172   *alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
173   gtk_alignment_set_padding(GTK_ALIGNMENT(*alignment),
174                             padding_top, padding_bottom, padding_left,
175                             padding_right);
176   gtk_container_add(GTK_CONTAINER(*alignment), child);
177   gtk_container_add(GTK_CONTAINER(*ebox), *alignment);
178 }
179
180 }  // namespace
181
182 FindBarGtk::FindBarGtk(BrowserWindowGtk* window)
183     : browser_(window->browser()),
184       window_(window),
185       theme_service_(GtkThemeService::GetFrom(browser_->profile())),
186       container_width_(-1),
187       container_height_(-1),
188       match_label_failure_(false),
189       ignore_changed_signal_(false) {
190   InitWidgets();
191   ViewIDUtil::SetID(text_entry_, VIEW_ID_FIND_IN_PAGE_TEXT_FIELD);
192
193   // Insert the widget into the browser gtk hierarchy.
194   window_->AddFindBar(this);
195
196   // Hook up signals after the widget has been added to the hierarchy so the
197   // widget will be realized.
198   g_signal_connect(text_entry_, "changed",
199                    G_CALLBACK(OnChanged), this);
200   g_signal_connect_after(text_entry_, "key-press-event",
201                          G_CALLBACK(OnKeyPressEvent), this);
202   g_signal_connect_after(text_entry_, "key-release-event",
203                          G_CALLBACK(OnKeyReleaseEvent), this);
204   // When the user tabs to us or clicks on us, save where the focus used to
205   // be.
206   g_signal_connect(text_entry_, "focus",
207                    G_CALLBACK(OnFocus), this);
208   gtk_widget_add_events(text_entry_, GDK_BUTTON_PRESS_MASK);
209   g_signal_connect(text_entry_, "button-press-event",
210                    G_CALLBACK(OnButtonPress), this);
211   g_signal_connect(text_entry_, "move-cursor", G_CALLBACK(OnMoveCursor), this);
212   g_signal_connect(text_entry_, "activate", G_CALLBACK(OnActivateThunk), this);
213   g_signal_connect(text_entry_, "direction-changed",
214                    G_CALLBACK(OnWidgetDirectionChanged), this);
215   g_signal_connect(text_entry_, "focus-in-event",
216                    G_CALLBACK(OnFocusInThunk), this);
217   g_signal_connect(text_entry_, "focus-out-event",
218                    G_CALLBACK(OnFocusOutThunk), this);
219   g_signal_connect(container_, "expose-event",
220                    G_CALLBACK(OnExpose), this);
221 }
222
223 FindBarGtk::~FindBarGtk() {
224 }
225
226 void FindBarGtk::InitWidgets() {
227   // The find bar is basically an hbox with a gtkentry (text box) followed by 3
228   // buttons (previous result, next result, close).  We wrap the hbox in a gtk
229   // alignment and a gtk event box to get the padding and light blue
230   // background. We put that event box in a fixed in order to control its
231   // lateral position. We put that fixed in a SlideAnimatorGtk in order to get
232   // the slide effect.
233   GtkWidget* hbox = gtk_hbox_new(false, 0);
234   container_ = gtk_util::CreateGtkBorderBin(hbox, NULL,
235       kBarPaddingTop, kBarPaddingBottom,
236       kEntryPaddingLeft, kBarPaddingRight);
237   gtk_widget_set_size_request(container_, kFindBarWidth, kFindBarHeight);
238   ViewIDUtil::SetID(container_, VIEW_ID_FIND_IN_PAGE);
239   gtk_widget_set_app_paintable(container_, TRUE);
240
241   slide_widget_.reset(new SlideAnimatorGtk(container_,
242                                            SlideAnimatorGtk::DOWN,
243                                            0, false, true, NULL));
244
245   GtkWidget* close_alignment = gtk_alignment_new(0, 0.6, 1, 0);
246   close_button_.reset(CustomDrawButton::CloseButtonBar(theme_service_));
247   gtk_container_add(GTK_CONTAINER(close_alignment), close_button_->widget());
248   gtk_box_pack_end(GTK_BOX(hbox), close_alignment, FALSE, FALSE,
249                    kCloseButtonPadding);
250   g_signal_connect(close_button_->widget(), "clicked",
251                    G_CALLBACK(OnClickedThunk), this);
252   gtk_widget_set_tooltip_text(close_button_->widget(),
253       l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_CLOSE_TOOLTIP).c_str());
254
255   find_next_button_.reset(new CustomDrawButton(theme_service_,
256       IDR_FINDINPAGE_NEXT, IDR_FINDINPAGE_NEXT_H, IDR_FINDINPAGE_NEXT_H,
257       IDR_FINDINPAGE_NEXT_D, GTK_STOCK_GO_DOWN, GTK_ICON_SIZE_MENU));
258   g_signal_connect(find_next_button_->widget(), "clicked",
259                    G_CALLBACK(OnClickedThunk), this);
260   gtk_widget_set_tooltip_text(find_next_button_->widget(),
261       l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_NEXT_TOOLTIP).c_str());
262   gtk_box_pack_end(GTK_BOX(hbox), find_next_button_->widget(),
263                    FALSE, FALSE, 0);
264
265   find_previous_button_.reset(new CustomDrawButton(theme_service_,
266       IDR_FINDINPAGE_PREV, IDR_FINDINPAGE_PREV_H, IDR_FINDINPAGE_PREV_H,
267       IDR_FINDINPAGE_PREV_D, GTK_STOCK_GO_UP, GTK_ICON_SIZE_MENU));
268   g_signal_connect(find_previous_button_->widget(), "clicked",
269                    G_CALLBACK(OnClickedThunk), this);
270   gtk_widget_set_tooltip_text(find_previous_button_->widget(),
271       l10n_util::GetStringUTF8(IDS_FIND_IN_PAGE_PREVIOUS_TOOLTIP).c_str());
272   gtk_box_pack_end(GTK_BOX(hbox), find_previous_button_->widget(),
273                    FALSE, FALSE, 0);
274
275   // Make a box for the edit and match count widgets.
276   GtkWidget* content_hbox = gtk_hbox_new(FALSE, 0);
277
278   text_entry_ = gtk_entry_new();
279   gtk_entry_set_has_frame(GTK_ENTRY(text_entry_), FALSE);
280
281   match_count_label_ = gtk_label_new(NULL);
282   // This line adds padding on the sides so that the label has even padding on
283   // all edges.
284   gtk_misc_set_padding(GTK_MISC(match_count_label_), 2, 0);
285   match_count_event_box_ = gtk_event_box_new();
286   GtkWidget* match_count_centerer = gtk_vbox_new(FALSE, 0);
287   gtk_box_pack_start(GTK_BOX(match_count_centerer), match_count_event_box_,
288                      TRUE, TRUE, 0);
289   gtk_container_set_border_width(GTK_CONTAINER(match_count_centerer), 1);
290   gtk_container_add(GTK_CONTAINER(match_count_event_box_), match_count_label_);
291
292   gtk_box_pack_end(GTK_BOX(content_hbox), match_count_centerer,
293                    FALSE, FALSE, 0);
294   gtk_box_pack_end(GTK_BOX(content_hbox), text_entry_, TRUE, TRUE, 0);
295
296   // This event box is necessary to color in the area above and below the match
297   // count label, and is where we draw the entry background onto in GTK mode.
298   BuildBorder(content_hbox, 0, 0, 0, 0,
299               &content_event_box_, &content_alignment_);
300   gtk_widget_set_app_paintable(content_event_box_, TRUE);
301   g_signal_connect(content_event_box_, "expose-event",
302                    G_CALLBACK(OnContentEventBoxExpose), this);
303
304   // This alignment isn't centered and is used for spacing in chrome theme
305   // mode. (It's also used in GTK mode for padding because left padding doesn't
306   // equal bottom padding naturally.)
307   BuildBorder(content_event_box_, 2, 2, 2, 0,
308               &border_bin_, &border_bin_alignment_);
309   gtk_box_pack_end(GTK_BOX(hbox), border_bin_, TRUE, TRUE, 0);
310
311   theme_service_->InitThemesFor(this);
312   registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
313                  content::Source<ThemeService>(theme_service_));
314
315   g_signal_connect(widget(), "parent-set", G_CALLBACK(OnParentSet), this);
316
317   // We take care to avoid showing the slide animator widget.
318   gtk_widget_show_all(container_);
319   gtk_widget_show(widget());
320 }
321
322 FindBarController* FindBarGtk::GetFindBarController() const {
323   return find_bar_controller_;
324 }
325
326 void FindBarGtk::SetFindBarController(FindBarController* find_bar_controller) {
327   find_bar_controller_ = find_bar_controller;
328 }
329
330 void FindBarGtk::Show(bool animate) {
331   if (animate) {
332     slide_widget_->Open();
333     selection_rect_ = gfx::Rect();
334     Reposition();
335     GdkWindow* gdk_window = gtk_widget_get_window(container_);
336     if (gdk_window)
337       gdk_window_raise(gdk_window);
338   } else {
339     slide_widget_->OpenWithoutAnimation();
340   }
341 }
342
343 void FindBarGtk::Hide(bool animate) {
344   if (animate)
345     slide_widget_->Close();
346   else
347     slide_widget_->CloseWithoutAnimation();
348 }
349
350 void FindBarGtk::SetFocusAndSelection() {
351   StoreOutsideFocus();
352   gtk_widget_grab_focus(text_entry_);
353   // Select all the text.
354   gtk_editable_select_region(GTK_EDITABLE(text_entry_), 0, -1);
355 }
356
357 void FindBarGtk::ClearResults(const FindNotificationDetails& results) {
358   UpdateUIForFindResult(results, string16());
359 }
360
361 void FindBarGtk::StopAnimation() {
362   slide_widget_->End();
363 }
364
365 void FindBarGtk::MoveWindowIfNecessary(const gfx::Rect& selection_rect,
366                                        bool no_redraw) {
367   // Not moving the window on demand, so do nothing.
368 }
369
370 void FindBarGtk::SetFindTextAndSelectedRange(const string16& find_text,
371                                              const gfx::Range& selected_range) {
372   std::string find_text_utf8 = UTF16ToUTF8(find_text);
373
374   // Ignore the "changed" signal handler because programatically setting the
375   // text should not fire a "changed" event.
376   ignore_changed_signal_ = true;
377   gtk_entry_set_text(GTK_ENTRY(text_entry_), find_text_utf8.c_str());
378   if (selected_range.IsValid()) {
379     gtk_editable_select_region(GTK_EDITABLE(text_entry_),
380                                selected_range.start(), selected_range.end());
381   }
382   ignore_changed_signal_ = false;
383 }
384
385 string16 FindBarGtk::GetFindText() {
386   std::string contents(gtk_entry_get_text(GTK_ENTRY(text_entry_)));
387   return UTF8ToUTF16(contents);
388 }
389
390 gfx::Range FindBarGtk::GetSelectedRange() {
391   gint start, end;
392   gtk_editable_get_selection_bounds(GTK_EDITABLE(text_entry_), &start, &end);
393   return gfx::Range(start, end);
394 }
395
396 void FindBarGtk::UpdateUIForFindResult(const FindNotificationDetails& result,
397                                        const string16& find_text) {
398   selection_rect_ = result.selection_rect();
399   int xposition = GetDialogPosition(result.selection_rect()).x();
400   GtkAllocation allocation;
401   gtk_widget_get_allocation(widget(), &allocation);
402   if (xposition != allocation.x)
403     Reposition();
404
405   // Once we find a match we no longer want to keep track of what had
406   // focus. EndFindSession will then set the focus to the page content.
407   if (result.number_of_matches() > 0)
408     focus_store_.Store(NULL);
409
410   std::string find_text_utf8 = UTF16ToUTF8(find_text);
411   bool have_valid_range =
412       result.number_of_matches() != -1 && result.active_match_ordinal() != -1;
413
414   std::string entry_text(gtk_entry_get_text(GTK_ENTRY(text_entry_)));
415   if (entry_text != find_text_utf8)
416     SetFindTextAndSelectedRange(find_text, gfx::Range(0, find_text.length()));
417
418   if (!find_text.empty() && have_valid_range) {
419     gtk_label_set_text(GTK_LABEL(match_count_label_),
420         l10n_util::GetStringFUTF8(IDS_FIND_IN_PAGE_COUNT,
421             base::IntToString16(result.active_match_ordinal()),
422             base::IntToString16(result.number_of_matches())).c_str());
423     UpdateMatchLabelAppearance(result.number_of_matches() == 0 &&
424                                result.final_update());
425   } else {
426     // If there was no text entered, we don't show anything in the result count
427     // area.
428     gtk_label_set_text(GTK_LABEL(match_count_label_), "");
429     UpdateMatchLabelAppearance(false);
430   }
431 }
432
433 void FindBarGtk::AudibleAlert() {
434   // This call causes a lot of weird bugs, especially when using the custom
435   // frame. TODO(estade): if people complain, re-enable it. See
436   // http://crbug.com/27635 and others.
437   //
438   //   gtk_widget_error_bell(widget());
439 }
440
441 gfx::Rect FindBarGtk::GetDialogPosition(
442     const gfx::Rect& avoid_overlapping_rect) {
443   bool ltr = !base::i18n::IsRTL();
444   // 15 is the size of the scrollbar, copied from ScrollbarThemeChromium.
445   // The height is not used.
446   // At very low browser widths we can wind up with a negative |dialog_bounds|
447   // width, so clamp it to 0.
448   GtkAllocation parent_allocation;
449   gtk_widget_get_allocation(gtk_widget_get_parent(widget()),
450                             &parent_allocation);
451   gfx::Rect dialog_bounds = gfx::Rect(ltr ? 0 : 15, 0,
452       std::max(0, parent_allocation.width - (ltr ? 15 : 0)), 0);
453
454   GtkRequisition req;
455   gtk_widget_size_request(container_, &req);
456   gfx::Size prefsize(req.width, req.height);
457
458   gfx::Rect view_location(
459       ltr ? dialog_bounds.width() - prefsize.width() : dialog_bounds.x(),
460       dialog_bounds.y(), prefsize.width(), prefsize.height());
461   gfx::Rect new_pos = FindBarController::GetLocationForFindbarView(
462       view_location, dialog_bounds, avoid_overlapping_rect);
463
464   return new_pos;
465 }
466
467 bool FindBarGtk::IsFindBarVisible() {
468   return gtk_widget_get_visible(widget());
469 }
470
471 void FindBarGtk::RestoreSavedFocus() {
472   // This function sometimes gets called when we don't have focus. We should do
473   // nothing in this case.
474   if (!gtk_widget_is_focus(text_entry_))
475     return;
476
477   if (focus_store_.widget())
478     gtk_widget_grab_focus(focus_store_.widget());
479   else
480     find_bar_controller_->web_contents()->GetView()->Focus();
481 }
482
483 bool FindBarGtk::HasGlobalFindPasteboard() {
484   return false;
485 }
486
487 void FindBarGtk::UpdateFindBarForChangedWebContents() {
488 }
489
490 FindBarTesting* FindBarGtk::GetFindBarTesting() {
491   return this;
492 }
493
494 void FindBarGtk::Observe(int type,
495                          const content::NotificationSource& source,
496                          const content::NotificationDetails& details) {
497   DCHECK_EQ(type, chrome::NOTIFICATION_BROWSER_THEME_CHANGED);
498
499   // Force reshapings of the find bar window.
500   container_width_ = -1;
501   container_height_ = -1;
502
503   if (theme_service_->UsingNativeTheme()) {
504     gtk_widget_modify_cursor(text_entry_, NULL, NULL);
505     gtk_widget_modify_base(text_entry_, GTK_STATE_NORMAL, NULL);
506     gtk_widget_modify_text(text_entry_, GTK_STATE_NORMAL, NULL);
507
508     // Prevent forced font sizes because it causes the jump up and down
509     // character movement (http://crbug.com/22614), and because it will
510     // prevent centering of the text entry.
511     gtk_util::UndoForceFontSize(text_entry_);
512     gtk_util::UndoForceFontSize(match_count_label_);
513
514     gtk_widget_set_size_request(content_event_box_, -1, -1);
515     gtk_widget_modify_bg(content_event_box_, GTK_STATE_NORMAL, NULL);
516
517     // Replicate the normal GtkEntry behaviour by drawing the entry
518     // background. We set the fake alignment to be the frame thickness.
519     GtkStyle* style = gtk_rc_get_style(text_entry_);
520     gint xborder = style->xthickness;
521     gint yborder = style->ythickness;
522     gtk_alignment_set_padding(GTK_ALIGNMENT(content_alignment_),
523                               yborder, yborder, xborder, xborder);
524
525     // We leave left padding on the left, even in GTK mode, as it's required
526     // for the left margin to be equivalent to the bottom margin.
527     gtk_alignment_set_padding(GTK_ALIGNMENT(border_bin_alignment_),
528                               0, 0, 1, 0);
529
530     // We need this event box to have its own window in GTK mode for doing the
531     // hacky widget rendering.
532     gtk_event_box_set_visible_window(GTK_EVENT_BOX(border_bin_), TRUE);
533     gtk_widget_set_app_paintable(border_bin_, TRUE);
534
535     gtk_misc_set_alignment(GTK_MISC(match_count_label_), 0.5, 0.5);
536   } else {
537     gtk_widget_modify_cursor(text_entry_, &ui::kGdkBlack, &ui::kGdkGray);
538     gtk_widget_modify_base(text_entry_, GTK_STATE_NORMAL,
539                            &kEntryBackgroundColor);
540     gtk_widget_modify_text(text_entry_, GTK_STATE_NORMAL, &kEntryTextColor);
541
542     // Until we switch to vector graphics, force the font size.
543     gtk_util::ForceFontSizePixels(text_entry_, 13.4);  // 13.4px == 10pt @ 96dpi
544     gtk_util::ForceFontSizePixels(match_count_label_, 13.4);
545
546     // Force the text widget height so it lines up with the buttons regardless
547     // of font size.
548     gtk_widget_set_size_request(content_event_box_, -1, 20);
549     gtk_widget_modify_bg(content_event_box_, GTK_STATE_NORMAL,
550                          &kEntryBackgroundColor);
551
552     gtk_alignment_set_padding(GTK_ALIGNMENT(content_alignment_),
553                               0.0, 0.0, 0.0, 0.0);
554
555     gtk_alignment_set_padding(GTK_ALIGNMENT(border_bin_alignment_),
556                               2, 2, 3, 0);
557
558     // We need this event box to be invisible because we're only going to draw
559     // on the background (but we can't take it out of the heiarchy entirely
560     // because we also need it to take up space).
561     gtk_event_box_set_visible_window(GTK_EVENT_BOX(border_bin_), FALSE);
562     gtk_widget_set_app_paintable(border_bin_, FALSE);
563
564     gtk_misc_set_alignment(GTK_MISC(match_count_label_), 0.5, 1.0);
565
566     // This is necessary to make the close button dark enough.
567     ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
568     close_button_->SetBackground(
569         theme_service_->GetColor(ThemeProperties::COLOR_TAB_TEXT),
570         rb.GetImageNamed(IDR_CLOSE_1).AsBitmap(),
571         rb.GetImageNamed(IDR_CLOSE_1).AsBitmap());
572   }
573
574   UpdateMatchLabelAppearance(match_label_failure_);
575 }
576
577 bool FindBarGtk::GetFindBarWindowInfo(gfx::Point* position,
578                                       bool* fully_visible) {
579   if (position)
580     *position = GetPosition();
581
582   if (fully_visible) {
583     *fully_visible = !slide_widget_->IsAnimating() &&
584                      slide_widget_->IsShowing();
585   }
586   return true;
587 }
588
589 string16 FindBarGtk::GetFindSelectedText() {
590   gint cursor_pos;
591   gint selection_bound;
592   g_object_get(G_OBJECT(text_entry_), "cursor-position", &cursor_pos,
593                NULL);
594   g_object_get(G_OBJECT(text_entry_), "selection-bound", &selection_bound,
595                NULL);
596   std::string contents(gtk_entry_get_text(GTK_ENTRY(text_entry_)));
597   return UTF8ToUTF16(contents.substr(cursor_pos, selection_bound));
598 }
599
600 string16 FindBarGtk::GetMatchCountText() {
601   std::string contents(gtk_label_get_text(GTK_LABEL(match_count_label_)));
602   return UTF8ToUTF16(contents);
603 }
604
605 int FindBarGtk::GetWidth() {
606   GtkAllocation allocation;
607   gtk_widget_get_allocation(container_, &allocation);
608   return allocation.width;
609 }
610
611 void FindBarGtk::FindEntryTextInContents(bool forward_search) {
612   content::WebContents* web_contents = find_bar_controller_->web_contents();
613   if (!web_contents)
614     return;
615   FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
616
617   std::string new_contents(gtk_entry_get_text(GTK_ENTRY(text_entry_)));
618
619   if (new_contents.length() > 0) {
620     find_tab_helper->StartFinding(UTF8ToUTF16(new_contents), forward_search,
621                                   false);  // Not case sensitive.
622   } else {
623     // The textbox is empty so we reset.
624     find_tab_helper->StopFinding(FindBarController::kClearSelectionOnPage);
625     UpdateUIForFindResult(find_tab_helper->find_result(), string16());
626
627     // Clearing the text box should also clear the prepopulate state so that
628     // when we close and reopen the Find box it doesn't show the search we
629     // just deleted.
630     FindBarState* find_bar_state = FindBarStateFactory::GetForProfile(
631         browser_->profile());
632     find_bar_state->set_last_prepopulate_text(string16());
633   }
634 }
635
636 void FindBarGtk::UpdateMatchLabelAppearance(bool failure) {
637   match_label_failure_ = failure;
638   bool use_gtk = theme_service_->UsingNativeTheme();
639
640   if (use_gtk) {
641     GtkStyle* style = gtk_rc_get_style(text_entry_);
642     GdkColor normal_bg = style->base[GTK_STATE_NORMAL];
643     GdkColor normal_text = gtk_util::AverageColors(
644         style->text[GTK_STATE_NORMAL], style->base[GTK_STATE_NORMAL]);
645
646     gtk_widget_modify_bg(match_count_event_box_, GTK_STATE_NORMAL,
647                          failure ? &kFindFailureBackgroundColor :
648                          &normal_bg);
649     gtk_widget_modify_fg(match_count_label_, GTK_STATE_NORMAL,
650                          failure ? &kEntryTextColor : &normal_text);
651   } else {
652     gtk_widget_modify_bg(match_count_event_box_, GTK_STATE_NORMAL,
653                          failure ? &kFindFailureBackgroundColor :
654                          &kEntryBackgroundColor);
655     gtk_widget_modify_fg(match_count_label_, GTK_STATE_NORMAL,
656                          failure ? &kEntryTextColor : &kFindSuccessTextColor);
657   }
658 }
659
660 void FindBarGtk::Reposition() {
661   if (!IsFindBarVisible())
662     return;
663
664   // This will trigger an allocate, which allows us to reposition.
665   GtkWidget* parent = gtk_widget_get_parent(widget());
666   if (parent)
667     gtk_widget_queue_resize(parent);
668 }
669
670 void FindBarGtk::StoreOutsideFocus() {
671   // |text_entry_| is the only widget in the find bar that can be focused,
672   // so it's the only one we have to check.
673   // TODO(estade): when we make the find bar buttons focusable, we'll have
674   // to change this (same above in RestoreSavedFocus).
675   if (!gtk_widget_is_focus(text_entry_))
676     focus_store_.Store(text_entry_);
677 }
678
679 bool FindBarGtk::MaybeForwardKeyEventToRenderer(GdkEventKey* event) {
680   switch (event->keyval) {
681     case GDK_Down:
682     case GDK_Up:
683     case GDK_Page_Up:
684     case GDK_Page_Down:
685       break;
686     case GDK_Home:
687     case GDK_End:
688       if ((event->state & gtk_accelerator_get_default_mod_mask()) ==
689           GDK_CONTROL_MASK) {
690         break;
691       }
692     // Fall through.
693     default:
694       return false;
695   }
696
697   content::WebContents* contents = find_bar_controller_->web_contents();
698   if (!contents)
699     return false;
700
701   content::RenderViewHost* render_view_host = contents->GetRenderViewHost();
702
703   // Make sure we don't have a text field element interfering with keyboard
704   // input. Otherwise Up and Down arrow key strokes get eaten. "Nom Nom Nom".
705   render_view_host->ClearFocusedNode();
706
707   NativeWebKeyboardEvent wke(reinterpret_cast<GdkEvent*>(event));
708   render_view_host->ForwardKeyboardEvent(wke);
709   return true;
710 }
711
712 void FindBarGtk::AdjustTextAlignment() {
713   PangoDirection content_dir =
714       pango_find_base_dir(gtk_entry_get_text(GTK_ENTRY(text_entry_)), -1);
715
716   GtkTextDirection widget_dir = gtk_widget_get_direction(text_entry_);
717
718   // Use keymap or widget direction if content does not have strong direction.
719   // It matches the behavior of GtkEntry.
720   if (content_dir == PANGO_DIRECTION_NEUTRAL) {
721     if (gtk_widget_has_focus(text_entry_)) {
722       content_dir = gdk_keymap_get_direction(
723         gdk_keymap_get_for_display(gtk_widget_get_display(text_entry_)));
724     } else {
725       if (widget_dir == GTK_TEXT_DIR_RTL)
726         content_dir = PANGO_DIRECTION_RTL;
727       else
728         content_dir = PANGO_DIRECTION_LTR;
729     }
730   }
731
732   if ((widget_dir == GTK_TEXT_DIR_RTL && content_dir == PANGO_DIRECTION_LTR) ||
733       (widget_dir == GTK_TEXT_DIR_LTR && content_dir == PANGO_DIRECTION_RTL)) {
734     gtk_entry_set_alignment(GTK_ENTRY(text_entry_), 1.0);
735   } else {
736     gtk_entry_set_alignment(GTK_ENTRY(text_entry_), 0.0);
737   }
738 }
739
740 gfx::Point FindBarGtk::GetPosition() {
741   gfx::Point point;
742
743   GtkWidget* parent = gtk_widget_get_parent(widget());
744
745   GValue value = { 0, };
746   g_value_init(&value, G_TYPE_INT);
747   gtk_container_child_get_property(GTK_CONTAINER(parent),
748                                    widget(), "x", &value);
749   point.set_x(g_value_get_int(&value));
750
751   gtk_container_child_get_property(GTK_CONTAINER(parent),
752                                    widget(), "y", &value);
753   point.set_y(g_value_get_int(&value));
754
755   g_value_unset(&value);
756
757   return point;
758 }
759
760 // static
761 void FindBarGtk::OnParentSet(GtkWidget* widget, GtkObject* old_parent,
762                              FindBarGtk* find_bar) {
763   if (!gtk_widget_get_parent(widget))
764     return;
765
766   g_signal_connect(gtk_widget_get_parent(widget), "set-floating-position",
767                    G_CALLBACK(OnSetFloatingPosition), find_bar);
768 }
769
770 // static
771 void FindBarGtk::OnSetFloatingPosition(GtkFloatingContainer* floating_container,
772                                        GtkAllocation* allocation,
773                                        FindBarGtk* find_bar) {
774   GtkWidget* findbar = find_bar->widget();
775
776   int xposition = find_bar->GetDialogPosition(find_bar->selection_rect_).x();
777
778   GValue value = { 0, };
779   g_value_init(&value, G_TYPE_INT);
780   g_value_set_int(&value, xposition);
781   gtk_container_child_set_property(GTK_CONTAINER(floating_container),
782                                    findbar, "x", &value);
783
784   g_value_set_int(&value, 0);
785   gtk_container_child_set_property(GTK_CONTAINER(floating_container),
786                                    findbar, "y", &value);
787   g_value_unset(&value);
788 }
789
790 // static
791 gboolean FindBarGtk::OnChanged(GtkWindow* window, FindBarGtk* find_bar) {
792   find_bar->AdjustTextAlignment();
793
794   if (!find_bar->ignore_changed_signal_)
795     find_bar->FindEntryTextInContents(true);
796
797   return FALSE;
798 }
799
800 // static
801 gboolean FindBarGtk::OnKeyPressEvent(GtkWidget* widget, GdkEventKey* event,
802                                      FindBarGtk* find_bar) {
803   if (find_bar->MaybeForwardKeyEventToRenderer(event)) {
804     return TRUE;
805   } else if (GDK_Escape == event->keyval) {
806     find_bar->find_bar_controller_->EndFindSession(
807         FindBarController::kKeepSelectionOnPage,
808         FindBarController::kKeepResultsInFindBox);
809     return TRUE;
810   } else if (GDK_Return == event->keyval ||
811              GDK_KP_Enter == event->keyval) {
812     if ((event->state & gtk_accelerator_get_default_mod_mask()) ==
813         GDK_CONTROL_MASK) {
814       find_bar->find_bar_controller_->EndFindSession(
815           FindBarController::kActivateSelectionOnPage,
816           FindBarController::kClearResultsInFindBox);
817       return TRUE;
818     }
819
820     bool forward = (event->state & gtk_accelerator_get_default_mod_mask()) !=
821                    GDK_SHIFT_MASK;
822     find_bar->FindEntryTextInContents(forward);
823     return TRUE;
824   } else if (GDK_F3 == event->keyval) {
825     // There is a bug in GTK+ version available with Ubuntu 12.04 which causes
826     // Shift+Fn key combination getting registered as Fn when used with
827     // GTK accelerators. And this broke the search backward functionality with
828     // Shift+F3. This is a workaround to fix the search functionality till we
829     // have the GTK+ fix available. The GTK+ issue is being tracked under
830     // https://bugzilla.gnome.org/show_bug.cgi?id=661973
831     bool forward = (event->state & gtk_accelerator_get_default_mod_mask()) !=
832                    GDK_SHIFT_MASK;
833     find_bar->FindEntryTextInContents(forward);
834     return TRUE;
835   }
836   return FALSE;
837 }
838
839 // static
840 gboolean FindBarGtk::OnKeyReleaseEvent(GtkWidget* widget, GdkEventKey* event,
841                                        FindBarGtk* find_bar) {
842   return find_bar->MaybeForwardKeyEventToRenderer(event);
843 }
844
845 void FindBarGtk::OnClicked(GtkWidget* button) {
846   if (button == close_button_->widget()) {
847     find_bar_controller_->EndFindSession(
848         FindBarController::kKeepSelectionOnPage,
849         FindBarController::kKeepResultsInFindBox);
850   } else if (button == find_previous_button_->widget() ||
851              button == find_next_button_->widget()) {
852     FindEntryTextInContents(button == find_next_button_->widget());
853   } else {
854     NOTREACHED();
855   }
856 }
857
858 // static
859 gboolean FindBarGtk::OnContentEventBoxExpose(GtkWidget* widget,
860                                              GdkEventExpose* event,
861                                              FindBarGtk* bar) {
862   TRACE_EVENT0("ui::gtk", "FindBarGtk::OnContentEventBoxExpose");
863   if (bar->theme_service_->UsingNativeTheme()) {
864     // Draw the text entry background around where we input stuff. Note the
865     // decrement to |width|. We do this because some theme engines
866     // (*cough*Clearlooks*cough*) don't do any blending and use thickness to
867     // make sure that widgets never overlap.
868     int padding = gtk_widget_get_style(widget)->xthickness;
869     GdkRectangle rec;
870     gtk_widget_get_allocation(widget, &rec);
871     rec.width -= padding;
872
873     gtk_util::DrawTextEntryBackground(bar->text_entry_, widget,
874                                       &event->area, &rec);
875   }
876
877   return FALSE;
878 }
879
880 // Used to handle custom painting of |container_|.
881 gboolean FindBarGtk::OnExpose(GtkWidget* widget, GdkEventExpose* e,
882                               FindBarGtk* bar) {
883   TRACE_EVENT0("ui::gtk", "FindBarGtk::OnExpose");
884
885   GtkAllocation allocation;
886   gtk_widget_get_allocation(widget, &allocation);
887
888   if (bar->theme_service_->UsingNativeTheme()) {
889     if (bar->container_width_ != allocation.width ||
890         bar->container_height_ != allocation.height) {
891       std::vector<GdkPoint> mask_points = MakeFramePolygonPoints(
892           allocation.width, allocation.height, FRAME_MASK);
893       GdkRegion* mask_region = gdk_region_polygon(&mask_points[0],
894                                                   mask_points.size(),
895                                                   GDK_EVEN_ODD_RULE);
896       // Reset the shape.
897       GdkWindow* gdk_window = gtk_widget_get_window(widget);
898       gdk_window_shape_combine_region(gdk_window, NULL, 0, 0);
899       gdk_window_shape_combine_region(gdk_window, mask_region, 0, 0);
900       gdk_region_destroy(mask_region);
901
902       bar->container_width_ = allocation.width;
903       bar->container_height_ = allocation.height;
904     }
905
906     GdkDrawable* drawable = GDK_DRAWABLE(e->window);
907     GdkGC* gc = gdk_gc_new(drawable);
908     gdk_gc_set_clip_rectangle(gc, &e->area);
909     GdkColor color = bar->theme_service_->GetBorderColor();
910     gdk_gc_set_rgb_fg_color(gc, &color);
911
912     // Stroke the frame border.
913     std::vector<GdkPoint> points = MakeFramePolygonPoints(
914         allocation.width, allocation.height, FRAME_STROKE);
915     gdk_draw_lines(drawable, gc, &points[0], points.size());
916
917     g_object_unref(gc);
918   } else {
919     if (bar->container_width_ != allocation.width ||
920         bar->container_height_ != allocation.height) {
921       // Reset the shape.
922       gdk_window_shape_combine_region(gtk_widget_get_window(widget),
923                                       NULL, 0, 0);
924       SetDialogShape(bar->container_);
925
926       bar->container_width_ = allocation.width;
927       bar->container_height_ = allocation.height;
928     }
929
930     cairo_t* cr = gdk_cairo_create(gtk_widget_get_window(widget));
931     gdk_cairo_rectangle(cr, &e->area);
932     cairo_clip(cr);
933
934     gfx::Point tabstrip_origin =
935         bar->window_->tabstrip()->GetTabStripOriginForWidget(widget);
936
937     gtk_util::DrawThemedToolbarBackground(widget, cr, e, tabstrip_origin,
938                                           bar->theme_service_);
939
940     // During chrome theme mode, we need to draw the border around content_hbox
941     // now instead of when we render |border_bin_|. We don't use stacked event
942     // boxes to simulate the effect because we need to blend them with this
943     // background.
944     GtkAllocation border_allocation;
945     gtk_widget_get_allocation(bar->border_bin_, &border_allocation);
946
947     // Blit the left part of the background image once on the left.
948     ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
949
950     gfx::CairoCachedSurface* background_left = rb.GetNativeImageNamed(
951         IDR_FIND_BOX_BACKGROUND_LEFT,
952         ui::ResourceBundle::RTL_ENABLED).ToCairo();
953     background_left->SetSource(cr, widget,
954                                border_allocation.x, border_allocation.y);
955     cairo_pattern_set_extend(cairo_get_source(cr), CAIRO_EXTEND_REPEAT);
956     cairo_rectangle(cr, border_allocation.x, border_allocation.y,
957                     background_left->Width(), background_left->Height());
958     cairo_fill(cr);
959
960     // Blit the center part of the background image in all the space between.
961     gfx::CairoCachedSurface* background =
962         rb.GetNativeImageNamed(IDR_FIND_BOX_BACKGROUND).ToCairo();
963     background->SetSource(cr, widget,
964                           border_allocation.x + background_left->Width(),
965                           border_allocation.y);
966     cairo_pattern_set_extend(cairo_get_source(cr), CAIRO_EXTEND_REPEAT);
967     cairo_rectangle(cr,
968                     border_allocation.x + background_left->Width(),
969                     border_allocation.y,
970                     border_allocation.width - background_left->Width(),
971                     background->Height());
972     cairo_fill(cr);
973
974     cairo_destroy(cr);
975
976     // Draw the border.
977     GetDialogBorder()->RenderToWidget(widget);
978   }
979
980   // Propagate to the container's child.
981   GtkWidget* child = gtk_bin_get_child(GTK_BIN(widget));
982   if (child)
983     gtk_container_propagate_expose(GTK_CONTAINER(widget), child, e);
984   return TRUE;
985 }
986
987 // static
988 gboolean FindBarGtk::OnFocus(GtkWidget* text_entry, GtkDirectionType focus,
989                              FindBarGtk* find_bar) {
990   find_bar->StoreOutsideFocus();
991
992   // Continue propagating the event.
993   return FALSE;
994 }
995
996 // static
997 gboolean FindBarGtk::OnButtonPress(GtkWidget* text_entry, GdkEventButton* e,
998                                    FindBarGtk* find_bar) {
999   find_bar->StoreOutsideFocus();
1000
1001   // Continue propagating the event.
1002   return FALSE;
1003 }
1004
1005 // static
1006 void FindBarGtk::OnMoveCursor(GtkEntry* entry, GtkMovementStep step, gint count,
1007                               gboolean selection, FindBarGtk* bar) {
1008   static guint signal_id = g_signal_lookup("move-cursor", GTK_TYPE_ENTRY);
1009
1010   GdkEvent* event = gtk_get_current_event();
1011   if (event) {
1012     if ((event->type == GDK_KEY_PRESS || event->type == GDK_KEY_RELEASE) &&
1013         bar->MaybeForwardKeyEventToRenderer(&(event->key))) {
1014       g_signal_stop_emission(entry, signal_id, 0);
1015     }
1016
1017     gdk_event_free(event);
1018   }
1019 }
1020
1021 void FindBarGtk::OnActivate(GtkWidget* entry) {
1022   FindEntryTextInContents(true);
1023 }
1024
1025 gboolean FindBarGtk::OnFocusIn(GtkWidget* entry, GdkEventFocus* event) {
1026   g_signal_connect(gdk_keymap_get_for_display(gtk_widget_get_display(entry)),
1027                    "direction-changed",
1028                    G_CALLBACK(&OnKeymapDirectionChanged), this);
1029
1030   AdjustTextAlignment();
1031
1032   return FALSE;  // Continue propagation.
1033 }
1034
1035 gboolean FindBarGtk::OnFocusOut(GtkWidget* entry, GdkEventFocus* event) {
1036   g_signal_handlers_disconnect_by_func(
1037       gdk_keymap_get_for_display(gtk_widget_get_display(entry)),
1038       reinterpret_cast<gpointer>(&OnKeymapDirectionChanged), this);
1039
1040   return FALSE;  // Continue propagation.
1041 }