find_bar_view.cc revision f2477e01787aa58f445919b809d89e252beef54f
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 views::Textfield;
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::SetFindTextAndSelectedRange(
170    const string16& find_text,
171    const gfx::Range& selected_range) {
172  find_text_->SetText(find_text);
173  find_text_->SelectRange(selected_range);
174}
175
176string16 FindBarView::GetFindText() const {
177  return find_text_->text();
178}
179
180gfx::Range FindBarView::GetSelectedRange() const {
181  return find_text_->GetSelectedRange();
182}
183
184string16 FindBarView::GetFindSelectedText() const {
185  return find_text_->GetSelectedText();
186}
187
188string16 FindBarView::GetMatchCountText() const {
189  return match_count_text_->text();
190}
191
192void FindBarView::UpdateForResult(const FindNotificationDetails& result,
193                                  const string16& find_text) {
194  bool have_valid_range =
195      result.number_of_matches() != -1 && result.active_match_ordinal() != -1;
196
197  // http://crbug.com/34970: some IMEs get confused if we change the text
198  // composed by them. To avoid this problem, we should check the IME status and
199  // update the text only when the IME is not composing text.
200  if (find_text_->text() != find_text && !find_text_->IsIMEComposing()) {
201    find_text_->SetText(find_text);
202    find_text_->SelectAll(true);
203  }
204
205  if (find_text.empty() || !have_valid_range) {
206    // If there was no text entered, we don't show anything in the result count
207    // area.
208    ClearMatchCount();
209    return;
210  }
211
212  match_count_text_->SetText(l10n_util::GetStringFUTF16(IDS_FIND_IN_PAGE_COUNT,
213      base::IntToString16(result.active_match_ordinal()),
214      base::IntToString16(result.number_of_matches())));
215
216  UpdateMatchCountAppearance(result.number_of_matches() == 0 &&
217                             result.final_update());
218
219  // The match_count label may have increased/decreased in size so we need to
220  // do a layout and repaint the dialog so that the find text field doesn't
221  // partially overlap the match-count label when it increases on no matches.
222  Layout();
223  SchedulePaint();
224}
225
226void FindBarView::ClearMatchCount() {
227  match_count_text_->SetText(string16());
228  UpdateMatchCountAppearance(false);
229  Layout();
230  SchedulePaint();
231}
232
233void FindBarView::SetFocusAndSelection(bool select_all) {
234  find_text_->RequestFocus();
235  if (select_all && !find_text_->text().empty())
236    find_text_->SelectAll(true);
237}
238
239///////////////////////////////////////////////////////////////////////////////
240// FindBarView, views::View overrides:
241
242void FindBarView::OnPaint(gfx::Canvas* canvas) {
243  // Paint drop down bar border and background.
244  DropdownBarView::OnPaint(canvas);
245
246  // Then we draw the background image for the Find Textfield. We start by
247  // calculating the position of background images for the Find text box.
248  int find_text_x = find_text_->x();
249  gfx::Point back_button_origin = find_previous_button_->bounds().origin();
250
251  // Draw the image to the left that creates a curved left edge for the box.
252  canvas->TileImageInt(*text_box_background_left_,
253      find_text_x - text_box_background_left_->width(),
254      back_button_origin.y(), text_box_background_left_->width(),
255      text_box_background_left_->height());
256
257  // Draw the top and bottom border for whole text box (encompasses both the
258  // find_text_ edit box and the match_count_text_ label).
259  canvas->TileImageInt(*text_box_background_, find_text_x,
260                       back_button_origin.y(),
261                       back_button_origin.x() - find_text_x,
262                       text_box_background_->height());
263
264  // Draw the background of the match text. We want to make sure the red
265  // "no-match" background almost completely fills up the amount of vertical
266  // space within the text box. We therefore fix the size relative to the button
267  // heights. We use the FindPrev button, which has a 1px outer whitespace
268  // margin, 1px border and we want to appear 1px below the border line so we
269  // subtract 3 for top and 3 for bottom.
270  gfx::Rect match_count_background_bounds(match_count_text_->bounds());
271  match_count_background_bounds.set_height(
272      find_previous_button_->height() - 6);  // Subtract 3px x 2.
273  match_count_background_bounds.set_y(
274      (height() - match_count_background_bounds.height()) / 2);
275  canvas->FillRect(match_count_background_bounds,
276                   match_count_text_->background_color());
277}
278
279void FindBarView::Layout() {
280  int panel_width = GetPreferredSize().width();
281
282  // Stay within view bounds.
283  int view_width = width();
284  if (view_width && view_width < panel_width)
285    panel_width = view_width;
286
287  // First we draw the close button on the far right.
288  gfx::Size sz = close_button_->GetPreferredSize();
289  close_button_->SetBounds(panel_width - sz.width() -
290                               kMarginRightOfCloseButton,
291                           (height() - sz.height()) / 2,
292                           sz.width(),
293                           sz.height());
294  // Set the color.
295  OnThemeChanged();
296
297  // Next, the FindNext button to the left the close button.
298  sz = find_next_button_->GetPreferredSize();
299  find_next_button_->SetBounds(close_button_->x() -
300                                   find_next_button_->width() -
301                                   kMarginLeftOfCloseButton,
302                               (height() - sz.height()) / 2,
303                                sz.width(),
304                                sz.height());
305
306  // Then, the FindPrevious button to the left the FindNext button.
307  sz = find_previous_button_->GetPreferredSize();
308  find_previous_button_->SetBounds(find_next_button_->x() -
309                                       find_previous_button_->width(),
310                                   (height() - sz.height()) / 2,
311                                   sz.width(),
312                                   sz.height());
313
314  // Then the label showing the match count number.
315  sz = match_count_text_->GetPreferredSize();
316  // We extend the label bounds a bit to give the background highlighting a bit
317  // of breathing room (margins around the text).
318  sz.Enlarge(kMatchCountExtraWidth, 0);
319  sz.SetToMax(gfx::Size(kMatchCountMinWidth, 0));
320  int match_count_x =
321      find_previous_button_->x() - kWhiteSpaceAfterMatchCountLabel - sz.width();
322  int find_text_y = (height() - find_text_->GetPreferredSize().height()) / 2;
323  match_count_text_->SetBounds(match_count_x,
324                               find_text_y + find_text_->GetBaseline() -
325                                   match_count_text_->GetBaseline(),
326                               sz.width(), sz.height());
327
328  // And whatever space is left in between, gets filled up by the find edit box.
329  int find_text_width = std::max(0, match_count_x - kMarginLeftOfFindTextfield);
330  find_text_->SetBounds(std::max(0, match_count_x - find_text_width),
331                        find_text_y, find_text_width,
332                        find_text_->GetPreferredSize().height());
333
334  // The focus forwarder view is a hidden view that should cover the area
335  // between the find text box and the find button so that when the user clicks
336  // in that area we focus on the find text box.
337  int find_text_edge = find_text_->x() + find_text_->width();
338  focus_forwarder_view_->SetBounds(
339      find_text_edge, find_previous_button_->y(),
340      find_previous_button_->x() - find_text_edge,
341      find_previous_button_->height());
342}
343
344void FindBarView::ViewHierarchyChanged(
345    const ViewHierarchyChangedDetails& details) {
346  if (details.is_add && details.child == this) {
347    find_text_->SetHorizontalMargins(0, 2);  // Left and Right margins.
348    find_text_->RemoveBorder();  // We draw our own border (a background image).
349  }
350}
351
352gfx::Size FindBarView::GetPreferredSize() {
353  gfx::Size prefsize = find_text_->GetPreferredSize();
354  prefsize.set_height(preferred_height_);
355
356  // Add up all the preferred sizes and margins of the rest of the controls.
357  prefsize.Enlarge(kMarginLeftOfCloseButton + kMarginRightOfCloseButton +
358                       kMarginLeftOfFindTextfield,
359                   0);
360  prefsize.Enlarge(find_previous_button_->GetPreferredSize().width(), 0);
361  prefsize.Enlarge(find_next_button_->GetPreferredSize().width(), 0);
362  prefsize.Enlarge(close_button_->GetPreferredSize().width(), 0);
363  return prefsize;
364}
365
366////////////////////////////////////////////////////////////////////////////////
367// FindBarView, views::ButtonListener implementation:
368
369void FindBarView::ButtonPressed(
370    views::Button* sender, const ui::Event& event) {
371  switch (sender->tag()) {
372    case FIND_PREVIOUS_TAG:
373    case FIND_NEXT_TAG:
374      if (!find_text_->text().empty()) {
375        FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(
376            find_bar_host()->GetFindBarController()->web_contents());
377        find_tab_helper->StartFinding(find_text_->text(),
378                                      sender->tag() == FIND_NEXT_TAG,
379                                      false);  // Not case sensitive.
380      }
381      if (event.IsMouseEvent()) {
382        // If mouse event, we move the focus back to the text-field, so that the
383        // user doesn't have to click on the text field to change the search. We
384        // don't want to do this for keyboard clicks on the button, since the
385        // user is more likely to press FindNext again than change the search
386        // query.
387        find_text_->RequestFocus();
388      }
389      break;
390    case CLOSE_TAG:
391      find_bar_host()->GetFindBarController()->EndFindSession(
392          FindBarController::kKeepSelectionOnPage,
393          FindBarController::kKeepResultsInFindBox);
394      break;
395    default:
396      NOTREACHED() << L"Unknown button";
397      break;
398  }
399}
400
401////////////////////////////////////////////////////////////////////////////////
402// FindBarView, views::TextfieldController implementation:
403
404bool FindBarView::HandleKeyEvent(views::Textfield* sender,
405                                 const ui::KeyEvent& key_event) {
406  // If the dialog is not visible, there is no reason to process keyboard input.
407  if (!host()->IsVisible())
408    return false;
409
410  if (find_bar_host()->MaybeForwardKeyEventToWebpage(key_event))
411    return true;  // Handled, we are done!
412
413  if (key_event.key_code() == ui::VKEY_RETURN) {
414    // Pressing Return/Enter starts the search (unless text box is empty).
415    string16 find_string = find_text_->text();
416    if (!find_string.empty()) {
417      FindBarController* controller = find_bar_host()->GetFindBarController();
418      FindTabHelper* find_tab_helper =
419          FindTabHelper::FromWebContents(controller->web_contents());
420      // Search forwards for enter, backwards for shift-enter.
421      find_tab_helper->StartFinding(find_string,
422                                    !key_event.IsShiftDown(),
423                                    false);  // Not case sensitive.
424    }
425    return true;
426  }
427
428  return false;
429}
430
431void FindBarView::OnAfterUserAction(views::Textfield* sender) {
432  // The composition text wouldn't be what the user is really looking for.
433  // We delay the search until the user commits the composition text.
434  if (!sender->IsIMEComposing() && sender->text() != last_searched_text_)
435    Find(sender->text());
436}
437
438void FindBarView::OnAfterPaste() {
439  // Clear the last search text so we always search for the user input after
440  // a paste operation, even if the pasted text is the same as before.
441  // See http://crbug.com/79002
442  last_searched_text_.clear();
443}
444
445void FindBarView::Find(const string16& search_text) {
446  FindBarController* controller = find_bar_host()->GetFindBarController();
447  DCHECK(controller);
448  content::WebContents* web_contents = controller->web_contents();
449  // We must guard against a NULL web_contents, which can happen if the text
450  // in the Find box is changed right after the tab is destroyed. Otherwise, it
451  // can lead to crashes, as exposed by automation testing in issue 8048.
452  if (!web_contents)
453    return;
454  FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
455
456  last_searched_text_ = search_text;
457
458  // When the user changes something in the text box we check the contents and
459  // if the textbox contains something we set it as the new search string and
460  // initiate search (even though old searches might be in progress).
461  if (!search_text.empty()) {
462    // The last two params here are forward (true) and case sensitive (false).
463    find_tab_helper->StartFinding(search_text, true, false);
464  } else {
465    find_tab_helper->StopFinding(FindBarController::kClearSelectionOnPage);
466    UpdateForResult(find_tab_helper->find_result(), string16());
467    find_bar_host()->MoveWindowIfNecessary(gfx::Rect(), false);
468
469    // Clearing the text box should clear the prepopulate state so that when
470    // we close and reopen the Find box it doesn't show the search we just
471    // deleted. We can't do this on ChromeOS yet because we get ContentsChanged
472    // sent for a lot more things than just the user nulling out the search
473    // terms. See http://crbug.com/45372.
474    Profile* profile =
475        Profile::FromBrowserContext(web_contents->GetBrowserContext());
476    FindBarState* find_bar_state = FindBarStateFactory::GetForProfile(profile);
477    find_bar_state->set_last_prepopulate_text(string16());
478  }
479}
480
481void FindBarView::UpdateMatchCountAppearance(bool no_match) {
482  if (no_match) {
483    match_count_text_->SetBackgroundColor(kBackgroundColorNoMatch);
484    match_count_text_->SetEnabledColor(kTextColorNoMatch);
485  } else {
486    match_count_text_->SetBackgroundColor(kBackgroundColorMatch);
487    match_count_text_->SetEnabledColor(kTextColorMatchCount);
488  }
489}
490
491bool FindBarView::FocusForwarderView::OnMousePressed(
492    const ui::MouseEvent& event) {
493  if (view_to_focus_on_mousedown_)
494    view_to_focus_on_mousedown_->RequestFocus();
495  return true;
496}
497
498FindBarHost* FindBarView::find_bar_host() const {
499  return static_cast<FindBarHost*>(host());
500}
501
502void FindBarView::OnThemeChanged() {
503  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
504  if (GetThemeProvider()) {
505    close_button_->SetBackground(
506        GetThemeProvider()->GetColor(ThemeProperties::COLOR_TAB_TEXT),
507        rb.GetImageSkiaNamed(IDR_CLOSE_1),
508        rb.GetImageSkiaNamed(IDR_CLOSE_1_MASK));
509  }
510}
511