blob: f2f89d0574dc05f70102cc592fa0250860e13031 [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"
brettw@chromium.org6318b392013-06-14 12:27:49 +090019#include "base/message_loop/message_loop_proxy.h"
alexeypa@chromium.org40183232013-07-23 07:24:13 +090020#include "base/message_loop/message_loop_proxy_impl.h"
brettw@chromium.org710ecb92013-06-19 05:27:52 +090021#include "base/message_loop/message_pump.h"
jeremy@chromium.org4d5a6b22014-06-06 04:36:20 +090022#include "base/message_loop/timer_slack.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090023#include "base/observer_list.h"
24#include "base/pending_task.h"
25#include "base/sequenced_task_runner_helpers.h"
26#include "base/synchronization/lock.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090027#include "base/time/time.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090028#include "base/tracking_info.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090029
sky@chromium.org66a00b32014-01-17 09:10:29 +090030// TODO(sky): these includes should not be necessary. Nuke them.
brettw@chromium.org6318b392013-06-14 12:27:49 +090031#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090032#include "base/message_loop/message_pump_win.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090033#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090034#include "base/message_loop/message_pump_io_ios.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090035#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090036#include "base/message_loop/message_pump_libevent.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090037#endif
38
39namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090040
brettw@chromium.org6318b392013-06-14 12:27:49 +090041class HistogramBase;
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,
thestigfa24e5b2015-01-22 16:09:45 +0900109#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.
kinukof25405c2015-05-23 20:38:37 +0900117 explicit MessageLoop(scoped_ptr<MessagePump> pump);
118
dcheng7dc8df52014-10-21 19:54:51 +0900119 ~MessageLoop() override;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900120
121 // Returns the MessageLoop object for the current thread, or null if none.
122 static MessageLoop* current();
123
124 static void EnableHistogrammer(bool enable_histogrammer);
125
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900126 typedef scoped_ptr<MessagePump> (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900127 // Uses the given base::MessagePumpForUIFactory to override the default
128 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
129 // was successfully registered.
130 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
131
sky@chromium.org4f426822013-11-13 01:35:02 +0900132 // Creates the default MessagePump based on |type|. Caller owns return
133 // value.
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900134 static scoped_ptr<MessagePump> CreateMessagePumpForType(Type type);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900135 // A DestructionObserver is notified when the current MessageLoop is being
136 // destroyed. These observers are notified prior to MessageLoop::current()
137 // being changed to return NULL. This gives interested parties the chance to
138 // do final cleanup that depends on the MessageLoop.
139 //
140 // NOTE: Any tasks posted to the MessageLoop during this notification will
141 // not be run. Instead, they will be deleted.
142 //
143 class BASE_EXPORT DestructionObserver {
144 public:
145 virtual void WillDestroyCurrentMessageLoop() = 0;
146
147 protected:
148 virtual ~DestructionObserver();
149 };
150
151 // Add a DestructionObserver, which will start receiving notifications
152 // immediately.
153 void AddDestructionObserver(DestructionObserver* destruction_observer);
154
155 // Remove a DestructionObserver. It is safe to call this method while a
156 // DestructionObserver is receiving a notification callback.
157 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
158
skyostildd4cb912015-03-21 09:56:51 +0900159 // NOTE: Deprecated; prefer task_runner() and the TaskRunner interfaces.
160 // TODO(skyostil): Remove these functions (crbug.com/465354).
161 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900162 // The "PostTask" family of methods call the task's Run method asynchronously
163 // from within a message loop at some point in the future.
164 //
165 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
166 // with normal UI or IO event processing. With the PostDelayedTask variant,
167 // tasks are called after at least approximately 'delay_ms' have elapsed.
168 //
169 // The NonNestable variants work similarly except that they promise never to
170 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
171 // such tasks get deferred until the top-most MessageLoop::Run is executing.
172 //
173 // The MessageLoop takes ownership of the Task, and deletes it after it has
174 // been Run().
175 //
176 // PostTask(from_here, task) is equivalent to
177 // PostDelayedTask(from_here, task, 0).
178 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900179 // NOTE: These methods may be called on any thread. The Task will be invoked
180 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900181 void PostTask(const tracked_objects::Location& from_here,
182 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900183
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900184 void PostDelayedTask(const tracked_objects::Location& from_here,
185 const Closure& task,
186 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900187
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900188 void PostNonNestableTask(const tracked_objects::Location& from_here,
189 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900190
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900191 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
192 const Closure& task,
193 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900194
195 // A variant on PostTask that deletes the given object. This is useful
196 // if the object needs to live until the next run of the MessageLoop (for
197 // example, deleting a RenderProcessHost from within an IPC callback is not
198 // good).
199 //
200 // NOTE: This method may be called on any thread. The object will be deleted
maniscalcocba1be92014-10-03 03:35:33 +0900201 // on the thread that executes MessageLoop::Run().
brettw@chromium.org6318b392013-06-14 12:27:49 +0900202 template <class T>
203 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
204 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
205 this, from_here, object);
206 }
207
208 // A variant on PostTask that releases the given reference counted object
209 // (by calling its Release method). This is useful if the object needs to
210 // live until the next run of the MessageLoop, or if the object needs to be
211 // released on a particular thread.
212 //
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900213 // A common pattern is to manually increment the object's reference count
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900214 // (AddRef), clear the pointer, then issue a ReleaseSoon. The reference count
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900215 // is incremented manually to ensure clearing the pointer does not trigger a
216 // delete and to account for the upcoming decrement (ReleaseSoon). For
217 // example:
218 //
219 // scoped_refptr<Foo> foo = ...
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900220 // foo->AddRef();
221 // Foo* raw_foo = foo.get();
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900222 // foo = NULL;
vkuzkokov@chromium.org49e37bd2014-05-31 03:07:17 +0900223 // message_loop->ReleaseSoon(raw_foo);
maniscalco@chromium.org26ea8ac2014-05-28 07:37:50 +0900224 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900225 // NOTE: This method may be called on any thread. The object will be
226 // released (and thus possibly deleted) on the thread that executes
227 // MessageLoop::Run(). If this is not the same as the thread that calls
maniscalcocba1be92014-10-03 03:35:33 +0900228 // ReleaseSoon(FROM_HERE, ), then T MUST inherit from
brettw@chromium.org6318b392013-06-14 12:27:49 +0900229 // RefCountedThreadSafe<T>!
230 template <class T>
231 void ReleaseSoon(const tracked_objects::Location& from_here,
232 const T* object) {
233 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
234 this, from_here, object);
235 }
236
237 // Deprecated: use RunLoop instead.
238 // Run the message loop.
239 void Run();
240
241 // Deprecated: use RunLoop instead.
242 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
243 // Return as soon as all items that can be run are taken care of.
244 void RunUntilIdle();
245
246 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
247 void Quit() { QuitWhenIdle(); }
248
249 // Deprecated: use RunLoop instead.
250 //
251 // Signals the Run method to return when it becomes idle. It will continue to
252 // process pending messages and future messages as long as they are enqueued.
253 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
254 // Quit method when looping procedures (such as web pages) have been shut
255 // down.
256 //
257 // This method may only be called on the same thread that called Run, and Run
258 // must still be on the call stack.
259 //
260 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
261 // but note that doing so is fairly dangerous if the target thread makes
262 // nested calls to MessageLoop::Run. The problem being that you won't know
263 // which nested run loop you are quitting, so be careful!
264 void QuitWhenIdle();
265
266 // Deprecated: use RunLoop instead.
267 //
268 // This method is a variant of Quit, that does not wait for pending messages
269 // to be processed before returning from Run.
270 void QuitNow();
271
272 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900273 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900274
275 // Deprecated: use RunLoop instead.
276 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
277 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900278 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900279
jeremy@chromium.org4d5a6b22014-06-06 04:36:20 +0900280 // Set the timer slack for this message loop.
281 void SetTimerSlack(TimerSlack timer_slack) {
282 pump_->SetTimerSlack(timer_slack);
283 }
284
brettw@chromium.org6318b392013-06-14 12:27:49 +0900285 // Returns true if this loop is |type|. This allows subclasses (especially
286 // those in tests) to specialize how they are identified.
287 virtual bool IsType(Type type) const;
288
289 // Returns the type passed to the constructor.
290 Type type() const { return type_; }
291
292 // Optional call to connect the thread name with this loop.
293 void set_thread_name(const std::string& thread_name) {
294 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
295 thread_name_ = thread_name;
296 }
297 const std::string& thread_name() const { return thread_name_; }
298
299 // Gets the message loop proxy associated with this message loop.
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900300 //
301 // NOTE: Deprecated; prefer task_runner() and the TaskRunner interfaces
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900302 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900303 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900304 }
305
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900306 // Gets the TaskRunner associated with this message loop.
skyostildd4cb912015-03-21 09:56:51 +0900307 // TODO(skyostil): Change this to return a const reference to a refptr
308 // once the internal type matches what is being returned (crbug.com/465354).
rsleevi@chromium.orgc9ff3782014-07-12 10:10:52 +0900309 scoped_refptr<SingleThreadTaskRunner> task_runner() {
310 return message_loop_proxy_;
311 }
312
brettw@chromium.org6318b392013-06-14 12:27:49 +0900313 // Enables or disables the recursive task processing. This happens in the case
314 // of recursive message loops. Some unwanted message loop may occurs when
315 // using common controls or printer functions. By default, recursive task
316 // processing is disabled.
317 //
318 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
319 // directly. In general nestable message loops are to be avoided. They are
320 // dangerous and difficult to get right, so please use with extreme caution.
321 //
322 // The specific case where tasks get queued is:
323 // - The thread is running a message loop.
324 // - It receives a task #1 and execute it.
325 // - The task #1 implicitly start a message loop, like a MessageBox in the
326 // unit test. This can also be StartDoc or GetSaveFileName.
327 // - The thread receives a task #2 before or while in this second message
328 // loop.
329 // - With NestableTasksAllowed set to true, the task #2 will run right away.
330 // Otherwise, it will get executed right after task #1 completes at "thread
331 // message loop level".
332 void SetNestableTasksAllowed(bool allowed);
333 bool NestableTasksAllowed() const;
334
335 // Enables nestable tasks on |loop| while in scope.
336 class ScopedNestableTaskAllower {
337 public:
338 explicit ScopedNestableTaskAllower(MessageLoop* loop)
339 : loop_(loop),
340 old_state_(loop_->NestableTasksAllowed()) {
341 loop_->SetNestableTasksAllowed(true);
342 }
343 ~ScopedNestableTaskAllower() {
344 loop_->SetNestableTasksAllowed(old_state_);
345 }
346
347 private:
348 MessageLoop* loop_;
349 bool old_state_;
350 };
351
brettw@chromium.org6318b392013-06-14 12:27:49 +0900352 // Returns true if we are currently running a nested message loop.
353 bool IsNested();
354
355 // A TaskObserver is an object that receives task notifications from the
356 // MessageLoop.
357 //
358 // NOTE: A TaskObserver implementation should be extremely fast!
359 class BASE_EXPORT TaskObserver {
360 public:
361 TaskObserver();
362
363 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900364 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900365
366 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900367 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900368
369 protected:
370 virtual ~TaskObserver();
371 };
372
373 // These functions can only be called on the same thread that |this| is
374 // running on.
375 void AddTaskObserver(TaskObserver* task_observer);
376 void RemoveTaskObserver(TaskObserver* task_observer);
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.
cpu410a98e2014-08-29 08:25:37 +0900393 bool HasHighResolutionTasks();
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900394
395 // Returns true if the message loop is "idle". Provided for testing.
396 bool IsIdleForTesting();
397
jamesr8d731062014-09-30 06:12:44 +0900398 // Returns the TaskAnnotator which is used to add debug information to posted
399 // tasks.
400 debug::TaskAnnotator* task_annotator() { return &task_annotator_; }
401
402 // Runs the specified PendingTask.
403 void RunTask(const PendingTask& pending_task);
404
brettw@chromium.org6318b392013-06-14 12:27:49 +0900405 //----------------------------------------------------------------------------
406 protected:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900407 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900408
409 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900410 friend class RunLoop;
kinukof25405c2015-05-23 20:38:37 +0900411 friend class internal::IncomingTaskQueue;
412 friend class ScheduleWorkTest;
413 friend class Thread;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900414
kinukof25405c2015-05-23 20:38:37 +0900415 using MessagePumpFactoryCallback = Callback<scoped_ptr<MessagePump>()>;
416
417 // Creates a MessageLoop without binding to a thread.
418 // If |type| is TYPE_CUSTOM non-null |pump_factory| must be also given
419 // to create a message pump for this message loop. Otherwise a default
420 // message pump for the |type| is created.
421 //
422 // It is valid to call this to create a new message loop on one thread,
423 // and then pass it to the thread where the message loop actually runs.
424 // The message loop's BindToCurrentThread() method must be called on the
425 // thread the message loop runs on, before calling Run().
426 // Before BindToCurrentThread() is called only Post*Task() functions can
427 // be called on the message loop.
428 scoped_ptr<MessageLoop> CreateUnbound(
429 Type type,
430 MessagePumpFactoryCallback pump_factory);
431
432 // Common private constructor. Other constructors delegate the initialization
433 // to this constructor.
434 MessageLoop(Type type, MessagePumpFactoryCallback pump_factory);
435
436 // Configure various members and bind this message loop to the current thread.
437 void BindToCurrentThread();
sky@chromium.orgab452802013-11-08 15:16:53 +0900438
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900439 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900440 void RunHandler();
441
brettw@chromium.org6318b392013-06-14 12:27:49 +0900442 // Called to process any delayed non-nestable tasks.
443 bool ProcessNextDelayedNonNestableTask();
444
brettw@chromium.org6318b392013-06-14 12:27:49 +0900445 // Calls RunTask or queues the pending_task on the deferred task list if it
446 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900447 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900448
449 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900450 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900451
brettw@chromium.org6318b392013-06-14 12:27:49 +0900452 // Delete tasks that haven't run yet without running them. Used in the
453 // destructor to make sure all the task's destructors get called. Returns
454 // true if some work was done.
455 bool DeletePendingTasks();
456
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900457 // Loads tasks from the incoming queue to |work_queue_| if the latter is
458 // empty.
459 void ReloadWorkQueue();
460
kinukof25405c2015-05-23 20:38:37 +0900461 // Wakes up the message pump. Can be called on any thread. The caller is
462 // responsible for synchronizing ScheduleWork() calls.
463 void ScheduleWork();
464
brettw@chromium.org6318b392013-06-14 12:27:49 +0900465 // Start recording histogram info about events and action IF it was enabled
466 // and IF the statistics recorder can accept a registration of our histogram.
467 void StartHistogrammer();
468
469 // Add occurrence of event to our histogram, so that we can see what is being
470 // done in a specific MessageLoop instance (i.e., specific thread).
471 // If message_histogram_ is NULL, this is a no-op.
472 void HistogramEvent(int event);
473
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900474 // MessagePump::Delegate methods:
dcheng7dc8df52014-10-21 19:54:51 +0900475 bool DoWork() override;
476 bool DoDelayedWork(TimeTicks* next_delayed_work_time) override;
477 bool DoIdleWork() override;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900478
sky@chromium.orgab452802013-11-08 15:16:53 +0900479 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900480
481 // A list of tasks that need to be processed by this instance. Note that
482 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900483 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900484
thestigfa24e5b2015-01-22 16:09:45 +0900485#if defined(OS_WIN)
cpu410a98e2014-08-29 08:25:37 +0900486 // How many high resolution tasks are in the pending task queue. This value
487 // increases by N every time we call ReloadWorkQueue() and decreases by 1
488 // every time we call RunTask() if the task needs a high resolution timer.
489 int pending_high_res_tasks_;
490 // Tracks if we have requested high resolution timers. Its only use is to
491 // turn off the high resolution timer upon loop destruction.
492 bool in_high_res_mode_;
thestigfa24e5b2015-01-22 16:09:45 +0900493#endif
cpu410a98e2014-08-29 08:25:37 +0900494
brettw@chromium.org6318b392013-06-14 12:27:49 +0900495 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900496 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900497
498 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900499 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900500
501 // A queue of non-nestable tasks that we had to defer because when it came
502 // time to execute them we were in a nested message loop. They will execute
503 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900504 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900505
506 ObserverList<DestructionObserver> destruction_observers_;
507
508 // A recursion block that prevents accidentally running additional tasks when
509 // insider a (accidentally induced?) nested message pump.
510 bool nestable_tasks_allowed_;
511
alexeypa@google.combb819d62013-07-23 05:06:56 +0900512#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900513 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
514 // which enter a modal message loop.
515 bool os_modal_loop_;
516#endif
517
kinukof25405c2015-05-23 20:38:37 +0900518 // pump_factory_.Run() is called to create a message pump for this loop
519 // if type_ is TYPE_CUSTOM and pump_ is null.
520 MessagePumpFactoryCallback pump_factory_;
521
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900522 std::string thread_name_;
523 // A profiling histogram showing the counts of various messages and events.
524 HistogramBase* message_histogram_;
525
526 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900527
brettw@chromium.org6318b392013-06-14 12:27:49 +0900528 ObserverList<TaskObserver> task_observers_;
529
skyostil@chromium.org2ca1bf32014-08-14 23:26:09 +0900530 debug::TaskAnnotator task_annotator_;
531
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900532 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
533
534 // The message loop proxy associated with this message loop.
535 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900536 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900537
538 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
539 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
540
541 void DeleteSoonInternal(const tracked_objects::Location& from_here,
542 void(*deleter)(const void*),
543 const void* object);
544 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
545 void(*releaser)(const void*),
546 const void* object);
547
548 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
549};
550
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900551#if !defined(OS_NACL)
552
brettw@chromium.org6318b392013-06-14 12:27:49 +0900553//-----------------------------------------------------------------------------
554// MessageLoopForUI extends MessageLoop with methods that are particular to a
555// MessageLoop instantiated with TYPE_UI.
556//
557// This class is typically used like so:
558// MessageLoopForUI::current()->...call some method...
559//
560class BASE_EXPORT MessageLoopForUI : public MessageLoop {
561 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900562 MessageLoopForUI() : MessageLoop(TYPE_UI) {
563 }
564
565 // Returns the MessageLoopForUI of the current thread.
566 static MessageLoopForUI* current() {
567 MessageLoop* loop = MessageLoop::current();
568 DCHECK(loop);
569 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
570 return static_cast<MessageLoopForUI*>(loop);
571 }
572
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900573 static bool IsCurrent() {
574 MessageLoop* loop = MessageLoop::current();
575 return loop && loop->type() == MessageLoop::TYPE_UI;
576 }
577
brettw@chromium.org6318b392013-06-14 12:27:49 +0900578#if defined(OS_IOS)
579 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
580 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
581 // PostTask() to work.
582 void Attach();
583#endif
584
585#if defined(OS_ANDROID)
586 // On Android, the UI message loop is handled by Java side. So Run() should
587 // never be called. Instead use Start(), which will forward all the native UI
588 // events to the Java message loop.
589 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900590#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900591
zhaoze.zhou@partner.samsung.com0137aa82014-07-17 04:12:40 +0900592#if defined(USE_OZONE) || (defined(USE_X11) && !defined(USE_GLIB))
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900593 // Please see MessagePumpLibevent for definition.
594 bool WatchFileDescriptor(
595 int fd,
596 bool persistent,
597 MessagePumpLibevent::Mode mode,
598 MessagePumpLibevent::FileDescriptorWatcher* controller,
599 MessagePumpLibevent::Watcher* delegate);
600#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900601};
602
603// Do not add any member variables to MessageLoopForUI! This is important b/c
604// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
605// data that you need should be stored on the MessageLoop's pump_ instance.
606COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
607 MessageLoopForUI_should_not_have_extra_member_variables);
608
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900609#endif // !defined(OS_NACL)
610
brettw@chromium.org6318b392013-06-14 12:27:49 +0900611//-----------------------------------------------------------------------------
612// MessageLoopForIO extends MessageLoop with methods that are particular to a
613// MessageLoop instantiated with TYPE_IO.
614//
615// This class is typically used like so:
616// MessageLoopForIO::current()->...call some method...
617//
618class BASE_EXPORT MessageLoopForIO : public MessageLoop {
619 public:
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900620 MessageLoopForIO() : MessageLoop(TYPE_IO) {
621 }
622
623 // Returns the MessageLoopForIO of the current thread.
624 static MessageLoopForIO* current() {
625 MessageLoop* loop = MessageLoop::current();
626 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
627 return static_cast<MessageLoopForIO*>(loop);
628 }
629
630 static bool IsCurrent() {
631 MessageLoop* loop = MessageLoop::current();
632 return loop && loop->type() == MessageLoop::TYPE_IO;
633 }
634
hidehiko58e19072014-11-06 08:51:52 +0900635#if !defined(OS_NACL_SFI)
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900636
brettw@chromium.org6318b392013-06-14 12:27:49 +0900637#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900638 typedef MessagePumpForIO::IOHandler IOHandler;
639 typedef MessagePumpForIO::IOContext IOContext;
640 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900641#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900642 typedef MessagePumpIOSForIO::Watcher Watcher;
643 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900644 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900645 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900646
647 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900648 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
649 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
650 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900651 };
652#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900653 typedef MessagePumpLibevent::Watcher Watcher;
654 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900655 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900656 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900657
658 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900659 WATCH_READ = MessagePumpLibevent::WATCH_READ,
660 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
661 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900662 };
brettw@chromium.org6318b392013-06-14 12:27:49 +0900663#endif
664
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900665 void AddIOObserver(IOObserver* io_observer);
666 void RemoveIOObserver(IOObserver* io_observer);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900667
668#if defined(OS_WIN)
669 // Please see MessagePumpWin for definitions of these methods.
670 void RegisterIOHandler(HANDLE file, IOHandler* handler);
671 bool RegisterJobObject(HANDLE job, IOHandler* handler);
672 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900673#elif defined(OS_POSIX)
674 // Please see MessagePumpIOSForIO/MessagePumpLibevent for definition.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900675 bool WatchFileDescriptor(int fd,
676 bool persistent,
677 Mode mode,
thestigfa24e5b2015-01-22 16:09:45 +0900678 FileDescriptorWatcher* controller,
679 Watcher* delegate);
sadrul@chromium.orgb169e222014-04-23 09:55:07 +0900680#endif // defined(OS_IOS) || defined(OS_POSIX)
hidehiko58e19072014-11-06 08:51:52 +0900681#endif // !defined(OS_NACL_SFI)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900682};
683
684// Do not add any member variables to MessageLoopForIO! This is important b/c
685// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
686// data that you need should be stored on the MessageLoop's pump_ instance.
687COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
688 MessageLoopForIO_should_not_have_extra_member_variables);
689
690} // namespace base
691
692#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_