blob: 25891c5dc7c7c4866a5b865b8b1cc13f9092daaa [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#endif
36
37namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090038
brettw@chromium.org6318b392013-06-14 12:27:49 +090039class HistogramBase;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090040class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090041class RunLoop;
42class ThreadTaskRunnerHandle;
alexeypa@chromium.org40183232013-07-23 07:24:13 +090043class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090044
45// A MessageLoop is used to process events for a particular thread. There is
46// at most one MessageLoop instance per thread.
47//
48// Events include at a minimum Task instances submitted to PostTask and its
49// variants. Depending on the type of message pump used by the MessageLoop
50// other events such as UI messages may be processed. On Windows APC calls (as
51// time permits) and signals sent to a registered set of HANDLEs may also be
52// processed.
53//
54// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
55// on the thread where the MessageLoop's Run method executes.
56//
57// NOTE: MessageLoop has task reentrancy protection. This means that if a
58// task is being processed, a second task cannot start until the first task is
59// finished. Reentrancy can happen when processing a task, and an inner
60// message pump is created. That inner pump then processes native messages
61// which could implicitly start an inner task. Inner message pumps are created
62// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
63// (DoDragDrop), printer functions (StartDoc) and *many* others.
64//
65// Sample workaround when inner task processing is needed:
66// HRESULT hr;
67// {
68// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
69// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
70// }
71// // Process |hr| (the result returned by DoDragDrop()).
72//
73// Please be SURE your task is reentrant (nestable) and all global variables
74// are stable and accessible before calling SetNestableTasksAllowed(true).
75//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090076class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090077 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +090078 // A MessageLoop has a particular type, which indicates the set of
79 // asynchronous events it may process in addition to tasks and timers.
80 //
81 // TYPE_DEFAULT
82 // This type of ML only supports tasks and timers.
83 //
84 // TYPE_UI
85 // This type of ML also supports native UI events (e.g., Windows messages).
86 // See also MessageLoopForUI.
87 //
88 // TYPE_IO
89 // This type of ML also supports asynchronous IO. See also
90 // MessageLoopForIO.
91 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +090092 // TYPE_JAVA
93 // This type of ML is backed by a Java message handler which is responsible
94 // for running the tasks added to the ML. This is only for use on Android.
95 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
96 // where it does not use the main thread specific pump factory.
97 //
sky@chromium.orgab452802013-11-08 15:16:53 +090098 // TYPE_CUSTOM
99 // MessagePump was supplied to constructor.
100 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900101 enum Type {
102 TYPE_DEFAULT,
103 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900104 TYPE_CUSTOM,
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900105 TYPE_IO,
106#if defined(OS_ANDROID)
107 TYPE_JAVA,
108#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900109 };
110
111 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
112 // is typical to make use of the current thread's MessageLoop instance.
113 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900114 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
115 // be non-NULL.
116 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900117 virtual ~MessageLoop();
118
119 // Returns the MessageLoop object for the current thread, or null if none.
120 static MessageLoop* current();
121
122 static void EnableHistogrammer(bool enable_histogrammer);
123
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900124 typedef scoped_ptr<MessagePump> (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900125 // Uses the given base::MessagePumpForUIFactory to override the default
126 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
127 // was successfully registered.
128 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
129
sky@chromium.org4f426822013-11-13 01:35:02 +0900130 // Creates the default MessagePump based on |type|. Caller owns return
131 // value.
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900132 static scoped_ptr<MessagePump> CreateMessagePumpForType(Type type);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900133 // A DestructionObserver is notified when the current MessageLoop is being
134 // destroyed. These observers are notified prior to MessageLoop::current()
135 // being changed to return NULL. This gives interested parties the chance to
136 // do final cleanup that depends on the MessageLoop.
137 //
138 // NOTE: Any tasks posted to the MessageLoop during this notification will
139 // not be run. Instead, they will be deleted.
140 //
141 class BASE_EXPORT DestructionObserver {
142 public:
143 virtual void WillDestroyCurrentMessageLoop() = 0;
144
145 protected:
146 virtual ~DestructionObserver();
147 };
148
149 // Add a DestructionObserver, which will start receiving notifications
150 // immediately.
151 void AddDestructionObserver(DestructionObserver* destruction_observer);
152
153 // Remove a DestructionObserver. It is safe to call this method while a
154 // DestructionObserver is receiving a notification callback.
155 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
156
157 // The "PostTask" family of methods call the task's Run method asynchronously
158 // from within a message loop at some point in the future.
159 //
160 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
161 // with normal UI or IO event processing. With the PostDelayedTask variant,
162 // tasks are called after at least approximately 'delay_ms' have elapsed.
163 //
164 // The NonNestable variants work similarly except that they promise never to
165 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
166 // such tasks get deferred until the top-most MessageLoop::Run is executing.
167 //
168 // The MessageLoop takes ownership of the Task, and deletes it after it has
169 // been Run().
170 //
171 // PostTask(from_here, task) is equivalent to
172 // PostDelayedTask(from_here, task, 0).
173 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900174 // NOTE: These methods may be called on any thread. The Task will be invoked
175 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900176 void PostTask(const tracked_objects::Location& from_here,
177 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900178
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900179 void PostDelayedTask(const tracked_objects::Location& from_here,
180 const Closure& task,
181 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900182
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900183 void PostNonNestableTask(const tracked_objects::Location& from_here,
184 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900185
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900186 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
187 const Closure& task,
188 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900189
190 // A variant on PostTask that deletes the given object. This is useful
191 // if the object needs to live until the next run of the MessageLoop (for
192 // example, deleting a RenderProcessHost from within an IPC callback is not
193 // good).
194 //
195 // NOTE: This method may be called on any thread. The object will be deleted
196 // on the thread that executes MessageLoop::Run(). If this is not the same
197 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
198 // from RefCountedThreadSafe<T>!
199 template <class T>
200 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
201 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
202 this, from_here, object);
203 }
204
205 // A variant on PostTask that releases the given reference counted object
206 // (by calling its Release method). This is useful if the object needs to
207 // live until the next run of the MessageLoop, or if the object needs to be
208 // released on a particular thread.
209 //
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900210 // A common pattern is to manually increment the object's reference count
211 // (AddRef), issue a ReleaseSoon, then clear the pointer. The reference count
212 // is incremented manually to ensure clearing the pointer does not trigger a
213 // delete and to account for the upcoming decrement (ReleaseSoon). For
214 // example:
215 //
216 // scoped_refptr<Foo> foo = ...
217 // foo.AddRef();
218 // message_loop->ReleaseSoon(foo.get());
219 // foo = NULL;
220 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900221 // NOTE: This method may be called on any thread. The object will be
222 // released (and thus possibly deleted) on the thread that executes
223 // MessageLoop::Run(). If this is not the same as the thread that calls
224 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
225 // RefCountedThreadSafe<T>!
226 template <class T>
227 void ReleaseSoon(const tracked_objects::Location& from_here,
228 const T* object) {
229 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
230 this, from_here, object);
231 }
232
233 // Deprecated: use RunLoop instead.
234 // Run the message loop.
235 void Run();
236
237 // Deprecated: use RunLoop instead.
238 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
239 // Return as soon as all items that can be run are taken care of.
240 void RunUntilIdle();
241
242 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
243 void Quit() { QuitWhenIdle(); }
244
245 // Deprecated: use RunLoop instead.
246 //
247 // Signals the Run method to return when it becomes idle. It will continue to
248 // process pending messages and future messages as long as they are enqueued.
249 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
250 // Quit method when looping procedures (such as web pages) have been shut
251 // down.
252 //
253 // This method may only be called on the same thread that called Run, and Run
254 // must still be on the call stack.
255 //
256 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
257 // but note that doing so is fairly dangerous if the target thread makes
258 // nested calls to MessageLoop::Run. The problem being that you won't know
259 // which nested run loop you are quitting, so be careful!
260 void QuitWhenIdle();
261
262 // Deprecated: use RunLoop instead.
263 //
264 // This method is a variant of Quit, that does not wait for pending messages
265 // to be processed before returning from Run.
266 void QuitNow();
267
268 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900269 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900270
271 // Deprecated: use RunLoop instead.
272 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
273 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900274 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900275
276 // Returns true if this loop is |type|. This allows subclasses (especially
277 // those in tests) to specialize how they are identified.
278 virtual bool IsType(Type type) const;
279
280 // Returns the type passed to the constructor.
281 Type type() const { return type_; }
282
283 // Optional call to connect the thread name with this loop.
284 void set_thread_name(const std::string& thread_name) {
285 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
286 thread_name_ = thread_name;
287 }
288 const std::string& thread_name() const { return thread_name_; }
289
290 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900291 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900292 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900293 }
294
295 // Enables or disables the recursive task processing. This happens in the case
296 // of recursive message loops. Some unwanted message loop may occurs when
297 // using common controls or printer functions. By default, recursive task
298 // processing is disabled.
299 //
300 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
301 // directly. In general nestable message loops are to be avoided. They are
302 // dangerous and difficult to get right, so please use with extreme caution.
303 //
304 // The specific case where tasks get queued is:
305 // - The thread is running a message loop.
306 // - It receives a task #1 and execute it.
307 // - The task #1 implicitly start a message loop, like a MessageBox in the
308 // unit test. This can also be StartDoc or GetSaveFileName.
309 // - The thread receives a task #2 before or while in this second message
310 // loop.
311 // - With NestableTasksAllowed set to true, the task #2 will run right away.
312 // Otherwise, it will get executed right after task #1 completes at "thread
313 // message loop level".
314 void SetNestableTasksAllowed(bool allowed);
315 bool NestableTasksAllowed() const;
316
317 // Enables nestable tasks on |loop| while in scope.
318 class ScopedNestableTaskAllower {
319 public:
320 explicit ScopedNestableTaskAllower(MessageLoop* loop)
321 : loop_(loop),
322 old_state_(loop_->NestableTasksAllowed()) {
323 loop_->SetNestableTasksAllowed(true);
324 }
325 ~ScopedNestableTaskAllower() {
326 loop_->SetNestableTasksAllowed(old_state_);
327 }
328
329 private:
330 MessageLoop* loop_;
331 bool old_state_;
332 };
333
brettw@chromium.org6318b392013-06-14 12:27:49 +0900334 // Returns true if we are currently running a nested message loop.
335 bool IsNested();
336
337 // A TaskObserver is an object that receives task notifications from the
338 // MessageLoop.
339 //
340 // NOTE: A TaskObserver implementation should be extremely fast!
341 class BASE_EXPORT TaskObserver {
342 public:
343 TaskObserver();
344
345 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900346 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900347
348 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900349 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900350
351 protected:
352 virtual ~TaskObserver();
353 };
354
355 // These functions can only be called on the same thread that |this| is
356 // running on.
357 void AddTaskObserver(TaskObserver* task_observer);
358 void RemoveTaskObserver(TaskObserver* task_observer);
359
brettw@chromium.org6318b392013-06-14 12:27:49 +0900360 // When we go into high resolution timer mode, we will stay in hi-res mode
361 // for at least 1s.
362 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
363
brettw@chromium.org6318b392013-06-14 12:27:49 +0900364#if defined(OS_WIN)
365 void set_os_modal_loop(bool os_modal_loop) {
366 os_modal_loop_ = os_modal_loop;
367 }
368
369 bool os_modal_loop() const {
370 return os_modal_loop_;
371 }
372#endif // OS_WIN
373
374 // Can only be called from the thread that owns the MessageLoop.
375 bool is_running() const;
376
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900377 // Returns true if the message loop has high resolution timers enabled.
378 // Provided for testing.
379 bool IsHighResolutionTimerEnabledForTesting();
380
381 // Returns true if the message loop is "idle". Provided for testing.
382 bool IsIdleForTesting();
383
brettw@chromium.org6318b392013-06-14 12:27:49 +0900384 //----------------------------------------------------------------------------
385 protected:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900386 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900387
388 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900389 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900390 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900391
sky@chromium.orgab452802013-11-08 15:16:53 +0900392 // Configures various members for the two constructors.
393 void Init();
394
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900395 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900396 void RunHandler();
397
brettw@chromium.org6318b392013-06-14 12:27:49 +0900398 // Called to process any delayed non-nestable tasks.
399 bool ProcessNextDelayedNonNestableTask();
400
401 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900402 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900403
404 // Calls RunTask or queues the pending_task on the deferred task list if it
405 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900406 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900407
408 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900409 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900410
brettw@chromium.org6318b392013-06-14 12:27:49 +0900411 // Delete tasks that haven't run yet without running them. Used in the
412 // destructor to make sure all the task's destructors get called. Returns
413 // true if some work was done.
414 bool DeletePendingTasks();
415
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900416 // Creates a process-wide unique ID to represent this task in trace events.
417 // This will be mangled with a Process ID hash to reduce the likelyhood of
418 // colliding with MessageLoop pointers on other processes.
419 uint64 GetTaskTraceID(const PendingTask& task);
420
421 // Loads tasks from the incoming queue to |work_queue_| if the latter is
422 // empty.
423 void ReloadWorkQueue();
424
425 // Wakes up the message pump. Can be called on any thread. The caller is
426 // responsible for synchronizing ScheduleWork() calls.
427 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900428
429 // Start recording histogram info about events and action IF it was enabled
430 // and IF the statistics recorder can accept a registration of our histogram.
431 void StartHistogrammer();
432
433 // Add occurrence of event to our histogram, so that we can see what is being
434 // done in a specific MessageLoop instance (i.e., specific thread).
435 // If message_histogram_ is NULL, this is a no-op.
436 void HistogramEvent(int event);
437
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900438 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900439 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900440 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900441 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900442 virtual void GetQueueingInformation(size_t* queue_size,
443 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900444
sky@chromium.orgab452802013-11-08 15:16:53 +0900445 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900446
447 // A list of tasks that need to be processed by this instance. Note that
448 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900449 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900450
451 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900452 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900453
454 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900455 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900456
457 // A queue of non-nestable tasks that we had to defer because when it came
458 // time to execute them we were in a nested message loop. They will execute
459 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900460 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900461
462 ObserverList<DestructionObserver> destruction_observers_;
463
464 // A recursion block that prevents accidentally running additional tasks when
465 // insider a (accidentally induced?) nested message pump.
466 bool nestable_tasks_allowed_;
467
alexeypa@google.combb819d62013-07-23 05:06:56 +0900468#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900469 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
470 // which enter a modal message loop.
471 bool os_modal_loop_;
472#endif
473
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900474 std::string thread_name_;
475 // A profiling histogram showing the counts of various messages and events.
476 HistogramBase* message_histogram_;
477
478 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900479
brettw@chromium.org6318b392013-06-14 12:27:49 +0900480 ObserverList<TaskObserver> task_observers_;
481
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900482 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
483
484 // The message loop proxy associated with this message loop.
485 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900486 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900487
488 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
489 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
490
491 void DeleteSoonInternal(const tracked_objects::Location& from_here,
492 void(*deleter)(const void*),
493 const void* object);
494 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
495 void(*releaser)(const void*),
496 const void* object);
497
498 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
499};
500
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900501#if !defined(OS_NACL)
502
brettw@chromium.org6318b392013-06-14 12:27:49 +0900503//-----------------------------------------------------------------------------
504// MessageLoopForUI extends MessageLoop with methods that are particular to a
505// MessageLoop instantiated with TYPE_UI.
506//
507// This class is typically used like so:
508// MessageLoopForUI::current()->...call some method...
509//
510class BASE_EXPORT MessageLoopForUI : public MessageLoop {
511 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900512 MessageLoopForUI() : MessageLoop(TYPE_UI) {
513 }
514
515 // Returns the MessageLoopForUI of the current thread.
516 static MessageLoopForUI* current() {
517 MessageLoop* loop = MessageLoop::current();
518 DCHECK(loop);
519 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
520 return static_cast<MessageLoopForUI*>(loop);
521 }
522
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900523 static bool IsCurrent() {
524 MessageLoop* loop = MessageLoop::current();
525 return loop && loop->type() == MessageLoop::TYPE_UI;
526 }
527
brettw@chromium.org6318b392013-06-14 12:27:49 +0900528#if defined(OS_IOS)
529 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
530 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
531 // PostTask() to work.
532 void Attach();
533#endif
534
535#if defined(OS_ANDROID)
536 // On Android, the UI message loop is handled by Java side. So Run() should
537 // never be called. Instead use Start(), which will forward all the native UI
538 // events to the Java message loop.
539 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900540#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900541
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900542#if defined(OS_WIN)
543 typedef MessagePumpObserver Observer;
544
sadrul@chromium.org25e9de22014-04-11 12:02:29 +0900545 // Please see message_pump_win for definitions of these methods.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900546 void AddObserver(Observer* observer);
547 void RemoveObserver(Observer* observer);
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900548#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900549
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900550#if defined(USE_OZONE) || (defined(OS_CHROMEOS) && !defined(USE_GLIB))
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900551 // Please see MessagePumpLibevent for definition.
552 bool WatchFileDescriptor(
553 int fd,
554 bool persistent,
555 MessagePumpLibevent::Mode mode,
556 MessagePumpLibevent::FileDescriptorWatcher* controller,
557 MessagePumpLibevent::Watcher* delegate);
558#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900559};
560
561// Do not add any member variables to MessageLoopForUI! This is important b/c
562// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
563// data that you need should be stored on the MessageLoop's pump_ instance.
564COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
565 MessageLoopForUI_should_not_have_extra_member_variables);
566
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900567#endif // !defined(OS_NACL)
568
brettw@chromium.org6318b392013-06-14 12:27:49 +0900569//-----------------------------------------------------------------------------
570// MessageLoopForIO extends MessageLoop with methods that are particular to a
571// MessageLoop instantiated with TYPE_IO.
572//
573// This class is typically used like so:
574// MessageLoopForIO::current()->...call some method...
575//
576class BASE_EXPORT MessageLoopForIO : public MessageLoop {
577 public:
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900578 MessageLoopForIO() : MessageLoop(TYPE_IO) {
579 }
580
581 // Returns the MessageLoopForIO of the current thread.
582 static MessageLoopForIO* current() {
583 MessageLoop* loop = MessageLoop::current();
584 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
585 return static_cast<MessageLoopForIO*>(loop);
586 }
587
588 static bool IsCurrent() {
589 MessageLoop* loop = MessageLoop::current();
590 return loop && loop->type() == MessageLoop::TYPE_IO;
591 }
592
593#if !defined(OS_NACL)
594
brettw@chromium.org6318b392013-06-14 12:27:49 +0900595#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900596 typedef MessagePumpForIO::IOHandler IOHandler;
597 typedef MessagePumpForIO::IOContext IOContext;
598 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900599#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900600 typedef MessagePumpIOSForIO::Watcher Watcher;
601 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900602 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900603 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900604
605 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900606 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
607 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
608 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900609 };
610#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900611 typedef MessagePumpLibevent::Watcher Watcher;
612 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900613 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900614 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900615
616 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900617 WATCH_READ = MessagePumpLibevent::WATCH_READ,
618 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
619 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900620 };
brettw@chromium.org6318b392013-06-14 12:27:49 +0900621#endif
622
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900623 void AddIOObserver(IOObserver* io_observer);
624 void RemoveIOObserver(IOObserver* io_observer);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900625
626#if defined(OS_WIN)
627 // Please see MessagePumpWin for definitions of these methods.
628 void RegisterIOHandler(HANDLE file, IOHandler* handler);
629 bool RegisterJobObject(HANDLE job, IOHandler* handler);
630 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900631#elif defined(OS_POSIX)
632 // Please see MessagePumpIOSForIO/MessagePumpLibevent for definition.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900633 bool WatchFileDescriptor(int fd,
634 bool persistent,
635 Mode mode,
636 FileDescriptorWatcher *controller,
637 Watcher *delegate);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900638#endif // defined(OS_IOS) || defined(OS_POSIX)
639#endif // !defined(OS_NACL)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900640};
641
642// Do not add any member variables to MessageLoopForIO! This is important b/c
643// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
644// data that you need should be stored on the MessageLoop's pump_ instance.
645COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
646 MessageLoopForIO_should_not_have_extra_member_variables);
647
648} // namespace base
649
650#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_