Home | History | Annotate | Download | only in views
      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/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/border.h"
     32 #include "ui/views/controls/button/image_button.h"
     33 #include "ui/views/controls/label.h"
     34 #include "ui/views/painter.h"
     35 #include "ui/views/widget/widget.h"
     36 
     37 namespace {
     38 
     39 // The margins around the search field, match count label, and the close button.
     40 const int kMarginLeftOfCloseButton = 3;
     41 const int kMarginRightOfCloseButton = 7;
     42 const int kMarginLeftOfMatchCountLabel = 2;
     43 const int kMarginRightOfMatchCountLabel = 1;
     44 const int kMarginLeftOfFindTextfield = 12;
     45 
     46 // The margins around the match count label (We add extra space so that the
     47 // background highlight extends beyond just the text).
     48 const int kMatchCountExtraWidth = 9;
     49 
     50 // Minimum width for the match count label.
     51 const int kMatchCountMinWidth = 30;
     52 
     53 // The text color for the match count label.
     54 const SkColor kTextColorMatchCount = SkColorSetRGB(178, 178, 178);
     55 
     56 // The text color for the match count label when no matches are found.
     57 const SkColor kTextColorNoMatch = SK_ColorBLACK;
     58 
     59 // The background color of the match count label when results are found.
     60 const SkColor kBackgroundColorMatch = SkColorSetARGB(0, 255, 255, 255);
     61 
     62 // The background color of the match count label when no results are found.
     63 const SkColor kBackgroundColorNoMatch = SkColorSetRGB(255, 102, 102);
     64 
     65 // The default number of average characters that the text box will be. This
     66 // number brings the width on a "regular fonts" system to about 300px.
     67 const int kDefaultCharWidth = 43;
     68 
     69 }  // namespace
     70 
     71 ////////////////////////////////////////////////////////////////////////////////
     72 // FindBarView, public:
     73 
     74 FindBarView::FindBarView(FindBarHost* host)
     75     : DropdownBarView(host),
     76       find_text_(NULL),
     77       match_count_text_(NULL),
     78       focus_forwarder_view_(NULL),
     79       find_previous_button_(NULL),
     80       find_next_button_(NULL),
     81       close_button_(NULL) {
     82   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
     83 
     84   find_text_ = new views::Textfield;
     85   find_text_->set_id(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD);
     86   find_text_->set_default_width_in_chars(kDefaultCharWidth);
     87   find_text_->set_controller(this);
     88   find_text_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_FIND));
     89   // The find bar textfield has a background image instead of a border.
     90   find_text_->SetBorder(views::Border::NullBorder());
     91   AddChildView(find_text_);
     92 
     93   match_count_text_ = new views::Label();
     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_->SetFocusable(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_->SetFocusable(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_->SetFocusable(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   SetBorderFromIds(
    154       IDR_FIND_DIALOG_LEFT, IDR_FIND_DIALOG_MIDDLE, IDR_FIND_DIALOG_RIGHT);
    155 
    156   preferred_height_ = rb.GetImageSkiaNamed(IDR_FIND_DIALOG_MIDDLE)->height();
    157 
    158   static const int kImages[] = IMAGE_GRID(IDR_TEXTFIELD);
    159   find_text_border_.reset(views::Painter::CreateImageGridPainter(kImages));
    160 
    161   EnableCanvasFlippingForRTLUI(true);
    162 }
    163 
    164 FindBarView::~FindBarView() {
    165 }
    166 
    167 void FindBarView::SetFindTextAndSelectedRange(
    168     const base::string16& find_text,
    169     const gfx::Range& selected_range) {
    170   find_text_->SetText(find_text);
    171   find_text_->SelectRange(selected_range);
    172 }
    173 
    174 base::string16 FindBarView::GetFindText() const {
    175   return find_text_->text();
    176 }
    177 
    178 gfx::Range FindBarView::GetSelectedRange() const {
    179   return find_text_->GetSelectedRange();
    180 }
    181 
    182 base::string16 FindBarView::GetFindSelectedText() const {
    183   return find_text_->GetSelectedText();
    184 }
    185 
    186 base::string16 FindBarView::GetMatchCountText() const {
    187   return match_count_text_->text();
    188 }
    189 
    190 void FindBarView::UpdateForResult(const FindNotificationDetails& result,
    191                                   const base::string16& find_text) {
    192   bool have_valid_range =
    193       result.number_of_matches() != -1 && result.active_match_ordinal() != -1;
    194 
    195   // http://crbug.com/34970: some IMEs get confused if we change the text
    196   // composed by them. To avoid this problem, we should check the IME status and
    197   // update the text only when the IME is not composing text.
    198   if (find_text_->text() != find_text && !find_text_->IsIMEComposing()) {
    199     find_text_->SetText(find_text);
    200     find_text_->SelectAll(true);
    201   }
    202 
    203   if (find_text.empty() || !have_valid_range) {
    204     // If there was no text entered, we don't show anything in the result count
    205     // area.
    206     ClearMatchCount();
    207     return;
    208   }
    209 
    210   match_count_text_->SetText(l10n_util::GetStringFUTF16(IDS_FIND_IN_PAGE_COUNT,
    211       base::IntToString16(result.active_match_ordinal()),
    212       base::IntToString16(result.number_of_matches())));
    213 
    214   UpdateMatchCountAppearance(result.number_of_matches() == 0 &&
    215                              result.final_update());
    216 
    217   // The match_count label may have increased/decreased in size so we need to
    218   // do a layout and repaint the dialog so that the find text field doesn't
    219   // partially overlap the match-count label when it increases on no matches.
    220   Layout();
    221   SchedulePaint();
    222 }
    223 
    224 void FindBarView::ClearMatchCount() {
    225   match_count_text_->SetText(base::string16());
    226   UpdateMatchCountAppearance(false);
    227   Layout();
    228   SchedulePaint();
    229 }
    230 
    231 void FindBarView::SetFocusAndSelection(bool select_all) {
    232   find_text_->RequestFocus();
    233   if (select_all && !find_text_->text().empty())
    234     find_text_->SelectAll(true);
    235 }
    236 
    237 ///////////////////////////////////////////////////////////////////////////////
    238 // FindBarView, views::View overrides:
    239 
    240 void FindBarView::OnPaint(gfx::Canvas* canvas) {
    241   // Paint drop down bar border and background.
    242   DropdownBarView::OnPaint(canvas);
    243 
    244   // Paint the background and border for the textfield.
    245   const int find_text_x = kMarginLeftOfFindTextfield / 2;
    246   const gfx::Rect text_bounds(find_text_x, find_next_button_->y(),
    247                               find_next_button_->bounds().right() - find_text_x,
    248                               find_next_button_->height());
    249   const int kBorderCornerRadius = 2;
    250   gfx::Rect background_bounds = text_bounds;
    251   background_bounds.Inset(kBorderCornerRadius, kBorderCornerRadius);
    252   SkPaint paint;
    253   paint.setStyle(SkPaint::kFill_Style);
    254   paint.setColor(find_text_->GetBackgroundColor());
    255   canvas->DrawRoundRect(background_bounds, kBorderCornerRadius, paint);
    256   canvas->Save();
    257   canvas->ClipRect(gfx::Rect(0, 0, find_previous_button_->x(), height()));
    258   views::Painter::PaintPainterAt(canvas, find_text_border_.get(), text_bounds);
    259   canvas->Restore();
    260 
    261   // Draw the background of the match text. We want to make sure the red
    262   // "no-match" background almost completely fills up the amount of vertical
    263   // space within the text box. We therefore fix the size relative to the button
    264   // heights. We use the FindPrev button, which has a 1px outer whitespace
    265   // margin, 1px border and we want to appear 1px below the border line so we
    266   // subtract 3 for top and 3 for bottom.
    267   gfx::Rect match_count_background_bounds(match_count_text_->bounds());
    268   match_count_background_bounds.set_height(
    269       find_previous_button_->height() - 6);  // Subtract 3px x 2.
    270   match_count_background_bounds.set_y(
    271       (height() - match_count_background_bounds.height()) / 2);
    272   canvas->FillRect(match_count_background_bounds,
    273                    match_count_text_->background_color());
    274 }
    275 
    276 void FindBarView::Layout() {
    277   int panel_width = GetPreferredSize().width();
    278 
    279   // Stay within view bounds.
    280   int view_width = width();
    281   if (view_width && view_width < panel_width)
    282     panel_width = view_width;
    283 
    284   // First we draw the close button on the far right.
    285   gfx::Size sz = close_button_->GetPreferredSize();
    286   close_button_->SetBounds(panel_width - sz.width() -
    287                                kMarginRightOfCloseButton,
    288                            (height() - sz.height()) / 2,
    289                            sz.width(),
    290                            sz.height());
    291   // Set the color.
    292   OnThemeChanged();
    293 
    294   // Next, the FindNext button to the left the close button.
    295   sz = find_next_button_->GetPreferredSize();
    296   find_next_button_->SetBounds(close_button_->x() -
    297                                    find_next_button_->width() -
    298                                    kMarginLeftOfCloseButton,
    299                                (height() - sz.height()) / 2,
    300                                 sz.width(),
    301                                 sz.height());
    302 
    303   // Then, the FindPrevious button to the left the FindNext button.
    304   sz = find_previous_button_->GetPreferredSize();
    305   find_previous_button_->SetBounds(find_next_button_->x() -
    306                                        find_previous_button_->width(),
    307                                    (height() - sz.height()) / 2,
    308                                    sz.width(),
    309                                    sz.height());
    310 
    311   // Then the label showing the match count number.
    312   sz = match_count_text_->GetPreferredSize();
    313   // We extend the label bounds a bit to give the background highlighting a bit
    314   // of breathing room (margins around the text).
    315   sz.Enlarge(kMatchCountExtraWidth, 0);
    316   sz.SetToMax(gfx::Size(kMatchCountMinWidth, 0));
    317   int match_count_x =
    318       find_previous_button_->x() - kMarginRightOfMatchCountLabel - sz.width();
    319   int find_text_y = (height() - find_text_->GetPreferredSize().height()) / 2;
    320   match_count_text_->SetBounds(match_count_x,
    321                                find_text_y + find_text_->GetBaseline() -
    322                                    match_count_text_->GetBaseline(),
    323                                sz.width(), sz.height());
    324 
    325   // And whatever space is left in between, gets filled up by the find edit box.
    326   int find_text_width = std::max(0, match_count_x -
    327       kMarginLeftOfMatchCountLabel - kMarginLeftOfFindTextfield);
    328   find_text_->SetBounds(kMarginLeftOfFindTextfield, find_text_y,
    329       find_text_width, find_text_->GetPreferredSize().height());
    330 
    331   // The focus forwarder view is a hidden view that should cover the area
    332   // between the find text box and the find button so that when the user clicks
    333   // in that area we focus on the find text box.
    334   int find_text_edge = find_text_->x() + find_text_->width();
    335   focus_forwarder_view_->SetBounds(
    336       find_text_edge, find_previous_button_->y(),
    337       find_previous_button_->x() - find_text_edge,
    338       find_previous_button_->height());
    339 }
    340 
    341 gfx::Size FindBarView::GetPreferredSize() const {
    342   gfx::Size prefsize = find_text_->GetPreferredSize();
    343   prefsize.set_height(preferred_height_);
    344 
    345   // Add up all the preferred sizes and margins of the rest of the controls.
    346   prefsize.Enlarge(kMarginLeftOfCloseButton + kMarginRightOfCloseButton +
    347                        kMarginLeftOfFindTextfield,
    348                    0);
    349   prefsize.Enlarge(find_previous_button_->GetPreferredSize().width(), 0);
    350   prefsize.Enlarge(find_next_button_->GetPreferredSize().width(), 0);
    351   prefsize.Enlarge(close_button_->GetPreferredSize().width(), 0);
    352   return prefsize;
    353 }
    354 
    355 ////////////////////////////////////////////////////////////////////////////////
    356 // FindBarView, views::ButtonListener implementation:
    357 
    358 void FindBarView::ButtonPressed(
    359     views::Button* sender, const ui::Event& event) {
    360   switch (sender->tag()) {
    361     case FIND_PREVIOUS_TAG:
    362     case FIND_NEXT_TAG:
    363       if (!find_text_->text().empty()) {
    364         FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(
    365             find_bar_host()->GetFindBarController()->web_contents());
    366         find_tab_helper->StartFinding(find_text_->text(),
    367                                       sender->tag() == FIND_NEXT_TAG,
    368                                       false);  // Not case sensitive.
    369       }
    370       if (event.IsMouseEvent()) {
    371         // If mouse event, we move the focus back to the text-field, so that the
    372         // user doesn't have to click on the text field to change the search. We
    373         // don't want to do this for keyboard clicks on the button, since the
    374         // user is more likely to press FindNext again than change the search
    375         // query.
    376         find_text_->RequestFocus();
    377       }
    378       break;
    379     case CLOSE_TAG:
    380       find_bar_host()->GetFindBarController()->EndFindSession(
    381           FindBarController::kKeepSelectionOnPage,
    382           FindBarController::kKeepResultsInFindBox);
    383       break;
    384     default:
    385       NOTREACHED() << L"Unknown button";
    386       break;
    387   }
    388 }
    389 
    390 ////////////////////////////////////////////////////////////////////////////////
    391 // FindBarView, views::TextfieldController implementation:
    392 
    393 bool FindBarView::HandleKeyEvent(views::Textfield* sender,
    394                                  const ui::KeyEvent& key_event) {
    395   // If the dialog is not visible, there is no reason to process keyboard input.
    396   if (!host()->IsVisible())
    397     return false;
    398 
    399   if (find_bar_host()->MaybeForwardKeyEventToWebpage(key_event))
    400     return true;  // Handled, we are done!
    401 
    402   if (key_event.key_code() == ui::VKEY_RETURN) {
    403     // Pressing Return/Enter starts the search (unless text box is empty).
    404     base::string16 find_string = find_text_->text();
    405     if (!find_string.empty()) {
    406       FindBarController* controller = find_bar_host()->GetFindBarController();
    407       FindTabHelper* find_tab_helper =
    408           FindTabHelper::FromWebContents(controller->web_contents());
    409       // Search forwards for enter, backwards for shift-enter.
    410       find_tab_helper->StartFinding(find_string,
    411                                     !key_event.IsShiftDown(),
    412                                     false);  // Not case sensitive.
    413     }
    414     return true;
    415   }
    416 
    417   return false;
    418 }
    419 
    420 void FindBarView::OnAfterUserAction(views::Textfield* sender) {
    421   // The composition text wouldn't be what the user is really looking for.
    422   // We delay the search until the user commits the composition text.
    423   if (!sender->IsIMEComposing() && sender->text() != last_searched_text_)
    424     Find(sender->text());
    425 }
    426 
    427 void FindBarView::OnAfterPaste() {
    428   // Clear the last search text so we always search for the user input after
    429   // a paste operation, even if the pasted text is the same as before.
    430   // See http://crbug.com/79002
    431   last_searched_text_.clear();
    432 }
    433 
    434 void FindBarView::Find(const base::string16& search_text) {
    435   FindBarController* controller = find_bar_host()->GetFindBarController();
    436   DCHECK(controller);
    437   content::WebContents* web_contents = controller->web_contents();
    438   // We must guard against a NULL web_contents, which can happen if the text
    439   // in the Find box is changed right after the tab is destroyed. Otherwise, it
    440   // can lead to crashes, as exposed by automation testing in issue 8048.
    441   if (!web_contents)
    442     return;
    443   FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
    444 
    445   last_searched_text_ = search_text;
    446 
    447   // When the user changes something in the text box we check the contents and
    448   // if the textbox contains something we set it as the new search string and
    449   // initiate search (even though old searches might be in progress).
    450   if (!search_text.empty()) {
    451     // The last two params here are forward (true) and case sensitive (false).
    452     find_tab_helper->StartFinding(search_text, true, false);
    453   } else {
    454     find_tab_helper->StopFinding(FindBarController::kClearSelectionOnPage);
    455     UpdateForResult(find_tab_helper->find_result(), base::string16());
    456     find_bar_host()->MoveWindowIfNecessary(gfx::Rect(), false);
    457 
    458     // Clearing the text box should clear the prepopulate state so that when
    459     // we close and reopen the Find box it doesn't show the search we just
    460     // deleted. We can't do this on ChromeOS yet because we get ContentsChanged
    461     // sent for a lot more things than just the user nulling out the search
    462     // terms. See http://crbug.com/45372.
    463     Profile* profile =
    464         Profile::FromBrowserContext(web_contents->GetBrowserContext());
    465     FindBarState* find_bar_state = FindBarStateFactory::GetForProfile(profile);
    466     find_bar_state->set_last_prepopulate_text(base::string16());
    467   }
    468 }
    469 
    470 void FindBarView::UpdateMatchCountAppearance(bool no_match) {
    471   if (no_match) {
    472     match_count_text_->SetBackgroundColor(kBackgroundColorNoMatch);
    473     match_count_text_->SetEnabledColor(kTextColorNoMatch);
    474   } else {
    475     match_count_text_->SetBackgroundColor(kBackgroundColorMatch);
    476     match_count_text_->SetEnabledColor(kTextColorMatchCount);
    477   }
    478 }
    479 
    480 bool FindBarView::FocusForwarderView::OnMousePressed(
    481     const ui::MouseEvent& event) {
    482   if (view_to_focus_on_mousedown_)
    483     view_to_focus_on_mousedown_->RequestFocus();
    484   return true;
    485 }
    486 
    487 FindBarHost* FindBarView::find_bar_host() const {
    488   return static_cast<FindBarHost*>(host());
    489 }
    490 
    491 void FindBarView::OnThemeChanged() {
    492   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    493   if (GetThemeProvider()) {
    494     close_button_->SetBackground(
    495         GetThemeProvider()->GetColor(ThemeProperties::COLOR_TAB_TEXT),
    496         rb.GetImageSkiaNamed(IDR_CLOSE_1),
    497         rb.GetImageSkiaNamed(IDR_CLOSE_1_MASK));
    498   }
    499 }
    500