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