blob: 9a980642541482e804ae28254b8c1645fbdd3add [file] [log] [blame]
[email protected]b2e97292008-09-02 18:20:341// 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.
4
5#include "base/message_pump_default.h"
6
7#include "base/logging.h"
[email protected]badf5cf2011-10-29 03:44:448
9#if defined(OS_MACOSX)
[email protected]c2818d42010-10-18 02:47:3910#include "base/mac/scoped_nsautorelease_pool.h"
[email protected]badf5cf2011-10-29 03:44:4411#endif
[email protected]b2e97292008-09-02 18:20:3412
13namespace base {
14
15MessagePumpDefault::MessagePumpDefault()
16 : keep_running_(true),
17 event_(false, false) {
18}
19
20void MessagePumpDefault::Run(Delegate* delegate) {
21 DCHECK(keep_running_) << "Quit must have been called outside of Run!";
22
23 for (;;) {
[email protected]badf5cf2011-10-29 03:44:4424#if defined(OS_MACOSX)
[email protected]c2818d42010-10-18 02:47:3925 mac::ScopedNSAutoreleasePool autorelease_pool;
[email protected]badf5cf2011-10-29 03:44:4426#endif
[email protected]89836e22008-09-25 20:33:4227
[email protected]b2e97292008-09-02 18:20:3428 bool did_work = delegate->DoWork();
29 if (!keep_running_)
30 break;
31
32 did_work |= delegate->DoDelayedWork(&delayed_work_time_);
33 if (!keep_running_)
34 break;
35
36 if (did_work)
37 continue;
38
39 did_work = delegate->DoIdleWork();
40 if (!keep_running_)
41 break;
42
43 if (did_work)
44 continue;
45
46 if (delayed_work_time_.is_null()) {
47 event_.Wait();
48 } else {
[email protected]7e7fab42010-11-06 22:23:2949 TimeDelta delay = delayed_work_time_ - TimeTicks::Now();
[email protected]b2e97292008-09-02 18:20:3450 if (delay > TimeDelta()) {
51 event_.TimedWait(delay);
52 } else {
53 // It looks like delayed_work_time_ indicates a time in the past, so we
54 // need to call DoDelayedWork now.
[email protected]7e7fab42010-11-06 22:23:2955 delayed_work_time_ = TimeTicks();
[email protected]b2e97292008-09-02 18:20:3456 }
57 }
58 // Since event_ is auto-reset, we don't need to do anything special here
59 // other than service each delegate method.
60 }
61
62 keep_running_ = true;
63}
64
65void MessagePumpDefault::Quit() {
66 keep_running_ = false;
67}
68
69void MessagePumpDefault::ScheduleWork() {
70 // Since this can be called on any thread, we need to ensure that our Run
71 // loop wakes up.
72 event_.Signal();
73}
74
[email protected]7e7fab42010-11-06 22:23:2975void MessagePumpDefault::ScheduleDelayedWork(
76 const TimeTicks& delayed_work_time) {
[email protected]b2e97292008-09-02 18:20:3477 // We know that we can't be blocked on Wait right now since this method can
78 // only be called on the same thread as Run, so we only need to update our
79 // record of how long to sleep when we do sleep.
80 delayed_work_time_ = delayed_work_time;
81}
82
83} // namespace base