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/popup_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 // TODO(gbillock): Ask the bubble manager whether the WebContents should be
319 // blocked, or just let the bubble manager make the blocking call directly
320 // and not use this at all.
321 web_modal::PopupManager* popup_manager =
322 web_modal::PopupManager::FromWebContents(contents);
324 data->set_blocked(popup_manager->IsWebModalDialogActive(contents));
326 contents_data_.insert(contents_data_.begin() + index, data);
328 selection_model_.IncrementFrom(index);
330 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
331 TabInsertedAt(contents, index, active));
333 ui::ListSelectionModel new_model;
334 new_model.Copy(selection_model_);
335 new_model.SetSelectedIndex(index);
336 SetSelection(new_model, NOTIFY_DEFAULT);
340 WebContents* TabStripModel::ReplaceWebContentsAt(int index,
341 WebContents* new_contents) {
342 delegate_->WillAddWebContents(new_contents);
344 DCHECK(ContainsIndex(index));
345 WebContents* old_contents = GetWebContentsAtImpl(index);
347 ForgetOpenersAndGroupsReferencing(old_contents);
349 contents_data_[index]->SetWebContents(new_contents);
351 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
352 TabReplacedAt(this, old_contents, new_contents, index));
354 // When the active WebContents is replaced send out a selection notification
355 // too. We do this as nearly all observers need to treat a replacement of the
356 // selected contents as the selection changing.
357 if (active_index() == index) {
359 TabStripModelObserver,
361 ActiveTabChanged(old_contents,
364 TabStripModelObserver::CHANGE_REASON_REPLACED));
369 WebContents* TabStripModel::DiscardWebContentsAt(int index) {
370 DCHECK(ContainsIndex(index));
371 // Do not discard active tab.
372 if (active_index() == index)
375 WebContents* null_contents =
376 WebContents::Create(WebContents::CreateParams(profile()));
377 WebContents* old_contents = GetWebContentsAtImpl(index);
378 // Copy over the state from the navigation controller so we preserve the
379 // back/forward history and continue to display the correct title/favicon.
380 null_contents->GetController().CopyStateFrom(old_contents->GetController());
381 // Replace the tab we're discarding with the null version.
382 ReplaceWebContentsAt(index, null_contents);
383 // Mark the tab so it will reload when we click.
384 contents_data_[index]->set_discarded(true);
385 // Discard the old tab's renderer.
386 // TODO(jamescook): This breaks script connections with other tabs.
387 // We need to find a different approach that doesn't do that, perhaps based
388 // on navigation to swappedout://.
390 return null_contents;
393 WebContents* TabStripModel::DetachWebContentsAt(int index) {
395 if (contents_data_.empty())
398 DCHECK(ContainsIndex(index));
400 WebContents* removed_contents = GetWebContentsAtImpl(index);
401 bool was_selected = IsTabSelected(index);
402 int next_selected_index = order_controller_->DetermineNewSelectedIndex(index);
403 delete contents_data_[index];
404 contents_data_.erase(contents_data_.begin() + index);
405 ForgetOpenersAndGroupsReferencing(removed_contents);
408 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
409 TabDetachedAt(removed_contents, index));
411 selection_model_.Clear();
412 // TabDetachedAt() might unregister observers, so send |TabStripEmpty()| in
414 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty());
416 int old_active = active_index();
417 selection_model_.DecrementFrom(index);
418 ui::ListSelectionModel old_model;
419 old_model.Copy(selection_model_);
420 if (index == old_active) {
421 NotifyIfTabDeactivated(removed_contents);
422 if (!selection_model_.empty()) {
423 // The active tab was removed, but there is still something selected.
424 // Move the active and anchor to the first selected index.
425 selection_model_.set_active(selection_model_.selected_indices()[0]);
426 selection_model_.set_anchor(selection_model_.active());
428 // The active tab was removed and nothing is selected. Reset the
429 // selection and send out notification.
430 selection_model_.SetSelectedIndex(next_selected_index);
432 NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT);
435 // Sending notification in case the detached tab was selected. Using
436 // NotifyIfActiveOrSelectionChanged() here would not guarantee that a
437 // notification is sent even though the tab selection has changed because
438 // |old_model| is stored after calling DecrementFrom().
440 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
441 TabSelectionChanged(this, old_model));
444 return removed_contents;
447 void TabStripModel::ActivateTabAt(int index, bool user_gesture) {
448 DCHECK(ContainsIndex(index));
449 ui::ListSelectionModel new_model;
450 new_model.Copy(selection_model_);
451 new_model.SetSelectedIndex(index);
452 SetSelection(new_model, user_gesture ? NOTIFY_USER_GESTURE : NOTIFY_DEFAULT);
455 void TabStripModel::AddTabAtToSelection(int index) {
456 DCHECK(ContainsIndex(index));
457 ui::ListSelectionModel new_model;
458 new_model.Copy(selection_model_);
459 new_model.AddIndexToSelection(index);
460 SetSelection(new_model, NOTIFY_DEFAULT);
463 void TabStripModel::MoveWebContentsAt(int index,
465 bool select_after_move) {
466 DCHECK(ContainsIndex(index));
467 if (index == to_position)
470 int first_non_mini_tab = IndexOfFirstNonMiniTab();
471 if ((index < first_non_mini_tab && to_position >= first_non_mini_tab) ||
472 (to_position < first_non_mini_tab && index >= first_non_mini_tab)) {
473 // This would result in mini tabs mixed with non-mini tabs. We don't allow
478 MoveWebContentsAtImpl(index, to_position, select_after_move);
481 void TabStripModel::MoveSelectedTabsTo(int index) {
482 int total_mini_count = IndexOfFirstNonMiniTab();
483 int selected_mini_count = 0;
485 static_cast<int>(selection_model_.selected_indices().size());
486 for (int i = 0; i < selected_count &&
487 IsMiniTab(selection_model_.selected_indices()[i]); ++i) {
488 selected_mini_count++;
491 // To maintain that all mini-tabs occur before non-mini-tabs we move them
493 if (selected_mini_count > 0) {
494 MoveSelectedTabsToImpl(
495 std::min(total_mini_count - selected_mini_count, index), 0u,
496 selected_mini_count);
497 if (index > total_mini_count - selected_mini_count) {
498 // We're being told to drag mini-tabs to an invalid location. Adjust the
499 // index such that non-mini-tabs end up at a location as though we could
500 // move the mini-tabs to index. See description in header for more
502 index += selected_mini_count;
505 if (selected_mini_count == selected_count)
508 // Then move the non-pinned tabs.
509 MoveSelectedTabsToImpl(std::max(index, total_mini_count),
511 selected_count - selected_mini_count);
514 WebContents* TabStripModel::GetActiveWebContents() const {
515 return GetWebContentsAt(active_index());
518 WebContents* TabStripModel::GetWebContentsAt(int index) const {
519 if (ContainsIndex(index))
520 return GetWebContentsAtImpl(index);
524 int TabStripModel::GetIndexOfWebContents(const WebContents* contents) const {
525 for (size_t i = 0; i < contents_data_.size(); ++i) {
526 if (contents_data_[i]->web_contents() == contents)
532 void TabStripModel::UpdateWebContentsStateAt(int index,
533 TabStripModelObserver::TabChangeType change_type) {
534 DCHECK(ContainsIndex(index));
536 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
537 TabChangedAt(GetWebContentsAtImpl(index), index, change_type));
540 void TabStripModel::CloseAllTabs() {
541 // Set state so that observers can adjust their behavior to suit this
542 // specific condition when CloseWebContentsAt causes a flurry of
543 // Close/Detach/Select notifications to be sent.
545 std::vector<int> closing_tabs;
546 for (int i = count() - 1; i >= 0; --i)
547 closing_tabs.push_back(i);
548 InternalCloseTabs(closing_tabs, CLOSE_CREATE_HISTORICAL_TAB);
551 bool TabStripModel::CloseWebContentsAt(int index, uint32 close_types) {
552 DCHECK(ContainsIndex(index));
553 std::vector<int> closing_tabs;
554 closing_tabs.push_back(index);
555 return InternalCloseTabs(closing_tabs, close_types);
558 bool TabStripModel::TabsAreLoading() const {
559 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
560 iter != contents_data_.end(); ++iter) {
561 if ((*iter)->web_contents()->IsLoading())
567 WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) {
568 DCHECK(ContainsIndex(index));
569 return contents_data_[index]->opener();
572 void TabStripModel::SetOpenerOfWebContentsAt(int index,
573 WebContents* opener) {
574 DCHECK(ContainsIndex(index));
576 contents_data_[index]->set_opener(opener);
579 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener,
581 bool use_group) const {
583 DCHECK(ContainsIndex(start_index));
585 // Check tabs after start_index first.
586 for (int i = start_index + 1; i < count(); ++i) {
587 if (OpenerMatches(contents_data_[i], opener, use_group))
590 // Then check tabs before start_index, iterating backwards.
591 for (int i = start_index - 1; i >= 0; --i) {
592 if (OpenerMatches(contents_data_[i], opener, use_group))
598 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
599 int start_index) const {
601 DCHECK(ContainsIndex(start_index));
603 for (int i = contents_data_.size() - 1; i > start_index; --i) {
604 if (contents_data_[i]->opener() == opener)
610 void TabStripModel::TabNavigating(WebContents* contents,
611 content::PageTransition transition) {
612 if (ShouldForgetOpenersForTransition(transition)) {
613 // Don't forget the openers if this tab is a New Tab page opened at the
614 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
615 // navigation of one of these transition types before resetting the
616 // opener relationships (this allows for the use case of opening a new
617 // tab to do a quick look-up of something while viewing a tab earlier in
618 // the strip). We can make this heuristic more permissive if need be.
619 if (!IsNewTabAtEndOfTabStrip(contents)) {
620 // If the user navigates the current tab to another page in any way
621 // other than by clicking a link, we want to pro-actively forget all
622 // TabStrip opener relationships since we assume they're beginning a
623 // different task by reusing the current tab.
625 // In this specific case we also want to reset the group relationship,
626 // since it is now technically invalid.
627 ForgetGroup(contents);
632 void TabStripModel::ForgetAllOpeners() {
633 // Forget all opener memories so we don't do anything weird with tab
634 // re-selection ordering.
635 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
636 iter != contents_data_.end(); ++iter)
637 (*iter)->set_opener(NULL);
640 void TabStripModel::ForgetGroup(WebContents* contents) {
641 int index = GetIndexOfWebContents(contents);
642 DCHECK(ContainsIndex(index));
643 contents_data_[index]->set_group(NULL);
644 contents_data_[index]->set_opener(NULL);
647 bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const {
648 int index = GetIndexOfWebContents(contents);
649 DCHECK(ContainsIndex(index));
650 return contents_data_[index]->reset_group_on_select();
653 void TabStripModel::SetTabBlocked(int index, bool blocked) {
654 DCHECK(ContainsIndex(index));
655 if (contents_data_[index]->blocked() == blocked)
657 contents_data_[index]->set_blocked(blocked);
659 TabStripModelObserver, observers_,
660 TabBlockedStateChanged(contents_data_[index]->web_contents(),
664 void TabStripModel::SetTabPinned(int index, bool pinned) {
665 DCHECK(ContainsIndex(index));
666 if (contents_data_[index]->pinned() == pinned)
669 if (IsAppTab(index)) {
671 // App tabs should always be pinned.
675 // Changing the pinned state of an app tab doesn't affect its mini-tab
677 contents_data_[index]->set_pinned(pinned);
679 // The tab is not an app tab, its position may have to change as the
680 // mini-tab state is changing.
681 int non_mini_tab_index = IndexOfFirstNonMiniTab();
682 contents_data_[index]->set_pinned(pinned);
683 if (pinned && index != non_mini_tab_index) {
684 MoveWebContentsAtImpl(index, non_mini_tab_index, false);
685 index = non_mini_tab_index;
686 } else if (!pinned && index + 1 != non_mini_tab_index) {
687 MoveWebContentsAtImpl(index, non_mini_tab_index - 1, false);
688 index = non_mini_tab_index - 1;
691 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
692 TabMiniStateChanged(contents_data_[index]->web_contents(),
696 // else: the tab was at the boundary and its position doesn't need to change.
697 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
698 TabPinnedStateChanged(contents_data_[index]->web_contents(),
702 bool TabStripModel::IsTabPinned(int index) const {
703 DCHECK(ContainsIndex(index));
704 return contents_data_[index]->pinned();
707 bool TabStripModel::IsMiniTab(int index) const {
708 return IsTabPinned(index) || IsAppTab(index);
711 bool TabStripModel::IsAppTab(int index) const {
712 WebContents* contents = GetWebContentsAt(index);
713 return contents && extensions::TabHelper::FromWebContents(contents)->is_app();
716 bool TabStripModel::IsTabBlocked(int index) const {
717 return contents_data_[index]->blocked();
720 bool TabStripModel::IsTabDiscarded(int index) const {
721 return contents_data_[index]->discarded();
724 int TabStripModel::IndexOfFirstNonMiniTab() const {
725 for (size_t i = 0; i < contents_data_.size(); ++i) {
726 if (!IsMiniTab(static_cast<int>(i)))
727 return static_cast<int>(i);
733 int TabStripModel::ConstrainInsertionIndex(int index, bool mini_tab) {
734 return mini_tab ? std::min(std::max(0, index), IndexOfFirstNonMiniTab()) :
735 std::min(count(), std::max(index, IndexOfFirstNonMiniTab()));
738 void TabStripModel::ExtendSelectionTo(int index) {
739 DCHECK(ContainsIndex(index));
740 ui::ListSelectionModel new_model;
741 new_model.Copy(selection_model_);
742 new_model.SetSelectionFromAnchorTo(index);
743 SetSelection(new_model, NOTIFY_DEFAULT);
746 void TabStripModel::ToggleSelectionAt(int index) {
747 DCHECK(ContainsIndex(index));
748 ui::ListSelectionModel new_model;
749 new_model.Copy(selection_model());
750 if (selection_model_.IsSelected(index)) {
751 if (selection_model_.size() == 1) {
752 // One tab must be selected and this tab is currently selected so we can't
756 new_model.RemoveIndexFromSelection(index);
757 new_model.set_anchor(index);
758 if (new_model.active() == index ||
759 new_model.active() == ui::ListSelectionModel::kUnselectedIndex)
760 new_model.set_active(new_model.selected_indices()[0]);
762 new_model.AddIndexToSelection(index);
763 new_model.set_anchor(index);
764 new_model.set_active(index);
766 SetSelection(new_model, NOTIFY_DEFAULT);
769 void TabStripModel::AddSelectionFromAnchorTo(int index) {
770 ui::ListSelectionModel new_model;
771 new_model.Copy(selection_model_);
772 new_model.AddSelectionFromAnchorTo(index);
773 SetSelection(new_model, NOTIFY_DEFAULT);
776 bool TabStripModel::IsTabSelected(int index) const {
777 DCHECK(ContainsIndex(index));
778 return selection_model_.IsSelected(index);
781 void TabStripModel::SetSelectionFromModel(
782 const ui::ListSelectionModel& source) {
783 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
784 SetSelection(source, NOTIFY_DEFAULT);
787 void TabStripModel::AddWebContents(WebContents* contents,
789 content::PageTransition transition,
791 // If the newly-opened tab is part of the same task as the parent tab, we want
792 // to inherit the parent's "group" attribute, so that if this tab is then
793 // closed we'll jump back to the parent tab.
794 bool inherit_group = (add_types & ADD_INHERIT_GROUP) == ADD_INHERIT_GROUP;
796 if (transition == content::PAGE_TRANSITION_LINK &&
797 (add_types & ADD_FORCE_INDEX) == 0) {
798 // We assume tabs opened via link clicks are part of the same task as their
799 // parent. Note that when |force_index| is true (e.g. when the user
800 // drag-and-drops a link to the tab strip), callers aren't really handling
801 // link clicks, they just want to score the navigation like a link click in
802 // the history backend, so we don't inherit the group in this case.
803 index = order_controller_->DetermineInsertionIndex(transition,
804 add_types & ADD_ACTIVE);
805 inherit_group = true;
807 // For all other types, respect what was passed to us, normalizing -1s and
808 // values that are too large.
809 if (index < 0 || index > count())
813 if (transition == content::PAGE_TRANSITION_TYPED && index == count()) {
814 // Also, any tab opened at the end of the TabStrip with a "TYPED"
815 // transition inherit group as well. This covers the cases where the user
816 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
817 // in the address bar and presses Alt+Enter. This allows for opening a new
818 // Tab to quickly look up something. When this Tab is closed, the old one
819 // is re-selected, not the next-adjacent.
820 inherit_group = true;
822 InsertWebContentsAt(index, contents,
823 add_types | (inherit_group ? ADD_INHERIT_GROUP : 0));
824 // Reset the index, just in case insert ended up moving it on us.
825 index = GetIndexOfWebContents(contents);
827 if (inherit_group && transition == content::PAGE_TRANSITION_TYPED)
828 contents_data_[index]->set_reset_group_on_select(true);
830 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
831 // here we seem to get failures in startup perf tests.
832 // Ensure that the new WebContentsView begins at the same size as the
833 // previous WebContentsView if it existed. Otherwise, the initial WebKit
834 // layout will be performed based on a width of 0 pixels, causing a
835 // very long, narrow, inaccurate layout. Because some scripts on pages (as
836 // well as WebKit's anchor link location calculation) are run on the
837 // initial layout and not recalculated later, we need to ensure the first
838 // layout is performed with sane view dimensions even when we're opening a
839 // new background tab.
840 if (WebContents* old_contents = GetActiveWebContents()) {
841 if ((add_types & ADD_ACTIVE) == 0) {
842 apps::ResizeWebContents(contents,
843 old_contents->GetContainerBounds().size());
848 void TabStripModel::CloseSelectedTabs() {
849 InternalCloseTabs(selection_model_.selected_indices(),
850 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
853 void TabStripModel::SelectNextTab() {
854 SelectRelativeTab(true);
857 void TabStripModel::SelectPreviousTab() {
858 SelectRelativeTab(false);
861 void TabStripModel::SelectLastTab() {
862 ActivateTabAt(count() - 1, true);
865 void TabStripModel::MoveTabNext() {
866 // TODO: this likely needs to be updated for multi-selection.
867 int new_index = std::min(active_index() + 1, count() - 1);
868 MoveWebContentsAt(active_index(), new_index, true);
871 void TabStripModel::MoveTabPrevious() {
872 // TODO: this likely needs to be updated for multi-selection.
873 int new_index = std::max(active_index() - 1, 0);
874 MoveWebContentsAt(active_index(), new_index, true);
877 // Context menu functions.
878 bool TabStripModel::IsContextMenuCommandEnabled(
879 int context_index, ContextMenuCommand command_id) const {
880 DCHECK(command_id > CommandFirst && command_id < CommandLast);
881 switch (command_id) {
883 case CommandCloseTab:
886 case CommandReload: {
887 std::vector<int> indices = GetIndicesForCommand(context_index);
888 for (size_t i = 0; i < indices.size(); ++i) {
889 WebContents* tab = GetWebContentsAt(indices[i]);
891 CoreTabHelperDelegate* core_delegate =
892 CoreTabHelper::FromWebContents(tab)->delegate();
893 if (!core_delegate || core_delegate->CanReloadContents(tab))
900 case CommandCloseOtherTabs:
901 case CommandCloseTabsToRight:
902 return !GetIndicesClosedByCommand(context_index, command_id).empty();
904 case CommandDuplicate: {
905 std::vector<int> indices = GetIndicesForCommand(context_index);
906 for (size_t i = 0; i < indices.size(); ++i) {
907 if (delegate_->CanDuplicateContentsAt(indices[i]))
913 case CommandRestoreTab:
914 return delegate_->GetRestoreTabType() !=
915 TabStripModelDelegate::RESTORE_NONE;
917 case CommandTogglePinned: {
918 std::vector<int> indices = GetIndicesForCommand(context_index);
919 for (size_t i = 0; i < indices.size(); ++i) {
920 if (!IsAppTab(indices[i]))
926 case CommandBookmarkAllTabs:
927 return browser_defaults::bookmarks_enabled &&
928 delegate_->CanBookmarkAllTabs();
930 case CommandSelectByDomain:
931 case CommandSelectByOpener:
940 void TabStripModel::ExecuteContextMenuCommand(
941 int context_index, ContextMenuCommand command_id) {
942 DCHECK(command_id > CommandFirst && command_id < CommandLast);
943 switch (command_id) {
945 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
946 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
947 TabStripModel::NEW_TAB_CONTEXT_MENU,
948 TabStripModel::NEW_TAB_ENUM_COUNT);
949 delegate()->AddTabAt(GURL(), context_index + 1, true);
952 case CommandReload: {
953 content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
954 std::vector<int> indices = GetIndicesForCommand(context_index);
955 for (size_t i = 0; i < indices.size(); ++i) {
956 WebContents* tab = GetWebContentsAt(indices[i]);
958 CoreTabHelperDelegate* core_delegate =
959 CoreTabHelper::FromWebContents(tab)->delegate();
960 if (!core_delegate || core_delegate->CanReloadContents(tab))
961 tab->GetController().Reload(true);
967 case CommandDuplicate: {
968 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
969 std::vector<int> indices = GetIndicesForCommand(context_index);
970 // Copy the WebContents off as the indices will change as tabs are
972 std::vector<WebContents*> tabs;
973 for (size_t i = 0; i < indices.size(); ++i)
974 tabs.push_back(GetWebContentsAt(indices[i]));
975 for (size_t i = 0; i < tabs.size(); ++i) {
976 int index = GetIndexOfWebContents(tabs[i]);
977 if (index != -1 && delegate_->CanDuplicateContentsAt(index))
978 delegate_->DuplicateContentsAt(index);
983 case CommandCloseTab: {
984 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
985 InternalCloseTabs(GetIndicesForCommand(context_index),
986 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
990 case CommandCloseOtherTabs: {
991 content::RecordAction(
992 UserMetricsAction("TabContextMenu_CloseOtherTabs"));
993 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
994 CLOSE_CREATE_HISTORICAL_TAB);
998 case CommandCloseTabsToRight: {
999 content::RecordAction(
1000 UserMetricsAction("TabContextMenu_CloseTabsToRight"));
1001 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1002 CLOSE_CREATE_HISTORICAL_TAB);
1006 case CommandRestoreTab: {
1007 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1008 delegate_->RestoreTab();
1012 case CommandTogglePinned: {
1013 content::RecordAction(
1014 UserMetricsAction("TabContextMenu_TogglePinned"));
1015 std::vector<int> indices = GetIndicesForCommand(context_index);
1016 bool pin = WillContextMenuPin(context_index);
1018 for (size_t i = 0; i < indices.size(); ++i) {
1019 if (!IsAppTab(indices[i]))
1020 SetTabPinned(indices[i], true);
1023 // Unpin from the back so that the order is maintained (unpinning can
1024 // trigger moving a tab).
1025 for (size_t i = indices.size(); i > 0; --i) {
1026 if (!IsAppTab(indices[i - 1]))
1027 SetTabPinned(indices[i - 1], false);
1033 case CommandBookmarkAllTabs: {
1034 content::RecordAction(
1035 UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1037 delegate_->BookmarkAllTabs();
1041 case CommandSelectByDomain:
1042 case CommandSelectByOpener: {
1043 std::vector<int> indices;
1044 if (command_id == CommandSelectByDomain)
1045 GetIndicesWithSameDomain(context_index, &indices);
1047 GetIndicesWithSameOpener(context_index, &indices);
1048 ui::ListSelectionModel selection_model;
1049 selection_model.SetSelectedIndex(context_index);
1050 for (size_t i = 0; i < indices.size(); ++i)
1051 selection_model.AddIndexToSelection(indices[i]);
1052 SetSelectionFromModel(selection_model);
1061 std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1063 ContextMenuCommand id) const {
1064 DCHECK(ContainsIndex(index));
1065 DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1066 bool is_selected = IsTabSelected(index);
1068 if (id == CommandCloseTabsToRight) {
1070 start = selection_model_.selected_indices()[
1071 selection_model_.selected_indices().size() - 1] + 1;
1078 // NOTE: callers expect the vector to be sorted in descending order.
1079 std::vector<int> indices;
1080 for (int i = count() - 1; i >= start; --i) {
1081 if (i != index && !IsMiniTab(i) && (!is_selected || !IsTabSelected(i)))
1082 indices.push_back(i);
1087 bool TabStripModel::WillContextMenuPin(int index) {
1088 std::vector<int> indices = GetIndicesForCommand(index);
1089 // If all tabs are pinned, then we unpin, otherwise we pin.
1090 bool all_pinned = true;
1091 for (size_t i = 0; i < indices.size() && all_pinned; ++i) {
1092 if (!IsAppTab(index)) // We never change app tabs.
1093 all_pinned = IsTabPinned(indices[i]);
1099 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1103 *browser_cmd = IDC_NEW_TAB;
1106 *browser_cmd = IDC_RELOAD;
1108 case CommandDuplicate:
1109 *browser_cmd = IDC_DUPLICATE_TAB;
1111 case CommandCloseTab:
1112 *browser_cmd = IDC_CLOSE_TAB;
1114 case CommandRestoreTab:
1115 *browser_cmd = IDC_RESTORE_TAB;
1117 case CommandBookmarkAllTabs:
1118 *browser_cmd = IDC_BOOKMARK_ALL_TABS;
1128 ///////////////////////////////////////////////////////////////////////////////
1129 // TabStripModel, private:
1131 std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices(
1132 const std::vector<int>& indices) const {
1133 std::vector<WebContents*> contents;
1134 for (size_t i = 0; i < indices.size(); ++i)
1135 contents.push_back(GetWebContentsAtImpl(indices[i]));
1139 void TabStripModel::GetIndicesWithSameDomain(int index,
1140 std::vector<int>* indices) {
1141 std::string domain = GetWebContentsAt(index)->GetURL().host();
1144 for (int i = 0; i < count(); ++i) {
1147 if (GetWebContentsAt(i)->GetURL().host() == domain)
1148 indices->push_back(i);
1152 void TabStripModel::GetIndicesWithSameOpener(int index,
1153 std::vector<int>* indices) {
1154 WebContents* opener = contents_data_[index]->group();
1156 // If there is no group, find all tabs with the selected tab as the opener.
1157 opener = GetWebContentsAt(index);
1161 for (int i = 0; i < count(); ++i) {
1164 if (contents_data_[i]->group() == opener ||
1165 GetWebContentsAtImpl(i) == opener) {
1166 indices->push_back(i);
1171 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1172 if (!IsTabSelected(index)) {
1173 std::vector<int> indices;
1174 indices.push_back(index);
1177 return selection_model_.selected_indices();
1180 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1181 const GURL& url = contents->GetURL();
1182 return url.SchemeIs(content::kChromeUIScheme) &&
1183 url.host() == chrome::kChromeUINewTabHost &&
1184 contents == GetWebContentsAtImpl(count() - 1) &&
1185 contents->GetController().GetEntryCount() == 1;
1188 bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
1189 uint32 close_types) {
1190 if (indices.empty())
1193 CloseTracker close_tracker(GetWebContentsFromIndices(indices));
1195 base::WeakPtr<TabStripModel> ref(weak_factory_.GetWeakPtr());
1196 const bool closing_all = indices.size() == contents_data_.size();
1198 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, WillCloseAllTabs());
1200 // We only try the fast shutdown path if the whole browser process is *not*
1201 // shutting down. Fast shutdown during browser termination is handled in
1203 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
1204 // Construct a map of processes to the number of associated tabs that are
1206 std::map<content::RenderProcessHost*, size_t> processes;
1207 for (size_t i = 0; i < indices.size(); ++i) {
1208 WebContents* closing_contents = GetWebContentsAtImpl(indices[i]);
1209 if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents))
1211 content::RenderProcessHost* process =
1212 closing_contents->GetRenderProcessHost();
1213 ++processes[process];
1216 // Try to fast shutdown the tabs that can close.
1217 for (std::map<content::RenderProcessHost*, size_t>::iterator iter =
1218 processes.begin(); iter != processes.end(); ++iter) {
1219 iter->first->FastShutdownForPageCount(iter->second);
1223 // We now return to our regularly scheduled shutdown procedure.
1225 while (close_tracker.HasNext()) {
1226 WebContents* closing_contents = close_tracker.Next();
1227 int index = GetIndexOfWebContents(closing_contents);
1228 // Make sure we still contain the tab.
1229 if (index == kNoTab)
1232 CoreTabHelper* core_tab_helper =
1233 CoreTabHelper::FromWebContents(closing_contents);
1234 core_tab_helper->OnCloseStarted();
1236 // Update the explicitly closed state. If the unload handlers cancel the
1237 // close the state is reset in Browser. We don't update the explicitly
1238 // closed state if already marked as explicitly closed as unload handlers
1239 // call back to this if the close is allowed.
1240 if (!closing_contents->GetClosedByUserGesture()) {
1241 closing_contents->SetClosedByUserGesture(
1242 close_types & CLOSE_USER_GESTURE);
1245 if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) {
1250 InternalCloseTab(closing_contents, index,
1251 (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
1254 if (ref && closing_all && !retval) {
1255 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1256 CloseAllTabsCanceled());
1262 void TabStripModel::InternalCloseTab(WebContents* contents,
1264 bool create_historical_tabs) {
1265 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1266 TabClosingAt(this, contents, index));
1268 // Ask the delegate to save an entry for this tab in the historical tab
1269 // database if applicable.
1270 if (create_historical_tabs)
1271 delegate_->CreateHistoricalTab(contents);
1273 // Deleting the WebContents will call back to us via
1274 // WebContentsData::WebContentsDestroyed and detach it.
1278 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1279 CHECK(ContainsIndex(index)) <<
1280 "Failed to find: " << index << " in: " << count() << " entries.";
1281 return contents_data_[index]->web_contents();
1284 void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) {
1286 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1287 TabDeactivated(contents));
1291 void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents,
1292 NotifyTypes notify_types) {
1293 WebContents* new_contents = GetWebContentsAtImpl(active_index());
1294 if (old_contents != new_contents) {
1295 int reason = notify_types == NOTIFY_USER_GESTURE
1296 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1297 : TabStripModelObserver::CHANGE_REASON_NONE;
1300 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1301 ActiveTabChanged(old_contents,
1306 // Activating a discarded tab reloads it, so it is no longer discarded.
1307 contents_data_[active_index()]->set_discarded(false);
1311 void TabStripModel::NotifyIfActiveOrSelectionChanged(
1312 WebContents* old_contents,
1313 NotifyTypes notify_types,
1314 const ui::ListSelectionModel& old_model) {
1315 NotifyIfActiveTabChanged(old_contents, notify_types);
1317 if (!selection_model().Equals(old_model)) {
1318 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1319 TabSelectionChanged(this, old_model));
1323 void TabStripModel::SetSelection(
1324 const ui::ListSelectionModel& new_model,
1325 NotifyTypes notify_types) {
1326 WebContents* old_contents = GetActiveWebContents();
1327 ui::ListSelectionModel old_model;
1328 old_model.Copy(selection_model_);
1329 if (new_model.active() != selection_model_.active())
1330 NotifyIfTabDeactivated(old_contents);
1331 selection_model_.Copy(new_model);
1332 NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model);
1335 void TabStripModel::SelectRelativeTab(bool next) {
1336 // This may happen during automated testing or if a user somehow buffers
1337 // many key accelerators.
1338 if (contents_data_.empty())
1341 int index = active_index();
1342 int delta = next ? 1 : -1;
1343 index = (index + count() + delta) % count();
1344 ActivateTabAt(index, true);
1347 void TabStripModel::MoveWebContentsAtImpl(int index,
1349 bool select_after_move) {
1350 WebContentsData* moved_data = contents_data_[index];
1351 contents_data_.erase(contents_data_.begin() + index);
1352 contents_data_.insert(contents_data_.begin() + to_position, moved_data);
1354 selection_model_.Move(index, to_position);
1355 if (!selection_model_.IsSelected(select_after_move) && select_after_move) {
1356 // TODO(sky): why doesn't this code notify observers?
1357 selection_model_.SetSelectedIndex(to_position);
1360 ForgetOpenersAndGroupsReferencing(moved_data->web_contents());
1362 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1363 TabMoved(moved_data->web_contents(), index, to_position));
1366 void TabStripModel::MoveSelectedTabsToImpl(int index,
1369 DCHECK(start < selection_model_.selected_indices().size() &&
1370 start + length <= selection_model_.selected_indices().size());
1371 size_t end = start + length;
1372 int count_before_index = 0;
1373 for (size_t i = start; i < end &&
1374 selection_model_.selected_indices()[i] < index + count_before_index;
1376 count_before_index++;
1379 // First move those before index. Any tabs before index end up moving in the
1380 // selection model so we use start each time through.
1381 int target_index = index + count_before_index;
1382 size_t tab_index = start;
1383 while (tab_index < end &&
1384 selection_model_.selected_indices()[start] < index) {
1385 MoveWebContentsAt(selection_model_.selected_indices()[start],
1386 target_index - 1, false);
1390 // Then move those after the index. These don't result in reordering the
1392 while (tab_index < end) {
1393 if (selection_model_.selected_indices()[tab_index] != target_index) {
1394 MoveWebContentsAt(selection_model_.selected_indices()[tab_index],
1395 target_index, false);
1403 bool TabStripModel::OpenerMatches(const WebContentsData* data,
1404 const WebContents* opener,
1406 return data->opener() == opener || (use_group && data->group() == opener);
1409 void TabStripModel::ForgetOpenersAndGroupsReferencing(
1410 const WebContents* tab) {
1411 for (WebContentsDataVector::const_iterator i = contents_data_.begin();
1412 i != contents_data_.end(); ++i) {
1413 if ((*i)->group() == tab)
1414 (*i)->set_group(NULL);
1415 if ((*i)->opener() == tab)
1416 (*i)->set_opener(NULL);