Reilly Grant | 0e21968 | 2020-09-16 21:05:31 | [diff] [blame] | 1 | // 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 | |
| 8 | #include <memory> |
| 9 | |
| 10 | #include "base/containers/circular_deque.h" |
| 11 | #include "content/public/browser/web_contents_observer.h" |
| 12 | #include "content/public/browser/web_contents_user_data.h" |
| 13 | |
| 14 | namespace base { |
| 15 | class RetainingOneShotTimer; |
| 16 | } |
| 17 | |
| 18 | // At most one of these is attached to each WebContents. It allows posting |
| 19 | // delayed tasks whose timer only counts down whilst the WebContents is visible |
| 20 | // (and whose timer is reset whenever the WebContents stops being visible). |
| 21 | class VisibilityTimerTabHelper |
| 22 | : public content::WebContentsObserver, |
| 23 | public content::WebContentsUserData<VisibilityTimerTabHelper> { |
| 24 | public: |
| 25 | VisibilityTimerTabHelper(const VisibilityTimerTabHelper&&) = delete; |
| 26 | VisibilityTimerTabHelper& operator=(const VisibilityTimerTabHelper&&) = |
| 27 | delete; |
| 28 | |
| 29 | ~VisibilityTimerTabHelper() override; |
| 30 | |
| 31 | // Runs |task| after the WebContents has been visible for a consecutive |
| 32 | // duration of at least |visible_delay|. |
| 33 | void PostTaskAfterVisibleDelay(const base::Location& from_here, |
| 34 | base::OnceClosure task, |
| 35 | base::TimeDelta visible_delay); |
| 36 | |
| 37 | // WebContentsObserver: |
| 38 | void OnVisibilityChanged(content::Visibility visibility) override; |
| 39 | |
| 40 | private: |
| 41 | friend class content::WebContentsUserData<VisibilityTimerTabHelper>; |
| 42 | explicit VisibilityTimerTabHelper(content::WebContents* contents); |
| 43 | |
| 44 | void RunTask(base::OnceClosure task); |
| 45 | |
| 46 | base::circular_deque<std::unique_ptr<base::RetainingOneShotTimer>> |
| 47 | task_queue_; |
| 48 | |
| 49 | WEB_CONTENTS_USER_DATA_KEY_DECL(); |
| 50 | }; |
| 51 | |
| 52 | #endif // CHROME_BROWSER_VISIBILITY_TIMER_TAB_HELPER_H_ |