blob: 64913e575badc303a16ae823e4138052a6fe7b41 [file] [log] [blame]
sky@chromium.orgf881d882009-04-11 00:09:39 +09001// Copyright (c) 2009 The Chromium Authors. All rights reserved.
license.botf003cfe2008-08-24 09:55:55 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
darin@google.com6ddeb842008-08-15 16:31:20 +09005#include "base/message_loop.h"
6
darin@google.com981f3552008-08-16 12:09:05 +09007#include <algorithm>
8
mmentovai@google.comfa5f9932008-08-22 07:26:06 +09009#include "base/compiler_specific.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090010#include "base/lazy_instance.h"
initial.commit3f4a7322008-07-27 06:49:38 +090011#include "base/logging.h"
darin@google.com12d40bb2008-08-20 03:36:23 +090012#include "base/message_pump_default.h"
initial.commit3f4a7322008-07-27 06:49:38 +090013#include "base/string_util.h"
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090014#include "base/thread_local.h"
initial.commit3f4a7322008-07-27 06:49:38 +090015
mark@chromium.org059d0492008-09-24 06:08:28 +090016#if defined(OS_MACOSX)
17#include "base/message_pump_mac.h"
18#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090019#if defined(OS_POSIX)
20#include "base/message_pump_libevent.h"
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +090021#include "base/third_party/valgrind/valgrind.h"
dkegel@google.com9e044ae2008-09-19 03:46:26 +090022#endif
sky@chromium.org3f8b9492009-04-28 03:17:24 +090023#if defined(OS_LINUX)
dsh@google.com119a2522008-10-04 01:52:59 +090024#include "base/message_pump_glib.h"
25#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090026
dsh@google.com0f8dd262008-10-28 05:43:33 +090027using base::Time;
28using base::TimeDelta;
29
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090030// A lazily created thread local storage for quick access to a thread's message
31// loop, if one exists. This should be safe and free of static constructors.
32static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
33 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090034
35//------------------------------------------------------------------------------
36
initial.commit3f4a7322008-07-27 06:49:38 +090037// Logical events for Histogram profiling. Run with -message-loop-histogrammer
38// to get an accounting of messages and actions taken on each thread.
darin@google.com981f3552008-08-16 12:09:05 +090039static const int kTaskRunEvent = 0x1;
40static const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090041
42// Provide range of message IDs for use in histogramming and debug display.
43static const int kLeastNonZeroMessageId = 1;
44static const int kMaxMessageId = 1099;
45static const int kNumberOfDistinctMessagesDisplayed = 1100;
46
47//------------------------------------------------------------------------------
48
darin@google.com981f3552008-08-16 12:09:05 +090049#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090050
initial.commit3f4a7322008-07-27 06:49:38 +090051// Upon a SEH exception in this thread, it restores the original unhandled
52// exception filter.
53static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
54 ::SetUnhandledExceptionFilter(old_filter);
55 return EXCEPTION_CONTINUE_SEARCH;
56}
57
58// Retrieves a pointer to the current unhandled exception filter. There
59// is no standalone getter method.
60static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
61 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
62 top_filter = ::SetUnhandledExceptionFilter(0);
63 ::SetUnhandledExceptionFilter(top_filter);
64 return top_filter;
65}
66
darin@google.com981f3552008-08-16 12:09:05 +090067#endif // defined(OS_WIN)
68
initial.commit3f4a7322008-07-27 06:49:38 +090069//------------------------------------------------------------------------------
70
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090071// static
72MessageLoop* MessageLoop::current() {
73 // TODO(darin): sadly, we cannot enable this yet since people call us even
74 // when they have no intention of using us.
75 //DCHECK(loop) << "Ouch, did you forget to initialize me?";
76 return lazy_tls_ptr.Pointer()->Get();
77}
78
darin@google.comd936b5b2008-08-26 14:53:57 +090079MessageLoop::MessageLoop(Type type)
80 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +090081 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +090082 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +090083 state_(NULL),
84 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090085 DCHECK(!current()) << "should only have one message loop per thread";
86 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +090087
darin@google.com981f3552008-08-16 12:09:05 +090088#if defined(OS_WIN)
rvargas@google.com670c3122008-09-26 05:33:04 +090089 // TODO(rvargas): Get rid of the OS guards.
darin@google.com0795f572008-08-30 09:22:48 +090090 if (type_ == TYPE_DEFAULT) {
91 pump_ = new base::MessagePumpDefault();
rvargas@google.com670c3122008-09-26 05:33:04 +090092 } else if (type_ == TYPE_IO) {
93 pump_ = new base::MessagePumpForIO();
darin@google.com0795f572008-08-30 09:22:48 +090094 } else {
rvargas@google.com670c3122008-09-26 05:33:04 +090095 DCHECK(type_ == TYPE_UI);
96 pump_ = new base::MessagePumpForUI();
darin@google.com0795f572008-08-30 09:22:48 +090097 }
dkegel@google.com9e044ae2008-09-19 03:46:26 +090098#elif defined(OS_POSIX)
mark@chromium.org059d0492008-09-24 06:08:28 +090099 if (type_ == TYPE_UI) {
dsh@google.com119a2522008-10-04 01:52:59 +0900100#if defined(OS_MACOSX)
mark@chromium.org059d0492008-09-24 06:08:28 +0900101 pump_ = base::MessagePumpMac::Create();
dsh@google.com119a2522008-10-04 01:52:59 +0900102#elif defined(OS_LINUX)
103 pump_ = new base::MessagePumpForUI();
104#endif // OS_LINUX
105 } else if (type_ == TYPE_IO) {
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900106 pump_ = new base::MessagePumpLibevent();
107 } else {
108 pump_ = new base::MessagePumpDefault();
109 }
mark@chromium.org059d0492008-09-24 06:08:28 +0900110#endif // OS_POSIX
initial.commit3f4a7322008-07-27 06:49:38 +0900111}
112
113MessageLoop::~MessageLoop() {
114 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900115
116 // Let interested parties have one last shot at accessing this.
117 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
118 WillDestroyCurrentMessageLoop());
119
darin@google.com0e500502008-09-09 14:55:35 +0900120 DCHECK(!state_);
121
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900122 // Clean up any unprocessed tasks, but take care: deleting a task could
123 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
124 // limit on the number of times we will allow a deleted task to generate more
125 // tasks. Normally, we should only pass through this loop once or twice. If
126 // we end up hitting the loop limit, then it is probably due to one task that
127 // is being stubborn. Inspect the queues to see who is left.
128 bool did_work;
129 for (int i = 0; i < 100; ++i) {
130 DeletePendingTasks();
131 ReloadWorkQueue();
132 // If we end up with empty queues, then break out of the loop.
133 did_work = DeletePendingTasks();
134 if (!did_work)
135 break;
darin@google.com0e500502008-09-09 14:55:35 +0900136 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900137 DCHECK(!did_work);
138
139 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900140 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900141}
142
darin@google.com965e5342008-08-06 08:16:41 +0900143void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
144 DCHECK(this == current());
145 destruction_observers_.AddObserver(obs);
146}
147
148void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
149 DCHECK(this == current());
150 destruction_observers_.RemoveObserver(obs);
151}
152
darin@google.com6ddeb842008-08-15 16:31:20 +0900153void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900154 AutoRunState save_state(this);
155 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900156}
157
jar@google.com9239e022008-07-31 22:10:20 +0900158void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900159 AutoRunState save_state(this);
160 state_->quit_received = true; // Means run until we would otherwise block.
161 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900162}
163
164// Runs the loop in two different SEH modes:
165// enable_SEH_restoration_ = false : any unhandled exception goes to the last
166// one that calls SetUnhandledExceptionFilter().
167// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
168// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900169void MessageLoop::RunHandler() {
170#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900171 if (exception_restoration_) {
stoyan@google.com283facb2009-10-27 03:15:59 +0900172 RunInternalInSEHFrame();
darin@google.com981f3552008-08-16 12:09:05 +0900173 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900174 }
darin@google.com981f3552008-08-16 12:09:05 +0900175#endif
176
177 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900178}
stoyan@google.com283facb2009-10-27 03:15:59 +0900179//------------------------------------------------------------------------------
180#if defined(OS_WIN)
181__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
182 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
183 __try {
184 RunInternal();
185 } __except(SEHFilter(current_filter)) {
186 }
187 return;
188}
189#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900190//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900191
darin@google.com981f3552008-08-16 12:09:05 +0900192void MessageLoop::RunInternal() {
193 DCHECK(this == current());
194
initial.commit3f4a7322008-07-27 06:49:38 +0900195 StartHistogrammer();
196
jcampan@chromium.org05423582009-08-01 07:53:37 +0900197#if defined(OS_WIN) || defined(OS_LINUX)
198 if (state_->dispatcher && type() == TYPE_UI) {
199 static_cast<base::MessagePumpForUI*>(pump_.get())->
200 RunWithDispatcher(this, state_->dispatcher);
darin@google.com981f3552008-08-16 12:09:05 +0900201 return;
jar@google.com9239e022008-07-31 22:10:20 +0900202 }
darin@google.com981f3552008-08-16 12:09:05 +0900203#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900204
darin@google.com981f3552008-08-16 12:09:05 +0900205 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900206}
jar@google.com7ff36e62008-07-30 15:58:56 +0900207
jar@google.comb4d1bff2008-07-31 04:03:59 +0900208//------------------------------------------------------------------------------
209// Wrapper functions for use in above message loop framework.
210
initial.commit3f4a7322008-07-27 06:49:38 +0900211bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900212 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900213 return false;
214
darin@google.combe165ae2008-09-07 17:08:29 +0900215 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900216 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900217
darin@google.combe165ae2008-09-07 17:08:29 +0900218 Task* task = deferred_non_nestable_work_queue_.front().task;
219 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900220
darin@google.combe165ae2008-09-07 17:08:29 +0900221 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900222 return true;
223}
224
initial.commit3f4a7322008-07-27 06:49:38 +0900225//------------------------------------------------------------------------------
226
227void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900228 DCHECK(current() == this);
229 if (state_) {
230 state_->quit_received = true;
231 } else {
232 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900233 }
initial.commit3f4a7322008-07-27 06:49:38 +0900234}
235
darin@google.combe165ae2008-09-07 17:08:29 +0900236void MessageLoop::PostTask(
237 const tracked_objects::Location& from_here, Task* task) {
238 PostTask_Helper(from_here, task, 0, true);
239}
240
241void MessageLoop::PostDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900242 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900243 PostTask_Helper(from_here, task, delay_ms, true);
244}
245
246void MessageLoop::PostNonNestableTask(
247 const tracked_objects::Location& from_here, Task* task) {
248 PostTask_Helper(from_here, task, 0, false);
249}
250
251void MessageLoop::PostNonNestableDelayedTask(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900252 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
darin@google.combe165ae2008-09-07 17:08:29 +0900253 PostTask_Helper(from_here, task, delay_ms, false);
254}
255
initial.commit3f4a7322008-07-27 06:49:38 +0900256// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900257void MessageLoop::PostTask_Helper(
phajdan.jr@chromium.orgc3c92252009-06-18 02:23:51 +0900258 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
darin@google.combe165ae2008-09-07 17:08:29 +0900259 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900260 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900261
darin@google.combe165ae2008-09-07 17:08:29 +0900262 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900263
264 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900265 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900266 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
267 } else {
268 DCHECK(delay_ms == 0) << "delay should not be negative";
269 }
270
initial.commit3f4a7322008-07-27 06:49:38 +0900271 // Warning: Don't try to short-circuit, and handle this thread's tasks more
272 // directly, as it could starve handling of foreign threads. Put every task
273 // into this queue.
274
darin@google.com981f3552008-08-16 12:09:05 +0900275 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900276 {
darin@google.com981f3552008-08-16 12:09:05 +0900277 AutoLock locked(incoming_queue_lock_);
278
darin@google.combe165ae2008-09-07 17:08:29 +0900279 bool was_empty = incoming_queue_.empty();
280 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900281 if (!was_empty)
282 return; // Someone else should have started the sub-pump.
283
darin@google.com981f3552008-08-16 12:09:05 +0900284 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900285 }
darin@google.com981f3552008-08-16 12:09:05 +0900286 // Since the incoming_queue_ may contain a task that destroys this message
287 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
288 // We use a stack-based reference to the message pump so that we can call
289 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900290
darin@google.com981f3552008-08-16 12:09:05 +0900291 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900292}
293
294void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900295 if (nestable_tasks_allowed_ != allowed) {
296 nestable_tasks_allowed_ = allowed;
297 if (!nestable_tasks_allowed_)
298 return;
299 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900300 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900301 }
initial.commit3f4a7322008-07-27 06:49:38 +0900302}
303
304bool MessageLoop::NestableTasksAllowed() const {
305 return nestable_tasks_allowed_;
306}
307
jcampan@chromium.orgeac57172009-07-02 04:53:59 +0900308bool MessageLoop::IsNested() {
309 return state_->run_depth > 1;
310}
311
initial.commit3f4a7322008-07-27 06:49:38 +0900312//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900313
initial.commit3f4a7322008-07-27 06:49:38 +0900314void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900315 DCHECK(nestable_tasks_allowed_);
316 // Execute the task and assume the worst: It is probably not reentrant.
317 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900318
319 HistogramEvent(kTaskRunEvent);
320 task->Run();
321 delete task;
322
323 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900324}
325
darin@google.combe165ae2008-09-07 17:08:29 +0900326bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
327 if (pending_task.nestable || state_->run_depth == 1) {
328 RunTask(pending_task.task);
329 // Show that we ran a task (Note: a new one might arrive as a
330 // consequence!).
331 return true;
332 }
333
334 // We couldn't run the task now because we're in a nested message loop
335 // and the task isn't nestable.
336 deferred_non_nestable_work_queue_.push(pending_task);
337 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900338}
339
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900340void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
341 // Move to the delayed work queue. Initialize the sequence number
342 // before inserting into the delayed_work_queue_. The sequence number
343 // is used to faciliate FIFO sorting when two tasks have the same
344 // delayed_run_time value.
345 PendingTask new_pending_task(pending_task);
346 new_pending_task.sequence_num = next_sequence_num_++;
347 delayed_work_queue_.push(new_pending_task);
348}
349
initial.commit3f4a7322008-07-27 06:49:38 +0900350void MessageLoop::ReloadWorkQueue() {
351 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900352 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
353 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900354 // queues get large.
355 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900356 return; // Wait till we *really* need to lock and load.
357
358 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900359 {
360 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900361 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900362 return;
darin@chromium.orgb80ef1a2009-09-03 05:05:21 +0900363 incoming_queue_.Swap(&work_queue_); // Constant time
darin@google.combe165ae2008-09-07 17:08:29 +0900364 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900365 }
366}
367
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900368bool MessageLoop::DeletePendingTasks() {
369 bool did_work = !work_queue_.empty();
370 while (!work_queue_.empty()) {
371 PendingTask pending_task = work_queue_.front();
372 work_queue_.pop();
373 if (!pending_task.delayed_run_time.is_null()) {
374 // We want to delete delayed tasks in the same order in which they would
375 // normally be deleted in case of any funny dependencies between delayed
376 // tasks.
377 AddToDelayedWorkQueue(pending_task);
378 } else {
379 // TODO(darin): Delete all tasks once it is safe to do so.
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +0900380 // Until it is totally safe, just do it when running Purify or
381 // Valgrind.
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900382#if defined(PURIFY)
jar@chromium.org63772352009-03-12 05:06:02 +0900383 delete pending_task.task;
kuchhal@chromium.orge3bd2eb2009-05-15 01:44:26 +0900384#elif defined(OS_POSIX)
385 if (RUNNING_ON_VALGRIND)
386 delete pending_task.task;
387#endif // defined(OS_POSIX)
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900388 }
initial.commit3f4a7322008-07-27 06:49:38 +0900389 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900390 did_work |= !deferred_non_nestable_work_queue_.empty();
391 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org47fb2852009-03-12 04:46:41 +0900392 // TODO(darin): Delete all tasks once it is safe to do so.
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900393 // Until it is totaly safe, only delete them under Purify and Valgrind.
394 Task* task = NULL;
395#if defined(PURIFY)
396 task = deferred_non_nestable_work_queue_.front().task;
397#elif defined(OS_POSIX)
398 if (RUNNING_ON_VALGRIND)
399 task = deferred_non_nestable_work_queue_.front().task;
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900400#endif
401 deferred_non_nestable_work_queue_.pop();
kuchhal@chromium.org3a6242e2009-07-24 07:28:49 +0900402 if (task)
403 delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900404 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900405 did_work |= !delayed_work_queue_.empty();
406 while (!delayed_work_queue_.empty()) {
407 Task* task = delayed_work_queue_.top().task;
408 delayed_work_queue_.pop();
409 delete task;
410 }
411 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900412}
413
darin@google.com981f3552008-08-16 12:09:05 +0900414bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900415 if (!nestable_tasks_allowed_) {
416 // Task can't be executed right now.
417 return false;
418 }
419
420 for (;;) {
421 ReloadWorkQueue();
422 if (work_queue_.empty())
423 break;
424
425 // Execute oldest task.
426 do {
427 PendingTask pending_task = work_queue_.front();
428 work_queue_.pop();
429 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900430 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900431 // If we changed the topmost task, then it is time to re-schedule.
432 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900433 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
434 } else {
435 if (DeferOrRunPendingTask(pending_task))
436 return true;
437 }
438 } while (!work_queue_.empty());
439 }
440
441 // Nothing happened.
442 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900443}
444
darin@google.com6393bed2008-08-20 15:30:58 +0900445bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900446 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
447 *next_delayed_work_time = Time();
448 return false;
449 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900450
darin@google.combe165ae2008-09-07 17:08:29 +0900451 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
452 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
453 return false;
454 }
darin@google.com981f3552008-08-16 12:09:05 +0900455
darin@google.combe165ae2008-09-07 17:08:29 +0900456 PendingTask pending_task = delayed_work_queue_.top();
457 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900458
darin@google.combe165ae2008-09-07 17:08:29 +0900459 if (!delayed_work_queue_.empty())
460 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900461
darin@google.combe165ae2008-09-07 17:08:29 +0900462 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900463}
464
465bool MessageLoop::DoIdleWork() {
466 if (ProcessNextDelayedNonNestableTask())
467 return true;
468
469 if (state_->quit_received)
470 pump_->Quit();
471
472 return false;
473}
474
475//------------------------------------------------------------------------------
476// MessageLoop::AutoRunState
477
478MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
479 // Make the loop reference us.
480 previous_state_ = loop_->state_;
481 if (previous_state_) {
482 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900483 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900484 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900485 }
darin@google.com981f3552008-08-16 12:09:05 +0900486 loop_->state_ = this;
487
488 // Initialize the other fields:
489 quit_received = false;
jcampan@chromium.org05423582009-08-01 07:53:37 +0900490#if defined(OS_WIN) || defined(OS_LINUX)
darin@google.com981f3552008-08-16 12:09:05 +0900491 dispatcher = NULL;
492#endif
493}
494
495MessageLoop::AutoRunState::~AutoRunState() {
496 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900497}
498
initial.commit3f4a7322008-07-27 06:49:38 +0900499//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900500// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900501
darin@google.combe165ae2008-09-07 17:08:29 +0900502bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
503 // Since the top of a priority queue is defined as the "greatest" element, we
504 // need to invert the comparison here. We want the smaller time to be at the
505 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900506
darin@google.combe165ae2008-09-07 17:08:29 +0900507 if (delayed_run_time < other.delayed_run_time)
508 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900509
darin@google.combe165ae2008-09-07 17:08:29 +0900510 if (delayed_run_time > other.delayed_run_time)
511 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900512
darin@google.combe165ae2008-09-07 17:08:29 +0900513 // If the times happen to match, then we use the sequence number to decide.
514 // Compare the difference to support integer roll-over.
515 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900516}
517
518//------------------------------------------------------------------------------
519// Method and data for histogramming events and actions taken by each instance
520// on each thread.
521
522// static
523bool MessageLoop::enable_histogrammer_ = false;
524
525// static
526void MessageLoop::EnableHistogrammer(bool enable) {
527 enable_histogrammer_ = enable;
528}
529
530void MessageLoop::StartHistogrammer() {
531 if (enable_histogrammer_ && !message_histogram_.get()
532 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900533 DCHECK(!thread_name_.empty());
jar@chromium.orgfe4c0d12009-12-06 09:09:37 +0900534 message_histogram_ =
535 LinearHistogram::LinearHistogramFactoryGet(
536 ("MsgLoop:" + thread_name_),
dsh@google.com6e7eb9f2009-02-25 04:08:23 +0900537 kLeastNonZeroMessageId,
538 kMaxMessageId,
jar@chromium.orgfe4c0d12009-12-06 09:09:37 +0900539 kNumberOfDistinctMessagesDisplayed);
initial.commit3f4a7322008-07-27 06:49:38 +0900540 message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
541 message_histogram_->SetRangeDescriptions(event_descriptions_);
542 }
543}
544
545void MessageLoop::HistogramEvent(int event) {
546 if (message_histogram_.get())
547 message_histogram_->Add(event);
548}
549
initial.commit3f4a7322008-07-27 06:49:38 +0900550// Provide a macro that takes an expression (such as a constant, or macro
551// constant) and creates a pair to initalize an array of pairs. In this case,
552// our pair consists of the expressions value, and the "stringized" version
553// of the expression (i.e., the exrpression put in quotes). For example, if
554// we have:
555// #define FOO 2
556// #define BAR 5
557// then the following:
558// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
559// will expand to:
560// {7, "FOO + BAR"}
561// We use the resulting array as an argument to our histogram, which reads the
562// number as a bucket identifier, and proceeds to use the corresponding name
563// in the pair (i.e., the quoted string) when printing out a histogram.
564#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
565
initial.commit3f4a7322008-07-27 06:49:38 +0900566// static
567const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commit3f4a7322008-07-27 06:49:38 +0900568 // Provide some pretty print capability in our histogram for our internal
569 // messages.
570
initial.commit3f4a7322008-07-27 06:49:38 +0900571 // A few events we handle (kindred to messages), and used to profile actions.
572 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commit3f4a7322008-07-27 06:49:38 +0900573 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
574
575 {-1, NULL} // The list must be null terminated, per API to histogram.
576};
license.botf003cfe2008-08-24 09:55:55 +0900577
darin@google.comd936b5b2008-08-26 14:53:57 +0900578//------------------------------------------------------------------------------
579// MessageLoopForUI
580
581#if defined(OS_WIN)
darin@google.comd936b5b2008-08-26 14:53:57 +0900582void MessageLoopForUI::WillProcessMessage(const MSG& message) {
583 pump_win()->WillProcessMessage(message);
584}
585void MessageLoopForUI::DidProcessMessage(const MSG& message) {
586 pump_win()->DidProcessMessage(message);
587}
588void MessageLoopForUI::PumpOutPendingPaintMessages() {
rvargas@google.com73887542008-11-08 06:52:15 +0900589 pump_ui()->PumpOutPendingPaintMessages();
darin@google.comd936b5b2008-08-26 14:53:57 +0900590}
591
592#endif // defined(OS_WIN)
593
jcampan@chromium.org05423582009-08-01 07:53:37 +0900594#if defined(OS_LINUX) || defined(OS_WIN)
595void MessageLoopForUI::AddObserver(Observer* observer) {
596 pump_ui()->AddObserver(observer);
597}
598
599void MessageLoopForUI::RemoveObserver(Observer* observer) {
600 pump_ui()->RemoveObserver(observer);
601}
602
603void MessageLoopForUI::Run(Dispatcher* dispatcher) {
604 AutoRunState save_state(this);
605 state_->dispatcher = dispatcher;
606 RunHandler();
607}
608#endif // defined(OS_LINUX) || defined(OS_WIN)
609
darin@google.comd936b5b2008-08-26 14:53:57 +0900610//------------------------------------------------------------------------------
611// MessageLoopForIO
612
613#if defined(OS_WIN)
614
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900615void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
616 pump_io()->RegisterIOHandler(file, handler);
617}
618
rvargas@google.com73887542008-11-08 06:52:15 +0900619bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
620 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900621}
622
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900623#elif defined(OS_POSIX)
624
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900625bool MessageLoopForIO::WatchFileDescriptor(int fd,
626 bool persistent,
627 Mode mode,
628 FileDescriptorWatcher *controller,
629 Watcher *delegate) {
630 return pump_libevent()->WatchFileDescriptor(
631 fd,
632 persistent,
633 static_cast<base::MessagePumpLibevent::Mode>(mode),
634 controller,
635 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900636}
637
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900638#endif