Cleanup: Update the path to insets and point headers.
[chromium-blink-merge.git] / ui / views / controls / menu / menu_controller.cc
blobcd6f5d343d33c2ff1cc8f6158ac47376a1129918
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/views/controls/menu/menu_controller.h"
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/geometry/point.h"
17 #include "ui/gfx/native_widget_types.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"
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
45 using base::Time;
46 using base::TimeDelta;
47 using ui::OSExchangeData;
49 // Period of the scroll timer (in milliseconds).
50 static const int kScrollTimerMS = 30;
52 // Amount of time from when the drop exits the menu and the menu is hidden.
53 static const int kCloseOnExitTime = 1200;
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.
57 static const int kCenteredContextMenuYOffset = -15;
59 namespace views {
61 namespace {
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.
66 static int menu_selection_hold_time_ms = kMinimumMsPressedToActivate;
68 // The spacing offset for the bubble tip.
69 const int kBubbleTipSizeLeftRight = 12;
70 const int kBubbleTipSizeTopBottom = 11;
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).
75 const float kMaximumLengthMovedToActivate = 4.0f;
77 // Returns true if the mnemonic of |menu| matches key.
78 bool MatchesMnemonic(MenuItemView* menu, base::char16 key) {
79 return key != 0 && menu->GetMnemonic() == key;
82 // Returns true if |menu| doesn't have a mnemonic and first character of the its
83 // title is |key|.
84 bool TitleMatchesMnemonic(MenuItemView* menu, base::char16 key) {
85 if (menu->GetMnemonic())
86 return false;
88 base::string16 lower_title = base::i18n::ToLower(menu->title());
89 return !lower_title.empty() && lower_title[0] == key;
92 } // namespace
94 // Returns the first descendant of |view| that is hot tracked.
95 static 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;
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;
109 return NULL;
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.
117 static 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;
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;
131 return view->IsFocusable() ? view : NULL;
134 // Returns the first child of |start| that is focusable.
135 static View* GetInitialFocusableView(View* start, bool forward) {
136 return GetFirstFocusableView(start, -1, forward);
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|.
141 static 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;
155 parent = new_parent;
156 } while (parent != ancestor);
157 return NULL;
160 // MenuScrollTask --------------------------------------------------------------
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.
167 class MenuController::MenuScrollTask {
168 public:
169 MenuScrollTask() : submenu_(NULL), is_scrolling_up_(false), start_y_(0) {
170 pixels_per_second_ = MenuItemView::pref_menu_height() * 20;
173 void Update(const MenuController::MenuPart& part) {
174 if (!part.is_scroll()) {
175 StopScrolling();
176 return;
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;
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;
189 if (!scrolling_timer_.IsRunning()) {
190 scrolling_timer_.Start(FROM_HERE,
191 TimeDelta::FromMilliseconds(kScrollTimerMS),
192 this, &MenuScrollTask::Run);
196 void StopScrolling() {
197 if (scrolling_timer_.IsRunning()) {
198 scrolling_timer_.Stop();
199 submenu_ = NULL;
203 // The menu being scrolled. Returns null if not scrolling.
204 SubmenuView* submenu() const { return submenu_; }
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);
219 // SubmenuView being scrolled.
220 SubmenuView* submenu_;
222 // Direction scrolling.
223 bool is_scrolling_up_;
225 // Timer to periodically scroll.
226 base::RepeatingTimer<MenuScrollTask> scrolling_timer_;
228 // Time we started scrolling at.
229 base::Time start_scroll_time_;
231 // How many pixels to scroll per second.
232 int pixels_per_second_;
234 // Y-coordinate of submenu_view_ when scrolling started.
235 int start_y_;
237 DISALLOW_COPY_AND_ASSIGN(MenuScrollTask);
240 // MenuController:SelectByCharDetails ----------------------------------------
242 struct MenuController::SelectByCharDetails {
243 SelectByCharDetails()
244 : first_match(-1),
245 has_multiple(false),
246 index_of_item(-1),
247 next_match(-1) {
250 // Index of the first menu with the specified mnemonic.
251 int first_match;
253 // If true there are multiple menu items with the same mnemonic.
254 bool has_multiple;
256 // Index of the selected item; may remain -1.
257 int index_of_item;
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;
265 // MenuController:State ------------------------------------------------------
267 MenuController::State::State()
268 : item(NULL),
269 submenu_open(false),
270 anchor(MENU_ANCHOR_TOPLEFT),
271 context_menu(false) {
274 MenuController::State::~State() {}
276 // MenuController ------------------------------------------------------------
278 // static
279 MenuController* MenuController::active_instance_ = NULL;
281 // static
282 MenuController* MenuController::GetActiveInstance() {
283 return active_instance_;
286 MenuItemView* 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();
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;
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_);
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())));
331 // The context menu should be owned by the same parent.
332 DCHECK_EQ(owner_, parent);
333 } else {
334 showing_ = true;
337 // Reset current state.
338 pending_state_ = State();
339 state_ = State();
340 UpdateInitialLocation(bounds, position, context_menu);
342 if (owner_)
343 owner_->RemoveObserver(this);
344 owner_ = parent;
345 if (owner_)
346 owner_->AddObserver(this);
348 // Set the selection, which opens the initial menu.
349 SetSelection(root, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
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();
357 return NULL;
360 if (button)
361 pressed_lock_.reset(new MenuButton::PressedLock(button));
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();
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_--;
376 if (ViewsDelegate::views_delegate)
377 ViewsDelegate::views_delegate->ReleaseRef();
379 // Close any open menus.
380 SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
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));
401 #endif
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;
417 MenuItemView* result = result_;
418 // In case we're nested, reset result_.
419 result_ = NULL;
421 if (result_event_flags)
422 *result_event_flags = accept_event_flags_;
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);
434 // Set exit_all_, which makes sure all nested loops exit immediately.
435 if (exit_type_ != EXIT_DESTROYED)
436 SetExitType(EXIT_ALL);
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());
444 return result;
447 void 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;
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;
460 MenuItemView* selected = state_.item;
461 SetExitType(type);
463 SendMouseCaptureLostToActiveView();
465 // Hide windows immediately.
466 SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
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;
481 void MenuController::OnMousePressed(SubmenuView* source,
482 const ui::MouseEvent& event) {
483 SetSelectionOnPointerDown(source, event);
486 void MenuController::OnMouseDragged(SubmenuView* source,
487 const ui::MouseEvent& event) {
488 MenuPart part = GetMenuPart(source, event.location());
489 UpdateScrolling(part);
491 if (!blocking_run_)
492 return;
494 if (possible_drag_) {
495 if (View::ExceededDragThreshold(event.location() - press_pt_))
496 StartDrag(source, press_pt_);
497 return;
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());
509 UpdateActiveMouseView(source, event, mouse_menu);
512 void MenuController::OnMouseReleased(SubmenuView* source,
513 const ui::MouseEvent& event) {
514 if (!blocking_run_)
515 return;
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;
531 if (menu != NULL && ShowContextMenu(menu, source, event,
532 ui::MENU_SOURCE_MOUSE))
533 return;
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;
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;
559 if (part.menu->GetDelegate()->ShouldExecuteCommandWithoutClosingMenu(
560 part.menu->GetCommand(), event)) {
561 part.menu->GetDelegate()->ExecuteCommand(part.menu->GetCommand(),
562 event.flags());
563 return;
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());
572 return;
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);
579 SendMouseCaptureLostToActiveView();
582 void MenuController::OnMouseMoved(SubmenuView* source,
583 const ui::MouseEvent& event) {
584 HandleMouseLocation(source, event.location());
587 void 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.
593 bool MenuController::OnMouseWheel(SubmenuView* source,
594 const ui::MouseWheelEvent& event) {
595 MenuPart part = GetMenuPart(source, event.location());
596 return part.submenu && part.submenu->OnMouseWheel(event);
599 void 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();
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;
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();
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();
636 if (event->stopped_propagation())
637 return;
639 if (!part.submenu)
640 return;
641 part.submenu->OnGestureEvent(event);
644 bool 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);
652 bool MenuController::AreDropTypesRequired(SubmenuView* source) {
653 return source->GetMenuItem()->GetDelegate()->AreDropTypesRequired(
654 source->GetMenuItem());
657 bool MenuController::CanDrop(SubmenuView* source, const OSExchangeData& data) {
658 return source->GetMenuItem()->GetDelegate()->CanDrop(source->GetMenuItem(),
659 data);
662 void MenuController::OnDragEntered(SubmenuView* source,
663 const ui::DropTargetEvent& event) {
664 valid_drop_coordinates_ = false;
667 int MenuController::OnDragUpdated(SubmenuView* source,
668 const ui::DropTargetEvent& event) {
669 StopCancelAllTimer();
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;
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;
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;
702 query_menu_item = menu_item;
703 } else {
704 query_menu_item = menu_item->GetParentMenuItem();
705 drop_position = MenuDelegate::DROP_ON;
707 drop_operation = menu_item->GetDelegate()->GetDropOperation(
708 query_menu_item, event, &drop_position);
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);
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);
720 SetDropMenuItem(menu_item, drop_position);
721 last_drop_operation_ = drop_operation;
722 return drop_operation;
725 void MenuController::OnDragExited(SubmenuView* source) {
726 StartCancelAllTimer();
728 if (drop_target_) {
729 StopShowTimer();
730 SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
734 int 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.
740 MenuItemView* item = state_.item;
741 DCHECK(item);
743 MenuItemView* drop_target = drop_target_;
744 MenuDelegate::DropPosition drop_position = drop_position_;
746 // Close all menus, including any nested menus.
747 SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
748 CloseAllNestedMenus();
750 // Set state such that we exit.
751 showing_ = false;
752 SetExitType(EXIT_ALL);
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();
758 if (!IsBlockingRun()) {
759 delegate_->DropMenuClosed(
760 internal::MenuControllerDelegate::DONT_NOTIFY_DELEGATE,
761 item->GetRootMenuItem());
764 // WARNING: the call to MenuClosed deletes us.
766 return drop_target->GetDelegate()->OnPerformDrop(
767 drop_target, drop_position, event);
770 void 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);
777 // Do this to force the selection to hide.
778 SetDropMenuItem(source->GetMenuItemAt(0), MenuDelegate::DROP_NONE);
780 StopCancelAllTimer();
783 void MenuController::OnDragExitedScrollButton(SubmenuView* source) {
784 StartCancelAllTimer();
785 SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
786 StopScrolling();
789 void MenuController::OnDragWillStart() {
790 DCHECK(!drag_in_progress_);
791 drag_in_progress_ = true;
794 void 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);
803 void 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);
814 void MenuController::OnWidgetDestroying(Widget* widget) {
815 DCHECK_EQ(owner_, widget);
816 owner_->RemoveObserver(this);
817 owner_ = NULL;
818 message_loop_->ClearOwner();
821 bool MenuController::IsCancelAllTimerRunningForTest() {
822 return cancel_all_timer_.IsRunning();
825 // static
826 void MenuController::TurnOffMenuSelectionHoldForTest() {
827 menu_selection_hold_time_ms = -1;
830 void 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);
838 size_t current_size = current_path.size();
839 size_t new_size = new_path.size();
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);
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]);
856 current_path[i]->SetSelected(false);
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);
865 if (menu_item && menu_item->GetDelegate())
866 menu_item->GetDelegate()->SelectionChanged(menu_item);
868 DCHECK(menu_item || (selection_types & SELECTION_EXIT) != 0);
870 pending_state_.item = menu_item;
871 pending_state_.submenu_open = (selection_types & SELECTION_OPEN_SUBMENU) != 0;
873 // Stop timers.
874 StopCancelAllTimer();
875 // Resets show timer only when pending menu item is changed.
876 if (pending_item_changed)
877 StopShowTimer();
879 if (selection_types & SELECTION_UPDATE_IMMEDIATELY)
880 CommitPendingSelection();
881 else if (pending_item_changed)
882 StartShowTimer();
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);
893 void MenuController::SetSelectionOnPointerDown(SubmenuView* source,
894 const ui::LocatedEvent& event) {
895 if (!blocking_run_)
896 return;
898 DCHECK(!GetActiveMouseView());
900 MenuPart part = GetMenuPart(source, event.location());
901 if (part.is_scroll())
902 return; // Ignore presses on scroll buttons.
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;
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 stamp of the current (press down) event. The owner can
914 // then use this to figure out if this menu was finished with the same click
915 // which is sent to it thereafter.
916 closing_event_time_ = event.time_stamp();
918 // Mouse wasn't pressed over any menu, or the active menu, cancel.
920 #if defined(OS_WIN)
921 // We're going to close and we own the mouse capture. We need to repost the
922 // mouse down, otherwise the window the user clicked on won't get the event.
923 RepostEvent(source, event);
924 #endif
926 // And close.
927 ExitType exit_type = EXIT_ALL;
928 if (!menu_stack_.empty()) {
929 // We're running nested menus. Only exit all if the mouse wasn't over one
930 // of the menus from the last run.
931 gfx::Point screen_loc(event.location());
932 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
933 MenuPart last_part = GetMenuPartByScreenCoordinateUsingMenu(
934 menu_stack_.back().first.item, screen_loc);
935 if (last_part.type != MenuPart::NONE)
936 exit_type = EXIT_OUTERMOST;
938 Cancel(exit_type);
940 #if defined(OS_CHROMEOS)
941 // We're going to exit the menu and want to repost the event so that is
942 // is handled normally after the context menu has exited. We call
943 // RepostEvent after Cancel so that mouse capture has been released so
944 // that finding the event target is unaffected by the current capture.
945 RepostEvent(source, event);
946 #endif
947 // Do not repost events for Linux Aura because this behavior is more
948 // consistent with the behavior of other Linux apps.
949 return;
952 // On a press we immediately commit the selection, that way a submenu
953 // pops up immediately rather than after a delay.
954 int selection_types = SELECTION_UPDATE_IMMEDIATELY;
955 if (!part.menu) {
956 part.menu = part.parent;
957 selection_types |= SELECTION_OPEN_SUBMENU;
958 } else {
959 if (part.menu->GetDelegate()->CanDrag(part.menu)) {
960 possible_drag_ = true;
961 press_pt_ = event.location();
963 if (part.menu->HasSubmenu())
964 selection_types |= SELECTION_OPEN_SUBMENU;
966 SetSelection(part.menu, selection_types);
969 void MenuController::StartDrag(SubmenuView* source,
970 const gfx::Point& location) {
971 MenuItemView* item = state_.item;
972 DCHECK(item);
973 // Points are in the coordinates of the submenu, need to map to that of
974 // the selected item. Additionally source may not be the parent of
975 // the selected item, so need to map to screen first then to item.
976 gfx::Point press_loc(location);
977 View::ConvertPointToScreen(source->GetScrollViewContainer(), &press_loc);
978 View::ConvertPointFromScreen(item, &press_loc);
979 gfx::Point widget_loc(press_loc);
980 View::ConvertPointToWidget(item, &widget_loc);
981 scoped_ptr<gfx::Canvas> canvas(GetCanvasForDragImage(
982 source->GetWidget(), gfx::Size(item->width(), item->height())));
983 item->PaintButton(canvas.get(), MenuItemView::PB_FOR_DRAG);
985 OSExchangeData data;
986 item->GetDelegate()->WriteDragData(item, &data);
987 drag_utils::SetDragImageOnDataObject(*canvas,
988 press_loc.OffsetFromOrigin(),
989 &data);
990 StopScrolling();
991 int drag_ops = item->GetDelegate()->GetDragOperations(item);
992 did_initiate_drag_ = true;
993 // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below.
994 item->GetWidget()->RunShellDrag(NULL, data, widget_loc, drag_ops,
995 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
996 did_initiate_drag_ = false;
999 bool MenuController::OnKeyDown(ui::KeyboardCode key_code) {
1000 DCHECK(blocking_run_);
1002 switch (key_code) {
1003 case ui::VKEY_UP:
1004 IncrementSelection(-1);
1005 break;
1007 case ui::VKEY_DOWN:
1008 IncrementSelection(1);
1009 break;
1011 // Handling of VK_RIGHT and VK_LEFT is different depending on the UI
1012 // layout.
1013 case ui::VKEY_RIGHT:
1014 if (base::i18n::IsRTL())
1015 CloseSubmenu();
1016 else
1017 OpenSubmenuChangeSelectionIfCan();
1018 break;
1020 case ui::VKEY_LEFT:
1021 if (base::i18n::IsRTL())
1022 OpenSubmenuChangeSelectionIfCan();
1023 else
1024 CloseSubmenu();
1025 break;
1027 case ui::VKEY_SPACE:
1028 if (SendAcceleratorToHotTrackedView() == ACCELERATOR_PROCESSED_EXIT)
1029 return false;
1030 break;
1032 case ui::VKEY_F4:
1033 if (!is_combobox_)
1034 break;
1035 // Fallthrough to accept or dismiss combobox menus on F4, like windows.
1036 case ui::VKEY_RETURN:
1037 if (pending_state_.item) {
1038 if (pending_state_.item->HasSubmenu()) {
1039 if (key_code == ui::VKEY_F4 &&
1040 pending_state_.item->GetSubmenu()->IsShowing())
1041 return false;
1042 else
1043 OpenSubmenuChangeSelectionIfCan();
1044 } else {
1045 SendAcceleratorResultType result = SendAcceleratorToHotTrackedView();
1046 if (result == ACCELERATOR_NOT_PROCESSED &&
1047 pending_state_.item->enabled()) {
1048 Accept(pending_state_.item, 0);
1049 return false;
1050 } else if (result == ACCELERATOR_PROCESSED_EXIT) {
1051 return false;
1055 break;
1057 case ui::VKEY_ESCAPE:
1058 if (!state_.item->GetParentMenuItem() ||
1059 (!state_.item->GetParentMenuItem()->GetParentMenuItem() &&
1060 (!state_.item->HasSubmenu() ||
1061 !state_.item->GetSubmenu()->IsShowing()))) {
1062 // User pressed escape and only one menu is shown, cancel it.
1063 Cancel(EXIT_OUTERMOST);
1064 return false;
1066 CloseSubmenu();
1067 break;
1069 default:
1070 break;
1072 return true;
1075 MenuController::MenuController(ui::NativeTheme* theme,
1076 bool blocking,
1077 internal::MenuControllerDelegate* delegate)
1078 : blocking_run_(blocking),
1079 showing_(false),
1080 exit_type_(EXIT_NONE),
1081 did_capture_(false),
1082 result_(NULL),
1083 accept_event_flags_(0),
1084 drop_target_(NULL),
1085 drop_position_(MenuDelegate::DROP_UNKNOWN),
1086 owner_(NULL),
1087 possible_drag_(false),
1088 drag_in_progress_(false),
1089 did_initiate_drag_(false),
1090 valid_drop_coordinates_(false),
1091 last_drop_operation_(MenuDelegate::DROP_UNKNOWN),
1092 showing_submenu_(false),
1093 active_mouse_view_id_(ViewStorage::GetInstance()->CreateStorageID()),
1094 delegate_(delegate),
1095 message_loop_depth_(0),
1096 menu_config_(theme),
1097 closing_event_time_(base::TimeDelta()),
1098 menu_start_time_(base::TimeTicks()),
1099 is_combobox_(false),
1100 item_selected_by_touch_(false),
1101 message_loop_(MenuMessageLoop::Create()) {
1102 active_instance_ = this;
1105 MenuController::~MenuController() {
1106 DCHECK(!showing_);
1107 if (owner_)
1108 owner_->RemoveObserver(this);
1109 if (active_instance_ == this)
1110 active_instance_ = NULL;
1111 StopShowTimer();
1112 StopCancelAllTimer();
1115 void MenuController::RunMessageLoop(bool nested_menu) {
1116 message_loop_->Run(this, owner_, nested_menu);
1119 MenuController::SendAcceleratorResultType
1120 MenuController::SendAcceleratorToHotTrackedView() {
1121 CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item);
1122 if (!hot_view)
1123 return ACCELERATOR_NOT_PROCESSED;
1125 ui::Accelerator accelerator(ui::VKEY_RETURN, ui::EF_NONE);
1126 hot_view->AcceleratorPressed(accelerator);
1127 CustomButton* button = static_cast<CustomButton*>(hot_view);
1128 button->SetHotTracked(true);
1129 return (exit_type_ == EXIT_NONE) ?
1130 ACCELERATOR_PROCESSED : ACCELERATOR_PROCESSED_EXIT;
1133 void MenuController::UpdateInitialLocation(const gfx::Rect& bounds,
1134 MenuAnchorPosition position,
1135 bool context_menu) {
1136 pending_state_.context_menu = context_menu;
1137 pending_state_.initial_bounds = bounds;
1138 if (bounds.height() > 1) {
1139 // Inset the bounds slightly, otherwise drag coordinates don't line up
1140 // nicely and menus close prematurely.
1141 pending_state_.initial_bounds.Inset(0, 1);
1144 // Reverse anchor position for RTL languages.
1145 if (base::i18n::IsRTL() &&
1146 (position == MENU_ANCHOR_TOPRIGHT || position == MENU_ANCHOR_TOPLEFT)) {
1147 pending_state_.anchor = position == MENU_ANCHOR_TOPRIGHT
1148 ? MENU_ANCHOR_TOPLEFT
1149 : MENU_ANCHOR_TOPRIGHT;
1150 } else {
1151 pending_state_.anchor = position;
1154 // Calculate the bounds of the monitor we'll show menus on. Do this once to
1155 // avoid repeated system queries for the info.
1156 pending_state_.monitor_bounds = GetScreen()->GetDisplayNearestPoint(
1157 bounds.origin()).work_area();
1159 if (!pending_state_.monitor_bounds.Contains(bounds)) {
1160 // Use the monitor area if the work area doesn't contain the bounds. This
1161 // handles showing a menu from the launcher.
1162 gfx::Rect monitor_area = GetScreen()->GetDisplayNearestPoint(
1163 bounds.origin()).bounds();
1164 if (monitor_area.Contains(bounds))
1165 pending_state_.monitor_bounds = monitor_area;
1169 void MenuController::Accept(MenuItemView* item, int event_flags) {
1170 DCHECK(IsBlockingRun());
1171 result_ = item;
1172 if (item && !menu_stack_.empty() &&
1173 !item->GetDelegate()->ShouldCloseAllMenusOnExecute(item->GetCommand())) {
1174 SetExitType(EXIT_OUTERMOST);
1175 } else {
1176 SetExitType(EXIT_ALL);
1178 accept_event_flags_ = event_flags;
1181 bool MenuController::ShowSiblingMenu(SubmenuView* source,
1182 const gfx::Point& mouse_location) {
1183 if (!menu_stack_.empty() || !pressed_lock_.get())
1184 return false;
1186 View* source_view = source->GetScrollViewContainer();
1187 if (mouse_location.x() >= 0 &&
1188 mouse_location.x() < source_view->width() &&
1189 mouse_location.y() >= 0 &&
1190 mouse_location.y() < source_view->height()) {
1191 // The mouse is over the menu, no need to continue.
1192 return false;
1195 gfx::NativeWindow window_under_mouse = GetScreen()->GetWindowUnderCursor();
1196 // TODO(oshima): Replace with views only API.
1197 if (!owner_ || window_under_mouse != owner_->GetNativeWindow())
1198 return false;
1200 // The user moved the mouse outside the menu and over the owning window. See
1201 // if there is a sibling menu we should show.
1202 gfx::Point screen_point(mouse_location);
1203 View::ConvertPointToScreen(source_view, &screen_point);
1204 MenuAnchorPosition anchor;
1205 bool has_mnemonics;
1206 MenuButton* button = NULL;
1207 MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->
1208 GetSiblingMenu(source->GetMenuItem()->GetRootMenuItem(),
1209 screen_point, &anchor, &has_mnemonics, &button);
1210 if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu))
1211 return false;
1213 delegate_->SiblingMenuCreated(alt_menu);
1215 if (!button) {
1216 // If the delegate returns a menu, they must also return a button.
1217 NOTREACHED();
1218 return false;
1221 // There is a sibling menu, update the button state, hide the current menu
1222 // and show the new one.
1223 pressed_lock_.reset(new MenuButton::PressedLock(button));
1225 // Need to reset capture when we show the menu again, otherwise we aren't
1226 // going to get any events.
1227 did_capture_ = false;
1228 gfx::Point screen_menu_loc;
1229 View::ConvertPointToScreen(button, &screen_menu_loc);
1231 // It is currently not possible to show a submenu recursively in a bubble.
1232 DCHECK(!MenuItemView::IsBubble(anchor));
1233 // Subtract 1 from the height to make the popup flush with the button border.
1234 UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(),
1235 button->width(), button->height() - 1),
1236 anchor, state_.context_menu);
1237 alt_menu->PrepareForRun(
1238 false, has_mnemonics,
1239 source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_);
1240 alt_menu->controller_ = this;
1241 SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1242 return true;
1245 bool MenuController::ShowContextMenu(MenuItemView* menu_item,
1246 SubmenuView* source,
1247 const ui::LocatedEvent& event,
1248 ui::MenuSourceType source_type) {
1249 // Set the selection immediately, making sure the submenu is only open
1250 // if it already was.
1251 int selection_types = SELECTION_UPDATE_IMMEDIATELY;
1252 if (state_.item == pending_state_.item && state_.submenu_open)
1253 selection_types |= SELECTION_OPEN_SUBMENU;
1254 SetSelection(pending_state_.item, selection_types);
1255 gfx::Point loc(event.location());
1256 View::ConvertPointToScreen(source->GetScrollViewContainer(), &loc);
1258 if (menu_item->GetDelegate()->ShowContextMenu(
1259 menu_item, menu_item->GetCommand(), loc, source_type)) {
1260 SendMouseCaptureLostToActiveView();
1261 return true;
1263 return false;
1266 void MenuController::CloseAllNestedMenus() {
1267 for (std::list<NestedState>::iterator i = menu_stack_.begin();
1268 i != menu_stack_.end(); ++i) {
1269 State& state = i->first;
1270 MenuItemView* last_item = state.item;
1271 for (MenuItemView* item = last_item; item;
1272 item = item->GetParentMenuItem()) {
1273 CloseMenu(item);
1274 last_item = item;
1276 state.submenu_open = false;
1277 state.item = last_item;
1281 MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) {
1282 // Walk the view hierarchy until we find a menu item (or the root).
1283 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1284 while (child_under_mouse &&
1285 child_under_mouse->id() != MenuItemView::kMenuItemViewID) {
1286 child_under_mouse = child_under_mouse->parent();
1288 if (child_under_mouse && child_under_mouse->enabled() &&
1289 child_under_mouse->id() == MenuItemView::kMenuItemViewID) {
1290 return static_cast<MenuItemView*>(child_under_mouse);
1292 return NULL;
1295 MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) {
1296 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1297 if (child_under_mouse &&
1298 child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) {
1299 return static_cast<MenuItemView*>(child_under_mouse);
1301 return NULL;
1304 bool MenuController::IsScrollButtonAt(SubmenuView* source,
1305 int x,
1306 int y,
1307 MenuPart::Type* part) {
1308 MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer();
1309 View* child_under_mouse =
1310 scroll_view->GetEventHandlerForPoint(gfx::Point(x, y));
1311 if (child_under_mouse && child_under_mouse->enabled()) {
1312 if (child_under_mouse == scroll_view->scroll_up_button()) {
1313 *part = MenuPart::SCROLL_UP;
1314 return true;
1316 if (child_under_mouse == scroll_view->scroll_down_button()) {
1317 *part = MenuPart::SCROLL_DOWN;
1318 return true;
1321 return false;
1324 MenuController::MenuPart MenuController::GetMenuPart(
1325 SubmenuView* source,
1326 const gfx::Point& source_loc) {
1327 gfx::Point screen_loc(source_loc);
1328 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
1329 return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc);
1332 MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu(
1333 MenuItemView* item,
1334 const gfx::Point& screen_loc) {
1335 MenuPart part;
1336 for (; item; item = item->GetParentMenuItem()) {
1337 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1338 GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc,
1339 &part)) {
1340 return part;
1343 return part;
1346 bool MenuController::GetMenuPartByScreenCoordinateImpl(
1347 SubmenuView* menu,
1348 const gfx::Point& screen_loc,
1349 MenuPart* part) {
1350 // Is the mouse over the scroll buttons?
1351 gfx::Point scroll_view_loc = screen_loc;
1352 View* scroll_view_container = menu->GetScrollViewContainer();
1353 View::ConvertPointFromScreen(scroll_view_container, &scroll_view_loc);
1354 if (scroll_view_loc.x() < 0 ||
1355 scroll_view_loc.x() >= scroll_view_container->width() ||
1356 scroll_view_loc.y() < 0 ||
1357 scroll_view_loc.y() >= scroll_view_container->height()) {
1358 // Point isn't contained in menu.
1359 return false;
1361 if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(),
1362 &(part->type))) {
1363 part->submenu = menu;
1364 return true;
1367 // Not over the scroll button. Check the actual menu.
1368 if (DoesSubmenuContainLocation(menu, screen_loc)) {
1369 gfx::Point menu_loc = screen_loc;
1370 View::ConvertPointFromScreen(menu, &menu_loc);
1371 part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y());
1372 part->type = MenuPart::MENU_ITEM;
1373 part->submenu = menu;
1374 if (!part->menu)
1375 part->parent = menu->GetMenuItem();
1376 return true;
1379 // While the mouse isn't over a menu item or the scroll buttons of menu, it
1380 // is contained by menu and so we return true. If we didn't return true other
1381 // menus would be searched, even though they are likely obscured by us.
1382 return true;
1385 bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu,
1386 const gfx::Point& screen_loc) {
1387 gfx::Point view_loc = screen_loc;
1388 View::ConvertPointFromScreen(submenu, &view_loc);
1389 gfx::Rect vis_rect = submenu->GetVisibleBounds();
1390 return vis_rect.Contains(view_loc.x(), view_loc.y());
1393 void MenuController::CommitPendingSelection() {
1394 StopShowTimer();
1396 size_t paths_differ_at = 0;
1397 std::vector<MenuItemView*> current_path;
1398 std::vector<MenuItemView*> new_path;
1399 BuildPathsAndCalculateDiff(state_.item, pending_state_.item, &current_path,
1400 &new_path, &paths_differ_at);
1402 // Hide the old menu.
1403 for (size_t i = paths_differ_at; i < current_path.size(); ++i) {
1404 if (current_path[i]->HasSubmenu()) {
1405 current_path[i]->GetSubmenu()->Hide();
1409 // Copy pending to state_, making sure to preserve the direction menus were
1410 // opened.
1411 std::list<bool> pending_open_direction;
1412 state_.open_leading.swap(pending_open_direction);
1413 state_ = pending_state_;
1414 state_.open_leading.swap(pending_open_direction);
1416 int menu_depth = MenuDepth(state_.item);
1417 if (menu_depth == 0) {
1418 state_.open_leading.clear();
1419 } else {
1420 int cached_size = static_cast<int>(state_.open_leading.size());
1421 DCHECK_GE(menu_depth, 0);
1422 while (cached_size-- >= menu_depth)
1423 state_.open_leading.pop_back();
1426 if (!state_.item) {
1427 // Nothing to select.
1428 StopScrolling();
1429 return;
1432 // Open all the submenus preceeding the last menu item (last menu item is
1433 // handled next).
1434 if (new_path.size() > 1) {
1435 for (std::vector<MenuItemView*>::iterator i = new_path.begin();
1436 i != new_path.end() - 1; ++i) {
1437 OpenMenu(*i);
1441 if (state_.submenu_open) {
1442 // The submenu should be open, open the submenu if the item has a submenu.
1443 if (state_.item->HasSubmenu()) {
1444 OpenMenu(state_.item);
1445 } else {
1446 state_.submenu_open = false;
1448 } else if (state_.item->HasSubmenu() &&
1449 state_.item->GetSubmenu()->IsShowing()) {
1450 state_.item->GetSubmenu()->Hide();
1453 if (scroll_task_.get() && scroll_task_->submenu()) {
1454 // Stop the scrolling if none of the elements of the selection contain
1455 // the menu being scrolled.
1456 bool found = false;
1457 for (MenuItemView* item = state_.item; item && !found;
1458 item = item->GetParentMenuItem()) {
1459 found = (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1460 item->GetSubmenu() == scroll_task_->submenu());
1462 if (!found)
1463 StopScrolling();
1467 void MenuController::CloseMenu(MenuItemView* item) {
1468 DCHECK(item);
1469 if (!item->HasSubmenu())
1470 return;
1471 item->GetSubmenu()->Hide();
1474 void MenuController::OpenMenu(MenuItemView* item) {
1475 DCHECK(item);
1476 if (item->GetSubmenu()->IsShowing()) {
1477 return;
1480 OpenMenuImpl(item, true);
1481 did_capture_ = true;
1484 void MenuController::OpenMenuImpl(MenuItemView* item, bool show) {
1485 // TODO(oshima|sky): Don't show the menu if drag is in progress and
1486 // this menu doesn't support drag drop. See crbug.com/110495.
1487 if (show) {
1488 int old_count = item->GetSubmenu()->child_count();
1489 item->GetDelegate()->WillShowMenu(item);
1490 if (old_count != item->GetSubmenu()->child_count()) {
1491 // If the number of children changed then we may need to add empty items.
1492 item->AddEmptyMenus();
1495 bool prefer_leading =
1496 state_.open_leading.empty() ? true : state_.open_leading.back();
1497 bool resulting_direction;
1498 gfx::Rect bounds = MenuItemView::IsBubble(state_.anchor) ?
1499 CalculateBubbleMenuBounds(item, prefer_leading, &resulting_direction) :
1500 CalculateMenuBounds(item, prefer_leading, &resulting_direction);
1501 state_.open_leading.push_back(resulting_direction);
1502 bool do_capture = (!did_capture_ && blocking_run_);
1503 showing_submenu_ = true;
1504 if (show) {
1505 // Menus are the only place using kGroupingPropertyKey, so any value (other
1506 // than 0) is fine.
1507 const int kGroupingId = 1001;
1508 item->GetSubmenu()->ShowAt(owner_, bounds, do_capture);
1509 item->GetSubmenu()->GetWidget()->SetNativeWindowProperty(
1510 TooltipManager::kGroupingPropertyKey,
1511 reinterpret_cast<void*>(kGroupingId));
1512 } else {
1513 item->GetSubmenu()->Reposition(bounds);
1515 showing_submenu_ = false;
1518 void MenuController::MenuChildrenChanged(MenuItemView* item) {
1519 DCHECK(item);
1520 // Menu shouldn't be updated during drag operation.
1521 DCHECK(!GetActiveMouseView());
1523 // If the current item or pending item is a descendant of the item
1524 // that changed, move the selection back to the changed item.
1525 const MenuItemView* ancestor = state_.item;
1526 while (ancestor && ancestor != item)
1527 ancestor = ancestor->GetParentMenuItem();
1528 if (!ancestor) {
1529 ancestor = pending_state_.item;
1530 while (ancestor && ancestor != item)
1531 ancestor = ancestor->GetParentMenuItem();
1532 if (!ancestor)
1533 return;
1535 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1536 if (item->HasSubmenu())
1537 OpenMenuImpl(item, false);
1540 void MenuController::BuildPathsAndCalculateDiff(
1541 MenuItemView* old_item,
1542 MenuItemView* new_item,
1543 std::vector<MenuItemView*>* old_path,
1544 std::vector<MenuItemView*>* new_path,
1545 size_t* first_diff_at) {
1546 DCHECK(old_path && new_path && first_diff_at);
1547 BuildMenuItemPath(old_item, old_path);
1548 BuildMenuItemPath(new_item, new_path);
1550 size_t common_size = std::min(old_path->size(), new_path->size());
1552 // Find the first difference between the two paths, when the loop
1553 // returns, diff_i is the first index where the two paths differ.
1554 for (size_t i = 0; i < common_size; ++i) {
1555 if ((*old_path)[i] != (*new_path)[i]) {
1556 *first_diff_at = i;
1557 return;
1561 *first_diff_at = common_size;
1564 void MenuController::BuildMenuItemPath(MenuItemView* item,
1565 std::vector<MenuItemView*>* path) {
1566 if (!item)
1567 return;
1568 BuildMenuItemPath(item->GetParentMenuItem(), path);
1569 path->push_back(item);
1572 void MenuController::StartShowTimer() {
1573 show_timer_.Start(FROM_HERE,
1574 TimeDelta::FromMilliseconds(menu_config_.show_delay),
1575 this, &MenuController::CommitPendingSelection);
1578 void MenuController::StopShowTimer() {
1579 show_timer_.Stop();
1582 void MenuController::StartCancelAllTimer() {
1583 cancel_all_timer_.Start(FROM_HERE,
1584 TimeDelta::FromMilliseconds(kCloseOnExitTime),
1585 this, &MenuController::CancelAll);
1588 void MenuController::StopCancelAllTimer() {
1589 cancel_all_timer_.Stop();
1592 gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item,
1593 bool prefer_leading,
1594 bool* is_leading) {
1595 DCHECK(item);
1597 SubmenuView* submenu = item->GetSubmenu();
1598 DCHECK(submenu);
1600 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1602 // Don't let the menu go too wide.
1603 pref.set_width(std::min(pref.width(),
1604 item->GetDelegate()->GetMaxWidthForMenu(item)));
1605 if (!state_.monitor_bounds.IsEmpty())
1606 pref.set_width(std::min(pref.width(), state_.monitor_bounds.width()));
1608 // Assume we can honor prefer_leading.
1609 *is_leading = prefer_leading;
1611 int x, y;
1613 const MenuConfig& menu_config = item->GetMenuConfig();
1615 if (!item->GetParentMenuItem()) {
1616 // First item, position relative to initial location.
1617 x = state_.initial_bounds.x();
1619 // Offsets for context menu prevent menu items being selected by
1620 // simply opening the menu (bug 142992).
1621 if (menu_config.offset_context_menus && state_.context_menu)
1622 x += 1;
1624 y = state_.initial_bounds.bottom();
1625 if (state_.anchor == MENU_ANCHOR_TOPRIGHT) {
1626 x = x + state_.initial_bounds.width() - pref.width();
1627 if (menu_config.offset_context_menus && state_.context_menu)
1628 x -= 1;
1629 } else if (state_.anchor == MENU_ANCHOR_BOTTOMCENTER) {
1630 x = x - (pref.width() - state_.initial_bounds.width()) / 2;
1631 if (pref.height() >
1632 state_.initial_bounds.y() + kCenteredContextMenuYOffset) {
1633 // Menu does not fit above the anchor. We move it to below.
1634 y = state_.initial_bounds.y() - kCenteredContextMenuYOffset;
1635 } else {
1636 y = std::max(0, state_.initial_bounds.y() - pref.height()) +
1637 kCenteredContextMenuYOffset;
1641 if (!state_.monitor_bounds.IsEmpty() &&
1642 y + pref.height() > state_.monitor_bounds.bottom()) {
1643 // The menu doesn't fit fully below the button on the screen. The menu
1644 // position with respect to the bounds will be preserved if it has
1645 // already been drawn. When the requested positioning is below the bounds
1646 // it will shrink the menu to make it fit below.
1647 // If the requested positioning is best fit, it will first try to fit the
1648 // menu below. If that does not fit it will try to place it above. If
1649 // that will not fit it will place it at the bottom of the work area and
1650 // moving it off the initial_bounds region to avoid overlap.
1651 // In all other requested position styles it will be flipped above and
1652 // the height will be shrunken to the usable height.
1653 if (item->actual_menu_position() == MenuItemView::POSITION_BELOW_BOUNDS) {
1654 pref.set_height(std::min(pref.height(),
1655 state_.monitor_bounds.bottom() - y));
1656 } else if (item->actual_menu_position() ==
1657 MenuItemView::POSITION_BEST_FIT) {
1658 MenuItemView::MenuPosition orientation =
1659 MenuItemView::POSITION_BELOW_BOUNDS;
1660 if (state_.monitor_bounds.height() < pref.height()) {
1661 // Handle very tall menus.
1662 pref.set_height(state_.monitor_bounds.height());
1663 y = state_.monitor_bounds.y();
1664 } else if (state_.monitor_bounds.y() + pref.height() <
1665 state_.initial_bounds.y()) {
1666 // Flipping upwards if there is enough space.
1667 y = state_.initial_bounds.y() - pref.height();
1668 orientation = MenuItemView::POSITION_ABOVE_BOUNDS;
1669 } else {
1670 // It is allowed to move the menu a bit around in order to get the
1671 // best fit and to avoid showing scroll elements.
1672 y = state_.monitor_bounds.bottom() - pref.height();
1674 if (orientation == MenuItemView::POSITION_BELOW_BOUNDS) {
1675 // The menu should never overlap the owning button. So move it.
1676 // We use the anchor view style to determine the preferred position
1677 // relative to the owning button.
1678 if (state_.anchor == MENU_ANCHOR_TOPLEFT) {
1679 // The menu starts with the same x coordinate as the owning button.
1680 if (x + state_.initial_bounds.width() + pref.width() >
1681 state_.monitor_bounds.right())
1682 x -= pref.width(); // Move the menu to the left of the button.
1683 else
1684 x += state_.initial_bounds.width(); // Move the menu right.
1685 } else {
1686 // The menu should end with the same x coordinate as the owning
1687 // button.
1688 if (state_.monitor_bounds.x() >
1689 state_.initial_bounds.x() - pref.width())
1690 x = state_.initial_bounds.right(); // Move right of the button.
1691 else
1692 x = state_.initial_bounds.x() - pref.width(); // Move left.
1695 item->set_actual_menu_position(orientation);
1696 } else {
1697 pref.set_height(std::min(pref.height(),
1698 state_.initial_bounds.y() - state_.monitor_bounds.y()));
1699 y = state_.initial_bounds.y() - pref.height();
1700 item->set_actual_menu_position(MenuItemView::POSITION_ABOVE_BOUNDS);
1702 } else if (item->actual_menu_position() ==
1703 MenuItemView::POSITION_ABOVE_BOUNDS) {
1704 pref.set_height(std::min(pref.height(),
1705 state_.initial_bounds.y() - state_.monitor_bounds.y()));
1706 y = state_.initial_bounds.y() - pref.height();
1707 } else {
1708 item->set_actual_menu_position(MenuItemView::POSITION_BELOW_BOUNDS);
1710 if (state_.monitor_bounds.width() != 0 &&
1711 menu_config.offset_context_menus && state_.context_menu) {
1712 if (x + pref.width() > state_.monitor_bounds.right())
1713 x = state_.initial_bounds.x() - pref.width() - 1;
1714 if (x < state_.monitor_bounds.x())
1715 x = state_.monitor_bounds.x();
1717 } else {
1718 // Not the first menu; position it relative to the bounds of the menu
1719 // item.
1720 gfx::Point item_loc;
1721 View::ConvertPointToScreen(item, &item_loc);
1723 // We must make sure we take into account the UI layout. If the layout is
1724 // RTL, then a 'leading' menu is positioned to the left of the parent menu
1725 // item and not to the right.
1726 bool layout_is_rtl = base::i18n::IsRTL();
1727 bool create_on_the_right = (prefer_leading && !layout_is_rtl) ||
1728 (!prefer_leading && layout_is_rtl);
1729 int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;
1731 if (create_on_the_right) {
1732 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1733 if (state_.monitor_bounds.width() != 0 &&
1734 x + pref.width() > state_.monitor_bounds.right()) {
1735 if (layout_is_rtl)
1736 *is_leading = true;
1737 else
1738 *is_leading = false;
1739 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1741 } else {
1742 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1743 if (state_.monitor_bounds.width() != 0 && x < state_.monitor_bounds.x()) {
1744 if (layout_is_rtl)
1745 *is_leading = false;
1746 else
1747 *is_leading = true;
1748 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1751 y = item_loc.y() - menu_config.menu_vertical_border_size;
1752 if (state_.monitor_bounds.width() != 0) {
1753 pref.set_height(std::min(pref.height(), state_.monitor_bounds.height()));
1754 if (y + pref.height() > state_.monitor_bounds.bottom())
1755 y = state_.monitor_bounds.bottom() - pref.height();
1756 if (y < state_.monitor_bounds.y())
1757 y = state_.monitor_bounds.y();
1761 if (state_.monitor_bounds.width() != 0) {
1762 if (x + pref.width() > state_.monitor_bounds.right())
1763 x = state_.monitor_bounds.right() - pref.width();
1764 if (x < state_.monitor_bounds.x())
1765 x = state_.monitor_bounds.x();
1767 return gfx::Rect(x, y, pref.width(), pref.height());
1770 gfx::Rect MenuController::CalculateBubbleMenuBounds(MenuItemView* item,
1771 bool prefer_leading,
1772 bool* is_leading) {
1773 DCHECK(item);
1774 DCHECK(!item->GetParentMenuItem());
1776 // Assume we can honor prefer_leading.
1777 *is_leading = prefer_leading;
1779 SubmenuView* submenu = item->GetSubmenu();
1780 DCHECK(submenu);
1782 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1783 const gfx::Rect& owner_bounds = pending_state_.initial_bounds;
1785 // First the size gets reduced to the possible space.
1786 if (!state_.monitor_bounds.IsEmpty()) {
1787 int max_width = state_.monitor_bounds.width();
1788 int max_height = state_.monitor_bounds.height();
1789 // In case of bubbles, the maximum width is limited by the space
1790 // between the display corner and the target area + the tip size.
1791 if (state_.anchor == MENU_ANCHOR_BUBBLE_LEFT) {
1792 max_width = owner_bounds.x() - state_.monitor_bounds.x() +
1793 kBubbleTipSizeLeftRight;
1794 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT) {
1795 max_width = state_.monitor_bounds.right() - owner_bounds.right() +
1796 kBubbleTipSizeLeftRight;
1797 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE) {
1798 max_height = owner_bounds.y() - state_.monitor_bounds.y() +
1799 kBubbleTipSizeTopBottom;
1800 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1801 max_height = state_.monitor_bounds.bottom() - owner_bounds.bottom() +
1802 kBubbleTipSizeTopBottom;
1804 // The space for the menu to cover should never get empty.
1805 DCHECK_GE(max_width, kBubbleTipSizeLeftRight);
1806 DCHECK_GE(max_height, kBubbleTipSizeTopBottom);
1807 pref.set_width(std::min(pref.width(), max_width));
1808 pref.set_height(std::min(pref.height(), max_height));
1810 // Also make sure that the menu does not go too wide.
1811 pref.set_width(std::min(pref.width(),
1812 item->GetDelegate()->GetMaxWidthForMenu(item)));
1814 int x, y;
1815 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE ||
1816 state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1817 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE)
1818 y = owner_bounds.y() - pref.height() + kBubbleTipSizeTopBottom;
1819 else
1820 y = owner_bounds.bottom() - kBubbleTipSizeTopBottom;
1822 x = owner_bounds.CenterPoint().x() - pref.width() / 2;
1823 int x_old = x;
1824 if (x < state_.monitor_bounds.x()) {
1825 x = state_.monitor_bounds.x();
1826 } else if (x + pref.width() > state_.monitor_bounds.right()) {
1827 x = state_.monitor_bounds.right() - pref.width();
1829 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1830 pref.width() / 2 - x + x_old);
1831 } else {
1832 if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT)
1833 x = owner_bounds.right() - kBubbleTipSizeLeftRight;
1834 else
1835 x = owner_bounds.x() - pref.width() + kBubbleTipSizeLeftRight;
1837 y = owner_bounds.CenterPoint().y() - pref.height() / 2;
1838 int y_old = y;
1839 if (y < state_.monitor_bounds.y()) {
1840 y = state_.monitor_bounds.y();
1841 } else if (y + pref.height() > state_.monitor_bounds.bottom()) {
1842 y = state_.monitor_bounds.bottom() - pref.height();
1844 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1845 pref.height() / 2 - y + y_old);
1847 return gfx::Rect(x, y, pref.width(), pref.height());
1850 // static
1851 int MenuController::MenuDepth(MenuItemView* item) {
1852 return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : 0;
1855 void MenuController::IncrementSelection(int delta) {
1856 MenuItemView* item = pending_state_.item;
1857 DCHECK(item);
1858 if (pending_state_.submenu_open && item->HasSubmenu() &&
1859 item->GetSubmenu()->IsShowing()) {
1860 // A menu is selected and open, but none of its children are selected,
1861 // select the first menu item.
1862 if (item->GetSubmenu()->GetMenuItemCount()) {
1863 SetSelection(item->GetSubmenu()->GetMenuItemAt(0), SELECTION_DEFAULT);
1864 return;
1868 if (item->has_children()) {
1869 CustomButton* button = GetFirstHotTrackedView(item);
1870 if (button) {
1871 button->SetHotTracked(false);
1872 View* to_make_hot = GetNextFocusableView(item, button, delta == 1);
1873 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1874 if (button_hot) {
1875 button_hot->SetHotTracked(true);
1876 return;
1878 } else {
1879 View* to_make_hot = GetInitialFocusableView(item, delta == 1);
1880 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1881 if (button_hot) {
1882 button_hot->SetHotTracked(true);
1883 return;
1888 MenuItemView* parent = item->GetParentMenuItem();
1889 if (parent) {
1890 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1891 if (parent_count > 1) {
1892 for (int i = 0; i < parent_count; ++i) {
1893 if (parent->GetSubmenu()->GetMenuItemAt(i) == item) {
1894 MenuItemView* to_select =
1895 FindNextSelectableMenuItem(parent, i, delta);
1896 if (!to_select)
1897 break;
1898 SetSelection(to_select, SELECTION_DEFAULT);
1899 View* to_make_hot = GetInitialFocusableView(to_select, delta == 1);
1900 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1901 if (button_hot)
1902 button_hot->SetHotTracked(true);
1903 break;
1910 MenuItemView* MenuController::FindNextSelectableMenuItem(MenuItemView* parent,
1911 int index,
1912 int delta) {
1913 int start_index = index;
1914 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1915 // Loop through the menu items skipping any invisible menus. The loop stops
1916 // when we wrap or find a visible child.
1917 do {
1918 index = (index + delta + parent_count) % parent_count;
1919 if (index == start_index)
1920 return NULL;
1921 MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
1922 if (child->visible())
1923 return child;
1924 } while (index != start_index);
1925 return NULL;
1928 void MenuController::OpenSubmenuChangeSelectionIfCan() {
1929 MenuItemView* item = pending_state_.item;
1930 if (item->HasSubmenu() && item->enabled()) {
1931 if (item->GetSubmenu()->GetMenuItemCount() > 0) {
1932 SetSelection(item->GetSubmenu()->GetMenuItemAt(0),
1933 SELECTION_UPDATE_IMMEDIATELY);
1934 } else {
1935 // No menu items, just show the sub-menu.
1936 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1941 void MenuController::CloseSubmenu() {
1942 MenuItemView* item = state_.item;
1943 DCHECK(item);
1944 if (!item->GetParentMenuItem())
1945 return;
1946 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing())
1947 SetSelection(item, SELECTION_UPDATE_IMMEDIATELY);
1948 else if (item->GetParentMenuItem()->GetParentMenuItem())
1949 SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY);
1952 MenuController::SelectByCharDetails MenuController::FindChildForMnemonic(
1953 MenuItemView* parent,
1954 base::char16 key,
1955 bool (*match_function)(MenuItemView* menu, base::char16 mnemonic)) {
1956 SubmenuView* submenu = parent->GetSubmenu();
1957 DCHECK(submenu);
1958 SelectByCharDetails details;
1960 for (int i = 0, menu_item_count = submenu->GetMenuItemCount();
1961 i < menu_item_count; ++i) {
1962 MenuItemView* child = submenu->GetMenuItemAt(i);
1963 if (child->enabled() && child->visible()) {
1964 if (child == pending_state_.item)
1965 details.index_of_item = i;
1966 if (match_function(child, key)) {
1967 if (details.first_match == -1)
1968 details.first_match = i;
1969 else
1970 details.has_multiple = true;
1971 if (details.next_match == -1 && details.index_of_item != -1 &&
1972 i > details.index_of_item)
1973 details.next_match = i;
1977 return details;
1980 bool MenuController::AcceptOrSelect(MenuItemView* parent,
1981 const SelectByCharDetails& details) {
1982 // This should only be invoked if there is a match.
1983 DCHECK(details.first_match != -1);
1984 DCHECK(parent->HasSubmenu());
1985 SubmenuView* submenu = parent->GetSubmenu();
1986 DCHECK(submenu);
1987 if (!details.has_multiple) {
1988 // There's only one match, activate it (or open if it has a submenu).
1989 if (submenu->GetMenuItemAt(details.first_match)->HasSubmenu()) {
1990 SetSelection(submenu->GetMenuItemAt(details.first_match),
1991 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1992 } else {
1993 Accept(submenu->GetMenuItemAt(details.first_match), 0);
1994 return true;
1996 } else if (details.index_of_item == -1 || details.next_match == -1) {
1997 SetSelection(submenu->GetMenuItemAt(details.first_match),
1998 SELECTION_DEFAULT);
1999 } else {
2000 SetSelection(submenu->GetMenuItemAt(details.next_match),
2001 SELECTION_DEFAULT);
2003 return false;
2006 bool MenuController::SelectByChar(base::char16 character) {
2007 base::char16 char_array[] = { character, 0 };
2008 base::char16 key = base::i18n::ToLower(char_array)[0];
2009 MenuItemView* item = pending_state_.item;
2010 if (!item->HasSubmenu() || !item->GetSubmenu()->IsShowing())
2011 item = item->GetParentMenuItem();
2012 DCHECK(item);
2013 DCHECK(item->HasSubmenu());
2014 DCHECK(item->GetSubmenu());
2015 if (item->GetSubmenu()->GetMenuItemCount() == 0)
2016 return false;
2018 // Look for matches based on mnemonic first.
2019 SelectByCharDetails details =
2020 FindChildForMnemonic(item, key, &MatchesMnemonic);
2021 if (details.first_match != -1)
2022 return AcceptOrSelect(item, details);
2024 if (is_combobox_) {
2025 item->GetSubmenu()->GetTextInputClient()->InsertChar(character, 0);
2026 } else {
2027 // If no mnemonics found, look at first character of titles.
2028 details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic);
2029 if (details.first_match != -1)
2030 return AcceptOrSelect(item, details);
2033 return false;
2036 void MenuController::RepostEvent(SubmenuView* source,
2037 const ui::LocatedEvent& event) {
2038 if (!event.IsMouseEvent()) {
2039 // TODO(rbyers): Gesture event repost is tricky to get right
2040 // crbug.com/170987.
2041 DCHECK(event.IsGestureEvent());
2042 return;
2045 #if defined(OS_WIN)
2046 if (!state_.item) {
2047 // We some times get an event after closing all the menus. Ignore it. Make
2048 // sure the menu is in fact not visible. If the menu is visible, then
2049 // we're in a bad state where we think the menu isn't visibile but it is.
2050 DCHECK(!source->GetWidget()->IsVisible());
2051 return;
2054 state_.item->GetRootMenuItem()->GetSubmenu()->ReleaseCapture();
2055 #endif
2057 gfx::Point screen_loc(event.location());
2058 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
2059 gfx::NativeView native_view = source->GetWidget()->GetNativeView();
2060 if (!native_view)
2061 return;
2063 gfx::Screen* screen = gfx::Screen::GetScreenFor(native_view);
2064 gfx::NativeWindow window = screen->GetWindowAtScreenPoint(screen_loc);
2066 #if defined(OS_WIN)
2067 // Convert screen_loc to pixels for the Win32 API's like WindowFromPoint,
2068 // PostMessage/SendMessage to work correctly. These API's expect the
2069 // coordinates to be in pixels.
2070 // PostMessage() to metro windows isn't allowed (access will be denied). Don't
2071 // try to repost with Win32 if the window under the mouse press is in metro.
2072 if (!ViewsDelegate::views_delegate ||
2073 !ViewsDelegate::views_delegate->IsWindowInMetro(window)) {
2074 gfx::Point screen_loc_pixels = gfx::win::DIPToScreenPoint(screen_loc);
2075 HWND target_window = window ? HWNDForNativeWindow(window) :
2076 WindowFromPoint(screen_loc_pixels.ToPOINT());
2077 HWND source_window = HWNDForNativeView(native_view);
2078 if (!target_window || !source_window ||
2079 GetWindowThreadProcessId(source_window, NULL) !=
2080 GetWindowThreadProcessId(target_window, NULL)) {
2081 // Even though we have mouse capture, windows generates a mouse event if
2082 // the other window is in a separate thread. Only repost an event if
2083 // |target_window| and |source_window| were created on the same thread,
2084 // else double events can occur and lead to bad behavior.
2085 return;
2088 // Determine whether the click was in the client area or not.
2089 // NOTE: WM_NCHITTEST coordinates are relative to the screen.
2090 LPARAM coords = MAKELPARAM(screen_loc_pixels.x(), screen_loc_pixels.y());
2091 LRESULT nc_hit_result = SendMessage(target_window, WM_NCHITTEST, 0, coords);
2092 const bool client_area = nc_hit_result == HTCLIENT;
2094 // TODO(sky): this isn't right. The event to generate should correspond with
2095 // the event we just got. MouseEvent only tells us what is down, which may
2096 // differ. Need to add ability to get changed button from MouseEvent.
2097 int event_type;
2098 int flags = event.flags();
2099 if (flags & ui::EF_LEFT_MOUSE_BUTTON) {
2100 event_type = client_area ? WM_LBUTTONDOWN : WM_NCLBUTTONDOWN;
2101 } else if (flags & ui::EF_MIDDLE_MOUSE_BUTTON) {
2102 event_type = client_area ? WM_MBUTTONDOWN : WM_NCMBUTTONDOWN;
2103 } else if (flags & ui::EF_RIGHT_MOUSE_BUTTON) {
2104 event_type = client_area ? WM_RBUTTONDOWN : WM_NCRBUTTONDOWN;
2105 } else {
2106 NOTREACHED();
2107 return;
2110 int window_x = screen_loc_pixels.x();
2111 int window_y = screen_loc_pixels.y();
2112 if (client_area) {
2113 POINT pt = { window_x, window_y };
2114 ScreenToClient(target_window, &pt);
2115 window_x = pt.x;
2116 window_y = pt.y;
2119 WPARAM target = client_area ? event.native_event().wParam : nc_hit_result;
2120 LPARAM window_coords = MAKELPARAM(window_x, window_y);
2121 PostMessage(target_window, event_type, target, window_coords);
2122 return;
2124 #endif
2125 // Non-Windows Aura or |window| is in metro mode.
2126 if (!window)
2127 return;
2129 message_loop_->RepostEventToWindow(event, window, screen_loc);
2132 void MenuController::SetDropMenuItem(
2133 MenuItemView* new_target,
2134 MenuDelegate::DropPosition new_position) {
2135 if (new_target == drop_target_ && new_position == drop_position_)
2136 return;
2138 if (drop_target_) {
2139 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2140 NULL, MenuDelegate::DROP_NONE);
2142 drop_target_ = new_target;
2143 drop_position_ = new_position;
2144 if (drop_target_) {
2145 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2146 drop_target_, drop_position_);
2150 void MenuController::UpdateScrolling(const MenuPart& part) {
2151 if (!part.is_scroll() && !scroll_task_.get())
2152 return;
2154 if (!scroll_task_.get())
2155 scroll_task_.reset(new MenuScrollTask());
2156 scroll_task_->Update(part);
2159 void MenuController::StopScrolling() {
2160 scroll_task_.reset(NULL);
2163 void MenuController::UpdateActiveMouseView(SubmenuView* event_source,
2164 const ui::MouseEvent& event,
2165 View* target_menu) {
2166 View* target = NULL;
2167 gfx::Point target_menu_loc(event.location());
2168 if (target_menu && target_menu->has_children()) {
2169 // Locate the deepest child view to send events to. This code assumes we
2170 // don't have to walk up the tree to find a view interested in events. This
2171 // is currently true for the cases we are embedding views, but if we embed
2172 // more complex hierarchies it'll need to change.
2173 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2174 &target_menu_loc);
2175 View::ConvertPointFromScreen(target_menu, &target_menu_loc);
2176 target = target_menu->GetEventHandlerForPoint(target_menu_loc);
2177 if (target == target_menu || !target->enabled())
2178 target = NULL;
2180 View* active_mouse_view = GetActiveMouseView();
2181 if (target != active_mouse_view) {
2182 SendMouseCaptureLostToActiveView();
2183 active_mouse_view = target;
2184 SetActiveMouseView(active_mouse_view);
2185 if (active_mouse_view) {
2186 gfx::Point target_point(target_menu_loc);
2187 View::ConvertPointToTarget(
2188 target_menu, active_mouse_view, &target_point);
2189 ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED,
2190 target_point, target_point,
2191 0, 0);
2192 active_mouse_view->OnMouseEntered(mouse_entered_event);
2194 ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED,
2195 target_point, target_point,
2196 event.flags(),
2197 event.changed_button_flags());
2198 active_mouse_view->OnMousePressed(mouse_pressed_event);
2202 if (active_mouse_view) {
2203 gfx::Point target_point(target_menu_loc);
2204 View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point);
2205 ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED,
2206 target_point, target_point,
2207 event.flags(),
2208 event.changed_button_flags());
2209 active_mouse_view->OnMouseDragged(mouse_dragged_event);
2213 void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source,
2214 const ui::MouseEvent& event) {
2215 View* active_mouse_view = GetActiveMouseView();
2216 if (!active_mouse_view)
2217 return;
2219 gfx::Point target_loc(event.location());
2220 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2221 &target_loc);
2222 View::ConvertPointFromScreen(active_mouse_view, &target_loc);
2223 ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, target_loc, target_loc,
2224 event.flags(), event.changed_button_flags());
2225 // Reset active mouse view before sending mouse released. That way if it calls
2226 // back to us, we aren't in a weird state.
2227 SetActiveMouseView(NULL);
2228 active_mouse_view->OnMouseReleased(release_event);
2231 void MenuController::SendMouseCaptureLostToActiveView() {
2232 View* active_mouse_view = GetActiveMouseView();
2233 if (!active_mouse_view)
2234 return;
2236 // Reset the active_mouse_view_ before sending mouse capture lost. That way if
2237 // it calls back to us, we aren't in a weird state.
2238 SetActiveMouseView(NULL);
2239 active_mouse_view->OnMouseCaptureLost();
2242 void MenuController::SetActiveMouseView(View* view) {
2243 if (view)
2244 ViewStorage::GetInstance()->StoreView(active_mouse_view_id_, view);
2245 else
2246 ViewStorage::GetInstance()->RemoveView(active_mouse_view_id_);
2249 View* MenuController::GetActiveMouseView() {
2250 return ViewStorage::GetInstance()->RetrieveView(active_mouse_view_id_);
2253 void MenuController::SetExitType(ExitType type) {
2254 exit_type_ = type;
2255 // Exit nested message loops as soon as possible. We do this as
2256 // MessagePumpDispatcher is only invoked before native events, which means
2257 // its entirely possible for a Widget::CloseNow() task to be processed before
2258 // the next native message. We quite the nested message loop as soon as
2259 // possible to avoid having deleted views classes (such as widgets and
2260 // rootviews) on the stack when the nested message loop stops.
2262 // It's safe to invoke QuitNestedMessageLoop() multiple times, it only effects
2263 // the current loop.
2264 bool quit_now = message_loop_->ShouldQuitNow() && exit_type_ != EXIT_NONE &&
2265 message_loop_depth_;
2266 if (quit_now)
2267 TerminateNestedMessageLoop();
2270 void MenuController::TerminateNestedMessageLoop() {
2271 message_loop_->QuitNow();
2274 void MenuController::HandleMouseLocation(SubmenuView* source,
2275 const gfx::Point& mouse_location) {
2276 if (showing_submenu_)
2277 return;
2279 // Ignore mouse events if we're closing the menu.
2280 if (exit_type_ != EXIT_NONE)
2281 return;
2283 MenuPart part = GetMenuPart(source, mouse_location);
2285 UpdateScrolling(part);
2287 if (!blocking_run_)
2288 return;
2290 if (part.type == MenuPart::NONE && ShowSiblingMenu(source, mouse_location))
2291 return;
2293 if (part.type == MenuPart::MENU_ITEM && part.menu) {
2294 SetSelection(part.menu, SELECTION_OPEN_SUBMENU);
2295 } else if (!part.is_scroll() && pending_state_.item &&
2296 pending_state_.item->GetParentMenuItem() &&
2297 (!pending_state_.item->HasSubmenu() ||
2298 !pending_state_.item->GetSubmenu()->IsShowing())) {
2299 // On exit if the user hasn't selected an item with a submenu, move the
2300 // selection back to the parent menu item.
2301 SetSelection(pending_state_.item->GetParentMenuItem(),
2302 SELECTION_OPEN_SUBMENU);
2306 gfx::Screen* MenuController::GetScreen() {
2307 Widget* root = owner_ ? owner_->GetTopLevelWidget() : NULL;
2308 return root ? gfx::Screen::GetScreenFor(root->GetNativeView())
2309 : gfx::Screen::GetNativeScreen();
2312 } // namespace views