Home | History | Annotate | Download | only in toolbar
      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 "ui/accessibility/ax_view_state.h"
     10 #include "ui/base/l10n/l10n_util.h"
     11 #include "ui/base/models/menu_model.h"
     12 #include "ui/base/theme_provider.h"
     13 #include "ui/gfx/display.h"
     14 #include "ui/gfx/screen.h"
     15 #include "ui/strings/grit/ui_strings.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 
     22 ToolbarButton::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 
     32 ToolbarButton::~ToolbarButton() {
     33 }
     34 
     35 void ToolbarButton::Init() {
     36   SetFocusable(false);
     37   SetAccessibilityFocusable(true);
     38   image()->EnableCanvasFlippingForRTLUI(true);
     39 }
     40 
     41 void ToolbarButton::ClearPendingMenu() {
     42   show_menu_factory_.InvalidateWeakPtrs();
     43 }
     44 
     45 bool ToolbarButton::IsMenuShowing() const {
     46   return menu_showing_;
     47 }
     48 
     49 gfx::Size ToolbarButton::GetPreferredSize() const {
     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::kItemPadding, 0);
     54   return size;
     55 }
     56 
     57 bool 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 
     77 bool 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 
     93 void 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 
    103 void ToolbarButton::OnMouseCaptureLost() {
    104 }
    105 
    106 void 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 
    114 void 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 
    124 void 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->AddStateFlag(ui::AX_STATE_HASPOPUP);
    129 }
    130 
    131 scoped_ptr<views::LabelButtonBorder>
    132 ToolbarButton::CreateDefaultBorder() const {
    133   scoped_ptr<views::LabelButtonBorder> border =
    134       LabelButton::CreateDefaultBorder();
    135 
    136   ui::ThemeProvider* provider = GetThemeProvider();
    137   if (provider && provider->UsingSystemTheme()) {
    138     // We set smaller insets here to accommodate the slightly larger GTK+
    139     // icons.
    140     border->set_insets(gfx::Insets(2, 2, 2, 2));
    141   }
    142 
    143   return border.Pass();
    144 }
    145 
    146 void ToolbarButton::ShowContextMenuForView(View* source,
    147                                            const gfx::Point& point,
    148                                            ui::MenuSourceType source_type) {
    149   if (!enabled())
    150     return;
    151 
    152   show_menu_factory_.InvalidateWeakPtrs();
    153   ShowDropDownMenu(source_type);
    154 }
    155 
    156 bool ToolbarButton::ShouldEnterPushedState(const ui::Event& event) {
    157   // Enter PUSHED state on press with Left or Right mouse button or on taps.
    158   // Remain in this state while the context menu is open.
    159   return event.type() == ui::ET_GESTURE_TAP ||
    160          event.type() == ui::ET_GESTURE_TAP_DOWN ||
    161          (event.IsMouseEvent() && ((ui::EF_LEFT_MOUSE_BUTTON |
    162              ui::EF_RIGHT_MOUSE_BUTTON) & event.flags()) != 0);
    163 }
    164 
    165 bool ToolbarButton::ShouldShowMenu() {
    166   return model_ != NULL;
    167 }
    168 
    169 void ToolbarButton::ShowDropDownMenu(ui::MenuSourceType source_type) {
    170   if (!ShouldShowMenu())
    171     return;
    172 
    173   gfx::Rect lb = GetLocalBounds();
    174 
    175   // Both the menu position and the menu anchor type change if the UI layout
    176   // is right-to-left.
    177   gfx::Point menu_position(lb.origin());
    178   menu_position.Offset(0, lb.height() - 1);
    179   if (base::i18n::IsRTL())
    180     menu_position.Offset(lb.width() - 1, 0);
    181 
    182   View::ConvertPointToScreen(this, &menu_position);
    183 
    184 #if defined(OS_WIN)
    185   int left_bound = GetSystemMetrics(SM_XVIRTUALSCREEN);
    186 #elif defined(OS_CHROMEOS)
    187   // A window won't overlap between displays on ChromeOS.
    188   // Use the left bound of the display on which
    189   // the menu button exists.
    190   gfx::NativeView view = GetWidget()->GetNativeView();
    191   gfx::Display display = gfx::Screen::GetScreenFor(
    192       view)->GetDisplayNearestWindow(view);
    193   int left_bound = display.bounds().x();
    194 #else
    195   // The window might be positioned over the edge between two screens. We'll
    196   // want to position the dropdown on the screen the mouse cursor is on.
    197   gfx::NativeView view = GetWidget()->GetNativeView();
    198   gfx::Screen* screen = gfx::Screen::GetScreenFor(view);
    199   gfx::Display display = screen->GetDisplayNearestPoint(
    200       screen->GetCursorScreenPoint());
    201   int left_bound = display.bounds().x();
    202 #endif
    203   if (menu_position.x() < left_bound)
    204     menu_position.set_x(left_bound);
    205 
    206   // Make the button look depressed while the menu is open.
    207   SetState(STATE_PRESSED);
    208 
    209   menu_showing_ = true;
    210 
    211   // Create and run menu.  Display an empty menu if model is NULL.
    212   if (model_.get()) {
    213     views::MenuModelAdapter menu_delegate(model_.get());
    214     menu_delegate.set_triggerable_event_flags(triggerable_event_flags());
    215     menu_runner_.reset(new views::MenuRunner(menu_delegate.CreateMenu(),
    216                                              views::MenuRunner::HAS_MNEMONICS));
    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     if (result == views::MenuRunner::MENU_DELETED)
    224       return;
    225   } else {
    226     views::MenuDelegate menu_delegate;
    227     views::MenuItemView* menu = new views::MenuItemView(&menu_delegate);
    228     menu_runner_.reset(
    229         new views::MenuRunner(menu, views::MenuRunner::HAS_MNEMONICS));
    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     if (result == views::MenuRunner::MENU_DELETED)
    237       return;
    238   }
    239 
    240   menu_showing_ = false;
    241 
    242   // Need to explicitly clear mouse handler so that events get sent
    243   // properly after the menu finishes running. If we don't do this, then
    244   // the first click to other parts of the UI is eaten.
    245   SetMouseHandler(NULL);
    246 
    247   // Set the state back to normal after the drop down menu is closed.
    248   if (state_ != STATE_DISABLED)
    249     SetState(STATE_NORMAL);
    250 }
    251