blob: cb112668bdd5f13c894ac0c5bd3c2ecfab4020eb [file] [log] [blame]
Reilly Grant0e219682020-09-16 21:05:311// Copyright 2020 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#ifndef CHROME_BROWSER_VISIBILITY_TIMER_TAB_HELPER_H_
6#define CHROME_BROWSER_VISIBILITY_TIMER_TAB_HELPER_H_
7
Dan Harrington92ddbc22021-06-04 17:22:498#include "base/callback_forward.h"
Reilly Grant0e219682020-09-16 21:05:319#include "base/containers/circular_deque.h"
Dan Harrington92ddbc22021-06-04 17:22:4910#include "base/timer/timer.h"
Reilly Grant0e219682020-09-16 21:05:3111#include "content/public/browser/web_contents_observer.h"
12#include "content/public/browser/web_contents_user_data.h"
13
Reilly Grant0e219682020-09-16 21:05:3114// 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).
Dan Harrington92ddbc22021-06-04 17:22:4917// If multiple tasks are added, they are queued in a dormant state -- their
18// timer will not elapse until earlier tasks are completed.
Reilly Grant0e219682020-09-16 21:05:3119class VisibilityTimerTabHelper
20 : public content::WebContentsObserver,
21 public content::WebContentsUserData<VisibilityTimerTabHelper> {
22 public:
23 VisibilityTimerTabHelper(const VisibilityTimerTabHelper&&) = delete;
24 VisibilityTimerTabHelper& operator=(const VisibilityTimerTabHelper&&) =
25 delete;
26
27 ~VisibilityTimerTabHelper() override;
28
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);
34
35 // WebContentsObserver:
36 void OnVisibilityChanged(content::Visibility visibility) override;
37
38 private:
Dan Harrington92ddbc22021-06-04 17:22:4939 struct Task;
Reilly Grant0e219682020-09-16 21:05:3140 friend class content::WebContentsUserData<VisibilityTimerTabHelper>;
41 explicit VisibilityTimerTabHelper(content::WebContents* contents);
42
43 void RunTask(base::OnceClosure task);
Dan Harrington92ddbc22021-06-04 17:22:4944 void StartNextTaskTimer();
Reilly Grant0e219682020-09-16 21:05:3145
Dan Harrington92ddbc22021-06-04 17:22:4946 base::OneShotTimer timer_;
47 base::circular_deque<Task> task_queue_;
Reilly Grant0e219682020-09-16 21:05:3148
49 WEB_CONTENTS_USER_DATA_KEY_DECL();
50};
51
52#endif // CHROME_BROWSER_VISIBILITY_TIMER_TAB_HELPER_H_