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.
4
5#include "chrome/browser/ui/tabs/tab_strip_model.h"
6
7#include <algorithm>
8#include <map>
9#include <string>
10
11#include "base/metrics/histogram.h"
12#include "base/stl_util.h"
13#include "chrome/app/chrome_command_ids.h"
14#include "chrome/browser/browser_shutdown.h"
15#include "chrome/browser/defaults.h"
16#include "chrome/browser/extensions/tab_helper.h"
17#include "chrome/browser/profiles/profile.h"
18#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
19#include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h"
20#include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
21#include "chrome/browser/ui/tabs/tab_strip_model_order_controller.h"
22#include "chrome/browser/ui/tabs/tab_utils.h"
23#include "chrome/browser/ui/web_contents_sizer.h"
24#include "chrome/common/url_constants.h"
25#include "components/web_modal/popup_manager.h"
26#include "content/public/browser/render_process_host.h"
27#include "content/public/browser/user_metrics.h"
28#include "content/public/browser/web_contents.h"
29#include "content/public/browser/web_contents_observer.h"
30using base::UserMetricsAction;
31using content::WebContents;
32
33namespace {
34
35// Returns true if the specified transition is one of the types that cause the
36// opener relationships for the tab in which the transition occurred to be
37// forgotten. This is generally any navigation that isn't a link click (i.e.
38// any navigation that can be considered to be the start of a new task distinct
39// from what had previously occurred in that tab).
40bool ShouldForgetOpenersForTransition(ui::PageTransition transition) {
41  return transition == ui::PAGE_TRANSITION_TYPED ||
42      transition == ui::PAGE_TRANSITION_AUTO_BOOKMARK ||
43      transition == ui::PAGE_TRANSITION_GENERATED ||
44      transition == ui::PAGE_TRANSITION_KEYWORD ||
45      transition == ui::PAGE_TRANSITION_AUTO_TOPLEVEL;
46}
47
48// CloseTracker is used when closing a set of WebContents. It listens for
49// deletions of the WebContents and removes from the internal set any time one
50// is deleted.
51class CloseTracker {
52 public:
53  typedef std::vector<WebContents*> Contents;
54
55  explicit CloseTracker(const Contents& contents);
56  virtual ~CloseTracker();
57
58  // Returns true if there is another WebContents in the Tracker.
59  bool HasNext() const;
60
61  // Returns the next WebContents, or NULL if there are no more.
62  WebContents* Next();
63
64 private:
65  class DeletionObserver : public content::WebContentsObserver {
66   public:
67    DeletionObserver(CloseTracker* parent, WebContents* web_contents)
68        : WebContentsObserver(web_contents),
69          parent_(parent) {
70    }
71
72   private:
73    // WebContentsObserver:
74    virtual void WebContentsDestroyed() OVERRIDE {
75      parent_->OnWebContentsDestroyed(this);
76    }
77
78    CloseTracker* parent_;
79
80    DISALLOW_COPY_AND_ASSIGN(DeletionObserver);
81  };
82
83  void OnWebContentsDestroyed(DeletionObserver* observer);
84
85  typedef std::vector<DeletionObserver*> Observers;
86  Observers observers_;
87
88  DISALLOW_COPY_AND_ASSIGN(CloseTracker);
89};
90
91CloseTracker::CloseTracker(const Contents& contents) {
92  for (size_t i = 0; i < contents.size(); ++i)
93    observers_.push_back(new DeletionObserver(this, contents[i]));
94}
95
96CloseTracker::~CloseTracker() {
97  DCHECK(observers_.empty());
98}
99
100bool CloseTracker::HasNext() const {
101  return !observers_.empty();
102}
103
104WebContents* CloseTracker::Next() {
105  if (observers_.empty())
106    return NULL;
107
108  DeletionObserver* observer = observers_[0];
109  WebContents* web_contents = observer->web_contents();
110  observers_.erase(observers_.begin());
111  delete observer;
112  return web_contents;
113}
114
115void CloseTracker::OnWebContentsDestroyed(DeletionObserver* observer) {
116  Observers::iterator i =
117      std::find(observers_.begin(), observers_.end(), observer);
118  if (i != observers_.end()) {
119    delete *i;
120    observers_.erase(i);
121    return;
122  }
123  NOTREACHED() << "WebContents destroyed that wasn't in the list";
124}
125
126}  // namespace
127
128///////////////////////////////////////////////////////////////////////////////
129// WebContentsData
130
131// An object to hold a reference to a WebContents that is in a tabstrip, as
132// well as other various properties it has.
133class TabStripModel::WebContentsData : public content::WebContentsObserver {
134 public:
135  WebContentsData(TabStripModel* tab_strip_model, WebContents* a_contents);
136
137  // Changes the WebContents that this WebContentsData tracks.
138  void SetWebContents(WebContents* contents);
139  WebContents* web_contents() { return contents_; }
140
141  // Create a relationship between this WebContentsData and other
142  // WebContentses. Used to identify which WebContents to select next after
143  // one is closed.
144  WebContents* group() const { return group_; }
145  void set_group(WebContents* value) { group_ = value; }
146  WebContents* opener() const { return opener_; }
147  void set_opener(WebContents* value) { opener_ = value; }
148
149  // Alters the properties of the WebContents.
150  bool reset_group_on_select() const { return reset_group_on_select_; }
151  void set_reset_group_on_select(bool value) { reset_group_on_select_ = value; }
152  bool pinned() const { return pinned_; }
153  void set_pinned(bool value) { pinned_ = value; }
154  bool blocked() const { return blocked_; }
155  void set_blocked(bool value) { blocked_ = value; }
156  bool discarded() const { return discarded_; }
157  void set_discarded(bool value) { discarded_ = value; }
158
159 private:
160  // Make sure that if someone deletes this WebContents out from under us, it
161  // is properly removed from the tab strip.
162  virtual void WebContentsDestroyed() OVERRIDE;
163
164  // The WebContents being tracked by this WebContentsData. The
165  // WebContentsObserver does keep a reference, but when the WebContents is
166  // deleted, the WebContentsObserver reference is NULLed and thus inaccessible.
167  WebContents* contents_;
168
169  // The TabStripModel containing this WebContents.
170  TabStripModel* tab_strip_model_;
171
172  // The group is used to model a set of tabs spawned from a single parent
173  // tab. This value is preserved for a given tab as long as the tab remains
174  // navigated to the link it was initially opened at or some navigation from
175  // that page (i.e. if the user types or visits a bookmark or some other
176  // navigation within that tab, the group relationship is lost). This
177  // property can safely be used to implement features that depend on a
178  // logical group of related tabs.
179  WebContents* group_;
180
181  // The owner models the same relationship as group, except it is more
182  // easily discarded, e.g. when the user switches to a tab not part of the
183  // same group. This property is used to determine what tab to select next
184  // when one is closed.
185  WebContents* opener_;
186
187  // True if our group should be reset the moment selection moves away from
188  // this tab. This is the case for tabs opened in the foreground at the end
189  // of the TabStrip while viewing another Tab. If these tabs are closed
190  // before selection moves elsewhere, their opener is selected. But if
191  // selection shifts to _any_ tab (including their opener), the group
192  // relationship is reset to avoid confusing close sequencing.
193  bool reset_group_on_select_;
194
195  // Is the tab pinned?
196  bool pinned_;
197
198  // Is the tab interaction blocked by a modal dialog?
199  bool blocked_;
200
201  // Has the tab data been discarded to save memory?
202  bool discarded_;
203
204  DISALLOW_COPY_AND_ASSIGN(WebContentsData);
205};
206
207TabStripModel::WebContentsData::WebContentsData(TabStripModel* tab_strip_model,
208                                                WebContents* contents)
209    : content::WebContentsObserver(contents),
210      contents_(contents),
211      tab_strip_model_(tab_strip_model),
212      group_(NULL),
213      opener_(NULL),
214      reset_group_on_select_(false),
215      pinned_(false),
216      blocked_(false),
217      discarded_(false) {
218}
219
220void TabStripModel::WebContentsData::SetWebContents(WebContents* contents) {
221  contents_ = contents;
222  Observe(contents);
223}
224
225void TabStripModel::WebContentsData::WebContentsDestroyed() {
226  DCHECK_EQ(contents_, web_contents());
227
228  // Note that we only detach the contents here, not close it - it's
229  // already been closed. We just want to undo our bookkeeping.
230  int index = tab_strip_model_->GetIndexOfWebContents(web_contents());
231  DCHECK_NE(TabStripModel::kNoTab, index);
232  tab_strip_model_->DetachWebContentsAt(index);
233}
234
235///////////////////////////////////////////////////////////////////////////////
236// TabStripModel, public:
237
238TabStripModel::TabStripModel(TabStripModelDelegate* delegate, Profile* profile)
239    : delegate_(delegate),
240      profile_(profile),
241      closing_all_(false),
242      in_notify_(false),
243      weak_factory_(this) {
244  DCHECK(delegate_);
245  order_controller_.reset(new TabStripModelOrderController(this));
246}
247
248TabStripModel::~TabStripModel() {
249  FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
250                    TabStripModelDeleted());
251  STLDeleteElements(&contents_data_);
252  order_controller_.reset();
253}
254
255void TabStripModel::AddObserver(TabStripModelObserver* observer) {
256  observers_.AddObserver(observer);
257}
258
259void TabStripModel::RemoveObserver(TabStripModelObserver* observer) {
260  observers_.RemoveObserver(observer);
261}
262
263bool TabStripModel::ContainsIndex(int index) const {
264  return index >= 0 && index < count();
265}
266
267void TabStripModel::AppendWebContents(WebContents* contents,
268                                      bool foreground) {
269  InsertWebContentsAt(count(), contents,
270                      foreground ? (ADD_INHERIT_GROUP | ADD_ACTIVE) :
271                                   ADD_NONE);
272}
273
274void TabStripModel::InsertWebContentsAt(int index,
275                                        WebContents* contents,
276                                        int add_types) {
277  delegate_->WillAddWebContents(contents);
278
279  bool active = add_types & ADD_ACTIVE;
280  // Force app tabs to be pinned.
281  extensions::TabHelper* extensions_tab_helper =
282      extensions::TabHelper::FromWebContents(contents);
283  bool pin = extensions_tab_helper->is_app() || add_types & ADD_PINNED;
284  index = ConstrainInsertionIndex(index, pin);
285
286  // In tab dragging situations, if the last tab in the window was detached
287  // then the user aborted the drag, we will have the |closing_all_| member
288  // set (see DetachWebContentsAt) which will mess with our mojo here. We need
289  // to clear this bit.
290  closing_all_ = false;
291
292  // Have to get the active contents before we monkey with the contents
293  // otherwise we run into problems when we try to change the active contents
294  // since the old contents and the new contents will be the same...
295  WebContents* active_contents = GetActiveWebContents();
296  WebContentsData* data = new WebContentsData(this, contents);
297  data->set_pinned(pin);
298  if ((add_types & ADD_INHERIT_GROUP) && active_contents) {
299    if (active) {
300      // Forget any existing relationships, we don't want to make things too
301      // confusing by having multiple groups active at the same time.
302      ForgetAllOpeners();
303    }
304    // Anything opened by a link we deem to have an opener.
305    data->set_group(active_contents);
306    data->set_opener(active_contents);
307  } else if ((add_types & ADD_INHERIT_OPENER) && active_contents) {
308    if (active) {
309      // Forget any existing relationships, we don't want to make things too
310      // confusing by having multiple groups active at the same time.
311      ForgetAllOpeners();
312    }
313    data->set_opener(active_contents);
314  }
315
316  // TODO(gbillock): Ask the bubble manager whether the WebContents should be
317  // blocked, or just let the bubble manager make the blocking call directly
318  // and not use this at all.
319  web_modal::PopupManager* popup_manager =
320      web_modal::PopupManager::FromWebContents(contents);
321  if (popup_manager)
322    data->set_blocked(popup_manager->IsWebModalDialogActive(contents));
323
324  contents_data_.insert(contents_data_.begin() + index, data);
325
326  selection_model_.IncrementFrom(index);
327
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);
335  }
336}
337
338WebContents* TabStripModel::ReplaceWebContentsAt(int index,
339                                                 WebContents* new_contents) {
340  delegate_->WillAddWebContents(new_contents);
341
342  DCHECK(ContainsIndex(index));
343  WebContents* old_contents = GetWebContentsAtImpl(index);
344
345  ForgetOpenersAndGroupsReferencing(old_contents);
346
347  contents_data_[index]->SetWebContents(new_contents);
348
349  FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
350                    TabReplacedAt(this, old_contents, new_contents, index));
351
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));
363  }
364  return old_contents;
365}
366
367WebContents* TabStripModel::DiscardWebContentsAt(int index) {
368  DCHECK(ContainsIndex(index));
369  // Do not discard active tab.
370  if (active_index() == index)
371    return NULL;
372
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;
389}
390
391WebContents* TabStripModel::DetachWebContentsAt(int index) {
392  CHECK(!in_notify_);
393  if (contents_data_.empty())
394    return NULL;
395
396  DCHECK(ContainsIndex(index));
397
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);
429      }
430      NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT);
431    }
432
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));
440    }
441  }
442  return removed_contents;
443}
444
445void 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);
451}
452
453void 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);
459}
460
461void TabStripModel::MoveWebContentsAt(int index,
462                                      int to_position,
463                                      bool select_after_move) {
464  DCHECK(ContainsIndex(index));
465  if (index == to_position)
466    return;
467
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;
474  }
475
476  MoveWebContentsAtImpl(index, to_position, select_after_move);
477}
478
479void 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++;
487  }
488
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;
501    }
502  }
503  if (selected_mini_count == selected_count)
504    return;
505
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);
510}
511
512WebContents* TabStripModel::GetActiveWebContents() const {
513  return GetWebContentsAt(active_index());
514}
515
516WebContents* TabStripModel::GetWebContentsAt(int index) const {
517  if (ContainsIndex(index))
518    return GetWebContentsAtImpl(index);
519  return NULL;
520}
521
522int 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;
526  }
527  return kNoTab;
528}
529
530void TabStripModel::UpdateWebContentsStateAt(int index,
531    TabStripModelObserver::TabChangeType change_type) {
532  DCHECK(ContainsIndex(index));
533
534  FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
535      TabChangedAt(GetWebContentsAtImpl(index), index, change_type));
536}
537
538void 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);
547}
548
549bool 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);
554}
555
556bool 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;
561  }
562  return false;
563}
564
565WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) {
566  DCHECK(ContainsIndex(index));
567  return contents_data_[index]->opener();
568}
569
570void TabStripModel::SetOpenerOfWebContentsAt(int index,
571                                             WebContents* opener) {
572  DCHECK(ContainsIndex(index));
573  DCHECK(opener);
574  contents_data_[index]->set_opener(opener);
575}
576
577int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener,
578                                                     int start_index,
579                                                     bool use_group) const {
580  DCHECK(opener);
581  DCHECK(ContainsIndex(start_index));
582
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;
587  }
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;
592  }
593  return kNoTab;
594}
595
596int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
597                                                     int start_index) const {
598  DCHECK(opener);
599  DCHECK(ContainsIndex(start_index));
600
601  for (int i = contents_data_.size() - 1; i > start_index; --i) {
602    if (contents_data_[i]->opener() == opener)
603      return i;
604  }
605  return kNoTab;
606}
607
608void TabStripModel::TabNavigating(WebContents* contents,
609                                  ui::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);
626    }
627  }
628}
629
630void 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);
636}
637
638void 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);
643}
644
645bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const {
646  int index = GetIndexOfWebContents(contents);
647  DCHECK(ContainsIndex(index));
648  return contents_data_[index]->reset_group_on_select();
649}
650
651void 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));
660}
661
662void TabStripModel::SetTabPinned(int index, bool pinned) {
663  DCHECK(ContainsIndex(index));
664  if (contents_data_[index]->pinned() == pinned)
665    return;
666
667  if (IsAppTab(index)) {
668    if (!pinned) {
669      // App tabs should always be pinned.
670      NOTREACHED();
671      return;
672    }
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;
687    }
688
689    FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
690                      TabMiniStateChanged(contents_data_[index]->web_contents(),
691                                          index));
692  }
693
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));
698}
699
700bool TabStripModel::IsTabPinned(int index) const {
701  DCHECK(ContainsIndex(index));
702  return contents_data_[index]->pinned();
703}
704
705bool TabStripModel::IsMiniTab(int index) const {
706  return IsTabPinned(index) || IsAppTab(index);
707}
708
709bool TabStripModel::IsAppTab(int index) const {
710  WebContents* contents = GetWebContentsAt(index);
711  return contents && extensions::TabHelper::FromWebContents(contents)->is_app();
712}
713
714bool TabStripModel::IsTabBlocked(int index) const {
715  return contents_data_[index]->blocked();
716}
717
718bool TabStripModel::IsTabDiscarded(int index) const {
719  return contents_data_[index]->discarded();
720}
721
722int 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);
726  }
727  // No mini-tabs.
728  return count();
729}
730
731int 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()));
734}
735
736void 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);
742}
743
744void 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;
753    }
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);
763  }
764  SetSelection(new_model, NOTIFY_DEFAULT);
765}
766
767void 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);
772}
773
774bool TabStripModel::IsTabSelected(int index) const {
775  DCHECK(ContainsIndex(index));
776  return selection_model_.IsSelected(index);
777}
778
779void TabStripModel::SetSelectionFromModel(
780    const ui::ListSelectionModel& source) {
781  DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
782  SetSelection(source, NOTIFY_DEFAULT);
783}
784
785void TabStripModel::AddWebContents(WebContents* contents,
786                                   int index,
787                                   ui::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;
793
794  if (transition == ui::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();
809  }
810
811  if (transition == ui::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;
819  }
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);
824
825  if (inherit_group && transition == ui::PAGE_TRANSITION_TYPED)
826    contents_data_[index]->set_reset_group_on_select(true);
827
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      ResizeWebContents(contents, old_contents->GetContainerBounds().size());
841    }
842  }
843}
844
845void TabStripModel::CloseSelectedTabs() {
846  InternalCloseTabs(selection_model_.selected_indices(),
847                    CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
848}
849
850void TabStripModel::SelectNextTab() {
851  SelectRelativeTab(true);
852}
853
854void TabStripModel::SelectPreviousTab() {
855  SelectRelativeTab(false);
856}
857
858void TabStripModel::SelectLastTab() {
859  ActivateTabAt(count() - 1, true);
860}
861
862void TabStripModel::MoveTabNext() {
863  // TODO: this likely needs to be updated for multi-selection.
864  int new_index = std::min(active_index() + 1, count() - 1);
865  MoveWebContentsAt(active_index(), new_index, true);
866}
867
868void TabStripModel::MoveTabPrevious() {
869  // TODO: this likely needs to be updated for multi-selection.
870  int new_index = std::max(active_index() - 1, 0);
871  MoveWebContentsAt(active_index(), new_index, true);
872}
873
874// Context menu functions.
875bool TabStripModel::IsContextMenuCommandEnabled(
876    int context_index, ContextMenuCommand command_id) const {
877  DCHECK(command_id > CommandFirst && command_id < CommandLast);
878  switch (command_id) {
879    case CommandNewTab:
880    case CommandCloseTab:
881      return true;
882
883    case CommandReload: {
884      std::vector<int> indices = GetIndicesForCommand(context_index);
885      for (size_t i = 0; i < indices.size(); ++i) {
886        WebContents* tab = GetWebContentsAt(indices[i]);
887        if (tab) {
888          CoreTabHelperDelegate* core_delegate =
889              CoreTabHelper::FromWebContents(tab)->delegate();
890          if (!core_delegate || core_delegate->CanReloadContents(tab))
891            return true;
892        }
893      }
894      return false;
895    }
896
897    case CommandCloseOtherTabs:
898    case CommandCloseTabsToRight:
899      return !GetIndicesClosedByCommand(context_index, command_id).empty();
900
901    case CommandDuplicate: {
902      std::vector<int> indices = GetIndicesForCommand(context_index);
903      for (size_t i = 0; i < indices.size(); ++i) {
904        if (delegate_->CanDuplicateContentsAt(indices[i]))
905          return true;
906      }
907      return false;
908    }
909
910    case CommandRestoreTab:
911      return delegate_->GetRestoreTabType() !=
912          TabStripModelDelegate::RESTORE_NONE;
913
914    case CommandTogglePinned: {
915      std::vector<int> indices = GetIndicesForCommand(context_index);
916      for (size_t i = 0; i < indices.size(); ++i) {
917        if (!IsAppTab(indices[i]))
918          return true;
919      }
920      return false;
921    }
922
923    case CommandToggleTabAudioMuted: {
924      std::vector<int> indices = GetIndicesForCommand(context_index);
925      for (size_t i = 0; i < indices.size(); ++i) {
926        if (!chrome::CanToggleAudioMute(GetWebContentsAt(indices[i])))
927          return false;
928      }
929      return true;
930    }
931
932    case CommandBookmarkAllTabs:
933      return browser_defaults::bookmarks_enabled &&
934          delegate_->CanBookmarkAllTabs();
935
936    case CommandSelectByDomain:
937    case CommandSelectByOpener:
938      return true;
939
940    default:
941      NOTREACHED();
942  }
943  return false;
944}
945
946void TabStripModel::ExecuteContextMenuCommand(
947    int context_index, ContextMenuCommand command_id) {
948  DCHECK(command_id > CommandFirst && command_id < CommandLast);
949  switch (command_id) {
950    case CommandNewTab:
951      content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
952      UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
953                                TabStripModel::NEW_TAB_CONTEXT_MENU,
954                                TabStripModel::NEW_TAB_ENUM_COUNT);
955      delegate()->AddTabAt(GURL(), context_index + 1, true);
956      break;
957
958    case CommandReload: {
959      content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
960      std::vector<int> indices = GetIndicesForCommand(context_index);
961      for (size_t i = 0; i < indices.size(); ++i) {
962        WebContents* tab = GetWebContentsAt(indices[i]);
963        if (tab) {
964          CoreTabHelperDelegate* core_delegate =
965              CoreTabHelper::FromWebContents(tab)->delegate();
966          if (!core_delegate || core_delegate->CanReloadContents(tab))
967            tab->GetController().Reload(true);
968        }
969      }
970      break;
971    }
972
973    case CommandDuplicate: {
974      content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
975      std::vector<int> indices = GetIndicesForCommand(context_index);
976      // Copy the WebContents off as the indices will change as tabs are
977      // duplicated.
978      std::vector<WebContents*> tabs;
979      for (size_t i = 0; i < indices.size(); ++i)
980        tabs.push_back(GetWebContentsAt(indices[i]));
981      for (size_t i = 0; i < tabs.size(); ++i) {
982        int index = GetIndexOfWebContents(tabs[i]);
983        if (index != -1 && delegate_->CanDuplicateContentsAt(index))
984          delegate_->DuplicateContentsAt(index);
985      }
986      break;
987    }
988
989    case CommandCloseTab: {
990      content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
991      InternalCloseTabs(GetIndicesForCommand(context_index),
992                        CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
993      break;
994    }
995
996    case CommandCloseOtherTabs: {
997      content::RecordAction(
998          UserMetricsAction("TabContextMenu_CloseOtherTabs"));
999      InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1000                        CLOSE_CREATE_HISTORICAL_TAB);
1001      break;
1002    }
1003
1004    case CommandCloseTabsToRight: {
1005      content::RecordAction(
1006          UserMetricsAction("TabContextMenu_CloseTabsToRight"));
1007      InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1008                        CLOSE_CREATE_HISTORICAL_TAB);
1009      break;
1010    }
1011
1012    case CommandRestoreTab: {
1013      content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1014      delegate_->RestoreTab();
1015      break;
1016    }
1017
1018    case CommandTogglePinned: {
1019      content::RecordAction(
1020          UserMetricsAction("TabContextMenu_TogglePinned"));
1021      std::vector<int> indices = GetIndicesForCommand(context_index);
1022      bool pin = WillContextMenuPin(context_index);
1023      if (pin) {
1024        for (size_t i = 0; i < indices.size(); ++i) {
1025          if (!IsAppTab(indices[i]))
1026            SetTabPinned(indices[i], true);
1027        }
1028      } else {
1029        // Unpin from the back so that the order is maintained (unpinning can
1030        // trigger moving a tab).
1031        for (size_t i = indices.size(); i > 0; --i) {
1032          if (!IsAppTab(indices[i - 1]))
1033            SetTabPinned(indices[i - 1], false);
1034        }
1035      }
1036      break;
1037    }
1038
1039    case CommandToggleTabAudioMuted: {
1040      const std::vector<int>& indices = GetIndicesForCommand(context_index);
1041      const bool mute = !chrome::AreAllTabsMuted(*this, indices);
1042      if (mute)
1043        content::RecordAction(UserMetricsAction("TabContextMenu_MuteTabs"));
1044      else
1045        content::RecordAction(UserMetricsAction("TabContextMenu_UnmuteTabs"));
1046      for (std::vector<int>::const_iterator i = indices.begin();
1047           i != indices.end(); ++i) {
1048        chrome::SetTabAudioMuted(GetWebContentsAt(*i), mute);
1049      }
1050      break;
1051    }
1052
1053    case CommandBookmarkAllTabs: {
1054      content::RecordAction(
1055          UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1056
1057      delegate_->BookmarkAllTabs();
1058      break;
1059    }
1060
1061    case CommandSelectByDomain:
1062    case CommandSelectByOpener: {
1063      std::vector<int> indices;
1064      if (command_id == CommandSelectByDomain)
1065        GetIndicesWithSameDomain(context_index, &indices);
1066      else
1067        GetIndicesWithSameOpener(context_index, &indices);
1068      ui::ListSelectionModel selection_model;
1069      selection_model.SetSelectedIndex(context_index);
1070      for (size_t i = 0; i < indices.size(); ++i)
1071        selection_model.AddIndexToSelection(indices[i]);
1072      SetSelectionFromModel(selection_model);
1073      break;
1074    }
1075
1076    default:
1077      NOTREACHED();
1078  }
1079}
1080
1081std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1082    int index,
1083    ContextMenuCommand id) const {
1084  DCHECK(ContainsIndex(index));
1085  DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1086  bool is_selected = IsTabSelected(index);
1087  int start;
1088  if (id == CommandCloseTabsToRight) {
1089    if (is_selected) {
1090      start = selection_model_.selected_indices()[
1091          selection_model_.selected_indices().size() - 1] + 1;
1092    } else {
1093      start = index + 1;
1094    }
1095  } else {
1096    start = 0;
1097  }
1098  // NOTE: callers expect the vector to be sorted in descending order.
1099  std::vector<int> indices;
1100  for (int i = count() - 1; i >= start; --i) {
1101    if (i != index && !IsMiniTab(i) && (!is_selected || !IsTabSelected(i)))
1102      indices.push_back(i);
1103  }
1104  return indices;
1105}
1106
1107bool TabStripModel::WillContextMenuPin(int index) {
1108  std::vector<int> indices = GetIndicesForCommand(index);
1109  // If all tabs are pinned, then we unpin, otherwise we pin.
1110  bool all_pinned = true;
1111  for (size_t i = 0; i < indices.size() && all_pinned; ++i) {
1112    if (!IsAppTab(index))  // We never change app tabs.
1113      all_pinned = IsTabPinned(indices[i]);
1114  }
1115  return !all_pinned;
1116}
1117
1118// static
1119bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1120                                                       int* browser_cmd) {
1121  switch (cmd_id) {
1122    case CommandNewTab:
1123      *browser_cmd = IDC_NEW_TAB;
1124      break;
1125    case CommandReload:
1126      *browser_cmd = IDC_RELOAD;
1127      break;
1128    case CommandDuplicate:
1129      *browser_cmd = IDC_DUPLICATE_TAB;
1130      break;
1131    case CommandCloseTab:
1132      *browser_cmd = IDC_CLOSE_TAB;
1133      break;
1134    case CommandRestoreTab:
1135      *browser_cmd = IDC_RESTORE_TAB;
1136      break;
1137    case CommandBookmarkAllTabs:
1138      *browser_cmd = IDC_BOOKMARK_ALL_TABS;
1139      break;
1140    default:
1141      *browser_cmd = 0;
1142      return false;
1143  }
1144
1145  return true;
1146}
1147
1148///////////////////////////////////////////////////////////////////////////////
1149// TabStripModel, private:
1150
1151std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices(
1152    const std::vector<int>& indices) const {
1153  std::vector<WebContents*> contents;
1154  for (size_t i = 0; i < indices.size(); ++i)
1155    contents.push_back(GetWebContentsAtImpl(indices[i]));
1156  return contents;
1157}
1158
1159void TabStripModel::GetIndicesWithSameDomain(int index,
1160                                             std::vector<int>* indices) {
1161  std::string domain = GetWebContentsAt(index)->GetURL().host();
1162  if (domain.empty())
1163    return;
1164  for (int i = 0; i < count(); ++i) {
1165    if (i == index)
1166      continue;
1167    if (GetWebContentsAt(i)->GetURL().host() == domain)
1168      indices->push_back(i);
1169  }
1170}
1171
1172void TabStripModel::GetIndicesWithSameOpener(int index,
1173                                             std::vector<int>* indices) {
1174  WebContents* opener = contents_data_[index]->group();
1175  if (!opener) {
1176    // If there is no group, find all tabs with the selected tab as the opener.
1177    opener = GetWebContentsAt(index);
1178    if (!opener)
1179      return;
1180  }
1181  for (int i = 0; i < count(); ++i) {
1182    if (i == index)
1183      continue;
1184    if (contents_data_[i]->group() == opener ||
1185        GetWebContentsAtImpl(i) == opener) {
1186      indices->push_back(i);
1187    }
1188  }
1189}
1190
1191std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1192  if (!IsTabSelected(index)) {
1193    std::vector<int> indices;
1194    indices.push_back(index);
1195    return indices;
1196  }
1197  return selection_model_.selected_indices();
1198}
1199
1200bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1201  const GURL& url = contents->GetURL();
1202  return url.SchemeIs(content::kChromeUIScheme) &&
1203         url.host() == chrome::kChromeUINewTabHost &&
1204         contents == GetWebContentsAtImpl(count() - 1) &&
1205         contents->GetController().GetEntryCount() == 1;
1206}
1207
1208bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
1209                                      uint32 close_types) {
1210  if (indices.empty())
1211    return true;
1212
1213  CloseTracker close_tracker(GetWebContentsFromIndices(indices));
1214
1215  base::WeakPtr<TabStripModel> ref(weak_factory_.GetWeakPtr());
1216  const bool closing_all = indices.size() == contents_data_.size();
1217  if (closing_all)
1218    FOR_EACH_OBSERVER(TabStripModelObserver, observers_, WillCloseAllTabs());
1219
1220  // We only try the fast shutdown path if the whole browser process is *not*
1221  // shutting down. Fast shutdown during browser termination is handled in
1222  // BrowserShutdown.
1223  if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
1224    // Construct a map of processes to the number of associated tabs that are
1225    // closing.
1226    std::map<content::RenderProcessHost*, size_t> processes;
1227    for (size_t i = 0; i < indices.size(); ++i) {
1228      WebContents* closing_contents = GetWebContentsAtImpl(indices[i]);
1229      if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents))
1230        continue;
1231      content::RenderProcessHost* process =
1232          closing_contents->GetRenderProcessHost();
1233      ++processes[process];
1234    }
1235
1236    // Try to fast shutdown the tabs that can close.
1237    for (std::map<content::RenderProcessHost*, size_t>::iterator iter =
1238         processes.begin(); iter != processes.end(); ++iter) {
1239      iter->first->FastShutdownForPageCount(iter->second);
1240    }
1241  }
1242
1243  // We now return to our regularly scheduled shutdown procedure.
1244  bool retval = true;
1245  while (close_tracker.HasNext()) {
1246    WebContents* closing_contents = close_tracker.Next();
1247    int index = GetIndexOfWebContents(closing_contents);
1248    // Make sure we still contain the tab.
1249    if (index == kNoTab)
1250      continue;
1251
1252    CoreTabHelper* core_tab_helper =
1253        CoreTabHelper::FromWebContents(closing_contents);
1254    core_tab_helper->OnCloseStarted();
1255
1256    // Update the explicitly closed state. If the unload handlers cancel the
1257    // close the state is reset in Browser. We don't update the explicitly
1258    // closed state if already marked as explicitly closed as unload handlers
1259    // call back to this if the close is allowed.
1260    if (!closing_contents->GetClosedByUserGesture()) {
1261      closing_contents->SetClosedByUserGesture(
1262          close_types & CLOSE_USER_GESTURE);
1263    }
1264
1265    if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) {
1266      retval = false;
1267      continue;
1268    }
1269
1270    InternalCloseTab(closing_contents, index,
1271                     (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
1272  }
1273
1274  if (ref && closing_all && !retval) {
1275    FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1276                      CloseAllTabsCanceled());
1277  }
1278
1279  return retval;
1280}
1281
1282void TabStripModel::InternalCloseTab(WebContents* contents,
1283                                     int index,
1284                                     bool create_historical_tabs) {
1285  FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1286                    TabClosingAt(this, contents, index));
1287
1288  // Ask the delegate to save an entry for this tab in the historical tab
1289  // database if applicable.
1290  if (create_historical_tabs)
1291    delegate_->CreateHistoricalTab(contents);
1292
1293  // Deleting the WebContents will call back to us via
1294  // WebContentsData::WebContentsDestroyed and detach it.
1295  delete contents;
1296}
1297
1298WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1299  CHECK(ContainsIndex(index)) <<
1300      "Failed to find: " << index << " in: " << count() << " entries.";
1301  return contents_data_[index]->web_contents();
1302}
1303
1304void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) {
1305  if (contents) {
1306    FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1307                      TabDeactivated(contents));
1308  }
1309}
1310
1311void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents,
1312                                             NotifyTypes notify_types) {
1313  WebContents* new_contents = GetWebContentsAtImpl(active_index());
1314  if (old_contents != new_contents) {
1315    int reason = notify_types == NOTIFY_USER_GESTURE
1316                 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1317                 : TabStripModelObserver::CHANGE_REASON_NONE;
1318    CHECK(!in_notify_);
1319    in_notify_ = true;
1320    FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1321        ActiveTabChanged(old_contents,
1322                         new_contents,
1323                         active_index(),
1324                         reason));
1325    in_notify_ = false;
1326    // Activating a discarded tab reloads it, so it is no longer discarded.
1327    contents_data_[active_index()]->set_discarded(false);
1328  }
1329}
1330
1331void TabStripModel::NotifyIfActiveOrSelectionChanged(
1332    WebContents* old_contents,
1333    NotifyTypes notify_types,
1334    const ui::ListSelectionModel& old_model) {
1335  NotifyIfActiveTabChanged(old_contents, notify_types);
1336
1337  if (!selection_model().Equals(old_model)) {
1338    FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1339                      TabSelectionChanged(this, old_model));
1340  }
1341}
1342
1343void TabStripModel::SetSelection(
1344    const ui::ListSelectionModel& new_model,
1345    NotifyTypes notify_types) {
1346  WebContents* old_contents = GetActiveWebContents();
1347  ui::ListSelectionModel old_model;
1348  old_model.Copy(selection_model_);
1349  if (new_model.active() != selection_model_.active())
1350    NotifyIfTabDeactivated(old_contents);
1351  selection_model_.Copy(new_model);
1352  NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model);
1353}
1354
1355void TabStripModel::SelectRelativeTab(bool next) {
1356  // This may happen during automated testing or if a user somehow buffers
1357  // many key accelerators.
1358  if (contents_data_.empty())
1359    return;
1360
1361  int index = active_index();
1362  int delta = next ? 1 : -1;
1363  index = (index + count() + delta) % count();
1364  ActivateTabAt(index, true);
1365}
1366
1367void TabStripModel::MoveWebContentsAtImpl(int index,
1368                                          int to_position,
1369                                          bool select_after_move) {
1370  WebContentsData* moved_data = contents_data_[index];
1371  contents_data_.erase(contents_data_.begin() + index);
1372  contents_data_.insert(contents_data_.begin() + to_position, moved_data);
1373
1374  selection_model_.Move(index, to_position);
1375  if (!selection_model_.IsSelected(select_after_move) && select_after_move) {
1376    // TODO(sky): why doesn't this code notify observers?
1377    selection_model_.SetSelectedIndex(to_position);
1378  }
1379
1380  ForgetOpenersAndGroupsReferencing(moved_data->web_contents());
1381
1382  FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1383                    TabMoved(moved_data->web_contents(), index, to_position));
1384}
1385
1386void TabStripModel::MoveSelectedTabsToImpl(int index,
1387                                           size_t start,
1388                                           size_t length) {
1389  DCHECK(start < selection_model_.selected_indices().size() &&
1390         start + length <= selection_model_.selected_indices().size());
1391  size_t end = start + length;
1392  int count_before_index = 0;
1393  for (size_t i = start; i < end &&
1394       selection_model_.selected_indices()[i] < index + count_before_index;
1395       ++i) {
1396    count_before_index++;
1397  }
1398
1399  // First move those before index. Any tabs before index end up moving in the
1400  // selection model so we use start each time through.
1401  int target_index = index + count_before_index;
1402  size_t tab_index = start;
1403  while (tab_index < end &&
1404         selection_model_.selected_indices()[start] < index) {
1405    MoveWebContentsAt(selection_model_.selected_indices()[start],
1406                      target_index - 1, false);
1407    tab_index++;
1408  }
1409
1410  // Then move those after the index. These don't result in reordering the
1411  // selection.
1412  while (tab_index < end) {
1413    if (selection_model_.selected_indices()[tab_index] != target_index) {
1414      MoveWebContentsAt(selection_model_.selected_indices()[tab_index],
1415                        target_index, false);
1416    }
1417    tab_index++;
1418    target_index++;
1419  }
1420}
1421
1422// static
1423bool TabStripModel::OpenerMatches(const WebContentsData* data,
1424                                  const WebContents* opener,
1425                                  bool use_group) {
1426  return data->opener() == opener || (use_group && data->group() == opener);
1427}
1428
1429void TabStripModel::ForgetOpenersAndGroupsReferencing(
1430    const WebContents* tab) {
1431  for (WebContentsDataVector::const_iterator i = contents_data_.begin();
1432       i != contents_data_.end(); ++i) {
1433    if ((*i)->group() == tab)
1434      (*i)->set_group(NULL);
1435    if ((*i)->opener() == tab)
1436      (*i)->set_opener(NULL);
1437  }
1438}
1439