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