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 "chrome/grit/generated_resources.h"
     23 #include "grit/theme_resources.h"
     24 #include "third_party/skia/include/core/SkPaint.h"
     25 #include "ui/base/l10n/l10n_util.h"
     26 #include "ui/base/resource/resource_bundle.h"
     27 #include "ui/base/theme_provider.h"
     28 #include "ui/events/event.h"
     29 #include "ui/gfx/canvas.h"
     30 #include "ui/resources/grit/ui_resources.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/ime/input_method.h"
     35 #include "ui/views/painter.h"
     36 #include "ui/views/widget/widget.h"
     37 
     38 namespace {
     39 
     40 // The margins around the UI controls, derived from assets and design specs.
     41 const int kMarginLeftOfCloseButton = 3;
     42 const int kMarginRightOfCloseButton = 7;
     43 const int kMarginLeftOfMatchCountLabel = 3;
     44 const int kMarginRightOfMatchCountLabel = 1;
     45 const int kMarginLeftOfFindTextfield = 12;
     46 const int kMarginVerticalFindTextfield = 6;
     47 
     48 // The margins around the match count label (We add extra space so that the
     49 // background highlight extends beyond just the text).
     50 const int kMatchCountExtraWidth = 9;
     51 
     52 // Minimum width for the match count label.
     53 const int kMatchCountMinWidth = 30;
     54 
     55 // The text color for the match count label.
     56 const SkColor kTextColorMatchCount = SkColorSetRGB(178, 178, 178);
     57 
     58 // The text color for the match count label when no matches are found.
     59 const SkColor kTextColorNoMatch = SK_ColorBLACK;
     60 
     61 // The background color of the match count label when results are found.
     62 const SkColor kBackgroundColorMatch = SkColorSetARGB(0, 255, 255, 255);
     63 
     64 // The background color of the match count label when no results are found.
     65 const SkColor kBackgroundColorNoMatch = SkColorSetRGB(255, 102, 102);
     66 
     67 // The default number of average characters that the text box will be. This
     68 // number brings the width on a "regular fonts" system to about 300px.
     69 const int kDefaultCharWidth = 43;
     70 
     71 }  // namespace
     72 
     73 ////////////////////////////////////////////////////////////////////////////////
     74 // FindBarView, public:
     75 
     76 FindBarView::FindBarView(FindBarHost* host)
     77     : DropdownBarView(host),
     78       find_text_(NULL),
     79       match_count_text_(NULL),
     80       focus_forwarder_view_(NULL),
     81       find_previous_button_(NULL),
     82       find_next_button_(NULL),
     83       close_button_(NULL) {
     84   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
     85 
     86   find_text_ = new views::Textfield;
     87   find_text_->set_id(VIEW_ID_FIND_IN_PAGE_TEXT_FIELD);
     88   find_text_->set_default_width_in_chars(kDefaultCharWidth);
     89   find_text_->set_controller(this);
     90   find_text_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_FIND));
     91   // The find bar textfield has a background image instead of a border.
     92   find_text_->SetBorder(views::Border::NullBorder());
     93   AddChildView(find_text_);
     94 
     95   match_count_text_ = new views::Label();
     96   AddChildView(match_count_text_);
     97 
     98   // Create a focus forwarder view which sends focus to find_text_.
     99   focus_forwarder_view_ = new FocusForwarderView(find_text_);
    100   AddChildView(focus_forwarder_view_);
    101 
    102   find_previous_button_ = new views::ImageButton(this);
    103   find_previous_button_->set_tag(FIND_PREVIOUS_TAG);
    104   find_previous_button_->SetFocusable(true);
    105   find_previous_button_->SetImage(views::CustomButton::STATE_NORMAL,
    106       rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV));
    107   find_previous_button_->SetImage(views::CustomButton::STATE_HOVERED,
    108       rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_H));
    109   find_previous_button_->SetImage(views::CustomButton::STATE_PRESSED,
    110       rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_P));
    111   find_previous_button_->SetImage(views::CustomButton::STATE_DISABLED,
    112       rb.GetImageSkiaNamed(IDR_FINDINPAGE_PREV_D));
    113   find_previous_button_->SetTooltipText(
    114       l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_PREVIOUS_TOOLTIP));
    115   find_previous_button_->SetAccessibleName(
    116       l10n_util::GetStringUTF16(IDS_ACCNAME_PREVIOUS));
    117   AddChildView(find_previous_button_);
    118 
    119   find_next_button_ = new views::ImageButton(this);
    120   find_next_button_->set_tag(FIND_NEXT_TAG);
    121   find_next_button_->SetFocusable(true);
    122   find_next_button_->SetImage(views::CustomButton::STATE_NORMAL,
    123       rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT));
    124   find_next_button_->SetImage(views::CustomButton::STATE_HOVERED,
    125       rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_H));
    126   find_next_button_->SetImage(views::CustomButton::STATE_PRESSED,
    127       rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_P));
    128   find_next_button_->SetImage(views::CustomButton::STATE_DISABLED,
    129       rb.GetImageSkiaNamed(IDR_FINDINPAGE_NEXT_D));
    130   find_next_button_->SetTooltipText(
    131       l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_NEXT_TOOLTIP));
    132   find_next_button_->SetAccessibleName(
    133       l10n_util::GetStringUTF16(IDS_ACCNAME_NEXT));
    134   AddChildView(find_next_button_);
    135 
    136   close_button_ = new views::ImageButton(this);
    137   close_button_->set_tag(CLOSE_TAG);
    138   close_button_->SetFocusable(true);
    139   close_button_->SetImage(views::CustomButton::STATE_NORMAL,
    140                           rb.GetImageSkiaNamed(IDR_CLOSE_1));
    141   close_button_->SetImage(views::CustomButton::STATE_HOVERED,
    142                           rb.GetImageSkiaNamed(IDR_CLOSE_1_H));
    143   close_button_->SetImage(views::CustomButton::STATE_PRESSED,
    144                           rb.GetImageSkiaNamed(IDR_CLOSE_1_P));
    145   close_button_->SetTooltipText(
    146       l10n_util::GetStringUTF16(IDS_FIND_IN_PAGE_CLOSE_TOOLTIP));
    147   close_button_->SetAccessibleName(
    148       l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
    149   close_button_->SetAnimationDuration(0);
    150   AddChildView(close_button_);
    151 
    152   SetBackground(rb.GetImageSkiaNamed(IDR_FIND_DLG_LEFT_BACKGROUND),
    153                 rb.GetImageSkiaNamed(IDR_FIND_DLG_RIGHT_BACKGROUND));
    154 
    155   SetBorderFromIds(
    156       IDR_FIND_DIALOG_LEFT, IDR_FIND_DIALOG_MIDDLE, IDR_FIND_DIALOG_RIGHT);
    157 
    158   preferred_height_ = rb.GetImageSkiaNamed(IDR_FIND_DIALOG_MIDDLE)->height();
    159 
    160   static const int kImages[] = IMAGE_GRID(IDR_TEXTFIELD);
    161   find_text_border_.reset(views::Painter::CreateImageGridPainter(kImages));
    162 
    163   EnableCanvasFlippingForRTLUI(true);
    164 }
    165 
    166 FindBarView::~FindBarView() {
    167 }
    168 
    169 void FindBarView::SetFindTextAndSelectedRange(
    170     const base::string16& find_text,
    171     const gfx::Range& selected_range) {
    172   find_text_->SetText(find_text);
    173   find_text_->SelectRange(selected_range);
    174 }
    175 
    176 base::string16 FindBarView::GetFindText() const {
    177   return find_text_->text();
    178 }
    179 
    180 gfx::Range FindBarView::GetSelectedRange() const {
    181   return find_text_->GetSelectedRange();
    182 }
    183 
    184 base::string16 FindBarView::GetFindSelectedText() const {
    185   return find_text_->GetSelectedText();
    186 }
    187 
    188 base::string16 FindBarView::GetMatchCountText() const {
    189   return match_count_text_->text();
    190 }
    191 
    192 void FindBarView::UpdateForResult(const FindNotificationDetails& result,
    193                                   const base::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 
    226 void FindBarView::ClearMatchCount() {
    227   match_count_text_->SetText(base::string16());
    228   UpdateMatchCountAppearance(false);
    229   Layout();
    230   SchedulePaint();
    231 }
    232 
    233 void FindBarView::SetFocusAndSelection(bool select_all) {
    234   find_text_->RequestFocus();
    235   GetInputMethod()->ShowImeIfNeeded();
    236   if (select_all && !find_text_->text().empty())
    237     find_text_->SelectAll(true);
    238 }
    239 
    240 ///////////////////////////////////////////////////////////////////////////////
    241 // FindBarView, views::View overrides:
    242 
    243 void FindBarView::OnPaint(gfx::Canvas* canvas) {
    244   // Paint drop down bar border and background.
    245   DropdownBarView::OnPaint(canvas);
    246 
    247   // Paint the background and border for the textfield.
    248   const int find_text_x = kMarginLeftOfFindTextfield / 2;
    249   const gfx::Rect text_bounds(find_text_x, find_next_button_->y(),
    250                               find_next_button_->bounds().right() - find_text_x,
    251                               find_next_button_->height());
    252   const int kBorderCornerRadius = 2;
    253   gfx::Rect background_bounds = text_bounds;
    254   background_bounds.Inset(kBorderCornerRadius, kBorderCornerRadius);
    255   SkPaint paint;
    256   paint.setStyle(SkPaint::kFill_Style);
    257   paint.setColor(find_text_->GetBackgroundColor());
    258   canvas->DrawRoundRect(background_bounds, kBorderCornerRadius, paint);
    259   canvas->Save();
    260   canvas->ClipRect(gfx::Rect(0, 0, find_previous_button_->x(), height()));
    261   views::Painter::PaintPainterAt(canvas, find_text_border_.get(), text_bounds);
    262   canvas->Restore();
    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 
    279 void 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   const int match_count_x =
    321       find_previous_button_->x() - kMarginRightOfMatchCountLabel - sz.width();
    322   const int find_text_y = kMarginVerticalFindTextfield;
    323   const gfx::Insets find_text_insets(find_text_->GetInsets());
    324   match_count_text_->SetBounds(match_count_x,
    325                                find_text_y - find_text_insets.top() +
    326                                    find_text_->GetBaseline() -
    327                                    match_count_text_->GetBaseline(),
    328                                sz.width(), sz.height());
    329 
    330   // Fill the remaining width and available height with the textfield.
    331   const int left_margin = kMarginLeftOfFindTextfield - find_text_insets.left();
    332   const int find_text_width = std::max(0, match_count_x - left_margin -
    333       kMarginLeftOfMatchCountLabel + find_text_insets.right());
    334   find_text_->SetBounds(left_margin, find_text_y, find_text_width,
    335                         height() - 2 * kMarginVerticalFindTextfield);
    336 
    337   // The focus forwarder view is a hidden view that should cover the area
    338   // between the find text box and the find button so that when the user clicks
    339   // in that area we focus on the find text box.
    340   const int find_text_edge = find_text_->x() + find_text_->width();
    341   focus_forwarder_view_->SetBounds(
    342       find_text_edge, find_previous_button_->y(),
    343       find_previous_button_->x() - find_text_edge,
    344       find_previous_button_->height());
    345 }
    346 
    347 gfx::Size FindBarView::GetPreferredSize() const {
    348   gfx::Size prefsize = find_text_->GetPreferredSize();
    349   prefsize.set_height(preferred_height_);
    350 
    351   // Add up all the preferred sizes and margins of the rest of the controls.
    352   prefsize.Enlarge(kMarginLeftOfCloseButton + kMarginRightOfCloseButton +
    353                        kMarginLeftOfFindTextfield -
    354                        find_text_->GetInsets().width(),
    355                    0);
    356   prefsize.Enlarge(find_previous_button_->GetPreferredSize().width(), 0);
    357   prefsize.Enlarge(find_next_button_->GetPreferredSize().width(), 0);
    358   prefsize.Enlarge(close_button_->GetPreferredSize().width(), 0);
    359   return prefsize;
    360 }
    361 
    362 ////////////////////////////////////////////////////////////////////////////////
    363 // FindBarView, views::ButtonListener implementation:
    364 
    365 void FindBarView::ButtonPressed(
    366     views::Button* sender, const ui::Event& event) {
    367   switch (sender->tag()) {
    368     case FIND_PREVIOUS_TAG:
    369     case FIND_NEXT_TAG:
    370       if (!find_text_->text().empty()) {
    371         FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(
    372             find_bar_host()->GetFindBarController()->web_contents());
    373         find_tab_helper->StartFinding(find_text_->text(),
    374                                       sender->tag() == FIND_NEXT_TAG,
    375                                       false);  // Not case sensitive.
    376       }
    377       if (event.IsMouseEvent()) {
    378         // If mouse event, we move the focus back to the text-field, so that the
    379         // user doesn't have to click on the text field to change the search. We
    380         // don't want to do this for keyboard clicks on the button, since the
    381         // user is more likely to press FindNext again than change the search
    382         // query.
    383         find_text_->RequestFocus();
    384       }
    385       break;
    386     case CLOSE_TAG:
    387       find_bar_host()->GetFindBarController()->EndFindSession(
    388           FindBarController::kKeepSelectionOnPage,
    389           FindBarController::kKeepResultsInFindBox);
    390       break;
    391     default:
    392       NOTREACHED() << L"Unknown button";
    393       break;
    394   }
    395 }
    396 
    397 ////////////////////////////////////////////////////////////////////////////////
    398 // FindBarView, views::TextfieldController implementation:
    399 
    400 bool FindBarView::HandleKeyEvent(views::Textfield* sender,
    401                                  const ui::KeyEvent& key_event) {
    402   // If the dialog is not visible, there is no reason to process keyboard input.
    403   if (!host()->IsVisible())
    404     return false;
    405 
    406   if (find_bar_host()->MaybeForwardKeyEventToWebpage(key_event))
    407     return true;  // Handled, we are done!
    408 
    409   if (key_event.key_code() == ui::VKEY_RETURN) {
    410     // Pressing Return/Enter starts the search (unless text box is empty).
    411     base::string16 find_string = find_text_->text();
    412     if (!find_string.empty()) {
    413       FindBarController* controller = find_bar_host()->GetFindBarController();
    414       FindTabHelper* find_tab_helper =
    415           FindTabHelper::FromWebContents(controller->web_contents());
    416       // Search forwards for enter, backwards for shift-enter.
    417       find_tab_helper->StartFinding(find_string,
    418                                     !key_event.IsShiftDown(),
    419                                     false);  // Not case sensitive.
    420     }
    421     return true;
    422   }
    423 
    424   return false;
    425 }
    426 
    427 void FindBarView::OnAfterUserAction(views::Textfield* sender) {
    428   // The composition text wouldn't be what the user is really looking for.
    429   // We delay the search until the user commits the composition text.
    430   if (!sender->IsIMEComposing() && sender->text() != last_searched_text_)
    431     Find(sender->text());
    432 }
    433 
    434 void FindBarView::OnAfterPaste() {
    435   // Clear the last search text so we always search for the user input after
    436   // a paste operation, even if the pasted text is the same as before.
    437   // See http://crbug.com/79002
    438   last_searched_text_.clear();
    439 }
    440 
    441 void FindBarView::Find(const base::string16& search_text) {
    442   FindBarController* controller = find_bar_host()->GetFindBarController();
    443   DCHECK(controller);
    444   content::WebContents* web_contents = controller->web_contents();
    445   // We must guard against a NULL web_contents, which can happen if the text
    446   // in the Find box is changed right after the tab is destroyed. Otherwise, it
    447   // can lead to crashes, as exposed by automation testing in issue 8048.
    448   if (!web_contents)
    449     return;
    450   FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents);
    451 
    452   last_searched_text_ = search_text;
    453 
    454   // When the user changes something in the text box we check the contents and
    455   // if the textbox contains something we set it as the new search string and
    456   // initiate search (even though old searches might be in progress).
    457   if (!search_text.empty()) {
    458     // The last two params here are forward (true) and case sensitive (false).
    459     find_tab_helper->StartFinding(search_text, true, false);
    460   } else {
    461     find_tab_helper->StopFinding(FindBarController::kClearSelectionOnPage);
    462     UpdateForResult(find_tab_helper->find_result(), base::string16());
    463     find_bar_host()->MoveWindowIfNecessary(gfx::Rect(), false);
    464 
    465     // Clearing the text box should clear the prepopulate state so that when
    466     // we close and reopen the Find box it doesn't show the search we just
    467     // deleted. We can't do this on ChromeOS yet because we get ContentsChanged
    468     // sent for a lot more things than just the user nulling out the search
    469     // terms. See http://crbug.com/45372.
    470     Profile* profile =
    471         Profile::FromBrowserContext(web_contents->GetBrowserContext());
    472     FindBarState* find_bar_state = FindBarStateFactory::GetForProfile(profile);
    473     find_bar_state->set_last_prepopulate_text(base::string16());
    474   }
    475 }
    476 
    477 void FindBarView::UpdateMatchCountAppearance(bool no_match) {
    478   if (no_match) {
    479     match_count_text_->SetBackgroundColor(kBackgroundColorNoMatch);
    480     match_count_text_->SetEnabledColor(kTextColorNoMatch);
    481   } else {
    482     match_count_text_->SetBackgroundColor(kBackgroundColorMatch);
    483     match_count_text_->SetEnabledColor(kTextColorMatchCount);
    484   }
    485 }
    486 
    487 bool FindBarView::FocusForwarderView::OnMousePressed(
    488     const ui::MouseEvent& event) {
    489   if (view_to_focus_on_mousedown_)
    490     view_to_focus_on_mousedown_->RequestFocus();
    491   return true;
    492 }
    493 
    494 FindBarHost* FindBarView::find_bar_host() const {
    495   return static_cast<FindBarHost*>(host());
    496 }
    497 
    498 void FindBarView::OnThemeChanged() {
    499   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
    500   if (GetThemeProvider()) {
    501     close_button_->SetBackground(
    502         GetThemeProvider()->GetColor(ThemeProperties::COLOR_TAB_TEXT),
    503         rb.GetImageSkiaNamed(IDR_CLOSE_1),
    504         rb.GetImageSkiaNamed(IDR_CLOSE_1_MASK));
    505   }
    506 }
    507