toolbar_button.cc revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
1// Copyright 2013 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/toolbar/toolbar_button.h"
6
7#include "base/bind.h"
8#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
9#include "grit/theme_resources.h"
10#include "grit/ui_strings.h"
11#include "ui/accessibility/ax_view_state.h"
12#include "ui/base/l10n/l10n_util.h"
13#include "ui/base/models/menu_model.h"
14#include "ui/gfx/display.h"
15#include "ui/gfx/screen.h"
16#include "ui/views/controls/button/label_button_border.h"
17#include "ui/views/controls/menu/menu_item_view.h"
18#include "ui/views/controls/menu/menu_model_adapter.h"
19#include "ui/views/controls/menu/menu_runner.h"
20#include "ui/views/widget/widget.h"
21
22ToolbarButton::ToolbarButton(views::ButtonListener* listener,
23                             ui::MenuModel* model)
24    : views::LabelButton(listener, base::string16()),
25      model_(model),
26      menu_showing_(false),
27      y_position_on_lbuttondown_(0),
28      show_menu_factory_(this) {
29  set_context_menu_controller(this);
30}
31
32ToolbarButton::~ToolbarButton() {
33}
34
35void ToolbarButton::Init() {
36  SetFocusable(false);
37  SetAccessibilityFocusable(true);
38  image()->EnableCanvasFlippingForRTLUI(true);
39}
40
41void ToolbarButton::ClearPendingMenu() {
42  show_menu_factory_.InvalidateWeakPtrs();
43}
44
45bool ToolbarButton::IsMenuShowing() const {
46  return menu_showing_;
47}
48
49gfx::Size ToolbarButton::GetPreferredSize() {
50  gfx::Size size(image()->GetPreferredSize());
51  gfx::Size label_size = label()->GetPreferredSize();
52  if (label_size.width() > 0)
53    size.Enlarge(label_size.width() + LocationBarView::GetItemPadding(), 0);
54  return size;
55}
56
57bool ToolbarButton::OnMousePressed(const ui::MouseEvent& event) {
58  if (enabled() && ShouldShowMenu() &&
59      IsTriggerableEvent(event) && HitTestPoint(event.location())) {
60    // Store the y pos of the mouse coordinates so we can use them later to
61    // determine if the user dragged the mouse down (which should pop up the
62    // drag down menu immediately, instead of waiting for the timer)
63    y_position_on_lbuttondown_ = event.y();
64
65    // Schedule a task that will show the menu.
66    const int kMenuTimerDelay = 500;
67    base::MessageLoop::current()->PostDelayedTask(
68        FROM_HERE,
69        base::Bind(&ToolbarButton::ShowDropDownMenu,
70                   show_menu_factory_.GetWeakPtr(),
71                   ui::GetMenuSourceTypeForEvent(event)),
72        base::TimeDelta::FromMilliseconds(kMenuTimerDelay));
73  }
74  return LabelButton::OnMousePressed(event);
75}
76
77bool ToolbarButton::OnMouseDragged(const ui::MouseEvent& event) {
78  bool result = LabelButton::OnMouseDragged(event);
79
80  if (show_menu_factory_.HasWeakPtrs()) {
81    // If the mouse is dragged to a y position lower than where it was when
82    // clicked then we should not wait for the menu to appear but show
83    // it immediately.
84    if (event.y() > y_position_on_lbuttondown_ + GetHorizontalDragThreshold()) {
85      show_menu_factory_.InvalidateWeakPtrs();
86      ShowDropDownMenu(ui::GetMenuSourceTypeForEvent(event));
87    }
88  }
89
90  return result;
91}
92
93void ToolbarButton::OnMouseReleased(const ui::MouseEvent& event) {
94  if (IsTriggerableEvent(event) ||
95      (event.IsRightMouseButton() && !HitTestPoint(event.location()))) {
96    LabelButton::OnMouseReleased(event);
97  }
98
99  if (IsTriggerableEvent(event))
100    show_menu_factory_.InvalidateWeakPtrs();
101}
102
103void ToolbarButton::OnMouseCaptureLost() {
104}
105
106void ToolbarButton::OnMouseExited(const ui::MouseEvent& event) {
107  // Starting a drag results in a MouseExited, we need to ignore it.
108  // A right click release triggers an exit event. We want to
109  // remain in a PUSHED state until the drop down menu closes.
110  if (state_ != STATE_DISABLED && !InDrag() && state_ != STATE_PRESSED)
111    SetState(STATE_NORMAL);
112}
113
114void ToolbarButton::OnGestureEvent(ui::GestureEvent* event) {
115  if (menu_showing_) {
116    // While dropdown menu is showing the button should not handle gestures.
117    event->StopPropagation();
118    return;
119  }
120
121  LabelButton::OnGestureEvent(event);
122}
123
124void ToolbarButton::GetAccessibleState(ui::AXViewState* state) {
125  CustomButton::GetAccessibleState(state);
126  state->role = ui::AX_ROLE_BUTTON_DROP_DOWN;
127  state->default_action = l10n_util::GetStringUTF16(IDS_APP_ACCACTION_PRESS);
128  state->state = ui::AX_STATE_HASPOPUP;
129}
130
131void ToolbarButton::ShowContextMenuForView(View* source,
132                                           const gfx::Point& point,
133                                           ui::MenuSourceType source_type) {
134  if (!enabled())
135    return;
136
137  show_menu_factory_.InvalidateWeakPtrs();
138  ShowDropDownMenu(source_type);
139}
140
141bool ToolbarButton::ShouldEnterPushedState(const ui::Event& event) {
142  // Enter PUSHED state on press with Left or Right mouse button or on taps.
143  // Remain in this state while the context menu is open.
144  return event.type() == ui::ET_GESTURE_TAP ||
145         event.type() == ui::ET_GESTURE_TAP_DOWN ||
146         (event.IsMouseEvent() && ((ui::EF_LEFT_MOUSE_BUTTON |
147             ui::EF_RIGHT_MOUSE_BUTTON) & event.flags()) != 0);
148}
149
150bool ToolbarButton::ShouldShowMenu() {
151  return model_ != NULL;
152}
153
154void ToolbarButton::ShowDropDownMenu(ui::MenuSourceType source_type) {
155  if (!ShouldShowMenu())
156    return;
157
158  gfx::Rect lb = GetLocalBounds();
159
160  // Both the menu position and the menu anchor type change if the UI layout
161  // is right-to-left.
162  gfx::Point menu_position(lb.origin());
163  menu_position.Offset(0, lb.height() - 1);
164  if (base::i18n::IsRTL())
165    menu_position.Offset(lb.width() - 1, 0);
166
167  View::ConvertPointToScreen(this, &menu_position);
168
169#if defined(OS_WIN)
170  int left_bound = GetSystemMetrics(SM_XVIRTUALSCREEN);
171#elif defined(OS_CHROMEOS)
172  // A window won't overlap between displays on ChromeOS.
173  // Use the left bound of the display on which
174  // the menu button exists.
175  gfx::NativeView view = GetWidget()->GetNativeView();
176  gfx::Display display = gfx::Screen::GetScreenFor(
177      view)->GetDisplayNearestWindow(view);
178  int left_bound = display.bounds().x();
179#else
180  // The window might be positioned over the edge between two screens. We'll
181  // want to position the dropdown on the screen the mouse cursor is on.
182  gfx::NativeView view = GetWidget()->GetNativeView();
183  gfx::Screen* screen = gfx::Screen::GetScreenFor(view);
184  gfx::Display display = screen->GetDisplayNearestPoint(
185      screen->GetCursorScreenPoint());
186  int left_bound = display.bounds().x();
187#endif
188  if (menu_position.x() < left_bound)
189    menu_position.set_x(left_bound);
190
191  // Make the button look depressed while the menu is open.
192  SetState(STATE_PRESSED);
193
194  menu_showing_ = true;
195
196  // Create and run menu.  Display an empty menu if model is NULL.
197  if (model_.get()) {
198    views::MenuModelAdapter menu_delegate(model_.get());
199    menu_delegate.set_triggerable_event_flags(triggerable_event_flags());
200    menu_runner_.reset(new views::MenuRunner(menu_delegate.CreateMenu()));
201    views::MenuRunner::RunResult result =
202        menu_runner_->RunMenuAt(GetWidget(), NULL,
203                                gfx::Rect(menu_position, gfx::Size(0, 0)),
204                                views::MenuItemView::TOPLEFT,
205                                source_type,
206                                views::MenuRunner::HAS_MNEMONICS);
207    if (result == views::MenuRunner::MENU_DELETED)
208      return;
209  } else {
210    views::MenuDelegate menu_delegate;
211    views::MenuItemView* menu = new views::MenuItemView(&menu_delegate);
212    menu_runner_.reset(new views::MenuRunner(menu));
213    views::MenuRunner::RunResult result =
214        menu_runner_->RunMenuAt(GetWidget(), NULL,
215                                gfx::Rect(menu_position, gfx::Size(0, 0)),
216                                views::MenuItemView::TOPLEFT,
217                                source_type,
218                                views::MenuRunner::HAS_MNEMONICS);
219    if (result == views::MenuRunner::MENU_DELETED)
220      return;
221  }
222
223  menu_showing_ = false;
224
225  // Need to explicitly clear mouse handler so that events get sent
226  // properly after the menu finishes running. If we don't do this, then
227  // the first click to other parts of the UI is eaten.
228  SetMouseHandler(NULL);
229
230  // Set the state back to normal after the drop down menu is closed.
231  if (state_ != STATE_DISABLED)
232    SetState(STATE_NORMAL);
233}
234