license.bot | f003cfe | 2008-08-24 09:55:55 +0900 | [diff] [blame^] | 1 | // Copyright (c) 2006-2008 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. |
initial.commit | 3f4a732 | 2008-07-27 06:49:38 +0900 | [diff] [blame] | 4 | |
| 5 | #include <windows.h> |
| 6 | |
| 7 | #include "base/idle_timer.h" |
| 8 | |
| 9 | #include "base/message_loop.h" |
| 10 | #include "base/time.h" |
| 11 | |
| 12 | IdleTimerTask::IdleTimerTask(TimeDelta idle_time, bool repeat) |
| 13 | : idle_interval_(idle_time), |
| 14 | repeat_(repeat), |
| 15 | get_last_input_info_fn_(GetLastInputInfo) { |
| 16 | } |
| 17 | |
| 18 | IdleTimerTask::~IdleTimerTask() { |
| 19 | Stop(); |
| 20 | } |
| 21 | |
| 22 | void IdleTimerTask::Start() { |
| 23 | DCHECK(!timer_.get()); |
| 24 | StartTimer(); |
| 25 | } |
| 26 | |
| 27 | void IdleTimerTask::Stop() { |
| 28 | timer_.reset(); |
| 29 | } |
| 30 | |
| 31 | void IdleTimerTask::Run() { |
| 32 | // Verify we can fire the idle timer. |
| 33 | if (TimeUntilIdle().InMilliseconds() <= 0) { |
| 34 | OnIdle(); |
| 35 | last_time_fired_ = Time::Now(); |
| 36 | } |
| 37 | Stop(); |
| 38 | StartTimer(); // Restart the timer for next run. |
| 39 | } |
| 40 | |
| 41 | void IdleTimerTask::StartTimer() { |
| 42 | DCHECK(timer_ == NULL); |
| 43 | TimeDelta delay = TimeUntilIdle(); |
| 44 | if (delay.InMilliseconds() < 0) |
| 45 | delay = TimeDelta(); |
| 46 | timer_.reset(new OneShotTimer(delay)); |
| 47 | timer_->set_unowned_task(this); |
| 48 | timer_->Start(); |
| 49 | } |
| 50 | |
| 51 | TimeDelta IdleTimerTask::CurrentIdleTime() { |
| 52 | // TODO(mbelshe): This is windows-specific code. |
| 53 | LASTINPUTINFO info; |
| 54 | info.cbSize = sizeof(info); |
| 55 | if (get_last_input_info_fn_(&info)) { |
| 56 | // Note: GetLastInputInfo returns a 32bit value which rolls over ~49days. |
| 57 | int32 last_input_time = info.dwTime; |
| 58 | int32 current_time = GetTickCount(); |
| 59 | int32 interval = current_time - last_input_time; |
| 60 | // Interval will go negative if we've been idle for 2GB of ticks. |
| 61 | if (interval < 0) |
| 62 | interval = -interval; |
| 63 | return TimeDelta::FromMilliseconds(interval); |
| 64 | } |
| 65 | NOTREACHED(); |
| 66 | return TimeDelta::FromMilliseconds(0); |
| 67 | } |
| 68 | |
| 69 | TimeDelta IdleTimerTask::TimeUntilIdle() { |
| 70 | TimeDelta time_since_last_fire = Time::Now() - last_time_fired_; |
| 71 | TimeDelta current_idle_time = CurrentIdleTime(); |
| 72 | if (current_idle_time > time_since_last_fire) { |
| 73 | if (repeat_) |
| 74 | return idle_interval_ - time_since_last_fire; |
| 75 | return idle_interval_; |
| 76 | } |
| 77 | return idle_interval_ - current_idle_time; |
| 78 | } |
license.bot | f003cfe | 2008-08-24 09:55:55 +0900 | [diff] [blame^] | 79 | |