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 "ui/views/controls/menu/menu_controller.h"
6
7#include "base/i18n/case_conversion.h"
8#include "base/i18n/rtl.h"
9#include "base/strings/utf_string_conversions.h"
10#include "base/time/time.h"
11#include "ui/base/dragdrop/drag_utils.h"
12#include "ui/base/dragdrop/os_exchange_data.h"
13#include "ui/events/event.h"
14#include "ui/events/event_utils.h"
15#include "ui/gfx/canvas.h"
16#include "ui/gfx/native_widget_types.h"
17#include "ui/gfx/point.h"
18#include "ui/gfx/screen.h"
19#include "ui/gfx/vector2d.h"
20#include "ui/native_theme/native_theme.h"
21#include "ui/views/controls/button/menu_button.h"
22#include "ui/views/controls/menu/menu_config.h"
23#include "ui/views/controls/menu/menu_controller_delegate.h"
24#include "ui/views/controls/menu/menu_host_root_view.h"
25#include "ui/views/controls/menu/menu_item_view.h"
26#include "ui/views/controls/menu/menu_message_loop.h"
27#include "ui/views/controls/menu/menu_scroll_view_container.h"
28#include "ui/views/controls/menu/submenu_view.h"
29#include "ui/views/drag_utils.h"
30#include "ui/views/focus/view_storage.h"
31#include "ui/views/mouse_constants.h"
32#include "ui/views/view.h"
33#include "ui/views/view_constants.h"
34#include "ui/views/views_delegate.h"
35#include "ui/views/widget/root_view.h"
36#include "ui/views/widget/tooltip_manager.h"
37#include "ui/views/widget/widget.h"
38
39#if defined(OS_WIN)
40#include "ui/base/win/internal_constants.h"
41#include "ui/gfx/win/dpi.h"
42#include "ui/views/win/hwnd_util.h"
43#endif
44
45using base::Time;
46using base::TimeDelta;
47using ui::OSExchangeData;
48
49// Period of the scroll timer (in milliseconds).
50static const int kScrollTimerMS = 30;
51
52// Amount of time from when the drop exits the menu and the menu is hidden.
53static const int kCloseOnExitTime = 1200;
54
55// If a context menu is invoked by touch, we shift the menu by this offset so
56// that the finger does not obscure the menu.
57static const int kCenteredContextMenuYOffset = -15;
58
59namespace views {
60
61namespace {
62
63// When showing context menu on mouse down, the user might accidentally select
64// the menu item on the subsequent mouse up. To prevent this, we add the
65// following delay before the user is able to select an item.
66static int menu_selection_hold_time_ms = kMinimumMsPressedToActivate;
67
68// The spacing offset for the bubble tip.
69const int kBubbleTipSizeLeftRight = 12;
70const int kBubbleTipSizeTopBottom = 11;
71
72// The maximum distance (in DIPS) that the mouse can be moved before it should
73// trigger a mouse menu item activation (regardless of how long the menu has
74// been showing).
75const float kMaximumLengthMovedToActivate = 4.0f;
76
77// Returns true if the mnemonic of |menu| matches key.
78bool MatchesMnemonic(MenuItemView* menu, base::char16 key) {
79  return key != 0 && menu->GetMnemonic() == key;
80}
81
82// Returns true if |menu| doesn't have a mnemonic and first character of the its
83// title is |key|.
84bool TitleMatchesMnemonic(MenuItemView* menu, base::char16 key) {
85  if (menu->GetMnemonic())
86    return false;
87
88  base::string16 lower_title = base::i18n::ToLower(menu->title());
89  return !lower_title.empty() && lower_title[0] == key;
90}
91
92}  // namespace
93
94// Returns the first descendant of |view| that is hot tracked.
95static CustomButton* GetFirstHotTrackedView(View* view) {
96  if (!view)
97    return NULL;
98  CustomButton* button = CustomButton::AsCustomButton(view);
99  if (button) {
100    if (button->IsHotTracked())
101      return button;
102  }
103
104  for (int i = 0; i < view->child_count(); ++i) {
105    CustomButton* hot_view = GetFirstHotTrackedView(view->child_at(i));
106    if (hot_view)
107      return hot_view;
108  }
109  return NULL;
110}
111
112// Recurses through the child views of |view| returning the first view starting
113// at |start| that is focusable. A value of -1 for |start| indicates to start at
114// the first view (if |forward| is false, iterating starts at the last view). If
115// |forward| is true the children are considered first to last, otherwise last
116// to first.
117static View* GetFirstFocusableView(View* view, int start, bool forward) {
118  if (forward) {
119    for (int i = start == -1 ? 0 : start; i < view->child_count(); ++i) {
120      View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
121      if (deepest)
122        return deepest;
123    }
124  } else {
125    for (int i = start == -1 ? view->child_count() - 1 : start; i >= 0; --i) {
126      View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
127      if (deepest)
128        return deepest;
129    }
130  }
131  return view->IsFocusable() ? view : NULL;
132}
133
134// Returns the first child of |start| that is focusable.
135static View* GetInitialFocusableView(View* start, bool forward) {
136  return GetFirstFocusableView(start, -1, forward);
137}
138
139// Returns the next view after |start_at| that is focusable. Returns NULL if
140// there are no focusable children of |ancestor| after |start_at|.
141static View* GetNextFocusableView(View* ancestor,
142                                  View* start_at,
143                                  bool forward) {
144  DCHECK(ancestor->Contains(start_at));
145  View* parent = start_at;
146  do {
147    View* new_parent = parent->parent();
148    int index = new_parent->GetIndexOf(parent);
149    index += forward ? 1 : -1;
150    if (forward || index != -1) {
151      View* next = GetFirstFocusableView(new_parent, index, forward);
152      if (next)
153        return next;
154    }
155    parent = new_parent;
156  } while (parent != ancestor);
157  return NULL;
158}
159
160// MenuScrollTask --------------------------------------------------------------
161
162// MenuScrollTask is used when the SubmenuView does not all fit on screen and
163// the mouse is over the scroll up/down buttons. MenuScrollTask schedules
164// itself with a RepeatingTimer. When Run is invoked MenuScrollTask scrolls
165// appropriately.
166
167class MenuController::MenuScrollTask {
168 public:
169  MenuScrollTask() : submenu_(NULL), is_scrolling_up_(false), start_y_(0) {
170    pixels_per_second_ = MenuItemView::pref_menu_height() * 20;
171  }
172
173  void Update(const MenuController::MenuPart& part) {
174    if (!part.is_scroll()) {
175      StopScrolling();
176      return;
177    }
178    DCHECK(part.submenu);
179    SubmenuView* new_menu = part.submenu;
180    bool new_is_up = (part.type == MenuController::MenuPart::SCROLL_UP);
181    if (new_menu == submenu_ && is_scrolling_up_ == new_is_up)
182      return;
183
184    start_scroll_time_ = base::Time::Now();
185    start_y_ = part.submenu->GetVisibleBounds().y();
186    submenu_ = new_menu;
187    is_scrolling_up_ = new_is_up;
188
189    if (!scrolling_timer_.IsRunning()) {
190      scrolling_timer_.Start(FROM_HERE,
191                             TimeDelta::FromMilliseconds(kScrollTimerMS),
192                             this, &MenuScrollTask::Run);
193    }
194  }
195
196  void StopScrolling() {
197    if (scrolling_timer_.IsRunning()) {
198      scrolling_timer_.Stop();
199      submenu_ = NULL;
200    }
201  }
202
203  // The menu being scrolled. Returns null if not scrolling.
204  SubmenuView* submenu() const { return submenu_; }
205
206 private:
207  void Run() {
208    DCHECK(submenu_);
209    gfx::Rect vis_rect = submenu_->GetVisibleBounds();
210    const int delta_y = static_cast<int>(
211        (base::Time::Now() - start_scroll_time_).InMilliseconds() *
212        pixels_per_second_ / 1000);
213    vis_rect.set_y(is_scrolling_up_ ?
214        std::max(0, start_y_ - delta_y) :
215        std::min(submenu_->height() - vis_rect.height(), start_y_ + delta_y));
216    submenu_->ScrollRectToVisible(vis_rect);
217  }
218
219  // SubmenuView being scrolled.
220  SubmenuView* submenu_;
221
222  // Direction scrolling.
223  bool is_scrolling_up_;
224
225  // Timer to periodically scroll.
226  base::RepeatingTimer<MenuScrollTask> scrolling_timer_;
227
228  // Time we started scrolling at.
229  base::Time start_scroll_time_;
230
231  // How many pixels to scroll per second.
232  int pixels_per_second_;
233
234  // Y-coordinate of submenu_view_ when scrolling started.
235  int start_y_;
236
237  DISALLOW_COPY_AND_ASSIGN(MenuScrollTask);
238};
239
240// MenuController:SelectByCharDetails ----------------------------------------
241
242struct MenuController::SelectByCharDetails {
243  SelectByCharDetails()
244      : first_match(-1),
245        has_multiple(false),
246        index_of_item(-1),
247        next_match(-1) {
248  }
249
250  // Index of the first menu with the specified mnemonic.
251  int first_match;
252
253  // If true there are multiple menu items with the same mnemonic.
254  bool has_multiple;
255
256  // Index of the selected item; may remain -1.
257  int index_of_item;
258
259  // If there are multiple matches this is the index of the item after the
260  // currently selected item whose mnemonic matches. This may remain -1 even
261  // though there are matches.
262  int next_match;
263};
264
265// MenuController:State ------------------------------------------------------
266
267MenuController::State::State()
268    : item(NULL),
269      submenu_open(false),
270      anchor(MENU_ANCHOR_TOPLEFT),
271      context_menu(false) {
272}
273
274MenuController::State::~State() {}
275
276// MenuController ------------------------------------------------------------
277
278// static
279MenuController* MenuController::active_instance_ = NULL;
280
281// static
282MenuController* MenuController::GetActiveInstance() {
283  return active_instance_;
284}
285
286MenuItemView* MenuController::Run(Widget* parent,
287                                  MenuButton* button,
288                                  MenuItemView* root,
289                                  const gfx::Rect& bounds,
290                                  MenuAnchorPosition position,
291                                  bool context_menu,
292                                  bool is_nested_drag,
293                                  int* result_event_flags) {
294  exit_type_ = EXIT_NONE;
295  possible_drag_ = false;
296  drag_in_progress_ = false;
297  did_initiate_drag_ = false;
298  closing_event_time_ = base::TimeDelta();
299  menu_start_time_ = base::TimeTicks::Now();
300  menu_start_mouse_press_loc_ = gfx::Point();
301
302  // If we are shown on mouse press, we will eat the subsequent mouse down and
303  // the parent widget will not be able to reset its state (it might have mouse
304  // capture from the mouse down). So we clear its state here.
305  if (parent) {
306    View* root_view = parent->GetRootView();
307    if (root_view) {
308      root_view->SetMouseHandler(NULL);
309      const ui::Event* event =
310          static_cast<internal::RootView*>(root_view)->current_event();
311      if (event && event->type() == ui::ET_MOUSE_PRESSED) {
312        gfx::Point screen_loc(
313            static_cast<const ui::MouseEvent*>(event)->location());
314        View::ConvertPointToScreen(
315            static_cast<View*>(event->target()), &screen_loc);
316        menu_start_mouse_press_loc_ = screen_loc;
317      }
318    }
319  }
320
321  bool nested_menu = showing_;
322  if (showing_) {
323    // Only support nesting of blocking_run menus, nesting of
324    // blocking/non-blocking shouldn't be needed.
325    DCHECK(blocking_run_);
326
327    // We're already showing, push the current state.
328    menu_stack_.push_back(
329        std::make_pair(state_, make_linked_ptr(pressed_lock_.release())));
330
331    // The context menu should be owned by the same parent.
332    DCHECK_EQ(owner_, parent);
333  } else {
334    showing_ = true;
335  }
336
337  // Reset current state.
338  pending_state_ = State();
339  state_ = State();
340  UpdateInitialLocation(bounds, position, context_menu);
341
342  if (owner_)
343    owner_->RemoveObserver(this);
344  owner_ = parent;
345  if (owner_)
346    owner_->AddObserver(this);
347
348  // Set the selection, which opens the initial menu.
349  SetSelection(root, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
350
351  if (!blocking_run_) {
352    if (!is_nested_drag) {
353      // Start the timer to hide the menu. This is needed as we get no
354      // notification when the drag has finished.
355      StartCancelAllTimer();
356    }
357    return NULL;
358  }
359
360  if (button)
361    pressed_lock_.reset(new MenuButton::PressedLock(button));
362
363  // Make sure Chrome doesn't attempt to shut down while the menu is showing.
364  if (ViewsDelegate::views_delegate)
365    ViewsDelegate::views_delegate->AddRef();
366
367  // We need to turn on nestable tasks as in some situations (pressing alt-f for
368  // one) the menus are run from a task. If we don't do this and are invoked
369  // from a task none of the tasks we schedule are processed and the menu
370  // appears totally broken.
371  message_loop_depth_++;
372  DCHECK_LE(message_loop_depth_, 2);
373  RunMessageLoop(nested_menu);
374  message_loop_depth_--;
375
376  if (ViewsDelegate::views_delegate)
377    ViewsDelegate::views_delegate->ReleaseRef();
378
379  // Close any open menus.
380  SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
381
382#if defined(OS_WIN)
383  // On Windows, if we select the menu item by touch and if the window at the
384  // location is another window on the same thread, that window gets a
385  // WM_MOUSEACTIVATE message and ends up activating itself, which is not
386  // correct. We workaround this by setting a property on the window at the
387  // current cursor location. We check for this property in our
388  // WM_MOUSEACTIVATE handler and don't activate the window if the property is
389  // set.
390  if (item_selected_by_touch_) {
391    item_selected_by_touch_ = false;
392    POINT cursor_pos;
393    ::GetCursorPos(&cursor_pos);
394     HWND window = ::WindowFromPoint(cursor_pos);
395     if (::GetWindowThreadProcessId(window, NULL) ==
396                                    ::GetCurrentThreadId()) {
397       ::SetProp(window, ui::kIgnoreTouchMouseActivateForWindow,
398                 reinterpret_cast<HANDLE>(true));
399     }
400  }
401#endif
402
403  linked_ptr<MenuButton::PressedLock> nested_pressed_lock;
404  if (nested_menu) {
405    DCHECK(!menu_stack_.empty());
406    // We're running from within a menu, restore the previous state.
407    // The menus are already showing, so we don't have to show them.
408    state_ = menu_stack_.back().first;
409    pending_state_ = menu_stack_.back().first;
410    nested_pressed_lock = menu_stack_.back().second;
411    menu_stack_.pop_back();
412  } else {
413    showing_ = false;
414    did_capture_ = false;
415  }
416
417  MenuItemView* result = result_;
418  // In case we're nested, reset result_.
419  result_ = NULL;
420
421  if (result_event_flags)
422    *result_event_flags = accept_event_flags_;
423
424  if (exit_type_ == EXIT_OUTERMOST) {
425    SetExitType(EXIT_NONE);
426  } else {
427    if (nested_menu && result) {
428      // We're nested and about to return a value. The caller might enter
429      // another blocking loop. We need to make sure all menus are hidden
430      // before that happens otherwise the menus will stay on screen.
431      CloseAllNestedMenus();
432      SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
433
434      // Set exit_all_, which makes sure all nested loops exit immediately.
435      if (exit_type_ != EXIT_DESTROYED)
436        SetExitType(EXIT_ALL);
437    }
438  }
439
440  // Reset our pressed lock to the previous state's, if there was one.
441  // The lock handles the case if the button was destroyed.
442  pressed_lock_.reset(nested_pressed_lock.release());
443
444  return result;
445}
446
447void MenuController::Cancel(ExitType type) {
448  // If the menu has already been destroyed, no further cancellation is
449  // needed.  We especially don't want to set the |exit_type_| to a lesser
450  // value.
451  if (exit_type_ == EXIT_DESTROYED || exit_type_ == type)
452    return;
453
454  if (!showing_) {
455    // This occurs if we're in the process of notifying the delegate for a drop
456    // and the delegate cancels us.
457    return;
458  }
459
460  MenuItemView* selected = state_.item;
461  SetExitType(type);
462
463  SendMouseCaptureLostToActiveView();
464
465  // Hide windows immediately.
466  SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
467
468  if (!blocking_run_) {
469    // If we didn't block the caller we need to notify the menu, which
470    // triggers deleting us.
471    DCHECK(selected);
472    showing_ = false;
473    delegate_->DropMenuClosed(
474        internal::MenuControllerDelegate::NOTIFY_DELEGATE,
475        selected->GetRootMenuItem());
476    // WARNING: the call to MenuClosed deletes us.
477    return;
478  }
479}
480
481void MenuController::OnMousePressed(SubmenuView* source,
482                                    const ui::MouseEvent& event) {
483  SetSelectionOnPointerDown(source, event);
484}
485
486void MenuController::OnMouseDragged(SubmenuView* source,
487                                    const ui::MouseEvent& event) {
488  MenuPart part = GetMenuPart(source, event.location());
489  UpdateScrolling(part);
490
491  if (!blocking_run_)
492    return;
493
494  if (possible_drag_) {
495    if (View::ExceededDragThreshold(event.location() - press_pt_))
496      StartDrag(source, press_pt_);
497    return;
498  }
499  MenuItemView* mouse_menu = NULL;
500  if (part.type == MenuPart::MENU_ITEM) {
501    if (!part.menu)
502      part.menu = source->GetMenuItem();
503    else
504      mouse_menu = part.menu;
505    SetSelection(part.menu ? part.menu : state_.item, SELECTION_OPEN_SUBMENU);
506  } else if (part.type == MenuPart::NONE) {
507    ShowSiblingMenu(source, event.location());
508  }
509  UpdateActiveMouseView(source, event, mouse_menu);
510}
511
512void MenuController::OnMouseReleased(SubmenuView* source,
513                                     const ui::MouseEvent& event) {
514  if (!blocking_run_)
515    return;
516
517  DCHECK(state_.item);
518  possible_drag_ = false;
519  DCHECK(blocking_run_);
520  MenuPart part = GetMenuPart(source, event.location());
521  if (event.IsRightMouseButton() && part.type == MenuPart::MENU_ITEM) {
522    MenuItemView* menu = part.menu;
523    // |menu| is NULL means this event is from an empty menu or a separator.
524    // If it is from an empty menu, use parent context menu instead of that.
525    if (menu == NULL &&
526        part.submenu->child_count() == 1 &&
527        part.submenu->child_at(0)->id() == MenuItemView::kEmptyMenuItemViewID) {
528      menu = part.parent;
529    }
530
531    if (menu != NULL && ShowContextMenu(menu, source, event,
532                                        ui::MENU_SOURCE_MOUSE))
533      return;
534  }
535
536  // We can use Ctrl+click or the middle mouse button to recursively open urls
537  // for selected folder menu items. If it's only a left click, show the
538  // contents of the folder.
539  if (!part.is_scroll() && part.menu &&
540      !(part.menu->HasSubmenu() &&
541        (event.flags() & ui::EF_LEFT_MOUSE_BUTTON))) {
542    if (GetActiveMouseView()) {
543      SendMouseReleaseToActiveView(source, event);
544      return;
545    }
546    // If a mouse release was received quickly after showing.
547    base::TimeDelta time_shown = base::TimeTicks::Now() - menu_start_time_;
548    if (time_shown.InMilliseconds() < menu_selection_hold_time_ms) {
549      // And it wasn't far from the mouse press location.
550      gfx::Point screen_loc(event.location());
551      View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
552      gfx::Vector2d moved = screen_loc - menu_start_mouse_press_loc_;
553      if (moved.Length() < kMaximumLengthMovedToActivate) {
554        // Ignore the mouse release as it was likely this menu was shown under
555        // the mouse and the action was just a normal click.
556        return;
557      }
558    }
559    if (part.menu->GetDelegate()->ShouldExecuteCommandWithoutClosingMenu(
560            part.menu->GetCommand(), event)) {
561      part.menu->GetDelegate()->ExecuteCommand(part.menu->GetCommand(),
562                                               event.flags());
563      return;
564    }
565    if (!part.menu->NonIconChildViewsCount() &&
566        part.menu->GetDelegate()->IsTriggerableEvent(part.menu, event)) {
567      base::TimeDelta shown_time = base::TimeTicks::Now() - menu_start_time_;
568      if (!state_.context_menu || !View::ShouldShowContextMenuOnMousePress() ||
569          shown_time.InMilliseconds() > menu_selection_hold_time_ms) {
570        Accept(part.menu, event.flags());
571      }
572      return;
573    }
574  } else if (part.type == MenuPart::MENU_ITEM) {
575    // User either clicked on empty space, or a menu that has children.
576    SetSelection(part.menu ? part.menu : state_.item,
577                 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
578  }
579  SendMouseCaptureLostToActiveView();
580}
581
582void MenuController::OnMouseMoved(SubmenuView* source,
583                                  const ui::MouseEvent& event) {
584  HandleMouseLocation(source, event.location());
585}
586
587void MenuController::OnMouseEntered(SubmenuView* source,
588                                    const ui::MouseEvent& event) {
589  // MouseEntered is always followed by a mouse moved, so don't need to
590  // do anything here.
591}
592
593bool MenuController::OnMouseWheel(SubmenuView* source,
594                                  const ui::MouseWheelEvent& event) {
595  MenuPart part = GetMenuPart(source, event.location());
596  return part.submenu && part.submenu->OnMouseWheel(event);
597}
598
599void MenuController::OnGestureEvent(SubmenuView* source,
600                                    ui::GestureEvent* event) {
601  MenuPart part = GetMenuPart(source, event->location());
602  if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
603    SetSelectionOnPointerDown(source, *event);
604    event->StopPropagation();
605  } else if (event->type() == ui::ET_GESTURE_LONG_PRESS) {
606    if (part.type == MenuPart::MENU_ITEM && part.menu) {
607      if (ShowContextMenu(part.menu, source, *event, ui::MENU_SOURCE_TOUCH))
608        event->StopPropagation();
609    }
610  } else if (event->type() == ui::ET_GESTURE_TAP) {
611    if (!part.is_scroll() && part.menu &&
612        !(part.menu->HasSubmenu())) {
613      if (part.menu->GetDelegate()->IsTriggerableEvent(
614          part.menu, *event)) {
615        Accept(part.menu, event->flags());
616        item_selected_by_touch_ = true;
617      }
618      event->StopPropagation();
619    } else if (part.type == MenuPart::MENU_ITEM) {
620      // User either tapped on empty space, or a menu that has children.
621      SetSelection(part.menu ? part.menu : state_.item,
622                   SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
623      event->StopPropagation();
624    }
625  } else if (event->type() == ui::ET_GESTURE_TAP_CANCEL &&
626             part.menu &&
627             part.type == MenuPart::MENU_ITEM) {
628    // Move the selection to the parent menu so that the selection in the
629    // current menu is unset. Make sure the submenu remains open by sending the
630    // appropriate SetSelectionTypes flags.
631    SetSelection(part.menu->GetParentMenuItem(),
632        SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
633    event->StopPropagation();
634  }
635
636  if (event->stopped_propagation())
637      return;
638
639  if (!part.submenu)
640    return;
641  part.submenu->OnGestureEvent(event);
642}
643
644bool MenuController::GetDropFormats(
645      SubmenuView* source,
646      int* formats,
647      std::set<OSExchangeData::CustomFormat>* custom_formats) {
648  return source->GetMenuItem()->GetDelegate()->GetDropFormats(
649      source->GetMenuItem(), formats, custom_formats);
650}
651
652bool MenuController::AreDropTypesRequired(SubmenuView* source) {
653  return source->GetMenuItem()->GetDelegate()->AreDropTypesRequired(
654      source->GetMenuItem());
655}
656
657bool MenuController::CanDrop(SubmenuView* source, const OSExchangeData& data) {
658  return source->GetMenuItem()->GetDelegate()->CanDrop(source->GetMenuItem(),
659                                                       data);
660}
661
662void MenuController::OnDragEntered(SubmenuView* source,
663                                   const ui::DropTargetEvent& event) {
664  valid_drop_coordinates_ = false;
665}
666
667int MenuController::OnDragUpdated(SubmenuView* source,
668                                  const ui::DropTargetEvent& event) {
669  StopCancelAllTimer();
670
671  gfx::Point screen_loc(event.location());
672  View::ConvertPointToScreen(source, &screen_loc);
673  if (valid_drop_coordinates_ && screen_loc == drop_pt_)
674    return last_drop_operation_;
675  drop_pt_ = screen_loc;
676  valid_drop_coordinates_ = true;
677
678  MenuItemView* menu_item = GetMenuItemAt(source, event.x(), event.y());
679  bool over_empty_menu = false;
680  if (!menu_item) {
681    // See if we're over an empty menu.
682    menu_item = GetEmptyMenuItemAt(source, event.x(), event.y());
683    if (menu_item)
684      over_empty_menu = true;
685  }
686  MenuDelegate::DropPosition drop_position = MenuDelegate::DROP_NONE;
687  int drop_operation = ui::DragDropTypes::DRAG_NONE;
688  if (menu_item) {
689    gfx::Point menu_item_loc(event.location());
690    View::ConvertPointToTarget(source, menu_item, &menu_item_loc);
691    MenuItemView* query_menu_item;
692    if (!over_empty_menu) {
693      int menu_item_height = menu_item->height();
694      if (menu_item->HasSubmenu() &&
695          (menu_item_loc.y() > kDropBetweenPixels &&
696           menu_item_loc.y() < (menu_item_height - kDropBetweenPixels))) {
697        drop_position = MenuDelegate::DROP_ON;
698      } else {
699        drop_position = (menu_item_loc.y() < menu_item_height / 2) ?
700            MenuDelegate::DROP_BEFORE : MenuDelegate::DROP_AFTER;
701      }
702      query_menu_item = menu_item;
703    } else {
704      query_menu_item = menu_item->GetParentMenuItem();
705      drop_position = MenuDelegate::DROP_ON;
706    }
707    drop_operation = menu_item->GetDelegate()->GetDropOperation(
708        query_menu_item, event, &drop_position);
709
710    // If the menu has a submenu, schedule the submenu to open.
711    SetSelection(menu_item, menu_item->HasSubmenu() ? SELECTION_OPEN_SUBMENU :
712                 SELECTION_DEFAULT);
713
714    if (drop_position == MenuDelegate::DROP_NONE ||
715        drop_operation == ui::DragDropTypes::DRAG_NONE)
716      menu_item = NULL;
717  } else {
718    SetSelection(source->GetMenuItem(), SELECTION_OPEN_SUBMENU);
719  }
720  SetDropMenuItem(menu_item, drop_position);
721  last_drop_operation_ = drop_operation;
722  return drop_operation;
723}
724
725void MenuController::OnDragExited(SubmenuView* source) {
726  StartCancelAllTimer();
727
728  if (drop_target_) {
729    StopShowTimer();
730    SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
731  }
732}
733
734int MenuController::OnPerformDrop(SubmenuView* source,
735                                  const ui::DropTargetEvent& event) {
736  DCHECK(drop_target_);
737  // NOTE: the delegate may delete us after invoking OnPerformDrop, as such
738  // we don't call cancel here.
739
740  MenuItemView* item = state_.item;
741  DCHECK(item);
742
743  MenuItemView* drop_target = drop_target_;
744  MenuDelegate::DropPosition drop_position = drop_position_;
745
746  // Close all menus, including any nested menus.
747  SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
748  CloseAllNestedMenus();
749
750  // Set state such that we exit.
751  showing_ = false;
752  SetExitType(EXIT_ALL);
753
754  // If over an empty menu item, drop occurs on the parent.
755  if (drop_target->id() == MenuItemView::kEmptyMenuItemViewID)
756    drop_target = drop_target->GetParentMenuItem();
757
758  if (!IsBlockingRun()) {
759    delegate_->DropMenuClosed(
760        internal::MenuControllerDelegate::DONT_NOTIFY_DELEGATE,
761        item->GetRootMenuItem());
762  }
763
764  // WARNING: the call to MenuClosed deletes us.
765
766  return drop_target->GetDelegate()->OnPerformDrop(
767      drop_target, drop_position, event);
768}
769
770void MenuController::OnDragEnteredScrollButton(SubmenuView* source,
771                                               bool is_up) {
772  MenuPart part;
773  part.type = is_up ? MenuPart::SCROLL_UP : MenuPart::SCROLL_DOWN;
774  part.submenu = source;
775  UpdateScrolling(part);
776
777  // Do this to force the selection to hide.
778  SetDropMenuItem(source->GetMenuItemAt(0), MenuDelegate::DROP_NONE);
779
780  StopCancelAllTimer();
781}
782
783void MenuController::OnDragExitedScrollButton(SubmenuView* source) {
784  StartCancelAllTimer();
785  SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
786  StopScrolling();
787}
788
789void MenuController::OnDragWillStart() {
790  DCHECK(!drag_in_progress_);
791  drag_in_progress_ = true;
792}
793
794void MenuController::OnDragComplete(bool should_close) {
795  DCHECK(drag_in_progress_);
796  drag_in_progress_ = false;
797  if (showing_ && should_close && GetActiveInstance() == this) {
798    CloseAllNestedMenus();
799    Cancel(EXIT_ALL);
800  }
801}
802
803void MenuController::UpdateSubmenuSelection(SubmenuView* submenu) {
804  if (submenu->IsShowing()) {
805    gfx::Point point = GetScreen()->GetCursorScreenPoint();
806    const SubmenuView* root_submenu =
807        submenu->GetMenuItem()->GetRootMenuItem()->GetSubmenu();
808    View::ConvertPointFromScreen(
809        root_submenu->GetWidget()->GetRootView(), &point);
810    HandleMouseLocation(submenu, point);
811  }
812}
813
814void MenuController::OnWidgetDestroying(Widget* widget) {
815  DCHECK_EQ(owner_, widget);
816  owner_->RemoveObserver(this);
817  owner_ = NULL;
818  message_loop_->ClearOwner();
819}
820
821bool MenuController::IsCancelAllTimerRunningForTest() {
822  return cancel_all_timer_.IsRunning();
823}
824
825// static
826void MenuController::TurnOffMenuSelectionHoldForTest() {
827  menu_selection_hold_time_ms = -1;
828}
829
830void MenuController::SetSelection(MenuItemView* menu_item,
831                                  int selection_types) {
832  size_t paths_differ_at = 0;
833  std::vector<MenuItemView*> current_path;
834  std::vector<MenuItemView*> new_path;
835  BuildPathsAndCalculateDiff(pending_state_.item, menu_item, &current_path,
836                             &new_path, &paths_differ_at);
837
838  size_t current_size = current_path.size();
839  size_t new_size = new_path.size();
840
841  bool pending_item_changed = pending_state_.item != menu_item;
842  if (pending_item_changed && pending_state_.item) {
843    CustomButton* button = GetFirstHotTrackedView(pending_state_.item);
844    if (button)
845      button->SetHotTracked(false);
846  }
847
848  // Notify the old path it isn't selected.
849  MenuDelegate* current_delegate =
850      current_path.empty() ? NULL : current_path.front()->GetDelegate();
851  for (size_t i = paths_differ_at; i < current_size; ++i) {
852    if (current_delegate &&
853        current_path[i]->GetType() == MenuItemView::SUBMENU) {
854      current_delegate->WillHideMenu(current_path[i]);
855    }
856    current_path[i]->SetSelected(false);
857  }
858
859  // Notify the new path it is selected.
860  for (size_t i = paths_differ_at; i < new_size; ++i) {
861    new_path[i]->ScrollRectToVisible(new_path[i]->GetLocalBounds());
862    new_path[i]->SetSelected(true);
863  }
864
865  if (menu_item && menu_item->GetDelegate())
866    menu_item->GetDelegate()->SelectionChanged(menu_item);
867
868  DCHECK(menu_item || (selection_types & SELECTION_EXIT) != 0);
869
870  pending_state_.item = menu_item;
871  pending_state_.submenu_open = (selection_types & SELECTION_OPEN_SUBMENU) != 0;
872
873  // Stop timers.
874  StopCancelAllTimer();
875  // Resets show timer only when pending menu item is changed.
876  if (pending_item_changed)
877    StopShowTimer();
878
879  if (selection_types & SELECTION_UPDATE_IMMEDIATELY)
880    CommitPendingSelection();
881  else if (pending_item_changed)
882    StartShowTimer();
883
884  // Notify an accessibility focus event on all menu items except for the root.
885  if (menu_item &&
886      (MenuDepth(menu_item) != 1 ||
887       menu_item->GetType() != MenuItemView::SUBMENU)) {
888    menu_item->NotifyAccessibilityEvent(
889        ui::AX_EVENT_FOCUS, true);
890  }
891}
892
893void MenuController::SetSelectionOnPointerDown(SubmenuView* source,
894                                               const ui::LocatedEvent& event) {
895  if (!blocking_run_)
896    return;
897
898  DCHECK(!GetActiveMouseView());
899
900  MenuPart part = GetMenuPart(source, event.location());
901  if (part.is_scroll())
902    return;  // Ignore presses on scroll buttons.
903
904  // When this menu is opened through a touch event, a simulated right-click
905  // is sent before the menu appears.  Ignore it.
906  if ((event.flags() & ui::EF_RIGHT_MOUSE_BUTTON) &&
907      (event.flags() & ui::EF_FROM_TOUCH))
908    return;
909
910  if (part.type == MenuPart::NONE ||
911      (part.type == MenuPart::MENU_ITEM && part.menu &&
912       part.menu->GetRootMenuItem() != state_.item->GetRootMenuItem())) {
913    // Remember the time when we repost the event. The owner can then use this
914    // to figure out if this menu was finished with the same click which is
915    // sent to it thereafter. Note that the time stamp front he event cannot be
916    // used since the reposting will set a new timestamp when the event gets
917    // processed. As such it is better to take the current time which will be
918    // closer to the time when it arrives again in the menu handler.
919    closing_event_time_ = ui::EventTimeForNow();
920
921    // Mouse wasn't pressed over any menu, or the active menu, cancel.
922
923#if defined(OS_WIN)
924    // We're going to close and we own the mouse capture. We need to repost the
925    // mouse down, otherwise the window the user clicked on won't get the event.
926    RepostEvent(source, event);
927#endif
928
929    // And close.
930    ExitType exit_type = EXIT_ALL;
931    if (!menu_stack_.empty()) {
932      // We're running nested menus. Only exit all if the mouse wasn't over one
933      // of the menus from the last run.
934      gfx::Point screen_loc(event.location());
935      View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
936      MenuPart last_part = GetMenuPartByScreenCoordinateUsingMenu(
937          menu_stack_.back().first.item, screen_loc);
938      if (last_part.type != MenuPart::NONE)
939        exit_type = EXIT_OUTERMOST;
940    }
941    Cancel(exit_type);
942
943#if defined(OS_CHROMEOS)
944    // We're going to exit the menu and want to repost the event so that is
945    // is handled normally after the context menu has exited. We call
946    // RepostEvent after Cancel so that mouse capture has been released so
947    // that finding the event target is unaffected by the current capture.
948    RepostEvent(source, event);
949#endif
950    // Do not repost events for Linux Aura because this behavior is more
951    // consistent with the behavior of other Linux apps.
952    return;
953  }
954
955  // On a press we immediately commit the selection, that way a submenu
956  // pops up immediately rather than after a delay.
957  int selection_types = SELECTION_UPDATE_IMMEDIATELY;
958  if (!part.menu) {
959    part.menu = part.parent;
960    selection_types |= SELECTION_OPEN_SUBMENU;
961  } else {
962    if (part.menu->GetDelegate()->CanDrag(part.menu)) {
963      possible_drag_ = true;
964      press_pt_ = event.location();
965    }
966    if (part.menu->HasSubmenu())
967      selection_types |= SELECTION_OPEN_SUBMENU;
968  }
969  SetSelection(part.menu, selection_types);
970}
971
972void MenuController::StartDrag(SubmenuView* source,
973                               const gfx::Point& location) {
974  MenuItemView* item = state_.item;
975  DCHECK(item);
976  // Points are in the coordinates of the submenu, need to map to that of
977  // the selected item. Additionally source may not be the parent of
978  // the selected item, so need to map to screen first then to item.
979  gfx::Point press_loc(location);
980  View::ConvertPointToScreen(source->GetScrollViewContainer(), &press_loc);
981  View::ConvertPointFromScreen(item, &press_loc);
982  gfx::Point widget_loc(press_loc);
983  View::ConvertPointToWidget(item, &widget_loc);
984  scoped_ptr<gfx::Canvas> canvas(GetCanvasForDragImage(
985      source->GetWidget(), gfx::Size(item->width(), item->height())));
986  item->PaintButton(canvas.get(), MenuItemView::PB_FOR_DRAG);
987
988  OSExchangeData data;
989  item->GetDelegate()->WriteDragData(item, &data);
990  drag_utils::SetDragImageOnDataObject(*canvas,
991                                       press_loc.OffsetFromOrigin(),
992                                       &data);
993  StopScrolling();
994  int drag_ops = item->GetDelegate()->GetDragOperations(item);
995  did_initiate_drag_ = true;
996  // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below.
997  item->GetWidget()->RunShellDrag(NULL, data, widget_loc, drag_ops,
998      ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
999  did_initiate_drag_ = false;
1000}
1001
1002bool MenuController::OnKeyDown(ui::KeyboardCode key_code) {
1003  DCHECK(blocking_run_);
1004
1005  switch (key_code) {
1006    case ui::VKEY_UP:
1007      IncrementSelection(-1);
1008      break;
1009
1010    case ui::VKEY_DOWN:
1011      IncrementSelection(1);
1012      break;
1013
1014    // Handling of VK_RIGHT and VK_LEFT is different depending on the UI
1015    // layout.
1016    case ui::VKEY_RIGHT:
1017      if (base::i18n::IsRTL())
1018        CloseSubmenu();
1019      else
1020        OpenSubmenuChangeSelectionIfCan();
1021      break;
1022
1023    case ui::VKEY_LEFT:
1024      if (base::i18n::IsRTL())
1025        OpenSubmenuChangeSelectionIfCan();
1026      else
1027        CloseSubmenu();
1028      break;
1029
1030    case ui::VKEY_SPACE:
1031      if (SendAcceleratorToHotTrackedView() == ACCELERATOR_PROCESSED_EXIT)
1032        return false;
1033      break;
1034
1035    case ui::VKEY_F4:
1036      if (!is_combobox_)
1037        break;
1038    // Fallthrough to accept or dismiss combobox menus on F4, like windows.
1039    case ui::VKEY_RETURN:
1040      if (pending_state_.item) {
1041        if (pending_state_.item->HasSubmenu()) {
1042          if (key_code == ui::VKEY_F4 &&
1043              pending_state_.item->GetSubmenu()->IsShowing())
1044            return false;
1045          else
1046            OpenSubmenuChangeSelectionIfCan();
1047        } else {
1048          SendAcceleratorResultType result = SendAcceleratorToHotTrackedView();
1049          if (result == ACCELERATOR_NOT_PROCESSED &&
1050              pending_state_.item->enabled()) {
1051            Accept(pending_state_.item, 0);
1052            return false;
1053          } else if (result == ACCELERATOR_PROCESSED_EXIT) {
1054            return false;
1055          }
1056        }
1057      }
1058      break;
1059
1060    case ui::VKEY_ESCAPE:
1061      if (!state_.item->GetParentMenuItem() ||
1062          (!state_.item->GetParentMenuItem()->GetParentMenuItem() &&
1063           (!state_.item->HasSubmenu() ||
1064            !state_.item->GetSubmenu()->IsShowing()))) {
1065        // User pressed escape and only one menu is shown, cancel it.
1066        Cancel(EXIT_OUTERMOST);
1067        return false;
1068      }
1069      CloseSubmenu();
1070      break;
1071
1072    default:
1073      break;
1074  }
1075  return true;
1076}
1077
1078MenuController::MenuController(ui::NativeTheme* theme,
1079                               bool blocking,
1080                               internal::MenuControllerDelegate* delegate)
1081    : blocking_run_(blocking),
1082      showing_(false),
1083      exit_type_(EXIT_NONE),
1084      did_capture_(false),
1085      result_(NULL),
1086      accept_event_flags_(0),
1087      drop_target_(NULL),
1088      drop_position_(MenuDelegate::DROP_UNKNOWN),
1089      owner_(NULL),
1090      possible_drag_(false),
1091      drag_in_progress_(false),
1092      did_initiate_drag_(false),
1093      valid_drop_coordinates_(false),
1094      last_drop_operation_(MenuDelegate::DROP_UNKNOWN),
1095      showing_submenu_(false),
1096      active_mouse_view_id_(ViewStorage::GetInstance()->CreateStorageID()),
1097      delegate_(delegate),
1098      message_loop_depth_(0),
1099      menu_config_(theme),
1100      closing_event_time_(base::TimeDelta()),
1101      menu_start_time_(base::TimeTicks()),
1102      is_combobox_(false),
1103      item_selected_by_touch_(false),
1104      message_loop_(MenuMessageLoop::Create()) {
1105  active_instance_ = this;
1106}
1107
1108MenuController::~MenuController() {
1109  DCHECK(!showing_);
1110  if (owner_)
1111    owner_->RemoveObserver(this);
1112  if (active_instance_ == this)
1113    active_instance_ = NULL;
1114  StopShowTimer();
1115  StopCancelAllTimer();
1116}
1117
1118void MenuController::RunMessageLoop(bool nested_menu) {
1119  message_loop_->Run(this, owner_, nested_menu);
1120}
1121
1122MenuController::SendAcceleratorResultType
1123    MenuController::SendAcceleratorToHotTrackedView() {
1124  CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item);
1125  if (!hot_view)
1126    return ACCELERATOR_NOT_PROCESSED;
1127
1128  ui::Accelerator accelerator(ui::VKEY_RETURN, ui::EF_NONE);
1129  hot_view->AcceleratorPressed(accelerator);
1130  CustomButton* button = static_cast<CustomButton*>(hot_view);
1131  button->SetHotTracked(true);
1132  return (exit_type_ == EXIT_NONE) ?
1133      ACCELERATOR_PROCESSED : ACCELERATOR_PROCESSED_EXIT;
1134}
1135
1136void MenuController::UpdateInitialLocation(const gfx::Rect& bounds,
1137                                           MenuAnchorPosition position,
1138                                           bool context_menu) {
1139  pending_state_.context_menu = context_menu;
1140  pending_state_.initial_bounds = bounds;
1141  if (bounds.height() > 1) {
1142    // Inset the bounds slightly, otherwise drag coordinates don't line up
1143    // nicely and menus close prematurely.
1144    pending_state_.initial_bounds.Inset(0, 1);
1145  }
1146
1147  // Reverse anchor position for RTL languages.
1148  if (base::i18n::IsRTL() &&
1149      (position == MENU_ANCHOR_TOPRIGHT || position == MENU_ANCHOR_TOPLEFT)) {
1150    pending_state_.anchor = position == MENU_ANCHOR_TOPRIGHT
1151                                ? MENU_ANCHOR_TOPLEFT
1152                                : MENU_ANCHOR_TOPRIGHT;
1153  } else {
1154    pending_state_.anchor = position;
1155  }
1156
1157  // Calculate the bounds of the monitor we'll show menus on. Do this once to
1158  // avoid repeated system queries for the info.
1159  pending_state_.monitor_bounds = GetScreen()->GetDisplayNearestPoint(
1160      bounds.origin()).work_area();
1161
1162  if (!pending_state_.monitor_bounds.Contains(bounds)) {
1163    // Use the monitor area if the work area doesn't contain the bounds. This
1164    // handles showing a menu from the launcher.
1165    gfx::Rect monitor_area = GetScreen()->GetDisplayNearestPoint(
1166        bounds.origin()).bounds();
1167    if (monitor_area.Contains(bounds))
1168      pending_state_.monitor_bounds = monitor_area;
1169  }
1170}
1171
1172void MenuController::Accept(MenuItemView* item, int event_flags) {
1173  DCHECK(IsBlockingRun());
1174  result_ = item;
1175  if (item && !menu_stack_.empty() &&
1176      !item->GetDelegate()->ShouldCloseAllMenusOnExecute(item->GetCommand())) {
1177    SetExitType(EXIT_OUTERMOST);
1178  } else {
1179    SetExitType(EXIT_ALL);
1180  }
1181  accept_event_flags_ = event_flags;
1182}
1183
1184bool MenuController::ShowSiblingMenu(SubmenuView* source,
1185                                     const gfx::Point& mouse_location) {
1186  if (!menu_stack_.empty() || !pressed_lock_.get())
1187    return false;
1188
1189  View* source_view = source->GetScrollViewContainer();
1190  if (mouse_location.x() >= 0 &&
1191      mouse_location.x() < source_view->width() &&
1192      mouse_location.y() >= 0 &&
1193      mouse_location.y() < source_view->height()) {
1194    // The mouse is over the menu, no need to continue.
1195    return false;
1196  }
1197
1198  gfx::NativeWindow window_under_mouse = GetScreen()->GetWindowUnderCursor();
1199  // TODO(oshima): Replace with views only API.
1200  if (!owner_ || window_under_mouse != owner_->GetNativeWindow())
1201    return false;
1202
1203  // The user moved the mouse outside the menu and over the owning window. See
1204  // if there is a sibling menu we should show.
1205  gfx::Point screen_point(mouse_location);
1206  View::ConvertPointToScreen(source_view, &screen_point);
1207  MenuAnchorPosition anchor;
1208  bool has_mnemonics;
1209  MenuButton* button = NULL;
1210  MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->
1211      GetSiblingMenu(source->GetMenuItem()->GetRootMenuItem(),
1212                     screen_point, &anchor, &has_mnemonics, &button);
1213  if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu))
1214    return false;
1215
1216  delegate_->SiblingMenuCreated(alt_menu);
1217
1218  if (!button) {
1219    // If the delegate returns a menu, they must also return a button.
1220    NOTREACHED();
1221    return false;
1222  }
1223
1224  // There is a sibling menu, update the button state, hide the current menu
1225  // and show the new one.
1226  pressed_lock_.reset(new MenuButton::PressedLock(button));
1227
1228  // Need to reset capture when we show the menu again, otherwise we aren't
1229  // going to get any events.
1230  did_capture_ = false;
1231  gfx::Point screen_menu_loc;
1232  View::ConvertPointToScreen(button, &screen_menu_loc);
1233
1234  // It is currently not possible to show a submenu recursively in a bubble.
1235  DCHECK(!MenuItemView::IsBubble(anchor));
1236  // Subtract 1 from the height to make the popup flush with the button border.
1237  UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(),
1238                                  button->width(), button->height() - 1),
1239                        anchor, state_.context_menu);
1240  alt_menu->PrepareForRun(
1241      false, has_mnemonics,
1242      source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_);
1243  alt_menu->controller_ = this;
1244  SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1245  return true;
1246}
1247
1248bool MenuController::ShowContextMenu(MenuItemView* menu_item,
1249                                     SubmenuView* source,
1250                                     const ui::LocatedEvent& event,
1251                                     ui::MenuSourceType source_type) {
1252  // Set the selection immediately, making sure the submenu is only open
1253  // if it already was.
1254  int selection_types = SELECTION_UPDATE_IMMEDIATELY;
1255  if (state_.item == pending_state_.item && state_.submenu_open)
1256    selection_types |= SELECTION_OPEN_SUBMENU;
1257  SetSelection(pending_state_.item, selection_types);
1258  gfx::Point loc(event.location());
1259  View::ConvertPointToScreen(source->GetScrollViewContainer(), &loc);
1260
1261  if (menu_item->GetDelegate()->ShowContextMenu(
1262          menu_item, menu_item->GetCommand(), loc, source_type)) {
1263    SendMouseCaptureLostToActiveView();
1264    return true;
1265  }
1266  return false;
1267}
1268
1269void MenuController::CloseAllNestedMenus() {
1270  for (std::list<NestedState>::iterator i = menu_stack_.begin();
1271       i != menu_stack_.end(); ++i) {
1272    State& state = i->first;
1273    MenuItemView* last_item = state.item;
1274    for (MenuItemView* item = last_item; item;
1275         item = item->GetParentMenuItem()) {
1276      CloseMenu(item);
1277      last_item = item;
1278    }
1279    state.submenu_open = false;
1280    state.item = last_item;
1281  }
1282}
1283
1284MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) {
1285  // Walk the view hierarchy until we find a menu item (or the root).
1286  View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1287  while (child_under_mouse &&
1288         child_under_mouse->id() != MenuItemView::kMenuItemViewID) {
1289    child_under_mouse = child_under_mouse->parent();
1290  }
1291  if (child_under_mouse && child_under_mouse->enabled() &&
1292      child_under_mouse->id() == MenuItemView::kMenuItemViewID) {
1293    return static_cast<MenuItemView*>(child_under_mouse);
1294  }
1295  return NULL;
1296}
1297
1298MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) {
1299  View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1300  if (child_under_mouse &&
1301      child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) {
1302    return static_cast<MenuItemView*>(child_under_mouse);
1303  }
1304  return NULL;
1305}
1306
1307bool MenuController::IsScrollButtonAt(SubmenuView* source,
1308                                      int x,
1309                                      int y,
1310                                      MenuPart::Type* part) {
1311  MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer();
1312  View* child_under_mouse =
1313      scroll_view->GetEventHandlerForPoint(gfx::Point(x, y));
1314  if (child_under_mouse && child_under_mouse->enabled()) {
1315    if (child_under_mouse == scroll_view->scroll_up_button()) {
1316      *part = MenuPart::SCROLL_UP;
1317      return true;
1318    }
1319    if (child_under_mouse == scroll_view->scroll_down_button()) {
1320      *part = MenuPart::SCROLL_DOWN;
1321      return true;
1322    }
1323  }
1324  return false;
1325}
1326
1327MenuController::MenuPart MenuController::GetMenuPart(
1328    SubmenuView* source,
1329    const gfx::Point& source_loc) {
1330  gfx::Point screen_loc(source_loc);
1331  View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
1332  return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc);
1333}
1334
1335MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu(
1336    MenuItemView* item,
1337    const gfx::Point& screen_loc) {
1338  MenuPart part;
1339  for (; item; item = item->GetParentMenuItem()) {
1340    if (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1341        GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc,
1342                                          &part)) {
1343      return part;
1344    }
1345  }
1346  return part;
1347}
1348
1349bool MenuController::GetMenuPartByScreenCoordinateImpl(
1350    SubmenuView* menu,
1351    const gfx::Point& screen_loc,
1352    MenuPart* part) {
1353  // Is the mouse over the scroll buttons?
1354  gfx::Point scroll_view_loc = screen_loc;
1355  View* scroll_view_container = menu->GetScrollViewContainer();
1356  View::ConvertPointFromScreen(scroll_view_container, &scroll_view_loc);
1357  if (scroll_view_loc.x() < 0 ||
1358      scroll_view_loc.x() >= scroll_view_container->width() ||
1359      scroll_view_loc.y() < 0 ||
1360      scroll_view_loc.y() >= scroll_view_container->height()) {
1361    // Point isn't contained in menu.
1362    return false;
1363  }
1364  if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(),
1365                       &(part->type))) {
1366    part->submenu = menu;
1367    return true;
1368  }
1369
1370  // Not over the scroll button. Check the actual menu.
1371  if (DoesSubmenuContainLocation(menu, screen_loc)) {
1372    gfx::Point menu_loc = screen_loc;
1373    View::ConvertPointFromScreen(menu, &menu_loc);
1374    part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y());
1375    part->type = MenuPart::MENU_ITEM;
1376    part->submenu = menu;
1377    if (!part->menu)
1378      part->parent = menu->GetMenuItem();
1379    return true;
1380  }
1381
1382  // While the mouse isn't over a menu item or the scroll buttons of menu, it
1383  // is contained by menu and so we return true. If we didn't return true other
1384  // menus would be searched, even though they are likely obscured by us.
1385  return true;
1386}
1387
1388bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu,
1389                                                const gfx::Point& screen_loc) {
1390  gfx::Point view_loc = screen_loc;
1391  View::ConvertPointFromScreen(submenu, &view_loc);
1392  gfx::Rect vis_rect = submenu->GetVisibleBounds();
1393  return vis_rect.Contains(view_loc.x(), view_loc.y());
1394}
1395
1396void MenuController::CommitPendingSelection() {
1397  StopShowTimer();
1398
1399  size_t paths_differ_at = 0;
1400  std::vector<MenuItemView*> current_path;
1401  std::vector<MenuItemView*> new_path;
1402  BuildPathsAndCalculateDiff(state_.item, pending_state_.item, &current_path,
1403                             &new_path, &paths_differ_at);
1404
1405  // Hide the old menu.
1406  for (size_t i = paths_differ_at; i < current_path.size(); ++i) {
1407    if (current_path[i]->HasSubmenu()) {
1408      current_path[i]->GetSubmenu()->Hide();
1409    }
1410  }
1411
1412  // Copy pending to state_, making sure to preserve the direction menus were
1413  // opened.
1414  std::list<bool> pending_open_direction;
1415  state_.open_leading.swap(pending_open_direction);
1416  state_ = pending_state_;
1417  state_.open_leading.swap(pending_open_direction);
1418
1419  int menu_depth = MenuDepth(state_.item);
1420  if (menu_depth == 0) {
1421    state_.open_leading.clear();
1422  } else {
1423    int cached_size = static_cast<int>(state_.open_leading.size());
1424    DCHECK_GE(menu_depth, 0);
1425    while (cached_size-- >= menu_depth)
1426      state_.open_leading.pop_back();
1427  }
1428
1429  if (!state_.item) {
1430    // Nothing to select.
1431    StopScrolling();
1432    return;
1433  }
1434
1435  // Open all the submenus preceeding the last menu item (last menu item is
1436  // handled next).
1437  if (new_path.size() > 1) {
1438    for (std::vector<MenuItemView*>::iterator i = new_path.begin();
1439         i != new_path.end() - 1; ++i) {
1440      OpenMenu(*i);
1441    }
1442  }
1443
1444  if (state_.submenu_open) {
1445    // The submenu should be open, open the submenu if the item has a submenu.
1446    if (state_.item->HasSubmenu()) {
1447      OpenMenu(state_.item);
1448    } else {
1449      state_.submenu_open = false;
1450    }
1451  } else if (state_.item->HasSubmenu() &&
1452             state_.item->GetSubmenu()->IsShowing()) {
1453    state_.item->GetSubmenu()->Hide();
1454  }
1455
1456  if (scroll_task_.get() && scroll_task_->submenu()) {
1457    // Stop the scrolling if none of the elements of the selection contain
1458    // the menu being scrolled.
1459    bool found = false;
1460    for (MenuItemView* item = state_.item; item && !found;
1461         item = item->GetParentMenuItem()) {
1462      found = (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1463               item->GetSubmenu() == scroll_task_->submenu());
1464    }
1465    if (!found)
1466      StopScrolling();
1467  }
1468}
1469
1470void MenuController::CloseMenu(MenuItemView* item) {
1471  DCHECK(item);
1472  if (!item->HasSubmenu())
1473    return;
1474  item->GetSubmenu()->Hide();
1475}
1476
1477void MenuController::OpenMenu(MenuItemView* item) {
1478  DCHECK(item);
1479  if (item->GetSubmenu()->IsShowing()) {
1480    return;
1481  }
1482
1483  OpenMenuImpl(item, true);
1484  did_capture_ = true;
1485}
1486
1487void MenuController::OpenMenuImpl(MenuItemView* item, bool show) {
1488  // TODO(oshima|sky): Don't show the menu if drag is in progress and
1489  // this menu doesn't support drag drop. See crbug.com/110495.
1490  if (show) {
1491    int old_count = item->GetSubmenu()->child_count();
1492    item->GetDelegate()->WillShowMenu(item);
1493    if (old_count != item->GetSubmenu()->child_count()) {
1494      // If the number of children changed then we may need to add empty items.
1495      item->AddEmptyMenus();
1496    }
1497  }
1498  bool prefer_leading =
1499      state_.open_leading.empty() ? true : state_.open_leading.back();
1500  bool resulting_direction;
1501  gfx::Rect bounds = MenuItemView::IsBubble(state_.anchor) ?
1502      CalculateBubbleMenuBounds(item, prefer_leading, &resulting_direction) :
1503      CalculateMenuBounds(item, prefer_leading, &resulting_direction);
1504  state_.open_leading.push_back(resulting_direction);
1505  bool do_capture = (!did_capture_ && blocking_run_);
1506  showing_submenu_ = true;
1507  if (show) {
1508    // Menus are the only place using kGroupingPropertyKey, so any value (other
1509    // than 0) is fine.
1510    const int kGroupingId = 1001;
1511    item->GetSubmenu()->ShowAt(owner_, bounds, do_capture);
1512    item->GetSubmenu()->GetWidget()->SetNativeWindowProperty(
1513        TooltipManager::kGroupingPropertyKey,
1514        reinterpret_cast<void*>(kGroupingId));
1515  } else {
1516    item->GetSubmenu()->Reposition(bounds);
1517  }
1518  showing_submenu_ = false;
1519}
1520
1521void MenuController::MenuChildrenChanged(MenuItemView* item) {
1522  DCHECK(item);
1523  // Menu shouldn't be updated during drag operation.
1524  DCHECK(!GetActiveMouseView());
1525
1526  // If the current item or pending item is a descendant of the item
1527  // that changed, move the selection back to the changed item.
1528  const MenuItemView* ancestor = state_.item;
1529  while (ancestor && ancestor != item)
1530    ancestor = ancestor->GetParentMenuItem();
1531  if (!ancestor) {
1532    ancestor = pending_state_.item;
1533    while (ancestor && ancestor != item)
1534      ancestor = ancestor->GetParentMenuItem();
1535    if (!ancestor)
1536      return;
1537  }
1538  SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1539  if (item->HasSubmenu())
1540    OpenMenuImpl(item, false);
1541}
1542
1543void MenuController::BuildPathsAndCalculateDiff(
1544    MenuItemView* old_item,
1545    MenuItemView* new_item,
1546    std::vector<MenuItemView*>* old_path,
1547    std::vector<MenuItemView*>* new_path,
1548    size_t* first_diff_at) {
1549  DCHECK(old_path && new_path && first_diff_at);
1550  BuildMenuItemPath(old_item, old_path);
1551  BuildMenuItemPath(new_item, new_path);
1552
1553  size_t common_size = std::min(old_path->size(), new_path->size());
1554
1555  // Find the first difference between the two paths, when the loop
1556  // returns, diff_i is the first index where the two paths differ.
1557  for (size_t i = 0; i < common_size; ++i) {
1558    if ((*old_path)[i] != (*new_path)[i]) {
1559      *first_diff_at = i;
1560      return;
1561    }
1562  }
1563
1564  *first_diff_at = common_size;
1565}
1566
1567void MenuController::BuildMenuItemPath(MenuItemView* item,
1568                                       std::vector<MenuItemView*>* path) {
1569  if (!item)
1570    return;
1571  BuildMenuItemPath(item->GetParentMenuItem(), path);
1572  path->push_back(item);
1573}
1574
1575void MenuController::StartShowTimer() {
1576  show_timer_.Start(FROM_HERE,
1577                    TimeDelta::FromMilliseconds(menu_config_.show_delay),
1578                    this, &MenuController::CommitPendingSelection);
1579}
1580
1581void MenuController::StopShowTimer() {
1582  show_timer_.Stop();
1583}
1584
1585void MenuController::StartCancelAllTimer() {
1586  cancel_all_timer_.Start(FROM_HERE,
1587                          TimeDelta::FromMilliseconds(kCloseOnExitTime),
1588                          this, &MenuController::CancelAll);
1589}
1590
1591void MenuController::StopCancelAllTimer() {
1592  cancel_all_timer_.Stop();
1593}
1594
1595gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item,
1596                                              bool prefer_leading,
1597                                              bool* is_leading) {
1598  DCHECK(item);
1599
1600  SubmenuView* submenu = item->GetSubmenu();
1601  DCHECK(submenu);
1602
1603  gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1604
1605  // Don't let the menu go too wide.
1606  pref.set_width(std::min(pref.width(),
1607                            item->GetDelegate()->GetMaxWidthForMenu(item)));
1608  if (!state_.monitor_bounds.IsEmpty())
1609    pref.set_width(std::min(pref.width(), state_.monitor_bounds.width()));
1610
1611  // Assume we can honor prefer_leading.
1612  *is_leading = prefer_leading;
1613
1614  int x, y;
1615
1616  const MenuConfig& menu_config = item->GetMenuConfig();
1617
1618  if (!item->GetParentMenuItem()) {
1619    // First item, position relative to initial location.
1620    x = state_.initial_bounds.x();
1621
1622    // Offsets for context menu prevent menu items being selected by
1623    // simply opening the menu (bug 142992).
1624    if (menu_config.offset_context_menus && state_.context_menu)
1625      x += 1;
1626
1627    y = state_.initial_bounds.bottom();
1628    if (state_.anchor == MENU_ANCHOR_TOPRIGHT) {
1629      x = x + state_.initial_bounds.width() - pref.width();
1630      if (menu_config.offset_context_menus && state_.context_menu)
1631        x -= 1;
1632    } else if (state_.anchor == MENU_ANCHOR_BOTTOMCENTER) {
1633      x = x - (pref.width() - state_.initial_bounds.width()) / 2;
1634      if (pref.height() >
1635          state_.initial_bounds.y() + kCenteredContextMenuYOffset) {
1636        // Menu does not fit above the anchor. We move it to below.
1637        y = state_.initial_bounds.y() - kCenteredContextMenuYOffset;
1638      } else {
1639        y = std::max(0, state_.initial_bounds.y() - pref.height()) +
1640            kCenteredContextMenuYOffset;
1641      }
1642    }
1643
1644    if (!state_.monitor_bounds.IsEmpty() &&
1645        y + pref.height() > state_.monitor_bounds.bottom()) {
1646      // The menu doesn't fit fully below the button on the screen. The menu
1647      // position with respect to the bounds will be preserved if it has
1648      // already been drawn. When the requested positioning is below the bounds
1649      // it will shrink the menu to make it fit below.
1650      // If the requested positioning is best fit, it will first try to fit the
1651      // menu below. If that does not fit it will try to place it above. If
1652      // that will not fit it will place it at the bottom of the work area and
1653      // moving it off the initial_bounds region to avoid overlap.
1654      // In all other requested position styles it will be flipped above and
1655      // the height will be shrunken to the usable height.
1656      if (item->actual_menu_position() == MenuItemView::POSITION_BELOW_BOUNDS) {
1657        pref.set_height(std::min(pref.height(),
1658                                 state_.monitor_bounds.bottom() - y));
1659      } else if (item->actual_menu_position() ==
1660                 MenuItemView::POSITION_BEST_FIT) {
1661        MenuItemView::MenuPosition orientation =
1662            MenuItemView::POSITION_BELOW_BOUNDS;
1663        if (state_.monitor_bounds.height() < pref.height()) {
1664          // Handle very tall menus.
1665          pref.set_height(state_.monitor_bounds.height());
1666          y = state_.monitor_bounds.y();
1667        } else if (state_.monitor_bounds.y() + pref.height() <
1668            state_.initial_bounds.y()) {
1669          // Flipping upwards if there is enough space.
1670          y = state_.initial_bounds.y() - pref.height();
1671          orientation = MenuItemView::POSITION_ABOVE_BOUNDS;
1672        } else {
1673          // It is allowed to move the menu a bit around in order to get the
1674          // best fit and to avoid showing scroll elements.
1675          y = state_.monitor_bounds.bottom() - pref.height();
1676        }
1677        if (orientation == MenuItemView::POSITION_BELOW_BOUNDS) {
1678          // The menu should never overlap the owning button. So move it.
1679          // We use the anchor view style to determine the preferred position
1680          // relative to the owning button.
1681          if (state_.anchor == MENU_ANCHOR_TOPLEFT) {
1682            // The menu starts with the same x coordinate as the owning button.
1683            if (x + state_.initial_bounds.width() + pref.width() >
1684                state_.monitor_bounds.right())
1685              x -= pref.width();  // Move the menu to the left of the button.
1686            else
1687              x += state_.initial_bounds.width(); // Move the menu right.
1688          } else {
1689            // The menu should end with the same x coordinate as the owning
1690            // button.
1691            if (state_.monitor_bounds.x() >
1692                state_.initial_bounds.x() - pref.width())
1693              x = state_.initial_bounds.right();  // Move right of the button.
1694            else
1695              x = state_.initial_bounds.x() - pref.width(); // Move left.
1696          }
1697        }
1698        item->set_actual_menu_position(orientation);
1699      } else {
1700        pref.set_height(std::min(pref.height(),
1701            state_.initial_bounds.y() - state_.monitor_bounds.y()));
1702        y = state_.initial_bounds.y() - pref.height();
1703        item->set_actual_menu_position(MenuItemView::POSITION_ABOVE_BOUNDS);
1704      }
1705    } else if (item->actual_menu_position() ==
1706               MenuItemView::POSITION_ABOVE_BOUNDS) {
1707      pref.set_height(std::min(pref.height(),
1708          state_.initial_bounds.y() - state_.monitor_bounds.y()));
1709      y = state_.initial_bounds.y() - pref.height();
1710    } else {
1711      item->set_actual_menu_position(MenuItemView::POSITION_BELOW_BOUNDS);
1712    }
1713    if (state_.monitor_bounds.width() != 0 &&
1714        menu_config.offset_context_menus && state_.context_menu) {
1715      if (x + pref.width() > state_.monitor_bounds.right())
1716        x = state_.initial_bounds.x() - pref.width() - 1;
1717      if (x < state_.monitor_bounds.x())
1718        x = state_.monitor_bounds.x();
1719    }
1720  } else {
1721    // Not the first menu; position it relative to the bounds of the menu
1722    // item.
1723    gfx::Point item_loc;
1724    View::ConvertPointToScreen(item, &item_loc);
1725
1726    // We must make sure we take into account the UI layout. If the layout is
1727    // RTL, then a 'leading' menu is positioned to the left of the parent menu
1728    // item and not to the right.
1729    bool layout_is_rtl = base::i18n::IsRTL();
1730    bool create_on_the_right = (prefer_leading && !layout_is_rtl) ||
1731                               (!prefer_leading && layout_is_rtl);
1732    int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;
1733
1734    if (create_on_the_right) {
1735      x = item_loc.x() + item->width() - submenu_horizontal_inset;
1736      if (state_.monitor_bounds.width() != 0 &&
1737          x + pref.width() > state_.monitor_bounds.right()) {
1738        if (layout_is_rtl)
1739          *is_leading = true;
1740        else
1741          *is_leading = false;
1742        x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1743      }
1744    } else {
1745      x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1746      if (state_.monitor_bounds.width() != 0 && x < state_.monitor_bounds.x()) {
1747        if (layout_is_rtl)
1748          *is_leading = false;
1749        else
1750          *is_leading = true;
1751        x = item_loc.x() + item->width() - submenu_horizontal_inset;
1752      }
1753    }
1754    y = item_loc.y() - menu_config.menu_vertical_border_size;
1755    if (state_.monitor_bounds.width() != 0) {
1756      pref.set_height(std::min(pref.height(), state_.monitor_bounds.height()));
1757      if (y + pref.height() > state_.monitor_bounds.bottom())
1758        y = state_.monitor_bounds.bottom() - pref.height();
1759      if (y < state_.monitor_bounds.y())
1760        y = state_.monitor_bounds.y();
1761    }
1762  }
1763
1764  if (state_.monitor_bounds.width() != 0) {
1765    if (x + pref.width() > state_.monitor_bounds.right())
1766      x = state_.monitor_bounds.right() - pref.width();
1767    if (x < state_.monitor_bounds.x())
1768      x = state_.monitor_bounds.x();
1769  }
1770  return gfx::Rect(x, y, pref.width(), pref.height());
1771}
1772
1773gfx::Rect MenuController::CalculateBubbleMenuBounds(MenuItemView* item,
1774                                                    bool prefer_leading,
1775                                                    bool* is_leading) {
1776  DCHECK(item);
1777  DCHECK(!item->GetParentMenuItem());
1778
1779  // Assume we can honor prefer_leading.
1780  *is_leading = prefer_leading;
1781
1782  SubmenuView* submenu = item->GetSubmenu();
1783  DCHECK(submenu);
1784
1785  gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1786  const gfx::Rect& owner_bounds = pending_state_.initial_bounds;
1787
1788  // First the size gets reduced to the possible space.
1789  if (!state_.monitor_bounds.IsEmpty()) {
1790    int max_width = state_.monitor_bounds.width();
1791    int max_height = state_.monitor_bounds.height();
1792    // In case of bubbles, the maximum width is limited by the space
1793    // between the display corner and the target area + the tip size.
1794    if (state_.anchor == MENU_ANCHOR_BUBBLE_LEFT) {
1795      max_width = owner_bounds.x() - state_.monitor_bounds.x() +
1796                  kBubbleTipSizeLeftRight;
1797    } else if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT) {
1798      max_width = state_.monitor_bounds.right() - owner_bounds.right() +
1799                  kBubbleTipSizeLeftRight;
1800    } else if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE) {
1801      max_height = owner_bounds.y() - state_.monitor_bounds.y() +
1802                   kBubbleTipSizeTopBottom;
1803    } else if (state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1804      max_height = state_.monitor_bounds.bottom() - owner_bounds.bottom() +
1805                   kBubbleTipSizeTopBottom;
1806    }
1807    // The space for the menu to cover should never get empty.
1808    DCHECK_GE(max_width, kBubbleTipSizeLeftRight);
1809    DCHECK_GE(max_height, kBubbleTipSizeTopBottom);
1810    pref.set_width(std::min(pref.width(), max_width));
1811    pref.set_height(std::min(pref.height(), max_height));
1812  }
1813  // Also make sure that the menu does not go too wide.
1814  pref.set_width(std::min(pref.width(),
1815                          item->GetDelegate()->GetMaxWidthForMenu(item)));
1816
1817  int x, y;
1818  if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE ||
1819      state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1820    if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE)
1821      y = owner_bounds.y() - pref.height() + kBubbleTipSizeTopBottom;
1822    else
1823      y = owner_bounds.bottom() - kBubbleTipSizeTopBottom;
1824
1825    x = owner_bounds.CenterPoint().x() - pref.width() / 2;
1826    int x_old = x;
1827    if (x < state_.monitor_bounds.x()) {
1828      x = state_.monitor_bounds.x();
1829    } else if (x + pref.width() > state_.monitor_bounds.right()) {
1830      x = state_.monitor_bounds.right() - pref.width();
1831    }
1832    submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1833        pref.width() / 2 - x + x_old);
1834  } else {
1835    if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT)
1836      x = owner_bounds.right() - kBubbleTipSizeLeftRight;
1837    else
1838      x = owner_bounds.x() - pref.width() + kBubbleTipSizeLeftRight;
1839
1840    y = owner_bounds.CenterPoint().y() - pref.height() / 2;
1841    int y_old = y;
1842    if (y < state_.monitor_bounds.y()) {
1843      y = state_.monitor_bounds.y();
1844    } else if (y + pref.height() > state_.monitor_bounds.bottom()) {
1845      y = state_.monitor_bounds.bottom() - pref.height();
1846    }
1847    submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1848        pref.height() / 2 - y + y_old);
1849  }
1850  return gfx::Rect(x, y, pref.width(), pref.height());
1851}
1852
1853// static
1854int MenuController::MenuDepth(MenuItemView* item) {
1855  return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : 0;
1856}
1857
1858void MenuController::IncrementSelection(int delta) {
1859  MenuItemView* item = pending_state_.item;
1860  DCHECK(item);
1861  if (pending_state_.submenu_open && item->HasSubmenu() &&
1862      item->GetSubmenu()->IsShowing()) {
1863    // A menu is selected and open, but none of its children are selected,
1864    // select the first menu item.
1865    if (item->GetSubmenu()->GetMenuItemCount()) {
1866      SetSelection(item->GetSubmenu()->GetMenuItemAt(0), SELECTION_DEFAULT);
1867      return;
1868    }
1869  }
1870
1871  if (item->has_children()) {
1872    CustomButton* button = GetFirstHotTrackedView(item);
1873    if (button) {
1874      button->SetHotTracked(false);
1875      View* to_make_hot = GetNextFocusableView(item, button, delta == 1);
1876      CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1877      if (button_hot) {
1878        button_hot->SetHotTracked(true);
1879        return;
1880      }
1881    } else {
1882      View* to_make_hot = GetInitialFocusableView(item, delta == 1);
1883      CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1884      if (button_hot) {
1885        button_hot->SetHotTracked(true);
1886        return;
1887      }
1888    }
1889  }
1890
1891  MenuItemView* parent = item->GetParentMenuItem();
1892  if (parent) {
1893    int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1894    if (parent_count > 1) {
1895      for (int i = 0; i < parent_count; ++i) {
1896        if (parent->GetSubmenu()->GetMenuItemAt(i) == item) {
1897          MenuItemView* to_select =
1898              FindNextSelectableMenuItem(parent, i, delta);
1899          if (!to_select)
1900            break;
1901          SetSelection(to_select, SELECTION_DEFAULT);
1902          View* to_make_hot = GetInitialFocusableView(to_select, delta == 1);
1903          CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1904          if (button_hot)
1905            button_hot->SetHotTracked(true);
1906          break;
1907        }
1908      }
1909    }
1910  }
1911}
1912
1913MenuItemView* MenuController::FindNextSelectableMenuItem(MenuItemView* parent,
1914                                                         int index,
1915                                                         int delta) {
1916  int start_index = index;
1917  int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1918  // Loop through the menu items skipping any invisible menus. The loop stops
1919  // when we wrap or find a visible child.
1920  do {
1921    index = (index + delta + parent_count) % parent_count;
1922    if (index == start_index)
1923      return NULL;
1924    MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
1925    if (child->visible())
1926      return child;
1927  } while (index != start_index);
1928  return NULL;
1929}
1930
1931void MenuController::OpenSubmenuChangeSelectionIfCan() {
1932  MenuItemView* item = pending_state_.item;
1933  if (item->HasSubmenu() && item->enabled()) {
1934    if (item->GetSubmenu()->GetMenuItemCount() > 0) {
1935      SetSelection(item->GetSubmenu()->GetMenuItemAt(0),
1936                   SELECTION_UPDATE_IMMEDIATELY);
1937    } else {
1938      // No menu items, just show the sub-menu.
1939      SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1940    }
1941  }
1942}
1943
1944void MenuController::CloseSubmenu() {
1945  MenuItemView* item = state_.item;
1946  DCHECK(item);
1947  if (!item->GetParentMenuItem())
1948    return;
1949  if (item->HasSubmenu() && item->GetSubmenu()->IsShowing())
1950    SetSelection(item, SELECTION_UPDATE_IMMEDIATELY);
1951  else if (item->GetParentMenuItem()->GetParentMenuItem())
1952    SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY);
1953}
1954
1955MenuController::SelectByCharDetails MenuController::FindChildForMnemonic(
1956    MenuItemView* parent,
1957    base::char16 key,
1958    bool (*match_function)(MenuItemView* menu, base::char16 mnemonic)) {
1959  SubmenuView* submenu = parent->GetSubmenu();
1960  DCHECK(submenu);
1961  SelectByCharDetails details;
1962
1963  for (int i = 0, menu_item_count = submenu->GetMenuItemCount();
1964       i < menu_item_count; ++i) {
1965    MenuItemView* child = submenu->GetMenuItemAt(i);
1966    if (child->enabled() && child->visible()) {
1967      if (child == pending_state_.item)
1968        details.index_of_item = i;
1969      if (match_function(child, key)) {
1970        if (details.first_match == -1)
1971          details.first_match = i;
1972        else
1973          details.has_multiple = true;
1974        if (details.next_match == -1 && details.index_of_item != -1 &&
1975            i > details.index_of_item)
1976          details.next_match = i;
1977      }
1978    }
1979  }
1980  return details;
1981}
1982
1983bool MenuController::AcceptOrSelect(MenuItemView* parent,
1984                                    const SelectByCharDetails& details) {
1985  // This should only be invoked if there is a match.
1986  DCHECK(details.first_match != -1);
1987  DCHECK(parent->HasSubmenu());
1988  SubmenuView* submenu = parent->GetSubmenu();
1989  DCHECK(submenu);
1990  if (!details.has_multiple) {
1991    // There's only one match, activate it (or open if it has a submenu).
1992    if (submenu->GetMenuItemAt(details.first_match)->HasSubmenu()) {
1993      SetSelection(submenu->GetMenuItemAt(details.first_match),
1994                   SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1995    } else {
1996      Accept(submenu->GetMenuItemAt(details.first_match), 0);
1997      return true;
1998    }
1999  } else if (details.index_of_item == -1 || details.next_match == -1) {
2000    SetSelection(submenu->GetMenuItemAt(details.first_match),
2001                 SELECTION_DEFAULT);
2002  } else {
2003    SetSelection(submenu->GetMenuItemAt(details.next_match),
2004                 SELECTION_DEFAULT);
2005  }
2006  return false;
2007}
2008
2009bool MenuController::SelectByChar(base::char16 character) {
2010  base::char16 char_array[] = { character, 0 };
2011  base::char16 key = base::i18n::ToLower(char_array)[0];
2012  MenuItemView* item = pending_state_.item;
2013  if (!item->HasSubmenu() || !item->GetSubmenu()->IsShowing())
2014    item = item->GetParentMenuItem();
2015  DCHECK(item);
2016  DCHECK(item->HasSubmenu());
2017  DCHECK(item->GetSubmenu());
2018  if (item->GetSubmenu()->GetMenuItemCount() == 0)
2019    return false;
2020
2021  // Look for matches based on mnemonic first.
2022  SelectByCharDetails details =
2023      FindChildForMnemonic(item, key, &MatchesMnemonic);
2024  if (details.first_match != -1)
2025    return AcceptOrSelect(item, details);
2026
2027  if (is_combobox_) {
2028    item->GetSubmenu()->GetTextInputClient()->InsertChar(character, 0);
2029  } else {
2030    // If no mnemonics found, look at first character of titles.
2031    details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic);
2032    if (details.first_match != -1)
2033      return AcceptOrSelect(item, details);
2034  }
2035
2036  return false;
2037}
2038
2039void MenuController::RepostEvent(SubmenuView* source,
2040                                 const ui::LocatedEvent& event) {
2041  if (!event.IsMouseEvent()) {
2042    // TODO(rbyers): Gesture event repost is tricky to get right
2043    // crbug.com/170987.
2044    DCHECK(event.IsGestureEvent());
2045    return;
2046  }
2047
2048#if defined(OS_WIN)
2049  if (!state_.item) {
2050    // We some times get an event after closing all the menus. Ignore it. Make
2051    // sure the menu is in fact not visible. If the menu is visible, then
2052    // we're in a bad state where we think the menu isn't visibile but it is.
2053    DCHECK(!source->GetWidget()->IsVisible());
2054    return;
2055  }
2056
2057  state_.item->GetRootMenuItem()->GetSubmenu()->ReleaseCapture();
2058#endif
2059
2060  gfx::Point screen_loc(event.location());
2061  View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
2062  gfx::NativeView native_view = source->GetWidget()->GetNativeView();
2063  if (!native_view)
2064    return;
2065
2066  gfx::Screen* screen = gfx::Screen::GetScreenFor(native_view);
2067  gfx::NativeWindow window = screen->GetWindowAtScreenPoint(screen_loc);
2068
2069#if defined(OS_WIN)
2070  // Convert screen_loc to pixels for the Win32 API's like WindowFromPoint,
2071  // PostMessage/SendMessage to work correctly. These API's expect the
2072  // coordinates to be in pixels.
2073  // PostMessage() to metro windows isn't allowed (access will be denied). Don't
2074  // try to repost with Win32 if the window under the mouse press is in metro.
2075  if (!ViewsDelegate::views_delegate ||
2076      !ViewsDelegate::views_delegate->IsWindowInMetro(window)) {
2077    gfx::Point screen_loc_pixels = gfx::win::DIPToScreenPoint(screen_loc);
2078    HWND target_window = window ? HWNDForNativeWindow(window) :
2079                                  WindowFromPoint(screen_loc_pixels.ToPOINT());
2080    HWND source_window = HWNDForNativeView(native_view);
2081    if (!target_window || !source_window ||
2082        GetWindowThreadProcessId(source_window, NULL) !=
2083        GetWindowThreadProcessId(target_window, NULL)) {
2084      // Even though we have mouse capture, windows generates a mouse event if
2085      // the other window is in a separate thread. Only repost an event if
2086      // |target_window| and |source_window| were created on the same thread,
2087      // else double events can occur and lead to bad behavior.
2088      return;
2089    }
2090
2091    // Determine whether the click was in the client area or not.
2092    // NOTE: WM_NCHITTEST coordinates are relative to the screen.
2093    LPARAM coords = MAKELPARAM(screen_loc_pixels.x(), screen_loc_pixels.y());
2094    LRESULT nc_hit_result = SendMessage(target_window, WM_NCHITTEST, 0, coords);
2095    const bool client_area = nc_hit_result == HTCLIENT;
2096
2097    // TODO(sky): this isn't right. The event to generate should correspond with
2098    // the event we just got. MouseEvent only tells us what is down, which may
2099    // differ. Need to add ability to get changed button from MouseEvent.
2100    int event_type;
2101    int flags = event.flags();
2102    if (flags & ui::EF_LEFT_MOUSE_BUTTON) {
2103      event_type = client_area ? WM_LBUTTONDOWN : WM_NCLBUTTONDOWN;
2104    } else if (flags & ui::EF_MIDDLE_MOUSE_BUTTON) {
2105      event_type = client_area ? WM_MBUTTONDOWN : WM_NCMBUTTONDOWN;
2106    } else if (flags & ui::EF_RIGHT_MOUSE_BUTTON) {
2107      event_type = client_area ? WM_RBUTTONDOWN : WM_NCRBUTTONDOWN;
2108    } else {
2109      NOTREACHED();
2110      return;
2111    }
2112
2113    int window_x = screen_loc_pixels.x();
2114    int window_y = screen_loc_pixels.y();
2115    if (client_area) {
2116      POINT pt = { window_x, window_y };
2117      ScreenToClient(target_window, &pt);
2118      window_x = pt.x;
2119      window_y = pt.y;
2120    }
2121
2122    WPARAM target = client_area ? event.native_event().wParam : nc_hit_result;
2123    LPARAM window_coords = MAKELPARAM(window_x, window_y);
2124    PostMessage(target_window, event_type, target, window_coords);
2125    return;
2126  }
2127#endif
2128  // Non-Windows Aura or |window| is in metro mode.
2129  if (!window)
2130    return;
2131
2132  message_loop_->RepostEventToWindow(event, window, screen_loc);
2133}
2134
2135void MenuController::SetDropMenuItem(
2136    MenuItemView* new_target,
2137    MenuDelegate::DropPosition new_position) {
2138  if (new_target == drop_target_ && new_position == drop_position_)
2139    return;
2140
2141  if (drop_target_) {
2142    drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2143        NULL, MenuDelegate::DROP_NONE);
2144  }
2145  drop_target_ = new_target;
2146  drop_position_ = new_position;
2147  if (drop_target_) {
2148    drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2149        drop_target_, drop_position_);
2150  }
2151}
2152
2153void MenuController::UpdateScrolling(const MenuPart& part) {
2154  if (!part.is_scroll() && !scroll_task_.get())
2155    return;
2156
2157  if (!scroll_task_.get())
2158    scroll_task_.reset(new MenuScrollTask());
2159  scroll_task_->Update(part);
2160}
2161
2162void MenuController::StopScrolling() {
2163  scroll_task_.reset(NULL);
2164}
2165
2166void MenuController::UpdateActiveMouseView(SubmenuView* event_source,
2167                                           const ui::MouseEvent& event,
2168                                           View* target_menu) {
2169  View* target = NULL;
2170  gfx::Point target_menu_loc(event.location());
2171  if (target_menu && target_menu->has_children()) {
2172    // Locate the deepest child view to send events to.  This code assumes we
2173    // don't have to walk up the tree to find a view interested in events. This
2174    // is currently true for the cases we are embedding views, but if we embed
2175    // more complex hierarchies it'll need to change.
2176    View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2177                               &target_menu_loc);
2178    View::ConvertPointFromScreen(target_menu, &target_menu_loc);
2179    target = target_menu->GetEventHandlerForPoint(target_menu_loc);
2180    if (target == target_menu || !target->enabled())
2181      target = NULL;
2182  }
2183  View* active_mouse_view = GetActiveMouseView();
2184  if (target != active_mouse_view) {
2185    SendMouseCaptureLostToActiveView();
2186    active_mouse_view = target;
2187    SetActiveMouseView(active_mouse_view);
2188    if (active_mouse_view) {
2189      gfx::Point target_point(target_menu_loc);
2190      View::ConvertPointToTarget(
2191          target_menu, active_mouse_view, &target_point);
2192      ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED,
2193                                         target_point, target_point,
2194                                         0, 0);
2195      active_mouse_view->OnMouseEntered(mouse_entered_event);
2196
2197      ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED,
2198                                         target_point, target_point,
2199                                         event.flags(),
2200                                         event.changed_button_flags());
2201      active_mouse_view->OnMousePressed(mouse_pressed_event);
2202    }
2203  }
2204
2205  if (active_mouse_view) {
2206    gfx::Point target_point(target_menu_loc);
2207    View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point);
2208    ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED,
2209                                       target_point, target_point,
2210                                       event.flags(),
2211                                       event.changed_button_flags());
2212    active_mouse_view->OnMouseDragged(mouse_dragged_event);
2213  }
2214}
2215
2216void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source,
2217                                                  const ui::MouseEvent& event) {
2218  View* active_mouse_view = GetActiveMouseView();
2219  if (!active_mouse_view)
2220    return;
2221
2222  gfx::Point target_loc(event.location());
2223  View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2224                             &target_loc);
2225  View::ConvertPointFromScreen(active_mouse_view, &target_loc);
2226  ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, target_loc, target_loc,
2227                               event.flags(), event.changed_button_flags());
2228  // Reset active mouse view before sending mouse released. That way if it calls
2229  // back to us, we aren't in a weird state.
2230  SetActiveMouseView(NULL);
2231  active_mouse_view->OnMouseReleased(release_event);
2232}
2233
2234void MenuController::SendMouseCaptureLostToActiveView() {
2235  View* active_mouse_view = GetActiveMouseView();
2236  if (!active_mouse_view)
2237    return;
2238
2239  // Reset the active_mouse_view_ before sending mouse capture lost. That way if
2240  // it calls back to us, we aren't in a weird state.
2241  SetActiveMouseView(NULL);
2242  active_mouse_view->OnMouseCaptureLost();
2243}
2244
2245void MenuController::SetActiveMouseView(View* view) {
2246  if (view)
2247    ViewStorage::GetInstance()->StoreView(active_mouse_view_id_, view);
2248  else
2249    ViewStorage::GetInstance()->RemoveView(active_mouse_view_id_);
2250}
2251
2252View* MenuController::GetActiveMouseView() {
2253  return ViewStorage::GetInstance()->RetrieveView(active_mouse_view_id_);
2254}
2255
2256void MenuController::SetExitType(ExitType type) {
2257  exit_type_ = type;
2258  // Exit nested message loops as soon as possible. We do this as
2259  // MessagePumpDispatcher is only invoked before native events, which means
2260  // its entirely possible for a Widget::CloseNow() task to be processed before
2261  // the next native message. We quite the nested message loop as soon as
2262  // possible to avoid having deleted views classes (such as widgets and
2263  // rootviews) on the stack when the nested message loop stops.
2264  //
2265  // It's safe to invoke QuitNestedMessageLoop() multiple times, it only effects
2266  // the current loop.
2267  bool quit_now = message_loop_->ShouldQuitNow() && exit_type_ != EXIT_NONE &&
2268      message_loop_depth_;
2269  if (quit_now)
2270    TerminateNestedMessageLoop();
2271}
2272
2273void MenuController::TerminateNestedMessageLoop() {
2274  message_loop_->QuitNow();
2275}
2276
2277void MenuController::HandleMouseLocation(SubmenuView* source,
2278                                         const gfx::Point& mouse_location) {
2279  if (showing_submenu_)
2280    return;
2281
2282  // Ignore mouse events if we're closing the menu.
2283  if (exit_type_ != EXIT_NONE)
2284    return;
2285
2286  MenuPart part = GetMenuPart(source, mouse_location);
2287
2288  UpdateScrolling(part);
2289
2290  if (!blocking_run_)
2291    return;
2292
2293  if (part.type == MenuPart::NONE && ShowSiblingMenu(source, mouse_location))
2294    return;
2295
2296  if (part.type == MenuPart::MENU_ITEM && part.menu) {
2297    SetSelection(part.menu, SELECTION_OPEN_SUBMENU);
2298  } else if (!part.is_scroll() && pending_state_.item &&
2299             pending_state_.item->GetParentMenuItem() &&
2300             (!pending_state_.item->HasSubmenu() ||
2301              !pending_state_.item->GetSubmenu()->IsShowing())) {
2302    // On exit if the user hasn't selected an item with a submenu, move the
2303    // selection back to the parent menu item.
2304    SetSelection(pending_state_.item->GetParentMenuItem(),
2305                 SELECTION_OPEN_SUBMENU);
2306  }
2307}
2308
2309gfx::Screen* MenuController::GetScreen() {
2310  Widget* root = owner_ ? owner_->GetTopLevelWidget() : NULL;
2311  return root ? gfx::Screen::GetScreenFor(root->GetNativeView())
2312              : gfx::Screen::GetNativeScreen();
2313}
2314
2315}  // namespace views
2316