tab_drag_controller.cc revision 58537e28ecd584eab876aee8be7156509866d23a
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 "chrome/browser/ui/views/tabs/tab_drag_controller.h" 6 7#include <math.h> 8#include <set> 9 10#include "base/auto_reset.h" 11#include "base/callback.h" 12#include "base/command_line.h" 13#include "base/i18n/rtl.h" 14#include "chrome/browser/chrome_notification_types.h" 15#include "chrome/browser/extensions/extension_function_dispatcher.h" 16#include "chrome/browser/profiles/profile.h" 17#include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h" 18#include "chrome/browser/ui/browser_window.h" 19#include "chrome/browser/ui/tabs/tab_strip_model.h" 20#include "chrome/browser/ui/tabs/tab_strip_model_delegate.h" 21#include "chrome/browser/ui/views/frame/browser_view.h" 22#include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h" 23#include "chrome/browser/ui/views/tabs/dragged_tab_view.h" 24#include "chrome/browser/ui/views/tabs/native_view_photobooth.h" 25#include "chrome/browser/ui/views/tabs/stacked_tab_strip_layout.h" 26#include "chrome/browser/ui/views/tabs/tab.h" 27#include "chrome/browser/ui/views/tabs/tab_strip.h" 28#include "chrome/common/chrome_switches.h" 29#include "content/public/browser/invalidate_type.h" 30#include "content/public/browser/notification_details.h" 31#include "content/public/browser/notification_service.h" 32#include "content/public/browser/notification_source.h" 33#include "content/public/browser/notification_types.h" 34#include "content/public/browser/user_metrics.h" 35#include "content/public/browser/web_contents.h" 36#include "content/public/browser/web_contents_view.h" 37#include "grit/theme_resources.h" 38#include "ui/base/animation/animation.h" 39#include "ui/base/animation/animation_delegate.h" 40#include "ui/base/animation/slide_animation.h" 41#include "ui/base/events/event_constants.h" 42#include "ui/base/events/event_utils.h" 43#include "ui/base/resource/resource_bundle.h" 44#include "ui/gfx/canvas.h" 45#include "ui/gfx/image/image_skia.h" 46#include "ui/gfx/screen.h" 47#include "ui/views/focus/view_storage.h" 48#include "ui/views/widget/root_view.h" 49#include "ui/views/widget/widget.h" 50 51#if defined(USE_ASH) 52#include "ash/shell.h" 53#include "ash/wm/coordinate_conversion.h" 54#include "ash/wm/window_settings.h" 55#include "ui/aura/env.h" 56#include "ui/aura/root_window.h" 57#include "ui/base/gestures/gesture_recognizer.h" 58#endif 59 60using content::OpenURLParams; 61using content::UserMetricsAction; 62using content::WebContents; 63 64static const int kHorizontalMoveThreshold = 16; // Pixels. 65 66// Distance from the next/previous stacked before before we consider the tab 67// close enough to trigger moving. 68static const int kStackedDistance = 36; 69 70// If non-null there is a drag underway. 71static TabDragController* instance_ = NULL; 72 73namespace { 74 75// Delay, in ms, during dragging before we bring a window to front. 76const int kBringToFrontDelay = 750; 77 78// Initial delay before moving tabs when the dragged tab is close to the edge of 79// the stacked tabs. 80const int kMoveAttachedInitialDelay = 600; 81 82// Delay for moving tabs after the initial delay has passed. 83const int kMoveAttachedSubsequentDelay = 300; 84 85// Radius of the rect drawn by DockView. 86const int kRoundedRectRadius = 4; 87 88// Spacing between tab icons when DockView is showing a docking location that 89// contains more than one tab. 90const int kTabSpacing = 4; 91 92// DockView is the view responsible for giving a visual indicator of where a 93// dock is going to occur. 94 95class DockView : public views::View { 96 public: 97 explicit DockView(DockInfo::Type type) : type_(type) {} 98 99 virtual gfx::Size GetPreferredSize() OVERRIDE { 100 return gfx::Size(DockInfo::popup_width(), DockInfo::popup_height()); 101 } 102 103 virtual void OnPaintBackground(gfx::Canvas* canvas) OVERRIDE { 104 // Fill the background rect. 105 SkPaint paint; 106 paint.setColor(SkColorSetRGB(108, 108, 108)); 107 paint.setStyle(SkPaint::kFill_Style); 108 canvas->DrawRoundRect(GetLocalBounds(), kRoundedRectRadius, paint); 109 110 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); 111 112 gfx::ImageSkia* high_icon = rb.GetImageSkiaNamed(IDR_DOCK_HIGH); 113 gfx::ImageSkia* wide_icon = rb.GetImageSkiaNamed(IDR_DOCK_WIDE); 114 115 canvas->Save(); 116 bool rtl_ui = base::i18n::IsRTL(); 117 if (rtl_ui) { 118 // Flip canvas to draw the mirrored tab images for RTL UI. 119 canvas->Translate(gfx::Vector2d(width(), 0)); 120 canvas->Scale(-1, 1); 121 } 122 int x_of_active_tab = width() / 2 + kTabSpacing / 2; 123 int x_of_inactive_tab = width() / 2 - high_icon->width() - kTabSpacing / 2; 124 switch (type_) { 125 case DockInfo::LEFT_OF_WINDOW: 126 case DockInfo::LEFT_HALF: 127 if (!rtl_ui) 128 std::swap(x_of_active_tab, x_of_inactive_tab); 129 canvas->DrawImageInt(*high_icon, x_of_active_tab, 130 (height() - high_icon->height()) / 2); 131 if (type_ == DockInfo::LEFT_OF_WINDOW) { 132 DrawImageWithAlpha(canvas, *high_icon, x_of_inactive_tab, 133 (height() - high_icon->height()) / 2); 134 } 135 break; 136 137 138 case DockInfo::RIGHT_OF_WINDOW: 139 case DockInfo::RIGHT_HALF: 140 if (rtl_ui) 141 std::swap(x_of_active_tab, x_of_inactive_tab); 142 canvas->DrawImageInt(*high_icon, x_of_active_tab, 143 (height() - high_icon->height()) / 2); 144 if (type_ == DockInfo::RIGHT_OF_WINDOW) { 145 DrawImageWithAlpha(canvas, *high_icon, x_of_inactive_tab, 146 (height() - high_icon->height()) / 2); 147 } 148 break; 149 150 case DockInfo::TOP_OF_WINDOW: 151 canvas->DrawImageInt(*wide_icon, (width() - wide_icon->width()) / 2, 152 height() / 2 - high_icon->height()); 153 break; 154 155 case DockInfo::MAXIMIZE: { 156 gfx::ImageSkia* max_icon = rb.GetImageSkiaNamed(IDR_DOCK_MAX); 157 canvas->DrawImageInt(*max_icon, (width() - max_icon->width()) / 2, 158 (height() - max_icon->height()) / 2); 159 break; 160 } 161 162 case DockInfo::BOTTOM_HALF: 163 case DockInfo::BOTTOM_OF_WINDOW: 164 canvas->DrawImageInt(*wide_icon, (width() - wide_icon->width()) / 2, 165 height() / 2 + kTabSpacing / 2); 166 if (type_ == DockInfo::BOTTOM_OF_WINDOW) { 167 DrawImageWithAlpha(canvas, *wide_icon, 168 (width() - wide_icon->width()) / 2, 169 height() / 2 - kTabSpacing / 2 - wide_icon->height()); 170 } 171 break; 172 173 default: 174 NOTREACHED(); 175 break; 176 } 177 canvas->Restore(); 178 } 179 180 private: 181 void DrawImageWithAlpha(gfx::Canvas* canvas, const gfx::ImageSkia& image, 182 int x, int y) { 183 SkPaint paint; 184 paint.setAlpha(128); 185 canvas->DrawImageInt(image, x, y, paint); 186 } 187 188 DockInfo::Type type_; 189 190 DISALLOW_COPY_AND_ASSIGN(DockView); 191}; 192 193void SetTrackedByWorkspace(gfx::NativeWindow window, bool value) { 194#if defined(USE_ASH) 195 ash::wm::GetWindowSettings(window)->SetTrackedByWorkspace(value); 196#endif 197} 198 199void SetWindowPositionManaged(gfx::NativeWindow window, bool value) { 200#if defined(USE_ASH) 201 ash::wm::GetWindowSettings(window)->set_window_position_managed(value); 202#endif 203} 204 205// Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate 206// of |bounds| is adjusted by |vertical_adjustment|. 207bool DoesRectContainVerticalPointExpanded( 208 const gfx::Rect& bounds, 209 int vertical_adjustment, 210 int y) { 211 int upper_threshold = bounds.bottom() + vertical_adjustment; 212 int lower_threshold = bounds.y() - vertical_adjustment; 213 return y >= lower_threshold && y <= upper_threshold; 214} 215 216// WidgetObserver implementation that resets the window position managed 217// property on Show. 218// We're forced to do this here since BrowserFrameAura resets the 'window 219// position managed' property during a show and we need the property set to 220// false before WorkspaceLayoutManager2 sees the visibility change. 221class WindowPositionManagedUpdater : public views::WidgetObserver { 222 public: 223 virtual void OnWidgetVisibilityChanged(views::Widget* widget, 224 bool visible) OVERRIDE { 225 SetWindowPositionManaged(widget->GetNativeView(), false); 226 } 227}; 228 229} // namespace 230 231/////////////////////////////////////////////////////////////////////////////// 232// DockDisplayer 233 234// DockDisplayer is responsible for giving the user a visual indication of a 235// possible dock position (as represented by DockInfo). DockDisplayer shows 236// a window with a DockView in it. Two animations are used that correspond to 237// the state of DockInfo::in_enable_area. 238class TabDragController::DockDisplayer : public ui::AnimationDelegate { 239 public: 240 DockDisplayer(TabDragController* controller, const DockInfo& info) 241 : controller_(controller), 242 popup_(NULL), 243 popup_view_(NULL), 244 animation_(this), 245 hidden_(false), 246 in_enable_area_(info.in_enable_area()) { 247 popup_ = new views::Widget; 248 views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); 249 params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; 250 params.keep_on_top = true; 251 params.bounds = info.GetPopupRect(); 252 popup_->Init(params); 253 popup_->SetContentsView(new DockView(info.type())); 254 popup_->SetOpacity(0x00); 255 if (info.in_enable_area()) 256 animation_.Reset(1); 257 else 258 animation_.Show(); 259 popup_->Show(); 260 popup_view_ = popup_->GetNativeView(); 261 } 262 263 virtual ~DockDisplayer() { 264 if (controller_) 265 controller_->DockDisplayerDestroyed(this); 266 } 267 268 // Updates the state based on |in_enable_area|. 269 void UpdateInEnabledArea(bool in_enable_area) { 270 if (in_enable_area != in_enable_area_) { 271 in_enable_area_ = in_enable_area; 272 UpdateLayeredAlpha(); 273 } 274 } 275 276 // Resets the reference to the hosting TabDragController. This is 277 // invoked when the TabDragController is destroyed. 278 void clear_controller() { controller_ = NULL; } 279 280 // NativeView of the window we create. 281 gfx::NativeView popup_view() { return popup_view_; } 282 283 // Starts the hide animation. When the window is closed the 284 // TabDragController is notified by way of the DockDisplayerDestroyed 285 // method 286 void Hide() { 287 if (hidden_) 288 return; 289 290 if (!popup_) { 291 delete this; 292 return; 293 } 294 hidden_ = true; 295 animation_.Hide(); 296 } 297 298 virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE { 299 UpdateLayeredAlpha(); 300 } 301 302 virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE { 303 if (!hidden_) 304 return; 305 popup_->Close(); 306 delete this; 307 } 308 309 private: 310 void UpdateLayeredAlpha() { 311 double scale = in_enable_area_ ? 1 : .5; 312 popup_->SetOpacity(static_cast<unsigned char>(animation_.GetCurrentValue() * 313 scale * 255.0)); 314 } 315 316 // TabDragController that created us. 317 TabDragController* controller_; 318 319 // Window we're showing. 320 views::Widget* popup_; 321 322 // NativeView of |popup_|. We cache this to avoid the possibility of 323 // invoking a method on popup_ after we close it. 324 gfx::NativeView popup_view_; 325 326 // Animation for when first made visible. 327 ui::SlideAnimation animation_; 328 329 // Have we been hidden? 330 bool hidden_; 331 332 // Value of DockInfo::in_enable_area. 333 bool in_enable_area_; 334}; 335 336TabDragController::TabDragData::TabDragData() 337 : contents(NULL), 338 original_delegate(NULL), 339 source_model_index(-1), 340 attached_tab(NULL), 341 pinned(false) { 342} 343 344TabDragController::TabDragData::~TabDragData() { 345} 346 347/////////////////////////////////////////////////////////////////////////////// 348// TabDragController, public: 349 350// static 351const int TabDragController::kTouchVerticalDetachMagnetism = 50; 352 353// static 354const int TabDragController::kVerticalDetachMagnetism = 15; 355 356TabDragController::TabDragController() 357 : detach_into_browser_(ShouldDetachIntoNewBrowser()), 358 event_source_(EVENT_SOURCE_MOUSE), 359 source_tabstrip_(NULL), 360 attached_tabstrip_(NULL), 361 screen_(NULL), 362 host_desktop_type_(chrome::HOST_DESKTOP_TYPE_NATIVE), 363 offset_to_width_ratio_(0), 364 old_focused_view_id_( 365 views::ViewStorage::GetInstance()->CreateStorageID()), 366 last_move_screen_loc_(0), 367 started_drag_(false), 368 active_(true), 369 source_tab_index_(std::numeric_limits<size_t>::max()), 370 initial_move_(true), 371 detach_behavior_(DETACHABLE), 372 move_behavior_(REORDER), 373 mouse_move_direction_(0), 374 is_dragging_window_(false), 375 end_run_loop_behavior_(END_RUN_LOOP_STOP_DRAGGING), 376 waiting_for_run_loop_to_exit_(false), 377 tab_strip_to_attach_to_after_exit_(NULL), 378 move_loop_widget_(NULL), 379 destroyed_(NULL), 380 is_mutating_(false) { 381 instance_ = this; 382} 383 384TabDragController::~TabDragController() { 385 views::ViewStorage::GetInstance()->RemoveView(old_focused_view_id_); 386 387 if (instance_ == this) 388 instance_ = NULL; 389 390 if (destroyed_) 391 *destroyed_ = true; 392 393 if (move_loop_widget_) { 394 move_loop_widget_->RemoveObserver(this); 395 SetTrackedByWorkspace(move_loop_widget_->GetNativeView(), true); 396 SetWindowPositionManaged(move_loop_widget_->GetNativeView(), true); 397 } 398 399 if (source_tabstrip_ && detach_into_browser_) 400 GetModel(source_tabstrip_)->RemoveObserver(this); 401 402 base::MessageLoopForUI::current()->RemoveObserver(this); 403 404 // Need to delete the view here manually _before_ we reset the dragged 405 // contents to NULL, otherwise if the view is animating to its destination 406 // bounds, it won't be able to clean up properly since its cleanup routine 407 // uses GetIndexForDraggedContents, which will be invalid. 408 view_.reset(NULL); 409 410 // Reset the delegate of the dragged WebContents. This ends up doing nothing 411 // if the drag was completed. 412 if (!detach_into_browser_) 413 ResetDelegates(); 414} 415 416void TabDragController::Init( 417 TabStrip* source_tabstrip, 418 Tab* source_tab, 419 const std::vector<Tab*>& tabs, 420 const gfx::Point& mouse_offset, 421 int source_tab_offset, 422 const ui::ListSelectionModel& initial_selection_model, 423 DetachBehavior detach_behavior, 424 MoveBehavior move_behavior, 425 EventSource event_source) { 426 DCHECK(!tabs.empty()); 427 DCHECK(std::find(tabs.begin(), tabs.end(), source_tab) != tabs.end()); 428 source_tabstrip_ = source_tabstrip; 429 screen_ = gfx::Screen::GetScreenFor( 430 source_tabstrip->GetWidget()->GetNativeView()); 431 host_desktop_type_ = chrome::GetHostDesktopTypeForNativeView( 432 source_tabstrip->GetWidget()->GetNativeView()); 433 start_point_in_screen_ = gfx::Point(source_tab_offset, mouse_offset.y()); 434 views::View::ConvertPointToScreen(source_tab, &start_point_in_screen_); 435 event_source_ = event_source; 436 mouse_offset_ = mouse_offset; 437 detach_behavior_ = detach_behavior; 438 move_behavior_ = move_behavior; 439 last_point_in_screen_ = start_point_in_screen_; 440 last_move_screen_loc_ = start_point_in_screen_.x(); 441 initial_tab_positions_ = source_tabstrip->GetTabXCoordinates(); 442 if (detach_behavior == NOT_DETACHABLE) 443 detach_into_browser_ = false; 444 445 if (detach_into_browser_) 446 GetModel(source_tabstrip_)->AddObserver(this); 447 448 drag_data_.resize(tabs.size()); 449 for (size_t i = 0; i < tabs.size(); ++i) 450 InitTabDragData(tabs[i], &(drag_data_[i])); 451 source_tab_index_ = 452 std::find(tabs.begin(), tabs.end(), source_tab) - tabs.begin(); 453 454 // Listen for Esc key presses. 455 base::MessageLoopForUI::current()->AddObserver(this); 456 457 if (source_tab->width() > 0) { 458 offset_to_width_ratio_ = static_cast<float>( 459 source_tab->GetMirroredXInView(source_tab_offset)) / 460 static_cast<float>(source_tab->width()); 461 } 462 InitWindowCreatePoint(); 463 initial_selection_model_.Copy(initial_selection_model); 464} 465 466// static 467bool TabDragController::IsAttachedTo(TabStrip* tab_strip) { 468 return (instance_ && instance_->active() && 469 instance_->attached_tabstrip() == tab_strip); 470} 471 472// static 473bool TabDragController::IsActive() { 474 return instance_ && instance_->active(); 475} 476 477// static 478bool TabDragController::ShouldDetachIntoNewBrowser() { 479#if defined(USE_AURA) 480 return true; 481#else 482 return CommandLine::ForCurrentProcess()->HasSwitch( 483 switches::kTabBrowserDragging); 484#endif 485} 486 487void TabDragController::SetMoveBehavior(MoveBehavior behavior) { 488 if (started_drag()) 489 return; 490 491 move_behavior_ = behavior; 492} 493 494void TabDragController::Drag(const gfx::Point& point_in_screen) { 495 bring_to_front_timer_.Stop(); 496 move_stacked_timer_.Stop(); 497 498 if (waiting_for_run_loop_to_exit_) 499 return; 500 501 if (!started_drag_) { 502 if (!CanStartDrag(point_in_screen)) 503 return; // User hasn't dragged far enough yet. 504 505 // On windows SaveFocus() may trigger a capture lost, which destroys us. 506 { 507 bool destroyed = false; 508 destroyed_ = &destroyed; 509 SaveFocus(); 510 if (destroyed) 511 return; 512 destroyed_ = NULL; 513 } 514 started_drag_ = true; 515 Attach(source_tabstrip_, gfx::Point()); 516 if (detach_into_browser_ && static_cast<int>(drag_data_.size()) == 517 GetModel(source_tabstrip_)->count()) { 518 RunMoveLoop(GetWindowOffset(point_in_screen)); 519 return; 520 } 521 } 522 523 ContinueDragging(point_in_screen); 524} 525 526void TabDragController::EndDrag(EndDragReason reason) { 527 // If we're dragging a window ignore capture lost since it'll ultimately 528 // trigger the move loop to end and we'll revert the drag when RunMoveLoop() 529 // finishes. 530 if (reason == END_DRAG_CAPTURE_LOST && is_dragging_window_) 531 return; 532 EndDragImpl(reason != END_DRAG_COMPLETE && source_tabstrip_ ? 533 CANCELED : NORMAL); 534} 535 536void TabDragController::InitTabDragData(Tab* tab, 537 TabDragData* drag_data) { 538 drag_data->source_model_index = 539 source_tabstrip_->GetModelIndexOfTab(tab); 540 drag_data->contents = GetModel(source_tabstrip_)->GetWebContentsAt( 541 drag_data->source_model_index); 542 drag_data->pinned = source_tabstrip_->IsTabPinned(tab); 543 registrar_.Add( 544 this, 545 content::NOTIFICATION_WEB_CONTENTS_DESTROYED, 546 content::Source<WebContents>(drag_data->contents)); 547 548 if (!detach_into_browser_) { 549 drag_data->original_delegate = drag_data->contents->GetDelegate(); 550 drag_data->contents->SetDelegate(this); 551 } 552} 553 554/////////////////////////////////////////////////////////////////////////////// 555// TabDragController, PageNavigator implementation: 556 557WebContents* TabDragController::OpenURLFromTab( 558 WebContents* source, 559 const OpenURLParams& params) { 560 if (source_tab_drag_data()->original_delegate) { 561 OpenURLParams forward_params = params; 562 if (params.disposition == CURRENT_TAB) 563 forward_params.disposition = NEW_WINDOW; 564 565 return source_tab_drag_data()->original_delegate->OpenURLFromTab( 566 source, forward_params); 567 } 568 return NULL; 569} 570 571/////////////////////////////////////////////////////////////////////////////// 572// TabDragController, content::WebContentsDelegate implementation: 573 574void TabDragController::NavigationStateChanged(const WebContents* source, 575 unsigned changed_flags) { 576 if (attached_tabstrip_ || 577 changed_flags == content::INVALIDATE_TYPE_PAGE_ACTIONS) { 578 for (size_t i = 0; i < drag_data_.size(); ++i) { 579 if (drag_data_[i].contents == source) { 580 // Pass the NavigationStateChanged call to the original delegate so 581 // that the title is updated. Do this only when we are attached as 582 // otherwise the Tab isn't in the TabStrip (except for page action 583 // updates). 584 drag_data_[i].original_delegate->NavigationStateChanged(source, 585 changed_flags); 586 break; 587 } 588 } 589 } 590 if (view_.get()) 591 view_->Update(); 592} 593 594void TabDragController::AddNewContents(WebContents* source, 595 WebContents* new_contents, 596 WindowOpenDisposition disposition, 597 const gfx::Rect& initial_pos, 598 bool user_gesture, 599 bool* was_blocked) { 600 DCHECK_NE(CURRENT_TAB, disposition); 601 602 // Theoretically could be called while dragging if the page tries to 603 // spawn a window. Route this message back to the browser in most cases. 604 if (source_tab_drag_data()->original_delegate) { 605 source_tab_drag_data()->original_delegate->AddNewContents( 606 source, new_contents, disposition, initial_pos, user_gesture, 607 was_blocked); 608 } 609} 610 611void TabDragController::LoadingStateChanged(WebContents* source) { 612 // It would be nice to respond to this message by changing the 613 // screen shot in the dragged tab. 614 if (view_.get()) 615 view_->Update(); 616} 617 618bool TabDragController::ShouldSuppressDialogs() { 619 // When a dialog is about to be shown we revert the drag. Otherwise a modal 620 // dialog might appear and attempt to parent itself to a hidden tabcontents. 621 EndDragImpl(CANCELED); 622 return false; 623} 624 625content::JavaScriptDialogManager* 626TabDragController::GetJavaScriptDialogManager() { 627 return GetJavaScriptDialogManagerInstance(); 628} 629 630/////////////////////////////////////////////////////////////////////////////// 631// TabDragController, content::NotificationObserver implementation: 632 633void TabDragController::Observe( 634 int type, 635 const content::NotificationSource& source, 636 const content::NotificationDetails& details) { 637 DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED, type); 638 WebContents* destroyed_web_contents = 639 content::Source<WebContents>(source).ptr(); 640 for (size_t i = 0; i < drag_data_.size(); ++i) { 641 if (drag_data_[i].contents == destroyed_web_contents) { 642 // One of the tabs we're dragging has been destroyed. Cancel the drag. 643 if (destroyed_web_contents->GetDelegate() == this) 644 destroyed_web_contents->SetDelegate(NULL); 645 drag_data_[i].contents = NULL; 646 drag_data_[i].original_delegate = NULL; 647 EndDragImpl(TAB_DESTROYED); 648 return; 649 } 650 } 651 // If we get here it means we got notification for a tab we don't know about. 652 NOTREACHED(); 653} 654 655/////////////////////////////////////////////////////////////////////////////// 656// TabDragController, MessageLoop::Observer implementation: 657 658base::EventStatus TabDragController::WillProcessEvent( 659 const base::NativeEvent& event) { 660 return base::EVENT_CONTINUE; 661} 662 663void TabDragController::DidProcessEvent(const base::NativeEvent& event) { 664 // If the user presses ESC during a drag, we need to abort and revert things 665 // to the way they were. This is the most reliable way to do this since no 666 // single view or window reliably receives events throughout all the various 667 // kinds of tab dragging. 668 if (ui::EventTypeFromNative(event) == ui::ET_KEY_PRESSED && 669 ui::KeyboardCodeFromNative(event) == ui::VKEY_ESCAPE) { 670 EndDrag(END_DRAG_CANCEL); 671 } 672} 673 674void TabDragController::OnWidgetBoundsChanged(views::Widget* widget, 675 const gfx::Rect& new_bounds) { 676 Drag(GetCursorScreenPoint()); 677} 678 679void TabDragController::TabStripEmpty() { 680 DCHECK(detach_into_browser_); 681 GetModel(source_tabstrip_)->RemoveObserver(this); 682 // NULL out source_tabstrip_ so that we don't attempt to add back to it (in 683 // the case of a revert). 684 source_tabstrip_ = NULL; 685} 686 687/////////////////////////////////////////////////////////////////////////////// 688// TabDragController, private: 689 690void TabDragController::InitWindowCreatePoint() { 691 // window_create_point_ is only used in CompleteDrag() (through 692 // GetWindowCreatePoint() to get the start point of the docked window) when 693 // the attached_tabstrip_ is NULL and all the window's related bound 694 // information are obtained from source_tabstrip_. So, we need to get the 695 // first_tab based on source_tabstrip_, not attached_tabstrip_. Otherwise, 696 // the window_create_point_ is not in the correct coordinate system. Please 697 // refer to http://crbug.com/6223 comment #15 for detailed information. 698 views::View* first_tab = source_tabstrip_->tab_at(0); 699 views::View::ConvertPointToWidget(first_tab, &first_source_tab_point_); 700 window_create_point_ = first_source_tab_point_; 701 window_create_point_.Offset(mouse_offset_.x(), mouse_offset_.y()); 702} 703 704gfx::Point TabDragController::GetWindowCreatePoint( 705 const gfx::Point& origin) const { 706 if (dock_info_.type() != DockInfo::NONE && dock_info_.in_enable_area()) { 707 // If we're going to dock, we need to return the exact coordinate, 708 // otherwise we may attempt to maximize on the wrong monitor. 709 return origin; 710 } 711 712 // If the cursor is outside the monitor area, move it inside. For example, 713 // dropping a tab onto the task bar on Windows produces this situation. 714 gfx::Rect work_area = screen_->GetDisplayNearestPoint(origin).work_area(); 715 gfx::Point create_point(origin); 716 if (!work_area.IsEmpty()) { 717 if (create_point.x() < work_area.x()) 718 create_point.set_x(work_area.x()); 719 else if (create_point.x() > work_area.right()) 720 create_point.set_x(work_area.right()); 721 if (create_point.y() < work_area.y()) 722 create_point.set_y(work_area.y()); 723 else if (create_point.y() > work_area.bottom()) 724 create_point.set_y(work_area.bottom()); 725 } 726 return gfx::Point(create_point.x() - window_create_point_.x(), 727 create_point.y() - window_create_point_.y()); 728} 729 730void TabDragController::UpdateDockInfo(const gfx::Point& point_in_screen) { 731 // Update the DockInfo for the current mouse coordinates. 732 DockInfo dock_info = GetDockInfoAtPoint(point_in_screen); 733 if (!dock_info.equals(dock_info_)) { 734 // DockInfo for current position differs. 735 if (dock_info_.type() != DockInfo::NONE && 736 !dock_controllers_.empty()) { 737 // Hide old visual indicator. 738 dock_controllers_.back()->Hide(); 739 } 740 dock_info_ = dock_info; 741 if (dock_info_.type() != DockInfo::NONE) { 742 // Show new docking position. 743 DockDisplayer* controller = new DockDisplayer(this, dock_info_); 744 if (controller->popup_view()) { 745 dock_controllers_.push_back(controller); 746 dock_windows_.insert(controller->popup_view()); 747 } else { 748 delete controller; 749 } 750 } 751 } else if (dock_info_.type() != DockInfo::NONE && 752 !dock_controllers_.empty()) { 753 // Current dock position is the same as last, update the controller's 754 // in_enable_area state as it may have changed. 755 dock_controllers_.back()->UpdateInEnabledArea(dock_info_.in_enable_area()); 756 } 757} 758 759void TabDragController::SaveFocus() { 760 DCHECK(source_tabstrip_); 761 views::View* focused_view = 762 source_tabstrip_->GetFocusManager()->GetFocusedView(); 763 if (focused_view) 764 views::ViewStorage::GetInstance()->StoreView(old_focused_view_id_, 765 focused_view); 766 source_tabstrip_->GetFocusManager()->SetFocusedView(source_tabstrip_); 767 // WARNING: we may have been deleted. 768} 769 770void TabDragController::RestoreFocus() { 771 if (attached_tabstrip_ != source_tabstrip_) 772 return; 773 views::View* old_focused_view = 774 views::ViewStorage::GetInstance()->RetrieveView( 775 old_focused_view_id_); 776 if (!old_focused_view) 777 return; 778 old_focused_view->GetFocusManager()->SetFocusedView(old_focused_view); 779} 780 781bool TabDragController::CanStartDrag(const gfx::Point& point_in_screen) const { 782 // Determine if the mouse has moved beyond a minimum elasticity distance in 783 // any direction from the starting point. 784 static const int kMinimumDragDistance = 10; 785 int x_offset = abs(point_in_screen.x() - start_point_in_screen_.x()); 786 int y_offset = abs(point_in_screen.y() - start_point_in_screen_.y()); 787 return sqrt(pow(static_cast<float>(x_offset), 2) + 788 pow(static_cast<float>(y_offset), 2)) > kMinimumDragDistance; 789} 790 791void TabDragController::ContinueDragging(const gfx::Point& point_in_screen) { 792 DCHECK(!detach_into_browser_ || attached_tabstrip_); 793 794 TabStrip* target_tabstrip = detach_behavior_ == DETACHABLE ? 795 GetTargetTabStripForPoint(point_in_screen) : source_tabstrip_; 796 bool tab_strip_changed = (target_tabstrip != attached_tabstrip_); 797 798 if (attached_tabstrip_) { 799 int move_delta = point_in_screen.x() - last_point_in_screen_.x(); 800 if (move_delta > 0) 801 mouse_move_direction_ |= kMovedMouseRight; 802 else if (move_delta < 0) 803 mouse_move_direction_ |= kMovedMouseLeft; 804 } 805 last_point_in_screen_ = point_in_screen; 806 807 if (tab_strip_changed) { 808 if (detach_into_browser_ && 809 DragBrowserToNewTabStrip(target_tabstrip, point_in_screen) == 810 DRAG_BROWSER_RESULT_STOP) { 811 return; 812 } else if (!detach_into_browser_) { 813 if (attached_tabstrip_) 814 Detach(RELEASE_CAPTURE); 815 if (target_tabstrip) 816 Attach(target_tabstrip, point_in_screen); 817 } 818 } 819 if (view_.get() || is_dragging_window_) { 820 static_cast<base::Timer*>(&bring_to_front_timer_)->Start(FROM_HERE, 821 base::TimeDelta::FromMilliseconds(kBringToFrontDelay), 822 base::Bind(&TabDragController::BringWindowUnderPointToFront, 823 base::Unretained(this), point_in_screen)); 824 } 825 826 UpdateDockInfo(point_in_screen); 827 828 if (!is_dragging_window_) { 829 if (attached_tabstrip_) { 830 if (move_only()) { 831 DragActiveTabStacked(point_in_screen); 832 } else { 833 MoveAttached(point_in_screen); 834 if (tab_strip_changed) { 835 // Move the corresponding window to the front. We do this after the 836 // move as on windows activate triggers a synchronous paint. 837 attached_tabstrip_->GetWidget()->Activate(); 838 } 839 } 840 } else { 841 MoveDetached(point_in_screen); 842 } 843 } 844} 845 846TabDragController::DragBrowserResultType 847TabDragController::DragBrowserToNewTabStrip( 848 TabStrip* target_tabstrip, 849 const gfx::Point& point_in_screen) { 850 if (!target_tabstrip) { 851 DetachIntoNewBrowserAndRunMoveLoop(point_in_screen); 852 return DRAG_BROWSER_RESULT_STOP; 853 } 854 if (is_dragging_window_) { 855 // ReleaseCapture() is going to result in calling back to us (because it 856 // results in a move). That'll cause all sorts of problems. Reset the 857 // observer so we don't get notified and process the event. 858 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) { 859 move_loop_widget_->RemoveObserver(this); 860 move_loop_widget_ = NULL; 861 } 862 views::Widget* browser_widget = GetAttachedBrowserWidget(); 863 // Need to release the drag controller before starting the move loop as it's 864 // going to trigger capture lost, which cancels drag. 865 attached_tabstrip_->ReleaseDragController(); 866 target_tabstrip->OwnDragController(this); 867 // Disable animations so that we don't see a close animation on aero. 868 browser_widget->SetVisibilityChangedAnimationsEnabled(false); 869 // For aura we can't release capture, otherwise it'll cancel a gesture. 870 // Instead we have to directly change capture. 871 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) 872 target_tabstrip->GetWidget()->SetCapture(attached_tabstrip_); 873 else 874 browser_widget->ReleaseCapture(); 875 // The window is going away. Since the drag is still on going we don't want 876 // that to effect the position of any windows. 877 SetWindowPositionManaged(browser_widget->GetNativeView(), false); 878 879 // EndMoveLoop is going to snap the window back to its original location. 880 // Hide it so users don't see this. 881 browser_widget->Hide(); 882 browser_widget->EndMoveLoop(); 883 884 // Ideally we would always swap the tabs now, but on non-ash it seems that 885 // running the move loop implicitly activates the window when done, leading 886 // to all sorts of flicker. So, on non-ash, instead we process the move 887 // after the loop completes. But on chromeos, we can do tab swapping now to 888 // avoid the tab flashing issue(crbug.com/116329). 889 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) { 890 is_dragging_window_ = false; 891 Detach(DONT_RELEASE_CAPTURE); 892 Attach(target_tabstrip, point_in_screen); 893 // Move the tabs into position. 894 MoveAttached(point_in_screen); 895 attached_tabstrip_->GetWidget()->Activate(); 896 } else { 897 tab_strip_to_attach_to_after_exit_ = target_tabstrip; 898 } 899 900 waiting_for_run_loop_to_exit_ = true; 901 end_run_loop_behavior_ = END_RUN_LOOP_CONTINUE_DRAGGING; 902 return DRAG_BROWSER_RESULT_STOP; 903 } 904 Detach(DONT_RELEASE_CAPTURE); 905 Attach(target_tabstrip, point_in_screen); 906 return DRAG_BROWSER_RESULT_CONTINUE; 907} 908 909void TabDragController::DragActiveTabStacked( 910 const gfx::Point& point_in_screen) { 911 if (attached_tabstrip_->tab_count() != 912 static_cast<int>(initial_tab_positions_.size())) 913 return; // TODO: should cancel drag if this happens. 914 915 int delta = point_in_screen.x() - start_point_in_screen_.x(); 916 attached_tabstrip_->DragActiveTab(initial_tab_positions_, delta); 917} 918 919void TabDragController::MoveAttachedToNextStackedIndex( 920 const gfx::Point& point_in_screen) { 921 int index = attached_tabstrip_->touch_layout_->active_index(); 922 if (index + 1 >= attached_tabstrip_->tab_count()) 923 return; 924 925 GetModel(attached_tabstrip_)->MoveSelectedTabsTo(index + 1); 926 StartMoveStackedTimerIfNecessary(point_in_screen, 927 kMoveAttachedSubsequentDelay); 928} 929 930void TabDragController::MoveAttachedToPreviousStackedIndex( 931 const gfx::Point& point_in_screen) { 932 int index = attached_tabstrip_->touch_layout_->active_index(); 933 if (index <= attached_tabstrip_->GetMiniTabCount()) 934 return; 935 936 GetModel(attached_tabstrip_)->MoveSelectedTabsTo(index - 1); 937 StartMoveStackedTimerIfNecessary(point_in_screen, 938 kMoveAttachedSubsequentDelay); 939} 940 941void TabDragController::MoveAttached(const gfx::Point& point_in_screen) { 942 DCHECK(attached_tabstrip_); 943 DCHECK(!view_.get()); 944 DCHECK(!is_dragging_window_); 945 946 gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen); 947 948 // Determine the horizontal move threshold. This is dependent on the width 949 // of tabs. The smaller the tabs compared to the standard size, the smaller 950 // the threshold. 951 int threshold = kHorizontalMoveThreshold; 952 if (!attached_tabstrip_->touch_layout_.get()) { 953 double unselected, selected; 954 attached_tabstrip_->GetCurrentTabWidths(&unselected, &selected); 955 double ratio = unselected / Tab::GetStandardSize().width(); 956 threshold = static_cast<int>(ratio * kHorizontalMoveThreshold); 957 } 958 // else case: touch tabs never shrink. 959 960 std::vector<Tab*> tabs(drag_data_.size()); 961 for (size_t i = 0; i < drag_data_.size(); ++i) 962 tabs[i] = drag_data_[i].attached_tab; 963 964 bool did_layout = false; 965 // Update the model, moving the WebContents from one index to another. Do this 966 // only if we have moved a minimum distance since the last reorder (to prevent 967 // jitter) or if this the first move and the tabs are not consecutive. 968 if ((abs(point_in_screen.x() - last_move_screen_loc_) > threshold || 969 (initial_move_ && !AreTabsConsecutive()))) { 970 TabStripModel* attached_model = GetModel(attached_tabstrip_); 971 gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_point); 972 int to_index = GetInsertionIndexForDraggedBounds(bounds); 973 WebContents* last_contents = drag_data_[drag_data_.size() - 1].contents; 974 int index_of_last_item = 975 attached_model->GetIndexOfWebContents(last_contents); 976 if (initial_move_) { 977 // TabStrip determines if the tabs needs to be animated based on model 978 // position. This means we need to invoke LayoutDraggedTabsAt before 979 // changing the model. 980 attached_tabstrip_->LayoutDraggedTabsAt( 981 tabs, source_tab_drag_data()->attached_tab, dragged_view_point, 982 initial_move_); 983 did_layout = true; 984 } 985 attached_model->MoveSelectedTabsTo(to_index); 986 987 // Move may do nothing in certain situations (such as when dragging pinned 988 // tabs). Make sure the tabstrip actually changed before updating 989 // last_move_screen_loc_. 990 if (index_of_last_item != 991 attached_model->GetIndexOfWebContents(last_contents)) { 992 last_move_screen_loc_ = point_in_screen.x(); 993 } 994 } 995 996 if (!did_layout) { 997 attached_tabstrip_->LayoutDraggedTabsAt( 998 tabs, source_tab_drag_data()->attached_tab, dragged_view_point, 999 initial_move_); 1000 } 1001 1002 StartMoveStackedTimerIfNecessary(point_in_screen, kMoveAttachedInitialDelay); 1003 1004 initial_move_ = false; 1005} 1006 1007void TabDragController::MoveDetached(const gfx::Point& point_in_screen) { 1008 DCHECK(!attached_tabstrip_); 1009 DCHECK(view_.get()); 1010 DCHECK(!is_dragging_window_); 1011 1012 // Move the View. There are no changes to the model if we're detached. 1013 view_->MoveTo(point_in_screen); 1014} 1015 1016void TabDragController::StartMoveStackedTimerIfNecessary( 1017 const gfx::Point& point_in_screen, 1018 int delay_ms) { 1019 DCHECK(attached_tabstrip_); 1020 1021 StackedTabStripLayout* touch_layout = attached_tabstrip_->touch_layout_.get(); 1022 if (!touch_layout) 1023 return; 1024 1025 gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen); 1026 gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_point); 1027 int index = touch_layout->active_index(); 1028 if (ShouldDragToNextStackedTab(bounds, index)) { 1029 static_cast<base::Timer*>(&move_stacked_timer_)->Start( 1030 FROM_HERE, 1031 base::TimeDelta::FromMilliseconds(delay_ms), 1032 base::Bind(&TabDragController::MoveAttachedToNextStackedIndex, 1033 base::Unretained(this), point_in_screen)); 1034 } else if (ShouldDragToPreviousStackedTab(bounds, index)) { 1035 static_cast<base::Timer*>(&move_stacked_timer_)->Start( 1036 FROM_HERE, 1037 base::TimeDelta::FromMilliseconds(delay_ms), 1038 base::Bind(&TabDragController::MoveAttachedToPreviousStackedIndex, 1039 base::Unretained(this), point_in_screen)); 1040 } 1041} 1042 1043TabDragController::DetachPosition TabDragController::GetDetachPosition( 1044 const gfx::Point& point_in_screen) { 1045 DCHECK(attached_tabstrip_); 1046 gfx::Point attached_point(point_in_screen); 1047 views::View::ConvertPointToTarget(NULL, attached_tabstrip_, &attached_point); 1048 if (attached_point.x() < 0) 1049 return DETACH_BEFORE; 1050 if (attached_point.x() >= attached_tabstrip_->width()) 1051 return DETACH_AFTER; 1052 return DETACH_ABOVE_OR_BELOW; 1053} 1054 1055DockInfo TabDragController::GetDockInfoAtPoint( 1056 const gfx::Point& point_in_screen) { 1057 // TODO: add support for dock info when |detach_into_browser_| is true. 1058 if (attached_tabstrip_ || detach_into_browser_) { 1059 // If the mouse is over a tab strip, don't offer a dock position. 1060 return DockInfo(); 1061 } 1062 1063 if (dock_info_.IsValidForPoint(point_in_screen)) { 1064 // It's possible any given screen coordinate has multiple docking 1065 // positions. Check the current info first to avoid having the docking 1066 // position bounce around. 1067 return dock_info_; 1068 } 1069 1070 gfx::NativeView dragged_view = view_->GetWidget()->GetNativeView(); 1071 dock_windows_.insert(dragged_view); 1072 DockInfo info = DockInfo::GetDockInfoAtPoint( 1073 host_desktop_type_, 1074 point_in_screen, 1075 dock_windows_); 1076 dock_windows_.erase(dragged_view); 1077 return info; 1078} 1079 1080TabStrip* TabDragController::GetTargetTabStripForPoint( 1081 const gfx::Point& point_in_screen) { 1082 if (move_only() && attached_tabstrip_) { 1083 DCHECK_EQ(DETACHABLE, detach_behavior_); 1084 // move_only() is intended for touch, in which case we only want to detach 1085 // if the touch point moves significantly in the vertical distance. 1086 gfx::Rect tabstrip_bounds = GetViewScreenBounds(attached_tabstrip_); 1087 if (DoesRectContainVerticalPointExpanded(tabstrip_bounds, 1088 kTouchVerticalDetachMagnetism, 1089 point_in_screen.y())) 1090 return attached_tabstrip_; 1091 } 1092 gfx::NativeView dragged_view = NULL; 1093 if (view_.get()) 1094 dragged_view = view_->GetWidget()->GetNativeView(); 1095 else if (is_dragging_window_) 1096 dragged_view = attached_tabstrip_->GetWidget()->GetNativeView(); 1097 if (dragged_view) 1098 dock_windows_.insert(dragged_view); 1099 gfx::NativeWindow local_window = 1100 DockInfo::GetLocalProcessWindowAtPoint( 1101 host_desktop_type_, 1102 point_in_screen, 1103 dock_windows_); 1104 if (dragged_view) 1105 dock_windows_.erase(dragged_view); 1106 TabStrip* tab_strip = GetTabStripForWindow(local_window); 1107 if (tab_strip && DoesTabStripContain(tab_strip, point_in_screen)) 1108 return tab_strip; 1109 return is_dragging_window_ ? attached_tabstrip_ : NULL; 1110} 1111 1112TabStrip* TabDragController::GetTabStripForWindow(gfx::NativeWindow window) { 1113 if (!window) 1114 return NULL; 1115 BrowserView* browser_view = 1116 BrowserView::GetBrowserViewForNativeWindow(window); 1117 // We don't allow drops on windows that don't have tabstrips. 1118 if (!browser_view || 1119 !browser_view->browser()->SupportsWindowFeature( 1120 Browser::FEATURE_TABSTRIP)) 1121 return NULL; 1122 1123 TabStrip* other_tabstrip = browser_view->tabstrip(); 1124 TabStrip* tab_strip = 1125 attached_tabstrip_ ? attached_tabstrip_ : source_tabstrip_; 1126 DCHECK(tab_strip); 1127 1128 return other_tabstrip->controller()->IsCompatibleWith(tab_strip) ? 1129 other_tabstrip : NULL; 1130} 1131 1132bool TabDragController::DoesTabStripContain( 1133 TabStrip* tabstrip, 1134 const gfx::Point& point_in_screen) const { 1135 // Make sure the specified screen point is actually within the bounds of the 1136 // specified tabstrip... 1137 gfx::Rect tabstrip_bounds = GetViewScreenBounds(tabstrip); 1138 return point_in_screen.x() < tabstrip_bounds.right() && 1139 point_in_screen.x() >= tabstrip_bounds.x() && 1140 DoesRectContainVerticalPointExpanded(tabstrip_bounds, 1141 kVerticalDetachMagnetism, 1142 point_in_screen.y()); 1143} 1144 1145void TabDragController::Attach(TabStrip* attached_tabstrip, 1146 const gfx::Point& point_in_screen) { 1147 DCHECK(!attached_tabstrip_); // We should already have detached by the time 1148 // we get here. 1149 1150 attached_tabstrip_ = attached_tabstrip; 1151 1152 // And we don't need the dragged view. 1153 view_.reset(); 1154 1155 std::vector<Tab*> tabs = 1156 GetTabsMatchingDraggedContents(attached_tabstrip_); 1157 1158 if (tabs.empty()) { 1159 // Transitioning from detached to attached to a new tabstrip. Add tabs to 1160 // the new model. 1161 1162 selection_model_before_attach_.Copy(attached_tabstrip->GetSelectionModel()); 1163 1164 if (!detach_into_browser_) { 1165 // Remove ourselves as the delegate now that the dragged WebContents is 1166 // being inserted back into a Browser. 1167 for (size_t i = 0; i < drag_data_.size(); ++i) { 1168 drag_data_[i].contents->SetDelegate(NULL); 1169 drag_data_[i].original_delegate = NULL; 1170 } 1171 1172 // Return the WebContents to normalcy. 1173 source_dragged_contents()->DecrementCapturerCount(); 1174 } 1175 1176 // Inserting counts as a move. We don't want the tabs to jitter when the 1177 // user moves the tab immediately after attaching it. 1178 last_move_screen_loc_ = point_in_screen.x(); 1179 1180 // Figure out where to insert the tab based on the bounds of the dragged 1181 // representation and the ideal bounds of the other Tabs already in the 1182 // strip. ("ideal bounds" are stable even if the Tabs' actual bounds are 1183 // changing due to animation). 1184 gfx::Point tab_strip_point(point_in_screen); 1185 views::View::ConvertPointToTarget(NULL, attached_tabstrip_, 1186 &tab_strip_point); 1187 tab_strip_point.set_x( 1188 attached_tabstrip_->GetMirroredXInView(tab_strip_point.x())); 1189 tab_strip_point.Offset(-mouse_offset_.x(), -mouse_offset_.y()); 1190 gfx::Rect bounds = GetDraggedViewTabStripBounds(tab_strip_point); 1191 int index = GetInsertionIndexForDraggedBounds(bounds); 1192 base::AutoReset<bool> setter(&is_mutating_, true); 1193 for (size_t i = 0; i < drag_data_.size(); ++i) { 1194 int add_types = TabStripModel::ADD_NONE; 1195 if (attached_tabstrip_->touch_layout_.get()) { 1196 // StackedTabStripLayout positions relative to the active tab, if we 1197 // don't add the tab as active things bounce around. 1198 DCHECK_EQ(1u, drag_data_.size()); 1199 add_types |= TabStripModel::ADD_ACTIVE; 1200 } 1201 if (drag_data_[i].pinned) 1202 add_types |= TabStripModel::ADD_PINNED; 1203 GetModel(attached_tabstrip_)->InsertWebContentsAt( 1204 index + i, drag_data_[i].contents, add_types); 1205 } 1206 1207 tabs = GetTabsMatchingDraggedContents(attached_tabstrip_); 1208 } 1209 DCHECK_EQ(tabs.size(), drag_data_.size()); 1210 for (size_t i = 0; i < drag_data_.size(); ++i) 1211 drag_data_[i].attached_tab = tabs[i]; 1212 1213 attached_tabstrip_->StartedDraggingTabs(tabs); 1214 1215 ResetSelection(GetModel(attached_tabstrip_)); 1216 1217 // The size of the dragged tab may have changed. Adjust the x offset so that 1218 // ratio of mouse_offset_ to original width is maintained. 1219 std::vector<Tab*> tabs_to_source(tabs); 1220 tabs_to_source.erase(tabs_to_source.begin() + source_tab_index_ + 1, 1221 tabs_to_source.end()); 1222 int new_x = attached_tabstrip_->GetSizeNeededForTabs(tabs_to_source) - 1223 tabs[source_tab_index_]->width() + 1224 static_cast<int>(offset_to_width_ratio_ * 1225 tabs[source_tab_index_]->width()); 1226 mouse_offset_.set_x(new_x); 1227 1228 // Transfer ownership of us to the new tabstrip as well as making sure the 1229 // window has capture. This is important so that if activation changes the 1230 // drag isn't prematurely canceled. 1231 if (detach_into_browser_) { 1232 attached_tabstrip_->GetWidget()->SetCapture(attached_tabstrip_); 1233 attached_tabstrip_->OwnDragController(this); 1234 } 1235 1236 // Redirect all mouse events to the TabStrip so that the tab that originated 1237 // the drag can safely be deleted. 1238 if (detach_into_browser_ || attached_tabstrip_ == source_tabstrip_) { 1239 static_cast<views::internal::RootView*>( 1240 attached_tabstrip_->GetWidget()->GetRootView())->SetMouseHandler( 1241 attached_tabstrip_); 1242 } 1243} 1244 1245void TabDragController::Detach(ReleaseCapture release_capture) { 1246 // When the user detaches we assume they want to reorder. 1247 move_behavior_ = REORDER; 1248 1249 // Release ownership of the drag controller and mouse capture. When we 1250 // reattach ownership is transfered. 1251 if (detach_into_browser_) { 1252 attached_tabstrip_->ReleaseDragController(); 1253 if (release_capture == RELEASE_CAPTURE) 1254 attached_tabstrip_->GetWidget()->ReleaseCapture(); 1255 } 1256 1257 mouse_move_direction_ = kMovedMouseLeft | kMovedMouseRight; 1258 1259 // Prevent the WebContents HWND from being hidden by any of the model 1260 // operations performed during the drag. 1261 if (!detach_into_browser_) 1262 source_dragged_contents()->IncrementCapturerCount(); 1263 1264 std::vector<gfx::Rect> drag_bounds = CalculateBoundsForDraggedTabs(0); 1265 TabStripModel* attached_model = GetModel(attached_tabstrip_); 1266 std::vector<TabRendererData> tab_data; 1267 for (size_t i = 0; i < drag_data_.size(); ++i) { 1268 tab_data.push_back(drag_data_[i].attached_tab->data()); 1269 int index = attached_model->GetIndexOfWebContents(drag_data_[i].contents); 1270 DCHECK_NE(-1, index); 1271 1272 // Hide the tab so that the user doesn't see it animate closed. 1273 drag_data_[i].attached_tab->SetVisible(false); 1274 1275 attached_model->DetachWebContentsAt(index); 1276 1277 // Detaching resets the delegate, but we still want to be the delegate. 1278 if (!detach_into_browser_) 1279 drag_data_[i].contents->SetDelegate(this); 1280 1281 // Detaching may end up deleting the tab, drop references to it. 1282 drag_data_[i].attached_tab = NULL; 1283 } 1284 1285 // If we've removed the last Tab from the TabStrip, hide the frame now. 1286 if (!attached_model->empty()) { 1287 if (!selection_model_before_attach_.empty() && 1288 selection_model_before_attach_.active() >= 0 && 1289 selection_model_before_attach_.active() < attached_model->count()) { 1290 // Restore the selection. 1291 attached_model->SetSelectionFromModel(selection_model_before_attach_); 1292 } else if (attached_tabstrip_ == source_tabstrip_ && 1293 !initial_selection_model_.empty()) { 1294 // First time detaching from the source tabstrip. Reset selection model to 1295 // initial_selection_model_. Before resetting though we have to remove all 1296 // the tabs from initial_selection_model_ as it was created with the tabs 1297 // still there. 1298 ui::ListSelectionModel selection_model; 1299 selection_model.Copy(initial_selection_model_); 1300 for (DragData::const_reverse_iterator i(drag_data_.rbegin()); 1301 i != drag_data_.rend(); ++i) { 1302 selection_model.DecrementFrom(i->source_model_index); 1303 } 1304 // We may have cleared out the selection model. Only reset it if it 1305 // contains something. 1306 if (!selection_model.empty()) 1307 attached_model->SetSelectionFromModel(selection_model); 1308 } 1309 } else if (!detach_into_browser_) { 1310 HideFrame(); 1311 } 1312 1313 // Create the dragged view. 1314 if (!detach_into_browser_) 1315 CreateDraggedView(tab_data, drag_bounds); 1316 1317 attached_tabstrip_->DraggedTabsDetached(); 1318 attached_tabstrip_ = NULL; 1319} 1320 1321void TabDragController::DetachIntoNewBrowserAndRunMoveLoop( 1322 const gfx::Point& point_in_screen) { 1323 if (GetModel(attached_tabstrip_)->count() == 1324 static_cast<int>(drag_data_.size())) { 1325 // All the tabs in a browser are being dragged but all the tabs weren't 1326 // initially being dragged. For this to happen the user would have to 1327 // start dragging a set of tabs, the other tabs close, then detach. 1328 RunMoveLoop(GetWindowOffset(point_in_screen)); 1329 return; 1330 } 1331 1332 // Create a new browser to house the dragged tabs and have the OS run a move 1333 // loop. 1334 gfx::Point attached_point = GetAttachedDragPoint(point_in_screen); 1335 1336 // Calculate the bounds for the tabs from the attached_tab_strip. We do this 1337 // so that the tabs don't change size when detached. 1338 std::vector<gfx::Rect> drag_bounds = 1339 CalculateBoundsForDraggedTabs(attached_point.x()); 1340 1341 // Stash the current window size and tab area width. 1342 gfx::Size source_size = 1343 attached_tabstrip_->GetWidget()->GetWindowBoundsInScreen().size(); 1344 int available_source_width = attached_tabstrip_->tab_area_width(); 1345 1346 gfx::Vector2d drag_offset; 1347 Browser* browser = CreateBrowserForDrag( 1348 attached_tabstrip_, point_in_screen, &drag_offset, &drag_bounds); 1349 Detach(DONT_RELEASE_CAPTURE); 1350 BrowserView* dragged_browser_view = 1351 BrowserView::GetBrowserViewForBrowser(browser); 1352 dragged_browser_view->GetWidget()->SetVisibilityChangedAnimationsEnabled( 1353 false); 1354 Attach(dragged_browser_view->tabstrip(), gfx::Point()); 1355 1356 // If the window size has changed, the tab positioning will be quite off. 1357 if (source_size != 1358 attached_tabstrip_->GetWidget()->GetWindowBoundsInScreen().size()) { 1359 // First, scale the drag bounds such that they fit within the new window 1360 // while maintaining the same relative positions. This scales the tabs 1361 // down so that they occupy the same relative width on the new tab strip, 1362 // clamping to minimum tab width. 1363 int available_attached_width = attached_tabstrip_->tab_area_width(); 1364 float x_scale = 1365 static_cast<float>(available_attached_width) / available_source_width; 1366 int x_offset = std::ceil((1.0 - x_scale) * drag_bounds[0].x()); 1367 int accumulated_width_offset = 0; 1368 for (size_t i = 0; i < drag_bounds.size(); ++i) { 1369 gfx::Rect& tab_bounds = drag_bounds[i]; 1370 tab_bounds.Offset(-(x_offset + accumulated_width_offset), 0); 1371 int old_width = tab_bounds.width(); 1372 int min_width = (i == source_tab_index_) ? 1373 drag_data_[i].attached_tab->GetMinimumSelectedSize().width() : 1374 drag_data_[i].attached_tab->GetMinimumUnselectedSize().width(); 1375 int new_width = 1376 std::max(min_width, static_cast<int>(std::ceil(old_width * x_scale))); 1377 tab_bounds.set_width(new_width); 1378 accumulated_width_offset += (old_width - tab_bounds.width()); 1379 } 1380 1381 // Next, re-position the restored window such that the tab that was dragged 1382 // remains centered under the mouse cursor. The two offsets needed here are 1383 // the offset of the dragged tab in widget coordinates, and half the dragged 1384 // tab width. The sum of these is the horizontal distance from the mouse 1385 // cursor to the window edge. 1386 gfx::Point offset(drag_bounds[source_tab_index_].origin()); 1387 views::View::ConvertPointToWidget(attached_tabstrip_, &offset); 1388 int half_tab_width = drag_bounds[source_tab_index_].width() / 2; 1389 gfx::Rect new_bounds = browser->window()->GetBounds(); 1390 new_bounds.set_x(point_in_screen.x() - offset.x() - half_tab_width); 1391 1392 // To account for the extra vertical on restored windows that is absent 1393 // on maximized windows, add an additional vertical offset extracted from 1394 // the tab strip. 1395 new_bounds.Offset(0, -attached_tabstrip_->button_v_offset()); 1396 browser->window()->SetBounds(new_bounds); 1397 } 1398 1399 attached_tabstrip_->SetTabBoundsForDrag(drag_bounds); 1400 1401 WindowPositionManagedUpdater updater; 1402 dragged_browser_view->GetWidget()->AddObserver(&updater); 1403 browser->window()->Show(); 1404 dragged_browser_view->GetWidget()->RemoveObserver(&updater); 1405 1406 browser->window()->Activate(); 1407 dragged_browser_view->GetWidget()->SetVisibilityChangedAnimationsEnabled( 1408 true); 1409 RunMoveLoop(drag_offset); 1410} 1411 1412void TabDragController::RunMoveLoop(const gfx::Vector2d& drag_offset) { 1413 // If the user drags the whole window we'll assume they are going to attach to 1414 // another window and therefore want to reorder. 1415 move_behavior_ = REORDER; 1416 1417 move_loop_widget_ = GetAttachedBrowserWidget(); 1418 DCHECK(move_loop_widget_); 1419 SetTrackedByWorkspace(move_loop_widget_->GetNativeView(), false); 1420 move_loop_widget_->AddObserver(this); 1421 is_dragging_window_ = true; 1422 bool destroyed = false; 1423 destroyed_ = &destroyed; 1424 // Running the move loop releases mouse capture on non-ash, which triggers 1425 // destroying the drag loop. Release mouse capture ourself before this while 1426 // the DragController isn't owned by the TabStrip. 1427 if (host_desktop_type_ != chrome::HOST_DESKTOP_TYPE_ASH) { 1428 attached_tabstrip_->ReleaseDragController(); 1429 attached_tabstrip_->GetWidget()->ReleaseCapture(); 1430 attached_tabstrip_->OwnDragController(this); 1431 } 1432 const views::Widget::MoveLoopSource move_loop_source = 1433 event_source_ == EVENT_SOURCE_MOUSE ? 1434 views::Widget::MOVE_LOOP_SOURCE_MOUSE : 1435 views::Widget::MOVE_LOOP_SOURCE_TOUCH; 1436 views::Widget::MoveLoopResult result = 1437 move_loop_widget_->RunMoveLoop(drag_offset, move_loop_source); 1438 content::NotificationService::current()->Notify( 1439 chrome::NOTIFICATION_TAB_DRAG_LOOP_DONE, 1440 content::NotificationService::AllBrowserContextsAndSources(), 1441 content::NotificationService::NoDetails()); 1442 1443 if (destroyed) 1444 return; 1445 destroyed_ = NULL; 1446 // Under chromeos we immediately set the |move_loop_widget_| to NULL. 1447 if (move_loop_widget_) { 1448 move_loop_widget_->RemoveObserver(this); 1449 move_loop_widget_ = NULL; 1450 } 1451 is_dragging_window_ = false; 1452 waiting_for_run_loop_to_exit_ = false; 1453 if (end_run_loop_behavior_ == END_RUN_LOOP_CONTINUE_DRAGGING) { 1454 end_run_loop_behavior_ = END_RUN_LOOP_STOP_DRAGGING; 1455 if (tab_strip_to_attach_to_after_exit_) { 1456 gfx::Point point_in_screen(GetCursorScreenPoint()); 1457 Detach(DONT_RELEASE_CAPTURE); 1458 Attach(tab_strip_to_attach_to_after_exit_, point_in_screen); 1459 // Move the tabs into position. 1460 MoveAttached(point_in_screen); 1461 attached_tabstrip_->GetWidget()->Activate(); 1462 tab_strip_to_attach_to_after_exit_ = NULL; 1463 } 1464 DCHECK(attached_tabstrip_); 1465 attached_tabstrip_->GetWidget()->SetCapture(attached_tabstrip_); 1466 } else if (active_) { 1467 EndDrag(result == views::Widget::MOVE_LOOP_CANCELED ? 1468 END_DRAG_CANCEL : END_DRAG_COMPLETE); 1469 } 1470} 1471 1472int TabDragController::GetInsertionIndexFrom(const gfx::Rect& dragged_bounds, 1473 int start, 1474 int delta) const { 1475 for (int i = start, tab_count = attached_tabstrip_->tab_count(); 1476 i >= 0 && i < tab_count; i += delta) { 1477 const gfx::Rect& ideal_bounds = attached_tabstrip_->ideal_bounds(i); 1478 gfx::Rect left_half, right_half; 1479 ideal_bounds.SplitVertically(&left_half, &right_half); 1480 if (dragged_bounds.x() >= right_half.x() && 1481 dragged_bounds.x() < right_half.right()) { 1482 return i + 1; 1483 } else if (dragged_bounds.x() >= left_half.x() && 1484 dragged_bounds.x() < left_half.right()) { 1485 return i; 1486 } 1487 } 1488 return -1; 1489} 1490 1491int TabDragController::GetInsertionIndexForDraggedBounds( 1492 const gfx::Rect& dragged_bounds) const { 1493 int index = -1; 1494 if (attached_tabstrip_->touch_layout_.get()) { 1495 index = GetInsertionIndexForDraggedBoundsStacked(dragged_bounds); 1496 if (index != -1) { 1497 // Only move the tab to the left/right if the user actually moved the 1498 // mouse that way. This is necessary as tabs with stacked tabs 1499 // before/after them have multiple drag positions. 1500 int active_index = attached_tabstrip_->touch_layout_->active_index(); 1501 if ((index < active_index && 1502 (mouse_move_direction_ & kMovedMouseLeft) == 0) || 1503 (index > active_index && 1504 (mouse_move_direction_ & kMovedMouseRight) == 0)) { 1505 index = active_index; 1506 } 1507 } 1508 } else { 1509 index = GetInsertionIndexFrom(dragged_bounds, 0, 1); 1510 } 1511 if (index == -1) { 1512 int tab_count = attached_tabstrip_->tab_count(); 1513 int right_tab_x = tab_count == 0 ? 0 : 1514 attached_tabstrip_->ideal_bounds(tab_count - 1).right(); 1515 if (dragged_bounds.right() > right_tab_x) { 1516 index = GetModel(attached_tabstrip_)->count(); 1517 } else { 1518 index = 0; 1519 } 1520 } 1521 1522 if (!drag_data_[0].attached_tab) { 1523 // If 'attached_tab' is NULL, it means we're in the process of attaching and 1524 // don't need to constrain the index. 1525 return index; 1526 } 1527 1528 int max_index = GetModel(attached_tabstrip_)->count() - 1529 static_cast<int>(drag_data_.size()); 1530 return std::max(0, std::min(max_index, index)); 1531} 1532 1533bool TabDragController::ShouldDragToNextStackedTab( 1534 const gfx::Rect& dragged_bounds, 1535 int index) const { 1536 if (index + 1 >= attached_tabstrip_->tab_count() || 1537 !attached_tabstrip_->touch_layout_->IsStacked(index + 1) || 1538 (mouse_move_direction_ & kMovedMouseRight) == 0) 1539 return false; 1540 1541 int active_x = attached_tabstrip_->ideal_bounds(index).x(); 1542 int next_x = attached_tabstrip_->ideal_bounds(index + 1).x(); 1543 int mid_x = std::min(next_x - kStackedDistance, 1544 active_x + (next_x - active_x) / 4); 1545 return dragged_bounds.x() >= mid_x; 1546} 1547 1548bool TabDragController::ShouldDragToPreviousStackedTab( 1549 const gfx::Rect& dragged_bounds, 1550 int index) const { 1551 if (index - 1 < attached_tabstrip_->GetMiniTabCount() || 1552 !attached_tabstrip_->touch_layout_->IsStacked(index - 1) || 1553 (mouse_move_direction_ & kMovedMouseLeft) == 0) 1554 return false; 1555 1556 int active_x = attached_tabstrip_->ideal_bounds(index).x(); 1557 int previous_x = attached_tabstrip_->ideal_bounds(index - 1).x(); 1558 int mid_x = std::max(previous_x + kStackedDistance, 1559 active_x - (active_x - previous_x) / 4); 1560 return dragged_bounds.x() <= mid_x; 1561} 1562 1563int TabDragController::GetInsertionIndexForDraggedBoundsStacked( 1564 const gfx::Rect& dragged_bounds) const { 1565 StackedTabStripLayout* touch_layout = attached_tabstrip_->touch_layout_.get(); 1566 int active_index = touch_layout->active_index(); 1567 // Search from the active index to the front of the tabstrip. Do this as tabs 1568 // overlap each other from the active index. 1569 int index = GetInsertionIndexFrom(dragged_bounds, active_index, -1); 1570 if (index != active_index) 1571 return index; 1572 if (index == -1) 1573 return GetInsertionIndexFrom(dragged_bounds, active_index + 1, 1); 1574 1575 // The position to drag to corresponds to the active tab. If the next/previous 1576 // tab is stacked, then shorten the distance used to determine insertion 1577 // bounds. We do this as GetInsertionIndexFrom() uses the bounds of the 1578 // tabs. When tabs are stacked the next/previous tab is on top of the tab. 1579 if (active_index + 1 < attached_tabstrip_->tab_count() && 1580 touch_layout->IsStacked(active_index + 1)) { 1581 index = GetInsertionIndexFrom(dragged_bounds, active_index + 1, 1); 1582 if (index == -1 && ShouldDragToNextStackedTab(dragged_bounds, active_index)) 1583 index = active_index + 1; 1584 else if (index == -1) 1585 index = active_index; 1586 } else if (ShouldDragToPreviousStackedTab(dragged_bounds, active_index)) { 1587 index = active_index - 1; 1588 } 1589 return index; 1590} 1591 1592gfx::Rect TabDragController::GetDraggedViewTabStripBounds( 1593 const gfx::Point& tab_strip_point) { 1594 // attached_tab is NULL when inserting into a new tabstrip. 1595 if (source_tab_drag_data()->attached_tab) { 1596 return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(), 1597 source_tab_drag_data()->attached_tab->width(), 1598 source_tab_drag_data()->attached_tab->height()); 1599 } 1600 1601 double sel_width, unselected_width; 1602 attached_tabstrip_->GetCurrentTabWidths(&sel_width, &unselected_width); 1603 return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(), 1604 static_cast<int>(sel_width), 1605 Tab::GetStandardSize().height()); 1606} 1607 1608gfx::Point TabDragController::GetAttachedDragPoint( 1609 const gfx::Point& point_in_screen) { 1610 DCHECK(attached_tabstrip_); // The tab must be attached. 1611 1612 gfx::Point tab_loc(point_in_screen); 1613 views::View::ConvertPointToTarget(NULL, attached_tabstrip_, &tab_loc); 1614 int x = 1615 attached_tabstrip_->GetMirroredXInView(tab_loc.x()) - mouse_offset_.x(); 1616 1617 // TODO: consider caching this. 1618 std::vector<Tab*> attached_tabs; 1619 for (size_t i = 0; i < drag_data_.size(); ++i) 1620 attached_tabs.push_back(drag_data_[i].attached_tab); 1621 int size = attached_tabstrip_->GetSizeNeededForTabs(attached_tabs); 1622 int max_x = attached_tabstrip_->width() - size; 1623 return gfx::Point(std::min(std::max(x, 0), max_x), 0); 1624} 1625 1626std::vector<Tab*> TabDragController::GetTabsMatchingDraggedContents( 1627 TabStrip* tabstrip) { 1628 TabStripModel* model = GetModel(attached_tabstrip_); 1629 std::vector<Tab*> tabs; 1630 for (size_t i = 0; i < drag_data_.size(); ++i) { 1631 int model_index = model->GetIndexOfWebContents(drag_data_[i].contents); 1632 if (model_index == TabStripModel::kNoTab) 1633 return std::vector<Tab*>(); 1634 tabs.push_back(tabstrip->tab_at(model_index)); 1635 } 1636 return tabs; 1637} 1638 1639std::vector<gfx::Rect> TabDragController::CalculateBoundsForDraggedTabs( 1640 int x_offset) { 1641 std::vector<gfx::Rect> drag_bounds; 1642 std::vector<Tab*> attached_tabs; 1643 for (size_t i = 0; i < drag_data_.size(); ++i) 1644 attached_tabs.push_back(drag_data_[i].attached_tab); 1645 attached_tabstrip_->CalculateBoundsForDraggedTabs(attached_tabs, 1646 &drag_bounds); 1647 if (x_offset != 0) { 1648 for (size_t i = 0; i < drag_bounds.size(); ++i) 1649 drag_bounds[i].set_x(drag_bounds[i].x() + x_offset); 1650 } 1651 return drag_bounds; 1652} 1653 1654void TabDragController::EndDragImpl(EndDragType type) { 1655 DCHECK(active_); 1656 active_ = false; 1657 1658 bring_to_front_timer_.Stop(); 1659 move_stacked_timer_.Stop(); 1660 1661 if (is_dragging_window_) { 1662 // SetTrackedByWorkspace() may call us back (by way of the window bounds 1663 // changing). Set |waiting_for_run_loop_to_exit_| here so that if that 1664 // happens we ignore it. 1665 waiting_for_run_loop_to_exit_ = true; 1666 1667 if (type == NORMAL || (type == TAB_DESTROYED && drag_data_.size() > 1)) { 1668 SetTrackedByWorkspace(GetAttachedBrowserWidget()->GetNativeView(), true); 1669 SetWindowPositionManaged(GetAttachedBrowserWidget()->GetNativeView(), 1670 true); 1671 } 1672 1673 // End the nested drag loop. 1674 GetAttachedBrowserWidget()->EndMoveLoop(); 1675 } 1676 1677 // Hide the current dock controllers. 1678 for (size_t i = 0; i < dock_controllers_.size(); ++i) { 1679 // Be sure and clear the controller first, that way if Hide ends up 1680 // deleting the controller it won't call us back. 1681 dock_controllers_[i]->clear_controller(); 1682 dock_controllers_[i]->Hide(); 1683 } 1684 dock_controllers_.clear(); 1685 dock_windows_.clear(); 1686 1687 if (type != TAB_DESTROYED) { 1688 // We only finish up the drag if we were actually dragging. If start_drag_ 1689 // is false, the user just clicked and released and didn't move the mouse 1690 // enough to trigger a drag. 1691 if (started_drag_) { 1692 RestoreFocus(); 1693 if (type == CANCELED) 1694 RevertDrag(); 1695 else 1696 CompleteDrag(); 1697 } 1698 } else if (drag_data_.size() > 1) { 1699 RevertDrag(); 1700 } // else case the only tab we were dragging was deleted. Nothing to do. 1701 1702 if (!detach_into_browser_) 1703 ResetDelegates(); 1704 1705 // Clear out drag data so we don't attempt to do anything with it. 1706 drag_data_.clear(); 1707 1708 TabStrip* owning_tabstrip = (attached_tabstrip_ && detach_into_browser_) ? 1709 attached_tabstrip_ : source_tabstrip_; 1710 owning_tabstrip->DestroyDragController(); 1711} 1712 1713void TabDragController::RevertDrag() { 1714 std::vector<Tab*> tabs; 1715 for (size_t i = 0; i < drag_data_.size(); ++i) { 1716 if (drag_data_[i].contents) { 1717 // Contents is NULL if a tab was destroyed while the drag was under way. 1718 tabs.push_back(drag_data_[i].attached_tab); 1719 RevertDragAt(i); 1720 } 1721 } 1722 1723 bool restore_frame = !detach_into_browser_ && 1724 attached_tabstrip_ != source_tabstrip_; 1725 if (attached_tabstrip_) { 1726 if (attached_tabstrip_ == source_tabstrip_) { 1727 source_tabstrip_->StoppedDraggingTabs( 1728 tabs, initial_tab_positions_, move_behavior_ == MOVE_VISIBILE_TABS, 1729 false); 1730 } else { 1731 attached_tabstrip_->DraggedTabsDetached(); 1732 } 1733 } 1734 1735 if (initial_selection_model_.empty()) 1736 ResetSelection(GetModel(source_tabstrip_)); 1737 else 1738 GetModel(source_tabstrip_)->SetSelectionFromModel(initial_selection_model_); 1739 1740 // If we're not attached to any TabStrip, or attached to some other TabStrip, 1741 // we need to restore the bounds of the original TabStrip's frame, in case 1742 // it has been hidden. 1743 if (restore_frame && !restore_bounds_.IsEmpty()) 1744 source_tabstrip_->GetWidget()->SetBounds(restore_bounds_); 1745 1746 if (detach_into_browser_ && source_tabstrip_) 1747 source_tabstrip_->GetWidget()->Activate(); 1748 1749 // Return the WebContents to normalcy. If the tab was attached to a 1750 // TabStrip before the revert, the decrement has already occurred. 1751 // If the tab was destroyed, don't attempt to dereference the 1752 // WebContents pointer. 1753 if (!detach_into_browser_ && !attached_tabstrip_ && source_dragged_contents()) 1754 source_dragged_contents()->DecrementCapturerCount(); 1755} 1756 1757void TabDragController::ResetSelection(TabStripModel* model) { 1758 DCHECK(model); 1759 ui::ListSelectionModel selection_model; 1760 bool has_one_valid_tab = false; 1761 for (size_t i = 0; i < drag_data_.size(); ++i) { 1762 // |contents| is NULL if a tab was deleted out from under us. 1763 if (drag_data_[i].contents) { 1764 int index = model->GetIndexOfWebContents(drag_data_[i].contents); 1765 DCHECK_NE(-1, index); 1766 selection_model.AddIndexToSelection(index); 1767 if (!has_one_valid_tab || i == source_tab_index_) { 1768 // Reset the active/lead to the first tab. If the source tab is still 1769 // valid we'll reset these again later on. 1770 selection_model.set_active(index); 1771 selection_model.set_anchor(index); 1772 has_one_valid_tab = true; 1773 } 1774 } 1775 } 1776 if (!has_one_valid_tab) 1777 return; 1778 1779 model->SetSelectionFromModel(selection_model); 1780} 1781 1782void TabDragController::RevertDragAt(size_t drag_index) { 1783 DCHECK(started_drag_); 1784 DCHECK(source_tabstrip_); 1785 1786 base::AutoReset<bool> setter(&is_mutating_, true); 1787 TabDragData* data = &(drag_data_[drag_index]); 1788 if (attached_tabstrip_) { 1789 int index = 1790 GetModel(attached_tabstrip_)->GetIndexOfWebContents(data->contents); 1791 if (attached_tabstrip_ != source_tabstrip_) { 1792 // The Tab was inserted into another TabStrip. We need to put it back 1793 // into the original one. 1794 GetModel(attached_tabstrip_)->DetachWebContentsAt(index); 1795 // TODO(beng): (Cleanup) seems like we should use Attach() for this 1796 // somehow. 1797 GetModel(source_tabstrip_)->InsertWebContentsAt( 1798 data->source_model_index, data->contents, 1799 (data->pinned ? TabStripModel::ADD_PINNED : 0)); 1800 } else { 1801 // The Tab was moved within the TabStrip where the drag was initiated. 1802 // Move it back to the starting location. 1803 GetModel(source_tabstrip_)->MoveWebContentsAt( 1804 index, data->source_model_index, false); 1805 } 1806 } else { 1807 // The Tab was detached from the TabStrip where the drag began, and has not 1808 // been attached to any other TabStrip. We need to put it back into the 1809 // source TabStrip. 1810 GetModel(source_tabstrip_)->InsertWebContentsAt( 1811 data->source_model_index, data->contents, 1812 (data->pinned ? TabStripModel::ADD_PINNED : 0)); 1813 } 1814} 1815 1816void TabDragController::CompleteDrag() { 1817 DCHECK(started_drag_); 1818 1819 if (attached_tabstrip_) { 1820 attached_tabstrip_->StoppedDraggingTabs( 1821 GetTabsMatchingDraggedContents(attached_tabstrip_), 1822 initial_tab_positions_, 1823 move_behavior_ == MOVE_VISIBILE_TABS, 1824 true); 1825 } else { 1826 if (dock_info_.type() != DockInfo::NONE) { 1827 switch (dock_info_.type()) { 1828 case DockInfo::LEFT_OF_WINDOW: 1829 content::RecordAction(UserMetricsAction("DockingWindow_Left")); 1830 break; 1831 1832 case DockInfo::RIGHT_OF_WINDOW: 1833 content::RecordAction(UserMetricsAction("DockingWindow_Right")); 1834 break; 1835 1836 case DockInfo::BOTTOM_OF_WINDOW: 1837 content::RecordAction(UserMetricsAction("DockingWindow_Bottom")); 1838 break; 1839 1840 case DockInfo::TOP_OF_WINDOW: 1841 content::RecordAction(UserMetricsAction("DockingWindow_Top")); 1842 break; 1843 1844 case DockInfo::MAXIMIZE: 1845 content::RecordAction( 1846 UserMetricsAction("DockingWindow_Maximize")); 1847 break; 1848 1849 case DockInfo::LEFT_HALF: 1850 content::RecordAction( 1851 UserMetricsAction("DockingWindow_LeftHalf")); 1852 break; 1853 1854 case DockInfo::RIGHT_HALF: 1855 content::RecordAction( 1856 UserMetricsAction("DockingWindow_RightHalf")); 1857 break; 1858 1859 case DockInfo::BOTTOM_HALF: 1860 content::RecordAction( 1861 UserMetricsAction("DockingWindow_BottomHalf")); 1862 break; 1863 1864 default: 1865 NOTREACHED(); 1866 break; 1867 } 1868 } 1869 // Compel the model to construct a new window for the detached 1870 // WebContentses. 1871 views::Widget* widget = source_tabstrip_->GetWidget(); 1872 gfx::Rect window_bounds(widget->GetRestoredBounds()); 1873 window_bounds.set_origin(GetWindowCreatePoint(last_point_in_screen_)); 1874 1875 // When modifying the following if statement, please make sure not to 1876 // introduce issue listed in http://crbug.com/6223 comment #11. 1877 bool rtl_ui = base::i18n::IsRTL(); 1878 bool has_dock_position = (dock_info_.type() != DockInfo::NONE); 1879 if (rtl_ui && has_dock_position) { 1880 // Mirror X axis so the docked tab is aligned using the mouse click as 1881 // the top-right corner. 1882 window_bounds.set_x(window_bounds.x() - window_bounds.width()); 1883 } 1884 base::AutoReset<bool> setter(&is_mutating_, true); 1885 1886 std::vector<TabStripModelDelegate::NewStripContents> contentses; 1887 for (size_t i = 0; i < drag_data_.size(); ++i) { 1888 TabStripModelDelegate::NewStripContents item; 1889 item.web_contents = drag_data_[i].contents; 1890 item.add_types = drag_data_[i].pinned ? TabStripModel::ADD_PINNED 1891 : TabStripModel::ADD_NONE; 1892 contentses.push_back(item); 1893 }; 1894 1895 Browser* new_browser = 1896 GetModel(source_tabstrip_)->delegate()->CreateNewStripWithContents( 1897 contentses, window_bounds, dock_info_, widget->IsMaximized()); 1898 ResetSelection(new_browser->tab_strip_model()); 1899 new_browser->window()->Show(); 1900 1901 // Return the WebContents to normalcy. 1902 if (!detach_into_browser_) 1903 source_dragged_contents()->DecrementCapturerCount(); 1904 } 1905 1906 CleanUpHiddenFrame(); 1907} 1908 1909void TabDragController::ResetDelegates() { 1910 DCHECK(!detach_into_browser_); 1911 for (size_t i = 0; i < drag_data_.size(); ++i) { 1912 if (drag_data_[i].contents && 1913 drag_data_[i].contents->GetDelegate() == this) { 1914 drag_data_[i].contents->SetDelegate( 1915 drag_data_[i].original_delegate); 1916 } 1917 } 1918} 1919 1920void TabDragController::CreateDraggedView( 1921 const std::vector<TabRendererData>& data, 1922 const std::vector<gfx::Rect>& renderer_bounds) { 1923#if !defined(USE_AURA) 1924 DCHECK(!view_.get()); 1925 DCHECK_EQ(data.size(), drag_data_.size()); 1926 1927 // Set up the photo booth to start capturing the contents of the dragged 1928 // WebContents. 1929 NativeViewPhotobooth* photobooth = NativeViewPhotobooth::Create( 1930 source_dragged_contents()->GetView()->GetNativeView()); 1931 1932 gfx::Rect content_bounds; 1933 source_dragged_contents()->GetView()->GetContainerBounds(&content_bounds); 1934 1935 std::vector<views::View*> renderers; 1936 for (size_t i = 0; i < drag_data_.size(); ++i) { 1937 Tab* renderer = source_tabstrip_->CreateTabForDragging(); 1938 renderer->SetData(data[i]); 1939 renderers.push_back(renderer); 1940 } 1941 // DraggedTabView takes ownership of the renderers. 1942 view_.reset(new DraggedTabView(renderers, renderer_bounds, mouse_offset_, 1943 content_bounds.size(), photobooth)); 1944#else 1945 // Aura always hits the |detach_into_browser_| path. 1946 NOTREACHED(); 1947#endif 1948} 1949 1950gfx::Rect TabDragController::GetViewScreenBounds( 1951 views::View* view) const { 1952 gfx::Point view_topleft; 1953 views::View::ConvertPointToScreen(view, &view_topleft); 1954 gfx::Rect view_screen_bounds = view->GetLocalBounds(); 1955 view_screen_bounds.Offset(view_topleft.x(), view_topleft.y()); 1956 return view_screen_bounds; 1957} 1958 1959void TabDragController::HideFrame() { 1960#if defined(OS_WIN) && !defined(USE_AURA) 1961 // We don't actually hide the window, rather we just move it way off-screen. 1962 // If we actually hide it, we stop receiving drag events. 1963 // 1964 // Windows coordinates are 16 bit values. Additionally mouse events are 1965 // relative, this means if we move this window to the max position it is easy 1966 // to trigger overflow. To avoid this we don't move to the max position, 1967 // rather some where reasonably large. This should avoid common overflow 1968 // problems. 1969 // An alternative approach is to query the mouse pointer and ignore the 1970 // location on the mouse (early versions did this). This proves problematic as 1971 // if we happen to get behind in event processing it is all to easy to process 1972 // a release in the wrong location, triggering either an unexpected move or an 1973 // unexpected detach. 1974 HWND frame_hwnd = source_tabstrip_->GetWidget()->GetNativeView(); 1975 RECT wr; 1976 GetWindowRect(frame_hwnd, &wr); 1977 MoveWindow(frame_hwnd, 0x3FFF, 0x3FFF, wr.right - wr.left, 1978 wr.bottom - wr.top, TRUE); 1979 1980 // We also save the bounds of the window prior to it being moved, so that if 1981 // the drag session is aborted we can restore them. 1982 restore_bounds_ = gfx::Rect(wr); 1983#else 1984 // Shouldn't hit as aura triggers the |detach_into_browser_| path. 1985 NOTREACHED(); 1986#endif 1987} 1988 1989void TabDragController::CleanUpHiddenFrame() { 1990 // If the model we started dragging from is now empty, we must ask the 1991 // delegate to close the frame. 1992 if (!detach_into_browser_ && GetModel(source_tabstrip_)->empty()) 1993 GetModel(source_tabstrip_)->delegate()->CloseFrameAfterDragSession(); 1994} 1995 1996void TabDragController::DockDisplayerDestroyed( 1997 DockDisplayer* controller) { 1998 DockWindows::iterator dock_i = 1999 dock_windows_.find(controller->popup_view()); 2000 if (dock_i != dock_windows_.end()) 2001 dock_windows_.erase(dock_i); 2002 else 2003 NOTREACHED(); 2004 2005 std::vector<DockDisplayer*>::iterator i = 2006 std::find(dock_controllers_.begin(), dock_controllers_.end(), 2007 controller); 2008 if (i != dock_controllers_.end()) 2009 dock_controllers_.erase(i); 2010 else 2011 NOTREACHED(); 2012} 2013 2014void TabDragController::BringWindowUnderPointToFront( 2015 const gfx::Point& point_in_screen) { 2016 // If we're going to dock to another window, bring it to the front. 2017 gfx::NativeWindow window = dock_info_.window(); 2018 if (!window) { 2019 views::View* dragged_view; 2020 if (view_.get()) 2021 dragged_view = view_.get(); 2022 else 2023 dragged_view = attached_tabstrip_; 2024 gfx::NativeView dragged_native_view = 2025 dragged_view->GetWidget()->GetNativeView(); 2026 dock_windows_.insert(dragged_native_view); 2027 window = DockInfo::GetLocalProcessWindowAtPoint( 2028 host_desktop_type_, 2029 point_in_screen, 2030 dock_windows_); 2031 dock_windows_.erase(dragged_native_view); 2032 // Only bring browser windows to front - only windows with a TabStrip can 2033 // be tab drag targets. 2034 if (!GetTabStripForWindow(window)) 2035 return; 2036 } 2037 if (window) { 2038 views::Widget* widget_window = views::Widget::GetWidgetForNativeView( 2039 window); 2040 if (!widget_window) 2041 return; 2042 2043#if defined(USE_ASH) 2044 // TODO(varkha): A better strategy would be for DragWindowController to 2045 // be able to observe stacking changes to the phantom drag widget's 2046 // siblings in order to keep it on top. 2047 // One way is to implement a notification that is sent to a window parent's 2048 // observers when a stacking order is changed among the children of that 2049 // same parent. Note that OnWindowStackingChanged is sent only to the 2050 // child that is the argument of one of the Window::StackChildX calls and 2051 // not to all its siblings affected by the stacking change. 2052 aura::Window* browser_window = widget_window->GetNativeView(); 2053 // Find a topmost non-popup window and stack the recipient browser window 2054 // above it in order to avoid stacking the browser window on top of the 2055 // phantom drag widget created by DragWindowController in a second display. 2056 for (aura::Window::Windows::const_reverse_iterator it = 2057 browser_window->parent()->children().rbegin(); 2058 it != browser_window->parent()->children().rend(); ++it) { 2059 // If the iteration reached the recipient browser window then it is 2060 // already topmost and it is safe to return early with no stacking change. 2061 if (*it == browser_window) 2062 return; 2063 if ((*it)->type() != aura::client::WINDOW_TYPE_POPUP) { 2064 widget_window->StackAbove(*it); 2065 break; 2066 } 2067 } 2068#else 2069 widget_window->StackAtTop(); 2070#endif 2071 2072 // The previous call made the window appear on top of the dragged window, 2073 // move the dragged window to the front. 2074 if (view_.get()) 2075 view_->GetWidget()->StackAtTop(); 2076 else if (is_dragging_window_) 2077 attached_tabstrip_->GetWidget()->StackAtTop(); 2078 } 2079} 2080 2081TabStripModel* TabDragController::GetModel( 2082 TabStrip* tabstrip) const { 2083 return static_cast<BrowserTabStripController*>(tabstrip->controller())-> 2084 model(); 2085} 2086 2087views::Widget* TabDragController::GetAttachedBrowserWidget() { 2088 return attached_tabstrip_->GetWidget(); 2089} 2090 2091bool TabDragController::AreTabsConsecutive() { 2092 for (size_t i = 1; i < drag_data_.size(); ++i) { 2093 if (drag_data_[i - 1].source_model_index + 1 != 2094 drag_data_[i].source_model_index) { 2095 return false; 2096 } 2097 } 2098 return true; 2099} 2100 2101Browser* TabDragController::CreateBrowserForDrag( 2102 TabStrip* source, 2103 const gfx::Point& point_in_screen, 2104 gfx::Vector2d* drag_offset, 2105 std::vector<gfx::Rect>* drag_bounds) { 2106 gfx::Point center(0, source->height() / 2); 2107 views::View::ConvertPointToWidget(source, ¢er); 2108 gfx::Rect new_bounds(source->GetWidget()->GetRestoredBounds()); 2109 new_bounds.set_y(point_in_screen.y() - center.y()); 2110 switch (GetDetachPosition(point_in_screen)) { 2111 case DETACH_BEFORE: 2112 new_bounds.set_x(point_in_screen.x() - center.x()); 2113 new_bounds.Offset(-mouse_offset_.x(), 0); 2114 break; 2115 case DETACH_AFTER: { 2116 gfx::Point right_edge(source->width(), 0); 2117 views::View::ConvertPointToWidget(source, &right_edge); 2118 new_bounds.set_x(point_in_screen.x() - right_edge.x()); 2119 new_bounds.Offset(drag_bounds->back().right() - mouse_offset_.x(), 0); 2120 int delta = (*drag_bounds)[0].x(); 2121 for (size_t i = 0; i < drag_bounds->size(); ++i) 2122 (*drag_bounds)[i].Offset(-delta, 0); 2123 break; 2124 } 2125 default: 2126 break; // Nothing to do for DETACH_ABOVE_OR_BELOW. 2127 } 2128 2129 *drag_offset = point_in_screen - new_bounds.origin(); 2130 2131 Profile* profile = 2132 Profile::FromBrowserContext(drag_data_[0].contents->GetBrowserContext()); 2133 Browser::CreateParams create_params(Browser::TYPE_TABBED, 2134 profile, 2135 host_desktop_type_); 2136 create_params.initial_bounds = new_bounds; 2137 Browser* browser = new Browser(create_params); 2138 SetTrackedByWorkspace(browser->window()->GetNativeWindow(), false); 2139 SetWindowPositionManaged(browser->window()->GetNativeWindow(), false); 2140 // If the window is created maximized then the bounds we supplied are ignored. 2141 // We need to reset them again so they are honored. 2142 browser->window()->SetBounds(new_bounds); 2143 2144 return browser; 2145} 2146 2147gfx::Point TabDragController::GetCursorScreenPoint() { 2148#if defined(USE_ASH) 2149 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH && 2150 event_source_ == EVENT_SOURCE_TOUCH && 2151 aura::Env::GetInstance()->is_touch_down()) { 2152 views::Widget* widget = GetAttachedBrowserWidget(); 2153 DCHECK(widget); 2154 aura::Window* widget_window = widget->GetNativeWindow(); 2155 DCHECK(widget_window->GetRootWindow()); 2156 gfx::Point touch_point; 2157 bool got_touch_point = widget_window->GetRootWindow()-> 2158 gesture_recognizer()->GetLastTouchPointForTarget(widget_window, 2159 &touch_point); 2160 DCHECK(got_touch_point); 2161 ash::wm::ConvertPointToScreen(widget_window->GetRootWindow(), &touch_point); 2162 return touch_point; 2163 } 2164#endif 2165 return screen_->GetCursorScreenPoint(); 2166} 2167 2168gfx::Vector2d TabDragController::GetWindowOffset( 2169 const gfx::Point& point_in_screen) { 2170 TabStrip* owning_tabstrip = (attached_tabstrip_ && detach_into_browser_) ? 2171 attached_tabstrip_ : source_tabstrip_; 2172 views::View* toplevel_view = owning_tabstrip->GetWidget()->GetContentsView(); 2173 2174 gfx::Point point = point_in_screen; 2175 views::View::ConvertPointFromScreen(toplevel_view, &point); 2176 return point.OffsetFromOrigin(); 2177} 2178