1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/gtk/find_bar_gtk.h"
7 #include <gdk/gdkkeysyms.h>
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"
51 using content::NativeWebKeyboardEvent;
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;
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);
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;
72 // The height of the findbar dialog, as dictated by the size of the background
74 const int kFindBarHeight = 32;
76 // The default width of the findbar dialog. It may get smaller if the window
78 const int kFindBarWidth = 303;
80 // The size of the "rounded" corners.
81 const int kCornerSize = 3;
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,
94 using gtk_util::MakeBidiGdkPoint;
95 std::vector<GdkPoint> points;
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
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;
109 points.push_back(MakeBidiGdkPoint(x_off_r, 0, width, ltr));
110 points.push_back(MakeBidiGdkPoint(
111 kCornerSize + x_off_r, kCornerSize, width, ltr));
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,
120 // Bottom right corner
121 points.push_back(MakeBidiGdkPoint(
122 width - (2 * kCornerSize) + x_off_r, height + y_off,
124 points.push_back(MakeBidiGdkPoint(
125 width - kCornerSize + x_off_l, height - kCornerSize, width, ltr));
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));
135 // Give the findbar dialog its unique shape using images.
136 void SetDialogShape(GtkWidget* widget) {
137 static NineBox* dialog_shape = NULL;
139 dialog_shape = new NineBox(
140 IDR_FIND_DLG_LEFT_BACKGROUND,
141 IDR_FIND_DLG_MIDDLE_BACKGROUND,
142 IDR_FIND_DLG_RIGHT_BACKGROUND,
146 dialog_shape->ContourWidget(widget);
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,
161 return dialog_border;
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,
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,
176 gtk_container_add(GTK_CONTAINER(*alignment), child);
177 gtk_container_add(GTK_CONTAINER(*ebox), *alignment);
182 FindBarGtk::FindBarGtk(BrowserWindowGtk* window)
183 : browser_(window->browser()),
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) {
191 ViewIDUtil::SetID(text_entry_, VIEW_ID_FIND_IN_PAGE_TEXT_FIELD);
193 // Insert the widget into the browser gtk hierarchy.
194 window_->AddFindBar(this);
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
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);
223 FindBarGtk::~FindBarGtk() {
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
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);
241 slide_widget_.reset(new SlideAnimatorGtk(container_,
242 SlideAnimatorGtk::DOWN,
243 0, false, true, NULL));
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());
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(),
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(),
275 // Make a box for the edit and match count widgets.
276 GtkWidget* content_hbox = gtk_hbox_new(FALSE, 0);
278 text_entry_ = gtk_entry_new();
279 gtk_entry_set_has_frame(GTK_ENTRY(text_entry_), FALSE);
281 match_count_label_ = gtk_label_new(NULL);
282 // This line adds padding on the sides so that the label has even padding on
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_,
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_);
292 gtk_box_pack_end(GTK_BOX(content_hbox), match_count_centerer,
294 gtk_box_pack_end(GTK_BOX(content_hbox), text_entry_, TRUE, TRUE, 0);
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);
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);
311 theme_service_->InitThemesFor(this);
312 registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
313 content::Source<ThemeService>(theme_service_));
315 g_signal_connect(widget(), "parent-set", G_CALLBACK(OnParentSet), this);
317 // We take care to avoid showing the slide animator widget.
318 gtk_widget_show_all(container_);
319 gtk_widget_show(widget());
322 FindBarController* FindBarGtk::GetFindBarController() const {
323 return find_bar_controller_;
326 void FindBarGtk::SetFindBarController(FindBarController* find_bar_controller) {
327 find_bar_controller_ = find_bar_controller;
330 void FindBarGtk::Show(bool animate) {
332 slide_widget_->Open();
333 selection_rect_ = gfx::Rect();
335 GdkWindow* gdk_window = gtk_widget_get_window(container_);
337 gdk_window_raise(gdk_window);
339 slide_widget_->OpenWithoutAnimation();
343 void FindBarGtk::Hide(bool animate) {
345 slide_widget_->Close();
347 slide_widget_->CloseWithoutAnimation();
350 void FindBarGtk::SetFocusAndSelection() {
352 gtk_widget_grab_focus(text_entry_);
353 // Select all the text.
354 gtk_editable_select_region(GTK_EDITABLE(text_entry_), 0, -1);
357 void FindBarGtk::ClearResults(const FindNotificationDetails& results) {
358 UpdateUIForFindResult(results, string16());
361 void FindBarGtk::StopAnimation() {
362 slide_widget_->End();
365 void FindBarGtk::MoveWindowIfNecessary(const gfx::Rect& selection_rect,
367 // Not moving the window on demand, so do nothing.
370 void FindBarGtk::SetFindTextAndSelectedRange(const string16& find_text,
371 const gfx::Range& selected_range) {
372 std::string find_text_utf8 = UTF16ToUTF8(find_text);
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());
382 ignore_changed_signal_ = false;
385 string16 FindBarGtk::GetFindText() {
386 std::string contents(gtk_entry_get_text(GTK_ENTRY(text_entry_)));
387 return UTF8ToUTF16(contents);
390 gfx::Range FindBarGtk::GetSelectedRange() {
392 gtk_editable_get_selection_bounds(GTK_EDITABLE(text_entry_), &start, &end);
393 return gfx::Range(start, end);
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)
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);
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;
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()));
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());
426 // If there was no text entered, we don't show anything in the result count
428 gtk_label_set_text(GTK_LABEL(match_count_label_), "");
429 UpdateMatchLabelAppearance(false);
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.
438 // gtk_widget_error_bell(widget());
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()),
451 gfx::Rect dialog_bounds = gfx::Rect(ltr ? 0 : 15, 0,
452 std::max(0, parent_allocation.width - (ltr ? 15 : 0)), 0);
455 gtk_widget_size_request(container_, &req);
456 gfx::Size prefsize(req.width, req.height);
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);
467 bool FindBarGtk::IsFindBarVisible() {
468 return gtk_widget_get_visible(widget());
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_))
477 if (focus_store_.widget())
478 gtk_widget_grab_focus(focus_store_.widget());
480 find_bar_controller_->web_contents()->GetView()->Focus();
483 bool FindBarGtk::HasGlobalFindPasteboard() {
487 void FindBarGtk::UpdateFindBarForChangedWebContents() {
490 FindBarTesting* FindBarGtk::GetFindBarTesting() {
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);
499 // Force reshapings of the find bar window.
500 container_width_ = -1;
501 container_height_ = -1;
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);
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_);
514 gtk_widget_set_size_request(content_event_box_, -1, -1);
515 gtk_widget_modify_bg(content_event_box_, GTK_STATE_NORMAL, NULL);
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);
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_),
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);
535 gtk_misc_set_alignment(GTK_MISC(match_count_label_), 0.5, 0.5);
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);
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);
546 // Force the text widget height so it lines up with the buttons regardless
548 gtk_widget_set_size_request(content_event_box_, -1, 20);
549 gtk_widget_modify_bg(content_event_box_, GTK_STATE_NORMAL,
550 &kEntryBackgroundColor);
552 gtk_alignment_set_padding(GTK_ALIGNMENT(content_alignment_),
555 gtk_alignment_set_padding(GTK_ALIGNMENT(border_bin_alignment_),
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);
564 gtk_misc_set_alignment(GTK_MISC(match_count_label_), 0.5, 1.0);
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());
574 UpdateMatchLabelAppearance(match_label_failure_);
577 bool FindBarGtk::GetFindBarWindowInfo(gfx::Point* position,
578 bool* fully_visible) {
580 *position = GetPosition();
583 *fully_visible = !slide_widget_->IsAnimating() &&
584 slide_widget_->IsShowing();
589 string16 FindBarGtk::GetFindSelectedText() {
591 gint selection_bound;
592 g_object_get(G_OBJECT(text_entry_), "cursor-position", &cursor_pos,
594 g_object_get(G_OBJECT(text_entry_), "selection-bound", &selection_bound,
596 std::string contents(gtk_entry_get_text(GTK_ENTRY(text_entry_)));
597 return UTF8ToUTF16(contents.substr(cursor_pos, selection_bound));
600 string16 FindBarGtk::GetMatchCountText() {
601 std::string contents(gtk_label_get_text(GTK_LABEL(match_count_label_)));
602 return UTF8ToUTF16(contents);
605 int FindBarGtk::GetWidth() {
606 GtkAllocation allocation;
607 gtk_widget_get_allocation(container_, &allocation);
608 return allocation.width;
611 void FindBarGtk::FindEntryTextInContents(bool forward_search) {
612 content::WebContents* web_contents = find_bar_controller_->web_contents();
615 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
617 std::string new_contents(gtk_entry_get_text(GTK_ENTRY(text_entry_)));
619 if (new_contents.length() > 0) {
620 find_tab_helper->StartFinding(UTF8ToUTF16(new_contents), forward_search,
621 false); // Not case sensitive.
623 // The textbox is empty so we reset.
624 find_tab_helper->StopFinding(FindBarController::kClearSelectionOnPage);
625 UpdateUIForFindResult(find_tab_helper->find_result(), string16());
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
630 FindBarState* find_bar_state = FindBarStateFactory::GetForProfile(
631 browser_->profile());
632 find_bar_state->set_last_prepopulate_text(string16());
636 void FindBarGtk::UpdateMatchLabelAppearance(bool failure) {
637 match_label_failure_ = failure;
638 bool use_gtk = theme_service_->UsingNativeTheme();
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]);
646 gtk_widget_modify_bg(match_count_event_box_, GTK_STATE_NORMAL,
647 failure ? &kFindFailureBackgroundColor :
649 gtk_widget_modify_fg(match_count_label_, GTK_STATE_NORMAL,
650 failure ? &kEntryTextColor : &normal_text);
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);
660 void FindBarGtk::Reposition() {
661 if (!IsFindBarVisible())
664 // This will trigger an allocate, which allows us to reposition.
665 GtkWidget* parent = gtk_widget_get_parent(widget());
667 gtk_widget_queue_resize(parent);
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_);
679 bool FindBarGtk::MaybeForwardKeyEventToRenderer(GdkEventKey* event) {
680 switch (event->keyval) {
688 if ((event->state & gtk_accelerator_get_default_mod_mask()) ==
697 content::WebContents* contents = find_bar_controller_->web_contents();
701 content::RenderViewHost* render_view_host = contents->GetRenderViewHost();
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();
707 NativeWebKeyboardEvent wke(reinterpret_cast<GdkEvent*>(event));
708 render_view_host->ForwardKeyboardEvent(wke);
712 void FindBarGtk::AdjustTextAlignment() {
713 PangoDirection content_dir =
714 pango_find_base_dir(gtk_entry_get_text(GTK_ENTRY(text_entry_)), -1);
716 GtkTextDirection widget_dir = gtk_widget_get_direction(text_entry_);
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_)));
725 if (widget_dir == GTK_TEXT_DIR_RTL)
726 content_dir = PANGO_DIRECTION_RTL;
728 content_dir = PANGO_DIRECTION_LTR;
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);
736 gtk_entry_set_alignment(GTK_ENTRY(text_entry_), 0.0);
740 gfx::Point FindBarGtk::GetPosition() {
743 GtkWidget* parent = gtk_widget_get_parent(widget());
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));
751 gtk_container_child_get_property(GTK_CONTAINER(parent),
752 widget(), "y", &value);
753 point.set_y(g_value_get_int(&value));
755 g_value_unset(&value);
761 void FindBarGtk::OnParentSet(GtkWidget* widget, GtkObject* old_parent,
762 FindBarGtk* find_bar) {
763 if (!gtk_widget_get_parent(widget))
766 g_signal_connect(gtk_widget_get_parent(widget), "set-floating-position",
767 G_CALLBACK(OnSetFloatingPosition), find_bar);
771 void FindBarGtk::OnSetFloatingPosition(GtkFloatingContainer* floating_container,
772 GtkAllocation* allocation,
773 FindBarGtk* find_bar) {
774 GtkWidget* findbar = find_bar->widget();
776 int xposition = find_bar->GetDialogPosition(find_bar->selection_rect_).x();
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);
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);
791 gboolean FindBarGtk::OnChanged(GtkWindow* window, FindBarGtk* find_bar) {
792 find_bar->AdjustTextAlignment();
794 if (!find_bar->ignore_changed_signal_)
795 find_bar->FindEntryTextInContents(true);
801 gboolean FindBarGtk::OnKeyPressEvent(GtkWidget* widget, GdkEventKey* event,
802 FindBarGtk* find_bar) {
803 if (find_bar->MaybeForwardKeyEventToRenderer(event)) {
805 } else if (GDK_Escape == event->keyval) {
806 find_bar->find_bar_controller_->EndFindSession(
807 FindBarController::kKeepSelectionOnPage,
808 FindBarController::kKeepResultsInFindBox);
810 } else if (GDK_Return == event->keyval ||
811 GDK_KP_Enter == event->keyval) {
812 if ((event->state & gtk_accelerator_get_default_mod_mask()) ==
814 find_bar->find_bar_controller_->EndFindSession(
815 FindBarController::kActivateSelectionOnPage,
816 FindBarController::kClearResultsInFindBox);
820 bool forward = (event->state & gtk_accelerator_get_default_mod_mask()) !=
822 find_bar->FindEntryTextInContents(forward);
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()) !=
833 find_bar->FindEntryTextInContents(forward);
840 gboolean FindBarGtk::OnKeyReleaseEvent(GtkWidget* widget, GdkEventKey* event,
841 FindBarGtk* find_bar) {
842 return find_bar->MaybeForwardKeyEventToRenderer(event);
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());
859 gboolean FindBarGtk::OnContentEventBoxExpose(GtkWidget* widget,
860 GdkEventExpose* event,
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;
870 gtk_widget_get_allocation(widget, &rec);
871 rec.width -= padding;
873 gtk_util::DrawTextEntryBackground(bar->text_entry_, widget,
880 // Used to handle custom painting of |container_|.
881 gboolean FindBarGtk::OnExpose(GtkWidget* widget, GdkEventExpose* e,
883 TRACE_EVENT0("ui::gtk", "FindBarGtk::OnExpose");
885 GtkAllocation allocation;
886 gtk_widget_get_allocation(widget, &allocation);
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],
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);
902 bar->container_width_ = allocation.width;
903 bar->container_height_ = allocation.height;
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);
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());
919 if (bar->container_width_ != allocation.width ||
920 bar->container_height_ != allocation.height) {
922 gdk_window_shape_combine_region(gtk_widget_get_window(widget),
924 SetDialogShape(bar->container_);
926 bar->container_width_ = allocation.width;
927 bar->container_height_ = allocation.height;
930 cairo_t* cr = gdk_cairo_create(gtk_widget_get_window(widget));
931 gdk_cairo_rectangle(cr, &e->area);
934 gfx::Point tabstrip_origin =
935 bar->window_->tabstrip()->GetTabStripOriginForWidget(widget);
937 gtk_util::DrawThemedToolbarBackground(widget, cr, e, tabstrip_origin,
938 bar->theme_service_);
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
944 GtkAllocation border_allocation;
945 gtk_widget_get_allocation(bar->border_bin_, &border_allocation);
947 // Blit the left part of the background image once on the left.
948 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
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());
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);
968 border_allocation.x + background_left->Width(),
970 border_allocation.width - background_left->Width(),
971 background->Height());
977 GetDialogBorder()->RenderToWidget(widget);
980 // Propagate to the container's child.
981 GtkWidget* child = gtk_bin_get_child(GTK_BIN(widget));
983 gtk_container_propagate_expose(GTK_CONTAINER(widget), child, e);
988 gboolean FindBarGtk::OnFocus(GtkWidget* text_entry, GtkDirectionType focus,
989 FindBarGtk* find_bar) {
990 find_bar->StoreOutsideFocus();
992 // Continue propagating the event.
997 gboolean FindBarGtk::OnButtonPress(GtkWidget* text_entry, GdkEventButton* e,
998 FindBarGtk* find_bar) {
999 find_bar->StoreOutsideFocus();
1001 // Continue propagating the event.
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);
1010 GdkEvent* event = gtk_get_current_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);
1017 gdk_event_free(event);
1021 void FindBarGtk::OnActivate(GtkWidget* entry) {
1022 FindEntryTextInContents(true);
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);
1030 AdjustTextAlignment();
1032 return FALSE; // Continue propagation.
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);
1040 return FALSE; // Continue propagation.