Fixed compile warnings.
[chromium-blink-merge.git] / base / message_loop.h
blobc1ffc89f74d5a8d98ddb51253ca33a53f4354b7f
1 // Copyright (c) 2012 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.
5 #ifndef BASE_MESSAGE_LOOP_H_
6 #define BASE_MESSAGE_LOOP_H_
7 #pragma once
9 #include <queue>
10 #include <string>
12 #include "base/base_export.h"
13 #include "base/basictypes.h"
14 #include "base/callback_forward.h"
15 #include "base/location.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/message_loop_proxy.h"
18 #include "base/message_pump.h"
19 #include "base/observer_list.h"
20 #include "base/pending_task.h"
21 #include "base/sequenced_task_runner_helpers.h"
22 #include "base/synchronization/lock.h"
23 #include "base/tracking_info.h"
24 #include "base/time.h"
26 #if defined(OS_WIN)
27 // We need this to declare base::MessagePumpWin::Dispatcher, which we should
28 // really just eliminate.
29 #include "base/message_pump_win.h"
30 #elif defined(OS_POSIX)
31 #include "base/message_pump_libevent.h"
32 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
34 #if defined(USE_AURA)
35 #include "base/message_pump_x.h"
36 #else
37 #include "base/message_pump_gtk.h"
38 #endif
40 #endif
41 #endif
43 namespace base {
44 class Histogram;
47 // A MessageLoop is used to process events for a particular thread. There is
48 // at most one MessageLoop instance per thread.
50 // Events include at a minimum Task instances submitted to PostTask or those
51 // managed by TimerManager. Depending on the type of message pump used by the
52 // MessageLoop other events such as UI messages may be processed. On Windows
53 // APC calls (as time permits) and signals sent to a registered set of HANDLEs
54 // may also be processed.
56 // NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
57 // on the thread where the MessageLoop's Run method executes.
59 // NOTE: MessageLoop has task reentrancy protection. This means that if a
60 // task is being processed, a second task cannot start until the first task is
61 // finished. Reentrancy can happen when processing a task, and an inner
62 // message pump is created. That inner pump then processes native messages
63 // which could implicitly start an inner task. Inner message pumps are created
64 // with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
65 // (DoDragDrop), printer functions (StartDoc) and *many* others.
67 // Sample workaround when inner task processing is needed:
68 // HRESULT hr;
69 // {
70 // MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
71 // hr = DoDragDrop(...); // Implicitly runs a modal message loop.
72 // }
73 // // Process |hr| (the result returned by DoDragDrop()).
75 // Please be SURE your task is reentrant (nestable) and all global variables
76 // are stable and accessible before calling SetNestableTasksAllowed(true).
78 class BASE_EXPORT MessageLoop : public base::MessagePump::Delegate {
79 public:
81 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
82 typedef base::MessagePumpDispatcher Dispatcher;
83 typedef base::MessagePumpObserver Observer;
84 #endif
86 // A MessageLoop has a particular type, which indicates the set of
87 // asynchronous events it may process in addition to tasks and timers.
89 // TYPE_DEFAULT
90 // This type of ML only supports tasks and timers.
92 // TYPE_UI
93 // This type of ML also supports native UI events (e.g., Windows messages).
94 // See also MessageLoopForUI.
96 // TYPE_IO
97 // This type of ML also supports asynchronous IO. See also
98 // MessageLoopForIO.
100 enum Type {
101 TYPE_DEFAULT,
102 TYPE_UI,
103 TYPE_IO
106 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
107 // is typical to make use of the current thread's MessageLoop instance.
108 explicit MessageLoop(Type type = TYPE_DEFAULT);
109 virtual ~MessageLoop();
111 // Returns the MessageLoop object for the current thread, or null if none.
112 static MessageLoop* current();
114 static void EnableHistogrammer(bool enable_histogrammer);
116 typedef base::MessagePump* (MessagePumpFactory)();
117 // Using the given base::MessagePumpForUIFactory to override the default
118 // MessagePump implementation for 'TYPE_UI'.
119 static void InitMessagePumpForUIFactory(MessagePumpFactory* factory);
121 // A DestructionObserver is notified when the current MessageLoop is being
122 // destroyed. These observers are notified prior to MessageLoop::current()
123 // being changed to return NULL. This gives interested parties the chance to
124 // do final cleanup that depends on the MessageLoop.
126 // NOTE: Any tasks posted to the MessageLoop during this notification will
127 // not be run. Instead, they will be deleted.
129 class BASE_EXPORT DestructionObserver {
130 public:
131 virtual void WillDestroyCurrentMessageLoop() = 0;
133 protected:
134 virtual ~DestructionObserver();
137 // Add a DestructionObserver, which will start receiving notifications
138 // immediately.
139 void AddDestructionObserver(DestructionObserver* destruction_observer);
141 // Remove a DestructionObserver. It is safe to call this method while a
142 // DestructionObserver is receiving a notification callback.
143 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
145 // The "PostTask" family of methods call the task's Run method asynchronously
146 // from within a message loop at some point in the future.
148 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
149 // with normal UI or IO event processing. With the PostDelayedTask variant,
150 // tasks are called after at least approximately 'delay_ms' have elapsed.
152 // The NonNestable variants work similarly except that they promise never to
153 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
154 // such tasks get deferred until the top-most MessageLoop::Run is executing.
156 // The MessageLoop takes ownership of the Task, and deletes it after it has
157 // been Run().
159 // NOTE: These methods may be called on any thread. The Task will be invoked
160 // on the thread that executes MessageLoop::Run().
161 void PostTask(
162 const tracked_objects::Location& from_here,
163 const base::Closure& task);
165 void PostDelayedTask(
166 const tracked_objects::Location& from_here,
167 const base::Closure& task, int64 delay_ms);
169 void PostDelayedTask(
170 const tracked_objects::Location& from_here,
171 const base::Closure& task,
172 base::TimeDelta delay);
174 void PostNonNestableTask(
175 const tracked_objects::Location& from_here,
176 const base::Closure& task);
178 void PostNonNestableDelayedTask(
179 const tracked_objects::Location& from_here,
180 const base::Closure& task, int64 delay_ms);
182 void PostNonNestableDelayedTask(
183 const tracked_objects::Location& from_here,
184 const base::Closure& task,
185 base::TimeDelta delay);
187 // A variant on PostTask that deletes the given object. This is useful
188 // if the object needs to live until the next run of the MessageLoop (for
189 // example, deleting a RenderProcessHost from within an IPC callback is not
190 // good).
192 // NOTE: This method may be called on any thread. The object will be deleted
193 // on the thread that executes MessageLoop::Run(). If this is not the same
194 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
195 // from RefCountedThreadSafe<T>!
196 template <class T>
197 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
198 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
199 this, from_here, object);
202 // A variant on PostTask that releases the given reference counted object
203 // (by calling its Release method). This is useful if the object needs to
204 // live until the next run of the MessageLoop, or if the object needs to be
205 // released on a particular thread.
207 // NOTE: This method may be called on any thread. The object will be
208 // released (and thus possibly deleted) on the thread that executes
209 // MessageLoop::Run(). If this is not the same as the thread that calls
210 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
211 // RefCountedThreadSafe<T>!
212 template <class T>
213 void ReleaseSoon(const tracked_objects::Location& from_here,
214 const T* object) {
215 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
216 this, from_here, object);
219 // Run the message loop.
220 void Run();
222 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
223 // Return as soon as all items that can be run are taken care of.
224 void RunAllPending();
226 // Signals the Run method to return after it is done processing all pending
227 // messages. This method may only be called on the same thread that called
228 // Run, and Run must still be on the call stack.
230 // Use QuitClosure if you need to Quit another thread's MessageLoop, but note
231 // that doing so is fairly dangerous if the target thread makes nested calls
232 // to MessageLoop::Run. The problem being that you won't know which nested
233 // run loop you are quitting, so be careful!
234 void Quit();
236 // This method is a variant of Quit, that does not wait for pending messages
237 // to be processed before returning from Run.
238 void QuitNow();
240 // Invokes Quit on the current MessageLoop when run. Useful to schedule an
241 // arbitrary MessageLoop to Quit.
242 static base::Closure QuitClosure();
244 // Returns the type passed to the constructor.
245 Type type() const { return type_; }
247 // Optional call to connect the thread name with this loop.
248 void set_thread_name(const std::string& thread_name) {
249 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
250 thread_name_ = thread_name;
252 const std::string& thread_name() const { return thread_name_; }
254 // Gets the message loop proxy associated with this message loop.
255 scoped_refptr<base::MessageLoopProxy> message_loop_proxy() {
256 return message_loop_proxy_.get();
259 // Enables or disables the recursive task processing. This happens in the case
260 // of recursive message loops. Some unwanted message loop may occurs when
261 // using common controls or printer functions. By default, recursive task
262 // processing is disabled.
264 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
265 // directly. In general nestable message loops are to be avoided. They are
266 // dangerous and difficult to get right, so please use with extreme caution.
268 // The specific case where tasks get queued is:
269 // - The thread is running a message loop.
270 // - It receives a task #1 and execute it.
271 // - The task #1 implicitly start a message loop, like a MessageBox in the
272 // unit test. This can also be StartDoc or GetSaveFileName.
273 // - The thread receives a task #2 before or while in this second message
274 // loop.
275 // - With NestableTasksAllowed set to true, the task #2 will run right away.
276 // Otherwise, it will get executed right after task #1 completes at "thread
277 // message loop level".
278 void SetNestableTasksAllowed(bool allowed);
279 bool NestableTasksAllowed() const;
281 // Enables nestable tasks on |loop| while in scope.
282 class ScopedNestableTaskAllower {
283 public:
284 explicit ScopedNestableTaskAllower(MessageLoop* loop)
285 : loop_(loop),
286 old_state_(loop_->NestableTasksAllowed()) {
287 loop_->SetNestableTasksAllowed(true);
289 ~ScopedNestableTaskAllower() {
290 loop_->SetNestableTasksAllowed(old_state_);
293 private:
294 MessageLoop* loop_;
295 bool old_state_;
298 // Enables or disables the restoration during an exception of the unhandled
299 // exception filter that was active when Run() was called. This can happen
300 // if some third party code call SetUnhandledExceptionFilter() and never
301 // restores the previous filter.
302 void set_exception_restoration(bool restore) {
303 exception_restoration_ = restore;
306 // Returns true if we are currently running a nested message loop.
307 bool IsNested();
309 // A TaskObserver is an object that receives task notifications from the
310 // MessageLoop.
312 // NOTE: A TaskObserver implementation should be extremely fast!
313 class BASE_EXPORT TaskObserver {
314 public:
315 TaskObserver();
317 // This method is called before processing a task.
318 virtual void WillProcessTask(base::TimeTicks time_posted) = 0;
320 // This method is called after processing a task.
321 virtual void DidProcessTask(base::TimeTicks time_posted) = 0;
323 protected:
324 virtual ~TaskObserver();
327 // These functions can only be called on the same thread that |this| is
328 // running on.
329 void AddTaskObserver(TaskObserver* task_observer);
330 void RemoveTaskObserver(TaskObserver* task_observer);
332 // Returns true if the message loop has high resolution timers enabled.
333 // Provided for testing.
334 bool high_resolution_timers_enabled() {
335 #if defined(OS_WIN)
336 return !high_resolution_timer_expiration_.is_null();
337 #else
338 return true;
339 #endif
342 // When we go into high resolution timer mode, we will stay in hi-res mode
343 // for at least 1s.
344 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
346 // Asserts that the MessageLoop is "idle".
347 void AssertIdle() const;
349 #if defined(OS_WIN)
350 void set_os_modal_loop(bool os_modal_loop) {
351 os_modal_loop_ = os_modal_loop;
354 bool os_modal_loop() const {
355 return os_modal_loop_;
357 #endif // OS_WIN
359 // Can only be called from the thread that owns the MessageLoop.
360 bool is_running() const;
362 //----------------------------------------------------------------------------
363 protected:
364 struct RunState {
365 // Used to count how many Run() invocations are on the stack.
366 int run_depth;
368 // Used to record that Quit() was called, or that we should quit the pump
369 // once it becomes idle.
370 bool quit_received;
372 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
373 Dispatcher* dispatcher;
374 #endif
377 #if defined(OS_ANDROID)
378 // Android Java process manages the UI thread message loop. So its
379 // MessagePumpForUI needs to keep the RunState.
380 public:
381 #endif
382 class BASE_EXPORT AutoRunState : RunState {
383 public:
384 explicit AutoRunState(MessageLoop* loop);
385 ~AutoRunState();
386 private:
387 MessageLoop* loop_;
388 RunState* previous_state_;
390 #if defined(OS_ANDROID)
391 protected:
392 #endif
394 #if defined(OS_WIN)
395 base::MessagePumpWin* pump_win() {
396 return static_cast<base::MessagePumpWin*>(pump_.get());
398 #elif defined(OS_POSIX)
399 base::MessagePumpLibevent* pump_libevent() {
400 return static_cast<base::MessagePumpLibevent*>(pump_.get());
402 #endif
404 // A function to encapsulate all the exception handling capability in the
405 // stacks around the running of a main message loop. It will run the message
406 // loop in a SEH try block or not depending on the set_SEH_restoration()
407 // flag invoking respectively RunInternalInSEHFrame() or RunInternal().
408 void RunHandler();
410 #if defined(OS_WIN)
411 __declspec(noinline) void RunInternalInSEHFrame();
412 #endif
414 // A surrounding stack frame around the running of the message loop that
415 // supports all saving and restoring of state, as is needed for any/all (ugly)
416 // recursive calls.
417 void RunInternal();
419 // Called to process any delayed non-nestable tasks.
420 bool ProcessNextDelayedNonNestableTask();
422 // Runs the specified PendingTask.
423 void RunTask(const base::PendingTask& pending_task);
425 // Calls RunTask or queues the pending_task on the deferred task list if it
426 // cannot be run right now. Returns true if the task was run.
427 bool DeferOrRunPendingTask(const base::PendingTask& pending_task);
429 // Adds the pending task to delayed_work_queue_.
430 void AddToDelayedWorkQueue(const base::PendingTask& pending_task);
432 // Adds the pending task to our incoming_queue_.
434 // Caller retains ownership of |pending_task|, but this function will
435 // reset the value of pending_task->task. This is needed to ensure
436 // that the posting call stack does not retain pending_task->task
437 // beyond this function call.
438 void AddToIncomingQueue(base::PendingTask* pending_task);
440 // Load tasks from the incoming_queue_ into work_queue_ if the latter is
441 // empty. The former requires a lock to access, while the latter is directly
442 // accessible on this thread.
443 void ReloadWorkQueue();
445 // Delete tasks that haven't run yet without running them. Used in the
446 // destructor to make sure all the task's destructors get called. Returns
447 // true if some work was done.
448 bool DeletePendingTasks();
450 // Calculates the time at which a PendingTask should run.
451 base::TimeTicks CalculateDelayedRuntime(int64 delay_ms);
453 // Start recording histogram info about events and action IF it was enabled
454 // and IF the statistics recorder can accept a registration of our histogram.
455 void StartHistogrammer();
457 // Add occurrence of event to our histogram, so that we can see what is being
458 // done in a specific MessageLoop instance (i.e., specific thread).
459 // If message_histogram_ is NULL, this is a no-op.
460 void HistogramEvent(int event);
462 // base::MessagePump::Delegate methods:
463 virtual bool DoWork() OVERRIDE;
464 virtual bool DoDelayedWork(base::TimeTicks* next_delayed_work_time) OVERRIDE;
465 virtual bool DoIdleWork() OVERRIDE;
467 Type type_;
469 // A list of tasks that need to be processed by this instance. Note that
470 // this queue is only accessed (push/pop) by our current thread.
471 base::TaskQueue work_queue_;
473 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
474 base::DelayedTaskQueue delayed_work_queue_;
476 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
477 base::TimeTicks recent_time_;
479 // A queue of non-nestable tasks that we had to defer because when it came
480 // time to execute them we were in a nested message loop. They will execute
481 // once we're out of nested message loops.
482 base::TaskQueue deferred_non_nestable_work_queue_;
484 scoped_refptr<base::MessagePump> pump_;
486 ObserverList<DestructionObserver> destruction_observers_;
488 // A recursion block that prevents accidentally running additional tasks when
489 // insider a (accidentally induced?) nested message pump.
490 bool nestable_tasks_allowed_;
492 bool exception_restoration_;
494 std::string thread_name_;
495 // A profiling histogram showing the counts of various messages and events.
496 base::Histogram* message_histogram_;
498 // A null terminated list which creates an incoming_queue of tasks that are
499 // acquired under a mutex for processing on this instance's thread. These
500 // tasks have not yet been sorted out into items for our work_queue_ vs items
501 // that will be handled by the TimerManager.
502 base::TaskQueue incoming_queue_;
503 // Protect access to incoming_queue_.
504 mutable base::Lock incoming_queue_lock_;
506 RunState* state_;
508 #if defined(OS_WIN)
509 base::TimeTicks high_resolution_timer_expiration_;
510 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
511 // which enter a modal message loop.
512 bool os_modal_loop_;
513 #endif
515 // The next sequence number to use for delayed tasks.
516 int next_sequence_num_;
518 ObserverList<TaskObserver> task_observers_;
520 // The message loop proxy associated with this message loop, if one exists.
521 scoped_refptr<base::MessageLoopProxy> message_loop_proxy_;
523 private:
524 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
525 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
527 void DeleteSoonInternal(const tracked_objects::Location& from_here,
528 void(*deleter)(const void*),
529 const void* object);
530 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
531 void(*releaser)(const void*),
532 const void* object);
535 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
538 //-----------------------------------------------------------------------------
539 // MessageLoopForUI extends MessageLoop with methods that are particular to a
540 // MessageLoop instantiated with TYPE_UI.
542 // This class is typically used like so:
543 // MessageLoopForUI::current()->...call some method...
545 class BASE_EXPORT MessageLoopForUI : public MessageLoop {
546 public:
547 MessageLoopForUI() : MessageLoop(TYPE_UI) {
550 // Returns the MessageLoopForUI of the current thread.
551 static MessageLoopForUI* current() {
552 MessageLoop* loop = MessageLoop::current();
553 DCHECK(loop);
554 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
555 return static_cast<MessageLoopForUI*>(loop);
558 #if defined(OS_WIN)
559 void DidProcessMessage(const MSG& message);
560 #endif // defined(OS_WIN)
562 #if defined(OS_ANDROID)
563 // On Android, the UI message loop is handled by Java side. So Run() should
564 // never be called. Instead use Start(), which will forward all the native UI
565 // events to the Java message loop.
566 void Start();
567 #elif !defined(OS_MACOSX)
568 // Please see message_pump_win/message_pump_glib for definitions of these
569 // methods.
570 void AddObserver(Observer* observer);
571 void RemoveObserver(Observer* observer);
572 void RunWithDispatcher(Dispatcher* dispatcher);
573 void RunAllPendingWithDispatcher(Dispatcher* dispatcher);
575 protected:
576 // TODO(rvargas): Make this platform independent.
577 base::MessagePumpForUI* pump_ui() {
578 return static_cast<base::MessagePumpForUI*>(pump_.get());
580 #endif // !defined(OS_MACOSX)
583 // Do not add any member variables to MessageLoopForUI! This is important b/c
584 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
585 // data that you need should be stored on the MessageLoop's pump_ instance.
586 COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
587 MessageLoopForUI_should_not_have_extra_member_variables);
589 //-----------------------------------------------------------------------------
590 // MessageLoopForIO extends MessageLoop with methods that are particular to a
591 // MessageLoop instantiated with TYPE_IO.
593 // This class is typically used like so:
594 // MessageLoopForIO::current()->...call some method...
596 class BASE_EXPORT MessageLoopForIO : public MessageLoop {
597 public:
598 #if defined(OS_WIN)
599 typedef base::MessagePumpForIO::IOHandler IOHandler;
600 typedef base::MessagePumpForIO::IOContext IOContext;
601 typedef base::MessagePumpForIO::IOObserver IOObserver;
602 #elif defined(OS_POSIX)
603 typedef base::MessagePumpLibevent::Watcher Watcher;
604 typedef base::MessagePumpLibevent::FileDescriptorWatcher
605 FileDescriptorWatcher;
606 typedef base::MessagePumpLibevent::IOObserver IOObserver;
608 enum Mode {
609 WATCH_READ = base::MessagePumpLibevent::WATCH_READ,
610 WATCH_WRITE = base::MessagePumpLibevent::WATCH_WRITE,
611 WATCH_READ_WRITE = base::MessagePumpLibevent::WATCH_READ_WRITE
614 #endif
616 MessageLoopForIO() : MessageLoop(TYPE_IO) {
619 // Returns the MessageLoopForIO of the current thread.
620 static MessageLoopForIO* current() {
621 MessageLoop* loop = MessageLoop::current();
622 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
623 return static_cast<MessageLoopForIO*>(loop);
626 void AddIOObserver(IOObserver* io_observer) {
627 pump_io()->AddIOObserver(io_observer);
630 void RemoveIOObserver(IOObserver* io_observer) {
631 pump_io()->RemoveIOObserver(io_observer);
634 #if defined(OS_WIN)
635 // Please see MessagePumpWin for definitions of these methods.
636 void RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
637 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
639 protected:
640 // TODO(rvargas): Make this platform independent.
641 base::MessagePumpForIO* pump_io() {
642 return static_cast<base::MessagePumpForIO*>(pump_.get());
645 #elif defined(OS_POSIX)
646 // Please see MessagePumpLibevent for definition.
647 bool WatchFileDescriptor(int fd,
648 bool persistent,
649 Mode mode,
650 FileDescriptorWatcher* controller,
651 Watcher* delegate);
653 private:
654 base::MessagePumpLibevent* pump_io() {
655 return static_cast<base::MessagePumpLibevent*>(pump_.get());
657 #endif // defined(OS_POSIX)
660 // Do not add any member variables to MessageLoopForIO! This is important b/c
661 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
662 // data that you need should be stored on the MessageLoop's pump_ instance.
663 COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
664 MessageLoopForIO_should_not_have_extra_member_variables);
666 #endif // BASE_MESSAGE_LOOP_H_