blob: 7a09f38dd962ef19f31347bba8e0c0870af102c3 [file] [log] [blame]
[email protected]e6e55fb2010-04-15 01:04:291// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]ea15e982008-08-15 07:31:205#include "base/message_loop.h"
6
[email protected]fc7fb6e2008-08-16 03:09:057#include <algorithm>
8
[email protected]f1ea2fa2008-08-21 22:26:069#include "base/compiler_specific.h"
[email protected]f886b7bf2008-09-10 10:54:0610#include "base/lazy_instance.h"
initial.commitd7cae122008-07-26 21:49:3811#include "base/logging.h"
[email protected]b16ef312008-08-19 18:36:2312#include "base/message_pump_default.h"
initial.commitd7cae122008-07-26 21:49:3813#include "base/string_util.h"
[email protected]f886b7bf2008-09-10 10:54:0614#include "base/thread_local.h"
initial.commitd7cae122008-07-26 21:49:3815
[email protected]96c9ea12008-09-23 21:08:2816#if defined(OS_MACOSX)
17#include "base/message_pump_mac.h"
18#endif
[email protected]36987e92008-09-18 18:46:2619#if defined(OS_POSIX)
20#include "base/message_pump_libevent.h"
[email protected]d680c5c2009-05-14 16:44:2621#include "base/third_party/valgrind/valgrind.h"
[email protected]36987e92008-09-18 18:46:2622#endif
[email protected]e43eddf12009-12-29 00:32:5223#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]8fc3a482008-10-03 16:52:5924#include "base/message_pump_glib.h"
25#endif
[email protected]36987e92008-09-18 18:46:2626
[email protected]e1acf6f2008-10-27 20:43:3327using base::Time;
28using base::TimeDelta;
29
[email protected]f886b7bf2008-09-10 10:54:0630// A lazily created thread local storage for quick access to a thread's message
31// loop, if one exists. This should be safe and free of static constructors.
32static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
33 base::LINKER_INITIALIZED);
initial.commitd7cae122008-07-26 21:49:3834
35//------------------------------------------------------------------------------
36
initial.commitd7cae122008-07-26 21:49:3837// Logical events for Histogram profiling. Run with -message-loop-histogrammer
38// to get an accounting of messages and actions taken on each thread.
[email protected]fc7fb6e2008-08-16 03:09:0539static const int kTaskRunEvent = 0x1;
40static const int kTimerEvent = 0x2;
initial.commitd7cae122008-07-26 21:49:3841
42// Provide range of message IDs for use in histogramming and debug display.
43static const int kLeastNonZeroMessageId = 1;
44static const int kMaxMessageId = 1099;
45static const int kNumberOfDistinctMessagesDisplayed = 1100;
46
47//------------------------------------------------------------------------------
48
[email protected]fc7fb6e2008-08-16 03:09:0549#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:3850
initial.commitd7cae122008-07-26 21:49:3851// Upon a SEH exception in this thread, it restores the original unhandled
52// exception filter.
53static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
54 ::SetUnhandledExceptionFilter(old_filter);
55 return EXCEPTION_CONTINUE_SEARCH;
56}
57
58// Retrieves a pointer to the current unhandled exception filter. There
59// is no standalone getter method.
60static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
61 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
62 top_filter = ::SetUnhandledExceptionFilter(0);
63 ::SetUnhandledExceptionFilter(top_filter);
64 return top_filter;
65}
66
[email protected]fc7fb6e2008-08-16 03:09:0567#endif // defined(OS_WIN)
68
initial.commitd7cae122008-07-26 21:49:3869//------------------------------------------------------------------------------
70
[email protected]f886b7bf2008-09-10 10:54:0671// static
72MessageLoop* MessageLoop::current() {
73 // TODO(darin): sadly, we cannot enable this yet since people call us even
74 // when they have no intention of using us.
[email protected]2fdc86a2010-01-26 23:08:0275 // DCHECK(loop) << "Ouch, did you forget to initialize me?";
[email protected]f886b7bf2008-09-10 10:54:0676 return lazy_tls_ptr.Pointer()->Get();
77}
78
[email protected]4d9bdfaf2008-08-26 05:53:5779MessageLoop::MessageLoop(Type type)
80 : type_(type),
[email protected]a5b94a92008-08-12 23:25:4381 nestable_tasks_allowed_(true),
[email protected]b16ef312008-08-19 18:36:2382 exception_restoration_(false),
[email protected]752578562008-09-07 08:08:2983 state_(NULL),
84 next_sequence_num_(0) {
[email protected]f886b7bf2008-09-10 10:54:0685 DCHECK(!current()) << "should only have one message loop per thread";
86 lazy_tls_ptr.Pointer()->Set(this);
[email protected]4d9bdfaf2008-08-26 05:53:5787
[email protected]e6e55fb2010-04-15 01:04:2988// TODO(rvargas): Get rid of the OS guards.
[email protected]fc7fb6e2008-08-16 03:09:0589#if defined(OS_WIN)
[email protected]e6e55fb2010-04-15 01:04:2990#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
91#define MESSAGE_PUMP_IO new base::MessagePumpForIO()
92#elif defined(OS_MACOSX)
93#define MESSAGE_PUMP_UI base::MessagePumpMac::Create()
94#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
95#elif defined(OS_POSIX) // POSIX but not MACOSX.
96#define MESSAGE_PUMP_UI new base::MessagePumpForUI()
97#define MESSAGE_PUMP_IO new base::MessagePumpLibevent()
[email protected]e43eddf12009-12-29 00:32:5298#else
[email protected]e6e55fb2010-04-15 01:04:2999#error Not implemented
[email protected]e43eddf12009-12-29 00:32:52100#endif
[email protected]e6e55fb2010-04-15 01:04:29101
102 if (type_ == TYPE_UI) {
103 pump_ = MESSAGE_PUMP_UI;
[email protected]8fc3a482008-10-03 16:52:59104 } else if (type_ == TYPE_IO) {
[email protected]e6e55fb2010-04-15 01:04:29105 pump_ = MESSAGE_PUMP_IO;
[email protected]36987e92008-09-18 18:46:26106 } else {
[email protected]e6e55fb2010-04-15 01:04:29107 DCHECK_EQ(TYPE_DEFAULT, type_);
[email protected]36987e92008-09-18 18:46:26108 pump_ = new base::MessagePumpDefault();
109 }
initial.commitd7cae122008-07-26 21:49:38110}
111
112MessageLoop::~MessageLoop() {
113 DCHECK(this == current());
[email protected]2a127252008-08-05 23:16:41114
115 // Let interested parties have one last shot at accessing this.
116 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
117 WillDestroyCurrentMessageLoop());
118
[email protected]08de3cde2008-09-09 05:55:35119 DCHECK(!state_);
120
[email protected]001747c2008-09-10 00:37:07121 // 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;
[email protected]08de3cde2008-09-09 05:55:35135 }
[email protected]001747c2008-09-10 00:37:07136 DCHECK(!did_work);
137
138 // OK, now make it so that no one can find us.
[email protected]2b89d22b22008-09-10 11:14:56139 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commitd7cae122008-07-26 21:49:38140}
141
[email protected]2a127252008-08-05 23:16:41142void 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
[email protected]ea15e982008-08-15 07:31:20152void MessageLoop::Run() {
[email protected]fc7fb6e2008-08-16 03:09:05153 AutoRunState save_state(this);
154 RunHandler();
[email protected]ea15e982008-08-15 07:31:20155}
156
[email protected]7e0e8762008-07-31 13:10:20157void MessageLoop::RunAllPending() {
[email protected]fc7fb6e2008-08-16 03:09:05158 AutoRunState save_state(this);
159 state_->quit_received = true; // Means run until we would otherwise block.
160 RunHandler();
initial.commitd7cae122008-07-26 21:49:38161}
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.
[email protected]fc7fb6e2008-08-16 03:09:05168void MessageLoop::RunHandler() {
169#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38170 if (exception_restoration_) {
[email protected]aff8a132009-10-26 18:15:59171 RunInternalInSEHFrame();
[email protected]fc7fb6e2008-08-16 03:09:05172 return;
initial.commitd7cae122008-07-26 21:49:38173 }
[email protected]fc7fb6e2008-08-16 03:09:05174#endif
175
176 RunInternal();
initial.commitd7cae122008-07-26 21:49:38177}
[email protected]aff8a132009-10-26 18:15:59178//------------------------------------------------------------------------------
179#if defined(OS_WIN)
180__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
181 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
182 __try {
183 RunInternal();
184 } __except(SEHFilter(current_filter)) {
185 }
186 return;
187}
188#endif
initial.commitd7cae122008-07-26 21:49:38189//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38190
[email protected]fc7fb6e2008-08-16 03:09:05191void MessageLoop::RunInternal() {
192 DCHECK(this == current());
193
initial.commitd7cae122008-07-26 21:49:38194 StartHistogrammer();
195
[email protected]e43eddf12009-12-29 00:32:52196#if !defined(OS_MACOSX)
[email protected]148d1052009-07-31 22:53:37197 if (state_->dispatcher && type() == TYPE_UI) {
198 static_cast<base::MessagePumpForUI*>(pump_.get())->
199 RunWithDispatcher(this, state_->dispatcher);
[email protected]fc7fb6e2008-08-16 03:09:05200 return;
[email protected]7e0e8762008-07-31 13:10:20201 }
[email protected]fc7fb6e2008-08-16 03:09:05202#endif
[email protected]1d2eb132008-12-08 17:36:06203
[email protected]fc7fb6e2008-08-16 03:09:05204 pump_->Run(this);
[email protected]b8f2fe5d2008-07-30 07:50:53205}
[email protected]7622bd02008-07-30 06:58:56206
[email protected]3882c4332008-07-30 19:03:59207//------------------------------------------------------------------------------
208// Wrapper functions for use in above message loop framework.
209
initial.commitd7cae122008-07-26 21:49:38210bool MessageLoop::ProcessNextDelayedNonNestableTask() {
[email protected]fc7fb6e2008-08-16 03:09:05211 if (state_->run_depth != 1)
initial.commitd7cae122008-07-26 21:49:38212 return false;
213
[email protected]752578562008-09-07 08:08:29214 if (deferred_non_nestable_work_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38215 return false;
[email protected]1d2eb132008-12-08 17:36:06216
[email protected]752578562008-09-07 08:08:29217 Task* task = deferred_non_nestable_work_queue_.front().task;
218 deferred_non_nestable_work_queue_.pop();
[email protected]1d2eb132008-12-08 17:36:06219
[email protected]752578562008-09-07 08:08:29220 RunTask(task);
initial.commitd7cae122008-07-26 21:49:38221 return true;
222}
223
initial.commitd7cae122008-07-26 21:49:38224//------------------------------------------------------------------------------
225
226void MessageLoop::Quit() {
[email protected]fc7fb6e2008-08-16 03:09:05227 DCHECK(current() == this);
228 if (state_) {
229 state_->quit_received = true;
230 } else {
231 NOTREACHED() << "Must be inside Run to call Quit";
initial.commitd7cae122008-07-26 21:49:38232 }
initial.commitd7cae122008-07-26 21:49:38233}
234
[email protected]781a7ed2010-02-23 07:12:22235void MessageLoop::QuitNow() {
236 DCHECK(current() == this);
237 if (state_) {
238 pump_->Quit();
239 } else {
240 NOTREACHED() << "Must be inside Run to call Quit";
241 }
242}
243
[email protected]752578562008-09-07 08:08:29244void MessageLoop::PostTask(
245 const tracked_objects::Location& from_here, Task* task) {
246 PostTask_Helper(from_here, task, 0, true);
247}
248
249void MessageLoop::PostDelayedTask(
[email protected]743ace42009-06-17 17:23:51250 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
[email protected]752578562008-09-07 08:08:29251 PostTask_Helper(from_here, task, delay_ms, true);
252}
253
254void MessageLoop::PostNonNestableTask(
255 const tracked_objects::Location& from_here, Task* task) {
256 PostTask_Helper(from_here, task, 0, false);
257}
258
259void MessageLoop::PostNonNestableDelayedTask(
[email protected]743ace42009-06-17 17:23:51260 const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
[email protected]752578562008-09-07 08:08:29261 PostTask_Helper(from_here, task, delay_ms, false);
262}
263
initial.commitd7cae122008-07-26 21:49:38264// Possibly called on a background thread!
[email protected]752578562008-09-07 08:08:29265void MessageLoop::PostTask_Helper(
[email protected]743ace42009-06-17 17:23:51266 const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
[email protected]752578562008-09-07 08:08:29267 bool nestable) {
initial.commitd7cae122008-07-26 21:49:38268 task->SetBirthPlace(from_here);
[email protected]9bcbf472008-08-30 00:22:48269
[email protected]752578562008-09-07 08:08:29270 PendingTask pending_task(task, nestable);
[email protected]9bcbf472008-08-30 00:22:48271
272 if (delay_ms > 0) {
[email protected]752578562008-09-07 08:08:29273 pending_task.delayed_run_time =
[email protected]9bcbf472008-08-30 00:22:48274 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
275 } else {
[email protected]2753b392009-12-28 06:59:52276 DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
[email protected]9bcbf472008-08-30 00:22:48277 }
278
initial.commitd7cae122008-07-26 21:49:38279 // Warning: Don't try to short-circuit, and handle this thread's tasks more
280 // directly, as it could starve handling of foreign threads. Put every task
281 // into this queue.
282
[email protected]fc7fb6e2008-08-16 03:09:05283 scoped_refptr<base::MessagePump> pump;
initial.commitd7cae122008-07-26 21:49:38284 {
[email protected]fc7fb6e2008-08-16 03:09:05285 AutoLock locked(incoming_queue_lock_);
286
[email protected]752578562008-09-07 08:08:29287 bool was_empty = incoming_queue_.empty();
288 incoming_queue_.push(pending_task);
initial.commitd7cae122008-07-26 21:49:38289 if (!was_empty)
290 return; // Someone else should have started the sub-pump.
291
[email protected]fc7fb6e2008-08-16 03:09:05292 pump = pump_;
[email protected]ea15e982008-08-15 07:31:20293 }
[email protected]fc7fb6e2008-08-16 03:09:05294 // Since the incoming_queue_ may contain a task that destroys this message
295 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
296 // We use a stack-based reference to the message pump so that we can call
297 // ScheduleWork outside of incoming_queue_lock_.
[email protected]ea15e982008-08-15 07:31:20298
[email protected]fc7fb6e2008-08-16 03:09:05299 pump->ScheduleWork();
initial.commitd7cae122008-07-26 21:49:38300}
301
302void MessageLoop::SetNestableTasksAllowed(bool allowed) {
[email protected]124a2bdf2008-08-09 00:14:09303 if (nestable_tasks_allowed_ != allowed) {
304 nestable_tasks_allowed_ = allowed;
305 if (!nestable_tasks_allowed_)
306 return;
307 // Start the native pump if we are not already pumping.
[email protected]fc7fb6e2008-08-16 03:09:05308 pump_->ScheduleWork();
[email protected]124a2bdf2008-08-09 00:14:09309 }
initial.commitd7cae122008-07-26 21:49:38310}
311
312bool MessageLoop::NestableTasksAllowed() const {
313 return nestable_tasks_allowed_;
314}
315
[email protected]b5f95102009-07-01 19:53:59316bool MessageLoop::IsNested() {
317 return state_->run_depth > 1;
318}
319
initial.commitd7cae122008-07-26 21:49:38320//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38321
initial.commitd7cae122008-07-26 21:49:38322void MessageLoop::RunTask(Task* task) {
initial.commitd7cae122008-07-26 21:49:38323 DCHECK(nestable_tasks_allowed_);
324 // Execute the task and assume the worst: It is probably not reentrant.
325 nestable_tasks_allowed_ = false;
[email protected]752578562008-09-07 08:08:29326
327 HistogramEvent(kTaskRunEvent);
328 task->Run();
329 delete task;
330
331 nestable_tasks_allowed_ = true;
initial.commitd7cae122008-07-26 21:49:38332}
333
[email protected]752578562008-09-07 08:08:29334bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
335 if (pending_task.nestable || state_->run_depth == 1) {
336 RunTask(pending_task.task);
337 // Show that we ran a task (Note: a new one might arrive as a
338 // consequence!).
339 return true;
340 }
341
342 // We couldn't run the task now because we're in a nested message loop
343 // and the task isn't nestable.
344 deferred_non_nestable_work_queue_.push(pending_task);
345 return false;
initial.commitd7cae122008-07-26 21:49:38346}
347
[email protected]001747c2008-09-10 00:37:07348void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
349 // Move to the delayed work queue. Initialize the sequence number
350 // before inserting into the delayed_work_queue_. The sequence number
351 // is used to faciliate FIFO sorting when two tasks have the same
352 // delayed_run_time value.
353 PendingTask new_pending_task(pending_task);
354 new_pending_task.sequence_num = next_sequence_num_++;
355 delayed_work_queue_.push(new_pending_task);
356}
357
initial.commitd7cae122008-07-26 21:49:38358void MessageLoop::ReloadWorkQueue() {
359 // We can improve performance of our loading tasks from incoming_queue_ to
[email protected]fc7fb6e2008-08-16 03:09:05360 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
361 // load. That reduces the number of locks-per-task significantly when our
[email protected]752578562008-09-07 08:08:29362 // queues get large.
363 if (!work_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38364 return; // Wait till we *really* need to lock and load.
365
366 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commitd7cae122008-07-26 21:49:38367 {
368 AutoLock lock(incoming_queue_lock_);
[email protected]752578562008-09-07 08:08:29369 if (incoming_queue_.empty())
initial.commitd7cae122008-07-26 21:49:38370 return;
[email protected]b2f0ea12009-09-02 20:05:21371 incoming_queue_.Swap(&work_queue_); // Constant time
[email protected]752578562008-09-07 08:08:29372 DCHECK(incoming_queue_.empty());
initial.commitd7cae122008-07-26 21:49:38373 }
374}
375
[email protected]001747c2008-09-10 00:37:07376bool MessageLoop::DeletePendingTasks() {
377 bool did_work = !work_queue_.empty();
378 while (!work_queue_.empty()) {
379 PendingTask pending_task = work_queue_.front();
380 work_queue_.pop();
381 if (!pending_task.delayed_run_time.is_null()) {
382 // We want to delete delayed tasks in the same order in which they would
383 // normally be deleted in case of any funny dependencies between delayed
384 // tasks.
385 AddToDelayedWorkQueue(pending_task);
386 } else {
387 // TODO(darin): Delete all tasks once it is safe to do so.
[email protected]d680c5c2009-05-14 16:44:26388 // Until it is totally safe, just do it when running Purify or
389 // Valgrind.
[email protected]686dd8d2009-07-23 22:28:49390#if defined(PURIFY)
[email protected]404ec5e2009-03-11 20:06:02391 delete pending_task.task;
[email protected]d680c5c2009-05-14 16:44:26392#elif defined(OS_POSIX)
393 if (RUNNING_ON_VALGRIND)
394 delete pending_task.task;
395#endif // defined(OS_POSIX)
[email protected]001747c2008-09-10 00:37:07396 }
initial.commitd7cae122008-07-26 21:49:38397 }
[email protected]001747c2008-09-10 00:37:07398 did_work |= !deferred_non_nestable_work_queue_.empty();
399 while (!deferred_non_nestable_work_queue_.empty()) {
[email protected]20472832009-03-11 19:46:41400 // TODO(darin): Delete all tasks once it is safe to do so.
[email protected]686dd8d2009-07-23 22:28:49401 // Until it is totaly safe, only delete them under Purify and Valgrind.
402 Task* task = NULL;
403#if defined(PURIFY)
404 task = deferred_non_nestable_work_queue_.front().task;
405#elif defined(OS_POSIX)
406 if (RUNNING_ON_VALGRIND)
407 task = deferred_non_nestable_work_queue_.front().task;
[email protected]8df21d32009-03-11 19:53:50408#endif
409 deferred_non_nestable_work_queue_.pop();
[email protected]686dd8d2009-07-23 22:28:49410 if (task)
411 delete task;
initial.commitd7cae122008-07-26 21:49:38412 }
[email protected]001747c2008-09-10 00:37:07413 did_work |= !delayed_work_queue_.empty();
414 while (!delayed_work_queue_.empty()) {
415 Task* task = delayed_work_queue_.top().task;
416 delayed_work_queue_.pop();
417 delete task;
418 }
419 return did_work;
initial.commitd7cae122008-07-26 21:49:38420}
421
[email protected]fc7fb6e2008-08-16 03:09:05422bool MessageLoop::DoWork() {
[email protected]752578562008-09-07 08:08:29423 if (!nestable_tasks_allowed_) {
424 // Task can't be executed right now.
425 return false;
426 }
427
428 for (;;) {
429 ReloadWorkQueue();
430 if (work_queue_.empty())
431 break;
432
433 // Execute oldest task.
434 do {
435 PendingTask pending_task = work_queue_.front();
436 work_queue_.pop();
437 if (!pending_task.delayed_run_time.is_null()) {
[email protected]001747c2008-09-10 00:37:07438 AddToDelayedWorkQueue(pending_task);
[email protected]72deacd2008-09-23 19:19:20439 // If we changed the topmost task, then it is time to re-schedule.
440 if (delayed_work_queue_.top().task == pending_task.task)
[email protected]752578562008-09-07 08:08:29441 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
442 } else {
443 if (DeferOrRunPendingTask(pending_task))
444 return true;
445 }
446 } while (!work_queue_.empty());
447 }
448
449 // Nothing happened.
450 return false;
[email protected]fc7fb6e2008-08-16 03:09:05451}
452
[email protected]b24250fc2008-08-20 06:30:58453bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
[email protected]752578562008-09-07 08:08:29454 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
455 *next_delayed_work_time = Time();
456 return false;
457 }
[email protected]1d2eb132008-12-08 17:36:06458
[email protected]752578562008-09-07 08:08:29459 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
460 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
461 return false;
462 }
[email protected]fc7fb6e2008-08-16 03:09:05463
[email protected]752578562008-09-07 08:08:29464 PendingTask pending_task = delayed_work_queue_.top();
465 delayed_work_queue_.pop();
[email protected]1d2eb132008-12-08 17:36:06466
[email protected]752578562008-09-07 08:08:29467 if (!delayed_work_queue_.empty())
468 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
[email protected]fc7fb6e2008-08-16 03:09:05469
[email protected]752578562008-09-07 08:08:29470 return DeferOrRunPendingTask(pending_task);
[email protected]fc7fb6e2008-08-16 03:09:05471}
472
473bool MessageLoop::DoIdleWork() {
474 if (ProcessNextDelayedNonNestableTask())
475 return true;
476
477 if (state_->quit_received)
478 pump_->Quit();
479
480 return false;
481}
482
483//------------------------------------------------------------------------------
484// MessageLoop::AutoRunState
485
486MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
487 // Make the loop reference us.
488 previous_state_ = loop_->state_;
489 if (previous_state_) {
490 run_depth = previous_state_->run_depth + 1;
[email protected]ea15e982008-08-15 07:31:20491 } else {
[email protected]fc7fb6e2008-08-16 03:09:05492 run_depth = 1;
[email protected]ea15e982008-08-15 07:31:20493 }
[email protected]fc7fb6e2008-08-16 03:09:05494 loop_->state_ = this;
495
496 // Initialize the other fields:
497 quit_received = false;
[email protected]e43eddf12009-12-29 00:32:52498#if !defined(OS_MACOSX)
[email protected]fc7fb6e2008-08-16 03:09:05499 dispatcher = NULL;
500#endif
501}
502
503MessageLoop::AutoRunState::~AutoRunState() {
504 loop_->state_ = previous_state_;
[email protected]a5b94a92008-08-12 23:25:43505}
506
initial.commitd7cae122008-07-26 21:49:38507//------------------------------------------------------------------------------
[email protected]752578562008-09-07 08:08:29508// MessageLoop::PendingTask
initial.commitd7cae122008-07-26 21:49:38509
[email protected]752578562008-09-07 08:08:29510bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
511 // Since the top of a priority queue is defined as the "greatest" element, we
512 // need to invert the comparison here. We want the smaller time to be at the
513 // top of the heap.
initial.commitd7cae122008-07-26 21:49:38514
[email protected]752578562008-09-07 08:08:29515 if (delayed_run_time < other.delayed_run_time)
516 return false;
initial.commitd7cae122008-07-26 21:49:38517
[email protected]752578562008-09-07 08:08:29518 if (delayed_run_time > other.delayed_run_time)
519 return true;
initial.commitd7cae122008-07-26 21:49:38520
[email protected]752578562008-09-07 08:08:29521 // If the times happen to match, then we use the sequence number to decide.
522 // Compare the difference to support integer roll-over.
523 return (sequence_num - other.sequence_num) > 0;
initial.commitd7cae122008-07-26 21:49:38524}
525
526//------------------------------------------------------------------------------
527// Method and data for histogramming events and actions taken by each instance
528// on each thread.
529
530// static
531bool MessageLoop::enable_histogrammer_ = false;
532
533// static
534void MessageLoop::EnableHistogrammer(bool enable) {
535 enable_histogrammer_ = enable;
536}
537
538void MessageLoop::StartHistogrammer() {
539 if (enable_histogrammer_ && !message_histogram_.get()
540 && StatisticsRecorder::WasStarted()) {
[email protected]fc7fb6e2008-08-16 03:09:05541 DCHECK(!thread_name_.empty());
[email protected]2753b392009-12-28 06:59:52542 message_histogram_ = LinearHistogram::FactoryGet("MsgLoop:" + thread_name_,
543 kLeastNonZeroMessageId, kMaxMessageId,
544 kNumberOfDistinctMessagesDisplayed,
545 message_histogram_->kHexRangePrintingFlag);
initial.commitd7cae122008-07-26 21:49:38546 message_histogram_->SetRangeDescriptions(event_descriptions_);
547 }
548}
549
550void MessageLoop::HistogramEvent(int event) {
551 if (message_histogram_.get())
552 message_histogram_->Add(event);
553}
554
initial.commitd7cae122008-07-26 21:49:38555// Provide a macro that takes an expression (such as a constant, or macro
556// constant) and creates a pair to initalize an array of pairs. In this case,
557// our pair consists of the expressions value, and the "stringized" version
558// of the expression (i.e., the exrpression put in quotes). For example, if
559// we have:
560// #define FOO 2
561// #define BAR 5
562// then the following:
563// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
564// will expand to:
565// {7, "FOO + BAR"}
566// We use the resulting array as an argument to our histogram, which reads the
567// number as a bucket identifier, and proceeds to use the corresponding name
568// in the pair (i.e., the quoted string) when printing out a histogram.
569#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
570
initial.commitd7cae122008-07-26 21:49:38571// static
572const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commitd7cae122008-07-26 21:49:38573 // Provide some pretty print capability in our histogram for our internal
574 // messages.
575
initial.commitd7cae122008-07-26 21:49:38576 // A few events we handle (kindred to messages), and used to profile actions.
577 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commitd7cae122008-07-26 21:49:38578 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
579
580 {-1, NULL} // The list must be null terminated, per API to histogram.
581};
license.botbf09a502008-08-24 00:55:55582
[email protected]4d9bdfaf2008-08-26 05:53:57583//------------------------------------------------------------------------------
584// MessageLoopForUI
585
[email protected]4d9bdfaf2008-08-26 05:53:57586#if defined(OS_WIN)
[email protected]4d9bdfaf2008-08-26 05:53:57587void MessageLoopForUI::WillProcessMessage(const MSG& message) {
588 pump_win()->WillProcessMessage(message);
589}
590void MessageLoopForUI::DidProcessMessage(const MSG& message) {
591 pump_win()->DidProcessMessage(message);
592}
593void MessageLoopForUI::PumpOutPendingPaintMessages() {
[email protected]17b89142008-11-07 21:52:15594 pump_ui()->PumpOutPendingPaintMessages();
[email protected]4d9bdfaf2008-08-26 05:53:57595}
596
597#endif // defined(OS_WIN)
598
[email protected]e43eddf12009-12-29 00:32:52599#if !defined(OS_MACOSX)
[email protected]148d1052009-07-31 22:53:37600void MessageLoopForUI::AddObserver(Observer* observer) {
601 pump_ui()->AddObserver(observer);
602}
603
604void MessageLoopForUI::RemoveObserver(Observer* observer) {
605 pump_ui()->RemoveObserver(observer);
606}
607
608void MessageLoopForUI::Run(Dispatcher* dispatcher) {
609 AutoRunState save_state(this);
610 state_->dispatcher = dispatcher;
611 RunHandler();
612}
[email protected]e43eddf12009-12-29 00:32:52613#endif // !defined(OS_MACOSX)
[email protected]148d1052009-07-31 22:53:37614
[email protected]4d9bdfaf2008-08-26 05:53:57615//------------------------------------------------------------------------------
616// MessageLoopForIO
617
618#if defined(OS_WIN)
619
[email protected]32cda29d2008-10-09 23:58:43620void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
621 pump_io()->RegisterIOHandler(file, handler);
622}
623
[email protected]17b89142008-11-07 21:52:15624bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
625 return pump_io()->WaitForIOCompletion(timeout, filter);
[email protected]32cda29d2008-10-09 23:58:43626}
627
[email protected]36987e92008-09-18 18:46:26628#elif defined(OS_POSIX)
629
[email protected]e45e6c02008-12-15 22:02:17630bool MessageLoopForIO::WatchFileDescriptor(int fd,
631 bool persistent,
632 Mode mode,
633 FileDescriptorWatcher *controller,
634 Watcher *delegate) {
635 return pump_libevent()->WatchFileDescriptor(
636 fd,
637 persistent,
638 static_cast<base::MessagePumpLibevent::Mode>(mode),
639 controller,
640 delegate);
[email protected]36987e92008-09-18 18:46:26641}
642
[email protected]36987e92008-09-18 18:46:26643#endif