blob: 4bb7d550bccf53a53c062daea1436208bd6e6b38 [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 //
210 // NOTE: This method may be called on any thread. The object will be
211 // released (and thus possibly deleted) on the thread that executes
212 // MessageLoop::Run(). If this is not the same as the thread that calls
213 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
214 // RefCountedThreadSafe<T>!
215 template <class T>
216 void ReleaseSoon(const tracked_objects::Location& from_here,
217 const T* object) {
218 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
219 this, from_here, object);
220 }
221
222 // Deprecated: use RunLoop instead.
223 // Run the message loop.
224 void Run();
225
226 // Deprecated: use RunLoop instead.
227 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
228 // Return as soon as all items that can be run are taken care of.
229 void RunUntilIdle();
230
231 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
232 void Quit() { QuitWhenIdle(); }
233
234 // Deprecated: use RunLoop instead.
235 //
236 // Signals the Run method to return when it becomes idle. It will continue to
237 // process pending messages and future messages as long as they are enqueued.
238 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
239 // Quit method when looping procedures (such as web pages) have been shut
240 // down.
241 //
242 // This method may only be called on the same thread that called Run, and Run
243 // must still be on the call stack.
244 //
245 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
246 // but note that doing so is fairly dangerous if the target thread makes
247 // nested calls to MessageLoop::Run. The problem being that you won't know
248 // which nested run loop you are quitting, so be careful!
249 void QuitWhenIdle();
250
251 // Deprecated: use RunLoop instead.
252 //
253 // This method is a variant of Quit, that does not wait for pending messages
254 // to be processed before returning from Run.
255 void QuitNow();
256
257 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900258 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900259
260 // Deprecated: use RunLoop instead.
261 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
262 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900263 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900264
265 // Returns true if this loop is |type|. This allows subclasses (especially
266 // those in tests) to specialize how they are identified.
267 virtual bool IsType(Type type) const;
268
269 // Returns the type passed to the constructor.
270 Type type() const { return type_; }
271
272 // Optional call to connect the thread name with this loop.
273 void set_thread_name(const std::string& thread_name) {
274 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
275 thread_name_ = thread_name;
276 }
277 const std::string& thread_name() const { return thread_name_; }
278
279 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900280 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900281 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900282 }
283
284 // Enables or disables the recursive task processing. This happens in the case
285 // of recursive message loops. Some unwanted message loop may occurs when
286 // using common controls or printer functions. By default, recursive task
287 // processing is disabled.
288 //
289 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
290 // directly. In general nestable message loops are to be avoided. They are
291 // dangerous and difficult to get right, so please use with extreme caution.
292 //
293 // The specific case where tasks get queued is:
294 // - The thread is running a message loop.
295 // - It receives a task #1 and execute it.
296 // - The task #1 implicitly start a message loop, like a MessageBox in the
297 // unit test. This can also be StartDoc or GetSaveFileName.
298 // - The thread receives a task #2 before or while in this second message
299 // loop.
300 // - With NestableTasksAllowed set to true, the task #2 will run right away.
301 // Otherwise, it will get executed right after task #1 completes at "thread
302 // message loop level".
303 void SetNestableTasksAllowed(bool allowed);
304 bool NestableTasksAllowed() const;
305
306 // Enables nestable tasks on |loop| while in scope.
307 class ScopedNestableTaskAllower {
308 public:
309 explicit ScopedNestableTaskAllower(MessageLoop* loop)
310 : loop_(loop),
311 old_state_(loop_->NestableTasksAllowed()) {
312 loop_->SetNestableTasksAllowed(true);
313 }
314 ~ScopedNestableTaskAllower() {
315 loop_->SetNestableTasksAllowed(old_state_);
316 }
317
318 private:
319 MessageLoop* loop_;
320 bool old_state_;
321 };
322
brettw@chromium.org6318b392013-06-14 12:27:49 +0900323 // Returns true if we are currently running a nested message loop.
324 bool IsNested();
325
326 // A TaskObserver is an object that receives task notifications from the
327 // MessageLoop.
328 //
329 // NOTE: A TaskObserver implementation should be extremely fast!
330 class BASE_EXPORT TaskObserver {
331 public:
332 TaskObserver();
333
334 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900335 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900336
337 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900338 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900339
340 protected:
341 virtual ~TaskObserver();
342 };
343
344 // These functions can only be called on the same thread that |this| is
345 // running on.
346 void AddTaskObserver(TaskObserver* task_observer);
347 void RemoveTaskObserver(TaskObserver* task_observer);
348
brettw@chromium.org6318b392013-06-14 12:27:49 +0900349 // When we go into high resolution timer mode, we will stay in hi-res mode
350 // for at least 1s.
351 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
352
brettw@chromium.org6318b392013-06-14 12:27:49 +0900353#if defined(OS_WIN)
354 void set_os_modal_loop(bool os_modal_loop) {
355 os_modal_loop_ = os_modal_loop;
356 }
357
358 bool os_modal_loop() const {
359 return os_modal_loop_;
360 }
361#endif // OS_WIN
362
363 // Can only be called from the thread that owns the MessageLoop.
364 bool is_running() const;
365
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900366 // Returns true if the message loop has high resolution timers enabled.
367 // Provided for testing.
368 bool IsHighResolutionTimerEnabledForTesting();
369
370 // Returns true if the message loop is "idle". Provided for testing.
371 bool IsIdleForTesting();
372
brettw@chromium.org6318b392013-06-14 12:27:49 +0900373 //----------------------------------------------------------------------------
374 protected:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900375 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900376
377 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900378 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900379 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900380
sky@chromium.orgab452802013-11-08 15:16:53 +0900381 // Configures various members for the two constructors.
382 void Init();
383
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900384 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900385 void RunHandler();
386
brettw@chromium.org6318b392013-06-14 12:27:49 +0900387 // Called to process any delayed non-nestable tasks.
388 bool ProcessNextDelayedNonNestableTask();
389
390 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900391 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900392
393 // Calls RunTask or queues the pending_task on the deferred task list if it
394 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900395 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900396
397 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900398 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900399
brettw@chromium.org6318b392013-06-14 12:27:49 +0900400 // Delete tasks that haven't run yet without running them. Used in the
401 // destructor to make sure all the task's destructors get called. Returns
402 // true if some work was done.
403 bool DeletePendingTasks();
404
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900405 // Creates a process-wide unique ID to represent this task in trace events.
406 // This will be mangled with a Process ID hash to reduce the likelyhood of
407 // colliding with MessageLoop pointers on other processes.
408 uint64 GetTaskTraceID(const PendingTask& task);
409
410 // Loads tasks from the incoming queue to |work_queue_| if the latter is
411 // empty.
412 void ReloadWorkQueue();
413
414 // Wakes up the message pump. Can be called on any thread. The caller is
415 // responsible for synchronizing ScheduleWork() calls.
416 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900417
418 // Start recording histogram info about events and action IF it was enabled
419 // and IF the statistics recorder can accept a registration of our histogram.
420 void StartHistogrammer();
421
422 // Add occurrence of event to our histogram, so that we can see what is being
423 // done in a specific MessageLoop instance (i.e., specific thread).
424 // If message_histogram_ is NULL, this is a no-op.
425 void HistogramEvent(int event);
426
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900427 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900428 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900429 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900430 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900431 virtual void GetQueueingInformation(size_t* queue_size,
432 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900433
sky@chromium.orgab452802013-11-08 15:16:53 +0900434 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900435
436 // A list of tasks that need to be processed by this instance. Note that
437 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900438 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900439
440 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900441 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900442
443 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900444 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900445
446 // A queue of non-nestable tasks that we had to defer because when it came
447 // time to execute them we were in a nested message loop. They will execute
448 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900449 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900450
451 ObserverList<DestructionObserver> destruction_observers_;
452
453 // A recursion block that prevents accidentally running additional tasks when
454 // insider a (accidentally induced?) nested message pump.
455 bool nestable_tasks_allowed_;
456
alexeypa@google.combb819d62013-07-23 05:06:56 +0900457#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900458 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
459 // which enter a modal message loop.
460 bool os_modal_loop_;
461#endif
462
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900463 std::string thread_name_;
464 // A profiling histogram showing the counts of various messages and events.
465 HistogramBase* message_histogram_;
466
467 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900468
brettw@chromium.org6318b392013-06-14 12:27:49 +0900469 ObserverList<TaskObserver> task_observers_;
470
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900471 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
472
473 // The message loop proxy associated with this message loop.
474 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900475 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900476
477 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
478 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
479
480 void DeleteSoonInternal(const tracked_objects::Location& from_here,
481 void(*deleter)(const void*),
482 const void* object);
483 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
484 void(*releaser)(const void*),
485 const void* object);
486
487 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
488};
489
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900490#if !defined(OS_NACL)
491
brettw@chromium.org6318b392013-06-14 12:27:49 +0900492//-----------------------------------------------------------------------------
493// MessageLoopForUI extends MessageLoop with methods that are particular to a
494// MessageLoop instantiated with TYPE_UI.
495//
496// This class is typically used like so:
497// MessageLoopForUI::current()->...call some method...
498//
499class BASE_EXPORT MessageLoopForUI : public MessageLoop {
500 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900501 MessageLoopForUI() : MessageLoop(TYPE_UI) {
502 }
503
504 // Returns the MessageLoopForUI of the current thread.
505 static MessageLoopForUI* current() {
506 MessageLoop* loop = MessageLoop::current();
507 DCHECK(loop);
508 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
509 return static_cast<MessageLoopForUI*>(loop);
510 }
511
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900512 static bool IsCurrent() {
513 MessageLoop* loop = MessageLoop::current();
514 return loop && loop->type() == MessageLoop::TYPE_UI;
515 }
516
brettw@chromium.org6318b392013-06-14 12:27:49 +0900517#if defined(OS_IOS)
518 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
519 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
520 // PostTask() to work.
521 void Attach();
522#endif
523
524#if defined(OS_ANDROID)
525 // On Android, the UI message loop is handled by Java side. So Run() should
526 // never be called. Instead use Start(), which will forward all the native UI
527 // events to the Java message loop.
528 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900529#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900530
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900531#if defined(OS_WIN)
532 typedef MessagePumpObserver Observer;
533
sadrul@chromium.org25e9de22014-04-11 12:02:29 +0900534 // Please see message_pump_win for definitions of these methods.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900535 void AddObserver(Observer* observer);
536 void RemoveObserver(Observer* observer);
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900537#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900538
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900539#if defined(USE_OZONE) || (defined(OS_CHROMEOS) && !defined(USE_GLIB))
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900540 // Please see MessagePumpLibevent for definition.
541 bool WatchFileDescriptor(
542 int fd,
543 bool persistent,
544 MessagePumpLibevent::Mode mode,
545 MessagePumpLibevent::FileDescriptorWatcher* controller,
546 MessagePumpLibevent::Watcher* delegate);
547#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900548};
549
550// Do not add any member variables to MessageLoopForUI! This is important b/c
551// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
552// data that you need should be stored on the MessageLoop's pump_ instance.
553COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
554 MessageLoopForUI_should_not_have_extra_member_variables);
555
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900556#endif // !defined(OS_NACL)
557
brettw@chromium.org6318b392013-06-14 12:27:49 +0900558//-----------------------------------------------------------------------------
559// MessageLoopForIO extends MessageLoop with methods that are particular to a
560// MessageLoop instantiated with TYPE_IO.
561//
562// This class is typically used like so:
563// MessageLoopForIO::current()->...call some method...
564//
565class BASE_EXPORT MessageLoopForIO : public MessageLoop {
566 public:
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900567 MessageLoopForIO() : MessageLoop(TYPE_IO) {
568 }
569
570 // Returns the MessageLoopForIO of the current thread.
571 static MessageLoopForIO* current() {
572 MessageLoop* loop = MessageLoop::current();
573 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
574 return static_cast<MessageLoopForIO*>(loop);
575 }
576
577 static bool IsCurrent() {
578 MessageLoop* loop = MessageLoop::current();
579 return loop && loop->type() == MessageLoop::TYPE_IO;
580 }
581
582#if !defined(OS_NACL)
583
brettw@chromium.org6318b392013-06-14 12:27:49 +0900584#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900585 typedef MessagePumpForIO::IOHandler IOHandler;
586 typedef MessagePumpForIO::IOContext IOContext;
587 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900588#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900589 typedef MessagePumpIOSForIO::Watcher Watcher;
590 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900591 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900592 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900593
594 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900595 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
596 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
597 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900598 };
599#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900600 typedef MessagePumpLibevent::Watcher Watcher;
601 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900602 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900603 typedef MessagePumpLibevent::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 = MessagePumpLibevent::WATCH_READ,
607 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
608 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900609 };
brettw@chromium.org6318b392013-06-14 12:27:49 +0900610#endif
611
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900612 void AddIOObserver(IOObserver* io_observer);
613 void RemoveIOObserver(IOObserver* io_observer);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900614
615#if defined(OS_WIN)
616 // Please see MessagePumpWin for definitions of these methods.
617 void RegisterIOHandler(HANDLE file, IOHandler* handler);
618 bool RegisterJobObject(HANDLE job, IOHandler* handler);
619 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900620#elif defined(OS_POSIX)
621 // Please see MessagePumpIOSForIO/MessagePumpLibevent for definition.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900622 bool WatchFileDescriptor(int fd,
623 bool persistent,
624 Mode mode,
625 FileDescriptorWatcher *controller,
626 Watcher *delegate);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900627#endif // defined(OS_IOS) || defined(OS_POSIX)
628#endif // !defined(OS_NACL)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900629};
630
631// Do not add any member variables to MessageLoopForIO! This is important b/c
632// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
633// data that you need should be stored on the MessageLoop's pump_ instance.
634COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
635 MessageLoopForIO_should_not_have_extra_member_variables);
636
637} // namespace base
638
639#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_