blob: 1145439c2ce5781ebfd8ab3670e1bc76212250e0 [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// 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.
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
dsh@google.com119a2522008-10-04 01:52:59 +090022#if defined(OS_LINUX)
23#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
196
197 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;
darin@google.combe165ae2008-09-07 17:08:29 +0900209
210 Task* task = deferred_non_nestable_work_queue_.front().task;
211 deferred_non_nestable_work_queue_.pop();
212
213 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.
368 //delete task;
369 }
initial.commit3f4a7322008-07-27 06:49:38 +0900370 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900371 did_work |= !deferred_non_nestable_work_queue_.empty();
372 while (!deferred_non_nestable_work_queue_.empty()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900373 // TODO(darin): Delete all tasks once it is safe to do so.
darin@chromium.orgfea7a862008-09-10 10:16:17 +0900374 //Task* task = deferred_non_nestable_work_queue_.front().task;
375 deferred_non_nestable_work_queue_.pop();
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900376 //delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900377 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900378 did_work |= !delayed_work_queue_.empty();
379 while (!delayed_work_queue_.empty()) {
380 Task* task = delayed_work_queue_.top().task;
381 delayed_work_queue_.pop();
382 delete task;
383 }
384 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900385}
386
darin@google.com981f3552008-08-16 12:09:05 +0900387bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900388 if (!nestable_tasks_allowed_) {
389 // Task can't be executed right now.
390 return false;
391 }
392
393 for (;;) {
394 ReloadWorkQueue();
395 if (work_queue_.empty())
396 break;
397
398 // Execute oldest task.
399 do {
400 PendingTask pending_task = work_queue_.front();
401 work_queue_.pop();
402 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900403 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900404 // If we changed the topmost task, then it is time to re-schedule.
405 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900406 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
407 } else {
408 if (DeferOrRunPendingTask(pending_task))
409 return true;
410 }
411 } while (!work_queue_.empty());
412 }
413
414 // Nothing happened.
415 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900416}
417
darin@google.com6393bed2008-08-20 15:30:58 +0900418bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900419 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
420 *next_delayed_work_time = Time();
421 return false;
422 }
423
424 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
425 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
426 return false;
427 }
darin@google.com981f3552008-08-16 12:09:05 +0900428
darin@google.combe165ae2008-09-07 17:08:29 +0900429 PendingTask pending_task = delayed_work_queue_.top();
430 delayed_work_queue_.pop();
431
432 if (!delayed_work_queue_.empty())
433 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900434
darin@google.combe165ae2008-09-07 17:08:29 +0900435 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900436}
437
438bool MessageLoop::DoIdleWork() {
439 if (ProcessNextDelayedNonNestableTask())
440 return true;
441
442 if (state_->quit_received)
443 pump_->Quit();
444
445 return false;
446}
447
448//------------------------------------------------------------------------------
449// MessageLoop::AutoRunState
450
451MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
452 // Make the loop reference us.
453 previous_state_ = loop_->state_;
454 if (previous_state_) {
455 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900456 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900457 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900458 }
darin@google.com981f3552008-08-16 12:09:05 +0900459 loop_->state_ = this;
460
461 // Initialize the other fields:
462 quit_received = false;
463#if defined(OS_WIN)
464 dispatcher = NULL;
465#endif
466}
467
468MessageLoop::AutoRunState::~AutoRunState() {
469 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900470}
471
initial.commit3f4a7322008-07-27 06:49:38 +0900472//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900473// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900474
darin@google.combe165ae2008-09-07 17:08:29 +0900475bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
476 // Since the top of a priority queue is defined as the "greatest" element, we
477 // need to invert the comparison here. We want the smaller time to be at the
478 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900479
darin@google.combe165ae2008-09-07 17:08:29 +0900480 if (delayed_run_time < other.delayed_run_time)
481 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900482
darin@google.combe165ae2008-09-07 17:08:29 +0900483 if (delayed_run_time > other.delayed_run_time)
484 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900485
darin@google.combe165ae2008-09-07 17:08:29 +0900486 // If the times happen to match, then we use the sequence number to decide.
487 // Compare the difference to support integer roll-over.
488 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900489}
490
491//------------------------------------------------------------------------------
492// Method and data for histogramming events and actions taken by each instance
493// on each thread.
494
495// static
496bool MessageLoop::enable_histogrammer_ = false;
497
498// static
499void MessageLoop::EnableHistogrammer(bool enable) {
500 enable_histogrammer_ = enable;
501}
502
503void MessageLoop::StartHistogrammer() {
504 if (enable_histogrammer_ && !message_histogram_.get()
505 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900506 DCHECK(!thread_name_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900507 message_histogram_.reset(new LinearHistogram(
508 ASCIIToWide("MsgLoop:" + thread_name_).c_str(),
509 kLeastNonZeroMessageId,
510 kMaxMessageId,
511 kNumberOfDistinctMessagesDisplayed));
512 message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
513 message_histogram_->SetRangeDescriptions(event_descriptions_);
514 }
515}
516
517void MessageLoop::HistogramEvent(int event) {
518 if (message_histogram_.get())
519 message_histogram_->Add(event);
520}
521
initial.commit3f4a7322008-07-27 06:49:38 +0900522// Provide a macro that takes an expression (such as a constant, or macro
523// constant) and creates a pair to initalize an array of pairs. In this case,
524// our pair consists of the expressions value, and the "stringized" version
525// of the expression (i.e., the exrpression put in quotes). For example, if
526// we have:
527// #define FOO 2
528// #define BAR 5
529// then the following:
530// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
531// will expand to:
532// {7, "FOO + BAR"}
533// We use the resulting array as an argument to our histogram, which reads the
534// number as a bucket identifier, and proceeds to use the corresponding name
535// in the pair (i.e., the quoted string) when printing out a histogram.
536#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
537
initial.commit3f4a7322008-07-27 06:49:38 +0900538// static
539const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commit3f4a7322008-07-27 06:49:38 +0900540 // Provide some pretty print capability in our histogram for our internal
541 // messages.
542
initial.commit3f4a7322008-07-27 06:49:38 +0900543 // A few events we handle (kindred to messages), and used to profile actions.
544 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commit3f4a7322008-07-27 06:49:38 +0900545 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
546
547 {-1, NULL} // The list must be null terminated, per API to histogram.
548};
license.botf003cfe2008-08-24 09:55:55 +0900549
darin@google.comd936b5b2008-08-26 14:53:57 +0900550//------------------------------------------------------------------------------
551// MessageLoopForUI
552
553#if defined(OS_WIN)
554
555void MessageLoopForUI::Run(Dispatcher* dispatcher) {
556 AutoRunState save_state(this);
557 state_->dispatcher = dispatcher;
558 RunHandler();
559}
560
561void MessageLoopForUI::AddObserver(Observer* observer) {
562 pump_win()->AddObserver(observer);
563}
564
565void MessageLoopForUI::RemoveObserver(Observer* observer) {
566 pump_win()->RemoveObserver(observer);
567}
568
569void MessageLoopForUI::WillProcessMessage(const MSG& message) {
570 pump_win()->WillProcessMessage(message);
571}
572void MessageLoopForUI::DidProcessMessage(const MSG& message) {
573 pump_win()->DidProcessMessage(message);
574}
575void MessageLoopForUI::PumpOutPendingPaintMessages() {
rvargas@google.com73887542008-11-08 06:52:15 +0900576 pump_ui()->PumpOutPendingPaintMessages();
darin@google.comd936b5b2008-08-26 14:53:57 +0900577}
578
579#endif // defined(OS_WIN)
580
581//------------------------------------------------------------------------------
582// MessageLoopForIO
583
584#if defined(OS_WIN)
585
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900586void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
587 pump_io()->RegisterIOHandler(file, handler);
588}
589
rvargas@google.com73887542008-11-08 06:52:15 +0900590bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
591 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900592}
593
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900594#elif defined(OS_POSIX)
595
596void MessageLoopForIO::WatchSocket(int socket, short interest_mask,
597 struct event* e, Watcher* watcher) {
598 pump_libevent()->WatchSocket(socket, interest_mask, e, watcher);
599}
600
601void MessageLoopForIO::UnwatchSocket(struct event* e) {
602 pump_libevent()->UnwatchSocket(e);
603}
604#endif