Roll src/third_party/skia d32087a:1052f51
[chromium-blink-merge.git] / ui / views / controls / menu / menu_controller.cc
blob53fa52c30564458e8089bf446a099a51cb69e7eb
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/geometry/vector2d.h"
18 #include "ui/gfx/native_widget_types.h"
19 #include "ui/gfx/screen.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 // Returns the first descendant of |view| that is hot tracked.
93 static CustomButton* GetFirstHotTrackedView(View* view) {
94 if (!view)
95 return NULL;
96 CustomButton* button = CustomButton::AsCustomButton(view);
97 if (button) {
98 if (button->IsHotTracked())
99 return button;
102 for (int i = 0; i < view->child_count(); ++i) {
103 CustomButton* hot_view = GetFirstHotTrackedView(view->child_at(i));
104 if (hot_view)
105 return hot_view;
107 return NULL;
110 // Recurses through the child views of |view| returning the first view starting
111 // at |start| that is focusable. A value of -1 for |start| indicates to start at
112 // the first view (if |forward| is false, iterating starts at the last view). If
113 // |forward| is true the children are considered first to last, otherwise last
114 // to first.
115 static View* GetFirstFocusableView(View* view, int start, bool forward) {
116 if (forward) {
117 for (int i = start == -1 ? 0 : start; i < view->child_count(); ++i) {
118 View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
119 if (deepest)
120 return deepest;
122 } else {
123 for (int i = start == -1 ? view->child_count() - 1 : start; i >= 0; --i) {
124 View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
125 if (deepest)
126 return deepest;
129 return view->IsFocusable() ? view : NULL;
132 // Returns the first child of |start| that is focusable.
133 static View* GetInitialFocusableView(View* start, bool forward) {
134 return GetFirstFocusableView(start, -1, forward);
137 // Returns the next view after |start_at| that is focusable. Returns NULL if
138 // there are no focusable children of |ancestor| after |start_at|.
139 static View* GetNextFocusableView(View* ancestor,
140 View* start_at,
141 bool forward) {
142 DCHECK(ancestor->Contains(start_at));
143 View* parent = start_at;
144 do {
145 View* new_parent = parent->parent();
146 int index = new_parent->GetIndexOf(parent);
147 index += forward ? 1 : -1;
148 if (forward || index != -1) {
149 View* next = GetFirstFocusableView(new_parent, index, forward);
150 if (next)
151 return next;
153 parent = new_parent;
154 } while (parent != ancestor);
155 return NULL;
158 } // namespace
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::GetInstance())
365 ViewsDelegate::GetInstance()->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::GetInstance())
377 ViewsDelegate::GetInstance()->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);
437 } else if (exit_type_ != EXIT_NONE && message_loop_depth_) {
438 // If we're closing all menus, also mark the next topmost menu
439 // message loop for termination, so that we'll unwind fully.
440 TerminateNestedMessageLoop();
444 // Reset our pressed lock to the previous state's, if there was one.
445 // The lock handles the case if the button was destroyed.
446 pressed_lock_.reset(nested_pressed_lock.release());
448 return result;
451 void MenuController::Cancel(ExitType type) {
452 // If the menu has already been destroyed, no further cancellation is
453 // needed. We especially don't want to set the |exit_type_| to a lesser
454 // value.
455 if (exit_type_ == EXIT_DESTROYED || exit_type_ == type)
456 return;
458 if (!showing_) {
459 // This occurs if we're in the process of notifying the delegate for a drop
460 // and the delegate cancels us.
461 return;
464 MenuItemView* selected = state_.item;
465 SetExitType(type);
467 SendMouseCaptureLostToActiveView();
469 // Hide windows immediately.
470 SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
472 if (!blocking_run_) {
473 // If we didn't block the caller we need to notify the menu, which
474 // triggers deleting us.
475 DCHECK(selected);
476 showing_ = false;
477 delegate_->DropMenuClosed(
478 internal::MenuControllerDelegate::NOTIFY_DELEGATE,
479 selected->GetRootMenuItem());
480 // WARNING: the call to MenuClosed deletes us.
481 return;
485 void MenuController::OnMousePressed(SubmenuView* source,
486 const ui::MouseEvent& event) {
487 SetSelectionOnPointerDown(source, event);
490 void MenuController::OnMouseDragged(SubmenuView* source,
491 const ui::MouseEvent& event) {
492 MenuPart part = GetMenuPart(source, event.location());
493 UpdateScrolling(part);
495 if (!blocking_run_)
496 return;
498 if (possible_drag_) {
499 if (View::ExceededDragThreshold(event.location() - press_pt_))
500 StartDrag(source, press_pt_);
501 return;
503 MenuItemView* mouse_menu = NULL;
504 if (part.type == MenuPart::MENU_ITEM) {
505 if (!part.menu)
506 part.menu = source->GetMenuItem();
507 else
508 mouse_menu = part.menu;
509 SetSelection(part.menu ? part.menu : state_.item, SELECTION_OPEN_SUBMENU);
510 } else if (part.type == MenuPart::NONE) {
511 ShowSiblingMenu(source, event.location());
513 UpdateActiveMouseView(source, event, mouse_menu);
516 void MenuController::OnMouseReleased(SubmenuView* source,
517 const ui::MouseEvent& event) {
518 if (!blocking_run_)
519 return;
521 DCHECK(state_.item);
522 possible_drag_ = false;
523 DCHECK(blocking_run_);
524 MenuPart part = GetMenuPart(source, event.location());
525 if (event.IsRightMouseButton() && part.type == MenuPart::MENU_ITEM) {
526 MenuItemView* menu = part.menu;
527 // |menu| is NULL means this event is from an empty menu or a separator.
528 // If it is from an empty menu, use parent context menu instead of that.
529 if (menu == NULL &&
530 part.submenu->child_count() == 1 &&
531 part.submenu->child_at(0)->id() == MenuItemView::kEmptyMenuItemViewID) {
532 menu = part.parent;
535 if (menu != NULL) {
536 gfx::Point screen_location(event.location());
537 View::ConvertPointToScreen(source->GetScrollViewContainer(),
538 &screen_location);
539 if (ShowContextMenu(menu, screen_location, ui::MENU_SOURCE_MOUSE))
540 return;
544 // We can use Ctrl+click or the middle mouse button to recursively open urls
545 // for selected folder menu items. If it's only a left click, show the
546 // contents of the folder.
547 if (!part.is_scroll() && part.menu &&
548 !(part.menu->HasSubmenu() &&
549 (event.flags() & ui::EF_LEFT_MOUSE_BUTTON))) {
550 if (GetActiveMouseView()) {
551 SendMouseReleaseToActiveView(source, event);
552 return;
554 // If a mouse release was received quickly after showing.
555 base::TimeDelta time_shown = base::TimeTicks::Now() - menu_start_time_;
556 if (time_shown.InMilliseconds() < menu_selection_hold_time_ms) {
557 // And it wasn't far from the mouse press location.
558 gfx::Point screen_loc(event.location());
559 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
560 gfx::Vector2d moved = screen_loc - menu_start_mouse_press_loc_;
561 if (moved.Length() < kMaximumLengthMovedToActivate) {
562 // Ignore the mouse release as it was likely this menu was shown under
563 // the mouse and the action was just a normal click.
564 return;
567 if (part.menu->GetDelegate()->ShouldExecuteCommandWithoutClosingMenu(
568 part.menu->GetCommand(), event)) {
569 part.menu->GetDelegate()->ExecuteCommand(part.menu->GetCommand(),
570 event.flags());
571 return;
573 if (!part.menu->NonIconChildViewsCount() &&
574 part.menu->GetDelegate()->IsTriggerableEvent(part.menu, event)) {
575 base::TimeDelta shown_time = base::TimeTicks::Now() - menu_start_time_;
576 if (!state_.context_menu || !View::ShouldShowContextMenuOnMousePress() ||
577 shown_time.InMilliseconds() > menu_selection_hold_time_ms) {
578 Accept(part.menu, event.flags());
580 return;
582 } else if (part.type == MenuPart::MENU_ITEM) {
583 // User either clicked on empty space, or a menu that has children.
584 SetSelection(part.menu ? part.menu : state_.item,
585 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
587 SendMouseCaptureLostToActiveView();
590 void MenuController::OnMouseMoved(SubmenuView* source,
591 const ui::MouseEvent& event) {
592 HandleMouseLocation(source, event.location());
595 void MenuController::OnMouseEntered(SubmenuView* source,
596 const ui::MouseEvent& event) {
597 // MouseEntered is always followed by a mouse moved, so don't need to
598 // do anything here.
601 bool MenuController::OnMouseWheel(SubmenuView* source,
602 const ui::MouseWheelEvent& event) {
603 MenuPart part = GetMenuPart(source, event.location());
604 return part.submenu && part.submenu->OnMouseWheel(event);
607 void MenuController::OnGestureEvent(SubmenuView* source,
608 ui::GestureEvent* event) {
609 MenuPart part = GetMenuPart(source, event->location());
610 if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
611 SetSelectionOnPointerDown(source, *event);
612 event->StopPropagation();
613 } else if (event->type() == ui::ET_GESTURE_LONG_PRESS) {
614 if (part.type == MenuPart::MENU_ITEM && part.menu) {
615 gfx::Point screen_location(event->location());
616 View::ConvertPointToScreen(source->GetScrollViewContainer(),
617 &screen_location);
618 if (ShowContextMenu(part.menu, screen_location, ui::MENU_SOURCE_TOUCH))
619 event->StopPropagation();
621 } else if (event->type() == ui::ET_GESTURE_TAP) {
622 if (!part.is_scroll() && part.menu &&
623 !(part.menu->HasSubmenu())) {
624 if (part.menu->GetDelegate()->IsTriggerableEvent(
625 part.menu, *event)) {
626 Accept(part.menu, event->flags());
627 item_selected_by_touch_ = true;
629 event->StopPropagation();
630 } else if (part.type == MenuPart::MENU_ITEM) {
631 // User either tapped on empty space, or a menu that has children.
632 SetSelection(part.menu ? part.menu : state_.item,
633 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
634 event->StopPropagation();
636 } else if (event->type() == ui::ET_GESTURE_TAP_CANCEL &&
637 part.menu &&
638 part.type == MenuPart::MENU_ITEM) {
639 // Move the selection to the parent menu so that the selection in the
640 // current menu is unset. Make sure the submenu remains open by sending the
641 // appropriate SetSelectionTypes flags.
642 SetSelection(part.menu->GetParentMenuItem(),
643 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
644 event->StopPropagation();
647 if (event->stopped_propagation())
648 return;
650 if (!part.submenu)
651 return;
652 part.submenu->OnGestureEvent(event);
655 bool MenuController::GetDropFormats(
656 SubmenuView* source,
657 int* formats,
658 std::set<OSExchangeData::CustomFormat>* custom_formats) {
659 return source->GetMenuItem()->GetDelegate()->GetDropFormats(
660 source->GetMenuItem(), formats, custom_formats);
663 bool MenuController::AreDropTypesRequired(SubmenuView* source) {
664 return source->GetMenuItem()->GetDelegate()->AreDropTypesRequired(
665 source->GetMenuItem());
668 bool MenuController::CanDrop(SubmenuView* source, const OSExchangeData& data) {
669 return source->GetMenuItem()->GetDelegate()->CanDrop(source->GetMenuItem(),
670 data);
673 void MenuController::OnDragEntered(SubmenuView* source,
674 const ui::DropTargetEvent& event) {
675 valid_drop_coordinates_ = false;
678 int MenuController::OnDragUpdated(SubmenuView* source,
679 const ui::DropTargetEvent& event) {
680 StopCancelAllTimer();
682 gfx::Point screen_loc(event.location());
683 View::ConvertPointToScreen(source, &screen_loc);
684 if (valid_drop_coordinates_ && screen_loc == drop_pt_)
685 return last_drop_operation_;
686 drop_pt_ = screen_loc;
687 valid_drop_coordinates_ = true;
689 MenuItemView* menu_item = GetMenuItemAt(source, event.x(), event.y());
690 bool over_empty_menu = false;
691 if (!menu_item) {
692 // See if we're over an empty menu.
693 menu_item = GetEmptyMenuItemAt(source, event.x(), event.y());
694 if (menu_item)
695 over_empty_menu = true;
697 MenuDelegate::DropPosition drop_position = MenuDelegate::DROP_NONE;
698 int drop_operation = ui::DragDropTypes::DRAG_NONE;
699 if (menu_item) {
700 gfx::Point menu_item_loc(event.location());
701 View::ConvertPointToTarget(source, menu_item, &menu_item_loc);
702 MenuItemView* query_menu_item;
703 if (!over_empty_menu) {
704 int menu_item_height = menu_item->height();
705 if (menu_item->HasSubmenu() &&
706 (menu_item_loc.y() > kDropBetweenPixels &&
707 menu_item_loc.y() < (menu_item_height - kDropBetweenPixels))) {
708 drop_position = MenuDelegate::DROP_ON;
709 } else {
710 drop_position = (menu_item_loc.y() < menu_item_height / 2) ?
711 MenuDelegate::DROP_BEFORE : MenuDelegate::DROP_AFTER;
713 query_menu_item = menu_item;
714 } else {
715 query_menu_item = menu_item->GetParentMenuItem();
716 drop_position = MenuDelegate::DROP_ON;
718 drop_operation = menu_item->GetDelegate()->GetDropOperation(
719 query_menu_item, event, &drop_position);
721 // If the menu has a submenu, schedule the submenu to open.
722 SetSelection(menu_item, menu_item->HasSubmenu() ? SELECTION_OPEN_SUBMENU :
723 SELECTION_DEFAULT);
725 if (drop_position == MenuDelegate::DROP_NONE ||
726 drop_operation == ui::DragDropTypes::DRAG_NONE)
727 menu_item = NULL;
728 } else {
729 SetSelection(source->GetMenuItem(), SELECTION_OPEN_SUBMENU);
731 SetDropMenuItem(menu_item, drop_position);
732 last_drop_operation_ = drop_operation;
733 return drop_operation;
736 void MenuController::OnDragExited(SubmenuView* source) {
737 StartCancelAllTimer();
739 if (drop_target_) {
740 StopShowTimer();
741 SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
745 int MenuController::OnPerformDrop(SubmenuView* source,
746 const ui::DropTargetEvent& event) {
747 DCHECK(drop_target_);
748 // NOTE: the delegate may delete us after invoking OnPerformDrop, as such
749 // we don't call cancel here.
751 MenuItemView* item = state_.item;
752 DCHECK(item);
754 MenuItemView* drop_target = drop_target_;
755 MenuDelegate::DropPosition drop_position = drop_position_;
757 // Close all menus, including any nested menus.
758 SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
759 CloseAllNestedMenus();
761 // Set state such that we exit.
762 showing_ = false;
763 SetExitType(EXIT_ALL);
765 // If over an empty menu item, drop occurs on the parent.
766 if (drop_target->id() == MenuItemView::kEmptyMenuItemViewID)
767 drop_target = drop_target->GetParentMenuItem();
769 if (!IsBlockingRun()) {
770 delegate_->DropMenuClosed(
771 internal::MenuControllerDelegate::DONT_NOTIFY_DELEGATE,
772 item->GetRootMenuItem());
775 // WARNING: the call to MenuClosed deletes us.
777 return drop_target->GetDelegate()->OnPerformDrop(
778 drop_target, drop_position, event);
781 void MenuController::OnDragEnteredScrollButton(SubmenuView* source,
782 bool is_up) {
783 MenuPart part;
784 part.type = is_up ? MenuPart::SCROLL_UP : MenuPart::SCROLL_DOWN;
785 part.submenu = source;
786 UpdateScrolling(part);
788 // Do this to force the selection to hide.
789 SetDropMenuItem(source->GetMenuItemAt(0), MenuDelegate::DROP_NONE);
791 StopCancelAllTimer();
794 void MenuController::OnDragExitedScrollButton(SubmenuView* source) {
795 StartCancelAllTimer();
796 SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
797 StopScrolling();
800 void MenuController::OnDragWillStart() {
801 DCHECK(!drag_in_progress_);
802 drag_in_progress_ = true;
805 void MenuController::OnDragComplete(bool should_close) {
806 DCHECK(drag_in_progress_);
807 drag_in_progress_ = false;
808 if (showing_ && should_close && GetActiveInstance() == this) {
809 CloseAllNestedMenus();
810 Cancel(EXIT_ALL);
814 ui::PostDispatchAction MenuController::OnWillDispatchKeyEvent(
815 base::char16 character,
816 ui::KeyboardCode key_code) {
817 if (exit_type() == MenuController::EXIT_ALL ||
818 exit_type() == MenuController::EXIT_DESTROYED) {
819 TerminateNestedMessageLoop();
820 return ui::POST_DISPATCH_PERFORM_DEFAULT;
823 if (character)
824 SelectByChar(character);
825 else
826 OnKeyDown(key_code);
828 if (exit_type() != MenuController::EXIT_NONE)
829 TerminateNestedMessageLoop();
831 return ui::POST_DISPATCH_NONE;
834 void MenuController::UpdateSubmenuSelection(SubmenuView* submenu) {
835 if (submenu->IsShowing()) {
836 gfx::Point point = GetScreen()->GetCursorScreenPoint();
837 const SubmenuView* root_submenu =
838 submenu->GetMenuItem()->GetRootMenuItem()->GetSubmenu();
839 View::ConvertPointFromScreen(
840 root_submenu->GetWidget()->GetRootView(), &point);
841 HandleMouseLocation(submenu, point);
845 void MenuController::OnWidgetDestroying(Widget* widget) {
846 DCHECK_EQ(owner_, widget);
847 owner_->RemoveObserver(this);
848 owner_ = NULL;
849 message_loop_->ClearOwner();
852 bool MenuController::IsCancelAllTimerRunningForTest() {
853 return cancel_all_timer_.IsRunning();
856 // static
857 void MenuController::TurnOffMenuSelectionHoldForTest() {
858 menu_selection_hold_time_ms = -1;
861 void MenuController::SetSelection(MenuItemView* menu_item,
862 int selection_types) {
863 size_t paths_differ_at = 0;
864 std::vector<MenuItemView*> current_path;
865 std::vector<MenuItemView*> new_path;
866 BuildPathsAndCalculateDiff(pending_state_.item, menu_item, &current_path,
867 &new_path, &paths_differ_at);
869 size_t current_size = current_path.size();
870 size_t new_size = new_path.size();
872 bool pending_item_changed = pending_state_.item != menu_item;
873 if (pending_item_changed && pending_state_.item) {
874 CustomButton* button = GetFirstHotTrackedView(pending_state_.item);
875 if (button)
876 button->SetHotTracked(false);
879 // Notify the old path it isn't selected.
880 MenuDelegate* current_delegate =
881 current_path.empty() ? NULL : current_path.front()->GetDelegate();
882 for (size_t i = paths_differ_at; i < current_size; ++i) {
883 if (current_delegate &&
884 current_path[i]->GetType() == MenuItemView::SUBMENU) {
885 current_delegate->WillHideMenu(current_path[i]);
887 current_path[i]->SetSelected(false);
890 // Notify the new path it is selected.
891 for (size_t i = paths_differ_at; i < new_size; ++i) {
892 new_path[i]->ScrollRectToVisible(new_path[i]->GetLocalBounds());
893 new_path[i]->SetSelected(true);
896 if (menu_item && menu_item->GetDelegate())
897 menu_item->GetDelegate()->SelectionChanged(menu_item);
899 DCHECK(menu_item || (selection_types & SELECTION_EXIT) != 0);
901 pending_state_.item = menu_item;
902 pending_state_.submenu_open = (selection_types & SELECTION_OPEN_SUBMENU) != 0;
904 // Stop timers.
905 StopCancelAllTimer();
906 // Resets show timer only when pending menu item is changed.
907 if (pending_item_changed)
908 StopShowTimer();
910 if (selection_types & SELECTION_UPDATE_IMMEDIATELY)
911 CommitPendingSelection();
912 else if (pending_item_changed)
913 StartShowTimer();
915 // Notify an accessibility focus event on all menu items except for the root.
916 if (menu_item &&
917 (MenuDepth(menu_item) != 1 ||
918 menu_item->GetType() != MenuItemView::SUBMENU)) {
919 menu_item->NotifyAccessibilityEvent(
920 ui::AX_EVENT_FOCUS, true);
924 void MenuController::SetSelectionOnPointerDown(SubmenuView* source,
925 const ui::LocatedEvent& event) {
926 if (!blocking_run_)
927 return;
929 DCHECK(!GetActiveMouseView());
931 MenuPart part = GetMenuPart(source, event.location());
932 if (part.is_scroll())
933 return; // Ignore presses on scroll buttons.
935 // When this menu is opened through a touch event, a simulated right-click
936 // is sent before the menu appears. Ignore it.
937 if ((event.flags() & ui::EF_RIGHT_MOUSE_BUTTON) &&
938 (event.flags() & ui::EF_FROM_TOUCH))
939 return;
941 if (part.type == MenuPart::NONE ||
942 (part.type == MenuPart::MENU_ITEM && part.menu &&
943 part.menu->GetRootMenuItem() != state_.item->GetRootMenuItem())) {
944 // Remember the time stamp of the current (press down) event. The owner can
945 // then use this to figure out if this menu was finished with the same click
946 // which is sent to it thereafter.
947 closing_event_time_ = event.time_stamp();
949 // Mouse wasn't pressed over any menu, or the active menu, cancel.
951 #if defined(OS_WIN)
952 // We're going to close and we own the mouse capture. We need to repost the
953 // mouse down, otherwise the window the user clicked on won't get the event.
954 RepostEvent(source, event);
955 #endif
957 // And close.
958 ExitType exit_type = EXIT_ALL;
959 if (!menu_stack_.empty()) {
960 // We're running nested menus. Only exit all if the mouse wasn't over one
961 // of the menus from the last run.
962 gfx::Point screen_loc(event.location());
963 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
964 MenuPart last_part = GetMenuPartByScreenCoordinateUsingMenu(
965 menu_stack_.back().first.item, screen_loc);
966 if (last_part.type != MenuPart::NONE)
967 exit_type = EXIT_OUTERMOST;
969 Cancel(exit_type);
971 #if defined(OS_CHROMEOS)
972 // We're going to exit the menu and want to repost the event so that is
973 // is handled normally after the context menu has exited. We call
974 // RepostEvent after Cancel so that mouse capture has been released so
975 // that finding the event target is unaffected by the current capture.
976 RepostEvent(source, event);
977 #endif
978 // Do not repost events for Linux Aura because this behavior is more
979 // consistent with the behavior of other Linux apps.
980 return;
983 // On a press we immediately commit the selection, that way a submenu
984 // pops up immediately rather than after a delay.
985 int selection_types = SELECTION_UPDATE_IMMEDIATELY;
986 if (!part.menu) {
987 part.menu = part.parent;
988 selection_types |= SELECTION_OPEN_SUBMENU;
989 } else {
990 if (part.menu->GetDelegate()->CanDrag(part.menu)) {
991 possible_drag_ = true;
992 press_pt_ = event.location();
994 if (part.menu->HasSubmenu())
995 selection_types |= SELECTION_OPEN_SUBMENU;
997 SetSelection(part.menu, selection_types);
1000 void MenuController::StartDrag(SubmenuView* source,
1001 const gfx::Point& location) {
1002 MenuItemView* item = state_.item;
1003 DCHECK(item);
1004 // Points are in the coordinates of the submenu, need to map to that of
1005 // the selected item. Additionally source may not be the parent of
1006 // the selected item, so need to map to screen first then to item.
1007 gfx::Point press_loc(location);
1008 View::ConvertPointToScreen(source->GetScrollViewContainer(), &press_loc);
1009 View::ConvertPointFromScreen(item, &press_loc);
1010 gfx::Point widget_loc(press_loc);
1011 View::ConvertPointToWidget(item, &widget_loc);
1012 scoped_ptr<gfx::Canvas> canvas(GetCanvasForDragImage(
1013 source->GetWidget(), gfx::Size(item->width(), item->height())));
1014 item->PaintButton(canvas.get(), MenuItemView::PB_FOR_DRAG);
1016 OSExchangeData data;
1017 item->GetDelegate()->WriteDragData(item, &data);
1018 drag_utils::SetDragImageOnDataObject(*canvas,
1019 press_loc.OffsetFromOrigin(),
1020 &data);
1021 StopScrolling();
1022 int drag_ops = item->GetDelegate()->GetDragOperations(item);
1023 did_initiate_drag_ = true;
1024 // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below.
1025 item->GetWidget()->RunShellDrag(NULL, data, widget_loc, drag_ops,
1026 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
1027 did_initiate_drag_ = false;
1030 void MenuController::OnKeyDown(ui::KeyboardCode key_code) {
1031 DCHECK(blocking_run_);
1033 switch (key_code) {
1034 case ui::VKEY_UP:
1035 IncrementSelection(INCREMENT_SELECTION_UP);
1036 break;
1038 case ui::VKEY_DOWN:
1039 IncrementSelection(INCREMENT_SELECTION_DOWN);
1040 break;
1042 // Handling of VK_RIGHT and VK_LEFT is different depending on the UI
1043 // layout.
1044 case ui::VKEY_RIGHT:
1045 if (base::i18n::IsRTL())
1046 CloseSubmenu();
1047 else
1048 OpenSubmenuChangeSelectionIfCan();
1049 break;
1051 case ui::VKEY_LEFT:
1052 if (base::i18n::IsRTL())
1053 OpenSubmenuChangeSelectionIfCan();
1054 else
1055 CloseSubmenu();
1056 break;
1058 // On Mac, treat space the same as return.
1059 #if !defined(OS_MACOSX)
1060 case ui::VKEY_SPACE:
1061 SendAcceleratorToHotTrackedView();
1062 break;
1063 #endif
1065 case ui::VKEY_F4:
1066 if (!is_combobox_)
1067 break;
1068 // Fallthrough to accept or dismiss combobox menus on F4, like windows.
1069 case ui::VKEY_RETURN:
1070 #if defined(OS_MACOSX)
1071 case ui::VKEY_SPACE:
1072 #endif
1073 if (pending_state_.item) {
1074 if (pending_state_.item->HasSubmenu()) {
1075 if (key_code == ui::VKEY_F4 &&
1076 pending_state_.item->GetSubmenu()->IsShowing())
1077 Cancel(EXIT_ALL);
1078 else
1079 OpenSubmenuChangeSelectionIfCan();
1080 } else {
1081 if (!SendAcceleratorToHotTrackedView() &&
1082 pending_state_.item->enabled()) {
1083 Accept(pending_state_.item, 0);
1087 break;
1089 case ui::VKEY_ESCAPE:
1090 if (!state_.item->GetParentMenuItem() ||
1091 (!state_.item->GetParentMenuItem()->GetParentMenuItem() &&
1092 (!state_.item->HasSubmenu() ||
1093 !state_.item->GetSubmenu()->IsShowing()))) {
1094 // User pressed escape and only one menu is shown, cancel it.
1095 Cancel(EXIT_OUTERMOST);
1096 break;
1098 CloseSubmenu();
1099 break;
1101 case ui::VKEY_APPS: {
1102 CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item);
1103 if (hot_view) {
1104 hot_view->ShowContextMenu(hot_view->GetKeyboardContextMenuLocation(),
1105 ui::MENU_SOURCE_KEYBOARD);
1106 } else if (pending_state_.item->enabled() &&
1107 pending_state_.item->GetRootMenuItem() !=
1108 pending_state_.item) {
1109 // Show the context menu for the given menu item. We don't try to show
1110 // the menu for the (boundless) root menu item. This can happen, e.g.,
1111 // when the user hits the APPS key after opening the menu, when no item
1112 // is selected, but showing a context menu for an implicitly-selected
1113 // and invisible item doesn't make sense.
1114 ShowContextMenu(pending_state_.item,
1115 pending_state_.item->GetKeyboardContextMenuLocation(),
1116 ui::MENU_SOURCE_KEYBOARD);
1118 break;
1121 default:
1122 break;
1126 MenuController::MenuController(ui::NativeTheme* theme,
1127 bool blocking,
1128 internal::MenuControllerDelegate* delegate)
1129 : blocking_run_(blocking),
1130 showing_(false),
1131 exit_type_(EXIT_NONE),
1132 did_capture_(false),
1133 result_(NULL),
1134 accept_event_flags_(0),
1135 drop_target_(NULL),
1136 drop_position_(MenuDelegate::DROP_UNKNOWN),
1137 owner_(NULL),
1138 possible_drag_(false),
1139 drag_in_progress_(false),
1140 did_initiate_drag_(false),
1141 valid_drop_coordinates_(false),
1142 last_drop_operation_(MenuDelegate::DROP_UNKNOWN),
1143 showing_submenu_(false),
1144 active_mouse_view_id_(ViewStorage::GetInstance()->CreateStorageID()),
1145 delegate_(delegate),
1146 message_loop_depth_(0),
1147 menu_config_(theme),
1148 closing_event_time_(base::TimeDelta()),
1149 menu_start_time_(base::TimeTicks()),
1150 is_combobox_(false),
1151 item_selected_by_touch_(false),
1152 message_loop_(MenuMessageLoop::Create()) {
1153 active_instance_ = this;
1156 MenuController::~MenuController() {
1157 DCHECK(!showing_);
1158 if (owner_)
1159 owner_->RemoveObserver(this);
1160 if (active_instance_ == this)
1161 active_instance_ = NULL;
1162 StopShowTimer();
1163 StopCancelAllTimer();
1166 void MenuController::RunMessageLoop(bool nested_menu) {
1167 message_loop_->Run(this, owner_, nested_menu);
1170 bool MenuController::SendAcceleratorToHotTrackedView() {
1171 CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item);
1172 if (!hot_view)
1173 return false;
1175 ui::Accelerator accelerator(ui::VKEY_RETURN, ui::EF_NONE);
1176 hot_view->AcceleratorPressed(accelerator);
1177 CustomButton* button = static_cast<CustomButton*>(hot_view);
1178 button->SetHotTracked(true);
1179 return true;
1182 void MenuController::UpdateInitialLocation(const gfx::Rect& bounds,
1183 MenuAnchorPosition position,
1184 bool context_menu) {
1185 pending_state_.context_menu = context_menu;
1186 pending_state_.initial_bounds = bounds;
1187 if (bounds.height() > 1) {
1188 // Inset the bounds slightly, otherwise drag coordinates don't line up
1189 // nicely and menus close prematurely.
1190 pending_state_.initial_bounds.Inset(0, 1);
1193 // Reverse anchor position for RTL languages.
1194 if (base::i18n::IsRTL() &&
1195 (position == MENU_ANCHOR_TOPRIGHT || position == MENU_ANCHOR_TOPLEFT)) {
1196 pending_state_.anchor = position == MENU_ANCHOR_TOPRIGHT
1197 ? MENU_ANCHOR_TOPLEFT
1198 : MENU_ANCHOR_TOPRIGHT;
1199 } else {
1200 pending_state_.anchor = position;
1203 // Calculate the bounds of the monitor we'll show menus on. Do this once to
1204 // avoid repeated system queries for the info.
1205 pending_state_.monitor_bounds = GetScreen()->GetDisplayNearestPoint(
1206 bounds.origin()).work_area();
1208 if (!pending_state_.monitor_bounds.Contains(bounds)) {
1209 // Use the monitor area if the work area doesn't contain the bounds. This
1210 // handles showing a menu from the launcher.
1211 gfx::Rect monitor_area = GetScreen()->GetDisplayNearestPoint(
1212 bounds.origin()).bounds();
1213 if (monitor_area.Contains(bounds))
1214 pending_state_.monitor_bounds = monitor_area;
1218 void MenuController::Accept(MenuItemView* item, int event_flags) {
1219 DCHECK(IsBlockingRun());
1220 result_ = item;
1221 if (item && !menu_stack_.empty() &&
1222 !item->GetDelegate()->ShouldCloseAllMenusOnExecute(item->GetCommand())) {
1223 SetExitType(EXIT_OUTERMOST);
1224 } else {
1225 SetExitType(EXIT_ALL);
1227 accept_event_flags_ = event_flags;
1230 bool MenuController::ShowSiblingMenu(SubmenuView* source,
1231 const gfx::Point& mouse_location) {
1232 if (!menu_stack_.empty() || !pressed_lock_.get())
1233 return false;
1235 View* source_view = source->GetScrollViewContainer();
1236 if (mouse_location.x() >= 0 &&
1237 mouse_location.x() < source_view->width() &&
1238 mouse_location.y() >= 0 &&
1239 mouse_location.y() < source_view->height()) {
1240 // The mouse is over the menu, no need to continue.
1241 return false;
1244 gfx::NativeWindow window_under_mouse = GetScreen()->GetWindowUnderCursor();
1245 // TODO(oshima): Replace with views only API.
1246 if (!owner_ || window_under_mouse != owner_->GetNativeWindow())
1247 return false;
1249 // The user moved the mouse outside the menu and over the owning window. See
1250 // if there is a sibling menu we should show.
1251 gfx::Point screen_point(mouse_location);
1252 View::ConvertPointToScreen(source_view, &screen_point);
1253 MenuAnchorPosition anchor;
1254 bool has_mnemonics;
1255 MenuButton* button = NULL;
1256 MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->
1257 GetSiblingMenu(source->GetMenuItem()->GetRootMenuItem(),
1258 screen_point, &anchor, &has_mnemonics, &button);
1259 if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu))
1260 return false;
1262 delegate_->SiblingMenuCreated(alt_menu);
1264 if (!button) {
1265 // If the delegate returns a menu, they must also return a button.
1266 NOTREACHED();
1267 return false;
1270 // There is a sibling menu, update the button state, hide the current menu
1271 // and show the new one.
1272 pressed_lock_.reset(new MenuButton::PressedLock(button));
1274 // Need to reset capture when we show the menu again, otherwise we aren't
1275 // going to get any events.
1276 did_capture_ = false;
1277 gfx::Point screen_menu_loc;
1278 View::ConvertPointToScreen(button, &screen_menu_loc);
1280 // It is currently not possible to show a submenu recursively in a bubble.
1281 DCHECK(!MenuItemView::IsBubble(anchor));
1282 // Subtract 1 from the height to make the popup flush with the button border.
1283 UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(),
1284 button->width(), button->height() - 1),
1285 anchor, state_.context_menu);
1286 alt_menu->PrepareForRun(
1287 false, has_mnemonics,
1288 source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_);
1289 alt_menu->controller_ = this;
1290 SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1291 return true;
1294 bool MenuController::ShowContextMenu(MenuItemView* menu_item,
1295 const gfx::Point& screen_location,
1296 ui::MenuSourceType source_type) {
1297 // Set the selection immediately, making sure the submenu is only open
1298 // if it already was.
1299 int selection_types = SELECTION_UPDATE_IMMEDIATELY;
1300 if (state_.item == pending_state_.item && state_.submenu_open)
1301 selection_types |= SELECTION_OPEN_SUBMENU;
1302 SetSelection(pending_state_.item, selection_types);
1304 if (menu_item->GetDelegate()->ShowContextMenu(
1305 menu_item, menu_item->GetCommand(), screen_location, source_type)) {
1306 SendMouseCaptureLostToActiveView();
1307 return true;
1309 return false;
1312 void MenuController::CloseAllNestedMenus() {
1313 for (std::list<NestedState>::iterator i = menu_stack_.begin();
1314 i != menu_stack_.end(); ++i) {
1315 State& state = i->first;
1316 MenuItemView* last_item = state.item;
1317 for (MenuItemView* item = last_item; item;
1318 item = item->GetParentMenuItem()) {
1319 CloseMenu(item);
1320 last_item = item;
1322 state.submenu_open = false;
1323 state.item = last_item;
1327 MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) {
1328 // Walk the view hierarchy until we find a menu item (or the root).
1329 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1330 while (child_under_mouse &&
1331 child_under_mouse->id() != MenuItemView::kMenuItemViewID) {
1332 child_under_mouse = child_under_mouse->parent();
1334 if (child_under_mouse && child_under_mouse->enabled() &&
1335 child_under_mouse->id() == MenuItemView::kMenuItemViewID) {
1336 return static_cast<MenuItemView*>(child_under_mouse);
1338 return NULL;
1341 MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) {
1342 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1343 if (child_under_mouse &&
1344 child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) {
1345 return static_cast<MenuItemView*>(child_under_mouse);
1347 return NULL;
1350 bool MenuController::IsScrollButtonAt(SubmenuView* source,
1351 int x,
1352 int y,
1353 MenuPart::Type* part) {
1354 MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer();
1355 View* child_under_mouse =
1356 scroll_view->GetEventHandlerForPoint(gfx::Point(x, y));
1357 if (child_under_mouse && child_under_mouse->enabled()) {
1358 if (child_under_mouse == scroll_view->scroll_up_button()) {
1359 *part = MenuPart::SCROLL_UP;
1360 return true;
1362 if (child_under_mouse == scroll_view->scroll_down_button()) {
1363 *part = MenuPart::SCROLL_DOWN;
1364 return true;
1367 return false;
1370 MenuController::MenuPart MenuController::GetMenuPart(
1371 SubmenuView* source,
1372 const gfx::Point& source_loc) {
1373 gfx::Point screen_loc(source_loc);
1374 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
1375 return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc);
1378 MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu(
1379 MenuItemView* item,
1380 const gfx::Point& screen_loc) {
1381 MenuPart part;
1382 for (; item; item = item->GetParentMenuItem()) {
1383 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1384 GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc,
1385 &part)) {
1386 return part;
1389 return part;
1392 bool MenuController::GetMenuPartByScreenCoordinateImpl(
1393 SubmenuView* menu,
1394 const gfx::Point& screen_loc,
1395 MenuPart* part) {
1396 // Is the mouse over the scroll buttons?
1397 gfx::Point scroll_view_loc = screen_loc;
1398 View* scroll_view_container = menu->GetScrollViewContainer();
1399 View::ConvertPointFromScreen(scroll_view_container, &scroll_view_loc);
1400 if (scroll_view_loc.x() < 0 ||
1401 scroll_view_loc.x() >= scroll_view_container->width() ||
1402 scroll_view_loc.y() < 0 ||
1403 scroll_view_loc.y() >= scroll_view_container->height()) {
1404 // Point isn't contained in menu.
1405 return false;
1407 if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(),
1408 &(part->type))) {
1409 part->submenu = menu;
1410 return true;
1413 // Not over the scroll button. Check the actual menu.
1414 if (DoesSubmenuContainLocation(menu, screen_loc)) {
1415 gfx::Point menu_loc = screen_loc;
1416 View::ConvertPointFromScreen(menu, &menu_loc);
1417 part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y());
1418 part->type = MenuPart::MENU_ITEM;
1419 part->submenu = menu;
1420 if (!part->menu)
1421 part->parent = menu->GetMenuItem();
1422 return true;
1425 // While the mouse isn't over a menu item or the scroll buttons of menu, it
1426 // is contained by menu and so we return true. If we didn't return true other
1427 // menus would be searched, even though they are likely obscured by us.
1428 return true;
1431 bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu,
1432 const gfx::Point& screen_loc) {
1433 gfx::Point view_loc = screen_loc;
1434 View::ConvertPointFromScreen(submenu, &view_loc);
1435 gfx::Rect vis_rect = submenu->GetVisibleBounds();
1436 return vis_rect.Contains(view_loc.x(), view_loc.y());
1439 void MenuController::CommitPendingSelection() {
1440 StopShowTimer();
1442 size_t paths_differ_at = 0;
1443 std::vector<MenuItemView*> current_path;
1444 std::vector<MenuItemView*> new_path;
1445 BuildPathsAndCalculateDiff(state_.item, pending_state_.item, &current_path,
1446 &new_path, &paths_differ_at);
1448 // Hide the old menu.
1449 for (size_t i = paths_differ_at; i < current_path.size(); ++i) {
1450 if (current_path[i]->HasSubmenu()) {
1451 current_path[i]->GetSubmenu()->Hide();
1455 // Copy pending to state_, making sure to preserve the direction menus were
1456 // opened.
1457 std::list<bool> pending_open_direction;
1458 state_.open_leading.swap(pending_open_direction);
1459 state_ = pending_state_;
1460 state_.open_leading.swap(pending_open_direction);
1462 int menu_depth = MenuDepth(state_.item);
1463 if (menu_depth == 0) {
1464 state_.open_leading.clear();
1465 } else {
1466 int cached_size = static_cast<int>(state_.open_leading.size());
1467 DCHECK_GE(menu_depth, 0);
1468 while (cached_size-- >= menu_depth)
1469 state_.open_leading.pop_back();
1472 if (!state_.item) {
1473 // Nothing to select.
1474 StopScrolling();
1475 return;
1478 // Open all the submenus preceeding the last menu item (last menu item is
1479 // handled next).
1480 if (new_path.size() > 1) {
1481 for (std::vector<MenuItemView*>::iterator i = new_path.begin();
1482 i != new_path.end() - 1; ++i) {
1483 OpenMenu(*i);
1487 if (state_.submenu_open) {
1488 // The submenu should be open, open the submenu if the item has a submenu.
1489 if (state_.item->HasSubmenu()) {
1490 OpenMenu(state_.item);
1491 } else {
1492 state_.submenu_open = false;
1494 } else if (state_.item->HasSubmenu() &&
1495 state_.item->GetSubmenu()->IsShowing()) {
1496 state_.item->GetSubmenu()->Hide();
1499 if (scroll_task_.get() && scroll_task_->submenu()) {
1500 // Stop the scrolling if none of the elements of the selection contain
1501 // the menu being scrolled.
1502 bool found = false;
1503 for (MenuItemView* item = state_.item; item && !found;
1504 item = item->GetParentMenuItem()) {
1505 found = (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1506 item->GetSubmenu() == scroll_task_->submenu());
1508 if (!found)
1509 StopScrolling();
1513 void MenuController::CloseMenu(MenuItemView* item) {
1514 DCHECK(item);
1515 if (!item->HasSubmenu())
1516 return;
1517 item->GetSubmenu()->Hide();
1520 void MenuController::OpenMenu(MenuItemView* item) {
1521 DCHECK(item);
1522 if (item->GetSubmenu()->IsShowing()) {
1523 return;
1526 OpenMenuImpl(item, true);
1527 did_capture_ = true;
1530 void MenuController::OpenMenuImpl(MenuItemView* item, bool show) {
1531 // TODO(oshima|sky): Don't show the menu if drag is in progress and
1532 // this menu doesn't support drag drop. See crbug.com/110495.
1533 if (show) {
1534 int old_count = item->GetSubmenu()->child_count();
1535 item->GetDelegate()->WillShowMenu(item);
1536 if (old_count != item->GetSubmenu()->child_count()) {
1537 // If the number of children changed then we may need to add empty items.
1538 item->RemoveEmptyMenus();
1539 item->AddEmptyMenus();
1542 bool prefer_leading =
1543 state_.open_leading.empty() ? true : state_.open_leading.back();
1544 bool resulting_direction;
1545 gfx::Rect bounds = MenuItemView::IsBubble(state_.anchor) ?
1546 CalculateBubbleMenuBounds(item, prefer_leading, &resulting_direction) :
1547 CalculateMenuBounds(item, prefer_leading, &resulting_direction);
1548 state_.open_leading.push_back(resulting_direction);
1549 bool do_capture = (!did_capture_ && blocking_run_);
1550 showing_submenu_ = true;
1551 if (show) {
1552 // Menus are the only place using kGroupingPropertyKey, so any value (other
1553 // than 0) is fine.
1554 const int kGroupingId = 1001;
1555 item->GetSubmenu()->ShowAt(owner_, bounds, do_capture);
1556 item->GetSubmenu()->GetWidget()->SetNativeWindowProperty(
1557 TooltipManager::kGroupingPropertyKey,
1558 reinterpret_cast<void*>(kGroupingId));
1559 } else {
1560 item->GetSubmenu()->Reposition(bounds);
1562 showing_submenu_ = false;
1565 void MenuController::MenuChildrenChanged(MenuItemView* item) {
1566 DCHECK(item);
1567 // Menu shouldn't be updated during drag operation.
1568 DCHECK(!GetActiveMouseView());
1570 // If the current item or pending item is a descendant of the item
1571 // that changed, move the selection back to the changed item.
1572 const MenuItemView* ancestor = state_.item;
1573 while (ancestor && ancestor != item)
1574 ancestor = ancestor->GetParentMenuItem();
1575 if (!ancestor) {
1576 ancestor = pending_state_.item;
1577 while (ancestor && ancestor != item)
1578 ancestor = ancestor->GetParentMenuItem();
1579 if (!ancestor)
1580 return;
1582 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1583 if (item->HasSubmenu())
1584 OpenMenuImpl(item, false);
1587 void MenuController::BuildPathsAndCalculateDiff(
1588 MenuItemView* old_item,
1589 MenuItemView* new_item,
1590 std::vector<MenuItemView*>* old_path,
1591 std::vector<MenuItemView*>* new_path,
1592 size_t* first_diff_at) {
1593 DCHECK(old_path && new_path && first_diff_at);
1594 BuildMenuItemPath(old_item, old_path);
1595 BuildMenuItemPath(new_item, new_path);
1597 size_t common_size = std::min(old_path->size(), new_path->size());
1599 // Find the first difference between the two paths, when the loop
1600 // returns, diff_i is the first index where the two paths differ.
1601 for (size_t i = 0; i < common_size; ++i) {
1602 if ((*old_path)[i] != (*new_path)[i]) {
1603 *first_diff_at = i;
1604 return;
1608 *first_diff_at = common_size;
1611 void MenuController::BuildMenuItemPath(MenuItemView* item,
1612 std::vector<MenuItemView*>* path) {
1613 if (!item)
1614 return;
1615 BuildMenuItemPath(item->GetParentMenuItem(), path);
1616 path->push_back(item);
1619 void MenuController::StartShowTimer() {
1620 show_timer_.Start(FROM_HERE,
1621 TimeDelta::FromMilliseconds(menu_config_.show_delay),
1622 this, &MenuController::CommitPendingSelection);
1625 void MenuController::StopShowTimer() {
1626 show_timer_.Stop();
1629 void MenuController::StartCancelAllTimer() {
1630 cancel_all_timer_.Start(FROM_HERE,
1631 TimeDelta::FromMilliseconds(kCloseOnExitTime),
1632 this, &MenuController::CancelAll);
1635 void MenuController::StopCancelAllTimer() {
1636 cancel_all_timer_.Stop();
1639 gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item,
1640 bool prefer_leading,
1641 bool* is_leading) {
1642 DCHECK(item);
1644 SubmenuView* submenu = item->GetSubmenu();
1645 DCHECK(submenu);
1647 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1649 // For comboboxes, ensure the menu is at least as wide as the anchor.
1650 if (is_combobox_)
1651 pref.set_width(std::max(pref.width(), state_.initial_bounds.width()));
1653 // Don't let the menu go too wide.
1654 pref.set_width(std::min(pref.width(),
1655 item->GetDelegate()->GetMaxWidthForMenu(item)));
1656 if (!state_.monitor_bounds.IsEmpty())
1657 pref.set_width(std::min(pref.width(), state_.monitor_bounds.width()));
1659 // Assume we can honor prefer_leading.
1660 *is_leading = prefer_leading;
1662 int x, y;
1664 const MenuConfig& menu_config = item->GetMenuConfig();
1666 if (!item->GetParentMenuItem()) {
1667 // First item, position relative to initial location.
1668 x = state_.initial_bounds.x();
1670 // Offsets for context menu prevent menu items being selected by
1671 // simply opening the menu (bug 142992).
1672 if (menu_config.offset_context_menus && state_.context_menu)
1673 x += 1;
1675 y = state_.initial_bounds.bottom();
1676 if (state_.anchor == MENU_ANCHOR_TOPRIGHT) {
1677 x = x + state_.initial_bounds.width() - pref.width();
1678 if (menu_config.offset_context_menus && state_.context_menu)
1679 x -= 1;
1680 } else if (state_.anchor == MENU_ANCHOR_BOTTOMCENTER) {
1681 x = x - (pref.width() - state_.initial_bounds.width()) / 2;
1682 if (pref.height() >
1683 state_.initial_bounds.y() + kCenteredContextMenuYOffset) {
1684 // Menu does not fit above the anchor. We move it to below.
1685 y = state_.initial_bounds.y() - kCenteredContextMenuYOffset;
1686 } else {
1687 y = std::max(0, state_.initial_bounds.y() - pref.height()) +
1688 kCenteredContextMenuYOffset;
1692 if (!state_.monitor_bounds.IsEmpty() &&
1693 y + pref.height() > state_.monitor_bounds.bottom()) {
1694 // The menu doesn't fit fully below the button on the screen. The menu
1695 // position with respect to the bounds will be preserved if it has
1696 // already been drawn. When the requested positioning is below the bounds
1697 // it will shrink the menu to make it fit below.
1698 // If the requested positioning is best fit, it will first try to fit the
1699 // menu below. If that does not fit it will try to place it above. If
1700 // that will not fit it will place it at the bottom of the work area and
1701 // moving it off the initial_bounds region to avoid overlap.
1702 // In all other requested position styles it will be flipped above and
1703 // the height will be shrunken to the usable height.
1704 if (item->actual_menu_position() == MenuItemView::POSITION_BELOW_BOUNDS) {
1705 pref.set_height(std::min(pref.height(),
1706 state_.monitor_bounds.bottom() - y));
1707 } else if (item->actual_menu_position() ==
1708 MenuItemView::POSITION_BEST_FIT) {
1709 MenuItemView::MenuPosition orientation =
1710 MenuItemView::POSITION_BELOW_BOUNDS;
1711 if (state_.monitor_bounds.height() < pref.height()) {
1712 // Handle very tall menus.
1713 pref.set_height(state_.monitor_bounds.height());
1714 y = state_.monitor_bounds.y();
1715 } else if (state_.monitor_bounds.y() + pref.height() <
1716 state_.initial_bounds.y()) {
1717 // Flipping upwards if there is enough space.
1718 y = state_.initial_bounds.y() - pref.height();
1719 orientation = MenuItemView::POSITION_ABOVE_BOUNDS;
1720 } else {
1721 // It is allowed to move the menu a bit around in order to get the
1722 // best fit and to avoid showing scroll elements.
1723 y = state_.monitor_bounds.bottom() - pref.height();
1725 if (orientation == MenuItemView::POSITION_BELOW_BOUNDS) {
1726 // The menu should never overlap the owning button. So move it.
1727 // We use the anchor view style to determine the preferred position
1728 // relative to the owning button.
1729 if (state_.anchor == MENU_ANCHOR_TOPLEFT) {
1730 // The menu starts with the same x coordinate as the owning button.
1731 if (x + state_.initial_bounds.width() + pref.width() >
1732 state_.monitor_bounds.right())
1733 x -= pref.width(); // Move the menu to the left of the button.
1734 else
1735 x += state_.initial_bounds.width(); // Move the menu right.
1736 } else {
1737 // The menu should end with the same x coordinate as the owning
1738 // button.
1739 if (state_.monitor_bounds.x() >
1740 state_.initial_bounds.x() - pref.width())
1741 x = state_.initial_bounds.right(); // Move right of the button.
1742 else
1743 x = state_.initial_bounds.x() - pref.width(); // Move left.
1746 item->set_actual_menu_position(orientation);
1747 } else {
1748 pref.set_height(std::min(pref.height(),
1749 state_.initial_bounds.y() - state_.monitor_bounds.y()));
1750 y = state_.initial_bounds.y() - pref.height();
1751 item->set_actual_menu_position(MenuItemView::POSITION_ABOVE_BOUNDS);
1753 } else if (item->actual_menu_position() ==
1754 MenuItemView::POSITION_ABOVE_BOUNDS) {
1755 pref.set_height(std::min(pref.height(),
1756 state_.initial_bounds.y() - state_.monitor_bounds.y()));
1757 y = state_.initial_bounds.y() - pref.height();
1758 } else {
1759 item->set_actual_menu_position(MenuItemView::POSITION_BELOW_BOUNDS);
1761 if (state_.monitor_bounds.width() != 0 &&
1762 menu_config.offset_context_menus && state_.context_menu) {
1763 if (x + pref.width() > state_.monitor_bounds.right())
1764 x = state_.initial_bounds.x() - pref.width() - 1;
1765 if (x < state_.monitor_bounds.x())
1766 x = state_.monitor_bounds.x();
1768 } else {
1769 // Not the first menu; position it relative to the bounds of the menu
1770 // item.
1771 gfx::Point item_loc;
1772 View::ConvertPointToScreen(item, &item_loc);
1774 // We must make sure we take into account the UI layout. If the layout is
1775 // RTL, then a 'leading' menu is positioned to the left of the parent menu
1776 // item and not to the right.
1777 bool layout_is_rtl = base::i18n::IsRTL();
1778 bool create_on_the_right = (prefer_leading && !layout_is_rtl) ||
1779 (!prefer_leading && layout_is_rtl);
1780 int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;
1782 if (create_on_the_right) {
1783 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1784 if (state_.monitor_bounds.width() != 0 &&
1785 x + pref.width() > state_.monitor_bounds.right()) {
1786 if (layout_is_rtl)
1787 *is_leading = true;
1788 else
1789 *is_leading = false;
1790 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1792 } else {
1793 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1794 if (state_.monitor_bounds.width() != 0 && x < state_.monitor_bounds.x()) {
1795 if (layout_is_rtl)
1796 *is_leading = false;
1797 else
1798 *is_leading = true;
1799 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1802 y = item_loc.y() - menu_config.menu_vertical_border_size;
1803 if (state_.monitor_bounds.width() != 0) {
1804 pref.set_height(std::min(pref.height(), state_.monitor_bounds.height()));
1805 if (y + pref.height() > state_.monitor_bounds.bottom())
1806 y = state_.monitor_bounds.bottom() - pref.height();
1807 if (y < state_.monitor_bounds.y())
1808 y = state_.monitor_bounds.y();
1812 if (state_.monitor_bounds.width() != 0) {
1813 if (x + pref.width() > state_.monitor_bounds.right())
1814 x = state_.monitor_bounds.right() - pref.width();
1815 if (x < state_.monitor_bounds.x())
1816 x = state_.monitor_bounds.x();
1818 return gfx::Rect(x, y, pref.width(), pref.height());
1821 gfx::Rect MenuController::CalculateBubbleMenuBounds(MenuItemView* item,
1822 bool prefer_leading,
1823 bool* is_leading) {
1824 DCHECK(item);
1825 DCHECK(!item->GetParentMenuItem());
1827 // Assume we can honor prefer_leading.
1828 *is_leading = prefer_leading;
1830 SubmenuView* submenu = item->GetSubmenu();
1831 DCHECK(submenu);
1833 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1834 const gfx::Rect& owner_bounds = pending_state_.initial_bounds;
1836 // First the size gets reduced to the possible space.
1837 if (!state_.monitor_bounds.IsEmpty()) {
1838 int max_width = state_.monitor_bounds.width();
1839 int max_height = state_.monitor_bounds.height();
1840 // In case of bubbles, the maximum width is limited by the space
1841 // between the display corner and the target area + the tip size.
1842 if (state_.anchor == MENU_ANCHOR_BUBBLE_LEFT) {
1843 max_width = owner_bounds.x() - state_.monitor_bounds.x() +
1844 kBubbleTipSizeLeftRight;
1845 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT) {
1846 max_width = state_.monitor_bounds.right() - owner_bounds.right() +
1847 kBubbleTipSizeLeftRight;
1848 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE) {
1849 max_height = owner_bounds.y() - state_.monitor_bounds.y() +
1850 kBubbleTipSizeTopBottom;
1851 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1852 max_height = state_.monitor_bounds.bottom() - owner_bounds.bottom() +
1853 kBubbleTipSizeTopBottom;
1855 // The space for the menu to cover should never get empty.
1856 DCHECK_GE(max_width, kBubbleTipSizeLeftRight);
1857 DCHECK_GE(max_height, kBubbleTipSizeTopBottom);
1858 pref.set_width(std::min(pref.width(), max_width));
1859 pref.set_height(std::min(pref.height(), max_height));
1861 // Also make sure that the menu does not go too wide.
1862 pref.set_width(std::min(pref.width(),
1863 item->GetDelegate()->GetMaxWidthForMenu(item)));
1865 int x, y;
1866 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE ||
1867 state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1868 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE)
1869 y = owner_bounds.y() - pref.height() + kBubbleTipSizeTopBottom;
1870 else
1871 y = owner_bounds.bottom() - kBubbleTipSizeTopBottom;
1873 x = owner_bounds.CenterPoint().x() - pref.width() / 2;
1874 int x_old = x;
1875 if (x < state_.monitor_bounds.x()) {
1876 x = state_.monitor_bounds.x();
1877 } else if (x + pref.width() > state_.monitor_bounds.right()) {
1878 x = state_.monitor_bounds.right() - pref.width();
1880 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1881 pref.width() / 2 - x + x_old);
1882 } else {
1883 if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT)
1884 x = owner_bounds.right() - kBubbleTipSizeLeftRight;
1885 else
1886 x = owner_bounds.x() - pref.width() + kBubbleTipSizeLeftRight;
1888 y = owner_bounds.CenterPoint().y() - pref.height() / 2;
1889 int y_old = y;
1890 if (y < state_.monitor_bounds.y()) {
1891 y = state_.monitor_bounds.y();
1892 } else if (y + pref.height() > state_.monitor_bounds.bottom()) {
1893 y = state_.monitor_bounds.bottom() - pref.height();
1895 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1896 pref.height() / 2 - y + y_old);
1898 return gfx::Rect(x, y, pref.width(), pref.height());
1901 // static
1902 int MenuController::MenuDepth(MenuItemView* item) {
1903 return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : 0;
1906 void MenuController::IncrementSelection(
1907 SelectionIncrementDirectionType direction) {
1908 MenuItemView* item = pending_state_.item;
1909 DCHECK(item);
1910 if (pending_state_.submenu_open && item->HasSubmenu() &&
1911 item->GetSubmenu()->IsShowing()) {
1912 // A menu is selected and open, but none of its children are selected,
1913 // select the first menu item that is visible and enabled.
1914 if (item->GetSubmenu()->GetMenuItemCount()) {
1915 MenuItemView* to_select = FindInitialSelectableMenuItem(item, direction);
1916 if (to_select)
1917 SetSelection(to_select, SELECTION_DEFAULT);
1918 return;
1922 if (item->has_children()) {
1923 CustomButton* button = GetFirstHotTrackedView(item);
1924 if (button) {
1925 button->SetHotTracked(false);
1926 View* to_make_hot = GetNextFocusableView(
1927 item, button, direction == INCREMENT_SELECTION_DOWN);
1928 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1929 if (button_hot) {
1930 button_hot->SetHotTracked(true);
1931 return;
1933 } else {
1934 View* to_make_hot =
1935 GetInitialFocusableView(item, direction == INCREMENT_SELECTION_DOWN);
1936 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1937 if (button_hot) {
1938 button_hot->SetHotTracked(true);
1939 return;
1944 MenuItemView* parent = item->GetParentMenuItem();
1945 if (parent) {
1946 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1947 if (parent_count > 1) {
1948 for (int i = 0; i < parent_count; ++i) {
1949 if (parent->GetSubmenu()->GetMenuItemAt(i) == item) {
1950 MenuItemView* to_select =
1951 FindNextSelectableMenuItem(parent, i, direction);
1952 if (!to_select)
1953 break;
1954 SetSelection(to_select, SELECTION_DEFAULT);
1955 View* to_make_hot = GetInitialFocusableView(
1956 to_select, direction == INCREMENT_SELECTION_DOWN);
1957 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1958 if (button_hot)
1959 button_hot->SetHotTracked(true);
1960 break;
1967 MenuItemView* MenuController::FindInitialSelectableMenuItem(
1968 MenuItemView* parent,
1969 SelectionIncrementDirectionType direction) {
1970 return FindNextSelectableMenuItem(
1971 parent, direction == INCREMENT_SELECTION_DOWN ? -1 : 0, direction);
1974 MenuItemView* MenuController::FindNextSelectableMenuItem(
1975 MenuItemView* parent,
1976 int index,
1977 SelectionIncrementDirectionType direction) {
1978 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1979 int stop_index = (index + parent_count) % parent_count;
1980 bool include_all_items =
1981 (index == -1 && direction == INCREMENT_SELECTION_DOWN) ||
1982 (index == 0 && direction == INCREMENT_SELECTION_UP);
1983 int delta = direction == INCREMENT_SELECTION_UP ? -1 : 1;
1984 // Loop through the menu items skipping any invisible menus. The loop stops
1985 // when we wrap or find a visible and enabled child.
1986 do {
1987 index = (index + delta + parent_count) % parent_count;
1988 if (index == stop_index && !include_all_items)
1989 return NULL;
1990 MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
1991 if (child->visible() && child->enabled())
1992 return child;
1993 } while (index != stop_index);
1994 return NULL;
1997 void MenuController::OpenSubmenuChangeSelectionIfCan() {
1998 MenuItemView* item = pending_state_.item;
1999 if (!item->HasSubmenu() || !item->enabled())
2000 return;
2001 MenuItemView* to_select = NULL;
2002 if (item->GetSubmenu()->GetMenuItemCount() > 0)
2003 to_select = FindInitialSelectableMenuItem(item, INCREMENT_SELECTION_DOWN);
2004 if (to_select) {
2005 SetSelection(to_select, SELECTION_UPDATE_IMMEDIATELY);
2006 return;
2008 // No menu items, just show the sub-menu.
2009 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
2012 void MenuController::CloseSubmenu() {
2013 MenuItemView* item = state_.item;
2014 DCHECK(item);
2015 if (!item->GetParentMenuItem())
2016 return;
2017 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing())
2018 SetSelection(item, SELECTION_UPDATE_IMMEDIATELY);
2019 else if (item->GetParentMenuItem()->GetParentMenuItem())
2020 SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY);
2023 MenuController::SelectByCharDetails MenuController::FindChildForMnemonic(
2024 MenuItemView* parent,
2025 base::char16 key,
2026 bool (*match_function)(MenuItemView* menu, base::char16 mnemonic)) {
2027 SubmenuView* submenu = parent->GetSubmenu();
2028 DCHECK(submenu);
2029 SelectByCharDetails details;
2031 for (int i = 0, menu_item_count = submenu->GetMenuItemCount();
2032 i < menu_item_count; ++i) {
2033 MenuItemView* child = submenu->GetMenuItemAt(i);
2034 if (child->enabled() && child->visible()) {
2035 if (child == pending_state_.item)
2036 details.index_of_item = i;
2037 if (match_function(child, key)) {
2038 if (details.first_match == -1)
2039 details.first_match = i;
2040 else
2041 details.has_multiple = true;
2042 if (details.next_match == -1 && details.index_of_item != -1 &&
2043 i > details.index_of_item)
2044 details.next_match = i;
2048 return details;
2051 void MenuController::AcceptOrSelect(MenuItemView* parent,
2052 const SelectByCharDetails& details) {
2053 // This should only be invoked if there is a match.
2054 DCHECK(details.first_match != -1);
2055 DCHECK(parent->HasSubmenu());
2056 SubmenuView* submenu = parent->GetSubmenu();
2057 DCHECK(submenu);
2058 if (!details.has_multiple) {
2059 // There's only one match, activate it (or open if it has a submenu).
2060 if (submenu->GetMenuItemAt(details.first_match)->HasSubmenu()) {
2061 SetSelection(submenu->GetMenuItemAt(details.first_match),
2062 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
2063 } else {
2064 Accept(submenu->GetMenuItemAt(details.first_match), 0);
2066 } else if (details.index_of_item == -1 || details.next_match == -1) {
2067 SetSelection(submenu->GetMenuItemAt(details.first_match),
2068 SELECTION_DEFAULT);
2069 } else {
2070 SetSelection(submenu->GetMenuItemAt(details.next_match),
2071 SELECTION_DEFAULT);
2075 void MenuController::SelectByChar(base::char16 character) {
2076 base::char16 char_array[] = { character, 0 };
2077 base::char16 key = base::i18n::ToLower(char_array)[0];
2078 MenuItemView* item = pending_state_.item;
2079 if (!item->HasSubmenu() || !item->GetSubmenu()->IsShowing())
2080 item = item->GetParentMenuItem();
2081 DCHECK(item);
2082 DCHECK(item->HasSubmenu());
2083 DCHECK(item->GetSubmenu());
2084 if (item->GetSubmenu()->GetMenuItemCount() == 0)
2085 return;
2087 // Look for matches based on mnemonic first.
2088 SelectByCharDetails details =
2089 FindChildForMnemonic(item, key, &MatchesMnemonic);
2090 if (details.first_match != -1) {
2091 AcceptOrSelect(item, details);
2092 return;
2095 if (is_combobox_) {
2096 item->GetSubmenu()->GetPrefixSelector()->InsertChar(character, 0);
2097 } else {
2098 // If no mnemonics found, look at first character of titles.
2099 details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic);
2100 if (details.first_match != -1)
2101 AcceptOrSelect(item, details);
2105 void MenuController::RepostEvent(SubmenuView* source,
2106 const ui::LocatedEvent& event) {
2107 if (!event.IsMouseEvent()) {
2108 // TODO(rbyers): Gesture event repost is tricky to get right
2109 // crbug.com/170987.
2110 DCHECK(event.IsGestureEvent());
2111 return;
2114 #if defined(OS_WIN)
2115 if (!state_.item) {
2116 // We some times get an event after closing all the menus. Ignore it. Make
2117 // sure the menu is in fact not visible. If the menu is visible, then
2118 // we're in a bad state where we think the menu isn't visibile but it is.
2119 DCHECK(!source->GetWidget()->IsVisible());
2120 return;
2123 state_.item->GetRootMenuItem()->GetSubmenu()->ReleaseCapture();
2124 #endif
2126 gfx::Point screen_loc(event.location());
2127 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
2128 gfx::NativeView native_view = source->GetWidget()->GetNativeView();
2129 if (!native_view)
2130 return;
2132 gfx::Screen* screen = gfx::Screen::GetScreenFor(native_view);
2133 gfx::NativeWindow window = screen->GetWindowAtScreenPoint(screen_loc);
2135 #if defined(OS_WIN)
2136 // Convert screen_loc to pixels for the Win32 API's like WindowFromPoint,
2137 // PostMessage/SendMessage to work correctly. These API's expect the
2138 // coordinates to be in pixels.
2139 // PostMessage() to metro windows isn't allowed (access will be denied). Don't
2140 // try to repost with Win32 if the window under the mouse press is in metro.
2141 if (!ViewsDelegate::GetInstance() ||
2142 !ViewsDelegate::GetInstance()->IsWindowInMetro(window)) {
2143 gfx::Point screen_loc_pixels = gfx::win::DIPToScreenPoint(screen_loc);
2144 HWND target_window = window ? HWNDForNativeWindow(window) :
2145 WindowFromPoint(screen_loc_pixels.ToPOINT());
2146 HWND source_window = HWNDForNativeView(native_view);
2147 if (!target_window || !source_window ||
2148 GetWindowThreadProcessId(source_window, NULL) !=
2149 GetWindowThreadProcessId(target_window, NULL)) {
2150 // Even though we have mouse capture, windows generates a mouse event if
2151 // the other window is in a separate thread. Only repost an event if
2152 // |target_window| and |source_window| were created on the same thread,
2153 // else double events can occur and lead to bad behavior.
2154 return;
2157 // Determine whether the click was in the client area or not.
2158 // NOTE: WM_NCHITTEST coordinates are relative to the screen.
2159 LPARAM coords = MAKELPARAM(screen_loc_pixels.x(), screen_loc_pixels.y());
2160 LRESULT nc_hit_result = SendMessage(target_window, WM_NCHITTEST, 0, coords);
2161 const bool client_area = nc_hit_result == HTCLIENT;
2163 // TODO(sky): this isn't right. The event to generate should correspond with
2164 // the event we just got. MouseEvent only tells us what is down, which may
2165 // differ. Need to add ability to get changed button from MouseEvent.
2166 int event_type;
2167 int flags = event.flags();
2168 if (flags & ui::EF_LEFT_MOUSE_BUTTON) {
2169 event_type = client_area ? WM_LBUTTONDOWN : WM_NCLBUTTONDOWN;
2170 } else if (flags & ui::EF_MIDDLE_MOUSE_BUTTON) {
2171 event_type = client_area ? WM_MBUTTONDOWN : WM_NCMBUTTONDOWN;
2172 } else if (flags & ui::EF_RIGHT_MOUSE_BUTTON) {
2173 event_type = client_area ? WM_RBUTTONDOWN : WM_NCRBUTTONDOWN;
2174 } else {
2175 NOTREACHED();
2176 return;
2179 int window_x = screen_loc_pixels.x();
2180 int window_y = screen_loc_pixels.y();
2181 if (client_area) {
2182 POINT pt = { window_x, window_y };
2183 ScreenToClient(target_window, &pt);
2184 window_x = pt.x;
2185 window_y = pt.y;
2188 WPARAM target = client_area ? event.native_event().wParam : nc_hit_result;
2189 LPARAM window_coords = MAKELPARAM(window_x, window_y);
2190 PostMessage(target_window, event_type, target, window_coords);
2191 return;
2193 #endif
2194 // Non-Windows Aura or |window| is in metro mode.
2195 if (!window)
2196 return;
2198 message_loop_->RepostEventToWindow(event, window, screen_loc);
2201 void MenuController::SetDropMenuItem(
2202 MenuItemView* new_target,
2203 MenuDelegate::DropPosition new_position) {
2204 if (new_target == drop_target_ && new_position == drop_position_)
2205 return;
2207 if (drop_target_) {
2208 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2209 NULL, MenuDelegate::DROP_NONE);
2211 drop_target_ = new_target;
2212 drop_position_ = new_position;
2213 if (drop_target_) {
2214 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2215 drop_target_, drop_position_);
2219 void MenuController::UpdateScrolling(const MenuPart& part) {
2220 if (!part.is_scroll() && !scroll_task_.get())
2221 return;
2223 if (!scroll_task_.get())
2224 scroll_task_.reset(new MenuScrollTask());
2225 scroll_task_->Update(part);
2228 void MenuController::StopScrolling() {
2229 scroll_task_.reset(NULL);
2232 void MenuController::UpdateActiveMouseView(SubmenuView* event_source,
2233 const ui::MouseEvent& event,
2234 View* target_menu) {
2235 View* target = NULL;
2236 gfx::Point target_menu_loc(event.location());
2237 if (target_menu && target_menu->has_children()) {
2238 // Locate the deepest child view to send events to. This code assumes we
2239 // don't have to walk up the tree to find a view interested in events. This
2240 // is currently true for the cases we are embedding views, but if we embed
2241 // more complex hierarchies it'll need to change.
2242 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2243 &target_menu_loc);
2244 View::ConvertPointFromScreen(target_menu, &target_menu_loc);
2245 target = target_menu->GetEventHandlerForPoint(target_menu_loc);
2246 if (target == target_menu || !target->enabled())
2247 target = NULL;
2249 View* active_mouse_view = GetActiveMouseView();
2250 if (target != active_mouse_view) {
2251 SendMouseCaptureLostToActiveView();
2252 active_mouse_view = target;
2253 SetActiveMouseView(active_mouse_view);
2254 if (active_mouse_view) {
2255 gfx::Point target_point(target_menu_loc);
2256 View::ConvertPointToTarget(
2257 target_menu, active_mouse_view, &target_point);
2258 ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED, target_point,
2259 target_point, ui::EventTimeForNow(), 0,
2261 active_mouse_view->OnMouseEntered(mouse_entered_event);
2263 ui::MouseEvent mouse_pressed_event(
2264 ui::ET_MOUSE_PRESSED, target_point, target_point,
2265 ui::EventTimeForNow(), event.flags(), event.changed_button_flags());
2266 active_mouse_view->OnMousePressed(mouse_pressed_event);
2270 if (active_mouse_view) {
2271 gfx::Point target_point(target_menu_loc);
2272 View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point);
2273 ui::MouseEvent mouse_dragged_event(
2274 ui::ET_MOUSE_DRAGGED, target_point, target_point, ui::EventTimeForNow(),
2275 event.flags(), event.changed_button_flags());
2276 active_mouse_view->OnMouseDragged(mouse_dragged_event);
2280 void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source,
2281 const ui::MouseEvent& event) {
2282 View* active_mouse_view = GetActiveMouseView();
2283 if (!active_mouse_view)
2284 return;
2286 gfx::Point target_loc(event.location());
2287 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2288 &target_loc);
2289 View::ConvertPointFromScreen(active_mouse_view, &target_loc);
2290 ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, target_loc, target_loc,
2291 ui::EventTimeForNow(), event.flags(),
2292 event.changed_button_flags());
2293 // Reset active mouse view before sending mouse released. That way if it calls
2294 // back to us, we aren't in a weird state.
2295 SetActiveMouseView(NULL);
2296 active_mouse_view->OnMouseReleased(release_event);
2299 void MenuController::SendMouseCaptureLostToActiveView() {
2300 View* active_mouse_view = GetActiveMouseView();
2301 if (!active_mouse_view)
2302 return;
2304 // Reset the active_mouse_view_ before sending mouse capture lost. That way if
2305 // it calls back to us, we aren't in a weird state.
2306 SetActiveMouseView(NULL);
2307 active_mouse_view->OnMouseCaptureLost();
2310 void MenuController::SetActiveMouseView(View* view) {
2311 if (view)
2312 ViewStorage::GetInstance()->StoreView(active_mouse_view_id_, view);
2313 else
2314 ViewStorage::GetInstance()->RemoveView(active_mouse_view_id_);
2317 View* MenuController::GetActiveMouseView() {
2318 return ViewStorage::GetInstance()->RetrieveView(active_mouse_view_id_);
2321 void MenuController::SetExitType(ExitType type) {
2322 exit_type_ = type;
2323 // Exit nested message loops as soon as possible. We do this as
2324 // MessagePumpDispatcher is only invoked before native events, which means
2325 // its entirely possible for a Widget::CloseNow() task to be processed before
2326 // the next native message. We quite the nested message loop as soon as
2327 // possible to avoid having deleted views classes (such as widgets and
2328 // rootviews) on the stack when the nested message loop stops.
2330 // It's safe to invoke QuitNestedMessageLoop() multiple times, it only effects
2331 // the current loop.
2332 bool quit_now = exit_type_ != EXIT_NONE && message_loop_depth_;
2333 if (quit_now)
2334 TerminateNestedMessageLoop();
2337 void MenuController::TerminateNestedMessageLoop() {
2338 message_loop_->QuitNow();
2341 void MenuController::HandleMouseLocation(SubmenuView* source,
2342 const gfx::Point& mouse_location) {
2343 if (showing_submenu_)
2344 return;
2346 // Ignore mouse events if we're closing the menu.
2347 if (exit_type_ != EXIT_NONE)
2348 return;
2350 MenuPart part = GetMenuPart(source, mouse_location);
2352 UpdateScrolling(part);
2354 if (!blocking_run_)
2355 return;
2357 if (part.type == MenuPart::NONE && ShowSiblingMenu(source, mouse_location))
2358 return;
2360 if (part.type == MenuPart::MENU_ITEM && part.menu) {
2361 SetSelection(part.menu, SELECTION_OPEN_SUBMENU);
2362 } else if (!part.is_scroll() && pending_state_.item &&
2363 pending_state_.item->GetParentMenuItem() &&
2364 (!pending_state_.item->HasSubmenu() ||
2365 !pending_state_.item->GetSubmenu()->IsShowing())) {
2366 // On exit if the user hasn't selected an item with a submenu, move the
2367 // selection back to the parent menu item.
2368 SetSelection(pending_state_.item->GetParentMenuItem(),
2369 SELECTION_OPEN_SUBMENU);
2373 gfx::Screen* MenuController::GetScreen() {
2374 Widget* root = owner_ ? owner_->GetTopLevelWidget() : NULL;
2375 return root ? gfx::Screen::GetScreenFor(root->GetNativeView())
2376 : gfx::Screen::GetNativeScreen();
2379 } // namespace views