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.
5 #include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h"
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 "ui/base/theme_provider.h"
15 #include "ui/gfx/canvas.h"
16 #include "ui/gfx/image/image.h"
17 #include "ui/gfx/path.h"
18 #include "ui/resources/grit/ui_resources.h"
19 #include "ui/views/controls/image_view.h"
20 #include "ui/views/view_targeter.h"
21 #include "ui/views/widget/widget.h"
22 #include "ui/views/window/non_client_view.h"
24 // This is the number of pixels in the border image interior to the actual
26 const int kBorderInterior = 6;
28 class OmniboxPopupContentsView::AutocompletePopupWidget
29 : public views::Widget,
30 public base::SupportsWeakPtr<AutocompletePopupWidget> {
32 AutocompletePopupWidget() {}
33 ~AutocompletePopupWidget() override {}
36 DISALLOW_COPY_AND_ASSIGN(AutocompletePopupWidget);
39 ////////////////////////////////////////////////////////////////////////////////
40 // OmniboxPopupContentsView, public:
42 OmniboxPopupView* 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);
54 OmniboxPopupContentsView::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),
67 outside_vertical_padding_(0) {
68 // The contents is owned by the LocationBarView.
69 set_owned_by_client();
71 ui::ThemeProvider* theme = location_bar_view_->GetThemeProvider();
72 bottom_shadow_ = theme->GetImageSkiaNamed(IDR_BUBBLE_B);
75 scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(this)));
78 void OmniboxPopupContentsView::Init() {
79 // This can't be done in the constructor as at that point we aren't
80 // necessarily our final class yet, and we may have subclasses
81 // overriding CreateResultView.
82 for (size_t i = 0; i < AutocompleteResult::kMaxMatches; ++i) {
83 OmniboxResultView* result_view = CreateResultView(i, font_list_);
84 result_view->SetVisible(false);
85 AddChildViewAt(result_view, static_cast<int>(i));
89 OmniboxPopupContentsView::~OmniboxPopupContentsView() {
90 // We don't need to do anything with |popup_| here. The OS either has already
91 // closed the window, in which case it's been deleted, or it will soon, in
92 // which case there's nothing we need to do.
95 gfx::Rect OmniboxPopupContentsView::GetPopupBounds() const {
96 if (!size_animation_.is_animating())
97 return target_bounds_;
99 gfx::Rect current_frame_bounds = start_bounds_;
100 int total_height_delta = target_bounds_.height() - start_bounds_.height();
101 // Round |current_height_delta| instead of truncating so we won't leave single
102 // white pixels at the bottom of the popup as long when animating very small
103 // height differences.
104 int current_height_delta = static_cast<int>(
105 size_animation_.GetCurrentValue() * total_height_delta - 0.5);
106 current_frame_bounds.set_height(
107 current_frame_bounds.height() + current_height_delta);
108 return current_frame_bounds;
111 void OmniboxPopupContentsView::LayoutChildren() {
112 gfx::Rect contents_rect = GetContentsBounds();
114 contents_rect.Inset(left_margin_,
115 views::NonClientFrameView::kClientEdgeThickness +
116 outside_vertical_padding_,
117 right_margin_, outside_vertical_padding_);
118 int top = contents_rect.y();
119 for (size_t i = 0; i < AutocompleteResult::kMaxMatches; ++i) {
120 View* v = child_at(i);
122 v->SetBounds(contents_rect.x(), top, contents_rect.width(),
123 v->GetPreferredSize().height());
124 top = v->bounds().bottom();
129 ////////////////////////////////////////////////////////////////////////////////
130 // OmniboxPopupContentsView, OmniboxPopupView overrides:
132 bool OmniboxPopupContentsView::IsOpen() const {
133 return popup_ != NULL;
136 void OmniboxPopupContentsView::InvalidateLine(size_t line) {
137 OmniboxResultView* result = result_view_at(line);
138 result->Invalidate();
140 if (HasMatchAt(line) && GetMatchAtIndex(line).associated_keyword.get()) {
141 result->ShowKeyword(IsSelectedIndex(line) &&
142 model_->selected_line_state() == OmniboxPopupModel::KEYWORD);
146 void OmniboxPopupContentsView::UpdatePopupAppearance() {
147 const size_t hidden_matches = model_->result().ShouldHideTopMatch() ? 1 : 0;
148 if (model_->result().size() <= hidden_matches ||
149 omnibox_view_->IsImeShowingPopup()) {
150 // No matches or the IME is showing a popup window which may overlap
151 // the omnibox popup window. Close any existing popup.
152 if (popup_ != NULL) {
153 size_animation_.Stop();
155 // NOTE: Do NOT use CloseNow() here, as we may be deep in a callstack
156 // triggered by the popup receiving a message (e.g. LBUTTONUP), and
157 // destroying the popup would cause us to read garbage when we unwind back
159 popup_->Close(); // This will eventually delete the popup.
165 // Update the match cached by each row, in the process of doing so make sure
166 // we have enough row views.
167 const size_t result_size = model_->result().size();
168 max_match_contents_width_ = 0;
169 for (size_t i = 0; i < result_size; ++i) {
170 OmniboxResultView* view = result_view_at(i);
171 const AutocompleteMatch& match = GetMatchAtIndex(i);
172 view->SetMatch(match);
173 view->SetVisible(i >= hidden_matches);
174 if (match.type == AutocompleteMatchType::SEARCH_SUGGEST_INFINITE) {
175 max_match_contents_width_ = std::max(
176 max_match_contents_width_, view->GetMatchContentsWidth());
180 for (size_t i = result_size; i < AutocompleteResult::kMaxMatches; ++i)
181 child_at(i)->SetVisible(false);
183 gfx::Point top_left_screen_coord;
185 location_bar_view_->GetOmniboxPopupPositioningInfo(
186 &top_left_screen_coord, &width, &left_margin_, &right_margin_);
187 gfx::Rect new_target_bounds(top_left_screen_coord,
188 gfx::Size(width, CalculatePopupHeight()));
190 // If we're animating and our target height changes, reset the animation.
191 // NOTE: If we just reset blindly on _every_ update, then when the user types
192 // rapidly we could get "stuck" trying repeatedly to animate shrinking by the
193 // last few pixels to get to one visible result.
194 if (new_target_bounds.height() != target_bounds_.height())
195 size_animation_.Reset();
196 target_bounds_ = new_target_bounds;
198 if (popup_ == NULL) {
199 views::Widget* popup_parent = location_bar_view_->GetWidget();
201 // If the popup is currently closed, we need to create it.
202 popup_ = (new AutocompletePopupWidget)->AsWeakPtr();
203 views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
204 params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
205 params.parent = popup_parent->GetNativeView();
206 params.bounds = GetPopupBounds();
207 params.context = popup_parent->GetNativeWindow();
208 popup_->Init(params);
209 // Third-party software such as DigitalPersona identity verification can
210 // hook the underlying window creation methods and use SendMessage to
211 // synchronously change focus/activation, resulting in the popup being
212 // destroyed by the time control returns here. Bail out in this case to
213 // avoid a NULL dereference.
216 popup_->SetVisibilityAnimationTransition(views::Widget::ANIMATE_NONE);
217 popup_->SetContentsView(this);
218 popup_->StackAbove(omnibox_view_->GetRelativeWindowForPopup());
220 // For some IMEs GetRelativeWindowForPopup triggers the omnibox to lose
221 // focus, thereby closing (and destroying) the popup.
222 // TODO(sky): this won't be needed once we close the omnibox on input
226 popup_->ShowInactive();
228 // Animate the popup shrinking, but don't animate growing larger since that
229 // would make the popup feel less responsive.
230 start_bounds_ = GetWidget()->GetWindowBoundsInScreen();
231 if (target_bounds_.height() < start_bounds_.height())
232 size_animation_.Show();
234 start_bounds_ = target_bounds_;
235 popup_->SetBounds(GetPopupBounds());
241 gfx::Rect OmniboxPopupContentsView::GetTargetBounds() {
242 return target_bounds_;
245 void OmniboxPopupContentsView::PaintUpdatesNow() {
246 // TODO(beng): remove this from the interface.
249 void OmniboxPopupContentsView::OnDragCanceled() {
250 ignore_mouse_drag_ = true;
253 ////////////////////////////////////////////////////////////////////////////////
254 // OmniboxPopupContentsView, OmniboxResultViewModel implementation:
256 bool OmniboxPopupContentsView::IsSelectedIndex(size_t index) const {
257 return index == model_->selected_line();
260 bool OmniboxPopupContentsView::IsHoveredIndex(size_t index) const {
261 return index == model_->hovered_line();
264 gfx::Image OmniboxPopupContentsView::GetIconIfExtensionMatch(
265 size_t index) const {
266 if (!HasMatchAt(index))
268 return model_->GetIconIfExtensionMatch(GetMatchAtIndex(index));
271 bool OmniboxPopupContentsView::IsStarredMatch(
272 const AutocompleteMatch& match) const {
273 return model_->IsStarredMatch(match);
276 ////////////////////////////////////////////////////////////////////////////////
277 // OmniboxPopupContentsView, AnimationDelegate implementation:
279 void OmniboxPopupContentsView::AnimationProgressed(
280 const gfx::Animation* animation) {
281 // We should only be running the animation when the popup is already visible.
282 DCHECK(popup_ != NULL);
283 popup_->SetBounds(GetPopupBounds());
286 ////////////////////////////////////////////////////////////////////////////////
287 // OmniboxPopupContentsView, views::View overrides:
289 void OmniboxPopupContentsView::Layout() {
290 // Size our children to the available content area.
293 // We need to manually schedule a paint here since we are a layered window and
294 // won't implicitly require painting until we ask for one.
298 views::View* OmniboxPopupContentsView::GetTooltipHandlerForPoint(
299 const gfx::Point& point) {
303 bool OmniboxPopupContentsView::OnMousePressed(
304 const ui::MouseEvent& event) {
305 ignore_mouse_drag_ = false; // See comment on |ignore_mouse_drag_| in header.
306 if (event.IsLeftMouseButton() || event.IsMiddleMouseButton())
307 UpdateLineEvent(event, event.IsLeftMouseButton());
311 bool OmniboxPopupContentsView::OnMouseDragged(
312 const ui::MouseEvent& event) {
313 if (event.IsLeftMouseButton() || event.IsMiddleMouseButton())
314 UpdateLineEvent(event, !ignore_mouse_drag_ && event.IsLeftMouseButton());
318 void OmniboxPopupContentsView::OnMouseReleased(
319 const ui::MouseEvent& event) {
320 if (ignore_mouse_drag_) {
321 OnMouseCaptureLost();
325 if (event.IsOnlyMiddleMouseButton() || event.IsOnlyLeftMouseButton()) {
326 OpenSelectedLine(event, event.IsOnlyLeftMouseButton() ? CURRENT_TAB :
331 void OmniboxPopupContentsView::OnMouseCaptureLost() {
332 ignore_mouse_drag_ = false;
335 void OmniboxPopupContentsView::OnMouseMoved(
336 const ui::MouseEvent& event) {
337 model_->SetHoveredLine(GetIndexForPoint(event.location()));
340 void OmniboxPopupContentsView::OnMouseEntered(
341 const ui::MouseEvent& event) {
342 model_->SetHoveredLine(GetIndexForPoint(event.location()));
345 void OmniboxPopupContentsView::OnMouseExited(
346 const ui::MouseEvent& event) {
347 model_->SetHoveredLine(OmniboxPopupModel::kNoMatch);
350 void OmniboxPopupContentsView::OnGestureEvent(ui::GestureEvent* event) {
351 switch (event->type()) {
352 case ui::ET_GESTURE_TAP_DOWN:
353 case ui::ET_GESTURE_SCROLL_BEGIN:
354 case ui::ET_GESTURE_SCROLL_UPDATE:
355 UpdateLineEvent(*event, true);
357 case ui::ET_GESTURE_TAP:
358 case ui::ET_GESTURE_SCROLL_END:
359 OpenSelectedLine(*event, CURRENT_TAB);
367 ////////////////////////////////////////////////////////////////////////////////
368 // OmniboxPopupContentsView, protected:
370 void OmniboxPopupContentsView::PaintResultViews(gfx::Canvas* canvas) {
371 canvas->DrawColor(result_view_at(0)->GetColor(
372 OmniboxResultView::NORMAL, OmniboxResultView::BACKGROUND));
373 View::PaintChildren(canvas, views::CullSet());
376 int OmniboxPopupContentsView::CalculatePopupHeight() {
377 DCHECK_GE(static_cast<size_t>(child_count()), model_->result().size());
378 int popup_height = 0;
379 for (size_t i = model_->result().ShouldHideTopMatch() ? 1 : 0;
380 i < model_->result().size(); ++i)
381 popup_height += child_at(i)->GetPreferredSize().height();
383 // Add enough space on the top and bottom so it looks like there is the same
384 // amount of space between the text and the popup border as there is in the
385 // interior between each row of text.
387 // Discovering the exact amount of leading and padding around the font is
388 // a bit tricky and platform-specific, but this computation seems to work in
390 OmniboxResultView* result_view = result_view_at(0);
391 outside_vertical_padding_ =
392 (result_view->GetPreferredSize().height() -
393 result_view->GetTextHeight());
395 return popup_height +
396 views::NonClientFrameView::kClientEdgeThickness + // Top border.
397 outside_vertical_padding_ * 2 + // Padding.
398 bottom_shadow_->height() - kBorderInterior; // Bottom border.
401 OmniboxResultView* OmniboxPopupContentsView::CreateResultView(
403 const gfx::FontList& font_list) {
404 return new OmniboxResultView(this, model_index, location_bar_view_,
408 ////////////////////////////////////////////////////////////////////////////////
409 // OmniboxPopupContentsView, views::View overrides, protected:
411 void OmniboxPopupContentsView::OnPaint(gfx::Canvas* canvas) {
412 gfx::Rect contents_bounds = GetContentsBounds();
413 contents_bounds.set_height(
414 contents_bounds.height() - bottom_shadow_->height() + kBorderInterior);
417 MakeContentsPath(&path, contents_bounds);
419 canvas->sk_canvas()->clipPath(path,
420 SkRegion::kIntersect_Op,
421 true /* doAntialias */);
422 PaintResultViews(canvas);
427 gfx::Rect(0, 0, width(), views::NonClientFrameView::kClientEdgeThickness),
428 ThemeProperties::GetDefaultColor(
429 ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
432 canvas->TileImageInt(*bottom_shadow_, 0, height() - bottom_shadow_->height(),
433 width(), bottom_shadow_->height());
436 void OmniboxPopupContentsView::PaintChildren(gfx::Canvas* canvas,
437 const views::CullSet& cull_set) {
438 // We paint our children inside OnPaint().
441 ////////////////////////////////////////////////////////////////////////////////
442 // OmniboxPopupContentsView, private:
444 views::View* OmniboxPopupContentsView::TargetForRect(views::View* root,
445 const gfx::Rect& rect) {
446 CHECK_EQ(root, this);
450 bool OmniboxPopupContentsView::HasMatchAt(size_t index) const {
451 return index < model_->result().size();
454 const AutocompleteMatch& OmniboxPopupContentsView::GetMatchAtIndex(
455 size_t index) const {
456 return model_->result().match_at(index);
459 void OmniboxPopupContentsView::MakeContentsPath(
461 const gfx::Rect& bounding_rect) {
463 rect.set(SkIntToScalar(bounding_rect.x()),
464 SkIntToScalar(bounding_rect.y()),
465 SkIntToScalar(bounding_rect.right()),
466 SkIntToScalar(bounding_rect.bottom()));
470 size_t OmniboxPopupContentsView::GetIndexForPoint(
471 const gfx::Point& point) {
472 if (!HitTestPoint(point))
473 return OmniboxPopupModel::kNoMatch;
475 int nb_match = model_->result().size();
476 DCHECK(nb_match <= child_count());
477 for (int i = 0; i < nb_match; ++i) {
478 views::View* child = child_at(i);
479 gfx::Point point_in_child_coords(point);
480 View::ConvertPointToTarget(this, child, &point_in_child_coords);
481 if (child->visible() && child->HitTestPoint(point_in_child_coords))
484 return OmniboxPopupModel::kNoMatch;
487 void OmniboxPopupContentsView::UpdateLineEvent(
488 const ui::LocatedEvent& event,
489 bool should_set_selected_line) {
490 size_t index = GetIndexForPoint(event.location());
491 model_->SetHoveredLine(index);
492 if (HasMatchAt(index) && should_set_selected_line)
493 model_->SetSelectedLine(index, false, false);
496 void OmniboxPopupContentsView::OpenSelectedLine(
497 const ui::LocatedEvent& event,
498 WindowOpenDisposition disposition) {
499 size_t index = GetIndexForPoint(event.location());
500 if (!HasMatchAt(index))
502 omnibox_view_->OpenMatch(model_->result().match_at(index), disposition,
503 GURL(), base::string16(), index);
506 OmniboxResultView* OmniboxPopupContentsView::result_view_at(size_t i) {
507 return static_cast<OmniboxResultView*>(child_at(static_cast<int>(i)));