blob: 84e1449f6cf03922e00a0c0fff16428e877dfeaa [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
166 // A DestructionObserver is notified when the current MessageLoop is being
167 // destroyed. These observers are notified prior to MessageLoop::current()
168 // being changed to return NULL. This gives interested parties the chance to
169 // do final cleanup that depends on the MessageLoop.
170 //
171 // NOTE: Any tasks posted to the MessageLoop during this notification will
172 // not be run. Instead, they will be deleted.
173 //
174 class BASE_EXPORT DestructionObserver {
175 public:
176 virtual void WillDestroyCurrentMessageLoop() = 0;
177
178 protected:
179 virtual ~DestructionObserver();
180 };
181
182 // Add a DestructionObserver, which will start receiving notifications
183 // immediately.
184 void AddDestructionObserver(DestructionObserver* destruction_observer);
185
186 // Remove a DestructionObserver. It is safe to call this method while a
187 // DestructionObserver is receiving a notification callback.
188 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
189
190 // The "PostTask" family of methods call the task's Run method asynchronously
191 // from within a message loop at some point in the future.
192 //
193 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
194 // with normal UI or IO event processing. With the PostDelayedTask variant,
195 // tasks are called after at least approximately 'delay_ms' have elapsed.
196 //
197 // The NonNestable variants work similarly except that they promise never to
198 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
199 // such tasks get deferred until the top-most MessageLoop::Run is executing.
200 //
201 // The MessageLoop takes ownership of the Task, and deletes it after it has
202 // been Run().
203 //
204 // PostTask(from_here, task) is equivalent to
205 // PostDelayedTask(from_here, task, 0).
206 //
207 // The TryPostTask is meant for the cases where the calling thread cannot
208 // block. If posting the task will block, the call returns false, the task
209 // is not posted but the task is consumed anyways.
210 //
211 // NOTE: These methods may be called on any thread. The Task will be invoked
212 // on the thread that executes MessageLoop::Run().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900213 void PostTask(const tracked_objects::Location& from_here,
214 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900215
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900216 bool TryPostTask(const tracked_objects::Location& from_here,
217 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900218
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900219 void PostDelayedTask(const tracked_objects::Location& from_here,
220 const Closure& task,
221 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900222
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900223 void PostNonNestableTask(const tracked_objects::Location& from_here,
224 const Closure& task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900225
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900226 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here,
227 const Closure& task,
228 TimeDelta delay);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900229
230 // A variant on PostTask that deletes the given object. This is useful
231 // if the object needs to live until the next run of the MessageLoop (for
232 // example, deleting a RenderProcessHost from within an IPC callback is not
233 // good).
234 //
235 // NOTE: This method may be called on any thread. The object will be deleted
236 // on the thread that executes MessageLoop::Run(). If this is not the same
237 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
238 // from RefCountedThreadSafe<T>!
239 template <class T>
240 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
241 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
242 this, from_here, object);
243 }
244
245 // A variant on PostTask that releases the given reference counted object
246 // (by calling its Release method). This is useful if the object needs to
247 // live until the next run of the MessageLoop, or if the object needs to be
248 // released on a particular thread.
249 //
250 // NOTE: This method may be called on any thread. The object will be
251 // released (and thus possibly deleted) on the thread that executes
252 // MessageLoop::Run(). If this is not the same as the thread that calls
253 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
254 // RefCountedThreadSafe<T>!
255 template <class T>
256 void ReleaseSoon(const tracked_objects::Location& from_here,
257 const T* object) {
258 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
259 this, from_here, object);
260 }
261
262 // Deprecated: use RunLoop instead.
263 // Run the message loop.
264 void Run();
265
266 // Deprecated: use RunLoop instead.
267 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
268 // Return as soon as all items that can be run are taken care of.
269 void RunUntilIdle();
270
271 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
272 void Quit() { QuitWhenIdle(); }
273
274 // Deprecated: use RunLoop instead.
275 //
276 // Signals the Run method to return when it becomes idle. It will continue to
277 // process pending messages and future messages as long as they are enqueued.
278 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
279 // Quit method when looping procedures (such as web pages) have been shut
280 // down.
281 //
282 // This method may only be called on the same thread that called Run, and Run
283 // must still be on the call stack.
284 //
285 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
286 // but note that doing so is fairly dangerous if the target thread makes
287 // nested calls to MessageLoop::Run. The problem being that you won't know
288 // which nested run loop you are quitting, so be careful!
289 void QuitWhenIdle();
290
291 // Deprecated: use RunLoop instead.
292 //
293 // This method is a variant of Quit, that does not wait for pending messages
294 // to be processed before returning from Run.
295 void QuitNow();
296
297 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900298 static Closure QuitClosure() { return QuitWhenIdleClosure(); }
brettw@chromium.org6318b392013-06-14 12:27:49 +0900299
300 // Deprecated: use RunLoop instead.
301 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
302 // arbitrary MessageLoop to QuitWhenIdle.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900303 static Closure QuitWhenIdleClosure();
brettw@chromium.org6318b392013-06-14 12:27:49 +0900304
305 // Returns true if this loop is |type|. This allows subclasses (especially
306 // those in tests) to specialize how they are identified.
307 virtual bool IsType(Type type) const;
308
309 // Returns the type passed to the constructor.
310 Type type() const { return type_; }
311
312 // Optional call to connect the thread name with this loop.
313 void set_thread_name(const std::string& thread_name) {
314 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
315 thread_name_ = thread_name;
316 }
317 const std::string& thread_name() const { return thread_name_; }
318
319 // Gets the message loop proxy associated with this message loop.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900320 scoped_refptr<MessageLoopProxy> message_loop_proxy() {
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900321 return message_loop_proxy_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900322 }
323
324 // Enables or disables the recursive task processing. This happens in the case
325 // of recursive message loops. Some unwanted message loop may occurs when
326 // using common controls or printer functions. By default, recursive task
327 // processing is disabled.
328 //
329 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
330 // directly. In general nestable message loops are to be avoided. They are
331 // dangerous and difficult to get right, so please use with extreme caution.
332 //
333 // The specific case where tasks get queued is:
334 // - The thread is running a message loop.
335 // - It receives a task #1 and execute it.
336 // - The task #1 implicitly start a message loop, like a MessageBox in the
337 // unit test. This can also be StartDoc or GetSaveFileName.
338 // - The thread receives a task #2 before or while in this second message
339 // loop.
340 // - With NestableTasksAllowed set to true, the task #2 will run right away.
341 // Otherwise, it will get executed right after task #1 completes at "thread
342 // message loop level".
343 void SetNestableTasksAllowed(bool allowed);
344 bool NestableTasksAllowed() const;
345
346 // Enables nestable tasks on |loop| while in scope.
347 class ScopedNestableTaskAllower {
348 public:
349 explicit ScopedNestableTaskAllower(MessageLoop* loop)
350 : loop_(loop),
351 old_state_(loop_->NestableTasksAllowed()) {
352 loop_->SetNestableTasksAllowed(true);
353 }
354 ~ScopedNestableTaskAllower() {
355 loop_->SetNestableTasksAllowed(old_state_);
356 }
357
358 private:
359 MessageLoop* loop_;
360 bool old_state_;
361 };
362
363 // Enables or disables the restoration during an exception of the unhandled
364 // exception filter that was active when Run() was called. This can happen
365 // if some third party code call SetUnhandledExceptionFilter() and never
366 // restores the previous filter.
367 void set_exception_restoration(bool restore) {
368 exception_restoration_ = restore;
369 }
370
371 // Returns true if we are currently running a nested message loop.
372 bool IsNested();
373
374 // A TaskObserver is an object that receives task notifications from the
375 // MessageLoop.
376 //
377 // NOTE: A TaskObserver implementation should be extremely fast!
378 class BASE_EXPORT TaskObserver {
379 public:
380 TaskObserver();
381
382 // This method is called before processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900383 virtual void WillProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900384
385 // This method is called after processing a task.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900386 virtual void DidProcessTask(const PendingTask& pending_task) = 0;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900387
388 protected:
389 virtual ~TaskObserver();
390 };
391
392 // These functions can only be called on the same thread that |this| is
393 // running on.
394 void AddTaskObserver(TaskObserver* task_observer);
395 void RemoveTaskObserver(TaskObserver* task_observer);
396
brettw@chromium.org6318b392013-06-14 12:27:49 +0900397 // When we go into high resolution timer mode, we will stay in hi-res mode
398 // for at least 1s.
399 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
400
brettw@chromium.org6318b392013-06-14 12:27:49 +0900401#if defined(OS_WIN)
402 void set_os_modal_loop(bool os_modal_loop) {
403 os_modal_loop_ = os_modal_loop;
404 }
405
406 bool os_modal_loop() const {
407 return os_modal_loop_;
408 }
409#endif // OS_WIN
410
411 // Can only be called from the thread that owns the MessageLoop.
412 bool is_running() const;
413
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900414 // Returns true if the message loop has high resolution timers enabled.
415 // Provided for testing.
416 bool IsHighResolutionTimerEnabledForTesting();
417
418 // Returns true if the message loop is "idle". Provided for testing.
419 bool IsIdleForTesting();
420
421 // Takes the incoming queue lock, signals |caller_wait| and waits until
422 // |caller_signal| is signalled.
423 void LockWaitUnLockForTesting(WaitableEvent* caller_wait,
424 WaitableEvent* caller_signal);
425
brettw@chromium.org6318b392013-06-14 12:27:49 +0900426 //----------------------------------------------------------------------------
427 protected:
428
429#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900430 MessagePumpWin* pump_win() {
431 return static_cast<MessagePumpWin*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900432 }
433#elif defined(OS_POSIX) && !defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900434 MessagePumpLibevent* pump_libevent() {
435 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900436 }
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900437#if defined(TOOLKIT_GTK)
438 friend class MessagePumpX11;
439 MessagePumpX11* pump_gpu() {
440 DCHECK_EQ(TYPE_GPU, type());
441 return static_cast<MessagePumpX11*>(pump_.get());
442 }
443#endif
brettw@chromium.org6318b392013-06-14 12:27:49 +0900444#endif
445
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900446 scoped_ptr<MessagePump> pump_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900447
448 private:
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900449 friend class internal::IncomingTaskQueue;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900450 friend class RunLoop;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900451
sky@chromium.orgab452802013-11-08 15:16:53 +0900452 // Configures various members for the two constructors.
453 void Init();
454
brettw@chromium.org6318b392013-06-14 12:27:49 +0900455 // A function to encapsulate all the exception handling capability in the
456 // stacks around the running of a main message loop. It will run the message
457 // loop in a SEH try block or not depending on the set_SEH_restoration()
458 // flag invoking respectively RunInternalInSEHFrame() or RunInternal().
459 void RunHandler();
460
461#if defined(OS_WIN)
462 __declspec(noinline) void RunInternalInSEHFrame();
463#endif
464
465 // A surrounding stack frame around the running of the message loop that
466 // supports all saving and restoring of state, as is needed for any/all (ugly)
467 // recursive calls.
468 void RunInternal();
469
470 // Called to process any delayed non-nestable tasks.
471 bool ProcessNextDelayedNonNestableTask();
472
473 // Runs the specified PendingTask.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900474 void RunTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900475
476 // Calls RunTask or queues the pending_task on the deferred task list if it
477 // cannot be run right now. Returns true if the task was run.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900478 bool DeferOrRunPendingTask(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900479
480 // Adds the pending task to delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900481 void AddToDelayedWorkQueue(const PendingTask& pending_task);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900482
brettw@chromium.org6318b392013-06-14 12:27:49 +0900483 // Delete tasks that haven't run yet without running them. Used in the
484 // destructor to make sure all the task's destructors get called. Returns
485 // true if some work was done.
486 bool DeletePendingTasks();
487
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900488 // Creates a process-wide unique ID to represent this task in trace events.
489 // This will be mangled with a Process ID hash to reduce the likelyhood of
490 // colliding with MessageLoop pointers on other processes.
491 uint64 GetTaskTraceID(const PendingTask& task);
492
493 // Loads tasks from the incoming queue to |work_queue_| if the latter is
494 // empty.
495 void ReloadWorkQueue();
496
497 // Wakes up the message pump. Can be called on any thread. The caller is
498 // responsible for synchronizing ScheduleWork() calls.
499 void ScheduleWork(bool was_empty);
brettw@chromium.org6318b392013-06-14 12:27:49 +0900500
501 // Start recording histogram info about events and action IF it was enabled
502 // and IF the statistics recorder can accept a registration of our histogram.
503 void StartHistogrammer();
504
505 // Add occurrence of event to our histogram, so that we can see what is being
506 // done in a specific MessageLoop instance (i.e., specific thread).
507 // If message_histogram_ is NULL, this is a no-op.
508 void HistogramEvent(int event);
509
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900510 // MessagePump::Delegate methods:
brettw@chromium.org6318b392013-06-14 12:27:49 +0900511 virtual bool DoWork() OVERRIDE;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900512 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900513 virtual bool DoIdleWork() OVERRIDE;
rsesek@chromium.orgee8420d2013-09-05 23:53:12 +0900514 virtual void GetQueueingInformation(size_t* queue_size,
515 TimeDelta* queueing_delay) OVERRIDE;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900516
sky@chromium.orgab452802013-11-08 15:16:53 +0900517 const Type type_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900518
519 // A list of tasks that need to be processed by this instance. Note that
520 // this queue is only accessed (push/pop) by our current thread.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900521 TaskQueue work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900522
523 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900524 DelayedTaskQueue delayed_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900525
526 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900527 TimeTicks recent_time_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900528
529 // A queue of non-nestable tasks that we had to defer because when it came
530 // time to execute them we were in a nested message loop. They will execute
531 // once we're out of nested message loops.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900532 TaskQueue deferred_non_nestable_work_queue_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900533
534 ObserverList<DestructionObserver> destruction_observers_;
535
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900536 bool exception_restoration_;
537
brettw@chromium.org6318b392013-06-14 12:27:49 +0900538 // A recursion block that prevents accidentally running additional tasks when
539 // insider a (accidentally induced?) nested message pump.
540 bool nestable_tasks_allowed_;
541
alexeypa@google.combb819d62013-07-23 05:06:56 +0900542#if defined(OS_WIN)
alexeypa@google.combb819d62013-07-23 05:06:56 +0900543 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
544 // which enter a modal message loop.
545 bool os_modal_loop_;
546#endif
547
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900548 std::string thread_name_;
549 // A profiling histogram showing the counts of various messages and events.
550 HistogramBase* message_histogram_;
551
552 RunLoop* run_loop_;
alexeypa@google.combb819d62013-07-23 05:06:56 +0900553
brettw@chromium.org6318b392013-06-14 12:27:49 +0900554 ObserverList<TaskObserver> task_observers_;
555
alexeypa@chromium.org40183232013-07-23 07:24:13 +0900556 scoped_refptr<internal::IncomingTaskQueue> incoming_task_queue_;
557
558 // The message loop proxy associated with this message loop.
559 scoped_refptr<internal::MessageLoopProxyImpl> message_loop_proxy_;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900560 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900561
562 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
563 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
564
565 void DeleteSoonInternal(const tracked_objects::Location& from_here,
566 void(*deleter)(const void*),
567 const void* object);
568 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
569 void(*releaser)(const void*),
570 const void* object);
571
572 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
573};
574
575//-----------------------------------------------------------------------------
576// MessageLoopForUI extends MessageLoop with methods that are particular to a
577// MessageLoop instantiated with TYPE_UI.
578//
579// This class is typically used like so:
580// MessageLoopForUI::current()->...call some method...
581//
582class BASE_EXPORT MessageLoopForUI : public MessageLoop {
583 public:
584#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900585 typedef MessagePumpForUI::MessageFilter MessageFilter;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900586#endif
587
588 MessageLoopForUI() : MessageLoop(TYPE_UI) {
589 }
590
591 // Returns the MessageLoopForUI of the current thread.
592 static MessageLoopForUI* current() {
593 MessageLoop* loop = MessageLoop::current();
594 DCHECK(loop);
595 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
596 return static_cast<MessageLoopForUI*>(loop);
597 }
598
brettw@chromium.org6318b392013-06-14 12:27:49 +0900599#if defined(OS_IOS)
600 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
601 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
602 // PostTask() to work.
603 void Attach();
604#endif
605
606#if defined(OS_ANDROID)
607 // On Android, the UI message loop is handled by Java side. So Run() should
608 // never be called. Instead use Start(), which will forward all the native UI
609 // events to the Java message loop.
610 void Start();
611#elif !defined(OS_MACOSX)
612
613 // Please see message_pump_win/message_pump_glib for definitions of these
614 // methods.
615 void AddObserver(Observer* observer);
616 void RemoveObserver(Observer* observer);
617
618#if defined(OS_WIN)
619 // Plese see MessagePumpForUI for definitions of this method.
620 void SetMessageFilter(scoped_ptr<MessageFilter> message_filter) {
621 pump_ui()->SetMessageFilter(message_filter.Pass());
622 }
623#endif
624
625 protected:
ccameron@chromium.orgbfe60072013-09-13 07:51:10 +0900626#if defined(USE_X11)
sadrul@chromium.org19995722013-09-07 12:21:04 +0900627 friend class MessagePumpX11;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900628#endif
629#if defined(USE_OZONE) && !defined(OS_NACL)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900630 friend class MessagePumpOzone;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900631#endif
632
633 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900634 MessagePumpForUI* pump_ui() {
635 return static_cast<MessagePumpForUI*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900636 }
637#endif // !defined(OS_MACOSX)
638};
639
640// Do not add any member variables to MessageLoopForUI! This is important b/c
641// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
642// data that you need should be stored on the MessageLoop's pump_ instance.
643COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
644 MessageLoopForUI_should_not_have_extra_member_variables);
645
646//-----------------------------------------------------------------------------
647// MessageLoopForIO extends MessageLoop with methods that are particular to a
648// MessageLoop instantiated with TYPE_IO.
649//
650// This class is typically used like so:
651// MessageLoopForIO::current()->...call some method...
652//
653class BASE_EXPORT MessageLoopForIO : public MessageLoop {
654 public:
655#if defined(OS_WIN)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900656 typedef MessagePumpForIO::IOHandler IOHandler;
657 typedef MessagePumpForIO::IOContext IOContext;
658 typedef MessagePumpForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900659#elif defined(OS_IOS)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900660 typedef MessagePumpIOSForIO::Watcher Watcher;
661 typedef MessagePumpIOSForIO::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900662 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900663 typedef MessagePumpIOSForIO::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900664
665 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900666 WATCH_READ = MessagePumpIOSForIO::WATCH_READ,
667 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE,
668 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900669 };
670#elif defined(OS_POSIX)
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900671 typedef MessagePumpLibevent::Watcher Watcher;
672 typedef MessagePumpLibevent::FileDescriptorWatcher
brettw@chromium.org6318b392013-06-14 12:27:49 +0900673 FileDescriptorWatcher;
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900674 typedef MessagePumpLibevent::IOObserver IOObserver;
brettw@chromium.org6318b392013-06-14 12:27:49 +0900675
676 enum Mode {
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900677 WATCH_READ = MessagePumpLibevent::WATCH_READ,
678 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE,
679 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE
brettw@chromium.org6318b392013-06-14 12:27:49 +0900680 };
681
682#endif
683
684 MessageLoopForIO() : MessageLoop(TYPE_IO) {
685 }
686
687 // Returns the MessageLoopForIO of the current thread.
688 static MessageLoopForIO* current() {
689 MessageLoop* loop = MessageLoop::current();
690 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
691 return static_cast<MessageLoopForIO*>(loop);
692 }
693
694 void AddIOObserver(IOObserver* io_observer) {
695 pump_io()->AddIOObserver(io_observer);
696 }
697
698 void RemoveIOObserver(IOObserver* io_observer) {
699 pump_io()->RemoveIOObserver(io_observer);
700 }
701
702#if defined(OS_WIN)
703 // Please see MessagePumpWin for definitions of these methods.
704 void RegisterIOHandler(HANDLE file, IOHandler* handler);
705 bool RegisterJobObject(HANDLE job, IOHandler* handler);
706 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
707
708 protected:
709 // TODO(rvargas): Make this platform independent.
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900710 MessagePumpForIO* pump_io() {
711 return static_cast<MessagePumpForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900712 }
713
714#elif defined(OS_IOS)
715 // Please see MessagePumpIOSForIO for definition.
716 bool WatchFileDescriptor(int fd,
717 bool persistent,
718 Mode mode,
719 FileDescriptorWatcher *controller,
720 Watcher *delegate);
721
722 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900723 MessagePumpIOSForIO* pump_io() {
724 return static_cast<MessagePumpIOSForIO*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900725 }
726
727#elif defined(OS_POSIX)
728 // Please see MessagePumpLibevent for definition.
729 bool WatchFileDescriptor(int fd,
730 bool persistent,
731 Mode mode,
732 FileDescriptorWatcher* controller,
733 Watcher* delegate);
734
735 private:
brettw@chromium.org710ecb92013-06-19 05:27:52 +0900736 MessagePumpLibevent* pump_io() {
737 return static_cast<MessagePumpLibevent*>(pump_.get());
brettw@chromium.org6318b392013-06-14 12:27:49 +0900738 }
739#endif // defined(OS_POSIX)
740};
741
742// Do not add any member variables to MessageLoopForIO! This is important b/c
743// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
744// data that you need should be stored on the MessageLoop's pump_ instance.
745COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
746 MessageLoopForIO_should_not_have_extra_member_variables);
747
748} // namespace base
749
750#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_