blob: 29e0f7e7ba174c56cdae673ba806dae0ab56053a [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
28#if defined(OS_WIN)
29// We need this to declare base::MessagePumpWin::Dispatcher, which we should
30// really just eliminate.
brettw@chromium.org710ecb92013-06-19 05:27:52 +090031#include "base/message_loop/message_pump_win.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090032#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090033#include "base/message_loop/message_pump_io_ios.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090034#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090035#include "base/message_loop/message_pump_libevent.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090036#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
37
38#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_NACL)
sadrul@chromium.org19995722013-09-07 12:21:04 +090039#include "base/message_loop/message_pump_x11.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090040#elif defined(USE_OZONE) && !defined(OS_NACL)
brettw@chromium.org710ecb92013-06-19 05:27:52 +090041#include "base/message_loop/message_pump_ozone.h"
brettw@chromium.org6318b392013-06-14 12:27:49 +090042#else
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090043#define USE_GTK_MESSAGE_PUMP
brettw@chromium.org710ecb92013-06-19 05:27:52 +090044#include "base/message_loop/message_pump_gtk.h"
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +090045#if defined(TOOLKIT_GTK)
46#include "base/message_loop/message_pump_x11.h"
47#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +090048#endif
49
50#endif
51#endif
52
53namespace base {
brettw@chromium.org710ecb92013-06-19 05:27:52 +090054
brettw@chromium.org6318b392013-06-14 12:27:49 +090055class HistogramBase;
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090056class MessagePumpDispatcher;
57class MessagePumpObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +090058class RunLoop;
59class ThreadTaskRunnerHandle;
60#if defined(OS_ANDROID)
61class MessagePumpForUI;
62#endif
alexeypa@chromium.org40183232013-07-23 07:24:13 +090063class WaitableEvent;
brettw@chromium.org6318b392013-06-14 12:27:49 +090064
65// A MessageLoop is used to process events for a particular thread. There is
66// at most one MessageLoop instance per thread.
67//
68// Events include at a minimum Task instances submitted to PostTask and its
69// variants. Depending on the type of message pump used by the MessageLoop
70// other events such as UI messages may be processed. On Windows APC calls (as
71// time permits) and signals sent to a registered set of HANDLEs may also be
72// processed.
73//
74// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
75// on the thread where the MessageLoop's Run method executes.
76//
77// NOTE: MessageLoop has task reentrancy protection. This means that if a
78// task is being processed, a second task cannot start until the first task is
79// finished. Reentrancy can happen when processing a task, and an inner
80// message pump is created. That inner pump then processes native messages
81// which could implicitly start an inner task. Inner message pumps are created
82// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
83// (DoDragDrop), printer functions (StartDoc) and *many* others.
84//
85// Sample workaround when inner task processing is needed:
86// HRESULT hr;
87// {
88// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
89// hr = DoDragDrop(...); // Implicitly runs a modal message loop.
90// }
91// // Process |hr| (the result returned by DoDragDrop()).
92//
93// Please be SURE your task is reentrant (nestable) and all global variables
94// are stable and accessible before calling SetNestableTasksAllowed(true).
95//
brettw@chromium.org710ecb92013-06-19 05:27:52 +090096class BASE_EXPORT MessageLoop : public MessagePump::Delegate {
brettw@chromium.org6318b392013-06-14 12:27:49 +090097 public:
98
sadrul@chromium.orga06ba832013-09-07 10:13:39 +090099#if defined(USE_GTK_MESSAGE_PUMP)
100 typedef MessagePumpGdkObserver Observer;
101#elif !defined(OS_MACOSX) && !defined(OS_ANDROID)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900102 typedef MessagePumpDispatcher Dispatcher;
103 typedef MessagePumpObserver Observer;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900104#endif
105
106 // A MessageLoop has a particular type, which indicates the set of
107 // asynchronous events it may process in addition to tasks and timers.
108 //
109 // TYPE_DEFAULT
110 // This type of ML only supports tasks and timers.
111 //
112 // TYPE_UI
113 // This type of ML also supports native UI events (e.g., Windows messages).
114 // See also MessageLoopForUI.
115 //
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900116 // TYPE_GPU
117 // This type of ML also supports native UI events for use in the GPU
118 // process. On Linux this will always be an X11 ML (as compared with the
119 // sometimes-GTK ML in the browser process).
120 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900121 // TYPE_IO
122 // This type of ML also supports asynchronous IO. See also
123 // MessageLoopForIO.
124 //
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900125 // TYPE_JAVA
126 // This type of ML is backed by a Java message handler which is responsible
127 // for running the tasks added to the ML. This is only for use on Android.
128 // TYPE_JAVA behaves in essence like TYPE_UI, except during construction
129 // where it does not use the main thread specific pump factory.
130 //
sky@chromium.orgab452802013-11-08 15:16:53 +0900131 // TYPE_CUSTOM
132 // MessagePump was supplied to constructor.
133 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900134 enum Type {
135 TYPE_DEFAULT,
136 TYPE_UI,
sky@chromium.orgab452802013-11-08 15:16:53 +0900137 TYPE_CUSTOM,
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900138#if defined(TOOLKIT_GTK)
139 TYPE_GPU,
140#endif
kristianm@chromium.orga78bfa92013-08-08 10:31:52 +0900141 TYPE_IO,
142#if defined(OS_ANDROID)
143 TYPE_JAVA,
144#endif // defined(OS_ANDROID)
brettw@chromium.org6318b392013-06-14 12:27:49 +0900145 };
146
147 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
148 // is typical to make use of the current thread's MessageLoop instance.
149 explicit MessageLoop(Type type = TYPE_DEFAULT);
sky@chromium.orgab452802013-11-08 15:16:53 +0900150 // Creates a TYPE_CUSTOM MessageLoop with the supplied MessagePump, which must
151 // be non-NULL.
152 explicit MessageLoop(scoped_ptr<base::MessagePump> pump);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900153 virtual ~MessageLoop();
154
155 // Returns the MessageLoop object for the current thread, or null if none.
156 static MessageLoop* current();
157
158 static void EnableHistogrammer(bool enable_histogrammer);
159
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900160 typedef MessagePump* (MessagePumpFactory)();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900161 // Uses the given base::MessagePumpForUIFactory to override the default
162 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory
163 // was successfully registered.
164 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory);
165
sky@chromium.org4f426822013-11-13 01:35:02 +0900166 // Creates the default MessagePump based on |type|. Caller owns return
167 // value.
168 // TODO(sky): convert this and InitMessagePumpForUIFactory() to return a
169 // scoped_ptr.
170 static MessagePump* CreateMessagePumpForType(Type type);
171
brettw@chromium.org6318b392013-06-14 12:27:49 +0900172 // A DestructionObserver is notified when the current MessageLoop is being
173 // destroyed. These observers are notified prior to MessageLoop::current()
174 // being changed to return NULL. This gives interested parties the chance to
175 // do final cleanup that depends on the MessageLoop.
176 //
177 // NOTE: Any tasks posted to the MessageLoop during this notification will
178 // not be run. Instead, they will be deleted.
179 //
180 class BASE_EXPORT DestructionObserver {
181 public:
182 virtual void WillDestroyCurrentMessageLoop() = 0;
183
184 protected:
185 virtual ~DestructionObserver();
186 };
187
188 // Add a DestructionObserver, which will start receiving notifications
189 // immediately.
190 void AddDestructionObserver(DestructionObserver* destruction_observer);
191
192 // Remove a DestructionObserver. It is safe to call this method while a
193 // DestructionObserver is receiving a notification callback.
194 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
195
196 // The "PostTask" family of methods call the task's Run method asynchronously
197 // from within a message loop at some point in the future.
198 //
199 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
200 // with normal UI or IO event processing. With the PostDelayedTask variant,
201 // tasks are called after at least approximately 'delay_ms' have elapsed.
202 //
203 // The NonNestable variants work similarly except that they promise never to
204 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
205 // such tasks get deferred until the top-most MessageLoop::Run is executing.
206 //
207 // The MessageLoop takes ownership of the Task, and deletes it after it has
208 // been Run().
209 //
210 // PostTask(from_here, task) is equivalent to
211 // PostDelayedTask(from_here, task, 0).
212 //
brettw@chromium.org6318b392013-06-14 12:27:49 +0900213 // NOTE: These methods may be called on any thread. The Task will be invoked
214 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900215 void PostTask(const tracked_objects::Location& from_here,
216 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900217
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900218 void PostDelayedTask(const tracked_objects::Location& from_here,
219 const Closure& task,
220 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900221
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900222 void PostNonNestableTask(const tracked_objects::Location& from_here,
223 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900224
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900225 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
226 const Closure& task,
227 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900228
229 // A variant on PostTask that deletes the given object. This is useful
230 // if the object needs to live until the next run of the MessageLoop (for
231 // example, deleting a RenderProcessHost from within an IPC callback is not
232 // good).
233 //
234 // NOTE: This method may be called on any thread. The object will be deleted
235 // on the thread that executes MessageLoop::Run(). If this is not the same
236 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
237 // from RefCountedThreadSafe<T>!
238 template <class T>
239 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
240 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
241 this, from_here, object);
242 }
243
244 // A variant on PostTask that releases the given reference counted object
245 // (by calling its Release method). This is useful if the object needs to
246 // live until the next run of the MessageLoop, or if the object needs to be
247 // released on a particular thread.
248 //
249 // NOTE: This method may be called on any thread. The object will be
250 // released (and thus possibly deleted) on the thread that executes
251 // MessageLoop::Run(). If this is not the same as the thread that calls
252 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
253 // RefCountedThreadSafe<T>!
254 template <class T>
255 void ReleaseSoon(const tracked_objects::Location& from_here,
256 const T* object) {
257 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
258 this, from_here, object);
259 }
260
261 // Deprecated: use RunLoop instead.
262 // Run the message loop.
263 void Run();
264
265 // Deprecated: use RunLoop instead.
266 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
267 // Return as soon as all items that can be run are taken care of.
268 void RunUntilIdle();
269
270 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
271 void Quit() { QuitWhenIdle(); }
272
273 // Deprecated: use RunLoop instead.
274 //
275 // Signals the Run method to return when it becomes idle. It will continue to
276 // process pending messages and future messages as long as they are enqueued.
277 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
278 // Quit method when looping procedures (such as web pages) have been shut
279 // down.
280 //
281 // This method may only be called on the same thread that called Run, and Run
282 // must still be on the call stack.
283 //
284 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
285 // but note that doing so is fairly dangerous if the target thread makes
286 // nested calls to MessageLoop::Run. The problem being that you won't know
287 // which nested run loop you are quitting, so be careful!
288 void QuitWhenIdle();
289
290 // Deprecated: use RunLoop instead.
291 //
292 // This method is a variant of Quit, that does not wait for pending messages
293 // to be processed before returning from Run.
294 void QuitNow();
295
296 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900297 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900298
299 // Deprecated: use RunLoop instead.
300 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
301 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900302 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900303
304 // Returns true if this loop is |type|. This allows subclasses (especially
305 // those in tests) to specialize how they are identified.
306 virtual bool IsType(Type type) const;
307
308 // Returns the type passed to the constructor.
309 Type type() const { return type_; }
310
311 // Optional call to connect the thread name with this loop.
312 void set_thread_name(const std::string& thread_name) {
313 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
314 thread_name_ = thread_name;
315 }
316 const std::string& thread_name() const { return thread_name_; }
317
318 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900319 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900320 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900321 }
322
323 // Enables or disables the recursive task processing. This happens in the case
324 // of recursive message loops. Some unwanted message loop may occurs when
325 // using common controls or printer functions. By default, recursive task
326 // processing is disabled.
327 //
328 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
329 // directly. In general nestable message loops are to be avoided. They are
330 // dangerous and difficult to get right, so please use with extreme caution.
331 //
332 // The specific case where tasks get queued is:
333 // - The thread is running a message loop.
334 // - It receives a task #1 and execute it.
335 // - The task #1 implicitly start a message loop, like a MessageBox in the
336 // unit test. This can also be StartDoc or GetSaveFileName.
337 // - The thread receives a task #2 before or while in this second message
338 // loop.
339 // - With NestableTasksAllowed set to true, the task #2 will run right away.
340 // Otherwise, it will get executed right after task #1 completes at "thread
341 // message loop level".
342 void SetNestableTasksAllowed(bool allowed);
343 bool NestableTasksAllowed() const;
344
345 // Enables nestable tasks on |loop| while in scope.
346 class ScopedNestableTaskAllower {
347 public:
348 explicit ScopedNestableTaskAllower(MessageLoop* loop)
349 : loop_(loop),
350 old_state_(loop_->NestableTasksAllowed()) {
351 loop_->SetNestableTasksAllowed(true);
352 }
353 ~ScopedNestableTaskAllower() {
354 loop_->SetNestableTasksAllowed(old_state_);
355 }
356
357 private:
358 MessageLoop* loop_;
359 bool old_state_;
360 };
361
362 // Enables or disables the restoration during an exception of the unhandled
363 // exception filter that was active when Run() was called. This can happen
364 // if some third party code call SetUnhandledExceptionFilter() and never
365 // restores the previous filter.
366 void set_exception_restoration(bool restore) {
367 exception_restoration_ = restore;
368 }
369
370 // Returns true if we are currently running a nested message loop.
371 bool IsNested();
372
373 // A TaskObserver is an object that receives task notifications from the
374 // MessageLoop.
375 //
376 // NOTE: A TaskObserver implementation should be extremely fast!
377 class BASE_EXPORT TaskObserver {
378 public:
379 TaskObserver();
380
381 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900382 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900383
384 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900385 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900386
387 protected:
388 virtual ~TaskObserver();
389 };
390
391 // These functions can only be called on the same thread that |this| is
392 // running on.
393 void AddTaskObserver(TaskObserver* task_observer);
394 void RemoveTaskObserver(TaskObserver* task_observer);
395
brettw@chromium.org6318b392013-06-14 12:27:49 +0900396 // When we go into high resolution timer mode, we will stay in hi-res mode
397 // for at least 1s.
398 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
399
brettw@chromium.org6318b392013-06-14 12:27:49 +0900400#if defined(OS_WIN)
401 void set_os_modal_loop(bool os_modal_loop) {
402 os_modal_loop_ = os_modal_loop;
403 }
404
405 bool os_modal_loop() const {
406 return os_modal_loop_;
407 }
408#endif // OS_WIN
409
410 // Can only be called from the thread that owns the MessageLoop.
411 bool is_running() const;
412
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900413 // Returns true if the message loop has high resolution timers enabled.
414 // Provided for testing.
415 bool IsHighResolutionTimerEnabledForTesting();
416
417 // Returns true if the message loop is "idle". Provided for testing.
418 bool IsIdleForTesting();
419
brettw@chromium.org6318b392013-06-14 12:27:49 +0900420 //----------------------------------------------------------------------------
421 protected:
422
423#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900424 MessagePumpWin* pump_win() {
425 return static_cast<MessagePumpWin*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900426 }
427#elif defined(OS_POSIX) && !defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900428 MessagePumpLibevent* pump_libevent() {
429 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900430 }
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900431#if defined(TOOLKIT_GTK)
432 friend class MessagePumpX11;
433 MessagePumpX11* pump_gpu() {
434 DCHECK_EQ(TYPE_GPU, type());
435 return static_cast<MessagePumpX11*>(pump_.get());
436 }
437#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900438#endif
439
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900440 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900441
442 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900443 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900444 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900445
sky@chromium.orgab452802013-11-08 15:16:53 +0900446 // Configures various members for the two constructors.
447 void Init();
448
brettw@chromium.org6318b392013-06-14 12:27:49 +0900449 // A function to encapsulate all the exception handling capability in the
450 // stacks around the running of a main message loop. It will run the message
451 // loop in a SEH try block or not depending on the set_SEH_restoration()
452 // flag invoking respectively RunInternalInSEHFrame() or RunInternal().
453 void RunHandler();
454
455#if defined(OS_WIN)
456 __declspec(noinline) void RunInternalInSEHFrame();
457#endif
458
459 // A surrounding stack frame around the running of the message loop that
460 // supports all saving and restoring of state, as is needed for any/all (ugly)
461 // recursive calls.
462 void RunInternal();
463
464 // Called to process any delayed non-nestable tasks.
465 bool ProcessNextDelayedNonNestableTask();
466
467 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900468 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900469
470 // Calls RunTask or queues the pending_task on the deferred task list if it
471 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900472 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900473
474 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900475 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900476
brettw@chromium.org6318b392013-06-14 12:27:49 +0900477 // Delete tasks that haven't run yet without running them. Used in the
478 // destructor to make sure all the task's destructors get called. Returns
479 // true if some work was done.
480 bool DeletePendingTasks();
481
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900482 // Creates a process-wide unique ID to represent this task in trace events.
483 // This will be mangled with a Process ID hash to reduce the likelyhood of
484 // colliding with MessageLoop pointers on other processes.
485 uint64 GetTaskTraceID(const PendingTask& task);
486
487 // Loads tasks from the incoming queue to |work_queue_| if the latter is
488 // empty.
489 void ReloadWorkQueue();
490
491 // Wakes up the message pump. Can be called on any thread. The caller is
492 // responsible for synchronizing ScheduleWork() calls.
493 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900494
495 // Start recording histogram info about events and action IF it was enabled
496 // and IF the statistics recorder can accept a registration of our histogram.
497 void StartHistogrammer();
498
499 // Add occurrence of event to our histogram, so that we can see what is being
500 // done in a specific MessageLoop instance (i.e., specific thread).
501 // If message_histogram_ is NULL, this is a no-op.
502 void HistogramEvent(int event);
503
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900504 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900505 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900506 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900507 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900508 virtual void GetQueueingInformation(size_t* queue_size,
509 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900510
sky@chromium.orgab452802013-11-08 15:16:53 +0900511 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900512
513 // A list of tasks that need to be processed by this instance. Note that
514 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900515 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900516
517 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900518 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900519
520 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900521 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900522
523 // A queue of non-nestable tasks that we had to defer because when it came
524 // time to execute them we were in a nested message loop. They will execute
525 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900526 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900527
528 ObserverList<DestructionObserver> destruction_observers_;
529
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900530 bool exception_restoration_;
531
brettw@chromium.org6318b392013-06-14 12:27:49 +0900532 // A recursion block that prevents accidentally running additional tasks when
533 // insider a (accidentally induced?) nested message pump.
534 bool nestable_tasks_allowed_;
535
alexeypa@google.combb819d62013-07-23 05:06:56 +0900536#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900537 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
538 // which enter a modal message loop.
539 bool os_modal_loop_;
540#endif
541
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900542 std::string thread_name_;
543 // A profiling histogram showing the counts of various messages and events.
544 HistogramBase* message_histogram_;
545
546 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900547
brettw@chromium.org6318b392013-06-14 12:27:49 +0900548 ObserverList<TaskObserver> task_observers_;
549
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900550 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
551
552 // The message loop proxy associated with this message loop.
553 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900554 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900555
556 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
557 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
558
559 void DeleteSoonInternal(const tracked_objects::Location& from_here,
560 void(*deleter)(const void*),
561 const void* object);
562 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
563 void(*releaser)(const void*),
564 const void* object);
565
566 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
567};
568
569//-----------------------------------------------------------------------------
570// MessageLoopForUI extends MessageLoop with methods that are particular to a
571// MessageLoop instantiated with TYPE_UI.
572//
573// This class is typically used like so:
574// MessageLoopForUI::current()->...call some method...
575//
576class BASE_EXPORT MessageLoopForUI : public MessageLoop {
577 public:
578#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900579 typedef MessagePumpForUI::MessageFilter MessageFilter;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900580#endif
581
582 MessageLoopForUI() : MessageLoop(TYPE_UI) {
583 }
584
585 // Returns the MessageLoopForUI of the current thread.
586 static MessageLoopForUI* current() {
587 MessageLoop* loop = MessageLoop::current();
588 DCHECK(loop);
589 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
590 return static_cast<MessageLoopForUI*>(loop);
591 }
592
brettw@chromium.org6318b392013-06-14 12:27:49 +0900593#if defined(OS_IOS)
594 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
595 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
596 // PostTask() to work.
597 void Attach();
598#endif
599
600#if defined(OS_ANDROID)
601 // On Android, the UI message loop is handled by Java side. So Run() should
602 // never be called. Instead use Start(), which will forward all the native UI
603 // events to the Java message loop.
604 void Start();
605#elif !defined(OS_MACOSX)
606
607 // Please see message_pump_win/message_pump_glib for definitions of these
608 // methods.
609 void AddObserver(Observer* observer);
610 void RemoveObserver(Observer* observer);
611
612#if defined(OS_WIN)
613 // Plese see MessagePumpForUI for definitions of this method.
614 void SetMessageFilter(scoped_ptr<MessageFilter> message_filter) {
615 pump_ui()->SetMessageFilter(message_filter.Pass());
616 }
617#endif
618
619 protected:
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900620#if defined(USE_X11)
sadrul@chromium.org19995722013-09-07 12:21:04 +0900621 friend class MessagePumpX11;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900622#endif
623#if defined(USE_OZONE) && !defined(OS_NACL)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900624 friend class MessagePumpOzone;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900625#endif
626
627 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900628 MessagePumpForUI* pump_ui() {
629 return static_cast<MessagePumpForUI*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900630 }
631#endif // !defined(OS_MACOSX)
632};
633
634// Do not add any member variables to MessageLoopForUI! This is important b/c
635// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
636// data that you need should be stored on the MessageLoop's pump_ instance.
637COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
638 MessageLoopForUI_should_not_have_extra_member_variables);
639
640//-----------------------------------------------------------------------------
641// MessageLoopForIO extends MessageLoop with methods that are particular to a
642// MessageLoop instantiated with TYPE_IO.
643//
644// This class is typically used like so:
645// MessageLoopForIO::current()->...call some method...
646//
647class BASE_EXPORT MessageLoopForIO : public MessageLoop {
648 public:
649#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900650 typedef MessagePumpForIO::IOHandler IOHandler;
651 typedef MessagePumpForIO::IOContext IOContext;
652 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900653#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900654 typedef MessagePumpIOSForIO::Watcher Watcher;
655 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900656 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900657 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900658
659 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900660 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
661 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
662 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900663 };
664#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900665 typedef MessagePumpLibevent::Watcher Watcher;
666 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900667 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900668 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900669
670 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900671 WATCH_READ = MessagePumpLibevent::WATCH_READ,
672 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
673 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900674 };
675
676#endif
677
678 MessageLoopForIO() : MessageLoop(TYPE_IO) {
679 }
680
681 // Returns the MessageLoopForIO of the current thread.
682 static MessageLoopForIO* current() {
683 MessageLoop* loop = MessageLoop::current();
684 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
685 return static_cast<MessageLoopForIO*>(loop);
686 }
687
688 void AddIOObserver(IOObserver* io_observer) {
689 pump_io()->AddIOObserver(io_observer);
690 }
691
692 void RemoveIOObserver(IOObserver* io_observer) {
693 pump_io()->RemoveIOObserver(io_observer);
694 }
695
696#if defined(OS_WIN)
697 // Please see MessagePumpWin for definitions of these methods.
698 void RegisterIOHandler(HANDLE file, IOHandler* handler);
699 bool RegisterJobObject(HANDLE job, IOHandler* handler);
700 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
701
702 protected:
703 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900704 MessagePumpForIO* pump_io() {
705 return static_cast<MessagePumpForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900706 }
707
708#elif defined(OS_IOS)
709 // Please see MessagePumpIOSForIO for definition.
710 bool WatchFileDescriptor(int fd,
711 bool persistent,
712 Mode mode,
713 FileDescriptorWatcher *controller,
714 Watcher *delegate);
715
716 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900717 MessagePumpIOSForIO* pump_io() {
718 return static_cast<MessagePumpIOSForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900719 }
720
721#elif defined(OS_POSIX)
722 // Please see MessagePumpLibevent for definition.
723 bool WatchFileDescriptor(int fd,
724 bool persistent,
725 Mode mode,
726 FileDescriptorWatcher* controller,
727 Watcher* delegate);
728
729 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900730 MessagePumpLibevent* pump_io() {
731 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900732 }
733#endif // defined(OS_POSIX)
734};
735
736// Do not add any member variables to MessageLoopForIO! This is important b/c
737// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
738// data that you need should be stored on the MessageLoop's pump_ instance.
739COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
740 MessageLoopForIO_should_not_have_extra_member_variables);
741
742} // namespace base
743
744#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_