blob: cc87fe6f296844dc5aa4f81aa27fe4fa3d3814b8 [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
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090026// A lazily created thread local storage for quick access to a thread's message
27// loop, if one exists. This should be safe and free of static constructors.
28static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
29 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090030
31//------------------------------------------------------------------------------
32
initial.commit3f4a7322008-07-27 06:49:38 +090033// Logical events for Histogram profiling. Run with -message-loop-histogrammer
34// to get an accounting of messages and actions taken on each thread.
darin@google.com981f3552008-08-16 12:09:05 +090035static const int kTaskRunEvent = 0x1;
36static const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090037
38// Provide range of message IDs for use in histogramming and debug display.
39static const int kLeastNonZeroMessageId = 1;
40static const int kMaxMessageId = 1099;
41static const int kNumberOfDistinctMessagesDisplayed = 1100;
42
43//------------------------------------------------------------------------------
44
darin@google.com981f3552008-08-16 12:09:05 +090045#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090046
initial.commit3f4a7322008-07-27 06:49:38 +090047// Upon a SEH exception in this thread, it restores the original unhandled
48// exception filter.
49static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
50 ::SetUnhandledExceptionFilter(old_filter);
51 return EXCEPTION_CONTINUE_SEARCH;
52}
53
54// Retrieves a pointer to the current unhandled exception filter. There
55// is no standalone getter method.
56static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
57 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
58 top_filter = ::SetUnhandledExceptionFilter(0);
59 ::SetUnhandledExceptionFilter(top_filter);
60 return top_filter;
61}
62
darin@google.com981f3552008-08-16 12:09:05 +090063#endif // defined(OS_WIN)
64
initial.commit3f4a7322008-07-27 06:49:38 +090065//------------------------------------------------------------------------------
66
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090067// static
68MessageLoop* MessageLoop::current() {
69 // TODO(darin): sadly, we cannot enable this yet since people call us even
70 // when they have no intention of using us.
71 //DCHECK(loop) << "Ouch, did you forget to initialize me?";
72 return lazy_tls_ptr.Pointer()->Get();
73}
74
darin@google.comd936b5b2008-08-26 14:53:57 +090075MessageLoop::MessageLoop(Type type)
76 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +090077 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +090078 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +090079 state_(NULL),
80 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090081 DCHECK(!current()) << "should only have one message loop per thread";
82 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +090083
darin@google.com981f3552008-08-16 12:09:05 +090084#if defined(OS_WIN)
rvargas@google.com670c3122008-09-26 05:33:04 +090085 // TODO(rvargas): Get rid of the OS guards.
darin@google.com0795f572008-08-30 09:22:48 +090086 if (type_ == TYPE_DEFAULT) {
87 pump_ = new base::MessagePumpDefault();
rvargas@google.com670c3122008-09-26 05:33:04 +090088 } else if (type_ == TYPE_IO) {
89 pump_ = new base::MessagePumpForIO();
darin@google.com0795f572008-08-30 09:22:48 +090090 } else {
rvargas@google.com670c3122008-09-26 05:33:04 +090091 DCHECK(type_ == TYPE_UI);
92 pump_ = new base::MessagePumpForUI();
darin@google.com0795f572008-08-30 09:22:48 +090093 }
dkegel@google.com9e044ae2008-09-19 03:46:26 +090094#elif defined(OS_POSIX)
mark@chromium.org059d0492008-09-24 06:08:28 +090095 if (type_ == TYPE_UI) {
dsh@google.com119a2522008-10-04 01:52:59 +090096#if defined(OS_MACOSX)
mark@chromium.org059d0492008-09-24 06:08:28 +090097 pump_ = base::MessagePumpMac::Create();
dsh@google.com119a2522008-10-04 01:52:59 +090098#elif defined(OS_LINUX)
99 pump_ = new base::MessagePumpForUI();
100#endif // OS_LINUX
101 } else if (type_ == TYPE_IO) {
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900102 pump_ = new base::MessagePumpLibevent();
103 } else {
104 pump_ = new base::MessagePumpDefault();
105 }
mark@chromium.org059d0492008-09-24 06:08:28 +0900106#endif // OS_POSIX
initial.commit3f4a7322008-07-27 06:49:38 +0900107}
108
109MessageLoop::~MessageLoop() {
110 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900111
112 // Let interested parties have one last shot at accessing this.
113 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
114 WillDestroyCurrentMessageLoop());
115
darin@google.com0e500502008-09-09 14:55:35 +0900116 DCHECK(!state_);
117
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900118 // Clean up any unprocessed tasks, but take care: deleting a task could
119 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
120 // limit on the number of times we will allow a deleted task to generate more
121 // tasks. Normally, we should only pass through this loop once or twice. If
122 // we end up hitting the loop limit, then it is probably due to one task that
123 // is being stubborn. Inspect the queues to see who is left.
124 bool did_work;
125 for (int i = 0; i < 100; ++i) {
126 DeletePendingTasks();
127 ReloadWorkQueue();
128 // If we end up with empty queues, then break out of the loop.
129 did_work = DeletePendingTasks();
130 if (!did_work)
131 break;
darin@google.com0e500502008-09-09 14:55:35 +0900132 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900133 DCHECK(!did_work);
134
135 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900136 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900137}
138
darin@google.com965e5342008-08-06 08:16:41 +0900139void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
140 DCHECK(this == current());
141 destruction_observers_.AddObserver(obs);
142}
143
144void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
145 DCHECK(this == current());
146 destruction_observers_.RemoveObserver(obs);
147}
148
darin@google.com6ddeb842008-08-15 16:31:20 +0900149void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900150 AutoRunState save_state(this);
151 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900152}
153
jar@google.com9239e022008-07-31 22:10:20 +0900154void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900155 AutoRunState save_state(this);
156 state_->quit_received = true; // Means run until we would otherwise block.
157 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900158}
159
160// Runs the loop in two different SEH modes:
161// enable_SEH_restoration_ = false : any unhandled exception goes to the last
162// one that calls SetUnhandledExceptionFilter().
163// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
164// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900165void MessageLoop::RunHandler() {
166#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900167 if (exception_restoration_) {
168 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
169 __try {
darin@google.com981f3552008-08-16 12:09:05 +0900170 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900171 } __except(SEHFilter(current_filter)) {
172 }
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}
179
180//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900181
darin@google.com981f3552008-08-16 12:09:05 +0900182void MessageLoop::RunInternal() {
183 DCHECK(this == current());
184
initial.commit3f4a7322008-07-27 06:49:38 +0900185 StartHistogrammer();
186
darin@google.com981f3552008-08-16 12:09:05 +0900187#if defined(OS_WIN)
188 if (state_->dispatcher) {
189 pump_win()->RunWithDispatcher(this, state_->dispatcher);
190 return;
jar@google.com9239e022008-07-31 22:10:20 +0900191 }
darin@google.com981f3552008-08-16 12:09:05 +0900192#endif
193
194 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900195}
jar@google.com7ff36e62008-07-30 15:58:56 +0900196
jar@google.comb4d1bff2008-07-31 04:03:59 +0900197//------------------------------------------------------------------------------
198// Wrapper functions for use in above message loop framework.
199
initial.commit3f4a7322008-07-27 06:49:38 +0900200bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900201 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900202 return false;
203
darin@google.combe165ae2008-09-07 17:08:29 +0900204 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900205 return false;
darin@google.combe165ae2008-09-07 17:08:29 +0900206
207 Task* task = deferred_non_nestable_work_queue_.front().task;
208 deferred_non_nestable_work_queue_.pop();
209
210 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900211 return true;
212}
213
initial.commit3f4a7322008-07-27 06:49:38 +0900214//------------------------------------------------------------------------------
215
216void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900217 DCHECK(current() == this);
218 if (state_) {
219 state_->quit_received = true;
220 } else {
221 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900222 }
initial.commit3f4a7322008-07-27 06:49:38 +0900223}
224
darin@google.combe165ae2008-09-07 17:08:29 +0900225void MessageLoop::PostTask(
226 const tracked_objects::Location& from_here, Task* task) {
227 PostTask_Helper(from_here, task, 0, true);
228}
229
230void MessageLoop::PostDelayedTask(
231 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
232 PostTask_Helper(from_here, task, delay_ms, true);
233}
234
235void MessageLoop::PostNonNestableTask(
236 const tracked_objects::Location& from_here, Task* task) {
237 PostTask_Helper(from_here, task, 0, false);
238}
239
240void MessageLoop::PostNonNestableDelayedTask(
241 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
242 PostTask_Helper(from_here, task, delay_ms, false);
243}
244
initial.commit3f4a7322008-07-27 06:49:38 +0900245// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900246void MessageLoop::PostTask_Helper(
247 const tracked_objects::Location& from_here, Task* task, int delay_ms,
248 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900249 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900250
darin@google.combe165ae2008-09-07 17:08:29 +0900251 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900252
253 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900254 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900255 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
256 } else {
257 DCHECK(delay_ms == 0) << "delay should not be negative";
258 }
259
initial.commit3f4a7322008-07-27 06:49:38 +0900260 // Warning: Don't try to short-circuit, and handle this thread's tasks more
261 // directly, as it could starve handling of foreign threads. Put every task
262 // into this queue.
263
darin@google.com981f3552008-08-16 12:09:05 +0900264 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900265 {
darin@google.com981f3552008-08-16 12:09:05 +0900266 AutoLock locked(incoming_queue_lock_);
267
darin@google.combe165ae2008-09-07 17:08:29 +0900268 bool was_empty = incoming_queue_.empty();
269 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900270 if (!was_empty)
271 return; // Someone else should have started the sub-pump.
272
darin@google.com981f3552008-08-16 12:09:05 +0900273 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900274 }
darin@google.com981f3552008-08-16 12:09:05 +0900275 // Since the incoming_queue_ may contain a task that destroys this message
276 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
277 // We use a stack-based reference to the message pump so that we can call
278 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900279
darin@google.com981f3552008-08-16 12:09:05 +0900280 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900281}
282
283void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900284 if (nestable_tasks_allowed_ != allowed) {
285 nestable_tasks_allowed_ = allowed;
286 if (!nestable_tasks_allowed_)
287 return;
288 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900289 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900290 }
initial.commit3f4a7322008-07-27 06:49:38 +0900291}
292
293bool MessageLoop::NestableTasksAllowed() const {
294 return nestable_tasks_allowed_;
295}
296
initial.commit3f4a7322008-07-27 06:49:38 +0900297//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900298
initial.commit3f4a7322008-07-27 06:49:38 +0900299void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900300 DCHECK(nestable_tasks_allowed_);
301 // Execute the task and assume the worst: It is probably not reentrant.
302 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900303
304 HistogramEvent(kTaskRunEvent);
305 task->Run();
306 delete task;
307
308 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900309}
310
darin@google.combe165ae2008-09-07 17:08:29 +0900311bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
312 if (pending_task.nestable || state_->run_depth == 1) {
313 RunTask(pending_task.task);
314 // Show that we ran a task (Note: a new one might arrive as a
315 // consequence!).
316 return true;
317 }
318
319 // We couldn't run the task now because we're in a nested message loop
320 // and the task isn't nestable.
321 deferred_non_nestable_work_queue_.push(pending_task);
322 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900323}
324
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900325void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
326 // Move to the delayed work queue. Initialize the sequence number
327 // before inserting into the delayed_work_queue_. The sequence number
328 // is used to faciliate FIFO sorting when two tasks have the same
329 // delayed_run_time value.
330 PendingTask new_pending_task(pending_task);
331 new_pending_task.sequence_num = next_sequence_num_++;
332 delayed_work_queue_.push(new_pending_task);
333}
334
initial.commit3f4a7322008-07-27 06:49:38 +0900335void MessageLoop::ReloadWorkQueue() {
336 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900337 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
338 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900339 // queues get large.
340 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900341 return; // Wait till we *really* need to lock and load.
342
343 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900344 {
345 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900346 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900347 return;
darin@google.combe165ae2008-09-07 17:08:29 +0900348 std::swap(incoming_queue_, work_queue_);
349 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900350 }
351}
352
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900353bool MessageLoop::DeletePendingTasks() {
354 bool did_work = !work_queue_.empty();
355 while (!work_queue_.empty()) {
356 PendingTask pending_task = work_queue_.front();
357 work_queue_.pop();
358 if (!pending_task.delayed_run_time.is_null()) {
359 // We want to delete delayed tasks in the same order in which they would
360 // normally be deleted in case of any funny dependencies between delayed
361 // tasks.
362 AddToDelayedWorkQueue(pending_task);
363 } else {
364 // TODO(darin): Delete all tasks once it is safe to do so.
365 //delete task;
366 }
initial.commit3f4a7322008-07-27 06:49:38 +0900367 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900368 did_work |= !deferred_non_nestable_work_queue_.empty();
369 while (!deferred_non_nestable_work_queue_.empty()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900370 // TODO(darin): Delete all tasks once it is safe to do so.
darin@chromium.orgfea7a862008-09-10 10:16:17 +0900371 //Task* task = deferred_non_nestable_work_queue_.front().task;
372 deferred_non_nestable_work_queue_.pop();
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900373 //delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900374 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900375 did_work |= !delayed_work_queue_.empty();
376 while (!delayed_work_queue_.empty()) {
377 Task* task = delayed_work_queue_.top().task;
378 delayed_work_queue_.pop();
379 delete task;
380 }
381 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900382}
383
darin@google.com981f3552008-08-16 12:09:05 +0900384bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900385 if (!nestable_tasks_allowed_) {
386 // Task can't be executed right now.
387 return false;
388 }
389
390 for (;;) {
391 ReloadWorkQueue();
392 if (work_queue_.empty())
393 break;
394
395 // Execute oldest task.
396 do {
397 PendingTask pending_task = work_queue_.front();
398 work_queue_.pop();
399 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900400 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900401 // If we changed the topmost task, then it is time to re-schedule.
402 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900403 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
404 } else {
405 if (DeferOrRunPendingTask(pending_task))
406 return true;
407 }
408 } while (!work_queue_.empty());
409 }
410
411 // Nothing happened.
412 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900413}
414
darin@google.com6393bed2008-08-20 15:30:58 +0900415bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900416 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
417 *next_delayed_work_time = Time();
418 return false;
419 }
420
421 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
422 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
423 return false;
424 }
darin@google.com981f3552008-08-16 12:09:05 +0900425
darin@google.combe165ae2008-09-07 17:08:29 +0900426 PendingTask pending_task = delayed_work_queue_.top();
427 delayed_work_queue_.pop();
428
429 if (!delayed_work_queue_.empty())
430 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900431
darin@google.combe165ae2008-09-07 17:08:29 +0900432 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900433}
434
435bool MessageLoop::DoIdleWork() {
436 if (ProcessNextDelayedNonNestableTask())
437 return true;
438
439 if (state_->quit_received)
440 pump_->Quit();
441
442 return false;
443}
444
445//------------------------------------------------------------------------------
446// MessageLoop::AutoRunState
447
448MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
449 // Make the loop reference us.
450 previous_state_ = loop_->state_;
451 if (previous_state_) {
452 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900453 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900454 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900455 }
darin@google.com981f3552008-08-16 12:09:05 +0900456 loop_->state_ = this;
457
458 // Initialize the other fields:
459 quit_received = false;
460#if defined(OS_WIN)
461 dispatcher = NULL;
462#endif
463}
464
465MessageLoop::AutoRunState::~AutoRunState() {
466 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900467}
468
initial.commit3f4a7322008-07-27 06:49:38 +0900469//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900470// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900471
darin@google.combe165ae2008-09-07 17:08:29 +0900472bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
473 // Since the top of a priority queue is defined as the "greatest" element, we
474 // need to invert the comparison here. We want the smaller time to be at the
475 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900476
darin@google.combe165ae2008-09-07 17:08:29 +0900477 if (delayed_run_time < other.delayed_run_time)
478 return false;
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 true;
initial.commit3f4a7322008-07-27 06:49:38 +0900482
darin@google.combe165ae2008-09-07 17:08:29 +0900483 // If the times happen to match, then we use the sequence number to decide.
484 // Compare the difference to support integer roll-over.
485 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900486}
487
488//------------------------------------------------------------------------------
489// Method and data for histogramming events and actions taken by each instance
490// on each thread.
491
492// static
493bool MessageLoop::enable_histogrammer_ = false;
494
495// static
496void MessageLoop::EnableHistogrammer(bool enable) {
497 enable_histogrammer_ = enable;
498}
499
500void MessageLoop::StartHistogrammer() {
501 if (enable_histogrammer_ && !message_histogram_.get()
502 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900503 DCHECK(!thread_name_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900504 message_histogram_.reset(new LinearHistogram(
505 ASCIIToWide("MsgLoop:" + thread_name_).c_str(),
506 kLeastNonZeroMessageId,
507 kMaxMessageId,
508 kNumberOfDistinctMessagesDisplayed));
509 message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
510 message_histogram_->SetRangeDescriptions(event_descriptions_);
511 }
512}
513
514void MessageLoop::HistogramEvent(int event) {
515 if (message_histogram_.get())
516 message_histogram_->Add(event);
517}
518
initial.commit3f4a7322008-07-27 06:49:38 +0900519// Provide a macro that takes an expression (such as a constant, or macro
520// constant) and creates a pair to initalize an array of pairs. In this case,
521// our pair consists of the expressions value, and the "stringized" version
522// of the expression (i.e., the exrpression put in quotes). For example, if
523// we have:
524// #define FOO 2
525// #define BAR 5
526// then the following:
527// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
528// will expand to:
529// {7, "FOO + BAR"}
530// We use the resulting array as an argument to our histogram, which reads the
531// number as a bucket identifier, and proceeds to use the corresponding name
532// in the pair (i.e., the quoted string) when printing out a histogram.
533#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
534
initial.commit3f4a7322008-07-27 06:49:38 +0900535// static
536const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commit3f4a7322008-07-27 06:49:38 +0900537 // Provide some pretty print capability in our histogram for our internal
538 // messages.
539
initial.commit3f4a7322008-07-27 06:49:38 +0900540 // A few events we handle (kindred to messages), and used to profile actions.
541 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commit3f4a7322008-07-27 06:49:38 +0900542 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
543
544 {-1, NULL} // The list must be null terminated, per API to histogram.
545};
license.botf003cfe2008-08-24 09:55:55 +0900546
darin@google.comd936b5b2008-08-26 14:53:57 +0900547//------------------------------------------------------------------------------
548// MessageLoopForUI
549
550#if defined(OS_WIN)
551
552void MessageLoopForUI::Run(Dispatcher* dispatcher) {
553 AutoRunState save_state(this);
554 state_->dispatcher = dispatcher;
555 RunHandler();
556}
557
558void MessageLoopForUI::AddObserver(Observer* observer) {
559 pump_win()->AddObserver(observer);
560}
561
562void MessageLoopForUI::RemoveObserver(Observer* observer) {
563 pump_win()->RemoveObserver(observer);
564}
565
566void MessageLoopForUI::WillProcessMessage(const MSG& message) {
567 pump_win()->WillProcessMessage(message);
568}
569void MessageLoopForUI::DidProcessMessage(const MSG& message) {
570 pump_win()->DidProcessMessage(message);
571}
572void MessageLoopForUI::PumpOutPendingPaintMessages() {
573 pump_win()->PumpOutPendingPaintMessages();
574}
575
576#endif // defined(OS_WIN)
577
578//------------------------------------------------------------------------------
579// MessageLoopForIO
580
581#if defined(OS_WIN)
582
583void MessageLoopForIO::WatchObject(HANDLE object, Watcher* watcher) {
rvargas@google.com670c3122008-09-26 05:33:04 +0900584 pump_io()->WatchObject(object, watcher);
darin@google.comd936b5b2008-08-26 14:53:57 +0900585}
586
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900587void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
588 pump_io()->RegisterIOHandler(file, handler);
589}
590
591void MessageLoopForIO::RegisterIOContext(OVERLAPPED* context,
592 IOHandler* handler) {
593 pump_io()->RegisterIOContext(context, handler);
594}
595
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900596#elif defined(OS_POSIX)
597
598void MessageLoopForIO::WatchSocket(int socket, short interest_mask,
599 struct event* e, Watcher* watcher) {
600 pump_libevent()->WatchSocket(socket, interest_mask, e, watcher);
601}
602
603void MessageLoopForIO::UnwatchSocket(struct event* e) {
604 pump_libevent()->UnwatchSocket(e);
605}
606#endif