blob: 1b6d407241acf9114495af249ba8aeb5428fae22 [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"
skyostil@chromium.org2ca1bf32014-08-14 23:26:09 +090014#include "base/debug/task_annotator.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090015#include "base/location.h"
16#include "base/memory/ref_counted.h"
alexeypa@chromium.org40183232013-07-23 07:24:13 +090017#include "base/memory/scoped_ptr.h"
18#include "base/message_loop/incoming_task_queue.h"
skyostil9368ac02015-06-20 02:22:54 +090019#include "base/message_loop/message_loop_task_runner.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,
thestigfa24e5b2015-01-22 16:09:45 +0900108#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.
kinukof25405c2015-05-23 20:38:37 +0900116 explicit MessageLoop(scoped_ptr<MessagePump> pump);
117
dcheng7dc8df52014-10-21 19:54:51 +0900118 ~MessageLoop() override;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900119
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
skyostildd4cb912015-03-21 09:56:51 +0900158 // NOTE: Deprecated; prefer task_runner() and the TaskRunner interfaces.
159 // TODO(skyostil): Remove these functions (crbug.com/465354).
160 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900161 // The "PostTask" family of methods call the task's Run method asynchronously
162 // from within a message loop at some point in the future.
163 //
164 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
165 // with normal UI or IO event processing. With the PostDelayedTask variant,
166 // tasks are called after at least approximately 'delay_ms' have elapsed.
167 //
168 // The NonNestable variants work similarly except that they promise never to
169 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
170 // such tasks get deferred until the top-most MessageLoop::Run is executing.
171 //
172 // The MessageLoop takes ownership of the Task, and deletes it after it has
173 // been Run().
174 //
175 // PostTask(from_here, task) is equivalent to
176 // PostDelayedTask(from_here, task, 0).
177 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900178 // NOTE: These methods may be called on any thread. The Task will be invoked
179 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900180 void PostTask(const tracked_objects::Location& from_here,
181 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900182
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900183 void PostDelayedTask(const tracked_objects::Location& from_here,
184 const Closure& task,
185 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900186
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900187 void PostNonNestableTask(const tracked_objects::Location& from_here,
188 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900189
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900190 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
191 const Closure& task,
192 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900193
194 // A variant on PostTask that deletes the given object. This is useful
195 // if the object needs to live until the next run of the MessageLoop (for
196 // example, deleting a RenderProcessHost from within an IPC callback is not
197 // good).
198 //
199 // NOTE: This method may be called on any thread. The object will be deleted
maniscalcocba1be92014-10-03 03:35:33 +0900200 // on the thread that executes MessageLoop::Run().
brettw@chromium.org6318b392013-06-14 12:27:49 +0900201 template <class T>
202 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
203 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
204 this, from_here, object);
205 }
206
207 // A variant on PostTask that releases the given reference counted object
208 // (by calling its Release method). This is useful if the object needs to
209 // live until the next run of the MessageLoop, or if the object needs to be
210 // released on a particular thread.
211 //
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900212 // A common pattern is to manually increment the object's reference count
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900213 // (AddRef), clear the pointer, then issue a ReleaseSoon. The reference count
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900214 // is incremented manually to ensure clearing the pointer does not trigger a
215 // delete and to account for the upcoming decrement (ReleaseSoon). For
216 // example:
217 //
218 // scoped_refptr<Foo> foo = ...
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900219 // foo->AddRef();
220 // Foo* raw_foo = foo.get();
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900221 // foo = NULL;
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900222 // message_loop->ReleaseSoon(raw_foo);
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900223 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900224 // NOTE: This method may be called on any thread. The object will be
225 // released (and thus possibly deleted) on the thread that executes
226 // MessageLoop::Run(). If this is not the same as the thread that calls
maniscalcocba1be92014-10-03 03:35:33 +0900227 // ReleaseSoon(FROM_HERE, ), then T MUST inherit from
brettw@chromium.org6318b392013-06-14 12:27:49 +0900228 // RefCountedThreadSafe<T>!
229 template <class T>
230 void ReleaseSoon(const tracked_objects::Location& from_here,
231 const T* object) {
232 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
233 this, from_here, object);
234 }
235
236 // Deprecated: use RunLoop instead.
237 // Run the message loop.
238 void Run();
239
240 // Deprecated: use RunLoop instead.
241 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
242 // Return as soon as all items that can be run are taken care of.
243 void RunUntilIdle();
244
245 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
246 void Quit() { QuitWhenIdle(); }
247
248 // Deprecated: use RunLoop instead.
249 //
250 // Signals the Run method to return when it becomes idle. It will continue to
251 // process pending messages and future messages as long as they are enqueued.
252 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
253 // Quit method when looping procedures (such as web pages) have been shut
254 // down.
255 //
256 // This method may only be called on the same thread that called Run, and Run
257 // must still be on the call stack.
258 //
259 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
260 // but note that doing so is fairly dangerous if the target thread makes
261 // nested calls to MessageLoop::Run. The problem being that you won't know
262 // which nested run loop you are quitting, so be careful!
263 void QuitWhenIdle();
264
265 // Deprecated: use RunLoop instead.
266 //
267 // This method is a variant of Quit, that does not wait for pending messages
268 // to be processed before returning from Run.
269 void QuitNow();
270
271 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900272 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900273
274 // Deprecated: use RunLoop instead.
275 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
276 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900277 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900278
jeremy@chromium.org4d5a6b22014-06-06 04:36:20 +0900279 // Set the timer slack for this message loop.
280 void SetTimerSlack(TimerSlack timer_slack) {
281 pump_->SetTimerSlack(timer_slack);
282 }
283
brettw@chromium.org6318b392013-06-14 12:27:49 +0900284 // Returns true if this loop is |type|. This allows subclasses (especially
285 // those in tests) to specialize how they are identified.
286 virtual bool IsType(Type type) const;
287
288 // Returns the type passed to the constructor.
289 Type type() const { return type_; }
290
291 // Optional call to connect the thread name with this loop.
292 void set_thread_name(const std::string& thread_name) {
293 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
294 thread_name_ = thread_name;
295 }
296 const std::string& thread_name() const { return thread_name_; }
297
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900298 // Gets the TaskRunner associated with this message loop.
skyostildd4cb912015-03-21 09:56:51 +0900299 // TODO(skyostil): Change this to return a const reference to a refptr
300 // once the internal type matches what is being returned (crbug.com/465354).
skyostil9368ac02015-06-20 02:22:54 +0900301 scoped_refptr<SingleThreadTaskRunner> task_runner() { return task_runner_; }
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900302
brettw@chromium.org6318b392013-06-14 12:27:49 +0900303 // Enables or disables the recursive task processing. This happens in the case
304 // of recursive message loops. Some unwanted message loop may occurs when
305 // using common controls or printer functions. By default, recursive task
306 // processing is disabled.
307 //
308 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
309 // directly. In general nestable message loops are to be avoided. They are
310 // dangerous and difficult to get right, so please use with extreme caution.
311 //
312 // The specific case where tasks get queued is:
313 // - The thread is running a message loop.
314 // - It receives a task #1 and execute it.
315 // - The task #1 implicitly start a message loop, like a MessageBox in the
316 // unit test. This can also be StartDoc or GetSaveFileName.
317 // - The thread receives a task #2 before or while in this second message
318 // loop.
319 // - With NestableTasksAllowed set to true, the task #2 will run right away.
320 // Otherwise, it will get executed right after task #1 completes at "thread
321 // message loop level".
322 void SetNestableTasksAllowed(bool allowed);
323 bool NestableTasksAllowed() const;
324
325 // Enables nestable tasks on |loop| while in scope.
326 class ScopedNestableTaskAllower {
327 public:
328 explicit ScopedNestableTaskAllower(MessageLoop* loop)
329 : loop_(loop),
330 old_state_(loop_->NestableTasksAllowed()) {
331 loop_->SetNestableTasksAllowed(true);
332 }
333 ~ScopedNestableTaskAllower() {
334 loop_->SetNestableTasksAllowed(old_state_);
335 }
336
337 private:
338 MessageLoop* loop_;
339 bool old_state_;
340 };
341
brettw@chromium.org6318b392013-06-14 12:27:49 +0900342 // Returns true if we are currently running a nested message loop.
343 bool IsNested();
344
345 // A TaskObserver is an object that receives task notifications from the
346 // MessageLoop.
347 //
348 // NOTE: A TaskObserver implementation should be extremely fast!
349 class BASE_EXPORT TaskObserver {
350 public:
351 TaskObserver();
352
353 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900354 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900355
356 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900357 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900358
359 protected:
360 virtual ~TaskObserver();
361 };
362
363 // These functions can only be called on the same thread that |this| is
364 // running on.
365 void AddTaskObserver(TaskObserver* task_observer);
366 void RemoveTaskObserver(TaskObserver* task_observer);
367
brettw@chromium.org6318b392013-06-14 12:27:49 +0900368#if defined(OS_WIN)
369 void set_os_modal_loop(bool os_modal_loop) {
370 os_modal_loop_ = os_modal_loop;
371 }
372
373 bool os_modal_loop() const {
374 return os_modal_loop_;
375 }
376#endif // OS_WIN
377
378 // Can only be called from the thread that owns the MessageLoop.
379 bool is_running() const;
380
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900381 // Returns true if the message loop has high resolution timers enabled.
382 // Provided for testing.
cpu410a98e2014-08-29 08:25:37 +0900383 bool HasHighResolutionTasks();
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900384
385 // Returns true if the message loop is "idle". Provided for testing.
386 bool IsIdleForTesting();
387
jamesr8d731062014-09-30 06:12:44 +0900388 // Returns the TaskAnnotator which is used to add debug information to posted
389 // tasks.
390 debug::TaskAnnotator* task_annotator() { return &task_annotator_; }
391
392 // Runs the specified PendingTask.
393 void RunTask(const PendingTask& pending_task);
394
brettw@chromium.org6318b392013-06-14 12:27:49 +0900395 //----------------------------------------------------------------------------
396 protected:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900397 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900398
399 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900400 friend class RunLoop;
kinukof25405c2015-05-23 20:38:37 +0900401 friend class internal::IncomingTaskQueue;
402 friend class ScheduleWorkTest;
403 friend class Thread;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900404
kinukof25405c2015-05-23 20:38:37 +0900405 using MessagePumpFactoryCallback = Callback<scoped_ptr<MessagePump>()>;
406
407 // Creates a MessageLoop without binding to a thread.
408 // If |type| is TYPE_CUSTOM non-null |pump_factory| must be also given
409 // to create a message pump for this message loop. Otherwise a default
410 // message pump for the |type| is created.
411 //
412 // It is valid to call this to create a new message loop on one thread,
413 // and then pass it to the thread where the message loop actually runs.
414 // The message loop's BindToCurrentThread() method must be called on the
415 // thread the message loop runs on, before calling Run().
416 // Before BindToCurrentThread() is called only Post*Task() functions can
417 // be called on the message loop.
kinuko9adf8ab2015-06-30 10:31:54 +0900418 static scoped_ptr<MessageLoop> CreateUnbound(
kinukof25405c2015-05-23 20:38:37 +0900419 Type type,
420 MessagePumpFactoryCallback pump_factory);
421
422 // Common private constructor. Other constructors delegate the initialization
423 // to this constructor.
424 MessageLoop(Type type, MessagePumpFactoryCallback pump_factory);
425
426 // Configure various members and bind this message loop to the current thread.
427 void BindToCurrentThread();
sky@chromium.orgab452802013-11-08 15:16:53 +0900428
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900429 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900430 void RunHandler();
431
brettw@chromium.org6318b392013-06-14 12:27:49 +0900432 // Called to process any delayed non-nestable tasks.
433 bool ProcessNextDelayedNonNestableTask();
434
brettw@chromium.org6318b392013-06-14 12:27:49 +0900435 // Calls RunTask or queues the pending_task on the deferred task list if it
436 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900437 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900438
439 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900440 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900441
brettw@chromium.org6318b392013-06-14 12:27:49 +0900442 // Delete tasks that haven't run yet without running them. Used in the
443 // destructor to make sure all the task's destructors get called. Returns
444 // true if some work was done.
445 bool DeletePendingTasks();
446
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900447 // Loads tasks from the incoming queue to |work_queue_| if the latter is
448 // empty.
449 void ReloadWorkQueue();
450
kinukof25405c2015-05-23 20:38:37 +0900451 // Wakes up the message pump. Can be called on any thread. The caller is
452 // responsible for synchronizing ScheduleWork() calls.
453 void ScheduleWork();
454
brettw@chromium.org6318b392013-06-14 12:27:49 +0900455 // Start recording histogram info about events and action IF it was enabled
456 // and IF the statistics recorder can accept a registration of our histogram.
457 void StartHistogrammer();
458
459 // Add occurrence of event to our histogram, so that we can see what is being
460 // done in a specific MessageLoop instance (i.e., specific thread).
461 // If message_histogram_ is NULL, this is a no-op.
462 void HistogramEvent(int event);
463
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900464 // MessagePump::Delegate methods:
dcheng7dc8df52014-10-21 19:54:51 +0900465 bool DoWork() override;
466 bool DoDelayedWork(TimeTicks* next_delayed_work_time) override;
467 bool DoIdleWork() override;
ananta8bd245c2015-06-22 15:10:42 +0900468 TimeTicks GetNewlyAddedTaskDelay() override;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900469
sky@chromium.orgab452802013-11-08 15:16:53 +0900470 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900471
472 // A list of tasks that need to be processed by this instance. Note that
473 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900474 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900475
thestigfa24e5b2015-01-22 16:09:45 +0900476#if defined(OS_WIN)
cpu410a98e2014-08-29 08:25:37 +0900477 // How many high resolution tasks are in the pending task queue. This value
478 // increases by N every time we call ReloadWorkQueue() and decreases by 1
479 // every time we call RunTask() if the task needs a high resolution timer.
480 int pending_high_res_tasks_;
481 // Tracks if we have requested high resolution timers. Its only use is to
482 // turn off the high resolution timer upon loop destruction.
483 bool in_high_res_mode_;
thestigfa24e5b2015-01-22 16:09:45 +0900484#endif
cpu410a98e2014-08-29 08:25:37 +0900485
brettw@chromium.org6318b392013-06-14 12:27:49 +0900486 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900487 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900488
489 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900490 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900491
492 // A queue of non-nestable tasks that we had to defer because when it came
493 // time to execute them we were in a nested message loop. They will execute
494 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900495 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900496
497 ObserverList<DestructionObserver> destruction_observers_;
498
499 // A recursion block that prevents accidentally running additional tasks when
500 // insider a (accidentally induced?) nested message pump.
501 bool nestable_tasks_allowed_;
502
alexeypa@google.combb819d62013-07-23 05:06:56 +0900503#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900504 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
505 // which enter a modal message loop.
506 bool os_modal_loop_;
507#endif
508
kinukof25405c2015-05-23 20:38:37 +0900509 // pump_factory_.Run() is called to create a message pump for this loop
510 // if type_ is TYPE_CUSTOM and pump_ is null.
511 MessagePumpFactoryCallback pump_factory_;
512
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900513 std::string thread_name_;
514 // A profiling histogram showing the counts of various messages and events.
515 HistogramBase* message_histogram_;
516
517 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900518
brettw@chromium.org6318b392013-06-14 12:27:49 +0900519 ObserverList<TaskObserver> task_observers_;
520
skyostil@chromium.org2ca1bf32014-08-14 23:26:09 +0900521 debug::TaskAnnotator task_annotator_;
522
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900523 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
524
skyostil9368ac02015-06-20 02:22:54 +0900525 // The task runner associated with this message loop.
526 scoped_refptr<internal::MessageLoopTaskRunner> task_runner_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900527 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900528
529 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
530 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
531
532 void DeleteSoonInternal(const tracked_objects::Location& from_here,
533 void(*deleter)(const void*),
534 const void* object);
535 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
536 void(*releaser)(const void*),
537 const void* object);
538
539 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
540};
541
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900542#if !defined(OS_NACL)
543
brettw@chromium.org6318b392013-06-14 12:27:49 +0900544//-----------------------------------------------------------------------------
545// MessageLoopForUI extends MessageLoop with methods that are particular to a
546// MessageLoop instantiated with TYPE_UI.
547//
548// This class is typically used like so:
549// MessageLoopForUI::current()->...call some method...
550//
551class BASE_EXPORT MessageLoopForUI : public MessageLoop {
552 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900553 MessageLoopForUI() : MessageLoop(TYPE_UI) {
554 }
555
556 // Returns the MessageLoopForUI of the current thread.
557 static MessageLoopForUI* current() {
558 MessageLoop* loop = MessageLoop::current();
559 DCHECK(loop);
560 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
561 return static_cast<MessageLoopForUI*>(loop);
562 }
563
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900564 static bool IsCurrent() {
565 MessageLoop* loop = MessageLoop::current();
566 return loop && loop->type() == MessageLoop::TYPE_UI;
567 }
568
brettw@chromium.org6318b392013-06-14 12:27:49 +0900569#if defined(OS_IOS)
570 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
571 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
572 // PostTask() to work.
573 void Attach();
574#endif
575
576#if defined(OS_ANDROID)
577 // On Android, the UI message loop is handled by Java side. So Run() should
578 // never be called. Instead use Start(), which will forward all the native UI
579 // events to the Java message loop.
580 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900581#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900582
zhaoze.zhou@partner.samsung.com0137aa82014-07-17 04:12:40 +0900583#if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB))
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900584 // Please see MessagePumpLibevent for definition.
585 bool WatchFileDescriptor(
586 int fd,
587 bool persistent,
588 MessagePumpLibevent::Mode mode,
589 MessagePumpLibevent::FileDescriptorWatcher* controller,
590 MessagePumpLibevent::Watcher* delegate);
591#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900592};
593
594// Do not add any member variables to MessageLoopForUI! This is important b/c
595// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
596// data that you need should be stored on the MessageLoop's pump_ instance.
597COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
598 MessageLoopForUI_should_not_have_extra_member_variables);
599
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900600#endif // !defined(OS_NACL)
601
brettw@chromium.org6318b392013-06-14 12:27:49 +0900602//-----------------------------------------------------------------------------
603// MessageLoopForIO extends MessageLoop with methods that are particular to a
604// MessageLoop instantiated with TYPE_IO.
605//
606// This class is typically used like so:
607// MessageLoopForIO::current()->...call some method...
608//
609class BASE_EXPORT MessageLoopForIO : public MessageLoop {
610 public:
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900611 MessageLoopForIO() : MessageLoop(TYPE_IO) {
612 }
613
614 // Returns the MessageLoopForIO of the current thread.
615 static MessageLoopForIO* current() {
616 MessageLoop* loop = MessageLoop::current();
617 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
618 return static_cast<MessageLoopForIO*>(loop);
619 }
620
621 static bool IsCurrent() {
622 MessageLoop* loop = MessageLoop::current();
623 return loop && loop->type() == MessageLoop::TYPE_IO;
624 }
625
hidehiko58e19072014-11-06 08:51:52 +0900626#if !defined(OS_NACL_SFI)
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900627
brettw@chromium.org6318b392013-06-14 12:27:49 +0900628#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900629 typedef MessagePumpForIO::IOHandler IOHandler;
630 typedef MessagePumpForIO::IOContext IOContext;
631 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900632#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900633 typedef MessagePumpIOSForIO::Watcher Watcher;
634 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900635 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900636 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900637
638 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900639 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
640 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
641 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900642 };
643#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900644 typedef MessagePumpLibevent::Watcher Watcher;
645 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900646 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900647 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900648
649 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900650 WATCH_READ = MessagePumpLibevent::WATCH_READ,
651 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
652 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900653 };
brettw@chromium.org6318b392013-06-14 12:27:49 +0900654#endif
655
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900656 void AddIOObserver(IOObserver* io_observer);
657 void RemoveIOObserver(IOObserver* io_observer);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900658
659#if defined(OS_WIN)
660 // Please see MessagePumpWin for definitions of these methods.
661 void RegisterIOHandler(HANDLE file, IOHandler* handler);
662 bool RegisterJobObject(HANDLE job, IOHandler* handler);
663 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900664#elif defined(OS_POSIX)
665 // Please see MessagePumpIOSForIO/MessagePumpLibevent for definition.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900666 bool WatchFileDescriptor(int fd,
667 bool persistent,
668 Mode mode,
thestigfa24e5b2015-01-22 16:09:45 +0900669 FileDescriptorWatcher* controller,
670 Watcher* delegate);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900671#endif // defined(OS_IOS) || defined(OS_POSIX)
hidehiko58e19072014-11-06 08:51:52 +0900672#endif // !defined(OS_NACL_SFI)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900673};
674
675// Do not add any member variables to MessageLoopForIO! This is important b/c
676// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
677// data that you need should be stored on the MessageLoop's pump_ instance.
678COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
679 MessageLoopForIO_should_not_have_extra_member_variables);
680
681} // namespace base
682
683#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_