scoped_visibility_tracker.cc 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2017 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. #include "ui/base/scoped_visibility_tracker.h"
  5. #include <utility>
  6. #include "base/time/tick_clock.h"
  7. namespace ui {
  8. ScopedVisibilityTracker::ScopedVisibilityTracker(
  9. const base::TickClock* tick_clock,
  10. bool is_shown)
  11. : tick_clock_(tick_clock) {
  12. DCHECK(tick_clock_);
  13. if (is_shown)
  14. OnShown();
  15. }
  16. ScopedVisibilityTracker::~ScopedVisibilityTracker() {}
  17. void ScopedVisibilityTracker::OnShown() {
  18. Update(true /* in_foreground */);
  19. }
  20. void ScopedVisibilityTracker::OnHidden() {
  21. Update(false /* in_foreground */);
  22. }
  23. base::TimeDelta ScopedVisibilityTracker::GetForegroundDuration() const {
  24. if (currently_in_foreground_)
  25. return foreground_duration_ + (tick_clock_->NowTicks() - last_time_shown_);
  26. return foreground_duration_;
  27. }
  28. void ScopedVisibilityTracker::Update(bool in_foreground) {
  29. base::TimeTicks now = tick_clock_->NowTicks();
  30. if (currently_in_foreground_)
  31. foreground_duration_ += now - last_time_shown_;
  32. if (in_foreground)
  33. last_time_shown_ = now;
  34. currently_in_foreground_ = in_foreground;
  35. }
  36. } // namespace ui