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