Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / chrome / browser / ui / tabs / tab_strip_model.cc
blob7a751eecaf3cec5f7ad14c3af04995b664cc35b1
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 // Skip over pinned tabs as new tabs are added after pinned tabs.
611 if (contents_data_[i]->pinned())
612 continue;
613 break;
615 opener_and_descendants.insert(contents_data_[i]->web_contents());
616 last_index = i;
618 return last_index;
621 void TabStripModel::TabNavigating(WebContents* contents,
622 ui::PageTransition transition) {
623 if (ShouldForgetOpenersForTransition(transition)) {
624 // Don't forget the openers if this tab is a New Tab page opened at the
625 // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
626 // navigation of one of these transition types before resetting the
627 // opener relationships (this allows for the use case of opening a new
628 // tab to do a quick look-up of something while viewing a tab earlier in
629 // the strip). We can make this heuristic more permissive if need be.
630 if (!IsNewTabAtEndOfTabStrip(contents)) {
631 // If the user navigates the current tab to another page in any way
632 // other than by clicking a link, we want to pro-actively forget all
633 // TabStrip opener relationships since we assume they're beginning a
634 // different task by reusing the current tab.
635 ForgetAllOpeners();
636 // In this specific case we also want to reset the group relationship,
637 // since it is now technically invalid.
638 ForgetGroup(contents);
643 void TabStripModel::ForgetAllOpeners() {
644 // Forget all opener memories so we don't do anything weird with tab
645 // re-selection ordering.
646 for (WebContentsDataVector::const_iterator iter = contents_data_.begin();
647 iter != contents_data_.end(); ++iter)
648 (*iter)->set_opener(NULL);
651 void TabStripModel::ForgetGroup(WebContents* contents) {
652 int index = GetIndexOfWebContents(contents);
653 DCHECK(ContainsIndex(index));
654 contents_data_[index]->set_group(NULL);
655 contents_data_[index]->set_opener(NULL);
658 bool TabStripModel::ShouldResetGroupOnSelect(WebContents* contents) const {
659 int index = GetIndexOfWebContents(contents);
660 DCHECK(ContainsIndex(index));
661 return contents_data_[index]->reset_group_on_select();
664 void TabStripModel::SetTabBlocked(int index, bool blocked) {
665 DCHECK(ContainsIndex(index));
666 if (contents_data_[index]->blocked() == blocked)
667 return;
668 contents_data_[index]->set_blocked(blocked);
669 FOR_EACH_OBSERVER(
670 TabStripModelObserver, observers_,
671 TabBlockedStateChanged(contents_data_[index]->web_contents(),
672 index));
675 void TabStripModel::SetTabPinned(int index, bool pinned) {
676 DCHECK(ContainsIndex(index));
677 if (contents_data_[index]->pinned() == pinned)
678 return;
680 if (IsAppTab(index)) {
681 if (!pinned) {
682 // App tabs should always be pinned.
683 NOTREACHED();
684 return;
686 // Changing the pinned state of an app tab doesn't affect its mini-tab
687 // status.
688 contents_data_[index]->set_pinned(pinned);
689 } else {
690 // The tab is not an app tab, its position may have to change as the
691 // mini-tab state is changing.
692 int non_mini_tab_index = IndexOfFirstNonMiniTab();
693 contents_data_[index]->set_pinned(pinned);
694 if (pinned && index != non_mini_tab_index) {
695 MoveWebContentsAtImpl(index, non_mini_tab_index, false);
696 index = non_mini_tab_index;
697 } else if (!pinned && index + 1 != non_mini_tab_index) {
698 MoveWebContentsAtImpl(index, non_mini_tab_index - 1, false);
699 index = non_mini_tab_index - 1;
702 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
703 TabMiniStateChanged(contents_data_[index]->web_contents(),
704 index));
707 // else: the tab was at the boundary and its position doesn't need to change.
708 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
709 TabPinnedStateChanged(contents_data_[index]->web_contents(),
710 index));
713 bool TabStripModel::IsTabPinned(int index) const {
714 DCHECK(ContainsIndex(index));
715 return contents_data_[index]->pinned();
718 bool TabStripModel::IsMiniTab(int index) const {
719 return IsTabPinned(index) || IsAppTab(index);
722 bool TabStripModel::IsAppTab(int index) const {
723 WebContents* contents = GetWebContentsAt(index);
724 return contents && extensions::TabHelper::FromWebContents(contents)->is_app();
727 bool TabStripModel::IsTabBlocked(int index) const {
728 return contents_data_[index]->blocked();
731 bool TabStripModel::IsTabDiscarded(int index) const {
732 return contents_data_[index]->discarded();
735 int TabStripModel::IndexOfFirstNonMiniTab() const {
736 for (size_t i = 0; i < contents_data_.size(); ++i) {
737 if (!IsMiniTab(static_cast<int>(i)))
738 return static_cast<int>(i);
740 // No mini-tabs.
741 return count();
744 int TabStripModel::ConstrainInsertionIndex(int index, bool mini_tab) {
745 return mini_tab ? std::min(std::max(0, index), IndexOfFirstNonMiniTab()) :
746 std::min(count(), std::max(index, IndexOfFirstNonMiniTab()));
749 void TabStripModel::ExtendSelectionTo(int index) {
750 DCHECK(ContainsIndex(index));
751 ui::ListSelectionModel new_model;
752 new_model.Copy(selection_model_);
753 new_model.SetSelectionFromAnchorTo(index);
754 SetSelection(new_model, NOTIFY_DEFAULT);
757 void TabStripModel::ToggleSelectionAt(int index) {
758 DCHECK(ContainsIndex(index));
759 ui::ListSelectionModel new_model;
760 new_model.Copy(selection_model());
761 if (selection_model_.IsSelected(index)) {
762 if (selection_model_.size() == 1) {
763 // One tab must be selected and this tab is currently selected so we can't
764 // unselect it.
765 return;
767 new_model.RemoveIndexFromSelection(index);
768 new_model.set_anchor(index);
769 if (new_model.active() == index ||
770 new_model.active() == ui::ListSelectionModel::kUnselectedIndex)
771 new_model.set_active(new_model.selected_indices()[0]);
772 } else {
773 new_model.AddIndexToSelection(index);
774 new_model.set_anchor(index);
775 new_model.set_active(index);
777 SetSelection(new_model, NOTIFY_DEFAULT);
780 void TabStripModel::AddSelectionFromAnchorTo(int index) {
781 ui::ListSelectionModel new_model;
782 new_model.Copy(selection_model_);
783 new_model.AddSelectionFromAnchorTo(index);
784 SetSelection(new_model, NOTIFY_DEFAULT);
787 bool TabStripModel::IsTabSelected(int index) const {
788 DCHECK(ContainsIndex(index));
789 return selection_model_.IsSelected(index);
792 void TabStripModel::SetSelectionFromModel(
793 const ui::ListSelectionModel& source) {
794 DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
795 SetSelection(source, NOTIFY_DEFAULT);
798 void TabStripModel::AddWebContents(WebContents* contents,
799 int index,
800 ui::PageTransition transition,
801 int add_types) {
802 // If the newly-opened tab is part of the same task as the parent tab, we want
803 // to inherit the parent's "group" attribute, so that if this tab is then
804 // closed we'll jump back to the parent tab.
805 bool inherit_group = (add_types & ADD_INHERIT_GROUP) == ADD_INHERIT_GROUP;
807 if (transition == ui::PAGE_TRANSITION_LINK &&
808 (add_types & ADD_FORCE_INDEX) == 0) {
809 // We assume tabs opened via link clicks are part of the same task as their
810 // parent. Note that when |force_index| is true (e.g. when the user
811 // drag-and-drops a link to the tab strip), callers aren't really handling
812 // link clicks, they just want to score the navigation like a link click in
813 // the history backend, so we don't inherit the group in this case.
814 index = order_controller_->DetermineInsertionIndex(transition,
815 add_types & ADD_ACTIVE);
816 inherit_group = true;
817 } else {
818 // For all other types, respect what was passed to us, normalizing -1s and
819 // values that are too large.
820 if (index < 0 || index > count())
821 index = count();
824 if (transition == ui::PAGE_TRANSITION_TYPED && index == count()) {
825 // Also, any tab opened at the end of the TabStrip with a "TYPED"
826 // transition inherit group as well. This covers the cases where the user
827 // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
828 // in the address bar and presses Alt+Enter. This allows for opening a new
829 // Tab to quickly look up something. When this Tab is closed, the old one
830 // is re-selected, not the next-adjacent.
831 inherit_group = true;
833 InsertWebContentsAt(index, contents,
834 add_types | (inherit_group ? ADD_INHERIT_GROUP : 0));
835 // Reset the index, just in case insert ended up moving it on us.
836 index = GetIndexOfWebContents(contents);
838 if (inherit_group && transition == ui::PAGE_TRANSITION_TYPED)
839 contents_data_[index]->set_reset_group_on_select(true);
841 // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
842 // here we seem to get failures in startup perf tests.
843 // Ensure that the new WebContentsView begins at the same size as the
844 // previous WebContentsView if it existed. Otherwise, the initial WebKit
845 // layout will be performed based on a width of 0 pixels, causing a
846 // very long, narrow, inaccurate layout. Because some scripts on pages (as
847 // well as WebKit's anchor link location calculation) are run on the
848 // initial layout and not recalculated later, we need to ensure the first
849 // layout is performed with sane view dimensions even when we're opening a
850 // new background tab.
851 if (WebContents* old_contents = GetActiveWebContents()) {
852 if ((add_types & ADD_ACTIVE) == 0) {
853 ResizeWebContents(contents, old_contents->GetContainerBounds().size());
858 void TabStripModel::CloseSelectedTabs() {
859 InternalCloseTabs(selection_model_.selected_indices(),
860 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
863 void TabStripModel::SelectNextTab() {
864 SelectRelativeTab(true);
867 void TabStripModel::SelectPreviousTab() {
868 SelectRelativeTab(false);
871 void TabStripModel::SelectLastTab() {
872 ActivateTabAt(count() - 1, true);
875 void TabStripModel::MoveTabNext() {
876 // TODO: this likely needs to be updated for multi-selection.
877 int new_index = std::min(active_index() + 1, count() - 1);
878 MoveWebContentsAt(active_index(), new_index, true);
881 void TabStripModel::MoveTabPrevious() {
882 // TODO: this likely needs to be updated for multi-selection.
883 int new_index = std::max(active_index() - 1, 0);
884 MoveWebContentsAt(active_index(), new_index, true);
887 // Context menu functions.
888 bool TabStripModel::IsContextMenuCommandEnabled(
889 int context_index, ContextMenuCommand command_id) const {
890 DCHECK(command_id > CommandFirst && command_id < CommandLast);
891 switch (command_id) {
892 case CommandNewTab:
893 case CommandCloseTab:
894 return true;
896 case CommandReload: {
897 std::vector<int> indices = GetIndicesForCommand(context_index);
898 for (size_t i = 0; i < indices.size(); ++i) {
899 WebContents* tab = GetWebContentsAt(indices[i]);
900 if (tab) {
901 CoreTabHelperDelegate* core_delegate =
902 CoreTabHelper::FromWebContents(tab)->delegate();
903 if (!core_delegate || core_delegate->CanReloadContents(tab))
904 return true;
907 return false;
910 case CommandCloseOtherTabs:
911 case CommandCloseTabsToRight:
912 return !GetIndicesClosedByCommand(context_index, command_id).empty();
914 case CommandDuplicate: {
915 std::vector<int> indices = GetIndicesForCommand(context_index);
916 for (size_t i = 0; i < indices.size(); ++i) {
917 if (delegate_->CanDuplicateContentsAt(indices[i]))
918 return true;
920 return false;
923 case CommandRestoreTab:
924 return delegate_->GetRestoreTabType() !=
925 TabStripModelDelegate::RESTORE_NONE;
927 case CommandTogglePinned: {
928 std::vector<int> indices = GetIndicesForCommand(context_index);
929 for (size_t i = 0; i < indices.size(); ++i) {
930 if (!IsAppTab(indices[i]))
931 return true;
933 return false;
936 case CommandToggleTabAudioMuted: {
937 std::vector<int> indices = GetIndicesForCommand(context_index);
938 for (size_t i = 0; i < indices.size(); ++i) {
939 if (!chrome::CanToggleAudioMute(GetWebContentsAt(indices[i])))
940 return false;
942 return true;
945 case CommandBookmarkAllTabs:
946 return browser_defaults::bookmarks_enabled &&
947 delegate_->CanBookmarkAllTabs();
949 case CommandSelectByDomain:
950 case CommandSelectByOpener:
951 return true;
953 default:
954 NOTREACHED();
956 return false;
959 void TabStripModel::ExecuteContextMenuCommand(
960 int context_index, ContextMenuCommand command_id) {
961 DCHECK(command_id > CommandFirst && command_id < CommandLast);
962 switch (command_id) {
963 case CommandNewTab:
964 content::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
965 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
966 TabStripModel::NEW_TAB_CONTEXT_MENU,
967 TabStripModel::NEW_TAB_ENUM_COUNT);
968 delegate()->AddTabAt(GURL(), context_index + 1, true);
969 break;
971 case CommandReload: {
972 content::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
973 std::vector<int> indices = GetIndicesForCommand(context_index);
974 for (size_t i = 0; i < indices.size(); ++i) {
975 WebContents* tab = GetWebContentsAt(indices[i]);
976 if (tab) {
977 CoreTabHelperDelegate* core_delegate =
978 CoreTabHelper::FromWebContents(tab)->delegate();
979 if (!core_delegate || core_delegate->CanReloadContents(tab))
980 tab->GetController().Reload(true);
983 break;
986 case CommandDuplicate: {
987 content::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
988 std::vector<int> indices = GetIndicesForCommand(context_index);
989 // Copy the WebContents off as the indices will change as tabs are
990 // duplicated.
991 std::vector<WebContents*> tabs;
992 for (size_t i = 0; i < indices.size(); ++i)
993 tabs.push_back(GetWebContentsAt(indices[i]));
994 for (size_t i = 0; i < tabs.size(); ++i) {
995 int index = GetIndexOfWebContents(tabs[i]);
996 if (index != -1 && delegate_->CanDuplicateContentsAt(index))
997 delegate_->DuplicateContentsAt(index);
999 break;
1002 case CommandCloseTab: {
1003 content::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
1004 InternalCloseTabs(GetIndicesForCommand(context_index),
1005 CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
1006 break;
1009 case CommandCloseOtherTabs: {
1010 content::RecordAction(
1011 UserMetricsAction("TabContextMenu_CloseOtherTabs"));
1012 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1013 CLOSE_CREATE_HISTORICAL_TAB);
1014 break;
1017 case CommandCloseTabsToRight: {
1018 content::RecordAction(
1019 UserMetricsAction("TabContextMenu_CloseTabsToRight"));
1020 InternalCloseTabs(GetIndicesClosedByCommand(context_index, command_id),
1021 CLOSE_CREATE_HISTORICAL_TAB);
1022 break;
1025 case CommandRestoreTab: {
1026 content::RecordAction(UserMetricsAction("TabContextMenu_RestoreTab"));
1027 delegate_->RestoreTab();
1028 break;
1031 case CommandTogglePinned: {
1032 content::RecordAction(
1033 UserMetricsAction("TabContextMenu_TogglePinned"));
1034 std::vector<int> indices = GetIndicesForCommand(context_index);
1035 bool pin = WillContextMenuPin(context_index);
1036 if (pin) {
1037 for (size_t i = 0; i < indices.size(); ++i) {
1038 if (!IsAppTab(indices[i]))
1039 SetTabPinned(indices[i], true);
1041 } else {
1042 // Unpin from the back so that the order is maintained (unpinning can
1043 // trigger moving a tab).
1044 for (size_t i = indices.size(); i > 0; --i) {
1045 if (!IsAppTab(indices[i - 1]))
1046 SetTabPinned(indices[i - 1], false);
1049 break;
1052 case CommandToggleTabAudioMuted: {
1053 const std::vector<int>& indices = GetIndicesForCommand(context_index);
1054 const bool mute = !chrome::AreAllTabsMuted(*this, indices);
1055 if (mute)
1056 content::RecordAction(UserMetricsAction("TabContextMenu_MuteTabs"));
1057 else
1058 content::RecordAction(UserMetricsAction("TabContextMenu_UnmuteTabs"));
1059 for (std::vector<int>::const_iterator i = indices.begin();
1060 i != indices.end(); ++i) {
1061 chrome::SetTabAudioMuted(GetWebContentsAt(*i), mute,
1062 chrome::kMutedToggleCauseUser);
1064 break;
1067 case CommandBookmarkAllTabs: {
1068 content::RecordAction(
1069 UserMetricsAction("TabContextMenu_BookmarkAllTabs"));
1071 delegate_->BookmarkAllTabs();
1072 break;
1075 case CommandSelectByDomain:
1076 case CommandSelectByOpener: {
1077 std::vector<int> indices;
1078 if (command_id == CommandSelectByDomain)
1079 GetIndicesWithSameDomain(context_index, &indices);
1080 else
1081 GetIndicesWithSameOpener(context_index, &indices);
1082 ui::ListSelectionModel selection_model;
1083 selection_model.SetSelectedIndex(context_index);
1084 for (size_t i = 0; i < indices.size(); ++i)
1085 selection_model.AddIndexToSelection(indices[i]);
1086 SetSelectionFromModel(selection_model);
1087 break;
1090 default:
1091 NOTREACHED();
1095 std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1096 int index,
1097 ContextMenuCommand id) const {
1098 DCHECK(ContainsIndex(index));
1099 DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1100 bool is_selected = IsTabSelected(index);
1101 int start;
1102 if (id == CommandCloseTabsToRight) {
1103 if (is_selected) {
1104 start = selection_model_.selected_indices()[
1105 selection_model_.selected_indices().size() - 1] + 1;
1106 } else {
1107 start = index + 1;
1109 } else {
1110 start = 0;
1112 // NOTE: callers expect the vector to be sorted in descending order.
1113 std::vector<int> indices;
1114 for (int i = count() - 1; i >= start; --i) {
1115 if (i != index && !IsMiniTab(i) && (!is_selected || !IsTabSelected(i)))
1116 indices.push_back(i);
1118 return indices;
1121 bool TabStripModel::WillContextMenuPin(int index) {
1122 std::vector<int> indices = GetIndicesForCommand(index);
1123 // If all tabs are pinned, then we unpin, otherwise we pin.
1124 bool all_pinned = true;
1125 for (size_t i = 0; i < indices.size() && all_pinned; ++i) {
1126 if (!IsAppTab(index)) // We never change app tabs.
1127 all_pinned = IsTabPinned(indices[i]);
1129 return !all_pinned;
1132 // static
1133 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1134 int* browser_cmd) {
1135 switch (cmd_id) {
1136 case CommandNewTab:
1137 *browser_cmd = IDC_NEW_TAB;
1138 break;
1139 case CommandReload:
1140 *browser_cmd = IDC_RELOAD;
1141 break;
1142 case CommandDuplicate:
1143 *browser_cmd = IDC_DUPLICATE_TAB;
1144 break;
1145 case CommandCloseTab:
1146 *browser_cmd = IDC_CLOSE_TAB;
1147 break;
1148 case CommandRestoreTab:
1149 *browser_cmd = IDC_RESTORE_TAB;
1150 break;
1151 case CommandBookmarkAllTabs:
1152 *browser_cmd = IDC_BOOKMARK_ALL_TABS;
1153 break;
1154 default:
1155 *browser_cmd = 0;
1156 return false;
1159 return true;
1162 ///////////////////////////////////////////////////////////////////////////////
1163 // TabStripModel, private:
1165 std::vector<WebContents*> TabStripModel::GetWebContentsFromIndices(
1166 const std::vector<int>& indices) const {
1167 std::vector<WebContents*> contents;
1168 for (size_t i = 0; i < indices.size(); ++i)
1169 contents.push_back(GetWebContentsAtImpl(indices[i]));
1170 return contents;
1173 void TabStripModel::GetIndicesWithSameDomain(int index,
1174 std::vector<int>* indices) {
1175 std::string domain = GetWebContentsAt(index)->GetURL().host();
1176 if (domain.empty())
1177 return;
1178 for (int i = 0; i < count(); ++i) {
1179 if (i == index)
1180 continue;
1181 if (GetWebContentsAt(i)->GetURL().host() == domain)
1182 indices->push_back(i);
1186 void TabStripModel::GetIndicesWithSameOpener(int index,
1187 std::vector<int>* indices) {
1188 WebContents* opener = contents_data_[index]->group();
1189 if (!opener) {
1190 // If there is no group, find all tabs with the selected tab as the opener.
1191 opener = GetWebContentsAt(index);
1192 if (!opener)
1193 return;
1195 for (int i = 0; i < count(); ++i) {
1196 if (i == index)
1197 continue;
1198 if (contents_data_[i]->group() == opener ||
1199 GetWebContentsAtImpl(i) == opener) {
1200 indices->push_back(i);
1205 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1206 if (!IsTabSelected(index)) {
1207 std::vector<int> indices;
1208 indices.push_back(index);
1209 return indices;
1211 return selection_model_.selected_indices();
1214 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1215 const GURL& url = contents->GetURL();
1216 return url.SchemeIs(content::kChromeUIScheme) &&
1217 url.host() == chrome::kChromeUINewTabHost &&
1218 contents == GetWebContentsAtImpl(count() - 1) &&
1219 contents->GetController().GetEntryCount() == 1;
1222 bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices,
1223 uint32 close_types) {
1224 if (indices.empty())
1225 return true;
1227 CloseTracker close_tracker(GetWebContentsFromIndices(indices));
1229 base::WeakPtr<TabStripModel> ref(weak_factory_.GetWeakPtr());
1230 const bool closing_all = indices.size() == contents_data_.size();
1231 if (closing_all)
1232 FOR_EACH_OBSERVER(TabStripModelObserver, observers_, WillCloseAllTabs());
1234 // We only try the fast shutdown path if the whole browser process is *not*
1235 // shutting down. Fast shutdown during browser termination is handled in
1236 // BrowserShutdown.
1237 if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) {
1238 // Construct a map of processes to the number of associated tabs that are
1239 // closing.
1240 std::map<content::RenderProcessHost*, size_t> processes;
1241 for (size_t i = 0; i < indices.size(); ++i) {
1242 WebContents* closing_contents = GetWebContentsAtImpl(indices[i]);
1243 if (delegate_->ShouldRunUnloadListenerBeforeClosing(closing_contents))
1244 continue;
1245 content::RenderProcessHost* process =
1246 closing_contents->GetRenderProcessHost();
1247 ++processes[process];
1250 // Try to fast shutdown the tabs that can close.
1251 for (std::map<content::RenderProcessHost*, size_t>::iterator iter =
1252 processes.begin(); iter != processes.end(); ++iter) {
1253 iter->first->FastShutdownForPageCount(iter->second);
1257 // We now return to our regularly scheduled shutdown procedure.
1258 bool retval = true;
1259 while (close_tracker.HasNext()) {
1260 WebContents* closing_contents = close_tracker.Next();
1261 int index = GetIndexOfWebContents(closing_contents);
1262 // Make sure we still contain the tab.
1263 if (index == kNoTab)
1264 continue;
1266 CoreTabHelper* core_tab_helper =
1267 CoreTabHelper::FromWebContents(closing_contents);
1268 core_tab_helper->OnCloseStarted();
1270 // Update the explicitly closed state. If the unload handlers cancel the
1271 // close the state is reset in Browser. We don't update the explicitly
1272 // closed state if already marked as explicitly closed as unload handlers
1273 // call back to this if the close is allowed.
1274 if (!closing_contents->GetClosedByUserGesture()) {
1275 closing_contents->SetClosedByUserGesture(
1276 close_types & CLOSE_USER_GESTURE);
1279 if (delegate_->RunUnloadListenerBeforeClosing(closing_contents)) {
1280 retval = false;
1281 continue;
1284 InternalCloseTab(closing_contents, index,
1285 (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0);
1288 if (ref && closing_all && !retval) {
1289 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1290 CloseAllTabsCanceled());
1293 return retval;
1296 void TabStripModel::InternalCloseTab(WebContents* contents,
1297 int index,
1298 bool create_historical_tabs) {
1299 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1300 TabClosingAt(this, contents, index));
1302 // Ask the delegate to save an entry for this tab in the historical tab
1303 // database if applicable.
1304 if (create_historical_tabs)
1305 delegate_->CreateHistoricalTab(contents);
1307 // Deleting the WebContents will call back to us via
1308 // WebContentsData::WebContentsDestroyed and detach it.
1309 delete contents;
1312 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1313 CHECK(ContainsIndex(index)) <<
1314 "Failed to find: " << index << " in: " << count() << " entries.";
1315 return contents_data_[index]->web_contents();
1318 void TabStripModel::NotifyIfTabDeactivated(WebContents* contents) {
1319 if (contents) {
1320 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1321 TabDeactivated(contents));
1325 void TabStripModel::NotifyIfActiveTabChanged(WebContents* old_contents,
1326 NotifyTypes notify_types) {
1327 WebContents* new_contents = GetWebContentsAtImpl(active_index());
1328 if (old_contents != new_contents) {
1329 int reason = notify_types == NOTIFY_USER_GESTURE
1330 ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
1331 : TabStripModelObserver::CHANGE_REASON_NONE;
1332 CHECK(!in_notify_);
1333 in_notify_ = true;
1334 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1335 ActiveTabChanged(old_contents,
1336 new_contents,
1337 active_index(),
1338 reason));
1339 in_notify_ = false;
1340 // Activating a discarded tab reloads it, so it is no longer discarded.
1341 contents_data_[active_index()]->set_discarded(false);
1345 void TabStripModel::NotifyIfActiveOrSelectionChanged(
1346 WebContents* old_contents,
1347 NotifyTypes notify_types,
1348 const ui::ListSelectionModel& old_model) {
1349 NotifyIfActiveTabChanged(old_contents, notify_types);
1351 if (!selection_model().Equals(old_model)) {
1352 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1353 TabSelectionChanged(this, old_model));
1357 void TabStripModel::SetSelection(
1358 const ui::ListSelectionModel& new_model,
1359 NotifyTypes notify_types) {
1360 WebContents* old_contents = GetActiveWebContents();
1361 ui::ListSelectionModel old_model;
1362 old_model.Copy(selection_model_);
1363 if (new_model.active() != selection_model_.active())
1364 NotifyIfTabDeactivated(old_contents);
1365 selection_model_.Copy(new_model);
1366 NotifyIfActiveOrSelectionChanged(old_contents, notify_types, old_model);
1369 void TabStripModel::SelectRelativeTab(bool next) {
1370 // This may happen during automated testing or if a user somehow buffers
1371 // many key accelerators.
1372 if (contents_data_.empty())
1373 return;
1375 int index = active_index();
1376 int delta = next ? 1 : -1;
1377 index = (index + count() + delta) % count();
1378 ActivateTabAt(index, true);
1381 void TabStripModel::MoveWebContentsAtImpl(int index,
1382 int to_position,
1383 bool select_after_move) {
1384 FixOpenersAndGroupsReferencing(index);
1386 WebContentsData* moved_data = contents_data_[index];
1387 contents_data_.erase(contents_data_.begin() + index);
1388 contents_data_.insert(contents_data_.begin() + to_position, moved_data);
1390 selection_model_.Move(index, to_position);
1391 if (!selection_model_.IsSelected(select_after_move) && select_after_move) {
1392 // TODO(sky): why doesn't this code notify observers?
1393 selection_model_.SetSelectedIndex(to_position);
1396 FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
1397 TabMoved(moved_data->web_contents(), index, to_position));
1400 void TabStripModel::MoveSelectedTabsToImpl(int index,
1401 size_t start,
1402 size_t length) {
1403 DCHECK(start < selection_model_.selected_indices().size() &&
1404 start + length <= selection_model_.selected_indices().size());
1405 size_t end = start + length;
1406 int count_before_index = 0;
1407 for (size_t i = start; i < end &&
1408 selection_model_.selected_indices()[i] < index + count_before_index;
1409 ++i) {
1410 count_before_index++;
1413 // First move those before index. Any tabs before index end up moving in the
1414 // selection model so we use start each time through.
1415 int target_index = index + count_before_index;
1416 size_t tab_index = start;
1417 while (tab_index < end &&
1418 selection_model_.selected_indices()[start] < index) {
1419 MoveWebContentsAt(selection_model_.selected_indices()[start],
1420 target_index - 1, false);
1421 tab_index++;
1424 // Then move those after the index. These don't result in reordering the
1425 // selection.
1426 while (tab_index < end) {
1427 if (selection_model_.selected_indices()[tab_index] != target_index) {
1428 MoveWebContentsAt(selection_model_.selected_indices()[tab_index],
1429 target_index, false);
1431 tab_index++;
1432 target_index++;
1436 // static
1437 bool TabStripModel::OpenerMatches(const WebContentsData* data,
1438 const WebContents* opener,
1439 bool use_group) {
1440 return data->opener() == opener || (use_group && data->group() == opener);
1443 void TabStripModel::FixOpenersAndGroupsReferencing(int index) {
1444 WebContents* old_contents = GetWebContentsAtImpl(index);
1445 for (WebContentsData* data : contents_data_) {
1446 if (data->group() == old_contents)
1447 data->set_group(contents_data_[index]->group());
1448 if (data->opener() == old_contents)
1449 data->set_opener(contents_data_[index]->opener());