blob: edb9da7b8960bf38c95c10b00f282a3811d9881f [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
sadrul@chromium.orgf59198c2014-04-15 12:34:54 +090037#if defined(USE_GLIB) && !defined(OS_NACL)
38#include "base/message_loop/message_pump_glib.h"
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090039#elif !defined(OS_ANDROID_HOST)
sadrul@chromium.orgf59198c2014-04-15 12:34:54 +090040#include "base/message_loop/message_pump_glib.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090041#endif
42
43#endif
44#endif
45
46namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090047
brettw@chromium.org6318b392013-06-14 12:27:49 +090048class HistogramBase;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090049class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090050class RunLoop;
51class ThreadTaskRunnerHandle;
52#if defined(OS_ANDROID)
53class MessagePumpForUI;
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090054#elif defined(OS_ANDROID_HOST)
55typedef MessagePumpLibevent MessagePumpForUI;
brettw@chromium.org6318b392013-06-14 12:27:49 +090056#endif
alexeypa@chromium.org40183232013-07-23 07:24:13 +090057class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090058
59// A MessageLoop is used to process events for a particular thread. There is
60// at most one MessageLoop instance per thread.
61//
62// Events include at a minimum Task instances submitted to PostTask and its
63// variants. Depending on the type of message pump used by the MessageLoop
64// other events such as UI messages may be processed. On Windows APC calls (as
65// time permits) and signals sent to a registered set of HANDLEs may also be
66// processed.
67//
68// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
69// on the thread where the MessageLoop's Run method executes.
70//
71// NOTE: MessageLoop has task reentrancy protection. This means that if a
72// task is being processed, a second task cannot start until the first task is
73// finished. Reentrancy can happen when processing a task, and an inner
74// message pump is created. That inner pump then processes native messages
75// which could implicitly start an inner task. Inner message pumps are created
76// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
77// (DoDragDrop), printer functions (StartDoc) and *many* others.
78//
79// Sample workaround when inner task processing is needed:
80// HRESULT hr;
81// {
82// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
83// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
84// }
85// // Process |hr| (the result returned by DoDragDrop()).
86//
87// Please be SURE your task is reentrant (nestable) and all global variables
88// are stable and accessible before calling SetNestableTasksAllowed(true).
89//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090090class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090091 public:
sadrul@chromium.org25e9de22014-04-11 12:02:29 +090092#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090093 typedef MessagePumpObserver Observer;
brettw@chromium.org6318b392013-06-14 12:27:49 +090094#endif
95
96 // A MessageLoop has a particular type, which indicates the set of
97 // asynchronous events it may process in addition to tasks and timers.
98 //
99 // TYPE_DEFAULT
100 // This type of ML only supports tasks and timers.
101 //
102 // TYPE_UI
103 // This type of ML also supports native UI events (e.g., Windows messages).
104 // See also MessageLoopForUI.
105 //
106 // TYPE_IO
107 // This type of ML also supports asynchronous IO. See also
108 // MessageLoopForIO.
109 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900110 // TYPE_JAVA
111 // This type of ML is backed by a Java message handler which is responsible
112 // for running the tasks added to the ML. This is only for use on Android.
113 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
114 // where it does not use the main thread specific pump factory.
115 //
sky@chromium.orgab452802013-11-08 15:16:53 +0900116 // TYPE_CUSTOM
117 // MessagePump was supplied to constructor.
118 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900119 enum Type {
120 TYPE_DEFAULT,
121 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900122 TYPE_CUSTOM,
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900123 TYPE_IO,
124#if defined(OS_ANDROID)
125 TYPE_JAVA,
126#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900127 };
128
129 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
130 // is typical to make use of the current thread's MessageLoop instance.
131 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900132 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
133 // be non-NULL.
134 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900135 virtual ~MessageLoop();
136
137 // Returns the MessageLoop object for the current thread, or null if none.
138 static MessageLoop* current();
139
140 static void EnableHistogrammer(bool enable_histogrammer);
141
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900142 typedef scoped_ptr<MessagePump> (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900143 // Uses the given base::MessagePumpForUIFactory to override the default
144 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
145 // was successfully registered.
146 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
147
sky@chromium.org4f426822013-11-13 01:35:02 +0900148 // Creates the default MessagePump based on |type|. Caller owns return
149 // value.
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900150 static scoped_ptr<MessagePump> CreateMessagePumpForType(Type type);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900151 // A DestructionObserver is notified when the current MessageLoop is being
152 // destroyed. These observers are notified prior to MessageLoop::current()
153 // being changed to return NULL. This gives interested parties the chance to
154 // do final cleanup that depends on the MessageLoop.
155 //
156 // NOTE: Any tasks posted to the MessageLoop during this notification will
157 // not be run. Instead, they will be deleted.
158 //
159 class BASE_EXPORT DestructionObserver {
160 public:
161 virtual void WillDestroyCurrentMessageLoop() = 0;
162
163 protected:
164 virtual ~DestructionObserver();
165 };
166
167 // Add a DestructionObserver, which will start receiving notifications
168 // immediately.
169 void AddDestructionObserver(DestructionObserver* destruction_observer);
170
171 // Remove a DestructionObserver. It is safe to call this method while a
172 // DestructionObserver is receiving a notification callback.
173 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
174
175 // The "PostTask" family of methods call the task's Run method asynchronously
176 // from within a message loop at some point in the future.
177 //
178 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
179 // with normal UI or IO event processing. With the PostDelayedTask variant,
180 // tasks are called after at least approximately 'delay_ms' have elapsed.
181 //
182 // The NonNestable variants work similarly except that they promise never to
183 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
184 // such tasks get deferred until the top-most MessageLoop::Run is executing.
185 //
186 // The MessageLoop takes ownership of the Task, and deletes it after it has
187 // been Run().
188 //
189 // PostTask(from_here, task) is equivalent to
190 // PostDelayedTask(from_here, task, 0).
191 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900192 // NOTE: These methods may be called on any thread. The Task will be invoked
193 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900194 void PostTask(const tracked_objects::Location& from_here,
195 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900196
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900197 void PostDelayedTask(const tracked_objects::Location& from_here,
198 const Closure& task,
199 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900200
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900201 void PostNonNestableTask(const tracked_objects::Location& from_here,
202 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900203
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900204 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
205 const Closure& task,
206 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900207
208 // A variant on PostTask that deletes the given object. This is useful
209 // if the object needs to live until the next run of the MessageLoop (for
210 // example, deleting a RenderProcessHost from within an IPC callback is not
211 // good).
212 //
213 // NOTE: This method may be called on any thread. The object will be deleted
214 // on the thread that executes MessageLoop::Run(). If this is not the same
215 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
216 // from RefCountedThreadSafe<T>!
217 template <class T>
218 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
219 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
220 this, from_here, object);
221 }
222
223 // A variant on PostTask that releases the given reference counted object
224 // (by calling its Release method). This is useful if the object needs to
225 // live until the next run of the MessageLoop, or if the object needs to be
226 // released on a particular thread.
227 //
228 // NOTE: This method may be called on any thread. The object will be
229 // released (and thus possibly deleted) on the thread that executes
230 // MessageLoop::Run(). If this is not the same as the thread that calls
231 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
232 // RefCountedThreadSafe<T>!
233 template <class T>
234 void ReleaseSoon(const tracked_objects::Location& from_here,
235 const T* object) {
236 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
237 this, from_here, object);
238 }
239
240 // Deprecated: use RunLoop instead.
241 // Run the message loop.
242 void Run();
243
244 // Deprecated: use RunLoop instead.
245 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
246 // Return as soon as all items that can be run are taken care of.
247 void RunUntilIdle();
248
249 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
250 void Quit() { QuitWhenIdle(); }
251
252 // Deprecated: use RunLoop instead.
253 //
254 // Signals the Run method to return when it becomes idle. It will continue to
255 // process pending messages and future messages as long as they are enqueued.
256 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
257 // Quit method when looping procedures (such as web pages) have been shut
258 // down.
259 //
260 // This method may only be called on the same thread that called Run, and Run
261 // must still be on the call stack.
262 //
263 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
264 // but note that doing so is fairly dangerous if the target thread makes
265 // nested calls to MessageLoop::Run. The problem being that you won't know
266 // which nested run loop you are quitting, so be careful!
267 void QuitWhenIdle();
268
269 // Deprecated: use RunLoop instead.
270 //
271 // This method is a variant of Quit, that does not wait for pending messages
272 // to be processed before returning from Run.
273 void QuitNow();
274
275 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900276 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900277
278 // Deprecated: use RunLoop instead.
279 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
280 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900281 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900282
283 // Returns true if this loop is |type|. This allows subclasses (especially
284 // those in tests) to specialize how they are identified.
285 virtual bool IsType(Type type) const;
286
287 // Returns the type passed to the constructor.
288 Type type() const { return type_; }
289
290 // Optional call to connect the thread name with this loop.
291 void set_thread_name(const std::string& thread_name) {
292 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
293 thread_name_ = thread_name;
294 }
295 const std::string& thread_name() const { return thread_name_; }
296
297 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900298 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900299 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900300 }
301
302 // Enables or disables the recursive task processing. This happens in the case
303 // of recursive message loops. Some unwanted message loop may occurs when
304 // using common controls or printer functions. By default, recursive task
305 // processing is disabled.
306 //
307 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
308 // directly. In general nestable message loops are to be avoided. They are
309 // dangerous and difficult to get right, so please use with extreme caution.
310 //
311 // The specific case where tasks get queued is:
312 // - The thread is running a message loop.
313 // - It receives a task #1 and execute it.
314 // - The task #1 implicitly start a message loop, like a MessageBox in the
315 // unit test. This can also be StartDoc or GetSaveFileName.
316 // - The thread receives a task #2 before or while in this second message
317 // loop.
318 // - With NestableTasksAllowed set to true, the task #2 will run right away.
319 // Otherwise, it will get executed right after task #1 completes at "thread
320 // message loop level".
321 void SetNestableTasksAllowed(bool allowed);
322 bool NestableTasksAllowed() const;
323
324 // Enables nestable tasks on |loop| while in scope.
325 class ScopedNestableTaskAllower {
326 public:
327 explicit ScopedNestableTaskAllower(MessageLoop* loop)
328 : loop_(loop),
329 old_state_(loop_->NestableTasksAllowed()) {
330 loop_->SetNestableTasksAllowed(true);
331 }
332 ~ScopedNestableTaskAllower() {
333 loop_->SetNestableTasksAllowed(old_state_);
334 }
335
336 private:
337 MessageLoop* loop_;
338 bool old_state_;
339 };
340
brettw@chromium.org6318b392013-06-14 12:27:49 +0900341 // Returns true if we are currently running a nested message loop.
342 bool IsNested();
343
344 // A TaskObserver is an object that receives task notifications from the
345 // MessageLoop.
346 //
347 // NOTE: A TaskObserver implementation should be extremely fast!
348 class BASE_EXPORT TaskObserver {
349 public:
350 TaskObserver();
351
352 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900353 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900354
355 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900356 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900357
358 protected:
359 virtual ~TaskObserver();
360 };
361
362 // These functions can only be called on the same thread that |this| is
363 // running on.
364 void AddTaskObserver(TaskObserver* task_observer);
365 void RemoveTaskObserver(TaskObserver* task_observer);
366
brettw@chromium.org6318b392013-06-14 12:27:49 +0900367 // When we go into high resolution timer mode, we will stay in hi-res mode
368 // for at least 1s.
369 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
370
brettw@chromium.org6318b392013-06-14 12:27:49 +0900371#if defined(OS_WIN)
372 void set_os_modal_loop(bool os_modal_loop) {
373 os_modal_loop_ = os_modal_loop;
374 }
375
376 bool os_modal_loop() const {
377 return os_modal_loop_;
378 }
379#endif // OS_WIN
380
381 // Can only be called from the thread that owns the MessageLoop.
382 bool is_running() const;
383
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900384 // Returns true if the message loop has high resolution timers enabled.
385 // Provided for testing.
386 bool IsHighResolutionTimerEnabledForTesting();
387
388 // Returns true if the message loop is "idle". Provided for testing.
389 bool IsIdleForTesting();
390
brettw@chromium.org6318b392013-06-14 12:27:49 +0900391 //----------------------------------------------------------------------------
392 protected:
393
394#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900395 MessagePumpWin* pump_win() {
396 return static_cast<MessagePumpWin*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900397 }
398#elif defined(OS_POSIX) && !defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900399 MessagePumpLibevent* pump_libevent() {
400 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900401 }
402#endif
403
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900404 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900405
406 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900407 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900408 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900409
sky@chromium.orgab452802013-11-08 15:16:53 +0900410 // Configures various members for the two constructors.
411 void Init();
412
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900413 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900414 void RunHandler();
415
brettw@chromium.org6318b392013-06-14 12:27:49 +0900416 // Called to process any delayed non-nestable tasks.
417 bool ProcessNextDelayedNonNestableTask();
418
419 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900420 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900421
422 // Calls RunTask or queues the pending_task on the deferred task list if it
423 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900424 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900425
426 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900427 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900428
brettw@chromium.org6318b392013-06-14 12:27:49 +0900429 // Delete tasks that haven't run yet without running them. Used in the
430 // destructor to make sure all the task's destructors get called. Returns
431 // true if some work was done.
432 bool DeletePendingTasks();
433
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900434 // Creates a process-wide unique ID to represent this task in trace events.
435 // This will be mangled with a Process ID hash to reduce the likelyhood of
436 // colliding with MessageLoop pointers on other processes.
437 uint64 GetTaskTraceID(const PendingTask& task);
438
439 // Loads tasks from the incoming queue to |work_queue_| if the latter is
440 // empty.
441 void ReloadWorkQueue();
442
443 // Wakes up the message pump. Can be called on any thread. The caller is
444 // responsible for synchronizing ScheduleWork() calls.
445 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900446
447 // Start recording histogram info about events and action IF it was enabled
448 // and IF the statistics recorder can accept a registration of our histogram.
449 void StartHistogrammer();
450
451 // Add occurrence of event to our histogram, so that we can see what is being
452 // done in a specific MessageLoop instance (i.e., specific thread).
453 // If message_histogram_ is NULL, this is a no-op.
454 void HistogramEvent(int event);
455
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900456 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900457 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900458 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900459 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900460 virtual void GetQueueingInformation(size_t* queue_size,
461 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900462
sky@chromium.orgab452802013-11-08 15:16:53 +0900463 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900464
465 // A list of tasks that need to be processed by this instance. Note that
466 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900467 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900468
469 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900470 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900471
472 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900473 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900474
475 // A queue of non-nestable tasks that we had to defer because when it came
476 // time to execute them we were in a nested message loop. They will execute
477 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900478 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900479
480 ObserverList<DestructionObserver> destruction_observers_;
481
482 // A recursion block that prevents accidentally running additional tasks when
483 // insider a (accidentally induced?) nested message pump.
484 bool nestable_tasks_allowed_;
485
alexeypa@google.combb819d62013-07-23 05:06:56 +0900486#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900487 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
488 // which enter a modal message loop.
489 bool os_modal_loop_;
490#endif
491
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900492 std::string thread_name_;
493 // A profiling histogram showing the counts of various messages and events.
494 HistogramBase* message_histogram_;
495
496 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900497
brettw@chromium.org6318b392013-06-14 12:27:49 +0900498 ObserverList<TaskObserver> task_observers_;
499
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900500 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
501
502 // The message loop proxy associated with this message loop.
503 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900504 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900505
506 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
507 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
508
509 void DeleteSoonInternal(const tracked_objects::Location& from_here,
510 void(*deleter)(const void*),
511 const void* object);
512 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
513 void(*releaser)(const void*),
514 const void* object);
515
516 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
517};
518
519//-----------------------------------------------------------------------------
520// MessageLoopForUI extends MessageLoop with methods that are particular to a
521// MessageLoop instantiated with TYPE_UI.
522//
523// This class is typically used like so:
524// MessageLoopForUI::current()->...call some method...
525//
526class BASE_EXPORT MessageLoopForUI : public MessageLoop {
527 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900528 MessageLoopForUI() : MessageLoop(TYPE_UI) {
529 }
530
531 // Returns the MessageLoopForUI of the current thread.
532 static MessageLoopForUI* current() {
533 MessageLoop* loop = MessageLoop::current();
534 DCHECK(loop);
535 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
536 return static_cast<MessageLoopForUI*>(loop);
537 }
538
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900539 static bool IsCurrent() {
540 MessageLoop* loop = MessageLoop::current();
541 return loop && loop->type() == MessageLoop::TYPE_UI;
542 }
543
brettw@chromium.org6318b392013-06-14 12:27:49 +0900544#if defined(OS_IOS)
545 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
546 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
547 // PostTask() to work.
548 void Attach();
549#endif
550
551#if defined(OS_ANDROID)
552 // On Android, the UI message loop is handled by Java side. So Run() should
553 // never be called. Instead use Start(), which will forward all the native UI
554 // events to the Java message loop.
555 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900556#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900557
sadrul@chromium.org25e9de22014-04-11 12:02:29 +0900558#if !defined(OS_NACL) && defined(OS_WIN)
559 // Please see message_pump_win for definitions of these methods.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900560 void AddObserver(Observer* observer);
561 void RemoveObserver(Observer* observer);
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900562#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900563
spang@chromium.orgcc842882014-04-11 05:03:11 +0900564#if defined(USE_OZONE) && !defined(OS_NACL)
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900565 // Please see MessagePumpLibevent for definition.
566 bool WatchFileDescriptor(
567 int fd,
568 bool persistent,
569 MessagePumpLibevent::Mode mode,
570 MessagePumpLibevent::FileDescriptorWatcher* controller,
571 MessagePumpLibevent::Watcher* delegate);
572#endif
573
brettw@chromium.org6318b392013-06-14 12:27:49 +0900574 protected:
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900575#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900576 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900577 MessagePumpForUI* pump_ui() {
578 return static_cast<MessagePumpForUI*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900579 }
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900580#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900581};
582
583// Do not add any member variables to MessageLoopForUI! This is important b/c
584// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
585// data that you need should be stored on the MessageLoop's pump_ instance.
586COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
587 MessageLoopForUI_should_not_have_extra_member_variables);
588
589//-----------------------------------------------------------------------------
590// MessageLoopForIO extends MessageLoop with methods that are particular to a
591// MessageLoop instantiated with TYPE_IO.
592//
593// This class is typically used like so:
594// MessageLoopForIO::current()->...call some method...
595//
596class BASE_EXPORT MessageLoopForIO : public MessageLoop {
597 public:
598#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900599 typedef MessagePumpForIO::IOHandler IOHandler;
600 typedef MessagePumpForIO::IOContext IOContext;
601 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900602#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900603 typedef MessagePumpIOSForIO::Watcher Watcher;
604 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900605 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900606 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900607
608 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900609 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
610 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
611 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900612 };
613#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900614 typedef MessagePumpLibevent::Watcher Watcher;
615 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900616 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900617 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900618
619 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900620 WATCH_READ = MessagePumpLibevent::WATCH_READ,
621 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
622 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900623 };
624
625#endif
626
627 MessageLoopForIO() : MessageLoop(TYPE_IO) {
628 }
629
630 // Returns the MessageLoopForIO of the current thread.
631 static MessageLoopForIO* current() {
632 MessageLoop* loop = MessageLoop::current();
633 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
634 return static_cast<MessageLoopForIO*>(loop);
635 }
636
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900637 static bool IsCurrent() {
638 MessageLoop* loop = MessageLoop::current();
639 return loop && loop->type() == MessageLoop::TYPE_IO;
640 }
641
brettw@chromium.org6318b392013-06-14 12:27:49 +0900642 void AddIOObserver(IOObserver* io_observer) {
643 pump_io()->AddIOObserver(io_observer);
644 }
645
646 void RemoveIOObserver(IOObserver* io_observer) {
647 pump_io()->RemoveIOObserver(io_observer);
648 }
649
650#if defined(OS_WIN)
651 // Please see MessagePumpWin for definitions of these methods.
652 void RegisterIOHandler(HANDLE file, IOHandler* handler);
653 bool RegisterJobObject(HANDLE job, IOHandler* handler);
654 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
655
656 protected:
657 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900658 MessagePumpForIO* pump_io() {
659 return static_cast<MessagePumpForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900660 }
661
662#elif defined(OS_IOS)
663 // Please see MessagePumpIOSForIO for definition.
664 bool WatchFileDescriptor(int fd,
665 bool persistent,
666 Mode mode,
667 FileDescriptorWatcher *controller,
668 Watcher *delegate);
669
670 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900671 MessagePumpIOSForIO* pump_io() {
672 return static_cast<MessagePumpIOSForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900673 }
674
675#elif defined(OS_POSIX)
676 // Please see MessagePumpLibevent for definition.
677 bool WatchFileDescriptor(int fd,
678 bool persistent,
679 Mode mode,
680 FileDescriptorWatcher* controller,
681 Watcher* delegate);
682
683 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900684 MessagePumpLibevent* pump_io() {
685 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900686 }
687#endif // defined(OS_POSIX)
688};
689
690// Do not add any member variables to MessageLoopForIO! This is important b/c
691// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
692// data that you need should be stored on the MessageLoop's pump_ instance.
693COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
694 MessageLoopForIO_should_not_have_extra_member_variables);
695
696} // namespace base
697
698#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_