blob: 60a8ce5689c815ce5938663950c1b926e08b359e [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
22
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090023// A lazily created thread local storage for quick access to a thread's message
24// loop, if one exists. This should be safe and free of static constructors.
25static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
26 base::LINKER_INITIALIZED);
initial.commit3f4a7322008-07-27 06:49:38 +090027
28//------------------------------------------------------------------------------
29
initial.commit3f4a7322008-07-27 06:49:38 +090030// Logical events for Histogram profiling. Run with -message-loop-histogrammer
31// to get an accounting of messages and actions taken on each thread.
darin@google.com981f3552008-08-16 12:09:05 +090032static const int kTaskRunEvent = 0x1;
33static const int kTimerEvent = 0x2;
initial.commit3f4a7322008-07-27 06:49:38 +090034
35// Provide range of message IDs for use in histogramming and debug display.
36static const int kLeastNonZeroMessageId = 1;
37static const int kMaxMessageId = 1099;
38static const int kNumberOfDistinctMessagesDisplayed = 1100;
39
40//------------------------------------------------------------------------------
41
darin@google.com981f3552008-08-16 12:09:05 +090042#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +090043
initial.commit3f4a7322008-07-27 06:49:38 +090044// Upon a SEH exception in this thread, it restores the original unhandled
45// exception filter.
46static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
47 ::SetUnhandledExceptionFilter(old_filter);
48 return EXCEPTION_CONTINUE_SEARCH;
49}
50
51// Retrieves a pointer to the current unhandled exception filter. There
52// is no standalone getter method.
53static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
54 LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
55 top_filter = ::SetUnhandledExceptionFilter(0);
56 ::SetUnhandledExceptionFilter(top_filter);
57 return top_filter;
58}
59
darin@google.com981f3552008-08-16 12:09:05 +090060#endif // defined(OS_WIN)
61
initial.commit3f4a7322008-07-27 06:49:38 +090062//------------------------------------------------------------------------------
63
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090064// static
65MessageLoop* MessageLoop::current() {
66 // TODO(darin): sadly, we cannot enable this yet since people call us even
67 // when they have no intention of using us.
68 //DCHECK(loop) << "Ouch, did you forget to initialize me?";
69 return lazy_tls_ptr.Pointer()->Get();
70}
71
darin@google.comd936b5b2008-08-26 14:53:57 +090072MessageLoop::MessageLoop(Type type)
73 : type_(type),
darin@google.comee6fa722008-08-13 08:25:43 +090074 nestable_tasks_allowed_(true),
darin@google.com12d40bb2008-08-20 03:36:23 +090075 exception_restoration_(false),
darin@google.combe165ae2008-09-07 17:08:29 +090076 state_(NULL),
77 next_sequence_num_(0) {
deanm@chromium.orgcd1ce302008-09-10 19:54:06 +090078 DCHECK(!current()) << "should only have one message loop per thread";
79 lazy_tls_ptr.Pointer()->Set(this);
darin@google.comd936b5b2008-08-26 14:53:57 +090080
darin@google.com981f3552008-08-16 12:09:05 +090081#if defined(OS_WIN)
rvargas@google.com670c3122008-09-26 05:33:04 +090082 // TODO(rvargas): Get rid of the OS guards.
darin@google.com0795f572008-08-30 09:22:48 +090083 if (type_ == TYPE_DEFAULT) {
84 pump_ = new base::MessagePumpDefault();
rvargas@google.com670c3122008-09-26 05:33:04 +090085 } else if (type_ == TYPE_IO) {
86 pump_ = new base::MessagePumpForIO();
darin@google.com0795f572008-08-30 09:22:48 +090087 } else {
rvargas@google.com670c3122008-09-26 05:33:04 +090088 DCHECK(type_ == TYPE_UI);
89 pump_ = new base::MessagePumpForUI();
darin@google.com0795f572008-08-30 09:22:48 +090090 }
dkegel@google.com9e044ae2008-09-19 03:46:26 +090091#elif defined(OS_POSIX)
mark@chromium.org059d0492008-09-24 06:08:28 +090092#if defined(OS_MACOSX)
93 if (type_ == TYPE_UI) {
94 pump_ = base::MessagePumpMac::Create();
95 } else
96#endif // OS_MACOSX
dkegel@google.com9e044ae2008-09-19 03:46:26 +090097 if (type_ == TYPE_IO) {
98 pump_ = new base::MessagePumpLibevent();
99 } else {
100 pump_ = new base::MessagePumpDefault();
101 }
mark@chromium.org059d0492008-09-24 06:08:28 +0900102#else // OS_POSIX
darin@google.com132072e2008-08-26 15:52:41 +0900103 pump_ = new base::MessagePumpDefault();
mark@chromium.org059d0492008-09-24 06:08:28 +0900104#endif // OS_POSIX
initial.commit3f4a7322008-07-27 06:49:38 +0900105}
106
107MessageLoop::~MessageLoop() {
108 DCHECK(this == current());
darin@google.com965e5342008-08-06 08:16:41 +0900109
110 // Let interested parties have one last shot at accessing this.
111 FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
112 WillDestroyCurrentMessageLoop());
113
darin@google.com0e500502008-09-09 14:55:35 +0900114 DCHECK(!state_);
115
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900116 // Clean up any unprocessed tasks, but take care: deleting a task could
117 // result in the addition of more tasks (e.g., via DeleteSoon). We set a
118 // limit on the number of times we will allow a deleted task to generate more
119 // tasks. Normally, we should only pass through this loop once or twice. If
120 // we end up hitting the loop limit, then it is probably due to one task that
121 // is being stubborn. Inspect the queues to see who is left.
122 bool did_work;
123 for (int i = 0; i < 100; ++i) {
124 DeletePendingTasks();
125 ReloadWorkQueue();
126 // If we end up with empty queues, then break out of the loop.
127 did_work = DeletePendingTasks();
128 if (!did_work)
129 break;
darin@google.com0e500502008-09-09 14:55:35 +0900130 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900131 DCHECK(!did_work);
132
133 // OK, now make it so that no one can find us.
deanm@chromium.orge4cc5922008-09-10 20:14:56 +0900134 lazy_tls_ptr.Pointer()->Set(NULL);
initial.commit3f4a7322008-07-27 06:49:38 +0900135}
136
darin@google.com965e5342008-08-06 08:16:41 +0900137void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
138 DCHECK(this == current());
139 destruction_observers_.AddObserver(obs);
140}
141
142void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
143 DCHECK(this == current());
144 destruction_observers_.RemoveObserver(obs);
145}
146
darin@google.com6ddeb842008-08-15 16:31:20 +0900147void MessageLoop::Run() {
darin@google.com981f3552008-08-16 12:09:05 +0900148 AutoRunState save_state(this);
149 RunHandler();
darin@google.com6ddeb842008-08-15 16:31:20 +0900150}
151
jar@google.com9239e022008-07-31 22:10:20 +0900152void MessageLoop::RunAllPending() {
darin@google.com981f3552008-08-16 12:09:05 +0900153 AutoRunState save_state(this);
154 state_->quit_received = true; // Means run until we would otherwise block.
155 RunHandler();
initial.commit3f4a7322008-07-27 06:49:38 +0900156}
157
158// Runs the loop in two different SEH modes:
159// enable_SEH_restoration_ = false : any unhandled exception goes to the last
160// one that calls SetUnhandledExceptionFilter().
161// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
162// that was existed before the loop was run.
darin@google.com981f3552008-08-16 12:09:05 +0900163void MessageLoop::RunHandler() {
164#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900165 if (exception_restoration_) {
166 LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
167 __try {
darin@google.com981f3552008-08-16 12:09:05 +0900168 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900169 } __except(SEHFilter(current_filter)) {
170 }
darin@google.com981f3552008-08-16 12:09:05 +0900171 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900172 }
darin@google.com981f3552008-08-16 12:09:05 +0900173#endif
174
175 RunInternal();
initial.commit3f4a7322008-07-27 06:49:38 +0900176}
177
178//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900179
darin@google.com981f3552008-08-16 12:09:05 +0900180void MessageLoop::RunInternal() {
181 DCHECK(this == current());
182
initial.commit3f4a7322008-07-27 06:49:38 +0900183 StartHistogrammer();
184
darin@google.com981f3552008-08-16 12:09:05 +0900185#if defined(OS_WIN)
186 if (state_->dispatcher) {
187 pump_win()->RunWithDispatcher(this, state_->dispatcher);
188 return;
jar@google.com9239e022008-07-31 22:10:20 +0900189 }
darin@google.com981f3552008-08-16 12:09:05 +0900190#endif
191
192 pump_->Run(this);
jar@google.comfbaaf692008-07-30 16:50:53 +0900193}
jar@google.com7ff36e62008-07-30 15:58:56 +0900194
jar@google.comb4d1bff2008-07-31 04:03:59 +0900195//------------------------------------------------------------------------------
196// Wrapper functions for use in above message loop framework.
197
initial.commit3f4a7322008-07-27 06:49:38 +0900198bool MessageLoop::ProcessNextDelayedNonNestableTask() {
darin@google.com981f3552008-08-16 12:09:05 +0900199 if (state_->run_depth != 1)
initial.commit3f4a7322008-07-27 06:49:38 +0900200 return false;
201
darin@google.combe165ae2008-09-07 17:08:29 +0900202 if (deferred_non_nestable_work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900203 return false;
darin@google.combe165ae2008-09-07 17:08:29 +0900204
205 Task* task = deferred_non_nestable_work_queue_.front().task;
206 deferred_non_nestable_work_queue_.pop();
207
208 RunTask(task);
initial.commit3f4a7322008-07-27 06:49:38 +0900209 return true;
210}
211
initial.commit3f4a7322008-07-27 06:49:38 +0900212//------------------------------------------------------------------------------
213
214void MessageLoop::Quit() {
darin@google.com981f3552008-08-16 12:09:05 +0900215 DCHECK(current() == this);
216 if (state_) {
217 state_->quit_received = true;
218 } else {
219 NOTREACHED() << "Must be inside Run to call Quit";
initial.commit3f4a7322008-07-27 06:49:38 +0900220 }
initial.commit3f4a7322008-07-27 06:49:38 +0900221}
222
darin@google.combe165ae2008-09-07 17:08:29 +0900223void MessageLoop::PostTask(
224 const tracked_objects::Location& from_here, Task* task) {
225 PostTask_Helper(from_here, task, 0, true);
226}
227
228void MessageLoop::PostDelayedTask(
229 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
230 PostTask_Helper(from_here, task, delay_ms, true);
231}
232
233void MessageLoop::PostNonNestableTask(
234 const tracked_objects::Location& from_here, Task* task) {
235 PostTask_Helper(from_here, task, 0, false);
236}
237
238void MessageLoop::PostNonNestableDelayedTask(
239 const tracked_objects::Location& from_here, Task* task, int delay_ms) {
240 PostTask_Helper(from_here, task, delay_ms, false);
241}
242
initial.commit3f4a7322008-07-27 06:49:38 +0900243// Possibly called on a background thread!
darin@google.combe165ae2008-09-07 17:08:29 +0900244void MessageLoop::PostTask_Helper(
245 const tracked_objects::Location& from_here, Task* task, int delay_ms,
246 bool nestable) {
initial.commit3f4a7322008-07-27 06:49:38 +0900247 task->SetBirthPlace(from_here);
darin@google.com0795f572008-08-30 09:22:48 +0900248
darin@google.combe165ae2008-09-07 17:08:29 +0900249 PendingTask pending_task(task, nestable);
darin@google.com0795f572008-08-30 09:22:48 +0900250
251 if (delay_ms > 0) {
darin@google.combe165ae2008-09-07 17:08:29 +0900252 pending_task.delayed_run_time =
darin@google.com0795f572008-08-30 09:22:48 +0900253 Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
254 } else {
255 DCHECK(delay_ms == 0) << "delay should not be negative";
256 }
257
initial.commit3f4a7322008-07-27 06:49:38 +0900258 // Warning: Don't try to short-circuit, and handle this thread's tasks more
259 // directly, as it could starve handling of foreign threads. Put every task
260 // into this queue.
261
darin@google.com981f3552008-08-16 12:09:05 +0900262 scoped_refptr<base::MessagePump> pump;
initial.commit3f4a7322008-07-27 06:49:38 +0900263 {
darin@google.com981f3552008-08-16 12:09:05 +0900264 AutoLock locked(incoming_queue_lock_);
265
darin@google.combe165ae2008-09-07 17:08:29 +0900266 bool was_empty = incoming_queue_.empty();
267 incoming_queue_.push(pending_task);
initial.commit3f4a7322008-07-27 06:49:38 +0900268 if (!was_empty)
269 return; // Someone else should have started the sub-pump.
270
darin@google.com981f3552008-08-16 12:09:05 +0900271 pump = pump_;
darin@google.com6ddeb842008-08-15 16:31:20 +0900272 }
darin@google.com981f3552008-08-16 12:09:05 +0900273 // Since the incoming_queue_ may contain a task that destroys this message
274 // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
275 // We use a stack-based reference to the message pump so that we can call
276 // ScheduleWork outside of incoming_queue_lock_.
darin@google.com6ddeb842008-08-15 16:31:20 +0900277
darin@google.com981f3552008-08-16 12:09:05 +0900278 pump->ScheduleWork();
initial.commit3f4a7322008-07-27 06:49:38 +0900279}
280
281void MessageLoop::SetNestableTasksAllowed(bool allowed) {
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900282 if (nestable_tasks_allowed_ != allowed) {
283 nestable_tasks_allowed_ = allowed;
284 if (!nestable_tasks_allowed_)
285 return;
286 // Start the native pump if we are not already pumping.
darin@google.com981f3552008-08-16 12:09:05 +0900287 pump_->ScheduleWork();
mpcomplete@google.com989d5f82008-08-09 09:14:09 +0900288 }
initial.commit3f4a7322008-07-27 06:49:38 +0900289}
290
291bool MessageLoop::NestableTasksAllowed() const {
292 return nestable_tasks_allowed_;
293}
294
initial.commit3f4a7322008-07-27 06:49:38 +0900295//------------------------------------------------------------------------------
initial.commit3f4a7322008-07-27 06:49:38 +0900296
initial.commit3f4a7322008-07-27 06:49:38 +0900297void MessageLoop::RunTask(Task* task) {
initial.commit3f4a7322008-07-27 06:49:38 +0900298 DCHECK(nestable_tasks_allowed_);
299 // Execute the task and assume the worst: It is probably not reentrant.
300 nestable_tasks_allowed_ = false;
darin@google.combe165ae2008-09-07 17:08:29 +0900301
302 HistogramEvent(kTaskRunEvent);
303 task->Run();
304 delete task;
305
306 nestable_tasks_allowed_ = true;
initial.commit3f4a7322008-07-27 06:49:38 +0900307}
308
darin@google.combe165ae2008-09-07 17:08:29 +0900309bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
310 if (pending_task.nestable || state_->run_depth == 1) {
311 RunTask(pending_task.task);
312 // Show that we ran a task (Note: a new one might arrive as a
313 // consequence!).
314 return true;
315 }
316
317 // We couldn't run the task now because we're in a nested message loop
318 // and the task isn't nestable.
319 deferred_non_nestable_work_queue_.push(pending_task);
320 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900321}
322
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900323void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
324 // Move to the delayed work queue. Initialize the sequence number
325 // before inserting into the delayed_work_queue_. The sequence number
326 // is used to faciliate FIFO sorting when two tasks have the same
327 // delayed_run_time value.
328 PendingTask new_pending_task(pending_task);
329 new_pending_task.sequence_num = next_sequence_num_++;
330 delayed_work_queue_.push(new_pending_task);
331}
332
initial.commit3f4a7322008-07-27 06:49:38 +0900333void MessageLoop::ReloadWorkQueue() {
334 // We can improve performance of our loading tasks from incoming_queue_ to
darin@google.com981f3552008-08-16 12:09:05 +0900335 // work_queue_ by waiting until the last minute (work_queue_ is empty) to
336 // load. That reduces the number of locks-per-task significantly when our
darin@google.combe165ae2008-09-07 17:08:29 +0900337 // queues get large.
338 if (!work_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900339 return; // Wait till we *really* need to lock and load.
340
341 // Acquire all we can from the inter-thread queue with one lock acquisition.
initial.commit3f4a7322008-07-27 06:49:38 +0900342 {
343 AutoLock lock(incoming_queue_lock_);
darin@google.combe165ae2008-09-07 17:08:29 +0900344 if (incoming_queue_.empty())
initial.commit3f4a7322008-07-27 06:49:38 +0900345 return;
darin@google.combe165ae2008-09-07 17:08:29 +0900346 std::swap(incoming_queue_, work_queue_);
347 DCHECK(incoming_queue_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900348 }
349}
350
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900351bool MessageLoop::DeletePendingTasks() {
352 bool did_work = !work_queue_.empty();
353 while (!work_queue_.empty()) {
354 PendingTask pending_task = work_queue_.front();
355 work_queue_.pop();
356 if (!pending_task.delayed_run_time.is_null()) {
357 // We want to delete delayed tasks in the same order in which they would
358 // normally be deleted in case of any funny dependencies between delayed
359 // tasks.
360 AddToDelayedWorkQueue(pending_task);
361 } else {
362 // TODO(darin): Delete all tasks once it is safe to do so.
363 //delete task;
364 }
initial.commit3f4a7322008-07-27 06:49:38 +0900365 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900366 did_work |= !deferred_non_nestable_work_queue_.empty();
367 while (!deferred_non_nestable_work_queue_.empty()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900368 // TODO(darin): Delete all tasks once it is safe to do so.
darin@chromium.orgfea7a862008-09-10 10:16:17 +0900369 //Task* task = deferred_non_nestable_work_queue_.front().task;
370 deferred_non_nestable_work_queue_.pop();
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900371 //delete task;
initial.commit3f4a7322008-07-27 06:49:38 +0900372 }
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900373 did_work |= !delayed_work_queue_.empty();
374 while (!delayed_work_queue_.empty()) {
375 Task* task = delayed_work_queue_.top().task;
376 delayed_work_queue_.pop();
377 delete task;
378 }
379 return did_work;
initial.commit3f4a7322008-07-27 06:49:38 +0900380}
381
darin@google.com981f3552008-08-16 12:09:05 +0900382bool MessageLoop::DoWork() {
darin@google.combe165ae2008-09-07 17:08:29 +0900383 if (!nestable_tasks_allowed_) {
384 // Task can't be executed right now.
385 return false;
386 }
387
388 for (;;) {
389 ReloadWorkQueue();
390 if (work_queue_.empty())
391 break;
392
393 // Execute oldest task.
394 do {
395 PendingTask pending_task = work_queue_.front();
396 work_queue_.pop();
397 if (!pending_task.delayed_run_time.is_null()) {
darin@chromium.orge3af17f2008-09-10 09:37:07 +0900398 AddToDelayedWorkQueue(pending_task);
darin@chromium.orgb2d33452008-09-24 04:19:20 +0900399 // If we changed the topmost task, then it is time to re-schedule.
400 if (delayed_work_queue_.top().task == pending_task.task)
darin@google.combe165ae2008-09-07 17:08:29 +0900401 pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
402 } else {
403 if (DeferOrRunPendingTask(pending_task))
404 return true;
405 }
406 } while (!work_queue_.empty());
407 }
408
409 // Nothing happened.
410 return false;
darin@google.com981f3552008-08-16 12:09:05 +0900411}
412
darin@google.com6393bed2008-08-20 15:30:58 +0900413bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
darin@google.combe165ae2008-09-07 17:08:29 +0900414 if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
415 *next_delayed_work_time = Time();
416 return false;
417 }
418
419 if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
420 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
421 return false;
422 }
darin@google.com981f3552008-08-16 12:09:05 +0900423
darin@google.combe165ae2008-09-07 17:08:29 +0900424 PendingTask pending_task = delayed_work_queue_.top();
425 delayed_work_queue_.pop();
426
427 if (!delayed_work_queue_.empty())
428 *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
darin@google.com981f3552008-08-16 12:09:05 +0900429
darin@google.combe165ae2008-09-07 17:08:29 +0900430 return DeferOrRunPendingTask(pending_task);
darin@google.com981f3552008-08-16 12:09:05 +0900431}
432
433bool MessageLoop::DoIdleWork() {
434 if (ProcessNextDelayedNonNestableTask())
435 return true;
436
437 if (state_->quit_received)
438 pump_->Quit();
439
440 return false;
441}
442
443//------------------------------------------------------------------------------
444// MessageLoop::AutoRunState
445
446MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
447 // Make the loop reference us.
448 previous_state_ = loop_->state_;
449 if (previous_state_) {
450 run_depth = previous_state_->run_depth + 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900451 } else {
darin@google.com981f3552008-08-16 12:09:05 +0900452 run_depth = 1;
darin@google.com6ddeb842008-08-15 16:31:20 +0900453 }
darin@google.com981f3552008-08-16 12:09:05 +0900454 loop_->state_ = this;
455
456 // Initialize the other fields:
457 quit_received = false;
458#if defined(OS_WIN)
459 dispatcher = NULL;
460#endif
461}
462
463MessageLoop::AutoRunState::~AutoRunState() {
464 loop_->state_ = previous_state_;
darin@google.comee6fa722008-08-13 08:25:43 +0900465}
466
initial.commit3f4a7322008-07-27 06:49:38 +0900467//------------------------------------------------------------------------------
darin@google.combe165ae2008-09-07 17:08:29 +0900468// MessageLoop::PendingTask
initial.commit3f4a7322008-07-27 06:49:38 +0900469
darin@google.combe165ae2008-09-07 17:08:29 +0900470bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
471 // Since the top of a priority queue is defined as the "greatest" element, we
472 // need to invert the comparison here. We want the smaller time to be at the
473 // top of the heap.
initial.commit3f4a7322008-07-27 06:49:38 +0900474
darin@google.combe165ae2008-09-07 17:08:29 +0900475 if (delayed_run_time < other.delayed_run_time)
476 return false;
initial.commit3f4a7322008-07-27 06:49:38 +0900477
darin@google.combe165ae2008-09-07 17:08:29 +0900478 if (delayed_run_time > other.delayed_run_time)
479 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900480
darin@google.combe165ae2008-09-07 17:08:29 +0900481 // If the times happen to match, then we use the sequence number to decide.
482 // Compare the difference to support integer roll-over.
483 return (sequence_num - other.sequence_num) > 0;
initial.commit3f4a7322008-07-27 06:49:38 +0900484}
485
486//------------------------------------------------------------------------------
487// Method and data for histogramming events and actions taken by each instance
488// on each thread.
489
490// static
491bool MessageLoop::enable_histogrammer_ = false;
492
493// static
494void MessageLoop::EnableHistogrammer(bool enable) {
495 enable_histogrammer_ = enable;
496}
497
498void MessageLoop::StartHistogrammer() {
499 if (enable_histogrammer_ && !message_histogram_.get()
500 && StatisticsRecorder::WasStarted()) {
darin@google.com981f3552008-08-16 12:09:05 +0900501 DCHECK(!thread_name_.empty());
initial.commit3f4a7322008-07-27 06:49:38 +0900502 message_histogram_.reset(new LinearHistogram(
503 ASCIIToWide("MsgLoop:" + thread_name_).c_str(),
504 kLeastNonZeroMessageId,
505 kMaxMessageId,
506 kNumberOfDistinctMessagesDisplayed));
507 message_histogram_->SetFlags(message_histogram_->kHexRangePrintingFlag);
508 message_histogram_->SetRangeDescriptions(event_descriptions_);
509 }
510}
511
512void MessageLoop::HistogramEvent(int event) {
513 if (message_histogram_.get())
514 message_histogram_->Add(event);
515}
516
initial.commit3f4a7322008-07-27 06:49:38 +0900517// Provide a macro that takes an expression (such as a constant, or macro
518// constant) and creates a pair to initalize an array of pairs. In this case,
519// our pair consists of the expressions value, and the "stringized" version
520// of the expression (i.e., the exrpression put in quotes). For example, if
521// we have:
522// #define FOO 2
523// #define BAR 5
524// then the following:
525// VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
526// will expand to:
527// {7, "FOO + BAR"}
528// We use the resulting array as an argument to our histogram, which reads the
529// number as a bucket identifier, and proceeds to use the corresponding name
530// in the pair (i.e., the quoted string) when printing out a histogram.
531#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
532
initial.commit3f4a7322008-07-27 06:49:38 +0900533// static
534const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
initial.commit3f4a7322008-07-27 06:49:38 +0900535 // Provide some pretty print capability in our histogram for our internal
536 // messages.
537
initial.commit3f4a7322008-07-27 06:49:38 +0900538 // A few events we handle (kindred to messages), and used to profile actions.
539 VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
initial.commit3f4a7322008-07-27 06:49:38 +0900540 VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
541
542 {-1, NULL} // The list must be null terminated, per API to histogram.
543};
license.botf003cfe2008-08-24 09:55:55 +0900544
darin@google.comd936b5b2008-08-26 14:53:57 +0900545//------------------------------------------------------------------------------
546// MessageLoopForUI
547
548#if defined(OS_WIN)
549
550void MessageLoopForUI::Run(Dispatcher* dispatcher) {
551 AutoRunState save_state(this);
552 state_->dispatcher = dispatcher;
553 RunHandler();
554}
555
556void MessageLoopForUI::AddObserver(Observer* observer) {
557 pump_win()->AddObserver(observer);
558}
559
560void MessageLoopForUI::RemoveObserver(Observer* observer) {
561 pump_win()->RemoveObserver(observer);
562}
563
564void MessageLoopForUI::WillProcessMessage(const MSG& message) {
565 pump_win()->WillProcessMessage(message);
566}
567void MessageLoopForUI::DidProcessMessage(const MSG& message) {
568 pump_win()->DidProcessMessage(message);
569}
570void MessageLoopForUI::PumpOutPendingPaintMessages() {
571 pump_win()->PumpOutPendingPaintMessages();
572}
573
574#endif // defined(OS_WIN)
575
576//------------------------------------------------------------------------------
577// MessageLoopForIO
578
579#if defined(OS_WIN)
580
581void MessageLoopForIO::WatchObject(HANDLE object, Watcher* watcher) {
rvargas@google.com670c3122008-09-26 05:33:04 +0900582 pump_io()->WatchObject(object, watcher);
darin@google.comd936b5b2008-08-26 14:53:57 +0900583}
584
dkegel@google.com9e044ae2008-09-19 03:46:26 +0900585#elif defined(OS_POSIX)
586
587void MessageLoopForIO::WatchSocket(int socket, short interest_mask,
588 struct event* e, Watcher* watcher) {
589 pump_libevent()->WatchSocket(socket, interest_mask, e, watcher);
590}
591
592void MessageLoopForIO::UnwatchSocket(struct event* e) {
593 pump_libevent()->UnwatchSocket(e);
594}
595#endif