blob: 1d13b126b0a9f616bb6bc7c25167a85fe08fd1aa [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"
jeremy@chromium.org4d5a6b22014-06-06 04:36:20 +090021#include "base/message_loop/timer_slack.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090022#include "base/observer_list.h"
23#include "base/pending_task.h"
24#include "base/sequenced_task_runner_helpers.h"
25#include "base/synchronization/lock.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090026#include "base/time/time.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090027#include "base/tracking_info.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090028
sky@chromium.org66a00b32014-01-17 09:10:29 +090029// TODO(sky): these includes should not be necessary. Nuke them.
brettw@chromium.org6318b392013-06-14 12:27:49 +090030#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090031#include "base/message_loop/message_pump_win.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090032#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090033#include "base/message_loop/message_pump_io_ios.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090034#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090035#include "base/message_loop/message_pump_libevent.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090036#endif
37
38namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090039
brettw@chromium.org6318b392013-06-14 12:27:49 +090040class HistogramBase;
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
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900211 // (AddRef), clear the pointer, then issue a ReleaseSoon. The reference count
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900212 // 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 = ...
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900217 // foo->AddRef();
218 // Foo* raw_foo = foo.get();
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900219 // foo = NULL;
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900220 // message_loop->ReleaseSoon(raw_foo);
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900221 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900222 // NOTE: This method may be called on any thread. The object will be
223 // released (and thus possibly deleted) on the thread that executes
224 // MessageLoop::Run(). If this is not the same as the thread that calls
225 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
226 // RefCountedThreadSafe<T>!
227 template <class T>
228 void ReleaseSoon(const tracked_objects::Location& from_here,
229 const T* object) {
230 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
231 this, from_here, object);
232 }
233
234 // Deprecated: use RunLoop instead.
235 // Run the message loop.
236 void Run();
237
238 // Deprecated: use RunLoop instead.
239 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
240 // Return as soon as all items that can be run are taken care of.
241 void RunUntilIdle();
242
243 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
244 void Quit() { QuitWhenIdle(); }
245
246 // Deprecated: use RunLoop instead.
247 //
248 // Signals the Run method to return when it becomes idle. It will continue to
249 // process pending messages and future messages as long as they are enqueued.
250 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
251 // Quit method when looping procedures (such as web pages) have been shut
252 // down.
253 //
254 // This method may only be called on the same thread that called Run, and Run
255 // must still be on the call stack.
256 //
257 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
258 // but note that doing so is fairly dangerous if the target thread makes
259 // nested calls to MessageLoop::Run. The problem being that you won't know
260 // which nested run loop you are quitting, so be careful!
261 void QuitWhenIdle();
262
263 // Deprecated: use RunLoop instead.
264 //
265 // This method is a variant of Quit, that does not wait for pending messages
266 // to be processed before returning from Run.
267 void QuitNow();
268
269 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900270 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900271
272 // Deprecated: use RunLoop instead.
273 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
274 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900275 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900276
jeremy@chromium.org4d5a6b22014-06-06 04:36:20 +0900277 // Set the timer slack for this message loop.
278 void SetTimerSlack(TimerSlack timer_slack) {
279 pump_->SetTimerSlack(timer_slack);
280 }
281
brettw@chromium.org6318b392013-06-14 12:27:49 +0900282 // Returns true if this loop is |type|. This allows subclasses (especially
283 // those in tests) to specialize how they are identified.
284 virtual bool IsType(Type type) const;
285
286 // Returns the type passed to the constructor.
287 Type type() const { return type_; }
288
289 // Optional call to connect the thread name with this loop.
290 void set_thread_name(const std::string& thread_name) {
291 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
292 thread_name_ = thread_name;
293 }
294 const std::string& thread_name() const { return thread_name_; }
295
296 // Gets the message loop proxy associated with this message loop.
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900297 //
298 // NOTE: Deprecated; prefer task_runner() and the TaskRunner interfaces
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900299 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900300 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900301 }
302
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900303 // Gets the TaskRunner associated with this message loop.
304 scoped_refptr<SingleThreadTaskRunner> task_runner() {
305 return message_loop_proxy_;
306 }
307
brettw@chromium.org6318b392013-06-14 12:27:49 +0900308 // Enables or disables the recursive task processing. This happens in the case
309 // of recursive message loops. Some unwanted message loop may occurs when
310 // using common controls or printer functions. By default, recursive task
311 // processing is disabled.
312 //
313 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
314 // directly. In general nestable message loops are to be avoided. They are
315 // dangerous and difficult to get right, so please use with extreme caution.
316 //
317 // The specific case where tasks get queued is:
318 // - The thread is running a message loop.
319 // - It receives a task #1 and execute it.
320 // - The task #1 implicitly start a message loop, like a MessageBox in the
321 // unit test. This can also be StartDoc or GetSaveFileName.
322 // - The thread receives a task #2 before or while in this second message
323 // loop.
324 // - With NestableTasksAllowed set to true, the task #2 will run right away.
325 // Otherwise, it will get executed right after task #1 completes at "thread
326 // message loop level".
327 void SetNestableTasksAllowed(bool allowed);
328 bool NestableTasksAllowed() const;
329
330 // Enables nestable tasks on |loop| while in scope.
331 class ScopedNestableTaskAllower {
332 public:
333 explicit ScopedNestableTaskAllower(MessageLoop* loop)
334 : loop_(loop),
335 old_state_(loop_->NestableTasksAllowed()) {
336 loop_->SetNestableTasksAllowed(true);
337 }
338 ~ScopedNestableTaskAllower() {
339 loop_->SetNestableTasksAllowed(old_state_);
340 }
341
342 private:
343 MessageLoop* loop_;
344 bool old_state_;
345 };
346
brettw@chromium.org6318b392013-06-14 12:27:49 +0900347 // Returns true if we are currently running a nested message loop.
348 bool IsNested();
349
350 // A TaskObserver is an object that receives task notifications from the
351 // MessageLoop.
352 //
353 // NOTE: A TaskObserver implementation should be extremely fast!
354 class BASE_EXPORT TaskObserver {
355 public:
356 TaskObserver();
357
358 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900359 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900360
361 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900362 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900363
364 protected:
365 virtual ~TaskObserver();
366 };
367
368 // These functions can only be called on the same thread that |this| is
369 // running on.
370 void AddTaskObserver(TaskObserver* task_observer);
371 void RemoveTaskObserver(TaskObserver* task_observer);
372
ksakamoto@chromium.org518c2112014-07-22 20:32:40 +0900373 // When we go into high resolution timer mode, we will stay in hi-res mode
374 // for at least 1s.
375 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
376
brettw@chromium.org6318b392013-06-14 12:27:49 +0900377#if defined(OS_WIN)
378 void set_os_modal_loop(bool os_modal_loop) {
379 os_modal_loop_ = os_modal_loop;
380 }
381
382 bool os_modal_loop() const {
383 return os_modal_loop_;
384 }
385#endif // OS_WIN
386
387 // Can only be called from the thread that owns the MessageLoop.
388 bool is_running() const;
389
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900390 // Returns true if the message loop has high resolution timers enabled.
391 // Provided for testing.
ksakamoto@chromium.org518c2112014-07-22 20:32:40 +0900392 bool IsHighResolutionTimerEnabledForTesting();
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900393
394 // Returns true if the message loop is "idle". Provided for testing.
395 bool IsIdleForTesting();
396
brettw@chromium.org6318b392013-06-14 12:27:49 +0900397 //----------------------------------------------------------------------------
398 protected:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900399 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900400
401 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900402 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900403 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900404
sky@chromium.orgab452802013-11-08 15:16:53 +0900405 // Configures various members for the two constructors.
406 void Init();
407
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900408 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900409 void RunHandler();
410
brettw@chromium.org6318b392013-06-14 12:27:49 +0900411 // Called to process any delayed non-nestable tasks.
412 bool ProcessNextDelayedNonNestableTask();
413
414 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900415 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900416
417 // Calls RunTask or queues the pending_task on the deferred task list if it
418 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900419 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900420
421 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900422 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900423
brettw@chromium.org6318b392013-06-14 12:27:49 +0900424 // Delete tasks that haven't run yet without running them. Used in the
425 // destructor to make sure all the task's destructors get called. Returns
426 // true if some work was done.
427 bool DeletePendingTasks();
428
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900429 // Creates a process-wide unique ID to represent this task in trace events.
430 // This will be mangled with a Process ID hash to reduce the likelyhood of
431 // colliding with MessageLoop pointers on other processes.
432 uint64 GetTaskTraceID(const PendingTask& task);
433
434 // Loads tasks from the incoming queue to |work_queue_| if the latter is
435 // empty.
436 void ReloadWorkQueue();
437
438 // Wakes up the message pump. Can be called on any thread. The caller is
439 // responsible for synchronizing ScheduleWork() calls.
440 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900441
442 // Start recording histogram info about events and action IF it was enabled
443 // and IF the statistics recorder can accept a registration of our histogram.
444 void StartHistogrammer();
445
446 // Add occurrence of event to our histogram, so that we can see what is being
447 // done in a specific MessageLoop instance (i.e., specific thread).
448 // If message_histogram_ is NULL, this is a no-op.
449 void HistogramEvent(int event);
450
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900451 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900452 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900453 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900454 virtual bool DoIdleWork() OVERRIDE;
455
sky@chromium.orgab452802013-11-08 15:16:53 +0900456 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900457
458 // A list of tasks that need to be processed by this instance. Note that
459 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900460 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900461
462 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900463 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900464
465 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900466 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900467
468 // A queue of non-nestable tasks that we had to defer because when it came
469 // time to execute them we were in a nested message loop. They will execute
470 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900471 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900472
473 ObserverList<DestructionObserver> destruction_observers_;
474
475 // A recursion block that prevents accidentally running additional tasks when
476 // insider a (accidentally induced?) nested message pump.
477 bool nestable_tasks_allowed_;
478
alexeypa@google.combb819d62013-07-23 05:06:56 +0900479#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900480 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
481 // which enter a modal message loop.
482 bool os_modal_loop_;
483#endif
484
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900485 std::string thread_name_;
486 // A profiling histogram showing the counts of various messages and events.
487 HistogramBase* message_histogram_;
488
489 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900490
brettw@chromium.org6318b392013-06-14 12:27:49 +0900491 ObserverList<TaskObserver> task_observers_;
492
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900493 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
494
495 // The message loop proxy associated with this message loop.
496 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900497 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900498
499 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
500 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
501
502 void DeleteSoonInternal(const tracked_objects::Location& from_here,
503 void(*deleter)(const void*),
504 const void* object);
505 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
506 void(*releaser)(const void*),
507 const void* object);
508
509 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
510};
511
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900512#if !defined(OS_NACL)
513
brettw@chromium.org6318b392013-06-14 12:27:49 +0900514//-----------------------------------------------------------------------------
515// MessageLoopForUI extends MessageLoop with methods that are particular to a
516// MessageLoop instantiated with TYPE_UI.
517//
518// This class is typically used like so:
519// MessageLoopForUI::current()->...call some method...
520//
521class BASE_EXPORT MessageLoopForUI : public MessageLoop {
522 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900523 MessageLoopForUI() : MessageLoop(TYPE_UI) {
524 }
525
526 // Returns the MessageLoopForUI of the current thread.
527 static MessageLoopForUI* current() {
528 MessageLoop* loop = MessageLoop::current();
529 DCHECK(loop);
530 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
531 return static_cast<MessageLoopForUI*>(loop);
532 }
533
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900534 static bool IsCurrent() {
535 MessageLoop* loop = MessageLoop::current();
536 return loop && loop->type() == MessageLoop::TYPE_UI;
537 }
538
brettw@chromium.org6318b392013-06-14 12:27:49 +0900539#if defined(OS_IOS)
540 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
541 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
542 // PostTask() to work.
543 void Attach();
544#endif
545
546#if defined(OS_ANDROID)
547 // On Android, the UI message loop is handled by Java side. So Run() should
548 // never be called. Instead use Start(), which will forward all the native UI
549 // events to the Java message loop.
550 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900551#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900552
zhaoze.zhou@partner.samsung.com0137aa82014-07-17 04:12:40 +0900553#if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB))
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900554 // Please see MessagePumpLibevent for definition.
555 bool WatchFileDescriptor(
556 int fd,
557 bool persistent,
558 MessagePumpLibevent::Mode mode,
559 MessagePumpLibevent::FileDescriptorWatcher* controller,
560 MessagePumpLibevent::Watcher* delegate);
561#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900562};
563
564// Do not add any member variables to MessageLoopForUI! This is important b/c
565// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
566// data that you need should be stored on the MessageLoop's pump_ instance.
567COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
568 MessageLoopForUI_should_not_have_extra_member_variables);
569
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900570#endif // !defined(OS_NACL)
571
brettw@chromium.org6318b392013-06-14 12:27:49 +0900572//-----------------------------------------------------------------------------
573// MessageLoopForIO extends MessageLoop with methods that are particular to a
574// MessageLoop instantiated with TYPE_IO.
575//
576// This class is typically used like so:
577// MessageLoopForIO::current()->...call some method...
578//
579class BASE_EXPORT MessageLoopForIO : public MessageLoop {
580 public:
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900581 MessageLoopForIO() : MessageLoop(TYPE_IO) {
582 }
583
584 // Returns the MessageLoopForIO of the current thread.
585 static MessageLoopForIO* current() {
586 MessageLoop* loop = MessageLoop::current();
587 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
588 return static_cast<MessageLoopForIO*>(loop);
589 }
590
591 static bool IsCurrent() {
592 MessageLoop* loop = MessageLoop::current();
593 return loop && loop->type() == MessageLoop::TYPE_IO;
594 }
595
596#if !defined(OS_NACL)
597
brettw@chromium.org6318b392013-06-14 12:27:49 +0900598#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 };
brettw@chromium.org6318b392013-06-14 12:27:49 +0900624#endif
625
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900626 void AddIOObserver(IOObserver* io_observer);
627 void RemoveIOObserver(IOObserver* io_observer);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900628
629#if defined(OS_WIN)
630 // Please see MessagePumpWin for definitions of these methods.
631 void RegisterIOHandler(HANDLE file, IOHandler* handler);
632 bool RegisterJobObject(HANDLE job, IOHandler* handler);
633 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900634#elif defined(OS_POSIX)
635 // Please see MessagePumpIOSForIO/MessagePumpLibevent for definition.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900636 bool WatchFileDescriptor(int fd,
637 bool persistent,
638 Mode mode,
639 FileDescriptorWatcher *controller,
640 Watcher *delegate);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900641#endif // defined(OS_IOS) || defined(OS_POSIX)
642#endif // !defined(OS_NACL)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900643};
644
645// Do not add any member variables to MessageLoopForIO! This is important b/c
646// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
647// data that you need should be stored on the MessageLoop's pump_ instance.
648COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
649 MessageLoopForIO_should_not_have_extra_member_variables);
650
651} // namespace base
652
653#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_