File: tab_declutter_controller.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (436 lines) | stat: -rw-r--r-- 14,856 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/tabs/organization/tab_declutter_controller.h"

#include <memory>
#include <optional>

#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/default_tick_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_source.h"
#include "chrome/browser/resource_coordinator/tab_manager.h"
#include "chrome/browser/resource_coordinator/time.h"
#include "chrome/browser/ui/browser_window/public/browser_window_interface.h"
#include "chrome/browser/ui/tabs/organization/trigger_policies.h"
#include "chrome/browser/ui/tabs/tab_enums.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/tab_search/tab_search.mojom.h"
#include "chrome/browser/ui/webui/tab_search/tab_search_prefs.h"
#include "components/prefs/pref_service.h"
#include "components/tabs/public/tab_interface.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "url/gurl.h"

namespace tabs {

namespace {
// Minimum number of duplicate tabs in the tabstrip that can be decluttered to
// show the nudge.
constexpr int kMinDeclutterableDuplicateTabCountForNudge = 3;
// Minimum number of inactive tabs in the tabstrip that can be decluttered to
// show the nudge.
constexpr int kMinTabCountForInactiveTabNudge = 15;
// Minimum percentage of stale tabs in the tabstrip to show the nudge.
constexpr double kStaleTabPercentageThreshold = 0.10;
}  // namespace

// static
void TabDeclutterController::EmitEntryPointHistogram(
    tab_search::mojom::TabDeclutterEntryPoint entry_point) {
  base::UmaHistogramEnumeration("Tab.Organization.Declutter.EntryPoint",
                                entry_point);
}

TabDeclutterController::TabDeclutterController(
    BrowserWindowInterface* browser_window_interface)
    : stale_tab_threshold_duration_(
          features::kTabstripDeclutterStaleThresholdDuration.Get()),
      declutter_timer_interval_(
          features::kTabstripDeclutterTimerInterval.Get()),
      nudge_timer_interval_(
          features::kTabstripDeclutterNudgeTimerInterval.Get()),
      declutter_timer_(std::make_unique<base::RepeatingTimer>()),
      usage_tick_clock_(std::make_unique<UsageTickClock>(
          base::DefaultTickClock::GetInstance())),
      next_nudge_valid_time_ticks_(usage_tick_clock_->NowTicks() +
                                   nudge_timer_interval_),
      tab_strip_model_(browser_window_interface->GetTabStripModel()),
      is_active_(false) {
  browser_subscriptions_.push_back(
      browser_window_interface->RegisterDidBecomeActive(base::BindRepeating(
          &TabDeclutterController::DidBecomeActive, base::Unretained(this))));
  browser_subscriptions_.push_back(
      browser_window_interface->RegisterDidBecomeInactive(base::BindRepeating(
          &TabDeclutterController::DidBecomeInactive, base::Unretained(this))));

  StartDeclutterTimer();
}

TabDeclutterController::~TabDeclutterController() = default;

void TabDeclutterController::StartDeclutterTimer() {
  declutter_timer_->Start(
      FROM_HERE, declutter_timer_interval_,
      base::BindRepeating(&TabDeclutterController::ProcessTabs,
                          base::Unretained(this)));
}

void TabDeclutterController::ProcessTabs() {
  std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs;

  if (features::IsTabstripDedupeEnabled()) {
    duplicate_tabs = GetDuplicateTabs();
  }

  std::vector<tabs::TabInterface*> stale_tabs = GetStaleTabs();

  for (auto& observer : observers_) {
    observer.OnUnusedTabsProcessed(stale_tabs, duplicate_tabs);
  }

  if (DeclutterNudgeCriteriaMet(stale_tabs, duplicate_tabs)) {
    next_nudge_valid_time_ticks_ =
        usage_tick_clock_->NowTicks() + nudge_timer_interval_;

    for (auto& observer : observers_) {
      observer.OnTriggerDeclutterUIVisibility();
    }

    tabs_previous_nudge_.clear();
    tabs_previous_nudge_.insert(stale_tabs.begin(), stale_tabs.end());

    for (const auto& [url, tabs] : duplicate_tabs) {
      tabs_previous_nudge_.insert(tabs.begin(), tabs.end());
    }
  }
}

std::map<GURL, std::vector<tabs::TabInterface*>>
TabDeclutterController::GetDuplicateTabs() {
  std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs;
  CHECK(features::IsTabstripDedupeEnabled());

  for (int tab_index = 0; tab_index < tab_strip_model_->GetTabCount();
       tab_index++) {
    tabs::TabInterface* tab = tab_strip_model_->GetTabAtIndex(tab_index);

    if (IsTabExcluded(tab)) {
      continue;
    }

    if (tab->IsPinned() || tab->GetGroup().has_value()) {
      continue;
    }

    GURL url = tab->GetContents()->GetLastCommittedURL().GetWithoutRef();

    if (!url.is_valid()) {
      continue;
    }

    if (duplicate_tabs.find(url) != duplicate_tabs.end()) {
      duplicate_tabs[url].push_back(tab);
    } else {
      duplicate_tabs[url] = std::vector<tabs::TabInterface*>{tab};
    }
  }

  // Filter out entries with only 1 unique GURL.
  for (auto it = duplicate_tabs.begin(); it != duplicate_tabs.end();) {
    if (it->second.size() <= 1) {
      it = duplicate_tabs.erase(it);
    } else {
      ++it;
    }
  }
  return duplicate_tabs;
}

std::vector<tabs::TabInterface*> TabDeclutterController::GetStaleTabs() {
  CHECK(features::IsTabstripDeclutterEnabled());
  std::vector<tabs::TabInterface*> tabs;

  const base::Time now = base::Time::Now();
  for (int tab_index = 0; tab_index < tab_strip_model_->GetTabCount();
       tab_index++) {
    tabs::TabInterface* tab = tab_strip_model_->GetTabAtIndex(tab_index);

    if (IsTabExcluded(tab)) {
      continue;
    }

    if (tab->IsPinned() || tab->GetGroup().has_value() ||
        tab->GetContents()->GetVisibility() == content::Visibility::VISIBLE) {
      continue;
    }

    auto* lifecycle_unit = resource_coordinator::TabLifecycleUnitSource::
        GetTabLifecycleUnitExternal(tab->GetContents());

    const base::Time last_focused_time = lifecycle_unit->GetLastFocusedTime();

    const base::TimeDelta elapsed = (last_focused_time == base::Time::Max())
                                        ? base::TimeDelta()
                                        : (now - last_focused_time);

    if (elapsed >= stale_tab_threshold_duration_) {
      tabs.push_back(tab);
    }
  }
  return tabs;
}

void TabDeclutterController::LogExcludedDuplicateTabMetrics() {
  int excluded_tab_count = 0;

  if (!excluded_urls_.empty()) {
    for (int index = 0; index < tab_strip_model_->GetTabCount(); index++) {
      if (excluded_urls_.contains(tab_strip_model_->GetTabAtIndex(index)
                                      ->GetContents()
                                      ->GetLastCommittedURL()
                                      .GetWithoutRef())) {
        excluded_tab_count++;
      }
    }
  }

  base::UmaHistogramCounts1000("Tab.Organization.Dedupe.ExcludedTabCount",
                               excluded_tab_count);
}

void TabDeclutterController::DeclutterTabs(
    std::vector<tabs::TabInterface*> tabs,
    const std::vector<GURL>& urls) {
  base::UmaHistogramCounts1000("Tab.Organization.Declutter.DeclutterTabCount",
                               tabs.size());
  base::UmaHistogramCounts1000("Tab.Organization.Declutter.TotalTabCount",
                               tab_strip_model_->count());
  base::UmaHistogramCounts1000("Tab.Organization.Declutter.ExcludedTabCount",
                               excluded_tabs_.size());

  LogExcludedDuplicateTabMetrics();

  PrefService* prefs =
      Profile::FromBrowserContext(tab_strip_model_->profile())->GetPrefs();

  int usage_count =
      prefs->GetInteger(tab_search_prefs::kTabDeclutterUsageCount);
  prefs->SetInteger(tab_search_prefs::kTabDeclutterUsageCount, ++usage_count);

  base::UmaHistogramCounts1000("Tab.Organization.Declutter.TotalUsageCount",
                               usage_count);

  for (tabs::TabInterface* tab : tabs) {
    if (tab_strip_model_->GetIndexOfTab(tab) == TabStripModel::kNoTab) {
      continue;
    }

    tab_strip_model_->CloseWebContentsAt(
        tab_strip_model_->GetIndexOfWebContents(tab->GetContents()),
        TabCloseTypes::CLOSE_CREATE_HISTORICAL_TAB);
  }

  int duplicate_tabs_decluttered = 0;
  for (const GURL& url : urls) {
    // Sort the tabs with `url` based on the last committed navigation time and
    // close all the tabs except the oldest tab.
    std::vector<std::pair<tabs::TabInterface*, base::Time>> url_matching_tabs;

    for (int tab_index = 0; tab_index < tab_strip_model_->GetTabCount();
         ++tab_index) {
      tabs::TabInterface* tab = tab_strip_model_->GetTabAtIndex(tab_index);

      if (tab->GetContents()->GetLastCommittedURL().GetWithoutRef() != url) {
        continue;
      }

      // It is possible that the timestamp is not present. Prefer to delete this
      // as a duplicate in that case. This can be due to
      //   - The navigation was restored and for some reason the
      //     timestamp wasn't available;
      //   - or the navigation was copied from a foreign session.
      auto* last_entry =
          tab->GetContents()->GetController().GetLastCommittedEntry();
      base::Time last_committed_time = last_entry->GetTimestamp().is_null()
                                           ? base::Time::Max()
                                           : last_entry->GetTimestamp();

      url_matching_tabs.emplace_back(tab, last_committed_time);
    }

    std::sort(url_matching_tabs.begin(), url_matching_tabs.end(),
              [](const std::pair<tabs::TabInterface*, base::Time>& a,
                 const std::pair<tabs::TabInterface*, base::Time>& b) {
                return a.second < b.second;
              });

    // Close all the tabs except the first tab which will be the oldest
    // duplicate tab.
    for (size_t i = 1; i < url_matching_tabs.size(); ++i) {
      tabs::TabInterface* tab = url_matching_tabs[i].first;
      tab_strip_model_->CloseWebContentsAt(
          tab_strip_model_->GetIndexOfWebContents(tab->GetContents()),
          TabCloseTypes::CLOSE_CREATE_HISTORICAL_TAB);
      duplicate_tabs_decluttered++;
    }
  }

  base::UmaHistogramCounts1000("Tab.Organization.Dedupe.DeclutterTabCount",
                               duplicate_tabs_decluttered);

  excluded_tabs_.clear();
  excluded_urls_.clear();
}

void TabDeclutterController::DidBecomeActive(BrowserWindowInterface* browser) {
  is_active_ = true;
}

void TabDeclutterController::DidBecomeInactive(
    BrowserWindowInterface* browser) {
  is_active_ = false;
}

void TabDeclutterController::ExcludeFromStaleTabs(tabs::TabInterface* tab) {
  if (tab_strip_model_->GetIndexOfTab(tab) == TabStripModel::kNoTab) {
    return;
  }

  excluded_tabs_.insert(tab);
}

void TabDeclutterController::ExcludeFromDuplicateTabs(GURL url) {
  if (!url.is_valid()) {
    return;
  }

  excluded_urls_.insert(url.GetWithoutRef());
}

bool TabDeclutterController::DeclutterNudgeCriteriaMet(
    base::span<tabs::TabInterface*> stale_tabs,
    std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs) {
  if (!is_active_ ||
      (usage_tick_clock_->NowTicks() < next_nudge_valid_time_ticks_)) {
    return false;
  }

  return HasNewUnusedTabsForNudge(stale_tabs, duplicate_tabs) &&
         (DeclutterStaleTabsNudgeCriteriaMet(stale_tabs) ||
          DeclutterDuplicateTabsNudgeCriteriaMet(duplicate_tabs));
}

bool TabDeclutterController::IsTabExcluded(tabs::TabInterface* tab) const {
  if (excluded_tabs_.find(tab) != excluded_tabs_.end()) {
    return true;
  }

  GURL url = tab->GetContents()->GetLastCommittedURL().GetWithoutRef();
  if (excluded_urls_.find(url) != excluded_urls_.end()) {
    return true;
  }

  return false;
}

bool TabDeclutterController::HasNewUnusedTabsForNudge(
    base::span<tabs::TabInterface*> stale_tabs,
    std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs) const {
  // Check for new unused stale tabs.
  if (IsNewTabDetectedForNudge(stale_tabs)) {
    return true;
  }

  // Check for new unused duplicate tabs.
  for (auto& [url, tabs] : duplicate_tabs) {
    if (IsNewTabDetectedForNudge(base::span(tabs))) {
      return true;
    }
  }

  return false;
}

bool TabDeclutterController::IsNewTabDetectedForNudge(
    base::span<tabs::TabInterface*> tabs) const {
  for (tabs::TabInterface* tab : tabs) {
    if (tabs_previous_nudge_.count(tab) == 0) {
      return true;
    }
  }
  return false;
}

bool TabDeclutterController::DeclutterStaleTabsNudgeCriteriaMet(
    base::span<tabs::TabInterface*> stale_tabs) {
  if (stale_tabs.empty()) {
    return false;
  }

  const int total_tab_count = tab_strip_model_->GetTabCount();

  if (total_tab_count < kMinTabCountForInactiveTabNudge) {
    return false;
  }

  const int required_stale_tabs = static_cast<int>(
      std::ceil(total_tab_count * kStaleTabPercentageThreshold));

  if (static_cast<int>(stale_tabs.size()) < required_stale_tabs) {
    return false;
  }

  return true;
}

bool TabDeclutterController::DeclutterDuplicateTabsNudgeCriteriaMet(
    std::map<GURL, std::vector<tabs::TabInterface*>> duplicate_tabs) {
  int declutterable_duplicate_tabs = 0;
  for (const auto& [url, tabs] : duplicate_tabs) {
    // The original duplicate tab is not declutterable.
    declutterable_duplicate_tabs += tabs.size() - 1;
  }

  return declutterable_duplicate_tabs >=
         kMinDeclutterableDuplicateTabCountForNudge;
}

void TabDeclutterController::ResetAndDoubleNudgeTimer() {
  nudge_timer_interval_ = nudge_timer_interval_ * 2;
  next_nudge_valid_time_ticks_ =
      usage_tick_clock_->NowTicks() + nudge_timer_interval_;
}
void TabDeclutterController::OnActionUIDismissed(
    base::PassKey<TabSearchContainer>) {
  ResetAndDoubleNudgeTimer();
}

void TabDeclutterController::OnActionUIDismissed(
    base::PassKey<TabStripActionContainer>) {
  ResetAndDoubleNudgeTimer();
}

void TabDeclutterController::SetTimerForTesting(
    const base::TickClock* tick_clock,
    scoped_refptr<base::SequencedTaskRunner> task_runner) {
  declutter_timer_->Stop();
  declutter_timer_ = std::make_unique<base::RepeatingTimer>(tick_clock);
  declutter_timer_->SetTaskRunner(task_runner);
  StartDeclutterTimer();

  usage_tick_clock_.reset();
  usage_tick_clock_ = std::make_unique<UsageTickClock>(tick_clock);
  next_nudge_valid_time_ticks_ =
      usage_tick_clock_->NowTicks() + nudge_timer_interval_;
}
}  // namespace tabs