find_bar_view.cc revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
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/views/find_bar_view.h"
6
7#include <algorithm>
8
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/effects/SkGradientShader.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/controls/textfield/textfield.h"
34#include "ui/views/widget/widget.h"
35
36// The amount of whitespace to have before the find button.
37static const int kWhiteSpaceAfterMatchCountLabel = 1;
38
39// The margins around the search field and the close button.
40static const int kMarginLeftOfCloseButton = 3;
41static const int kMarginRightOfCloseButton = 7;
42static const int kMarginLeftOfFindTextfield = 12;
43
44// The margins around the match count label (We add extra space so that the
45// background highlight extends beyond just the text).
46static const int kMatchCountExtraWidth = 9;
47
48// Minimum width for the match count label.
49static const int kMatchCountMinWidth = 30;
50
51// The text color for the match count label.
52static const SkColor kTextColorMatchCount = SkColorSetRGB(178, 178, 178);
53
54// The text color for the match count label when no matches are found.
55static const SkColor kTextColorNoMatch = SK_ColorBLACK;
56
57// The background color of the match count label when results are found.
58static const SkColor kBackgroundColorMatch = SkColorSetARGB(0, 255, 255, 255);
59
60// The background color of the match count label when no results are found.
61static const SkColor kBackgroundColorNoMatch = SkColorSetRGB(255, 102, 102);
62
63// The default number of average characters that the text box will be. This
64// number brings the width on a "regular fonts" system to about 300px.
65static const int kDefaultCharWidth = 43;
66
67////////////////////////////////////////////////////////////////////////////////
68// FindBarView, public:
69
70FindBarView::FindBarView(FindBarHost* host)
71    : DropdownBarView(host),
72      find_text_(NULL),
73      match_count_text_(NULL),
74      focus_forwarder_view_(NULL),
75      find_previous_button_(NULL),
76      find_next_button_(NULL),
77      close_button_(NULL),
78      text_box_background_(NULL),
79      text_box_background_left_(NULL) {
80  set_id(VIEW_ID_FIND_IN_PAGE);
81  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
82
83  find_text_ = new SearchTextfieldView;
84  find_text_->set_id(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD);
85  find_text_->SetFont(rb.GetFont(ui::ResourceBundle::BaseFont));
86  find_text_->set_default_width_in_chars(kDefaultCharWidth);
87  find_text_->SetController(this);
88  find_text_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_FIND));
89
90  AddChildView(find_text_);
91
92  match_count_text_ = new views::Label();
93  match_count_text_->SetFont(rb.GetFont(ui::ResourceBundle::BaseFont));
94  AddChildView(match_count_text_);
95
96  // Create a focus forwarder view which sends focus to find_text_.
97  focus_forwarder_view_ = new FocusForwarderView(find_text_);
98  AddChildView(focus_forwarder_view_);
99
100  find_previous_button_ = new views::ImageButton(this);
101  find_previous_button_->set_tag(FIND_PREVIOUS_TAG);
102  find_previous_button_->set_focusable(true);
103  find_previous_button_->SetImage(views::CustomButton::STATE_NORMAL,
104      rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV));
105  find_previous_button_->SetImage(views::CustomButton::STATE_HOVERED,
106      rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_H));
107  find_previous_button_->SetImage(views::CustomButton::STATE_PRESSED,
108      rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_P));
109  find_previous_button_->SetImage(views::CustomButton::STATE_DISABLED,
110      rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_D));
111  find_previous_button_->SetTooltipText(
112      l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_PREVIOUS_TOOLTIP));
113  find_previous_button_->SetAccessibleName(
114      l10n_util::GetStringUTF16(IDS_ACCNAME_PREVIOUS));
115  AddChildView(find_previous_button_);
116
117  find_next_button_ = new views::ImageButton(this);
118  find_next_button_->set_tag(FIND_NEXT_TAG);
119  find_next_button_->set_focusable(true);
120  find_next_button_->SetImage(views::CustomButton::STATE_NORMAL,
121      rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT));
122  find_next_button_->SetImage(views::CustomButton::STATE_HOVERED,
123      rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_H));
124  find_next_button_->SetImage(views::CustomButton::STATE_PRESSED,
125      rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_P));
126  find_next_button_->SetImage(views::CustomButton::STATE_DISABLED,
127      rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_D));
128  find_next_button_->SetTooltipText(
129      l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_NEXT_TOOLTIP));
130  find_next_button_->SetAccessibleName(
131      l10n_util::GetStringUTF16(IDS_ACCNAME_NEXT));
132  AddChildView(find_next_button_);
133
134  close_button_ = new views::ImageButton(this);
135  close_button_->set_tag(CLOSE_TAG);
136  close_button_->set_focusable(true);
137  close_button_->SetImage(views::CustomButton::STATE_NORMAL,
138                          rb.GetImageSkiaNamed(IDR_CLOSE_1));
139  close_button_->SetImage(views::CustomButton::STATE_HOVERED,
140                          rb.GetImageSkiaNamed(IDR_CLOSE_1_H));
141  close_button_->SetImage(views::CustomButton::STATE_PRESSED,
142                          rb.GetImageSkiaNamed(IDR_CLOSE_1_P));
143  close_button_->SetTooltipText(
144      l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_CLOSE_TOOLTIP));
145  close_button_->SetAccessibleName(
146      l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
147  close_button_->SetAnimationDuration(0);
148  AddChildView(close_button_);
149
150  SetBackground(rb.GetImageSkiaNamed(IDR_FIND_DLG_LEFT_BACKGROUND),
151                rb.GetImageSkiaNamed(IDR_FIND_DLG_RIGHT_BACKGROUND));
152
153  SetBorder(IDR_FIND_DIALOG_LEFT, IDR_FIND_DIALOG_MIDDLE,
154            IDR_FIND_DIALOG_RIGHT);
155
156  preferred_height_ = rb.GetImageSkiaNamed(IDR_FIND_DIALOG_MIDDLE)->height();
157
158  // Background images for the Find edit box.
159  text_box_background_ = rb.GetImageSkiaNamed(IDR_FIND_BOX_BACKGROUND);
160  text_box_background_left_ =
161      rb.GetImageSkiaNamed(IDR_FIND_BOX_BACKGROUND_LEFT);
162
163  EnableCanvasFlippingForRTLUI(true);
164}
165
166FindBarView::~FindBarView() {
167}
168
169void FindBarView::SetFindText(const string16& find_text) {
170  find_text_->SetText(find_text);
171}
172
173string16 FindBarView::GetFindText() const {
174  return find_text_->text();
175}
176
177string16 FindBarView::GetFindSelectedText() const {
178  return find_text_->GetSelectedText();
179}
180
181string16 FindBarView::GetMatchCountText() const {
182  return match_count_text_->text();
183}
184
185void FindBarView::UpdateForResult(const FindNotificationDetails& result,
186                                  const string16& find_text) {
187  bool have_valid_range =
188      result.number_of_matches() != -1 && result.active_match_ordinal() != -1;
189
190  // http://crbug.com/34970: some IMEs get confused if we change the text
191  // composed by them. To avoid this problem, we should check the IME status and
192  // update the text only when the IME is not composing text.
193  if (find_text_->text() != find_text && !find_text_->IsIMEComposing()) {
194    SetFindText(find_text);
195    find_text_->SelectAll(true);
196  }
197
198  if (find_text.empty() || !have_valid_range) {
199    // If there was no text entered, we don't show anything in the result count
200    // area.
201    ClearMatchCount();
202    return;
203  }
204
205  match_count_text_->SetText(l10n_util::GetStringFUTF16(IDS_FIND_IN_PAGE_COUNT,
206      base::IntToString16(result.active_match_ordinal()),
207      base::IntToString16(result.number_of_matches())));
208
209  UpdateMatchCountAppearance(result.number_of_matches() == 0 &&
210                             result.final_update());
211
212  // The match_count label may have increased/decreased in size so we need to
213  // do a layout and repaint the dialog so that the find text field doesn't
214  // partially overlap the match-count label when it increases on no matches.
215  Layout();
216  SchedulePaint();
217}
218
219void FindBarView::ClearMatchCount() {
220  match_count_text_->SetText(string16());
221  UpdateMatchCountAppearance(false);
222  Layout();
223  SchedulePaint();
224}
225
226void FindBarView::SetFocusAndSelection(bool select_all) {
227  find_text_->RequestFocus();
228  if (select_all && !find_text_->text().empty())
229    find_text_->SelectAll(true);
230}
231
232///////////////////////////////////////////////////////////////////////////////
233// FindBarView, views::View overrides:
234
235void FindBarView::OnPaint(gfx::Canvas* canvas) {
236  // Paint drop down bar border and background.
237  DropdownBarView::OnPaint(canvas);
238
239  // Then we draw the background image for the Find Textfield. We start by
240  // calculating the position of background images for the Find text box.
241  int find_text_x = find_text_->x();
242  gfx::Point back_button_origin = find_previous_button_->bounds().origin();
243
244  // Draw the image to the left that creates a curved left edge for the box.
245  canvas->TileImageInt(*text_box_background_left_,
246      find_text_x - text_box_background_left_->width(),
247      back_button_origin.y(), text_box_background_left_->width(),
248      text_box_background_left_->height());
249
250  // Draw the top and bottom border for whole text box (encompasses both the
251  // find_text_ edit box and the match_count_text_ label).
252  canvas->TileImageInt(*text_box_background_, find_text_x,
253                       back_button_origin.y(),
254                       back_button_origin.x() - find_text_x,
255                       text_box_background_->height());
256
257  // Draw the background of the match text. We want to make sure the red
258  // "no-match" background almost completely fills up the amount of vertical
259  // space within the text box. We therefore fix the size relative to the button
260  // heights. We use the FindPrev button, which has a 1px outer whitespace
261  // margin, 1px border and we want to appear 1px below the border line so we
262  // subtract 3 for top and 3 for bottom.
263  gfx::Rect match_count_background_bounds(match_count_text_->bounds());
264  match_count_background_bounds.set_height(
265      find_previous_button_->height() - 6);  // Subtract 3px x 2.
266  match_count_background_bounds.set_y(
267      (height() - match_count_background_bounds.height()) / 2);
268  canvas->FillRect(match_count_background_bounds,
269                   match_count_text_->background_color());
270}
271
272void FindBarView::Layout() {
273  int panel_width = GetPreferredSize().width();
274
275  // Stay within view bounds.
276  int view_width = width();
277  if (view_width && view_width < panel_width)
278    panel_width = view_width;
279
280  // First we draw the close button on the far right.
281  gfx::Size sz = close_button_->GetPreferredSize();
282  close_button_->SetBounds(panel_width - sz.width() -
283                               kMarginRightOfCloseButton,
284                           (height() - sz.height()) / 2,
285                           sz.width(),
286                           sz.height());
287  // Set the color.
288  OnThemeChanged();
289
290  // Next, the FindNext button to the left the close button.
291  sz = find_next_button_->GetPreferredSize();
292  find_next_button_->SetBounds(close_button_->x() -
293                                   find_next_button_->width() -
294                                   kMarginLeftOfCloseButton,
295                               (height() - sz.height()) / 2,
296                                sz.width(),
297                                sz.height());
298
299  // Then, the FindPrevious button to the left the FindNext button.
300  sz = find_previous_button_->GetPreferredSize();
301  find_previous_button_->SetBounds(find_next_button_->x() -
302                                       find_previous_button_->width(),
303                                   (height() - sz.height()) / 2,
304                                   sz.width(),
305                                   sz.height());
306
307  // Then the label showing the match count number.
308  sz = match_count_text_->GetPreferredSize();
309  // We extend the label bounds a bit to give the background highlighting a bit
310  // of breathing room (margins around the text).
311  sz.Enlarge(kMatchCountExtraWidth, 0);
312  sz.SetToMax(gfx::Size(kMatchCountMinWidth, 0));
313  int match_count_x =
314      find_previous_button_->x() - kWhiteSpaceAfterMatchCountLabel - sz.width();
315  int find_text_y = (height() - find_text_->GetPreferredSize().height()) / 2;
316  match_count_text_->SetBounds(match_count_x,
317                               find_text_y + find_text_->GetBaseline() -
318                                   match_count_text_->GetBaseline(),
319                               sz.width(), sz.height());
320
321  // And whatever space is left in between, gets filled up by the find edit box.
322  int find_text_width = std::max(0, match_count_x - kMarginLeftOfFindTextfield);
323  find_text_->SetBounds(std::max(0, match_count_x - find_text_width),
324                        find_text_y, find_text_width,
325                        find_text_->GetPreferredSize().height());
326
327  // The focus forwarder view is a hidden view that should cover the area
328  // between the find text box and the find button so that when the user clicks
329  // in that area we focus on the find text box.
330  int find_text_edge = find_text_->x() + find_text_->width();
331  focus_forwarder_view_->SetBounds(
332      find_text_edge, find_previous_button_->y(),
333      find_previous_button_->x() - find_text_edge,
334      find_previous_button_->height());
335}
336
337void FindBarView::ViewHierarchyChanged(
338    const ViewHierarchyChangedDetails& details) {
339  if (details.is_add && details.child == this) {
340    find_text_->SetHorizontalMargins(0, 2);  // Left and Right margins.
341    find_text_->RemoveBorder();  // We draw our own border (a background image).
342  }
343}
344
345gfx::Size FindBarView::GetPreferredSize() {
346  gfx::Size prefsize = find_text_->GetPreferredSize();
347  prefsize.set_height(preferred_height_);
348
349  // Add up all the preferred sizes and margins of the rest of the controls.
350  prefsize.Enlarge(kMarginLeftOfCloseButton + kMarginRightOfCloseButton +
351                       kMarginLeftOfFindTextfield,
352                   0);
353  prefsize.Enlarge(find_previous_button_->GetPreferredSize().width(), 0);
354  prefsize.Enlarge(find_next_button_->GetPreferredSize().width(), 0);
355  prefsize.Enlarge(close_button_->GetPreferredSize().width(), 0);
356  return prefsize;
357}
358
359////////////////////////////////////////////////////////////////////////////////
360// FindBarView, views::ButtonListener implementation:
361
362void FindBarView::ButtonPressed(
363    views::Button* sender, const ui::Event& event) {
364  switch (sender->tag()) {
365    case FIND_PREVIOUS_TAG:
366    case FIND_NEXT_TAG:
367      if (!find_text_->text().empty()) {
368        FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(
369            find_bar_host()->GetFindBarController()->web_contents());
370        find_tab_helper->StartFinding(find_text_->text(),
371                                      sender->tag() == FIND_NEXT_TAG,
372                                      false);  // Not case sensitive.
373      }
374      if (event.IsMouseEvent()) {
375        // If mouse event, we move the focus back to the text-field, so that the
376        // user doesn't have to click on the text field to change the search. We
377        // don't want to do this for keyboard clicks on the button, since the
378        // user is more likely to press FindNext again than change the search
379        // query.
380        find_text_->RequestFocus();
381      }
382      break;
383    case CLOSE_TAG:
384      find_bar_host()->GetFindBarController()->EndFindSession(
385          FindBarController::kKeepSelectionOnPage,
386          FindBarController::kKeepResultsInFindBox);
387      break;
388    default:
389      NOTREACHED() << L"Unknown button";
390      break;
391  }
392}
393
394////////////////////////////////////////////////////////////////////////////////
395// FindBarView, views::TextfieldController implementation:
396
397void FindBarView::ContentsChanged(views::Textfield* sender,
398                                  const string16& new_contents) {
399  // TextfieldController::OnAfterUserAction() is supported only by Views
400  // implementation, and NativeTextfieldWin doesn't call OnAfterUserAction().
401  // Call Find() here.
402  // TODO(yukishiino): Remove this code after the migration to Views.
403  if (!views::Textfield::IsViewsTextfieldEnabled())
404    Find(new_contents);
405}
406
407bool FindBarView::HandleKeyEvent(views::Textfield* sender,
408                                 const ui::KeyEvent& key_event) {
409  // If the dialog is not visible, there is no reason to process keyboard input.
410  if (!host()->IsVisible())
411    return false;
412
413  if (find_bar_host()->MaybeForwardKeyEventToWebpage(key_event))
414    return true;  // Handled, we are done!
415
416  if (key_event.key_code() == ui::VKEY_RETURN) {
417    // Pressing Return/Enter starts the search (unless text box is empty).
418    string16 find_string = find_text_->text();
419    if (!find_string.empty()) {
420      FindBarController* controller = find_bar_host()->GetFindBarController();
421      FindTabHelper* find_tab_helper =
422          FindTabHelper::FromWebContents(controller->web_contents());
423      // Search forwards for enter, backwards for shift-enter.
424      find_tab_helper->StartFinding(find_string,
425                                    !key_event.IsShiftDown(),
426                                    false);  // Not case sensitive.
427    }
428    return true;
429  }
430
431  return false;
432}
433
434void FindBarView::OnAfterUserAction(views::Textfield* sender) {
435  // The composition text wouldn't be what the user is really looking for.
436  // We delay the search until the user commits the composition text.
437  if (sender->IsIMEComposing() || sender->text() == last_searched_text_)
438    return;
439
440  // TODO(yukishiino): Remove this condition check after the migration to Views.
441  if (views::Textfield::IsViewsTextfieldEnabled())
442    Find(sender->text());
443}
444
445void FindBarView::OnAfterPaste() {
446  // Clear the last search text so we always search for the user input after
447  // a paste operation, even if the pasted text is the same as before.
448  // See http://crbug.com/79002
449  last_searched_text_.clear();
450}
451
452void FindBarView::Find(const string16& search_text) {
453  FindBarController* controller = find_bar_host()->GetFindBarController();
454  DCHECK(controller);
455  content::WebContents* web_contents = controller->web_contents();
456  // We must guard against a NULL web_contents, which can happen if the text
457  // in the Find box is changed right after the tab is destroyed. Otherwise, it
458  // can lead to crashes, as exposed by automation testing in issue 8048.
459  if (!web_contents)
460    return;
461  FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
462
463  last_searched_text_ = search_text;
464
465  // When the user changes something in the text box we check the contents and
466  // if the textbox contains something we set it as the new search string and
467  // initiate search (even though old searches might be in progress).
468  if (!search_text.empty()) {
469    // The last two params here are forward (true) and case sensitive (false).
470    find_tab_helper->StartFinding(search_text, true, false);
471  } else {
472    find_tab_helper->StopFinding(FindBarController::kClearSelectionOnPage);
473    UpdateForResult(find_tab_helper->find_result(), string16());
474    find_bar_host()->MoveWindowIfNecessary(gfx::Rect(), false);
475
476    // Clearing the text box should clear the prepopulate state so that when
477    // we close and reopen the Find box it doesn't show the search we just
478    // deleted. We can't do this on ChromeOS yet because we get ContentsChanged
479    // sent for a lot more things than just the user nulling out the search
480    // terms. See http://crbug.com/45372.
481    Profile* profile =
482        Profile::FromBrowserContext(web_contents->GetBrowserContext());
483    FindBarState* find_bar_state = FindBarStateFactory::GetForProfile(profile);
484    find_bar_state->set_last_prepopulate_text(string16());
485  }
486}
487
488void FindBarView::UpdateMatchCountAppearance(bool no_match) {
489  if (no_match) {
490    match_count_text_->SetBackgroundColor(kBackgroundColorNoMatch);
491    match_count_text_->SetEnabledColor(kTextColorNoMatch);
492  } else {
493    match_count_text_->SetBackgroundColor(kBackgroundColorMatch);
494    match_count_text_->SetEnabledColor(kTextColorMatchCount);
495  }
496}
497
498bool FindBarView::FocusForwarderView::OnMousePressed(
499    const ui::MouseEvent& event) {
500  if (view_to_focus_on_mousedown_)
501    view_to_focus_on_mousedown_->RequestFocus();
502  return true;
503}
504
505FindBarView::SearchTextfieldView::SearchTextfieldView()
506    : select_all_on_focus_(true) {}
507
508FindBarView::SearchTextfieldView::~SearchTextfieldView() {}
509
510bool FindBarView::SearchTextfieldView::OnMousePressed(
511    const ui::MouseEvent& event) {
512  // Avoid temporarily selecting all the text on focus from a mouse press; this
513  // prevents flickering before setting a cursor or dragging to select text.
514  select_all_on_focus_ = false;
515  return views::Textfield::OnMousePressed(event);
516}
517
518void FindBarView::SearchTextfieldView::OnMouseReleased(
519    const ui::MouseEvent& event) {
520  views::Textfield::OnMouseReleased(event);
521  select_all_on_focus_ = true;
522}
523
524void FindBarView::SearchTextfieldView::OnFocus() {
525  views::Textfield::OnFocus();
526  if (select_all_on_focus_)
527    SelectAll(true);
528}
529
530FindBarHost* FindBarView::find_bar_host() const {
531  return static_cast<FindBarHost*>(host());
532}
533
534void FindBarView::OnThemeChanged() {
535  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
536  if (GetThemeProvider()) {
537    close_button_->SetBackground(
538        GetThemeProvider()->GetColor(ThemeProperties::COLOR_TAB_TEXT),
539        rb.GetImageSkiaNamed(IDR_CLOSE_1),
540        rb.GetImageSkiaNamed(IDR_CLOSE_1_MASK));
541  }
542}
543