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.
5 #include "chrome/browser/ui/tabs/tab_strip_model.h"
11 #include "apps/ui/web_contents_sizer.h"
12 #include "base/metrics/histogram.h"
13 #include "base/stl_util.h"
14 #include "chrome/app/chrome_command_ids.h"
15 #include "chrome/browser/browser_shutdown.h"
16 #include "chrome/browser/defaults.h"
17 #include "chrome/browser/extensions/tab_helper.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
20 #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h"
21 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
22 #include "chrome/browser/ui/tabs/tab_strip_model_order_controller.h"
23 #include "chrome/common/url_constants.h"
24 #include "components/web_modal/web_contents_modal_dialog_manager.h"
25 #include "content/public/browser/render_process_host.h"
26 #include "content/public/browser/user_metrics.h"
27 #include "content/public/browser/web_contents.h"
28 #include "content/public/browser/web_contents_observer.h"
29 using base::UserMetricsAction;
30 using content::WebContents;
34 // Returns true if the specified transition is one of the types that cause the
35 // opener relationships for the tab in which the transition occurred to be
36 // forgotten. This is generally any navigation that isn't a link click (i.e.
37 // any navigation that can be considered to be the start of a new task distinct
38 // from what had previously occurred in that tab).
39 bool ShouldForgetOpenersForTransition(content::PageTransition transition) {
40 return transition == content::PAGE_TRANSITION_TYPED ||
41 transition == content::PAGE_TRANSITION_AUTO_BOOKMARK ||
42 transition == content::PAGE_TRANSITION_GENERATED ||
43 transition == content::PAGE_TRANSITION_KEYWORD ||
44 transition == content::PAGE_TRANSITION_AUTO_TOPLEVEL;
47 // CloseTracker is used when closing a set of WebContents. It listens for
48 // deletions of the WebContents and removes from the internal set any time one
52 typedef std::vector<WebContents*> Contents;
54 explicit CloseTracker(const Contents& contents);
55 virtual ~CloseTracker();
57 // Returns true if there is another WebContents in the Tracker.
60 // Returns the next WebContents, or NULL if there are no more.
64 class DeletionObserver : public content::WebContentsObserver {
66 DeletionObserver(CloseTracker* parent, WebContents* web_contents)
67 : WebContentsObserver(web_contents),
71 // Expose web_contents() publicly.
72 using content::WebContentsObserver::web_contents;
75 // WebContentsObserver:
76 virtual void WebContentsDestroyed() OVERRIDE {
77 parent_->OnWebContentsDestroyed(this);
80 CloseTracker* parent_;
82 DISALLOW_COPY_AND_ASSIGN(DeletionObserver);
85 void OnWebContentsDestroyed(DeletionObserver* observer);
87 typedef std::vector<DeletionObserver*> Observers;
90 DISALLOW_COPY_AND_ASSIGN(CloseTracker);
93 CloseTracker::CloseTracker(const Contents& contents) {
94 for (size_t i = 0; i < contents.size(); ++i)
95 observers_.push_back(new DeletionObserver(this, contents[i]));
98 CloseTracker::~CloseTracker() {
99 DCHECK(observers_.empty());
102 bool CloseTracker::HasNext() const {
103 return !observers_.empty();
106 WebContents* CloseTracker::Next() {
107 if (observers_.empty())
110 DeletionObserver* observer = observers_[0];
111 WebContents* web_contents = observer->web_contents();
112 observers_.erase(observers_.begin());
117 void CloseTracker::OnWebContentsDestroyed(DeletionObserver* observer) {
118 Observers::iterator i =
119 std::find(observers_.begin(), observers_.end(), observer);
120 if (i != observers_.end()) {
125 NOTREACHED() << "WebContents destroyed that wasn't in the list";
130 ///////////////////////////////////////////////////////////////////////////////
133 // An object to hold a reference to a WebContents that is in a tabstrip, as
134 // well as other various properties it has.
135 class TabStripModel::WebContentsData : public content::WebContentsObserver {
137 WebContentsData(TabStripModel* tab_strip_model, WebContents* a_contents);
139 // Changes the WebContents that this WebContentsData tracks.
140 void SetWebContents(WebContents* contents);
141 WebContents* web_contents() { return contents_; }
143 // Create a relationship between this WebContentsData and other
144 // WebContentses. Used to identify which WebContents to select next after
146 WebContents* group() const { return group_; }
147 void set_group(WebContents* value) { group_ = value; }
148 WebContents* opener() const { return opener_; }
149 void set_opener(WebContents* value) { opener_ = value; }
151 // Alters the properties of the WebContents.
152 bool reset_group_on_select() const { return reset_group_on_select_; }
153 void set_reset_group_on_select(bool value) { reset_group_on_select_ = value; }
154 bool pinned() const { return pinned_; }
155 void set_pinned(bool value) { pinned_ = value; }
156 bool blocked() const { return blocked_; }
157 void set_blocked(bool value) { blocked_ = value; }
158 bool discarded() const { return discarded_; }
159 void set_discarded(bool value) { discarded_ = value; }
162 // Make sure that if someone deletes this WebContents out from under us, it
163 // is properly removed from the tab strip.
164 virtual void WebContentsDestroyed() OVERRIDE;
166 // The WebContents being tracked by this WebContentsData. The
167 // WebContentsObserver does keep a reference, but when the WebContents is
168 // deleted, the WebContentsObserver reference is NULLed and thus inaccessible.
169 WebContents* contents_;
171 // The TabStripModel containing this WebContents.
172 TabStripModel* tab_strip_model_;
174 // The group is used to model a set of tabs spawned from a single parent
175 // tab. This value is preserved for a given tab as long as the tab remains
176 // navigated to the link it was initially opened at or some navigation from
177 // that page (i.e. if the user types or visits a bookmark or some other
178 // navigation within that tab, the group relationship is lost). This
179 // property can safely be used to implement features that depend on a
180 // logical group of related tabs.
183 // The owner models the same relationship as group, except it is more
184 // easily discarded, e.g. when the user switches to a tab not part of the
185 // same group. This property is used to determine what tab to select next
186 // when one is closed.
187 WebContents* opener_;
189 // True if our group should be reset the moment selection moves away from
190 // this tab. This is the case for tabs opened in the foreground at the end
191 // of the TabStrip while viewing another Tab. If these tabs are closed
192 // before selection moves elsewhere, their opener is selected. But if
193 // selection shifts to _any_ tab (including their opener), the group
194 // relationship is reset to avoid confusing close sequencing.
195 bool reset_group_on_select_;
197 // Is the tab pinned?
200 // Is the tab interaction blocked by a modal dialog?
203 // Has the tab data been discarded to save memory?
206 DISALLOW_COPY_AND_ASSIGN(WebContentsData);
209 TabStripModel::WebContentsData::WebContentsData(TabStripModel* tab_strip_model,
210 WebContents* contents)
211 : content::WebContentsObserver(contents),
213 tab_strip_model_(tab_strip_model),
216 reset_group_on_select_(false),
222 void TabStripModel::WebContentsData::SetWebContents(WebContents* contents) {
223 contents_ = contents;
227 void TabStripModel::WebContentsData::WebContentsDestroyed() {
228 DCHECK_EQ(contents_, web_contents());
230 // Note that we only detach the contents here, not close it - it's
231 // already been closed. We just want to undo our bookkeeping.
232 int index = tab_strip_model_->GetIndexOfWebContents(web_contents());
233 DCHECK_NE(TabStripModel::kNoTab, index);
234 tab_strip_model_->DetachWebContentsAt(index);
237 ///////////////////////////////////////////////////////////////////////////////
238 // TabStripModel, public:
240 TabStripModel::TabStripModel(TabStripModelDelegate* delegate, Profile* profile)
241 : delegate_(delegate),
245 weak_factory_(this) {
247 order_controller_.reset(new TabStripModelOrderController(this));
250 TabStripModel::~TabStripModel() {
251 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
252 TabStripModelDeleted());
253 STLDeleteElements(&contents_data_);
254 order_controller_.reset();
257 void TabStripModel::AddObserver(TabStripModelObserver* observer) {
258 observers_.AddObserver(observer);
261 void TabStripModel::RemoveObserver(TabStripModelObserver* observer) {
262 observers_.RemoveObserver(observer);
265 bool TabStripModel::ContainsIndex(int index) const {
266 return index >= 0 && index < count();
269 void TabStripModel::AppendWebContents(WebContents* contents,
271 InsertWebContentsAt(count(), contents,
272 foreground ? (ADD_INHERIT_GROUP | ADD_ACTIVE) :
276 void TabStripModel::InsertWebContentsAt(int index,
277 WebContents* contents,
279 delegate_->WillAddWebContents(contents);
281 bool active = add_types & ADD_ACTIVE;
282 // Force app tabs to be pinned.
283 extensions::TabHelper* extensions_tab_helper =
284 extensions::TabHelper::FromWebContents(contents);
285 bool pin = extensions_tab_helper->is_app() || add_types & ADD_PINNED;
286 index = ConstrainInsertionIndex(index, pin);
288 // In tab dragging situations, if the last tab in the window was detached
289 // then the user aborted the drag, we will have the |closing_all_| member
290 // set (see DetachWebContentsAt) which will mess with our mojo here. We need
291 // to clear this bit.
292 closing_all_ = false;
294 // Have to get the active contents before we monkey with the contents
295 // otherwise we run into problems when we try to change the active contents
296 // since the old contents and the new contents will be the same...
297 WebContents* active_contents = GetActiveWebContents();
298 WebContentsData* data = new WebContentsData(this, contents);
299 data->set_pinned(pin);
300 if ((add_types & ADD_INHERIT_GROUP) && active_contents) {
302 // Forget any existing relationships, we don't want to make things too
303 // confusing by having multiple groups active at the same time.
306 // Anything opened by a link we deem to have an opener.
307 data->set_group(active_contents);
308 data->set_opener(active_contents);
309 } else if ((add_types & ADD_INHERIT_OPENER) && active_contents) {
311 // Forget any existing relationships, we don't want to make things too
312 // confusing by having multiple groups active at the same time.
315 data->set_opener(active_contents);
318 web_modal::WebContentsModalDialogManager* modal_dialog_manager =
319 web_modal::WebContentsModalDialogManager::FromWebContents(contents);
320 if (modal_dialog_manager)
321 data->set_blocked(modal_dialog_manager->IsDialogActive());
323 contents_data_.insert(contents_data_.begin() + index, data);
325 selection_model_.IncrementFrom(index);
327 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
328 TabInsertedAt(contents, index, active));
330 ui::ListSelectionModel new_model;
331 new_model.Copy(selection_model_);
332 new_model.SetSelectedIndex(index);
333 SetSelection(new_model, NOTIFY_DEFAULT);
337 WebContents* TabStripModel::ReplaceWebContentsAt(int index,
338 WebContents* new_contents) {
339 delegate_->WillAddWebContents(new_contents);
341 DCHECK(ContainsIndex(index));
342 WebContents* old_contents = GetWebContentsAtImpl(index);
344 ForgetOpenersAndGroupsReferencing(old_contents);
346 contents_data_[index]->SetWebContents(new_contents);
348 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
349 TabReplacedAt(this, old_contents, new_contents, index));
351 // When the active WebContents is replaced send out a selection notification
352 // too. We do this as nearly all observers need to treat a replacement of the
353 // selected contents as the selection changing.
354 if (active_index() == index) {
356 TabStripModelObserver,
358 ActiveTabChanged(old_contents,
361 TabStripModelObserver::CHANGE_REASON_REPLACED));
366 WebContents* TabStripModel::DiscardWebContentsAt(int index) {
367 DCHECK(ContainsIndex(index));
368 // Do not discard active tab.
369 if (active_index() == index)
372 WebContents* null_contents =
373 WebContents::Create(WebContents::CreateParams(profile()));
374 WebContents* old_contents = GetWebContentsAtImpl(index);
375 // Copy over the state from the navigation controller so we preserve the
376 // back/forward history and continue to display the correct title/favicon.
377 null_contents->GetController().CopyStateFrom(old_contents->GetController());
378 // Replace the tab we're discarding with the null version.
379 ReplaceWebContentsAt(index, null_contents);
380 // Mark the tab so it will reload when we click.
381 contents_data_[index]->set_discarded(true);
382 // Discard the old tab's renderer.
383 // TODO(jamescook): This breaks script connections with other tabs.
384 // We need to find a different approach that doesn't do that, perhaps based
385 // on navigation to swappedout://.
387 return null_contents;
390 WebContents* TabStripModel::DetachWebContentsAt(int index) {
392 if (contents_data_.empty())
395 DCHECK(ContainsIndex(index));
397 WebContents* removed_contents = GetWebContentsAtImpl(index);
398 bool was_selected = IsTabSelected(index);
399 int next_selected_index = order_controller_->DetermineNewSelectedIndex(index);
400 delete contents_data_[index];
401 contents_data_.erase(contents_data_.begin() + index);
402 ForgetOpenersAndGroupsReferencing(removed_contents);
405 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
406 TabDetachedAt(removed_contents, index));
408 selection_model_.Clear();
409 // TabDetachedAt() might unregister observers, so send |TabStripEmpty()| in
411 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty());
413 int old_active = active_index();
414 selection_model_.DecrementFrom(index);
415 ui::ListSelectionModel old_model;
416 old_model.Copy(selection_model_);
417 if (index == old_active) {
418 NotifyIfTabDeactivated(removed_contents);
419 if (!selection_model_.empty()) {
420 // The active tab was removed, but there is still something selected.
421 // Move the active and anchor to the first selected index.
422 selection_model_.set_active(selection_model_.selected_indices()[0]);
423 selection_model_.set_anchor(selection_model_.active());
425 // The active tab was removed and nothing is selected. Reset the
426 // selection and send out notification.
427 selection_model_.SetSelectedIndex(next_selected_index);
429 NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT);
432 // Sending notification in case the detached tab was selected. Using
433 // NotifyIfActiveOrSelectionChanged() here would not guarantee that a
434 // notification is sent even though the tab selection has changed because
435 // |old_model| is stored after calling DecrementFrom().
437 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
438 TabSelectionChanged(this, old_model));
441 return removed_contents;
444 void TabStripModel::ActivateTabAt(int index, bool user_gesture) {
445 DCHECK(ContainsIndex(index));
446 ui::ListSelectionModel new_model;
447 new_model.Copy(selection_model_);
448 new_model.SetSelectedIndex(index);
449 SetSelection(new_model, user_gesture ? NOTIFY_USER_GESTURE : NOTIFY_DEFAULT);
452 void TabStripModel::AddTabAtToSelection(int index) {
453 DCHECK(ContainsIndex(index));
454 ui::ListSelectionModel new_model;
455 new_model.Copy(selection_model_);
456 new_model.AddIndexToSelection(index);
457 SetSelection(new_model, NOTIFY_DEFAULT);
460 void TabStripModel::MoveWebContentsAt(int index,
462 bool select_after_move) {
463 DCHECK(ContainsIndex(index));
464 if (index == to_position)
467 int first_non_mini_tab = IndexOfFirstNonMiniTab();
468 if ((index < first_non_mini_tab && to_position >= first_non_mini_tab) ||
469 (to_position < first_non_mini_tab && index >= first_non_mini_tab)) {
470 // This would result in mini tabs mixed with non-mini tabs. We don't allow
475 MoveWebContentsAtImpl(index, to_position, select_after_move);
478 void TabStripModel::MoveSelectedTabsTo(int index) {
479 int total_mini_count = IndexOfFirstNonMiniTab();
480 int selected_mini_count = 0;
482 static_cast<int>(selection_model_.selected_indices().size());
483 for (int i = 0; i < selected_count &&
484 IsMiniTab(selection_model_.selected_indices()[i]); ++i) {
485 selected_mini_count++;
488 // To maintain that all mini-tabs occur before non-mini-tabs we move them
490 if (selected_mini_count > 0) {
491 MoveSelectedTabsToImpl(
492 std::min(total_mini_count - selected_mini_count, index), 0u,
493 selected_mini_count);
494 if (index > total_mini_count - selected_mini_count) {
495 // We're being told to drag mini-tabs to an invalid location. Adjust the
496 // index such that non-mini-tabs end up at a location as though we could
497 // move the mini-tabs to index. See description in header for more
499 index += selected_mini_count;
502 if (selected_mini_count == selected_count)
505 // Then move the non-pinned tabs.
506 MoveSelectedTabsToImpl(std::max(index, total_mini_count),
508 selected_count - selected_mini_count);
511 WebContents* TabStripModel::GetActiveWebContents() const {
512 return GetWebContentsAt(active_index());
515 WebContents* TabStripModel::GetWebContentsAt(int index) const {
516 if (ContainsIndex(index))
517 return GetWebContentsAtImpl(index);
521 int TabStripModel::GetIndexOfWebContents(const WebContents* contents) const {
522 for (size_t i = 0; i < contents_data_.size(); ++i) {
523 if (contents_data_[i]->web_contents() == contents)
529 void TabStripModel::UpdateWebContentsStateAt(int index,
530 TabStripModelObserver::TabChangeType change_type) {
531 DCHECK(ContainsIndex(index));
533 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
534 TabChangedAt(GetWebContentsAtImpl(index), index, change_type));
537 void TabStripModel::CloseAllTabs() {
538 // Set state so that observers can adjust their behavior to suit this
539 // specific condition when CloseWebContentsAt causes a flurry of
540 // Close/Detach/Select notifications to be sent.
542 std::vector<int> closing_tabs;
543 for (int i = count() - 1; i >= 0; --i)
544 closing_tabs.push_back(i);
545 InternalCloseTabs(closing_tabs, CLOSE_CREATE_HISTORICAL_TAB);
548 bool TabStripModel::CloseWebContentsAt(int index, uint32 close_types) {
549 DCHECK(ContainsIndex(index));
550 std::vector<int> closing_tabs;
551 closing_tabs.push_back(index);
552 return InternalCloseTabs(closing_tabs, close_types);
555 bool TabStripModel::TabsAreLoading() const {
556 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
557 iter != contents_data_.end(); ++iter) {
558 if ((*iter)->web_contents()->IsLoading())
564 WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) {
565 DCHECK(ContainsIndex(index));
566 return contents_data_[index]->opener();
569 void TabStripModel::SetOpenerOfWebContentsAt(int index,
570 WebContents* opener) {
571 DCHECK(ContainsIndex(index));
573 contents_data_[index]->set_opener(opener);
576 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener,
578 bool use_group) const {
580 DCHECK(ContainsIndex(start_index));
582 // Check tabs after start_index first.
583 for (int i = start_index + 1; i < count(); ++i) {
584 if (OpenerMatches(contents_data_[i], opener, use_group))
587 // Then check tabs before start_index, iterating backwards.
588 for (int i = start_index - 1; i >= 0; --i) {
589 if (OpenerMatches(contents_data_[i], opener, use_group))
595 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
596 int start_index) const {
598 DCHECK(ContainsIndex(start_index));
600 for (int i = contents_data_.size() - 1; i > start_index; --i) {
601 if (contents_data_[i]->opener() == opener)
607 void TabStripModel::TabNavigating(WebContents* contents,
608 content::PageTransition transition) {
609 if (ShouldForgetOpenersForTransition(transition)) {
610 // Don't forget the openers if this tab is a New Tab page opened at the
611 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
612 // navigation of one of these transition types before resetting the
613 // opener relationships (this allows for the use case of opening a new
614 // tab to do a quick look-up of something while viewing a tab earlier in
615 // the strip). We can make this heuristic more permissive if need be.
616 if (!IsNewTabAtEndOfTabStrip(contents)) {
617 // If the user navigates the current tab to another page in any way
618 // other than by clicking a link, we want to pro-actively forget all
619 // TabStrip opener relationships since we assume they're beginning a
620 // different task by reusing the current tab.
622 // In this specific case we also want to reset the group relationship,
623 // since it is now technically invalid.
624 ForgetGroup(contents);
629 void TabStripModel::ForgetAllOpeners() {
630 // Forget all opener memories so we don't do anything weird with tab
631 // re-selection ordering.
632 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
633 iter != contents_data_.end(); ++iter)
634 (*iter)->set_opener(NULL);
637 void TabStripModel::ForgetGroup(WebContents* contents) {
638 int index = GetIndexOfWebContents(contents);
639 DCHECK(ContainsIndex(index));
640 contents_data_[index]->set_group(NULL);
641 contents_data_[index]->set_opener(NULL);
644 bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const {
645 int index = GetIndexOfWebContents(contents);
646 DCHECK(ContainsIndex(index));
647 return contents_data_[index]->reset_group_on_select();
650 void TabStripModel::SetTabBlocked(int index, bool blocked) {
651 DCHECK(ContainsIndex(index));
652 if (contents_data_[index]->blocked() == blocked)
654 contents_data_[index]->set_blocked(blocked);
656 TabStripModelObserver, observers_,
657 TabBlockedStateChanged(contents_data_[index]->web_contents(),
661 void TabStripModel::SetTabPinned(int index, bool pinned) {
662 DCHECK(ContainsIndex(index));
663 if (contents_data_[index]->pinned() == pinned)
666 if (IsAppTab(index)) {
668 // App tabs should always be pinned.
672 // Changing the pinned state of an app tab doesn't affect its mini-tab
674 contents_data_[index]->set_pinned(pinned);
676 // The tab is not an app tab, its position may have to change as the
677 // mini-tab state is changing.
678 int non_mini_tab_index = IndexOfFirstNonMiniTab();
679 contents_data_[index]->set_pinned(pinned);
680 if (pinned && index != non_mini_tab_index) {
681 MoveWebContentsAtImpl(index, non_mini_tab_index, false);
682 index = non_mini_tab_index;
683 } else if (!pinned && index + 1 != non_mini_tab_index) {
684 MoveWebContentsAtImpl(index, non_mini_tab_index - 1, false);
685 index = non_mini_tab_index - 1;
688 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
689 TabMiniStateChanged(contents_data_[index]->web_contents(),
693 // else: the tab was at the boundary and its position doesn't need to change.
694 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
695 TabPinnedStateChanged(contents_data_[index]->web_contents(),
699 bool TabStripModel::IsTabPinned(int index) const {
700 DCHECK(ContainsIndex(index));
701 return contents_data_[index]->pinned();
704 bool TabStripModel::IsMiniTab(int index) const {
705 return IsTabPinned(index) || IsAppTab(index);
708 bool TabStripModel::IsAppTab(int index) const {
709 WebContents* contents = GetWebContentsAt(index);
710 return contents && extensions::TabHelper::FromWebContents(contents)->is_app();
713 bool TabStripModel::IsTabBlocked(int index) const {
714 return contents_data_[index]->blocked();
717 bool TabStripModel::IsTabDiscarded(int index) const {
718 return contents_data_[index]->discarded();
721 int TabStripModel::IndexOfFirstNonMiniTab() const {
722 for (size_t i = 0; i < contents_data_.size(); ++i) {
723 if (!IsMiniTab(static_cast<int>(i)))
724 return static_cast<int>(i);
730 int TabStripModel::ConstrainInsertionIndex(int index, bool mini_tab) {
731 return mini_tab ? std::min(std::max(0, index), IndexOfFirstNonMiniTab()) :
732 std::min(count(), std::max(index, IndexOfFirstNonMiniTab()));
735 void TabStripModel::ExtendSelectionTo(int index) {
736 DCHECK(ContainsIndex(index));
737 ui::ListSelectionModel new_model;
738 new_model.Copy(selection_model_);
739 new_model.SetSelectionFromAnchorTo(index);
740 SetSelection(new_model, NOTIFY_DEFAULT);
743 void TabStripModel::ToggleSelectionAt(int index) {
744 DCHECK(ContainsIndex(index));
745 ui::ListSelectionModel new_model;
746 new_model.Copy(selection_model());
747 if (selection_model_.IsSelected(index)) {
748 if (selection_model_.size() == 1) {
749 // One tab must be selected and this tab is currently selected so we can't
753 new_model.RemoveIndexFromSelection(index);
754 new_model.set_anchor(index);
755 if (new_model.active() == index ||
756 new_model.active() == ui::ListSelectionModel::kUnselectedIndex)
757 new_model.set_active(new_model.selected_indices()[0]);
759 new_model.AddIndexToSelection(index);
760 new_model.set_anchor(index);
761 new_model.set_active(index);
763 SetSelection(new_model, NOTIFY_DEFAULT);
766 void TabStripModel::AddSelectionFromAnchorTo(int index) {
767 ui::ListSelectionModel new_model;
768 new_model.Copy(selection_model_);
769 new_model.AddSelectionFromAnchorTo(index);
770 SetSelection(new_model, NOTIFY_DEFAULT);
773 bool TabStripModel::IsTabSelected(int index) const {
774 DCHECK(ContainsIndex(index));
775 return selection_model_.IsSelected(index);
778 void TabStripModel::SetSelectionFromModel(
779 const ui::ListSelectionModel& source) {
780 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
781 SetSelection(source, NOTIFY_DEFAULT);
784 void TabStripModel::AddWebContents(WebContents* contents,
786 content::PageTransition transition,
788 // If the newly-opened tab is part of the same task as the parent tab, we want
789 // to inherit the parent's "group" attribute, so that if this tab is then
790 // closed we'll jump back to the parent tab.
791 bool inherit_group = (add_types & ADD_INHERIT_GROUP) == ADD_INHERIT_GROUP;
793 if (transition == content::PAGE_TRANSITION_LINK &&
794 (add_types & ADD_FORCE_INDEX) == 0) {
795 // We assume tabs opened via link clicks are part of the same task as their
796 // parent. Note that when |force_index| is true (e.g. when the user
797 // drag-and-drops a link to the tab strip), callers aren't really handling
798 // link clicks, they just want to score the navigation like a link click in
799 // the history backend, so we don't inherit the group in this case.
800 index = order_controller_->DetermineInsertionIndex(transition,
801 add_types & ADD_ACTIVE);
802 inherit_group = true;
804 // For all other types, respect what was passed to us, normalizing -1s and
805 // values that are too large.
806 if (index < 0 || index > count())
810 if (transition == content::PAGE_TRANSITION_TYPED && index == count()) {
811 // Also, any tab opened at the end of the TabStrip with a "TYPED"
812 // transition inherit group as well. This covers the cases where the user
813 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
814 // in the address bar and presses Alt+Enter. This allows for opening a new
815 // Tab to quickly look up something. When this Tab is closed, the old one
816 // is re-selected, not the next-adjacent.
817 inherit_group = true;
819 InsertWebContentsAt(index, contents,
820 add_types | (inherit_group ? ADD_INHERIT_GROUP : 0));
821 // Reset the index, just in case insert ended up moving it on us.
822 index = GetIndexOfWebContents(contents);
824 if (inherit_group && transition == content::PAGE_TRANSITION_TYPED)
825 contents_data_[index]->set_reset_group_on_select(true);
827 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
828 // here we seem to get failures in startup perf tests.
829 // Ensure that the new WebContentsView begins at the same size as the
830 // previous WebContentsView if it existed. Otherwise, the initial WebKit
831 // layout will be performed based on a width of 0 pixels, causing a
832 // very long, narrow, inaccurate layout. Because some scripts on pages (as
833 // well as WebKit's anchor link location calculation) are run on the
834 // initial layout and not recalculated later, we need to ensure the first
835 // layout is performed with sane view dimensions even when we're opening a
836 // new background tab.
837 if (WebContents* old_contents = GetActiveWebContents()) {
838 if ((add_types & ADD_ACTIVE) == 0) {
839 apps::ResizeWebContents(contents,
840 old_contents->GetContainerBounds().size());
845 void TabStripModel::CloseSelectedTabs() {
846 InternalCloseTabs(selection_model_.selected_indices(),
847 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
850 void TabStripModel::SelectNextTab() {
851 SelectRelativeTab(true);
854 void TabStripModel::SelectPreviousTab() {
855 SelectRelativeTab(false);
858 void TabStripModel::SelectLastTab() {
859 ActivateTabAt(count() - 1, true);
862 void TabStripModel::MoveTabNext() {
863 // TODO: this likely needs to be updated for multi-selection.
864 int new_index = std::min(active_index() + 1, count() - 1);
865 MoveWebContentsAt(active_index(), new_index, true);
868 void TabStripModel::MoveTabPrevious() {
869 // TODO: this likely needs to be updated for multi-selection.
870 int new_index = std::max(active_index() - 1, 0);
871 MoveWebContentsAt(active_index(), new_index, true);
874 // Context menu functions.
875 bool TabStripModel::IsContextMenuCommandEnabled(
876 int context_index, ContextMenuCommand command_id) const {
877 DCHECK(command_id > CommandFirst && command_id < CommandLast);
878 switch (command_id) {
880 case CommandCloseTab:
883 case CommandReload: {
884 std::vector<int> indices = GetIndicesForCommand(context_index);
885 for (size_t i = 0; i < indices.size(); ++i) {
886 WebContents* tab = GetWebContentsAt(indices[i]);
888 CoreTabHelperDelegate* core_delegate =
889 CoreTabHelper::FromWebContents(tab)->delegate();
890 if (!core_delegate || core_delegate->CanReloadContents(tab))
897 case CommandCloseOtherTabs:
898 case CommandCloseTabsToRight:
899 return !GetIndicesClosedByCommand(context_index, command_id).empty();
901 case CommandDuplicate: {
902 std::vector<int> indices = GetIndicesForCommand(context_index);
903 for (size_t i = 0; i < indices.size(); ++i) {
904 if (delegate_->CanDuplicateContentsAt(indices[i]))
910 case CommandRestoreTab:
911 return delegate_->GetRestoreTabType() !=
912 TabStripModelDelegate::RESTORE_NONE;
914 case CommandTogglePinned: {
915 std::vector<int> indices = GetIndicesForCommand(context_index);
916 for (size_t i = 0; i < indices.size(); ++i) {
917 if (!IsAppTab(indices[i]))
923 case CommandBookmarkAllTabs:
924 return browser_defaults::bookmarks_enabled &&
925 delegate_->CanBookmarkAllTabs();
927 case CommandSelectByDomain:
928 case CommandSelectByOpener:
937 void TabStripModel::ExecuteContextMenuCommand(
938 int context_index, ContextMenuCommand command_id) {
939 DCHECK(command_id > CommandFirst && command_id < CommandLast);
940 switch (command_id) {
942 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
943 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
944 TabStripModel::NEW_TAB_CONTEXT_MENU,
945 TabStripModel::NEW_TAB_ENUM_COUNT);
946 delegate()->AddTabAt(GURL(), context_index + 1, true);
949 case CommandReload: {
950 content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
951 std::vector<int> indices = GetIndicesForCommand(context_index);
952 for (size_t i = 0; i < indices.size(); ++i) {
953 WebContents* tab = GetWebContentsAt(indices[i]);
955 CoreTabHelperDelegate* core_delegate =
956 CoreTabHelper::FromWebContents(tab)->delegate();
957 if (!core_delegate || core_delegate->CanReloadContents(tab))
958 tab->GetController().Reload(true);
964 case CommandDuplicate: {
965 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
966 std::vector<int> indices = GetIndicesForCommand(context_index);
967 // Copy the WebContents off as the indices will change as tabs are
969 std::vector<WebContents*> tabs;
970 for (size_t i = 0; i < indices.size(); ++i)
971 tabs.push_back(GetWebContentsAt(indices[i]));
972 for (size_t i = 0; i < tabs.size(); ++i) {
973 int index = GetIndexOfWebContents(tabs[i]);
974 if (index != -1 && delegate_->CanDuplicateContentsAt(index))
975 delegate_->DuplicateContentsAt(index);
980 case CommandCloseTab: {
981 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
982 InternalCloseTabs(GetIndicesForCommand(context_index),
983 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
987 case CommandCloseOtherTabs: {
988 content::RecordAction(
989 UserMetricsAction("TabContextMenu_CloseOtherTabs"));
990 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
991 CLOSE_CREATE_HISTORICAL_TAB);
995 case CommandCloseTabsToRight: {
996 content::RecordAction(
997 UserMetricsAction("TabContextMenu_CloseTabsToRight"));
998 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
999 CLOSE_CREATE_HISTORICAL_TAB);
1003 case CommandRestoreTab: {
1004 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1005 delegate_->RestoreTab();
1009 case CommandTogglePinned: {
1010 content::RecordAction(
1011 UserMetricsAction("TabContextMenu_TogglePinned"));
1012 std::vector<int> indices = GetIndicesForCommand(context_index);
1013 bool pin = WillContextMenuPin(context_index);
1015 for (size_t i = 0; i < indices.size(); ++i) {
1016 if (!IsAppTab(indices[i]))
1017 SetTabPinned(indices[i], true);
1020 // Unpin from the back so that the order is maintained (unpinning can
1021 // trigger moving a tab).
1022 for (size_t i = indices.size(); i > 0; --i) {
1023 if (!IsAppTab(indices[i - 1]))
1024 SetTabPinned(indices[i - 1], false);
1030 case CommandBookmarkAllTabs: {
1031 content::RecordAction(
1032 UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1034 delegate_->BookmarkAllTabs();
1038 case CommandSelectByDomain:
1039 case CommandSelectByOpener: {
1040 std::vector<int> indices;
1041 if (command_id == CommandSelectByDomain)
1042 GetIndicesWithSameDomain(context_index, &indices);
1044 GetIndicesWithSameOpener(context_index, &indices);
1045 ui::ListSelectionModel selection_model;
1046 selection_model.SetSelectedIndex(context_index);
1047 for (size_t i = 0; i < indices.size(); ++i)
1048 selection_model.AddIndexToSelection(indices[i]);
1049 SetSelectionFromModel(selection_model);
1058 std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1060 ContextMenuCommand id) const {
1061 DCHECK(ContainsIndex(index));
1062 DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1063 bool is_selected = IsTabSelected(index);
1065 if (id == CommandCloseTabsToRight) {
1067 start = selection_model_.selected_indices()[
1068 selection_model_.selected_indices().size() - 1] + 1;
1075 // NOTE: callers expect the vector to be sorted in descending order.
1076 std::vector<int> indices;
1077 for (int i = count() - 1; i >= start; --i) {
1078 if (i != index && !IsMiniTab(i) && (!is_selected || !IsTabSelected(i)))
1079 indices.push_back(i);
1084 bool TabStripModel::WillContextMenuPin(int index) {
1085 std::vector<int> indices = GetIndicesForCommand(index);
1086 // If all tabs are pinned, then we unpin, otherwise we pin.
1087 bool all_pinned = true;
1088 for (size_t i = 0; i < indices.size() && all_pinned; ++i) {
1089 if (!IsAppTab(index)) // We never change app tabs.
1090 all_pinned = IsTabPinned(indices[i]);
1096 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1100 *browser_cmd = IDC_NEW_TAB;
1103 *browser_cmd = IDC_RELOAD;
1105 case CommandDuplicate:
1106 *browser_cmd = IDC_DUPLICATE_TAB;
1108 case CommandCloseTab:
1109 *browser_cmd = IDC_CLOSE_TAB;
1111 case CommandRestoreTab:
1112 *browser_cmd = IDC_RESTORE_TAB;
1114 case CommandBookmarkAllTabs:
1115 *browser_cmd = IDC_BOOKMARK_ALL_TABS;
1125 ///////////////////////////////////////////////////////////////////////////////
1126 // TabStripModel, private:
1128 std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices(
1129 const std::vector<int>& indices) const {
1130 std::vector<WebContents*> contents;
1131 for (size_t i = 0; i < indices.size(); ++i)
1132 contents.push_back(GetWebContentsAtImpl(indices[i]));
1136 void TabStripModel::GetIndicesWithSameDomain(int index,
1137 std::vector<int>* indices) {
1138 std::string domain = GetWebContentsAt(index)->GetURL().host();
1141 for (int i = 0; i < count(); ++i) {
1144 if (GetWebContentsAt(i)->GetURL().host() == domain)
1145 indices->push_back(i);
1149 void TabStripModel::GetIndicesWithSameOpener(int index,
1150 std::vector<int>* indices) {
1151 WebContents* opener = contents_data_[index]->group();
1153 // If there is no group, find all tabs with the selected tab as the opener.
1154 opener = GetWebContentsAt(index);
1158 for (int i = 0; i < count(); ++i) {
1161 if (contents_data_[i]->group() == opener ||
1162 GetWebContentsAtImpl(i) == opener) {
1163 indices->push_back(i);
1168 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1169 if (!IsTabSelected(index)) {
1170 std::vector<int> indices;
1171 indices.push_back(index);
1174 return selection_model_.selected_indices();
1177 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1178 const GURL& url = contents->GetURL();
1179 return url.SchemeIs(content::kChromeUIScheme) &&
1180 url.host() == chrome::kChromeUINewTabHost &&
1181 contents == GetWebContentsAtImpl(count() - 1) &&
1182 contents->GetController().GetEntryCount() == 1;
1185 bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
1186 uint32 close_types) {
1187 if (indices.empty())
1190 CloseTracker close_tracker(GetWebContentsFromIndices(indices));
1192 base::WeakPtr<TabStripModel> ref(weak_factory_.GetWeakPtr());
1193 const bool closing_all = indices.size() == contents_data_.size();
1195 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, WillCloseAllTabs());
1197 // We only try the fast shutdown path if the whole browser process is *not*
1198 // shutting down. Fast shutdown during browser termination is handled in
1200 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
1201 // Construct a map of processes to the number of associated tabs that are
1203 std::map<content::RenderProcessHost*, size_t> processes;
1204 for (size_t i = 0; i < indices.size(); ++i) {
1205 WebContents* closing_contents = GetWebContentsAtImpl(indices[i]);
1206 if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents))
1208 content::RenderProcessHost* process =
1209 closing_contents->GetRenderProcessHost();
1210 ++processes[process];
1213 // Try to fast shutdown the tabs that can close.
1214 for (std::map<content::RenderProcessHost*, size_t>::iterator iter =
1215 processes.begin(); iter != processes.end(); ++iter) {
1216 iter->first->FastShutdownForPageCount(iter->second);
1220 // We now return to our regularly scheduled shutdown procedure.
1222 while (close_tracker.HasNext()) {
1223 WebContents* closing_contents = close_tracker.Next();
1224 int index = GetIndexOfWebContents(closing_contents);
1225 // Make sure we still contain the tab.
1226 if (index == kNoTab)
1229 CoreTabHelper* core_tab_helper =
1230 CoreTabHelper::FromWebContents(closing_contents);
1231 core_tab_helper->OnCloseStarted();
1233 // Update the explicitly closed state. If the unload handlers cancel the
1234 // close the state is reset in Browser. We don't update the explicitly
1235 // closed state if already marked as explicitly closed as unload handlers
1236 // call back to this if the close is allowed.
1237 if (!closing_contents->GetClosedByUserGesture()) {
1238 closing_contents->SetClosedByUserGesture(
1239 close_types & CLOSE_USER_GESTURE);
1242 if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) {
1247 InternalCloseTab(closing_contents, index,
1248 (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
1251 if (ref && closing_all && !retval) {
1252 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1253 CloseAllTabsCanceled());
1259 void TabStripModel::InternalCloseTab(WebContents* contents,
1261 bool create_historical_tabs) {
1262 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1263 TabClosingAt(this, contents, index));
1265 // Ask the delegate to save an entry for this tab in the historical tab
1266 // database if applicable.
1267 if (create_historical_tabs)
1268 delegate_->CreateHistoricalTab(contents);
1270 // Deleting the WebContents will call back to us via
1271 // WebContentsData::WebContentsDestroyed and detach it.
1275 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1276 CHECK(ContainsIndex(index)) <<
1277 "Failed to find: " << index << " in: " << count() << " entries.";
1278 return contents_data_[index]->web_contents();
1281 void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) {
1283 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1284 TabDeactivated(contents));
1288 void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents,
1289 NotifyTypes notify_types) {
1290 WebContents* new_contents = GetWebContentsAtImpl(active_index());
1291 if (old_contents != new_contents) {
1292 int reason = notify_types == NOTIFY_USER_GESTURE
1293 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1294 : TabStripModelObserver::CHANGE_REASON_NONE;
1297 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1298 ActiveTabChanged(old_contents,
1303 // Activating a discarded tab reloads it, so it is no longer discarded.
1304 contents_data_[active_index()]->set_discarded(false);
1308 void TabStripModel::NotifyIfActiveOrSelectionChanged(
1309 WebContents* old_contents,
1310 NotifyTypes notify_types,
1311 const ui::ListSelectionModel& old_model) {
1312 NotifyIfActiveTabChanged(old_contents, notify_types);
1314 if (!selection_model().Equals(old_model)) {
1315 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1316 TabSelectionChanged(this, old_model));
1320 void TabStripModel::SetSelection(
1321 const ui::ListSelectionModel& new_model,
1322 NotifyTypes notify_types) {
1323 WebContents* old_contents = GetActiveWebContents();
1324 ui::ListSelectionModel old_model;
1325 old_model.Copy(selection_model_);
1326 if (new_model.active() != selection_model_.active())
1327 NotifyIfTabDeactivated(old_contents);
1328 selection_model_.Copy(new_model);
1329 NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model);
1332 void TabStripModel::SelectRelativeTab(bool next) {
1333 // This may happen during automated testing or if a user somehow buffers
1334 // many key accelerators.
1335 if (contents_data_.empty())
1338 int index = active_index();
1339 int delta = next ? 1 : -1;
1340 index = (index + count() + delta) % count();
1341 ActivateTabAt(index, true);
1344 void TabStripModel::MoveWebContentsAtImpl(int index,
1346 bool select_after_move) {
1347 WebContentsData* moved_data = contents_data_[index];
1348 contents_data_.erase(contents_data_.begin() + index);
1349 contents_data_.insert(contents_data_.begin() + to_position, moved_data);
1351 selection_model_.Move(index, to_position);
1352 if (!selection_model_.IsSelected(select_after_move) && select_after_move) {
1353 // TODO(sky): why doesn't this code notify observers?
1354 selection_model_.SetSelectedIndex(to_position);
1357 ForgetOpenersAndGroupsReferencing(moved_data->web_contents());
1359 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1360 TabMoved(moved_data->web_contents(), index, to_position));
1363 void TabStripModel::MoveSelectedTabsToImpl(int index,
1366 DCHECK(start < selection_model_.selected_indices().size() &&
1367 start + length <= selection_model_.selected_indices().size());
1368 size_t end = start + length;
1369 int count_before_index = 0;
1370 for (size_t i = start; i < end &&
1371 selection_model_.selected_indices()[i] < index + count_before_index;
1373 count_before_index++;
1376 // First move those before index. Any tabs before index end up moving in the
1377 // selection model so we use start each time through.
1378 int target_index = index + count_before_index;
1379 size_t tab_index = start;
1380 while (tab_index < end &&
1381 selection_model_.selected_indices()[start] < index) {
1382 MoveWebContentsAt(selection_model_.selected_indices()[start],
1383 target_index - 1, false);
1387 // Then move those after the index. These don't result in reordering the
1389 while (tab_index < end) {
1390 if (selection_model_.selected_indices()[tab_index] != target_index) {
1391 MoveWebContentsAt(selection_model_.selected_indices()[tab_index],
1392 target_index, false);
1400 bool TabStripModel::OpenerMatches(const WebContentsData* data,
1401 const WebContents* opener,
1403 return data->opener() == opener || (use_group && data->group() == opener);
1406 void TabStripModel::ForgetOpenersAndGroupsReferencing(
1407 const WebContents* tab) {
1408 for (WebContentsDataVector::const_iterator i = contents_data_.begin();
1409 i != contents_data_.end(); ++i) {
1410 if ((*i)->group() == tab)
1411 (*i)->set_group(NULL);
1412 if ((*i)->opener() == tab)
1413 (*i)->set_opener(NULL);