blob: 764a96332560529138ca1bdcaa37a9f97f95cb39 [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.org3f8b9492009-04-28 03:17:24 +090022#if defined(OS_LINUX)
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)
102 pump_ = new base::MessagePumpForUI();
103#endif // OS_LINUX
104 } else if (type_ == TYPE_IO) {
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900105 pump_ = new base::MessagePumpLibevent();
106 } else {
107 pump_ = new base::MessagePumpDefault();
108 }
mark@chromium.org059d0492008-09-24 06:08:28 +0900109#endif // OS_POSIX
initial.commit3f4a7322008-07-27 06:49:38 +0900110}
111
112MessageLoop::~MessageLoop() {
113 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900114
115 // Let interested parties have one last shot at accessing this.
116 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
117 WillDestroyCurrentMessageLoop());
118
darin@google.com0e500502008-09-09 14:55:35 +0900119 DCHECK(!state_);
120
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900121 // Clean up any unprocessed tasks, but take care: deleting a task could
122 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
123 // limit on the number of times we will allow a deleted task to generate more
124 // tasks. Normally, we should only pass through this loop once or twice. If
125 // we end up hitting the loop limit, then it is probably due to one task that
126 // is being stubborn. Inspect the queues to see who is left.
127 bool did_work;
128 for (int i = 0; i < 100; ++i) {
129 DeletePendingTasks();
130 ReloadWorkQueue();
131 // If we end up with empty queues, then break out of the loop.
132 did_work = DeletePendingTasks();
133 if (!did_work)
134 break;
darin@google.com0e500502008-09-09 14:55:35 +0900135 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900136 DCHECK(!did_work);
137
138 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900139 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900140}
141
darin@google.com965e5342008-08-06 08:16:41 +0900142void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
143 DCHECK(this == current());
144 destruction_observers_.AddObserver(obs);
145}
146
147void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
148 DCHECK(this == current());
149 destruction_observers_.RemoveObserver(obs);
150}
151
darin@google.com6ddeb842008-08-15 16:31:20 +0900152void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900153 AutoRunState save_state(this);
154 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900155}
156
jar@google.com9239e022008-07-31 22:10:20 +0900157void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900158 AutoRunState save_state(this);
159 state_->quit_received = true; // Means run until we would otherwise block.
160 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900161}
162
163// Runs the loop in two different SEH modes:
164// enable_SEH_restoration_ = false : any unhandled exception goes to the last
165// one that calls SetUnhandledExceptionFilter().
166// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
167// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900168void MessageLoop::RunHandler() {
169#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900170 if (exception_restoration_) {
171 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
172 __try {
darin@google.com981f3552008-08-16 12:09:05 +0900173 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900174 } __except(SEHFilter(current_filter)) {
175 }
darin@google.com981f3552008-08-16 12:09:05 +0900176 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900177 }
darin@google.com981f3552008-08-16 12:09:05 +0900178#endif
179
180 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900181}
182
183//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900184
darin@google.com981f3552008-08-16 12:09:05 +0900185void MessageLoop::RunInternal() {
186 DCHECK(this == current());
187
initial.commit3f4a7322008-07-27 06:49:38 +0900188 StartHistogrammer();
189
darin@google.com981f3552008-08-16 12:09:05 +0900190#if defined(OS_WIN)
191 if (state_->dispatcher) {
192 pump_win()->RunWithDispatcher(this, state_->dispatcher);
193 return;
jar@google.com9239e022008-07-31 22:10:20 +0900194 }
darin@google.com981f3552008-08-16 12:09:05 +0900195#endif
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900196
darin@google.com981f3552008-08-16 12:09:05 +0900197 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900198}
jar@google.com7ff36e62008-07-30 15:58:56 +0900199
jar@google.comb4d1bff2008-07-31 04:03:59 +0900200//------------------------------------------------------------------------------
201// Wrapper functions for use in above message loop framework.
202
initial.commit3f4a7322008-07-27 06:49:38 +0900203bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900204 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900205 return false;
206
darin@google.combe165ae2008-09-07 17:08:29 +0900207 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900208 return false;
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900209
darin@google.combe165ae2008-09-07 17:08:29 +0900210 Task* task = deferred_non_nestable_work_queue_.front().task;
211 deferred_non_nestable_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900212
darin@google.combe165ae2008-09-07 17:08:29 +0900213 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900214 return true;
215}
216
initial.commit3f4a7322008-07-27 06:49:38 +0900217//------------------------------------------------------------------------------
218
219void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900220 DCHECK(current() == this);
221 if (state_) {
222 state_->quit_received = true;
223 } else {
224 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900225 }
initial.commit3f4a7322008-07-27 06:49:38 +0900226}
227
darin@google.combe165ae2008-09-07 17:08:29 +0900228void MessageLoop::PostTask(
229 const tracked_objects::Location& from_here, Task* task) {
230 PostTask_Helper(from_here, task, 0, true);
231}
232
233void MessageLoop::PostDelayedTask(
234 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
235 PostTask_Helper(from_here, task, delay_ms, true);
236}
237
238void MessageLoop::PostNonNestableTask(
239 const tracked_objects::Location& from_here, Task* task) {
240 PostTask_Helper(from_here, task, 0, false);
241}
242
243void MessageLoop::PostNonNestableDelayedTask(
244 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
245 PostTask_Helper(from_here, task, delay_ms, false);
246}
247
initial.commit3f4a7322008-07-27 06:49:38 +0900248// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900249void MessageLoop::PostTask_Helper(
250 const tracked_objects::Location& from_here, Task* task, int delay_ms,
251 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900252 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900253
darin@google.combe165ae2008-09-07 17:08:29 +0900254 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900255
256 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900257 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900258 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
259 } else {
260 DCHECK(delay_ms == 0) << "delay should not be negative";
261 }
262
initial.commit3f4a7322008-07-27 06:49:38 +0900263 // Warning: Don't try to short-circuit, and handle this thread's tasks more
264 // directly, as it could starve handling of foreign threads. Put every task
265 // into this queue.
266
darin@google.com981f3552008-08-16 12:09:05 +0900267 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900268 {
darin@google.com981f3552008-08-16 12:09:05 +0900269 AutoLock locked(incoming_queue_lock_);
270
darin@google.combe165ae2008-09-07 17:08:29 +0900271 bool was_empty = incoming_queue_.empty();
272 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900273 if (!was_empty)
274 return; // Someone else should have started the sub-pump.
275
darin@google.com981f3552008-08-16 12:09:05 +0900276 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900277 }
darin@google.com981f3552008-08-16 12:09:05 +0900278 // Since the incoming_queue_ may contain a task that destroys this message
279 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
280 // We use a stack-based reference to the message pump so that we can call
281 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900282
darin@google.com981f3552008-08-16 12:09:05 +0900283 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900284}
285
286void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900287 if (nestable_tasks_allowed_ != allowed) {
288 nestable_tasks_allowed_ = allowed;
289 if (!nestable_tasks_allowed_)
290 return;
291 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900292 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900293 }
initial.commit3f4a7322008-07-27 06:49:38 +0900294}
295
296bool MessageLoop::NestableTasksAllowed() const {
297 return nestable_tasks_allowed_;
298}
299
initial.commit3f4a7322008-07-27 06:49:38 +0900300//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900301
initial.commit3f4a7322008-07-27 06:49:38 +0900302void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900303 DCHECK(nestable_tasks_allowed_);
304 // Execute the task and assume the worst: It is probably not reentrant.
305 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900306
307 HistogramEvent(kTaskRunEvent);
308 task->Run();
309 delete task;
310
311 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900312}
313
darin@google.combe165ae2008-09-07 17:08:29 +0900314bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
315 if (pending_task.nestable || state_->run_depth == 1) {
316 RunTask(pending_task.task);
317 // Show that we ran a task (Note: a new one might arrive as a
318 // consequence!).
319 return true;
320 }
321
322 // We couldn't run the task now because we're in a nested message loop
323 // and the task isn't nestable.
324 deferred_non_nestable_work_queue_.push(pending_task);
325 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900326}
327
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900328void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
329 // Move to the delayed work queue. Initialize the sequence number
330 // before inserting into the delayed_work_queue_. The sequence number
331 // is used to faciliate FIFO sorting when two tasks have the same
332 // delayed_run_time value.
333 PendingTask new_pending_task(pending_task);
334 new_pending_task.sequence_num = next_sequence_num_++;
335 delayed_work_queue_.push(new_pending_task);
336}
337
initial.commit3f4a7322008-07-27 06:49:38 +0900338void MessageLoop::ReloadWorkQueue() {
339 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900340 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
341 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900342 // queues get large.
343 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900344 return; // Wait till we *really* need to lock and load.
345
346 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900347 {
348 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900349 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900350 return;
darin@google.combe165ae2008-09-07 17:08:29 +0900351 std::swap(incoming_queue_, work_queue_);
352 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900353 }
354}
355
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900356bool MessageLoop::DeletePendingTasks() {
357 bool did_work = !work_queue_.empty();
358 while (!work_queue_.empty()) {
359 PendingTask pending_task = work_queue_.front();
360 work_queue_.pop();
361 if (!pending_task.delayed_run_time.is_null()) {
362 // We want to delete delayed tasks in the same order in which they would
363 // normally be deleted in case of any funny dependencies between delayed
364 // tasks.
365 AddToDelayedWorkQueue(pending_task);
366 } else {
367 // TODO(darin): Delete all tasks once it is safe to do so.
jar@chromium.org47fb2852009-03-12 04:46:41 +0900368 // Until it is totally safe, just do it when running purify.
369#ifdef PURIFY
jar@chromium.org63772352009-03-12 05:06:02 +0900370 delete pending_task.task;
jar@chromium.org47fb2852009-03-12 04:46:41 +0900371#endif // PURIFY
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900372 }
initial.commit3f4a7322008-07-27 06:49:38 +0900373 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900374 did_work |= !deferred_non_nestable_work_queue_.empty();
375 while (!deferred_non_nestable_work_queue_.empty()) {
jar@chromium.org47fb2852009-03-12 04:46:41 +0900376 // TODO(darin): Delete all tasks once it is safe to do so.
377 // Until it is totaly safe, just delete them to keep purify happy.
378#ifdef PURIFY
jar@chromium.org2fa6b4b2009-03-12 04:53:50 +0900379 Task* task = deferred_non_nestable_work_queue_.front().task;
380#endif
381 deferred_non_nestable_work_queue_.pop();
382#ifdef PURIFY
jar@chromium.org47fb2852009-03-12 04:46:41 +0900383 delete task;
384#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900385 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900386 did_work |= !delayed_work_queue_.empty();
387 while (!delayed_work_queue_.empty()) {
388 Task* task = delayed_work_queue_.top().task;
389 delayed_work_queue_.pop();
390 delete task;
391 }
392 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900393}
394
darin@google.com981f3552008-08-16 12:09:05 +0900395bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900396 if (!nestable_tasks_allowed_) {
397 // Task can't be executed right now.
398 return false;
399 }
400
401 for (;;) {
402 ReloadWorkQueue();
403 if (work_queue_.empty())
404 break;
405
406 // Execute oldest task.
407 do {
408 PendingTask pending_task = work_queue_.front();
409 work_queue_.pop();
410 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900411 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900412 // If we changed the topmost task, then it is time to re-schedule.
413 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900414 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
415 } else {
416 if (DeferOrRunPendingTask(pending_task))
417 return true;
418 }
419 } while (!work_queue_.empty());
420 }
421
422 // Nothing happened.
423 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900424}
425
darin@google.com6393bed2008-08-20 15:30:58 +0900426bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900427 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
428 *next_delayed_work_time = Time();
429 return false;
430 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900431
darin@google.combe165ae2008-09-07 17:08:29 +0900432 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
433 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
434 return false;
435 }
darin@google.com981f3552008-08-16 12:09:05 +0900436
darin@google.combe165ae2008-09-07 17:08:29 +0900437 PendingTask pending_task = delayed_work_queue_.top();
438 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900439
darin@google.combe165ae2008-09-07 17:08:29 +0900440 if (!delayed_work_queue_.empty())
441 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900442
darin@google.combe165ae2008-09-07 17:08:29 +0900443 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900444}
445
446bool MessageLoop::DoIdleWork() {
447 if (ProcessNextDelayedNonNestableTask())
448 return true;
449
450 if (state_->quit_received)
451 pump_->Quit();
452
453 return false;
454}
455
456//------------------------------------------------------------------------------
457// MessageLoop::AutoRunState
458
459MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
460 // Make the loop reference us.
461 previous_state_ = loop_->state_;
462 if (previous_state_) {
463 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900464 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900465 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900466 }
darin@google.com981f3552008-08-16 12:09:05 +0900467 loop_->state_ = this;
468
469 // Initialize the other fields:
470 quit_received = false;
471#if defined(OS_WIN)
472 dispatcher = NULL;
473#endif
474}
475
476MessageLoop::AutoRunState::~AutoRunState() {
477 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900478}
479
initial.commit3f4a7322008-07-27 06:49:38 +0900480//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900481// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900482
darin@google.combe165ae2008-09-07 17:08:29 +0900483bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
484 // Since the top of a priority queue is defined as the "greatest" element, we
485 // need to invert the comparison here. We want the smaller time to be at the
486 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900487
darin@google.combe165ae2008-09-07 17:08:29 +0900488 if (delayed_run_time < other.delayed_run_time)
489 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900490
darin@google.combe165ae2008-09-07 17:08:29 +0900491 if (delayed_run_time > other.delayed_run_time)
492 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900493
darin@google.combe165ae2008-09-07 17:08:29 +0900494 // If the times happen to match, then we use the sequence number to decide.
495 // Compare the difference to support integer roll-over.
496 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900497}
498
499//------------------------------------------------------------------------------
500// Method and data for histogramming events and actions taken by each instance
501// on each thread.
502
503// static
504bool MessageLoop::enable_histogrammer_ = false;
505
506// static
507void MessageLoop::EnableHistogrammer(bool enable) {
508 enable_histogrammer_ = enable;
509}
510
511void MessageLoop::StartHistogrammer() {
512 if (enable_histogrammer_ && !message_histogram_.get()
513 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900514 DCHECK(!thread_name_.empty());
dsh@google.com6e7eb9f2009-02-25 04:08:23 +0900515 message_histogram_.reset(
516 new LinearHistogram(("MsgLoop:" + thread_name_).c_str(),
517 kLeastNonZeroMessageId,
518 kMaxMessageId,
519 kNumberOfDistinctMessagesDisplayed));
initial.commit3f4a7322008-07-27 06:49:38 +0900520 message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
521 message_histogram_->SetRangeDescriptions(event_descriptions_);
522 }
523}
524
525void MessageLoop::HistogramEvent(int event) {
526 if (message_histogram_.get())
527 message_histogram_->Add(event);
528}
529
initial.commit3f4a7322008-07-27 06:49:38 +0900530// Provide a macro that takes an expression (such as a constant, or macro
531// constant) and creates a pair to initalize an array of pairs. In this case,
532// our pair consists of the expressions value, and the "stringized" version
533// of the expression (i.e., the exrpression put in quotes). For example, if
534// we have:
535// #define FOO 2
536// #define BAR 5
537// then the following:
538// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
539// will expand to:
540// {7, "FOO + BAR"}
541// We use the resulting array as an argument to our histogram, which reads the
542// number as a bucket identifier, and proceeds to use the corresponding name
543// in the pair (i.e., the quoted string) when printing out a histogram.
544#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
545
initial.commit3f4a7322008-07-27 06:49:38 +0900546// static
547const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commit3f4a7322008-07-27 06:49:38 +0900548 // Provide some pretty print capability in our histogram for our internal
549 // messages.
550
initial.commit3f4a7322008-07-27 06:49:38 +0900551 // A few events we handle (kindred to messages), and used to profile actions.
552 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commit3f4a7322008-07-27 06:49:38 +0900553 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
554
555 {-1, NULL} // The list must be null terminated, per API to histogram.
556};
license.botf003cfe2008-08-24 09:55:55 +0900557
darin@google.comd936b5b2008-08-26 14:53:57 +0900558//------------------------------------------------------------------------------
559// MessageLoopForUI
560
561#if defined(OS_WIN)
562
563void MessageLoopForUI::Run(Dispatcher* dispatcher) {
564 AutoRunState save_state(this);
565 state_->dispatcher = dispatcher;
566 RunHandler();
567}
568
569void MessageLoopForUI::AddObserver(Observer* observer) {
570 pump_win()->AddObserver(observer);
571}
572
573void MessageLoopForUI::RemoveObserver(Observer* observer) {
574 pump_win()->RemoveObserver(observer);
575}
576
577void MessageLoopForUI::WillProcessMessage(const MSG& message) {
578 pump_win()->WillProcessMessage(message);
579}
580void MessageLoopForUI::DidProcessMessage(const MSG& message) {
581 pump_win()->DidProcessMessage(message);
582}
583void MessageLoopForUI::PumpOutPendingPaintMessages() {
rvargas@google.com73887542008-11-08 06:52:15 +0900584 pump_ui()->PumpOutPendingPaintMessages();
darin@google.comd936b5b2008-08-26 14:53:57 +0900585}
586
587#endif // defined(OS_WIN)
588
589//------------------------------------------------------------------------------
590// MessageLoopForIO
591
592#if defined(OS_WIN)
593
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900594void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
595 pump_io()->RegisterIOHandler(file, handler);
596}
597
rvargas@google.com73887542008-11-08 06:52:15 +0900598bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
599 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900600}
601
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900602#elif defined(OS_POSIX)
603
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900604bool MessageLoopForIO::WatchFileDescriptor(int fd,
605 bool persistent,
606 Mode mode,
607 FileDescriptorWatcher *controller,
608 Watcher *delegate) {
609 return pump_libevent()->WatchFileDescriptor(
610 fd,
611 persistent,
612 static_cast<base::MessagePumpLibevent::Mode>(mode),
613 controller,
614 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900615}
616
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900617#endif