blob: 07f910525ff71db0191d566e3bb2fabd2af3308a [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.orgf59198c2014-04-15 12:34:54 +090037#if defined(USE_GLIB) && !defined(OS_NACL)
38#include "base/message_loop/message_pump_glib.h"
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090039#elif !defined(OS_ANDROID_HOST)
sadrul@chromium.orgf59198c2014-04-15 12:34:54 +090040#include "base/message_loop/message_pump_glib.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090041#endif
42
43#endif
44#endif
45
46namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090047
brettw@chromium.org6318b392013-06-14 12:27:49 +090048class HistogramBase;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090049class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090050class RunLoop;
51class ThreadTaskRunnerHandle;
52#if defined(OS_ANDROID)
53class MessagePumpForUI;
zhenyu.liang@intel.comd4ad4362014-03-19 14:47:01 +090054#elif defined(OS_ANDROID_HOST)
55typedef MessagePumpLibevent MessagePumpForUI;
brettw@chromium.org6318b392013-06-14 12:27:49 +090056#endif
alexeypa@chromium.org40183232013-07-23 07:24:13 +090057class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090058
59// A MessageLoop is used to process events for a particular thread. There is
60// at most one MessageLoop instance per thread.
61//
62// Events include at a minimum Task instances submitted to PostTask and its
63// variants. Depending on the type of message pump used by the MessageLoop
64// other events such as UI messages may be processed. On Windows APC calls (as
65// time permits) and signals sent to a registered set of HANDLEs may also be
66// processed.
67//
68// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
69// on the thread where the MessageLoop's Run method executes.
70//
71// NOTE: MessageLoop has task reentrancy protection. This means that if a
72// task is being processed, a second task cannot start until the first task is
73// finished. Reentrancy can happen when processing a task, and an inner
74// message pump is created. That inner pump then processes native messages
75// which could implicitly start an inner task. Inner message pumps are created
76// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
77// (DoDragDrop), printer functions (StartDoc) and *many* others.
78//
79// Sample workaround when inner task processing is needed:
80// HRESULT hr;
81// {
82// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
83// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
84// }
85// // Process |hr| (the result returned by DoDragDrop()).
86//
87// Please be SURE your task is reentrant (nestable) and all global variables
88// are stable and accessible before calling SetNestableTasksAllowed(true).
89//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090090class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090091 public:
sadrul@chromium.org25e9de22014-04-11 12:02:29 +090092#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090093 typedef MessagePumpObserver Observer;
brettw@chromium.org6318b392013-06-14 12:27:49 +090094#endif
95
96 // A MessageLoop has a particular type, which indicates the set of
97 // asynchronous events it may process in addition to tasks and timers.
98 //
99 // TYPE_DEFAULT
100 // This type of ML only supports tasks and timers.
101 //
102 // TYPE_UI
103 // This type of ML also supports native UI events (e.g., Windows messages).
104 // See also MessageLoopForUI.
105 //
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900106 // TYPE_GPU
107 // This type of ML also supports native UI events for use in the GPU
108 // process. On Linux this will always be an X11 ML (as compared with the
109 // sometimes-GTK ML in the browser process).
110 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900111 // TYPE_IO
112 // This type of ML also supports asynchronous IO. See also
113 // MessageLoopForIO.
114 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900115 // TYPE_JAVA
116 // This type of ML is backed by a Java message handler which is responsible
117 // for running the tasks added to the ML. This is only for use on Android.
118 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
119 // where it does not use the main thread specific pump factory.
120 //
sky@chromium.orgab452802013-11-08 15:16:53 +0900121 // TYPE_CUSTOM
122 // MessagePump was supplied to constructor.
123 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900124 enum Type {
125 TYPE_DEFAULT,
126 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900127 TYPE_CUSTOM,
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900128#if defined(TOOLKIT_GTK)
129 TYPE_GPU,
130#endif
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900131 TYPE_IO,
132#if defined(OS_ANDROID)
133 TYPE_JAVA,
134#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900135 };
136
137 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
138 // is typical to make use of the current thread's MessageLoop instance.
139 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900140 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
141 // be non-NULL.
142 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900143 virtual ~MessageLoop();
144
145 // Returns the MessageLoop object for the current thread, or null if none.
146 static MessageLoop* current();
147
148 static void EnableHistogrammer(bool enable_histogrammer);
149
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900150 typedef scoped_ptr<MessagePump> (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900151 // Uses the given base::MessagePumpForUIFactory to override the default
152 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
153 // was successfully registered.
154 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
155
sky@chromium.org4f426822013-11-13 01:35:02 +0900156 // Creates the default MessagePump based on |type|. Caller owns return
157 // value.
suyash.s@samsung.comb5f1fc92014-03-08 02:03:54 +0900158 static scoped_ptr<MessagePump> CreateMessagePumpForType(Type type);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900159 // A DestructionObserver is notified when the current MessageLoop is being
160 // destroyed. These observers are notified prior to MessageLoop::current()
161 // being changed to return NULL. This gives interested parties the chance to
162 // do final cleanup that depends on the MessageLoop.
163 //
164 // NOTE: Any tasks posted to the MessageLoop during this notification will
165 // not be run. Instead, they will be deleted.
166 //
167 class BASE_EXPORT DestructionObserver {
168 public:
169 virtual void WillDestroyCurrentMessageLoop() = 0;
170
171 protected:
172 virtual ~DestructionObserver();
173 };
174
175 // Add a DestructionObserver, which will start receiving notifications
176 // immediately.
177 void AddDestructionObserver(DestructionObserver* destruction_observer);
178
179 // Remove a DestructionObserver. It is safe to call this method while a
180 // DestructionObserver is receiving a notification callback.
181 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
182
183 // The "PostTask" family of methods call the task's Run method asynchronously
184 // from within a message loop at some point in the future.
185 //
186 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
187 // with normal UI or IO event processing. With the PostDelayedTask variant,
188 // tasks are called after at least approximately 'delay_ms' have elapsed.
189 //
190 // The NonNestable variants work similarly except that they promise never to
191 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
192 // such tasks get deferred until the top-most MessageLoop::Run is executing.
193 //
194 // The MessageLoop takes ownership of the Task, and deletes it after it has
195 // been Run().
196 //
197 // PostTask(from_here, task) is equivalent to
198 // PostDelayedTask(from_here, task, 0).
199 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900200 // NOTE: These methods may be called on any thread. The Task will be invoked
201 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900202 void PostTask(const tracked_objects::Location& from_here,
203 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900204
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900205 void PostDelayedTask(const tracked_objects::Location& from_here,
206 const Closure& task,
207 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900208
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900209 void PostNonNestableTask(const tracked_objects::Location& from_here,
210 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900211
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900212 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
213 const Closure& task,
214 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900215
216 // A variant on PostTask that deletes the given object. This is useful
217 // if the object needs to live until the next run of the MessageLoop (for
218 // example, deleting a RenderProcessHost from within an IPC callback is not
219 // good).
220 //
221 // NOTE: This method may be called on any thread. The object will be deleted
222 // on the thread that executes MessageLoop::Run(). If this is not the same
223 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
224 // from RefCountedThreadSafe<T>!
225 template <class T>
226 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
227 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
228 this, from_here, object);
229 }
230
231 // A variant on PostTask that releases the given reference counted object
232 // (by calling its Release method). This is useful if the object needs to
233 // live until the next run of the MessageLoop, or if the object needs to be
234 // released on a particular thread.
235 //
236 // NOTE: This method may be called on any thread. The object will be
237 // released (and thus possibly deleted) on the thread that executes
238 // MessageLoop::Run(). If this is not the same as the thread that calls
239 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
240 // RefCountedThreadSafe<T>!
241 template <class T>
242 void ReleaseSoon(const tracked_objects::Location& from_here,
243 const T* object) {
244 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
245 this, from_here, object);
246 }
247
248 // Deprecated: use RunLoop instead.
249 // Run the message loop.
250 void Run();
251
252 // Deprecated: use RunLoop instead.
253 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
254 // Return as soon as all items that can be run are taken care of.
255 void RunUntilIdle();
256
257 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
258 void Quit() { QuitWhenIdle(); }
259
260 // Deprecated: use RunLoop instead.
261 //
262 // Signals the Run method to return when it becomes idle. It will continue to
263 // process pending messages and future messages as long as they are enqueued.
264 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
265 // Quit method when looping procedures (such as web pages) have been shut
266 // down.
267 //
268 // This method may only be called on the same thread that called Run, and Run
269 // must still be on the call stack.
270 //
271 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
272 // but note that doing so is fairly dangerous if the target thread makes
273 // nested calls to MessageLoop::Run. The problem being that you won't know
274 // which nested run loop you are quitting, so be careful!
275 void QuitWhenIdle();
276
277 // Deprecated: use RunLoop instead.
278 //
279 // This method is a variant of Quit, that does not wait for pending messages
280 // to be processed before returning from Run.
281 void QuitNow();
282
283 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900284 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900285
286 // Deprecated: use RunLoop instead.
287 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
288 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900289 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900290
291 // Returns true if this loop is |type|. This allows subclasses (especially
292 // those in tests) to specialize how they are identified.
293 virtual bool IsType(Type type) const;
294
295 // Returns the type passed to the constructor.
296 Type type() const { return type_; }
297
298 // Optional call to connect the thread name with this loop.
299 void set_thread_name(const std::string& thread_name) {
300 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
301 thread_name_ = thread_name;
302 }
303 const std::string& thread_name() const { return thread_name_; }
304
305 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900306 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900307 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900308 }
309
310 // Enables or disables the recursive task processing. This happens in the case
311 // of recursive message loops. Some unwanted message loop may occurs when
312 // using common controls or printer functions. By default, recursive task
313 // processing is disabled.
314 //
315 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
316 // directly. In general nestable message loops are to be avoided. They are
317 // dangerous and difficult to get right, so please use with extreme caution.
318 //
319 // The specific case where tasks get queued is:
320 // - The thread is running a message loop.
321 // - It receives a task #1 and execute it.
322 // - The task #1 implicitly start a message loop, like a MessageBox in the
323 // unit test. This can also be StartDoc or GetSaveFileName.
324 // - The thread receives a task #2 before or while in this second message
325 // loop.
326 // - With NestableTasksAllowed set to true, the task #2 will run right away.
327 // Otherwise, it will get executed right after task #1 completes at "thread
328 // message loop level".
329 void SetNestableTasksAllowed(bool allowed);
330 bool NestableTasksAllowed() const;
331
332 // Enables nestable tasks on |loop| while in scope.
333 class ScopedNestableTaskAllower {
334 public:
335 explicit ScopedNestableTaskAllower(MessageLoop* loop)
336 : loop_(loop),
337 old_state_(loop_->NestableTasksAllowed()) {
338 loop_->SetNestableTasksAllowed(true);
339 }
340 ~ScopedNestableTaskAllower() {
341 loop_->SetNestableTasksAllowed(old_state_);
342 }
343
344 private:
345 MessageLoop* loop_;
346 bool old_state_;
347 };
348
brettw@chromium.org6318b392013-06-14 12:27:49 +0900349 // Returns true if we are currently running a nested message loop.
350 bool IsNested();
351
352 // A TaskObserver is an object that receives task notifications from the
353 // MessageLoop.
354 //
355 // NOTE: A TaskObserver implementation should be extremely fast!
356 class BASE_EXPORT TaskObserver {
357 public:
358 TaskObserver();
359
360 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900361 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900362
363 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900364 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900365
366 protected:
367 virtual ~TaskObserver();
368 };
369
370 // These functions can only be called on the same thread that |this| is
371 // running on.
372 void AddTaskObserver(TaskObserver* task_observer);
373 void RemoveTaskObserver(TaskObserver* task_observer);
374
brettw@chromium.org6318b392013-06-14 12:27:49 +0900375 // When we go into high resolution timer mode, we will stay in hi-res mode
376 // for at least 1s.
377 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
378
brettw@chromium.org6318b392013-06-14 12:27:49 +0900379#if defined(OS_WIN)
380 void set_os_modal_loop(bool os_modal_loop) {
381 os_modal_loop_ = os_modal_loop;
382 }
383
384 bool os_modal_loop() const {
385 return os_modal_loop_;
386 }
387#endif // OS_WIN
388
389 // Can only be called from the thread that owns the MessageLoop.
390 bool is_running() const;
391
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900392 // Returns true if the message loop has high resolution timers enabled.
393 // Provided for testing.
394 bool IsHighResolutionTimerEnabledForTesting();
395
396 // Returns true if the message loop is "idle". Provided for testing.
397 bool IsIdleForTesting();
398
brettw@chromium.org6318b392013-06-14 12:27:49 +0900399 //----------------------------------------------------------------------------
400 protected:
401
402#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900403 MessagePumpWin* pump_win() {
404 return static_cast<MessagePumpWin*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900405 }
406#elif defined(OS_POSIX) && !defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900407 MessagePumpLibevent* pump_libevent() {
408 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900409 }
410#endif
411
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900412 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900413
414 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900415 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900416 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900417
sky@chromium.orgab452802013-11-08 15:16:53 +0900418 // Configures various members for the two constructors.
419 void Init();
420
cpu@chromium.org33353ba2014-01-04 06:25:26 +0900421 // Invokes the actual run loop using the message pump.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900422 void RunHandler();
423
brettw@chromium.org6318b392013-06-14 12:27:49 +0900424 // Called to process any delayed non-nestable tasks.
425 bool ProcessNextDelayedNonNestableTask();
426
427 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900428 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900429
430 // Calls RunTask or queues the pending_task on the deferred task list if it
431 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900432 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900433
434 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900435 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900436
brettw@chromium.org6318b392013-06-14 12:27:49 +0900437 // Delete tasks that haven't run yet without running them. Used in the
438 // destructor to make sure all the task's destructors get called. Returns
439 // true if some work was done.
440 bool DeletePendingTasks();
441
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900442 // Creates a process-wide unique ID to represent this task in trace events.
443 // This will be mangled with a Process ID hash to reduce the likelyhood of
444 // colliding with MessageLoop pointers on other processes.
445 uint64 GetTaskTraceID(const PendingTask& task);
446
447 // Loads tasks from the incoming queue to |work_queue_| if the latter is
448 // empty.
449 void ReloadWorkQueue();
450
451 // Wakes up the message pump. Can be called on any thread. The caller is
452 // responsible for synchronizing ScheduleWork() calls.
453 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900454
455 // 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:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900465 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900466 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900467 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900468 virtual void GetQueueingInformation(size_t* queue_size,
469 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900470
sky@chromium.orgab452802013-11-08 15:16:53 +0900471 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900472
473 // A list of tasks that need to be processed by this instance. Note that
474 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900475 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900476
477 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900478 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900479
480 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900481 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900482
483 // A queue of non-nestable tasks that we had to defer because when it came
484 // time to execute them we were in a nested message loop. They will execute
485 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900486 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900487
488 ObserverList<DestructionObserver> destruction_observers_;
489
490 // A recursion block that prevents accidentally running additional tasks when
491 // insider a (accidentally induced?) nested message pump.
492 bool nestable_tasks_allowed_;
493
alexeypa@google.combb819d62013-07-23 05:06:56 +0900494#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900495 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
496 // which enter a modal message loop.
497 bool os_modal_loop_;
498#endif
499
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900500 std::string thread_name_;
501 // A profiling histogram showing the counts of various messages and events.
502 HistogramBase* message_histogram_;
503
504 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900505
brettw@chromium.org6318b392013-06-14 12:27:49 +0900506 ObserverList<TaskObserver> task_observers_;
507
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900508 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
509
510 // The message loop proxy associated with this message loop.
511 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900512 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900513
514 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
515 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
516
517 void DeleteSoonInternal(const tracked_objects::Location& from_here,
518 void(*deleter)(const void*),
519 const void* object);
520 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
521 void(*releaser)(const void*),
522 const void* object);
523
524 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
525};
526
527//-----------------------------------------------------------------------------
528// MessageLoopForUI extends MessageLoop with methods that are particular to a
529// MessageLoop instantiated with TYPE_UI.
530//
531// This class is typically used like so:
532// MessageLoopForUI::current()->...call some method...
533//
534class BASE_EXPORT MessageLoopForUI : public MessageLoop {
535 public:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900536 MessageLoopForUI() : MessageLoop(TYPE_UI) {
537 }
538
539 // Returns the MessageLoopForUI of the current thread.
540 static MessageLoopForUI* current() {
541 MessageLoop* loop = MessageLoop::current();
542 DCHECK(loop);
543 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
544 return static_cast<MessageLoopForUI*>(loop);
545 }
546
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900547 static bool IsCurrent() {
548 MessageLoop* loop = MessageLoop::current();
549 return loop && loop->type() == MessageLoop::TYPE_UI;
550 }
551
brettw@chromium.org6318b392013-06-14 12:27:49 +0900552#if defined(OS_IOS)
553 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
554 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
555 // PostTask() to work.
556 void Attach();
557#endif
558
559#if defined(OS_ANDROID)
560 // On Android, the UI message loop is handled by Java side. So Run() should
561 // never be called. Instead use Start(), which will forward all the native UI
562 // events to the Java message loop.
563 void Start();
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900564#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900565
sadrul@chromium.org25e9de22014-04-11 12:02:29 +0900566#if !defined(OS_NACL) && defined(OS_WIN)
567 // Please see message_pump_win for definitions of these methods.
brettw@chromium.org6318b392013-06-14 12:27:49 +0900568 void AddObserver(Observer* observer);
569 void RemoveObserver(Observer* observer);
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900570#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900571
spang@chromium.orgcc842882014-04-11 05:03:11 +0900572#if defined(USE_OZONE) && !defined(OS_NACL)
sadrul@chromium.org7aff5f62014-04-11 02:19:38 +0900573 // Please see MessagePumpLibevent for definition.
574 bool WatchFileDescriptor(
575 int fd,
576 bool persistent,
577 MessagePumpLibevent::Mode mode,
578 MessagePumpLibevent::FileDescriptorWatcher* controller,
579 MessagePumpLibevent::Watcher* delegate);
580#endif
581
brettw@chromium.org6318b392013-06-14 12:27:49 +0900582 protected:
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900583#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900584 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900585 MessagePumpForUI* pump_ui() {
586 return static_cast<MessagePumpForUI*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900587 }
sky@chromium.orgf0ef6b62014-01-12 08:12:06 +0900588#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900589};
590
591// Do not add any member variables to MessageLoopForUI! This is important b/c
592// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
593// data that you need should be stored on the MessageLoop's pump_ instance.
594COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
595 MessageLoopForUI_should_not_have_extra_member_variables);
596
597//-----------------------------------------------------------------------------
598// MessageLoopForIO extends MessageLoop with methods that are particular to a
599// MessageLoop instantiated with TYPE_IO.
600//
601// This class is typically used like so:
602// MessageLoopForIO::current()->...call some method...
603//
604class BASE_EXPORT MessageLoopForIO : public MessageLoop {
605 public:
606#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900607 typedef MessagePumpForIO::IOHandler IOHandler;
608 typedef MessagePumpForIO::IOContext IOContext;
609 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900610#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900611 typedef MessagePumpIOSForIO::Watcher Watcher;
612 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900613 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900614 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900615
616 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900617 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
618 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
619 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900620 };
621#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900622 typedef MessagePumpLibevent::Watcher Watcher;
623 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900624 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900625 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900626
627 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900628 WATCH_READ = MessagePumpLibevent::WATCH_READ,
629 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
630 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900631 };
632
633#endif
634
635 MessageLoopForIO() : MessageLoop(TYPE_IO) {
636 }
637
638 // Returns the MessageLoopForIO of the current thread.
639 static MessageLoopForIO* current() {
640 MessageLoop* loop = MessageLoop::current();
641 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
642 return static_cast<MessageLoopForIO*>(loop);
643 }
644
sky@chromium.org8a7aae72014-01-20 17:59:52 +0900645 static bool IsCurrent() {
646 MessageLoop* loop = MessageLoop::current();
647 return loop && loop->type() == MessageLoop::TYPE_IO;
648 }
649
brettw@chromium.org6318b392013-06-14 12:27:49 +0900650 void AddIOObserver(IOObserver* io_observer) {
651 pump_io()->AddIOObserver(io_observer);
652 }
653
654 void RemoveIOObserver(IOObserver* io_observer) {
655 pump_io()->RemoveIOObserver(io_observer);
656 }
657
658#if defined(OS_WIN)
659 // Please see MessagePumpWin for definitions of these methods.
660 void RegisterIOHandler(HANDLE file, IOHandler* handler);
661 bool RegisterJobObject(HANDLE job, IOHandler* handler);
662 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
663
664 protected:
665 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900666 MessagePumpForIO* pump_io() {
667 return static_cast<MessagePumpForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900668 }
669
670#elif defined(OS_IOS)
671 // Please see MessagePumpIOSForIO for definition.
672 bool WatchFileDescriptor(int fd,
673 bool persistent,
674 Mode mode,
675 FileDescriptorWatcher *controller,
676 Watcher *delegate);
677
678 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900679 MessagePumpIOSForIO* pump_io() {
680 return static_cast<MessagePumpIOSForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900681 }
682
683#elif defined(OS_POSIX)
684 // Please see MessagePumpLibevent for definition.
685 bool WatchFileDescriptor(int fd,
686 bool persistent,
687 Mode mode,
688 FileDescriptorWatcher* controller,
689 Watcher* delegate);
690
691 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900692 MessagePumpLibevent* pump_io() {
693 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900694 }
695#endif // defined(OS_POSIX)
696};
697
698// Do not add any member variables to MessageLoopForIO! This is important b/c
699// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
700// data that you need should be stored on the MessageLoop's pump_ instance.
701COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
702 MessageLoopForIO_should_not_have_extra_member_variables);
703
704} // namespace base
705
706#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_