Add ICU message format support
[chromium-blink-merge.git] / ui / views / controls / menu / menu_controller.cc
blob2702529c43d08d38b4a31479217295307b3a1311
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 bool should_quit = character ? SelectByChar(character) : !OnKeyDown(key_code);
824 if (should_quit || exit_type() != MenuController::EXIT_NONE)
825 TerminateNestedMessageLoop();
827 return ui::POST_DISPATCH_NONE;
830 void MenuController::UpdateSubmenuSelection(SubmenuView* submenu) {
831 if (submenu->IsShowing()) {
832 gfx::Point point = GetScreen()->GetCursorScreenPoint();
833 const SubmenuView* root_submenu =
834 submenu->GetMenuItem()->GetRootMenuItem()->GetSubmenu();
835 View::ConvertPointFromScreen(
836 root_submenu->GetWidget()->GetRootView(), &point);
837 HandleMouseLocation(submenu, point);
841 void MenuController::OnWidgetDestroying(Widget* widget) {
842 DCHECK_EQ(owner_, widget);
843 owner_->RemoveObserver(this);
844 owner_ = NULL;
845 message_loop_->ClearOwner();
848 bool MenuController::IsCancelAllTimerRunningForTest() {
849 return cancel_all_timer_.IsRunning();
852 // static
853 void MenuController::TurnOffMenuSelectionHoldForTest() {
854 menu_selection_hold_time_ms = -1;
857 void MenuController::SetSelection(MenuItemView* menu_item,
858 int selection_types) {
859 size_t paths_differ_at = 0;
860 std::vector<MenuItemView*> current_path;
861 std::vector<MenuItemView*> new_path;
862 BuildPathsAndCalculateDiff(pending_state_.item, menu_item, &current_path,
863 &new_path, &paths_differ_at);
865 size_t current_size = current_path.size();
866 size_t new_size = new_path.size();
868 bool pending_item_changed = pending_state_.item != menu_item;
869 if (pending_item_changed && pending_state_.item) {
870 CustomButton* button = GetFirstHotTrackedView(pending_state_.item);
871 if (button)
872 button->SetHotTracked(false);
875 // Notify the old path it isn't selected.
876 MenuDelegate* current_delegate =
877 current_path.empty() ? NULL : current_path.front()->GetDelegate();
878 for (size_t i = paths_differ_at; i < current_size; ++i) {
879 if (current_delegate &&
880 current_path[i]->GetType() == MenuItemView::SUBMENU) {
881 current_delegate->WillHideMenu(current_path[i]);
883 current_path[i]->SetSelected(false);
886 // Notify the new path it is selected.
887 for (size_t i = paths_differ_at; i < new_size; ++i) {
888 new_path[i]->ScrollRectToVisible(new_path[i]->GetLocalBounds());
889 new_path[i]->SetSelected(true);
892 if (menu_item && menu_item->GetDelegate())
893 menu_item->GetDelegate()->SelectionChanged(menu_item);
895 DCHECK(menu_item || (selection_types & SELECTION_EXIT) != 0);
897 pending_state_.item = menu_item;
898 pending_state_.submenu_open = (selection_types & SELECTION_OPEN_SUBMENU) != 0;
900 // Stop timers.
901 StopCancelAllTimer();
902 // Resets show timer only when pending menu item is changed.
903 if (pending_item_changed)
904 StopShowTimer();
906 if (selection_types & SELECTION_UPDATE_IMMEDIATELY)
907 CommitPendingSelection();
908 else if (pending_item_changed)
909 StartShowTimer();
911 // Notify an accessibility focus event on all menu items except for the root.
912 if (menu_item &&
913 (MenuDepth(menu_item) != 1 ||
914 menu_item->GetType() != MenuItemView::SUBMENU)) {
915 menu_item->NotifyAccessibilityEvent(
916 ui::AX_EVENT_FOCUS, true);
920 void MenuController::SetSelectionOnPointerDown(SubmenuView* source,
921 const ui::LocatedEvent& event) {
922 if (!blocking_run_)
923 return;
925 DCHECK(!GetActiveMouseView());
927 MenuPart part = GetMenuPart(source, event.location());
928 if (part.is_scroll())
929 return; // Ignore presses on scroll buttons.
931 // When this menu is opened through a touch event, a simulated right-click
932 // is sent before the menu appears. Ignore it.
933 if ((event.flags() & ui::EF_RIGHT_MOUSE_BUTTON) &&
934 (event.flags() & ui::EF_FROM_TOUCH))
935 return;
937 if (part.type == MenuPart::NONE ||
938 (part.type == MenuPart::MENU_ITEM && part.menu &&
939 part.menu->GetRootMenuItem() != state_.item->GetRootMenuItem())) {
940 // Remember the time stamp of the current (press down) event. The owner can
941 // then use this to figure out if this menu was finished with the same click
942 // which is sent to it thereafter.
943 closing_event_time_ = event.time_stamp();
945 // Mouse wasn't pressed over any menu, or the active menu, cancel.
947 #if defined(OS_WIN)
948 // We're going to close and we own the mouse capture. We need to repost the
949 // mouse down, otherwise the window the user clicked on won't get the event.
950 RepostEvent(source, event);
951 #endif
953 // And close.
954 ExitType exit_type = EXIT_ALL;
955 if (!menu_stack_.empty()) {
956 // We're running nested menus. Only exit all if the mouse wasn't over one
957 // of the menus from the last run.
958 gfx::Point screen_loc(event.location());
959 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
960 MenuPart last_part = GetMenuPartByScreenCoordinateUsingMenu(
961 menu_stack_.back().first.item, screen_loc);
962 if (last_part.type != MenuPart::NONE)
963 exit_type = EXIT_OUTERMOST;
965 Cancel(exit_type);
967 #if defined(OS_CHROMEOS)
968 // We're going to exit the menu and want to repost the event so that is
969 // is handled normally after the context menu has exited. We call
970 // RepostEvent after Cancel so that mouse capture has been released so
971 // that finding the event target is unaffected by the current capture.
972 RepostEvent(source, event);
973 #endif
974 // Do not repost events for Linux Aura because this behavior is more
975 // consistent with the behavior of other Linux apps.
976 return;
979 // On a press we immediately commit the selection, that way a submenu
980 // pops up immediately rather than after a delay.
981 int selection_types = SELECTION_UPDATE_IMMEDIATELY;
982 if (!part.menu) {
983 part.menu = part.parent;
984 selection_types |= SELECTION_OPEN_SUBMENU;
985 } else {
986 if (part.menu->GetDelegate()->CanDrag(part.menu)) {
987 possible_drag_ = true;
988 press_pt_ = event.location();
990 if (part.menu->HasSubmenu())
991 selection_types |= SELECTION_OPEN_SUBMENU;
993 SetSelection(part.menu, selection_types);
996 void MenuController::StartDrag(SubmenuView* source,
997 const gfx::Point& location) {
998 MenuItemView* item = state_.item;
999 DCHECK(item);
1000 // Points are in the coordinates of the submenu, need to map to that of
1001 // the selected item. Additionally source may not be the parent of
1002 // the selected item, so need to map to screen first then to item.
1003 gfx::Point press_loc(location);
1004 View::ConvertPointToScreen(source->GetScrollViewContainer(), &press_loc);
1005 View::ConvertPointFromScreen(item, &press_loc);
1006 gfx::Point widget_loc(press_loc);
1007 View::ConvertPointToWidget(item, &widget_loc);
1008 scoped_ptr<gfx::Canvas> canvas(GetCanvasForDragImage(
1009 source->GetWidget(), gfx::Size(item->width(), item->height())));
1010 item->PaintButton(canvas.get(), MenuItemView::PB_FOR_DRAG);
1012 OSExchangeData data;
1013 item->GetDelegate()->WriteDragData(item, &data);
1014 drag_utils::SetDragImageOnDataObject(*canvas,
1015 press_loc.OffsetFromOrigin(),
1016 &data);
1017 StopScrolling();
1018 int drag_ops = item->GetDelegate()->GetDragOperations(item);
1019 did_initiate_drag_ = true;
1020 // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below.
1021 item->GetWidget()->RunShellDrag(NULL, data, widget_loc, drag_ops,
1022 ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
1023 did_initiate_drag_ = false;
1026 bool MenuController::OnKeyDown(ui::KeyboardCode key_code) {
1027 DCHECK(blocking_run_);
1029 switch (key_code) {
1030 case ui::VKEY_UP:
1031 IncrementSelection(INCREMENT_SELECTION_UP);
1032 break;
1034 case ui::VKEY_DOWN:
1035 IncrementSelection(INCREMENT_SELECTION_DOWN);
1036 break;
1038 // Handling of VK_RIGHT and VK_LEFT is different depending on the UI
1039 // layout.
1040 case ui::VKEY_RIGHT:
1041 if (base::i18n::IsRTL())
1042 CloseSubmenu();
1043 else
1044 OpenSubmenuChangeSelectionIfCan();
1045 break;
1047 case ui::VKEY_LEFT:
1048 if (base::i18n::IsRTL())
1049 OpenSubmenuChangeSelectionIfCan();
1050 else
1051 CloseSubmenu();
1052 break;
1054 // On Mac, treat space the same as return.
1055 #if !defined(OS_MACOSX)
1056 case ui::VKEY_SPACE:
1057 if (SendAcceleratorToHotTrackedView() == ACCELERATOR_PROCESSED_EXIT)
1058 return false;
1059 break;
1060 #endif
1062 case ui::VKEY_F4:
1063 if (!is_combobox_)
1064 break;
1065 // Fallthrough to accept or dismiss combobox menus on F4, like windows.
1066 case ui::VKEY_RETURN:
1067 #if defined(OS_MACOSX)
1068 case ui::VKEY_SPACE:
1069 #endif
1070 if (pending_state_.item) {
1071 if (pending_state_.item->HasSubmenu()) {
1072 if (key_code == ui::VKEY_F4 &&
1073 pending_state_.item->GetSubmenu()->IsShowing())
1074 return false;
1075 else
1076 OpenSubmenuChangeSelectionIfCan();
1077 } else {
1078 SendAcceleratorResultType result = SendAcceleratorToHotTrackedView();
1079 if (result == ACCELERATOR_NOT_PROCESSED &&
1080 pending_state_.item->enabled()) {
1081 Accept(pending_state_.item, 0);
1082 return false;
1083 } else if (result == ACCELERATOR_PROCESSED_EXIT) {
1084 return false;
1088 break;
1090 case ui::VKEY_ESCAPE:
1091 if (!state_.item->GetParentMenuItem() ||
1092 (!state_.item->GetParentMenuItem()->GetParentMenuItem() &&
1093 (!state_.item->HasSubmenu() ||
1094 !state_.item->GetSubmenu()->IsShowing()))) {
1095 // User pressed escape and only one menu is shown, cancel it.
1096 Cancel(EXIT_OUTERMOST);
1097 return false;
1099 CloseSubmenu();
1100 break;
1102 case ui::VKEY_APPS: {
1103 CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item);
1104 if (hot_view) {
1105 hot_view->ShowContextMenu(hot_view->GetKeyboardContextMenuLocation(),
1106 ui::MENU_SOURCE_KEYBOARD);
1107 return false;
1108 } else if (pending_state_.item->enabled() &&
1109 pending_state_.item->GetRootMenuItem() !=
1110 pending_state_.item) {
1111 // Show the context menu for the given menu item. We don't try to show
1112 // the menu for the (boundless) root menu item. This can happen, e.g.,
1113 // when the user hits the APPS key after opening the menu, when no item
1114 // is selected, but showing a context menu for an implicitly-selected
1115 // and invisible item doesn't make sense.
1116 ShowContextMenu(pending_state_.item,
1117 pending_state_.item->GetKeyboardContextMenuLocation(),
1118 ui::MENU_SOURCE_KEYBOARD);
1119 return false;
1121 break;
1124 default:
1125 break;
1127 return true;
1130 MenuController::MenuController(ui::NativeTheme* theme,
1131 bool blocking,
1132 internal::MenuControllerDelegate* delegate)
1133 : blocking_run_(blocking),
1134 showing_(false),
1135 exit_type_(EXIT_NONE),
1136 did_capture_(false),
1137 result_(NULL),
1138 accept_event_flags_(0),
1139 drop_target_(NULL),
1140 drop_position_(MenuDelegate::DROP_UNKNOWN),
1141 owner_(NULL),
1142 possible_drag_(false),
1143 drag_in_progress_(false),
1144 did_initiate_drag_(false),
1145 valid_drop_coordinates_(false),
1146 last_drop_operation_(MenuDelegate::DROP_UNKNOWN),
1147 showing_submenu_(false),
1148 active_mouse_view_id_(ViewStorage::GetInstance()->CreateStorageID()),
1149 delegate_(delegate),
1150 message_loop_depth_(0),
1151 menu_config_(theme),
1152 closing_event_time_(base::TimeDelta()),
1153 menu_start_time_(base::TimeTicks()),
1154 is_combobox_(false),
1155 item_selected_by_touch_(false),
1156 message_loop_(MenuMessageLoop::Create()) {
1157 active_instance_ = this;
1160 MenuController::~MenuController() {
1161 DCHECK(!showing_);
1162 if (owner_)
1163 owner_->RemoveObserver(this);
1164 if (active_instance_ == this)
1165 active_instance_ = NULL;
1166 StopShowTimer();
1167 StopCancelAllTimer();
1170 void MenuController::RunMessageLoop(bool nested_menu) {
1171 message_loop_->Run(this, owner_, nested_menu);
1174 MenuController::SendAcceleratorResultType
1175 MenuController::SendAcceleratorToHotTrackedView() {
1176 CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item);
1177 if (!hot_view)
1178 return ACCELERATOR_NOT_PROCESSED;
1180 ui::Accelerator accelerator(ui::VKEY_RETURN, ui::EF_NONE);
1181 hot_view->AcceleratorPressed(accelerator);
1182 CustomButton* button = static_cast<CustomButton*>(hot_view);
1183 button->SetHotTracked(true);
1184 return (exit_type_ == EXIT_NONE) ?
1185 ACCELERATOR_PROCESSED : ACCELERATOR_PROCESSED_EXIT;
1188 void MenuController::UpdateInitialLocation(const gfx::Rect& bounds,
1189 MenuAnchorPosition position,
1190 bool context_menu) {
1191 pending_state_.context_menu = context_menu;
1192 pending_state_.initial_bounds = bounds;
1193 if (bounds.height() > 1) {
1194 // Inset the bounds slightly, otherwise drag coordinates don't line up
1195 // nicely and menus close prematurely.
1196 pending_state_.initial_bounds.Inset(0, 1);
1199 // Reverse anchor position for RTL languages.
1200 if (base::i18n::IsRTL() &&
1201 (position == MENU_ANCHOR_TOPRIGHT || position == MENU_ANCHOR_TOPLEFT)) {
1202 pending_state_.anchor = position == MENU_ANCHOR_TOPRIGHT
1203 ? MENU_ANCHOR_TOPLEFT
1204 : MENU_ANCHOR_TOPRIGHT;
1205 } else {
1206 pending_state_.anchor = position;
1209 // Calculate the bounds of the monitor we'll show menus on. Do this once to
1210 // avoid repeated system queries for the info.
1211 pending_state_.monitor_bounds = GetScreen()->GetDisplayNearestPoint(
1212 bounds.origin()).work_area();
1214 if (!pending_state_.monitor_bounds.Contains(bounds)) {
1215 // Use the monitor area if the work area doesn't contain the bounds. This
1216 // handles showing a menu from the launcher.
1217 gfx::Rect monitor_area = GetScreen()->GetDisplayNearestPoint(
1218 bounds.origin()).bounds();
1219 if (monitor_area.Contains(bounds))
1220 pending_state_.monitor_bounds = monitor_area;
1224 void MenuController::Accept(MenuItemView* item, int event_flags) {
1225 DCHECK(IsBlockingRun());
1226 result_ = item;
1227 if (item && !menu_stack_.empty() &&
1228 !item->GetDelegate()->ShouldCloseAllMenusOnExecute(item->GetCommand())) {
1229 SetExitType(EXIT_OUTERMOST);
1230 } else {
1231 SetExitType(EXIT_ALL);
1233 accept_event_flags_ = event_flags;
1236 bool MenuController::ShowSiblingMenu(SubmenuView* source,
1237 const gfx::Point& mouse_location) {
1238 if (!menu_stack_.empty() || !pressed_lock_.get())
1239 return false;
1241 View* source_view = source->GetScrollViewContainer();
1242 if (mouse_location.x() >= 0 &&
1243 mouse_location.x() < source_view->width() &&
1244 mouse_location.y() >= 0 &&
1245 mouse_location.y() < source_view->height()) {
1246 // The mouse is over the menu, no need to continue.
1247 return false;
1250 gfx::NativeWindow window_under_mouse = GetScreen()->GetWindowUnderCursor();
1251 // TODO(oshima): Replace with views only API.
1252 if (!owner_ || window_under_mouse != owner_->GetNativeWindow())
1253 return false;
1255 // The user moved the mouse outside the menu and over the owning window. See
1256 // if there is a sibling menu we should show.
1257 gfx::Point screen_point(mouse_location);
1258 View::ConvertPointToScreen(source_view, &screen_point);
1259 MenuAnchorPosition anchor;
1260 bool has_mnemonics;
1261 MenuButton* button = NULL;
1262 MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->
1263 GetSiblingMenu(source->GetMenuItem()->GetRootMenuItem(),
1264 screen_point, &anchor, &has_mnemonics, &button);
1265 if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu))
1266 return false;
1268 delegate_->SiblingMenuCreated(alt_menu);
1270 if (!button) {
1271 // If the delegate returns a menu, they must also return a button.
1272 NOTREACHED();
1273 return false;
1276 // There is a sibling menu, update the button state, hide the current menu
1277 // and show the new one.
1278 pressed_lock_.reset(new MenuButton::PressedLock(button));
1280 // Need to reset capture when we show the menu again, otherwise we aren't
1281 // going to get any events.
1282 did_capture_ = false;
1283 gfx::Point screen_menu_loc;
1284 View::ConvertPointToScreen(button, &screen_menu_loc);
1286 // It is currently not possible to show a submenu recursively in a bubble.
1287 DCHECK(!MenuItemView::IsBubble(anchor));
1288 // Subtract 1 from the height to make the popup flush with the button border.
1289 UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(),
1290 button->width(), button->height() - 1),
1291 anchor, state_.context_menu);
1292 alt_menu->PrepareForRun(
1293 false, has_mnemonics,
1294 source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_);
1295 alt_menu->controller_ = this;
1296 SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1297 return true;
1300 bool MenuController::ShowContextMenu(MenuItemView* menu_item,
1301 const gfx::Point& screen_location,
1302 ui::MenuSourceType source_type) {
1303 // Set the selection immediately, making sure the submenu is only open
1304 // if it already was.
1305 int selection_types = SELECTION_UPDATE_IMMEDIATELY;
1306 if (state_.item == pending_state_.item && state_.submenu_open)
1307 selection_types |= SELECTION_OPEN_SUBMENU;
1308 SetSelection(pending_state_.item, selection_types);
1310 if (menu_item->GetDelegate()->ShowContextMenu(
1311 menu_item, menu_item->GetCommand(), screen_location, source_type)) {
1312 SendMouseCaptureLostToActiveView();
1313 return true;
1315 return false;
1318 void MenuController::CloseAllNestedMenus() {
1319 for (std::list<NestedState>::iterator i = menu_stack_.begin();
1320 i != menu_stack_.end(); ++i) {
1321 State& state = i->first;
1322 MenuItemView* last_item = state.item;
1323 for (MenuItemView* item = last_item; item;
1324 item = item->GetParentMenuItem()) {
1325 CloseMenu(item);
1326 last_item = item;
1328 state.submenu_open = false;
1329 state.item = last_item;
1333 MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) {
1334 // Walk the view hierarchy until we find a menu item (or the root).
1335 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1336 while (child_under_mouse &&
1337 child_under_mouse->id() != MenuItemView::kMenuItemViewID) {
1338 child_under_mouse = child_under_mouse->parent();
1340 if (child_under_mouse && child_under_mouse->enabled() &&
1341 child_under_mouse->id() == MenuItemView::kMenuItemViewID) {
1342 return static_cast<MenuItemView*>(child_under_mouse);
1344 return NULL;
1347 MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) {
1348 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1349 if (child_under_mouse &&
1350 child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) {
1351 return static_cast<MenuItemView*>(child_under_mouse);
1353 return NULL;
1356 bool MenuController::IsScrollButtonAt(SubmenuView* source,
1357 int x,
1358 int y,
1359 MenuPart::Type* part) {
1360 MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer();
1361 View* child_under_mouse =
1362 scroll_view->GetEventHandlerForPoint(gfx::Point(x, y));
1363 if (child_under_mouse && child_under_mouse->enabled()) {
1364 if (child_under_mouse == scroll_view->scroll_up_button()) {
1365 *part = MenuPart::SCROLL_UP;
1366 return true;
1368 if (child_under_mouse == scroll_view->scroll_down_button()) {
1369 *part = MenuPart::SCROLL_DOWN;
1370 return true;
1373 return false;
1376 MenuController::MenuPart MenuController::GetMenuPart(
1377 SubmenuView* source,
1378 const gfx::Point& source_loc) {
1379 gfx::Point screen_loc(source_loc);
1380 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
1381 return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc);
1384 MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu(
1385 MenuItemView* item,
1386 const gfx::Point& screen_loc) {
1387 MenuPart part;
1388 for (; item; item = item->GetParentMenuItem()) {
1389 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1390 GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc,
1391 &part)) {
1392 return part;
1395 return part;
1398 bool MenuController::GetMenuPartByScreenCoordinateImpl(
1399 SubmenuView* menu,
1400 const gfx::Point& screen_loc,
1401 MenuPart* part) {
1402 // Is the mouse over the scroll buttons?
1403 gfx::Point scroll_view_loc = screen_loc;
1404 View* scroll_view_container = menu->GetScrollViewContainer();
1405 View::ConvertPointFromScreen(scroll_view_container, &scroll_view_loc);
1406 if (scroll_view_loc.x() < 0 ||
1407 scroll_view_loc.x() >= scroll_view_container->width() ||
1408 scroll_view_loc.y() < 0 ||
1409 scroll_view_loc.y() >= scroll_view_container->height()) {
1410 // Point isn't contained in menu.
1411 return false;
1413 if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(),
1414 &(part->type))) {
1415 part->submenu = menu;
1416 return true;
1419 // Not over the scroll button. Check the actual menu.
1420 if (DoesSubmenuContainLocation(menu, screen_loc)) {
1421 gfx::Point menu_loc = screen_loc;
1422 View::ConvertPointFromScreen(menu, &menu_loc);
1423 part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y());
1424 part->type = MenuPart::MENU_ITEM;
1425 part->submenu = menu;
1426 if (!part->menu)
1427 part->parent = menu->GetMenuItem();
1428 return true;
1431 // While the mouse isn't over a menu item or the scroll buttons of menu, it
1432 // is contained by menu and so we return true. If we didn't return true other
1433 // menus would be searched, even though they are likely obscured by us.
1434 return true;
1437 bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu,
1438 const gfx::Point& screen_loc) {
1439 gfx::Point view_loc = screen_loc;
1440 View::ConvertPointFromScreen(submenu, &view_loc);
1441 gfx::Rect vis_rect = submenu->GetVisibleBounds();
1442 return vis_rect.Contains(view_loc.x(), view_loc.y());
1445 void MenuController::CommitPendingSelection() {
1446 StopShowTimer();
1448 size_t paths_differ_at = 0;
1449 std::vector<MenuItemView*> current_path;
1450 std::vector<MenuItemView*> new_path;
1451 BuildPathsAndCalculateDiff(state_.item, pending_state_.item, &current_path,
1452 &new_path, &paths_differ_at);
1454 // Hide the old menu.
1455 for (size_t i = paths_differ_at; i < current_path.size(); ++i) {
1456 if (current_path[i]->HasSubmenu()) {
1457 current_path[i]->GetSubmenu()->Hide();
1461 // Copy pending to state_, making sure to preserve the direction menus were
1462 // opened.
1463 std::list<bool> pending_open_direction;
1464 state_.open_leading.swap(pending_open_direction);
1465 state_ = pending_state_;
1466 state_.open_leading.swap(pending_open_direction);
1468 int menu_depth = MenuDepth(state_.item);
1469 if (menu_depth == 0) {
1470 state_.open_leading.clear();
1471 } else {
1472 int cached_size = static_cast<int>(state_.open_leading.size());
1473 DCHECK_GE(menu_depth, 0);
1474 while (cached_size-- >= menu_depth)
1475 state_.open_leading.pop_back();
1478 if (!state_.item) {
1479 // Nothing to select.
1480 StopScrolling();
1481 return;
1484 // Open all the submenus preceeding the last menu item (last menu item is
1485 // handled next).
1486 if (new_path.size() > 1) {
1487 for (std::vector<MenuItemView*>::iterator i = new_path.begin();
1488 i != new_path.end() - 1; ++i) {
1489 OpenMenu(*i);
1493 if (state_.submenu_open) {
1494 // The submenu should be open, open the submenu if the item has a submenu.
1495 if (state_.item->HasSubmenu()) {
1496 OpenMenu(state_.item);
1497 } else {
1498 state_.submenu_open = false;
1500 } else if (state_.item->HasSubmenu() &&
1501 state_.item->GetSubmenu()->IsShowing()) {
1502 state_.item->GetSubmenu()->Hide();
1505 if (scroll_task_.get() && scroll_task_->submenu()) {
1506 // Stop the scrolling if none of the elements of the selection contain
1507 // the menu being scrolled.
1508 bool found = false;
1509 for (MenuItemView* item = state_.item; item && !found;
1510 item = item->GetParentMenuItem()) {
1511 found = (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1512 item->GetSubmenu() == scroll_task_->submenu());
1514 if (!found)
1515 StopScrolling();
1519 void MenuController::CloseMenu(MenuItemView* item) {
1520 DCHECK(item);
1521 if (!item->HasSubmenu())
1522 return;
1523 item->GetSubmenu()->Hide();
1526 void MenuController::OpenMenu(MenuItemView* item) {
1527 DCHECK(item);
1528 if (item->GetSubmenu()->IsShowing()) {
1529 return;
1532 OpenMenuImpl(item, true);
1533 did_capture_ = true;
1536 void MenuController::OpenMenuImpl(MenuItemView* item, bool show) {
1537 // TODO(oshima|sky): Don't show the menu if drag is in progress and
1538 // this menu doesn't support drag drop. See crbug.com/110495.
1539 if (show) {
1540 int old_count = item->GetSubmenu()->child_count();
1541 item->GetDelegate()->WillShowMenu(item);
1542 if (old_count != item->GetSubmenu()->child_count()) {
1543 // If the number of children changed then we may need to add empty items.
1544 item->RemoveEmptyMenus();
1545 item->AddEmptyMenus();
1548 bool prefer_leading =
1549 state_.open_leading.empty() ? true : state_.open_leading.back();
1550 bool resulting_direction;
1551 gfx::Rect bounds = MenuItemView::IsBubble(state_.anchor) ?
1552 CalculateBubbleMenuBounds(item, prefer_leading, &resulting_direction) :
1553 CalculateMenuBounds(item, prefer_leading, &resulting_direction);
1554 state_.open_leading.push_back(resulting_direction);
1555 bool do_capture = (!did_capture_ && blocking_run_);
1556 showing_submenu_ = true;
1557 if (show) {
1558 // Menus are the only place using kGroupingPropertyKey, so any value (other
1559 // than 0) is fine.
1560 const int kGroupingId = 1001;
1561 item->GetSubmenu()->ShowAt(owner_, bounds, do_capture);
1562 item->GetSubmenu()->GetWidget()->SetNativeWindowProperty(
1563 TooltipManager::kGroupingPropertyKey,
1564 reinterpret_cast<void*>(kGroupingId));
1565 } else {
1566 item->GetSubmenu()->Reposition(bounds);
1568 showing_submenu_ = false;
1571 void MenuController::MenuChildrenChanged(MenuItemView* item) {
1572 DCHECK(item);
1573 // Menu shouldn't be updated during drag operation.
1574 DCHECK(!GetActiveMouseView());
1576 // If the current item or pending item is a descendant of the item
1577 // that changed, move the selection back to the changed item.
1578 const MenuItemView* ancestor = state_.item;
1579 while (ancestor && ancestor != item)
1580 ancestor = ancestor->GetParentMenuItem();
1581 if (!ancestor) {
1582 ancestor = pending_state_.item;
1583 while (ancestor && ancestor != item)
1584 ancestor = ancestor->GetParentMenuItem();
1585 if (!ancestor)
1586 return;
1588 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1589 if (item->HasSubmenu())
1590 OpenMenuImpl(item, false);
1593 void MenuController::BuildPathsAndCalculateDiff(
1594 MenuItemView* old_item,
1595 MenuItemView* new_item,
1596 std::vector<MenuItemView*>* old_path,
1597 std::vector<MenuItemView*>* new_path,
1598 size_t* first_diff_at) {
1599 DCHECK(old_path && new_path && first_diff_at);
1600 BuildMenuItemPath(old_item, old_path);
1601 BuildMenuItemPath(new_item, new_path);
1603 size_t common_size = std::min(old_path->size(), new_path->size());
1605 // Find the first difference between the two paths, when the loop
1606 // returns, diff_i is the first index where the two paths differ.
1607 for (size_t i = 0; i < common_size; ++i) {
1608 if ((*old_path)[i] != (*new_path)[i]) {
1609 *first_diff_at = i;
1610 return;
1614 *first_diff_at = common_size;
1617 void MenuController::BuildMenuItemPath(MenuItemView* item,
1618 std::vector<MenuItemView*>* path) {
1619 if (!item)
1620 return;
1621 BuildMenuItemPath(item->GetParentMenuItem(), path);
1622 path->push_back(item);
1625 void MenuController::StartShowTimer() {
1626 show_timer_.Start(FROM_HERE,
1627 TimeDelta::FromMilliseconds(menu_config_.show_delay),
1628 this, &MenuController::CommitPendingSelection);
1631 void MenuController::StopShowTimer() {
1632 show_timer_.Stop();
1635 void MenuController::StartCancelAllTimer() {
1636 cancel_all_timer_.Start(FROM_HERE,
1637 TimeDelta::FromMilliseconds(kCloseOnExitTime),
1638 this, &MenuController::CancelAll);
1641 void MenuController::StopCancelAllTimer() {
1642 cancel_all_timer_.Stop();
1645 gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item,
1646 bool prefer_leading,
1647 bool* is_leading) {
1648 DCHECK(item);
1650 SubmenuView* submenu = item->GetSubmenu();
1651 DCHECK(submenu);
1653 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1655 // Don't let the menu go too wide.
1656 pref.set_width(std::min(pref.width(),
1657 item->GetDelegate()->GetMaxWidthForMenu(item)));
1658 if (!state_.monitor_bounds.IsEmpty())
1659 pref.set_width(std::min(pref.width(), state_.monitor_bounds.width()));
1661 // Assume we can honor prefer_leading.
1662 *is_leading = prefer_leading;
1664 int x, y;
1666 const MenuConfig& menu_config = item->GetMenuConfig();
1668 if (!item->GetParentMenuItem()) {
1669 // First item, position relative to initial location.
1670 x = state_.initial_bounds.x();
1672 // Offsets for context menu prevent menu items being selected by
1673 // simply opening the menu (bug 142992).
1674 if (menu_config.offset_context_menus && state_.context_menu)
1675 x += 1;
1677 y = state_.initial_bounds.bottom();
1678 if (state_.anchor == MENU_ANCHOR_TOPRIGHT) {
1679 x = x + state_.initial_bounds.width() - pref.width();
1680 if (menu_config.offset_context_menus && state_.context_menu)
1681 x -= 1;
1682 } else if (state_.anchor == MENU_ANCHOR_BOTTOMCENTER) {
1683 x = x - (pref.width() - state_.initial_bounds.width()) / 2;
1684 if (pref.height() >
1685 state_.initial_bounds.y() + kCenteredContextMenuYOffset) {
1686 // Menu does not fit above the anchor. We move it to below.
1687 y = state_.initial_bounds.y() - kCenteredContextMenuYOffset;
1688 } else {
1689 y = std::max(0, state_.initial_bounds.y() - pref.height()) +
1690 kCenteredContextMenuYOffset;
1694 if (!state_.monitor_bounds.IsEmpty() &&
1695 y + pref.height() > state_.monitor_bounds.bottom()) {
1696 // The menu doesn't fit fully below the button on the screen. The menu
1697 // position with respect to the bounds will be preserved if it has
1698 // already been drawn. When the requested positioning is below the bounds
1699 // it will shrink the menu to make it fit below.
1700 // If the requested positioning is best fit, it will first try to fit the
1701 // menu below. If that does not fit it will try to place it above. If
1702 // that will not fit it will place it at the bottom of the work area and
1703 // moving it off the initial_bounds region to avoid overlap.
1704 // In all other requested position styles it will be flipped above and
1705 // the height will be shrunken to the usable height.
1706 if (item->actual_menu_position() == MenuItemView::POSITION_BELOW_BOUNDS) {
1707 pref.set_height(std::min(pref.height(),
1708 state_.monitor_bounds.bottom() - y));
1709 } else if (item->actual_menu_position() ==
1710 MenuItemView::POSITION_BEST_FIT) {
1711 MenuItemView::MenuPosition orientation =
1712 MenuItemView::POSITION_BELOW_BOUNDS;
1713 if (state_.monitor_bounds.height() < pref.height()) {
1714 // Handle very tall menus.
1715 pref.set_height(state_.monitor_bounds.height());
1716 y = state_.monitor_bounds.y();
1717 } else if (state_.monitor_bounds.y() + pref.height() <
1718 state_.initial_bounds.y()) {
1719 // Flipping upwards if there is enough space.
1720 y = state_.initial_bounds.y() - pref.height();
1721 orientation = MenuItemView::POSITION_ABOVE_BOUNDS;
1722 } else {
1723 // It is allowed to move the menu a bit around in order to get the
1724 // best fit and to avoid showing scroll elements.
1725 y = state_.monitor_bounds.bottom() - pref.height();
1727 if (orientation == MenuItemView::POSITION_BELOW_BOUNDS) {
1728 // The menu should never overlap the owning button. So move it.
1729 // We use the anchor view style to determine the preferred position
1730 // relative to the owning button.
1731 if (state_.anchor == MENU_ANCHOR_TOPLEFT) {
1732 // The menu starts with the same x coordinate as the owning button.
1733 if (x + state_.initial_bounds.width() + pref.width() >
1734 state_.monitor_bounds.right())
1735 x -= pref.width(); // Move the menu to the left of the button.
1736 else
1737 x += state_.initial_bounds.width(); // Move the menu right.
1738 } else {
1739 // The menu should end with the same x coordinate as the owning
1740 // button.
1741 if (state_.monitor_bounds.x() >
1742 state_.initial_bounds.x() - pref.width())
1743 x = state_.initial_bounds.right(); // Move right of the button.
1744 else
1745 x = state_.initial_bounds.x() - pref.width(); // Move left.
1748 item->set_actual_menu_position(orientation);
1749 } else {
1750 pref.set_height(std::min(pref.height(),
1751 state_.initial_bounds.y() - state_.monitor_bounds.y()));
1752 y = state_.initial_bounds.y() - pref.height();
1753 item->set_actual_menu_position(MenuItemView::POSITION_ABOVE_BOUNDS);
1755 } else if (item->actual_menu_position() ==
1756 MenuItemView::POSITION_ABOVE_BOUNDS) {
1757 pref.set_height(std::min(pref.height(),
1758 state_.initial_bounds.y() - state_.monitor_bounds.y()));
1759 y = state_.initial_bounds.y() - pref.height();
1760 } else {
1761 item->set_actual_menu_position(MenuItemView::POSITION_BELOW_BOUNDS);
1763 if (state_.monitor_bounds.width() != 0 &&
1764 menu_config.offset_context_menus && state_.context_menu) {
1765 if (x + pref.width() > state_.monitor_bounds.right())
1766 x = state_.initial_bounds.x() - pref.width() - 1;
1767 if (x < state_.monitor_bounds.x())
1768 x = state_.monitor_bounds.x();
1770 } else {
1771 // Not the first menu; position it relative to the bounds of the menu
1772 // item.
1773 gfx::Point item_loc;
1774 View::ConvertPointToScreen(item, &item_loc);
1776 // We must make sure we take into account the UI layout. If the layout is
1777 // RTL, then a 'leading' menu is positioned to the left of the parent menu
1778 // item and not to the right.
1779 bool layout_is_rtl = base::i18n::IsRTL();
1780 bool create_on_the_right = (prefer_leading && !layout_is_rtl) ||
1781 (!prefer_leading && layout_is_rtl);
1782 int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;
1784 if (create_on_the_right) {
1785 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1786 if (state_.monitor_bounds.width() != 0 &&
1787 x + pref.width() > state_.monitor_bounds.right()) {
1788 if (layout_is_rtl)
1789 *is_leading = true;
1790 else
1791 *is_leading = false;
1792 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1794 } else {
1795 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1796 if (state_.monitor_bounds.width() != 0 && x < state_.monitor_bounds.x()) {
1797 if (layout_is_rtl)
1798 *is_leading = false;
1799 else
1800 *is_leading = true;
1801 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1804 y = item_loc.y() - menu_config.menu_vertical_border_size;
1805 if (state_.monitor_bounds.width() != 0) {
1806 pref.set_height(std::min(pref.height(), state_.monitor_bounds.height()));
1807 if (y + pref.height() > state_.monitor_bounds.bottom())
1808 y = state_.monitor_bounds.bottom() - pref.height();
1809 if (y < state_.monitor_bounds.y())
1810 y = state_.monitor_bounds.y();
1814 if (state_.monitor_bounds.width() != 0) {
1815 if (x + pref.width() > state_.monitor_bounds.right())
1816 x = state_.monitor_bounds.right() - pref.width();
1817 if (x < state_.monitor_bounds.x())
1818 x = state_.monitor_bounds.x();
1820 return gfx::Rect(x, y, pref.width(), pref.height());
1823 gfx::Rect MenuController::CalculateBubbleMenuBounds(MenuItemView* item,
1824 bool prefer_leading,
1825 bool* is_leading) {
1826 DCHECK(item);
1827 DCHECK(!item->GetParentMenuItem());
1829 // Assume we can honor prefer_leading.
1830 *is_leading = prefer_leading;
1832 SubmenuView* submenu = item->GetSubmenu();
1833 DCHECK(submenu);
1835 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1836 const gfx::Rect& owner_bounds = pending_state_.initial_bounds;
1838 // First the size gets reduced to the possible space.
1839 if (!state_.monitor_bounds.IsEmpty()) {
1840 int max_width = state_.monitor_bounds.width();
1841 int max_height = state_.monitor_bounds.height();
1842 // In case of bubbles, the maximum width is limited by the space
1843 // between the display corner and the target area + the tip size.
1844 if (state_.anchor == MENU_ANCHOR_BUBBLE_LEFT) {
1845 max_width = owner_bounds.x() - state_.monitor_bounds.x() +
1846 kBubbleTipSizeLeftRight;
1847 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT) {
1848 max_width = state_.monitor_bounds.right() - owner_bounds.right() +
1849 kBubbleTipSizeLeftRight;
1850 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE) {
1851 max_height = owner_bounds.y() - state_.monitor_bounds.y() +
1852 kBubbleTipSizeTopBottom;
1853 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1854 max_height = state_.monitor_bounds.bottom() - owner_bounds.bottom() +
1855 kBubbleTipSizeTopBottom;
1857 // The space for the menu to cover should never get empty.
1858 DCHECK_GE(max_width, kBubbleTipSizeLeftRight);
1859 DCHECK_GE(max_height, kBubbleTipSizeTopBottom);
1860 pref.set_width(std::min(pref.width(), max_width));
1861 pref.set_height(std::min(pref.height(), max_height));
1863 // Also make sure that the menu does not go too wide.
1864 pref.set_width(std::min(pref.width(),
1865 item->GetDelegate()->GetMaxWidthForMenu(item)));
1867 int x, y;
1868 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE ||
1869 state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1870 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE)
1871 y = owner_bounds.y() - pref.height() + kBubbleTipSizeTopBottom;
1872 else
1873 y = owner_bounds.bottom() - kBubbleTipSizeTopBottom;
1875 x = owner_bounds.CenterPoint().x() - pref.width() / 2;
1876 int x_old = x;
1877 if (x < state_.monitor_bounds.x()) {
1878 x = state_.monitor_bounds.x();
1879 } else if (x + pref.width() > state_.monitor_bounds.right()) {
1880 x = state_.monitor_bounds.right() - pref.width();
1882 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1883 pref.width() / 2 - x + x_old);
1884 } else {
1885 if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT)
1886 x = owner_bounds.right() - kBubbleTipSizeLeftRight;
1887 else
1888 x = owner_bounds.x() - pref.width() + kBubbleTipSizeLeftRight;
1890 y = owner_bounds.CenterPoint().y() - pref.height() / 2;
1891 int y_old = y;
1892 if (y < state_.monitor_bounds.y()) {
1893 y = state_.monitor_bounds.y();
1894 } else if (y + pref.height() > state_.monitor_bounds.bottom()) {
1895 y = state_.monitor_bounds.bottom() - pref.height();
1897 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1898 pref.height() / 2 - y + y_old);
1900 return gfx::Rect(x, y, pref.width(), pref.height());
1903 // static
1904 int MenuController::MenuDepth(MenuItemView* item) {
1905 return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : 0;
1908 void MenuController::IncrementSelection(
1909 SelectionIncrementDirectionType direction) {
1910 MenuItemView* item = pending_state_.item;
1911 DCHECK(item);
1912 if (pending_state_.submenu_open && item->HasSubmenu() &&
1913 item->GetSubmenu()->IsShowing()) {
1914 // A menu is selected and open, but none of its children are selected,
1915 // select the first menu item that is visible and enabled.
1916 if (item->GetSubmenu()->GetMenuItemCount()) {
1917 MenuItemView* to_select = FindInitialSelectableMenuItem(item, direction);
1918 if (to_select)
1919 SetSelection(to_select, SELECTION_DEFAULT);
1920 return;
1924 if (item->has_children()) {
1925 CustomButton* button = GetFirstHotTrackedView(item);
1926 if (button) {
1927 button->SetHotTracked(false);
1928 View* to_make_hot = GetNextFocusableView(
1929 item, button, direction == INCREMENT_SELECTION_DOWN);
1930 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1931 if (button_hot) {
1932 button_hot->SetHotTracked(true);
1933 return;
1935 } else {
1936 View* to_make_hot =
1937 GetInitialFocusableView(item, direction == INCREMENT_SELECTION_DOWN);
1938 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1939 if (button_hot) {
1940 button_hot->SetHotTracked(true);
1941 return;
1946 MenuItemView* parent = item->GetParentMenuItem();
1947 if (parent) {
1948 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1949 if (parent_count > 1) {
1950 for (int i = 0; i < parent_count; ++i) {
1951 if (parent->GetSubmenu()->GetMenuItemAt(i) == item) {
1952 MenuItemView* to_select =
1953 FindNextSelectableMenuItem(parent, i, direction);
1954 if (!to_select)
1955 break;
1956 SetSelection(to_select, SELECTION_DEFAULT);
1957 View* to_make_hot = GetInitialFocusableView(
1958 to_select, direction == INCREMENT_SELECTION_DOWN);
1959 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1960 if (button_hot)
1961 button_hot->SetHotTracked(true);
1962 break;
1969 MenuItemView* MenuController::FindInitialSelectableMenuItem(
1970 MenuItemView* parent,
1971 SelectionIncrementDirectionType direction) {
1972 return FindNextSelectableMenuItem(
1973 parent, direction == INCREMENT_SELECTION_DOWN ? -1 : 0, direction);
1976 MenuItemView* MenuController::FindNextSelectableMenuItem(
1977 MenuItemView* parent,
1978 int index,
1979 SelectionIncrementDirectionType direction) {
1980 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1981 int stop_index = (index + parent_count) % parent_count;
1982 bool include_all_items =
1983 (index == -1 && direction == INCREMENT_SELECTION_DOWN) ||
1984 (index == 0 && direction == INCREMENT_SELECTION_UP);
1985 int delta = direction == INCREMENT_SELECTION_UP ? -1 : 1;
1986 // Loop through the menu items skipping any invisible menus. The loop stops
1987 // when we wrap or find a visible and enabled child.
1988 do {
1989 index = (index + delta + parent_count) % parent_count;
1990 if (index == stop_index && !include_all_items)
1991 return NULL;
1992 MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
1993 if (child->visible() && child->enabled())
1994 return child;
1995 } while (index != stop_index);
1996 return NULL;
1999 void MenuController::OpenSubmenuChangeSelectionIfCan() {
2000 MenuItemView* item = pending_state_.item;
2001 if (!item->HasSubmenu() || !item->enabled())
2002 return;
2003 MenuItemView* to_select = NULL;
2004 if (item->GetSubmenu()->GetMenuItemCount() > 0)
2005 to_select = FindInitialSelectableMenuItem(item, INCREMENT_SELECTION_DOWN);
2006 if (to_select) {
2007 SetSelection(to_select, SELECTION_UPDATE_IMMEDIATELY);
2008 return;
2010 // No menu items, just show the sub-menu.
2011 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
2014 void MenuController::CloseSubmenu() {
2015 MenuItemView* item = state_.item;
2016 DCHECK(item);
2017 if (!item->GetParentMenuItem())
2018 return;
2019 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing())
2020 SetSelection(item, SELECTION_UPDATE_IMMEDIATELY);
2021 else if (item->GetParentMenuItem()->GetParentMenuItem())
2022 SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY);
2025 MenuController::SelectByCharDetails MenuController::FindChildForMnemonic(
2026 MenuItemView* parent,
2027 base::char16 key,
2028 bool (*match_function)(MenuItemView* menu, base::char16 mnemonic)) {
2029 SubmenuView* submenu = parent->GetSubmenu();
2030 DCHECK(submenu);
2031 SelectByCharDetails details;
2033 for (int i = 0, menu_item_count = submenu->GetMenuItemCount();
2034 i < menu_item_count; ++i) {
2035 MenuItemView* child = submenu->GetMenuItemAt(i);
2036 if (child->enabled() && child->visible()) {
2037 if (child == pending_state_.item)
2038 details.index_of_item = i;
2039 if (match_function(child, key)) {
2040 if (details.first_match == -1)
2041 details.first_match = i;
2042 else
2043 details.has_multiple = true;
2044 if (details.next_match == -1 && details.index_of_item != -1 &&
2045 i > details.index_of_item)
2046 details.next_match = i;
2050 return details;
2053 bool MenuController::AcceptOrSelect(MenuItemView* parent,
2054 const SelectByCharDetails& details) {
2055 // This should only be invoked if there is a match.
2056 DCHECK(details.first_match != -1);
2057 DCHECK(parent->HasSubmenu());
2058 SubmenuView* submenu = parent->GetSubmenu();
2059 DCHECK(submenu);
2060 if (!details.has_multiple) {
2061 // There's only one match, activate it (or open if it has a submenu).
2062 if (submenu->GetMenuItemAt(details.first_match)->HasSubmenu()) {
2063 SetSelection(submenu->GetMenuItemAt(details.first_match),
2064 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
2065 } else {
2066 Accept(submenu->GetMenuItemAt(details.first_match), 0);
2067 return true;
2069 } else if (details.index_of_item == -1 || details.next_match == -1) {
2070 SetSelection(submenu->GetMenuItemAt(details.first_match),
2071 SELECTION_DEFAULT);
2072 } else {
2073 SetSelection(submenu->GetMenuItemAt(details.next_match),
2074 SELECTION_DEFAULT);
2076 return false;
2079 bool MenuController::SelectByChar(base::char16 character) {
2080 base::char16 char_array[] = { character, 0 };
2081 base::char16 key = base::i18n::ToLower(char_array)[0];
2082 MenuItemView* item = pending_state_.item;
2083 if (!item->HasSubmenu() || !item->GetSubmenu()->IsShowing())
2084 item = item->GetParentMenuItem();
2085 DCHECK(item);
2086 DCHECK(item->HasSubmenu());
2087 DCHECK(item->GetSubmenu());
2088 if (item->GetSubmenu()->GetMenuItemCount() == 0)
2089 return false;
2091 // Look for matches based on mnemonic first.
2092 SelectByCharDetails details =
2093 FindChildForMnemonic(item, key, &MatchesMnemonic);
2094 if (details.first_match != -1)
2095 return AcceptOrSelect(item, details);
2097 if (is_combobox_) {
2098 item->GetSubmenu()->GetPrefixSelector()->InsertChar(character, 0);
2099 } else {
2100 // If no mnemonics found, look at first character of titles.
2101 details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic);
2102 if (details.first_match != -1)
2103 return AcceptOrSelect(item, details);
2106 return false;
2109 void MenuController::RepostEvent(SubmenuView* source,
2110 const ui::LocatedEvent& event) {
2111 if (!event.IsMouseEvent()) {
2112 // TODO(rbyers): Gesture event repost is tricky to get right
2113 // crbug.com/170987.
2114 DCHECK(event.IsGestureEvent());
2115 return;
2118 #if defined(OS_WIN)
2119 if (!state_.item) {
2120 // We some times get an event after closing all the menus. Ignore it. Make
2121 // sure the menu is in fact not visible. If the menu is visible, then
2122 // we're in a bad state where we think the menu isn't visibile but it is.
2123 DCHECK(!source->GetWidget()->IsVisible());
2124 return;
2127 state_.item->GetRootMenuItem()->GetSubmenu()->ReleaseCapture();
2128 #endif
2130 gfx::Point screen_loc(event.location());
2131 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
2132 gfx::NativeView native_view = source->GetWidget()->GetNativeView();
2133 if (!native_view)
2134 return;
2136 gfx::Screen* screen = gfx::Screen::GetScreenFor(native_view);
2137 gfx::NativeWindow window = screen->GetWindowAtScreenPoint(screen_loc);
2139 #if defined(OS_WIN)
2140 // Convert screen_loc to pixels for the Win32 API's like WindowFromPoint,
2141 // PostMessage/SendMessage to work correctly. These API's expect the
2142 // coordinates to be in pixels.
2143 // PostMessage() to metro windows isn't allowed (access will be denied). Don't
2144 // try to repost with Win32 if the window under the mouse press is in metro.
2145 if (!ViewsDelegate::GetInstance() ||
2146 !ViewsDelegate::GetInstance()->IsWindowInMetro(window)) {
2147 gfx::Point screen_loc_pixels = gfx::win::DIPToScreenPoint(screen_loc);
2148 HWND target_window = window ? HWNDForNativeWindow(window) :
2149 WindowFromPoint(screen_loc_pixels.ToPOINT());
2150 HWND source_window = HWNDForNativeView(native_view);
2151 if (!target_window || !source_window ||
2152 GetWindowThreadProcessId(source_window, NULL) !=
2153 GetWindowThreadProcessId(target_window, NULL)) {
2154 // Even though we have mouse capture, windows generates a mouse event if
2155 // the other window is in a separate thread. Only repost an event if
2156 // |target_window| and |source_window| were created on the same thread,
2157 // else double events can occur and lead to bad behavior.
2158 return;
2161 // Determine whether the click was in the client area or not.
2162 // NOTE: WM_NCHITTEST coordinates are relative to the screen.
2163 LPARAM coords = MAKELPARAM(screen_loc_pixels.x(), screen_loc_pixels.y());
2164 LRESULT nc_hit_result = SendMessage(target_window, WM_NCHITTEST, 0, coords);
2165 const bool client_area = nc_hit_result == HTCLIENT;
2167 // TODO(sky): this isn't right. The event to generate should correspond with
2168 // the event we just got. MouseEvent only tells us what is down, which may
2169 // differ. Need to add ability to get changed button from MouseEvent.
2170 int event_type;
2171 int flags = event.flags();
2172 if (flags & ui::EF_LEFT_MOUSE_BUTTON) {
2173 event_type = client_area ? WM_LBUTTONDOWN : WM_NCLBUTTONDOWN;
2174 } else if (flags & ui::EF_MIDDLE_MOUSE_BUTTON) {
2175 event_type = client_area ? WM_MBUTTONDOWN : WM_NCMBUTTONDOWN;
2176 } else if (flags & ui::EF_RIGHT_MOUSE_BUTTON) {
2177 event_type = client_area ? WM_RBUTTONDOWN : WM_NCRBUTTONDOWN;
2178 } else {
2179 NOTREACHED();
2180 return;
2183 int window_x = screen_loc_pixels.x();
2184 int window_y = screen_loc_pixels.y();
2185 if (client_area) {
2186 POINT pt = { window_x, window_y };
2187 ScreenToClient(target_window, &pt);
2188 window_x = pt.x;
2189 window_y = pt.y;
2192 WPARAM target = client_area ? event.native_event().wParam : nc_hit_result;
2193 LPARAM window_coords = MAKELPARAM(window_x, window_y);
2194 PostMessage(target_window, event_type, target, window_coords);
2195 return;
2197 #endif
2198 // Non-Windows Aura or |window| is in metro mode.
2199 if (!window)
2200 return;
2202 message_loop_->RepostEventToWindow(event, window, screen_loc);
2205 void MenuController::SetDropMenuItem(
2206 MenuItemView* new_target,
2207 MenuDelegate::DropPosition new_position) {
2208 if (new_target == drop_target_ && new_position == drop_position_)
2209 return;
2211 if (drop_target_) {
2212 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2213 NULL, MenuDelegate::DROP_NONE);
2215 drop_target_ = new_target;
2216 drop_position_ = new_position;
2217 if (drop_target_) {
2218 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2219 drop_target_, drop_position_);
2223 void MenuController::UpdateScrolling(const MenuPart& part) {
2224 if (!part.is_scroll() && !scroll_task_.get())
2225 return;
2227 if (!scroll_task_.get())
2228 scroll_task_.reset(new MenuScrollTask());
2229 scroll_task_->Update(part);
2232 void MenuController::StopScrolling() {
2233 scroll_task_.reset(NULL);
2236 void MenuController::UpdateActiveMouseView(SubmenuView* event_source,
2237 const ui::MouseEvent& event,
2238 View* target_menu) {
2239 View* target = NULL;
2240 gfx::Point target_menu_loc(event.location());
2241 if (target_menu && target_menu->has_children()) {
2242 // Locate the deepest child view to send events to. This code assumes we
2243 // don't have to walk up the tree to find a view interested in events. This
2244 // is currently true for the cases we are embedding views, but if we embed
2245 // more complex hierarchies it'll need to change.
2246 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2247 &target_menu_loc);
2248 View::ConvertPointFromScreen(target_menu, &target_menu_loc);
2249 target = target_menu->GetEventHandlerForPoint(target_menu_loc);
2250 if (target == target_menu || !target->enabled())
2251 target = NULL;
2253 View* active_mouse_view = GetActiveMouseView();
2254 if (target != active_mouse_view) {
2255 SendMouseCaptureLostToActiveView();
2256 active_mouse_view = target;
2257 SetActiveMouseView(active_mouse_view);
2258 if (active_mouse_view) {
2259 gfx::Point target_point(target_menu_loc);
2260 View::ConvertPointToTarget(
2261 target_menu, active_mouse_view, &target_point);
2262 ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED, target_point,
2263 target_point, ui::EventTimeForNow(), 0,
2265 active_mouse_view->OnMouseEntered(mouse_entered_event);
2267 ui::MouseEvent mouse_pressed_event(
2268 ui::ET_MOUSE_PRESSED, target_point, target_point,
2269 ui::EventTimeForNow(), event.flags(), event.changed_button_flags());
2270 active_mouse_view->OnMousePressed(mouse_pressed_event);
2274 if (active_mouse_view) {
2275 gfx::Point target_point(target_menu_loc);
2276 View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point);
2277 ui::MouseEvent mouse_dragged_event(
2278 ui::ET_MOUSE_DRAGGED, target_point, target_point, ui::EventTimeForNow(),
2279 event.flags(), event.changed_button_flags());
2280 active_mouse_view->OnMouseDragged(mouse_dragged_event);
2284 void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source,
2285 const ui::MouseEvent& event) {
2286 View* active_mouse_view = GetActiveMouseView();
2287 if (!active_mouse_view)
2288 return;
2290 gfx::Point target_loc(event.location());
2291 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2292 &target_loc);
2293 View::ConvertPointFromScreen(active_mouse_view, &target_loc);
2294 ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, target_loc, target_loc,
2295 ui::EventTimeForNow(), event.flags(),
2296 event.changed_button_flags());
2297 // Reset active mouse view before sending mouse released. That way if it calls
2298 // back to us, we aren't in a weird state.
2299 SetActiveMouseView(NULL);
2300 active_mouse_view->OnMouseReleased(release_event);
2303 void MenuController::SendMouseCaptureLostToActiveView() {
2304 View* active_mouse_view = GetActiveMouseView();
2305 if (!active_mouse_view)
2306 return;
2308 // Reset the active_mouse_view_ before sending mouse capture lost. That way if
2309 // it calls back to us, we aren't in a weird state.
2310 SetActiveMouseView(NULL);
2311 active_mouse_view->OnMouseCaptureLost();
2314 void MenuController::SetActiveMouseView(View* view) {
2315 if (view)
2316 ViewStorage::GetInstance()->StoreView(active_mouse_view_id_, view);
2317 else
2318 ViewStorage::GetInstance()->RemoveView(active_mouse_view_id_);
2321 View* MenuController::GetActiveMouseView() {
2322 return ViewStorage::GetInstance()->RetrieveView(active_mouse_view_id_);
2325 void MenuController::SetExitType(ExitType type) {
2326 exit_type_ = type;
2327 // Exit nested message loops as soon as possible. We do this as
2328 // MessagePumpDispatcher is only invoked before native events, which means
2329 // its entirely possible for a Widget::CloseNow() task to be processed before
2330 // the next native message. We quite the nested message loop as soon as
2331 // possible to avoid having deleted views classes (such as widgets and
2332 // rootviews) on the stack when the nested message loop stops.
2334 // It's safe to invoke QuitNestedMessageLoop() multiple times, it only effects
2335 // the current loop.
2336 bool quit_now = exit_type_ != EXIT_NONE && message_loop_depth_;
2337 if (quit_now)
2338 TerminateNestedMessageLoop();
2341 void MenuController::TerminateNestedMessageLoop() {
2342 message_loop_->QuitNow();
2345 void MenuController::HandleMouseLocation(SubmenuView* source,
2346 const gfx::Point& mouse_location) {
2347 if (showing_submenu_)
2348 return;
2350 // Ignore mouse events if we're closing the menu.
2351 if (exit_type_ != EXIT_NONE)
2352 return;
2354 MenuPart part = GetMenuPart(source, mouse_location);
2356 UpdateScrolling(part);
2358 if (!blocking_run_)
2359 return;
2361 if (part.type == MenuPart::NONE && ShowSiblingMenu(source, mouse_location))
2362 return;
2364 if (part.type == MenuPart::MENU_ITEM && part.menu) {
2365 SetSelection(part.menu, SELECTION_OPEN_SUBMENU);
2366 } else if (!part.is_scroll() && pending_state_.item &&
2367 pending_state_.item->GetParentMenuItem() &&
2368 (!pending_state_.item->HasSubmenu() ||
2369 !pending_state_.item->GetSubmenu()->IsShowing())) {
2370 // On exit if the user hasn't selected an item with a submenu, move the
2371 // selection back to the parent menu item.
2372 SetSelection(pending_state_.item->GetParentMenuItem(),
2373 SELECTION_OPEN_SUBMENU);
2377 gfx::Screen* MenuController::GetScreen() {
2378 Widget* root = owner_ ? owner_->GetTopLevelWidget() : NULL;
2379 return root ? gfx::Screen::GetScreenFor(root->GetNativeView())
2380 : gfx::Screen::GetNativeScreen();
2383 } // namespace views