Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / ui / tabs / tab_strip_model.cc
blob06ac829caee55219f88d5b595bef67b64b3762d0
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"
7 #include <algorithm>
8 #include <map>
9 #include <string>
11 #include "apps/ui/web_contents_sizer.h"
12 #include "base/metrics/histogram.h"
13 #include "base/stl_util.h"
14 #include "chrome/app/chrome_command_ids.h"
15 #include "chrome/browser/browser_shutdown.h"
16 #include "chrome/browser/defaults.h"
17 #include "chrome/browser/extensions/tab_helper.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
20 #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h"
21 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
22 #include "chrome/browser/ui/tabs/tab_strip_model_order_controller.h"
23 #include "chrome/common/url_constants.h"
24 #include "components/web_modal/web_contents_modal_dialog_manager.h"
25 #include "content/public/browser/render_process_host.h"
26 #include "content/public/browser/user_metrics.h"
27 #include "content/public/browser/web_contents.h"
28 #include "content/public/browser/web_contents_observer.h"
29 using base::UserMetricsAction;
30 using content::WebContents;
32 namespace {
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
49 // is deleted.
50 class CloseTracker {
51 public:
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.
58 bool HasNext() const;
60 // Returns the next WebContents, or NULL if there are no more.
61 WebContents* Next();
63 private:
64 class DeletionObserver : public content::WebContentsObserver {
65 public:
66 DeletionObserver(CloseTracker* parent, WebContents* web_contents)
67 : WebContentsObserver(web_contents),
68 parent_(parent) {
71 // Expose web_contents() publicly.
72 using content::WebContentsObserver::web_contents;
74 private:
75 // WebContentsObserver:
76 virtual void WebContentsDestroyed(WebContents* web_contents) 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;
88 Observers 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())
108 return NULL;
110 DeletionObserver* observer = observers_[0];
111 WebContents* web_contents = observer->web_contents();
112 observers_.erase(observers_.begin());
113 delete observer;
114 return web_contents;
117 void CloseTracker::OnWebContentsDestroyed(DeletionObserver* observer) {
118 Observers::iterator i =
119 std::find(observers_.begin(), observers_.end(), observer);
120 if (i != observers_.end()) {
121 delete *i;
122 observers_.erase(i);
123 return;
125 NOTREACHED() << "WebContents destroyed that wasn't in the list";
128 } // namespace
130 ///////////////////////////////////////////////////////////////////////////////
131 // WebContentsData
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 {
136 public:
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
145 // one is closed.
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; }
161 private:
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(WebContents* web_contents) 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.
181 WebContents* group_;
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?
198 bool pinned_;
200 // Is the tab interaction blocked by a modal dialog?
201 bool blocked_;
203 // Has the tab data been discarded to save memory?
204 bool discarded_;
206 DISALLOW_COPY_AND_ASSIGN(WebContentsData);
209 TabStripModel::WebContentsData::WebContentsData(TabStripModel* tab_strip_model,
210 WebContents* contents)
211 : content::WebContentsObserver(contents),
212 contents_(contents),
213 tab_strip_model_(tab_strip_model),
214 group_(NULL),
215 opener_(NULL),
216 reset_group_on_select_(false),
217 pinned_(false),
218 blocked_(false),
219 discarded_(false) {
222 void TabStripModel::WebContentsData::SetWebContents(WebContents* contents) {
223 contents_ = contents;
224 Observe(contents);
227 void TabStripModel::WebContentsData::WebContentsDestroyed(
228 WebContents* web_contents) {
229 DCHECK_EQ(contents_, web_contents);
231 // Note that we only detach the contents here, not close it - it's
232 // already been closed. We just want to undo our bookkeeping.
233 int index = tab_strip_model_->GetIndexOfWebContents(web_contents);
234 DCHECK_NE(TabStripModel::kNoTab, index);
235 tab_strip_model_->DetachWebContentsAt(index);
238 ///////////////////////////////////////////////////////////////////////////////
239 // TabStripModel, public:
241 TabStripModel::TabStripModel(TabStripModelDelegate* delegate, Profile* profile)
242 : delegate_(delegate),
243 profile_(profile),
244 closing_all_(false),
245 in_notify_(false),
246 weak_factory_(this) {
247 DCHECK(delegate_);
248 order_controller_.reset(new TabStripModelOrderController(this));
251 TabStripModel::~TabStripModel() {
252 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
253 TabStripModelDeleted());
254 STLDeleteElements(&contents_data_);
255 order_controller_.reset();
258 void TabStripModel::AddObserver(TabStripModelObserver* observer) {
259 observers_.AddObserver(observer);
262 void TabStripModel::RemoveObserver(TabStripModelObserver* observer) {
263 observers_.RemoveObserver(observer);
266 bool TabStripModel::ContainsIndex(int index) const {
267 return index >= 0 && index < count();
270 void TabStripModel::AppendWebContents(WebContents* contents,
271 bool foreground) {
272 InsertWebContentsAt(count(), contents,
273 foreground ? (ADD_INHERIT_GROUP | ADD_ACTIVE) :
274 ADD_NONE);
277 void TabStripModel::InsertWebContentsAt(int index,
278 WebContents* contents,
279 int add_types) {
280 delegate_->WillAddWebContents(contents);
282 bool active = add_types & ADD_ACTIVE;
283 // Force app tabs to be pinned.
284 extensions::TabHelper* extensions_tab_helper =
285 extensions::TabHelper::FromWebContents(contents);
286 bool pin = extensions_tab_helper->is_app() || add_types & ADD_PINNED;
287 index = ConstrainInsertionIndex(index, pin);
289 // In tab dragging situations, if the last tab in the window was detached
290 // then the user aborted the drag, we will have the |closing_all_| member
291 // set (see DetachWebContentsAt) which will mess with our mojo here. We need
292 // to clear this bit.
293 closing_all_ = false;
295 // Have to get the active contents before we monkey with the contents
296 // otherwise we run into problems when we try to change the active contents
297 // since the old contents and the new contents will be the same...
298 WebContents* active_contents = GetActiveWebContents();
299 WebContentsData* data = new WebContentsData(this, contents);
300 data->set_pinned(pin);
301 if ((add_types & ADD_INHERIT_GROUP) && active_contents) {
302 if (active) {
303 // Forget any existing relationships, we don't want to make things too
304 // confusing by having multiple groups active at the same time.
305 ForgetAllOpeners();
307 // Anything opened by a link we deem to have an opener.
308 data->set_group(active_contents);
309 data->set_opener(active_contents);
310 } else if ((add_types & ADD_INHERIT_OPENER) && active_contents) {
311 if (active) {
312 // Forget any existing relationships, we don't want to make things too
313 // confusing by having multiple groups active at the same time.
314 ForgetAllOpeners();
316 data->set_opener(active_contents);
319 web_modal::WebContentsModalDialogManager* modal_dialog_manager =
320 web_modal::WebContentsModalDialogManager::FromWebContents(contents);
321 if (modal_dialog_manager)
322 data->set_blocked(modal_dialog_manager->IsDialogActive());
324 contents_data_.insert(contents_data_.begin() + index, data);
326 selection_model_.IncrementFrom(index);
328 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
329 TabInsertedAt(contents, index, active));
330 if (active) {
331 ui::ListSelectionModel new_model;
332 new_model.Copy(selection_model_);
333 new_model.SetSelectedIndex(index);
334 SetSelection(new_model, NOTIFY_DEFAULT);
338 WebContents* TabStripModel::ReplaceWebContentsAt(int index,
339 WebContents* new_contents) {
340 delegate_->WillAddWebContents(new_contents);
342 DCHECK(ContainsIndex(index));
343 WebContents* old_contents = GetWebContentsAtImpl(index);
345 ForgetOpenersAndGroupsReferencing(old_contents);
347 contents_data_[index]->SetWebContents(new_contents);
349 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
350 TabReplacedAt(this, old_contents, new_contents, index));
352 // When the active WebContents is replaced send out a selection notification
353 // too. We do this as nearly all observers need to treat a replacement of the
354 // selected contents as the selection changing.
355 if (active_index() == index) {
356 FOR_EACH_OBSERVER(
357 TabStripModelObserver,
358 observers_,
359 ActiveTabChanged(old_contents,
360 new_contents,
361 active_index(),
362 TabStripModelObserver::CHANGE_REASON_REPLACED));
364 return old_contents;
367 WebContents* TabStripModel::DiscardWebContentsAt(int index) {
368 DCHECK(ContainsIndex(index));
369 // Do not discard active tab.
370 if (active_index() == index)
371 return NULL;
373 WebContents* null_contents =
374 WebContents::Create(WebContents::CreateParams(profile()));
375 WebContents* old_contents = GetWebContentsAtImpl(index);
376 // Copy over the state from the navigation controller so we preserve the
377 // back/forward history and continue to display the correct title/favicon.
378 null_contents->GetController().CopyStateFrom(old_contents->GetController());
379 // Replace the tab we're discarding with the null version.
380 ReplaceWebContentsAt(index, null_contents);
381 // Mark the tab so it will reload when we click.
382 contents_data_[index]->set_discarded(true);
383 // Discard the old tab's renderer.
384 // TODO(jamescook): This breaks script connections with other tabs.
385 // We need to find a different approach that doesn't do that, perhaps based
386 // on navigation to swappedout://.
387 delete old_contents;
388 return null_contents;
391 WebContents* TabStripModel::DetachWebContentsAt(int index) {
392 CHECK(!in_notify_);
393 if (contents_data_.empty())
394 return NULL;
396 DCHECK(ContainsIndex(index));
398 WebContents* removed_contents = GetWebContentsAtImpl(index);
399 bool was_selected = IsTabSelected(index);
400 int next_selected_index = order_controller_->DetermineNewSelectedIndex(index);
401 delete contents_data_[index];
402 contents_data_.erase(contents_data_.begin() + index);
403 ForgetOpenersAndGroupsReferencing(removed_contents);
404 if (empty())
405 closing_all_ = true;
406 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
407 TabDetachedAt(removed_contents, index));
408 if (empty()) {
409 selection_model_.Clear();
410 // TabDetachedAt() might unregister observers, so send |TabStripEmpty()| in
411 // a second pass.
412 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty());
413 } else {
414 int old_active = active_index();
415 selection_model_.DecrementFrom(index);
416 ui::ListSelectionModel old_model;
417 old_model.Copy(selection_model_);
418 if (index == old_active) {
419 NotifyIfTabDeactivated(removed_contents);
420 if (!selection_model_.empty()) {
421 // The active tab was removed, but there is still something selected.
422 // Move the active and anchor to the first selected index.
423 selection_model_.set_active(selection_model_.selected_indices()[0]);
424 selection_model_.set_anchor(selection_model_.active());
425 } else {
426 // The active tab was removed and nothing is selected. Reset the
427 // selection and send out notification.
428 selection_model_.SetSelectedIndex(next_selected_index);
430 NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT);
433 // Sending notification in case the detached tab was selected. Using
434 // NotifyIfActiveOrSelectionChanged() here would not guarantee that a
435 // notification is sent even though the tab selection has changed because
436 // |old_model| is stored after calling DecrementFrom().
437 if (was_selected) {
438 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
439 TabSelectionChanged(this, old_model));
442 return removed_contents;
445 void TabStripModel::ActivateTabAt(int index, bool user_gesture) {
446 DCHECK(ContainsIndex(index));
447 ui::ListSelectionModel new_model;
448 new_model.Copy(selection_model_);
449 new_model.SetSelectedIndex(index);
450 SetSelection(new_model, user_gesture ? NOTIFY_USER_GESTURE : NOTIFY_DEFAULT);
453 void TabStripModel::AddTabAtToSelection(int index) {
454 DCHECK(ContainsIndex(index));
455 ui::ListSelectionModel new_model;
456 new_model.Copy(selection_model_);
457 new_model.AddIndexToSelection(index);
458 SetSelection(new_model, NOTIFY_DEFAULT);
461 void TabStripModel::MoveWebContentsAt(int index,
462 int to_position,
463 bool select_after_move) {
464 DCHECK(ContainsIndex(index));
465 if (index == to_position)
466 return;
468 int first_non_mini_tab = IndexOfFirstNonMiniTab();
469 if ((index < first_non_mini_tab && to_position >= first_non_mini_tab) ||
470 (to_position < first_non_mini_tab && index >= first_non_mini_tab)) {
471 // This would result in mini tabs mixed with non-mini tabs. We don't allow
472 // that.
473 return;
476 MoveWebContentsAtImpl(index, to_position, select_after_move);
479 void TabStripModel::MoveSelectedTabsTo(int index) {
480 int total_mini_count = IndexOfFirstNonMiniTab();
481 int selected_mini_count = 0;
482 int selected_count =
483 static_cast<int>(selection_model_.selected_indices().size());
484 for (int i = 0; i < selected_count &&
485 IsMiniTab(selection_model_.selected_indices()[i]); ++i) {
486 selected_mini_count++;
489 // To maintain that all mini-tabs occur before non-mini-tabs we move them
490 // first.
491 if (selected_mini_count > 0) {
492 MoveSelectedTabsToImpl(
493 std::min(total_mini_count - selected_mini_count, index), 0u,
494 selected_mini_count);
495 if (index > total_mini_count - selected_mini_count) {
496 // We're being told to drag mini-tabs to an invalid location. Adjust the
497 // index such that non-mini-tabs end up at a location as though we could
498 // move the mini-tabs to index. See description in header for more
499 // details.
500 index += selected_mini_count;
503 if (selected_mini_count == selected_count)
504 return;
506 // Then move the non-pinned tabs.
507 MoveSelectedTabsToImpl(std::max(index, total_mini_count),
508 selected_mini_count,
509 selected_count - selected_mini_count);
512 WebContents* TabStripModel::GetActiveWebContents() const {
513 return GetWebContentsAt(active_index());
516 WebContents* TabStripModel::GetWebContentsAt(int index) const {
517 if (ContainsIndex(index))
518 return GetWebContentsAtImpl(index);
519 return NULL;
522 int TabStripModel::GetIndexOfWebContents(const WebContents* contents) const {
523 for (size_t i = 0; i < contents_data_.size(); ++i) {
524 if (contents_data_[i]->web_contents() == contents)
525 return i;
527 return kNoTab;
530 void TabStripModel::UpdateWebContentsStateAt(int index,
531 TabStripModelObserver::TabChangeType change_type) {
532 DCHECK(ContainsIndex(index));
534 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
535 TabChangedAt(GetWebContentsAtImpl(index), index, change_type));
538 void TabStripModel::CloseAllTabs() {
539 // Set state so that observers can adjust their behavior to suit this
540 // specific condition when CloseWebContentsAt causes a flurry of
541 // Close/Detach/Select notifications to be sent.
542 closing_all_ = true;
543 std::vector<int> closing_tabs;
544 for (int i = count() - 1; i >= 0; --i)
545 closing_tabs.push_back(i);
546 InternalCloseTabs(closing_tabs, CLOSE_CREATE_HISTORICAL_TAB);
549 bool TabStripModel::CloseWebContentsAt(int index, uint32 close_types) {
550 DCHECK(ContainsIndex(index));
551 std::vector<int> closing_tabs;
552 closing_tabs.push_back(index);
553 return InternalCloseTabs(closing_tabs, close_types);
556 bool TabStripModel::TabsAreLoading() const {
557 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
558 iter != contents_data_.end(); ++iter) {
559 if ((*iter)->web_contents()->IsLoading())
560 return true;
562 return false;
565 WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) {
566 DCHECK(ContainsIndex(index));
567 return contents_data_[index]->opener();
570 void TabStripModel::SetOpenerOfWebContentsAt(int index,
571 WebContents* opener) {
572 DCHECK(ContainsIndex(index));
573 DCHECK(opener);
574 contents_data_[index]->set_opener(opener);
577 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener,
578 int start_index,
579 bool use_group) const {
580 DCHECK(opener);
581 DCHECK(ContainsIndex(start_index));
583 // Check tabs after start_index first.
584 for (int i = start_index + 1; i < count(); ++i) {
585 if (OpenerMatches(contents_data_[i], opener, use_group))
586 return i;
588 // Then check tabs before start_index, iterating backwards.
589 for (int i = start_index - 1; i >= 0; --i) {
590 if (OpenerMatches(contents_data_[i], opener, use_group))
591 return i;
593 return kNoTab;
596 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
597 int start_index) const {
598 DCHECK(opener);
599 DCHECK(ContainsIndex(start_index));
601 for (int i = contents_data_.size() - 1; i > start_index; --i) {
602 if (contents_data_[i]->opener() == opener)
603 return i;
605 return kNoTab;
608 void TabStripModel::TabNavigating(WebContents* contents,
609 content::PageTransition transition) {
610 if (ShouldForgetOpenersForTransition(transition)) {
611 // Don't forget the openers if this tab is a New Tab page opened at the
612 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
613 // navigation of one of these transition types before resetting the
614 // opener relationships (this allows for the use case of opening a new
615 // tab to do a quick look-up of something while viewing a tab earlier in
616 // the strip). We can make this heuristic more permissive if need be.
617 if (!IsNewTabAtEndOfTabStrip(contents)) {
618 // If the user navigates the current tab to another page in any way
619 // other than by clicking a link, we want to pro-actively forget all
620 // TabStrip opener relationships since we assume they're beginning a
621 // different task by reusing the current tab.
622 ForgetAllOpeners();
623 // In this specific case we also want to reset the group relationship,
624 // since it is now technically invalid.
625 ForgetGroup(contents);
630 void TabStripModel::ForgetAllOpeners() {
631 // Forget all opener memories so we don't do anything weird with tab
632 // re-selection ordering.
633 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
634 iter != contents_data_.end(); ++iter)
635 (*iter)->set_opener(NULL);
638 void TabStripModel::ForgetGroup(WebContents* contents) {
639 int index = GetIndexOfWebContents(contents);
640 DCHECK(ContainsIndex(index));
641 contents_data_[index]->set_group(NULL);
642 contents_data_[index]->set_opener(NULL);
645 bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const {
646 int index = GetIndexOfWebContents(contents);
647 DCHECK(ContainsIndex(index));
648 return contents_data_[index]->reset_group_on_select();
651 void TabStripModel::SetTabBlocked(int index, bool blocked) {
652 DCHECK(ContainsIndex(index));
653 if (contents_data_[index]->blocked() == blocked)
654 return;
655 contents_data_[index]->set_blocked(blocked);
656 FOR_EACH_OBSERVER(
657 TabStripModelObserver, observers_,
658 TabBlockedStateChanged(contents_data_[index]->web_contents(),
659 index));
662 void TabStripModel::SetTabPinned(int index, bool pinned) {
663 DCHECK(ContainsIndex(index));
664 if (contents_data_[index]->pinned() == pinned)
665 return;
667 if (IsAppTab(index)) {
668 if (!pinned) {
669 // App tabs should always be pinned.
670 NOTREACHED();
671 return;
673 // Changing the pinned state of an app tab doesn't affect its mini-tab
674 // status.
675 contents_data_[index]->set_pinned(pinned);
676 } else {
677 // The tab is not an app tab, its position may have to change as the
678 // mini-tab state is changing.
679 int non_mini_tab_index = IndexOfFirstNonMiniTab();
680 contents_data_[index]->set_pinned(pinned);
681 if (pinned && index != non_mini_tab_index) {
682 MoveWebContentsAtImpl(index, non_mini_tab_index, false);
683 index = non_mini_tab_index;
684 } else if (!pinned && index + 1 != non_mini_tab_index) {
685 MoveWebContentsAtImpl(index, non_mini_tab_index - 1, false);
686 index = non_mini_tab_index - 1;
689 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
690 TabMiniStateChanged(contents_data_[index]->web_contents(),
691 index));
694 // else: the tab was at the boundary and its position doesn't need to change.
695 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
696 TabPinnedStateChanged(contents_data_[index]->web_contents(),
697 index));
700 bool TabStripModel::IsTabPinned(int index) const {
701 DCHECK(ContainsIndex(index));
702 return contents_data_[index]->pinned();
705 bool TabStripModel::IsMiniTab(int index) const {
706 return IsTabPinned(index) || IsAppTab(index);
709 bool TabStripModel::IsAppTab(int index) const {
710 WebContents* contents = GetWebContentsAt(index);
711 return contents && extensions::TabHelper::FromWebContents(contents)->is_app();
714 bool TabStripModel::IsTabBlocked(int index) const {
715 return contents_data_[index]->blocked();
718 bool TabStripModel::IsTabDiscarded(int index) const {
719 return contents_data_[index]->discarded();
722 int TabStripModel::IndexOfFirstNonMiniTab() const {
723 for (size_t i = 0; i < contents_data_.size(); ++i) {
724 if (!IsMiniTab(static_cast<int>(i)))
725 return static_cast<int>(i);
727 // No mini-tabs.
728 return count();
731 int TabStripModel::ConstrainInsertionIndex(int index, bool mini_tab) {
732 return mini_tab ? std::min(std::max(0, index), IndexOfFirstNonMiniTab()) :
733 std::min(count(), std::max(index, IndexOfFirstNonMiniTab()));
736 void TabStripModel::ExtendSelectionTo(int index) {
737 DCHECK(ContainsIndex(index));
738 ui::ListSelectionModel new_model;
739 new_model.Copy(selection_model_);
740 new_model.SetSelectionFromAnchorTo(index);
741 SetSelection(new_model, NOTIFY_DEFAULT);
744 void TabStripModel::ToggleSelectionAt(int index) {
745 DCHECK(ContainsIndex(index));
746 ui::ListSelectionModel new_model;
747 new_model.Copy(selection_model());
748 if (selection_model_.IsSelected(index)) {
749 if (selection_model_.size() == 1) {
750 // One tab must be selected and this tab is currently selected so we can't
751 // unselect it.
752 return;
754 new_model.RemoveIndexFromSelection(index);
755 new_model.set_anchor(index);
756 if (new_model.active() == index ||
757 new_model.active() == ui::ListSelectionModel::kUnselectedIndex)
758 new_model.set_active(new_model.selected_indices()[0]);
759 } else {
760 new_model.AddIndexToSelection(index);
761 new_model.set_anchor(index);
762 new_model.set_active(index);
764 SetSelection(new_model, NOTIFY_DEFAULT);
767 void TabStripModel::AddSelectionFromAnchorTo(int index) {
768 ui::ListSelectionModel new_model;
769 new_model.Copy(selection_model_);
770 new_model.AddSelectionFromAnchorTo(index);
771 SetSelection(new_model, NOTIFY_DEFAULT);
774 bool TabStripModel::IsTabSelected(int index) const {
775 DCHECK(ContainsIndex(index));
776 return selection_model_.IsSelected(index);
779 void TabStripModel::SetSelectionFromModel(
780 const ui::ListSelectionModel& source) {
781 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
782 SetSelection(source, NOTIFY_DEFAULT);
785 void TabStripModel::AddWebContents(WebContents* contents,
786 int index,
787 content::PageTransition transition,
788 int add_types) {
789 // If the newly-opened tab is part of the same task as the parent tab, we want
790 // to inherit the parent's "group" attribute, so that if this tab is then
791 // closed we'll jump back to the parent tab.
792 bool inherit_group = (add_types & ADD_INHERIT_GROUP) == ADD_INHERIT_GROUP;
794 if (transition == content::PAGE_TRANSITION_LINK &&
795 (add_types & ADD_FORCE_INDEX) == 0) {
796 // We assume tabs opened via link clicks are part of the same task as their
797 // parent. Note that when |force_index| is true (e.g. when the user
798 // drag-and-drops a link to the tab strip), callers aren't really handling
799 // link clicks, they just want to score the navigation like a link click in
800 // the history backend, so we don't inherit the group in this case.
801 index = order_controller_->DetermineInsertionIndex(transition,
802 add_types & ADD_ACTIVE);
803 inherit_group = true;
804 } else {
805 // For all other types, respect what was passed to us, normalizing -1s and
806 // values that are too large.
807 if (index < 0 || index > count())
808 index = count();
811 if (transition == content::PAGE_TRANSITION_TYPED && index == count()) {
812 // Also, any tab opened at the end of the TabStrip with a "TYPED"
813 // transition inherit group as well. This covers the cases where the user
814 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
815 // in the address bar and presses Alt+Enter. This allows for opening a new
816 // Tab to quickly look up something. When this Tab is closed, the old one
817 // is re-selected, not the next-adjacent.
818 inherit_group = true;
820 InsertWebContentsAt(index, contents,
821 add_types | (inherit_group ? ADD_INHERIT_GROUP : 0));
822 // Reset the index, just in case insert ended up moving it on us.
823 index = GetIndexOfWebContents(contents);
825 if (inherit_group && transition == content::PAGE_TRANSITION_TYPED)
826 contents_data_[index]->set_reset_group_on_select(true);
828 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
829 // here we seem to get failures in startup perf tests.
830 // Ensure that the new WebContentsView begins at the same size as the
831 // previous WebContentsView if it existed. Otherwise, the initial WebKit
832 // layout will be performed based on a width of 0 pixels, causing a
833 // very long, narrow, inaccurate layout. Because some scripts on pages (as
834 // well as WebKit's anchor link location calculation) are run on the
835 // initial layout and not recalculated later, we need to ensure the first
836 // layout is performed with sane view dimensions even when we're opening a
837 // new background tab.
838 if (WebContents* old_contents = GetActiveWebContents()) {
839 if ((add_types & ADD_ACTIVE) == 0) {
840 apps::ResizeWebContents(contents,
841 old_contents->GetContainerBounds().size());
846 void TabStripModel::CloseSelectedTabs() {
847 InternalCloseTabs(selection_model_.selected_indices(),
848 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
851 void TabStripModel::SelectNextTab() {
852 SelectRelativeTab(true);
855 void TabStripModel::SelectPreviousTab() {
856 SelectRelativeTab(false);
859 void TabStripModel::SelectLastTab() {
860 ActivateTabAt(count() - 1, true);
863 void TabStripModel::MoveTabNext() {
864 // TODO: this likely needs to be updated for multi-selection.
865 int new_index = std::min(active_index() + 1, count() - 1);
866 MoveWebContentsAt(active_index(), new_index, true);
869 void TabStripModel::MoveTabPrevious() {
870 // TODO: this likely needs to be updated for multi-selection.
871 int new_index = std::max(active_index() - 1, 0);
872 MoveWebContentsAt(active_index(), new_index, true);
875 // Context menu functions.
876 bool TabStripModel::IsContextMenuCommandEnabled(
877 int context_index, ContextMenuCommand command_id) const {
878 DCHECK(command_id > CommandFirst && command_id < CommandLast);
879 switch (command_id) {
880 case CommandNewTab:
881 case CommandCloseTab:
882 return true;
884 case CommandReload: {
885 std::vector<int> indices = GetIndicesForCommand(context_index);
886 for (size_t i = 0; i < indices.size(); ++i) {
887 WebContents* tab = GetWebContentsAt(indices[i]);
888 if (tab) {
889 CoreTabHelperDelegate* core_delegate =
890 CoreTabHelper::FromWebContents(tab)->delegate();
891 if (!core_delegate || core_delegate->CanReloadContents(tab))
892 return true;
895 return false;
898 case CommandCloseOtherTabs:
899 case CommandCloseTabsToRight:
900 return !GetIndicesClosedByCommand(context_index, command_id).empty();
902 case CommandDuplicate: {
903 std::vector<int> indices = GetIndicesForCommand(context_index);
904 for (size_t i = 0; i < indices.size(); ++i) {
905 if (delegate_->CanDuplicateContentsAt(indices[i]))
906 return true;
908 return false;
911 case CommandRestoreTab:
912 return delegate_->GetRestoreTabType() !=
913 TabStripModelDelegate::RESTORE_NONE;
915 case CommandTogglePinned: {
916 std::vector<int> indices = GetIndicesForCommand(context_index);
917 for (size_t i = 0; i < indices.size(); ++i) {
918 if (!IsAppTab(indices[i]))
919 return true;
921 return false;
924 case CommandBookmarkAllTabs:
925 return browser_defaults::bookmarks_enabled &&
926 delegate_->CanBookmarkAllTabs();
928 case CommandSelectByDomain:
929 case CommandSelectByOpener:
930 return true;
932 default:
933 NOTREACHED();
935 return false;
938 void TabStripModel::ExecuteContextMenuCommand(
939 int context_index, ContextMenuCommand command_id) {
940 DCHECK(command_id > CommandFirst && command_id < CommandLast);
941 switch (command_id) {
942 case CommandNewTab:
943 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
944 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
945 TabStripModel::NEW_TAB_CONTEXT_MENU,
946 TabStripModel::NEW_TAB_ENUM_COUNT);
947 delegate()->AddTabAt(GURL(), context_index + 1, true);
948 break;
950 case CommandReload: {
951 content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
952 std::vector<int> indices = GetIndicesForCommand(context_index);
953 for (size_t i = 0; i < indices.size(); ++i) {
954 WebContents* tab = GetWebContentsAt(indices[i]);
955 if (tab) {
956 CoreTabHelperDelegate* core_delegate =
957 CoreTabHelper::FromWebContents(tab)->delegate();
958 if (!core_delegate || core_delegate->CanReloadContents(tab))
959 tab->GetController().Reload(true);
962 break;
965 case CommandDuplicate: {
966 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
967 std::vector<int> indices = GetIndicesForCommand(context_index);
968 // Copy the WebContents off as the indices will change as tabs are
969 // duplicated.
970 std::vector<WebContents*> tabs;
971 for (size_t i = 0; i < indices.size(); ++i)
972 tabs.push_back(GetWebContentsAt(indices[i]));
973 for (size_t i = 0; i < tabs.size(); ++i) {
974 int index = GetIndexOfWebContents(tabs[i]);
975 if (index != -1 && delegate_->CanDuplicateContentsAt(index))
976 delegate_->DuplicateContentsAt(index);
978 break;
981 case CommandCloseTab: {
982 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
983 InternalCloseTabs(GetIndicesForCommand(context_index),
984 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
985 break;
988 case CommandCloseOtherTabs: {
989 content::RecordAction(
990 UserMetricsAction("TabContextMenu_CloseOtherTabs"));
991 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
992 CLOSE_CREATE_HISTORICAL_TAB);
993 break;
996 case CommandCloseTabsToRight: {
997 content::RecordAction(
998 UserMetricsAction("TabContextMenu_CloseTabsToRight"));
999 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1000 CLOSE_CREATE_HISTORICAL_TAB);
1001 break;
1004 case CommandRestoreTab: {
1005 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1006 delegate_->RestoreTab();
1007 break;
1010 case CommandTogglePinned: {
1011 content::RecordAction(
1012 UserMetricsAction("TabContextMenu_TogglePinned"));
1013 std::vector<int> indices = GetIndicesForCommand(context_index);
1014 bool pin = WillContextMenuPin(context_index);
1015 if (pin) {
1016 for (size_t i = 0; i < indices.size(); ++i) {
1017 if (!IsAppTab(indices[i]))
1018 SetTabPinned(indices[i], true);
1020 } else {
1021 // Unpin from the back so that the order is maintained (unpinning can
1022 // trigger moving a tab).
1023 for (size_t i = indices.size(); i > 0; --i) {
1024 if (!IsAppTab(indices[i - 1]))
1025 SetTabPinned(indices[i - 1], false);
1028 break;
1031 case CommandBookmarkAllTabs: {
1032 content::RecordAction(
1033 UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1035 delegate_->BookmarkAllTabs();
1036 break;
1039 case CommandSelectByDomain:
1040 case CommandSelectByOpener: {
1041 std::vector<int> indices;
1042 if (command_id == CommandSelectByDomain)
1043 GetIndicesWithSameDomain(context_index, &indices);
1044 else
1045 GetIndicesWithSameOpener(context_index, &indices);
1046 ui::ListSelectionModel selection_model;
1047 selection_model.SetSelectedIndex(context_index);
1048 for (size_t i = 0; i < indices.size(); ++i)
1049 selection_model.AddIndexToSelection(indices[i]);
1050 SetSelectionFromModel(selection_model);
1051 break;
1054 default:
1055 NOTREACHED();
1059 std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1060 int index,
1061 ContextMenuCommand id) const {
1062 DCHECK(ContainsIndex(index));
1063 DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1064 bool is_selected = IsTabSelected(index);
1065 int start;
1066 if (id == CommandCloseTabsToRight) {
1067 if (is_selected) {
1068 start = selection_model_.selected_indices()[
1069 selection_model_.selected_indices().size() - 1] + 1;
1070 } else {
1071 start = index + 1;
1073 } else {
1074 start = 0;
1076 // NOTE: callers expect the vector to be sorted in descending order.
1077 std::vector<int> indices;
1078 for (int i = count() - 1; i >= start; --i) {
1079 if (i != index && !IsMiniTab(i) && (!is_selected || !IsTabSelected(i)))
1080 indices.push_back(i);
1082 return indices;
1085 bool TabStripModel::WillContextMenuPin(int index) {
1086 std::vector<int> indices = GetIndicesForCommand(index);
1087 // If all tabs are pinned, then we unpin, otherwise we pin.
1088 bool all_pinned = true;
1089 for (size_t i = 0; i < indices.size() && all_pinned; ++i) {
1090 if (!IsAppTab(index)) // We never change app tabs.
1091 all_pinned = IsTabPinned(indices[i]);
1093 return !all_pinned;
1096 // static
1097 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1098 int* browser_cmd) {
1099 switch (cmd_id) {
1100 case CommandNewTab:
1101 *browser_cmd = IDC_NEW_TAB;
1102 break;
1103 case CommandReload:
1104 *browser_cmd = IDC_RELOAD;
1105 break;
1106 case CommandDuplicate:
1107 *browser_cmd = IDC_DUPLICATE_TAB;
1108 break;
1109 case CommandCloseTab:
1110 *browser_cmd = IDC_CLOSE_TAB;
1111 break;
1112 case CommandRestoreTab:
1113 *browser_cmd = IDC_RESTORE_TAB;
1114 break;
1115 case CommandBookmarkAllTabs:
1116 *browser_cmd = IDC_BOOKMARK_ALL_TABS;
1117 break;
1118 default:
1119 *browser_cmd = 0;
1120 return false;
1123 return true;
1126 ///////////////////////////////////////////////////////////////////////////////
1127 // TabStripModel, private:
1129 std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices(
1130 const std::vector<int>& indices) const {
1131 std::vector<WebContents*> contents;
1132 for (size_t i = 0; i < indices.size(); ++i)
1133 contents.push_back(GetWebContentsAtImpl(indices[i]));
1134 return contents;
1137 void TabStripModel::GetIndicesWithSameDomain(int index,
1138 std::vector<int>* indices) {
1139 std::string domain = GetWebContentsAt(index)->GetURL().host();
1140 if (domain.empty())
1141 return;
1142 for (int i = 0; i < count(); ++i) {
1143 if (i == index)
1144 continue;
1145 if (GetWebContentsAt(i)->GetURL().host() == domain)
1146 indices->push_back(i);
1150 void TabStripModel::GetIndicesWithSameOpener(int index,
1151 std::vector<int>* indices) {
1152 WebContents* opener = contents_data_[index]->group();
1153 if (!opener) {
1154 // If there is no group, find all tabs with the selected tab as the opener.
1155 opener = GetWebContentsAt(index);
1156 if (!opener)
1157 return;
1159 for (int i = 0; i < count(); ++i) {
1160 if (i == index)
1161 continue;
1162 if (contents_data_[i]->group() == opener ||
1163 GetWebContentsAtImpl(i) == opener) {
1164 indices->push_back(i);
1169 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1170 if (!IsTabSelected(index)) {
1171 std::vector<int> indices;
1172 indices.push_back(index);
1173 return indices;
1175 return selection_model_.selected_indices();
1178 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1179 const GURL& url = contents->GetURL();
1180 return url.SchemeIs(content::kChromeUIScheme) &&
1181 url.host() == chrome::kChromeUINewTabHost &&
1182 contents == GetWebContentsAtImpl(count() - 1) &&
1183 contents->GetController().GetEntryCount() == 1;
1186 bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
1187 uint32 close_types) {
1188 if (indices.empty())
1189 return true;
1191 CloseTracker close_tracker(GetWebContentsFromIndices(indices));
1193 base::WeakPtr<TabStripModel> ref(weak_factory_.GetWeakPtr());
1194 const bool closing_all = indices.size() == contents_data_.size();
1195 if (closing_all)
1196 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, WillCloseAllTabs());
1198 // We only try the fast shutdown path if the whole browser process is *not*
1199 // shutting down. Fast shutdown during browser termination is handled in
1200 // BrowserShutdown.
1201 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
1202 // Construct a map of processes to the number of associated tabs that are
1203 // closing.
1204 std::map<content::RenderProcessHost*, size_t> processes;
1205 for (size_t i = 0; i < indices.size(); ++i) {
1206 WebContents* closing_contents = GetWebContentsAtImpl(indices[i]);
1207 if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents))
1208 continue;
1209 content::RenderProcessHost* process =
1210 closing_contents->GetRenderProcessHost();
1211 ++processes[process];
1214 // Try to fast shutdown the tabs that can close.
1215 for (std::map<content::RenderProcessHost*, size_t>::iterator iter =
1216 processes.begin(); iter != processes.end(); ++iter) {
1217 iter->first->FastShutdownForPageCount(iter->second);
1221 // We now return to our regularly scheduled shutdown procedure.
1222 bool retval = true;
1223 while (close_tracker.HasNext()) {
1224 WebContents* closing_contents = close_tracker.Next();
1225 int index = GetIndexOfWebContents(closing_contents);
1226 // Make sure we still contain the tab.
1227 if (index == kNoTab)
1228 continue;
1230 CoreTabHelper* core_tab_helper =
1231 CoreTabHelper::FromWebContents(closing_contents);
1232 core_tab_helper->OnCloseStarted();
1234 // Update the explicitly closed state. If the unload handlers cancel the
1235 // close the state is reset in Browser. We don't update the explicitly
1236 // closed state if already marked as explicitly closed as unload handlers
1237 // call back to this if the close is allowed.
1238 if (!closing_contents->GetClosedByUserGesture()) {
1239 closing_contents->SetClosedByUserGesture(
1240 close_types & CLOSE_USER_GESTURE);
1243 if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) {
1244 retval = false;
1245 continue;
1248 InternalCloseTab(closing_contents, index,
1249 (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
1252 if (ref && closing_all && !retval) {
1253 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1254 CloseAllTabsCanceled());
1257 return retval;
1260 void TabStripModel::InternalCloseTab(WebContents* contents,
1261 int index,
1262 bool create_historical_tabs) {
1263 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1264 TabClosingAt(this, contents, index));
1266 // Ask the delegate to save an entry for this tab in the historical tab
1267 // database if applicable.
1268 if (create_historical_tabs)
1269 delegate_->CreateHistoricalTab(contents);
1271 // Deleting the WebContents will call back to us via
1272 // WebContentsData::WebContentsDestroyed and detach it.
1273 delete contents;
1276 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1277 CHECK(ContainsIndex(index)) <<
1278 "Failed to find: " << index << " in: " << count() << " entries.";
1279 return contents_data_[index]->web_contents();
1282 void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) {
1283 if (contents) {
1284 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1285 TabDeactivated(contents));
1289 void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents,
1290 NotifyTypes notify_types) {
1291 WebContents* new_contents = GetWebContentsAtImpl(active_index());
1292 if (old_contents != new_contents) {
1293 int reason = notify_types == NOTIFY_USER_GESTURE
1294 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1295 : TabStripModelObserver::CHANGE_REASON_NONE;
1296 CHECK(!in_notify_);
1297 in_notify_ = true;
1298 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1299 ActiveTabChanged(old_contents,
1300 new_contents,
1301 active_index(),
1302 reason));
1303 in_notify_ = false;
1304 // Activating a discarded tab reloads it, so it is no longer discarded.
1305 contents_data_[active_index()]->set_discarded(false);
1309 void TabStripModel::NotifyIfActiveOrSelectionChanged(
1310 WebContents* old_contents,
1311 NotifyTypes notify_types,
1312 const ui::ListSelectionModel& old_model) {
1313 NotifyIfActiveTabChanged(old_contents, notify_types);
1315 if (!selection_model().Equals(old_model)) {
1316 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1317 TabSelectionChanged(this, old_model));
1321 void TabStripModel::SetSelection(
1322 const ui::ListSelectionModel& new_model,
1323 NotifyTypes notify_types) {
1324 WebContents* old_contents = GetActiveWebContents();
1325 ui::ListSelectionModel old_model;
1326 old_model.Copy(selection_model_);
1327 if (new_model.active() != selection_model_.active())
1328 NotifyIfTabDeactivated(old_contents);
1329 selection_model_.Copy(new_model);
1330 NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model);
1333 void TabStripModel::SelectRelativeTab(bool next) {
1334 // This may happen during automated testing or if a user somehow buffers
1335 // many key accelerators.
1336 if (contents_data_.empty())
1337 return;
1339 int index = active_index();
1340 int delta = next ? 1 : -1;
1341 index = (index + count() + delta) % count();
1342 ActivateTabAt(index, true);
1345 void TabStripModel::MoveWebContentsAtImpl(int index,
1346 int to_position,
1347 bool select_after_move) {
1348 WebContentsData* moved_data = contents_data_[index];
1349 contents_data_.erase(contents_data_.begin() + index);
1350 contents_data_.insert(contents_data_.begin() + to_position, moved_data);
1352 selection_model_.Move(index, to_position);
1353 if (!selection_model_.IsSelected(select_after_move) && select_after_move) {
1354 // TODO(sky): why doesn't this code notify observers?
1355 selection_model_.SetSelectedIndex(to_position);
1358 ForgetOpenersAndGroupsReferencing(moved_data->web_contents());
1360 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1361 TabMoved(moved_data->web_contents(), index, to_position));
1364 void TabStripModel::MoveSelectedTabsToImpl(int index,
1365 size_t start,
1366 size_t length) {
1367 DCHECK(start < selection_model_.selected_indices().size() &&
1368 start + length <= selection_model_.selected_indices().size());
1369 size_t end = start + length;
1370 int count_before_index = 0;
1371 for (size_t i = start; i < end &&
1372 selection_model_.selected_indices()[i] < index + count_before_index;
1373 ++i) {
1374 count_before_index++;
1377 // First move those before index. Any tabs before index end up moving in the
1378 // selection model so we use start each time through.
1379 int target_index = index + count_before_index;
1380 size_t tab_index = start;
1381 while (tab_index < end &&
1382 selection_model_.selected_indices()[start] < index) {
1383 MoveWebContentsAt(selection_model_.selected_indices()[start],
1384 target_index - 1, false);
1385 tab_index++;
1388 // Then move those after the index. These don't result in reordering the
1389 // selection.
1390 while (tab_index < end) {
1391 if (selection_model_.selected_indices()[tab_index] != target_index) {
1392 MoveWebContentsAt(selection_model_.selected_indices()[tab_index],
1393 target_index, false);
1395 tab_index++;
1396 target_index++;
1400 // static
1401 bool TabStripModel::OpenerMatches(const WebContentsData* data,
1402 const WebContents* opener,
1403 bool use_group) {
1404 return data->opener() == opener || (use_group && data->group() == opener);
1407 void TabStripModel::ForgetOpenersAndGroupsReferencing(
1408 const WebContents* tab) {
1409 for (WebContentsDataVector::const_iterator i = contents_data_.begin();
1410 i != contents_data_.end(); ++i) {
1411 if ((*i)->group() == tab)
1412 (*i)->set_group(NULL);
1413 if ((*i)->opener() == tab)
1414 (*i)->set_opener(NULL);