omnibox_popup_contents_view.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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/omnibox/omnibox_popup_contents_view.h"
6
7#include <algorithm>
8
9#include "chrome/browser/search/search.h"
10#include "chrome/browser/themes/theme_properties.h"
11#include "chrome/browser/ui/omnibox/omnibox_view.h"
12#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
13#include "chrome/browser/ui/views/omnibox/omnibox_result_view.h"
14#include "grit/ui_resources.h"
15#include "ui/base/theme_provider.h"
16#include "ui/gfx/canvas.h"
17#include "ui/gfx/image/image.h"
18#include "ui/gfx/path.h"
19#include "ui/views/controls/image_view.h"
20#include "ui/views/widget/widget.h"
21#include "ui/views/window/non_client_view.h"
22#include "ui/wm/core/window_animations.h"
23
24// This is the number of pixels in the border image interior to the actual
25// border.
26const int kBorderInterior = 6;
27
28class OmniboxPopupContentsView::AutocompletePopupWidget
29    : public views::Widget,
30      public base::SupportsWeakPtr<AutocompletePopupWidget> {
31 public:
32  AutocompletePopupWidget() {}
33  virtual ~AutocompletePopupWidget() {}
34
35 private:
36  DISALLOW_COPY_AND_ASSIGN(AutocompletePopupWidget);
37};
38
39////////////////////////////////////////////////////////////////////////////////
40// OmniboxPopupContentsView, public:
41
42OmniboxPopupView* OmniboxPopupContentsView::Create(
43    const gfx::FontList& font_list,
44    OmniboxView* omnibox_view,
45    OmniboxEditModel* edit_model,
46    LocationBarView* location_bar_view) {
47  OmniboxPopupContentsView* view = NULL;
48  view = new OmniboxPopupContentsView(
49      font_list, omnibox_view, edit_model, location_bar_view);
50  view->Init();
51  return view;
52}
53
54OmniboxPopupContentsView::OmniboxPopupContentsView(
55    const gfx::FontList& font_list,
56    OmniboxView* omnibox_view,
57    OmniboxEditModel* edit_model,
58    LocationBarView* location_bar_view)
59    : model_(new OmniboxPopupModel(this, edit_model)),
60      omnibox_view_(omnibox_view),
61      location_bar_view_(location_bar_view),
62      font_list_(font_list),
63      ignore_mouse_drag_(false),
64      size_animation_(this),
65      left_margin_(0),
66      right_margin_(0),
67      outside_vertical_padding_(0) {
68  // The contents is owned by the LocationBarView.
69  set_owned_by_client();
70
71  ui::ThemeProvider* theme = location_bar_view_->GetThemeProvider();
72  bottom_shadow_ = theme->GetImageSkiaNamed(IDR_BUBBLE_B);
73}
74
75void OmniboxPopupContentsView::Init() {
76  // This can't be done in the constructor as at that point we aren't
77  // necessarily our final class yet, and we may have subclasses
78  // overriding CreateResultView.
79  for (size_t i = 0; i < AutocompleteResult::kMaxMatches; ++i) {
80    OmniboxResultView* result_view = CreateResultView(i, font_list_);
81    result_view->SetVisible(false);
82    AddChildViewAt(result_view, static_cast<int>(i));
83  }
84}
85
86OmniboxPopupContentsView::~OmniboxPopupContentsView() {
87  // We don't need to do anything with |popup_| here.  The OS either has already
88  // closed the window, in which case it's been deleted, or it will soon, in
89  // which case there's nothing we need to do.
90}
91
92gfx::Rect OmniboxPopupContentsView::GetPopupBounds() const {
93  if (!size_animation_.is_animating())
94    return target_bounds_;
95
96  gfx::Rect current_frame_bounds = start_bounds_;
97  int total_height_delta = target_bounds_.height() - start_bounds_.height();
98  // Round |current_height_delta| instead of truncating so we won't leave single
99  // white pixels at the bottom of the popup as long when animating very small
100  // height differences.
101  int current_height_delta = static_cast<int>(
102      size_animation_.GetCurrentValue() * total_height_delta - 0.5);
103  current_frame_bounds.set_height(
104      current_frame_bounds.height() + current_height_delta);
105  return current_frame_bounds;
106}
107
108void OmniboxPopupContentsView::LayoutChildren() {
109  gfx::Rect contents_rect = GetContentsBounds();
110
111  contents_rect.Inset(left_margin_,
112                      views::NonClientFrameView::kClientEdgeThickness +
113                          outside_vertical_padding_,
114                      right_margin_, outside_vertical_padding_);
115  int top = contents_rect.y();
116  for (size_t i = 0; i < AutocompleteResult::kMaxMatches; ++i) {
117    View* v = child_at(i);
118    if (v->visible()) {
119      v->SetBounds(contents_rect.x(), top, contents_rect.width(),
120                   v->GetPreferredSize().height());
121      top = v->bounds().bottom();
122    }
123  }
124}
125
126////////////////////////////////////////////////////////////////////////////////
127// OmniboxPopupContentsView, OmniboxPopupView overrides:
128
129bool OmniboxPopupContentsView::IsOpen() const {
130  return popup_ != NULL;
131}
132
133void OmniboxPopupContentsView::InvalidateLine(size_t line) {
134  OmniboxResultView* result = result_view_at(line);
135  result->Invalidate();
136
137  if (HasMatchAt(line) && GetMatchAtIndex(line).associated_keyword.get()) {
138    result->ShowKeyword(IsSelectedIndex(line) &&
139        model_->selected_line_state() == OmniboxPopupModel::KEYWORD);
140  }
141}
142
143void OmniboxPopupContentsView::UpdatePopupAppearance() {
144  const size_t hidden_matches = model_->result().ShouldHideTopMatch() ? 1 : 0;
145  if (model_->result().size() <= hidden_matches ||
146      omnibox_view_->IsImeShowingPopup()) {
147    // No matches or the IME is showing a popup window which may overlap
148    // the omnibox popup window.  Close any existing popup.
149    if (popup_ != NULL) {
150      size_animation_.Stop();
151
152      // NOTE: Do NOT use CloseNow() here, as we may be deep in a callstack
153      // triggered by the popup receiving a message (e.g. LBUTTONUP), and
154      // destroying the popup would cause us to read garbage when we unwind back
155      // to that level.
156      popup_->Close();  // This will eventually delete the popup.
157      popup_.reset();
158    }
159    return;
160  }
161
162  // Update the match cached by each row, in the process of doing so make sure
163  // we have enough row views.
164  const size_t result_size = model_->result().size();
165  max_match_contents_width_ = 0;
166  for (size_t i = 0; i < result_size; ++i) {
167    OmniboxResultView* view = result_view_at(i);
168    const AutocompleteMatch& match = GetMatchAtIndex(i);
169    view->SetMatch(match);
170    view->SetVisible(i >= hidden_matches);
171    if (match.type == AutocompleteMatchType::SEARCH_SUGGEST_INFINITE) {
172      max_match_contents_width_ = std::max(
173          max_match_contents_width_, view->GetMatchContentsWidth());
174    }
175  }
176
177  for (size_t i = result_size; i < AutocompleteResult::kMaxMatches; ++i)
178    child_at(i)->SetVisible(false);
179
180  gfx::Point top_left_screen_coord;
181  int width;
182  location_bar_view_->GetOmniboxPopupPositioningInfo(
183      &top_left_screen_coord, &width, &left_margin_, &right_margin_);
184  gfx::Rect new_target_bounds(top_left_screen_coord,
185                              gfx::Size(width, CalculatePopupHeight()));
186
187  // If we're animating and our target height changes, reset the animation.
188  // NOTE: If we just reset blindly on _every_ update, then when the user types
189  // rapidly we could get "stuck" trying repeatedly to animate shrinking by the
190  // last few pixels to get to one visible result.
191  if (new_target_bounds.height() != target_bounds_.height())
192    size_animation_.Reset();
193  target_bounds_ = new_target_bounds;
194
195  if (popup_ == NULL) {
196    views::Widget* popup_parent = location_bar_view_->GetWidget();
197
198    // If the popup is currently closed, we need to create it.
199    popup_ = (new AutocompletePopupWidget)->AsWeakPtr();
200    views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
201    params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
202    params.parent = popup_parent->GetNativeView();
203    params.bounds = GetPopupBounds();
204    params.context = popup_parent->GetNativeWindow();
205    popup_->Init(params);
206    // Third-party software such as DigitalPersona identity verification can
207    // hook the underlying window creation methods and use SendMessage to
208    // synchronously change focus/activation, resulting in the popup being
209    // destroyed by the time control returns here.  Bail out in this case to
210    // avoid a NULL dereference.
211    if (!popup_.get())
212      return;
213    wm::SetWindowVisibilityAnimationTransition(
214        popup_->GetNativeView(), wm::ANIMATE_NONE);
215    popup_->SetContentsView(this);
216    popup_->StackAbove(omnibox_view_->GetRelativeWindowForPopup());
217    if (!popup_.get()) {
218      // For some IMEs GetRelativeWindowForPopup triggers the omnibox to lose
219      // focus, thereby closing (and destroying) the popup.
220      // TODO(sky): this won't be needed once we close the omnibox on input
221      // window showing.
222      return;
223    }
224    popup_->ShowInactive();
225  } else {
226    // Animate the popup shrinking, but don't animate growing larger since that
227    // would make the popup feel less responsive.
228    start_bounds_ = GetWidget()->GetWindowBoundsInScreen();
229    if (target_bounds_.height() < start_bounds_.height())
230      size_animation_.Show();
231    else
232      start_bounds_ = target_bounds_;
233    popup_->SetBounds(GetPopupBounds());
234  }
235
236  Layout();
237}
238
239gfx::Rect OmniboxPopupContentsView::GetTargetBounds() {
240  return target_bounds_;
241}
242
243void OmniboxPopupContentsView::PaintUpdatesNow() {
244  // TODO(beng): remove this from the interface.
245}
246
247void OmniboxPopupContentsView::OnDragCanceled() {
248  ignore_mouse_drag_ = true;
249}
250
251////////////////////////////////////////////////////////////////////////////////
252// OmniboxPopupContentsView, OmniboxResultViewModel implementation:
253
254bool OmniboxPopupContentsView::IsSelectedIndex(size_t index) const {
255  return index == model_->selected_line();
256}
257
258bool OmniboxPopupContentsView::IsHoveredIndex(size_t index) const {
259  return index == model_->hovered_line();
260}
261
262gfx::Image OmniboxPopupContentsView::GetIconIfExtensionMatch(
263    size_t index) const {
264  if (!HasMatchAt(index))
265    return gfx::Image();
266  return model_->GetIconIfExtensionMatch(GetMatchAtIndex(index));
267}
268
269////////////////////////////////////////////////////////////////////////////////
270// OmniboxPopupContentsView, AnimationDelegate implementation:
271
272void OmniboxPopupContentsView::AnimationProgressed(
273    const gfx::Animation* animation) {
274  // We should only be running the animation when the popup is already visible.
275  DCHECK(popup_ != NULL);
276  popup_->SetBounds(GetPopupBounds());
277}
278
279////////////////////////////////////////////////////////////////////////////////
280// OmniboxPopupContentsView, views::View overrides:
281
282void OmniboxPopupContentsView::Layout() {
283  // Size our children to the available content area.
284  LayoutChildren();
285
286  // We need to manually schedule a paint here since we are a layered window and
287  // won't implicitly require painting until we ask for one.
288  SchedulePaint();
289}
290
291views::View* OmniboxPopupContentsView::GetEventHandlerForRect(
292    const gfx::Rect& rect) {
293  return this;
294}
295
296views::View* OmniboxPopupContentsView::GetTooltipHandlerForPoint(
297    const gfx::Point& point) {
298  return NULL;
299}
300
301bool OmniboxPopupContentsView::OnMousePressed(
302    const ui::MouseEvent& event) {
303  ignore_mouse_drag_ = false;  // See comment on |ignore_mouse_drag_| in header.
304  if (event.IsLeftMouseButton() || event.IsMiddleMouseButton())
305    UpdateLineEvent(event, event.IsLeftMouseButton());
306  return true;
307}
308
309bool OmniboxPopupContentsView::OnMouseDragged(
310    const ui::MouseEvent& event) {
311  if (event.IsLeftMouseButton() || event.IsMiddleMouseButton())
312    UpdateLineEvent(event, !ignore_mouse_drag_ && event.IsLeftMouseButton());
313  return true;
314}
315
316void OmniboxPopupContentsView::OnMouseReleased(
317    const ui::MouseEvent& event) {
318  if (ignore_mouse_drag_) {
319    OnMouseCaptureLost();
320    return;
321  }
322
323  if (event.IsOnlyMiddleMouseButton() || event.IsOnlyLeftMouseButton()) {
324    OpenSelectedLine(event, event.IsOnlyLeftMouseButton() ? CURRENT_TAB :
325                                                            NEW_BACKGROUND_TAB);
326  }
327}
328
329void OmniboxPopupContentsView::OnMouseCaptureLost() {
330  ignore_mouse_drag_ = false;
331}
332
333void OmniboxPopupContentsView::OnMouseMoved(
334    const ui::MouseEvent& event) {
335  model_->SetHoveredLine(GetIndexForPoint(event.location()));
336}
337
338void OmniboxPopupContentsView::OnMouseEntered(
339    const ui::MouseEvent& event) {
340  model_->SetHoveredLine(GetIndexForPoint(event.location()));
341}
342
343void OmniboxPopupContentsView::OnMouseExited(
344    const ui::MouseEvent& event) {
345  model_->SetHoveredLine(OmniboxPopupModel::kNoMatch);
346}
347
348void OmniboxPopupContentsView::OnGestureEvent(ui::GestureEvent* event) {
349  switch (event->type()) {
350    case ui::ET_GESTURE_TAP_DOWN:
351    case ui::ET_GESTURE_SCROLL_BEGIN:
352    case ui::ET_GESTURE_SCROLL_UPDATE:
353      UpdateLineEvent(*event, true);
354      break;
355    case ui::ET_GESTURE_TAP:
356    case ui::ET_GESTURE_SCROLL_END:
357      OpenSelectedLine(*event, CURRENT_TAB);
358      break;
359    default:
360      return;
361  }
362  event->SetHandled();
363}
364
365////////////////////////////////////////////////////////////////////////////////
366// OmniboxPopupContentsView, protected:
367
368void OmniboxPopupContentsView::PaintResultViews(gfx::Canvas* canvas) {
369  canvas->DrawColor(result_view_at(0)->GetColor(
370      OmniboxResultView::NORMAL, OmniboxResultView::BACKGROUND));
371  View::PaintChildren(canvas, views::CullSet());
372}
373
374int OmniboxPopupContentsView::CalculatePopupHeight() {
375  DCHECK_GE(static_cast<size_t>(child_count()), model_->result().size());
376  int popup_height = 0;
377  for (size_t i = model_->result().ShouldHideTopMatch() ? 1 : 0;
378       i < model_->result().size(); ++i)
379    popup_height += child_at(i)->GetPreferredSize().height();
380
381  // Add enough space on the top and bottom so it looks like there is the same
382  // amount of space between the text and the popup border as there is in the
383  // interior between each row of text.
384  //
385  // Discovering the exact amount of leading and padding around the font is
386  // a bit tricky and platform-specific, but this computation seems to work in
387  // practice.
388  OmniboxResultView* result_view = result_view_at(0);
389  outside_vertical_padding_ =
390      (result_view->GetPreferredSize().height() -
391       result_view->GetTextHeight());
392
393  return popup_height +
394         views::NonClientFrameView::kClientEdgeThickness +  // Top border.
395         outside_vertical_padding_ * 2 +                    // Padding.
396         bottom_shadow_->height() - kBorderInterior;        // Bottom border.
397}
398
399OmniboxResultView* OmniboxPopupContentsView::CreateResultView(
400    int model_index,
401    const gfx::FontList& font_list) {
402  return new OmniboxResultView(this, model_index, location_bar_view_,
403                               font_list);
404}
405
406////////////////////////////////////////////////////////////////////////////////
407// OmniboxPopupContentsView, views::View overrides, protected:
408
409void OmniboxPopupContentsView::OnPaint(gfx::Canvas* canvas) {
410  gfx::Rect contents_bounds = GetContentsBounds();
411  contents_bounds.set_height(
412      contents_bounds.height() - bottom_shadow_->height() + kBorderInterior);
413
414  gfx::Path path;
415  MakeContentsPath(&path, contents_bounds);
416  canvas->Save();
417  canvas->sk_canvas()->clipPath(path,
418                                SkRegion::kIntersect_Op,
419                                true /* doAntialias */);
420  PaintResultViews(canvas);
421  canvas->Restore();
422
423  // Top border.
424  canvas->FillRect(
425      gfx::Rect(0, 0, width(), views::NonClientFrameView::kClientEdgeThickness),
426      ThemeProperties::GetDefaultColor(
427          ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
428
429  // Bottom border.
430  canvas->TileImageInt(*bottom_shadow_, 0, height() - bottom_shadow_->height(),
431                       width(), bottom_shadow_->height());
432}
433
434void OmniboxPopupContentsView::PaintChildren(gfx::Canvas* canvas,
435                                             const views::CullSet& cull_set) {
436  // We paint our children inside OnPaint().
437}
438
439////////////////////////////////////////////////////////////////////////////////
440// OmniboxPopupContentsView, private:
441
442bool OmniboxPopupContentsView::HasMatchAt(size_t index) const {
443  return index < model_->result().size();
444}
445
446const AutocompleteMatch& OmniboxPopupContentsView::GetMatchAtIndex(
447    size_t index) const {
448  return model_->result().match_at(index);
449}
450
451void OmniboxPopupContentsView::MakeContentsPath(
452    gfx::Path* path,
453    const gfx::Rect& bounding_rect) {
454  SkRect rect;
455  rect.set(SkIntToScalar(bounding_rect.x()),
456           SkIntToScalar(bounding_rect.y()),
457           SkIntToScalar(bounding_rect.right()),
458           SkIntToScalar(bounding_rect.bottom()));
459  path->addRect(rect);
460}
461
462size_t OmniboxPopupContentsView::GetIndexForPoint(
463    const gfx::Point& point) {
464  if (!HitTestPoint(point))
465    return OmniboxPopupModel::kNoMatch;
466
467  int nb_match = model_->result().size();
468  DCHECK(nb_match <= child_count());
469  for (int i = 0; i < nb_match; ++i) {
470    views::View* child = child_at(i);
471    gfx::Point point_in_child_coords(point);
472    View::ConvertPointToTarget(this, child, &point_in_child_coords);
473    if (child->visible() && child->HitTestPoint(point_in_child_coords))
474      return i;
475  }
476  return OmniboxPopupModel::kNoMatch;
477}
478
479void OmniboxPopupContentsView::UpdateLineEvent(
480    const ui::LocatedEvent& event,
481    bool should_set_selected_line) {
482  size_t index = GetIndexForPoint(event.location());
483  model_->SetHoveredLine(index);
484  if (HasMatchAt(index) && should_set_selected_line)
485    model_->SetSelectedLine(index, false, false);
486}
487
488void OmniboxPopupContentsView::OpenSelectedLine(
489    const ui::LocatedEvent& event,
490    WindowOpenDisposition disposition) {
491  size_t index = GetIndexForPoint(event.location());
492  if (!HasMatchAt(index))
493    return;
494  omnibox_view_->OpenMatch(model_->result().match_at(index), disposition,
495                           GURL(), base::string16(), index);
496}
497
498OmniboxResultView* OmniboxPopupContentsView::result_view_at(size_t i) {
499  return static_cast<OmniboxResultView*>(child_at(static_cast<int>(i)));
500}
501