Elim cr-checkbox
[chromium-blink-merge.git] / chrome / browser / ui / tabs / tab_strip_model.cc
bloba005461387077d52003010394282de5feb1b06ae
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 <set>
10 #include <string>
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_discard_state.h"
22 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
23 #include "chrome/browser/ui/tabs/tab_strip_model_order_controller.h"
24 #include "chrome/browser/ui/tabs/tab_utils.h"
25 #include "chrome/browser/ui/web_contents_sizer.h"
26 #include "chrome/common/url_constants.h"
27 #include "components/web_modal/web_contents_modal_dialog_manager.h"
28 #include "content/public/browser/render_process_host.h"
29 #include "content/public/browser/user_metrics.h"
30 #include "content/public/browser/web_contents.h"
31 #include "content/public/browser/web_contents_observer.h"
32 using base::UserMetricsAction;
33 using content::WebContents;
35 namespace {
37 // Enumeration for UMA tab discarding events.
38 enum UMATabDiscarding {
39 UMA_TAB_DISCARDING_SWITCH_TO_LOADED_TAB,
40 UMA_TAB_DISCARDING_SWITCH_TO_DISCARDED_TAB,
41 UMA_TAB_DISCARDING_DISCARD_TAB,
42 UMA_TAB_DISCARDING_DISCARD_TAB_AUDIO,
43 UMA_TAB_DISCARDING_TAB_DISCARDING_MAX
46 // Records an UMA tab discarding event.
47 void RecordUMATabDiscarding(UMATabDiscarding event) {
48 UMA_HISTOGRAM_ENUMERATION("Tab.Discarding", event,
49 UMA_TAB_DISCARDING_TAB_DISCARDING_MAX);
52 // Records the number of discards that a tab has been through.
53 void RecordUMADiscardCount(int discard_count) {
54 UMA_HISTOGRAM_COUNTS("Tab.Discarding.DiscardCount", discard_count);
57 // Returns true if the specified transition is one of the types that cause the
58 // opener relationships for the tab in which the transition occurred to be
59 // forgotten. This is generally any navigation that isn't a link click (i.e.
60 // any navigation that can be considered to be the start of a new task distinct
61 // from what had previously occurred in that tab).
62 bool ShouldForgetOpenersForTransition(ui::PageTransition transition) {
63 return transition == ui::PAGE_TRANSITION_TYPED ||
64 transition == ui::PAGE_TRANSITION_AUTO_BOOKMARK ||
65 transition == ui::PAGE_TRANSITION_GENERATED ||
66 transition == ui::PAGE_TRANSITION_KEYWORD ||
67 transition == ui::PAGE_TRANSITION_AUTO_TOPLEVEL;
70 // CloseTracker is used when closing a set of WebContents. It listens for
71 // deletions of the WebContents and removes from the internal set any time one
72 // is deleted.
73 class CloseTracker {
74 public:
75 typedef std::vector<WebContents*> Contents;
77 explicit CloseTracker(const Contents& contents);
78 virtual ~CloseTracker();
80 // Returns true if there is another WebContents in the Tracker.
81 bool HasNext() const;
83 // Returns the next WebContents, or NULL if there are no more.
84 WebContents* Next();
86 private:
87 class DeletionObserver : public content::WebContentsObserver {
88 public:
89 DeletionObserver(CloseTracker* parent, WebContents* web_contents)
90 : WebContentsObserver(web_contents),
91 parent_(parent) {
94 private:
95 // WebContentsObserver:
96 void WebContentsDestroyed() override {
97 parent_->OnWebContentsDestroyed(this);
100 CloseTracker* parent_;
102 DISALLOW_COPY_AND_ASSIGN(DeletionObserver);
105 void OnWebContentsDestroyed(DeletionObserver* observer);
107 typedef std::vector<DeletionObserver*> Observers;
108 Observers observers_;
110 DISALLOW_COPY_AND_ASSIGN(CloseTracker);
113 CloseTracker::CloseTracker(const Contents& contents) {
114 for (size_t i = 0; i < contents.size(); ++i)
115 observers_.push_back(new DeletionObserver(this, contents[i]));
118 CloseTracker::~CloseTracker() {
119 DCHECK(observers_.empty());
122 bool CloseTracker::HasNext() const {
123 return !observers_.empty();
126 WebContents* CloseTracker::Next() {
127 if (observers_.empty())
128 return NULL;
130 DeletionObserver* observer = observers_[0];
131 WebContents* web_contents = observer->web_contents();
132 observers_.erase(observers_.begin());
133 delete observer;
134 return web_contents;
137 void CloseTracker::OnWebContentsDestroyed(DeletionObserver* observer) {
138 Observers::iterator i =
139 std::find(observers_.begin(), observers_.end(), observer);
140 if (i != observers_.end()) {
141 delete *i;
142 observers_.erase(i);
143 return;
145 NOTREACHED() << "WebContents destroyed that wasn't in the list";
148 } // namespace
150 ///////////////////////////////////////////////////////////////////////////////
151 // WebContentsData
153 // An object to hold a reference to a WebContents that is in a tabstrip, as
154 // well as other various properties it has.
155 class TabStripModel::WebContentsData : public content::WebContentsObserver {
156 public:
157 WebContentsData(TabStripModel* tab_strip_model, WebContents* a_contents);
159 // Changes the WebContents that this WebContentsData tracks.
160 void SetWebContents(WebContents* contents);
161 WebContents* web_contents() { return contents_; }
163 // Create a relationship between this WebContentsData and other
164 // WebContentses. Used to identify which WebContents to select next after
165 // one is closed.
166 WebContents* group() const { return group_; }
167 void set_group(WebContents* value) { group_ = value; }
168 WebContents* opener() const { return opener_; }
169 void set_opener(WebContents* value) { opener_ = value; }
171 // Alters the properties of the WebContents.
172 bool reset_group_on_select() const { return reset_group_on_select_; }
173 void set_reset_group_on_select(bool value) { reset_group_on_select_ = value; }
174 bool pinned() const { return pinned_; }
175 void set_pinned(bool value) { pinned_ = value; }
176 bool blocked() const { return blocked_; }
177 void set_blocked(bool value) { blocked_ = value; }
179 private:
180 // Make sure that if someone deletes this WebContents out from under us, it
181 // is properly removed from the tab strip.
182 void WebContentsDestroyed() override;
184 // Marks the tab as no longer discarded if it has been reloaded from another
185 // source (ie: context menu).
186 void DidStartLoading() override;
188 // The WebContents being tracked by this WebContentsData. The
189 // WebContentsObserver does keep a reference, but when the WebContents is
190 // deleted, the WebContentsObserver reference is NULLed and thus inaccessible.
191 WebContents* contents_;
193 // The TabStripModel containing this WebContents.
194 TabStripModel* tab_strip_model_;
196 // The group is used to model a set of tabs spawned from a single parent
197 // tab. This value is preserved for a given tab as long as the tab remains
198 // navigated to the link it was initially opened at or some navigation from
199 // that page (i.e. if the user types or visits a bookmark or some other
200 // navigation within that tab, the group relationship is lost). This
201 // property can safely be used to implement features that depend on a
202 // logical group of related tabs.
203 WebContents* group_;
205 // The owner models the same relationship as group, except it is more
206 // easily discarded, e.g. when the user switches to a tab not part of the
207 // same group. This property is used to determine what tab to select next
208 // when one is closed.
209 WebContents* opener_;
211 // True if our group should be reset the moment selection moves away from
212 // this tab. This is the case for tabs opened in the foreground at the end
213 // of the TabStrip while viewing another Tab. If these tabs are closed
214 // before selection moves elsewhere, their opener is selected. But if
215 // selection shifts to _any_ tab (including their opener), the group
216 // relationship is reset to avoid confusing close sequencing.
217 bool reset_group_on_select_;
219 // Is the tab pinned?
220 bool pinned_;
222 // Is the tab interaction blocked by a modal dialog?
223 bool blocked_;
225 DISALLOW_COPY_AND_ASSIGN(WebContentsData);
228 TabStripModel::WebContentsData::WebContentsData(TabStripModel* tab_strip_model,
229 WebContents* contents)
230 : content::WebContentsObserver(contents),
231 contents_(contents),
232 tab_strip_model_(tab_strip_model),
233 group_(NULL),
234 opener_(NULL),
235 reset_group_on_select_(false),
236 pinned_(false),
237 blocked_(false) {}
239 void TabStripModel::WebContentsData::SetWebContents(WebContents* contents) {
240 contents_ = contents;
241 Observe(contents);
244 void TabStripModel::WebContentsData::WebContentsDestroyed() {
245 DCHECK_EQ(contents_, web_contents());
247 // Note that we only detach the contents here, not close it - it's
248 // already been closed. We just want to undo our bookkeeping.
249 int index = tab_strip_model_->GetIndexOfWebContents(web_contents());
250 DCHECK_NE(TabStripModel::kNoTab, index);
251 tab_strip_model_->DetachWebContentsAt(index);
254 void TabStripModel::WebContentsData::DidStartLoading() {
255 TabDiscardState::SetDiscardState(contents_, false);
258 ///////////////////////////////////////////////////////////////////////////////
259 // TabStripModel, public:
261 TabStripModel::TabStripModel(TabStripModelDelegate* delegate, Profile* profile)
262 : delegate_(delegate),
263 profile_(profile),
264 closing_all_(false),
265 in_notify_(false),
266 weak_factory_(this) {
267 DCHECK(delegate_);
268 order_controller_.reset(new TabStripModelOrderController(this));
271 TabStripModel::~TabStripModel() {
272 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
273 TabStripModelDeleted());
274 STLDeleteElements(&contents_data_);
275 order_controller_.reset();
278 void TabStripModel::AddObserver(TabStripModelObserver* observer) {
279 observers_.AddObserver(observer);
282 void TabStripModel::RemoveObserver(TabStripModelObserver* observer) {
283 observers_.RemoveObserver(observer);
286 bool TabStripModel::ContainsIndex(int index) const {
287 return index >= 0 && index < count();
290 void TabStripModel::AppendWebContents(WebContents* contents,
291 bool foreground) {
292 InsertWebContentsAt(count(), contents,
293 foreground ? (ADD_INHERIT_GROUP | ADD_ACTIVE) :
294 ADD_NONE);
297 void TabStripModel::InsertWebContentsAt(int index,
298 WebContents* contents,
299 int add_types) {
300 delegate_->WillAddWebContents(contents);
302 bool active = (add_types & ADD_ACTIVE) != 0;
303 bool pin = (add_types & ADD_PINNED) != 0;
304 index = ConstrainInsertionIndex(index, pin);
306 // In tab dragging situations, if the last tab in the window was detached
307 // then the user aborted the drag, we will have the |closing_all_| member
308 // set (see DetachWebContentsAt) which will mess with our mojo here. We need
309 // to clear this bit.
310 closing_all_ = false;
312 // Have to get the active contents before we monkey with the contents
313 // otherwise we run into problems when we try to change the active contents
314 // since the old contents and the new contents will be the same...
315 WebContents* active_contents = GetActiveWebContents();
316 WebContentsData* data = new WebContentsData(this, contents);
317 data->set_pinned(pin);
318 if ((add_types & ADD_INHERIT_GROUP) && active_contents) {
319 if (active) {
320 // Forget any existing relationships, we don't want to make things too
321 // confusing by having multiple groups active at the same time.
322 ForgetAllOpeners();
324 // Anything opened by a link we deem to have an opener.
325 data->set_group(active_contents);
326 data->set_opener(active_contents);
327 } else if ((add_types & ADD_INHERIT_OPENER) && active_contents) {
328 if (active) {
329 // Forget any existing relationships, we don't want to make things too
330 // confusing by having multiple groups active at the same time.
331 ForgetAllOpeners();
333 data->set_opener(active_contents);
336 // TODO(gbillock): Ask the modal dialog manager whether the WebContents should
337 // be blocked, or just let the modal dialog manager make the blocking call
338 // directly and not use this at all.
339 const web_modal::WebContentsModalDialogManager* manager =
340 web_modal::WebContentsModalDialogManager::FromWebContents(contents);
341 if (manager)
342 data->set_blocked(manager->IsDialogActive());
344 contents_data_.insert(contents_data_.begin() + index, data);
346 selection_model_.IncrementFrom(index);
348 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
349 TabInsertedAt(contents, index, active));
350 if (active) {
351 ui::ListSelectionModel new_model;
352 new_model.Copy(selection_model_);
353 new_model.SetSelectedIndex(index);
354 SetSelection(new_model, NOTIFY_DEFAULT);
358 WebContents* TabStripModel::ReplaceWebContentsAt(int index,
359 WebContents* new_contents) {
360 delegate_->WillAddWebContents(new_contents);
362 DCHECK(ContainsIndex(index));
363 WebContents* old_contents = GetWebContentsAtImpl(index);
365 FixOpenersAndGroupsReferencing(index);
367 contents_data_[index]->SetWebContents(new_contents);
369 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
370 TabReplacedAt(this, old_contents, new_contents, index));
372 // When the active WebContents is replaced send out a selection notification
373 // too. We do this as nearly all observers need to treat a replacement of the
374 // selected contents as the selection changing.
375 if (active_index() == index) {
376 FOR_EACH_OBSERVER(
377 TabStripModelObserver,
378 observers_,
379 ActiveTabChanged(old_contents,
380 new_contents,
381 active_index(),
382 TabStripModelObserver::CHANGE_REASON_REPLACED));
384 return old_contents;
387 WebContents* TabStripModel::DiscardWebContentsAt(int index) {
388 DCHECK(ContainsIndex(index));
389 // Do not discard active tab.
390 if (active_index() == index)
391 return NULL;
393 WebContents* null_contents =
394 WebContents::Create(WebContents::CreateParams(profile()));
395 WebContents* old_contents = GetWebContentsAtImpl(index);
396 bool is_playing_audio = old_contents->WasRecentlyAudible();
397 // Copy over the state from the navigation controller so we preserve the
398 // back/forward history and continue to display the correct title/favicon.
399 null_contents->GetController().CopyStateFrom(old_contents->GetController());
401 // Make sure we persist the last active time property.
402 null_contents->SetLastActiveTime(old_contents->GetLastActiveTime());
403 // Copy over the discard count.
404 TabDiscardState::CopyState(old_contents, null_contents);
406 // Replace the tab we're discarding with the null version.
407 ReplaceWebContentsAt(index, null_contents);
408 // Mark the tab so it will reload when we click.
409 if (!TabDiscardState::IsDiscarded(null_contents)) {
410 TabDiscardState::SetDiscardState(null_contents, true);
411 TabDiscardState::IncrementDiscardCount(null_contents);
412 RecordUMATabDiscarding(UMA_TAB_DISCARDING_DISCARD_TAB);
413 RecordUMADiscardCount(TabDiscardState::DiscardCount(null_contents));
414 if (is_playing_audio)
415 RecordUMATabDiscarding(UMA_TAB_DISCARDING_DISCARD_TAB_AUDIO);
417 // Discard the old tab's renderer.
418 // TODO(jamescook): This breaks script connections with other tabs.
419 // We need to find a different approach that doesn't do that, perhaps based
420 // on navigation to swappedout://.
421 delete old_contents;
422 return null_contents;
425 WebContents* TabStripModel::DetachWebContentsAt(int index) {
426 CHECK(!in_notify_);
427 if (contents_data_.empty())
428 return NULL;
429 DCHECK(ContainsIndex(index));
431 FixOpenersAndGroupsReferencing(index);
433 WebContents* removed_contents = GetWebContentsAtImpl(index);
434 bool was_selected = IsTabSelected(index);
435 int next_selected_index = order_controller_->DetermineNewSelectedIndex(index);
436 delete contents_data_[index];
437 contents_data_.erase(contents_data_.begin() + index);
438 if (empty())
439 closing_all_ = true;
440 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
441 TabDetachedAt(removed_contents, index));
442 if (empty()) {
443 selection_model_.Clear();
444 // TabDetachedAt() might unregister observers, so send |TabStripEmpty()| in
445 // a second pass.
446 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty());
447 } else {
448 int old_active = active_index();
449 selection_model_.DecrementFrom(index);
450 ui::ListSelectionModel old_model;
451 old_model.Copy(selection_model_);
452 if (index == old_active) {
453 NotifyIfTabDeactivated(removed_contents);
454 if (!selection_model_.empty()) {
455 // The active tab was removed, but there is still something selected.
456 // Move the active and anchor to the first selected index.
457 selection_model_.set_active(selection_model_.selected_indices()[0]);
458 selection_model_.set_anchor(selection_model_.active());
459 } else {
460 // The active tab was removed and nothing is selected. Reset the
461 // selection and send out notification.
462 selection_model_.SetSelectedIndex(next_selected_index);
464 NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT);
467 // Sending notification in case the detached tab was selected. Using
468 // NotifyIfActiveOrSelectionChanged() here would not guarantee that a
469 // notification is sent even though the tab selection has changed because
470 // |old_model| is stored after calling DecrementFrom().
471 if (was_selected) {
472 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
473 TabSelectionChanged(this, old_model));
476 return removed_contents;
479 void TabStripModel::ActivateTabAt(int index, bool user_gesture) {
480 DCHECK(ContainsIndex(index));
481 ui::ListSelectionModel new_model;
482 new_model.Copy(selection_model_);
483 new_model.SetSelectedIndex(index);
484 SetSelection(new_model, user_gesture ? NOTIFY_USER_GESTURE : NOTIFY_DEFAULT);
487 void TabStripModel::AddTabAtToSelection(int index) {
488 DCHECK(ContainsIndex(index));
489 ui::ListSelectionModel new_model;
490 new_model.Copy(selection_model_);
491 new_model.AddIndexToSelection(index);
492 SetSelection(new_model, NOTIFY_DEFAULT);
495 void TabStripModel::MoveWebContentsAt(int index,
496 int to_position,
497 bool select_after_move) {
498 DCHECK(ContainsIndex(index));
499 if (index == to_position)
500 return;
502 int first_non_pinned_tab = IndexOfFirstNonPinnedTab();
503 if ((index < first_non_pinned_tab && to_position >= first_non_pinned_tab) ||
504 (to_position < first_non_pinned_tab && index >= first_non_pinned_tab)) {
505 // This would result in pinned tabs mixed with non-pinned tabs. We don't
506 // allow that.
507 return;
510 MoveWebContentsAtImpl(index, to_position, select_after_move);
513 void TabStripModel::MoveSelectedTabsTo(int index) {
514 int total_pinned_count = IndexOfFirstNonPinnedTab();
515 int selected_pinned_count = 0;
516 int selected_count =
517 static_cast<int>(selection_model_.selected_indices().size());
518 for (int i = 0; i < selected_count &&
519 IsTabPinned(selection_model_.selected_indices()[i]); ++i) {
520 selected_pinned_count++;
523 // To maintain that all pinned tabs occur before non-pinned tabs we move them
524 // first.
525 if (selected_pinned_count > 0) {
526 MoveSelectedTabsToImpl(
527 std::min(total_pinned_count - selected_pinned_count, index), 0u,
528 selected_pinned_count);
529 if (index > total_pinned_count - selected_pinned_count) {
530 // We're being told to drag pinned tabs to an invalid location. Adjust the
531 // index such that non-pinned tabs end up at a location as though we could
532 // move the pinned tabs to index. See description in header for more
533 // details.
534 index += selected_pinned_count;
537 if (selected_pinned_count == selected_count)
538 return;
540 // Then move the non-pinned tabs.
541 MoveSelectedTabsToImpl(std::max(index, total_pinned_count),
542 selected_pinned_count,
543 selected_count - selected_pinned_count);
546 WebContents* TabStripModel::GetActiveWebContents() const {
547 return GetWebContentsAt(active_index());
550 WebContents* TabStripModel::GetWebContentsAt(int index) const {
551 if (ContainsIndex(index))
552 return GetWebContentsAtImpl(index);
553 return NULL;
556 int TabStripModel::GetIndexOfWebContents(const WebContents* contents) const {
557 for (size_t i = 0; i < contents_data_.size(); ++i) {
558 if (contents_data_[i]->web_contents() == contents)
559 return i;
561 return kNoTab;
564 void TabStripModel::UpdateWebContentsStateAt(int index,
565 TabStripModelObserver::TabChangeType change_type) {
566 DCHECK(ContainsIndex(index));
568 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
569 TabChangedAt(GetWebContentsAtImpl(index), index, change_type));
572 void TabStripModel::CloseAllTabs() {
573 // Set state so that observers can adjust their behavior to suit this
574 // specific condition when CloseWebContentsAt causes a flurry of
575 // Close/Detach/Select notifications to be sent.
576 closing_all_ = true;
577 std::vector<int> closing_tabs;
578 for (int i = count() - 1; i >= 0; --i)
579 closing_tabs.push_back(i);
580 InternalCloseTabs(closing_tabs, CLOSE_CREATE_HISTORICAL_TAB);
583 bool TabStripModel::CloseWebContentsAt(int index, uint32 close_types) {
584 DCHECK(ContainsIndex(index));
585 std::vector<int> closing_tabs;
586 closing_tabs.push_back(index);
587 return InternalCloseTabs(closing_tabs, close_types);
590 bool TabStripModel::TabsAreLoading() const {
591 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
592 iter != contents_data_.end(); ++iter) {
593 if ((*iter)->web_contents()->IsLoading())
594 return true;
596 return false;
599 WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) {
600 DCHECK(ContainsIndex(index));
601 return contents_data_[index]->opener();
604 void TabStripModel::SetOpenerOfWebContentsAt(int index,
605 WebContents* opener) {
606 DCHECK(ContainsIndex(index));
607 DCHECK(opener);
608 contents_data_[index]->set_opener(opener);
611 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener,
612 int start_index,
613 bool use_group) const {
614 DCHECK(opener);
615 DCHECK(ContainsIndex(start_index));
617 // Check tabs after start_index first.
618 for (int i = start_index + 1; i < count(); ++i) {
619 if (OpenerMatches(contents_data_[i], opener, use_group))
620 return i;
622 // Then check tabs before start_index, iterating backwards.
623 for (int i = start_index - 1; i >= 0; --i) {
624 if (OpenerMatches(contents_data_[i], opener, use_group))
625 return i;
627 return kNoTab;
630 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
631 int start_index) const {
632 DCHECK(opener);
633 DCHECK(ContainsIndex(start_index));
635 std::set<const WebContents*> opener_and_descendants;
636 opener_and_descendants.insert(opener);
637 int last_index = kNoTab;
639 for (int i = start_index + 1; i < count(); ++i) {
640 // Test opened by transitively, i.e. include tabs opened by tabs opened by
641 // opener, etc. Stop when we find the first non-descendant.
642 if (!opener_and_descendants.count(contents_data_[i]->opener())) {
643 // Skip over pinned tabs as new tabs are added after pinned tabs.
644 if (contents_data_[i]->pinned())
645 continue;
646 break;
648 opener_and_descendants.insert(contents_data_[i]->web_contents());
649 last_index = i;
651 return last_index;
654 void TabStripModel::TabNavigating(WebContents* contents,
655 ui::PageTransition transition) {
656 if (ShouldForgetOpenersForTransition(transition)) {
657 // Don't forget the openers if this tab is a New Tab page opened at the
658 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
659 // navigation of one of these transition types before resetting the
660 // opener relationships (this allows for the use case of opening a new
661 // tab to do a quick look-up of something while viewing a tab earlier in
662 // the strip). We can make this heuristic more permissive if need be.
663 if (!IsNewTabAtEndOfTabStrip(contents)) {
664 // If the user navigates the current tab to another page in any way
665 // other than by clicking a link, we want to pro-actively forget all
666 // TabStrip opener relationships since we assume they're beginning a
667 // different task by reusing the current tab.
668 ForgetAllOpeners();
669 // In this specific case we also want to reset the group relationship,
670 // since it is now technically invalid.
671 ForgetGroup(contents);
676 void TabStripModel::ForgetAllOpeners() {
677 // Forget all opener memories so we don't do anything weird with tab
678 // re-selection ordering.
679 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
680 iter != contents_data_.end(); ++iter)
681 (*iter)->set_opener(NULL);
684 void TabStripModel::ForgetGroup(WebContents* contents) {
685 int index = GetIndexOfWebContents(contents);
686 DCHECK(ContainsIndex(index));
687 contents_data_[index]->set_group(NULL);
688 contents_data_[index]->set_opener(NULL);
691 bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const {
692 int index = GetIndexOfWebContents(contents);
693 DCHECK(ContainsIndex(index));
694 return contents_data_[index]->reset_group_on_select();
697 void TabStripModel::SetTabBlocked(int index, bool blocked) {
698 DCHECK(ContainsIndex(index));
699 if (contents_data_[index]->blocked() == blocked)
700 return;
701 contents_data_[index]->set_blocked(blocked);
702 FOR_EACH_OBSERVER(
703 TabStripModelObserver, observers_,
704 TabBlockedStateChanged(contents_data_[index]->web_contents(),
705 index));
708 void TabStripModel::SetTabPinned(int index, bool pinned) {
709 DCHECK(ContainsIndex(index));
710 if (contents_data_[index]->pinned() == pinned)
711 return;
713 // The tab's position may have to change as the pinned tab state is changing.
714 int non_pinned_tab_index = IndexOfFirstNonPinnedTab();
715 contents_data_[index]->set_pinned(pinned);
716 if (pinned && index != non_pinned_tab_index) {
717 MoveWebContentsAtImpl(index, non_pinned_tab_index, false);
718 index = non_pinned_tab_index;
719 } else if (!pinned && index + 1 != non_pinned_tab_index) {
720 MoveWebContentsAtImpl(index, non_pinned_tab_index - 1, false);
721 index = non_pinned_tab_index - 1;
724 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
725 TabPinnedStateChanged(contents_data_[index]->web_contents(),
726 index));
729 bool TabStripModel::IsTabPinned(int index) const {
730 DCHECK(ContainsIndex(index));
731 return contents_data_[index]->pinned();
734 bool TabStripModel::IsTabBlocked(int index) const {
735 return contents_data_[index]->blocked();
738 int TabStripModel::IndexOfFirstNonPinnedTab() const {
739 for (size_t i = 0; i < contents_data_.size(); ++i) {
740 if (!IsTabPinned(static_cast<int>(i)))
741 return static_cast<int>(i);
743 // No pinned tabs.
744 return count();
747 int TabStripModel::ConstrainInsertionIndex(int index, bool pinned_tab) {
748 return pinned_tab ? std::min(std::max(0, index), IndexOfFirstNonPinnedTab()) :
749 std::min(count(), std::max(index, IndexOfFirstNonPinnedTab()));
752 void TabStripModel::ExtendSelectionTo(int index) {
753 DCHECK(ContainsIndex(index));
754 ui::ListSelectionModel new_model;
755 new_model.Copy(selection_model_);
756 new_model.SetSelectionFromAnchorTo(index);
757 SetSelection(new_model, NOTIFY_DEFAULT);
760 void TabStripModel::ToggleSelectionAt(int index) {
761 DCHECK(ContainsIndex(index));
762 ui::ListSelectionModel new_model;
763 new_model.Copy(selection_model());
764 if (selection_model_.IsSelected(index)) {
765 if (selection_model_.size() == 1) {
766 // One tab must be selected and this tab is currently selected so we can't
767 // unselect it.
768 return;
770 new_model.RemoveIndexFromSelection(index);
771 new_model.set_anchor(index);
772 if (new_model.active() == index ||
773 new_model.active() == ui::ListSelectionModel::kUnselectedIndex)
774 new_model.set_active(new_model.selected_indices()[0]);
775 } else {
776 new_model.AddIndexToSelection(index);
777 new_model.set_anchor(index);
778 new_model.set_active(index);
780 SetSelection(new_model, NOTIFY_DEFAULT);
783 void TabStripModel::AddSelectionFromAnchorTo(int index) {
784 ui::ListSelectionModel new_model;
785 new_model.Copy(selection_model_);
786 new_model.AddSelectionFromAnchorTo(index);
787 SetSelection(new_model, NOTIFY_DEFAULT);
790 bool TabStripModel::IsTabSelected(int index) const {
791 DCHECK(ContainsIndex(index));
792 return selection_model_.IsSelected(index);
795 void TabStripModel::SetSelectionFromModel(
796 const ui::ListSelectionModel& source) {
797 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
798 SetSelection(source, NOTIFY_DEFAULT);
801 void TabStripModel::AddWebContents(WebContents* contents,
802 int index,
803 ui::PageTransition transition,
804 int add_types) {
805 // If the newly-opened tab is part of the same task as the parent tab, we want
806 // to inherit the parent's "group" attribute, so that if this tab is then
807 // closed we'll jump back to the parent tab.
808 bool inherit_group = (add_types & ADD_INHERIT_GROUP) == ADD_INHERIT_GROUP;
810 if (transition == ui::PAGE_TRANSITION_LINK &&
811 (add_types & ADD_FORCE_INDEX) == 0) {
812 // We assume tabs opened via link clicks are part of the same task as their
813 // parent. Note that when |force_index| is true (e.g. when the user
814 // drag-and-drops a link to the tab strip), callers aren't really handling
815 // link clicks, they just want to score the navigation like a link click in
816 // the history backend, so we don't inherit the group in this case.
817 index = order_controller_->DetermineInsertionIndex(transition,
818 add_types & ADD_ACTIVE);
819 inherit_group = true;
820 } else {
821 // For all other types, respect what was passed to us, normalizing -1s and
822 // values that are too large.
823 if (index < 0 || index > count())
824 index = count();
827 if (transition == ui::PAGE_TRANSITION_TYPED && index == count()) {
828 // Also, any tab opened at the end of the TabStrip with a "TYPED"
829 // transition inherit group as well. This covers the cases where the user
830 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
831 // in the address bar and presses Alt+Enter. This allows for opening a new
832 // Tab to quickly look up something. When this Tab is closed, the old one
833 // is re-selected, not the next-adjacent.
834 inherit_group = true;
836 InsertWebContentsAt(index, contents,
837 add_types | (inherit_group ? ADD_INHERIT_GROUP : 0));
838 // Reset the index, just in case insert ended up moving it on us.
839 index = GetIndexOfWebContents(contents);
841 if (inherit_group && transition == ui::PAGE_TRANSITION_TYPED)
842 contents_data_[index]->set_reset_group_on_select(true);
844 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
845 // here we seem to get failures in startup perf tests.
846 // Ensure that the new WebContentsView begins at the same size as the
847 // previous WebContentsView if it existed. Otherwise, the initial WebKit
848 // layout will be performed based on a width of 0 pixels, causing a
849 // very long, narrow, inaccurate layout. Because some scripts on pages (as
850 // well as WebKit's anchor link location calculation) are run on the
851 // initial layout and not recalculated later, we need to ensure the first
852 // layout is performed with sane view dimensions even when we're opening a
853 // new background tab.
854 if (WebContents* old_contents = GetActiveWebContents()) {
855 if ((add_types & ADD_ACTIVE) == 0) {
856 ResizeWebContents(contents, old_contents->GetContainerBounds().size());
861 void TabStripModel::CloseSelectedTabs() {
862 InternalCloseTabs(selection_model_.selected_indices(),
863 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
866 void TabStripModel::SelectNextTab() {
867 SelectRelativeTab(true);
870 void TabStripModel::SelectPreviousTab() {
871 SelectRelativeTab(false);
874 void TabStripModel::SelectLastTab() {
875 ActivateTabAt(count() - 1, true);
878 void TabStripModel::MoveTabNext() {
879 // TODO: this likely needs to be updated for multi-selection.
880 int new_index = std::min(active_index() + 1, count() - 1);
881 MoveWebContentsAt(active_index(), new_index, true);
884 void TabStripModel::MoveTabPrevious() {
885 // TODO: this likely needs to be updated for multi-selection.
886 int new_index = std::max(active_index() - 1, 0);
887 MoveWebContentsAt(active_index(), new_index, true);
890 // Context menu functions.
891 bool TabStripModel::IsContextMenuCommandEnabled(
892 int context_index, ContextMenuCommand command_id) const {
893 DCHECK(command_id > CommandFirst && command_id < CommandLast);
894 switch (command_id) {
895 case CommandNewTab:
896 case CommandCloseTab:
897 return true;
899 case CommandReload: {
900 std::vector<int> indices = GetIndicesForCommand(context_index);
901 for (size_t i = 0; i < indices.size(); ++i) {
902 WebContents* tab = GetWebContentsAt(indices[i]);
903 if (tab) {
904 CoreTabHelperDelegate* core_delegate =
905 CoreTabHelper::FromWebContents(tab)->delegate();
906 if (!core_delegate || core_delegate->CanReloadContents(tab))
907 return true;
910 return false;
913 case CommandCloseOtherTabs:
914 case CommandCloseTabsToRight:
915 return !GetIndicesClosedByCommand(context_index, command_id).empty();
917 case CommandDuplicate: {
918 std::vector<int> indices = GetIndicesForCommand(context_index);
919 for (size_t i = 0; i < indices.size(); ++i) {
920 if (delegate_->CanDuplicateContentsAt(indices[i]))
921 return true;
923 return false;
926 case CommandRestoreTab:
927 return delegate_->GetRestoreTabType() !=
928 TabStripModelDelegate::RESTORE_NONE;
930 case CommandToggleTabAudioMuted: {
931 std::vector<int> indices = GetIndicesForCommand(context_index);
932 for (size_t i = 0; i < indices.size(); ++i) {
933 if (!chrome::CanToggleAudioMute(GetWebContentsAt(indices[i])))
934 return false;
936 return true;
939 case CommandBookmarkAllTabs:
940 return browser_defaults::bookmarks_enabled &&
941 delegate_->CanBookmarkAllTabs();
943 case CommandTogglePinned:
944 case CommandSelectByDomain:
945 case CommandSelectByOpener:
946 return true;
948 default:
949 NOTREACHED();
951 return false;
954 void TabStripModel::ExecuteContextMenuCommand(
955 int context_index, ContextMenuCommand command_id) {
956 DCHECK(command_id > CommandFirst && command_id < CommandLast);
957 switch (command_id) {
958 case CommandNewTab:
959 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
960 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
961 TabStripModel::NEW_TAB_CONTEXT_MENU,
962 TabStripModel::NEW_TAB_ENUM_COUNT);
963 delegate()->AddTabAt(GURL(), context_index + 1, true);
964 break;
966 case CommandReload: {
967 content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
968 std::vector<int> indices = GetIndicesForCommand(context_index);
969 for (size_t i = 0; i < indices.size(); ++i) {
970 WebContents* tab = GetWebContentsAt(indices[i]);
971 if (tab) {
972 CoreTabHelperDelegate* core_delegate =
973 CoreTabHelper::FromWebContents(tab)->delegate();
974 if (!core_delegate || core_delegate->CanReloadContents(tab))
975 tab->GetController().Reload(true);
978 break;
981 case CommandDuplicate: {
982 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
983 std::vector<int> indices = GetIndicesForCommand(context_index);
984 // Copy the WebContents off as the indices will change as tabs are
985 // duplicated.
986 std::vector<WebContents*> tabs;
987 for (size_t i = 0; i < indices.size(); ++i)
988 tabs.push_back(GetWebContentsAt(indices[i]));
989 for (size_t i = 0; i < tabs.size(); ++i) {
990 int index = GetIndexOfWebContents(tabs[i]);
991 if (index != -1 && delegate_->CanDuplicateContentsAt(index))
992 delegate_->DuplicateContentsAt(index);
994 break;
997 case CommandCloseTab: {
998 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
999 InternalCloseTabs(GetIndicesForCommand(context_index),
1000 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
1001 break;
1004 case CommandCloseOtherTabs: {
1005 content::RecordAction(
1006 UserMetricsAction("TabContextMenu_CloseOtherTabs"));
1007 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1008 CLOSE_CREATE_HISTORICAL_TAB);
1009 break;
1012 case CommandCloseTabsToRight: {
1013 content::RecordAction(
1014 UserMetricsAction("TabContextMenu_CloseTabsToRight"));
1015 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1016 CLOSE_CREATE_HISTORICAL_TAB);
1017 break;
1020 case CommandRestoreTab: {
1021 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1022 delegate_->RestoreTab();
1023 break;
1026 case CommandTogglePinned: {
1027 content::RecordAction(
1028 UserMetricsAction("TabContextMenu_TogglePinned"));
1029 std::vector<int> indices = GetIndicesForCommand(context_index);
1030 bool pin = WillContextMenuPin(context_index);
1031 if (pin) {
1032 for (size_t i = 0; i < indices.size(); ++i)
1033 SetTabPinned(indices[i], true);
1034 } else {
1035 // Unpin from the back so that the order is maintained (unpinning can
1036 // trigger moving a tab).
1037 for (size_t i = indices.size(); i > 0; --i)
1038 SetTabPinned(indices[i - 1], false);
1040 break;
1043 case CommandToggleTabAudioMuted: {
1044 const std::vector<int>& indices = GetIndicesForCommand(context_index);
1045 const bool mute = !chrome::AreAllTabsMuted(*this, indices);
1046 if (mute)
1047 content::RecordAction(UserMetricsAction("TabContextMenu_MuteTabs"));
1048 else
1049 content::RecordAction(UserMetricsAction("TabContextMenu_UnmuteTabs"));
1050 for (std::vector<int>::const_iterator i = indices.begin();
1051 i != indices.end(); ++i) {
1052 chrome::SetTabAudioMuted(GetWebContentsAt(*i), mute,
1053 TAB_MUTED_REASON_CONTEXT_MENU, std::string());
1055 break;
1058 case CommandBookmarkAllTabs: {
1059 content::RecordAction(
1060 UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1062 delegate_->BookmarkAllTabs();
1063 break;
1066 case CommandSelectByDomain:
1067 case CommandSelectByOpener: {
1068 std::vector<int> indices;
1069 if (command_id == CommandSelectByDomain)
1070 GetIndicesWithSameDomain(context_index, &indices);
1071 else
1072 GetIndicesWithSameOpener(context_index, &indices);
1073 ui::ListSelectionModel selection_model;
1074 selection_model.SetSelectedIndex(context_index);
1075 for (size_t i = 0; i < indices.size(); ++i)
1076 selection_model.AddIndexToSelection(indices[i]);
1077 SetSelectionFromModel(selection_model);
1078 break;
1081 default:
1082 NOTREACHED();
1086 std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1087 int index,
1088 ContextMenuCommand id) const {
1089 DCHECK(ContainsIndex(index));
1090 DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1091 bool is_selected = IsTabSelected(index);
1092 int start;
1093 if (id == CommandCloseTabsToRight) {
1094 if (is_selected) {
1095 start = selection_model_.selected_indices()[
1096 selection_model_.selected_indices().size() - 1] + 1;
1097 } else {
1098 start = index + 1;
1100 } else {
1101 start = 0;
1103 // NOTE: callers expect the vector to be sorted in descending order.
1104 std::vector<int> indices;
1105 for (int i = count() - 1; i >= start; --i) {
1106 if (i != index && !IsTabPinned(i) && (!is_selected || !IsTabSelected(i)))
1107 indices.push_back(i);
1109 return indices;
1112 bool TabStripModel::WillContextMenuPin(int index) {
1113 std::vector<int> indices = GetIndicesForCommand(index);
1114 // If all tabs are pinned, then we unpin, otherwise we pin.
1115 bool all_pinned = true;
1116 for (size_t i = 0; i < indices.size() && all_pinned; ++i)
1117 all_pinned = IsTabPinned(indices[i]);
1118 return !all_pinned;
1121 // static
1122 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1123 int* browser_cmd) {
1124 switch (cmd_id) {
1125 case CommandNewTab:
1126 *browser_cmd = IDC_NEW_TAB;
1127 break;
1128 case CommandReload:
1129 *browser_cmd = IDC_RELOAD;
1130 break;
1131 case CommandDuplicate:
1132 *browser_cmd = IDC_DUPLICATE_TAB;
1133 break;
1134 case CommandCloseTab:
1135 *browser_cmd = IDC_CLOSE_TAB;
1136 break;
1137 case CommandRestoreTab:
1138 *browser_cmd = IDC_RESTORE_TAB;
1139 break;
1140 case CommandBookmarkAllTabs:
1141 *browser_cmd = IDC_BOOKMARK_ALL_TABS;
1142 break;
1143 default:
1144 *browser_cmd = 0;
1145 return false;
1148 return true;
1151 ///////////////////////////////////////////////////////////////////////////////
1152 // TabStripModel, private:
1154 std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices(
1155 const std::vector<int>& indices) const {
1156 std::vector<WebContents*> contents;
1157 for (size_t i = 0; i < indices.size(); ++i)
1158 contents.push_back(GetWebContentsAtImpl(indices[i]));
1159 return contents;
1162 void TabStripModel::GetIndicesWithSameDomain(int index,
1163 std::vector<int>* indices) {
1164 std::string domain = GetWebContentsAt(index)->GetURL().host();
1165 if (domain.empty())
1166 return;
1167 for (int i = 0; i < count(); ++i) {
1168 if (i == index)
1169 continue;
1170 if (GetWebContentsAt(i)->GetURL().host() == domain)
1171 indices->push_back(i);
1175 void TabStripModel::GetIndicesWithSameOpener(int index,
1176 std::vector<int>* indices) {
1177 WebContents* opener = contents_data_[index]->group();
1178 if (!opener) {
1179 // If there is no group, find all tabs with the selected tab as the opener.
1180 opener = GetWebContentsAt(index);
1181 if (!opener)
1182 return;
1184 for (int i = 0; i < count(); ++i) {
1185 if (i == index)
1186 continue;
1187 if (contents_data_[i]->group() == opener ||
1188 GetWebContentsAtImpl(i) == opener) {
1189 indices->push_back(i);
1194 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1195 if (!IsTabSelected(index)) {
1196 std::vector<int> indices;
1197 indices.push_back(index);
1198 return indices;
1200 return selection_model_.selected_indices();
1203 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1204 const GURL& url = contents->GetURL();
1205 return url.SchemeIs(content::kChromeUIScheme) &&
1206 url.host() == chrome::kChromeUINewTabHost &&
1207 contents == GetWebContentsAtImpl(count() - 1) &&
1208 contents->GetController().GetEntryCount() == 1;
1211 bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
1212 uint32 close_types) {
1213 if (indices.empty())
1214 return true;
1216 CloseTracker close_tracker(GetWebContentsFromIndices(indices));
1218 base::WeakPtr<TabStripModel> ref(weak_factory_.GetWeakPtr());
1219 const bool closing_all = indices.size() == contents_data_.size();
1220 if (closing_all)
1221 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, WillCloseAllTabs());
1223 // We only try the fast shutdown path if the whole browser process is *not*
1224 // shutting down. Fast shutdown during browser termination is handled in
1225 // BrowserShutdown.
1226 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
1227 // Construct a map of processes to the number of associated tabs that are
1228 // closing.
1229 std::map<content::RenderProcessHost*, size_t> processes;
1230 for (size_t i = 0; i < indices.size(); ++i) {
1231 WebContents* closing_contents = GetWebContentsAtImpl(indices[i]);
1232 if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents))
1233 continue;
1234 content::RenderProcessHost* process =
1235 closing_contents->GetRenderProcessHost();
1236 ++processes[process];
1239 // Try to fast shutdown the tabs that can close.
1240 for (std::map<content::RenderProcessHost*, size_t>::iterator iter =
1241 processes.begin(); iter != processes.end(); ++iter) {
1242 iter->first->FastShutdownForPageCount(iter->second);
1246 // We now return to our regularly scheduled shutdown procedure.
1247 bool retval = true;
1248 while (close_tracker.HasNext()) {
1249 WebContents* closing_contents = close_tracker.Next();
1250 int index = GetIndexOfWebContents(closing_contents);
1251 // Make sure we still contain the tab.
1252 if (index == kNoTab)
1253 continue;
1255 CoreTabHelper* core_tab_helper =
1256 CoreTabHelper::FromWebContents(closing_contents);
1257 core_tab_helper->OnCloseStarted();
1259 // Update the explicitly closed state. If the unload handlers cancel the
1260 // close the state is reset in Browser. We don't update the explicitly
1261 // closed state if already marked as explicitly closed as unload handlers
1262 // call back to this if the close is allowed.
1263 if (!closing_contents->GetClosedByUserGesture()) {
1264 closing_contents->SetClosedByUserGesture(
1265 close_types & CLOSE_USER_GESTURE);
1268 if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) {
1269 retval = false;
1270 continue;
1273 InternalCloseTab(closing_contents, index,
1274 (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
1277 if (ref && closing_all && !retval) {
1278 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1279 CloseAllTabsCanceled());
1282 return retval;
1285 void TabStripModel::InternalCloseTab(WebContents* contents,
1286 int index,
1287 bool create_historical_tabs) {
1288 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1289 TabClosingAt(this, contents, index));
1291 // Ask the delegate to save an entry for this tab in the historical tab
1292 // database if applicable.
1293 if (create_historical_tabs)
1294 delegate_->CreateHistoricalTab(contents);
1296 // Deleting the WebContents will call back to us via
1297 // WebContentsData::WebContentsDestroyed and detach it.
1298 delete contents;
1301 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1302 CHECK(ContainsIndex(index)) <<
1303 "Failed to find: " << index << " in: " << count() << " entries.";
1304 return contents_data_[index]->web_contents();
1307 void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) {
1308 if (contents) {
1309 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1310 TabDeactivated(contents));
1314 void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents,
1315 NotifyTypes notify_types) {
1316 WebContents* new_contents = GetWebContentsAtImpl(active_index());
1317 if (old_contents != new_contents) {
1318 int reason = notify_types == NOTIFY_USER_GESTURE
1319 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1320 : TabStripModelObserver::CHANGE_REASON_NONE;
1321 CHECK(!in_notify_);
1322 in_notify_ = true;
1323 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1324 ActiveTabChanged(old_contents,
1325 new_contents,
1326 active_index(),
1327 reason));
1328 in_notify_ = false;
1329 TabDiscardState::SetDiscardState(new_contents, false);
1333 void TabStripModel::NotifyIfActiveOrSelectionChanged(
1334 WebContents* old_contents,
1335 NotifyTypes notify_types,
1336 const ui::ListSelectionModel& old_model) {
1337 NotifyIfActiveTabChanged(old_contents, notify_types);
1339 if (!selection_model().Equals(old_model)) {
1340 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1341 TabSelectionChanged(this, old_model));
1345 void TabStripModel::SetSelection(
1346 const ui::ListSelectionModel& new_model,
1347 NotifyTypes notify_types) {
1348 WebContents* old_contents = GetActiveWebContents();
1349 ui::ListSelectionModel old_model;
1350 old_model.Copy(selection_model_);
1351 if (new_model.active() != selection_model_.active())
1352 NotifyIfTabDeactivated(old_contents);
1353 selection_model_.Copy(new_model);
1354 NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model);
1357 void TabStripModel::SelectRelativeTab(bool next) {
1358 // This may happen during automated testing or if a user somehow buffers
1359 // many key accelerators.
1360 if (contents_data_.empty())
1361 return;
1363 int index = active_index();
1364 int delta = next ? 1 : -1;
1365 index = (index + count() + delta) % count();
1366 ActivateTabAt(index, true);
1369 void TabStripModel::MoveWebContentsAtImpl(int index,
1370 int to_position,
1371 bool select_after_move) {
1372 FixOpenersAndGroupsReferencing(index);
1374 WebContentsData* moved_data = contents_data_[index];
1375 contents_data_.erase(contents_data_.begin() + index);
1376 contents_data_.insert(contents_data_.begin() + to_position, moved_data);
1378 selection_model_.Move(index, to_position);
1379 if (!selection_model_.IsSelected(select_after_move) && select_after_move) {
1380 // TODO(sky): why doesn't this code notify observers?
1381 selection_model_.SetSelectedIndex(to_position);
1384 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1385 TabMoved(moved_data->web_contents(), index, to_position));
1388 void TabStripModel::MoveSelectedTabsToImpl(int index,
1389 size_t start,
1390 size_t length) {
1391 DCHECK(start < selection_model_.selected_indices().size() &&
1392 start + length <= selection_model_.selected_indices().size());
1393 size_t end = start + length;
1394 int count_before_index = 0;
1395 for (size_t i = start; i < end &&
1396 selection_model_.selected_indices()[i] < index + count_before_index;
1397 ++i) {
1398 count_before_index++;
1401 // First move those before index. Any tabs before index end up moving in the
1402 // selection model so we use start each time through.
1403 int target_index = index + count_before_index;
1404 size_t tab_index = start;
1405 while (tab_index < end &&
1406 selection_model_.selected_indices()[start] < index) {
1407 MoveWebContentsAt(selection_model_.selected_indices()[start],
1408 target_index - 1, false);
1409 tab_index++;
1412 // Then move those after the index. These don't result in reordering the
1413 // selection.
1414 while (tab_index < end) {
1415 if (selection_model_.selected_indices()[tab_index] != target_index) {
1416 MoveWebContentsAt(selection_model_.selected_indices()[tab_index],
1417 target_index, false);
1419 tab_index++;
1420 target_index++;
1424 // static
1425 bool TabStripModel::OpenerMatches(const WebContentsData* data,
1426 const WebContents* opener,
1427 bool use_group) {
1428 return data->opener() == opener || (use_group && data->group() == opener);
1431 void TabStripModel::FixOpenersAndGroupsReferencing(int index) {
1432 WebContents* old_contents = GetWebContentsAtImpl(index);
1433 for (WebContentsData* data : contents_data_) {
1434 if (data->group() == old_contents)
1435 data->set_group(contents_data_[index]->group());
1436 if (data->opener() == old_contents)
1437 data->set_opener(contents_data_[index]->opener());