blob: 6539c65654926e986530b020fa22f92c9afb3420 [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
sky@chromium.org66a00b32014-01-17 09:10:29 +090028// TODO(sky): these includes should not be necessary. Nuke them.
brettw@chromium.org6318b392013-06-14 12:27:49 +090029#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090030#include "base/message_loop/message_pump_win.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090031#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090032#include "base/message_loop/message_pump_io_ios.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090033#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090034#include "base/message_loop/message_pump_libevent.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090035#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
36
37#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_NACL)
sadrul@chromium.org19995722013-09-07 12:21:04 +090038#include "base/message_loop/message_pump_x11.h"
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090039#elif !defined(OS_ANDROID_HOST)
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090040#define USE_GTK_MESSAGE_PUMP
brettw@chromium.org710ecb92013-06-19 05:27:52 +090041#include "base/message_loop/message_pump_gtk.h"
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +090042#if defined(TOOLKIT_GTK)
43#include "base/message_loop/message_pump_x11.h"
44#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +090045#endif
46
47#endif
48#endif
49
50namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090051
brettw@chromium.org6318b392013-06-14 12:27:49 +090052class HistogramBase;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090053class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090054class RunLoop;
55class ThreadTaskRunnerHandle;
56#if defined(OS_ANDROID)
57class MessagePumpForUI;
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090058#elif defined(OS_ANDROID_HOST)
59typedef MessagePumpLibevent MessagePumpForUI;
brettw@chromium.org6318b392013-06-14 12:27:49 +090060#endif
alexeypa@chromium.org40183232013-07-23 07:24:13 +090061class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090062
63// A MessageLoop is used to process events for a particular thread. There is
64// at most one MessageLoop instance per thread.
65//
66// Events include at a minimum Task instances submitted to PostTask and its
67// variants. Depending on the type of message pump used by the MessageLoop
68// other events such as UI messages may be processed. On Windows APC calls (as
69// time permits) and signals sent to a registered set of HANDLEs may also be
70// processed.
71//
72// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
73// on the thread where the MessageLoop's Run method executes.
74//
75// NOTE: MessageLoop has task reentrancy protection. This means that if a
76// task is being processed, a second task cannot start until the first task is
77// finished. Reentrancy can happen when processing a task, and an inner
78// message pump is created. That inner pump then processes native messages
79// which could implicitly start an inner task. Inner message pumps are created
80// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
81// (DoDragDrop), printer functions (StartDoc) and *many* others.
82//
83// Sample workaround when inner task processing is needed:
84// HRESULT hr;
85// {
86// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
87// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
88// }
89// // Process |hr| (the result returned by DoDragDrop()).
90//
91// Please be SURE your task is reentrant (nestable) and all global variables
92// are stable and accessible before calling SetNestableTasksAllowed(true).
93//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090094class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090095 public:
sadrul@chromium.org25e9de22014-04-11 12:02:29 +090096#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090097 typedef MessagePumpObserver Observer;
ccameron@chromium.org6c63e292014-01-08 06:42:02 +090098#elif defined(USE_GTK_MESSAGE_PUMP)
99 typedef MessagePumpGdkObserver Observer;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900100#endif
101
102 // A MessageLoop has a particular type, which indicates the set of
103 // asynchronous events it may process in addition to tasks and timers.
104 //
105 // TYPE_DEFAULT
106 // This type of ML only supports tasks and timers.
107 //
108 // TYPE_UI
109 // This type of ML also supports native UI events (e.g., Windows messages).
110 // See also MessageLoopForUI.
111 //
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900112 // TYPE_GPU
113 // This type of ML also supports native UI events for use in the GPU
114 // process. On Linux this will always be an X11 ML (as compared with the
115 // sometimes-GTK ML in the browser process).
116 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900117 // TYPE_IO
118 // This type of ML also supports asynchronous IO. See also
119 // MessageLoopForIO.
120 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900121 // TYPE_JAVA
122 // This type of ML is backed by a Java message handler which is responsible
123 // for running the tasks added to the ML. This is only for use on Android.
124 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
125 // where it does not use the main thread specific pump factory.
126 //
sky@chromium.orgab452802013-11-08 15:16:53 +0900127 // TYPE_CUSTOM
128 // MessagePump was supplied to constructor.
129 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900130 enum Type {
131 TYPE_DEFAULT,
132 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900133 TYPE_CUSTOM,
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900134#if defined(TOOLKIT_GTK)
135 TYPE_GPU,
136#endif
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900137 TYPE_IO,
138#if defined(OS_ANDROID)
139 TYPE_JAVA,
140#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900141 };
142
143 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
144 // is typical to make use of the current thread's MessageLoop instance.
145 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900146 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
147 // be non-NULL.
148 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900149 virtual ~MessageLoop();
150
151 // Returns the MessageLoop object for the current thread, or null if none.
152 static MessageLoop* current();
153
154 static void EnableHistogrammer(bool enable_histogrammer);
155
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900156 typedef scoped_ptr<MessagePump> (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900157 // Uses the given base::MessagePumpForUIFactory to override the default
158 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
159 // was successfully registered.
160 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
161
sky@chromium.org4f426822013-11-13 01:35:02 +0900162 // Creates the default MessagePump based on |type|. Caller owns return
163 // value.
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900164 static scoped_ptr<MessagePump> CreateMessagePumpForType(Type type);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900165 // A DestructionObserver is notified when the current MessageLoop is being
166 // destroyed. These observers are notified prior to MessageLoop::current()
167 // being changed to return NULL. This gives interested parties the chance to
168 // do final cleanup that depends on the MessageLoop.
169 //
170 // NOTE: Any tasks posted to the MessageLoop during this notification will
171 // not be run. Instead, they will be deleted.
172 //
173 class BASE_EXPORT DestructionObserver {
174 public:
175 virtual void WillDestroyCurrentMessageLoop() = 0;
176
177 protected:
178 virtual ~DestructionObserver();
179 };
180
181 // Add a DestructionObserver, which will start receiving notifications
182 // immediately.
183 void AddDestructionObserver(DestructionObserver* destruction_observer);
184
185 // Remove a DestructionObserver. It is safe to call this method while a
186 // DestructionObserver is receiving a notification callback.
187 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
188
189 // The "PostTask" family of methods call the task's Run method asynchronously
190 // from within a message loop at some point in the future.
191 //
192 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
193 // with normal UI or IO event processing. With the PostDelayedTask variant,
194 // tasks are called after at least approximately 'delay_ms' have elapsed.
195 //
196 // The NonNestable variants work similarly except that they promise never to
197 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
198 // such tasks get deferred until the top-most MessageLoop::Run is executing.
199 //
200 // The MessageLoop takes ownership of the Task, and deletes it after it has
201 // been Run().
202 //
203 // PostTask(from_here, task) is equivalent to
204 // PostDelayedTask(from_here, task, 0).
205 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900206 // NOTE: These methods may be called on any thread. The Task will be invoked
207 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900208 void PostTask(const tracked_objects::Location& from_here,
209 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900210
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900211 void PostDelayedTask(const tracked_objects::Location& from_here,
212 const Closure& task,
213 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900214
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900215 void PostNonNestableTask(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 PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
219 const Closure& task,
220 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900221
222 // A variant on PostTask that deletes the given object. This is useful
223 // if the object needs to live until the next run of the MessageLoop (for
224 // example, deleting a RenderProcessHost from within an IPC callback is not
225 // good).
226 //
227 // NOTE: This method may be called on any thread. The object will be deleted
228 // on the thread that executes MessageLoop::Run(). If this is not the same
229 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
230 // from RefCountedThreadSafe<T>!
231 template <class T>
232 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
233 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
234 this, from_here, object);
235 }
236
237 // A variant on PostTask that releases the given reference counted object
238 // (by calling its Release method). This is useful if the object needs to
239 // live until the next run of the MessageLoop, or if the object needs to be
240 // released on a particular thread.
241 //
242 // NOTE: This method may be called on any thread. The object will be
243 // released (and thus possibly deleted) on the thread that executes
244 // MessageLoop::Run(). If this is not the same as the thread that calls
245 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
246 // RefCountedThreadSafe<T>!
247 template <class T>
248 void ReleaseSoon(const tracked_objects::Location& from_here,
249 const T* object) {
250 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
251 this, from_here, object);
252 }
253
254 // Deprecated: use RunLoop instead.
255 // Run the message loop.
256 void Run();
257
258 // Deprecated: use RunLoop instead.
259 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
260 // Return as soon as all items that can be run are taken care of.
261 void RunUntilIdle();
262
263 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
264 void Quit() { QuitWhenIdle(); }
265
266 // Deprecated: use RunLoop instead.
267 //
268 // Signals the Run method to return when it becomes idle. It will continue to
269 // process pending messages and future messages as long as they are enqueued.
270 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
271 // Quit method when looping procedures (such as web pages) have been shut
272 // down.
273 //
274 // This method may only be called on the same thread that called Run, and Run
275 // must still be on the call stack.
276 //
277 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
278 // but note that doing so is fairly dangerous if the target thread makes
279 // nested calls to MessageLoop::Run. The problem being that you won't know
280 // which nested run loop you are quitting, so be careful!
281 void QuitWhenIdle();
282
283 // Deprecated: use RunLoop instead.
284 //
285 // This method is a variant of Quit, that does not wait for pending messages
286 // to be processed before returning from Run.
287 void QuitNow();
288
289 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900290 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900291
292 // Deprecated: use RunLoop instead.
293 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
294 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900295 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900296
297 // Returns true if this loop is |type|. This allows subclasses (especially
298 // those in tests) to specialize how they are identified.
299 virtual bool IsType(Type type) const;
300
301 // Returns the type passed to the constructor.
302 Type type() const { return type_; }
303
304 // Optional call to connect the thread name with this loop.
305 void set_thread_name(const std::string& thread_name) {
306 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
307 thread_name_ = thread_name;
308 }
309 const std::string& thread_name() const { return thread_name_; }
310
311 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900312 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900313 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900314 }
315
316 // Enables or disables the recursive task processing. This happens in the case
317 // of recursive message loops. Some unwanted message loop may occurs when
318 // using common controls or printer functions. By default, recursive task
319 // processing is disabled.
320 //
321 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
322 // directly. In general nestable message loops are to be avoided. They are
323 // dangerous and difficult to get right, so please use with extreme caution.
324 //
325 // The specific case where tasks get queued is:
326 // - The thread is running a message loop.
327 // - It receives a task #1 and execute it.
328 // - The task #1 implicitly start a message loop, like a MessageBox in the
329 // unit test. This can also be StartDoc or GetSaveFileName.
330 // - The thread receives a task #2 before or while in this second message
331 // loop.
332 // - With NestableTasksAllowed set to true, the task #2 will run right away.
333 // Otherwise, it will get executed right after task #1 completes at "thread
334 // message loop level".
335 void SetNestableTasksAllowed(bool allowed);
336 bool NestableTasksAllowed() const;
337
338 // Enables nestable tasks on |loop| while in scope.
339 class ScopedNestableTaskAllower {
340 public:
341 explicit ScopedNestableTaskAllower(MessageLoop* loop)
342 : loop_(loop),
343 old_state_(loop_->NestableTasksAllowed()) {
344 loop_->SetNestableTasksAllowed(true);
345 }
346 ~ScopedNestableTaskAllower() {
347 loop_->SetNestableTasksAllowed(old_state_);
348 }
349
350 private:
351 MessageLoop* loop_;
352 bool old_state_;
353 };
354
brettw@chromium.org6318b392013-06-14 12:27:49 +0900355 // Returns true if we are currently running a nested message loop.
356 bool IsNested();
357
358 // A TaskObserver is an object that receives task notifications from the
359 // MessageLoop.
360 //
361 // NOTE: A TaskObserver implementation should be extremely fast!
362 class BASE_EXPORT TaskObserver {
363 public:
364 TaskObserver();
365
366 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900367 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900368
369 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900370 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900371
372 protected:
373 virtual ~TaskObserver();
374 };
375
376 // These functions can only be called on the same thread that |this| is
377 // running on.
378 void AddTaskObserver(TaskObserver* task_observer);
379 void RemoveTaskObserver(TaskObserver* task_observer);
380
brettw@chromium.org6318b392013-06-14 12:27:49 +0900381 // When we go into high resolution timer mode, we will stay in hi-res mode
382 // for at least 1s.
383 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
384
brettw@chromium.org6318b392013-06-14 12:27:49 +0900385#if defined(OS_WIN)
386 void set_os_modal_loop(bool os_modal_loop) {
387 os_modal_loop_ = os_modal_loop;
388 }
389
390 bool os_modal_loop() const {
391 return os_modal_loop_;
392 }
393#endif // OS_WIN
394
395 // Can only be called from the thread that owns the MessageLoop.
396 bool is_running() const;
397
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900398 // Returns true if the message loop has high resolution timers enabled.
399 // Provided for testing.
400 bool IsHighResolutionTimerEnabledForTesting();
401
402 // Returns true if the message loop is "idle". Provided for testing.
403 bool IsIdleForTesting();
404
brettw@chromium.org6318b392013-06-14 12:27:49 +0900405 //----------------------------------------------------------------------------
406 protected:
407
408#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900409 MessagePumpWin* pump_win() {
410 return static_cast<MessagePumpWin*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900411 }
412#elif defined(OS_POSIX) && !defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900413 MessagePumpLibevent* pump_libevent() {
414 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900415 }
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900416#if defined(TOOLKIT_GTK)
417 friend class MessagePumpX11;
418 MessagePumpX11* pump_gpu() {
419 DCHECK_EQ(TYPE_GPU, type());
420 return static_cast<MessagePumpX11*>(pump_.get());
421 }
422#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900423#endif
424
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900425 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900426
427 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900428 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900429 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900430
sky@chromium.orgab452802013-11-08 15:16:53 +0900431 // Configures various members for the two constructors.
432 void Init();
433
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900434 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900435 void RunHandler();
436
brettw@chromium.org6318b392013-06-14 12:27:49 +0900437 // Called to process any delayed non-nestable tasks.
438 bool ProcessNextDelayedNonNestableTask();
439
440 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900441 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900442
443 // Calls RunTask or queues the pending_task on the deferred task list if it
444 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900445 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900446
447 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900448 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900449
brettw@chromium.org6318b392013-06-14 12:27:49 +0900450 // Delete tasks that haven't run yet without running them. Used in the
451 // destructor to make sure all the task's destructors get called. Returns
452 // true if some work was done.
453 bool DeletePendingTasks();
454
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900455 // Creates a process-wide unique ID to represent this task in trace events.
456 // This will be mangled with a Process ID hash to reduce the likelyhood of
457 // colliding with MessageLoop pointers on other processes.
458 uint64 GetTaskTraceID(const PendingTask& task);
459
460 // Loads tasks from the incoming queue to |work_queue_| if the latter is
461 // empty.
462 void ReloadWorkQueue();
463
464 // Wakes up the message pump. Can be called on any thread. The caller is
465 // responsible for synchronizing ScheduleWork() calls.
466 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900467
468 // Start recording histogram info about events and action IF it was enabled
469 // and IF the statistics recorder can accept a registration of our histogram.
470 void StartHistogrammer();
471
472 // Add occurrence of event to our histogram, so that we can see what is being
473 // done in a specific MessageLoop instance (i.e., specific thread).
474 // If message_histogram_ is NULL, this is a no-op.
475 void HistogramEvent(int event);
476
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900477 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900478 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900479 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900480 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900481 virtual void GetQueueingInformation(size_t* queue_size,
482 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900483
sky@chromium.orgab452802013-11-08 15:16:53 +0900484 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900485
486 // A list of tasks that need to be processed by this instance. Note that
487 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900488 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900489
490 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900491 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900492
493 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900494 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900495
496 // A queue of non-nestable tasks that we had to defer because when it came
497 // time to execute them we were in a nested message loop. They will execute
498 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900499 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900500
501 ObserverList<DestructionObserver> destruction_observers_;
502
503 // A recursion block that prevents accidentally running additional tasks when
504 // insider a (accidentally induced?) nested message pump.
505 bool nestable_tasks_allowed_;
506
alexeypa@google.combb819d62013-07-23 05:06:56 +0900507#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900508 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
509 // which enter a modal message loop.
510 bool os_modal_loop_;
511#endif
512
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900513 std::string thread_name_;
514 // A profiling histogram showing the counts of various messages and events.
515 HistogramBase* message_histogram_;
516
517 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900518
brettw@chromium.org6318b392013-06-14 12:27:49 +0900519 ObserverList<TaskObserver> task_observers_;
520
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900521 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
522
523 // The message loop proxy associated with this message loop.
524 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900525 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900526
527 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
528 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
529
530 void DeleteSoonInternal(const tracked_objects::Location& from_here,
531 void(*deleter)(const void*),
532 const void* object);
533 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
534 void(*releaser)(const void*),
535 const void* object);
536
537 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
538};
539
540//-----------------------------------------------------------------------------
541// MessageLoopForUI extends MessageLoop with methods that are particular to a
542// MessageLoop instantiated with TYPE_UI.
543//
544// This class is typically used like so:
545// MessageLoopForUI::current()->...call some method...
546//
547class BASE_EXPORT MessageLoopForUI : public MessageLoop {
548 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900549 MessageLoopForUI() : MessageLoop(TYPE_UI) {
550 }
551
552 // Returns the MessageLoopForUI of the current thread.
553 static MessageLoopForUI* current() {
554 MessageLoop* loop = MessageLoop::current();
555 DCHECK(loop);
556 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
557 return static_cast<MessageLoopForUI*>(loop);
558 }
559
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900560 static bool IsCurrent() {
561 MessageLoop* loop = MessageLoop::current();
562 return loop && loop->type() == MessageLoop::TYPE_UI;
563 }
564
brettw@chromium.org6318b392013-06-14 12:27:49 +0900565#if defined(OS_IOS)
566 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
567 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
568 // PostTask() to work.
569 void Attach();
570#endif
571
572#if defined(OS_ANDROID)
573 // On Android, the UI message loop is handled by Java side. So Run() should
574 // never be called. Instead use Start(), which will forward all the native UI
575 // events to the Java message loop.
576 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900577#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900578
sadrul@chromium.org25e9de22014-04-11 12:02:29 +0900579#if !defined(OS_NACL) && defined(OS_WIN)
580 // Please see message_pump_win for definitions of these methods.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900581 void AddObserver(Observer* observer);
582 void RemoveObserver(Observer* observer);
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900583#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900584
spang@chromium.orgcc842882014-04-11 05:03:11 +0900585#if defined(USE_OZONE) && !defined(OS_NACL)
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900586 // Please see MessagePumpLibevent for definition.
587 bool WatchFileDescriptor(
588 int fd,
589 bool persistent,
590 MessagePumpLibevent::Mode mode,
591 MessagePumpLibevent::FileDescriptorWatcher* controller,
592 MessagePumpLibevent::Watcher* delegate);
593#endif
594
brettw@chromium.org6318b392013-06-14 12:27:49 +0900595 protected:
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900596#if defined(USE_X11)
sadrul@chromium.org19995722013-09-07 12:21:04 +0900597 friend class MessagePumpX11;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900598#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900599
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900600#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900601 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900602 MessagePumpForUI* pump_ui() {
603 return static_cast<MessagePumpForUI*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900604 }
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900605#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900606};
607
608// Do not add any member variables to MessageLoopForUI! This is important b/c
609// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
610// data that you need should be stored on the MessageLoop's pump_ instance.
611COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
612 MessageLoopForUI_should_not_have_extra_member_variables);
613
614//-----------------------------------------------------------------------------
615// MessageLoopForIO extends MessageLoop with methods that are particular to a
616// MessageLoop instantiated with TYPE_IO.
617//
618// This class is typically used like so:
619// MessageLoopForIO::current()->...call some method...
620//
621class BASE_EXPORT MessageLoopForIO : public MessageLoop {
622 public:
623#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900624 typedef MessagePumpForIO::IOHandler IOHandler;
625 typedef MessagePumpForIO::IOContext IOContext;
626 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900627#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900628 typedef MessagePumpIOSForIO::Watcher Watcher;
629 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900630 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900631 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900632
633 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900634 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
635 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
636 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900637 };
638#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900639 typedef MessagePumpLibevent::Watcher Watcher;
640 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900641 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900642 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900643
644 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900645 WATCH_READ = MessagePumpLibevent::WATCH_READ,
646 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
647 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900648 };
649
650#endif
651
652 MessageLoopForIO() : MessageLoop(TYPE_IO) {
653 }
654
655 // Returns the MessageLoopForIO of the current thread.
656 static MessageLoopForIO* current() {
657 MessageLoop* loop = MessageLoop::current();
658 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
659 return static_cast<MessageLoopForIO*>(loop);
660 }
661
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900662 static bool IsCurrent() {
663 MessageLoop* loop = MessageLoop::current();
664 return loop && loop->type() == MessageLoop::TYPE_IO;
665 }
666
brettw@chromium.org6318b392013-06-14 12:27:49 +0900667 void AddIOObserver(IOObserver* io_observer) {
668 pump_io()->AddIOObserver(io_observer);
669 }
670
671 void RemoveIOObserver(IOObserver* io_observer) {
672 pump_io()->RemoveIOObserver(io_observer);
673 }
674
675#if defined(OS_WIN)
676 // Please see MessagePumpWin for definitions of these methods.
677 void RegisterIOHandler(HANDLE file, IOHandler* handler);
678 bool RegisterJobObject(HANDLE job, IOHandler* handler);
679 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
680
681 protected:
682 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900683 MessagePumpForIO* pump_io() {
684 return static_cast<MessagePumpForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900685 }
686
687#elif defined(OS_IOS)
688 // Please see MessagePumpIOSForIO for definition.
689 bool WatchFileDescriptor(int fd,
690 bool persistent,
691 Mode mode,
692 FileDescriptorWatcher *controller,
693 Watcher *delegate);
694
695 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900696 MessagePumpIOSForIO* pump_io() {
697 return static_cast<MessagePumpIOSForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900698 }
699
700#elif defined(OS_POSIX)
701 // Please see MessagePumpLibevent for definition.
702 bool WatchFileDescriptor(int fd,
703 bool persistent,
704 Mode mode,
705 FileDescriptorWatcher* controller,
706 Watcher* delegate);
707
708 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900709 MessagePumpLibevent* pump_io() {
710 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900711 }
712#endif // defined(OS_POSIX)
713};
714
715// Do not add any member variables to MessageLoopForIO! This is important b/c
716// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
717// data that you need should be stored on the MessageLoop's pump_ instance.
718COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
719 MessageLoopForIO_should_not_have_extra_member_variables);
720
721} // namespace base
722
723#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_