[Metrics] Make MetricsStateManager take a callback param to check if UMA is enabled.
[chromium-blink-merge.git] / chrome / browser / ui / views / find_bar_view.cc
blob37bca60c96ed5f377fe22c43867cc0dd24d1f9f4
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/views/find_bar_view.h"
7 #include <algorithm>
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/browser/profiles/profile.h"
13 #include "chrome/browser/themes/theme_properties.h"
14 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
15 #include "chrome/browser/ui/find_bar/find_bar_state.h"
16 #include "chrome/browser/ui/find_bar/find_bar_state_factory.h"
17 #include "chrome/browser/ui/find_bar/find_notification_details.h"
18 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
19 #include "chrome/browser/ui/view_ids.h"
20 #include "chrome/browser/ui/views/find_bar_host.h"
21 #include "chrome/browser/ui/views/frame/browser_view.h"
22 #include "grit/generated_resources.h"
23 #include "grit/theme_resources.h"
24 #include "grit/ui_resources.h"
25 #include "third_party/skia/include/core/SkPaint.h"
26 #include "ui/base/l10n/l10n_util.h"
27 #include "ui/base/resource/resource_bundle.h"
28 #include "ui/base/theme_provider.h"
29 #include "ui/events/event.h"
30 #include "ui/gfx/canvas.h"
31 #include "ui/views/controls/button/image_button.h"
32 #include "ui/views/controls/label.h"
33 #include "ui/views/painter.h"
34 #include "ui/views/widget/widget.h"
36 namespace {
38 // The margins around the search field, match count label, and the close button.
39 const int kMarginLeftOfCloseButton = 3;
40 const int kMarginRightOfCloseButton = 7;
41 const int kMarginLeftOfMatchCountLabel = 2;
42 const int kMarginRightOfMatchCountLabel = 1;
43 const int kMarginLeftOfFindTextfield = 12;
45 // The margins around the match count label (We add extra space so that the
46 // background highlight extends beyond just the text).
47 const int kMatchCountExtraWidth = 9;
49 // Minimum width for the match count label.
50 const int kMatchCountMinWidth = 30;
52 // The text color for the match count label.
53 const SkColor kTextColorMatchCount = SkColorSetRGB(178, 178, 178);
55 // The text color for the match count label when no matches are found.
56 const SkColor kTextColorNoMatch = SK_ColorBLACK;
58 // The background color of the match count label when results are found.
59 const SkColor kBackgroundColorMatch = SkColorSetARGB(0, 255, 255, 255);
61 // The background color of the match count label when no results are found.
62 const SkColor kBackgroundColorNoMatch = SkColorSetRGB(255, 102, 102);
64 // The default number of average characters that the text box will be. This
65 // number brings the width on a "regular fonts" system to about 300px.
66 const int kDefaultCharWidth = 43;
68 } // namespace
70 ////////////////////////////////////////////////////////////////////////////////
71 // FindBarView, public:
73 FindBarView::FindBarView(FindBarHost* host)
74 : DropdownBarView(host),
75 find_text_(NULL),
76 match_count_text_(NULL),
77 focus_forwarder_view_(NULL),
78 find_previous_button_(NULL),
79 find_next_button_(NULL),
80 close_button_(NULL) {
81 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
83 find_text_ = new views::Textfield;
84 find_text_->set_id(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD);
85 find_text_->set_default_width_in_chars(kDefaultCharWidth);
86 find_text_->set_controller(this);
87 find_text_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_FIND));
88 // The find bar textfield has a background image instead of a border.
89 find_text_->SetBorder(views::Border::NullBorder());
90 AddChildView(find_text_);
92 match_count_text_ = new views::Label();
93 AddChildView(match_count_text_);
95 // Create a focus forwarder view which sends focus to find_text_.
96 focus_forwarder_view_ = new FocusForwarderView(find_text_);
97 AddChildView(focus_forwarder_view_);
99 find_previous_button_ = new views::ImageButton(this);
100 find_previous_button_->set_tag(FIND_PREVIOUS_TAG);
101 find_previous_button_->SetFocusable(true);
102 find_previous_button_->SetImage(views::CustomButton::STATE_NORMAL,
103 rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV));
104 find_previous_button_->SetImage(views::CustomButton::STATE_HOVERED,
105 rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_H));
106 find_previous_button_->SetImage(views::CustomButton::STATE_PRESSED,
107 rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_P));
108 find_previous_button_->SetImage(views::CustomButton::STATE_DISABLED,
109 rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_D));
110 find_previous_button_->SetTooltipText(
111 l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_PREVIOUS_TOOLTIP));
112 find_previous_button_->SetAccessibleName(
113 l10n_util::GetStringUTF16(IDS_ACCNAME_PREVIOUS));
114 AddChildView(find_previous_button_);
116 find_next_button_ = new views::ImageButton(this);
117 find_next_button_->set_tag(FIND_NEXT_TAG);
118 find_next_button_->SetFocusable(true);
119 find_next_button_->SetImage(views::CustomButton::STATE_NORMAL,
120 rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT));
121 find_next_button_->SetImage(views::CustomButton::STATE_HOVERED,
122 rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_H));
123 find_next_button_->SetImage(views::CustomButton::STATE_PRESSED,
124 rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_P));
125 find_next_button_->SetImage(views::CustomButton::STATE_DISABLED,
126 rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_D));
127 find_next_button_->SetTooltipText(
128 l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_NEXT_TOOLTIP));
129 find_next_button_->SetAccessibleName(
130 l10n_util::GetStringUTF16(IDS_ACCNAME_NEXT));
131 AddChildView(find_next_button_);
133 close_button_ = new views::ImageButton(this);
134 close_button_->set_tag(CLOSE_TAG);
135 close_button_->SetFocusable(true);
136 close_button_->SetImage(views::CustomButton::STATE_NORMAL,
137 rb.GetImageSkiaNamed(IDR_CLOSE_1));
138 close_button_->SetImage(views::CustomButton::STATE_HOVERED,
139 rb.GetImageSkiaNamed(IDR_CLOSE_1_H));
140 close_button_->SetImage(views::CustomButton::STATE_PRESSED,
141 rb.GetImageSkiaNamed(IDR_CLOSE_1_P));
142 close_button_->SetTooltipText(
143 l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_CLOSE_TOOLTIP));
144 close_button_->SetAccessibleName(
145 l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
146 close_button_->SetAnimationDuration(0);
147 AddChildView(close_button_);
149 SetBackground(rb.GetImageSkiaNamed(IDR_FIND_DLG_LEFT_BACKGROUND),
150 rb.GetImageSkiaNamed(IDR_FIND_DLG_RIGHT_BACKGROUND));
152 SetBorderFromIds(
153 IDR_FIND_DIALOG_LEFT, IDR_FIND_DIALOG_MIDDLE, IDR_FIND_DIALOG_RIGHT);
155 preferred_height_ = rb.GetImageSkiaNamed(IDR_FIND_DIALOG_MIDDLE)->height();
157 static const int kImages[] = IMAGE_GRID(IDR_TEXTFIELD);
158 find_text_border_.reset(views::Painter::CreateImageGridPainter(kImages));
160 EnableCanvasFlippingForRTLUI(true);
163 FindBarView::~FindBarView() {
166 void FindBarView::SetFindTextAndSelectedRange(
167 const base::string16& find_text,
168 const gfx::Range& selected_range) {
169 find_text_->SetText(find_text);
170 find_text_->SelectRange(selected_range);
173 base::string16 FindBarView::GetFindText() const {
174 return find_text_->text();
177 gfx::Range FindBarView::GetSelectedRange() const {
178 return find_text_->GetSelectedRange();
181 base::string16 FindBarView::GetFindSelectedText() const {
182 return find_text_->GetSelectedText();
185 base::string16 FindBarView::GetMatchCountText() const {
186 return match_count_text_->text();
189 void FindBarView::UpdateForResult(const FindNotificationDetails& result,
190 const base::string16& find_text) {
191 bool have_valid_range =
192 result.number_of_matches() != -1 && result.active_match_ordinal() != -1;
194 // http://crbug.com/34970: some IMEs get confused if we change the text
195 // composed by them. To avoid this problem, we should check the IME status and
196 // update the text only when the IME is not composing text.
197 if (find_text_->text() != find_text && !find_text_->IsIMEComposing()) {
198 find_text_->SetText(find_text);
199 find_text_->SelectAll(true);
202 if (find_text.empty() || !have_valid_range) {
203 // If there was no text entered, we don't show anything in the result count
204 // area.
205 ClearMatchCount();
206 return;
209 match_count_text_->SetText(l10n_util::GetStringFUTF16(IDS_FIND_IN_PAGE_COUNT,
210 base::IntToString16(result.active_match_ordinal()),
211 base::IntToString16(result.number_of_matches())));
213 UpdateMatchCountAppearance(result.number_of_matches() == 0 &&
214 result.final_update());
216 // The match_count label may have increased/decreased in size so we need to
217 // do a layout and repaint the dialog so that the find text field doesn't
218 // partially overlap the match-count label when it increases on no matches.
219 Layout();
220 SchedulePaint();
223 void FindBarView::ClearMatchCount() {
224 match_count_text_->SetText(base::string16());
225 UpdateMatchCountAppearance(false);
226 Layout();
227 SchedulePaint();
230 void FindBarView::SetFocusAndSelection(bool select_all) {
231 find_text_->RequestFocus();
232 if (select_all && !find_text_->text().empty())
233 find_text_->SelectAll(true);
236 ///////////////////////////////////////////////////////////////////////////////
237 // FindBarView, views::View overrides:
239 void FindBarView::OnPaint(gfx::Canvas* canvas) {
240 // Paint drop down bar border and background.
241 DropdownBarView::OnPaint(canvas);
243 // Paint the background and border for the textfield.
244 const int find_text_x = kMarginLeftOfFindTextfield / 2;
245 const gfx::Rect text_bounds(find_text_x, find_next_button_->y(),
246 find_next_button_->bounds().right() - find_text_x,
247 find_next_button_->height());
248 const int kBorderCornerRadius = 2;
249 gfx::Rect background_bounds = text_bounds;
250 background_bounds.Inset(kBorderCornerRadius, kBorderCornerRadius);
251 SkPaint paint;
252 paint.setStyle(SkPaint::kFill_Style);
253 paint.setColor(find_text_->GetBackgroundColor());
254 canvas->DrawRoundRect(background_bounds, kBorderCornerRadius, paint);
255 canvas->Save();
256 canvas->ClipRect(gfx::Rect(0, 0, find_previous_button_->x(), height()));
257 views::Painter::PaintPainterAt(canvas, find_text_border_.get(), text_bounds);
258 canvas->Restore();
260 // Draw the background of the match text. We want to make sure the red
261 // "no-match" background almost completely fills up the amount of vertical
262 // space within the text box. We therefore fix the size relative to the button
263 // heights. We use the FindPrev button, which has a 1px outer whitespace
264 // margin, 1px border and we want to appear 1px below the border line so we
265 // subtract 3 for top and 3 for bottom.
266 gfx::Rect match_count_background_bounds(match_count_text_->bounds());
267 match_count_background_bounds.set_height(
268 find_previous_button_->height() - 6); // Subtract 3px x 2.
269 match_count_background_bounds.set_y(
270 (height() - match_count_background_bounds.height()) / 2);
271 canvas->FillRect(match_count_background_bounds,
272 match_count_text_->background_color());
275 void FindBarView::Layout() {
276 int panel_width = GetPreferredSize().width();
278 // Stay within view bounds.
279 int view_width = width();
280 if (view_width && view_width < panel_width)
281 panel_width = view_width;
283 // First we draw the close button on the far right.
284 gfx::Size sz = close_button_->GetPreferredSize();
285 close_button_->SetBounds(panel_width - sz.width() -
286 kMarginRightOfCloseButton,
287 (height() - sz.height()) / 2,
288 sz.width(),
289 sz.height());
290 // Set the color.
291 OnThemeChanged();
293 // Next, the FindNext button to the left the close button.
294 sz = find_next_button_->GetPreferredSize();
295 find_next_button_->SetBounds(close_button_->x() -
296 find_next_button_->width() -
297 kMarginLeftOfCloseButton,
298 (height() - sz.height()) / 2,
299 sz.width(),
300 sz.height());
302 // Then, the FindPrevious button to the left the FindNext button.
303 sz = find_previous_button_->GetPreferredSize();
304 find_previous_button_->SetBounds(find_next_button_->x() -
305 find_previous_button_->width(),
306 (height() - sz.height()) / 2,
307 sz.width(),
308 sz.height());
310 // Then the label showing the match count number.
311 sz = match_count_text_->GetPreferredSize();
312 // We extend the label bounds a bit to give the background highlighting a bit
313 // of breathing room (margins around the text).
314 sz.Enlarge(kMatchCountExtraWidth, 0);
315 sz.SetToMax(gfx::Size(kMatchCountMinWidth, 0));
316 int match_count_x =
317 find_previous_button_->x() - kMarginRightOfMatchCountLabel - sz.width();
318 int find_text_y = (height() - find_text_->GetPreferredSize().height()) / 2;
319 match_count_text_->SetBounds(match_count_x,
320 find_text_y + find_text_->GetBaseline() -
321 match_count_text_->GetBaseline(),
322 sz.width(), sz.height());
324 // And whatever space is left in between, gets filled up by the find edit box.
325 int find_text_width = std::max(0, match_count_x -
326 kMarginLeftOfMatchCountLabel - kMarginLeftOfFindTextfield);
327 find_text_->SetBounds(kMarginLeftOfFindTextfield, find_text_y,
328 find_text_width, find_text_->GetPreferredSize().height());
330 // The focus forwarder view is a hidden view that should cover the area
331 // between the find text box and the find button so that when the user clicks
332 // in that area we focus on the find text box.
333 int find_text_edge = find_text_->x() + find_text_->width();
334 focus_forwarder_view_->SetBounds(
335 find_text_edge, find_previous_button_->y(),
336 find_previous_button_->x() - find_text_edge,
337 find_previous_button_->height());
340 gfx::Size FindBarView::GetPreferredSize() const {
341 gfx::Size prefsize = find_text_->GetPreferredSize();
342 prefsize.set_height(preferred_height_);
344 // Add up all the preferred sizes and margins of the rest of the controls.
345 prefsize.Enlarge(kMarginLeftOfCloseButton + kMarginRightOfCloseButton +
346 kMarginLeftOfFindTextfield,
348 prefsize.Enlarge(find_previous_button_->GetPreferredSize().width(), 0);
349 prefsize.Enlarge(find_next_button_->GetPreferredSize().width(), 0);
350 prefsize.Enlarge(close_button_->GetPreferredSize().width(), 0);
351 return prefsize;
354 ////////////////////////////////////////////////////////////////////////////////
355 // FindBarView, views::ButtonListener implementation:
357 void FindBarView::ButtonPressed(
358 views::Button* sender, const ui::Event& event) {
359 switch (sender->tag()) {
360 case FIND_PREVIOUS_TAG:
361 case FIND_NEXT_TAG:
362 if (!find_text_->text().empty()) {
363 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(
364 find_bar_host()->GetFindBarController()->web_contents());
365 find_tab_helper->StartFinding(find_text_->text(),
366 sender->tag() == FIND_NEXT_TAG,
367 false); // Not case sensitive.
369 if (event.IsMouseEvent()) {
370 // If mouse event, we move the focus back to the text-field, so that the
371 // user doesn't have to click on the text field to change the search. We
372 // don't want to do this for keyboard clicks on the button, since the
373 // user is more likely to press FindNext again than change the search
374 // query.
375 find_text_->RequestFocus();
377 break;
378 case CLOSE_TAG:
379 find_bar_host()->GetFindBarController()->EndFindSession(
380 FindBarController::kKeepSelectionOnPage,
381 FindBarController::kKeepResultsInFindBox);
382 break;
383 default:
384 NOTREACHED() << L"Unknown button";
385 break;
389 ////////////////////////////////////////////////////////////////////////////////
390 // FindBarView, views::TextfieldController implementation:
392 bool FindBarView::HandleKeyEvent(views::Textfield* sender,
393 const ui::KeyEvent& key_event) {
394 // If the dialog is not visible, there is no reason to process keyboard input.
395 if (!host()->IsVisible())
396 return false;
398 if (find_bar_host()->MaybeForwardKeyEventToWebpage(key_event))
399 return true; // Handled, we are done!
401 if (key_event.key_code() == ui::VKEY_RETURN) {
402 // Pressing Return/Enter starts the search (unless text box is empty).
403 base::string16 find_string = find_text_->text();
404 if (!find_string.empty()) {
405 FindBarController* controller = find_bar_host()->GetFindBarController();
406 FindTabHelper* find_tab_helper =
407 FindTabHelper::FromWebContents(controller->web_contents());
408 // Search forwards for enter, backwards for shift-enter.
409 find_tab_helper->StartFinding(find_string,
410 !key_event.IsShiftDown(),
411 false); // Not case sensitive.
413 return true;
416 return false;
419 void FindBarView::OnAfterUserAction(views::Textfield* sender) {
420 // The composition text wouldn't be what the user is really looking for.
421 // We delay the search until the user commits the composition text.
422 if (!sender->IsIMEComposing() && sender->text() != last_searched_text_)
423 Find(sender->text());
426 void FindBarView::OnAfterPaste() {
427 // Clear the last search text so we always search for the user input after
428 // a paste operation, even if the pasted text is the same as before.
429 // See http://crbug.com/79002
430 last_searched_text_.clear();
433 void FindBarView::Find(const base::string16& search_text) {
434 FindBarController* controller = find_bar_host()->GetFindBarController();
435 DCHECK(controller);
436 content::WebContents* web_contents = controller->web_contents();
437 // We must guard against a NULL web_contents, which can happen if the text
438 // in the Find box is changed right after the tab is destroyed. Otherwise, it
439 // can lead to crashes, as exposed by automation testing in issue 8048.
440 if (!web_contents)
441 return;
442 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
444 last_searched_text_ = search_text;
446 // When the user changes something in the text box we check the contents and
447 // if the textbox contains something we set it as the new search string and
448 // initiate search (even though old searches might be in progress).
449 if (!search_text.empty()) {
450 // The last two params here are forward (true) and case sensitive (false).
451 find_tab_helper->StartFinding(search_text, true, false);
452 } else {
453 find_tab_helper->StopFinding(FindBarController::kClearSelectionOnPage);
454 UpdateForResult(find_tab_helper->find_result(), base::string16());
455 find_bar_host()->MoveWindowIfNecessary(gfx::Rect(), false);
457 // Clearing the text box should clear the prepopulate state so that when
458 // we close and reopen the Find box it doesn't show the search we just
459 // deleted. We can't do this on ChromeOS yet because we get ContentsChanged
460 // sent for a lot more things than just the user nulling out the search
461 // terms. See http://crbug.com/45372.
462 Profile* profile =
463 Profile::FromBrowserContext(web_contents->GetBrowserContext());
464 FindBarState* find_bar_state = FindBarStateFactory::GetForProfile(profile);
465 find_bar_state->set_last_prepopulate_text(base::string16());
469 void FindBarView::UpdateMatchCountAppearance(bool no_match) {
470 if (no_match) {
471 match_count_text_->SetBackgroundColor(kBackgroundColorNoMatch);
472 match_count_text_->SetEnabledColor(kTextColorNoMatch);
473 } else {
474 match_count_text_->SetBackgroundColor(kBackgroundColorMatch);
475 match_count_text_->SetEnabledColor(kTextColorMatchCount);
479 bool FindBarView::FocusForwarderView::OnMousePressed(
480 const ui::MouseEvent& event) {
481 if (view_to_focus_on_mousedown_)
482 view_to_focus_on_mousedown_->RequestFocus();
483 return true;
486 FindBarHost* FindBarView::find_bar_host() const {
487 return static_cast<FindBarHost*>(host());
490 void FindBarView::OnThemeChanged() {
491 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
492 if (GetThemeProvider()) {
493 close_button_->SetBackground(
494 GetThemeProvider()->GetColor(ThemeProperties::COLOR_TAB_TEXT),
495 rb.GetImageSkiaNamed(IDR_CLOSE_1),
496 rb.GetImageSkiaNamed(IDR_CLOSE_1_MASK));