blob: d836c92441596adea3479812c87a6a0cbf4f807a [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"
21#endif
sky@chromium.orgf881d882009-04-11 00:09:39 +090022#if defined(TOOLKIT_GTK)
dsh@google.com119a2522008-10-04 01:52:59 +090023#include "base/message_pump_glib.h"
24#endif
dkegel@google.com9e044ae2008-09-19 03:46:26 +090025
dsh@google.com0f8dd262008-10-28 05:43:33 +090026using base::Time;
27using base::TimeDelta;
28
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090029// A lazily created thread local storage for quick access to a thread's message
30// loop, if one exists. This should be safe and free of static constructors.
31static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
32 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090033
34//------------------------------------------------------------------------------
35
initial.commit3f4a7322008-07-27 06:49:38 +090036// Logical events for Histogram profiling. Run with -message-loop-histogrammer
37// to get an accounting of messages and actions taken on each thread.
darin@google.com981f3552008-08-16 12:09:05 +090038static const int kTaskRunEvent = 0x1;
39static const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090040
41// Provide range of message IDs for use in histogramming and debug display.
42static const int kLeastNonZeroMessageId = 1;
43static const int kMaxMessageId = 1099;
44static const int kNumberOfDistinctMessagesDisplayed = 1100;
45
46//------------------------------------------------------------------------------
47
darin@google.com981f3552008-08-16 12:09:05 +090048#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090049
initial.commit3f4a7322008-07-27 06:49:38 +090050// Upon a SEH exception in this thread, it restores the original unhandled
51// exception filter.
52static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
53 ::SetUnhandledExceptionFilter(old_filter);
54 return EXCEPTION_CONTINUE_SEARCH;
55}
56
57// Retrieves a pointer to the current unhandled exception filter. There
58// is no standalone getter method.
59static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
60 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
61 top_filter = ::SetUnhandledExceptionFilter(0);
62 ::SetUnhandledExceptionFilter(top_filter);
63 return top_filter;
64}
65
darin@google.com981f3552008-08-16 12:09:05 +090066#endif // defined(OS_WIN)
67
initial.commit3f4a7322008-07-27 06:49:38 +090068//------------------------------------------------------------------------------
69
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090070// static
71MessageLoop* MessageLoop::current() {
72 // TODO(darin): sadly, we cannot enable this yet since people call us even
73 // when they have no intention of using us.
74 //DCHECK(loop) << "Ouch, did you forget to initialize me?";
75 return lazy_tls_ptr.Pointer()->Get();
76}
77
darin@google.comd936b5b2008-08-26 14:53:57 +090078MessageLoop::MessageLoop(Type type)
79 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +090080 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +090081 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +090082 state_(NULL),
83 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090084 DCHECK(!current()) << "should only have one message loop per thread";
85 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +090086
darin@google.com981f3552008-08-16 12:09:05 +090087#if defined(OS_WIN)
rvargas@google.com670c3122008-09-26 05:33:04 +090088 // TODO(rvargas): Get rid of the OS guards.
darin@google.com0795f572008-08-30 09:22:48 +090089 if (type_ == TYPE_DEFAULT) {
90 pump_ = new base::MessagePumpDefault();
rvargas@google.com670c3122008-09-26 05:33:04 +090091 } else if (type_ == TYPE_IO) {
92 pump_ = new base::MessagePumpForIO();
darin@google.com0795f572008-08-30 09:22:48 +090093 } else {
rvargas@google.com670c3122008-09-26 05:33:04 +090094 DCHECK(type_ == TYPE_UI);
95 pump_ = new base::MessagePumpForUI();
darin@google.com0795f572008-08-30 09:22:48 +090096 }
dkegel@google.com9e044ae2008-09-19 03:46:26 +090097#elif defined(OS_POSIX)
mark@chromium.org059d0492008-09-24 06:08:28 +090098 if (type_ == TYPE_UI) {
dsh@google.com119a2522008-10-04 01:52:59 +090099#if defined(OS_MACOSX)
mark@chromium.org059d0492008-09-24 06:08:28 +0900100 pump_ = base::MessagePumpMac::Create();
dsh@google.com119a2522008-10-04 01:52:59 +0900101#elif defined(OS_LINUX)
sky@chromium.orgf881d882009-04-11 00:09:39 +0900102#if defined(TOOLKIT_GTK)
dsh@google.com119a2522008-10-04 01:52:59 +0900103 pump_ = new base::MessagePumpForUI();
sky@chromium.orgf881d882009-04-11 00:09:39 +0900104#else
105 pump_ = new base::MessagePumpDefault();
106#endif
dsh@google.com119a2522008-10-04 01:52:59 +0900107#endif // OS_LINUX
108 } else if (type_ == TYPE_IO) {
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900109 pump_ = new base::MessagePumpLibevent();
110 } else {
111 pump_ = new base::MessagePumpDefault();
112 }
mark@chromium.org059d0492008-09-24 06:08:28 +0900113#endif // OS_POSIX
initial.commit3f4a7322008-07-27 06:49:38 +0900114}
115
116MessageLoop::~MessageLoop() {
117 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900118
119 // Let interested parties have one last shot at accessing this.
120 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
121 WillDestroyCurrentMessageLoop());
122
darin@google.com0e500502008-09-09 14:55:35 +0900123 DCHECK(!state_);
124
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900125 // Clean up any unprocessed tasks, but take care: deleting a task could
126 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
127 // limit on the number of times we will allow a deleted task to generate more
128 // tasks. Normally, we should only pass through this loop once or twice. If
129 // we end up hitting the loop limit, then it is probably due to one task that
130 // is being stubborn. Inspect the queues to see who is left.
131 bool did_work;
132 for (int i = 0; i < 100; ++i) {
133 DeletePendingTasks();
134 ReloadWorkQueue();
135 // If we end up with empty queues, then break out of the loop.
136 did_work = DeletePendingTasks();
137 if (!did_work)
138 break;
darin@google.com0e500502008-09-09 14:55:35 +0900139 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900140 DCHECK(!did_work);
141
142 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900143 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900144}
145
darin@google.com965e5342008-08-06 08:16:41 +0900146void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
147 DCHECK(this == current());
148 destruction_observers_.AddObserver(obs);
149}
150
151void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
152 DCHECK(this == current());
153 destruction_observers_.RemoveObserver(obs);
154}
155
darin@google.com6ddeb842008-08-15 16:31:20 +0900156void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900157 AutoRunState save_state(this);
158 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900159}
160
jar@google.com9239e022008-07-31 22:10:20 +0900161void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900162 AutoRunState save_state(this);
163 state_->quit_received = true; // Means run until we would otherwise block.
164 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900165}
166
167// Runs the loop in two different SEH modes:
168// enable_SEH_restoration_ = false : any unhandled exception goes to the last
169// one that calls SetUnhandledExceptionFilter().
170// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
171// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900172void MessageLoop::RunHandler() {
173#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900174 if (exception_restoration_) {
175 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
176 __try {
darin@google.com981f3552008-08-16 12:09:05 +0900177 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900178 } __except(SEHFilter(current_filter)) {
179 }
darin@google.com981f3552008-08-16 12:09:05 +0900180 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900181 }
darin@google.com981f3552008-08-16 12:09:05 +0900182#endif
183
184 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900185}
186
187//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900188
darin@google.com981f3552008-08-16 12:09:05 +0900189void MessageLoop::RunInternal() {
190 DCHECK(this == current());
191
initial.commit3f4a7322008-07-27 06:49:38 +0900192 StartHistogrammer();
193
darin@google.com981f3552008-08-16 12:09:05 +0900194#if defined(OS_WIN)
195 if (state_->dispatcher) {
196 pump_win()->RunWithDispatcher(this, state_->dispatcher);
197 return;
jar@google.com9239e022008-07-31 22:10:20 +0900198 }
darin@google.com981f3552008-08-16 12:09:05 +0900199#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900200
darin@google.com981f3552008-08-16 12:09:05 +0900201 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900202}
jar@google.com7ff36e62008-07-30 15:58:56 +0900203
jar@google.comb4d1bff2008-07-31 04:03:59 +0900204//------------------------------------------------------------------------------
205// Wrapper functions for use in above message loop framework.
206
initial.commit3f4a7322008-07-27 06:49:38 +0900207bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900208 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900209 return false;
210
darin@google.combe165ae2008-09-07 17:08:29 +0900211 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900212 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900213
darin@google.combe165ae2008-09-07 17:08:29 +0900214 Task* task = deferred_non_nestable_work_queue_.front().task;
215 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900216
darin@google.combe165ae2008-09-07 17:08:29 +0900217 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900218 return true;
219}
220
initial.commit3f4a7322008-07-27 06:49:38 +0900221//------------------------------------------------------------------------------
222
223void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900224 DCHECK(current() == this);
225 if (state_) {
226 state_->quit_received = true;
227 } else {
228 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900229 }
initial.commit3f4a7322008-07-27 06:49:38 +0900230}
231
darin@google.combe165ae2008-09-07 17:08:29 +0900232void MessageLoop::PostTask(
233 const tracked_objects::Location& from_here, Task* task) {
234 PostTask_Helper(from_here, task, 0, true);
235}
236
237void MessageLoop::PostDelayedTask(
238 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
239 PostTask_Helper(from_here, task, delay_ms, true);
240}
241
242void MessageLoop::PostNonNestableTask(
243 const tracked_objects::Location& from_here, Task* task) {
244 PostTask_Helper(from_here, task, 0, false);
245}
246
247void MessageLoop::PostNonNestableDelayedTask(
248 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
249 PostTask_Helper(from_here, task, delay_ms, false);
250}
251
initial.commit3f4a7322008-07-27 06:49:38 +0900252// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900253void MessageLoop::PostTask_Helper(
254 const tracked_objects::Location& from_here, Task* task, int delay_ms,
255 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900256 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900257
darin@google.combe165ae2008-09-07 17:08:29 +0900258 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900259
260 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900261 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900262 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
263 } else {
264 DCHECK(delay_ms == 0) << "delay should not be negative";
265 }
266
initial.commit3f4a7322008-07-27 06:49:38 +0900267 // Warning: Don't try to short-circuit, and handle this thread's tasks more
268 // directly, as it could starve handling of foreign threads. Put every task
269 // into this queue.
270
darin@google.com981f3552008-08-16 12:09:05 +0900271 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900272 {
darin@google.com981f3552008-08-16 12:09:05 +0900273 AutoLock locked(incoming_queue_lock_);
274
darin@google.combe165ae2008-09-07 17:08:29 +0900275 bool was_empty = incoming_queue_.empty();
276 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900277 if (!was_empty)
278 return; // Someone else should have started the sub-pump.
279
darin@google.com981f3552008-08-16 12:09:05 +0900280 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900281 }
darin@google.com981f3552008-08-16 12:09:05 +0900282 // Since the incoming_queue_ may contain a task that destroys this message
283 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
284 // We use a stack-based reference to the message pump so that we can call
285 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900286
darin@google.com981f3552008-08-16 12:09:05 +0900287 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900288}
289
290void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900291 if (nestable_tasks_allowed_ != allowed) {
292 nestable_tasks_allowed_ = allowed;
293 if (!nestable_tasks_allowed_)
294 return;
295 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900296 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900297 }
initial.commit3f4a7322008-07-27 06:49:38 +0900298}
299
300bool MessageLoop::NestableTasksAllowed() const {
301 return nestable_tasks_allowed_;
302}
303
initial.commit3f4a7322008-07-27 06:49:38 +0900304//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900305
initial.commit3f4a7322008-07-27 06:49:38 +0900306void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900307 DCHECK(nestable_tasks_allowed_);
308 // Execute the task and assume the worst: It is probably not reentrant.
309 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900310
311 HistogramEvent(kTaskRunEvent);
312 task->Run();
313 delete task;
314
315 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900316}
317
darin@google.combe165ae2008-09-07 17:08:29 +0900318bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
319 if (pending_task.nestable || state_->run_depth == 1) {
320 RunTask(pending_task.task);
321 // Show that we ran a task (Note: a new one might arrive as a
322 // consequence!).
323 return true;
324 }
325
326 // We couldn't run the task now because we're in a nested message loop
327 // and the task isn't nestable.
328 deferred_non_nestable_work_queue_.push(pending_task);
329 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900330}
331
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900332void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
333 // Move to the delayed work queue. Initialize the sequence number
334 // before inserting into the delayed_work_queue_. The sequence number
335 // is used to faciliate FIFO sorting when two tasks have the same
336 // delayed_run_time value.
337 PendingTask new_pending_task(pending_task);
338 new_pending_task.sequence_num = next_sequence_num_++;
339 delayed_work_queue_.push(new_pending_task);
340}
341
initial.commit3f4a7322008-07-27 06:49:38 +0900342void MessageLoop::ReloadWorkQueue() {
343 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900344 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
345 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900346 // queues get large.
347 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900348 return; // Wait till we *really* need to lock and load.
349
350 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900351 {
352 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900353 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900354 return;
darin@google.combe165ae2008-09-07 17:08:29 +0900355 std::swap(incoming_queue_, work_queue_);
356 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900357 }
358}
359
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900360bool MessageLoop::DeletePendingTasks() {
361 bool did_work = !work_queue_.empty();
362 while (!work_queue_.empty()) {
363 PendingTask pending_task = work_queue_.front();
364 work_queue_.pop();
365 if (!pending_task.delayed_run_time.is_null()) {
366 // We want to delete delayed tasks in the same order in which they would
367 // normally be deleted in case of any funny dependencies between delayed
368 // tasks.
369 AddToDelayedWorkQueue(pending_task);
370 } else {
371 // TODO(darin): Delete all tasks once it is safe to do so.
jar@chromium.org47fb2852009-03-12 04:46:41 +0900372 // Until it is totally safe, just do it when running purify.
373#ifdef PURIFY
jar@chromium.org63772352009-03-12 05:06:02 +0900374 delete pending_task.task;
jar@chromium.org47fb2852009-03-12 04:46:41 +0900375#endif // PURIFY
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900376 }
initial.commit3f4a7322008-07-27 06:49:38 +0900377 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900378 did_work |= !deferred_non_nestable_work_queue_.empty();
379 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org47fb2852009-03-12 04:46:41 +0900380 // TODO(darin): Delete all tasks once it is safe to do so.
381 // Until it is totaly safe, just delete them to keep purify happy.
382#ifdef PURIFY
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900383 Task* task = deferred_non_nestable_work_queue_.front().task;
384#endif
385 deferred_non_nestable_work_queue_.pop();
386#ifdef PURIFY
jar@chromium.org47fb2852009-03-12 04:46:41 +0900387 delete task;
388#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900389 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900390 did_work |= !delayed_work_queue_.empty();
391 while (!delayed_work_queue_.empty()) {
392 Task* task = delayed_work_queue_.top().task;
393 delayed_work_queue_.pop();
394 delete task;
395 }
396 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900397}
398
darin@google.com981f3552008-08-16 12:09:05 +0900399bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900400 if (!nestable_tasks_allowed_) {
401 // Task can't be executed right now.
402 return false;
403 }
404
405 for (;;) {
406 ReloadWorkQueue();
407 if (work_queue_.empty())
408 break;
409
410 // Execute oldest task.
411 do {
412 PendingTask pending_task = work_queue_.front();
413 work_queue_.pop();
414 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900415 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900416 // If we changed the topmost task, then it is time to re-schedule.
417 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900418 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
419 } else {
420 if (DeferOrRunPendingTask(pending_task))
421 return true;
422 }
423 } while (!work_queue_.empty());
424 }
425
426 // Nothing happened.
427 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900428}
429
darin@google.com6393bed2008-08-20 15:30:58 +0900430bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900431 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
432 *next_delayed_work_time = Time();
433 return false;
434 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900435
darin@google.combe165ae2008-09-07 17:08:29 +0900436 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
437 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
438 return false;
439 }
darin@google.com981f3552008-08-16 12:09:05 +0900440
darin@google.combe165ae2008-09-07 17:08:29 +0900441 PendingTask pending_task = delayed_work_queue_.top();
442 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900443
darin@google.combe165ae2008-09-07 17:08:29 +0900444 if (!delayed_work_queue_.empty())
445 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900446
darin@google.combe165ae2008-09-07 17:08:29 +0900447 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900448}
449
450bool MessageLoop::DoIdleWork() {
451 if (ProcessNextDelayedNonNestableTask())
452 return true;
453
454 if (state_->quit_received)
455 pump_->Quit();
456
457 return false;
458}
459
460//------------------------------------------------------------------------------
461// MessageLoop::AutoRunState
462
463MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
464 // Make the loop reference us.
465 previous_state_ = loop_->state_;
466 if (previous_state_) {
467 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900468 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900469 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900470 }
darin@google.com981f3552008-08-16 12:09:05 +0900471 loop_->state_ = this;
472
473 // Initialize the other fields:
474 quit_received = false;
475#if defined(OS_WIN)
476 dispatcher = NULL;
477#endif
478}
479
480MessageLoop::AutoRunState::~AutoRunState() {
481 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900482}
483
initial.commit3f4a7322008-07-27 06:49:38 +0900484//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900485// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900486
darin@google.combe165ae2008-09-07 17:08:29 +0900487bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
488 // Since the top of a priority queue is defined as the "greatest" element, we
489 // need to invert the comparison here. We want the smaller time to be at the
490 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900491
darin@google.combe165ae2008-09-07 17:08:29 +0900492 if (delayed_run_time < other.delayed_run_time)
493 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900494
darin@google.combe165ae2008-09-07 17:08:29 +0900495 if (delayed_run_time > other.delayed_run_time)
496 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900497
darin@google.combe165ae2008-09-07 17:08:29 +0900498 // If the times happen to match, then we use the sequence number to decide.
499 // Compare the difference to support integer roll-over.
500 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900501}
502
503//------------------------------------------------------------------------------
504// Method and data for histogramming events and actions taken by each instance
505// on each thread.
506
507// static
508bool MessageLoop::enable_histogrammer_ = false;
509
510// static
511void MessageLoop::EnableHistogrammer(bool enable) {
512 enable_histogrammer_ = enable;
513}
514
515void MessageLoop::StartHistogrammer() {
516 if (enable_histogrammer_ && !message_histogram_.get()
517 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900518 DCHECK(!thread_name_.empty());
dsh@google.com6e7eb9f2009-02-25 04:08:23 +0900519 message_histogram_.reset(
520 new LinearHistogram(("MsgLoop:" + thread_name_).c_str(),
521 kLeastNonZeroMessageId,
522 kMaxMessageId,
523 kNumberOfDistinctMessagesDisplayed));
initial.commit3f4a7322008-07-27 06:49:38 +0900524 message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
525 message_histogram_->SetRangeDescriptions(event_descriptions_);
526 }
527}
528
529void MessageLoop::HistogramEvent(int event) {
530 if (message_histogram_.get())
531 message_histogram_->Add(event);
532}
533
initial.commit3f4a7322008-07-27 06:49:38 +0900534// Provide a macro that takes an expression (such as a constant, or macro
535// constant) and creates a pair to initalize an array of pairs. In this case,
536// our pair consists of the expressions value, and the "stringized" version
537// of the expression (i.e., the exrpression put in quotes). For example, if
538// we have:
539// #define FOO 2
540// #define BAR 5
541// then the following:
542// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
543// will expand to:
544// {7, "FOO + BAR"}
545// We use the resulting array as an argument to our histogram, which reads the
546// number as a bucket identifier, and proceeds to use the corresponding name
547// in the pair (i.e., the quoted string) when printing out a histogram.
548#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
549
initial.commit3f4a7322008-07-27 06:49:38 +0900550// static
551const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commit3f4a7322008-07-27 06:49:38 +0900552 // Provide some pretty print capability in our histogram for our internal
553 // messages.
554
initial.commit3f4a7322008-07-27 06:49:38 +0900555 // A few events we handle (kindred to messages), and used to profile actions.
556 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commit3f4a7322008-07-27 06:49:38 +0900557 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
558
559 {-1, NULL} // The list must be null terminated, per API to histogram.
560};
license.botf003cfe2008-08-24 09:55:55 +0900561
darin@google.comd936b5b2008-08-26 14:53:57 +0900562//------------------------------------------------------------------------------
563// MessageLoopForUI
564
565#if defined(OS_WIN)
566
567void MessageLoopForUI::Run(Dispatcher* dispatcher) {
568 AutoRunState save_state(this);
569 state_->dispatcher = dispatcher;
570 RunHandler();
571}
572
573void MessageLoopForUI::AddObserver(Observer* observer) {
574 pump_win()->AddObserver(observer);
575}
576
577void MessageLoopForUI::RemoveObserver(Observer* observer) {
578 pump_win()->RemoveObserver(observer);
579}
580
581void MessageLoopForUI::WillProcessMessage(const MSG& message) {
582 pump_win()->WillProcessMessage(message);
583}
584void MessageLoopForUI::DidProcessMessage(const MSG& message) {
585 pump_win()->DidProcessMessage(message);
586}
587void MessageLoopForUI::PumpOutPendingPaintMessages() {
rvargas@google.com73887542008-11-08 06:52:15 +0900588 pump_ui()->PumpOutPendingPaintMessages();
darin@google.comd936b5b2008-08-26 14:53:57 +0900589}
590
591#endif // defined(OS_WIN)
592
593//------------------------------------------------------------------------------
594// MessageLoopForIO
595
596#if defined(OS_WIN)
597
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900598void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
599 pump_io()->RegisterIOHandler(file, handler);
600}
601
rvargas@google.com73887542008-11-08 06:52:15 +0900602bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
603 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900604}
605
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900606#elif defined(OS_POSIX)
607
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900608bool MessageLoopForIO::WatchFileDescriptor(int fd,
609 bool persistent,
610 Mode mode,
611 FileDescriptorWatcher *controller,
612 Watcher *delegate) {
613 return pump_libevent()->WatchFileDescriptor(
614 fd,
615 persistent,
616 static_cast<base::MessagePumpLibevent::Mode>(mode),
617 controller,
618 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900619}
620
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900621#endif