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/tabs/tab_strip_model.h" 6 7 #include <algorithm> 8 #include <map> 9 #include <string> 10 11 #include "base/metrics/histogram.h" 12 #include "base/stl_util.h" 13 #include "chrome/app/chrome_command_ids.h" 14 #include "chrome/browser/browser_shutdown.h" 15 #include "chrome/browser/defaults.h" 16 #include "chrome/browser/extensions/tab_helper.h" 17 #include "chrome/browser/profiles/profile.h" 18 #include "chrome/browser/ui/tab_contents/core_tab_helper.h" 19 #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h" 20 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h" 21 #include "chrome/browser/ui/tabs/tab_strip_model_order_controller.h" 22 #include "chrome/common/url_constants.h" 23 #include "components/web_modal/web_contents_modal_dialog_manager.h" 24 #include "content/public/browser/render_process_host.h" 25 #include "content/public/browser/user_metrics.h" 26 #include "content/public/browser/web_contents.h" 27 #include "content/public/browser/web_contents_observer.h" 28 #include "content/public/browser/web_contents_view.h" 29 30 using content::UserMetricsAction; 31 using content::WebContents; 32 33 namespace { 34 35 // Returns true if the specified transition is one of the types that cause the 36 // opener relationships for the tab in which the transition occurred to be 37 // forgotten. This is generally any navigation that isn't a link click (i.e. 38 // any navigation that can be considered to be the start of a new task distinct 39 // from what had previously occurred in that tab). 40 bool ShouldForgetOpenersForTransition(content::PageTransition transition) { 41 return transition == content::PAGE_TRANSITION_TYPED || 42 transition == content::PAGE_TRANSITION_AUTO_BOOKMARK || 43 transition == content::PAGE_TRANSITION_GENERATED || 44 transition == content::PAGE_TRANSITION_KEYWORD || 45 transition == content::PAGE_TRANSITION_AUTO_TOPLEVEL; 46 } 47 48 // CloseTracker is used when closing a set of WebContents. It listens for 49 // deletions of the WebContents and removes from the internal set any time one 50 // is deleted. 51 class CloseTracker { 52 public: 53 typedef std::vector<WebContents*> Contents; 54 55 explicit CloseTracker(const Contents& contents); 56 virtual ~CloseTracker(); 57 58 // Returns true if there is another WebContents in the Tracker. 59 bool HasNext() const; 60 61 // Returns the next WebContents, or NULL if there are no more. 62 WebContents* Next(); 63 64 private: 65 class DeletionObserver : public content::WebContentsObserver { 66 public: 67 DeletionObserver(CloseTracker* parent, WebContents* web_contents) 68 : WebContentsObserver(web_contents), 69 parent_(parent) { 70 } 71 72 // Expose web_contents() publicly. 73 using content::WebContentsObserver::web_contents; 74 75 private: 76 // WebContentsObserver: 77 virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE { 78 parent_->OnWebContentsDestroyed(this); 79 } 80 81 CloseTracker* parent_; 82 83 DISALLOW_COPY_AND_ASSIGN(DeletionObserver); 84 }; 85 86 void OnWebContentsDestroyed(DeletionObserver* observer); 87 88 typedef std::vector<DeletionObserver*> Observers; 89 Observers observers_; 90 91 DISALLOW_COPY_AND_ASSIGN(CloseTracker); 92 }; 93 94 CloseTracker::CloseTracker(const Contents& contents) { 95 for (size_t i = 0; i < contents.size(); ++i) 96 observers_.push_back(new DeletionObserver(this, contents[i])); 97 } 98 99 CloseTracker::~CloseTracker() { 100 DCHECK(observers_.empty()); 101 } 102 103 bool CloseTracker::HasNext() const { 104 return !observers_.empty(); 105 } 106 107 WebContents* CloseTracker::Next() { 108 if (observers_.empty()) 109 return NULL; 110 111 DeletionObserver* observer = observers_[0]; 112 WebContents* web_contents = observer->web_contents(); 113 observers_.erase(observers_.begin()); 114 delete observer; 115 return web_contents; 116 } 117 118 void CloseTracker::OnWebContentsDestroyed(DeletionObserver* observer) { 119 Observers::iterator i = 120 std::find(observers_.begin(), observers_.end(), observer); 121 if (i != observers_.end()) { 122 delete *i; 123 observers_.erase(i); 124 return; 125 } 126 NOTREACHED() << "WebContents destroyed that wasn't in the list"; 127 } 128 129 } // namespace 130 131 /////////////////////////////////////////////////////////////////////////////// 132 // WebContentsData 133 134 // An object to hold a reference to a WebContents that is in a tabstrip, as 135 // well as other various properties it has. 136 class TabStripModel::WebContentsData : public content::WebContentsObserver { 137 public: 138 WebContentsData(TabStripModel* tab_strip_model, WebContents* a_contents); 139 140 // Changes the WebContents that this WebContentsData tracks. 141 void SetWebContents(WebContents* contents); 142 WebContents* web_contents() { return contents_; } 143 144 // Create a relationship between this WebContentsData and other 145 // WebContentses. Used to identify which WebContents to select next after 146 // one is closed. 147 WebContents* group() const { return group_; } 148 void set_group(WebContents* value) { group_ = value; } 149 WebContents* opener() const { return opener_; } 150 void set_opener(WebContents* value) { opener_ = value; } 151 152 // Alters the properties of the WebContents. 153 bool reset_group_on_select() const { return reset_group_on_select_; } 154 void set_reset_group_on_select(bool value) { reset_group_on_select_ = value; } 155 bool pinned() const { return pinned_; } 156 void set_pinned(bool value) { pinned_ = value; } 157 bool blocked() const { return blocked_; } 158 void set_blocked(bool value) { blocked_ = value; } 159 bool discarded() const { return discarded_; } 160 void set_discarded(bool value) { discarded_ = value; } 161 162 private: 163 // Make sure that if someone deletes this WebContents out from under us, it 164 // is properly removed from the tab strip. 165 virtual void WebContentsDestroyed(WebContents* web_contents) OVERRIDE; 166 167 // The WebContents being tracked by this WebContentsData. The 168 // WebContentsObserver does keep a reference, but when the WebContents is 169 // deleted, the WebContentsObserver reference is NULLed and thus inaccessible. 170 WebContents* contents_; 171 172 // The TabStripModel containing this WebContents. 173 TabStripModel* tab_strip_model_; 174 175 // The group is used to model a set of tabs spawned from a single parent 176 // tab. This value is preserved for a given tab as long as the tab remains 177 // navigated to the link it was initially opened at or some navigation from 178 // that page (i.e. if the user types or visits a bookmark or some other 179 // navigation within that tab, the group relationship is lost). This 180 // property can safely be used to implement features that depend on a 181 // logical group of related tabs. 182 WebContents* group_; 183 184 // The owner models the same relationship as group, except it is more 185 // easily discarded, e.g. when the user switches to a tab not part of the 186 // same group. This property is used to determine what tab to select next 187 // when one is closed. 188 WebContents* opener_; 189 190 // True if our group should be reset the moment selection moves away from 191 // this tab. This is the case for tabs opened in the foreground at the end 192 // of the TabStrip while viewing another Tab. If these tabs are closed 193 // before selection moves elsewhere, their opener is selected. But if 194 // selection shifts to _any_ tab (including their opener), the group 195 // relationship is reset to avoid confusing close sequencing. 196 bool reset_group_on_select_; 197 198 // Is the tab pinned? 199 bool pinned_; 200 201 // Is the tab interaction blocked by a modal dialog? 202 bool blocked_; 203 204 // Has the tab data been discarded to save memory? 205 bool discarded_; 206 207 DISALLOW_COPY_AND_ASSIGN(WebContentsData); 208 }; 209 210 TabStripModel::WebContentsData::WebContentsData(TabStripModel* tab_strip_model, 211 WebContents* contents) 212 : content::WebContentsObserver(contents), 213 contents_(contents), 214 tab_strip_model_(tab_strip_model), 215 group_(NULL), 216 opener_(NULL), 217 reset_group_on_select_(false), 218 pinned_(false), 219 blocked_(false), 220 discarded_(false) { 221 } 222 223 void TabStripModel::WebContentsData::SetWebContents(WebContents* contents) { 224 contents_ = contents; 225 Observe(contents); 226 } 227 228 void TabStripModel::WebContentsData::WebContentsDestroyed( 229 WebContents* web_contents) { 230 DCHECK_EQ(contents_, web_contents); 231 232 // Note that we only detach the contents here, not close it - it's 233 // already been closed. We just want to undo our bookkeeping. 234 int index = tab_strip_model_->GetIndexOfWebContents(web_contents); 235 DCHECK_NE(TabStripModel::kNoTab, index); 236 tab_strip_model_->DetachWebContentsAt(index); 237 } 238 239 /////////////////////////////////////////////////////////////////////////////// 240 // TabStripModel, public: 241 242 TabStripModel::TabStripModel(TabStripModelDelegate* delegate, Profile* profile) 243 : delegate_(delegate), 244 profile_(profile), 245 closing_all_(false), 246 in_notify_(false) { 247 DCHECK(delegate_); 248 order_controller_.reset(new TabStripModelOrderController(this)); 249 } 250 251 TabStripModel::~TabStripModel() { 252 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 253 TabStripModelDeleted()); 254 STLDeleteElements(&contents_data_); 255 order_controller_.reset(); 256 } 257 258 void TabStripModel::AddObserver(TabStripModelObserver* observer) { 259 observers_.AddObserver(observer); 260 } 261 262 void TabStripModel::RemoveObserver(TabStripModelObserver* observer) { 263 observers_.RemoveObserver(observer); 264 } 265 266 bool TabStripModel::ContainsIndex(int index) const { 267 return index >= 0 && index < count(); 268 } 269 270 void TabStripModel::AppendWebContents(WebContents* contents, 271 bool foreground) { 272 InsertWebContentsAt(count(), contents, 273 foreground ? (ADD_INHERIT_GROUP | ADD_ACTIVE) : 274 ADD_NONE); 275 } 276 277 void TabStripModel::InsertWebContentsAt(int index, 278 WebContents* contents, 279 int add_types) { 280 delegate_->WillAddWebContents(contents); 281 282 bool active = add_types & ADD_ACTIVE; 283 // Force app tabs to be pinned. 284 extensions::TabHelper* extensions_tab_helper = 285 extensions::TabHelper::FromWebContents(contents); 286 bool pin = extensions_tab_helper->is_app() || add_types & ADD_PINNED; 287 index = ConstrainInsertionIndex(index, pin); 288 289 // In tab dragging situations, if the last tab in the window was detached 290 // then the user aborted the drag, we will have the |closing_all_| member 291 // set (see DetachWebContentsAt) which will mess with our mojo here. We need 292 // to clear this bit. 293 closing_all_ = false; 294 295 // Have to get the active contents before we monkey with the contents 296 // otherwise we run into problems when we try to change the active contents 297 // since the old contents and the new contents will be the same... 298 WebContents* active_contents = GetActiveWebContents(); 299 WebContentsData* data = new WebContentsData(this, contents); 300 data->set_pinned(pin); 301 if ((add_types & ADD_INHERIT_GROUP) && active_contents) { 302 if (active) { 303 // Forget any existing relationships, we don't want to make things too 304 // confusing by having multiple groups active at the same time. 305 ForgetAllOpeners(); 306 } 307 // Anything opened by a link we deem to have an opener. 308 data->set_group(active_contents); 309 data->set_opener(active_contents); 310 } else if ((add_types & ADD_INHERIT_OPENER) && active_contents) { 311 if (active) { 312 // Forget any existing relationships, we don't want to make things too 313 // confusing by having multiple groups active at the same time. 314 ForgetAllOpeners(); 315 } 316 data->set_opener(active_contents); 317 } 318 319 web_modal::WebContentsModalDialogManager* modal_dialog_manager = 320 web_modal::WebContentsModalDialogManager::FromWebContents(contents); 321 if (modal_dialog_manager) 322 data->set_blocked(modal_dialog_manager->IsDialogActive()); 323 324 contents_data_.insert(contents_data_.begin() + index, data); 325 326 selection_model_.IncrementFrom(index); 327 328 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 329 TabInsertedAt(contents, index, active)); 330 if (active) { 331 ui::ListSelectionModel new_model; 332 new_model.Copy(selection_model_); 333 new_model.SetSelectedIndex(index); 334 SetSelection(new_model, NOTIFY_DEFAULT); 335 } 336 } 337 338 WebContents* TabStripModel::ReplaceWebContentsAt(int index, 339 WebContents* new_contents) { 340 delegate_->WillAddWebContents(new_contents); 341 342 DCHECK(ContainsIndex(index)); 343 WebContents* old_contents = GetWebContentsAtImpl(index); 344 345 ForgetOpenersAndGroupsReferencing(old_contents); 346 347 contents_data_[index]->SetWebContents(new_contents); 348 349 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 350 TabReplacedAt(this, old_contents, new_contents, index)); 351 352 // When the active WebContents is replaced send out a selection notification 353 // too. We do this as nearly all observers need to treat a replacement of the 354 // selected contents as the selection changing. 355 if (active_index() == index) { 356 FOR_EACH_OBSERVER( 357 TabStripModelObserver, 358 observers_, 359 ActiveTabChanged(old_contents, 360 new_contents, 361 active_index(), 362 TabStripModelObserver::CHANGE_REASON_REPLACED)); 363 } 364 return old_contents; 365 } 366 367 WebContents* TabStripModel::DiscardWebContentsAt(int index) { 368 DCHECK(ContainsIndex(index)); 369 // Do not discard active tab. 370 if (active_index() == index) 371 return NULL; 372 373 WebContents* null_contents = 374 WebContents::Create(WebContents::CreateParams(profile())); 375 WebContents* old_contents = GetWebContentsAtImpl(index); 376 // Copy over the state from the navigation controller so we preserve the 377 // back/forward history and continue to display the correct title/favicon. 378 null_contents->GetController().CopyStateFrom(old_contents->GetController()); 379 // Replace the tab we're discarding with the null version. 380 ReplaceWebContentsAt(index, null_contents); 381 // Mark the tab so it will reload when we click. 382 contents_data_[index]->set_discarded(true); 383 // Discard the old tab's renderer. 384 // TODO(jamescook): This breaks script connections with other tabs. 385 // We need to find a different approach that doesn't do that, perhaps based 386 // on navigation to swappedout://. 387 delete old_contents; 388 return null_contents; 389 } 390 391 WebContents* TabStripModel::DetachWebContentsAt(int index) { 392 CHECK(!in_notify_); 393 if (contents_data_.empty()) 394 return NULL; 395 396 DCHECK(ContainsIndex(index)); 397 398 WebContents* removed_contents = GetWebContentsAtImpl(index); 399 bool was_selected = IsTabSelected(index); 400 int next_selected_index = order_controller_->DetermineNewSelectedIndex(index); 401 delete contents_data_[index]; 402 contents_data_.erase(contents_data_.begin() + index); 403 ForgetOpenersAndGroupsReferencing(removed_contents); 404 if (empty()) 405 closing_all_ = true; 406 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 407 TabDetachedAt(removed_contents, index)); 408 if (empty()) { 409 selection_model_.Clear(); 410 // TabDetachedAt() might unregister observers, so send |TabStripEmpty()| in 411 // a second pass. 412 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty()); 413 } else { 414 int old_active = active_index(); 415 selection_model_.DecrementFrom(index); 416 ui::ListSelectionModel old_model; 417 old_model.Copy(selection_model_); 418 if (index == old_active) { 419 NotifyIfTabDeactivated(removed_contents); 420 if (!selection_model_.empty()) { 421 // The active tab was removed, but there is still something selected. 422 // Move the active and anchor to the first selected index. 423 selection_model_.set_active(selection_model_.selected_indices()[0]); 424 selection_model_.set_anchor(selection_model_.active()); 425 } else { 426 // The active tab was removed and nothing is selected. Reset the 427 // selection and send out notification. 428 selection_model_.SetSelectedIndex(next_selected_index); 429 } 430 NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT); 431 } 432 433 // Sending notification in case the detached tab was selected. Using 434 // NotifyIfActiveOrSelectionChanged() here would not guarantee that a 435 // notification is sent even though the tab selection has changed because 436 // |old_model| is stored after calling DecrementFrom(). 437 if (was_selected) { 438 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 439 TabSelectionChanged(this, old_model)); 440 } 441 } 442 return removed_contents; 443 } 444 445 void TabStripModel::ActivateTabAt(int index, bool user_gesture) { 446 DCHECK(ContainsIndex(index)); 447 ui::ListSelectionModel new_model; 448 new_model.Copy(selection_model_); 449 new_model.SetSelectedIndex(index); 450 SetSelection(new_model, user_gesture ? NOTIFY_USER_GESTURE : NOTIFY_DEFAULT); 451 } 452 453 void TabStripModel::AddTabAtToSelection(int index) { 454 DCHECK(ContainsIndex(index)); 455 ui::ListSelectionModel new_model; 456 new_model.Copy(selection_model_); 457 new_model.AddIndexToSelection(index); 458 SetSelection(new_model, NOTIFY_DEFAULT); 459 } 460 461 void TabStripModel::MoveWebContentsAt(int index, 462 int to_position, 463 bool select_after_move) { 464 DCHECK(ContainsIndex(index)); 465 if (index == to_position) 466 return; 467 468 int first_non_mini_tab = IndexOfFirstNonMiniTab(); 469 if ((index < first_non_mini_tab && to_position >= first_non_mini_tab) || 470 (to_position < first_non_mini_tab && index >= first_non_mini_tab)) { 471 // This would result in mini tabs mixed with non-mini tabs. We don't allow 472 // that. 473 return; 474 } 475 476 MoveWebContentsAtImpl(index, to_position, select_after_move); 477 } 478 479 void TabStripModel::MoveSelectedTabsTo(int index) { 480 int total_mini_count = IndexOfFirstNonMiniTab(); 481 int selected_mini_count = 0; 482 int selected_count = 483 static_cast<int>(selection_model_.selected_indices().size()); 484 for (int i = 0; i < selected_count && 485 IsMiniTab(selection_model_.selected_indices()[i]); ++i) { 486 selected_mini_count++; 487 } 488 489 // To maintain that all mini-tabs occur before non-mini-tabs we move them 490 // first. 491 if (selected_mini_count > 0) { 492 MoveSelectedTabsToImpl( 493 std::min(total_mini_count - selected_mini_count, index), 0u, 494 selected_mini_count); 495 if (index > total_mini_count - selected_mini_count) { 496 // We're being told to drag mini-tabs to an invalid location. Adjust the 497 // index such that non-mini-tabs end up at a location as though we could 498 // move the mini-tabs to index. See description in header for more 499 // details. 500 index += selected_mini_count; 501 } 502 } 503 if (selected_mini_count == selected_count) 504 return; 505 506 // Then move the non-pinned tabs. 507 MoveSelectedTabsToImpl(std::max(index, total_mini_count), 508 selected_mini_count, 509 selected_count - selected_mini_count); 510 } 511 512 WebContents* TabStripModel::GetActiveWebContents() const { 513 return GetWebContentsAt(active_index()); 514 } 515 516 WebContents* TabStripModel::GetWebContentsAt(int index) const { 517 if (ContainsIndex(index)) 518 return GetWebContentsAtImpl(index); 519 return NULL; 520 } 521 522 int TabStripModel::GetIndexOfWebContents(const WebContents* contents) const { 523 for (size_t i = 0; i < contents_data_.size(); ++i) { 524 if (contents_data_[i]->web_contents() == contents) 525 return i; 526 } 527 return kNoTab; 528 } 529 530 void TabStripModel::UpdateWebContentsStateAt(int index, 531 TabStripModelObserver::TabChangeType change_type) { 532 DCHECK(ContainsIndex(index)); 533 534 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 535 TabChangedAt(GetWebContentsAtImpl(index), index, change_type)); 536 } 537 538 void TabStripModel::CloseAllTabs() { 539 // Set state so that observers can adjust their behavior to suit this 540 // specific condition when CloseWebContentsAt causes a flurry of 541 // Close/Detach/Select notifications to be sent. 542 closing_all_ = true; 543 std::vector<int> closing_tabs; 544 for (int i = count() - 1; i >= 0; --i) 545 closing_tabs.push_back(i); 546 InternalCloseTabs(closing_tabs, CLOSE_CREATE_HISTORICAL_TAB); 547 } 548 549 bool TabStripModel::CloseWebContentsAt(int index, uint32 close_types) { 550 DCHECK(ContainsIndex(index)); 551 std::vector<int> closing_tabs; 552 closing_tabs.push_back(index); 553 return InternalCloseTabs(closing_tabs, close_types); 554 } 555 556 bool TabStripModel::TabsAreLoading() const { 557 for (WebContentsDataVector::const_iterator iter = contents_data_.begin(); 558 iter != contents_data_.end(); ++iter) { 559 if ((*iter)->web_contents()->IsLoading()) 560 return true; 561 } 562 return false; 563 } 564 565 WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) { 566 DCHECK(ContainsIndex(index)); 567 return contents_data_[index]->opener(); 568 } 569 570 void TabStripModel::SetOpenerOfWebContentsAt(int index, 571 WebContents* opener) { 572 DCHECK(ContainsIndex(index)); 573 DCHECK(opener); 574 contents_data_[index]->set_opener(opener); 575 } 576 577 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener, 578 int start_index, 579 bool use_group) const { 580 DCHECK(opener); 581 DCHECK(ContainsIndex(start_index)); 582 583 // Check tabs after start_index first. 584 for (int i = start_index + 1; i < count(); ++i) { 585 if (OpenerMatches(contents_data_[i], opener, use_group)) 586 return i; 587 } 588 // Then check tabs before start_index, iterating backwards. 589 for (int i = start_index - 1; i >= 0; --i) { 590 if (OpenerMatches(contents_data_[i], opener, use_group)) 591 return i; 592 } 593 return kNoTab; 594 } 595 596 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener, 597 int start_index) const { 598 DCHECK(opener); 599 DCHECK(ContainsIndex(start_index)); 600 601 for (int i = contents_data_.size() - 1; i > start_index; --i) { 602 if (contents_data_[i]->opener() == opener) 603 return i; 604 } 605 return kNoTab; 606 } 607 608 void TabStripModel::TabNavigating(WebContents* contents, 609 content::PageTransition transition) { 610 if (ShouldForgetOpenersForTransition(transition)) { 611 // Don't forget the openers if this tab is a New Tab page opened at the 612 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one 613 // navigation of one of these transition types before resetting the 614 // opener relationships (this allows for the use case of opening a new 615 // tab to do a quick look-up of something while viewing a tab earlier in 616 // the strip). We can make this heuristic more permissive if need be. 617 if (!IsNewTabAtEndOfTabStrip(contents)) { 618 // If the user navigates the current tab to another page in any way 619 // other than by clicking a link, we want to pro-actively forget all 620 // TabStrip opener relationships since we assume they're beginning a 621 // different task by reusing the current tab. 622 ForgetAllOpeners(); 623 // In this specific case we also want to reset the group relationship, 624 // since it is now technically invalid. 625 ForgetGroup(contents); 626 } 627 } 628 } 629 630 void TabStripModel::ForgetAllOpeners() { 631 // Forget all opener memories so we don't do anything weird with tab 632 // re-selection ordering. 633 for (WebContentsDataVector::const_iterator iter = contents_data_.begin(); 634 iter != contents_data_.end(); ++iter) 635 (*iter)->set_opener(NULL); 636 } 637 638 void TabStripModel::ForgetGroup(WebContents* contents) { 639 int index = GetIndexOfWebContents(contents); 640 DCHECK(ContainsIndex(index)); 641 contents_data_[index]->set_group(NULL); 642 contents_data_[index]->set_opener(NULL); 643 } 644 645 bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const { 646 int index = GetIndexOfWebContents(contents); 647 DCHECK(ContainsIndex(index)); 648 return contents_data_[index]->reset_group_on_select(); 649 } 650 651 void TabStripModel::SetTabBlocked(int index, bool blocked) { 652 DCHECK(ContainsIndex(index)); 653 if (contents_data_[index]->blocked() == blocked) 654 return; 655 contents_data_[index]->set_blocked(blocked); 656 FOR_EACH_OBSERVER( 657 TabStripModelObserver, observers_, 658 TabBlockedStateChanged(contents_data_[index]->web_contents(), 659 index)); 660 } 661 662 void TabStripModel::SetTabPinned(int index, bool pinned) { 663 DCHECK(ContainsIndex(index)); 664 if (contents_data_[index]->pinned() == pinned) 665 return; 666 667 if (IsAppTab(index)) { 668 if (!pinned) { 669 // App tabs should always be pinned. 670 NOTREACHED(); 671 return; 672 } 673 // Changing the pinned state of an app tab doesn't affect its mini-tab 674 // status. 675 contents_data_[index]->set_pinned(pinned); 676 } else { 677 // The tab is not an app tab, its position may have to change as the 678 // mini-tab state is changing. 679 int non_mini_tab_index = IndexOfFirstNonMiniTab(); 680 contents_data_[index]->set_pinned(pinned); 681 if (pinned && index != non_mini_tab_index) { 682 MoveWebContentsAtImpl(index, non_mini_tab_index, false); 683 index = non_mini_tab_index; 684 } else if (!pinned && index + 1 != non_mini_tab_index) { 685 MoveWebContentsAtImpl(index, non_mini_tab_index - 1, false); 686 index = non_mini_tab_index - 1; 687 } 688 689 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 690 TabMiniStateChanged(contents_data_[index]->web_contents(), 691 index)); 692 } 693 694 // else: the tab was at the boundary and its position doesn't need to change. 695 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 696 TabPinnedStateChanged(contents_data_[index]->web_contents(), 697 index)); 698 } 699 700 bool TabStripModel::IsTabPinned(int index) const { 701 DCHECK(ContainsIndex(index)); 702 return contents_data_[index]->pinned(); 703 } 704 705 bool TabStripModel::IsMiniTab(int index) const { 706 return IsTabPinned(index) || IsAppTab(index); 707 } 708 709 bool TabStripModel::IsAppTab(int index) const { 710 WebContents* contents = GetWebContentsAt(index); 711 return contents && extensions::TabHelper::FromWebContents(contents)->is_app(); 712 } 713 714 bool TabStripModel::IsTabBlocked(int index) const { 715 return contents_data_[index]->blocked(); 716 } 717 718 bool TabStripModel::IsTabDiscarded(int index) const { 719 return contents_data_[index]->discarded(); 720 } 721 722 int TabStripModel::IndexOfFirstNonMiniTab() const { 723 for (size_t i = 0; i < contents_data_.size(); ++i) { 724 if (!IsMiniTab(static_cast<int>(i))) 725 return static_cast<int>(i); 726 } 727 // No mini-tabs. 728 return count(); 729 } 730 731 int TabStripModel::ConstrainInsertionIndex(int index, bool mini_tab) { 732 return mini_tab ? std::min(std::max(0, index), IndexOfFirstNonMiniTab()) : 733 std::min(count(), std::max(index, IndexOfFirstNonMiniTab())); 734 } 735 736 void TabStripModel::ExtendSelectionTo(int index) { 737 DCHECK(ContainsIndex(index)); 738 ui::ListSelectionModel new_model; 739 new_model.Copy(selection_model_); 740 new_model.SetSelectionFromAnchorTo(index); 741 SetSelection(new_model, NOTIFY_DEFAULT); 742 } 743 744 void TabStripModel::ToggleSelectionAt(int index) { 745 DCHECK(ContainsIndex(index)); 746 ui::ListSelectionModel new_model; 747 new_model.Copy(selection_model()); 748 if (selection_model_.IsSelected(index)) { 749 if (selection_model_.size() == 1) { 750 // One tab must be selected and this tab is currently selected so we can't 751 // unselect it. 752 return; 753 } 754 new_model.RemoveIndexFromSelection(index); 755 new_model.set_anchor(index); 756 if (new_model.active() == index || 757 new_model.active() == ui::ListSelectionModel::kUnselectedIndex) 758 new_model.set_active(new_model.selected_indices()[0]); 759 } else { 760 new_model.AddIndexToSelection(index); 761 new_model.set_anchor(index); 762 new_model.set_active(index); 763 } 764 SetSelection(new_model, NOTIFY_DEFAULT); 765 } 766 767 void TabStripModel::AddSelectionFromAnchorTo(int index) { 768 ui::ListSelectionModel new_model; 769 new_model.Copy(selection_model_); 770 new_model.AddSelectionFromAnchorTo(index); 771 SetSelection(new_model, NOTIFY_DEFAULT); 772 } 773 774 bool TabStripModel::IsTabSelected(int index) const { 775 DCHECK(ContainsIndex(index)); 776 return selection_model_.IsSelected(index); 777 } 778 779 void TabStripModel::SetSelectionFromModel( 780 const ui::ListSelectionModel& source) { 781 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active()); 782 SetSelection(source, NOTIFY_DEFAULT); 783 } 784 785 void TabStripModel::AddWebContents(WebContents* contents, 786 int index, 787 content::PageTransition transition, 788 int add_types) { 789 // If the newly-opened tab is part of the same task as the parent tab, we want 790 // to inherit the parent's "group" attribute, so that if this tab is then 791 // closed we'll jump back to the parent tab. 792 bool inherit_group = (add_types & ADD_INHERIT_GROUP) == ADD_INHERIT_GROUP; 793 794 if (transition == content::PAGE_TRANSITION_LINK && 795 (add_types & ADD_FORCE_INDEX) == 0) { 796 // We assume tabs opened via link clicks are part of the same task as their 797 // parent. Note that when |force_index| is true (e.g. when the user 798 // drag-and-drops a link to the tab strip), callers aren't really handling 799 // link clicks, they just want to score the navigation like a link click in 800 // the history backend, so we don't inherit the group in this case. 801 index = order_controller_->DetermineInsertionIndex(transition, 802 add_types & ADD_ACTIVE); 803 inherit_group = true; 804 } else { 805 // For all other types, respect what was passed to us, normalizing -1s and 806 // values that are too large. 807 if (index < 0 || index > count()) 808 index = count(); 809 } 810 811 if (transition == content::PAGE_TRANSITION_TYPED && index == count()) { 812 // Also, any tab opened at the end of the TabStrip with a "TYPED" 813 // transition inherit group as well. This covers the cases where the user 814 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types 815 // in the address bar and presses Alt+Enter. This allows for opening a new 816 // Tab to quickly look up something. When this Tab is closed, the old one 817 // is re-selected, not the next-adjacent. 818 inherit_group = true; 819 } 820 InsertWebContentsAt(index, contents, 821 add_types | (inherit_group ? ADD_INHERIT_GROUP : 0)); 822 // Reset the index, just in case insert ended up moving it on us. 823 index = GetIndexOfWebContents(contents); 824 825 if (inherit_group && transition == content::PAGE_TRANSITION_TYPED) 826 contents_data_[index]->set_reset_group_on_select(true); 827 828 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When 829 // here we seem to get failures in startup perf tests. 830 // Ensure that the new WebContentsView begins at the same size as the 831 // previous WebContentsView if it existed. Otherwise, the initial WebKit 832 // layout will be performed based on a width of 0 pixels, causing a 833 // very long, narrow, inaccurate layout. Because some scripts on pages (as 834 // well as WebKit's anchor link location calculation) are run on the 835 // initial layout and not recalculated later, we need to ensure the first 836 // layout is performed with sane view dimensions even when we're opening a 837 // new background tab. 838 if (WebContents* old_contents = GetActiveWebContents()) { 839 if ((add_types & ADD_ACTIVE) == 0) { 840 contents->GetView()->SizeContents( 841 old_contents->GetView()->GetContainerSize()); 842 } 843 } 844 } 845 846 void TabStripModel::CloseSelectedTabs() { 847 InternalCloseTabs(selection_model_.selected_indices(), 848 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE); 849 } 850 851 void TabStripModel::SelectNextTab() { 852 SelectRelativeTab(true); 853 } 854 855 void TabStripModel::SelectPreviousTab() { 856 SelectRelativeTab(false); 857 } 858 859 void TabStripModel::SelectLastTab() { 860 ActivateTabAt(count() - 1, true); 861 } 862 863 void TabStripModel::MoveTabNext() { 864 // TODO: this likely needs to be updated for multi-selection. 865 int new_index = std::min(active_index() + 1, count() - 1); 866 MoveWebContentsAt(active_index(), new_index, true); 867 } 868 869 void TabStripModel::MoveTabPrevious() { 870 // TODO: this likely needs to be updated for multi-selection. 871 int new_index = std::max(active_index() - 1, 0); 872 MoveWebContentsAt(active_index(), new_index, true); 873 } 874 875 // Context menu functions. 876 bool TabStripModel::IsContextMenuCommandEnabled( 877 int context_index, ContextMenuCommand command_id) const { 878 DCHECK(command_id > CommandFirst && command_id < CommandLast); 879 switch (command_id) { 880 case CommandNewTab: 881 case CommandCloseTab: 882 return true; 883 884 case CommandReload: { 885 std::vector<int> indices = GetIndicesForCommand(context_index); 886 for (size_t i = 0; i < indices.size(); ++i) { 887 WebContents* tab = GetWebContentsAt(indices[i]); 888 if (tab) { 889 CoreTabHelperDelegate* core_delegate = 890 CoreTabHelper::FromWebContents(tab)->delegate(); 891 if (!core_delegate || core_delegate->CanReloadContents(tab)) 892 return true; 893 } 894 } 895 return false; 896 } 897 898 case CommandCloseOtherTabs: 899 case CommandCloseTabsToRight: 900 return !GetIndicesClosedByCommand(context_index, command_id).empty(); 901 902 case CommandDuplicate: { 903 std::vector<int> indices = GetIndicesForCommand(context_index); 904 for (size_t i = 0; i < indices.size(); ++i) { 905 if (delegate_->CanDuplicateContentsAt(indices[i])) 906 return true; 907 } 908 return false; 909 } 910 911 case CommandRestoreTab: 912 return delegate_->GetRestoreTabType() != 913 TabStripModelDelegate::RESTORE_NONE; 914 915 case CommandTogglePinned: { 916 std::vector<int> indices = GetIndicesForCommand(context_index); 917 for (size_t i = 0; i < indices.size(); ++i) { 918 if (!IsAppTab(indices[i])) 919 return true; 920 } 921 return false; 922 } 923 924 case CommandBookmarkAllTabs: 925 return browser_defaults::bookmarks_enabled && 926 delegate_->CanBookmarkAllTabs(); 927 928 case CommandSelectByDomain: 929 case CommandSelectByOpener: 930 return true; 931 932 default: 933 NOTREACHED(); 934 } 935 return false; 936 } 937 938 void TabStripModel::ExecuteContextMenuCommand( 939 int context_index, ContextMenuCommand command_id) { 940 DCHECK(command_id > CommandFirst && command_id < CommandLast); 941 switch (command_id) { 942 case CommandNewTab: 943 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab")); 944 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab", 945 TabStripModel::NEW_TAB_CONTEXT_MENU, 946 TabStripModel::NEW_TAB_ENUM_COUNT); 947 delegate()->AddTabAt(GURL(), context_index + 1, true); 948 break; 949 950 case CommandReload: { 951 content::RecordAction(UserMetricsAction("TabContextMenu_Reload")); 952 std::vector<int> indices = GetIndicesForCommand(context_index); 953 for (size_t i = 0; i < indices.size(); ++i) { 954 WebContents* tab = GetWebContentsAt(indices[i]); 955 if (tab) { 956 CoreTabHelperDelegate* core_delegate = 957 CoreTabHelper::FromWebContents(tab)->delegate(); 958 if (!core_delegate || core_delegate->CanReloadContents(tab)) 959 tab->GetController().Reload(true); 960 } 961 } 962 break; 963 } 964 965 case CommandDuplicate: { 966 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate")); 967 std::vector<int> indices = GetIndicesForCommand(context_index); 968 // Copy the WebContents off as the indices will change as tabs are 969 // duplicated. 970 std::vector<WebContents*> tabs; 971 for (size_t i = 0; i < indices.size(); ++i) 972 tabs.push_back(GetWebContentsAt(indices[i])); 973 for (size_t i = 0; i < tabs.size(); ++i) { 974 int index = GetIndexOfWebContents(tabs[i]); 975 if (index != -1 && delegate_->CanDuplicateContentsAt(index)) 976 delegate_->DuplicateContentsAt(index); 977 } 978 break; 979 } 980 981 case CommandCloseTab: { 982 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab")); 983 InternalCloseTabs(GetIndicesForCommand(context_index), 984 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE); 985 break; 986 } 987 988 case CommandCloseOtherTabs: { 989 content::RecordAction( 990 UserMetricsAction("TabContextMenu_CloseOtherTabs")); 991 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id), 992 CLOSE_CREATE_HISTORICAL_TAB); 993 break; 994 } 995 996 case CommandCloseTabsToRight: { 997 content::RecordAction( 998 UserMetricsAction("TabContextMenu_CloseTabsToRight")); 999 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id), 1000 CLOSE_CREATE_HISTORICAL_TAB); 1001 break; 1002 } 1003 1004 case CommandRestoreTab: { 1005 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab")); 1006 delegate_->RestoreTab(); 1007 break; 1008 } 1009 1010 case CommandTogglePinned: { 1011 content::RecordAction( 1012 UserMetricsAction("TabContextMenu_TogglePinned")); 1013 std::vector<int> indices = GetIndicesForCommand(context_index); 1014 bool pin = WillContextMenuPin(context_index); 1015 if (pin) { 1016 for (size_t i = 0; i < indices.size(); ++i) { 1017 if (!IsAppTab(indices[i])) 1018 SetTabPinned(indices[i], true); 1019 } 1020 } else { 1021 // Unpin from the back so that the order is maintained (unpinning can 1022 // trigger moving a tab). 1023 for (size_t i = indices.size(); i > 0; --i) { 1024 if (!IsAppTab(indices[i - 1])) 1025 SetTabPinned(indices[i - 1], false); 1026 } 1027 } 1028 break; 1029 } 1030 1031 case CommandBookmarkAllTabs: { 1032 content::RecordAction( 1033 UserMetricsAction("TabContextMenu_BookmarkAllTabs")); 1034 1035 delegate_->BookmarkAllTabs(); 1036 break; 1037 } 1038 1039 case CommandSelectByDomain: 1040 case CommandSelectByOpener: { 1041 std::vector<int> indices; 1042 if (command_id == CommandSelectByDomain) 1043 GetIndicesWithSameDomain(context_index, &indices); 1044 else 1045 GetIndicesWithSameOpener(context_index, &indices); 1046 ui::ListSelectionModel selection_model; 1047 selection_model.SetSelectedIndex(context_index); 1048 for (size_t i = 0; i < indices.size(); ++i) 1049 selection_model.AddIndexToSelection(indices[i]); 1050 SetSelectionFromModel(selection_model); 1051 break; 1052 } 1053 1054 default: 1055 NOTREACHED(); 1056 } 1057 } 1058 1059 std::vector<int> TabStripModel::GetIndicesClosedByCommand( 1060 int index, 1061 ContextMenuCommand id) const { 1062 DCHECK(ContainsIndex(index)); 1063 DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs); 1064 bool is_selected = IsTabSelected(index); 1065 int start; 1066 if (id == CommandCloseTabsToRight) { 1067 if (is_selected) { 1068 start = selection_model_.selected_indices()[ 1069 selection_model_.selected_indices().size() - 1] + 1; 1070 } else { 1071 start = index + 1; 1072 } 1073 } else { 1074 start = 0; 1075 } 1076 // NOTE: callers expect the vector to be sorted in descending order. 1077 std::vector<int> indices; 1078 for (int i = count() - 1; i >= start; --i) { 1079 if (i != index && !IsMiniTab(i) && (!is_selected || !IsTabSelected(i))) 1080 indices.push_back(i); 1081 } 1082 return indices; 1083 } 1084 1085 bool TabStripModel::WillContextMenuPin(int index) { 1086 std::vector<int> indices = GetIndicesForCommand(index); 1087 // If all tabs are pinned, then we unpin, otherwise we pin. 1088 bool all_pinned = true; 1089 for (size_t i = 0; i < indices.size() && all_pinned; ++i) { 1090 if (!IsAppTab(index)) // We never change app tabs. 1091 all_pinned = IsTabPinned(indices[i]); 1092 } 1093 return !all_pinned; 1094 } 1095 1096 // static 1097 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id, 1098 int* browser_cmd) { 1099 switch (cmd_id) { 1100 case CommandNewTab: 1101 *browser_cmd = IDC_NEW_TAB; 1102 break; 1103 case CommandReload: 1104 *browser_cmd = IDC_RELOAD; 1105 break; 1106 case CommandDuplicate: 1107 *browser_cmd = IDC_DUPLICATE_TAB; 1108 break; 1109 case CommandCloseTab: 1110 *browser_cmd = IDC_CLOSE_TAB; 1111 break; 1112 case CommandRestoreTab: 1113 *browser_cmd = IDC_RESTORE_TAB; 1114 break; 1115 case CommandBookmarkAllTabs: 1116 *browser_cmd = IDC_BOOKMARK_ALL_TABS; 1117 break; 1118 default: 1119 *browser_cmd = 0; 1120 return false; 1121 } 1122 1123 return true; 1124 } 1125 1126 /////////////////////////////////////////////////////////////////////////////// 1127 // TabStripModel, private: 1128 1129 std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices( 1130 const std::vector<int>& indices) const { 1131 std::vector<WebContents*> contents; 1132 for (size_t i = 0; i < indices.size(); ++i) 1133 contents.push_back(GetWebContentsAtImpl(indices[i])); 1134 return contents; 1135 } 1136 1137 void TabStripModel::GetIndicesWithSameDomain(int index, 1138 std::vector<int>* indices) { 1139 std::string domain = GetWebContentsAt(index)->GetURL().host(); 1140 if (domain.empty()) 1141 return; 1142 for (int i = 0; i < count(); ++i) { 1143 if (i == index) 1144 continue; 1145 if (GetWebContentsAt(i)->GetURL().host() == domain) 1146 indices->push_back(i); 1147 } 1148 } 1149 1150 void TabStripModel::GetIndicesWithSameOpener(int index, 1151 std::vector<int>* indices) { 1152 WebContents* opener = contents_data_[index]->group(); 1153 if (!opener) { 1154 // If there is no group, find all tabs with the selected tab as the opener. 1155 opener = GetWebContentsAt(index); 1156 if (!opener) 1157 return; 1158 } 1159 for (int i = 0; i < count(); ++i) { 1160 if (i == index) 1161 continue; 1162 if (contents_data_[i]->group() == opener || 1163 GetWebContentsAtImpl(i) == opener) { 1164 indices->push_back(i); 1165 } 1166 } 1167 } 1168 1169 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const { 1170 if (!IsTabSelected(index)) { 1171 std::vector<int> indices; 1172 indices.push_back(index); 1173 return indices; 1174 } 1175 return selection_model_.selected_indices(); 1176 } 1177 1178 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const { 1179 const GURL& url = contents->GetURL(); 1180 return url.SchemeIs(chrome::kChromeUIScheme) && 1181 url.host() == chrome::kChromeUINewTabHost && 1182 contents == GetWebContentsAtImpl(count() - 1) && 1183 contents->GetController().GetEntryCount() == 1; 1184 } 1185 1186 bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices, 1187 uint32 close_types) { 1188 if (indices.empty()) 1189 return true; 1190 1191 CloseTracker close_tracker(GetWebContentsFromIndices(indices)); 1192 1193 // We only try the fast shutdown path if the whole browser process is *not* 1194 // shutting down. Fast shutdown during browser termination is handled in 1195 // BrowserShutdown. 1196 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) { 1197 // Construct a map of processes to the number of associated tabs that are 1198 // closing. 1199 std::map<content::RenderProcessHost*, size_t> processes; 1200 for (size_t i = 0; i < indices.size(); ++i) { 1201 WebContents* closing_contents = GetWebContentsAtImpl(indices[i]); 1202 if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents)) 1203 continue; 1204 content::RenderProcessHost* process = 1205 closing_contents->GetRenderProcessHost(); 1206 ++processes[process]; 1207 } 1208 1209 // Try to fast shutdown the tabs that can close. 1210 for (std::map<content::RenderProcessHost*, size_t>::iterator iter = 1211 processes.begin(); iter != processes.end(); ++iter) { 1212 iter->first->FastShutdownForPageCount(iter->second); 1213 } 1214 } 1215 1216 // We now return to our regularly scheduled shutdown procedure. 1217 bool retval = true; 1218 while (close_tracker.HasNext()) { 1219 WebContents* closing_contents = close_tracker.Next(); 1220 int index = GetIndexOfWebContents(closing_contents); 1221 // Make sure we still contain the tab. 1222 if (index == kNoTab) 1223 continue; 1224 1225 CoreTabHelper* core_tab_helper = 1226 CoreTabHelper::FromWebContents(closing_contents); 1227 core_tab_helper->OnCloseStarted(); 1228 1229 // Update the explicitly closed state. If the unload handlers cancel the 1230 // close the state is reset in Browser. We don't update the explicitly 1231 // closed state if already marked as explicitly closed as unload handlers 1232 // call back to this if the close is allowed. 1233 if (!closing_contents->GetClosedByUserGesture()) { 1234 closing_contents->SetClosedByUserGesture( 1235 close_types & CLOSE_USER_GESTURE); 1236 } 1237 1238 if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) { 1239 retval = false; 1240 continue; 1241 } 1242 1243 InternalCloseTab(closing_contents, index, 1244 (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0); 1245 } 1246 1247 return retval; 1248 } 1249 1250 void TabStripModel::InternalCloseTab(WebContents* contents, 1251 int index, 1252 bool create_historical_tabs) { 1253 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 1254 TabClosingAt(this, contents, index)); 1255 1256 // Ask the delegate to save an entry for this tab in the historical tab 1257 // database if applicable. 1258 if (create_historical_tabs) 1259 delegate_->CreateHistoricalTab(contents); 1260 1261 // Deleting the WebContents will call back to us via 1262 // WebContentsData::WebContentsDestroyed and detach it. 1263 delete contents; 1264 } 1265 1266 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const { 1267 CHECK(ContainsIndex(index)) << 1268 "Failed to find: " << index << " in: " << count() << " entries."; 1269 return contents_data_[index]->web_contents(); 1270 } 1271 1272 void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) { 1273 if (contents) { 1274 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 1275 TabDeactivated(contents)); 1276 } 1277 } 1278 1279 void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents, 1280 NotifyTypes notify_types) { 1281 WebContents* new_contents = GetWebContentsAtImpl(active_index()); 1282 if (old_contents != new_contents) { 1283 int reason = notify_types == NOTIFY_USER_GESTURE 1284 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE 1285 : TabStripModelObserver::CHANGE_REASON_NONE; 1286 CHECK(!in_notify_); 1287 in_notify_ = true; 1288 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 1289 ActiveTabChanged(old_contents, 1290 new_contents, 1291 active_index(), 1292 reason)); 1293 in_notify_ = false; 1294 // Activating a discarded tab reloads it, so it is no longer discarded. 1295 contents_data_[active_index()]->set_discarded(false); 1296 } 1297 } 1298 1299 void TabStripModel::NotifyIfActiveOrSelectionChanged( 1300 WebContents* old_contents, 1301 NotifyTypes notify_types, 1302 const ui::ListSelectionModel& old_model) { 1303 NotifyIfActiveTabChanged(old_contents, notify_types); 1304 1305 if (!selection_model().Equals(old_model)) { 1306 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 1307 TabSelectionChanged(this, old_model)); 1308 } 1309 } 1310 1311 void TabStripModel::SetSelection( 1312 const ui::ListSelectionModel& new_model, 1313 NotifyTypes notify_types) { 1314 WebContents* old_contents = GetActiveWebContents(); 1315 ui::ListSelectionModel old_model; 1316 old_model.Copy(selection_model_); 1317 if (new_model.active() != selection_model_.active()) 1318 NotifyIfTabDeactivated(old_contents); 1319 selection_model_.Copy(new_model); 1320 NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model); 1321 } 1322 1323 void TabStripModel::SelectRelativeTab(bool next) { 1324 // This may happen during automated testing or if a user somehow buffers 1325 // many key accelerators. 1326 if (contents_data_.empty()) 1327 return; 1328 1329 int index = active_index(); 1330 int delta = next ? 1 : -1; 1331 index = (index + count() + delta) % count(); 1332 ActivateTabAt(index, true); 1333 } 1334 1335 void TabStripModel::MoveWebContentsAtImpl(int index, 1336 int to_position, 1337 bool select_after_move) { 1338 WebContentsData* moved_data = contents_data_[index]; 1339 contents_data_.erase(contents_data_.begin() + index); 1340 contents_data_.insert(contents_data_.begin() + to_position, moved_data); 1341 1342 selection_model_.Move(index, to_position); 1343 if (!selection_model_.IsSelected(select_after_move) && select_after_move) { 1344 // TODO(sky): why doesn't this code notify observers? 1345 selection_model_.SetSelectedIndex(to_position); 1346 } 1347 1348 ForgetOpenersAndGroupsReferencing(moved_data->web_contents()); 1349 1350 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, 1351 TabMoved(moved_data->web_contents(), index, to_position)); 1352 } 1353 1354 void TabStripModel::MoveSelectedTabsToImpl(int index, 1355 size_t start, 1356 size_t length) { 1357 DCHECK(start < selection_model_.selected_indices().size() && 1358 start + length <= selection_model_.selected_indices().size()); 1359 size_t end = start + length; 1360 int count_before_index = 0; 1361 for (size_t i = start; i < end && 1362 selection_model_.selected_indices()[i] < index + count_before_index; 1363 ++i) { 1364 count_before_index++; 1365 } 1366 1367 // First move those before index. Any tabs before index end up moving in the 1368 // selection model so we use start each time through. 1369 int target_index = index + count_before_index; 1370 size_t tab_index = start; 1371 while (tab_index < end && 1372 selection_model_.selected_indices()[start] < index) { 1373 MoveWebContentsAt(selection_model_.selected_indices()[start], 1374 target_index - 1, false); 1375 tab_index++; 1376 } 1377 1378 // Then move those after the index. These don't result in reordering the 1379 // selection. 1380 while (tab_index < end) { 1381 if (selection_model_.selected_indices()[tab_index] != target_index) { 1382 MoveWebContentsAt(selection_model_.selected_indices()[tab_index], 1383 target_index, false); 1384 } 1385 tab_index++; 1386 target_index++; 1387 } 1388 } 1389 1390 // static 1391 bool TabStripModel::OpenerMatches(const WebContentsData* data, 1392 const WebContents* opener, 1393 bool use_group) { 1394 return data->opener() == opener || (use_group && data->group() == opener); 1395 } 1396 1397 void TabStripModel::ForgetOpenersAndGroupsReferencing( 1398 const WebContents* tab) { 1399 for (WebContentsDataVector::const_iterator i = contents_data_.begin(); 1400 i != contents_data_.end(); ++i) { 1401 if ((*i)->group() == tab) 1402 (*i)->set_group(NULL); 1403 if ((*i)->opener() == tab) 1404 (*i)->set_opener(NULL); 1405 } 1406 } 1407