blob: 330bde6d2e8da68dccf0c1af1fcfaf2a8d081138 [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;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090041class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090042class RunLoop;
43class ThreadTaskRunnerHandle;
alexeypa@chromium.org40183232013-07-23 07:24:13 +090044class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090045
46// A MessageLoop is used to process events for a particular thread. There is
47// at most one MessageLoop instance per thread.
48//
49// Events include at a minimum Task instances submitted to PostTask and its
50// variants. Depending on the type of message pump used by the MessageLoop
51// other events such as UI messages may be processed. On Windows APC calls (as
52// time permits) and signals sent to a registered set of HANDLEs may also be
53// processed.
54//
55// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
56// on the thread where the MessageLoop's Run method executes.
57//
58// NOTE: MessageLoop has task reentrancy protection. This means that if a
59// task is being processed, a second task cannot start until the first task is
60// finished. Reentrancy can happen when processing a task, and an inner
61// message pump is created. That inner pump then processes native messages
62// which could implicitly start an inner task. Inner message pumps are created
63// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
64// (DoDragDrop), printer functions (StartDoc) and *many* others.
65//
66// Sample workaround when inner task processing is needed:
67// HRESULT hr;
68// {
69// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
70// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
71// }
72// // Process |hr| (the result returned by DoDragDrop()).
73//
74// Please be SURE your task is reentrant (nestable) and all global variables
75// are stable and accessible before calling SetNestableTasksAllowed(true).
76//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090077class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090078 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +090079 // A MessageLoop has a particular type, which indicates the set of
80 // asynchronous events it may process in addition to tasks and timers.
81 //
82 // TYPE_DEFAULT
83 // This type of ML only supports tasks and timers.
84 //
85 // TYPE_UI
86 // This type of ML also supports native UI events (e.g., Windows messages).
87 // See also MessageLoopForUI.
88 //
89 // TYPE_IO
90 // This type of ML also supports asynchronous IO. See also
91 // MessageLoopForIO.
92 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +090093 // TYPE_JAVA
94 // This type of ML is backed by a Java message handler which is responsible
95 // for running the tasks added to the ML. This is only for use on Android.
96 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
97 // where it does not use the main thread specific pump factory.
98 //
sky@chromium.orgab452802013-11-08 15:16:53 +090099 // TYPE_CUSTOM
100 // MessagePump was supplied to constructor.
101 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900102 enum Type {
103 TYPE_DEFAULT,
104 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900105 TYPE_CUSTOM,
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900106 TYPE_IO,
107#if defined(OS_ANDROID)
108 TYPE_JAVA,
109#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900110 };
111
112 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
113 // is typical to make use of the current thread's MessageLoop instance.
114 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900115 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
116 // be non-NULL.
117 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900118 virtual ~MessageLoop();
119
120 // Returns the MessageLoop object for the current thread, or null if none.
121 static MessageLoop* current();
122
123 static void EnableHistogrammer(bool enable_histogrammer);
124
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900125 typedef scoped_ptr<MessagePump> (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900126 // Uses the given base::MessagePumpForUIFactory to override the default
127 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
128 // was successfully registered.
129 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
130
sky@chromium.org4f426822013-11-13 01:35:02 +0900131 // Creates the default MessagePump based on |type|. Caller owns return
132 // value.
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900133 static scoped_ptr<MessagePump> CreateMessagePumpForType(Type type);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900134 // A DestructionObserver is notified when the current MessageLoop is being
135 // destroyed. These observers are notified prior to MessageLoop::current()
136 // being changed to return NULL. This gives interested parties the chance to
137 // do final cleanup that depends on the MessageLoop.
138 //
139 // NOTE: Any tasks posted to the MessageLoop during this notification will
140 // not be run. Instead, they will be deleted.
141 //
142 class BASE_EXPORT DestructionObserver {
143 public:
144 virtual void WillDestroyCurrentMessageLoop() = 0;
145
146 protected:
147 virtual ~DestructionObserver();
148 };
149
150 // Add a DestructionObserver, which will start receiving notifications
151 // immediately.
152 void AddDestructionObserver(DestructionObserver* destruction_observer);
153
154 // Remove a DestructionObserver. It is safe to call this method while a
155 // DestructionObserver is receiving a notification callback.
156 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
157
158 // The "PostTask" family of methods call the task's Run method asynchronously
159 // from within a message loop at some point in the future.
160 //
161 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
162 // with normal UI or IO event processing. With the PostDelayedTask variant,
163 // tasks are called after at least approximately 'delay_ms' have elapsed.
164 //
165 // The NonNestable variants work similarly except that they promise never to
166 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
167 // such tasks get deferred until the top-most MessageLoop::Run is executing.
168 //
169 // The MessageLoop takes ownership of the Task, and deletes it after it has
170 // been Run().
171 //
172 // PostTask(from_here, task) is equivalent to
173 // PostDelayedTask(from_here, task, 0).
174 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900175 // NOTE: These methods may be called on any thread. The Task will be invoked
176 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900177 void PostTask(const tracked_objects::Location& from_here,
178 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900179
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900180 void PostDelayedTask(const tracked_objects::Location& from_here,
181 const Closure& task,
182 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900183
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900184 void PostNonNestableTask(const tracked_objects::Location& from_here,
185 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900186
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900187 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
188 const Closure& task,
189 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900190
191 // A variant on PostTask that deletes the given object. This is useful
192 // if the object needs to live until the next run of the MessageLoop (for
193 // example, deleting a RenderProcessHost from within an IPC callback is not
194 // good).
195 //
196 // NOTE: This method may be called on any thread. The object will be deleted
197 // on the thread that executes MessageLoop::Run(). If this is not the same
198 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
199 // from RefCountedThreadSafe<T>!
200 template <class T>
201 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
202 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
203 this, from_here, object);
204 }
205
206 // A variant on PostTask that releases the given reference counted object
207 // (by calling its Release method). This is useful if the object needs to
208 // live until the next run of the MessageLoop, or if the object needs to be
209 // released on a particular thread.
210 //
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900211 // A common pattern is to manually increment the object's reference count
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900212 // (AddRef), clear the pointer, then issue a ReleaseSoon. The reference count
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900213 // is incremented manually to ensure clearing the pointer does not trigger a
214 // delete and to account for the upcoming decrement (ReleaseSoon). For
215 // example:
216 //
217 // scoped_refptr<Foo> foo = ...
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900218 // foo->AddRef();
219 // Foo* raw_foo = foo.get();
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900220 // foo = NULL;
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900221 // message_loop->ReleaseSoon(raw_foo);
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900222 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900223 // NOTE: This method may be called on any thread. The object will be
224 // released (and thus possibly deleted) on the thread that executes
225 // MessageLoop::Run(). If this is not the same as the thread that calls
226 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
227 // RefCountedThreadSafe<T>!
228 template <class T>
229 void ReleaseSoon(const tracked_objects::Location& from_here,
230 const T* object) {
231 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
232 this, from_here, object);
233 }
234
235 // Deprecated: use RunLoop instead.
236 // Run the message loop.
237 void Run();
238
239 // Deprecated: use RunLoop instead.
240 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
241 // Return as soon as all items that can be run are taken care of.
242 void RunUntilIdle();
243
244 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
245 void Quit() { QuitWhenIdle(); }
246
247 // Deprecated: use RunLoop instead.
248 //
249 // Signals the Run method to return when it becomes idle. It will continue to
250 // process pending messages and future messages as long as they are enqueued.
251 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
252 // Quit method when looping procedures (such as web pages) have been shut
253 // down.
254 //
255 // This method may only be called on the same thread that called Run, and Run
256 // must still be on the call stack.
257 //
258 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
259 // but note that doing so is fairly dangerous if the target thread makes
260 // nested calls to MessageLoop::Run. The problem being that you won't know
261 // which nested run loop you are quitting, so be careful!
262 void QuitWhenIdle();
263
264 // Deprecated: use RunLoop instead.
265 //
266 // This method is a variant of Quit, that does not wait for pending messages
267 // to be processed before returning from Run.
268 void QuitNow();
269
270 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900271 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900272
273 // Deprecated: use RunLoop instead.
274 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
275 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900276 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900277
jeremy@chromium.org4d5a6b22014-06-06 04:36:20 +0900278 // Set the timer slack for this message loop.
279 void SetTimerSlack(TimerSlack timer_slack) {
280 pump_->SetTimerSlack(timer_slack);
281 }
282
brettw@chromium.org6318b392013-06-14 12:27:49 +0900283 // Returns true if this loop is |type|. This allows subclasses (especially
284 // those in tests) to specialize how they are identified.
285 virtual bool IsType(Type type) const;
286
287 // Returns the type passed to the constructor.
288 Type type() const { return type_; }
289
290 // Optional call to connect the thread name with this loop.
291 void set_thread_name(const std::string& thread_name) {
292 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
293 thread_name_ = thread_name;
294 }
295 const std::string& thread_name() const { return thread_name_; }
296
297 // Gets the message loop proxy associated with this message loop.
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900298 //
299 // NOTE: Deprecated; prefer task_runner() and the TaskRunner interfaces
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900300 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900301 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900302 }
303
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900304 // Gets the TaskRunner associated with this message loop.
305 scoped_refptr<SingleThreadTaskRunner> task_runner() {
306 return message_loop_proxy_;
307 }
308
brettw@chromium.org6318b392013-06-14 12:27:49 +0900309 // Enables or disables the recursive task processing. This happens in the case
310 // of recursive message loops. Some unwanted message loop may occurs when
311 // using common controls or printer functions. By default, recursive task
312 // processing is disabled.
313 //
314 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
315 // directly. In general nestable message loops are to be avoided. They are
316 // dangerous and difficult to get right, so please use with extreme caution.
317 //
318 // The specific case where tasks get queued is:
319 // - The thread is running a message loop.
320 // - It receives a task #1 and execute it.
321 // - The task #1 implicitly start a message loop, like a MessageBox in the
322 // unit test. This can also be StartDoc or GetSaveFileName.
323 // - The thread receives a task #2 before or while in this second message
324 // loop.
325 // - With NestableTasksAllowed set to true, the task #2 will run right away.
326 // Otherwise, it will get executed right after task #1 completes at "thread
327 // message loop level".
328 void SetNestableTasksAllowed(bool allowed);
329 bool NestableTasksAllowed() const;
330
331 // Enables nestable tasks on |loop| while in scope.
332 class ScopedNestableTaskAllower {
333 public:
334 explicit ScopedNestableTaskAllower(MessageLoop* loop)
335 : loop_(loop),
336 old_state_(loop_->NestableTasksAllowed()) {
337 loop_->SetNestableTasksAllowed(true);
338 }
339 ~ScopedNestableTaskAllower() {
340 loop_->SetNestableTasksAllowed(old_state_);
341 }
342
343 private:
344 MessageLoop* loop_;
345 bool old_state_;
346 };
347
brettw@chromium.org6318b392013-06-14 12:27:49 +0900348 // Returns true if we are currently running a nested message loop.
349 bool IsNested();
350
351 // A TaskObserver is an object that receives task notifications from the
352 // MessageLoop.
353 //
354 // NOTE: A TaskObserver implementation should be extremely fast!
355 class BASE_EXPORT TaskObserver {
356 public:
357 TaskObserver();
358
359 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900360 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900361
362 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900363 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900364
365 protected:
366 virtual ~TaskObserver();
367 };
368
369 // These functions can only be called on the same thread that |this| is
370 // running on.
371 void AddTaskObserver(TaskObserver* task_observer);
372 void RemoveTaskObserver(TaskObserver* task_observer);
373
brettw@chromium.org6318b392013-06-14 12:27:49 +0900374 // When we go into high resolution timer mode, we will stay in hi-res mode
375 // for at least 1s.
376 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
377
brettw@chromium.org6318b392013-06-14 12:27:49 +0900378#if defined(OS_WIN)
379 void set_os_modal_loop(bool os_modal_loop) {
380 os_modal_loop_ = os_modal_loop;
381 }
382
383 bool os_modal_loop() const {
384 return os_modal_loop_;
385 }
386#endif // OS_WIN
387
388 // Can only be called from the thread that owns the MessageLoop.
389 bool is_running() const;
390
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900391 // Returns true if the message loop has high resolution timers enabled.
392 // Provided for testing.
393 bool IsHighResolutionTimerEnabledForTesting();
394
395 // Returns true if the message loop is "idle". Provided for testing.
396 bool IsIdleForTesting();
397
brettw@chromium.org6318b392013-06-14 12:27:49 +0900398 //----------------------------------------------------------------------------
399 protected:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900400 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900401
402 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900403 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900404 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900405
sky@chromium.orgab452802013-11-08 15:16:53 +0900406 // Configures various members for the two constructors.
407 void Init();
408
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900409 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900410 void RunHandler();
411
brettw@chromium.org6318b392013-06-14 12:27:49 +0900412 // Called to process any delayed non-nestable tasks.
413 bool ProcessNextDelayedNonNestableTask();
414
415 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900416 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900417
418 // Calls RunTask or queues the pending_task on the deferred task list if it
419 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900420 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900421
422 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900423 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900424
brettw@chromium.org6318b392013-06-14 12:27:49 +0900425 // Delete tasks that haven't run yet without running them. Used in the
426 // destructor to make sure all the task's destructors get called. Returns
427 // true if some work was done.
428 bool DeletePendingTasks();
429
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900430 // Creates a process-wide unique ID to represent this task in trace events.
431 // This will be mangled with a Process ID hash to reduce the likelyhood of
432 // colliding with MessageLoop pointers on other processes.
433 uint64 GetTaskTraceID(const PendingTask& task);
434
435 // Loads tasks from the incoming queue to |work_queue_| if the latter is
436 // empty.
437 void ReloadWorkQueue();
438
439 // Wakes up the message pump. Can be called on any thread. The caller is
440 // responsible for synchronizing ScheduleWork() calls.
441 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900442
443 // Start recording histogram info about events and action IF it was enabled
444 // and IF the statistics recorder can accept a registration of our histogram.
445 void StartHistogrammer();
446
447 // Add occurrence of event to our histogram, so that we can see what is being
448 // done in a specific MessageLoop instance (i.e., specific thread).
449 // If message_histogram_ is NULL, this is a no-op.
450 void HistogramEvent(int event);
451
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900452 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900453 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900454 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900455 virtual bool DoIdleWork() OVERRIDE;
456
sky@chromium.orgab452802013-11-08 15:16:53 +0900457 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900458
459 // A list of tasks that need to be processed by this instance. Note that
460 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900461 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900462
463 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900464 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900465
466 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900467 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900468
469 // A queue of non-nestable tasks that we had to defer because when it came
470 // time to execute them we were in a nested message loop. They will execute
471 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900472 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900473
474 ObserverList<DestructionObserver> destruction_observers_;
475
476 // A recursion block that prevents accidentally running additional tasks when
477 // insider a (accidentally induced?) nested message pump.
478 bool nestable_tasks_allowed_;
479
alexeypa@google.combb819d62013-07-23 05:06:56 +0900480#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900481 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
482 // which enter a modal message loop.
483 bool os_modal_loop_;
484#endif
485
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900486 std::string thread_name_;
487 // A profiling histogram showing the counts of various messages and events.
488 HistogramBase* message_histogram_;
489
490 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900491
brettw@chromium.org6318b392013-06-14 12:27:49 +0900492 ObserverList<TaskObserver> task_observers_;
493
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900494 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
495
496 // The message loop proxy associated with this message loop.
497 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900498 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900499
500 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
501 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
502
503 void DeleteSoonInternal(const tracked_objects::Location& from_here,
504 void(*deleter)(const void*),
505 const void* object);
506 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
507 void(*releaser)(const void*),
508 const void* object);
509
510 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
511};
512
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900513#if !defined(OS_NACL)
514
brettw@chromium.org6318b392013-06-14 12:27:49 +0900515//-----------------------------------------------------------------------------
516// MessageLoopForUI extends MessageLoop with methods that are particular to a
517// MessageLoop instantiated with TYPE_UI.
518//
519// This class is typically used like so:
520// MessageLoopForUI::current()->...call some method...
521//
522class BASE_EXPORT MessageLoopForUI : public MessageLoop {
523 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900524 MessageLoopForUI() : MessageLoop(TYPE_UI) {
525 }
526
527 // Returns the MessageLoopForUI of the current thread.
528 static MessageLoopForUI* current() {
529 MessageLoop* loop = MessageLoop::current();
530 DCHECK(loop);
531 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
532 return static_cast<MessageLoopForUI*>(loop);
533 }
534
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900535 static bool IsCurrent() {
536 MessageLoop* loop = MessageLoop::current();
537 return loop && loop->type() == MessageLoop::TYPE_UI;
538 }
539
brettw@chromium.org6318b392013-06-14 12:27:49 +0900540#if defined(OS_IOS)
541 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
542 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
543 // PostTask() to work.
544 void Attach();
545#endif
546
547#if defined(OS_ANDROID)
548 // On Android, the UI message loop is handled by Java side. So Run() should
549 // never be called. Instead use Start(), which will forward all the native UI
550 // events to the Java message loop.
551 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900552#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900553
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900554#if defined(OS_WIN)
555 typedef MessagePumpObserver Observer;
556
sadrul@chromium.org25e9de22014-04-11 12:02:29 +0900557 // Please see message_pump_win for definitions of these methods.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900558 void AddObserver(Observer* observer);
559 void RemoveObserver(Observer* observer);
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900560#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900561
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900562#if defined(USE_OZONE) || (defined(OS_CHROMEOS) && !defined(USE_GLIB))
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900563 // Please see MessagePumpLibevent for definition.
564 bool WatchFileDescriptor(
565 int fd,
566 bool persistent,
567 MessagePumpLibevent::Mode mode,
568 MessagePumpLibevent::FileDescriptorWatcher* controller,
569 MessagePumpLibevent::Watcher* delegate);
570#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900571};
572
573// Do not add any member variables to MessageLoopForUI! This is important b/c
574// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
575// data that you need should be stored on the MessageLoop's pump_ instance.
576COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
577 MessageLoopForUI_should_not_have_extra_member_variables);
578
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900579#endif // !defined(OS_NACL)
580
brettw@chromium.org6318b392013-06-14 12:27:49 +0900581//-----------------------------------------------------------------------------
582// MessageLoopForIO extends MessageLoop with methods that are particular to a
583// MessageLoop instantiated with TYPE_IO.
584//
585// This class is typically used like so:
586// MessageLoopForIO::current()->...call some method...
587//
588class BASE_EXPORT MessageLoopForIO : public MessageLoop {
589 public:
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900590 MessageLoopForIO() : MessageLoop(TYPE_IO) {
591 }
592
593 // Returns the MessageLoopForIO of the current thread.
594 static MessageLoopForIO* current() {
595 MessageLoop* loop = MessageLoop::current();
596 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
597 return static_cast<MessageLoopForIO*>(loop);
598 }
599
600 static bool IsCurrent() {
601 MessageLoop* loop = MessageLoop::current();
602 return loop && loop->type() == MessageLoop::TYPE_IO;
603 }
604
605#if !defined(OS_NACL)
606
brettw@chromium.org6318b392013-06-14 12:27:49 +0900607#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900608 typedef MessagePumpForIO::IOHandler IOHandler;
609 typedef MessagePumpForIO::IOContext IOContext;
610 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900611#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900612 typedef MessagePumpIOSForIO::Watcher Watcher;
613 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900614 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900615 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900616
617 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900618 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
619 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
620 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900621 };
622#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900623 typedef MessagePumpLibevent::Watcher Watcher;
624 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900625 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900626 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900627
628 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900629 WATCH_READ = MessagePumpLibevent::WATCH_READ,
630 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
631 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900632 };
brettw@chromium.org6318b392013-06-14 12:27:49 +0900633#endif
634
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900635 void AddIOObserver(IOObserver* io_observer);
636 void RemoveIOObserver(IOObserver* io_observer);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900637
638#if defined(OS_WIN)
639 // Please see MessagePumpWin for definitions of these methods.
640 void RegisterIOHandler(HANDLE file, IOHandler* handler);
641 bool RegisterJobObject(HANDLE job, IOHandler* handler);
642 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900643#elif defined(OS_POSIX)
644 // Please see MessagePumpIOSForIO/MessagePumpLibevent for definition.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900645 bool WatchFileDescriptor(int fd,
646 bool persistent,
647 Mode mode,
648 FileDescriptorWatcher *controller,
649 Watcher *delegate);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900650#endif // defined(OS_IOS) || defined(OS_POSIX)
651#endif // !defined(OS_NACL)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900652};
653
654// Do not add any member variables to MessageLoopForIO! This is important b/c
655// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
656// data that you need should be stored on the MessageLoop's pump_ instance.
657COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
658 MessageLoopForIO_should_not_have_extra_member_variables);
659
660} // namespace base
661
662#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_