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