File: tab_lifecycle_unit_source.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 (370 lines) | stat: -rw-r--r-- 13,948 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
// Copyright 2017 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/resource_coordinator/tab_lifecycle_unit_source.h"

#include <utility>

#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/resource_coordinator/discard_metrics_lifecycle_unit_observer.h"
#include "chrome/browser/resource_coordinator/lifecycle_unit_source_observer.h"
#include "chrome/browser/resource_coordinator/resource_coordinator_parts.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit.h"
#include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h"
#include "chrome/browser/resource_coordinator/tab_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/recently_audible_helper.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/pref_names.h"
#include "components/performance_manager/public/graph/graph.h"
#include "components/performance_manager/public/graph/page_node.h"
#include "components/performance_manager/public/performance_manager.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_user_data.h"

namespace resource_coordinator {

// Allows storage of a TabLifecycleUnit on a WebContents.
class TabLifecycleUnitSource::TabLifecycleUnitHolder
    : public content::WebContentsUserData<
          TabLifecycleUnitSource::TabLifecycleUnitHolder> {
 public:
  TabLifecycleUnitHolder(const TabLifecycleUnitHolder&) = delete;
  TabLifecycleUnitHolder& operator=(const TabLifecycleUnitHolder&) = delete;

  ~TabLifecycleUnitHolder() override = default;

  TabLifecycleUnit* lifecycle_unit() const { return lifecycle_unit_.get(); }
  void set_lifecycle_unit(std::unique_ptr<TabLifecycleUnit> lifecycle_unit) {
    lifecycle_unit_ = std::move(lifecycle_unit);
  }
  std::unique_ptr<TabLifecycleUnit> TakeTabLifecycleUnit() {
    return std::move(lifecycle_unit_);
  }

 private:
  friend class content::WebContentsUserData<TabLifecycleUnitHolder>;

  explicit TabLifecycleUnitHolder(content::WebContents* web_contents)
      : content::WebContentsUserData<
            TabLifecycleUnitSource::TabLifecycleUnitHolder>(*web_contents) {}

  std::unique_ptr<TabLifecycleUnit> lifecycle_unit_;
  WEB_CONTENTS_USER_DATA_KEY_DECL();
};

WEB_CONTENTS_USER_DATA_KEY_IMPL(TabLifecycleUnitSource::TabLifecycleUnitHolder);

// A very simple graph observer that forwards events over to the
// TabLifecycleUnitSource on the UI thread. This is created on the UI thread
// and ownership passed to the performance manager.
class TabLifecycleStateObserver : public performance_manager::PageNodeObserver,
                                  public performance_manager::GraphOwned {
 public:
  using Graph = performance_manager::Graph;
  using PageNode = performance_manager::PageNode;

  TabLifecycleStateObserver() = default;

  TabLifecycleStateObserver(const TabLifecycleStateObserver&) = delete;
  TabLifecycleStateObserver& operator=(const TabLifecycleStateObserver&) =
      delete;

  ~TabLifecycleStateObserver() override = default;

 private:
  static void OnLifecycleStateChangedImpl(
      base::WeakPtr<content::WebContents> contents,
      performance_manager::mojom::LifecycleState state) {
    DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
    // If the web contents is still alive then dispatch to the actual
    // implementation in TabLifecycleUnitSource.
    if (contents) {
      TabLifecycleUnitSource::OnLifecycleStateChanged(contents.get(), state);
    }
  }

  // PageNodeObserver:
  void OnPageLifecycleStateChanged(const PageNode* page_node) override {
    // Forward the notification over to the UI thread.
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE,
        base::BindOnce(&TabLifecycleStateObserver::OnLifecycleStateChangedImpl,
                       page_node->GetWebContents(),
                       page_node->GetLifecycleState()));
  }

  void OnPassedToGraph(Graph* graph) override {
    graph->AddPageNodeObserver(this);
  }

  void OnTakenFromGraph(Graph* graph) override {
    graph->RemovePageNodeObserver(this);
  }
};

TabLifecycleUnitSource::TabLifecycleUnitSource()
    : browser_tab_strip_tracker_(this, nullptr) {
  // In unit tests, tabs might already exist when TabLifecycleUnitSource is
  // instantiated. No TabLifecycleUnit is created for these tabs.

  BrowserList::AddObserver(this);
  browser_tab_strip_tracker_.Init();
}

TabLifecycleUnitSource::~TabLifecycleUnitSource() {
  BrowserList::RemoveObserver(this);
}

void TabLifecycleUnitSource::Start() {
  // TODO(sebmarchand): Remove the "IsAvailable" check, or merge the TM into the
  // PM. The TM and PM must always exist together.
  if (performance_manager::PerformanceManager::IsAvailable()) {
    performance_manager::PerformanceManager::GetGraph()->PassToGraph(
        std::make_unique<TabLifecycleStateObserver>());
  }
}

// static
TabLifecycleUnitExternal* TabLifecycleUnitSource::GetTabLifecycleUnitExternal(
    content::WebContents* web_contents) {
  auto* lu = GetTabLifecycleUnit(web_contents);
  if (!lu) {
    return nullptr;
  }
  return lu->AsTabLifecycleUnitExternal();
}

void TabLifecycleUnitSource::AddLifecycleObserver(
    LifecycleUnitObserver* observer) {
  lifecycle_unit_observers_.AddObserver(observer);
}

void TabLifecycleUnitSource::RemoveLifecycleObserver(
    LifecycleUnitObserver* observer) {
  lifecycle_unit_observers_.RemoveObserver(observer);
}

void TabLifecycleUnitSource::SetFocusedTabStripModelForTesting(
    TabStripModel* tab_strip) {
  focused_tab_strip_model_for_testing_ = tab_strip;
  UpdateFocusedTab();
}

void TabLifecycleUnitSource::SetMemoryLimitEnterprisePolicyFlag(bool enabled) {
  memory_limit_enterprise_policy_ = enabled;
}

// static
TabLifecycleUnitSource::TabLifecycleUnit*
TabLifecycleUnitSource::GetTabLifecycleUnit(
    content::WebContents* web_contents) {
  auto* holder = TabLifecycleUnitHolder::FromWebContents(web_contents);
  if (holder)
    return holder->lifecycle_unit();
  return nullptr;
}

TabStripModel* TabLifecycleUnitSource::GetFocusedTabStripModel() const {
  if (focused_tab_strip_model_for_testing_)
    return focused_tab_strip_model_for_testing_;
  Browser* const focused_browser = chrome::FindBrowserWithActiveWindow();
  if (!focused_browser)
    return nullptr;
  return focused_browser->tab_strip_model();
}

void TabLifecycleUnitSource::UpdateFocusedTab(Browser* browser) {
  TabStripModel* const focused_tab_strip_model =
      browser ? browser->tab_strip_model() : GetFocusedTabStripModel();
  content::WebContents* const focused_web_contents =
      focused_tab_strip_model ? focused_tab_strip_model->GetActiveWebContents()
                              : nullptr;
  TabLifecycleUnit* focused_lifecycle_unit =
      focused_web_contents ? GetTabLifecycleUnit(focused_web_contents)
                           : nullptr;

  // TODO(sangwoo.ko) We are refactoring TabStripModel API and this is
  // workaround to avoid DCHECK failure on Chromium os. This DCHECK is supposing
  // that OnTabInserted() is always called before OnBrowserSetLastActive is
  // called but it's not. After replacing old API use in BrowserView,
  // restore this to DCHECK(!focused_web_contents || focused_lifecycle_unit);
  // else case will be handled by following OnTabInserted().
  if (!focused_web_contents || focused_lifecycle_unit)
    UpdateFocusedTabTo(focused_lifecycle_unit);
}

void TabLifecycleUnitSource::UpdateFocusedTabTo(
    TabLifecycleUnit* new_focused_lifecycle_unit) {
  if (new_focused_lifecycle_unit == focused_lifecycle_unit_) {
    return;
  }
  if (focused_lifecycle_unit_) {
    focused_lifecycle_unit_->SetFocused(false);
  }
  if (new_focused_lifecycle_unit) {
    new_focused_lifecycle_unit->SetFocused(true);
  }
  focused_lifecycle_unit_ = new_focused_lifecycle_unit;
}

void TabLifecycleUnitSource::OnTabInserted(TabStripModel* tab_strip_model,
                                           content::WebContents* contents,
                                           bool foreground) {
  TabLifecycleUnit* lifecycle_unit = GetTabLifecycleUnit(contents);
  if (lifecycle_unit) {
    // An existing tab was moved to a new window.
    lifecycle_unit->SetTabStripModel(tab_strip_model);
    if (foreground)
      UpdateFocusedTab();
  } else {
    // A tab was created.
    TabLifecycleUnitHolder::CreateForWebContents(contents);
    auto* holder = TabLifecycleUnitHolder::FromWebContents(contents);
    holder->set_lifecycle_unit(
        std::make_unique<TabLifecycleUnit>(this, contents, tab_strip_model));
    lifecycle_unit = holder->lifecycle_unit();
    lifecycle_unit_observations_.AddObservation(lifecycle_unit);
    if (GetFocusedTabStripModel() == tab_strip_model && foreground) {
      UpdateFocusedTabTo(lifecycle_unit);
    }

    // Add a self-owned observers to record metrics and trace events.
    lifecycle_unit->AddObserver(new DiscardMetricsLifecycleUnitObserver());

    NotifyLifecycleUnitCreated(lifecycle_unit);
  }
}

void TabLifecycleUnitSource::OnTabDetached(content::WebContents* contents) {
  TabLifecycleUnit* lifecycle_unit = GetTabLifecycleUnit(contents);
  DCHECK(lifecycle_unit);
  if (focused_lifecycle_unit_ == lifecycle_unit)
    UpdateFocusedTabTo(nullptr);
  lifecycle_unit->SetTabStripModel(nullptr);
}

void TabLifecycleUnitSource::OnTabReplaced(content::WebContents* old_contents,
                                           content::WebContents* new_contents) {
  auto* old_contents_holder =
      TabLifecycleUnitHolder::FromWebContents(old_contents);
  DCHECK(old_contents_holder);
  DCHECK(old_contents_holder->lifecycle_unit());
  TabLifecycleUnitHolder::CreateForWebContents(new_contents);
  auto* new_contents_holder =
      TabLifecycleUnitHolder::FromWebContents(new_contents);
  DCHECK(new_contents_holder);
  DCHECK(!new_contents_holder->lifecycle_unit());
  new_contents_holder->set_lifecycle_unit(
      old_contents_holder->TakeTabLifecycleUnit());
  new_contents_holder->lifecycle_unit()->SetWebContents(new_contents);
}

void TabLifecycleUnitSource::OnTabStripModelChanged(
    TabStripModel* tab_strip_model,
    const TabStripModelChange& change,
    const TabStripSelectionChange& selection) {
  switch (change.type()) {
    case TabStripModelChange::kInserted: {
      for (const auto& contents : change.GetInsert()->contents) {
        OnTabInserted(tab_strip_model, contents.contents,
                      selection.new_contents == contents.contents);
      }
      break;
    }
    case TabStripModelChange::kRemoved: {
      for (const auto& contents : change.GetRemove()->contents)
        OnTabDetached(contents.contents);
      break;
    }
    case TabStripModelChange::kReplaced: {
      auto* replace = change.GetReplace();
      OnTabReplaced(replace->old_contents, replace->new_contents);
      break;
    }
    case TabStripModelChange::kMoved:
    case TabStripModelChange::kSelectionOnly:
      break;
  }

  if (selection.active_tab_changed() && !tab_strip_model->empty()) {
    UpdateFocusedTab();
  }
}

void TabLifecycleUnitSource::TabChangedAt(content::WebContents* contents,
                                          int index,
                                          TabChangeType change_type) {
  if (change_type != TabChangeType::kAll)
    return;
  TabLifecycleUnit* lifecycle_unit = GetTabLifecycleUnit(contents);
  // This can be called before OnTabStripModelChanged() and |lifecycle_unit|
  // will be null in that case. http://crbug.com/877940
  if (!lifecycle_unit)
    return;

  auto* audible_helper = RecentlyAudibleHelper::FromWebContents(contents);
  lifecycle_unit->SetRecentlyAudible(audible_helper->WasRecentlyAudible());
}


void TabLifecycleUnitSource::OnBrowserRemoved(Browser* browser) {
  // An active browser may be removed without OnBrowserNoLongerActive() being
  // invoked. crbug.com/1206458
  UpdateFocusedTab();
}

void TabLifecycleUnitSource::OnBrowserSetLastActive(Browser* browser) {
  // In this case, we know that `browser` is active. Pass it directly into
  // `UpdateFocusedTab` since during startup
  // `chrome::FindBrowserWithActiveWindow()` sometimes fails to return the
  // proper browser.
  UpdateFocusedTab(browser);
}

void TabLifecycleUnitSource::OnBrowserNoLongerActive(Browser* browser) {
  UpdateFocusedTab();
}

void TabLifecycleUnitSource::OnLifecycleUnitStateChanged(
    LifecycleUnit* lifecycle_unit,
    LifecycleUnitState last_state,
    LifecycleUnitStateChangeReason reason) {
  lifecycle_unit_observers_.Notify(
      &LifecycleUnitObserver::OnLifecycleUnitStateChanged, lifecycle_unit,
      last_state, reason);
}

void TabLifecycleUnitSource::OnLifecycleUnitDestroyed(
    LifecycleUnit* lifecycle_unit) {
  lifecycle_unit_observers_.Notify(
      &LifecycleUnitObserver::OnLifecycleUnitDestroyed, lifecycle_unit);
  lifecycle_unit_observations_.RemoveObservation(lifecycle_unit);
}

// static
void TabLifecycleUnitSource::OnLifecycleStateChanged(
    content::WebContents* web_contents,
    performance_manager::mojom::LifecycleState state) {
  TabLifecycleUnit* lifecycle_unit = GetTabLifecycleUnit(web_contents);

  // Lifecycle state is updated independently from navigations. Therefore, there
  // is no need to filter out the event if it was generated before the last
  // navigation.
  if (lifecycle_unit)
    lifecycle_unit->UpdateLifecycleState(state);
}

}  // namespace resource_coordinator