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