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 <set>
9 #include <string>
10 #include <utility>
11 
12 #include "base/auto_reset.h"
13 #include "base/containers/flat_map.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/metrics/user_metrics.h"
16 #include "base/numerics/ranges.h"
17 #include "base/ranges/algorithm.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "build/build_config.h"
21 #include "chrome/app/chrome_command_ids.h"
22 #include "chrome/browser/content_settings/host_content_settings_map_factory.h"
23 #include "chrome/browser/defaults.h"
24 #include "chrome/browser/extensions/tab_helper.h"
25 #include "chrome/browser/lifetime/browser_shutdown.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/resource_coordinator/tab_helper.h"
28 #include "chrome/browser/send_tab_to_self/send_tab_to_self_desktop_util.h"
29 #include "chrome/browser/send_tab_to_self/send_tab_to_self_util.h"
30 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
31 #include "chrome/browser/ui/browser.h"
32 #include "chrome/browser/ui/browser_finder.h"
33 #include "chrome/browser/ui/read_later/reading_list_model_factory.h"
34 #include "chrome/browser/ui/tab_ui_helper.h"
35 #include "chrome/browser/ui/tabs/tab_group.h"
36 #include "chrome/browser/ui/tabs/tab_group_model.h"
37 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
38 #include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
39 #include "chrome/browser/ui/tabs/tab_strip_model_order_controller.h"
40 #include "chrome/browser/ui/tabs/tab_utils.h"
41 #include "chrome/browser/ui/web_applications/web_app_dialog_utils.h"
42 #include "chrome/browser/ui/web_applications/web_app_launch_utils.h"
43 #include "chrome/common/url_constants.h"
44 #include "chrome/grit/generated_resources.h"
45 #include "components/content_settings/core/browser/host_content_settings_map.h"
46 #include "components/reading_list/core/reading_list_model.h"
47 #include "components/tab_groups/tab_group_id.h"
48 #include "components/tab_groups/tab_group_visual_data.h"
49 #include "components/web_modal/web_contents_modal_dialog_manager.h"
50 #include "content/public/browser/render_process_host.h"
51 #include "content/public/browser/render_widget_host.h"
52 #include "content/public/browser/render_widget_host_observer.h"
53 #include "content/public/browser/render_widget_host_view.h"
54 #include "content/public/browser/web_contents.h"
55 #include "content/public/browser/web_contents_observer.h"
56 #include "ui/base/l10n/l10n_util.h"
57 #include "ui/gfx/text_elider.h"
58 
59 using base::UserMetricsAction;
60 using content::WebContents;
61 
62 namespace {
63 
64 class RenderWidgetHostVisibilityTracker;
65 
66 // Works similarly to base::AutoReset but checks for access from the wrong
67 // thread as well as ensuring that the previous value of the re-entrancy guard
68 // variable was false.
69 class ReentrancyCheck {
70  public:
ReentrancyCheck(bool * guard_flag)71   explicit ReentrancyCheck(bool* guard_flag) : guard_flag_(guard_flag) {
72     DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
73     DCHECK(!*guard_flag_);
74     *guard_flag_ = true;
75   }
76 
~ReentrancyCheck()77   ~ReentrancyCheck() { *guard_flag_ = false; }
78 
79  private:
80   bool* const guard_flag_;
81 };
82 
83 // Returns true if the specified transition is one of the types that cause the
84 // opener relationships for the tab in which the transition occurred to be
85 // forgotten. This is generally any navigation that isn't a link click (i.e.
86 // any navigation that can be considered to be the start of a new task distinct
87 // from what had previously occurred in that tab).
ShouldForgetOpenersForTransition(ui::PageTransition transition)88 bool ShouldForgetOpenersForTransition(ui::PageTransition transition) {
89   return ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_TYPED) ||
90          ui::PageTransitionCoreTypeIs(transition,
91                                       ui::PAGE_TRANSITION_AUTO_BOOKMARK) ||
92          ui::PageTransitionCoreTypeIs(transition,
93                                       ui::PAGE_TRANSITION_GENERATED) ||
94          ui::PageTransitionCoreTypeIs(transition,
95                                       ui::PAGE_TRANSITION_KEYWORD) ||
96          ui::PageTransitionCoreTypeIs(transition,
97                                       ui::PAGE_TRANSITION_AUTO_TOPLEVEL);
98 }
99 
100 // Intalls RenderWidgetVisibilityTracker when the active tab has changed.
101 std::unique_ptr<RenderWidgetHostVisibilityTracker>
InstallRenderWigetVisibilityTracker(const TabStripSelectionChange & selection)102 InstallRenderWigetVisibilityTracker(const TabStripSelectionChange& selection) {
103   if (!selection.active_tab_changed())
104     return nullptr;
105 
106   content::RenderWidgetHost* track_host = nullptr;
107   if (selection.new_contents &&
108       selection.new_contents->GetRenderWidgetHostView()) {
109     track_host = selection.new_contents->GetRenderWidgetHostView()
110                      ->GetRenderWidgetHost();
111   }
112   return std::make_unique<RenderWidgetHostVisibilityTracker>(track_host);
113 }
114 
115 // This tracks (and reports via UMA and tracing) how long it takes before a
116 // RenderWidgetHost is requested to become visible.
117 class RenderWidgetHostVisibilityTracker
118     : public content::RenderWidgetHostObserver {
119  public:
RenderWidgetHostVisibilityTracker(content::RenderWidgetHost * host)120   explicit RenderWidgetHostVisibilityTracker(content::RenderWidgetHost* host)
121       : host_(host) {
122     if (!host_ || host_->GetView()->IsShowing())
123       return;
124     host_->AddObserver(this);
125     TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("ui,latency",
126                                       "TabSwitchVisibilityRequest", this);
127   }
128 
129   RenderWidgetHostVisibilityTracker(const RenderWidgetHostVisibilityTracker&) =
130       delete;
131   RenderWidgetHostVisibilityTracker& operator=(
132       const RenderWidgetHostVisibilityTracker&) = delete;
133 
~RenderWidgetHostVisibilityTracker()134   ~RenderWidgetHostVisibilityTracker() override {
135     if (host_)
136       host_->RemoveObserver(this);
137   }
138 
139  private:
140   // content::RenderWidgetHostObserver:
RenderWidgetHostVisibilityChanged(content::RenderWidgetHost * host,bool became_visible)141   void RenderWidgetHostVisibilityChanged(content::RenderWidgetHost* host,
142                                          bool became_visible) override {
143     DCHECK_EQ(host_, host);
144     DCHECK(became_visible);
145     UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
146         "Browser.Tabs.SelectionToVisibilityRequestTime", timer_.Elapsed(),
147         base::TimeDelta::FromMicroseconds(1), base::TimeDelta::FromSeconds(3),
148         50);
149     TRACE_EVENT_NESTABLE_ASYNC_END0("ui,latency", "TabSwitchVisibilityRequest",
150                                     this);
151   }
152 
RenderWidgetHostDestroyed(content::RenderWidgetHost * host)153   void RenderWidgetHostDestroyed(content::RenderWidgetHost* host) override {
154     DCHECK_EQ(host_, host);
155     host_->RemoveObserver(this);
156     host_ = nullptr;
157   }
158 
159   content::RenderWidgetHost* host_ = nullptr;
160   base::ElapsedTimer timer_;
161 };
162 
163 }  // namespace
164 
165 ///////////////////////////////////////////////////////////////////////////////
166 // WebContentsData
167 
168 // An object to own a WebContents that is in a tabstrip, as well as other
169 // various properties it has.
170 class TabStripModel::WebContentsData : public content::WebContentsObserver {
171  public:
172   explicit WebContentsData(std::unique_ptr<WebContents> a_contents);
173   WebContentsData(const WebContentsData&) = delete;
174   WebContentsData& operator=(const WebContentsData&) = delete;
175 
176   // Changes the WebContents that this WebContentsData tracks.
177   std::unique_ptr<WebContents> ReplaceWebContents(
178       std::unique_ptr<WebContents> contents);
web_contents()179   WebContents* web_contents() { return contents_.get(); }
180 
181   // See comments on fields.
opener() const182   WebContents* opener() const { return opener_; }
set_opener(WebContents * value)183   void set_opener(WebContents* value) {
184     DCHECK_NE(value, web_contents()) << "A tab should not be its own opener.";
185     opener_ = value;
186   }
set_reset_opener_on_active_tab_change(bool value)187   void set_reset_opener_on_active_tab_change(bool value) {
188     reset_opener_on_active_tab_change_ = value;
189   }
reset_opener_on_active_tab_change() const190   bool reset_opener_on_active_tab_change() const {
191     return reset_opener_on_active_tab_change_;
192   }
pinned() const193   bool pinned() const { return pinned_; }
set_pinned(bool value)194   void set_pinned(bool value) { pinned_ = value; }
blocked() const195   bool blocked() const { return blocked_; }
set_blocked(bool value)196   void set_blocked(bool value) { blocked_ = value; }
group() const197   base::Optional<tab_groups::TabGroupId> group() const { return group_; }
set_group(base::Optional<tab_groups::TabGroupId> value)198   void set_group(base::Optional<tab_groups::TabGroupId> value) {
199     group_ = value;
200   }
201 
202  private:
203   // Make sure that if someone deletes this WebContents out from under us, it
204   // is properly removed from the tab strip.
205   void WebContentsDestroyed() override;
206 
207   // The WebContents owned by this WebContentsData.
208   std::unique_ptr<WebContents> contents_;
209 
210   // The opener is used to model a set of tabs spawned from a single parent tab.
211   // The relationship is discarded easily, e.g. when the user switches to a tab
212   // not part of the set. This property is used to determine what tab to
213   // activate next when one is closed.
214   WebContents* opener_ = nullptr;
215 
216   // True if |opener_| should be reset when any active tab change occurs (rather
217   // than just one outside the current tree of openers).
218   bool reset_opener_on_active_tab_change_ = false;
219 
220   // Whether the tab is pinned.
221   bool pinned_ = false;
222 
223   // Whether the tab interaction is blocked by a modal dialog.
224   bool blocked_ = false;
225 
226   // The group that contains this tab, if any.
227   base::Optional<tab_groups::TabGroupId> group_ = base::nullopt;
228 };
229 
WebContentsData(std::unique_ptr<WebContents> contents)230 TabStripModel::WebContentsData::WebContentsData(
231     std::unique_ptr<WebContents> contents)
232     : content::WebContentsObserver(contents.get()),
233       contents_(std::move(contents)) {}
234 
ReplaceWebContents(std::unique_ptr<WebContents> contents)235 std::unique_ptr<WebContents> TabStripModel::WebContentsData::ReplaceWebContents(
236     std::unique_ptr<WebContents> contents) {
237   contents_.swap(contents);
238   Observe(contents_.get());
239   return contents;
240 }
241 
WebContentsDestroyed()242 void TabStripModel::WebContentsData::WebContentsDestroyed() {
243   // TODO(erikchen): Remove this NOTREACHED statement as well as the
244   // WebContents observer - this is just a temporary sanity check to make sure
245   // that unit tests are not destroyed a WebContents out from under a
246   // TabStripModel.
247   NOTREACHED();
248 }
249 
250 // Holds state for a WebContents that has been detached from the tab strip.
251 struct TabStripModel::DetachedWebContents {
DetachedWebContentsTabStripModel::DetachedWebContents252   DetachedWebContents(int index_before_any_removals,
253                       int index_at_time_of_removal,
254                       std::unique_ptr<WebContents> contents)
255       : contents(std::move(contents)),
256         index_before_any_removals(index_before_any_removals),
257         index_at_time_of_removal(index_at_time_of_removal) {}
258   DetachedWebContents(const DetachedWebContents&) = delete;
259   DetachedWebContents& operator=(const DetachedWebContents&) = delete;
260   ~DetachedWebContents() = default;
261   DetachedWebContents(DetachedWebContents&&) = default;
262 
263   std::unique_ptr<WebContents> contents;
264 
265   // The index of the WebContents in the original selection model of the tab
266   // strip [prior to any tabs being removed, if multiple tabs are being
267   // simultaneously removed].
268   const int index_before_any_removals;
269 
270   // The index of the WebContents at the time it is being removed. If multiple
271   // tabs are being simultaneously removed, the index reflects previously
272   // removed tabs in this batch.
273   const int index_at_time_of_removal;
274 };
275 
276 // Holds all state necessary to send notifications for detached tabs. Will
277 // also handle WebContents deletion if |will_delete| is true.
278 struct TabStripModel::DetachNotifications {
DetachNotificationsTabStripModel::DetachNotifications279   DetachNotifications(WebContents* initially_active_web_contents,
280                       const ui::ListSelectionModel& selection_model,
281                       bool will_delete)
282       : initially_active_web_contents(initially_active_web_contents),
283         selection_model(selection_model),
284         will_delete(will_delete) {}
285   DetachNotifications(const DetachNotifications&) = delete;
286   DetachNotifications& operator=(const DetachNotifications&) = delete;
287   ~DetachNotifications() = default;
288 
289   // The WebContents that was active prior to any detaches happening.
290   //
291   // It's safe to use a raw pointer here because the active web contents, if
292   // detached, is owned by |detached_web_contents|.
293   //
294   // Once the notification for change of active web contents has been sent,
295   // this field is set to nullptr.
296   WebContents* initially_active_web_contents = nullptr;
297 
298   // The WebContents that were recently detached. Observers need to be notified
299   // about these. These must be updated after construction.
300   std::vector<std::unique_ptr<DetachedWebContents>> detached_web_contents;
301 
302   // The selection model prior to any tabs being detached.
303   const ui::ListSelectionModel selection_model;
304 
305   // Whether to delete the WebContents after sending notifications.
306   const bool will_delete;
307 };
308 
309 ///////////////////////////////////////////////////////////////////////////////
310 // TabStripModel, public:
311 
312 constexpr int TabStripModel::kNoTab;
313 
TabStripModel(TabStripModelDelegate * delegate,Profile * profile)314 TabStripModel::TabStripModel(TabStripModelDelegate* delegate, Profile* profile)
315     : delegate_(delegate), profile_(profile) {
316   DCHECK(delegate_);
317   order_controller_ = std::make_unique<TabStripModelOrderController>(this);
318   group_model_ = std::make_unique<TabGroupModel>(this);
319 
320   constexpr base::TimeDelta kTabScrubbingHistogramIntervalTime =
321       base::TimeDelta::FromSeconds(30);
322 
323   last_tab_switch_timestamp_ = base::TimeTicks::Now();
324   tab_scrubbing_interval_timer_.Start(
325       FROM_HERE, kTabScrubbingHistogramIntervalTime,
326       base::BindRepeating(&TabStripModel::RecordTabScrubbingMetrics,
327                           base::Unretained(this)));
328 }
329 
~TabStripModel()330 TabStripModel::~TabStripModel() {
331   std::vector<TabStripModelObserver*> observers;
332   for (auto& observer : observers_)
333     observer.ModelDestroyed(TabStripModelObserver::ModelPasskey(), this);
334 
335   contents_data_.clear();
336   order_controller_.reset();
337 }
338 
SetTabStripUI(TabStripModelObserver * observer)339 void TabStripModel::SetTabStripUI(TabStripModelObserver* observer) {
340   DCHECK(!tab_strip_ui_was_set_);
341 
342   std::vector<TabStripModelObserver*> new_observers{observer};
343   for (auto& old_observer : observers_)
344     new_observers.push_back(&old_observer);
345 
346   observers_.Clear();
347 
348   for (auto* new_observer : new_observers)
349     observers_.AddObserver(new_observer);
350 
351   observer->StartedObserving(TabStripModelObserver::ModelPasskey(), this);
352   tab_strip_ui_was_set_ = true;
353 }
354 
AddObserver(TabStripModelObserver * observer)355 void TabStripModel::AddObserver(TabStripModelObserver* observer) {
356   observers_.AddObserver(observer);
357   observer->StartedObserving(TabStripModelObserver::ModelPasskey(), this);
358 }
359 
RemoveObserver(TabStripModelObserver * observer)360 void TabStripModel::RemoveObserver(TabStripModelObserver* observer) {
361   observer->StoppedObserving(TabStripModelObserver::ModelPasskey(), this);
362   observers_.RemoveObserver(observer);
363 }
364 
ContainsIndex(int index) const365 bool TabStripModel::ContainsIndex(int index) const {
366   return index >= 0 && index < count();
367 }
368 
AppendWebContents(std::unique_ptr<WebContents> contents,bool foreground)369 void TabStripModel::AppendWebContents(std::unique_ptr<WebContents> contents,
370                                       bool foreground) {
371   InsertWebContentsAt(
372       count(), std::move(contents),
373       foreground ? (ADD_INHERIT_OPENER | ADD_ACTIVE) : ADD_NONE);
374 }
375 
InsertWebContentsAt(int index,std::unique_ptr<WebContents> contents,int add_types,base::Optional<tab_groups::TabGroupId> group)376 int TabStripModel::InsertWebContentsAt(
377     int index,
378     std::unique_ptr<WebContents> contents,
379     int add_types,
380     base::Optional<tab_groups::TabGroupId> group) {
381   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
382   return InsertWebContentsAtImpl(index, std::move(contents), add_types, group);
383 }
384 
ReplaceWebContentsAt(int index,std::unique_ptr<WebContents> new_contents)385 std::unique_ptr<content::WebContents> TabStripModel::ReplaceWebContentsAt(
386     int index,
387     std::unique_ptr<WebContents> new_contents) {
388   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
389 
390   delegate()->WillAddWebContents(new_contents.get());
391 
392   DCHECK(ContainsIndex(index));
393 
394   FixOpeners(index);
395 
396   TabStripSelectionChange selection(GetActiveWebContents(), selection_model_);
397   WebContents* raw_new_contents = new_contents.get();
398   std::unique_ptr<WebContents> old_contents =
399       contents_data_[index]->ReplaceWebContents(std::move(new_contents));
400 
401   // When the active WebContents is replaced send out a selection notification
402   // too. We do this as nearly all observers need to treat a replacement of the
403   // selected contents as the selection changing.
404   if (active_index() == index) {
405     selection.new_contents = raw_new_contents;
406     selection.reason = TabStripModelObserver::CHANGE_REASON_REPLACED;
407   }
408 
409   TabStripModelChange::Replace replace;
410   replace.old_contents = old_contents.get();
411   replace.new_contents = raw_new_contents;
412   replace.index = index;
413   TabStripModelChange change(replace);
414   for (auto& observer : observers_)
415     observer.OnTabStripModelChanged(this, change, selection);
416 
417   return old_contents;
418 }
419 
DetachWebContentsAt(int index)420 std::unique_ptr<content::WebContents> TabStripModel::DetachWebContentsAt(
421     int index) {
422   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
423 
424   DCHECK_NE(active_index(), kNoTab) << "Activate the TabStripModel by "
425                                        "selecting at least one tab before "
426                                        "trying to detach web contents.";
427   WebContents* initially_active_web_contents =
428       GetWebContentsAtImpl(active_index());
429 
430   DetachNotifications notifications(initially_active_web_contents,
431                                     selection_model_, /*will_delete=*/false);
432   std::unique_ptr<DetachedWebContents> dwc =
433       std::make_unique<DetachedWebContents>(
434           index, index,
435           DetachWebContentsImpl(index, /*create_historical_tab=*/false,
436                                 /*will_delete=*/false));
437   notifications.detached_web_contents.push_back(std::move(dwc));
438   SendDetachWebContentsNotifications(&notifications);
439   return std::move(notifications.detached_web_contents[0]->contents);
440 }
441 
DetachWebContentsImpl(int index,bool create_historical_tab,bool will_delete)442 std::unique_ptr<content::WebContents> TabStripModel::DetachWebContentsImpl(
443     int index,
444     bool create_historical_tab,
445     bool will_delete) {
446   if (contents_data_.empty())
447     return nullptr;
448   DCHECK(ContainsIndex(index));
449 
450   FixOpeners(index);
451 
452   // Ask the delegate to save an entry for this tab in the historical tab
453   // database.
454   WebContents* raw_web_contents = GetWebContentsAtImpl(index);
455   if (create_historical_tab)
456     delegate_->CreateHistoricalTab(raw_web_contents);
457 
458   base::Optional<int> next_selected_index =
459       order_controller_->DetermineNewSelectedIndex(index);
460 
461   UngroupTab(index);
462 
463   std::unique_ptr<WebContentsData> old_data = std::move(contents_data_[index]);
464   contents_data_.erase(contents_data_.begin() + index);
465 
466   if (empty()) {
467     selection_model_.Clear();
468   } else {
469     int old_active = active_index();
470     selection_model_.DecrementFrom(index);
471     ui::ListSelectionModel old_model;
472     old_model = selection_model_;
473     if (index == old_active) {
474       if (!selection_model_.empty()) {
475         // The active tab was removed, but there is still something selected.
476         // Move the active and anchor to the first selected index.
477         selection_model_.set_active(selection_model_.selected_indices()[0]);
478         selection_model_.set_anchor(selection_model_.active());
479       } else {
480         DCHECK(next_selected_index.has_value());
481         // The active tab was removed and nothing is selected. Reset the
482         // selection and send out notification.
483         selection_model_.SetSelectedIndex(next_selected_index.value());
484       }
485     }
486   }
487   return old_data->ReplaceWebContents(nullptr);
488 }
489 
SendDetachWebContentsNotifications(DetachNotifications * notifications)490 void TabStripModel::SendDetachWebContentsNotifications(
491     DetachNotifications* notifications) {
492   // Sort the DetachedWebContents in decreasing order of
493   // |index_before_any_removals|. This is because |index_before_any_removals| is
494   // used by observers to update their own copy of TabStripModel state, and each
495   // removal affects subsequent removals of higher index.
496   std::sort(notifications->detached_web_contents.begin(),
497             notifications->detached_web_contents.end(),
498             [](const std::unique_ptr<DetachedWebContents>& dwc1,
499                const std::unique_ptr<DetachedWebContents>& dwc2) {
500               return dwc1->index_before_any_removals >
501                      dwc2->index_before_any_removals;
502             });
503 
504   TabStripModelChange::Remove remove;
505   remove.will_be_deleted = notifications->will_delete;
506   for (auto& dwc : notifications->detached_web_contents) {
507     remove.contents.push_back(
508         {dwc->contents.get(), dwc->index_before_any_removals});
509   }
510   TabStripModelChange change(std::move(remove));
511 
512   TabStripSelectionChange selection;
513   selection.old_contents = notifications->initially_active_web_contents;
514   selection.new_contents = GetActiveWebContents();
515   selection.old_model = notifications->selection_model;
516   selection.new_model = selection_model_;
517   selection.reason = TabStripModelObserver::CHANGE_REASON_NONE;
518   selection.selected_tabs_were_removed = std::any_of(
519       notifications->detached_web_contents.begin(),
520       notifications->detached_web_contents.end(), [&notifications](auto& dwc) {
521         return notifications->selection_model.IsSelected(
522             dwc->index_before_any_removals);
523       });
524 
525   {
526     auto visibility_tracker =
527         empty() ? nullptr : InstallRenderWigetVisibilityTracker(selection);
528     for (auto& observer : observers_)
529       observer.OnTabStripModelChanged(this, change, selection);
530   }
531 
532   for (auto& dwc : notifications->detached_web_contents) {
533     if (notifications->will_delete) {
534       // This destroys the WebContents, which will also send
535       // WebContentsDestroyed notifications.
536       dwc->contents.reset();
537     }
538   }
539 
540   if (empty()) {
541     for (auto& observer : observers_)
542       observer.TabStripEmpty();
543   }
544 }
545 
ActivateTabAt(int index,UserGestureDetails user_gesture)546 void TabStripModel::ActivateTabAt(int index, UserGestureDetails user_gesture) {
547   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
548 
549   DCHECK(ContainsIndex(index));
550   TRACE_EVENT0("ui", "TabStripModel::ActivateTabAt");
551 
552   // Maybe increment count of tabs 'scrubbed' by mouse or key press for
553   // histogram data.
554   if (user_gesture.type == GestureType::kMouse ||
555       user_gesture.type == GestureType::kKeyboard) {
556     constexpr base::TimeDelta kMaxTimeConsideredScrubbing =
557         base::TimeDelta::FromMilliseconds(1500);
558     base::TimeDelta elapsed_time_since_tab_switch =
559         base::TimeTicks::Now() - last_tab_switch_timestamp_;
560     if (elapsed_time_since_tab_switch <= kMaxTimeConsideredScrubbing) {
561       if (user_gesture.type == GestureType::kMouse)
562         ++tabs_scrubbed_by_mouse_press_count_;
563       else if (user_gesture.type == GestureType::kKeyboard)
564         ++tabs_scrubbed_by_key_press_count_;
565     }
566   }
567   last_tab_switch_timestamp_ = base::TimeTicks::Now();
568 
569   TabSwitchEventLatencyRecorder::EventType event_type;
570   switch (user_gesture.type) {
571     case GestureType::kMouse:
572       event_type = TabSwitchEventLatencyRecorder::EventType::kMouse;
573       break;
574     case GestureType::kKeyboard:
575       event_type = TabSwitchEventLatencyRecorder::EventType::kKeyboard;
576       break;
577     case GestureType::kTouch:
578       event_type = TabSwitchEventLatencyRecorder::EventType::kTouch;
579       break;
580     case GestureType::kWheel:
581       event_type = TabSwitchEventLatencyRecorder::EventType::kWheel;
582       break;
583     default:
584       event_type = TabSwitchEventLatencyRecorder::EventType::kOther;
585       break;
586   }
587   tab_switch_event_latency_recorder_.BeginLatencyTiming(user_gesture.time_stamp,
588                                                         event_type);
589   ui::ListSelectionModel new_model = selection_model_;
590   new_model.SetSelectedIndex(index);
591   SetSelection(std::move(new_model),
592                user_gesture.type != GestureType::kNone
593                    ? TabStripModelObserver::CHANGE_REASON_USER_GESTURE
594                    : TabStripModelObserver::CHANGE_REASON_NONE,
595                /*triggered_by_other_operation=*/false);
596 }
597 
RecordTabScrubbingMetrics()598 void TabStripModel::RecordTabScrubbingMetrics() {
599   UMA_HISTOGRAM_COUNTS_10000("Tabs.ScrubbedInInterval.MousePress",
600                              tabs_scrubbed_by_mouse_press_count_);
601   UMA_HISTOGRAM_COUNTS_10000("Tabs.ScrubbedInInterval.KeyPress",
602                              tabs_scrubbed_by_key_press_count_);
603   tabs_scrubbed_by_mouse_press_count_ = 0;
604   tabs_scrubbed_by_key_press_count_ = 0;
605 }
606 
MoveWebContentsAt(int index,int to_position,bool select_after_move)607 int TabStripModel::MoveWebContentsAt(int index,
608                                      int to_position,
609                                      bool select_after_move) {
610   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
611 
612   DCHECK(ContainsIndex(index));
613 
614   to_position = ConstrainMoveIndex(to_position, IsTabPinned(index));
615 
616   if (index == to_position)
617     return to_position;
618 
619   MoveWebContentsAtImpl(index, to_position, select_after_move);
620   EnsureGroupContiguity(to_position);
621 
622   return to_position;
623 }
624 
MoveSelectedTabsTo(int index)625 void TabStripModel::MoveSelectedTabsTo(int index) {
626   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
627 
628   int total_pinned_count = IndexOfFirstNonPinnedTab();
629   int selected_pinned_count = 0;
630   int selected_count =
631       static_cast<int>(selection_model_.selected_indices().size());
632   for (int i = 0; i < selected_count &&
633                   IsTabPinned(selection_model_.selected_indices()[i]);
634        ++i) {
635     selected_pinned_count++;
636   }
637 
638   // To maintain that all pinned tabs occur before non-pinned tabs we move them
639   // first.
640   if (selected_pinned_count > 0) {
641     MoveSelectedTabsToImpl(
642         std::min(total_pinned_count - selected_pinned_count, index), 0u,
643         selected_pinned_count);
644     if (index > total_pinned_count - selected_pinned_count) {
645       // We're being told to drag pinned tabs to an invalid location. Adjust the
646       // index such that non-pinned tabs end up at a location as though we could
647       // move the pinned tabs to index. See description in header for more
648       // details.
649       index += selected_pinned_count;
650     }
651   }
652   if (selected_pinned_count == selected_count)
653     return;
654 
655   // Then move the non-pinned tabs.
656   MoveSelectedTabsToImpl(std::max(index, total_pinned_count),
657                          selected_pinned_count,
658                          selected_count - selected_pinned_count);
659 }
660 
MoveGroupTo(const tab_groups::TabGroupId & group,int to_index)661 void TabStripModel::MoveGroupTo(const tab_groups::TabGroupId& group,
662                                 int to_index) {
663   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
664 
665   DCHECK_NE(to_index, kNoTab);
666 
667   std::vector<int> tabs_in_group = group_model_->GetTabGroup(group)->ListTabs();
668 
669   int from_index = tabs_in_group.front();
670   if (to_index < from_index)
671     from_index = tabs_in_group.back();
672 
673   for (size_t i = 0; i < tabs_in_group.size(); ++i)
674     MoveWebContentsAtImpl(from_index, to_index, false);
675 
676   MoveTabGroup(group);
677 }
678 
GetActiveWebContents() const679 WebContents* TabStripModel::GetActiveWebContents() const {
680   return GetWebContentsAt(active_index());
681 }
682 
GetWebContentsAt(int index) const683 WebContents* TabStripModel::GetWebContentsAt(int index) const {
684   if (ContainsIndex(index))
685     return GetWebContentsAtImpl(index);
686   return nullptr;
687 }
688 
GetIndexOfWebContents(const WebContents * contents) const689 int TabStripModel::GetIndexOfWebContents(const WebContents* contents) const {
690   for (size_t i = 0; i < contents_data_.size(); ++i) {
691     if (contents_data_[i]->web_contents() == contents)
692       return i;
693   }
694   return kNoTab;
695 }
696 
UpdateWebContentsStateAt(int index,TabChangeType change_type)697 void TabStripModel::UpdateWebContentsStateAt(int index,
698                                              TabChangeType change_type) {
699   DCHECK(ContainsIndex(index));
700 
701   for (auto& observer : observers_)
702     observer.TabChangedAt(GetWebContentsAtImpl(index), index, change_type);
703 }
704 
SetTabNeedsAttentionAt(int index,bool attention)705 void TabStripModel::SetTabNeedsAttentionAt(int index, bool attention) {
706   DCHECK(ContainsIndex(index));
707 
708   for (auto& observer : observers_)
709     observer.SetTabNeedsAttentionAt(index, attention);
710 }
711 
CloseAllTabs()712 void TabStripModel::CloseAllTabs() {
713   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
714 
715   // Set state so that observers can adjust their behavior to suit this
716   // specific condition when CloseWebContentsAt causes a flurry of
717   // Close/Detach/Select notifications to be sent.
718   closing_all_ = true;
719   std::vector<content::WebContents*> closing_tabs;
720   closing_tabs.reserve(count());
721   for (int i = count() - 1; i >= 0; --i)
722     closing_tabs.push_back(GetWebContentsAt(i));
723   InternalCloseTabs(closing_tabs, CLOSE_CREATE_HISTORICAL_TAB);
724 }
725 
CloseWebContentsAt(int index,uint32_t close_types)726 bool TabStripModel::CloseWebContentsAt(int index, uint32_t close_types) {
727   DCHECK(ContainsIndex(index));
728   WebContents* contents = GetWebContentsAt(index);
729   return InternalCloseTabs(base::span<WebContents* const>(&contents, 1),
730                            close_types);
731 }
732 
TabsAreLoading() const733 bool TabStripModel::TabsAreLoading() const {
734   for (const auto& data : contents_data_) {
735     if (data->web_contents()->IsLoading())
736       return true;
737   }
738 
739   return false;
740 }
741 
GetOpenerOfWebContentsAt(int index)742 WebContents* TabStripModel::GetOpenerOfWebContentsAt(int index) {
743   DCHECK(ContainsIndex(index));
744   return contents_data_[index]->opener();
745 }
746 
SetOpenerOfWebContentsAt(int index,WebContents * opener)747 void TabStripModel::SetOpenerOfWebContentsAt(int index, WebContents* opener) {
748   DCHECK(ContainsIndex(index));
749   // The TabStripModel only maintains the references to openers that it itself
750   // owns; trying to set an opener to an external WebContents can result in
751   // the opener being used after its freed. See crbug.com/698681.
752   DCHECK(!opener || GetIndexOfWebContents(opener) != kNoTab)
753       << "Cannot set opener to a web contents not owned by this tab strip.";
754   contents_data_[index]->set_opener(opener);
755 }
756 
GetIndexOfLastWebContentsOpenedBy(const WebContents * opener,int start_index) const757 int TabStripModel::GetIndexOfLastWebContentsOpenedBy(const WebContents* opener,
758                                                      int start_index) const {
759   DCHECK(opener);
760   DCHECK(ContainsIndex(start_index));
761 
762   std::set<const WebContents*> opener_and_descendants;
763   opener_and_descendants.insert(opener);
764   int last_index = kNoTab;
765 
766   for (int i = start_index + 1; i < count(); ++i) {
767     // Test opened by transitively, i.e. include tabs opened by tabs opened by
768     // opener, etc. Stop when we find the first non-descendant.
769     if (!opener_and_descendants.count(contents_data_[i]->opener())) {
770       // Skip over pinned tabs as new tabs are added after pinned tabs.
771       if (contents_data_[i]->pinned())
772         continue;
773       break;
774     }
775     opener_and_descendants.insert(contents_data_[i]->web_contents());
776     last_index = i;
777   }
778   return last_index;
779 }
780 
TabNavigating(WebContents * contents,ui::PageTransition transition)781 void TabStripModel::TabNavigating(WebContents* contents,
782                                   ui::PageTransition transition) {
783   if (ShouldForgetOpenersForTransition(transition)) {
784     // Don't forget the openers if this tab is a New Tab page opened at the
785     // end of the TabStrip (e.g. by pressing Ctrl+T). Give the user one
786     // navigation of one of these transition types before resetting the
787     // opener relationships (this allows for the use case of opening a new
788     // tab to do a quick look-up of something while viewing a tab earlier in
789     // the strip). We can make this heuristic more permissive if need be.
790     if (!IsNewTabAtEndOfTabStrip(contents)) {
791       // If the user navigates the current tab to another page in any way
792       // other than by clicking a link, we want to pro-actively forget all
793       // TabStrip opener relationships since we assume they're beginning a
794       // different task by reusing the current tab.
795       ForgetAllOpeners();
796     }
797   }
798 }
799 
SetTabBlocked(int index,bool blocked)800 void TabStripModel::SetTabBlocked(int index, bool blocked) {
801   DCHECK(ContainsIndex(index));
802   if (contents_data_[index]->blocked() == blocked)
803     return;
804   contents_data_[index]->set_blocked(blocked);
805   for (auto& observer : observers_)
806     observer.TabBlockedStateChanged(contents_data_[index]->web_contents(),
807                                     index);
808 }
809 
SetTabPinned(int index,bool pinned)810 void TabStripModel::SetTabPinned(int index, bool pinned) {
811   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
812 
813   SetTabPinnedImpl(index, pinned);
814 }
815 
IsTabPinned(int index) const816 bool TabStripModel::IsTabPinned(int index) const {
817   DCHECK(ContainsIndex(index)) << index;
818   return contents_data_[index]->pinned();
819 }
820 
IsTabCollapsed(int index) const821 bool TabStripModel::IsTabCollapsed(int index) const {
822   base::Optional<tab_groups::TabGroupId> group = GetTabGroupForTab(index);
823   return group.has_value() && IsGroupCollapsed(group.value());
824 }
825 
IsGroupCollapsed(const tab_groups::TabGroupId & group) const826 bool TabStripModel::IsGroupCollapsed(
827     const tab_groups::TabGroupId& group) const {
828   return group_model()->ContainsTabGroup(group) &&
829          group_model()->GetTabGroup(group)->visual_data()->is_collapsed();
830 }
831 
IsTabBlocked(int index) const832 bool TabStripModel::IsTabBlocked(int index) const {
833   return contents_data_[index]->blocked();
834 }
835 
GetTabGroupForTab(int index) const836 base::Optional<tab_groups::TabGroupId> TabStripModel::GetTabGroupForTab(
837     int index) const {
838   return ContainsIndex(index) ? contents_data_[index]->group() : base::nullopt;
839 }
840 
GetSurroundingTabGroup(int index) const841 base::Optional<tab_groups::TabGroupId> TabStripModel::GetSurroundingTabGroup(
842     int index) const {
843   if (!ContainsIndex(index - 1) || !ContainsIndex(index))
844     return base::nullopt;
845 
846   // If the tab before is not in a group, a tab inserted at |index|
847   // wouldn't be surrounded by one group.
848   base::Optional<tab_groups::TabGroupId> group = GetTabGroupForTab(index - 1);
849   if (!group)
850     return base::nullopt;
851 
852   // If the tab after is in a different (or no) group, a new tab at
853   // |index| isn't surrounded.
854   if (group != GetTabGroupForTab(index))
855     return base::nullopt;
856   return group;
857 }
858 
IndexOfFirstNonPinnedTab() const859 int TabStripModel::IndexOfFirstNonPinnedTab() const {
860   for (size_t i = 0; i < contents_data_.size(); ++i) {
861     if (!IsTabPinned(static_cast<int>(i)))
862       return static_cast<int>(i);
863   }
864   // No pinned tabs.
865   return count();
866 }
867 
ExtendSelectionTo(int index)868 void TabStripModel::ExtendSelectionTo(int index) {
869   DCHECK(ContainsIndex(index));
870   ui::ListSelectionModel new_model = selection_model_;
871   new_model.SetSelectionFromAnchorTo(index);
872   SetSelection(std::move(new_model), TabStripModelObserver::CHANGE_REASON_NONE,
873                /*triggered_by_other_operation=*/false);
874 }
875 
ToggleSelectionAt(int index)876 void TabStripModel::ToggleSelectionAt(int index) {
877   DCHECK(ContainsIndex(index));
878   ui::ListSelectionModel new_model = selection_model();
879   if (selection_model_.IsSelected(index)) {
880     if (selection_model_.size() == 1) {
881       // One tab must be selected and this tab is currently selected so we can't
882       // unselect it.
883       return;
884     }
885     new_model.RemoveIndexFromSelection(index);
886     new_model.set_anchor(index);
887     if (new_model.active() == index ||
888         new_model.active() == ui::ListSelectionModel::kUnselectedIndex)
889       new_model.set_active(new_model.selected_indices()[0]);
890   } else {
891     new_model.AddIndexToSelection(index);
892     new_model.set_anchor(index);
893     new_model.set_active(index);
894   }
895   SetSelection(std::move(new_model), TabStripModelObserver::CHANGE_REASON_NONE,
896                /*triggered_by_other_operation=*/false);
897 }
898 
AddSelectionFromAnchorTo(int index)899 void TabStripModel::AddSelectionFromAnchorTo(int index) {
900   ui::ListSelectionModel new_model = selection_model_;
901   new_model.AddSelectionFromAnchorTo(index);
902   SetSelection(std::move(new_model), TabStripModelObserver::CHANGE_REASON_NONE,
903                /*triggered_by_other_operation=*/false);
904 }
905 
IsTabSelected(int index) const906 bool TabStripModel::IsTabSelected(int index) const {
907   DCHECK(ContainsIndex(index));
908   return selection_model_.IsSelected(index);
909 }
910 
SetSelectionFromModel(ui::ListSelectionModel source)911 void TabStripModel::SetSelectionFromModel(ui::ListSelectionModel source) {
912   DCHECK_NE(ui::ListSelectionModel::kUnselectedIndex, source.active());
913   SetSelection(std::move(source), TabStripModelObserver::CHANGE_REASON_NONE,
914                /*triggered_by_other_operation=*/false);
915 }
916 
selection_model() const917 const ui::ListSelectionModel& TabStripModel::selection_model() const {
918   return selection_model_;
919 }
920 
AddWebContents(std::unique_ptr<WebContents> contents,int index,ui::PageTransition transition,int add_types,base::Optional<tab_groups::TabGroupId> group)921 void TabStripModel::AddWebContents(
922     std::unique_ptr<WebContents> contents,
923     int index,
924     ui::PageTransition transition,
925     int add_types,
926     base::Optional<tab_groups::TabGroupId> group) {
927   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
928 
929   // If the newly-opened tab is part of the same task as the parent tab, we want
930   // to inherit the parent's opener attribute, so that if this tab is then
931   // closed we'll jump back to the parent tab.
932   bool inherit_opener = (add_types & ADD_INHERIT_OPENER) == ADD_INHERIT_OPENER;
933 
934   if (ui::PageTransitionTypeIncludingQualifiersIs(transition,
935                                                   ui::PAGE_TRANSITION_LINK) &&
936       (add_types & ADD_FORCE_INDEX) == 0) {
937     // We assume tabs opened via link clicks are part of the same task as their
938     // parent.  Note that when |force_index| is true (e.g. when the user
939     // drag-and-drops a link to the tab strip), callers aren't really handling
940     // link clicks, they just want to score the navigation like a link click in
941     // the history backend, so we don't inherit the opener in this case.
942     index = order_controller_->DetermineInsertionIndex(transition,
943                                                        add_types & ADD_ACTIVE);
944     inherit_opener = true;
945 
946     // The current active index is our opener. If the tab we are adding is not
947     // in a group, set the group of the tab to that of its opener.
948     if (!group.has_value())
949       group = GetTabGroupForTab(active_index());
950   } else {
951     // For all other types, respect what was passed to us, normalizing -1s and
952     // values that are too large.
953     if (index < 0 || index > count())
954       index = count();
955   }
956 
957   // Prevent the tab from being inserted at an index that would make the group
958   // non-contiguous. Most commonly, the new-tab button always attempts to insert
959   // at the end of the tab strip. Extensions can insert at an arbitrary index,
960   // so we have to handle the general case.
961   if (group.has_value()) {
962     auto grouped_tabs = group_model_->GetTabGroup(group.value())->ListTabs();
963     if (grouped_tabs.size() > 0) {
964       DCHECK(base::ranges::is_sorted(grouped_tabs));
965       index = base::ClampToRange(index, grouped_tabs.front(),
966                                  grouped_tabs.back() + 1);
967     }
968   } else if (GetTabGroupForTab(index - 1) == GetTabGroupForTab(index)) {
969     group = GetTabGroupForTab(index);
970   }
971 
972   if (ui::PageTransitionTypeIncludingQualifiersIs(transition,
973                                                   ui::PAGE_TRANSITION_TYPED) &&
974       index == count()) {
975     // Also, any tab opened at the end of the TabStrip with a "TYPED"
976     // transition inherit opener as well. This covers the cases where the user
977     // creates a New Tab (e.g. Ctrl+T, or clicks the New Tab button), or types
978     // in the address bar and presses Alt+Enter. This allows for opening a new
979     // Tab to quickly look up something. When this Tab is closed, the old one
980     // is re-activated, not the next-adjacent.
981     inherit_opener = true;
982   }
983   WebContents* raw_contents = contents.get();
984   InsertWebContentsAtImpl(index, std::move(contents),
985                           add_types | (inherit_opener ? ADD_INHERIT_OPENER : 0),
986                           group);
987   // Reset the index, just in case insert ended up moving it on us.
988   index = GetIndexOfWebContents(raw_contents);
989 
990   // In the "quick look-up" case detailed above, we want to reset the opener
991   // relationship on any active tab change, even to another tab in the same tree
992   // of openers. A jump would be too confusing at that point.
993   if (inherit_opener && ui::PageTransitionTypeIncludingQualifiersIs(
994                             transition, ui::PAGE_TRANSITION_TYPED))
995     contents_data_[index]->set_reset_opener_on_active_tab_change(true);
996 
997   // TODO(sky): figure out why this is here and not in InsertWebContentsAt. When
998   // here we seem to get failures in startup perf tests.
999   // Ensure that the new WebContentsView begins at the same size as the
1000   // previous WebContentsView if it existed.  Otherwise, the initial WebKit
1001   // layout will be performed based on a width of 0 pixels, causing a
1002   // very long, narrow, inaccurate layout.  Because some scripts on pages (as
1003   // well as WebKit's anchor link location calculation) are run on the
1004   // initial layout and not recalculated later, we need to ensure the first
1005   // layout is performed with sane view dimensions even when we're opening a
1006   // new background tab.
1007   if (WebContents* old_contents = GetActiveWebContents()) {
1008     if ((add_types & ADD_ACTIVE) == 0) {
1009       raw_contents->Resize(
1010           gfx::Rect(old_contents->GetContainerBounds().size()));
1011     }
1012   }
1013 }
1014 
CloseSelectedTabs()1015 void TabStripModel::CloseSelectedTabs() {
1016   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1017 
1018   InternalCloseTabs(
1019       GetWebContentsesByIndices(selection_model_.selected_indices()),
1020       CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
1021 }
1022 
SelectNextTab(UserGestureDetails detail)1023 void TabStripModel::SelectNextTab(UserGestureDetails detail) {
1024   SelectRelativeTab(true, detail);
1025 }
1026 
SelectPreviousTab(UserGestureDetails detail)1027 void TabStripModel::SelectPreviousTab(UserGestureDetails detail) {
1028   SelectRelativeTab(false, detail);
1029 }
1030 
SelectLastTab(UserGestureDetails detail)1031 void TabStripModel::SelectLastTab(UserGestureDetails detail) {
1032   ActivateTabAt(count() - 1, detail);
1033 }
1034 
MoveTabNext()1035 void TabStripModel::MoveTabNext() {
1036   MoveTabRelative(true);
1037 }
1038 
MoveTabPrevious()1039 void TabStripModel::MoveTabPrevious() {
1040   MoveTabRelative(false);
1041 }
1042 
AddToNewGroup(const std::vector<int> & indices)1043 tab_groups::TabGroupId TabStripModel::AddToNewGroup(
1044     const std::vector<int>& indices) {
1045   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1046 
1047   // Ensure that the indices are sorted and unique.
1048   DCHECK(base::ranges::is_sorted(indices));
1049   DCHECK(std::adjacent_find(indices.begin(), indices.end()) == indices.end());
1050 
1051   // The odds of |new_group| colliding with an existing group are astronomically
1052   // low. If there is a collision, a DCHECK will fail in |AddToNewGroupImpl()|,
1053   // in which case there is probably something wrong with
1054   // |tab_groups::TabGroupId::GenerateNew()|.
1055   const tab_groups::TabGroupId new_group =
1056       tab_groups::TabGroupId::GenerateNew();
1057   AddToNewGroupImpl(indices, new_group);
1058   OpenTabGroupEditor(new_group);
1059   return new_group;
1060 }
1061 
AddToExistingGroup(const std::vector<int> & indices,const tab_groups::TabGroupId & group)1062 void TabStripModel::AddToExistingGroup(const std::vector<int>& indices,
1063                                        const tab_groups::TabGroupId& group) {
1064   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1065 
1066   // Ensure that the indices are sorted and unique.
1067   DCHECK(base::ranges::is_sorted(indices));
1068   DCHECK(std::adjacent_find(indices.begin(), indices.end()) == indices.end());
1069 
1070   AddToExistingGroupImpl(indices, group);
1071 }
1072 
MoveTabsAndSetGroup(const std::vector<int> & indices,int destination_index,base::Optional<tab_groups::TabGroupId> group)1073 void TabStripModel::MoveTabsAndSetGroup(
1074     const std::vector<int>& indices,
1075     int destination_index,
1076     base::Optional<tab_groups::TabGroupId> group) {
1077   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1078 
1079   MoveTabsAndSetGroupImpl(indices, destination_index, group);
1080 }
1081 
AddToGroupForRestore(const std::vector<int> & indices,const tab_groups::TabGroupId & group)1082 void TabStripModel::AddToGroupForRestore(const std::vector<int>& indices,
1083                                          const tab_groups::TabGroupId& group) {
1084   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1085 
1086   const bool group_exists = group_model_->ContainsTabGroup(group);
1087   if (group_exists)
1088     AddToExistingGroupImpl(indices, group);
1089   else
1090     AddToNewGroupImpl(indices, group);
1091 }
1092 
UpdateGroupForDragRevert(int index,base::Optional<tab_groups::TabGroupId> group_id,base::Optional<tab_groups::TabGroupVisualData> group_data)1093 void TabStripModel::UpdateGroupForDragRevert(
1094     int index,
1095     base::Optional<tab_groups::TabGroupId> group_id,
1096     base::Optional<tab_groups::TabGroupVisualData> group_data) {
1097   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1098   if (group_id.has_value()) {
1099     const bool group_exists = group_model_->ContainsTabGroup(group_id.value());
1100     if (!group_exists)
1101       group_model_->AddTabGroup(group_id.value(), group_data);
1102     GroupTab(index, group_id.value());
1103   } else {
1104     UngroupTab(index);
1105   }
1106 }
1107 
RemoveFromGroup(const std::vector<int> & indices)1108 void TabStripModel::RemoveFromGroup(const std::vector<int>& indices) {
1109   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1110 
1111   std::map<tab_groups::TabGroupId, std::vector<int>> indices_per_tab_group;
1112 
1113   for (int index : indices) {
1114     base::Optional<tab_groups::TabGroupId> old_group = GetTabGroupForTab(index);
1115     if (old_group.has_value())
1116       indices_per_tab_group[old_group.value()].push_back(index);
1117   }
1118 
1119   for (const auto& kv : indices_per_tab_group) {
1120     const std::vector<int>& tabs_in_group =
1121         group_model_->GetTabGroup(kv.first)->ListTabs();
1122 
1123     // Split group into |left_of_group| and |right_of_group| depending on
1124     // whether the index is closest to the left or right edge.
1125     std::vector<int> left_of_group;
1126     std::vector<int> right_of_group;
1127     for (int index : kv.second) {
1128       if (index < tabs_in_group[tabs_in_group.size() / 2]) {
1129         left_of_group.push_back(index);
1130       } else {
1131         right_of_group.push_back(index);
1132       }
1133     }
1134     MoveTabsAndSetGroupImpl(left_of_group, tabs_in_group.front(),
1135                             base::nullopt);
1136     MoveTabsAndSetGroupImpl(right_of_group, tabs_in_group.back() + 1,
1137                             base::nullopt);
1138   }
1139 }
1140 
IsReadLaterSupportedForAny(const std::vector<int> indices)1141 bool TabStripModel::IsReadLaterSupportedForAny(const std::vector<int> indices) {
1142   ReadingListModel* model =
1143       ReadingListModelFactory::GetForBrowserContext(profile_);
1144   if (!model || !model->loaded())
1145     return false;
1146   for (int index : indices) {
1147     if (model->IsUrlSupported(
1148             chrome::GetURLToBookmark(GetWebContentsAt(index))))
1149       return true;
1150   }
1151   return false;
1152 }
1153 
AddToReadLater(const std::vector<int> & indices)1154 void TabStripModel::AddToReadLater(const std::vector<int>& indices) {
1155   ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1156 
1157   AddToReadLaterImpl(indices);
1158 }
1159 
CreateTabGroup(const tab_groups::TabGroupId & group)1160 void TabStripModel::CreateTabGroup(const tab_groups::TabGroupId& group) {
1161   TabGroupChange change(group, TabGroupChange::kCreated);
1162   for (auto& observer : observers_)
1163     observer.OnTabGroupChanged(change);
1164 }
1165 
OpenTabGroupEditor(const tab_groups::TabGroupId & group)1166 void TabStripModel::OpenTabGroupEditor(const tab_groups::TabGroupId& group) {
1167   TabGroupChange change(group, TabGroupChange::kEditorOpened);
1168   for (auto& observer : observers_)
1169     observer.OnTabGroupChanged(change);
1170 }
1171 
ChangeTabGroupContents(const tab_groups::TabGroupId & group)1172 void TabStripModel::ChangeTabGroupContents(
1173     const tab_groups::TabGroupId& group) {
1174   TabGroupChange change(group, TabGroupChange::kContentsChanged);
1175   for (auto& observer : observers_)
1176     observer.OnTabGroupChanged(change);
1177 }
1178 
ChangeTabGroupVisuals(const tab_groups::TabGroupId & group)1179 void TabStripModel::ChangeTabGroupVisuals(const tab_groups::TabGroupId& group) {
1180   TabGroupChange change(group, TabGroupChange::kVisualsChanged);
1181   for (auto& observer : observers_)
1182     observer.OnTabGroupChanged(change);
1183 }
1184 
MoveTabGroup(const tab_groups::TabGroupId & group)1185 void TabStripModel::MoveTabGroup(const tab_groups::TabGroupId& group) {
1186   TabGroupChange change(group, TabGroupChange::kMoved);
1187   for (auto& observer : observers_)
1188     observer.OnTabGroupChanged(change);
1189 }
1190 
CloseTabGroup(const tab_groups::TabGroupId & group)1191 void TabStripModel::CloseTabGroup(const tab_groups::TabGroupId& group) {
1192   TabGroupChange change(group, TabGroupChange::kClosed);
1193   for (auto& observer : observers_)
1194     observer.OnTabGroupChanged(change);
1195 }
1196 
GetTabCount() const1197 int TabStripModel::GetTabCount() const {
1198   return static_cast<int>(contents_data_.size());
1199 }
1200 
1201 // Context menu functions.
IsContextMenuCommandEnabled(int context_index,ContextMenuCommand command_id) const1202 bool TabStripModel::IsContextMenuCommandEnabled(
1203     int context_index,
1204     ContextMenuCommand command_id) const {
1205   DCHECK(command_id > CommandFirst && command_id < CommandLast);
1206   switch (command_id) {
1207     case CommandNewTabToRight:
1208     case CommandCloseTab:
1209       return true;
1210 
1211     case CommandReload: {
1212       std::vector<int> indices = GetIndicesForCommand(context_index);
1213       for (size_t i = 0; i < indices.size(); ++i) {
1214         WebContents* tab = GetWebContentsAt(indices[i]);
1215         if (tab) {
1216           Browser* browser = chrome::FindBrowserWithWebContents(tab);
1217           if (!browser || browser->CanReloadContents(tab))
1218             return true;
1219         }
1220       }
1221       return false;
1222     }
1223 
1224     case CommandCloseOtherTabs:
1225     case CommandCloseTabsToRight:
1226       return !GetIndicesClosedByCommand(context_index, command_id).empty();
1227 
1228     case CommandDuplicate: {
1229       std::vector<int> indices = GetIndicesForCommand(context_index);
1230       for (size_t i = 0; i < indices.size(); ++i) {
1231         if (delegate()->CanDuplicateContentsAt(indices[i]))
1232           return true;
1233       }
1234       return false;
1235     }
1236 
1237     case CommandToggleSiteMuted:
1238       return true;
1239 
1240     case CommandTogglePinned:
1241       return true;
1242 
1243     case CommandToggleGrouped:
1244       return true;
1245 
1246     case CommandFocusMode:
1247       return GetIndicesForCommand(context_index).size() == 1;
1248 
1249     case CommandSendTabToSelf:
1250       return true;
1251 
1252     case CommandSendTabToSelfSingleTarget:
1253       return true;
1254 
1255     case CommandAddToReadLater:
1256       return true;
1257 
1258     case CommandAddToNewGroup:
1259       return true;
1260 
1261     case CommandAddToExistingGroup:
1262       return true;
1263 
1264     case CommandRemoveFromGroup:
1265       return true;
1266 
1267     case CommandMoveToExistingWindow:
1268       return true;
1269 
1270     case CommandMoveTabsToNewWindow:
1271       return delegate()->CanMoveTabsToWindow(
1272           GetIndicesForCommand(context_index));
1273 
1274     default:
1275       NOTREACHED();
1276   }
1277   return false;
1278 }
1279 
ExecuteContextMenuCommand(int context_index,ContextMenuCommand command_id)1280 void TabStripModel::ExecuteContextMenuCommand(int context_index,
1281                                               ContextMenuCommand command_id) {
1282   DCHECK(command_id > CommandFirst && command_id < CommandLast);
1283   switch (command_id) {
1284     case CommandNewTabToRight: {
1285       base::RecordAction(UserMetricsAction("TabContextMenu_NewTab"));
1286       UMA_HISTOGRAM_ENUMERATION("Tab.NewTab",
1287                                 TabStripModel::NEW_TAB_CONTEXT_MENU,
1288                                 TabStripModel::NEW_TAB_ENUM_COUNT);
1289       delegate()->AddTabAt(GURL(), context_index + 1, true,
1290                            GetTabGroupForTab(context_index));
1291       break;
1292     }
1293 
1294     case CommandReload: {
1295       base::RecordAction(UserMetricsAction("TabContextMenu_Reload"));
1296       std::vector<int> indices = GetIndicesForCommand(context_index);
1297       for (size_t i = 0; i < indices.size(); ++i) {
1298         WebContents* tab = GetWebContentsAt(indices[i]);
1299         if (tab) {
1300           Browser* browser = chrome::FindBrowserWithWebContents(tab);
1301           if (!browser || browser->CanReloadContents(tab))
1302             tab->GetController().Reload(content::ReloadType::NORMAL, true);
1303         }
1304       }
1305       break;
1306     }
1307 
1308     case CommandDuplicate: {
1309       base::RecordAction(UserMetricsAction("TabContextMenu_Duplicate"));
1310       std::vector<int> indices = GetIndicesForCommand(context_index);
1311       // Copy the WebContents off as the indices will change as tabs are
1312       // duplicated.
1313       std::vector<WebContents*> tabs;
1314       for (size_t i = 0; i < indices.size(); ++i)
1315         tabs.push_back(GetWebContentsAt(indices[i]));
1316       for (size_t i = 0; i < tabs.size(); ++i) {
1317         int index = GetIndexOfWebContents(tabs[i]);
1318         if (index != -1 && delegate()->CanDuplicateContentsAt(index))
1319           delegate()->DuplicateContentsAt(index);
1320       }
1321       break;
1322     }
1323 
1324     case CommandCloseTab: {
1325       ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1326 
1327       base::RecordAction(UserMetricsAction("TabContextMenu_CloseTab"));
1328       InternalCloseTabs(
1329           GetWebContentsesByIndices(GetIndicesForCommand(context_index)),
1330           CLOSE_CREATE_HISTORICAL_TAB | CLOSE_USER_GESTURE);
1331       break;
1332     }
1333 
1334     case CommandCloseOtherTabs: {
1335       ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1336 
1337       base::RecordAction(UserMetricsAction("TabContextMenu_CloseOtherTabs"));
1338       InternalCloseTabs(GetWebContentsesByIndices(GetIndicesClosedByCommand(
1339                             context_index, command_id)),
1340                         CLOSE_CREATE_HISTORICAL_TAB);
1341       break;
1342     }
1343 
1344     case CommandCloseTabsToRight: {
1345       ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1346 
1347       base::RecordAction(UserMetricsAction("TabContextMenu_CloseTabsToRight"));
1348       InternalCloseTabs(GetWebContentsesByIndices(GetIndicesClosedByCommand(
1349                             context_index, command_id)),
1350                         CLOSE_CREATE_HISTORICAL_TAB);
1351       break;
1352     }
1353 
1354     case CommandSendTabToSelfSingleTarget: {
1355       send_tab_to_self::ShareToSingleTarget(GetWebContentsAt(context_index));
1356       send_tab_to_self::RecordSendTabToSelfClickResult(
1357           send_tab_to_self::kTabMenu, SendTabToSelfClickResult::kClickItem);
1358       break;
1359     }
1360 
1361     case CommandTogglePinned: {
1362       ReentrancyCheck reentrancy_check(&reentrancy_guard_);
1363 
1364       base::RecordAction(UserMetricsAction("TabContextMenu_TogglePinned"));
1365       std::vector<int> indices = GetIndicesForCommand(context_index);
1366       bool pin = WillContextMenuPin(context_index);
1367       if (pin) {
1368         for (size_t i = 0; i < indices.size(); ++i)
1369           SetTabPinnedImpl(indices[i], true);
1370       } else {
1371         // Unpin from the back so that the order is maintained (unpinning can
1372         // trigger moving a tab).
1373         for (size_t i = indices.size(); i > 0; --i)
1374           SetTabPinnedImpl(indices[i - 1], false);
1375       }
1376       break;
1377     }
1378 
1379     case CommandToggleGrouped: {
1380       std::vector<int> indices = GetIndicesForCommand(context_index);
1381       bool group = WillContextMenuGroup(context_index);
1382       if (group)
1383         AddToNewGroup(indices);
1384       else
1385         RemoveFromGroup(indices);
1386 
1387       break;
1388     }
1389 
1390     case CommandFocusMode: {
1391       base::RecordAction(UserMetricsAction("TabContextMenu_FocusMode"));
1392       std::vector<int> indices = GetIndicesForCommand(context_index);
1393       WebContents* contents = GetWebContentsAt(indices[0]);
1394       web_app::ReparentWebContentsForFocusMode(contents);
1395       break;
1396     }
1397 
1398     case CommandToggleSiteMuted: {
1399       const bool mute = WillContextMenuMuteSites(context_index);
1400       if (mute) {
1401         base::RecordAction(
1402             UserMetricsAction("SoundContentSetting.MuteBy.TabStrip"));
1403       } else {
1404         base::RecordAction(
1405             UserMetricsAction("SoundContentSetting.UnmuteBy.TabStrip"));
1406       }
1407       SetSitesMuted(GetIndicesForCommand(context_index), mute);
1408       break;
1409     }
1410 
1411     case CommandAddToReadLater: {
1412       AddToReadLater(GetIndicesForCommand(context_index));
1413       break;
1414     }
1415 
1416     case CommandAddToNewGroup: {
1417       base::RecordAction(UserMetricsAction("TabContextMenu_AddToNewGroup"));
1418 
1419       AddToNewGroup(GetIndicesForCommand(context_index));
1420       break;
1421     }
1422 
1423     case CommandAddToExistingGroup: {
1424       // Do nothing. The submenu's delegate will invoke
1425       // ExecuteAddToExistingGroupCommand with the correct group later.
1426       break;
1427     }
1428 
1429     case CommandRemoveFromGroup: {
1430       base::RecordAction(UserMetricsAction("TabContextMenu_RemoveFromGroup"));
1431       RemoveFromGroup(GetIndicesForCommand(context_index));
1432       break;
1433     }
1434 
1435     case CommandMoveToExistingWindow: {
1436       // Do nothing. The submenu's delegate will invoke
1437       // ExecuteAddToExistingWindowCommand with the correct window later.
1438       break;
1439     }
1440 
1441     case CommandMoveTabsToNewWindow: {
1442       base::RecordAction(
1443           UserMetricsAction("TabContextMenu_MoveTabToNewWindow"));
1444       delegate()->MoveTabsToNewWindow(GetIndicesForCommand(context_index));
1445       break;
1446     }
1447 
1448     default:
1449       NOTREACHED();
1450   }
1451 }
1452 
ExecuteAddToExistingGroupCommand(int context_index,const tab_groups::TabGroupId & group)1453 void TabStripModel::ExecuteAddToExistingGroupCommand(
1454     int context_index,
1455     const tab_groups::TabGroupId& group) {
1456   base::RecordAction(UserMetricsAction("TabContextMenu_AddToExistingGroup"));
1457 
1458   AddToExistingGroup(GetIndicesForCommand(context_index), group);
1459 }
1460 
ExecuteAddToExistingWindowCommand(int context_index,int browser_index)1461 void TabStripModel::ExecuteAddToExistingWindowCommand(int context_index,
1462                                                       int browser_index) {
1463   base::RecordAction(UserMetricsAction("TabContextMenu_AddToExistingWindow"));
1464   delegate()->MoveToExistingWindow(GetIndicesForCommand(context_index),
1465                                    browser_index);
1466 }
1467 
GetExistingWindowsForMoveMenu()1468 std::vector<base::string16> TabStripModel::GetExistingWindowsForMoveMenu() {
1469   return delegate()->GetExistingWindowsForMoveMenu();
1470 }
1471 
WillContextMenuMuteSites(int index)1472 bool TabStripModel::WillContextMenuMuteSites(int index) {
1473   return !chrome::AreAllSitesMuted(*this, GetIndicesForCommand(index));
1474 }
1475 
WillContextMenuPin(int index)1476 bool TabStripModel::WillContextMenuPin(int index) {
1477   std::vector<int> indices = GetIndicesForCommand(index);
1478   // If all tabs are pinned, then we unpin, otherwise we pin.
1479   bool all_pinned = true;
1480   for (size_t i = 0; i < indices.size() && all_pinned; ++i)
1481     all_pinned = IsTabPinned(indices[i]);
1482   return !all_pinned;
1483 }
1484 
WillContextMenuGroup(int index)1485 bool TabStripModel::WillContextMenuGroup(int index) {
1486   std::vector<int> indices = GetIndicesForCommand(index);
1487   DCHECK(!indices.empty());
1488 
1489   // If all tabs are in the same group, then we ungroup, otherwise we group.
1490   base::Optional<tab_groups::TabGroupId> group = GetTabGroupForTab(indices[0]);
1491   if (!group.has_value())
1492     return true;
1493 
1494   for (size_t i = 1; i < indices.size(); ++i) {
1495     if (GetTabGroupForTab(indices[i]) != group)
1496       return true;
1497   }
1498   return false;
1499 }
1500 
1501 // static
ContextMenuCommandToBrowserCommand(int cmd_id,int * browser_cmd)1502 bool TabStripModel::ContextMenuCommandToBrowserCommand(int cmd_id,
1503                                                        int* browser_cmd) {
1504   switch (cmd_id) {
1505     case CommandReload:
1506       *browser_cmd = IDC_RELOAD;
1507       break;
1508     case CommandDuplicate:
1509       *browser_cmd = IDC_DUPLICATE_TAB;
1510       break;
1511     case CommandSendTabToSelf:
1512       *browser_cmd = IDC_SEND_TAB_TO_SELF;
1513       break;
1514     case CommandSendTabToSelfSingleTarget:
1515       *browser_cmd = IDC_SEND_TAB_TO_SELF_SINGLE_TARGET;
1516       break;
1517     case CommandCloseTab:
1518       *browser_cmd = IDC_CLOSE_TAB;
1519       break;
1520     case CommandFocusMode:
1521       *browser_cmd = IDC_FOCUS_THIS_TAB;
1522       break;
1523     default:
1524       *browser_cmd = 0;
1525       return false;
1526   }
1527 
1528   return true;
1529 }
1530 
GetIndexOfNextWebContentsOpenedBy(const WebContents * opener,int start_index) const1531 int TabStripModel::GetIndexOfNextWebContentsOpenedBy(const WebContents* opener,
1532                                                      int start_index) const {
1533   DCHECK(opener);
1534   DCHECK(ContainsIndex(start_index));
1535 
1536   // Check tabs after start_index first.
1537   for (int i = start_index + 1; i < count(); ++i) {
1538     if (contents_data_[i]->opener() == opener)
1539       return i;
1540   }
1541   // Then check tabs before start_index, iterating backwards.
1542   for (int i = start_index - 1; i >= 0; --i) {
1543     if (contents_data_[i]->opener() == opener)
1544       return i;
1545   }
1546   return kNoTab;
1547 }
1548 
GetNextExpandedActiveTab(int start_index,base::Optional<tab_groups::TabGroupId> collapsing_group) const1549 base::Optional<int> TabStripModel::GetNextExpandedActiveTab(
1550     int start_index,
1551     base::Optional<tab_groups::TabGroupId> collapsing_group) const {
1552   // Check tabs from the start_index first.
1553   for (int i = start_index + 1; i < count(); ++i) {
1554     base::Optional<tab_groups::TabGroupId> current_group = GetTabGroupForTab(i);
1555     if (!current_group.has_value() ||
1556         (!IsGroupCollapsed(current_group.value()) &&
1557          current_group != collapsing_group)) {
1558       return i;
1559     }
1560   }
1561   // Then check tabs before start_index, iterating backwards.
1562   for (int i = start_index - 1; i >= 0; --i) {
1563     base::Optional<tab_groups::TabGroupId> current_group = GetTabGroupForTab(i);
1564     if (!current_group.has_value() ||
1565         (!IsGroupCollapsed(current_group.value()) &&
1566          current_group != collapsing_group)) {
1567       return i;
1568     }
1569   }
1570   return base::nullopt;
1571 }
1572 
ForgetAllOpeners()1573 void TabStripModel::ForgetAllOpeners() {
1574   for (const auto& data : contents_data_)
1575     data->set_opener(nullptr);
1576 }
1577 
ForgetOpener(WebContents * contents)1578 void TabStripModel::ForgetOpener(WebContents* contents) {
1579   const int index = GetIndexOfWebContents(contents);
1580   DCHECK(ContainsIndex(index));
1581   contents_data_[index]->set_opener(nullptr);
1582 }
1583 
ShouldResetOpenerOnActiveTabChange(WebContents * contents) const1584 bool TabStripModel::ShouldResetOpenerOnActiveTabChange(
1585     WebContents* contents) const {
1586   const int index = GetIndexOfWebContents(contents);
1587   DCHECK(ContainsIndex(index));
1588   return contents_data_[index]->reset_opener_on_active_tab_change();
1589 }
1590 
1591 ///////////////////////////////////////////////////////////////////////////////
1592 // TabStripModel, private:
1593 
RunUnloadListenerBeforeClosing(content::WebContents * contents)1594 bool TabStripModel::RunUnloadListenerBeforeClosing(
1595     content::WebContents* contents) {
1596   return delegate_->RunUnloadListenerBeforeClosing(contents);
1597 }
1598 
ShouldRunUnloadListenerBeforeClosing(content::WebContents * contents)1599 bool TabStripModel::ShouldRunUnloadListenerBeforeClosing(
1600     content::WebContents* contents) {
1601   return contents->NeedToFireBeforeUnloadOrUnloadEvents() ||
1602          delegate_->ShouldRunUnloadListenerBeforeClosing(contents);
1603 }
1604 
ConstrainInsertionIndex(int index,bool pinned_tab) const1605 int TabStripModel::ConstrainInsertionIndex(int index, bool pinned_tab) const {
1606   return pinned_tab
1607              ? base::ClampToRange(index, 0, IndexOfFirstNonPinnedTab())
1608              : base::ClampToRange(index, IndexOfFirstNonPinnedTab(), count());
1609 }
1610 
ConstrainMoveIndex(int index,bool pinned_tab) const1611 int TabStripModel::ConstrainMoveIndex(int index, bool pinned_tab) const {
1612   return pinned_tab
1613              ? base::ClampToRange(index, 0, IndexOfFirstNonPinnedTab() - 1)
1614              : base::ClampToRange(index, IndexOfFirstNonPinnedTab(),
1615                                   count() - 1);
1616 }
1617 
GetIndicesForCommand(int index) const1618 std::vector<int> TabStripModel::GetIndicesForCommand(int index) const {
1619   if (!IsTabSelected(index))
1620     return {index};
1621   return selection_model_.selected_indices();
1622 }
1623 
GetIndicesClosedByCommand(int index,ContextMenuCommand id) const1624 std::vector<int> TabStripModel::GetIndicesClosedByCommand(
1625     int index,
1626     ContextMenuCommand id) const {
1627   DCHECK(ContainsIndex(index));
1628   DCHECK(id == CommandCloseTabsToRight || id == CommandCloseOtherTabs);
1629   bool is_selected = IsTabSelected(index);
1630   int last_unclosed_tab = -1;
1631   if (id == CommandCloseTabsToRight) {
1632     last_unclosed_tab =
1633         is_selected ? selection_model_.selected_indices().back() : index;
1634   }
1635 
1636   // NOTE: callers expect the vector to be sorted in descending order.
1637   std::vector<int> indices;
1638   for (int i = count() - 1; i > last_unclosed_tab; --i) {
1639     if (i != index && !IsTabPinned(i) && (!is_selected || !IsTabSelected(i)))
1640       indices.push_back(i);
1641   }
1642   return indices;
1643 }
1644 
IsNewTabAtEndOfTabStrip(WebContents * contents) const1645 bool TabStripModel::IsNewTabAtEndOfTabStrip(WebContents* contents) const {
1646   const GURL& url = contents->GetLastCommittedURL();
1647   return url.SchemeIs(content::kChromeUIScheme) &&
1648          url.host_piece() == chrome::kChromeUINewTabHost &&
1649          contents == GetWebContentsAtImpl(count() - 1) &&
1650          contents->GetController().GetEntryCount() == 1;
1651 }
1652 
GetWebContentsesByIndices(const std::vector<int> & indices)1653 std::vector<content::WebContents*> TabStripModel::GetWebContentsesByIndices(
1654     const std::vector<int>& indices) {
1655   std::vector<content::WebContents*> items;
1656   items.reserve(indices.size());
1657   for (int index : indices)
1658     items.push_back(GetWebContentsAtImpl(index));
1659   return items;
1660 }
1661 
InsertWebContentsAtImpl(int index,std::unique_ptr<content::WebContents> contents,int add_types,base::Optional<tab_groups::TabGroupId> group)1662 int TabStripModel::InsertWebContentsAtImpl(
1663     int index,
1664     std::unique_ptr<content::WebContents> contents,
1665     int add_types,
1666     base::Optional<tab_groups::TabGroupId> group) {
1667   delegate()->WillAddWebContents(contents.get());
1668 
1669   bool active = (add_types & ADD_ACTIVE) != 0;
1670   bool pin = (add_types & ADD_PINNED) != 0;
1671   index = ConstrainInsertionIndex(index, pin);
1672 
1673   // Have to get the active contents before we monkey with the contents
1674   // otherwise we run into problems when we try to change the active contents
1675   // since the old contents and the new contents will be the same...
1676   WebContents* active_contents = GetActiveWebContents();
1677   WebContents* raw_contents = contents.get();
1678   std::unique_ptr<WebContentsData> data =
1679       std::make_unique<WebContentsData>(std::move(contents));
1680   data->set_pinned(pin);
1681   if ((add_types & ADD_INHERIT_OPENER) && active_contents) {
1682     if (active) {
1683       // Forget any existing relationships, we don't want to make things too
1684       // confusing by having multiple openers active at the same time.
1685       ForgetAllOpeners();
1686     }
1687     data->set_opener(active_contents);
1688   }
1689 
1690   // TODO(gbillock): Ask the modal dialog manager whether the WebContents should
1691   // be blocked, or just let the modal dialog manager make the blocking call
1692   // directly and not use this at all.
1693   const web_modal::WebContentsModalDialogManager* manager =
1694       web_modal::WebContentsModalDialogManager::FromWebContents(raw_contents);
1695   if (manager)
1696     data->set_blocked(manager->IsDialogActive());
1697 
1698   TabStripSelectionChange selection(GetActiveWebContents(), selection_model_);
1699 
1700   contents_data_.insert(contents_data_.begin() + index, std::move(data));
1701 
1702   selection_model_.IncrementFrom(index);
1703 
1704   if (active) {
1705     ui::ListSelectionModel new_model = selection_model_;
1706     new_model.SetSelectedIndex(index);
1707     selection = SetSelection(std::move(new_model),
1708                              TabStripModelObserver::CHANGE_REASON_NONE,
1709                              /*triggered_by_other_operation=*/true);
1710   }
1711 
1712   TabStripModelChange::Insert insert;
1713   insert.contents.push_back({raw_contents, index});
1714   TabStripModelChange change(std::move(insert));
1715   for (auto& observer : observers_)
1716     observer.OnTabStripModelChanged(this, change, selection);
1717   if (group.has_value())
1718     GroupTab(index, group.value());
1719 
1720   return index;
1721 }
1722 
InternalCloseTabs(base::span<content::WebContents * const> items,uint32_t close_types)1723 bool TabStripModel::InternalCloseTabs(
1724     base::span<content::WebContents* const> items,
1725     uint32_t close_types) {
1726   if (items.empty())
1727     return true;
1728 
1729   const bool closing_all = static_cast<int>(items.size()) == count();
1730   base::WeakPtr<TabStripModel> ref = weak_factory_.GetWeakPtr();
1731   if (closing_all) {
1732     for (auto& observer : observers_)
1733       observer.WillCloseAllTabs(this);
1734   }
1735   const bool closed_all = CloseWebContentses(items, close_types);
1736   if (!ref)
1737     return closed_all;
1738   if (closing_all) {
1739     // CloseAllTabsStopped is sent with reason kCloseAllCompleted if
1740     // closed_all; otherwise kCloseAllCanceled is sent.
1741     for (auto& observer : observers_)
1742       observer.CloseAllTabsStopped(
1743           this, closed_all ? TabStripModelObserver::kCloseAllCompleted
1744                            : TabStripModelObserver::kCloseAllCanceled);
1745   }
1746 
1747   return closed_all;
1748 }
1749 
CloseWebContentses(base::span<content::WebContents * const> items,uint32_t close_types)1750 bool TabStripModel::CloseWebContentses(
1751     base::span<content::WebContents* const> items,
1752     uint32_t close_types) {
1753   if (items.empty())
1754     return true;
1755 
1756   // We only try the fast shutdown path if the whole browser process is *not*
1757   // shutting down. Fast shutdown during browser termination is handled in
1758   // browser_shutdown::OnShutdownStarting.
1759   if (!browser_shutdown::HasShutdownStarted()) {
1760     // Construct a map of processes to the number of associated tabs that are
1761     // closing.
1762     base::flat_map<content::RenderProcessHost*, size_t> processes;
1763     for (content::WebContents* contents : items) {
1764       if (ShouldRunUnloadListenerBeforeClosing(contents))
1765         continue;
1766       content::RenderProcessHost* process =
1767           contents->GetMainFrame()->GetProcess();
1768       ++processes[process];
1769     }
1770 
1771     // Try to fast shutdown the tabs that can close.
1772     for (const auto& pair : processes)
1773       pair.first->FastShutdownIfPossible(pair.second, false);
1774   }
1775 
1776   DetachNotifications notifications(GetWebContentsAtImpl(active_index()),
1777                                     selection_model_, /*will_delete=*/true);
1778 
1779   // We now return to our regularly scheduled shutdown procedure.
1780   bool closed_all = true;
1781 
1782   // The indices of WebContents prior to any modification of the internal state.
1783   std::vector<int> original_indices;
1784   original_indices.resize(items.size());
1785   for (size_t i = 0; i < items.size(); ++i)
1786     original_indices[i] = GetIndexOfWebContents(items[i]);
1787 
1788   for (size_t i = 0; i < items.size(); ++i) {
1789     WebContents* closing_contents = items[i];
1790 
1791     // The index into contents_data_.
1792     int current_index = GetIndexOfWebContents(closing_contents);
1793     DCHECK_NE(current_index, kNoTab);
1794 
1795     // Update the explicitly closed state. If the unload handlers cancel the
1796     // close the state is reset in Browser. We don't update the explicitly
1797     // closed state if already marked as explicitly closed as unload handlers
1798     // call back to this if the close is allowed.
1799     if (!closing_contents->GetClosedByUserGesture()) {
1800       closing_contents->SetClosedByUserGesture(
1801           close_types & TabStripModel::CLOSE_USER_GESTURE);
1802     }
1803 
1804     if (RunUnloadListenerBeforeClosing(closing_contents)) {
1805       closed_all = false;
1806       continue;
1807     }
1808 
1809     std::unique_ptr<DetachedWebContents> dwc =
1810         std::make_unique<DetachedWebContents>(
1811             original_indices[i], current_index,
1812             DetachWebContentsImpl(current_index,
1813                                   close_types & CLOSE_CREATE_HISTORICAL_TAB,
1814                                   /*will_delete=*/true));
1815     notifications.detached_web_contents.push_back(std::move(dwc));
1816   }
1817 
1818   // When unload handler is triggered for all items, we should wait for the
1819   // result.
1820   if (!notifications.detached_web_contents.empty())
1821     SendDetachWebContentsNotifications(&notifications);
1822 
1823   return closed_all;
1824 }
1825 
GetWebContentsAtImpl(int index) const1826 WebContents* TabStripModel::GetWebContentsAtImpl(int index) const {
1827   CHECK(ContainsIndex(index))
1828       << "Failed to find: " << index << " in: " << count() << " entries.";
1829   return contents_data_[index]->web_contents();
1830 }
1831 
SetSelection(ui::ListSelectionModel new_model,TabStripModelObserver::ChangeReason reason,bool triggered_by_other_operation)1832 TabStripSelectionChange TabStripModel::SetSelection(
1833     ui::ListSelectionModel new_model,
1834     TabStripModelObserver::ChangeReason reason,
1835     bool triggered_by_other_operation) {
1836   TabStripSelectionChange selection;
1837   selection.old_model = selection_model_;
1838   selection.old_contents = GetActiveWebContents();
1839   selection.new_model = new_model;
1840   selection.reason = reason;
1841 
1842   // This is done after notifying TabDeactivated() because caller can assume
1843   // that TabStripModel::active_index() would return the index for
1844   // |selection.old_contents|.
1845   selection_model_ = new_model;
1846   selection.new_contents = GetActiveWebContents();
1847 
1848   if (!triggered_by_other_operation &&
1849       (selection.active_tab_changed() || selection.selection_changed())) {
1850     if (selection.active_tab_changed()) {
1851       auto now = base::TimeTicks::Now();
1852       if (selection.new_contents &&
1853           selection.new_contents->GetRenderWidgetHostView()) {
1854         auto input_event_timestamp =
1855             tab_switch_event_latency_recorder_.input_event_timestamp();
1856         // input_event_timestamp may be null in some cases, e.g. in tests.
1857         selection.new_contents->GetRenderWidgetHostView()
1858             ->SetRecordContentToVisibleTimeRequest(
1859                 !input_event_timestamp.is_null() ? input_event_timestamp : now,
1860                 resource_coordinator::ResourceCoordinatorTabHelper::IsLoaded(
1861                     selection.new_contents),
1862                 /*show_reason_tab_switching=*/true,
1863                 /*show_reason_unoccluded=*/false,
1864                 /*show_reason_bfcache_restore=*/false);
1865       }
1866       tab_switch_event_latency_recorder_.OnWillChangeActiveTab(now);
1867     }
1868     TabStripModelChange change;
1869     auto visibility_tracker = InstallRenderWigetVisibilityTracker(selection);
1870     for (auto& observer : observers_)
1871       observer.OnTabStripModelChanged(this, change, selection);
1872   }
1873 
1874   return selection;
1875 }
1876 
SelectRelativeTab(bool next,UserGestureDetails detail)1877 void TabStripModel::SelectRelativeTab(bool next, UserGestureDetails detail) {
1878   // This may happen during automated testing or if a user somehow buffers
1879   // many key accelerators.
1880   if (contents_data_.empty())
1881     return;
1882 
1883   const int start_index = active_index();
1884   base::Optional<tab_groups::TabGroupId> start_group =
1885       GetTabGroupForTab(start_index);
1886 
1887   // Ensure the active tab is not in a collapsed group so the while loop can
1888   // fallback on activating the active tab.
1889   DCHECK(!start_group.has_value() || !IsGroupCollapsed(start_group.value()));
1890   const int delta = next ? 1 : -1;
1891   int index = (start_index + count() + delta) % count();
1892   base::Optional<tab_groups::TabGroupId> group = GetTabGroupForTab(index);
1893   while (group.has_value() && IsGroupCollapsed(group.value())) {
1894     index = (index + count() + delta) % count();
1895     group = GetTabGroupForTab(index);
1896   }
1897   ActivateTabAt(index, detail);
1898 }
1899 
MoveTabRelative(bool forward)1900 void TabStripModel::MoveTabRelative(bool forward) {
1901   const int offset = forward ? 1 : -1;
1902 
1903   // TODO: this needs to be updated for multi-selection.
1904   const int current_index = active_index();
1905   base::Optional<tab_groups::TabGroupId> current_group =
1906       GetTabGroupForTab(current_index);
1907 
1908   int target_index = std::max(std::min(current_index + offset, count() - 1), 0);
1909   base::Optional<tab_groups::TabGroupId> target_group =
1910       GetTabGroupForTab(target_index);
1911 
1912   // If the tab is at a group boundary and the group is expanded, instead of
1913   // actually moving the tab just change its group membership.
1914   if (current_group != target_group) {
1915     if (current_group.has_value()) {
1916       UngroupTab(current_index);
1917       return;
1918     } else if (target_group.has_value()) {
1919       // If the tab is at a group boundary and the group is collapsed, treat the
1920       // collapsed group as a tab and find the next available slot for the tab
1921       // to move to.
1922       const TabGroup* group = group_model_->GetTabGroup(target_group.value());
1923       if (group->visual_data()->is_collapsed()) {
1924         const std::vector<int> tabs_in_group = group->ListTabs();
1925         target_index = forward ? tabs_in_group.back() : tabs_in_group.front();
1926       } else {
1927         GroupTab(current_index, target_group.value());
1928         return;
1929       }
1930     }
1931   }
1932   MoveWebContentsAt(current_index, target_index, true);
1933 }
1934 
MoveWebContentsAtImpl(int index,int to_position,bool select_after_move)1935 void TabStripModel::MoveWebContentsAtImpl(int index,
1936                                           int to_position,
1937                                           bool select_after_move) {
1938   FixOpeners(index);
1939 
1940   TabStripSelectionChange selection(GetActiveWebContents(), selection_model_);
1941 
1942   std::unique_ptr<WebContentsData> moved_data =
1943       std::move(contents_data_[index]);
1944   WebContents* web_contents = moved_data->web_contents();
1945   contents_data_.erase(contents_data_.begin() + index);
1946   contents_data_.insert(contents_data_.begin() + to_position,
1947                         std::move(moved_data));
1948 
1949   selection_model_.Move(index, to_position, 1);
1950   if (!selection_model_.IsSelected(to_position) && select_after_move)
1951     selection_model_.SetSelectedIndex(to_position);
1952   selection.new_model = selection_model_;
1953 
1954   TabStripModelChange::Move move;
1955   move.contents = web_contents;
1956   move.from_index = index;
1957   move.to_index = to_position;
1958   TabStripModelChange change(move);
1959   for (auto& observer : observers_)
1960     observer.OnTabStripModelChanged(this, change, selection);
1961 }
1962 
MoveSelectedTabsToImpl(int index,size_t start,size_t length)1963 void TabStripModel::MoveSelectedTabsToImpl(int index,
1964                                            size_t start,
1965                                            size_t length) {
1966   DCHECK(start < selection_model_.selected_indices().size() &&
1967          start + length <= selection_model_.selected_indices().size());
1968   size_t end = start + length;
1969   int count_before_index = 0;
1970   for (size_t i = start; i < end && selection_model_.selected_indices()[i] <
1971                                         index + count_before_index;
1972        ++i) {
1973     count_before_index++;
1974   }
1975 
1976   // First move those before index. Any tabs before index end up moving in the
1977   // selection model so we use start each time through.
1978   int target_index = index + count_before_index;
1979   size_t tab_index = start;
1980   while (tab_index < end &&
1981          selection_model_.selected_indices()[start] < index) {
1982     MoveWebContentsAtImpl(selection_model_.selected_indices()[start],
1983                           target_index - 1, false);
1984     tab_index++;
1985   }
1986 
1987   // Then move those after the index. These don't result in reordering the
1988   // selection.
1989   while (tab_index < end) {
1990     if (selection_model_.selected_indices()[tab_index] != target_index) {
1991       MoveWebContentsAtImpl(selection_model_.selected_indices()[tab_index],
1992                             target_index, false);
1993     }
1994     tab_index++;
1995     target_index++;
1996   }
1997 }
1998 
AddToNewGroupImpl(const std::vector<int> & indices,const tab_groups::TabGroupId & new_group)1999 void TabStripModel::AddToNewGroupImpl(const std::vector<int>& indices,
2000                                       const tab_groups::TabGroupId& new_group) {
2001   DCHECK(!std::any_of(
2002       contents_data_.cbegin(), contents_data_.cend(),
2003       [new_group](const auto& datum) { return datum->group() == new_group; }));
2004 
2005   group_model_->AddTabGroup(new_group, base::nullopt);
2006 
2007   // Find a destination for the first tab that's not pinned or inside another
2008   // group. We will stack the rest of the tabs up to its right.
2009   int destination_index = -1;
2010   for (int i = indices[0]; i < count(); i++) {
2011     const int destination_candidate = i + 1;
2012 
2013     // Grouping at the end of the tabstrip is always valid.
2014     if (!ContainsIndex(destination_candidate)) {
2015       destination_index = destination_candidate;
2016       break;
2017     }
2018 
2019     // Grouping in the middle of pinned tabs is never valid.
2020     if (IsTabPinned(destination_candidate))
2021       continue;
2022 
2023     // Otherwise, grouping is valid if the destination is not in the middle of a
2024     // different group.
2025     base::Optional<tab_groups::TabGroupId> destination_group =
2026         GetTabGroupForTab(destination_candidate);
2027     if (!destination_group.has_value() ||
2028         destination_group != GetTabGroupForTab(indices[0])) {
2029       destination_index = destination_candidate;
2030       break;
2031     }
2032   }
2033 
2034   MoveTabsAndSetGroupImpl(indices, destination_index, new_group);
2035 }
2036 
AddToExistingGroupImpl(const std::vector<int> & indices,const tab_groups::TabGroupId & group)2037 void TabStripModel::AddToExistingGroupImpl(
2038     const std::vector<int>& indices,
2039     const tab_groups::TabGroupId& group) {
2040   // Do nothing if the "existing" group can't be found. This would only happen
2041   // if the existing group is closed programmatically while the user is
2042   // interacting with the UI - e.g. if a group close operation is started by an
2043   // extension while the user clicks "Add to existing group" in the context
2044   // menu.
2045   // If this happens, the browser should not crash. So here we just make it a
2046   // no-op, since we don't want to create unintended side effects in this rare
2047   // corner case.
2048   if (!group_model_->ContainsTabGroup(group))
2049     return;
2050 
2051   std::vector<int> tabs_in_group = group_model_->GetTabGroup(group)->ListTabs();
2052   DCHECK(base::ranges::is_sorted(tabs_in_group));
2053 
2054   // Split |indices| into |tabs_left_of_group| and |tabs_right_of_group| to
2055   // be moved to proper destination index. Directly set the group for indices
2056   // that are inside the group.
2057   std::vector<int> tabs_left_of_group;
2058   std::vector<int> tabs_right_of_group;
2059   for (int index : indices) {
2060     if (index >= tabs_in_group.front() &&
2061         index <= tabs_in_group.back()) {
2062       GroupTab(index, group);
2063     } else if (index < tabs_in_group.front()) {
2064       tabs_left_of_group.push_back(index);
2065     } else {
2066       DCHECK(index > tabs_in_group.back());
2067       tabs_right_of_group.push_back(index);
2068     }
2069   }
2070 
2071   MoveTabsAndSetGroupImpl(tabs_left_of_group, tabs_in_group.front(), group);
2072   MoveTabsAndSetGroupImpl(tabs_right_of_group, tabs_in_group.back() + 1, group);
2073 }
2074 
MoveTabsAndSetGroupImpl(const std::vector<int> & indices,int destination_index,base::Optional<tab_groups::TabGroupId> group)2075 void TabStripModel::MoveTabsAndSetGroupImpl(
2076     const std::vector<int>& indices,
2077     int destination_index,
2078     base::Optional<tab_groups::TabGroupId> group) {
2079   // Some tabs will need to be moved to the right, some to the left. We need to
2080   // handle those separately. First, move tabs to the right, starting with the
2081   // rightmost tab so we don't cause other tabs we are about to move to shift.
2082   int numTabsMovingRight = 0;
2083   for (size_t i = 0; i < indices.size() && indices[i] < destination_index;
2084        i++) {
2085     numTabsMovingRight++;
2086   }
2087   for (int i = numTabsMovingRight - 1; i >= 0; i--) {
2088     MoveAndSetGroup(indices[i], destination_index - numTabsMovingRight + i,
2089                     group);
2090   }
2091 
2092   // Collect indices for tabs moving to the left.
2093   std::vector<int> move_left_indices;
2094   for (size_t i = numTabsMovingRight; i < indices.size(); i++) {
2095     move_left_indices.push_back(indices[i]);
2096   }
2097 
2098   // Move tabs to the left, starting with the leftmost tab.
2099   for (size_t i = 0; i < move_left_indices.size(); i++)
2100     MoveAndSetGroup(move_left_indices[i], destination_index + i, group);
2101 }
2102 
MoveAndSetGroup(int index,int new_index,base::Optional<tab_groups::TabGroupId> new_group)2103 void TabStripModel::MoveAndSetGroup(
2104     int index,
2105     int new_index,
2106     base::Optional<tab_groups::TabGroupId> new_group) {
2107   if (new_group.has_value()) {
2108     // Unpin tabs when grouping -- the states should be mutually exclusive.
2109     // Here we manually unpin the tab to avoid moving the tab twice, which can
2110     // potentially cause race conditions.
2111     if (IsTabPinned(index)) {
2112       contents_data_[index]->set_pinned(false);
2113       for (auto& observer : observers_) {
2114         observer.TabPinnedStateChanged(
2115             this, contents_data_[index]->web_contents(), index);
2116       }
2117     }
2118 
2119     GroupTab(index, new_group.value());
2120   } else {
2121     UngroupTab(index);
2122   }
2123 
2124   if (index != new_index)
2125     MoveWebContentsAtImpl(index, new_index, false);
2126 }
2127 
AddToReadLaterImpl(const std::vector<int> & indices)2128 void TabStripModel::AddToReadLaterImpl(const std::vector<int>& indices) {
2129   ReadingListModel* model =
2130       ReadingListModelFactory::GetForBrowserContext(profile_);
2131   if (!model || !model->loaded())
2132     return;
2133 
2134   for (int index : indices) {
2135     WebContents* contents = GetWebContentsAt(index);
2136     GURL url;
2137     base::string16 title;
2138     chrome::GetURLAndTitleToBookmark(contents, &url, &title);
2139     if (model->IsUrlSupported(url)) {
2140       model->AddEntry(url, base::UTF16ToUTF8(title),
2141                       reading_list::EntrySource::ADDED_VIA_CURRENT_APP);
2142     }
2143   }
2144 }
2145 
UngroupTab(int index)2146 base::Optional<tab_groups::TabGroupId> TabStripModel::UngroupTab(int index) {
2147   base::Optional<tab_groups::TabGroupId> group = GetTabGroupForTab(index);
2148   if (!group.has_value())
2149     return base::nullopt;
2150 
2151   // Update the tab.
2152   contents_data_[index]->set_group(base::nullopt);
2153   for (auto& observer : observers_) {
2154     observer.TabGroupedStateChanged(
2155         base::nullopt, contents_data_[index]->web_contents(), index);
2156   }
2157 
2158   // Update the group model.
2159   TabGroup* tab_group = group_model_->GetTabGroup(group.value());
2160   tab_group->RemoveTab();
2161   if (tab_group->IsEmpty())
2162     group_model_->RemoveTabGroup(group.value());
2163 
2164   return group;
2165 }
2166 
GroupTab(int index,const tab_groups::TabGroupId & group)2167 void TabStripModel::GroupTab(int index, const tab_groups::TabGroupId& group) {
2168   // Check for an old group first, so that any groups that are changed can be
2169   // notified appropriately.
2170   base::Optional<tab_groups::TabGroupId> old_group = GetTabGroupForTab(index);
2171   if (old_group.has_value()) {
2172     if (old_group.value() == group)
2173       return;
2174     else
2175       UngroupTab(index);
2176   }
2177   contents_data_[index]->set_group(group);
2178   for (auto& observer : observers_) {
2179     observer.TabGroupedStateChanged(
2180         group, contents_data_[index]->web_contents(), index);
2181   }
2182 
2183   group_model_->GetTabGroup(group)->AddTab();
2184 }
2185 
SetTabPinnedImpl(int index,bool pinned)2186 void TabStripModel::SetTabPinnedImpl(int index, bool pinned) {
2187   DCHECK(ContainsIndex(index));
2188   if (contents_data_[index]->pinned() == pinned)
2189     return;
2190 
2191   // Upgroup tabs if pinning -- the states should be mutually exclusive.
2192   if (pinned)
2193     UngroupTab(index);
2194 
2195   // The tab's position may have to change as the pinned tab state is changing.
2196   int non_pinned_tab_index = IndexOfFirstNonPinnedTab();
2197   contents_data_[index]->set_pinned(pinned);
2198   if (pinned && index != non_pinned_tab_index) {
2199     MoveWebContentsAtImpl(index, non_pinned_tab_index, false);
2200     index = non_pinned_tab_index;
2201   } else if (!pinned && index + 1 != non_pinned_tab_index) {
2202     MoveWebContentsAtImpl(index, non_pinned_tab_index - 1, false);
2203     index = non_pinned_tab_index - 1;
2204   }
2205 
2206   for (auto& observer : observers_) {
2207     observer.TabPinnedStateChanged(this, contents_data_[index]->web_contents(),
2208                                    index);
2209   }
2210 }
2211 
SetTabsPinned(const std::vector<int> & indices,bool pinned)2212 std::vector<int> TabStripModel::SetTabsPinned(const std::vector<int>& indices,
2213                                               bool pinned) {
2214   std::vector<int> new_indices;
2215   if (pinned) {
2216     for (size_t i = 0; i < indices.size(); i++) {
2217       if (IsTabPinned(indices[i])) {
2218         new_indices.push_back(indices[i]);
2219       } else {
2220         SetTabPinnedImpl(indices[i], true);
2221         new_indices.push_back(IndexOfFirstNonPinnedTab() - 1);
2222       }
2223     }
2224   } else {
2225     for (size_t i = indices.size() - 1; i < indices.size(); i--) {
2226       if (!IsTabPinned(indices[i])) {
2227         new_indices.push_back(indices[i]);
2228       } else {
2229         SetTabPinnedImpl(indices[i], false);
2230         new_indices.push_back(IndexOfFirstNonPinnedTab());
2231       }
2232     }
2233     std::reverse(new_indices.begin(), new_indices.end());
2234   }
2235   return new_indices;
2236 }
2237 
2238 // Sets the sound content setting for each site at the |indices|.
SetSitesMuted(const std::vector<int> & indices,bool mute) const2239 void TabStripModel::SetSitesMuted(const std::vector<int>& indices,
2240                                   bool mute) const {
2241   for (int tab_index : indices) {
2242     content::WebContents* web_contents = GetWebContentsAt(tab_index);
2243     GURL url = web_contents->GetLastCommittedURL();
2244     if (url.SchemeIs(content::kChromeUIScheme)) {
2245       // chrome:// URLs don't have content settings but can be muted, so just
2246       // mute the WebContents.
2247       chrome::SetTabAudioMuted(web_contents, mute,
2248                                TabMutedReason::CONTENT_SETTING_CHROME,
2249                                std::string());
2250     } else {
2251       Profile* profile =
2252           Profile::FromBrowserContext(web_contents->GetBrowserContext());
2253       HostContentSettingsMap* settings =
2254           HostContentSettingsMapFactory::GetForProfile(profile);
2255       ContentSetting setting =
2256           mute ? CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW;
2257       if (setting == settings->GetDefaultContentSetting(
2258                          ContentSettingsType::SOUND, nullptr)) {
2259         setting = CONTENT_SETTING_DEFAULT;
2260       }
2261       settings->SetContentSettingDefaultScope(
2262           url, url, ContentSettingsType::SOUND, setting);
2263     }
2264   }
2265 }
2266 
FixOpeners(int index)2267 void TabStripModel::FixOpeners(int index) {
2268   WebContents* old_contents = GetWebContentsAtImpl(index);
2269   WebContents* new_opener = GetOpenerOfWebContentsAt(index);
2270 
2271   for (auto& data : contents_data_) {
2272     if (data->opener() != old_contents)
2273       continue;
2274 
2275     // Ensure a tab isn't its own opener.
2276     data->set_opener(new_opener == data->web_contents() ? nullptr : new_opener);
2277   }
2278 
2279   // Sanity check that none of the tabs' openers refer |old_contents| or
2280   // themselves.
2281   DCHECK(!std::any_of(
2282       contents_data_.begin(), contents_data_.end(),
2283       [old_contents](const std::unique_ptr<WebContentsData>& data) {
2284         return data->opener() == old_contents ||
2285                data->opener() == data->web_contents();
2286       }));
2287 }
2288 
EnsureGroupContiguity(int index)2289 void TabStripModel::EnsureGroupContiguity(int index) {
2290   const auto old_group = GetTabGroupForTab(index);
2291   const auto new_left_group = GetTabGroupForTab(index - 1);
2292   const auto new_right_group = GetTabGroupForTab(index + 1);
2293   if (old_group != new_left_group && old_group != new_right_group) {
2294     if (new_left_group == new_right_group && new_left_group.has_value()) {
2295       // The tab is in the middle of an existing group, so add it to that group.
2296       GroupTab(index, new_left_group.value());
2297     } else if (old_group.has_value() &&
2298                group_model_->GetTabGroup(old_group.value())->ListTabs().size() >
2299                    1) {
2300       // The tab is between groups and its group is non-contiguous, so clear
2301       // this tab's group.
2302       UngroupTab(index);
2303     }
2304   }
2305 }
2306