1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_VISIBILITY_TIMER_TAB_HELPER_H_
6 #define CHROME_BROWSER_VISIBILITY_TIMER_TAB_HELPER_H_
8 #include "base/containers/circular_deque.h"
9 #include "base/functional/callback_forward.h"
10 #include "base/timer/timer.h"
11 #include "content/public/browser/web_contents_observer.h"
12 #include "content/public/browser/web_contents_user_data.h"
14 // At most one of these is attached to each WebContents. It allows posting
15 // delayed tasks whose timer only counts down whilst the WebContents is visible
16 // (and whose timer is reset whenever the WebContents stops being visible).
17 // If multiple tasks are added, they are queued in a dormant state -- their
18 // timer will not elapse until earlier tasks are completed.
19 class VisibilityTimerTabHelper
20 : public content::WebContentsObserver,
21 public content::WebContentsUserData<VisibilityTimerTabHelper> {
23 VisibilityTimerTabHelper(const VisibilityTimerTabHelper&&) = delete;
24 VisibilityTimerTabHelper& operator=(const VisibilityTimerTabHelper&&) =
27 ~VisibilityTimerTabHelper() override;
29 // Runs |task| after the WebContents has been visible for a consecutive
30 // duration of at least |visible_delay|.
31 void PostTaskAfterVisibleDelay(const base::Location& from_here,
32 base::OnceClosure task,
33 base::TimeDelta visible_delay);
35 // WebContentsObserver:
36 void OnVisibilityChanged(content::Visibility visibility) override;
40 friend class content::WebContentsUserData<VisibilityTimerTabHelper>;
41 explicit VisibilityTimerTabHelper(content::WebContents* contents);
43 void RunTask(base::OnceClosure task);
44 void StartNextTaskTimer();
46 base::OneShotTimer timer_;
47 base::circular_deque<Task> task_queue_;
49 WEB_CONTENTS_USER_DATA_KEY_DECL();
52 #endif // CHROME_BROWSER_VISIBILITY_TIMER_TAB_HELPER_H_