Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / ui / views / controls / menu / menu_controller.cc
blob8d6a7a283dd347f197075042e926b94729d00add
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 } // namespace
94 // Returns the first descendant of |view| that is hot tracked.
95 static CustomButton* GetFirstHotTrackedView(View* view) {
96 if (!view)
97 return NULL;
98 CustomButton* button = CustomButton::AsCustomButton(view);
99 if (button) {
100 if (button->IsHotTracked())
101 return button;
104 for (int i = 0; i < view->child_count(); ++i) {
105 CustomButton* hot_view = GetFirstHotTrackedView(view->child_at(i));
106 if (hot_view)
107 return hot_view;
109 return NULL;
112 // Recurses through the child views of |view| returning the first view starting
113 // at |start| that is focusable. A value of -1 for |start| indicates to start at
114 // the first view (if |forward| is false, iterating starts at the last view). If
115 // |forward| is true the children are considered first to last, otherwise last
116 // to first.
117 static View* GetFirstFocusableView(View* view, int start, bool forward) {
118 if (forward) {
119 for (int i = start == -1 ? 0 : start; i < view->child_count(); ++i) {
120 View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
121 if (deepest)
122 return deepest;
124 } else {
125 for (int i = start == -1 ? view->child_count() - 1 : start; i >= 0; --i) {
126 View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
127 if (deepest)
128 return deepest;
131 return view->IsFocusable() ? view : NULL;
134 // Returns the first child of |start| that is focusable.
135 static View* GetInitialFocusableView(View* start, bool forward) {
136 return GetFirstFocusableView(start, -1, forward);
139 // Returns the next view after |start_at| that is focusable. Returns NULL if
140 // there are no focusable children of |ancestor| after |start_at|.
141 static View* GetNextFocusableView(View* ancestor,
142 View* start_at,
143 bool forward) {
144 DCHECK(ancestor->Contains(start_at));
145 View* parent = start_at;
146 do {
147 View* new_parent = parent->parent();
148 int index = new_parent->GetIndexOf(parent);
149 index += forward ? 1 : -1;
150 if (forward || index != -1) {
151 View* next = GetFirstFocusableView(new_parent, index, forward);
152 if (next)
153 return next;
155 parent = new_parent;
156 } while (parent != ancestor);
157 return NULL;
160 // MenuScrollTask --------------------------------------------------------------
162 // MenuScrollTask is used when the SubmenuView does not all fit on screen and
163 // the mouse is over the scroll up/down buttons. MenuScrollTask schedules
164 // itself with a RepeatingTimer. When Run is invoked MenuScrollTask scrolls
165 // appropriately.
167 class MenuController::MenuScrollTask {
168 public:
169 MenuScrollTask() : submenu_(NULL), is_scrolling_up_(false), start_y_(0) {
170 pixels_per_second_ = MenuItemView::pref_menu_height() * 20;
173 void Update(const MenuController::MenuPart& part) {
174 if (!part.is_scroll()) {
175 StopScrolling();
176 return;
178 DCHECK(part.submenu);
179 SubmenuView* new_menu = part.submenu;
180 bool new_is_up = (part.type == MenuController::MenuPart::SCROLL_UP);
181 if (new_menu == submenu_ && is_scrolling_up_ == new_is_up)
182 return;
184 start_scroll_time_ = base::Time::Now();
185 start_y_ = part.submenu->GetVisibleBounds().y();
186 submenu_ = new_menu;
187 is_scrolling_up_ = new_is_up;
189 if (!scrolling_timer_.IsRunning()) {
190 scrolling_timer_.Start(FROM_HERE,
191 TimeDelta::FromMilliseconds(kScrollTimerMS),
192 this, &MenuScrollTask::Run);
196 void StopScrolling() {
197 if (scrolling_timer_.IsRunning()) {
198 scrolling_timer_.Stop();
199 submenu_ = NULL;
203 // The menu being scrolled. Returns null if not scrolling.
204 SubmenuView* submenu() const { return submenu_; }
206 private:
207 void Run() {
208 DCHECK(submenu_);
209 gfx::Rect vis_rect = submenu_->GetVisibleBounds();
210 const int delta_y = static_cast<int>(
211 (base::Time::Now() - start_scroll_time_).InMilliseconds() *
212 pixels_per_second_ / 1000);
213 vis_rect.set_y(is_scrolling_up_ ?
214 std::max(0, start_y_ - delta_y) :
215 std::min(submenu_->height() - vis_rect.height(), start_y_ + delta_y));
216 submenu_->ScrollRectToVisible(vis_rect);
219 // SubmenuView being scrolled.
220 SubmenuView* submenu_;
222 // Direction scrolling.
223 bool is_scrolling_up_;
225 // Timer to periodically scroll.
226 base::RepeatingTimer<MenuScrollTask> scrolling_timer_;
228 // Time we started scrolling at.
229 base::Time start_scroll_time_;
231 // How many pixels to scroll per second.
232 int pixels_per_second_;
234 // Y-coordinate of submenu_view_ when scrolling started.
235 int start_y_;
237 DISALLOW_COPY_AND_ASSIGN(MenuScrollTask);
240 // MenuController:SelectByCharDetails ----------------------------------------
242 struct MenuController::SelectByCharDetails {
243 SelectByCharDetails()
244 : first_match(-1),
245 has_multiple(false),
246 index_of_item(-1),
247 next_match(-1) {
250 // Index of the first menu with the specified mnemonic.
251 int first_match;
253 // If true there are multiple menu items with the same mnemonic.
254 bool has_multiple;
256 // Index of the selected item; may remain -1.
257 int index_of_item;
259 // If there are multiple matches this is the index of the item after the
260 // currently selected item whose mnemonic matches. This may remain -1 even
261 // though there are matches.
262 int next_match;
265 // MenuController:State ------------------------------------------------------
267 MenuController::State::State()
268 : item(NULL),
269 submenu_open(false),
270 anchor(MENU_ANCHOR_TOPLEFT),
271 context_menu(false) {
274 MenuController::State::~State() {}
276 // MenuController ------------------------------------------------------------
278 // static
279 MenuController* MenuController::active_instance_ = NULL;
281 // static
282 MenuController* MenuController::GetActiveInstance() {
283 return active_instance_;
286 MenuItemView* MenuController::Run(Widget* parent,
287 MenuButton* button,
288 MenuItemView* root,
289 const gfx::Rect& bounds,
290 MenuAnchorPosition position,
291 bool context_menu,
292 bool is_nested_drag,
293 int* result_event_flags) {
294 exit_type_ = EXIT_NONE;
295 possible_drag_ = false;
296 drag_in_progress_ = false;
297 did_initiate_drag_ = false;
298 closing_event_time_ = base::TimeDelta();
299 menu_start_time_ = base::TimeTicks::Now();
300 menu_start_mouse_press_loc_ = gfx::Point();
302 // If we are shown on mouse press, we will eat the subsequent mouse down and
303 // the parent widget will not be able to reset its state (it might have mouse
304 // capture from the mouse down). So we clear its state here.
305 if (parent) {
306 View* root_view = parent->GetRootView();
307 if (root_view) {
308 root_view->SetMouseHandler(NULL);
309 const ui::Event* event =
310 static_cast<internal::RootView*>(root_view)->current_event();
311 if (event && event->type() == ui::ET_MOUSE_PRESSED) {
312 gfx::Point screen_loc(
313 static_cast<const ui::MouseEvent*>(event)->location());
314 View::ConvertPointToScreen(
315 static_cast<View*>(event->target()), &screen_loc);
316 menu_start_mouse_press_loc_ = screen_loc;
321 bool nested_menu = showing_;
322 if (showing_) {
323 // Only support nesting of blocking_run menus, nesting of
324 // blocking/non-blocking shouldn't be needed.
325 DCHECK(blocking_run_);
327 // We're already showing, push the current state.
328 menu_stack_.push_back(
329 std::make_pair(state_, make_linked_ptr(pressed_lock_.release())));
331 // The context menu should be owned by the same parent.
332 DCHECK_EQ(owner_, parent);
333 } else {
334 showing_ = true;
337 // Reset current state.
338 pending_state_ = State();
339 state_ = State();
340 UpdateInitialLocation(bounds, position, context_menu);
342 if (owner_)
343 owner_->RemoveObserver(this);
344 owner_ = parent;
345 if (owner_)
346 owner_->AddObserver(this);
348 // Set the selection, which opens the initial menu.
349 SetSelection(root, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
351 if (!blocking_run_) {
352 if (!is_nested_drag) {
353 // Start the timer to hide the menu. This is needed as we get no
354 // notification when the drag has finished.
355 StartCancelAllTimer();
357 return NULL;
360 if (button)
361 pressed_lock_.reset(new MenuButton::PressedLock(button));
363 // Make sure Chrome doesn't attempt to shut down while the menu is showing.
364 if (ViewsDelegate::views_delegate)
365 ViewsDelegate::views_delegate->AddRef();
367 // We need to turn on nestable tasks as in some situations (pressing alt-f for
368 // one) the menus are run from a task. If we don't do this and are invoked
369 // from a task none of the tasks we schedule are processed and the menu
370 // appears totally broken.
371 message_loop_depth_++;
372 DCHECK_LE(message_loop_depth_, 2);
373 RunMessageLoop(nested_menu);
374 message_loop_depth_--;
376 if (ViewsDelegate::views_delegate)
377 ViewsDelegate::views_delegate->ReleaseRef();
379 // Close any open menus.
380 SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
382 #if defined(OS_WIN)
383 // On Windows, if we select the menu item by touch and if the window at the
384 // location is another window on the same thread, that window gets a
385 // WM_MOUSEACTIVATE message and ends up activating itself, which is not
386 // correct. We workaround this by setting a property on the window at the
387 // current cursor location. We check for this property in our
388 // WM_MOUSEACTIVATE handler and don't activate the window if the property is
389 // set.
390 if (item_selected_by_touch_) {
391 item_selected_by_touch_ = false;
392 POINT cursor_pos;
393 ::GetCursorPos(&cursor_pos);
394 HWND window = ::WindowFromPoint(cursor_pos);
395 if (::GetWindowThreadProcessId(window, NULL) ==
396 ::GetCurrentThreadId()) {
397 ::SetProp(window, ui::kIgnoreTouchMouseActivateForWindow,
398 reinterpret_cast<HANDLE>(true));
401 #endif
403 linked_ptr<MenuButton::PressedLock> nested_pressed_lock;
404 if (nested_menu) {
405 DCHECK(!menu_stack_.empty());
406 // We're running from within a menu, restore the previous state.
407 // The menus are already showing, so we don't have to show them.
408 state_ = menu_stack_.back().first;
409 pending_state_ = menu_stack_.back().first;
410 nested_pressed_lock = menu_stack_.back().second;
411 menu_stack_.pop_back();
412 } else {
413 showing_ = false;
414 did_capture_ = false;
417 MenuItemView* result = result_;
418 // In case we're nested, reset result_.
419 result_ = NULL;
421 if (result_event_flags)
422 *result_event_flags = accept_event_flags_;
424 if (exit_type_ == EXIT_OUTERMOST) {
425 SetExitType(EXIT_NONE);
426 } else {
427 if (nested_menu && result) {
428 // We're nested and about to return a value. The caller might enter
429 // another blocking loop. We need to make sure all menus are hidden
430 // before that happens otherwise the menus will stay on screen.
431 CloseAllNestedMenus();
432 SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
434 // Set exit_all_, which makes sure all nested loops exit immediately.
435 if (exit_type_ != EXIT_DESTROYED)
436 SetExitType(EXIT_ALL);
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(-1);
1032 break;
1034 case ui::VKEY_DOWN:
1035 IncrementSelection(1);
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 } else if (pending_state_.item->enabled()) {
1108 ShowContextMenu(pending_state_.item,
1109 pending_state_.item->GetKeyboardContextMenuLocation(),
1110 ui::MENU_SOURCE_KEYBOARD);
1112 break;
1115 default:
1116 break;
1118 return true;
1121 MenuController::MenuController(ui::NativeTheme* theme,
1122 bool blocking,
1123 internal::MenuControllerDelegate* delegate)
1124 : blocking_run_(blocking),
1125 showing_(false),
1126 exit_type_(EXIT_NONE),
1127 did_capture_(false),
1128 result_(NULL),
1129 accept_event_flags_(0),
1130 drop_target_(NULL),
1131 drop_position_(MenuDelegate::DROP_UNKNOWN),
1132 owner_(NULL),
1133 possible_drag_(false),
1134 drag_in_progress_(false),
1135 did_initiate_drag_(false),
1136 valid_drop_coordinates_(false),
1137 last_drop_operation_(MenuDelegate::DROP_UNKNOWN),
1138 showing_submenu_(false),
1139 active_mouse_view_id_(ViewStorage::GetInstance()->CreateStorageID()),
1140 delegate_(delegate),
1141 message_loop_depth_(0),
1142 menu_config_(theme),
1143 closing_event_time_(base::TimeDelta()),
1144 menu_start_time_(base::TimeTicks()),
1145 is_combobox_(false),
1146 item_selected_by_touch_(false),
1147 message_loop_(MenuMessageLoop::Create()) {
1148 active_instance_ = this;
1151 MenuController::~MenuController() {
1152 DCHECK(!showing_);
1153 if (owner_)
1154 owner_->RemoveObserver(this);
1155 if (active_instance_ == this)
1156 active_instance_ = NULL;
1157 StopShowTimer();
1158 StopCancelAllTimer();
1161 void MenuController::RunMessageLoop(bool nested_menu) {
1162 message_loop_->Run(this, owner_, nested_menu);
1165 MenuController::SendAcceleratorResultType
1166 MenuController::SendAcceleratorToHotTrackedView() {
1167 CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item);
1168 if (!hot_view)
1169 return ACCELERATOR_NOT_PROCESSED;
1171 ui::Accelerator accelerator(ui::VKEY_RETURN, ui::EF_NONE);
1172 hot_view->AcceleratorPressed(accelerator);
1173 CustomButton* button = static_cast<CustomButton*>(hot_view);
1174 button->SetHotTracked(true);
1175 return (exit_type_ == EXIT_NONE) ?
1176 ACCELERATOR_PROCESSED : ACCELERATOR_PROCESSED_EXIT;
1179 void MenuController::UpdateInitialLocation(const gfx::Rect& bounds,
1180 MenuAnchorPosition position,
1181 bool context_menu) {
1182 pending_state_.context_menu = context_menu;
1183 pending_state_.initial_bounds = bounds;
1184 if (bounds.height() > 1) {
1185 // Inset the bounds slightly, otherwise drag coordinates don't line up
1186 // nicely and menus close prematurely.
1187 pending_state_.initial_bounds.Inset(0, 1);
1190 // Reverse anchor position for RTL languages.
1191 if (base::i18n::IsRTL() &&
1192 (position == MENU_ANCHOR_TOPRIGHT || position == MENU_ANCHOR_TOPLEFT)) {
1193 pending_state_.anchor = position == MENU_ANCHOR_TOPRIGHT
1194 ? MENU_ANCHOR_TOPLEFT
1195 : MENU_ANCHOR_TOPRIGHT;
1196 } else {
1197 pending_state_.anchor = position;
1200 // Calculate the bounds of the monitor we'll show menus on. Do this once to
1201 // avoid repeated system queries for the info.
1202 pending_state_.monitor_bounds = GetScreen()->GetDisplayNearestPoint(
1203 bounds.origin()).work_area();
1205 if (!pending_state_.monitor_bounds.Contains(bounds)) {
1206 // Use the monitor area if the work area doesn't contain the bounds. This
1207 // handles showing a menu from the launcher.
1208 gfx::Rect monitor_area = GetScreen()->GetDisplayNearestPoint(
1209 bounds.origin()).bounds();
1210 if (monitor_area.Contains(bounds))
1211 pending_state_.monitor_bounds = monitor_area;
1215 void MenuController::Accept(MenuItemView* item, int event_flags) {
1216 DCHECK(IsBlockingRun());
1217 result_ = item;
1218 if (item && !menu_stack_.empty() &&
1219 !item->GetDelegate()->ShouldCloseAllMenusOnExecute(item->GetCommand())) {
1220 SetExitType(EXIT_OUTERMOST);
1221 } else {
1222 SetExitType(EXIT_ALL);
1224 accept_event_flags_ = event_flags;
1227 bool MenuController::ShowSiblingMenu(SubmenuView* source,
1228 const gfx::Point& mouse_location) {
1229 if (!menu_stack_.empty() || !pressed_lock_.get())
1230 return false;
1232 View* source_view = source->GetScrollViewContainer();
1233 if (mouse_location.x() >= 0 &&
1234 mouse_location.x() < source_view->width() &&
1235 mouse_location.y() >= 0 &&
1236 mouse_location.y() < source_view->height()) {
1237 // The mouse is over the menu, no need to continue.
1238 return false;
1241 gfx::NativeWindow window_under_mouse = GetScreen()->GetWindowUnderCursor();
1242 // TODO(oshima): Replace with views only API.
1243 if (!owner_ || window_under_mouse != owner_->GetNativeWindow())
1244 return false;
1246 // The user moved the mouse outside the menu and over the owning window. See
1247 // if there is a sibling menu we should show.
1248 gfx::Point screen_point(mouse_location);
1249 View::ConvertPointToScreen(source_view, &screen_point);
1250 MenuAnchorPosition anchor;
1251 bool has_mnemonics;
1252 MenuButton* button = NULL;
1253 MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->
1254 GetSiblingMenu(source->GetMenuItem()->GetRootMenuItem(),
1255 screen_point, &anchor, &has_mnemonics, &button);
1256 if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu))
1257 return false;
1259 delegate_->SiblingMenuCreated(alt_menu);
1261 if (!button) {
1262 // If the delegate returns a menu, they must also return a button.
1263 NOTREACHED();
1264 return false;
1267 // There is a sibling menu, update the button state, hide the current menu
1268 // and show the new one.
1269 pressed_lock_.reset(new MenuButton::PressedLock(button));
1271 // Need to reset capture when we show the menu again, otherwise we aren't
1272 // going to get any events.
1273 did_capture_ = false;
1274 gfx::Point screen_menu_loc;
1275 View::ConvertPointToScreen(button, &screen_menu_loc);
1277 // It is currently not possible to show a submenu recursively in a bubble.
1278 DCHECK(!MenuItemView::IsBubble(anchor));
1279 // Subtract 1 from the height to make the popup flush with the button border.
1280 UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(),
1281 button->width(), button->height() - 1),
1282 anchor, state_.context_menu);
1283 alt_menu->PrepareForRun(
1284 false, has_mnemonics,
1285 source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_);
1286 alt_menu->controller_ = this;
1287 SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1288 return true;
1291 bool MenuController::ShowContextMenu(MenuItemView* menu_item,
1292 const gfx::Point& screen_location,
1293 ui::MenuSourceType source_type) {
1294 // Set the selection immediately, making sure the submenu is only open
1295 // if it already was.
1296 int selection_types = SELECTION_UPDATE_IMMEDIATELY;
1297 if (state_.item == pending_state_.item && state_.submenu_open)
1298 selection_types |= SELECTION_OPEN_SUBMENU;
1299 SetSelection(pending_state_.item, selection_types);
1301 if (menu_item->GetDelegate()->ShowContextMenu(
1302 menu_item, menu_item->GetCommand(), screen_location, source_type)) {
1303 SendMouseCaptureLostToActiveView();
1304 return true;
1306 return false;
1309 void MenuController::CloseAllNestedMenus() {
1310 for (std::list<NestedState>::iterator i = menu_stack_.begin();
1311 i != menu_stack_.end(); ++i) {
1312 State& state = i->first;
1313 MenuItemView* last_item = state.item;
1314 for (MenuItemView* item = last_item; item;
1315 item = item->GetParentMenuItem()) {
1316 CloseMenu(item);
1317 last_item = item;
1319 state.submenu_open = false;
1320 state.item = last_item;
1324 MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) {
1325 // Walk the view hierarchy until we find a menu item (or the root).
1326 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1327 while (child_under_mouse &&
1328 child_under_mouse->id() != MenuItemView::kMenuItemViewID) {
1329 child_under_mouse = child_under_mouse->parent();
1331 if (child_under_mouse && child_under_mouse->enabled() &&
1332 child_under_mouse->id() == MenuItemView::kMenuItemViewID) {
1333 return static_cast<MenuItemView*>(child_under_mouse);
1335 return NULL;
1338 MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) {
1339 View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
1340 if (child_under_mouse &&
1341 child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) {
1342 return static_cast<MenuItemView*>(child_under_mouse);
1344 return NULL;
1347 bool MenuController::IsScrollButtonAt(SubmenuView* source,
1348 int x,
1349 int y,
1350 MenuPart::Type* part) {
1351 MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer();
1352 View* child_under_mouse =
1353 scroll_view->GetEventHandlerForPoint(gfx::Point(x, y));
1354 if (child_under_mouse && child_under_mouse->enabled()) {
1355 if (child_under_mouse == scroll_view->scroll_up_button()) {
1356 *part = MenuPart::SCROLL_UP;
1357 return true;
1359 if (child_under_mouse == scroll_view->scroll_down_button()) {
1360 *part = MenuPart::SCROLL_DOWN;
1361 return true;
1364 return false;
1367 MenuController::MenuPart MenuController::GetMenuPart(
1368 SubmenuView* source,
1369 const gfx::Point& source_loc) {
1370 gfx::Point screen_loc(source_loc);
1371 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
1372 return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc);
1375 MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu(
1376 MenuItemView* item,
1377 const gfx::Point& screen_loc) {
1378 MenuPart part;
1379 for (; item; item = item->GetParentMenuItem()) {
1380 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1381 GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc,
1382 &part)) {
1383 return part;
1386 return part;
1389 bool MenuController::GetMenuPartByScreenCoordinateImpl(
1390 SubmenuView* menu,
1391 const gfx::Point& screen_loc,
1392 MenuPart* part) {
1393 // Is the mouse over the scroll buttons?
1394 gfx::Point scroll_view_loc = screen_loc;
1395 View* scroll_view_container = menu->GetScrollViewContainer();
1396 View::ConvertPointFromScreen(scroll_view_container, &scroll_view_loc);
1397 if (scroll_view_loc.x() < 0 ||
1398 scroll_view_loc.x() >= scroll_view_container->width() ||
1399 scroll_view_loc.y() < 0 ||
1400 scroll_view_loc.y() >= scroll_view_container->height()) {
1401 // Point isn't contained in menu.
1402 return false;
1404 if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(),
1405 &(part->type))) {
1406 part->submenu = menu;
1407 return true;
1410 // Not over the scroll button. Check the actual menu.
1411 if (DoesSubmenuContainLocation(menu, screen_loc)) {
1412 gfx::Point menu_loc = screen_loc;
1413 View::ConvertPointFromScreen(menu, &menu_loc);
1414 part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y());
1415 part->type = MenuPart::MENU_ITEM;
1416 part->submenu = menu;
1417 if (!part->menu)
1418 part->parent = menu->GetMenuItem();
1419 return true;
1422 // While the mouse isn't over a menu item or the scroll buttons of menu, it
1423 // is contained by menu and so we return true. If we didn't return true other
1424 // menus would be searched, even though they are likely obscured by us.
1425 return true;
1428 bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu,
1429 const gfx::Point& screen_loc) {
1430 gfx::Point view_loc = screen_loc;
1431 View::ConvertPointFromScreen(submenu, &view_loc);
1432 gfx::Rect vis_rect = submenu->GetVisibleBounds();
1433 return vis_rect.Contains(view_loc.x(), view_loc.y());
1436 void MenuController::CommitPendingSelection() {
1437 StopShowTimer();
1439 size_t paths_differ_at = 0;
1440 std::vector<MenuItemView*> current_path;
1441 std::vector<MenuItemView*> new_path;
1442 BuildPathsAndCalculateDiff(state_.item, pending_state_.item, &current_path,
1443 &new_path, &paths_differ_at);
1445 // Hide the old menu.
1446 for (size_t i = paths_differ_at; i < current_path.size(); ++i) {
1447 if (current_path[i]->HasSubmenu()) {
1448 current_path[i]->GetSubmenu()->Hide();
1452 // Copy pending to state_, making sure to preserve the direction menus were
1453 // opened.
1454 std::list<bool> pending_open_direction;
1455 state_.open_leading.swap(pending_open_direction);
1456 state_ = pending_state_;
1457 state_.open_leading.swap(pending_open_direction);
1459 int menu_depth = MenuDepth(state_.item);
1460 if (menu_depth == 0) {
1461 state_.open_leading.clear();
1462 } else {
1463 int cached_size = static_cast<int>(state_.open_leading.size());
1464 DCHECK_GE(menu_depth, 0);
1465 while (cached_size-- >= menu_depth)
1466 state_.open_leading.pop_back();
1469 if (!state_.item) {
1470 // Nothing to select.
1471 StopScrolling();
1472 return;
1475 // Open all the submenus preceeding the last menu item (last menu item is
1476 // handled next).
1477 if (new_path.size() > 1) {
1478 for (std::vector<MenuItemView*>::iterator i = new_path.begin();
1479 i != new_path.end() - 1; ++i) {
1480 OpenMenu(*i);
1484 if (state_.submenu_open) {
1485 // The submenu should be open, open the submenu if the item has a submenu.
1486 if (state_.item->HasSubmenu()) {
1487 OpenMenu(state_.item);
1488 } else {
1489 state_.submenu_open = false;
1491 } else if (state_.item->HasSubmenu() &&
1492 state_.item->GetSubmenu()->IsShowing()) {
1493 state_.item->GetSubmenu()->Hide();
1496 if (scroll_task_.get() && scroll_task_->submenu()) {
1497 // Stop the scrolling if none of the elements of the selection contain
1498 // the menu being scrolled.
1499 bool found = false;
1500 for (MenuItemView* item = state_.item; item && !found;
1501 item = item->GetParentMenuItem()) {
1502 found = (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
1503 item->GetSubmenu() == scroll_task_->submenu());
1505 if (!found)
1506 StopScrolling();
1510 void MenuController::CloseMenu(MenuItemView* item) {
1511 DCHECK(item);
1512 if (!item->HasSubmenu())
1513 return;
1514 item->GetSubmenu()->Hide();
1517 void MenuController::OpenMenu(MenuItemView* item) {
1518 DCHECK(item);
1519 if (item->GetSubmenu()->IsShowing()) {
1520 return;
1523 OpenMenuImpl(item, true);
1524 did_capture_ = true;
1527 void MenuController::OpenMenuImpl(MenuItemView* item, bool show) {
1528 // TODO(oshima|sky): Don't show the menu if drag is in progress and
1529 // this menu doesn't support drag drop. See crbug.com/110495.
1530 if (show) {
1531 int old_count = item->GetSubmenu()->child_count();
1532 item->GetDelegate()->WillShowMenu(item);
1533 if (old_count != item->GetSubmenu()->child_count()) {
1534 // If the number of children changed then we may need to add empty items.
1535 item->RemoveEmptyMenus();
1536 item->AddEmptyMenus();
1539 bool prefer_leading =
1540 state_.open_leading.empty() ? true : state_.open_leading.back();
1541 bool resulting_direction;
1542 gfx::Rect bounds = MenuItemView::IsBubble(state_.anchor) ?
1543 CalculateBubbleMenuBounds(item, prefer_leading, &resulting_direction) :
1544 CalculateMenuBounds(item, prefer_leading, &resulting_direction);
1545 state_.open_leading.push_back(resulting_direction);
1546 bool do_capture = (!did_capture_ && blocking_run_);
1547 showing_submenu_ = true;
1548 if (show) {
1549 // Menus are the only place using kGroupingPropertyKey, so any value (other
1550 // than 0) is fine.
1551 const int kGroupingId = 1001;
1552 item->GetSubmenu()->ShowAt(owner_, bounds, do_capture);
1553 item->GetSubmenu()->GetWidget()->SetNativeWindowProperty(
1554 TooltipManager::kGroupingPropertyKey,
1555 reinterpret_cast<void*>(kGroupingId));
1556 } else {
1557 item->GetSubmenu()->Reposition(bounds);
1559 showing_submenu_ = false;
1562 void MenuController::MenuChildrenChanged(MenuItemView* item) {
1563 DCHECK(item);
1564 // Menu shouldn't be updated during drag operation.
1565 DCHECK(!GetActiveMouseView());
1567 // If the current item or pending item is a descendant of the item
1568 // that changed, move the selection back to the changed item.
1569 const MenuItemView* ancestor = state_.item;
1570 while (ancestor && ancestor != item)
1571 ancestor = ancestor->GetParentMenuItem();
1572 if (!ancestor) {
1573 ancestor = pending_state_.item;
1574 while (ancestor && ancestor != item)
1575 ancestor = ancestor->GetParentMenuItem();
1576 if (!ancestor)
1577 return;
1579 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1580 if (item->HasSubmenu())
1581 OpenMenuImpl(item, false);
1584 void MenuController::BuildPathsAndCalculateDiff(
1585 MenuItemView* old_item,
1586 MenuItemView* new_item,
1587 std::vector<MenuItemView*>* old_path,
1588 std::vector<MenuItemView*>* new_path,
1589 size_t* first_diff_at) {
1590 DCHECK(old_path && new_path && first_diff_at);
1591 BuildMenuItemPath(old_item, old_path);
1592 BuildMenuItemPath(new_item, new_path);
1594 size_t common_size = std::min(old_path->size(), new_path->size());
1596 // Find the first difference between the two paths, when the loop
1597 // returns, diff_i is the first index where the two paths differ.
1598 for (size_t i = 0; i < common_size; ++i) {
1599 if ((*old_path)[i] != (*new_path)[i]) {
1600 *first_diff_at = i;
1601 return;
1605 *first_diff_at = common_size;
1608 void MenuController::BuildMenuItemPath(MenuItemView* item,
1609 std::vector<MenuItemView*>* path) {
1610 if (!item)
1611 return;
1612 BuildMenuItemPath(item->GetParentMenuItem(), path);
1613 path->push_back(item);
1616 void MenuController::StartShowTimer() {
1617 show_timer_.Start(FROM_HERE,
1618 TimeDelta::FromMilliseconds(menu_config_.show_delay),
1619 this, &MenuController::CommitPendingSelection);
1622 void MenuController::StopShowTimer() {
1623 show_timer_.Stop();
1626 void MenuController::StartCancelAllTimer() {
1627 cancel_all_timer_.Start(FROM_HERE,
1628 TimeDelta::FromMilliseconds(kCloseOnExitTime),
1629 this, &MenuController::CancelAll);
1632 void MenuController::StopCancelAllTimer() {
1633 cancel_all_timer_.Stop();
1636 gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item,
1637 bool prefer_leading,
1638 bool* is_leading) {
1639 DCHECK(item);
1641 SubmenuView* submenu = item->GetSubmenu();
1642 DCHECK(submenu);
1644 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1646 // Don't let the menu go too wide.
1647 pref.set_width(std::min(pref.width(),
1648 item->GetDelegate()->GetMaxWidthForMenu(item)));
1649 if (!state_.monitor_bounds.IsEmpty())
1650 pref.set_width(std::min(pref.width(), state_.monitor_bounds.width()));
1652 // Assume we can honor prefer_leading.
1653 *is_leading = prefer_leading;
1655 int x, y;
1657 const MenuConfig& menu_config = item->GetMenuConfig();
1659 if (!item->GetParentMenuItem()) {
1660 // First item, position relative to initial location.
1661 x = state_.initial_bounds.x();
1663 // Offsets for context menu prevent menu items being selected by
1664 // simply opening the menu (bug 142992).
1665 if (menu_config.offset_context_menus && state_.context_menu)
1666 x += 1;
1668 y = state_.initial_bounds.bottom();
1669 if (state_.anchor == MENU_ANCHOR_TOPRIGHT) {
1670 x = x + state_.initial_bounds.width() - pref.width();
1671 if (menu_config.offset_context_menus && state_.context_menu)
1672 x -= 1;
1673 } else if (state_.anchor == MENU_ANCHOR_BOTTOMCENTER) {
1674 x = x - (pref.width() - state_.initial_bounds.width()) / 2;
1675 if (pref.height() >
1676 state_.initial_bounds.y() + kCenteredContextMenuYOffset) {
1677 // Menu does not fit above the anchor. We move it to below.
1678 y = state_.initial_bounds.y() - kCenteredContextMenuYOffset;
1679 } else {
1680 y = std::max(0, state_.initial_bounds.y() - pref.height()) +
1681 kCenteredContextMenuYOffset;
1685 if (!state_.monitor_bounds.IsEmpty() &&
1686 y + pref.height() > state_.monitor_bounds.bottom()) {
1687 // The menu doesn't fit fully below the button on the screen. The menu
1688 // position with respect to the bounds will be preserved if it has
1689 // already been drawn. When the requested positioning is below the bounds
1690 // it will shrink the menu to make it fit below.
1691 // If the requested positioning is best fit, it will first try to fit the
1692 // menu below. If that does not fit it will try to place it above. If
1693 // that will not fit it will place it at the bottom of the work area and
1694 // moving it off the initial_bounds region to avoid overlap.
1695 // In all other requested position styles it will be flipped above and
1696 // the height will be shrunken to the usable height.
1697 if (item->actual_menu_position() == MenuItemView::POSITION_BELOW_BOUNDS) {
1698 pref.set_height(std::min(pref.height(),
1699 state_.monitor_bounds.bottom() - y));
1700 } else if (item->actual_menu_position() ==
1701 MenuItemView::POSITION_BEST_FIT) {
1702 MenuItemView::MenuPosition orientation =
1703 MenuItemView::POSITION_BELOW_BOUNDS;
1704 if (state_.monitor_bounds.height() < pref.height()) {
1705 // Handle very tall menus.
1706 pref.set_height(state_.monitor_bounds.height());
1707 y = state_.monitor_bounds.y();
1708 } else if (state_.monitor_bounds.y() + pref.height() <
1709 state_.initial_bounds.y()) {
1710 // Flipping upwards if there is enough space.
1711 y = state_.initial_bounds.y() - pref.height();
1712 orientation = MenuItemView::POSITION_ABOVE_BOUNDS;
1713 } else {
1714 // It is allowed to move the menu a bit around in order to get the
1715 // best fit and to avoid showing scroll elements.
1716 y = state_.monitor_bounds.bottom() - pref.height();
1718 if (orientation == MenuItemView::POSITION_BELOW_BOUNDS) {
1719 // The menu should never overlap the owning button. So move it.
1720 // We use the anchor view style to determine the preferred position
1721 // relative to the owning button.
1722 if (state_.anchor == MENU_ANCHOR_TOPLEFT) {
1723 // The menu starts with the same x coordinate as the owning button.
1724 if (x + state_.initial_bounds.width() + pref.width() >
1725 state_.monitor_bounds.right())
1726 x -= pref.width(); // Move the menu to the left of the button.
1727 else
1728 x += state_.initial_bounds.width(); // Move the menu right.
1729 } else {
1730 // The menu should end with the same x coordinate as the owning
1731 // button.
1732 if (state_.monitor_bounds.x() >
1733 state_.initial_bounds.x() - pref.width())
1734 x = state_.initial_bounds.right(); // Move right of the button.
1735 else
1736 x = state_.initial_bounds.x() - pref.width(); // Move left.
1739 item->set_actual_menu_position(orientation);
1740 } else {
1741 pref.set_height(std::min(pref.height(),
1742 state_.initial_bounds.y() - state_.monitor_bounds.y()));
1743 y = state_.initial_bounds.y() - pref.height();
1744 item->set_actual_menu_position(MenuItemView::POSITION_ABOVE_BOUNDS);
1746 } else if (item->actual_menu_position() ==
1747 MenuItemView::POSITION_ABOVE_BOUNDS) {
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 } else {
1752 item->set_actual_menu_position(MenuItemView::POSITION_BELOW_BOUNDS);
1754 if (state_.monitor_bounds.width() != 0 &&
1755 menu_config.offset_context_menus && state_.context_menu) {
1756 if (x + pref.width() > state_.monitor_bounds.right())
1757 x = state_.initial_bounds.x() - pref.width() - 1;
1758 if (x < state_.monitor_bounds.x())
1759 x = state_.monitor_bounds.x();
1761 } else {
1762 // Not the first menu; position it relative to the bounds of the menu
1763 // item.
1764 gfx::Point item_loc;
1765 View::ConvertPointToScreen(item, &item_loc);
1767 // We must make sure we take into account the UI layout. If the layout is
1768 // RTL, then a 'leading' menu is positioned to the left of the parent menu
1769 // item and not to the right.
1770 bool layout_is_rtl = base::i18n::IsRTL();
1771 bool create_on_the_right = (prefer_leading && !layout_is_rtl) ||
1772 (!prefer_leading && layout_is_rtl);
1773 int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;
1775 if (create_on_the_right) {
1776 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1777 if (state_.monitor_bounds.width() != 0 &&
1778 x + pref.width() > state_.monitor_bounds.right()) {
1779 if (layout_is_rtl)
1780 *is_leading = true;
1781 else
1782 *is_leading = false;
1783 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1785 } else {
1786 x = item_loc.x() - pref.width() + submenu_horizontal_inset;
1787 if (state_.monitor_bounds.width() != 0 && x < state_.monitor_bounds.x()) {
1788 if (layout_is_rtl)
1789 *is_leading = false;
1790 else
1791 *is_leading = true;
1792 x = item_loc.x() + item->width() - submenu_horizontal_inset;
1795 y = item_loc.y() - menu_config.menu_vertical_border_size;
1796 if (state_.monitor_bounds.width() != 0) {
1797 pref.set_height(std::min(pref.height(), state_.monitor_bounds.height()));
1798 if (y + pref.height() > state_.monitor_bounds.bottom())
1799 y = state_.monitor_bounds.bottom() - pref.height();
1800 if (y < state_.monitor_bounds.y())
1801 y = state_.monitor_bounds.y();
1805 if (state_.monitor_bounds.width() != 0) {
1806 if (x + pref.width() > state_.monitor_bounds.right())
1807 x = state_.monitor_bounds.right() - pref.width();
1808 if (x < state_.monitor_bounds.x())
1809 x = state_.monitor_bounds.x();
1811 return gfx::Rect(x, y, pref.width(), pref.height());
1814 gfx::Rect MenuController::CalculateBubbleMenuBounds(MenuItemView* item,
1815 bool prefer_leading,
1816 bool* is_leading) {
1817 DCHECK(item);
1818 DCHECK(!item->GetParentMenuItem());
1820 // Assume we can honor prefer_leading.
1821 *is_leading = prefer_leading;
1823 SubmenuView* submenu = item->GetSubmenu();
1824 DCHECK(submenu);
1826 gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
1827 const gfx::Rect& owner_bounds = pending_state_.initial_bounds;
1829 // First the size gets reduced to the possible space.
1830 if (!state_.monitor_bounds.IsEmpty()) {
1831 int max_width = state_.monitor_bounds.width();
1832 int max_height = state_.monitor_bounds.height();
1833 // In case of bubbles, the maximum width is limited by the space
1834 // between the display corner and the target area + the tip size.
1835 if (state_.anchor == MENU_ANCHOR_BUBBLE_LEFT) {
1836 max_width = owner_bounds.x() - state_.monitor_bounds.x() +
1837 kBubbleTipSizeLeftRight;
1838 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT) {
1839 max_width = state_.monitor_bounds.right() - owner_bounds.right() +
1840 kBubbleTipSizeLeftRight;
1841 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE) {
1842 max_height = owner_bounds.y() - state_.monitor_bounds.y() +
1843 kBubbleTipSizeTopBottom;
1844 } else if (state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1845 max_height = state_.monitor_bounds.bottom() - owner_bounds.bottom() +
1846 kBubbleTipSizeTopBottom;
1848 // The space for the menu to cover should never get empty.
1849 DCHECK_GE(max_width, kBubbleTipSizeLeftRight);
1850 DCHECK_GE(max_height, kBubbleTipSizeTopBottom);
1851 pref.set_width(std::min(pref.width(), max_width));
1852 pref.set_height(std::min(pref.height(), max_height));
1854 // Also make sure that the menu does not go too wide.
1855 pref.set_width(std::min(pref.width(),
1856 item->GetDelegate()->GetMaxWidthForMenu(item)));
1858 int x, y;
1859 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE ||
1860 state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) {
1861 if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE)
1862 y = owner_bounds.y() - pref.height() + kBubbleTipSizeTopBottom;
1863 else
1864 y = owner_bounds.bottom() - kBubbleTipSizeTopBottom;
1866 x = owner_bounds.CenterPoint().x() - pref.width() / 2;
1867 int x_old = x;
1868 if (x < state_.monitor_bounds.x()) {
1869 x = state_.monitor_bounds.x();
1870 } else if (x + pref.width() > state_.monitor_bounds.right()) {
1871 x = state_.monitor_bounds.right() - pref.width();
1873 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1874 pref.width() / 2 - x + x_old);
1875 } else {
1876 if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT)
1877 x = owner_bounds.right() - kBubbleTipSizeLeftRight;
1878 else
1879 x = owner_bounds.x() - pref.width() + kBubbleTipSizeLeftRight;
1881 y = owner_bounds.CenterPoint().y() - pref.height() / 2;
1882 int y_old = y;
1883 if (y < state_.monitor_bounds.y()) {
1884 y = state_.monitor_bounds.y();
1885 } else if (y + pref.height() > state_.monitor_bounds.bottom()) {
1886 y = state_.monitor_bounds.bottom() - pref.height();
1888 submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
1889 pref.height() / 2 - y + y_old);
1891 return gfx::Rect(x, y, pref.width(), pref.height());
1894 // static
1895 int MenuController::MenuDepth(MenuItemView* item) {
1896 return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : 0;
1899 void MenuController::IncrementSelection(int delta) {
1900 MenuItemView* item = pending_state_.item;
1901 DCHECK(item);
1902 if (pending_state_.submenu_open && item->HasSubmenu() &&
1903 item->GetSubmenu()->IsShowing()) {
1904 // A menu is selected and open, but none of its children are selected,
1905 // select the first menu item that is visible and enabled.
1906 if (item->GetSubmenu()->GetMenuItemCount()) {
1907 MenuItemView* to_select = FindFirstSelectableMenuItem(item);
1908 if (to_select)
1909 SetSelection(to_select, SELECTION_DEFAULT);
1910 return;
1914 if (item->has_children()) {
1915 CustomButton* button = GetFirstHotTrackedView(item);
1916 if (button) {
1917 button->SetHotTracked(false);
1918 View* to_make_hot = GetNextFocusableView(item, button, delta == 1);
1919 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1920 if (button_hot) {
1921 button_hot->SetHotTracked(true);
1922 return;
1924 } else {
1925 View* to_make_hot = GetInitialFocusableView(item, delta == 1);
1926 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1927 if (button_hot) {
1928 button_hot->SetHotTracked(true);
1929 return;
1934 MenuItemView* parent = item->GetParentMenuItem();
1935 if (parent) {
1936 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1937 if (parent_count > 1) {
1938 for (int i = 0; i < parent_count; ++i) {
1939 if (parent->GetSubmenu()->GetMenuItemAt(i) == item) {
1940 MenuItemView* to_select =
1941 FindNextSelectableMenuItem(parent, i, delta);
1942 if (!to_select)
1943 break;
1944 SetSelection(to_select, SELECTION_DEFAULT);
1945 View* to_make_hot = GetInitialFocusableView(to_select, delta == 1);
1946 CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot);
1947 if (button_hot)
1948 button_hot->SetHotTracked(true);
1949 break;
1956 MenuItemView* MenuController::FindFirstSelectableMenuItem(
1957 MenuItemView* parent) {
1958 MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(0);
1959 if (!child->visible() || !child->enabled())
1960 child = FindNextSelectableMenuItem(parent, 0, 1);
1961 return child;
1964 MenuItemView* MenuController::FindNextSelectableMenuItem(MenuItemView* parent,
1965 int index,
1966 int delta) {
1967 int start_index = index;
1968 int parent_count = parent->GetSubmenu()->GetMenuItemCount();
1969 // Loop through the menu items skipping any invisible menus. The loop stops
1970 // when we wrap or find a visible and enabled child.
1971 do {
1972 index = (index + delta + parent_count) % parent_count;
1973 if (index == start_index)
1974 return NULL;
1975 MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
1976 if (child->visible() && child->enabled())
1977 return child;
1978 } while (index != start_index);
1979 return NULL;
1982 void MenuController::OpenSubmenuChangeSelectionIfCan() {
1983 MenuItemView* item = pending_state_.item;
1984 if (!item->HasSubmenu() || !item->enabled())
1985 return;
1986 MenuItemView* to_select = NULL;
1987 if (item->GetSubmenu()->GetMenuItemCount() > 0)
1988 to_select = FindFirstSelectableMenuItem(item);
1989 if (to_select) {
1990 SetSelection(to_select, SELECTION_UPDATE_IMMEDIATELY);
1991 return;
1993 // No menu items, just show the sub-menu.
1994 SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
1997 void MenuController::CloseSubmenu() {
1998 MenuItemView* item = state_.item;
1999 DCHECK(item);
2000 if (!item->GetParentMenuItem())
2001 return;
2002 if (item->HasSubmenu() && item->GetSubmenu()->IsShowing())
2003 SetSelection(item, SELECTION_UPDATE_IMMEDIATELY);
2004 else if (item->GetParentMenuItem()->GetParentMenuItem())
2005 SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY);
2008 MenuController::SelectByCharDetails MenuController::FindChildForMnemonic(
2009 MenuItemView* parent,
2010 base::char16 key,
2011 bool (*match_function)(MenuItemView* menu, base::char16 mnemonic)) {
2012 SubmenuView* submenu = parent->GetSubmenu();
2013 DCHECK(submenu);
2014 SelectByCharDetails details;
2016 for (int i = 0, menu_item_count = submenu->GetMenuItemCount();
2017 i < menu_item_count; ++i) {
2018 MenuItemView* child = submenu->GetMenuItemAt(i);
2019 if (child->enabled() && child->visible()) {
2020 if (child == pending_state_.item)
2021 details.index_of_item = i;
2022 if (match_function(child, key)) {
2023 if (details.first_match == -1)
2024 details.first_match = i;
2025 else
2026 details.has_multiple = true;
2027 if (details.next_match == -1 && details.index_of_item != -1 &&
2028 i > details.index_of_item)
2029 details.next_match = i;
2033 return details;
2036 bool MenuController::AcceptOrSelect(MenuItemView* parent,
2037 const SelectByCharDetails& details) {
2038 // This should only be invoked if there is a match.
2039 DCHECK(details.first_match != -1);
2040 DCHECK(parent->HasSubmenu());
2041 SubmenuView* submenu = parent->GetSubmenu();
2042 DCHECK(submenu);
2043 if (!details.has_multiple) {
2044 // There's only one match, activate it (or open if it has a submenu).
2045 if (submenu->GetMenuItemAt(details.first_match)->HasSubmenu()) {
2046 SetSelection(submenu->GetMenuItemAt(details.first_match),
2047 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
2048 } else {
2049 Accept(submenu->GetMenuItemAt(details.first_match), 0);
2050 return true;
2052 } else if (details.index_of_item == -1 || details.next_match == -1) {
2053 SetSelection(submenu->GetMenuItemAt(details.first_match),
2054 SELECTION_DEFAULT);
2055 } else {
2056 SetSelection(submenu->GetMenuItemAt(details.next_match),
2057 SELECTION_DEFAULT);
2059 return false;
2062 bool MenuController::SelectByChar(base::char16 character) {
2063 base::char16 char_array[] = { character, 0 };
2064 base::char16 key = base::i18n::ToLower(char_array)[0];
2065 MenuItemView* item = pending_state_.item;
2066 if (!item->HasSubmenu() || !item->GetSubmenu()->IsShowing())
2067 item = item->GetParentMenuItem();
2068 DCHECK(item);
2069 DCHECK(item->HasSubmenu());
2070 DCHECK(item->GetSubmenu());
2071 if (item->GetSubmenu()->GetMenuItemCount() == 0)
2072 return false;
2074 // Look for matches based on mnemonic first.
2075 SelectByCharDetails details =
2076 FindChildForMnemonic(item, key, &MatchesMnemonic);
2077 if (details.first_match != -1)
2078 return AcceptOrSelect(item, details);
2080 if (is_combobox_) {
2081 item->GetSubmenu()->GetTextInputClient()->InsertChar(character, 0);
2082 } else {
2083 // If no mnemonics found, look at first character of titles.
2084 details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic);
2085 if (details.first_match != -1)
2086 return AcceptOrSelect(item, details);
2089 return false;
2092 void MenuController::RepostEvent(SubmenuView* source,
2093 const ui::LocatedEvent& event) {
2094 if (!event.IsMouseEvent()) {
2095 // TODO(rbyers): Gesture event repost is tricky to get right
2096 // crbug.com/170987.
2097 DCHECK(event.IsGestureEvent());
2098 return;
2101 #if defined(OS_WIN)
2102 if (!state_.item) {
2103 // We some times get an event after closing all the menus. Ignore it. Make
2104 // sure the menu is in fact not visible. If the menu is visible, then
2105 // we're in a bad state where we think the menu isn't visibile but it is.
2106 DCHECK(!source->GetWidget()->IsVisible());
2107 return;
2110 state_.item->GetRootMenuItem()->GetSubmenu()->ReleaseCapture();
2111 #endif
2113 gfx::Point screen_loc(event.location());
2114 View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
2115 gfx::NativeView native_view = source->GetWidget()->GetNativeView();
2116 if (!native_view)
2117 return;
2119 gfx::Screen* screen = gfx::Screen::GetScreenFor(native_view);
2120 gfx::NativeWindow window = screen->GetWindowAtScreenPoint(screen_loc);
2122 #if defined(OS_WIN)
2123 // Convert screen_loc to pixels for the Win32 API's like WindowFromPoint,
2124 // PostMessage/SendMessage to work correctly. These API's expect the
2125 // coordinates to be in pixels.
2126 // PostMessage() to metro windows isn't allowed (access will be denied). Don't
2127 // try to repost with Win32 if the window under the mouse press is in metro.
2128 if (!ViewsDelegate::views_delegate ||
2129 !ViewsDelegate::views_delegate->IsWindowInMetro(window)) {
2130 gfx::Point screen_loc_pixels = gfx::win::DIPToScreenPoint(screen_loc);
2131 HWND target_window = window ? HWNDForNativeWindow(window) :
2132 WindowFromPoint(screen_loc_pixels.ToPOINT());
2133 HWND source_window = HWNDForNativeView(native_view);
2134 if (!target_window || !source_window ||
2135 GetWindowThreadProcessId(source_window, NULL) !=
2136 GetWindowThreadProcessId(target_window, NULL)) {
2137 // Even though we have mouse capture, windows generates a mouse event if
2138 // the other window is in a separate thread. Only repost an event if
2139 // |target_window| and |source_window| were created on the same thread,
2140 // else double events can occur and lead to bad behavior.
2141 return;
2144 // Determine whether the click was in the client area or not.
2145 // NOTE: WM_NCHITTEST coordinates are relative to the screen.
2146 LPARAM coords = MAKELPARAM(screen_loc_pixels.x(), screen_loc_pixels.y());
2147 LRESULT nc_hit_result = SendMessage(target_window, WM_NCHITTEST, 0, coords);
2148 const bool client_area = nc_hit_result == HTCLIENT;
2150 // TODO(sky): this isn't right. The event to generate should correspond with
2151 // the event we just got. MouseEvent only tells us what is down, which may
2152 // differ. Need to add ability to get changed button from MouseEvent.
2153 int event_type;
2154 int flags = event.flags();
2155 if (flags & ui::EF_LEFT_MOUSE_BUTTON) {
2156 event_type = client_area ? WM_LBUTTONDOWN : WM_NCLBUTTONDOWN;
2157 } else if (flags & ui::EF_MIDDLE_MOUSE_BUTTON) {
2158 event_type = client_area ? WM_MBUTTONDOWN : WM_NCMBUTTONDOWN;
2159 } else if (flags & ui::EF_RIGHT_MOUSE_BUTTON) {
2160 event_type = client_area ? WM_RBUTTONDOWN : WM_NCRBUTTONDOWN;
2161 } else {
2162 NOTREACHED();
2163 return;
2166 int window_x = screen_loc_pixels.x();
2167 int window_y = screen_loc_pixels.y();
2168 if (client_area) {
2169 POINT pt = { window_x, window_y };
2170 ScreenToClient(target_window, &pt);
2171 window_x = pt.x;
2172 window_y = pt.y;
2175 WPARAM target = client_area ? event.native_event().wParam : nc_hit_result;
2176 LPARAM window_coords = MAKELPARAM(window_x, window_y);
2177 PostMessage(target_window, event_type, target, window_coords);
2178 return;
2180 #endif
2181 // Non-Windows Aura or |window| is in metro mode.
2182 if (!window)
2183 return;
2185 message_loop_->RepostEventToWindow(event, window, screen_loc);
2188 void MenuController::SetDropMenuItem(
2189 MenuItemView* new_target,
2190 MenuDelegate::DropPosition new_position) {
2191 if (new_target == drop_target_ && new_position == drop_position_)
2192 return;
2194 if (drop_target_) {
2195 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2196 NULL, MenuDelegate::DROP_NONE);
2198 drop_target_ = new_target;
2199 drop_position_ = new_position;
2200 if (drop_target_) {
2201 drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
2202 drop_target_, drop_position_);
2206 void MenuController::UpdateScrolling(const MenuPart& part) {
2207 if (!part.is_scroll() && !scroll_task_.get())
2208 return;
2210 if (!scroll_task_.get())
2211 scroll_task_.reset(new MenuScrollTask());
2212 scroll_task_->Update(part);
2215 void MenuController::StopScrolling() {
2216 scroll_task_.reset(NULL);
2219 void MenuController::UpdateActiveMouseView(SubmenuView* event_source,
2220 const ui::MouseEvent& event,
2221 View* target_menu) {
2222 View* target = NULL;
2223 gfx::Point target_menu_loc(event.location());
2224 if (target_menu && target_menu->has_children()) {
2225 // Locate the deepest child view to send events to. This code assumes we
2226 // don't have to walk up the tree to find a view interested in events. This
2227 // is currently true for the cases we are embedding views, but if we embed
2228 // more complex hierarchies it'll need to change.
2229 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2230 &target_menu_loc);
2231 View::ConvertPointFromScreen(target_menu, &target_menu_loc);
2232 target = target_menu->GetEventHandlerForPoint(target_menu_loc);
2233 if (target == target_menu || !target->enabled())
2234 target = NULL;
2236 View* active_mouse_view = GetActiveMouseView();
2237 if (target != active_mouse_view) {
2238 SendMouseCaptureLostToActiveView();
2239 active_mouse_view = target;
2240 SetActiveMouseView(active_mouse_view);
2241 if (active_mouse_view) {
2242 gfx::Point target_point(target_menu_loc);
2243 View::ConvertPointToTarget(
2244 target_menu, active_mouse_view, &target_point);
2245 ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED, target_point,
2246 target_point, ui::EventTimeForNow(), 0,
2248 active_mouse_view->OnMouseEntered(mouse_entered_event);
2250 ui::MouseEvent mouse_pressed_event(
2251 ui::ET_MOUSE_PRESSED, target_point, target_point,
2252 ui::EventTimeForNow(), event.flags(), event.changed_button_flags());
2253 active_mouse_view->OnMousePressed(mouse_pressed_event);
2257 if (active_mouse_view) {
2258 gfx::Point target_point(target_menu_loc);
2259 View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point);
2260 ui::MouseEvent mouse_dragged_event(
2261 ui::ET_MOUSE_DRAGGED, target_point, target_point, ui::EventTimeForNow(),
2262 event.flags(), event.changed_button_flags());
2263 active_mouse_view->OnMouseDragged(mouse_dragged_event);
2267 void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source,
2268 const ui::MouseEvent& event) {
2269 View* active_mouse_view = GetActiveMouseView();
2270 if (!active_mouse_view)
2271 return;
2273 gfx::Point target_loc(event.location());
2274 View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
2275 &target_loc);
2276 View::ConvertPointFromScreen(active_mouse_view, &target_loc);
2277 ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, target_loc, target_loc,
2278 ui::EventTimeForNow(), event.flags(),
2279 event.changed_button_flags());
2280 // Reset active mouse view before sending mouse released. That way if it calls
2281 // back to us, we aren't in a weird state.
2282 SetActiveMouseView(NULL);
2283 active_mouse_view->OnMouseReleased(release_event);
2286 void MenuController::SendMouseCaptureLostToActiveView() {
2287 View* active_mouse_view = GetActiveMouseView();
2288 if (!active_mouse_view)
2289 return;
2291 // Reset the active_mouse_view_ before sending mouse capture lost. That way if
2292 // it calls back to us, we aren't in a weird state.
2293 SetActiveMouseView(NULL);
2294 active_mouse_view->OnMouseCaptureLost();
2297 void MenuController::SetActiveMouseView(View* view) {
2298 if (view)
2299 ViewStorage::GetInstance()->StoreView(active_mouse_view_id_, view);
2300 else
2301 ViewStorage::GetInstance()->RemoveView(active_mouse_view_id_);
2304 View* MenuController::GetActiveMouseView() {
2305 return ViewStorage::GetInstance()->RetrieveView(active_mouse_view_id_);
2308 void MenuController::SetExitType(ExitType type) {
2309 exit_type_ = type;
2310 // Exit nested message loops as soon as possible. We do this as
2311 // MessagePumpDispatcher is only invoked before native events, which means
2312 // its entirely possible for a Widget::CloseNow() task to be processed before
2313 // the next native message. We quite the nested message loop as soon as
2314 // possible to avoid having deleted views classes (such as widgets and
2315 // rootviews) on the stack when the nested message loop stops.
2317 // It's safe to invoke QuitNestedMessageLoop() multiple times, it only effects
2318 // the current loop.
2319 bool quit_now = exit_type_ != EXIT_NONE && message_loop_depth_;
2320 if (quit_now)
2321 TerminateNestedMessageLoop();
2324 void MenuController::TerminateNestedMessageLoop() {
2325 message_loop_->QuitNow();
2328 void MenuController::HandleMouseLocation(SubmenuView* source,
2329 const gfx::Point& mouse_location) {
2330 if (showing_submenu_)
2331 return;
2333 // Ignore mouse events if we're closing the menu.
2334 if (exit_type_ != EXIT_NONE)
2335 return;
2337 MenuPart part = GetMenuPart(source, mouse_location);
2339 UpdateScrolling(part);
2341 if (!blocking_run_)
2342 return;
2344 if (part.type == MenuPart::NONE && ShowSiblingMenu(source, mouse_location))
2345 return;
2347 if (part.type == MenuPart::MENU_ITEM && part.menu) {
2348 SetSelection(part.menu, SELECTION_OPEN_SUBMENU);
2349 } else if (!part.is_scroll() && pending_state_.item &&
2350 pending_state_.item->GetParentMenuItem() &&
2351 (!pending_state_.item->HasSubmenu() ||
2352 !pending_state_.item->GetSubmenu()->IsShowing())) {
2353 // On exit if the user hasn't selected an item with a submenu, move the
2354 // selection back to the parent menu item.
2355 SetSelection(pending_state_.item->GetParentMenuItem(),
2356 SELECTION_OPEN_SUBMENU);
2360 gfx::Screen* MenuController::GetScreen() {
2361 Widget* root = owner_ ? owner_->GetTopLevelWidget() : NULL;
2362 return root ? gfx::Screen::GetScreenFor(root->GetNativeView())
2363 : gfx::Screen::GetNativeScreen();
2366 } // namespace views