diff options
author | darin@google.com <darin@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2008-09-03 18:18:14 +0000 |
---|---|---|
committer | darin@google.com <darin@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2008-09-03 18:18:14 +0000 |
commit | 2d31666a58e746b7a1d415c99e5f68ad9256d236 (patch) | |
tree | 144c99d4b80df0f0f9a3ded83f9d21a8b36f17cc | |
parent | 90d6958fe2374a00d3c8583cf4d3b8a509ae8e90 (diff) | |
download | chromium_src-2d31666a58e746b7a1d415c99e5f68ad9256d236.zip chromium_src-2d31666a58e746b7a1d415c99e5f68ad9256d236.tar.gz chromium_src-2d31666a58e746b7a1d415c99e5f68ad9256d236.tar.bz2 |
Minor cleanup to OneShotTimer and RepeatingTimer: moves more of the member variables into the Task subclass.
Also included in this change: deprecate MessageLoop::timer_manager(), and change consumers over to use OneShotTimer or RepeatingTimer.
R=beng
BUG=1346553
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@1684 0039d316-1c4b-4281-b951-d872f2087c98
37 files changed, 329 insertions, 620 deletions
diff --git a/base/idletimer_unittest.cc b/base/idletimer_unittest.cc index 1e2baa9..dab445e 100644 --- a/base/idletimer_unittest.cc +++ b/base/idletimer_unittest.cc @@ -46,7 +46,7 @@ class TestIdleTask : public IdleTimer { }; // A task to help us quit the test. -class TestFinishedTask : public Task { +class TestFinishedTask { public: TestFinishedTask() {} void Run() { @@ -55,7 +55,7 @@ class TestFinishedTask : public Task { }; // A timer which resets the idle clock. -class ResetIdleTask : public Task { +class ResetIdleTask { public: ResetIdleTask() {} void Run() { @@ -77,14 +77,15 @@ TEST_F(IdleTimerTest, NoRepeatIdle) { mock_idle_time = GetTickCount(); TestIdleTask test_task(false); + TestFinishedTask finish_task; - MessageLoop* loop = MessageLoop::current(); - Timer* t = loop->timer_manager()->StartTimer(1000, &finish_task, false); + base::OneShotTimer<TestFinishedTask> timer; + timer.Start(TimeDelta::FromSeconds(1), &finish_task, &TestFinishedTask::Run); + test_task.Start(); - loop->Run(); + MessageLoop::current()->Run(); EXPECT_EQ(test_task.get_idle_counter(), 1); - delete t; } TEST_F(IdleTimerTest, NoRepeatFlipIdleOnce) { @@ -95,17 +96,22 @@ TEST_F(IdleTimerTest, NoRepeatFlipIdleOnce) { mock_idle_time = GetTickCount(); TestIdleTask test_task(false); + TestFinishedTask finish_task; ResetIdleTask reset_task; - MessageLoop* loop = MessageLoop::current(); - Timer* t1 = loop->timer_manager()->StartTimer(1000, &finish_task, false); - Timer* t2 = loop->timer_manager()->StartTimer(500, &reset_task, false); + + base::OneShotTimer<TestFinishedTask> t1; + t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task, + &TestFinishedTask::Run); + + base::OneShotTimer<ResetIdleTask> t2; + t2.Start(TimeDelta::FromMilliseconds(500), &reset_task, + &ResetIdleTask::Run); + test_task.Start(); - loop->Run(); + MessageLoop::current()->Run(); EXPECT_EQ(test_task.get_idle_counter(), 2); - delete t1; - delete t2; } TEST_F(IdleTimerTest, NoRepeatNotIdle) { @@ -116,18 +122,25 @@ TEST_F(IdleTimerTest, NoRepeatNotIdle) { mock_idle_time = GetTickCount(); TestIdleTask test_task(false); + TestFinishedTask finish_task; ResetIdleTask reset_task; - MessageLoop* loop = MessageLoop::current(); - Timer* t = loop->timer_manager()->StartTimer(1000, &finish_task, false); - Timer* reset_timer = loop->timer_manager()->StartTimer(50, &reset_task, true); + + base::OneShotTimer<TestFinishedTask> t; + t.Start(TimeDelta::FromMilliseconds(1000), &finish_task, + &TestFinishedTask::Run); + + base::RepeatingTimer<ResetIdleTask> reset_timer; + reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task, + &ResetIdleTask::Run); + test_task.Start(); - loop->Run(); - loop->timer_manager()->StopTimer(reset_timer); + + MessageLoop::current()->Run(); + + reset_timer.Stop(); EXPECT_EQ(test_task.get_idle_counter(), 0); - delete t; - delete reset_timer; } /////////////////////////////////////////////////////////////////////////////// @@ -142,18 +155,21 @@ TEST_F(IdleTimerTest, Repeat) { // Verify that we fired 10 times. mock_idle_time = GetTickCount(); TestIdleTask test_task(true); + TestFinishedTask finish_task; - MessageLoop* loop = MessageLoop::current(); - Timer* t = loop->timer_manager()->StartTimer(1050, &finish_task, false); + + base::OneShotTimer<TestFinishedTask> t; + t.Start(TimeDelta::FromMilliseconds(1050), &finish_task, + &TestFinishedTask::Run); + test_task.Start(); - loop->Run(); + MessageLoop::current()->Run(); // In a perfect world, the idle_counter should be 10. However, // since timers aren't guaranteed to fire perfectly, this can // be less. Just expect more than 5 and no more than 10. EXPECT_GT(test_task.get_idle_counter(), 5); EXPECT_LE(test_task.get_idle_counter(), 10); - delete t; } TEST_F(IdleTimerTest, RepeatIdleReset) { @@ -163,21 +179,26 @@ TEST_F(IdleTimerTest, RepeatIdleReset) { // Verify that we fired 9 times. mock_idle_time = GetTickCount(); TestIdleTask test_task(true); + ResetIdleTask reset_task; TestFinishedTask finish_task; - MessageLoop* loop = MessageLoop::current(); - Timer* t1 = loop->timer_manager()->StartTimer(1000, &finish_task, false); - Timer* t2 = loop->timer_manager()->StartTimer(550, &reset_task, false); + + base::OneShotTimer<TestFinishedTask> t1; + t1.Start(TimeDelta::FromMilliseconds(1000), &finish_task, + &TestFinishedTask::Run); + + base::OneShotTimer<ResetIdleTask> t2; + t2.Start(TimeDelta::FromMilliseconds(550), &reset_task, + &ResetIdleTask::Run); + test_task.Start(); - loop->Run(); + MessageLoop::current()->Run(); // In a perfect world, the idle_counter should be 9. However, // since timers aren't guaranteed to fire perfectly, this can // be less. Just expect more than 5 and no more than 9. EXPECT_GT(test_task.get_idle_counter(), 5); EXPECT_LE(test_task.get_idle_counter(), 9); - delete t1; - delete t2; } TEST_F(IdleTimerTest, RepeatNotIdle) { @@ -188,17 +209,23 @@ TEST_F(IdleTimerTest, RepeatNotIdle) { mock_idle_time = GetTickCount(); TestIdleTask test_task(true); + TestFinishedTask finish_task; ResetIdleTask reset_task; - MessageLoop* loop = MessageLoop::current(); - Timer* t1 = loop->timer_manager()->StartTimer(1000, &finish_task, false); - Timer* reset_timer = loop->timer_manager()->StartTimer(50, &reset_task, true); + + base::OneShotTimer<TestFinishedTask> t; + t.Start(TimeDelta::FromMilliseconds(1000), &finish_task, + &TestFinishedTask::Run); + + base::RepeatingTimer<ResetIdleTask> reset_timer; + reset_timer.Start(TimeDelta::FromMilliseconds(50), &reset_task, + &ResetIdleTask::Run); + test_task.Start(); - loop->Run(); - loop->timer_manager()->StopTimer(reset_timer); + MessageLoop::current()->Run(); + + reset_timer.Stop(); EXPECT_EQ(test_task.get_idle_counter(), 0); - delete t1; - delete reset_timer; } diff --git a/base/message_loop.h b/base/message_loop.h index efdb5d7..babc17a 100644 --- a/base/message_loop.h +++ b/base/message_loop.h @@ -199,8 +199,9 @@ class MessageLoop : public base::MessagePump::Delegate { return loop; } - // Returns the TimerManager object for the current thread. - base::TimerManager* timer_manager() { return &timer_manager_; } + // Returns the TimerManager object for the current thread. This getter is + // deprecated. Please use OneShotTimer or RepeatingTimer instead. + base::TimerManager* timer_manager_deprecated() { return &timer_manager_; } // Enables or disables the recursive task processing. This happens in the case // of recursive message loops. Some unwanted message loop may occurs when diff --git a/base/timer.cc b/base/timer.cc index 7de55c7..9f6e7b0 100644 --- a/base/timer.cc +++ b/base/timer.cc @@ -231,7 +231,8 @@ void BaseTimer_Helper::InitiateDelayedTask(TimerTask* timer_task) { delayed_task_ = timer_task; delayed_task_->timer_ = this; MessageLoop::current()->PostDelayedTask( - FROM_HERE, timer_task, static_cast<int>(delay_.InMilliseconds())); + FROM_HERE, timer_task, + static_cast<int>(timer_task->delay_.InMilliseconds())); } } // namespace base diff --git a/base/timer.h b/base/timer.h index d78423a..e1a77e2 100644 --- a/base/timer.h +++ b/base/timer.h @@ -260,14 +260,16 @@ class BaseTimer_Helper { } protected: - BaseTimer_Helper(bool repeating) - : delayed_task_(NULL), repeating_(repeating) { - } + BaseTimer_Helper() : delayed_task_(NULL) {} // We have access to the timer_ member so we can orphan this task. class TimerTask : public Task { public: + TimerTask(TimeDelta delay) : delay_(delay) { + // timer_ is set in InitiateDelayedTask. + } BaseTimer_Helper* timer_; + TimeDelta delay_; }; // Used to orphan delayed_task_ so that when it runs it does nothing. @@ -278,8 +280,6 @@ class BaseTimer_Helper { void InitiateDelayedTask(TimerTask* timer_task); TimerTask* delayed_task_; - TimeDelta delay_; - bool repeating_; DISALLOW_COPY_AND_ASSIGN(BaseTimer_Helper); }; @@ -287,76 +287,69 @@ class BaseTimer_Helper { //----------------------------------------------------------------------------- // This class is an implementation detail of OneShotTimer and RepeatingTimer. // Please do not use this class directly. -template <class Receiver> +template <class Receiver, bool kIsRepeating> class BaseTimer : public BaseTimer_Helper { public: typedef void (Receiver::*ReceiverMethod)(); - // The task must be set using set_task before calling Start. - BaseTimer(bool repeating) - : BaseTimer_Helper(repeating), receiver_(NULL), receiver_method_(NULL) { - } - // Call this method to start the timer. It is an error to call this method // while the timer is already running. void Start(TimeDelta delay, Receiver* receiver, ReceiverMethod method) { DCHECK(!IsRunning()); - delay_ = delay; - receiver_ = receiver; - receiver_method_ = method; - InitiateDelayedTask(new TimerTask()); + InitiateDelayedTask(new TimerTask(delay, receiver, method)); } // Call this method to stop the timer. It is a no-op if the timer is not // running. void Stop() { - receiver_ = NULL; - receiver_method_ = NULL; OrphanDelayedTask(); } // Call this method to reset the timer delay of an already running timer. void Reset() { DCHECK(IsRunning()); - OrphanDelayedTask(); - InitiateDelayedTask(new TimerTask()); + InitiateDelayedTask(static_cast<TimerTask*>(delayed_task_)->Clone()); } private: + typedef BaseTimer<Receiver, kIsRepeating> SelfType; + class TimerTask : public BaseTimer_Helper::TimerTask { public: + TimerTask(TimeDelta delay, Receiver* receiver, ReceiverMethod method) + : BaseTimer_Helper::TimerTask(delay), + receiver_(receiver), + method_(method) { + } virtual void Run() { if (!timer_) // timer_ is null if we were orphaned. return; - BaseTimer<Receiver>* self = static_cast<BaseTimer<Receiver>*>(timer_); - if (self->repeating_) { + SelfType* self = static_cast<SelfType*>(timer_); + if (kIsRepeating) { self->Reset(); } else { self->delayed_task_ = NULL; } - DispatchToMethod(self->receiver_, self->receiver_method_, Tuple0()); + DispatchToMethod(receiver_, method_, Tuple0()); + } + TimerTask* Clone() const { + return new TimerTask(delay_, receiver_, method_); } + private: + Receiver* receiver_; + ReceiverMethod method_; }; - - Receiver* receiver_; - ReceiverMethod receiver_method_; }; //----------------------------------------------------------------------------- // A simple, one-shot timer. See usage notes at the top of the file. template <class Receiver> -class OneShotTimer : public BaseTimer<Receiver> { - public: - OneShotTimer() : BaseTimer<Receiver>(false) {} -}; +class OneShotTimer : public BaseTimer<Receiver, false> {}; //----------------------------------------------------------------------------- // A simple, repeating timer. See usage notes at the top of the file. template <class Receiver> -class RepeatingTimer : public BaseTimer<Receiver> { - public: - RepeatingTimer() : BaseTimer<Receiver>(true) {} -}; +class RepeatingTimer : public BaseTimer<Receiver, true> {}; } // namespace base diff --git a/base/timer_unittest.cc b/base/timer_unittest.cc index e4b45ec..6645885 100644 --- a/base/timer_unittest.cc +++ b/base/timer_unittest.cc @@ -75,12 +75,13 @@ TimerTask::TimerTask(int delay, bool repeating) timer_(NULL) { Reset(); // This will just set up the variables to indicate we have a // running timer. - timer_ = message_loop()->timer_manager()->StartTimer(delay, this, repeating); + timer_ = message_loop()->timer_manager_deprecated()->StartTimer( + delay, this, repeating); } TimerTask::~TimerTask() { if (timer_) { - message_loop()->timer_manager()->StopTimer(timer_); + message_loop()->timer_manager_deprecated()->StopTimer(timer_); delete timer_; } if (timer_running_) { @@ -97,7 +98,7 @@ void TimerTask::Reset() { } if (timer_) { start_ticks_ = TimeTicks::Now(); - message_loop()->timer_manager()->ResetTimer(timer_); + message_loop()->timer_manager_deprecated()->ResetTimer(timer_); } } @@ -116,7 +117,7 @@ void TimerTask::Run() { // If we're done running, shut down the message loop. if (timer_->repeating() && (iterations_ < 10)) return; // Iterate 10 times before terminating. - message_loop()->timer_manager()->StopTimer(timer_); + message_loop()->timer_manager_deprecated()->StopTimer(timer_); timer_running_ = false; if (--timer_count_ <= 0) QuitMessageLoop(); @@ -224,7 +225,7 @@ void RunTest_BrokenTimer(MessageLoop::Type message_loop_type) { // Simulate faulty early-firing timers. The tasks in RunTimerTest should // nevertheless be invoked after their specified delays, regardless of when // WM_TIMER fires. - TimerManager* manager = MessageLoop::current()->timer_manager(); + TimerManager* manager = MessageLoop::current()->timer_manager_deprecated(); manager->set_use_broken_delay(true); RunTimerTest(); manager->set_use_broken_delay(false); diff --git a/chrome/browser/autocomplete/autocomplete_popup.cc b/chrome/browser/autocomplete/autocomplete_popup.cc index b272143..ca2dcbc 100644 --- a/chrome/browser/autocomplete/autocomplete_popup.cc +++ b/chrome/browser/autocomplete/autocomplete_popup.cc @@ -721,10 +721,6 @@ AutocompletePopupModel::AutocompletePopupModel(const ChromeFont& font, profile_(profile), query_in_progress_(false), update_pending_(false), - // Creating the Timers directly instead of using StartTimer() ensures - // they won't actually start running until we use ResetTimer(). - coalesce_timer_(new Timer(kPopupCoalesceMs, this, false)), - max_delay_timer_(new Timer(kPopupUpdateMaxDelayMs, this, true)), hovered_line_(kNoMatch), selected_line_(kNoMatch) { } @@ -773,10 +769,9 @@ void AutocompletePopupModel::StartAutocomplete( input_ = input; // If we're starting a brand new query, stop caring about any old query. - TimerManager* const tm = MessageLoop::current()->timer_manager(); if (!minimal_changes && query_in_progress_) { update_pending_ = false; - tm->StopTimer(coalesce_timer_.get()); + coalesce_timer_.Stop(); } // Start the new query. @@ -785,8 +780,9 @@ void AutocompletePopupModel::StartAutocomplete( // If we're not ready to show results and the max update interval timer isn't // already running, start it now. - if (query_in_progress_ && !tm->IsTimerRunning(max_delay_timer_.get())) - tm->ResetTimer(max_delay_timer_.get()); + if (query_in_progress_ && !max_delay_timer_.IsRunning()) + max_delay_timer_.Start(TimeDelta::FromMilliseconds(kPopupUpdateMaxDelayMs), + this, &AutocompletePopupModel::Run); SetDefaultMatchAndUpdate(!query_in_progress_); } @@ -1030,7 +1026,9 @@ void AutocompletePopupModel::SetDefaultMatchAndUpdate(bool immediately) { } else if (!update_pending_) { // Coalesce the results for the next kPopupCoalesceMs milliseconds. update_pending_ = true; - MessageLoop::current()->timer_manager()->ResetTimer(coalesce_timer_.get()); + coalesce_timer_.Stop(); + coalesce_timer_.Start(TimeDelta::FromMilliseconds(kPopupCoalesceMs), this, + &AutocompletePopupModel::Run); } // Update the edit with the possibly new data for this match. @@ -1087,12 +1085,11 @@ void AutocompletePopupModel::CommitLatestResults(bool force) { // The max update interval timer either needs to be reset (if more updates // are to come) or stopped (when we're done with the query). The coalesce // timer should always just be stopped. - TimerManager* const tm = MessageLoop::current()->timer_manager(); - tm->StopTimer(coalesce_timer_.get()); + coalesce_timer_.Stop(); if (query_in_progress_) - tm->ResetTimer(max_delay_timer_.get()); + max_delay_timer_.Reset(); else - tm->StopTimer(max_delay_timer_.get()); + max_delay_timer_.Stop(); } bool AutocompletePopupModel::GetKeywordForMatch(const AutocompleteMatch& match, diff --git a/chrome/browser/autocomplete/autocomplete_popup.h b/chrome/browser/autocomplete/autocomplete_popup.h index 395f774..160c766 100644 --- a/chrome/browser/autocomplete/autocomplete_popup.h +++ b/chrome/browser/autocomplete/autocomplete_popup.h @@ -385,15 +385,12 @@ class AutocompletePopupModel : public ACControllerListener, public Task { // Timer that tracks how long it's been since the last provider update we // received. Instead of displaying each update immediately, we batch updates // into groups, which reduces flicker. - // - // NOTE: Both coalesce_timer_ and max_delay_timer_ (below) are set up during - // the constructor, and are guaranteed non-NULL for the life of the popup. - scoped_ptr<Timer> coalesce_timer_; + base::OneShotTimer<AutocompletePopupModel> coalesce_timer_; // Timer that tracks how long it's been since the last time we updated the // onscreen results. This is used to ensure that the popup is somewhat // responsive even when the user types continuously. - scoped_ptr<Timer> max_delay_timer_; + base::RepeatingTimer<AutocompletePopupModel> max_delay_timer_; // The line that's currently hovered. If we're not drawing a hover rect, // this will be kNoMatch, even if the cursor is over the popup contents. diff --git a/chrome/browser/autocomplete/search_provider.cc b/chrome/browser/autocomplete/search_provider.cc index 23b6063..9126a35 100644 --- a/chrome/browser/autocomplete/search_provider.cc +++ b/chrome/browser/autocomplete/search_provider.cc @@ -180,7 +180,10 @@ void SearchProvider::StartOrStopSuggestQuery(bool minimal_changes, // Kick off a timer that will start the URL fetch if it completes before // the user types another character. suggest_results_pending_ = true; - MessageLoop::current()->timer_manager()->ResetTimer(timer_.get()); + + timer_.Stop(); + timer_.Start(TimeDelta::FromMilliseconds(kQueryDelayMs), this, + &SearchProvider::Run); } void SearchProvider::StopHistory() { @@ -192,7 +195,7 @@ void SearchProvider::StopHistory() { void SearchProvider::StopSuggest() { suggest_results_pending_ = false; - MessageLoop::current()->timer_manager()->StopTimer(timer_.get()); + timer_.Stop(); fetcher_.reset(); // Stop any in-progress URL fetch. suggest_results_.clear(); have_suggest_results_ = false; diff --git a/chrome/browser/autocomplete/search_provider.h b/chrome/browser/autocomplete/search_provider.h index 9af8a53..4c509c5 100644 --- a/chrome/browser/autocomplete/search_provider.h +++ b/chrome/browser/autocomplete/search_provider.h @@ -34,14 +34,11 @@ class Value; // comes back, the provider creates and returns matches for the best // suggestions. class SearchProvider : public AutocompleteProvider, - public URLFetcher::Delegate, - public Task { + public URLFetcher::Delegate { public: SearchProvider(ACProviderListener* listener, Profile* profile) : AutocompleteProvider(listener, profile, "Search"), last_default_provider_(NULL), -#pragma warning(suppress: 4355) // Okay to pass "this" here. - timer_(new Timer(kQueryDelayMs, this, false)), fetcher_(NULL), history_request_pending_(false), have_history_results_(false), @@ -63,9 +60,6 @@ class SearchProvider : public AutocompleteProvider, const ResponseCookies& cookies, const std::string& data); - // Task - void Run(); - private: struct NavigationResult { NavigationResult(const std::wstring& url, const std::wstring& site_name) @@ -85,6 +79,9 @@ class SearchProvider : public AutocompleteProvider, typedef std::vector<history::KeywordSearchTermVisit> HistoryResults; typedef std::map<std::wstring, AutocompleteMatch> MatchMap; + // Called when timer_ expires. + void Run(); + // Determines whether an asynchronous subcomponent query should run for the // current input. If so, starts it if necessary; otherwise stops it. // NOTE: These functions do not update |done_|. Callers must do so. @@ -173,7 +170,7 @@ class SearchProvider : public AutocompleteProvider, // A timer to start a query to the suggest server after the user has stopped // typing for long enough. - scoped_ptr<Timer> timer_; + base::OneShotTimer<SearchProvider> timer_; // The fetcher that retrieves suggest results from the server. scoped_ptr<URLFetcher> fetcher_; diff --git a/chrome/browser/download_file.cc b/chrome/browser/download_file.cc index a7f796e..8b1da8c 100644 --- a/chrome/browser/download_file.cc +++ b/chrome/browser/download_file.cc @@ -12,7 +12,6 @@ #include "base/scoped_ptr.h" #include "base/string_util.h" #include "base/task.h" -#include "base/timer.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/download_manager.h" #include "chrome/browser/profile.h" @@ -137,8 +136,6 @@ bool DownloadFile::Open(const wchar_t* open_mode) { DownloadFileManager::DownloadFileManager(MessageLoop* ui_loop, ResourceDispatcherHost* rdh) : next_id_(0), - update_task_(NULL), - update_timer_(NULL), ui_loop_(ui_loop), resource_dispatcher_host_(rdh) { } @@ -146,7 +143,6 @@ DownloadFileManager::DownloadFileManager(MessageLoop* ui_loop, DownloadFileManager::~DownloadFileManager() { // Check for clean shutdown. DCHECK(downloads_.empty()); - DCHECK(!update_timer_ && !update_task_); ui_progress_.clear(); } @@ -197,22 +193,15 @@ void DownloadFileManager::RemoveDownloadFromUIProgress(int id) { // regularly controlled interval. void DownloadFileManager::StartUpdateTimer() { DCHECK(MessageLoop::current() == ui_loop_); - if (update_timer_ == NULL) { - update_task_ = new DownloadFileUpdateTask(this); - TimerManager* tm = ui_loop_->timer_manager(); - update_timer_ = tm->StartTimer(kUpdatePeriodMs, update_task_, true); + if (!update_timer_.IsRunning()) { + update_timer_.Start(TimeDelta::FromMilliseconds(kUpdatePeriodMs), this, + &DownloadFileManager::UpdateInProgressDownloads); } } void DownloadFileManager::StopUpdateTimer() { DCHECK(MessageLoop::current() == ui_loop_); - if (update_timer_ && update_task_) { - ui_loop_->timer_manager()->StopTimer(update_timer_); - delete update_timer_; - update_timer_ = NULL; - delete update_task_; - update_task_ = NULL; - } + update_timer_.Stop(); } // Called on the IO thread once the ResourceDispatcherHost has decided that a diff --git a/chrome/browser/download_file.h b/chrome/browser/download_file.h index f9c6e91..4b50c13 100644 --- a/chrome/browser/download_file.h +++ b/chrome/browser/download_file.h @@ -50,19 +50,15 @@ #include "base/lock.h" #include "base/ref_counted.h" #include "base/thread.h" +#include "base/timer.h" #include "chrome/browser/history/download_types.h" class DownloadManager; class GURL; class MessageLoop; class ResourceDispatcherHost; -class Task; class URLRequestContext; -namespace base { -class Timer; -} - // DownloadBuffer -------------------------------------------------------------- // This container is created and populated on the io_thread, and passed to the @@ -242,8 +238,7 @@ class DownloadFileManager DownloadFileMap downloads_; // Throttle updates to the UI thread. - Task* update_task_; - base::Timer* update_timer_; + base::RepeatingTimer<DownloadFileManager> update_timer_; // The MessageLoop that the DownloadManagers live on. MessageLoop* ui_loop_; diff --git a/chrome/browser/download_manager.cc b/chrome/browser/download_manager.cc index aef9b14..4f008d8 100644 --- a/chrome/browser/download_manager.cc +++ b/chrome/browser/download_manager.cc @@ -95,8 +95,6 @@ DownloadItem::DownloadItem(const DownloadCreateInfo& info) state_(static_cast<DownloadState>(info.state)), start_time_(info.start_time), db_handle_(info.db_handle), - update_task_(NULL), - timer_(NULL), manager_(NULL), is_paused_(false), open_when_complete_(false), @@ -124,8 +122,6 @@ DownloadItem::DownloadItem(int32 download_id, state_(IN_PROGRESS), start_time_(start_time), db_handle_(kUninitializedHandle), - update_task_(NULL), - timer_(NULL), manager_(NULL), is_paused_(false), open_when_complete_(false), @@ -141,7 +137,6 @@ void DownloadItem::Init(bool start_timer) { } DownloadItem::~DownloadItem() { - DCHECK(timer_ == NULL && update_task_ == NULL); state_ = REMOVING; UpdateObservers(); } @@ -205,20 +200,12 @@ void DownloadItem::Remove() { } void DownloadItem::StartProgressTimer() { - DCHECK(update_task_ == NULL && timer_ == NULL); - update_task_ = new DownloadItemUpdateTask(this); - TimerManager* tm = MessageLoop::current()->timer_manager(); - timer_ = tm->StartTimer(kUpdateTimeMs, update_task_, true); + update_timer_.Start(TimeDelta::FromMilliseconds(kUpdateTimeMs), this, + &DownloadItem::UpdateObservers); } void DownloadItem::StopProgressTimer() { - if (timer_) { - MessageLoop::current()->timer_manager()->StopTimer(timer_); - delete timer_; - timer_ = NULL; - delete update_task_; - update_task_ = NULL; - } + update_timer_.Stop(); } bool DownloadItem::TimeRemaining(TimeDelta* remaining) const { diff --git a/chrome/browser/download_manager.h b/chrome/browser/download_manager.h index 89773fe..a9ffc27 100644 --- a/chrome/browser/download_manager.h +++ b/chrome/browser/download_manager.h @@ -59,8 +59,6 @@ class MessageLoop; class PrefService; class Profile; class ResourceDispatcherHost; -class Task; -class Timer; class URLRequestContext; class WebContents; @@ -216,9 +214,8 @@ class DownloadItem { // Our persistent store handle int64 db_handle_; - // Timer & task for regularly updating our observers - Task* update_task_; - Timer* timer_; + // Timer for regularly updating our observers + base::RepeatingTimer<DownloadItem> update_timer_; // Our owning object DownloadManager* manager_; diff --git a/chrome/browser/download_tab_view.cc b/chrome/browser/download_tab_view.cc index ee74590..56b7c3e 100644 --- a/chrome/browser/download_tab_view.cc +++ b/chrome/browser/download_tab_view.cc @@ -663,8 +663,6 @@ void DownloadItemTabView::LinkActivated(ChromeViews::Link* source, DownloadTabView::DownloadTabView(DownloadManager* model) : model_(model), - progress_timer_(NULL), - progress_task_(NULL), start_angle_(download_util::kStartAngleDegrees), scroll_helper_(kSpacer, kProgressIconSize + kSpacer), selected_index_(-1) { @@ -688,25 +686,16 @@ void DownloadTabView::Initialize() { // Start progress animation timers when we get our first (in-progress) download. void DownloadTabView::StartDownloadProgress() { - if (progress_task_ || progress_timer_) + if (progress_timer_.IsRunning()) return; - progress_task_ = - new download_util::DownloadProgressTask<DownloadTabView>(this); - progress_timer_ = - MessageLoop::current()->timer_manager()-> - StartTimer(download_util::kProgressRateMs, progress_task_, true); + progress_timer_.Start( + TimeDelta::FromMilliseconds(download_util::kProgressRateMs), this, + &DownloadTabView::UpdateDownloadProgress); } // Stop progress animation when there are no more in-progress downloads. void DownloadTabView::StopDownloadProgress() { - if (progress_timer_) { - DCHECK(progress_task_); - MessageLoop::current()->timer_manager()->StopTimer(progress_timer_); - delete progress_timer_; - progress_timer_ = NULL; - delete progress_task_; - progress_task_ = NULL; - } + progress_timer_.Stop(); } // Update our animations. diff --git a/chrome/browser/download_tab_view.h b/chrome/browser/download_tab_view.h index 346a903..92ca343 100644 --- a/chrome/browser/download_tab_view.h +++ b/chrome/browser/download_tab_view.h @@ -173,8 +173,7 @@ class DownloadTabView : public ChromeViews::View, OrderedDownloads downloads_; // Progress animations - base::Timer* progress_timer_; - Task* progress_task_; + base::RepeatingTimer<DownloadTabView> progress_timer_; // Since this view manages the progress animation timers for all the floating // views, we need to track the current in progress downloads. This container diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index decd853..b1e2bdc 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -267,18 +267,14 @@ bool PrintJob::FlushJob(int timeout_ms) { // Make sure the object outlive this message loop. scoped_refptr<PrintJob> handle(this); - MessageLoop::QuitTask timeout_task; - scoped_ptr<Timer> timeout; - if (timeout_ms) { - timeout.reset(MessageLoop::current()->timer_manager()->StartTimer( - timeout_ms, - &timeout_task, - false)); - } - // Stop() will eventually be called, which will get out of the inner message // loop. But, don't take it for granted and set a timer in case something goes // wrong. + base::OneShotTimer<MessageLoop> quit_task; + if (timeout_ms) { + quit_task.Start(TimeDelta::FromMilliseconds(timeout_ms), + MessageLoop::current(), &MessageLoop::Quit); + } bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); @@ -286,9 +282,6 @@ bool PrintJob::FlushJob(int timeout_ms) { // Restore task state. MessageLoop::current()->SetNestableTasksAllowed(old_state); - if (timeout.get()) { - MessageLoop::current()->timer_manager()->StopTimer(timeout.get()); - } return true; } diff --git a/chrome/browser/printing/print_view_manager.cc b/chrome/browser/printing/print_view_manager.cc index 39e3bda..1157d64 100644 --- a/chrome/browser/printing/print_view_manager.cc +++ b/chrome/browser/printing/print_view_manager.cc @@ -492,12 +492,12 @@ bool PrintViewManager::RunInnerMessageLoop() { // be cpu bound, the page overly complex/large or the system just // memory-bound. static const int kPrinterSettingsTimeout = 60000; - MessageLoop::QuitTask timeout_task; - Timer* timeout = MessageLoop::current()->timer_manager()->StartTimer( - kPrinterSettingsTimeout, - &timeout_task, - false); + base::OneShotTimer<MessageLoop> quit_timer; + quit_timer.Start(TimeDelta::FromMilliseconds(kPrinterSettingsTimeout), + MessageLoop::current(), &MessageLoop::Quit); + inside_inner_message_loop_ = true; + // Need to enable recursive task. bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); @@ -512,11 +512,6 @@ bool PrintViewManager::RunInnerMessageLoop() { success = false; } - if (timeout) { - MessageLoop::current()->timer_manager()->StopTimer(timeout); - delete timeout; - timeout = NULL; - } return success; } diff --git a/chrome/browser/printing/printing_layout_uitest.cc b/chrome/browser/printing/printing_layout_uitest.cc index a55e246..943aeb6 100644 --- a/chrome/browser/printing/printing_layout_uitest.cc +++ b/chrome/browser/printing/printing_layout_uitest.cc @@ -399,23 +399,29 @@ class PrintingLayoutTextTest : public PrintingLayoutTest { // Dismiss the first dialog box child of owner_window by "executing" the // default button. -class DismissTheWindow : public Task { +class DismissTheWindow : public base::RefCountedThreadSafe<DismissTheWindow> { public: DismissTheWindow(DWORD owner_process) : owner_process_(owner_process), dialog_was_found_(false), dialog_window_(NULL), other_thread_(MessageLoop::current()), - timer_(NULL), start_time_(Time::Now()) { } - virtual void Run() { + + void Start() { + timer_.Start(TimeDelta::FromMilliseconds(250), this, + &DismissTheWindow::DoTimeout); + } + + private: + void DoTimeout() { // A bit twisted code that runs in 2 passes or more. First it tries to find // a dialog box, if it finds it, it will execute the default action. If it // still works, it will loop again but then it will try to *not* find the // window. Once this is right, it will stop the timer and unlock the // other_thread_ message loop. - if (!timer_) + if (!timer_.IsRunning()) return; if (!dialog_window_) { @@ -464,8 +470,7 @@ class DismissTheWindow : public Task { // Now verify that it indeed closed itself. if (!IsWindow(dialog_window_)) { - MessageLoop::current()->timer_manager()->StopTimer(timer_); - timer_ = NULL; + timer_.Stop(); // Unlock the other thread. other_thread_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } else { @@ -473,15 +478,12 @@ class DismissTheWindow : public Task { dialog_window_ = NULL; } } - void SetTimer(Timer* timer) { - timer_ = timer; - } - private: + DWORD owner_process_; bool dialog_was_found_; HWND dialog_window_; MessageLoop* other_thread_; - Timer* timer_; + base::RepeatingTimer<DismissTheWindow> timer_; Time start_time_; }; @@ -562,14 +564,13 @@ TEST_F(PrintingLayoutTest, DISABLED_Delayed) { scoped_ptr<base::Thread> worker( new base::Thread("PrintingLayoutTest_worker")); - DismissTheWindow dismiss_task(process_util::GetProcId(process())); + scoped_refptr<DismissTheWindow> dismiss_task = + new DismissTheWindow(process_util::GetProcId(process())); // We need to start the thread to be able to set the timer. worker->Start(); - scoped_ptr<Timer> timer(worker->message_loop()->timer_manager()->StartTimer( - 250, - &dismiss_task, - true)); - dismiss_task.SetTimer(timer.get()); + worker->message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(dismiss_task.get(), &DismissTheWindow::Start)); + MessageLoop::current()->Run(); worker->Stop(); @@ -601,14 +602,13 @@ TEST_F(PrintingLayoutTest, DISABLED_IFrame) { scoped_ptr<base::Thread> worker( new base::Thread("PrintingLayoutTest_worker")); - DismissTheWindow dismiss_task(process_util::GetProcId(process())); + scoped_refptr<DismissTheWindow> dismiss_task = + new DismissTheWindow(process_util::GetProcId(process())); // We need to start the thread to be able to set the timer. worker->Start(); - scoped_ptr<Timer> timer(worker->message_loop()->timer_manager()->StartTimer( - 250, - &dismiss_task, - true)); - dismiss_task.SetTimer(timer.get()); + worker->message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(dismiss_task.get(), &DismissTheWindow::Start)); + MessageLoop::current()->Run(); worker->Stop(); diff --git a/chrome/browser/profile.cc b/chrome/browser/profile.cc index 9a64b40..b55a065 100644 --- a/chrome/browser/profile.cc +++ b/chrome/browser/profile.cc @@ -551,9 +551,6 @@ ProfileImpl::ProfileImpl(const std::wstring& path) created_web_data_service_(false), created_download_manager_(false), request_context_(NULL), -#pragma warning(suppress: 4355) // Okay to pass "this" here. - create_session_service_timer_(NULL), - create_session_service_task_(this), start_time_(Time::Now()), spellchecker_(NULL), #ifdef CHROME_PERSONALIZATION @@ -562,9 +559,9 @@ ProfileImpl::ProfileImpl(const std::wstring& path) shutdown_session_service_(false) { DCHECK(!path.empty()) << "Using an empty path will attempt to write " << "profile files to the root directory!"; - create_session_service_timer_ = - MessageLoop::current()->timer_manager()->StartTimer( - kCreateSessionServiceDelayMS, &create_session_service_task_, false); + create_session_service_timer_.Start( + TimeDelta::FromMilliseconds(kCreateSessionServiceDelayMS), this, + &ProfileImpl::EnsureSessionServiceCreated); } ProfileImpl::~ProfileImpl() { @@ -913,12 +910,7 @@ void ProfileImpl::MarkAsCleanShutdown() { } void ProfileImpl::StopCreateSessionServiceTimer() { - if (create_session_service_timer_) { - MessageLoop::current()->timer_manager()-> - StopTimer(create_session_service_timer_); - delete create_session_service_timer_; - create_session_service_timer_ = NULL; - } + create_session_service_timer_.Stop(); } #ifdef CHROME_PERSONALIZATION diff --git a/chrome/browser/profile.h b/chrome/browser/profile.h index e4057c6..238ce41 100644 --- a/chrome/browser/profile.h +++ b/chrome/browser/profile.h @@ -14,7 +14,7 @@ #include "base/ref_counted.h" #include "base/scoped_ptr.h" #include "base/task.h" -#include "base/time.h" +#include "base/timer.h" #ifdef CHROME_PERSONALIZATION #include "chrome/personalization/personalization.h" #endif @@ -33,10 +33,6 @@ class URLRequestContext; class VisitedLinkMaster; class WebDataService; -namespace base { -class Timer; -} - class Profile { public: @@ -291,23 +287,6 @@ class ProfileImpl : public Profile { private: class RequestContext; - // TODO(sky): replace this with a generic invokeLater that doesn't require - // arg to be ref counted. - class CreateSessionServiceTask : public Task { - public: - explicit CreateSessionServiceTask(ProfileImpl* profile) - : profile_(profile) { - } - void Run() { - profile_->GetSessionService(); - } - - private: - ProfileImpl* profile_; - - DISALLOW_EVIL_CONSTRUCTORS(CreateSessionServiceTask); - }; - friend class Profile; ProfileImpl(const std::wstring& path); @@ -316,6 +295,10 @@ class ProfileImpl : public Profile { std::wstring GetPrefFilePath(); void StopCreateSessionServiceTimer(); + + void EnsureSessionServiceCreated() { + GetSessionService(); + } std::wstring path_; bool off_the_record_; @@ -343,8 +326,7 @@ class ProfileImpl : public Profile { ProfileControllerSet controllers_; - base::Timer* create_session_service_timer_; - CreateSessionServiceTask create_session_service_task_; + base::OneShotTimer<ProfileImpl> create_session_service_timer_; scoped_ptr<OffTheRecordProfileImpl> off_the_record_profile_; diff --git a/chrome/browser/safe_browsing/protocol_manager.cc b/chrome/browser/safe_browsing/protocol_manager.cc index c1ed1b4..e66afc5 100644 --- a/chrome/browser/safe_browsing/protocol_manager.cc +++ b/chrome/browser/safe_browsing/protocol_manager.cc @@ -49,22 +49,6 @@ static const int kSbClientMinorVersion = 0; static const int kSbMaxBackOff = 8; -// Periodic update task -------------------------------------------------------- -class SafeBrowsingProtocolUpdateTask : public Task { - public: - explicit SafeBrowsingProtocolUpdateTask(SafeBrowsingProtocolManager* manager) - : manager_(manager) { - } - - void Run() { - manager_->GetNextUpdate(); - } - - private: - SafeBrowsingProtocolManager* manager_; -}; - - // SafeBrowsingProtocolManager implementation ---------------------------------- SafeBrowsingProtocolManager::SafeBrowsingProtocolManager( @@ -93,9 +77,6 @@ SafeBrowsingProtocolManager::SafeBrowsingProtocolManager( } SafeBrowsingProtocolManager::~SafeBrowsingProtocolManager() { - if (update_timer_.get()) - MessageLoop::current()->timer_manager()->StopTimer(update_timer_.get()); - // Delete in-progress SafeBrowsing requests. STLDeleteContainerPairFirstPointers(hash_requests_.begin(), hash_requests_.end()); @@ -399,17 +380,13 @@ void SafeBrowsingProtocolManager::Initialize() { void SafeBrowsingProtocolManager::ScheduleNextUpdate(bool back_off) { DCHECK(next_update_sec_ > 0); - if (!update_task_.get()) - update_task_.reset(new SafeBrowsingProtocolUpdateTask(this)); - - // Unschedule any current timer & task. - TimerManager* tm = MessageLoop::current()->timer_manager(); - if (update_timer_.get()) - tm->StopTimer(update_timer_.get()); + // Unschedule any current timer. + update_timer_.Stop(); // Reschedule with the new update. const int next_update = GetNextUpdateTime(back_off); - update_timer_.reset(tm->StartTimer(next_update, update_task_.get(), false)); + update_timer_.Start(TimeDelta::FromMilliseconds(next_update), this, + &SafeBrowsingProtocolManager::GetNextUpdate); } // According to section 5 of the SafeBrowsing protocol specification, we must diff --git a/chrome/browser/safe_browsing/protocol_manager.h b/chrome/browser/safe_browsing/protocol_manager.h index 1b12d5c6..c7276c6 100644 --- a/chrome/browser/safe_browsing/protocol_manager.h +++ b/chrome/browser/safe_browsing/protocol_manager.h @@ -159,8 +159,7 @@ class SafeBrowsingProtocolManager : public URLFetcher::Delegate { // For managing the next earliest time to query the SafeBrowsing servers for // updates. int next_update_sec_; - scoped_ptr<Task> update_task_; - scoped_ptr<Timer> update_timer_; + base::OneShotTimer<SafeBrowsingProtocolManager> update_timer_; // All chunk requests that need to be made, along with their MAC. std::deque<ChunkUrl> chunk_request_urls_; diff --git a/chrome/browser/tabs/tab_strip.cc b/chrome/browser/tabs/tab_strip.cc index d38be5a..03f6c2e 100644 --- a/chrome/browser/tabs/tab_strip.cc +++ b/chrome/browser/tabs/tab_strip.cc @@ -462,10 +462,6 @@ TabStrip::~TabStrip() { // TODO(beng): remove this if it doesn't work to fix the TabSelectedAt bug. drag_controller_.reset(NULL); - // Stop any existing Loading Animation timer. - MessageLoop::current()->timer_manager()->StopTimer( - loading_animation_timer_.get()); - // Make sure we unhook ourselves as a message loop observer so that we don't // crash in the case where the user closes the window after closing a tab // but before moving the mouse. @@ -849,18 +845,18 @@ void TabStrip::TabChangedAt(TabContents* contents, int index) { } void TabStrip::TabValidateAnimations() { - TimerManager* tm = MessageLoop::current()->timer_manager(); - Timer* timer = loading_animation_timer_.get(); if (model_->TabsAreLoading()) { - if (!tm->IsTimerRunning(timer)) { + if (!loading_animation_timer_.IsRunning()) { // Loads are happening, and the timer isn't running, so start it. - tm->ResetTimer(timer); + loading_animation_timer_.Start( + TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this, + &TabStrip::LoadingAnimationCallback); } } else { - if (tm->IsTimerRunning(timer)) { + if (loading_animation_timer_.IsRunning()) { + loading_animation_timer_.Stop(); // Loads are now complete, update the state if a task was scheduled. LoadingAnimationCallback(); - tm->StopTimer(timer); } } } @@ -1000,15 +996,6 @@ void TabStrip::ButtonPressed(ChromeViews::BaseButton* sender) { } /////////////////////////////////////////////////////////////////////////////// -// TabStrip, Task implementation: - -void TabStrip::Run() { - // Loading Animation frame advancement timer has fired, update all of the - // loading animations as applicable... - LoadingAnimationCallback(); -} - -/////////////////////////////////////////////////////////////////////////////// // TabStrip, MessageLoop::Observer implementation: void TabStrip::WillProcessMessage(const MSG& msg) { @@ -1085,11 +1072,6 @@ void TabStrip::Init() { newtab_button_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_NEWTAB)); AddChildView(newtab_button_); - // Creating the Timer directly instead of using StartTimer() ensures it won't - // actually start running until we use ResetTimer(); - loading_animation_timer_.reset( - new Timer(kLoadingAnimationFrameTimeMs, this, true)); - if (drop_indicator_width == 0) { // Direction doesn't matter, both images are the same size. SkBitmap* drop_image = GetDropArrowImage(true); diff --git a/chrome/browser/tabs/tab_strip.h b/chrome/browser/tabs/tab_strip.h index 9d2ed08..11f6f64 100644 --- a/chrome/browser/tabs/tab_strip.h +++ b/chrome/browser/tabs/tab_strip.h @@ -6,7 +6,6 @@ #define CHROME_BROWSER_TABS_TAB_STRIP_H__ #include "base/gfx/point.h" -#include "base/task.h" #include "chrome/browser/tabs/tab.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/views/button.h" @@ -17,7 +16,6 @@ class DraggedTabController; class ScopedMouseCloseWidthCalculator; class TabStripModel; -class Timer; namespace ChromeViews { class ImageView; @@ -40,7 +38,6 @@ class TabStrip : public ChromeViews::View, public TabStripModelObserver, public Tab::TabDelegate, public ChromeViews::Button::ButtonListener, - public Task, public MessageLoopForUI::Observer { public: TabStrip(TabStripModel* model); @@ -153,9 +150,6 @@ class TabStrip : public ChromeViews::View, // ChromeViews::Button::ButtonListener implementation: virtual void ButtonPressed(ChromeViews::BaseButton* sender); - // Task implementation: - virtual void Run(); - // MessageLoop::Observer implementation: virtual void WillProcessMessage(const MSG& msg); virtual void DidProcessMessage(const MSG& msg); @@ -303,7 +297,7 @@ class TabStrip : public ChromeViews::View, bool resize_layout_scheduled_; // The timer used to update frames for the Loading Animation. - scoped_ptr<Timer> loading_animation_timer_; + base::RepeatingTimer<TabStrip> loading_animation_timer_; // The "New Tab" button. ChromeViews::Button* newtab_button_; diff --git a/chrome/browser/task_manager.cc b/chrome/browser/task_manager.cc index 06c7bbc..7cb75ff 100644 --- a/chrome/browser/task_manager.cc +++ b/chrome/browser/task_manager.cc @@ -7,7 +7,6 @@ #include "base/process_util.h" #include "base/stats_table.h" #include "base/string_util.h" -#include "base/timer.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/render_process_host.h" @@ -44,26 +43,6 @@ static const int kGoatsTeleportedColumn = (94024 * kNuthMagicNumber) & kBitMask; //////////////////////////////////////////////////////////////////////////////// -// TaskManagerUpdateTask class. -// -// Used to periodically updates the task manager contents. -// -//////////////////////////////////////////////////////////////////////////////// - -class TaskManagerUpdateTask : public Task { - public: - explicit TaskManagerUpdateTask(TaskManagerTableModel* model) : model_(model) { - } - void Run() { - if (model_) model_->Refresh(); - } - - private: - TaskManagerTableModel* model_; - DISALLOW_EVIL_CONSTRUCTORS(TaskManagerUpdateTask); -}; - -//////////////////////////////////////////////////////////////////////////////// // TaskManagerTableModel class //////////////////////////////////////////////////////////////////////////////// @@ -72,7 +51,6 @@ int TaskManagerTableModel::goats_teleported_ = 0; TaskManagerTableModel::TaskManagerTableModel(TaskManager* task_manager) : observer_(NULL), - timer_(NULL), ui_loop_(MessageLoop::current()), is_updating_(false) { @@ -88,11 +66,9 @@ TaskManagerTableModel::TaskManagerTableModel(TaskManager* task_manager) new TaskManagerPluginProcessResourceProvider(task_manager); plugin_provider->AddRef(); providers_.push_back(plugin_provider); - update_task_.reset(new TaskManagerUpdateTask(this)); } TaskManagerTableModel::~TaskManagerTableModel() { - DCHECK(timer_ == NULL); for (ResourceProviderList::iterator iter = providers_.begin(); iter != providers_.end(); ++iter) { (*iter)->Release(); @@ -229,9 +205,8 @@ HANDLE TaskManagerTableModel::GetProcessAt(int index) { void TaskManagerTableModel::StartUpdating() { DCHECK(!is_updating_); is_updating_ = true; - DCHECK(timer_ == NULL); - TimerManager* tm = MessageLoop::current()->timer_manager(); - timer_ = tm->StartTimer(kUpdateTimeMs, update_task_.get(), true); + update_timer_.Start(TimeDelta::FromMilliseconds(kUpdateTimeMs), this, + &TaskManagerTableModel::Refresh); // Register jobs notifications so we can compute network usage (it must be // done from the IO thread). @@ -250,9 +225,7 @@ void TaskManagerTableModel::StartUpdating() { void TaskManagerTableModel::StopUpdating() { DCHECK(is_updating_); is_updating_ = false; - MessageLoop::current()->timer_manager()->StopTimer(timer_); - delete timer_; - timer_ = NULL; + update_timer_.Stop(); // Notify resource providers that we are done updating. for (ResourceProviderList::const_iterator iter = providers_.begin(); diff --git a/chrome/browser/task_manager.h b/chrome/browser/task_manager.h index a84917c..9b8687f 100644 --- a/chrome/browser/task_manager.h +++ b/chrome/browser/task_manager.h @@ -8,6 +8,7 @@ #include "base/lock.h" #include "base/singleton.h" #include "base/ref_counted.h" +#include "base/timer.h" #include "chrome/views/dialog_delegate.h" #include "chrome/views/group_table_view.h" #include "chrome/browser/cache_manager_host.h" @@ -25,10 +26,6 @@ class TaskManagerWindow; struct BytesReadParam; -namespace base { -class Timer; -} - namespace ChromeViews { class View; class Window; @@ -263,9 +260,8 @@ class TaskManagerTableModel : public ChromeViews::GroupTableModel, // The timer controlling the updates of the information. The timer is // allocated every time the task manager is shown and deleted when it is // hidden/closed. - base::Timer* timer_; + base::RepeatingTimer<TaskManagerTableModel> update_timer_; - scoped_ptr<Task> update_task_; MessageLoop* ui_loop_; // See design doc at http://go/at-teleporter for more information. diff --git a/chrome/browser/views/constrained_window_impl.cc b/chrome/browser/views/constrained_window_impl.cc index 8c66ad3..86f5677 100644 --- a/chrome/browser/views/constrained_window_impl.cc +++ b/chrome/browser/views/constrained_window_impl.cc @@ -208,8 +208,7 @@ ChromeFont OTRWindowResources::title_font_; class ConstrainedWindowNonClientView : public ChromeViews::NonClientView, public ChromeViews::BaseButton::ButtonListener, - public LocationBarView::Delegate, - public Task { + public LocationBarView::Delegate { public: ConstrainedWindowNonClientView(ConstrainedWindowImpl* container, TabContents* owner); @@ -256,9 +255,6 @@ class ConstrainedWindowNonClientView virtual TabContents* GetTabContents(); virtual void OnInputInProgress(bool in_progress); - // Overridden from Task: - virtual void Run(); - // Updates the current throbber animation frame; called from the // overloaded Run() and from SetShowThrobber(). void UpdateThrobber(); @@ -319,7 +315,7 @@ class ConstrainedWindowNonClientView bool show_throbber_; // The timer used to update frames for the throbber. - scoped_ptr<Timer> throbber_animation_timer_; + base::RepeatingTimer<ConstrainedWindowNonClientView> throbber_timer_; // The current index into the throbber image strip. int current_throbber_frame_; @@ -395,9 +391,6 @@ ConstrainedWindowNonClientView::ConstrainedWindowNonClientView( close_button_->SetListener(this, 0); AddChildView(close_button_); - throbber_animation_timer_.reset( - new Timer(kThrobberFrameTimeMs, this, true)); - // Note: we don't need for a controller because no input event will be ever // processed from a constrained window. location_bar_ = new LocationBarView(owner->profile(), @@ -409,8 +402,6 @@ ConstrainedWindowNonClientView::ConstrainedWindowNonClientView( } ConstrainedWindowNonClientView::~ConstrainedWindowNonClientView() { - MessageLoop::current()->timer_manager()->StopTimer( - throbber_animation_timer_.get()); } void ConstrainedWindowNonClientView::UpdateLocationBar() { @@ -483,25 +474,21 @@ void ConstrainedWindowNonClientView::UpdateWindowTitle() { void ConstrainedWindowNonClientView::SetShowThrobber(bool show_throbber) { show_throbber_ = show_throbber; - TimerManager* tm = MessageLoop::current()->timer_manager(); - Timer* timer = throbber_animation_timer_.get(); if (show_throbber) { - if (!tm->IsTimerRunning(timer)) - tm->ResetTimer(timer); + if (!throbber_timer_.IsRunning()) + throbber_timer_.Start( + TimeDelta::FromMilliseconds(kThrobberFrameTimeMs), this, + &ConstrainedWindowNonClientView::UpdateThrobber); } else { - if (tm->IsTimerRunning(timer)) { + if (throbber_timer_.IsRunning()) { + throbber_timer_.Stop(); UpdateThrobber(); - tm->StopTimer(timer); } } Layout(); } -void ConstrainedWindowNonClientView::Run() { - UpdateThrobber(); -} - //////////////////////////////////////////////////////////////////////////////// // ConstrainedWindowNonClientView, ChromeViews::NonClientView implementation: diff --git a/chrome/browser/views/download_item_view.cc b/chrome/browser/views/download_item_view.cc index 923752e..bde72f2 100644 --- a/chrome/browser/views/download_item_view.cc +++ b/chrome/browser/views/download_item_view.cc @@ -46,8 +46,6 @@ DownloadItemView::DownloadItemView(DownloadItem* download, parent_(parent), model_(model), progress_angle_(download_util::kStartAngleDegrees), - progress_timer_(NULL), - progress_task_(NULL), body_state_(NORMAL), drop_down_state_(NORMAL), drop_down_pressed_(false), @@ -175,24 +173,15 @@ void DownloadItemView::UpdateDownloadProgress() { } void DownloadItemView::StartDownloadProgress() { - if (progress_task_ || progress_timer_) + if (progress_timer_.IsRunning()) return; - progress_task_ = - new download_util::DownloadProgressTask<DownloadItemView>(this); - progress_timer_ = - MessageLoop::current()->timer_manager()-> - StartTimer(download_util::kProgressRateMs, progress_task_, true); + progress_timer_.Start( + TimeDelta::FromMilliseconds(download_util::kProgressRateMs), this, + &DownloadItemView::UpdateDownloadProgress); } void DownloadItemView::StopDownloadProgress() { - if (progress_timer_) { - DCHECK(progress_task_); - MessageLoop::current()->timer_manager()->StopTimer(progress_timer_); - delete progress_timer_; - progress_timer_ = NULL; - delete progress_task_; - progress_task_ = NULL; - } + progress_timer_.Stop(); } // DownloadObserver interface diff --git a/chrome/browser/views/download_item_view.h b/chrome/browser/views/download_item_view.h index 619c5ea..ab42fd5 100644 --- a/chrome/browser/views/download_item_view.h +++ b/chrome/browser/views/download_item_view.h @@ -20,6 +20,7 @@ #include "base/basictypes.h" #include "base/scoped_ptr.h" +#include "base/timer.h" #include "chrome/common/slide_animation.h" #include "chrome/browser/cancelable_request.h" #include "chrome/browser/download_manager.h" @@ -30,8 +31,6 @@ class DownloadShelfView; class SkBitmap; -class Task; -class Timer; class DownloadItemView : public ChromeViews::View, public DownloadItem::Observer, @@ -188,8 +187,7 @@ class DownloadItemView : public ChromeViews::View, scoped_ptr<SlideAnimation> complete_animation_; // Progress animation - Timer* progress_timer_; - Task* progress_task_; + base::RepeatingTimer<DownloadItemView> progress_timer_; DISALLOW_EVIL_CONSTRUCTORS(DownloadItemView); }; diff --git a/chrome/views/chrome_menu.cc b/chrome/views/chrome_menu.cc index a1f9306..360f6c1 100644 --- a/chrome/views/chrome_menu.cc +++ b/chrome/views/chrome_menu.cc @@ -181,36 +181,16 @@ static void ScrollToVisible(View* view) { // MenuScrollTask -------------------------------------------------------------- // MenuScrollTask is used when the SubmenuView does not all fit on screen and -// the mouse is over the scroll up/down buttons. MenuScrollTask schedules itself -// with the TimerManager. When Run is invoked MenuScrollTask scrolls +// the mouse is over the scroll up/down buttons. MenuScrollTask schedules +// itself with a RepeatingTimer. When Run is invoked MenuScrollTask scrolls // appropriately. -class MenuScrollTask : public Task { +class MenuScrollTask { public: MenuScrollTask() : submenu_(NULL) { pixels_per_second_ = pref_menu_height * 20; } - virtual ~MenuScrollTask() { - StopScrolling(); - } - - virtual void Run() { - DCHECK(submenu_); - gfx::Rect vis_rect = submenu_->GetVisibleBounds(); - const int delta_y = static_cast<int>( - (Time::Now() - start_scroll_time_).InMilliseconds() * - pixels_per_second_ / 1000); - int target_y = start_y_; - if (is_scrolling_up_) - target_y = std::max(0, target_y - delta_y); - else - target_y = std::min(submenu_->GetHeight() - vis_rect.height(), - target_y + delta_y); - submenu_->ScrollRectToVisible(vis_rect.x(), target_y, vis_rect.width(), - vis_rect.height()); - } - void Update(const MenuController::MenuPart& part) { if (!part.is_scroll()) { StopScrolling(); @@ -227,18 +207,15 @@ public: submenu_ = new_menu; is_scrolling_up_ = new_is_up; - if (!scrolling_timer_.get()) { - scrolling_timer_.reset(new Timer(kScrollTimerMS, this, true)); - TimerManager* tm = MessageLoop::current()->timer_manager(); - tm->StartTimer(scrolling_timer_.get()); + if (!scrolling_timer_.IsRunning()) { + scrolling_timer_.Start(TimeDelta::FromMilliseconds(kScrollTimerMS), this, + &MenuScrollTask::Run); } } void StopScrolling() { - if (scrolling_timer_.get()) { - TimerManager* tm = MessageLoop::current()->timer_manager(); - tm->StopTimer(scrolling_timer_.get()); - scrolling_timer_.reset(NULL); + if (scrolling_timer_.IsRunning()) { + scrolling_timer_.Stop(); submenu_ = NULL; } } @@ -247,6 +224,22 @@ public: SubmenuView* submenu() const { return submenu_; } private: + void Run() { + DCHECK(submenu_); + gfx::Rect vis_rect = submenu_->GetVisibleBounds(); + const int delta_y = static_cast<int>( + (Time::Now() - start_scroll_time_).InMilliseconds() * + pixels_per_second_ / 1000); + int target_y = start_y_; + if (is_scrolling_up_) + target_y = std::max(0, target_y - delta_y); + else + target_y = std::min(submenu_->GetHeight() - vis_rect.height(), + target_y + delta_y); + submenu_->ScrollRectToVisible(vis_rect.x(), target_y, vis_rect.width(), + vis_rect.height()); + } + // SubmenuView being scrolled. SubmenuView* submenu_; @@ -254,7 +247,7 @@ public: bool is_scrolling_up_; // Timer to periodically scroll. - scoped_ptr<Timer> scrolling_timer_; + base::RepeatingTimer<MenuScrollTask> scrolling_timer_; // Time we started scrolling at. Time start_scroll_time_; @@ -2088,13 +2081,7 @@ MenuController::MenuController(bool blocking) showing_(false), exit_all_(false), did_capture_(false), -#pragma warning(suppress: 4355) // Okay to pass "this" here. - show_task_(this), result_(NULL), - show_timer_(NULL), -#pragma warning(suppress: 4355) // Okay to pass "this" here. - cancel_all_task_(this), - cancel_all_timer_(NULL), drop_target_(NULL), owner_(NULL), possible_drag_(false), @@ -2384,31 +2371,21 @@ void MenuController::BuildMenuItemPath(MenuItemView* item, } void MenuController::StartShowTimer() { - StopShowTimer(); - show_timer_ = MessageLoop::current()->timer_manager()-> - StartTimer(kShowDelay, &show_task_, false); + show_timer_.Start(TimeDelta::FromMilliseconds(kShowDelay), this, + &MenuController::CommitPendingSelection); } void MenuController::StopShowTimer() { - if (show_timer_) { - MessageLoop::current()->timer_manager()->StopTimer(show_timer_); - delete show_timer_; - show_timer_ = NULL; - } + show_timer_.Stop(); } void MenuController::StartCancelAllTimer() { - StopCancelAllTimer(); - cancel_all_timer_ = MessageLoop::current()->timer_manager()-> - StartTimer(kCloseOnExitTime, &cancel_all_task_, false); + cancel_all_timer_.Start(TimeDelta::FromMilliseconds(kCloseOnExitTime), + this, &MenuController::CancelAll); } void MenuController::StopCancelAllTimer() { - if (cancel_all_timer_) { - MessageLoop::current()->timer_manager()->StopTimer(cancel_all_timer_); - delete cancel_all_timer_; - cancel_all_timer_ = NULL; - } + cancel_all_timer_.Stop(); } gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item, diff --git a/chrome/views/chrome_menu.h b/chrome/views/chrome_menu.h index 1377155..a017b3d 100644 --- a/chrome/views/chrome_menu.h +++ b/chrome/views/chrome_menu.h @@ -17,8 +17,6 @@ #include "chrome/views/view.h" #include "skia/include/SkBitmap.h" -class Timer; - namespace ChromeViews { class HWNDViewContainer; @@ -595,7 +593,6 @@ class MenuController : public MessageLoopForUI::Dispatcher { public: friend class MenuHostRootView; friend class MenuItemView; - friend class ShowSubmenusTask; friend class MenuScrollTask; // If a menu is currently active, this returns the controller for it. @@ -629,6 +626,9 @@ class MenuController : public MessageLoopForUI::Dispatcher { // as well. This immediatley hides all menus. void Cancel(bool all); + // An alternative to Cancel(true) that can be used with a OneShotTimer. + void CancelAll() { return Cancel(true); } + // Various events, forwarded from the submenu. // // NOTE: the coordinates of the events are in that of the @@ -649,42 +649,6 @@ class MenuController : public MessageLoopForUI::Dispatcher { void OnDragExitedScrollButton(SubmenuView* source); private: - // As the mouse moves around submenus are not opened immediately. Instead - // they open after this timer fires. - class ShowSubmenusTask : public Task { - public: - explicit ShowSubmenusTask(MenuController* controller) - : controller_(controller) {} - - virtual void Run() { - controller_->CommitPendingSelection(); - } - - private: - MenuController* controller_; - - DISALLOW_EVIL_CONSTRUCTORS(ShowSubmenusTask); - }; - - // Task used to invoke Cancel(true). This is used during drag and drop - // to hide the menu after the mouse moves out of the of the menu. This is - // necessitated by the lack of an ability to detect when the drag has - // completed from the drop side. - class CancelAllTask : public Task { - public: - explicit CancelAllTask(MenuController* controller) - : controller_(controller) {} - - virtual void Run() { - controller_->Cancel(true); - } - - private: - MenuController* controller_; - - DISALLOW_EVIL_CONSTRUCTORS(CancelAllTask); - }; - // Tracks selection information. struct State { State() : item(NULL), submenu_open(false) {} @@ -914,13 +878,15 @@ class MenuController : public MessageLoopForUI::Dispatcher { // MenuController to restore the state when the nested run returns. std::list<State> menu_stack_; - // Used to comming pending to state. - ShowSubmenusTask show_task_; - Timer* show_timer_; + // As the mouse moves around submenus are not opened immediately. Instead + // they open after this timer fires. + base::OneShotTimer<MenuController> show_timer_; - // Used to cancel all menus. - CancelAllTask cancel_all_task_; - Timer* cancel_all_timer_; + // Used to invoke CancelAll(). This is used during drag and drop to hide the + // menu after the mouse moves out of the of the menu. This is necessitated by + // the lack of an ability to detect when the drag has completed from the drop + // side. + base::OneShotTimer<MenuController> cancel_all_timer_; // Drop target. MenuItemView* drop_target_; diff --git a/chrome/views/repeat_controller.cc b/chrome/views/repeat_controller.cc index cf41dea..96aa923 100644 --- a/chrome/views/repeat_controller.cc +++ b/chrome/views/repeat_controller.cc @@ -15,45 +15,29 @@ static const int kRepeatDelay = 50; // RepeatController, public: RepeatController::RepeatController(RepeatCallback* callback) - : timer_(NULL), - callback_(callback) { + : callback_(callback) { } RepeatController::~RepeatController() { - DestroyTimer(); } void RepeatController::Start() { - DCHECK(!timer_); // The first timer is slightly longer than subsequent repeats. - timer_ = MessageLoop::current()->timer_manager()->StartTimer( - kInitialRepeatDelay, this, false); + timer_.Start(TimeDelta::FromMilliseconds(kInitialRepeatDelay), this, + &RepeatController::Run); } void RepeatController::Stop() { - DestroyTimer(); -} - -void RepeatController::Run() { - DestroyTimer(); - - // TODO(beng): (Cleanup) change this to just Run() when base rolls forward. - callback_->RunWithParams(Tuple0()); - timer_ = MessageLoop::current()->timer_manager()->StartTimer( - kRepeatDelay, this, true); + timer_.Stop(); } /////////////////////////////////////////////////////////////////////////////// // RepeatController, private: -void RepeatController::DestroyTimer() { - if (!timer_) - return; - - MessageLoop::current()->timer_manager()->StopTimer(timer_); - delete timer_; - timer_ = NULL; -} - +void RepeatController::Run() { + timer_.Start(TimeDelta::FromMilliseconds(kRepeatDelay), this, + &RepeatController::Run); + callback_->Run(); } +} // namespace ChromeViews diff --git a/chrome/views/repeat_controller.h b/chrome/views/repeat_controller.h index 69c539a..92434f6 100644 --- a/chrome/views/repeat_controller.h +++ b/chrome/views/repeat_controller.h @@ -2,11 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_VIEWS_REPEAT_CONTROLLER_H__ -#define CHROME_VIEWS_REPEAT_CONTROLLER_H__ +#ifndef CHROME_VIEWS_REPEAT_CONTROLLER_H_ +#define CHROME_VIEWS_REPEAT_CONTROLLER_H_ -#include "base/message_loop.h" -#include "base/task.h" +#include "base/timer.h" namespace ChromeViews { @@ -20,7 +19,7 @@ namespace ChromeViews { // associated action. // /////////////////////////////////////////////////////////////////////////////// -class RepeatController : public Task { +class RepeatController { public: typedef Callback0::Type RepeatCallback; @@ -34,24 +33,20 @@ class RepeatController : public Task { // Stop repeating. void Stop(); - // Task implementation: - void Run(); - private: RepeatController(); - // Stop and delete the timer. - void DestroyTimer(); + // Called when the timer expires. + void Run(); // The current timer. - Timer* timer_; + base::OneShotTimer<RepeatController> timer_; scoped_ptr<RepeatCallback> callback_; - DISALLOW_EVIL_CONSTRUCTORS(RepeatController); + DISALLOW_COPY_AND_ASSIGN(RepeatController); }; -} - -#endif // #ifndef CHROME_VIEWS_REPEAT_CONTROLLER_H__ +} // namespace ChromeViews +#endif // #ifndef CHROME_VIEWS_REPEAT_CONTROLLER_H_ diff --git a/chrome/views/throbber.cc b/chrome/views/throbber.cc index 6697d80..eee8a02 100644 --- a/chrome/views/throbber.cc +++ b/chrome/views/throbber.cc @@ -4,8 +4,6 @@ #include "chrome/views/throbber.h" -#include "base/message_loop.h" -#include "base/timer.h" #include "chrome/app/theme/theme_resources.h" #include "chrome/common/gfx/chrome_canvas.h" #include "chrome/common/logging_chrome.h" @@ -40,8 +38,8 @@ void Throbber::Start() { start_time_ = GetTickCount(); last_time_recorded_ = start_time_; - timer_ = MessageLoop::current()->timer_manager()->StartTimer( - frame_time_ms_ - 10, this, true); + timer_.Start( + TimeDelta::FromMilliseconds(frame_time_ms_ - 10), this, &Throbber::Run); running_ = true; @@ -52,8 +50,7 @@ void Throbber::Stop() { if (!running_) return; - MessageLoop::current()->timer_manager()->StopTimer(timer_); - timer_ = NULL; + timer_.Stop(); running_ = false; SchedulePaint(); // Important if we're not painting while stopped @@ -111,19 +108,15 @@ static const int kStopDelay = 50; SmoothedThrobber::SmoothedThrobber(int frame_time_ms) - : Throbber(frame_time_ms, /* paint_while_stopped= */ false), - start_delay_factory_(this), - end_delay_factory_(this) { + : Throbber(frame_time_ms, /* paint_while_stopped= */ false) { } void SmoothedThrobber::Start() { - end_delay_factory_.RevokeAll(); + stop_timer_.Stop(); - if (!running_ && start_delay_factory_.empty()) { - MessageLoop::current()->PostDelayedTask(FROM_HERE, - start_delay_factory_.NewRunnableMethod( - &SmoothedThrobber::StartDelayOver), - kStartDelay); + if (!running_ && !start_timer_.IsRunning()) { + start_timer_.Start(TimeDelta::FromMilliseconds(kStartDelay), this, + &SmoothedThrobber::StartDelayOver); } } @@ -132,15 +125,12 @@ void SmoothedThrobber::StartDelayOver() { } void SmoothedThrobber::Stop() { - TimerManager* timer_manager = MessageLoop::current()->timer_manager(); - if (!running_) - start_delay_factory_.RevokeAll(); + start_timer_.Stop(); - end_delay_factory_.RevokeAll(); - MessageLoop::current()->PostDelayedTask(FROM_HERE, - end_delay_factory_.NewRunnableMethod(&SmoothedThrobber::StopDelayOver), - kStopDelay); + stop_timer_.Stop(); + stop_timer_.Start(TimeDelta::FromMilliseconds(kStopDelay), this, + &SmoothedThrobber::StopDelayOver); } void SmoothedThrobber::StopDelayOver() { diff --git a/chrome/views/throbber.h b/chrome/views/throbber.h index 812cae1..3c42fde 100644 --- a/chrome/views/throbber.h +++ b/chrome/views/throbber.h @@ -8,19 +8,14 @@ #define CHROME_VIEWS_THROBBER_H__ #include "base/basictypes.h" -#include "base/task.h" +#include "base/timer.h" #include "chrome/views/view.h" class SkBitmap; -namespace base { -class Timer; -} - namespace ChromeViews { -class Throbber : public ChromeViews::View, - public Task { +class Throbber : public ChromeViews::View { public: // |frame_time_ms| is the amount of time that should elapse between frames // (in milliseconds) @@ -37,14 +32,13 @@ class Throbber : public ChromeViews::View, virtual void GetPreferredSize(CSize *out); virtual void Paint(ChromeCanvas* canvas); - // implemented from Task - virtual void Run(); - protected: // Specifies whether the throbber is currently animating or not bool running_; private: + void Run(); + bool paint_while_stopped_; int frame_count_; int last_frame_drawn_; @@ -52,7 +46,7 @@ class Throbber : public ChromeViews::View, DWORD last_time_recorded_; SkBitmap* frames_; int frame_time_ms_; - base::Timer* timer_; + base::RepeatingTimer<Throbber> timer_; DISALLOW_EVIL_CONSTRUCTORS(Throbber); }; @@ -77,10 +71,8 @@ class SmoothedThrobber : public Throbber { // This function stops the actual throbbing. void StopDelayOver(); - // Method factory for delaying throbber startup. - ScopedRunnableMethodFactory<SmoothedThrobber> start_delay_factory_; - // Method factory for delaying throbber shutdown. - ScopedRunnableMethodFactory<SmoothedThrobber> end_delay_factory_; + base::OneShotTimer<SmoothedThrobber> start_timer_; + base::OneShotTimer<SmoothedThrobber> stop_timer_; DISALLOW_EVIL_CONSTRUCTORS(SmoothedThrobber); }; diff --git a/net/disk_cache/disk_cache_test_util.cc b/net/disk_cache/disk_cache_test_util.cc index 98bd092..d82cbb4 100644 --- a/net/disk_cache/disk_cache_test_util.cc +++ b/net/disk_cache/disk_cache_test_util.cc @@ -96,9 +96,28 @@ void CallbackTest::RunWithParams(const Tuple1<int>& params) { // ----------------------------------------------------------------------- +MessageLoopHelper::MessageLoopHelper() + : num_callbacks_(0), + num_iterations_(0), + last_(0), + completed_(false) { + // Create a recurrent timer of 50 mS. + timer_.Start( + TimeDelta::FromMilliseconds(50), this, &MessageLoopHelper::TimerExpired); +} + +bool MessageLoopHelper::WaitUntilCacheIoFinished(int num_callbacks) { + if (num_callbacks == g_cache_tests_received) + return true; + + ExpectCallbacks(num_callbacks); + MessageLoop::current()->Run(); + return completed_; +} + // Quits the message loop when all callbacks are called or we've been waiting // too long for them (2 secs without a callback). -void TimerTask::Run() { +void MessageLoopHelper::TimerExpired() { if (g_cache_tests_received > num_callbacks_) { NOTREACHED(); } else if (g_cache_tests_received == num_callbacks_) { @@ -114,27 +133,3 @@ void TimerTask::Run() { MessageLoop::current()->Quit(); } } - -// ----------------------------------------------------------------------- - -MessageLoopHelper::MessageLoopHelper() { - message_loop_ = MessageLoop::current(); - // Create a recurrent timer of 50 mS. - timer_ = message_loop_->timer_manager()->StartTimer(50, &timer_task_, true); -} - -MessageLoopHelper::~MessageLoopHelper() { - message_loop_->timer_manager()->StopTimer(timer_); - delete timer_; -} - -bool MessageLoopHelper::WaitUntilCacheIoFinished(int num_callbacks) { - if (num_callbacks == g_cache_tests_received) - return true; - - timer_task_.ExpectCallbacks(num_callbacks); - message_loop_->Run(); - return timer_task_.GetSate(); -} - - diff --git a/net/disk_cache/disk_cache_test_util.h b/net/disk_cache/disk_cache_test_util.h index 3b5c9ef8..4277d02 100644 --- a/net/disk_cache/disk_cache_test_util.h +++ b/net/disk_cache/disk_cache_test_util.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef NET_DISK_CACHE_DISK_CACHE_TEST_UTIL_H__ -#define NET_DISK_CACHE_DISK_CACHE_TEST_UTIL_H__ +#ifndef NET_DISK_CACHE_DISK_CACHE_TEST_UTIL_H_ +#define NET_DISK_CACHE_DISK_CACHE_TEST_UTIL_H_ #include <string> @@ -46,20 +46,21 @@ class CallbackTest : public CallbackRunner< Tuple1<int> > { private: int id_; int reuse_; - DISALLOW_EVIL_CONSTRUCTORS(CallbackTest); + DISALLOW_COPY_AND_ASSIGN(CallbackTest); }; // ----------------------------------------------------------------------- -// We'll use a timer to fire from time to time to check the number of IO -// operations finished so far. -class TimerTask : public Task { +// Simple helper to deal with the message loop on a test. +class MessageLoopHelper { public: - TimerTask() : num_callbacks_(0), num_iterations_(0) {} - ~TimerTask() {} + MessageLoopHelper(); - virtual void Run(); + // Run the message loop and wait for num_callbacks before returning. Returns + // false if we are waiting to long. + bool WaitUntilCacheIoFinished(int num_callbacks); + private: // Sets the number of callbacks that can be received so far. void ExpectCallbacks(int num_callbacks) { num_callbacks_ = num_callbacks; @@ -67,37 +68,16 @@ class TimerTask : public Task { completed_ = false; } - // Returns true if all callbacks were invoked. - bool GetSate() { - return completed_; - } + // Called periodically to test if WaitUntilCacheIoFinished should return. + void TimerExpired(); - private: + base::RepeatingTimer<MessageLoopHelper> timer_; int num_callbacks_; int num_iterations_; int last_; bool completed_; - DISALLOW_EVIL_CONSTRUCTORS(TimerTask); -}; - -// ----------------------------------------------------------------------- -// Simple helper to deal with the message loop on a test. -class MessageLoopHelper { - public: - MessageLoopHelper(); - ~MessageLoopHelper(); - - // Run the message loop and wait for num_callbacks before returning. Returns - // false if we are waiting to long. - bool WaitUntilCacheIoFinished(int num_callbacks); - - private: - MessageLoop* message_loop_; - Timer* timer_; - TimerTask timer_task_; - DISALLOW_EVIL_CONSTRUCTORS(MessageLoopHelper); + DISALLOW_COPY_AND_ASSIGN(MessageLoopHelper); }; -#endif // NET_DISK_CACHE_DISK_CACHE_TEST_UTIL_H__ - +#endif // NET_DISK_CACHE_DISK_CACHE_TEST_UTIL_H_ |