blob: 3f216dc98bb9a0f7cc82fcc23de8be10d736e644 [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
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
370 delete task;
371#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 Task* task = deferred_non_nestable_work_queue_.front().task;
darin@chromium.orgfea7a862008-09-10 10:16:17 +0900377 deferred_non_nestable_work_queue_.pop();
jar@chromium.org47fb2852009-03-12 04:46:41 +0900378 // TODO(darin): Delete all tasks once it is safe to do so.
379 // Until it is totaly safe, just delete them to keep purify happy.
380#ifdef PURIFY
381 delete task;
382#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900383 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900384 did_work |= !delayed_work_queue_.empty();
385 while (!delayed_work_queue_.empty()) {
386 Task* task = delayed_work_queue_.top().task;
387 delayed_work_queue_.pop();
388 delete task;
389 }
390 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900391}
392
darin@google.com981f3552008-08-16 12:09:05 +0900393bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900394 if (!nestable_tasks_allowed_) {
395 // Task can't be executed right now.
396 return false;
397 }
398
399 for (;;) {
400 ReloadWorkQueue();
401 if (work_queue_.empty())
402 break;
403
404 // Execute oldest task.
405 do {
406 PendingTask pending_task = work_queue_.front();
407 work_queue_.pop();
408 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900409 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900410 // If we changed the topmost task, then it is time to re-schedule.
411 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900412 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
413 } else {
414 if (DeferOrRunPendingTask(pending_task))
415 return true;
416 }
417 } while (!work_queue_.empty());
418 }
419
420 // Nothing happened.
421 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900422}
423
darin@google.com6393bed2008-08-20 15:30:58 +0900424bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900425 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
426 *next_delayed_work_time = Time();
427 return false;
428 }
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900429
darin@google.combe165ae2008-09-07 17:08:29 +0900430 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
431 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
432 return false;
433 }
darin@google.com981f3552008-08-16 12:09:05 +0900434
darin@google.combe165ae2008-09-07 17:08:29 +0900435 PendingTask pending_task = delayed_work_queue_.top();
436 delayed_work_queue_.pop();
jeremy@chromium.org2ed223c2008-12-09 02:36:06 +0900437
darin@google.combe165ae2008-09-07 17:08:29 +0900438 if (!delayed_work_queue_.empty())
439 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900440
darin@google.combe165ae2008-09-07 17:08:29 +0900441 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900442}
443
444bool MessageLoop::DoIdleWork() {
445 if (ProcessNextDelayedNonNestableTask())
446 return true;
447
448 if (state_->quit_received)
449 pump_->Quit();
450
451 return false;
452}
453
454//------------------------------------------------------------------------------
455// MessageLoop::AutoRunState
456
457MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
458 // Make the loop reference us.
459 previous_state_ = loop_->state_;
460 if (previous_state_) {
461 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900462 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900463 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900464 }
darin@google.com981f3552008-08-16 12:09:05 +0900465 loop_->state_ = this;
466
467 // Initialize the other fields:
468 quit_received = false;
469#if defined(OS_WIN)
470 dispatcher = NULL;
471#endif
472}
473
474MessageLoop::AutoRunState::~AutoRunState() {
475 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900476}
477
initial.commit3f4a7322008-07-27 06:49:38 +0900478//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900479// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900480
darin@google.combe165ae2008-09-07 17:08:29 +0900481bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
482 // Since the top of a priority queue is defined as the "greatest" element, we
483 // need to invert the comparison here. We want the smaller time to be at the
484 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900485
darin@google.combe165ae2008-09-07 17:08:29 +0900486 if (delayed_run_time < other.delayed_run_time)
487 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900488
darin@google.combe165ae2008-09-07 17:08:29 +0900489 if (delayed_run_time > other.delayed_run_time)
490 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900491
darin@google.combe165ae2008-09-07 17:08:29 +0900492 // If the times happen to match, then we use the sequence number to decide.
493 // Compare the difference to support integer roll-over.
494 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900495}
496
497//------------------------------------------------------------------------------
498// Method and data for histogramming events and actions taken by each instance
499// on each thread.
500
501// static
502bool MessageLoop::enable_histogrammer_ = false;
503
504// static
505void MessageLoop::EnableHistogrammer(bool enable) {
506 enable_histogrammer_ = enable;
507}
508
509void MessageLoop::StartHistogrammer() {
510 if (enable_histogrammer_ && !message_histogram_.get()
511 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900512 DCHECK(!thread_name_.empty());
dsh@google.com6e7eb9f2009-02-25 04:08:23 +0900513 message_histogram_.reset(
514 new LinearHistogram(("MsgLoop:" + thread_name_).c_str(),
515 kLeastNonZeroMessageId,
516 kMaxMessageId,
517 kNumberOfDistinctMessagesDisplayed));
initial.commit3f4a7322008-07-27 06:49:38 +0900518 message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
519 message_histogram_->SetRangeDescriptions(event_descriptions_);
520 }
521}
522
523void MessageLoop::HistogramEvent(int event) {
524 if (message_histogram_.get())
525 message_histogram_->Add(event);
526}
527
initial.commit3f4a7322008-07-27 06:49:38 +0900528// Provide a macro that takes an expression (such as a constant, or macro
529// constant) and creates a pair to initalize an array of pairs. In this case,
530// our pair consists of the expressions value, and the "stringized" version
531// of the expression (i.e., the exrpression put in quotes). For example, if
532// we have:
533// #define FOO 2
534// #define BAR 5
535// then the following:
536// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
537// will expand to:
538// {7, "FOO + BAR"}
539// We use the resulting array as an argument to our histogram, which reads the
540// number as a bucket identifier, and proceeds to use the corresponding name
541// in the pair (i.e., the quoted string) when printing out a histogram.
542#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
543
initial.commit3f4a7322008-07-27 06:49:38 +0900544// static
545const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commit3f4a7322008-07-27 06:49:38 +0900546 // Provide some pretty print capability in our histogram for our internal
547 // messages.
548
initial.commit3f4a7322008-07-27 06:49:38 +0900549 // A few events we handle (kindred to messages), and used to profile actions.
550 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commit3f4a7322008-07-27 06:49:38 +0900551 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
552
553 {-1, NULL} // The list must be null terminated, per API to histogram.
554};
license.botf003cfe2008-08-24 09:55:55 +0900555
darin@google.comd936b5b2008-08-26 14:53:57 +0900556//------------------------------------------------------------------------------
557// MessageLoopForUI
558
559#if defined(OS_WIN)
560
561void MessageLoopForUI::Run(Dispatcher* dispatcher) {
562 AutoRunState save_state(this);
563 state_->dispatcher = dispatcher;
564 RunHandler();
565}
566
567void MessageLoopForUI::AddObserver(Observer* observer) {
568 pump_win()->AddObserver(observer);
569}
570
571void MessageLoopForUI::RemoveObserver(Observer* observer) {
572 pump_win()->RemoveObserver(observer);
573}
574
575void MessageLoopForUI::WillProcessMessage(const MSG& message) {
576 pump_win()->WillProcessMessage(message);
577}
578void MessageLoopForUI::DidProcessMessage(const MSG& message) {
579 pump_win()->DidProcessMessage(message);
580}
581void MessageLoopForUI::PumpOutPendingPaintMessages() {
rvargas@google.com73887542008-11-08 06:52:15 +0900582 pump_ui()->PumpOutPendingPaintMessages();
darin@google.comd936b5b2008-08-26 14:53:57 +0900583}
584
585#endif // defined(OS_WIN)
586
587//------------------------------------------------------------------------------
588// MessageLoopForIO
589
590#if defined(OS_WIN)
591
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900592void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
593 pump_io()->RegisterIOHandler(file, handler);
594}
595
rvargas@google.com73887542008-11-08 06:52:15 +0900596bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
597 return pump_io()->WaitForIOCompletion(timeout, filter);
rvargas@google.com9e49aa22008-10-10 08:58:43 +0900598}
599
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900600#elif defined(OS_POSIX)
601
jeremy@chromium.orgefc0db02008-12-16 07:02:17 +0900602bool MessageLoopForIO::WatchFileDescriptor(int fd,
603 bool persistent,
604 Mode mode,
605 FileDescriptorWatcher *controller,
606 Watcher *delegate) {
607 return pump_libevent()->WatchFileDescriptor(
608 fd,
609 persistent,
610 static_cast<base::MessagePumpLibevent::Mode>(mode),
611 controller,
612 delegate);
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900613}
614
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900615#endif