blob: f4ed5a17b4941f27b757b8db9b001a806b8f1e70 [file] [log] [blame]
brettw@chromium.org6318b392013-06-14 12:27:49 +09001// Copyright 2013 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.
4
5#ifndef BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
6#define BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
7
8#include <queue>
9#include <string>
10
11#include "base/base_export.h"
12#include "base/basictypes.h"
13#include "base/callback_forward.h"
14#include "base/location.h"
15#include "base/memory/ref_counted.h"
alexeypa@chromium.org40183232013-07-23 07:24:13 +090016#include "base/memory/scoped_ptr.h"
17#include "base/message_loop/incoming_task_queue.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090018#include "base/message_loop/message_loop_proxy.h"
alexeypa@chromium.org40183232013-07-23 07:24:13 +090019#include "base/message_loop/message_loop_proxy_impl.h"
brettw@chromium.org710ecb92013-06-19 05:27:52 +090020#include "base/message_loop/message_pump.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090021#include "base/observer_list.h"
22#include "base/pending_task.h"
23#include "base/sequenced_task_runner_helpers.h"
24#include "base/synchronization/lock.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090025#include "base/time/time.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090026#include "base/tracking_info.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090027
28#if defined(OS_WIN)
29// We need this to declare base::MessagePumpWin::Dispatcher, which we should
30// really just eliminate.
brettw@chromium.org710ecb92013-06-19 05:27:52 +090031#include "base/message_loop/message_pump_win.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090032#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090033#include "base/message_loop/message_pump_io_ios.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090034#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090035#include "base/message_loop/message_pump_libevent.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090036#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
37
38#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_NACL)
sadrul@chromium.org19995722013-09-07 12:21:04 +090039#include "base/message_loop/message_pump_x11.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090040#elif defined(USE_OZONE) && !defined(OS_NACL)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090041#include "base/message_loop/message_pump_ozone.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090042#else
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090043#define USE_GTK_MESSAGE_PUMP
brettw@chromium.org710ecb92013-06-19 05:27:52 +090044#include "base/message_loop/message_pump_gtk.h"
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +090045#if defined(TOOLKIT_GTK)
46#include "base/message_loop/message_pump_x11.h"
47#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +090048#endif
49
50#endif
51#endif
52
53namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090054
brettw@chromium.org6318b392013-06-14 12:27:49 +090055class HistogramBase;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090056class MessagePumpDispatcher;
57class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090058class RunLoop;
59class ThreadTaskRunnerHandle;
60#if defined(OS_ANDROID)
61class MessagePumpForUI;
62#endif
alexeypa@chromium.org40183232013-07-23 07:24:13 +090063class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090064
65// A MessageLoop is used to process events for a particular thread. There is
66// at most one MessageLoop instance per thread.
67//
68// Events include at a minimum Task instances submitted to PostTask and its
69// variants. Depending on the type of message pump used by the MessageLoop
70// other events such as UI messages may be processed. On Windows APC calls (as
71// time permits) and signals sent to a registered set of HANDLEs may also be
72// processed.
73//
74// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
75// on the thread where the MessageLoop's Run method executes.
76//
77// NOTE: MessageLoop has task reentrancy protection. This means that if a
78// task is being processed, a second task cannot start until the first task is
79// finished. Reentrancy can happen when processing a task, and an inner
80// message pump is created. That inner pump then processes native messages
81// which could implicitly start an inner task. Inner message pumps are created
82// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
83// (DoDragDrop), printer functions (StartDoc) and *many* others.
84//
85// Sample workaround when inner task processing is needed:
86// HRESULT hr;
87// {
88// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
89// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
90// }
91// // Process |hr| (the result returned by DoDragDrop()).
92//
93// Please be SURE your task is reentrant (nestable) and all global variables
94// are stable and accessible before calling SetNestableTasksAllowed(true).
95//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090096class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090097 public:
98
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090099#if defined(USE_GTK_MESSAGE_PUMP)
100 typedef MessagePumpGdkObserver Observer;
101#elif !defined(OS_MACOSX) && !defined(OS_ANDROID)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900102 typedef MessagePumpDispatcher Dispatcher;
103 typedef MessagePumpObserver Observer;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900104#endif
105
106 // A MessageLoop has a particular type, which indicates the set of
107 // asynchronous events it may process in addition to tasks and timers.
108 //
109 // TYPE_DEFAULT
110 // This type of ML only supports tasks and timers.
111 //
112 // TYPE_UI
113 // This type of ML also supports native UI events (e.g., Windows messages).
114 // See also MessageLoopForUI.
115 //
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900116 // TYPE_GPU
117 // This type of ML also supports native UI events for use in the GPU
118 // process. On Linux this will always be an X11 ML (as compared with the
119 // sometimes-GTK ML in the browser process).
120 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900121 // TYPE_IO
122 // This type of ML also supports asynchronous IO. See also
123 // MessageLoopForIO.
124 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900125 // TYPE_JAVA
126 // This type of ML is backed by a Java message handler which is responsible
127 // for running the tasks added to the ML. This is only for use on Android.
128 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
129 // where it does not use the main thread specific pump factory.
130 //
sky@chromium.orgab452802013-11-08 15:16:53 +0900131 // TYPE_CUSTOM
132 // MessagePump was supplied to constructor.
133 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900134 enum Type {
135 TYPE_DEFAULT,
136 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900137 TYPE_CUSTOM,
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900138#if defined(TOOLKIT_GTK)
139 TYPE_GPU,
140#endif
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900141 TYPE_IO,
142#if defined(OS_ANDROID)
143 TYPE_JAVA,
144#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900145 };
146
147 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
148 // is typical to make use of the current thread's MessageLoop instance.
149 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900150 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
151 // be non-NULL.
152 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900153 virtual ~MessageLoop();
154
155 // Returns the MessageLoop object for the current thread, or null if none.
156 static MessageLoop* current();
157
158 static void EnableHistogrammer(bool enable_histogrammer);
159
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900160 typedef MessagePump* (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900161 // Uses the given base::MessagePumpForUIFactory to override the default
162 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
163 // was successfully registered.
164 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
165
sky@chromium.org4f426822013-11-13 01:35:02 +0900166 // Creates the default MessagePump based on |type|. Caller owns return
167 // value.
168 // TODO(sky): convert this and InitMessagePumpForUIFactory() to return a
169 // scoped_ptr.
170 static MessagePump* CreateMessagePumpForType(Type type);
171
brettw@chromium.org6318b392013-06-14 12:27:49 +0900172 // A DestructionObserver is notified when the current MessageLoop is being
173 // destroyed. These observers are notified prior to MessageLoop::current()
174 // being changed to return NULL. This gives interested parties the chance to
175 // do final cleanup that depends on the MessageLoop.
176 //
177 // NOTE: Any tasks posted to the MessageLoop during this notification will
178 // not be run. Instead, they will be deleted.
179 //
180 class BASE_EXPORT DestructionObserver {
181 public:
182 virtual void WillDestroyCurrentMessageLoop() = 0;
183
184 protected:
185 virtual ~DestructionObserver();
186 };
187
188 // Add a DestructionObserver, which will start receiving notifications
189 // immediately.
190 void AddDestructionObserver(DestructionObserver* destruction_observer);
191
192 // Remove a DestructionObserver. It is safe to call this method while a
193 // DestructionObserver is receiving a notification callback.
194 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
195
196 // The "PostTask" family of methods call the task's Run method asynchronously
197 // from within a message loop at some point in the future.
198 //
199 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
200 // with normal UI or IO event processing. With the PostDelayedTask variant,
201 // tasks are called after at least approximately 'delay_ms' have elapsed.
202 //
203 // The NonNestable variants work similarly except that they promise never to
204 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
205 // such tasks get deferred until the top-most MessageLoop::Run is executing.
206 //
207 // The MessageLoop takes ownership of the Task, and deletes it after it has
208 // been Run().
209 //
210 // PostTask(from_here, task) is equivalent to
211 // PostDelayedTask(from_here, task, 0).
212 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900213 // NOTE: These methods may be called on any thread. The Task will be invoked
214 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900215 void PostTask(const tracked_objects::Location& from_here,
216 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900217
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900218 void PostDelayedTask(const tracked_objects::Location& from_here,
219 const Closure& task,
220 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900221
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900222 void PostNonNestableTask(const tracked_objects::Location& from_here,
223 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900224
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900225 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
226 const Closure& task,
227 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900228
229 // A variant on PostTask that deletes the given object. This is useful
230 // if the object needs to live until the next run of the MessageLoop (for
231 // example, deleting a RenderProcessHost from within an IPC callback is not
232 // good).
233 //
234 // NOTE: This method may be called on any thread. The object will be deleted
235 // on the thread that executes MessageLoop::Run(). If this is not the same
236 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
237 // from RefCountedThreadSafe<T>!
238 template <class T>
239 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
240 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
241 this, from_here, object);
242 }
243
244 // A variant on PostTask that releases the given reference counted object
245 // (by calling its Release method). This is useful if the object needs to
246 // live until the next run of the MessageLoop, or if the object needs to be
247 // released on a particular thread.
248 //
249 // NOTE: This method may be called on any thread. The object will be
250 // released (and thus possibly deleted) on the thread that executes
251 // MessageLoop::Run(). If this is not the same as the thread that calls
252 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
253 // RefCountedThreadSafe<T>!
254 template <class T>
255 void ReleaseSoon(const tracked_objects::Location& from_here,
256 const T* object) {
257 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
258 this, from_here, object);
259 }
260
261 // Deprecated: use RunLoop instead.
262 // Run the message loop.
263 void Run();
264
265 // Deprecated: use RunLoop instead.
266 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
267 // Return as soon as all items that can be run are taken care of.
268 void RunUntilIdle();
269
270 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
271 void Quit() { QuitWhenIdle(); }
272
273 // Deprecated: use RunLoop instead.
274 //
275 // Signals the Run method to return when it becomes idle. It will continue to
276 // process pending messages and future messages as long as they are enqueued.
277 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
278 // Quit method when looping procedures (such as web pages) have been shut
279 // down.
280 //
281 // This method may only be called on the same thread that called Run, and Run
282 // must still be on the call stack.
283 //
284 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
285 // but note that doing so is fairly dangerous if the target thread makes
286 // nested calls to MessageLoop::Run. The problem being that you won't know
287 // which nested run loop you are quitting, so be careful!
288 void QuitWhenIdle();
289
290 // Deprecated: use RunLoop instead.
291 //
292 // This method is a variant of Quit, that does not wait for pending messages
293 // to be processed before returning from Run.
294 void QuitNow();
295
296 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900297 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900298
299 // Deprecated: use RunLoop instead.
300 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
301 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900302 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900303
304 // Returns true if this loop is |type|. This allows subclasses (especially
305 // those in tests) to specialize how they are identified.
306 virtual bool IsType(Type type) const;
307
308 // Returns the type passed to the constructor.
309 Type type() const { return type_; }
310
311 // Optional call to connect the thread name with this loop.
312 void set_thread_name(const std::string& thread_name) {
313 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
314 thread_name_ = thread_name;
315 }
316 const std::string& thread_name() const { return thread_name_; }
317
318 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900319 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900320 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900321 }
322
323 // Enables or disables the recursive task processing. This happens in the case
324 // of recursive message loops. Some unwanted message loop may occurs when
325 // using common controls or printer functions. By default, recursive task
326 // processing is disabled.
327 //
328 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
329 // directly. In general nestable message loops are to be avoided. They are
330 // dangerous and difficult to get right, so please use with extreme caution.
331 //
332 // The specific case where tasks get queued is:
333 // - The thread is running a message loop.
334 // - It receives a task #1 and execute it.
335 // - The task #1 implicitly start a message loop, like a MessageBox in the
336 // unit test. This can also be StartDoc or GetSaveFileName.
337 // - The thread receives a task #2 before or while in this second message
338 // loop.
339 // - With NestableTasksAllowed set to true, the task #2 will run right away.
340 // Otherwise, it will get executed right after task #1 completes at "thread
341 // message loop level".
342 void SetNestableTasksAllowed(bool allowed);
343 bool NestableTasksAllowed() const;
344
345 // Enables nestable tasks on |loop| while in scope.
346 class ScopedNestableTaskAllower {
347 public:
348 explicit ScopedNestableTaskAllower(MessageLoop* loop)
349 : loop_(loop),
350 old_state_(loop_->NestableTasksAllowed()) {
351 loop_->SetNestableTasksAllowed(true);
352 }
353 ~ScopedNestableTaskAllower() {
354 loop_->SetNestableTasksAllowed(old_state_);
355 }
356
357 private:
358 MessageLoop* loop_;
359 bool old_state_;
360 };
361
brettw@chromium.org6318b392013-06-14 12:27:49 +0900362 // Returns true if we are currently running a nested message loop.
363 bool IsNested();
364
365 // A TaskObserver is an object that receives task notifications from the
366 // MessageLoop.
367 //
368 // NOTE: A TaskObserver implementation should be extremely fast!
369 class BASE_EXPORT TaskObserver {
370 public:
371 TaskObserver();
372
373 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900374 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900375
376 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900377 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900378
379 protected:
380 virtual ~TaskObserver();
381 };
382
383 // These functions can only be called on the same thread that |this| is
384 // running on.
385 void AddTaskObserver(TaskObserver* task_observer);
386 void RemoveTaskObserver(TaskObserver* task_observer);
387
brettw@chromium.org6318b392013-06-14 12:27:49 +0900388 // When we go into high resolution timer mode, we will stay in hi-res mode
389 // for at least 1s.
390 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
391
brettw@chromium.org6318b392013-06-14 12:27:49 +0900392#if defined(OS_WIN)
393 void set_os_modal_loop(bool os_modal_loop) {
394 os_modal_loop_ = os_modal_loop;
395 }
396
397 bool os_modal_loop() const {
398 return os_modal_loop_;
399 }
400#endif // OS_WIN
401
402 // Can only be called from the thread that owns the MessageLoop.
403 bool is_running() const;
404
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900405 // Returns true if the message loop has high resolution timers enabled.
406 // Provided for testing.
407 bool IsHighResolutionTimerEnabledForTesting();
408
409 // Returns true if the message loop is "idle". Provided for testing.
410 bool IsIdleForTesting();
411
brettw@chromium.org6318b392013-06-14 12:27:49 +0900412 //----------------------------------------------------------------------------
413 protected:
414
415#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900416 MessagePumpWin* pump_win() {
417 return static_cast<MessagePumpWin*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900418 }
419#elif defined(OS_POSIX) && !defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900420 MessagePumpLibevent* pump_libevent() {
421 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900422 }
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900423#if defined(TOOLKIT_GTK)
424 friend class MessagePumpX11;
425 MessagePumpX11* pump_gpu() {
426 DCHECK_EQ(TYPE_GPU, type());
427 return static_cast<MessagePumpX11*>(pump_.get());
428 }
429#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900430#endif
431
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900432 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900433
434 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900435 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900436 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900437
sky@chromium.orgab452802013-11-08 15:16:53 +0900438 // Configures various members for the two constructors.
439 void Init();
440
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900441 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900442 void RunHandler();
443
brettw@chromium.org6318b392013-06-14 12:27:49 +0900444 // Called to process any delayed non-nestable tasks.
445 bool ProcessNextDelayedNonNestableTask();
446
447 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900448 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900449
450 // Calls RunTask or queues the pending_task on the deferred task list if it
451 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900452 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900453
454 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900455 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900456
brettw@chromium.org6318b392013-06-14 12:27:49 +0900457 // Delete tasks that haven't run yet without running them. Used in the
458 // destructor to make sure all the task's destructors get called. Returns
459 // true if some work was done.
460 bool DeletePendingTasks();
461
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900462 // Creates a process-wide unique ID to represent this task in trace events.
463 // This will be mangled with a Process ID hash to reduce the likelyhood of
464 // colliding with MessageLoop pointers on other processes.
465 uint64 GetTaskTraceID(const PendingTask& task);
466
467 // Loads tasks from the incoming queue to |work_queue_| if the latter is
468 // empty.
469 void ReloadWorkQueue();
470
471 // Wakes up the message pump. Can be called on any thread. The caller is
472 // responsible for synchronizing ScheduleWork() calls.
473 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900474
475 // Start recording histogram info about events and action IF it was enabled
476 // and IF the statistics recorder can accept a registration of our histogram.
477 void StartHistogrammer();
478
479 // Add occurrence of event to our histogram, so that we can see what is being
480 // done in a specific MessageLoop instance (i.e., specific thread).
481 // If message_histogram_ is NULL, this is a no-op.
482 void HistogramEvent(int event);
483
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900484 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900485 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900486 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900487 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900488 virtual void GetQueueingInformation(size_t* queue_size,
489 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900490
sky@chromium.orgab452802013-11-08 15:16:53 +0900491 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900492
493 // A list of tasks that need to be processed by this instance. Note that
494 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900495 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900496
497 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900498 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900499
500 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900501 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900502
503 // A queue of non-nestable tasks that we had to defer because when it came
504 // time to execute them we were in a nested message loop. They will execute
505 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900506 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900507
508 ObserverList<DestructionObserver> destruction_observers_;
509
510 // A recursion block that prevents accidentally running additional tasks when
511 // insider a (accidentally induced?) nested message pump.
512 bool nestable_tasks_allowed_;
513
alexeypa@google.combb819d62013-07-23 05:06:56 +0900514#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900515 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
516 // which enter a modal message loop.
517 bool os_modal_loop_;
518#endif
519
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900520 std::string thread_name_;
521 // A profiling histogram showing the counts of various messages and events.
522 HistogramBase* message_histogram_;
523
524 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900525
brettw@chromium.org6318b392013-06-14 12:27:49 +0900526 ObserverList<TaskObserver> task_observers_;
527
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900528 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
529
530 // The message loop proxy associated with this message loop.
531 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900532 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900533
534 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
535 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
536
537 void DeleteSoonInternal(const tracked_objects::Location& from_here,
538 void(*deleter)(const void*),
539 const void* object);
540 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
541 void(*releaser)(const void*),
542 const void* object);
543
544 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
545};
546
547//-----------------------------------------------------------------------------
548// MessageLoopForUI extends MessageLoop with methods that are particular to a
549// MessageLoop instantiated with TYPE_UI.
550//
551// This class is typically used like so:
552// MessageLoopForUI::current()->...call some method...
553//
554class BASE_EXPORT MessageLoopForUI : public MessageLoop {
555 public:
556#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900557 typedef MessagePumpForUI::MessageFilter MessageFilter;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900558#endif
559
560 MessageLoopForUI() : MessageLoop(TYPE_UI) {
561 }
562
563 // Returns the MessageLoopForUI of the current thread.
564 static MessageLoopForUI* current() {
565 MessageLoop* loop = MessageLoop::current();
566 DCHECK(loop);
567 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
568 return static_cast<MessageLoopForUI*>(loop);
569 }
570
brettw@chromium.org6318b392013-06-14 12:27:49 +0900571#if defined(OS_IOS)
572 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
573 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
574 // PostTask() to work.
575 void Attach();
576#endif
577
578#if defined(OS_ANDROID)
579 // On Android, the UI message loop is handled by Java side. So Run() should
580 // never be called. Instead use Start(), which will forward all the native UI
581 // events to the Java message loop.
582 void Start();
583#elif !defined(OS_MACOSX)
584
585 // Please see message_pump_win/message_pump_glib for definitions of these
586 // methods.
587 void AddObserver(Observer* observer);
588 void RemoveObserver(Observer* observer);
589
590#if defined(OS_WIN)
591 // Plese see MessagePumpForUI for definitions of this method.
592 void SetMessageFilter(scoped_ptr<MessageFilter> message_filter) {
593 pump_ui()->SetMessageFilter(message_filter.Pass());
594 }
595#endif
596
597 protected:
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900598#if defined(USE_X11)
sadrul@chromium.org19995722013-09-07 12:21:04 +0900599 friend class MessagePumpX11;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900600#endif
601#if defined(USE_OZONE) && !defined(OS_NACL)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900602 friend class MessagePumpOzone;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900603#endif
604
605 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900606 MessagePumpForUI* pump_ui() {
607 return static_cast<MessagePumpForUI*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900608 }
609#endif // !defined(OS_MACOSX)
610};
611
612// Do not add any member variables to MessageLoopForUI! This is important b/c
613// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
614// data that you need should be stored on the MessageLoop's pump_ instance.
615COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
616 MessageLoopForUI_should_not_have_extra_member_variables);
617
618//-----------------------------------------------------------------------------
619// MessageLoopForIO extends MessageLoop with methods that are particular to a
620// MessageLoop instantiated with TYPE_IO.
621//
622// This class is typically used like so:
623// MessageLoopForIO::current()->...call some method...
624//
625class BASE_EXPORT MessageLoopForIO : public MessageLoop {
626 public:
627#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900628 typedef MessagePumpForIO::IOHandler IOHandler;
629 typedef MessagePumpForIO::IOContext IOContext;
630 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900631#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900632 typedef MessagePumpIOSForIO::Watcher Watcher;
633 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900634 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900635 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900636
637 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900638 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
639 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
640 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900641 };
642#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900643 typedef MessagePumpLibevent::Watcher Watcher;
644 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900645 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900646 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900647
648 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900649 WATCH_READ = MessagePumpLibevent::WATCH_READ,
650 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
651 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900652 };
653
654#endif
655
656 MessageLoopForIO() : MessageLoop(TYPE_IO) {
657 }
658
659 // Returns the MessageLoopForIO of the current thread.
660 static MessageLoopForIO* current() {
661 MessageLoop* loop = MessageLoop::current();
662 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
663 return static_cast<MessageLoopForIO*>(loop);
664 }
665
666 void AddIOObserver(IOObserver* io_observer) {
667 pump_io()->AddIOObserver(io_observer);
668 }
669
670 void RemoveIOObserver(IOObserver* io_observer) {
671 pump_io()->RemoveIOObserver(io_observer);
672 }
673
674#if defined(OS_WIN)
675 // Please see MessagePumpWin for definitions of these methods.
676 void RegisterIOHandler(HANDLE file, IOHandler* handler);
677 bool RegisterJobObject(HANDLE job, IOHandler* handler);
678 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
679
680 protected:
681 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900682 MessagePumpForIO* pump_io() {
683 return static_cast<MessagePumpForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900684 }
685
686#elif defined(OS_IOS)
687 // Please see MessagePumpIOSForIO for definition.
688 bool WatchFileDescriptor(int fd,
689 bool persistent,
690 Mode mode,
691 FileDescriptorWatcher *controller,
692 Watcher *delegate);
693
694 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900695 MessagePumpIOSForIO* pump_io() {
696 return static_cast<MessagePumpIOSForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900697 }
698
699#elif defined(OS_POSIX)
700 // Please see MessagePumpLibevent for definition.
701 bool WatchFileDescriptor(int fd,
702 bool persistent,
703 Mode mode,
704 FileDescriptorWatcher* controller,
705 Watcher* delegate);
706
707 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900708 MessagePumpLibevent* pump_io() {
709 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900710 }
711#endif // defined(OS_POSIX)
712};
713
714// Do not add any member variables to MessageLoopForIO! This is important b/c
715// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
716// data that you need should be stored on the MessageLoop's pump_ instance.
717COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
718 MessageLoopForIO_should_not_have_extra_member_variables);
719
720} // namespace base
721
722#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_