blob: 66176466cfd1e7131987697076f81dbb50399799 [file] [log] [blame]
brettw@chromium.org6318b392013-06-14 12:27:49 +09001// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
6#define BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_
7
8#include <queue>
9#include <string>
10
11#include "base/base_export.h"
12#include "base/basictypes.h"
13#include "base/callback_forward.h"
14#include "base/location.h"
15#include "base/memory/ref_counted.h"
alexeypa@chromium.org40183232013-07-23 07:24:13 +090016#include "base/memory/scoped_ptr.h"
17#include "base/message_loop/incoming_task_queue.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090018#include "base/message_loop/message_loop_proxy.h"
alexeypa@chromium.org40183232013-07-23 07:24:13 +090019#include "base/message_loop/message_loop_proxy_impl.h"
brettw@chromium.org710ecb92013-06-19 05:27:52 +090020#include "base/message_loop/message_pump.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090021#include "base/observer_list.h"
22#include "base/pending_task.h"
23#include "base/sequenced_task_runner_helpers.h"
24#include "base/synchronization/lock.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090025#include "base/time/time.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090026#include "base/tracking_info.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090027
sky@chromium.org66a00b32014-01-17 09:10:29 +090028// TODO(sky): these includes should not be necessary. Nuke them.
brettw@chromium.org6318b392013-06-14 12:27:49 +090029#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090030#include "base/message_loop/message_pump_win.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090031#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090032#include "base/message_loop/message_pump_io_ios.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090033#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090034#include "base/message_loop/message_pump_libevent.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090035#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
36
sadrul@chromium.orgea5d6f72014-04-22 01:24:24 +090037#if defined(OS_CHROMEOS) && !defined(OS_NACL) && !defined(USE_GLIB)
38#include "base/message_loop/message_pump_libevent.h"
39#elif defined(USE_GLIB) && !defined(OS_NACL)
sadrul@chromium.orgf59198c2014-04-15 12:34:54 +090040#include "base/message_loop/message_pump_glib.h"
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090041#elif !defined(OS_ANDROID_HOST)
sadrul@chromium.orgf59198c2014-04-15 12:34:54 +090042#include "base/message_loop/message_pump_glib.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090043#endif
44
45#endif
46#endif
47
48namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090049
brettw@chromium.org6318b392013-06-14 12:27:49 +090050class HistogramBase;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090051class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090052class RunLoop;
53class ThreadTaskRunnerHandle;
54#if defined(OS_ANDROID)
55class MessagePumpForUI;
sadrul@chromium.orgea5d6f72014-04-22 01:24:24 +090056#elif defined(OS_ANDROID_HOST) || (defined(OS_CHROMEOS) && !defined(USE_GLIB))
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090057typedef MessagePumpLibevent MessagePumpForUI;
brettw@chromium.org6318b392013-06-14 12:27:49 +090058#endif
alexeypa@chromium.org40183232013-07-23 07:24:13 +090059class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090060
61// A MessageLoop is used to process events for a particular thread. There is
62// at most one MessageLoop instance per thread.
63//
64// Events include at a minimum Task instances submitted to PostTask and its
65// variants. Depending on the type of message pump used by the MessageLoop
66// other events such as UI messages may be processed. On Windows APC calls (as
67// time permits) and signals sent to a registered set of HANDLEs may also be
68// processed.
69//
70// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
71// on the thread where the MessageLoop's Run method executes.
72//
73// NOTE: MessageLoop has task reentrancy protection. This means that if a
74// task is being processed, a second task cannot start until the first task is
75// finished. Reentrancy can happen when processing a task, and an inner
76// message pump is created. That inner pump then processes native messages
77// which could implicitly start an inner task. Inner message pumps are created
78// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
79// (DoDragDrop), printer functions (StartDoc) and *many* others.
80//
81// Sample workaround when inner task processing is needed:
82// HRESULT hr;
83// {
84// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
85// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
86// }
87// // Process |hr| (the result returned by DoDragDrop()).
88//
89// Please be SURE your task is reentrant (nestable) and all global variables
90// are stable and accessible before calling SetNestableTasksAllowed(true).
91//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090092class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090093 public:
sadrul@chromium.org25e9de22014-04-11 12:02:29 +090094#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090095 typedef MessagePumpObserver Observer;
brettw@chromium.org6318b392013-06-14 12:27:49 +090096#endif
97
98 // A MessageLoop has a particular type, which indicates the set of
99 // asynchronous events it may process in addition to tasks and timers.
100 //
101 // TYPE_DEFAULT
102 // This type of ML only supports tasks and timers.
103 //
104 // TYPE_UI
105 // This type of ML also supports native UI events (e.g., Windows messages).
106 // See also MessageLoopForUI.
107 //
108 // TYPE_IO
109 // This type of ML also supports asynchronous IO. See also
110 // MessageLoopForIO.
111 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900112 // TYPE_JAVA
113 // This type of ML is backed by a Java message handler which is responsible
114 // for running the tasks added to the ML. This is only for use on Android.
115 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
116 // where it does not use the main thread specific pump factory.
117 //
sky@chromium.orgab452802013-11-08 15:16:53 +0900118 // TYPE_CUSTOM
119 // MessagePump was supplied to constructor.
120 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900121 enum Type {
122 TYPE_DEFAULT,
123 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900124 TYPE_CUSTOM,
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900125 TYPE_IO,
126#if defined(OS_ANDROID)
127 TYPE_JAVA,
128#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900129 };
130
131 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
132 // is typical to make use of the current thread's MessageLoop instance.
133 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900134 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
135 // be non-NULL.
136 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900137 virtual ~MessageLoop();
138
139 // Returns the MessageLoop object for the current thread, or null if none.
140 static MessageLoop* current();
141
142 static void EnableHistogrammer(bool enable_histogrammer);
143
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900144 typedef scoped_ptr<MessagePump> (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900145 // Uses the given base::MessagePumpForUIFactory to override the default
146 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
147 // was successfully registered.
148 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
149
sky@chromium.org4f426822013-11-13 01:35:02 +0900150 // Creates the default MessagePump based on |type|. Caller owns return
151 // value.
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900152 static scoped_ptr<MessagePump> CreateMessagePumpForType(Type type);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900153 // A DestructionObserver is notified when the current MessageLoop is being
154 // destroyed. These observers are notified prior to MessageLoop::current()
155 // being changed to return NULL. This gives interested parties the chance to
156 // do final cleanup that depends on the MessageLoop.
157 //
158 // NOTE: Any tasks posted to the MessageLoop during this notification will
159 // not be run. Instead, they will be deleted.
160 //
161 class BASE_EXPORT DestructionObserver {
162 public:
163 virtual void WillDestroyCurrentMessageLoop() = 0;
164
165 protected:
166 virtual ~DestructionObserver();
167 };
168
169 // Add a DestructionObserver, which will start receiving notifications
170 // immediately.
171 void AddDestructionObserver(DestructionObserver* destruction_observer);
172
173 // Remove a DestructionObserver. It is safe to call this method while a
174 // DestructionObserver is receiving a notification callback.
175 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
176
177 // The "PostTask" family of methods call the task's Run method asynchronously
178 // from within a message loop at some point in the future.
179 //
180 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
181 // with normal UI or IO event processing. With the PostDelayedTask variant,
182 // tasks are called after at least approximately 'delay_ms' have elapsed.
183 //
184 // The NonNestable variants work similarly except that they promise never to
185 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
186 // such tasks get deferred until the top-most MessageLoop::Run is executing.
187 //
188 // The MessageLoop takes ownership of the Task, and deletes it after it has
189 // been Run().
190 //
191 // PostTask(from_here, task) is equivalent to
192 // PostDelayedTask(from_here, task, 0).
193 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900194 // NOTE: These methods may be called on any thread. The Task will be invoked
195 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900196 void PostTask(const tracked_objects::Location& from_here,
197 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900198
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900199 void PostDelayedTask(const tracked_objects::Location& from_here,
200 const Closure& task,
201 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900202
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900203 void PostNonNestableTask(const tracked_objects::Location& from_here,
204 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900205
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900206 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
207 const Closure& task,
208 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900209
210 // A variant on PostTask that deletes the given object. This is useful
211 // if the object needs to live until the next run of the MessageLoop (for
212 // example, deleting a RenderProcessHost from within an IPC callback is not
213 // good).
214 //
215 // NOTE: This method may be called on any thread. The object will be deleted
216 // on the thread that executes MessageLoop::Run(). If this is not the same
217 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
218 // from RefCountedThreadSafe<T>!
219 template <class T>
220 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
221 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
222 this, from_here, object);
223 }
224
225 // A variant on PostTask that releases the given reference counted object
226 // (by calling its Release method). This is useful if the object needs to
227 // live until the next run of the MessageLoop, or if the object needs to be
228 // released on a particular thread.
229 //
230 // NOTE: This method may be called on any thread. The object will be
231 // released (and thus possibly deleted) on the thread that executes
232 // MessageLoop::Run(). If this is not the same as the thread that calls
233 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
234 // RefCountedThreadSafe<T>!
235 template <class T>
236 void ReleaseSoon(const tracked_objects::Location& from_here,
237 const T* object) {
238 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
239 this, from_here, object);
240 }
241
242 // Deprecated: use RunLoop instead.
243 // Run the message loop.
244 void Run();
245
246 // Deprecated: use RunLoop instead.
247 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
248 // Return as soon as all items that can be run are taken care of.
249 void RunUntilIdle();
250
251 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
252 void Quit() { QuitWhenIdle(); }
253
254 // Deprecated: use RunLoop instead.
255 //
256 // Signals the Run method to return when it becomes idle. It will continue to
257 // process pending messages and future messages as long as they are enqueued.
258 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
259 // Quit method when looping procedures (such as web pages) have been shut
260 // down.
261 //
262 // This method may only be called on the same thread that called Run, and Run
263 // must still be on the call stack.
264 //
265 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
266 // but note that doing so is fairly dangerous if the target thread makes
267 // nested calls to MessageLoop::Run. The problem being that you won't know
268 // which nested run loop you are quitting, so be careful!
269 void QuitWhenIdle();
270
271 // Deprecated: use RunLoop instead.
272 //
273 // This method is a variant of Quit, that does not wait for pending messages
274 // to be processed before returning from Run.
275 void QuitNow();
276
277 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900278 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900279
280 // Deprecated: use RunLoop instead.
281 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
282 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900283 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900284
285 // 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.
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
304 // Enables or disables the recursive task processing. This happens in the case
305 // of recursive message loops. Some unwanted message loop may occurs when
306 // using common controls or printer functions. By default, recursive task
307 // processing is disabled.
308 //
309 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
310 // directly. In general nestable message loops are to be avoided. They are
311 // dangerous and difficult to get right, so please use with extreme caution.
312 //
313 // The specific case where tasks get queued is:
314 // - The thread is running a message loop.
315 // - It receives a task #1 and execute it.
316 // - The task #1 implicitly start a message loop, like a MessageBox in the
317 // unit test. This can also be StartDoc or GetSaveFileName.
318 // - The thread receives a task #2 before or while in this second message
319 // loop.
320 // - With NestableTasksAllowed set to true, the task #2 will run right away.
321 // Otherwise, it will get executed right after task #1 completes at "thread
322 // message loop level".
323 void SetNestableTasksAllowed(bool allowed);
324 bool NestableTasksAllowed() const;
325
326 // Enables nestable tasks on |loop| while in scope.
327 class ScopedNestableTaskAllower {
328 public:
329 explicit ScopedNestableTaskAllower(MessageLoop* loop)
330 : loop_(loop),
331 old_state_(loop_->NestableTasksAllowed()) {
332 loop_->SetNestableTasksAllowed(true);
333 }
334 ~ScopedNestableTaskAllower() {
335 loop_->SetNestableTasksAllowed(old_state_);
336 }
337
338 private:
339 MessageLoop* loop_;
340 bool old_state_;
341 };
342
brettw@chromium.org6318b392013-06-14 12:27:49 +0900343 // Returns true if we are currently running a nested message loop.
344 bool IsNested();
345
346 // A TaskObserver is an object that receives task notifications from the
347 // MessageLoop.
348 //
349 // NOTE: A TaskObserver implementation should be extremely fast!
350 class BASE_EXPORT TaskObserver {
351 public:
352 TaskObserver();
353
354 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900355 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900356
357 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900358 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900359
360 protected:
361 virtual ~TaskObserver();
362 };
363
364 // These functions can only be called on the same thread that |this| is
365 // running on.
366 void AddTaskObserver(TaskObserver* task_observer);
367 void RemoveTaskObserver(TaskObserver* task_observer);
368
brettw@chromium.org6318b392013-06-14 12:27:49 +0900369 // When we go into high resolution timer mode, we will stay in hi-res mode
370 // for at least 1s.
371 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
372
brettw@chromium.org6318b392013-06-14 12:27:49 +0900373#if defined(OS_WIN)
374 void set_os_modal_loop(bool os_modal_loop) {
375 os_modal_loop_ = os_modal_loop;
376 }
377
378 bool os_modal_loop() const {
379 return os_modal_loop_;
380 }
381#endif // OS_WIN
382
383 // Can only be called from the thread that owns the MessageLoop.
384 bool is_running() const;
385
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900386 // Returns true if the message loop has high resolution timers enabled.
387 // Provided for testing.
388 bool IsHighResolutionTimerEnabledForTesting();
389
390 // Returns true if the message loop is "idle". Provided for testing.
391 bool IsIdleForTesting();
392
brettw@chromium.org6318b392013-06-14 12:27:49 +0900393 //----------------------------------------------------------------------------
394 protected:
395
396#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900397 MessagePumpWin* pump_win() {
398 return static_cast<MessagePumpWin*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900399 }
400#elif defined(OS_POSIX) && !defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900401 MessagePumpLibevent* pump_libevent() {
402 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900403 }
404#endif
405
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900406 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900407
408 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900409 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900410 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900411
sky@chromium.orgab452802013-11-08 15:16:53 +0900412 // Configures various members for the two constructors.
413 void Init();
414
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900415 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900416 void RunHandler();
417
brettw@chromium.org6318b392013-06-14 12:27:49 +0900418 // Called to process any delayed non-nestable tasks.
419 bool ProcessNextDelayedNonNestableTask();
420
421 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900422 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900423
424 // Calls RunTask or queues the pending_task on the deferred task list if it
425 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900426 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900427
428 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900429 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900430
brettw@chromium.org6318b392013-06-14 12:27:49 +0900431 // Delete tasks that haven't run yet without running them. Used in the
432 // destructor to make sure all the task's destructors get called. Returns
433 // true if some work was done.
434 bool DeletePendingTasks();
435
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900436 // Creates a process-wide unique ID to represent this task in trace events.
437 // This will be mangled with a Process ID hash to reduce the likelyhood of
438 // colliding with MessageLoop pointers on other processes.
439 uint64 GetTaskTraceID(const PendingTask& task);
440
441 // Loads tasks from the incoming queue to |work_queue_| if the latter is
442 // empty.
443 void ReloadWorkQueue();
444
445 // Wakes up the message pump. Can be called on any thread. The caller is
446 // responsible for synchronizing ScheduleWork() calls.
447 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900448
449 // Start recording histogram info about events and action IF it was enabled
450 // and IF the statistics recorder can accept a registration of our histogram.
451 void StartHistogrammer();
452
453 // Add occurrence of event to our histogram, so that we can see what is being
454 // done in a specific MessageLoop instance (i.e., specific thread).
455 // If message_histogram_ is NULL, this is a no-op.
456 void HistogramEvent(int event);
457
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900458 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900459 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900460 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900461 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900462 virtual void GetQueueingInformation(size_t* queue_size,
463 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900464
sky@chromium.orgab452802013-11-08 15:16:53 +0900465 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900466
467 // A list of tasks that need to be processed by this instance. Note that
468 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900469 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900470
471 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900472 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900473
474 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900475 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900476
477 // A queue of non-nestable tasks that we had to defer because when it came
478 // time to execute them we were in a nested message loop. They will execute
479 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900480 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900481
482 ObserverList<DestructionObserver> destruction_observers_;
483
484 // A recursion block that prevents accidentally running additional tasks when
485 // insider a (accidentally induced?) nested message pump.
486 bool nestable_tasks_allowed_;
487
alexeypa@google.combb819d62013-07-23 05:06:56 +0900488#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900489 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
490 // which enter a modal message loop.
491 bool os_modal_loop_;
492#endif
493
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900494 std::string thread_name_;
495 // A profiling histogram showing the counts of various messages and events.
496 HistogramBase* message_histogram_;
497
498 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900499
brettw@chromium.org6318b392013-06-14 12:27:49 +0900500 ObserverList<TaskObserver> task_observers_;
501
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900502 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
503
504 // The message loop proxy associated with this message loop.
505 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900506 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900507
508 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
509 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
510
511 void DeleteSoonInternal(const tracked_objects::Location& from_here,
512 void(*deleter)(const void*),
513 const void* object);
514 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
515 void(*releaser)(const void*),
516 const void* object);
517
518 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
519};
520
521//-----------------------------------------------------------------------------
522// MessageLoopForUI extends MessageLoop with methods that are particular to a
523// MessageLoop instantiated with TYPE_UI.
524//
525// This class is typically used like so:
526// MessageLoopForUI::current()->...call some method...
527//
528class BASE_EXPORT MessageLoopForUI : public MessageLoop {
529 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900530 MessageLoopForUI() : MessageLoop(TYPE_UI) {
531 }
532
533 // Returns the MessageLoopForUI of the current thread.
534 static MessageLoopForUI* current() {
535 MessageLoop* loop = MessageLoop::current();
536 DCHECK(loop);
537 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
538 return static_cast<MessageLoopForUI*>(loop);
539 }
540
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900541 static bool IsCurrent() {
542 MessageLoop* loop = MessageLoop::current();
543 return loop && loop->type() == MessageLoop::TYPE_UI;
544 }
545
brettw@chromium.org6318b392013-06-14 12:27:49 +0900546#if defined(OS_IOS)
547 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
548 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
549 // PostTask() to work.
550 void Attach();
551#endif
552
553#if defined(OS_ANDROID)
554 // On Android, the UI message loop is handled by Java side. So Run() should
555 // never be called. Instead use Start(), which will forward all the native UI
556 // events to the Java message loop.
557 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900558#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900559
sadrul@chromium.org25e9de22014-04-11 12:02:29 +0900560#if !defined(OS_NACL) && defined(OS_WIN)
561 // Please see message_pump_win for definitions of these methods.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900562 void AddObserver(Observer* observer);
563 void RemoveObserver(Observer* observer);
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900564#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900565
sadrul@chromium.orgea5d6f72014-04-22 01:24:24 +0900566#if !defined(OS_NACL) && \
567 (defined(USE_OZONE) || (defined(OS_CHROMEOS) && !defined(USE_GLIB)))
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900568 // Please see MessagePumpLibevent for definition.
569 bool WatchFileDescriptor(
570 int fd,
571 bool persistent,
572 MessagePumpLibevent::Mode mode,
573 MessagePumpLibevent::FileDescriptorWatcher* controller,
574 MessagePumpLibevent::Watcher* delegate);
575#endif
576
brettw@chromium.org6318b392013-06-14 12:27:49 +0900577 protected:
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900578#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900579 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900580 MessagePumpForUI* pump_ui() {
581 return static_cast<MessagePumpForUI*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900582 }
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900583#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900584};
585
586// Do not add any member variables to MessageLoopForUI! This is important b/c
587// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
588// data that you need should be stored on the MessageLoop's pump_ instance.
589COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
590 MessageLoopForUI_should_not_have_extra_member_variables);
591
592//-----------------------------------------------------------------------------
593// MessageLoopForIO extends MessageLoop with methods that are particular to a
594// MessageLoop instantiated with TYPE_IO.
595//
596// This class is typically used like so:
597// MessageLoopForIO::current()->...call some method...
598//
599class BASE_EXPORT MessageLoopForIO : public MessageLoop {
600 public:
601#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900602 typedef MessagePumpForIO::IOHandler IOHandler;
603 typedef MessagePumpForIO::IOContext IOContext;
604 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900605#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900606 typedef MessagePumpIOSForIO::Watcher Watcher;
607 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900608 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900609 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900610
611 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900612 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
613 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
614 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900615 };
616#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900617 typedef MessagePumpLibevent::Watcher Watcher;
618 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900619 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900620 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900621
622 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900623 WATCH_READ = MessagePumpLibevent::WATCH_READ,
624 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
625 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900626 };
627
628#endif
629
630 MessageLoopForIO() : MessageLoop(TYPE_IO) {
631 }
632
633 // Returns the MessageLoopForIO of the current thread.
634 static MessageLoopForIO* current() {
635 MessageLoop* loop = MessageLoop::current();
636 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
637 return static_cast<MessageLoopForIO*>(loop);
638 }
639
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900640 static bool IsCurrent() {
641 MessageLoop* loop = MessageLoop::current();
642 return loop && loop->type() == MessageLoop::TYPE_IO;
643 }
644
brettw@chromium.org6318b392013-06-14 12:27:49 +0900645 void AddIOObserver(IOObserver* io_observer) {
646 pump_io()->AddIOObserver(io_observer);
647 }
648
649 void RemoveIOObserver(IOObserver* io_observer) {
650 pump_io()->RemoveIOObserver(io_observer);
651 }
652
653#if defined(OS_WIN)
654 // Please see MessagePumpWin for definitions of these methods.
655 void RegisterIOHandler(HANDLE file, IOHandler* handler);
656 bool RegisterJobObject(HANDLE job, IOHandler* handler);
657 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
658
659 protected:
660 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900661 MessagePumpForIO* pump_io() {
662 return static_cast<MessagePumpForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900663 }
664
665#elif defined(OS_IOS)
666 // Please see MessagePumpIOSForIO for definition.
667 bool WatchFileDescriptor(int fd,
668 bool persistent,
669 Mode mode,
670 FileDescriptorWatcher *controller,
671 Watcher *delegate);
672
673 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900674 MessagePumpIOSForIO* pump_io() {
675 return static_cast<MessagePumpIOSForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900676 }
677
678#elif defined(OS_POSIX)
679 // Please see MessagePumpLibevent for definition.
680 bool WatchFileDescriptor(int fd,
681 bool persistent,
682 Mode mode,
683 FileDescriptorWatcher* controller,
684 Watcher* delegate);
685
686 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900687 MessagePumpLibevent* pump_io() {
688 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900689 }
690#endif // defined(OS_POSIX)
691};
692
693// Do not add any member variables to MessageLoopForIO! This is important b/c
694// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
695// data that you need should be stored on the MessageLoop's pump_ instance.
696COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
697 MessageLoopForIO_should_not_have_extra_member_variables);
698
699} // namespace base
700
701#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_