Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / ui / tabs / tab_strip_model.cc
blob08671ff46422047cf7dab27b5cb6f18005bcd170
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_strip_model_delegate.h"
22 #include "chrome/browser/ui/tabs/tab_strip_model_order_controller.h"
23 #include "chrome/browser/ui/tabs/tab_utils.h"
24 #include "chrome/browser/ui/web_contents_sizer.h"
25 #include "chrome/common/url_constants.h"
26 #include "components/web_modal/popup_manager.h"
27 #include "content/public/browser/render_process_host.h"
28 #include "content/public/browser/user_metrics.h"
29 #include "content/public/browser/web_contents.h"
30 #include "content/public/browser/web_contents_observer.h"
31 using base::UserMetricsAction;
32 using content::WebContents;
34 namespace {
36 // Returns true if the specified transition is one of the types that cause the
37 // opener relationships for the tab in which the transition occurred to be
38 // forgotten. This is generally any navigation that isn't a link click (i.e.
39 // any navigation that can be considered to be the start of a new task distinct
40 // from what had previously occurred in that tab).
41 bool ShouldForgetOpenersForTransition(ui::PageTransition transition) {
42 return transition == ui::PAGE_TRANSITION_TYPED ||
43 transition == ui::PAGE_TRANSITION_AUTO_BOOKMARK ||
44 transition == ui::PAGE_TRANSITION_GENERATED ||
45 transition == ui::PAGE_TRANSITION_KEYWORD ||
46 transition == ui::PAGE_TRANSITION_AUTO_TOPLEVEL;
49 // CloseTracker is used when closing a set of WebContents. It listens for
50 // deletions of the WebContents and removes from the internal set any time one
51 // is deleted.
52 class CloseTracker {
53 public:
54 typedef std::vector<WebContents*> Contents;
56 explicit CloseTracker(const Contents& contents);
57 virtual ~CloseTracker();
59 // Returns true if there is another WebContents in the Tracker.
60 bool HasNext() const;
62 // Returns the next WebContents, or NULL if there are no more.
63 WebContents* Next();
65 private:
66 class DeletionObserver : public content::WebContentsObserver {
67 public:
68 DeletionObserver(CloseTracker* parent, WebContents* web_contents)
69 : WebContentsObserver(web_contents),
70 parent_(parent) {
73 private:
74 // WebContentsObserver:
75 void WebContentsDestroyed() override {
76 parent_->OnWebContentsDestroyed(this);
79 CloseTracker* parent_;
81 DISALLOW_COPY_AND_ASSIGN(DeletionObserver);
84 void OnWebContentsDestroyed(DeletionObserver* observer);
86 typedef std::vector<DeletionObserver*> Observers;
87 Observers observers_;
89 DISALLOW_COPY_AND_ASSIGN(CloseTracker);
92 CloseTracker::CloseTracker(const Contents& contents) {
93 for (size_t i = 0; i < contents.size(); ++i)
94 observers_.push_back(new DeletionObserver(this, contents[i]));
97 CloseTracker::~CloseTracker() {
98 DCHECK(observers_.empty());
101 bool CloseTracker::HasNext() const {
102 return !observers_.empty();
105 WebContents* CloseTracker::Next() {
106 if (observers_.empty())
107 return NULL;
109 DeletionObserver* observer = observers_[0];
110 WebContents* web_contents = observer->web_contents();
111 observers_.erase(observers_.begin());
112 delete observer;
113 return web_contents;
116 void CloseTracker::OnWebContentsDestroyed(DeletionObserver* observer) {
117 Observers::iterator i =
118 std::find(observers_.begin(), observers_.end(), observer);
119 if (i != observers_.end()) {
120 delete *i;
121 observers_.erase(i);
122 return;
124 NOTREACHED() << "WebContents destroyed that wasn't in the list";
127 } // namespace
129 ///////////////////////////////////////////////////////////////////////////////
130 // WebContentsData
132 // An object to hold a reference to a WebContents that is in a tabstrip, as
133 // well as other various properties it has.
134 class TabStripModel::WebContentsData : public content::WebContentsObserver {
135 public:
136 WebContentsData(TabStripModel* tab_strip_model, WebContents* a_contents);
138 // Changes the WebContents that this WebContentsData tracks.
139 void SetWebContents(WebContents* contents);
140 WebContents* web_contents() { return contents_; }
142 // Create a relationship between this WebContentsData and other
143 // WebContentses. Used to identify which WebContents to select next after
144 // one is closed.
145 WebContents* group() const { return group_; }
146 void set_group(WebContents* value) { group_ = value; }
147 WebContents* opener() const { return opener_; }
148 void set_opener(WebContents* value) { opener_ = value; }
150 // Alters the properties of the WebContents.
151 bool reset_group_on_select() const { return reset_group_on_select_; }
152 void set_reset_group_on_select(bool value) { reset_group_on_select_ = value; }
153 bool pinned() const { return pinned_; }
154 void set_pinned(bool value) { pinned_ = value; }
155 bool blocked() const { return blocked_; }
156 void set_blocked(bool value) { blocked_ = value; }
157 bool discarded() const { return discarded_; }
158 void set_discarded(bool value) { discarded_ = value; }
160 private:
161 // Make sure that if someone deletes this WebContents out from under us, it
162 // is properly removed from the tab strip.
163 void WebContentsDestroyed() override;
165 // The WebContents being tracked by this WebContentsData. The
166 // WebContentsObserver does keep a reference, but when the WebContents is
167 // deleted, the WebContentsObserver reference is NULLed and thus inaccessible.
168 WebContents* contents_;
170 // The TabStripModel containing this WebContents.
171 TabStripModel* tab_strip_model_;
173 // The group is used to model a set of tabs spawned from a single parent
174 // tab. This value is preserved for a given tab as long as the tab remains
175 // navigated to the link it was initially opened at or some navigation from
176 // that page (i.e. if the user types or visits a bookmark or some other
177 // navigation within that tab, the group relationship is lost). This
178 // property can safely be used to implement features that depend on a
179 // logical group of related tabs.
180 WebContents* group_;
182 // The owner models the same relationship as group, except it is more
183 // easily discarded, e.g. when the user switches to a tab not part of the
184 // same group. This property is used to determine what tab to select next
185 // when one is closed.
186 WebContents* opener_;
188 // True if our group should be reset the moment selection moves away from
189 // this tab. This is the case for tabs opened in the foreground at the end
190 // of the TabStrip while viewing another Tab. If these tabs are closed
191 // before selection moves elsewhere, their opener is selected. But if
192 // selection shifts to _any_ tab (including their opener), the group
193 // relationship is reset to avoid confusing close sequencing.
194 bool reset_group_on_select_;
196 // Is the tab pinned?
197 bool pinned_;
199 // Is the tab interaction blocked by a modal dialog?
200 bool blocked_;
202 // Has the tab data been discarded to save memory?
203 bool discarded_;
205 DISALLOW_COPY_AND_ASSIGN(WebContentsData);
208 TabStripModel::WebContentsData::WebContentsData(TabStripModel* tab_strip_model,
209 WebContents* contents)
210 : content::WebContentsObserver(contents),
211 contents_(contents),
212 tab_strip_model_(tab_strip_model),
213 group_(NULL),
214 opener_(NULL),
215 reset_group_on_select_(false),
216 pinned_(false),
217 blocked_(false),
218 discarded_(false) {
221 void TabStripModel::WebContentsData::SetWebContents(WebContents* contents) {
222 contents_ = contents;
223 Observe(contents);
226 void TabStripModel::WebContentsData::WebContentsDestroyed() {
227 DCHECK_EQ(contents_, web_contents());
229 // Note that we only detach the contents here, not close it - it's
230 // already been closed. We just want to undo our bookkeeping.
231 int index = tab_strip_model_->GetIndexOfWebContents(web_contents());
232 DCHECK_NE(TabStripModel::kNoTab, index);
233 tab_strip_model_->DetachWebContentsAt(index);
236 ///////////////////////////////////////////////////////////////////////////////
237 // TabStripModel, public:
239 TabStripModel::TabStripModel(TabStripModelDelegate* delegate, Profile* profile)
240 : delegate_(delegate),
241 profile_(profile),
242 closing_all_(false),
243 in_notify_(false),
244 weak_factory_(this) {
245 DCHECK(delegate_);
246 order_controller_.reset(new TabStripModelOrderController(this));
249 TabStripModel::~TabStripModel() {
250 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
251 TabStripModelDeleted());
252 STLDeleteElements(&contents_data_);
253 order_controller_.reset();
256 void TabStripModel::AddObserver(TabStripModelObserver* observer) {
257 observers_.AddObserver(observer);
260 void TabStripModel::RemoveObserver(TabStripModelObserver* observer) {
261 observers_.RemoveObserver(observer);
264 bool TabStripModel::ContainsIndex(int index) const {
265 return index >= 0 && index < count();
268 void TabStripModel::AppendWebContents(WebContents* contents,
269 bool foreground) {
270 InsertWebContentsAt(count(), contents,
271 foreground ? (ADD_INHERIT_GROUP | ADD_ACTIVE) :
272 ADD_NONE);
275 void TabStripModel::InsertWebContentsAt(int index,
276 WebContents* contents,
277 int add_types) {
278 delegate_->WillAddWebContents(contents);
280 bool active = add_types & ADD_ACTIVE;
281 // Force app tabs to be pinned.
282 extensions::TabHelper* extensions_tab_helper =
283 extensions::TabHelper::FromWebContents(contents);
284 bool pin = extensions_tab_helper->is_app() || add_types & ADD_PINNED;
285 index = ConstrainInsertionIndex(index, pin);
287 // In tab dragging situations, if the last tab in the window was detached
288 // then the user aborted the drag, we will have the |closing_all_| member
289 // set (see DetachWebContentsAt) which will mess with our mojo here. We need
290 // to clear this bit.
291 closing_all_ = false;
293 // Have to get the active contents before we monkey with the contents
294 // otherwise we run into problems when we try to change the active contents
295 // since the old contents and the new contents will be the same...
296 WebContents* active_contents = GetActiveWebContents();
297 WebContentsData* data = new WebContentsData(this, contents);
298 data->set_pinned(pin);
299 if ((add_types & ADD_INHERIT_GROUP) && active_contents) {
300 if (active) {
301 // Forget any existing relationships, we don't want to make things too
302 // confusing by having multiple groups active at the same time.
303 ForgetAllOpeners();
305 // Anything opened by a link we deem to have an opener.
306 data->set_group(active_contents);
307 data->set_opener(active_contents);
308 } else if ((add_types & ADD_INHERIT_OPENER) && active_contents) {
309 if (active) {
310 // Forget any existing relationships, we don't want to make things too
311 // confusing by having multiple groups active at the same time.
312 ForgetAllOpeners();
314 data->set_opener(active_contents);
317 // TODO(gbillock): Ask the bubble manager whether the WebContents should be
318 // blocked, or just let the bubble manager make the blocking call directly
319 // and not use this at all.
320 web_modal::PopupManager* popup_manager =
321 web_modal::PopupManager::FromWebContents(contents);
322 if (popup_manager)
323 data->set_blocked(popup_manager->IsWebModalDialogActive(contents));
325 contents_data_.insert(contents_data_.begin() + index, data);
327 selection_model_.IncrementFrom(index);
329 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
330 TabInsertedAt(contents, index, active));
331 if (active) {
332 ui::ListSelectionModel new_model;
333 new_model.Copy(selection_model_);
334 new_model.SetSelectedIndex(index);
335 SetSelection(new_model, NOTIFY_DEFAULT);
339 WebContents* TabStripModel::ReplaceWebContentsAt(int index,
340 WebContents* new_contents) {
341 delegate_->WillAddWebContents(new_contents);
343 DCHECK(ContainsIndex(index));
344 WebContents* old_contents = GetWebContentsAtImpl(index);
346 FixOpenersAndGroupsReferencing(index);
348 contents_data_[index]->SetWebContents(new_contents);
350 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
351 TabReplacedAt(this, old_contents, new_contents, index));
353 // When the active WebContents is replaced send out a selection notification
354 // too. We do this as nearly all observers need to treat a replacement of the
355 // selected contents as the selection changing.
356 if (active_index() == index) {
357 FOR_EACH_OBSERVER(
358 TabStripModelObserver,
359 observers_,
360 ActiveTabChanged(old_contents,
361 new_contents,
362 active_index(),
363 TabStripModelObserver::CHANGE_REASON_REPLACED));
365 return old_contents;
368 WebContents* TabStripModel::DiscardWebContentsAt(int index) {
369 DCHECK(ContainsIndex(index));
370 // Do not discard active tab.
371 if (active_index() == index)
372 return NULL;
374 WebContents* null_contents =
375 WebContents::Create(WebContents::CreateParams(profile()));
376 WebContents* old_contents = GetWebContentsAtImpl(index);
377 // Copy over the state from the navigation controller so we preserve the
378 // back/forward history and continue to display the correct title/favicon.
379 null_contents->GetController().CopyStateFrom(old_contents->GetController());
380 // Replace the tab we're discarding with the null version.
381 ReplaceWebContentsAt(index, null_contents);
382 // Mark the tab so it will reload when we click.
383 contents_data_[index]->set_discarded(true);
384 // Discard the old tab's renderer.
385 // TODO(jamescook): This breaks script connections with other tabs.
386 // We need to find a different approach that doesn't do that, perhaps based
387 // on navigation to swappedout://.
388 delete old_contents;
389 return null_contents;
392 WebContents* TabStripModel::DetachWebContentsAt(int index) {
393 CHECK(!in_notify_);
394 if (contents_data_.empty())
395 return NULL;
396 DCHECK(ContainsIndex(index));
398 FixOpenersAndGroupsReferencing(index);
400 WebContents* removed_contents = GetWebContentsAtImpl(index);
401 bool was_selected = IsTabSelected(index);
402 int next_selected_index = order_controller_->DetermineNewSelectedIndex(index);
403 delete contents_data_[index];
404 contents_data_.erase(contents_data_.begin() + index);
405 if (empty())
406 closing_all_ = true;
407 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
408 TabDetachedAt(removed_contents, index));
409 if (empty()) {
410 selection_model_.Clear();
411 // TabDetachedAt() might unregister observers, so send |TabStripEmpty()| in
412 // a second pass.
413 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty());
414 } else {
415 int old_active = active_index();
416 selection_model_.DecrementFrom(index);
417 ui::ListSelectionModel old_model;
418 old_model.Copy(selection_model_);
419 if (index == old_active) {
420 NotifyIfTabDeactivated(removed_contents);
421 if (!selection_model_.empty()) {
422 // The active tab was removed, but there is still something selected.
423 // Move the active and anchor to the first selected index.
424 selection_model_.set_active(selection_model_.selected_indices()[0]);
425 selection_model_.set_anchor(selection_model_.active());
426 } else {
427 // The active tab was removed and nothing is selected. Reset the
428 // selection and send out notification.
429 selection_model_.SetSelectedIndex(next_selected_index);
431 NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT);
434 // Sending notification in case the detached tab was selected. Using
435 // NotifyIfActiveOrSelectionChanged() here would not guarantee that a
436 // notification is sent even though the tab selection has changed because
437 // |old_model| is stored after calling DecrementFrom().
438 if (was_selected) {
439 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
440 TabSelectionChanged(this, old_model));
443 return removed_contents;
446 void TabStripModel::ActivateTabAt(int index, bool user_gesture) {
447 DCHECK(ContainsIndex(index));
448 ui::ListSelectionModel new_model;
449 new_model.Copy(selection_model_);
450 new_model.SetSelectedIndex(index);
451 SetSelection(new_model, user_gesture ? NOTIFY_USER_GESTURE : NOTIFY_DEFAULT);
454 void TabStripModel::AddTabAtToSelection(int index) {
455 DCHECK(ContainsIndex(index));
456 ui::ListSelectionModel new_model;
457 new_model.Copy(selection_model_);
458 new_model.AddIndexToSelection(index);
459 SetSelection(new_model, NOTIFY_DEFAULT);
462 void TabStripModel::MoveWebContentsAt(int index,
463 int to_position,
464 bool select_after_move) {
465 DCHECK(ContainsIndex(index));
466 if (index == to_position)
467 return;
469 int first_non_mini_tab = IndexOfFirstNonMiniTab();
470 if ((index < first_non_mini_tab && to_position >= first_non_mini_tab) ||
471 (to_position < first_non_mini_tab && index >= first_non_mini_tab)) {
472 // This would result in mini tabs mixed with non-mini tabs. We don't allow
473 // that.
474 return;
477 MoveWebContentsAtImpl(index, to_position, select_after_move);
480 void TabStripModel::MoveSelectedTabsTo(int index) {
481 int total_mini_count = IndexOfFirstNonMiniTab();
482 int selected_mini_count = 0;
483 int selected_count =
484 static_cast<int>(selection_model_.selected_indices().size());
485 for (int i = 0; i < selected_count &&
486 IsMiniTab(selection_model_.selected_indices()[i]); ++i) {
487 selected_mini_count++;
490 // To maintain that all mini-tabs occur before non-mini-tabs we move them
491 // first.
492 if (selected_mini_count > 0) {
493 MoveSelectedTabsToImpl(
494 std::min(total_mini_count - selected_mini_count, index), 0u,
495 selected_mini_count);
496 if (index > total_mini_count - selected_mini_count) {
497 // We're being told to drag mini-tabs to an invalid location. Adjust the
498 // index such that non-mini-tabs end up at a location as though we could
499 // move the mini-tabs to index. See description in header for more
500 // details.
501 index += selected_mini_count;
504 if (selected_mini_count == selected_count)
505 return;
507 // Then move the non-pinned tabs.
508 MoveSelectedTabsToImpl(std::max(index, total_mini_count),
509 selected_mini_count,
510 selected_count - selected_mini_count);
513 WebContents* TabStripModel::GetActiveWebContents() const {
514 return GetWebContentsAt(active_index());
517 WebContents* TabStripModel::GetWebContentsAt(int index) const {
518 if (ContainsIndex(index))
519 return GetWebContentsAtImpl(index);
520 return NULL;
523 int TabStripModel::GetIndexOfWebContents(const WebContents* contents) const {
524 for (size_t i = 0; i < contents_data_.size(); ++i) {
525 if (contents_data_[i]->web_contents() == contents)
526 return i;
528 return kNoTab;
531 void TabStripModel::UpdateWebContentsStateAt(int index,
532 TabStripModelObserver::TabChangeType change_type) {
533 DCHECK(ContainsIndex(index));
535 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
536 TabChangedAt(GetWebContentsAtImpl(index), index, change_type));
539 void TabStripModel::CloseAllTabs() {
540 // Set state so that observers can adjust their behavior to suit this
541 // specific condition when CloseWebContentsAt causes a flurry of
542 // Close/Detach/Select notifications to be sent.
543 closing_all_ = true;
544 std::vector<int> closing_tabs;
545 for (int i = count() - 1; i >= 0; --i)
546 closing_tabs.push_back(i);
547 InternalCloseTabs(closing_tabs, CLOSE_CREATE_HISTORICAL_TAB);
550 bool TabStripModel::CloseWebContentsAt(int index, uint32 close_types) {
551 DCHECK(ContainsIndex(index));
552 std::vector<int> closing_tabs;
553 closing_tabs.push_back(index);
554 return InternalCloseTabs(closing_tabs, close_types);
557 bool TabStripModel::TabsAreLoading() const {
558 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
559 iter != contents_data_.end(); ++iter) {
560 if ((*iter)->web_contents()->IsLoading())
561 return true;
563 return false;
566 WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) {
567 DCHECK(ContainsIndex(index));
568 return contents_data_[index]->opener();
571 void TabStripModel::SetOpenerOfWebContentsAt(int index,
572 WebContents* opener) {
573 DCHECK(ContainsIndex(index));
574 DCHECK(opener);
575 contents_data_[index]->set_opener(opener);
578 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener,
579 int start_index,
580 bool use_group) const {
581 DCHECK(opener);
582 DCHECK(ContainsIndex(start_index));
584 // Check tabs after start_index first.
585 for (int i = start_index + 1; i < count(); ++i) {
586 if (OpenerMatches(contents_data_[i], opener, use_group))
587 return i;
589 // Then check tabs before start_index, iterating backwards.
590 for (int i = start_index - 1; i >= 0; --i) {
591 if (OpenerMatches(contents_data_[i], opener, use_group))
592 return i;
594 return kNoTab;
597 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
598 int start_index) const {
599 DCHECK(opener);
600 DCHECK(ContainsIndex(start_index));
602 std::set<const WebContents*> opener_and_descendants;
603 opener_and_descendants.insert(opener);
604 int last_index = kNoTab;
606 for (int i = start_index + 1; i < count(); ++i) {
607 // Test opened by transitively, i.e. include tabs opened by tabs opened by
608 // opener, etc. Stop when we find the first non-descendant.
609 if (!opener_and_descendants.count(contents_data_[i]->opener()))
610 break;
611 opener_and_descendants.insert(contents_data_[i]->web_contents());
612 last_index = i;
614 return last_index;
617 void TabStripModel::TabNavigating(WebContents* contents,
618 ui::PageTransition transition) {
619 if (ShouldForgetOpenersForTransition(transition)) {
620 // Don't forget the openers if this tab is a New Tab page opened at the
621 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
622 // navigation of one of these transition types before resetting the
623 // opener relationships (this allows for the use case of opening a new
624 // tab to do a quick look-up of something while viewing a tab earlier in
625 // the strip). We can make this heuristic more permissive if need be.
626 if (!IsNewTabAtEndOfTabStrip(contents)) {
627 // If the user navigates the current tab to another page in any way
628 // other than by clicking a link, we want to pro-actively forget all
629 // TabStrip opener relationships since we assume they're beginning a
630 // different task by reusing the current tab.
631 ForgetAllOpeners();
632 // In this specific case we also want to reset the group relationship,
633 // since it is now technically invalid.
634 ForgetGroup(contents);
639 void TabStripModel::ForgetAllOpeners() {
640 // Forget all opener memories so we don't do anything weird with tab
641 // re-selection ordering.
642 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
643 iter != contents_data_.end(); ++iter)
644 (*iter)->set_opener(NULL);
647 void TabStripModel::ForgetGroup(WebContents* contents) {
648 int index = GetIndexOfWebContents(contents);
649 DCHECK(ContainsIndex(index));
650 contents_data_[index]->set_group(NULL);
651 contents_data_[index]->set_opener(NULL);
654 bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const {
655 int index = GetIndexOfWebContents(contents);
656 DCHECK(ContainsIndex(index));
657 return contents_data_[index]->reset_group_on_select();
660 void TabStripModel::SetTabBlocked(int index, bool blocked) {
661 DCHECK(ContainsIndex(index));
662 if (contents_data_[index]->blocked() == blocked)
663 return;
664 contents_data_[index]->set_blocked(blocked);
665 FOR_EACH_OBSERVER(
666 TabStripModelObserver, observers_,
667 TabBlockedStateChanged(contents_data_[index]->web_contents(),
668 index));
671 void TabStripModel::SetTabPinned(int index, bool pinned) {
672 DCHECK(ContainsIndex(index));
673 if (contents_data_[index]->pinned() == pinned)
674 return;
676 if (IsAppTab(index)) {
677 if (!pinned) {
678 // App tabs should always be pinned.
679 NOTREACHED();
680 return;
682 // Changing the pinned state of an app tab doesn't affect its mini-tab
683 // status.
684 contents_data_[index]->set_pinned(pinned);
685 } else {
686 // The tab is not an app tab, its position may have to change as the
687 // mini-tab state is changing.
688 int non_mini_tab_index = IndexOfFirstNonMiniTab();
689 contents_data_[index]->set_pinned(pinned);
690 if (pinned && index != non_mini_tab_index) {
691 MoveWebContentsAtImpl(index, non_mini_tab_index, false);
692 index = non_mini_tab_index;
693 } else if (!pinned && index + 1 != non_mini_tab_index) {
694 MoveWebContentsAtImpl(index, non_mini_tab_index - 1, false);
695 index = non_mini_tab_index - 1;
698 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
699 TabMiniStateChanged(contents_data_[index]->web_contents(),
700 index));
703 // else: the tab was at the boundary and its position doesn't need to change.
704 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
705 TabPinnedStateChanged(contents_data_[index]->web_contents(),
706 index));
709 bool TabStripModel::IsTabPinned(int index) const {
710 DCHECK(ContainsIndex(index));
711 return contents_data_[index]->pinned();
714 bool TabStripModel::IsMiniTab(int index) const {
715 return IsTabPinned(index) || IsAppTab(index);
718 bool TabStripModel::IsAppTab(int index) const {
719 WebContents* contents = GetWebContentsAt(index);
720 return contents && extensions::TabHelper::FromWebContents(contents)->is_app();
723 bool TabStripModel::IsTabBlocked(int index) const {
724 return contents_data_[index]->blocked();
727 bool TabStripModel::IsTabDiscarded(int index) const {
728 return contents_data_[index]->discarded();
731 int TabStripModel::IndexOfFirstNonMiniTab() const {
732 for (size_t i = 0; i < contents_data_.size(); ++i) {
733 if (!IsMiniTab(static_cast<int>(i)))
734 return static_cast<int>(i);
736 // No mini-tabs.
737 return count();
740 int TabStripModel::ConstrainInsertionIndex(int index, bool mini_tab) {
741 return mini_tab ? std::min(std::max(0, index), IndexOfFirstNonMiniTab()) :
742 std::min(count(), std::max(index, IndexOfFirstNonMiniTab()));
745 void TabStripModel::ExtendSelectionTo(int index) {
746 DCHECK(ContainsIndex(index));
747 ui::ListSelectionModel new_model;
748 new_model.Copy(selection_model_);
749 new_model.SetSelectionFromAnchorTo(index);
750 SetSelection(new_model, NOTIFY_DEFAULT);
753 void TabStripModel::ToggleSelectionAt(int index) {
754 DCHECK(ContainsIndex(index));
755 ui::ListSelectionModel new_model;
756 new_model.Copy(selection_model());
757 if (selection_model_.IsSelected(index)) {
758 if (selection_model_.size() == 1) {
759 // One tab must be selected and this tab is currently selected so we can't
760 // unselect it.
761 return;
763 new_model.RemoveIndexFromSelection(index);
764 new_model.set_anchor(index);
765 if (new_model.active() == index ||
766 new_model.active() == ui::ListSelectionModel::kUnselectedIndex)
767 new_model.set_active(new_model.selected_indices()[0]);
768 } else {
769 new_model.AddIndexToSelection(index);
770 new_model.set_anchor(index);
771 new_model.set_active(index);
773 SetSelection(new_model, NOTIFY_DEFAULT);
776 void TabStripModel::AddSelectionFromAnchorTo(int index) {
777 ui::ListSelectionModel new_model;
778 new_model.Copy(selection_model_);
779 new_model.AddSelectionFromAnchorTo(index);
780 SetSelection(new_model, NOTIFY_DEFAULT);
783 bool TabStripModel::IsTabSelected(int index) const {
784 DCHECK(ContainsIndex(index));
785 return selection_model_.IsSelected(index);
788 void TabStripModel::SetSelectionFromModel(
789 const ui::ListSelectionModel& source) {
790 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
791 SetSelection(source, NOTIFY_DEFAULT);
794 void TabStripModel::AddWebContents(WebContents* contents,
795 int index,
796 ui::PageTransition transition,
797 int add_types) {
798 // If the newly-opened tab is part of the same task as the parent tab, we want
799 // to inherit the parent's "group" attribute, so that if this tab is then
800 // closed we'll jump back to the parent tab.
801 bool inherit_group = (add_types & ADD_INHERIT_GROUP) == ADD_INHERIT_GROUP;
803 if (transition == ui::PAGE_TRANSITION_LINK &&
804 (add_types & ADD_FORCE_INDEX) == 0) {
805 // We assume tabs opened via link clicks are part of the same task as their
806 // parent. Note that when |force_index| is true (e.g. when the user
807 // drag-and-drops a link to the tab strip), callers aren't really handling
808 // link clicks, they just want to score the navigation like a link click in
809 // the history backend, so we don't inherit the group in this case.
810 index = order_controller_->DetermineInsertionIndex(transition,
811 add_types & ADD_ACTIVE);
812 inherit_group = true;
813 } else {
814 // For all other types, respect what was passed to us, normalizing -1s and
815 // values that are too large.
816 if (index < 0 || index > count())
817 index = count();
820 if (transition == ui::PAGE_TRANSITION_TYPED && index == count()) {
821 // Also, any tab opened at the end of the TabStrip with a "TYPED"
822 // transition inherit group as well. This covers the cases where the user
823 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
824 // in the address bar and presses Alt+Enter. This allows for opening a new
825 // Tab to quickly look up something. When this Tab is closed, the old one
826 // is re-selected, not the next-adjacent.
827 inherit_group = true;
829 InsertWebContentsAt(index, contents,
830 add_types | (inherit_group ? ADD_INHERIT_GROUP : 0));
831 // Reset the index, just in case insert ended up moving it on us.
832 index = GetIndexOfWebContents(contents);
834 if (inherit_group && transition == ui::PAGE_TRANSITION_TYPED)
835 contents_data_[index]->set_reset_group_on_select(true);
837 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
838 // here we seem to get failures in startup perf tests.
839 // Ensure that the new WebContentsView begins at the same size as the
840 // previous WebContentsView if it existed. Otherwise, the initial WebKit
841 // layout will be performed based on a width of 0 pixels, causing a
842 // very long, narrow, inaccurate layout. Because some scripts on pages (as
843 // well as WebKit's anchor link location calculation) are run on the
844 // initial layout and not recalculated later, we need to ensure the first
845 // layout is performed with sane view dimensions even when we're opening a
846 // new background tab.
847 if (WebContents* old_contents = GetActiveWebContents()) {
848 if ((add_types & ADD_ACTIVE) == 0) {
849 ResizeWebContents(contents, old_contents->GetContainerBounds().size());
854 void TabStripModel::CloseSelectedTabs() {
855 InternalCloseTabs(selection_model_.selected_indices(),
856 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
859 void TabStripModel::SelectNextTab() {
860 SelectRelativeTab(true);
863 void TabStripModel::SelectPreviousTab() {
864 SelectRelativeTab(false);
867 void TabStripModel::SelectLastTab() {
868 ActivateTabAt(count() - 1, true);
871 void TabStripModel::MoveTabNext() {
872 // TODO: this likely needs to be updated for multi-selection.
873 int new_index = std::min(active_index() + 1, count() - 1);
874 MoveWebContentsAt(active_index(), new_index, true);
877 void TabStripModel::MoveTabPrevious() {
878 // TODO: this likely needs to be updated for multi-selection.
879 int new_index = std::max(active_index() - 1, 0);
880 MoveWebContentsAt(active_index(), new_index, true);
883 // Context menu functions.
884 bool TabStripModel::IsContextMenuCommandEnabled(
885 int context_index, ContextMenuCommand command_id) const {
886 DCHECK(command_id > CommandFirst && command_id < CommandLast);
887 switch (command_id) {
888 case CommandNewTab:
889 case CommandCloseTab:
890 return true;
892 case CommandReload: {
893 std::vector<int> indices = GetIndicesForCommand(context_index);
894 for (size_t i = 0; i < indices.size(); ++i) {
895 WebContents* tab = GetWebContentsAt(indices[i]);
896 if (tab) {
897 CoreTabHelperDelegate* core_delegate =
898 CoreTabHelper::FromWebContents(tab)->delegate();
899 if (!core_delegate || core_delegate->CanReloadContents(tab))
900 return true;
903 return false;
906 case CommandCloseOtherTabs:
907 case CommandCloseTabsToRight:
908 return !GetIndicesClosedByCommand(context_index, command_id).empty();
910 case CommandDuplicate: {
911 std::vector<int> indices = GetIndicesForCommand(context_index);
912 for (size_t i = 0; i < indices.size(); ++i) {
913 if (delegate_->CanDuplicateContentsAt(indices[i]))
914 return true;
916 return false;
919 case CommandRestoreTab:
920 return delegate_->GetRestoreTabType() !=
921 TabStripModelDelegate::RESTORE_NONE;
923 case CommandTogglePinned: {
924 std::vector<int> indices = GetIndicesForCommand(context_index);
925 for (size_t i = 0; i < indices.size(); ++i) {
926 if (!IsAppTab(indices[i]))
927 return true;
929 return false;
932 case CommandToggleTabAudioMuted: {
933 std::vector<int> indices = GetIndicesForCommand(context_index);
934 for (size_t i = 0; i < indices.size(); ++i) {
935 if (!chrome::CanToggleAudioMute(GetWebContentsAt(indices[i])))
936 return false;
938 return true;
941 case CommandBookmarkAllTabs:
942 return browser_defaults::bookmarks_enabled &&
943 delegate_->CanBookmarkAllTabs();
945 case CommandSelectByDomain:
946 case CommandSelectByOpener:
947 return true;
949 default:
950 NOTREACHED();
952 return false;
955 void TabStripModel::ExecuteContextMenuCommand(
956 int context_index, ContextMenuCommand command_id) {
957 DCHECK(command_id > CommandFirst && command_id < CommandLast);
958 switch (command_id) {
959 case CommandNewTab:
960 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
961 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
962 TabStripModel::NEW_TAB_CONTEXT_MENU,
963 TabStripModel::NEW_TAB_ENUM_COUNT);
964 delegate()->AddTabAt(GURL(), context_index + 1, true);
965 break;
967 case CommandReload: {
968 content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
969 std::vector<int> indices = GetIndicesForCommand(context_index);
970 for (size_t i = 0; i < indices.size(); ++i) {
971 WebContents* tab = GetWebContentsAt(indices[i]);
972 if (tab) {
973 CoreTabHelperDelegate* core_delegate =
974 CoreTabHelper::FromWebContents(tab)->delegate();
975 if (!core_delegate || core_delegate->CanReloadContents(tab))
976 tab->GetController().Reload(true);
979 break;
982 case CommandDuplicate: {
983 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
984 std::vector<int> indices = GetIndicesForCommand(context_index);
985 // Copy the WebContents off as the indices will change as tabs are
986 // duplicated.
987 std::vector<WebContents*> tabs;
988 for (size_t i = 0; i < indices.size(); ++i)
989 tabs.push_back(GetWebContentsAt(indices[i]));
990 for (size_t i = 0; i < tabs.size(); ++i) {
991 int index = GetIndexOfWebContents(tabs[i]);
992 if (index != -1 && delegate_->CanDuplicateContentsAt(index))
993 delegate_->DuplicateContentsAt(index);
995 break;
998 case CommandCloseTab: {
999 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
1000 InternalCloseTabs(GetIndicesForCommand(context_index),
1001 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
1002 break;
1005 case CommandCloseOtherTabs: {
1006 content::RecordAction(
1007 UserMetricsAction("TabContextMenu_CloseOtherTabs"));
1008 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1009 CLOSE_CREATE_HISTORICAL_TAB);
1010 break;
1013 case CommandCloseTabsToRight: {
1014 content::RecordAction(
1015 UserMetricsAction("TabContextMenu_CloseTabsToRight"));
1016 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1017 CLOSE_CREATE_HISTORICAL_TAB);
1018 break;
1021 case CommandRestoreTab: {
1022 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1023 delegate_->RestoreTab();
1024 break;
1027 case CommandTogglePinned: {
1028 content::RecordAction(
1029 UserMetricsAction("TabContextMenu_TogglePinned"));
1030 std::vector<int> indices = GetIndicesForCommand(context_index);
1031 bool pin = WillContextMenuPin(context_index);
1032 if (pin) {
1033 for (size_t i = 0; i < indices.size(); ++i) {
1034 if (!IsAppTab(indices[i]))
1035 SetTabPinned(indices[i], true);
1037 } else {
1038 // Unpin from the back so that the order is maintained (unpinning can
1039 // trigger moving a tab).
1040 for (size_t i = indices.size(); i > 0; --i) {
1041 if (!IsAppTab(indices[i - 1]))
1042 SetTabPinned(indices[i - 1], false);
1045 break;
1048 case CommandToggleTabAudioMuted: {
1049 const std::vector<int>& indices = GetIndicesForCommand(context_index);
1050 const bool mute = !chrome::AreAllTabsMuted(*this, indices);
1051 if (mute)
1052 content::RecordAction(UserMetricsAction("TabContextMenu_MuteTabs"));
1053 else
1054 content::RecordAction(UserMetricsAction("TabContextMenu_UnmuteTabs"));
1055 for (std::vector<int>::const_iterator i = indices.begin();
1056 i != indices.end(); ++i) {
1057 chrome::SetTabAudioMuted(GetWebContentsAt(*i), mute,
1058 chrome::kMutedToggleCauseUser);
1060 break;
1063 case CommandBookmarkAllTabs: {
1064 content::RecordAction(
1065 UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1067 delegate_->BookmarkAllTabs();
1068 break;
1071 case CommandSelectByDomain:
1072 case CommandSelectByOpener: {
1073 std::vector<int> indices;
1074 if (command_id == CommandSelectByDomain)
1075 GetIndicesWithSameDomain(context_index, &indices);
1076 else
1077 GetIndicesWithSameOpener(context_index, &indices);
1078 ui::ListSelectionModel selection_model;
1079 selection_model.SetSelectedIndex(context_index);
1080 for (size_t i = 0; i < indices.size(); ++i)
1081 selection_model.AddIndexToSelection(indices[i]);
1082 SetSelectionFromModel(selection_model);
1083 break;
1086 default:
1087 NOTREACHED();
1091 std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1092 int index,
1093 ContextMenuCommand id) const {
1094 DCHECK(ContainsIndex(index));
1095 DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1096 bool is_selected = IsTabSelected(index);
1097 int start;
1098 if (id == CommandCloseTabsToRight) {
1099 if (is_selected) {
1100 start = selection_model_.selected_indices()[
1101 selection_model_.selected_indices().size() - 1] + 1;
1102 } else {
1103 start = index + 1;
1105 } else {
1106 start = 0;
1108 // NOTE: callers expect the vector to be sorted in descending order.
1109 std::vector<int> indices;
1110 for (int i = count() - 1; i >= start; --i) {
1111 if (i != index && !IsMiniTab(i) && (!is_selected || !IsTabSelected(i)))
1112 indices.push_back(i);
1114 return indices;
1117 bool TabStripModel::WillContextMenuPin(int index) {
1118 std::vector<int> indices = GetIndicesForCommand(index);
1119 // If all tabs are pinned, then we unpin, otherwise we pin.
1120 bool all_pinned = true;
1121 for (size_t i = 0; i < indices.size() && all_pinned; ++i) {
1122 if (!IsAppTab(index)) // We never change app tabs.
1123 all_pinned = IsTabPinned(indices[i]);
1125 return !all_pinned;
1128 // static
1129 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1130 int* browser_cmd) {
1131 switch (cmd_id) {
1132 case CommandNewTab:
1133 *browser_cmd = IDC_NEW_TAB;
1134 break;
1135 case CommandReload:
1136 *browser_cmd = IDC_RELOAD;
1137 break;
1138 case CommandDuplicate:
1139 *browser_cmd = IDC_DUPLICATE_TAB;
1140 break;
1141 case CommandCloseTab:
1142 *browser_cmd = IDC_CLOSE_TAB;
1143 break;
1144 case CommandRestoreTab:
1145 *browser_cmd = IDC_RESTORE_TAB;
1146 break;
1147 case CommandBookmarkAllTabs:
1148 *browser_cmd = IDC_BOOKMARK_ALL_TABS;
1149 break;
1150 default:
1151 *browser_cmd = 0;
1152 return false;
1155 return true;
1158 ///////////////////////////////////////////////////////////////////////////////
1159 // TabStripModel, private:
1161 std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices(
1162 const std::vector<int>& indices) const {
1163 std::vector<WebContents*> contents;
1164 for (size_t i = 0; i < indices.size(); ++i)
1165 contents.push_back(GetWebContentsAtImpl(indices[i]));
1166 return contents;
1169 void TabStripModel::GetIndicesWithSameDomain(int index,
1170 std::vector<int>* indices) {
1171 std::string domain = GetWebContentsAt(index)->GetURL().host();
1172 if (domain.empty())
1173 return;
1174 for (int i = 0; i < count(); ++i) {
1175 if (i == index)
1176 continue;
1177 if (GetWebContentsAt(i)->GetURL().host() == domain)
1178 indices->push_back(i);
1182 void TabStripModel::GetIndicesWithSameOpener(int index,
1183 std::vector<int>* indices) {
1184 WebContents* opener = contents_data_[index]->group();
1185 if (!opener) {
1186 // If there is no group, find all tabs with the selected tab as the opener.
1187 opener = GetWebContentsAt(index);
1188 if (!opener)
1189 return;
1191 for (int i = 0; i < count(); ++i) {
1192 if (i == index)
1193 continue;
1194 if (contents_data_[i]->group() == opener ||
1195 GetWebContentsAtImpl(i) == opener) {
1196 indices->push_back(i);
1201 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1202 if (!IsTabSelected(index)) {
1203 std::vector<int> indices;
1204 indices.push_back(index);
1205 return indices;
1207 return selection_model_.selected_indices();
1210 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1211 const GURL& url = contents->GetURL();
1212 return url.SchemeIs(content::kChromeUIScheme) &&
1213 url.host() == chrome::kChromeUINewTabHost &&
1214 contents == GetWebContentsAtImpl(count() - 1) &&
1215 contents->GetController().GetEntryCount() == 1;
1218 bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
1219 uint32 close_types) {
1220 if (indices.empty())
1221 return true;
1223 CloseTracker close_tracker(GetWebContentsFromIndices(indices));
1225 base::WeakPtr<TabStripModel> ref(weak_factory_.GetWeakPtr());
1226 const bool closing_all = indices.size() == contents_data_.size();
1227 if (closing_all)
1228 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, WillCloseAllTabs());
1230 // We only try the fast shutdown path if the whole browser process is *not*
1231 // shutting down. Fast shutdown during browser termination is handled in
1232 // BrowserShutdown.
1233 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
1234 // Construct a map of processes to the number of associated tabs that are
1235 // closing.
1236 std::map<content::RenderProcessHost*, size_t> processes;
1237 for (size_t i = 0; i < indices.size(); ++i) {
1238 WebContents* closing_contents = GetWebContentsAtImpl(indices[i]);
1239 if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents))
1240 continue;
1241 content::RenderProcessHost* process =
1242 closing_contents->GetRenderProcessHost();
1243 ++processes[process];
1246 // Try to fast shutdown the tabs that can close.
1247 for (std::map<content::RenderProcessHost*, size_t>::iterator iter =
1248 processes.begin(); iter != processes.end(); ++iter) {
1249 iter->first->FastShutdownForPageCount(iter->second);
1253 // We now return to our regularly scheduled shutdown procedure.
1254 bool retval = true;
1255 while (close_tracker.HasNext()) {
1256 WebContents* closing_contents = close_tracker.Next();
1257 int index = GetIndexOfWebContents(closing_contents);
1258 // Make sure we still contain the tab.
1259 if (index == kNoTab)
1260 continue;
1262 CoreTabHelper* core_tab_helper =
1263 CoreTabHelper::FromWebContents(closing_contents);
1264 core_tab_helper->OnCloseStarted();
1266 // Update the explicitly closed state. If the unload handlers cancel the
1267 // close the state is reset in Browser. We don't update the explicitly
1268 // closed state if already marked as explicitly closed as unload handlers
1269 // call back to this if the close is allowed.
1270 if (!closing_contents->GetClosedByUserGesture()) {
1271 closing_contents->SetClosedByUserGesture(
1272 close_types & CLOSE_USER_GESTURE);
1275 if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) {
1276 retval = false;
1277 continue;
1280 InternalCloseTab(closing_contents, index,
1281 (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
1284 if (ref && closing_all && !retval) {
1285 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1286 CloseAllTabsCanceled());
1289 return retval;
1292 void TabStripModel::InternalCloseTab(WebContents* contents,
1293 int index,
1294 bool create_historical_tabs) {
1295 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1296 TabClosingAt(this, contents, index));
1298 // Ask the delegate to save an entry for this tab in the historical tab
1299 // database if applicable.
1300 if (create_historical_tabs)
1301 delegate_->CreateHistoricalTab(contents);
1303 // Deleting the WebContents will call back to us via
1304 // WebContentsData::WebContentsDestroyed and detach it.
1305 delete contents;
1308 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1309 CHECK(ContainsIndex(index)) <<
1310 "Failed to find: " << index << " in: " << count() << " entries.";
1311 return contents_data_[index]->web_contents();
1314 void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) {
1315 if (contents) {
1316 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1317 TabDeactivated(contents));
1321 void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents,
1322 NotifyTypes notify_types) {
1323 WebContents* new_contents = GetWebContentsAtImpl(active_index());
1324 if (old_contents != new_contents) {
1325 int reason = notify_types == NOTIFY_USER_GESTURE
1326 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1327 : TabStripModelObserver::CHANGE_REASON_NONE;
1328 CHECK(!in_notify_);
1329 in_notify_ = true;
1330 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1331 ActiveTabChanged(old_contents,
1332 new_contents,
1333 active_index(),
1334 reason));
1335 in_notify_ = false;
1336 // Activating a discarded tab reloads it, so it is no longer discarded.
1337 contents_data_[active_index()]->set_discarded(false);
1341 void TabStripModel::NotifyIfActiveOrSelectionChanged(
1342 WebContents* old_contents,
1343 NotifyTypes notify_types,
1344 const ui::ListSelectionModel& old_model) {
1345 NotifyIfActiveTabChanged(old_contents, notify_types);
1347 if (!selection_model().Equals(old_model)) {
1348 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1349 TabSelectionChanged(this, old_model));
1353 void TabStripModel::SetSelection(
1354 const ui::ListSelectionModel& new_model,
1355 NotifyTypes notify_types) {
1356 WebContents* old_contents = GetActiveWebContents();
1357 ui::ListSelectionModel old_model;
1358 old_model.Copy(selection_model_);
1359 if (new_model.active() != selection_model_.active())
1360 NotifyIfTabDeactivated(old_contents);
1361 selection_model_.Copy(new_model);
1362 NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model);
1365 void TabStripModel::SelectRelativeTab(bool next) {
1366 // This may happen during automated testing or if a user somehow buffers
1367 // many key accelerators.
1368 if (contents_data_.empty())
1369 return;
1371 int index = active_index();
1372 int delta = next ? 1 : -1;
1373 index = (index + count() + delta) % count();
1374 ActivateTabAt(index, true);
1377 void TabStripModel::MoveWebContentsAtImpl(int index,
1378 int to_position,
1379 bool select_after_move) {
1380 FixOpenersAndGroupsReferencing(index);
1382 WebContentsData* moved_data = contents_data_[index];
1383 contents_data_.erase(contents_data_.begin() + index);
1384 contents_data_.insert(contents_data_.begin() + to_position, moved_data);
1386 selection_model_.Move(index, to_position);
1387 if (!selection_model_.IsSelected(select_after_move) && select_after_move) {
1388 // TODO(sky): why doesn't this code notify observers?
1389 selection_model_.SetSelectedIndex(to_position);
1392 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1393 TabMoved(moved_data->web_contents(), index, to_position));
1396 void TabStripModel::MoveSelectedTabsToImpl(int index,
1397 size_t start,
1398 size_t length) {
1399 DCHECK(start < selection_model_.selected_indices().size() &&
1400 start + length <= selection_model_.selected_indices().size());
1401 size_t end = start + length;
1402 int count_before_index = 0;
1403 for (size_t i = start; i < end &&
1404 selection_model_.selected_indices()[i] < index + count_before_index;
1405 ++i) {
1406 count_before_index++;
1409 // First move those before index. Any tabs before index end up moving in the
1410 // selection model so we use start each time through.
1411 int target_index = index + count_before_index;
1412 size_t tab_index = start;
1413 while (tab_index < end &&
1414 selection_model_.selected_indices()[start] < index) {
1415 MoveWebContentsAt(selection_model_.selected_indices()[start],
1416 target_index - 1, false);
1417 tab_index++;
1420 // Then move those after the index. These don't result in reordering the
1421 // selection.
1422 while (tab_index < end) {
1423 if (selection_model_.selected_indices()[tab_index] != target_index) {
1424 MoveWebContentsAt(selection_model_.selected_indices()[tab_index],
1425 target_index, false);
1427 tab_index++;
1428 target_index++;
1432 // static
1433 bool TabStripModel::OpenerMatches(const WebContentsData* data,
1434 const WebContents* opener,
1435 bool use_group) {
1436 return data->opener() == opener || (use_group && data->group() == opener);
1439 void TabStripModel::FixOpenersAndGroupsReferencing(int index) {
1440 WebContents* old_contents = GetWebContentsAtImpl(index);
1441 for (WebContentsData* data : contents_data_) {
1442 if (data->group() == old_contents)
1443 data->set_group(contents_data_[index]->group());
1444 if (data->opener() == old_contents)
1445 data->set_opener(contents_data_[index]->opener());