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"
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/browser/ui/tabs/tab_utils.h"
24 #include "chrome/browser/ui/web_contents_sizer.h"
25 #include "chrome/common/url_constants.h"
26 #include "components/web_modal/web_contents_modal_dialog_manager.h"
27 #include "content/public/browser/render_process_host.h"
28 #include "content/public/browser/user_metrics.h"
29 #include "content/public/browser/web_contents.h"
30 #include "content/public/browser/web_contents_observer.h"
31 using base::UserMetricsAction
;
32 using content::WebContents
;
36 // Enumeration for UMA tab discarding events.
37 enum UMATabDiscarding
{
38 UMA_TAB_DISCARDING_SWITCH_TO_LOADED_TAB
,
39 UMA_TAB_DISCARDING_SWITCH_TO_DISCARDED_TAB
,
40 UMA_TAB_DISCARDING_DISCARD_TAB
,
41 UMA_TAB_DISCARDING_DISCARD_TAB_AUDIO
,
42 UMA_TAB_DISCARDING_TAB_DISCARDING_MAX
45 // Records an UMA tab discarding event.
46 void RecordUMATabDiscarding(UMATabDiscarding event
) {
47 UMA_HISTOGRAM_ENUMERATION("Tab.Discarding", event
,
48 UMA_TAB_DISCARDING_TAB_DISCARDING_MAX
);
51 // Returns true if the specified transition is one of the types that cause the
52 // opener relationships for the tab in which the transition occurred to be
53 // forgotten. This is generally any navigation that isn't a link click (i.e.
54 // any navigation that can be considered to be the start of a new task distinct
55 // from what had previously occurred in that tab).
56 bool ShouldForgetOpenersForTransition(ui::PageTransition transition
) {
57 return transition
== ui::PAGE_TRANSITION_TYPED
||
58 transition
== ui::PAGE_TRANSITION_AUTO_BOOKMARK
||
59 transition
== ui::PAGE_TRANSITION_GENERATED
||
60 transition
== ui::PAGE_TRANSITION_KEYWORD
||
61 transition
== ui::PAGE_TRANSITION_AUTO_TOPLEVEL
;
64 // CloseTracker is used when closing a set of WebContents. It listens for
65 // deletions of the WebContents and removes from the internal set any time one
69 typedef std::vector
<WebContents
*> Contents
;
71 explicit CloseTracker(const Contents
& contents
);
72 virtual ~CloseTracker();
74 // Returns true if there is another WebContents in the Tracker.
77 // Returns the next WebContents, or NULL if there are no more.
81 class DeletionObserver
: public content::WebContentsObserver
{
83 DeletionObserver(CloseTracker
* parent
, WebContents
* web_contents
)
84 : WebContentsObserver(web_contents
),
89 // WebContentsObserver:
90 void WebContentsDestroyed() override
{
91 parent_
->OnWebContentsDestroyed(this);
94 CloseTracker
* parent_
;
96 DISALLOW_COPY_AND_ASSIGN(DeletionObserver
);
99 void OnWebContentsDestroyed(DeletionObserver
* observer
);
101 typedef std::vector
<DeletionObserver
*> Observers
;
102 Observers observers_
;
104 DISALLOW_COPY_AND_ASSIGN(CloseTracker
);
107 CloseTracker::CloseTracker(const Contents
& contents
) {
108 for (size_t i
= 0; i
< contents
.size(); ++i
)
109 observers_
.push_back(new DeletionObserver(this, contents
[i
]));
112 CloseTracker::~CloseTracker() {
113 DCHECK(observers_
.empty());
116 bool CloseTracker::HasNext() const {
117 return !observers_
.empty();
120 WebContents
* CloseTracker::Next() {
121 if (observers_
.empty())
124 DeletionObserver
* observer
= observers_
[0];
125 WebContents
* web_contents
= observer
->web_contents();
126 observers_
.erase(observers_
.begin());
131 void CloseTracker::OnWebContentsDestroyed(DeletionObserver
* observer
) {
132 Observers::iterator i
=
133 std::find(observers_
.begin(), observers_
.end(), observer
);
134 if (i
!= observers_
.end()) {
139 NOTREACHED() << "WebContents destroyed that wasn't in the list";
144 ///////////////////////////////////////////////////////////////////////////////
147 // An object to hold a reference to a WebContents that is in a tabstrip, as
148 // well as other various properties it has.
149 class TabStripModel::WebContentsData
: public content::WebContentsObserver
{
151 WebContentsData(TabStripModel
* tab_strip_model
, WebContents
* a_contents
);
153 // Changes the WebContents that this WebContentsData tracks.
154 void SetWebContents(WebContents
* contents
);
155 WebContents
* web_contents() { return contents_
; }
157 // Create a relationship between this WebContentsData and other
158 // WebContentses. Used to identify which WebContents to select next after
160 WebContents
* group() const { return group_
; }
161 void set_group(WebContents
* value
) { group_
= value
; }
162 WebContents
* opener() const { return opener_
; }
163 void set_opener(WebContents
* value
) { opener_
= value
; }
165 // Alters the properties of the WebContents.
166 bool reset_group_on_select() const { return reset_group_on_select_
; }
167 void set_reset_group_on_select(bool value
) { reset_group_on_select_
= value
; }
168 bool pinned() const { return pinned_
; }
169 void set_pinned(bool value
) { pinned_
= value
; }
170 bool blocked() const { return blocked_
; }
171 void set_blocked(bool value
) { blocked_
= value
; }
172 bool discarded() const { return discarded_
; }
173 void set_discarded(bool value
) { discarded_
= value
; }
176 // Make sure that if someone deletes this WebContents out from under us, it
177 // is properly removed from the tab strip.
178 void WebContentsDestroyed() override
;
180 // Marks the tab as no longer discarded if it has been reloaded from another
181 // source (ie: context menu).
182 void DidStartLoading() override
;
184 // The WebContents being tracked by this WebContentsData. The
185 // WebContentsObserver does keep a reference, but when the WebContents is
186 // deleted, the WebContentsObserver reference is NULLed and thus inaccessible.
187 WebContents
* contents_
;
189 // The TabStripModel containing this WebContents.
190 TabStripModel
* tab_strip_model_
;
192 // The group is used to model a set of tabs spawned from a single parent
193 // tab. This value is preserved for a given tab as long as the tab remains
194 // navigated to the link it was initially opened at or some navigation from
195 // that page (i.e. if the user types or visits a bookmark or some other
196 // navigation within that tab, the group relationship is lost). This
197 // property can safely be used to implement features that depend on a
198 // logical group of related tabs.
201 // The owner models the same relationship as group, except it is more
202 // easily discarded, e.g. when the user switches to a tab not part of the
203 // same group. This property is used to determine what tab to select next
204 // when one is closed.
205 WebContents
* opener_
;
207 // True if our group should be reset the moment selection moves away from
208 // this tab. This is the case for tabs opened in the foreground at the end
209 // of the TabStrip while viewing another Tab. If these tabs are closed
210 // before selection moves elsewhere, their opener is selected. But if
211 // selection shifts to _any_ tab (including their opener), the group
212 // relationship is reset to avoid confusing close sequencing.
213 bool reset_group_on_select_
;
215 // Is the tab pinned?
218 // Is the tab interaction blocked by a modal dialog?
221 // Has the tab data been discarded to save memory?
224 DISALLOW_COPY_AND_ASSIGN(WebContentsData
);
227 TabStripModel::WebContentsData::WebContentsData(TabStripModel
* tab_strip_model
,
228 WebContents
* contents
)
229 : content::WebContentsObserver(contents
),
231 tab_strip_model_(tab_strip_model
),
234 reset_group_on_select_(false),
240 void TabStripModel::WebContentsData::SetWebContents(WebContents
* contents
) {
241 contents_
= contents
;
245 void TabStripModel::WebContentsData::WebContentsDestroyed() {
246 DCHECK_EQ(contents_
, web_contents());
248 // Note that we only detach the contents here, not close it - it's
249 // already been closed. We just want to undo our bookkeeping.
250 int index
= tab_strip_model_
->GetIndexOfWebContents(web_contents());
251 DCHECK_NE(TabStripModel::kNoTab
, index
);
252 tab_strip_model_
->DetachWebContentsAt(index
);
255 void TabStripModel::WebContentsData::DidStartLoading() {
256 set_discarded(false);
259 ///////////////////////////////////////////////////////////////////////////////
260 // TabStripModel, public:
262 TabStripModel::TabStripModel(TabStripModelDelegate
* delegate
, Profile
* profile
)
263 : delegate_(delegate
),
267 weak_factory_(this) {
269 order_controller_
.reset(new TabStripModelOrderController(this));
272 TabStripModel::~TabStripModel() {
273 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
274 TabStripModelDeleted());
275 STLDeleteElements(&contents_data_
);
276 order_controller_
.reset();
279 void TabStripModel::AddObserver(TabStripModelObserver
* observer
) {
280 observers_
.AddObserver(observer
);
283 void TabStripModel::RemoveObserver(TabStripModelObserver
* observer
) {
284 observers_
.RemoveObserver(observer
);
287 bool TabStripModel::ContainsIndex(int index
) const {
288 return index
>= 0 && index
< count();
291 void TabStripModel::AppendWebContents(WebContents
* contents
,
293 InsertWebContentsAt(count(), contents
,
294 foreground
? (ADD_INHERIT_GROUP
| ADD_ACTIVE
) :
298 void TabStripModel::InsertWebContentsAt(int index
,
299 WebContents
* contents
,
301 delegate_
->WillAddWebContents(contents
);
303 bool active
= (add_types
& ADD_ACTIVE
) != 0;
304 bool pin
= (add_types
& ADD_PINNED
) != 0;
305 index
= ConstrainInsertionIndex(index
, pin
);
307 // In tab dragging situations, if the last tab in the window was detached
308 // then the user aborted the drag, we will have the |closing_all_| member
309 // set (see DetachWebContentsAt) which will mess with our mojo here. We need
310 // to clear this bit.
311 closing_all_
= false;
313 // Have to get the active contents before we monkey with the contents
314 // otherwise we run into problems when we try to change the active contents
315 // since the old contents and the new contents will be the same...
316 WebContents
* active_contents
= GetActiveWebContents();
317 WebContentsData
* data
= new WebContentsData(this, contents
);
318 data
->set_pinned(pin
);
319 if ((add_types
& ADD_INHERIT_GROUP
) && active_contents
) {
321 // Forget any existing relationships, we don't want to make things too
322 // confusing by having multiple groups active at the same time.
325 // Anything opened by a link we deem to have an opener.
326 data
->set_group(active_contents
);
327 data
->set_opener(active_contents
);
328 } else if ((add_types
& ADD_INHERIT_OPENER
) && active_contents
) {
330 // Forget any existing relationships, we don't want to make things too
331 // confusing by having multiple groups active at the same time.
334 data
->set_opener(active_contents
);
337 // TODO(gbillock): Ask the modal dialog manager whether the WebContents should
338 // be blocked, or just let the modal dialog manager make the blocking call
339 // directly and not use this at all.
340 const web_modal::WebContentsModalDialogManager
* manager
=
341 web_modal::WebContentsModalDialogManager::FromWebContents(contents
);
343 data
->set_blocked(manager
->IsDialogActive());
345 contents_data_
.insert(contents_data_
.begin() + index
, data
);
347 selection_model_
.IncrementFrom(index
);
349 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
350 TabInsertedAt(contents
, index
, active
));
352 ui::ListSelectionModel new_model
;
353 new_model
.Copy(selection_model_
);
354 new_model
.SetSelectedIndex(index
);
355 SetSelection(new_model
, NOTIFY_DEFAULT
);
359 WebContents
* TabStripModel::ReplaceWebContentsAt(int index
,
360 WebContents
* new_contents
) {
361 delegate_
->WillAddWebContents(new_contents
);
363 DCHECK(ContainsIndex(index
));
364 WebContents
* old_contents
= GetWebContentsAtImpl(index
);
366 FixOpenersAndGroupsReferencing(index
);
368 contents_data_
[index
]->SetWebContents(new_contents
);
370 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
371 TabReplacedAt(this, old_contents
, new_contents
, index
));
373 // When the active WebContents is replaced send out a selection notification
374 // too. We do this as nearly all observers need to treat a replacement of the
375 // selected contents as the selection changing.
376 if (active_index() == index
) {
378 TabStripModelObserver
,
380 ActiveTabChanged(old_contents
,
383 TabStripModelObserver::CHANGE_REASON_REPLACED
));
388 WebContents
* TabStripModel::DiscardWebContentsAt(int index
) {
389 DCHECK(ContainsIndex(index
));
390 // Do not discard active tab.
391 if (active_index() == index
)
394 WebContents
* null_contents
=
395 WebContents::Create(WebContents::CreateParams(profile()));
396 WebContents
* old_contents
= GetWebContentsAtImpl(index
);
397 bool is_playing_audio
= old_contents
->WasRecentlyAudible();
398 // Copy over the state from the navigation controller so we preserve the
399 // back/forward history and continue to display the correct title/favicon.
400 null_contents
->GetController().CopyStateFrom(old_contents
->GetController());
402 // Make sure we persist the last active time property.
403 null_contents
->SetLastActiveTime(old_contents
->GetLastActiveTime());
405 // Replace the tab we're discarding with the null version.
406 ReplaceWebContentsAt(index
, null_contents
);
407 // Mark the tab so it will reload when we click.
408 if (!contents_data_
[index
]->discarded()) {
409 contents_data_
[index
]->set_discarded(true);
410 RecordUMATabDiscarding(UMA_TAB_DISCARDING_DISCARD_TAB
);
411 if (is_playing_audio
)
412 RecordUMATabDiscarding(UMA_TAB_DISCARDING_DISCARD_TAB_AUDIO
);
414 // Discard the old tab's renderer.
415 // TODO(jamescook): This breaks script connections with other tabs.
416 // We need to find a different approach that doesn't do that, perhaps based
417 // on navigation to swappedout://.
419 return null_contents
;
422 WebContents
* TabStripModel::DetachWebContentsAt(int index
) {
424 if (contents_data_
.empty())
426 DCHECK(ContainsIndex(index
));
428 FixOpenersAndGroupsReferencing(index
);
430 WebContents
* removed_contents
= GetWebContentsAtImpl(index
);
431 bool was_selected
= IsTabSelected(index
);
432 int next_selected_index
= order_controller_
->DetermineNewSelectedIndex(index
);
433 delete contents_data_
[index
];
434 contents_data_
.erase(contents_data_
.begin() + index
);
437 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
438 TabDetachedAt(removed_contents
, index
));
440 selection_model_
.Clear();
441 // TabDetachedAt() might unregister observers, so send |TabStripEmpty()| in
443 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
, TabStripEmpty());
445 int old_active
= active_index();
446 selection_model_
.DecrementFrom(index
);
447 ui::ListSelectionModel old_model
;
448 old_model
.Copy(selection_model_
);
449 if (index
== old_active
) {
450 NotifyIfTabDeactivated(removed_contents
);
451 if (!selection_model_
.empty()) {
452 // The active tab was removed, but there is still something selected.
453 // Move the active and anchor to the first selected index.
454 selection_model_
.set_active(selection_model_
.selected_indices()[0]);
455 selection_model_
.set_anchor(selection_model_
.active());
457 // The active tab was removed and nothing is selected. Reset the
458 // selection and send out notification.
459 selection_model_
.SetSelectedIndex(next_selected_index
);
461 NotifyIfActiveTabChanged(removed_contents
, NOTIFY_DEFAULT
);
464 // Sending notification in case the detached tab was selected. Using
465 // NotifyIfActiveOrSelectionChanged() here would not guarantee that a
466 // notification is sent even though the tab selection has changed because
467 // |old_model| is stored after calling DecrementFrom().
469 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
470 TabSelectionChanged(this, old_model
));
473 return removed_contents
;
476 void TabStripModel::ActivateTabAt(int index
, bool user_gesture
) {
477 DCHECK(ContainsIndex(index
));
478 ui::ListSelectionModel new_model
;
479 new_model
.Copy(selection_model_
);
480 new_model
.SetSelectedIndex(index
);
481 SetSelection(new_model
, user_gesture
? NOTIFY_USER_GESTURE
: NOTIFY_DEFAULT
);
484 void TabStripModel::AddTabAtToSelection(int index
) {
485 DCHECK(ContainsIndex(index
));
486 ui::ListSelectionModel new_model
;
487 new_model
.Copy(selection_model_
);
488 new_model
.AddIndexToSelection(index
);
489 SetSelection(new_model
, NOTIFY_DEFAULT
);
492 void TabStripModel::MoveWebContentsAt(int index
,
494 bool select_after_move
) {
495 DCHECK(ContainsIndex(index
));
496 if (index
== to_position
)
499 int first_non_pinned_tab
= IndexOfFirstNonPinnedTab();
500 if ((index
< first_non_pinned_tab
&& to_position
>= first_non_pinned_tab
) ||
501 (to_position
< first_non_pinned_tab
&& index
>= first_non_pinned_tab
)) {
502 // This would result in pinned tabs mixed with non-pinned tabs. We don't
507 MoveWebContentsAtImpl(index
, to_position
, select_after_move
);
510 void TabStripModel::MoveSelectedTabsTo(int index
) {
511 int total_pinned_count
= IndexOfFirstNonPinnedTab();
512 int selected_pinned_count
= 0;
514 static_cast<int>(selection_model_
.selected_indices().size());
515 for (int i
= 0; i
< selected_count
&&
516 IsTabPinned(selection_model_
.selected_indices()[i
]); ++i
) {
517 selected_pinned_count
++;
520 // To maintain that all pinned tabs occur before non-pinned tabs we move them
522 if (selected_pinned_count
> 0) {
523 MoveSelectedTabsToImpl(
524 std::min(total_pinned_count
- selected_pinned_count
, index
), 0u,
525 selected_pinned_count
);
526 if (index
> total_pinned_count
- selected_pinned_count
) {
527 // We're being told to drag pinned tabs to an invalid location. Adjust the
528 // index such that non-pinned tabs end up at a location as though we could
529 // move the pinned tabs to index. See description in header for more
531 index
+= selected_pinned_count
;
534 if (selected_pinned_count
== selected_count
)
537 // Then move the non-pinned tabs.
538 MoveSelectedTabsToImpl(std::max(index
, total_pinned_count
),
539 selected_pinned_count
,
540 selected_count
- selected_pinned_count
);
543 WebContents
* TabStripModel::GetActiveWebContents() const {
544 return GetWebContentsAt(active_index());
547 WebContents
* TabStripModel::GetWebContentsAt(int index
) const {
548 if (ContainsIndex(index
))
549 return GetWebContentsAtImpl(index
);
553 int TabStripModel::GetIndexOfWebContents(const WebContents
* contents
) const {
554 for (size_t i
= 0; i
< contents_data_
.size(); ++i
) {
555 if (contents_data_
[i
]->web_contents() == contents
)
561 void TabStripModel::UpdateWebContentsStateAt(int index
,
562 TabStripModelObserver::TabChangeType change_type
) {
563 DCHECK(ContainsIndex(index
));
565 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
566 TabChangedAt(GetWebContentsAtImpl(index
), index
, change_type
));
569 void TabStripModel::CloseAllTabs() {
570 // Set state so that observers can adjust their behavior to suit this
571 // specific condition when CloseWebContentsAt causes a flurry of
572 // Close/Detach/Select notifications to be sent.
574 std::vector
<int> closing_tabs
;
575 for (int i
= count() - 1; i
>= 0; --i
)
576 closing_tabs
.push_back(i
);
577 InternalCloseTabs(closing_tabs
, CLOSE_CREATE_HISTORICAL_TAB
);
580 bool TabStripModel::CloseWebContentsAt(int index
, uint32 close_types
) {
581 DCHECK(ContainsIndex(index
));
582 std::vector
<int> closing_tabs
;
583 closing_tabs
.push_back(index
);
584 return InternalCloseTabs(closing_tabs
, close_types
);
587 bool TabStripModel::TabsAreLoading() const {
588 for (WebContentsDataVector::const_iterator iter
= contents_data_
.begin();
589 iter
!= contents_data_
.end(); ++iter
) {
590 if ((*iter
)->web_contents()->IsLoading())
596 WebContents
* TabStripModel::GetOpenerOfWebContentsAt(int index
) {
597 DCHECK(ContainsIndex(index
));
598 return contents_data_
[index
]->opener();
601 void TabStripModel::SetOpenerOfWebContentsAt(int index
,
602 WebContents
* opener
) {
603 DCHECK(ContainsIndex(index
));
605 contents_data_
[index
]->set_opener(opener
);
608 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents
* opener
,
610 bool use_group
) const {
612 DCHECK(ContainsIndex(start_index
));
614 // Check tabs after start_index first.
615 for (int i
= start_index
+ 1; i
< count(); ++i
) {
616 if (OpenerMatches(contents_data_
[i
], opener
, use_group
))
619 // Then check tabs before start_index, iterating backwards.
620 for (int i
= start_index
- 1; i
>= 0; --i
) {
621 if (OpenerMatches(contents_data_
[i
], opener
, use_group
))
627 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents
* opener
,
628 int start_index
) const {
630 DCHECK(ContainsIndex(start_index
));
632 std::set
<const WebContents
*> opener_and_descendants
;
633 opener_and_descendants
.insert(opener
);
634 int last_index
= kNoTab
;
636 for (int i
= start_index
+ 1; i
< count(); ++i
) {
637 // Test opened by transitively, i.e. include tabs opened by tabs opened by
638 // opener, etc. Stop when we find the first non-descendant.
639 if (!opener_and_descendants
.count(contents_data_
[i
]->opener())) {
640 // Skip over pinned tabs as new tabs are added after pinned tabs.
641 if (contents_data_
[i
]->pinned())
645 opener_and_descendants
.insert(contents_data_
[i
]->web_contents());
651 void TabStripModel::TabNavigating(WebContents
* contents
,
652 ui::PageTransition transition
) {
653 if (ShouldForgetOpenersForTransition(transition
)) {
654 // Don't forget the openers if this tab is a New Tab page opened at the
655 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
656 // navigation of one of these transition types before resetting the
657 // opener relationships (this allows for the use case of opening a new
658 // tab to do a quick look-up of something while viewing a tab earlier in
659 // the strip). We can make this heuristic more permissive if need be.
660 if (!IsNewTabAtEndOfTabStrip(contents
)) {
661 // If the user navigates the current tab to another page in any way
662 // other than by clicking a link, we want to pro-actively forget all
663 // TabStrip opener relationships since we assume they're beginning a
664 // different task by reusing the current tab.
666 // In this specific case we also want to reset the group relationship,
667 // since it is now technically invalid.
668 ForgetGroup(contents
);
673 void TabStripModel::ForgetAllOpeners() {
674 // Forget all opener memories so we don't do anything weird with tab
675 // re-selection ordering.
676 for (WebContentsDataVector::const_iterator iter
= contents_data_
.begin();
677 iter
!= contents_data_
.end(); ++iter
)
678 (*iter
)->set_opener(NULL
);
681 void TabStripModel::ForgetGroup(WebContents
* contents
) {
682 int index
= GetIndexOfWebContents(contents
);
683 DCHECK(ContainsIndex(index
));
684 contents_data_
[index
]->set_group(NULL
);
685 contents_data_
[index
]->set_opener(NULL
);
688 bool TabStripModel::ShouldResetGroupOnSelect(WebContents
* contents
) const {
689 int index
= GetIndexOfWebContents(contents
);
690 DCHECK(ContainsIndex(index
));
691 return contents_data_
[index
]->reset_group_on_select();
694 void TabStripModel::SetTabBlocked(int index
, bool blocked
) {
695 DCHECK(ContainsIndex(index
));
696 if (contents_data_
[index
]->blocked() == blocked
)
698 contents_data_
[index
]->set_blocked(blocked
);
700 TabStripModelObserver
, observers_
,
701 TabBlockedStateChanged(contents_data_
[index
]->web_contents(),
705 void TabStripModel::SetTabPinned(int index
, bool pinned
) {
706 DCHECK(ContainsIndex(index
));
707 if (contents_data_
[index
]->pinned() == pinned
)
710 // The tab's position may have to change as the pinned tab state is changing.
711 int non_pinned_tab_index
= IndexOfFirstNonPinnedTab();
712 contents_data_
[index
]->set_pinned(pinned
);
713 if (pinned
&& index
!= non_pinned_tab_index
) {
714 MoveWebContentsAtImpl(index
, non_pinned_tab_index
, false);
715 index
= non_pinned_tab_index
;
716 } else if (!pinned
&& index
+ 1 != non_pinned_tab_index
) {
717 MoveWebContentsAtImpl(index
, non_pinned_tab_index
- 1, false);
718 index
= non_pinned_tab_index
- 1;
721 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
722 TabPinnedStateChanged(contents_data_
[index
]->web_contents(),
726 bool TabStripModel::IsTabPinned(int index
) const {
727 DCHECK(ContainsIndex(index
));
728 return contents_data_
[index
]->pinned();
731 bool TabStripModel::IsTabBlocked(int index
) const {
732 return contents_data_
[index
]->blocked();
735 bool TabStripModel::IsTabDiscarded(int index
) const {
736 return contents_data_
[index
]->discarded();
739 int TabStripModel::IndexOfFirstNonPinnedTab() const {
740 for (size_t i
= 0; i
< contents_data_
.size(); ++i
) {
741 if (!IsTabPinned(static_cast<int>(i
)))
742 return static_cast<int>(i
);
748 int TabStripModel::ConstrainInsertionIndex(int index
, bool pinned_tab
) {
749 return pinned_tab
? std::min(std::max(0, index
), IndexOfFirstNonPinnedTab()) :
750 std::min(count(), std::max(index
, IndexOfFirstNonPinnedTab()));
753 void TabStripModel::ExtendSelectionTo(int index
) {
754 DCHECK(ContainsIndex(index
));
755 ui::ListSelectionModel new_model
;
756 new_model
.Copy(selection_model_
);
757 new_model
.SetSelectionFromAnchorTo(index
);
758 SetSelection(new_model
, NOTIFY_DEFAULT
);
761 void TabStripModel::ToggleSelectionAt(int index
) {
762 DCHECK(ContainsIndex(index
));
763 ui::ListSelectionModel new_model
;
764 new_model
.Copy(selection_model());
765 if (selection_model_
.IsSelected(index
)) {
766 if (selection_model_
.size() == 1) {
767 // One tab must be selected and this tab is currently selected so we can't
771 new_model
.RemoveIndexFromSelection(index
);
772 new_model
.set_anchor(index
);
773 if (new_model
.active() == index
||
774 new_model
.active() == ui::ListSelectionModel::kUnselectedIndex
)
775 new_model
.set_active(new_model
.selected_indices()[0]);
777 new_model
.AddIndexToSelection(index
);
778 new_model
.set_anchor(index
);
779 new_model
.set_active(index
);
781 SetSelection(new_model
, NOTIFY_DEFAULT
);
784 void TabStripModel::AddSelectionFromAnchorTo(int index
) {
785 ui::ListSelectionModel new_model
;
786 new_model
.Copy(selection_model_
);
787 new_model
.AddSelectionFromAnchorTo(index
);
788 SetSelection(new_model
, NOTIFY_DEFAULT
);
791 bool TabStripModel::IsTabSelected(int index
) const {
792 DCHECK(ContainsIndex(index
));
793 return selection_model_
.IsSelected(index
);
796 void TabStripModel::SetSelectionFromModel(
797 const ui::ListSelectionModel
& source
) {
798 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex
, source
.active());
799 SetSelection(source
, NOTIFY_DEFAULT
);
802 void TabStripModel::AddWebContents(WebContents
* contents
,
804 ui::PageTransition transition
,
806 // If the newly-opened tab is part of the same task as the parent tab, we want
807 // to inherit the parent's "group" attribute, so that if this tab is then
808 // closed we'll jump back to the parent tab.
809 bool inherit_group
= (add_types
& ADD_INHERIT_GROUP
) == ADD_INHERIT_GROUP
;
811 if (transition
== ui::PAGE_TRANSITION_LINK
&&
812 (add_types
& ADD_FORCE_INDEX
) == 0) {
813 // We assume tabs opened via link clicks are part of the same task as their
814 // parent. Note that when |force_index| is true (e.g. when the user
815 // drag-and-drops a link to the tab strip), callers aren't really handling
816 // link clicks, they just want to score the navigation like a link click in
817 // the history backend, so we don't inherit the group in this case.
818 index
= order_controller_
->DetermineInsertionIndex(transition
,
819 add_types
& ADD_ACTIVE
);
820 inherit_group
= true;
822 // For all other types, respect what was passed to us, normalizing -1s and
823 // values that are too large.
824 if (index
< 0 || index
> count())
828 if (transition
== ui::PAGE_TRANSITION_TYPED
&& index
== count()) {
829 // Also, any tab opened at the end of the TabStrip with a "TYPED"
830 // transition inherit group as well. This covers the cases where the user
831 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
832 // in the address bar and presses Alt+Enter. This allows for opening a new
833 // Tab to quickly look up something. When this Tab is closed, the old one
834 // is re-selected, not the next-adjacent.
835 inherit_group
= true;
837 InsertWebContentsAt(index
, contents
,
838 add_types
| (inherit_group
? ADD_INHERIT_GROUP
: 0));
839 // Reset the index, just in case insert ended up moving it on us.
840 index
= GetIndexOfWebContents(contents
);
842 if (inherit_group
&& transition
== ui::PAGE_TRANSITION_TYPED
)
843 contents_data_
[index
]->set_reset_group_on_select(true);
845 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
846 // here we seem to get failures in startup perf tests.
847 // Ensure that the new WebContentsView begins at the same size as the
848 // previous WebContentsView if it existed. Otherwise, the initial WebKit
849 // layout will be performed based on a width of 0 pixels, causing a
850 // very long, narrow, inaccurate layout. Because some scripts on pages (as
851 // well as WebKit's anchor link location calculation) are run on the
852 // initial layout and not recalculated later, we need to ensure the first
853 // layout is performed with sane view dimensions even when we're opening a
854 // new background tab.
855 if (WebContents
* old_contents
= GetActiveWebContents()) {
856 if ((add_types
& ADD_ACTIVE
) == 0) {
857 ResizeWebContents(contents
, old_contents
->GetContainerBounds().size());
862 void TabStripModel::CloseSelectedTabs() {
863 InternalCloseTabs(selection_model_
.selected_indices(),
864 CLOSE_CREATE_HISTORICAL_TAB
| CLOSE_USER_GESTURE
);
867 void TabStripModel::SelectNextTab() {
868 SelectRelativeTab(true);
871 void TabStripModel::SelectPreviousTab() {
872 SelectRelativeTab(false);
875 void TabStripModel::SelectLastTab() {
876 ActivateTabAt(count() - 1, true);
879 void TabStripModel::MoveTabNext() {
880 // TODO: this likely needs to be updated for multi-selection.
881 int new_index
= std::min(active_index() + 1, count() - 1);
882 MoveWebContentsAt(active_index(), new_index
, true);
885 void TabStripModel::MoveTabPrevious() {
886 // TODO: this likely needs to be updated for multi-selection.
887 int new_index
= std::max(active_index() - 1, 0);
888 MoveWebContentsAt(active_index(), new_index
, true);
891 // Context menu functions.
892 bool TabStripModel::IsContextMenuCommandEnabled(
893 int context_index
, ContextMenuCommand command_id
) const {
894 DCHECK(command_id
> CommandFirst
&& command_id
< CommandLast
);
895 switch (command_id
) {
897 case CommandCloseTab
:
900 case CommandReload
: {
901 std::vector
<int> indices
= GetIndicesForCommand(context_index
);
902 for (size_t i
= 0; i
< indices
.size(); ++i
) {
903 WebContents
* tab
= GetWebContentsAt(indices
[i
]);
905 CoreTabHelperDelegate
* core_delegate
=
906 CoreTabHelper::FromWebContents(tab
)->delegate();
907 if (!core_delegate
|| core_delegate
->CanReloadContents(tab
))
914 case CommandCloseOtherTabs
:
915 case CommandCloseTabsToRight
:
916 return !GetIndicesClosedByCommand(context_index
, command_id
).empty();
918 case CommandDuplicate
: {
919 std::vector
<int> indices
= GetIndicesForCommand(context_index
);
920 for (size_t i
= 0; i
< indices
.size(); ++i
) {
921 if (delegate_
->CanDuplicateContentsAt(indices
[i
]))
927 case CommandRestoreTab
:
928 return delegate_
->GetRestoreTabType() !=
929 TabStripModelDelegate::RESTORE_NONE
;
931 case CommandToggleTabAudioMuted
: {
932 std::vector
<int> indices
= GetIndicesForCommand(context_index
);
933 for (size_t i
= 0; i
< indices
.size(); ++i
) {
934 if (!chrome::CanToggleAudioMute(GetWebContentsAt(indices
[i
])))
940 case CommandBookmarkAllTabs
:
941 return browser_defaults::bookmarks_enabled
&&
942 delegate_
->CanBookmarkAllTabs();
944 case CommandTogglePinned
:
945 case CommandSelectByDomain
:
946 case CommandSelectByOpener
:
955 void TabStripModel::ExecuteContextMenuCommand(
956 int context_index
, ContextMenuCommand command_id
) {
957 DCHECK(command_id
> CommandFirst
&& command_id
< CommandLast
);
958 switch (command_id
) {
960 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
961 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
962 TabStripModel::NEW_TAB_CONTEXT_MENU
,
963 TabStripModel::NEW_TAB_ENUM_COUNT
);
964 delegate()->AddTabAt(GURL(), context_index
+ 1, true);
967 case CommandReload
: {
968 content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
969 std::vector
<int> indices
= GetIndicesForCommand(context_index
);
970 for (size_t i
= 0; i
< indices
.size(); ++i
) {
971 WebContents
* tab
= GetWebContentsAt(indices
[i
]);
973 CoreTabHelperDelegate
* core_delegate
=
974 CoreTabHelper::FromWebContents(tab
)->delegate();
975 if (!core_delegate
|| core_delegate
->CanReloadContents(tab
))
976 tab
->GetController().Reload(true);
982 case CommandDuplicate
: {
983 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
984 std::vector
<int> indices
= GetIndicesForCommand(context_index
);
985 // Copy the WebContents off as the indices will change as tabs are
987 std::vector
<WebContents
*> tabs
;
988 for (size_t i
= 0; i
< indices
.size(); ++i
)
989 tabs
.push_back(GetWebContentsAt(indices
[i
]));
990 for (size_t i
= 0; i
< tabs
.size(); ++i
) {
991 int index
= GetIndexOfWebContents(tabs
[i
]);
992 if (index
!= -1 && delegate_
->CanDuplicateContentsAt(index
))
993 delegate_
->DuplicateContentsAt(index
);
998 case CommandCloseTab
: {
999 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
1000 InternalCloseTabs(GetIndicesForCommand(context_index
),
1001 CLOSE_CREATE_HISTORICAL_TAB
| CLOSE_USER_GESTURE
);
1005 case CommandCloseOtherTabs
: {
1006 content::RecordAction(
1007 UserMetricsAction("TabContextMenu_CloseOtherTabs"));
1008 InternalCloseTabs(GetIndicesClosedByCommand(context_index
, command_id
),
1009 CLOSE_CREATE_HISTORICAL_TAB
);
1013 case CommandCloseTabsToRight
: {
1014 content::RecordAction(
1015 UserMetricsAction("TabContextMenu_CloseTabsToRight"));
1016 InternalCloseTabs(GetIndicesClosedByCommand(context_index
, command_id
),
1017 CLOSE_CREATE_HISTORICAL_TAB
);
1021 case CommandRestoreTab
: {
1022 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1023 delegate_
->RestoreTab();
1027 case CommandTogglePinned
: {
1028 content::RecordAction(
1029 UserMetricsAction("TabContextMenu_TogglePinned"));
1030 std::vector
<int> indices
= GetIndicesForCommand(context_index
);
1031 bool pin
= WillContextMenuPin(context_index
);
1033 for (size_t i
= 0; i
< indices
.size(); ++i
)
1034 SetTabPinned(indices
[i
], true);
1036 // Unpin from the back so that the order is maintained (unpinning can
1037 // trigger moving a tab).
1038 for (size_t i
= indices
.size(); i
> 0; --i
)
1039 SetTabPinned(indices
[i
- 1], false);
1044 case CommandToggleTabAudioMuted
: {
1045 const std::vector
<int>& indices
= GetIndicesForCommand(context_index
);
1046 const bool mute
= !chrome::AreAllTabsMuted(*this, indices
);
1048 content::RecordAction(UserMetricsAction("TabContextMenu_MuteTabs"));
1050 content::RecordAction(UserMetricsAction("TabContextMenu_UnmuteTabs"));
1051 for (std::vector
<int>::const_iterator i
= indices
.begin();
1052 i
!= indices
.end(); ++i
) {
1053 chrome::SetTabAudioMuted(GetWebContentsAt(*i
), mute
,
1054 TAB_MUTED_REASON_CONTEXT_MENU
, std::string());
1059 case CommandBookmarkAllTabs
: {
1060 content::RecordAction(
1061 UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1063 delegate_
->BookmarkAllTabs();
1067 case CommandSelectByDomain
:
1068 case CommandSelectByOpener
: {
1069 std::vector
<int> indices
;
1070 if (command_id
== CommandSelectByDomain
)
1071 GetIndicesWithSameDomain(context_index
, &indices
);
1073 GetIndicesWithSameOpener(context_index
, &indices
);
1074 ui::ListSelectionModel selection_model
;
1075 selection_model
.SetSelectedIndex(context_index
);
1076 for (size_t i
= 0; i
< indices
.size(); ++i
)
1077 selection_model
.AddIndexToSelection(indices
[i
]);
1078 SetSelectionFromModel(selection_model
);
1087 std::vector
<int> TabStripModel::GetIndicesClosedByCommand(
1089 ContextMenuCommand id
) const {
1090 DCHECK(ContainsIndex(index
));
1091 DCHECK(id
== CommandCloseTabsToRight
|| id
== CommandCloseOtherTabs
);
1092 bool is_selected
= IsTabSelected(index
);
1094 if (id
== CommandCloseTabsToRight
) {
1096 start
= selection_model_
.selected_indices()[
1097 selection_model_
.selected_indices().size() - 1] + 1;
1104 // NOTE: callers expect the vector to be sorted in descending order.
1105 std::vector
<int> indices
;
1106 for (int i
= count() - 1; i
>= start
; --i
) {
1107 if (i
!= index
&& !IsTabPinned(i
) && (!is_selected
|| !IsTabSelected(i
)))
1108 indices
.push_back(i
);
1113 bool TabStripModel::WillContextMenuPin(int index
) {
1114 std::vector
<int> indices
= GetIndicesForCommand(index
);
1115 // If all tabs are pinned, then we unpin, otherwise we pin.
1116 bool all_pinned
= true;
1117 for (size_t i
= 0; i
< indices
.size() && all_pinned
; ++i
)
1118 all_pinned
= IsTabPinned(indices
[i
]);
1123 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id
,
1127 *browser_cmd
= IDC_NEW_TAB
;
1130 *browser_cmd
= IDC_RELOAD
;
1132 case CommandDuplicate
:
1133 *browser_cmd
= IDC_DUPLICATE_TAB
;
1135 case CommandCloseTab
:
1136 *browser_cmd
= IDC_CLOSE_TAB
;
1138 case CommandRestoreTab
:
1139 *browser_cmd
= IDC_RESTORE_TAB
;
1141 case CommandBookmarkAllTabs
:
1142 *browser_cmd
= IDC_BOOKMARK_ALL_TABS
;
1152 ///////////////////////////////////////////////////////////////////////////////
1153 // TabStripModel, private:
1155 std::vector
<WebContents
*> TabStripModel::GetWebContentsFromIndices(
1156 const std::vector
<int>& indices
) const {
1157 std::vector
<WebContents
*> contents
;
1158 for (size_t i
= 0; i
< indices
.size(); ++i
)
1159 contents
.push_back(GetWebContentsAtImpl(indices
[i
]));
1163 void TabStripModel::GetIndicesWithSameDomain(int index
,
1164 std::vector
<int>* indices
) {
1165 std::string domain
= GetWebContentsAt(index
)->GetURL().host();
1168 for (int i
= 0; i
< count(); ++i
) {
1171 if (GetWebContentsAt(i
)->GetURL().host() == domain
)
1172 indices
->push_back(i
);
1176 void TabStripModel::GetIndicesWithSameOpener(int index
,
1177 std::vector
<int>* indices
) {
1178 WebContents
* opener
= contents_data_
[index
]->group();
1180 // If there is no group, find all tabs with the selected tab as the opener.
1181 opener
= GetWebContentsAt(index
);
1185 for (int i
= 0; i
< count(); ++i
) {
1188 if (contents_data_
[i
]->group() == opener
||
1189 GetWebContentsAtImpl(i
) == opener
) {
1190 indices
->push_back(i
);
1195 std::vector
<int> TabStripModel::GetIndicesForCommand(int index
) const {
1196 if (!IsTabSelected(index
)) {
1197 std::vector
<int> indices
;
1198 indices
.push_back(index
);
1201 return selection_model_
.selected_indices();
1204 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents
* contents
) const {
1205 const GURL
& url
= contents
->GetURL();
1206 return url
.SchemeIs(content::kChromeUIScheme
) &&
1207 url
.host() == chrome::kChromeUINewTabHost
&&
1208 contents
== GetWebContentsAtImpl(count() - 1) &&
1209 contents
->GetController().GetEntryCount() == 1;
1212 bool TabStripModel::InternalCloseTabs(const std::vector
<int>& indices
,
1213 uint32 close_types
) {
1214 if (indices
.empty())
1217 CloseTracker
close_tracker(GetWebContentsFromIndices(indices
));
1219 base::WeakPtr
<TabStripModel
> ref(weak_factory_
.GetWeakPtr());
1220 const bool closing_all
= indices
.size() == contents_data_
.size();
1222 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
, WillCloseAllTabs());
1224 // We only try the fast shutdown path if the whole browser process is *not*
1225 // shutting down. Fast shutdown during browser termination is handled in
1227 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID
) {
1228 // Construct a map of processes to the number of associated tabs that are
1230 std::map
<content::RenderProcessHost
*, size_t> processes
;
1231 for (size_t i
= 0; i
< indices
.size(); ++i
) {
1232 WebContents
* closing_contents
= GetWebContentsAtImpl(indices
[i
]);
1233 if (delegate_
->ShouldRunUnloadListenerBeforeClosing(closing_contents
))
1235 content::RenderProcessHost
* process
=
1236 closing_contents
->GetRenderProcessHost();
1237 ++processes
[process
];
1240 // Try to fast shutdown the tabs that can close.
1241 for (std::map
<content::RenderProcessHost
*, size_t>::iterator iter
=
1242 processes
.begin(); iter
!= processes
.end(); ++iter
) {
1243 iter
->first
->FastShutdownForPageCount(iter
->second
);
1247 // We now return to our regularly scheduled shutdown procedure.
1249 while (close_tracker
.HasNext()) {
1250 WebContents
* closing_contents
= close_tracker
.Next();
1251 int index
= GetIndexOfWebContents(closing_contents
);
1252 // Make sure we still contain the tab.
1253 if (index
== kNoTab
)
1256 CoreTabHelper
* core_tab_helper
=
1257 CoreTabHelper::FromWebContents(closing_contents
);
1258 core_tab_helper
->OnCloseStarted();
1260 // Update the explicitly closed state. If the unload handlers cancel the
1261 // close the state is reset in Browser. We don't update the explicitly
1262 // closed state if already marked as explicitly closed as unload handlers
1263 // call back to this if the close is allowed.
1264 if (!closing_contents
->GetClosedByUserGesture()) {
1265 closing_contents
->SetClosedByUserGesture(
1266 close_types
& CLOSE_USER_GESTURE
);
1269 if (delegate_
->RunUnloadListenerBeforeClosing(closing_contents
)) {
1274 InternalCloseTab(closing_contents
, index
,
1275 (close_types
& CLOSE_CREATE_HISTORICAL_TAB
) != 0);
1278 if (ref
&& closing_all
&& !retval
) {
1279 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
1280 CloseAllTabsCanceled());
1286 void TabStripModel::InternalCloseTab(WebContents
* contents
,
1288 bool create_historical_tabs
) {
1289 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
1290 TabClosingAt(this, contents
, index
));
1292 // Ask the delegate to save an entry for this tab in the historical tab
1293 // database if applicable.
1294 if (create_historical_tabs
)
1295 delegate_
->CreateHistoricalTab(contents
);
1297 // Deleting the WebContents will call back to us via
1298 // WebContentsData::WebContentsDestroyed and detach it.
1302 WebContents
* TabStripModel::GetWebContentsAtImpl(int index
) const {
1303 CHECK(ContainsIndex(index
)) <<
1304 "Failed to find: " << index
<< " in: " << count() << " entries.";
1305 return contents_data_
[index
]->web_contents();
1308 void TabStripModel::NotifyIfTabDeactivated(WebContents
* contents
) {
1310 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
1311 TabDeactivated(contents
));
1315 void TabStripModel::NotifyIfActiveTabChanged(WebContents
* old_contents
,
1316 NotifyTypes notify_types
) {
1317 WebContents
* new_contents
= GetWebContentsAtImpl(active_index());
1318 if (old_contents
!= new_contents
) {
1319 int reason
= notify_types
== NOTIFY_USER_GESTURE
1320 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1321 : TabStripModelObserver::CHANGE_REASON_NONE
;
1324 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
1325 ActiveTabChanged(old_contents
,
1330 // Activating a discarded tab reloads it, so it is no longer discarded.
1331 if (contents_data_
[active_index()]->discarded()) {
1332 contents_data_
[active_index()]->set_discarded(false);
1333 RecordUMATabDiscarding(UMA_TAB_DISCARDING_SWITCH_TO_DISCARDED_TAB
);
1335 RecordUMATabDiscarding(UMA_TAB_DISCARDING_SWITCH_TO_LOADED_TAB
);
1340 void TabStripModel::NotifyIfActiveOrSelectionChanged(
1341 WebContents
* old_contents
,
1342 NotifyTypes notify_types
,
1343 const ui::ListSelectionModel
& old_model
) {
1344 NotifyIfActiveTabChanged(old_contents
, notify_types
);
1346 if (!selection_model().Equals(old_model
)) {
1347 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
1348 TabSelectionChanged(this, old_model
));
1352 void TabStripModel::SetSelection(
1353 const ui::ListSelectionModel
& new_model
,
1354 NotifyTypes notify_types
) {
1355 WebContents
* old_contents
= GetActiveWebContents();
1356 ui::ListSelectionModel old_model
;
1357 old_model
.Copy(selection_model_
);
1358 if (new_model
.active() != selection_model_
.active())
1359 NotifyIfTabDeactivated(old_contents
);
1360 selection_model_
.Copy(new_model
);
1361 NotifyIfActiveOrSelectionChanged(old_contents
, notify_types
, old_model
);
1364 void TabStripModel::SelectRelativeTab(bool next
) {
1365 // This may happen during automated testing or if a user somehow buffers
1366 // many key accelerators.
1367 if (contents_data_
.empty())
1370 int index
= active_index();
1371 int delta
= next
? 1 : -1;
1372 index
= (index
+ count() + delta
) % count();
1373 ActivateTabAt(index
, true);
1376 void TabStripModel::MoveWebContentsAtImpl(int index
,
1378 bool select_after_move
) {
1379 FixOpenersAndGroupsReferencing(index
);
1381 WebContentsData
* moved_data
= contents_data_
[index
];
1382 contents_data_
.erase(contents_data_
.begin() + index
);
1383 contents_data_
.insert(contents_data_
.begin() + to_position
, moved_data
);
1385 selection_model_
.Move(index
, to_position
);
1386 if (!selection_model_
.IsSelected(select_after_move
) && select_after_move
) {
1387 // TODO(sky): why doesn't this code notify observers?
1388 selection_model_
.SetSelectedIndex(to_position
);
1391 FOR_EACH_OBSERVER(TabStripModelObserver
, observers_
,
1392 TabMoved(moved_data
->web_contents(), index
, to_position
));
1395 void TabStripModel::MoveSelectedTabsToImpl(int index
,
1398 DCHECK(start
< selection_model_
.selected_indices().size() &&
1399 start
+ length
<= selection_model_
.selected_indices().size());
1400 size_t end
= start
+ length
;
1401 int count_before_index
= 0;
1402 for (size_t i
= start
; i
< end
&&
1403 selection_model_
.selected_indices()[i
] < index
+ count_before_index
;
1405 count_before_index
++;
1408 // First move those before index. Any tabs before index end up moving in the
1409 // selection model so we use start each time through.
1410 int target_index
= index
+ count_before_index
;
1411 size_t tab_index
= start
;
1412 while (tab_index
< end
&&
1413 selection_model_
.selected_indices()[start
] < index
) {
1414 MoveWebContentsAt(selection_model_
.selected_indices()[start
],
1415 target_index
- 1, false);
1419 // Then move those after the index. These don't result in reordering the
1421 while (tab_index
< end
) {
1422 if (selection_model_
.selected_indices()[tab_index
] != target_index
) {
1423 MoveWebContentsAt(selection_model_
.selected_indices()[tab_index
],
1424 target_index
, false);
1432 bool TabStripModel::OpenerMatches(const WebContentsData
* data
,
1433 const WebContents
* opener
,
1435 return data
->opener() == opener
|| (use_group
&& data
->group() == opener
);
1438 void TabStripModel::FixOpenersAndGroupsReferencing(int index
) {
1439 WebContents
* old_contents
= GetWebContentsAtImpl(index
);
1440 for (WebContentsData
* data
: contents_data_
) {
1441 if (data
->group() == old_contents
)
1442 data
->set_group(contents_data_
[index
]->group());
1443 if (data
->opener() == old_contents
)
1444 data
->set_opener(contents_data_
[index
]->opener());