"Make Chrome your default browser" should now appear as a checkbox at the bottom...
[chromium-blink-merge.git] / base / message_loop.h
blobcc6758752ff3540f49a7a272e2f2afc35c02e1c3
1 // Copyright (c) 2006-2008 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_
8 #include <deque>
9 #include <queue>
10 #include <string>
11 #include <vector>
13 #include "base/histogram.h"
14 #include "base/message_pump.h"
15 #include "base/observer_list.h"
16 #include "base/ref_counted.h"
17 #include "base/task.h"
18 #include "base/timer.h"
20 #if defined(OS_WIN)
21 // We need this to declare base::MessagePumpWin::Dispatcher, which we should
22 // really just eliminate.
23 #include "base/message_pump_win.h"
24 #elif defined(OS_POSIX)
25 #include "base/message_pump_libevent.h"
26 #endif
28 // A MessageLoop is used to process events for a particular thread. There is
29 // at most one MessageLoop instance per thread.
31 // Events include at a minimum Task instances submitted to PostTask or those
32 // managed by TimerManager. Depending on the type of message pump used by the
33 // MessageLoop other events such as UI messages may be processed. On Windows
34 // APC calls (as time permits) and signals sent to a registered set of HANDLEs
35 // may also be processed.
37 // NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
38 // on the thread where the MessageLoop's Run method executes.
40 // NOTE: MessageLoop has task reentrancy protection. This means that if a
41 // task is being processed, a second task cannot start until the first task is
42 // finished. Reentrancy can happen when processing a task, and an inner
43 // message pump is created. That inner pump then processes native messages
44 // which could implicitly start an inner task. Inner message pumps are created
45 // with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
46 // (DoDragDrop), printer functions (StartDoc) and *many* others.
48 // Sample workaround when inner task processing is needed:
49 // bool old_state = MessageLoop::current()->NestableTasksAllowed();
50 // MessageLoop::current()->SetNestableTasksAllowed(true);
51 // HRESULT hr = DoDragDrop(...); // Implicitly runs a modal message loop here.
52 // MessageLoop::current()->SetNestableTasksAllowed(old_state);
53 // // Process hr (the result returned by DoDragDrop().
55 // Please be SURE your task is reentrant (nestable) and all global variables
56 // are stable and accessible before calling SetNestableTasksAllowed(true).
58 class MessageLoop : public base::MessagePump::Delegate {
59 public:
60 static void EnableHistogrammer(bool enable_histogrammer);
62 // A DestructionObserver is notified when the current MessageLoop is being
63 // destroyed. These obsevers are notified prior to MessageLoop::current()
64 // being changed to return NULL. This gives interested parties the chance to
65 // do final cleanup that depends on the MessageLoop.
67 // NOTE: Any tasks posted to the MessageLoop during this notification will
68 // not be run. Instead, they will be deleted.
70 class DestructionObserver {
71 public:
72 virtual ~DestructionObserver() {}
73 virtual void WillDestroyCurrentMessageLoop() = 0;
76 // Add a DestructionObserver, which will start receiving notifications
77 // immediately.
78 void AddDestructionObserver(DestructionObserver* destruction_observer);
80 // Remove a DestructionObserver. It is safe to call this method while a
81 // DestructionObserver is receiving a notification callback.
82 void RemoveDestructionObserver(DestructionObserver* destruction_observer);
84 // The "PostTask" family of methods call the task's Run method asynchronously
85 // from within a message loop at some point in the future.
87 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
88 // with normal UI or IO event processing. With the PostDelayedTask variant,
89 // tasks are called after at least approximately 'delay_ms' have elapsed.
91 // The NonNestable variants work similarly except that they promise never to
92 // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
93 // such tasks get deferred until the top-most MessageLoop::Run is executing.
95 // The MessageLoop takes ownership of the Task, and deletes it after it has
96 // been Run().
98 // NOTE: These methods may be called on any thread. The Task will be invoked
99 // on the thread that executes MessageLoop::Run().
101 void PostTask(
102 const tracked_objects::Location& from_here, Task* task);
104 void PostDelayedTask(
105 const tracked_objects::Location& from_here, Task* task, int delay_ms);
107 void PostNonNestableTask(
108 const tracked_objects::Location& from_here, Task* task);
110 void PostNonNestableDelayedTask(
111 const tracked_objects::Location& from_here, Task* task, int delay_ms);
113 // A variant on PostTask that deletes the given object. This is useful
114 // if the object needs to live until the next run of the MessageLoop (for
115 // example, deleting a RenderProcessHost from within an IPC callback is not
116 // good).
118 // NOTE: This method may be called on any thread. The object will be deleted
119 // on the thread that executes MessageLoop::Run(). If this is not the same
120 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
121 // from RefCountedThreadSafe<T>!
122 template <class T>
123 void DeleteSoon(const tracked_objects::Location& from_here, T* object) {
124 PostNonNestableTask(from_here, new DeleteTask<T>(object));
127 // A variant on PostTask that releases the given reference counted object
128 // (by calling its Release method). This is useful if the object needs to
129 // live until the next run of the MessageLoop, or if the object needs to be
130 // released on a particular thread.
132 // NOTE: This method may be called on any thread. The object will be
133 // released (and thus possibly deleted) on the thread that executes
134 // MessageLoop::Run(). If this is not the same as the thread that calls
135 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
136 // RefCountedThreadSafe<T>!
137 template <class T>
138 void ReleaseSoon(const tracked_objects::Location& from_here, T* object) {
139 PostNonNestableTask(from_here, new ReleaseTask<T>(object));
142 // Run the message loop.
143 void Run();
145 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
146 // Return as soon as all items that can be run are taken care of.
147 void RunAllPending();
149 // Signals the Run method to return after it is done processing all pending
150 // messages. This method may only be called on the same thread that called
151 // Run, and Run must still be on the call stack.
153 // Use QuitTask if you need to Quit another thread's MessageLoop, but note
154 // that doing so is fairly dangerous if the target thread makes nested calls
155 // to MessageLoop::Run. The problem being that you won't know which nested
156 // run loop you are quiting, so be careful!
158 void Quit();
160 // Invokes Quit on the current MessageLoop when run. Useful to schedule an
161 // arbitrary MessageLoop to Quit.
162 class QuitTask : public Task {
163 public:
164 virtual void Run() {
165 MessageLoop::current()->Quit();
169 // A MessageLoop has a particular type, which indicates the set of
170 // asynchronous events it may process in addition to tasks and timers.
172 // TYPE_DEFAULT
173 // This type of ML only supports tasks and timers.
175 // TYPE_UI
176 // This type of ML also supports native UI events (e.g., Windows messages).
177 // See also MessageLoopForUI.
179 // TYPE_IO
180 // This type of ML also supports asynchronous IO. See also
181 // MessageLoopForIO.
183 enum Type {
184 TYPE_DEFAULT,
185 TYPE_UI,
186 TYPE_IO
189 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
190 // is typical to make use of the current thread's MessageLoop instance.
191 explicit MessageLoop(Type type = TYPE_DEFAULT);
192 ~MessageLoop();
194 // Returns the type passed to the constructor.
195 Type type() const { return type_; }
197 // Optional call to connect the thread name with this loop.
198 void set_thread_name(const std::string& thread_name) {
199 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
200 thread_name_ = thread_name;
202 const std::string& thread_name() const { return thread_name_; }
204 // Returns the MessageLoop object for the current thread, or null if none.
205 static MessageLoop* current();
207 // Enables or disables the recursive task processing. This happens in the case
208 // of recursive message loops. Some unwanted message loop may occurs when
209 // using common controls or printer functions. By default, recursive task
210 // processing is disabled.
212 // The specific case where tasks get queued is:
213 // - The thread is running a message loop.
214 // - It receives a task #1 and execute it.
215 // - The task #1 implicitly start a message loop, like a MessageBox in the
216 // unit test. This can also be StartDoc or GetSaveFileName.
217 // - The thread receives a task #2 before or while in this second message
218 // loop.
219 // - With NestableTasksAllowed set to true, the task #2 will run right away.
220 // Otherwise, it will get executed right after task #1 completes at "thread
221 // message loop level".
222 void SetNestableTasksAllowed(bool allowed);
223 bool NestableTasksAllowed() const;
225 // Enables or disables the restoration during an exception of the unhandled
226 // exception filter that was active when Run() was called. This can happen
227 // if some third party code call SetUnhandledExceptionFilter() and never
228 // restores the previous filter.
229 void set_exception_restoration(bool restore) {
230 exception_restoration_ = restore;
233 //----------------------------------------------------------------------------
234 protected:
235 struct RunState {
236 // Used to count how many Run() invocations are on the stack.
237 int run_depth;
239 // Used to record that Quit() was called, or that we should quit the pump
240 // once it becomes idle.
241 bool quit_received;
243 #if defined(OS_WIN)
244 base::MessagePumpWin::Dispatcher* dispatcher;
245 #endif
248 class AutoRunState : RunState {
249 public:
250 AutoRunState(MessageLoop* loop);
251 ~AutoRunState();
252 private:
253 MessageLoop* loop_;
254 RunState* previous_state_;
257 // This structure is copied around by value.
258 struct PendingTask {
259 Task* task; // The task to run.
260 Time delayed_run_time; // The time when the task should be run.
261 int sequence_num; // Used to facilitate sorting by run time.
262 bool nestable; // True if OK to dispatch from a nested loop.
264 PendingTask(Task* task, bool nestable)
265 : task(task), sequence_num(0), nestable(nestable) {
268 // Used to support sorting.
269 bool operator<(const PendingTask& other) const;
272 typedef std::queue<PendingTask> TaskQueue;
273 typedef std::priority_queue<PendingTask> DelayedTaskQueue;
275 #if defined(OS_WIN)
276 base::MessagePumpWin* pump_win() {
277 return static_cast<base::MessagePumpWin*>(pump_.get());
279 #elif defined(OS_POSIX)
280 base::MessagePumpLibevent* pump_libevent() {
281 return static_cast<base::MessagePumpLibevent*>(pump_.get());
283 #endif
285 // A function to encapsulate all the exception handling capability in the
286 // stacks around the running of a main message loop. It will run the message
287 // loop in a SEH try block or not depending on the set_SEH_restoration()
288 // flag.
289 void RunHandler();
291 // A surrounding stack frame around the running of the message loop that
292 // supports all saving and restoring of state, as is needed for any/all (ugly)
293 // recursive calls.
294 void RunInternal();
296 // Called to process any delayed non-nestable tasks.
297 bool ProcessNextDelayedNonNestableTask();
299 //----------------------------------------------------------------------------
300 // Run a work_queue_ task or new_task, and delete it (if it was processed by
301 // PostTask). If there are queued tasks, the oldest one is executed and
302 // new_task is queued. new_task is optional and can be NULL. In this NULL
303 // case, the method will run one pending task (if any exist). Returns true if
304 // it executes a task. Queued tasks accumulate only when there is a
305 // non-nestable task currently processing, in which case the new_task is
306 // appended to the list work_queue_. Such re-entrancy generally happens when
307 // an unrequested message pump (typical of a native dialog) is executing in
308 // the context of a task.
309 bool QueueOrRunTask(Task* new_task);
311 // Runs the specified task and deletes it.
312 void RunTask(Task* task);
314 // Calls RunTask or queues the pending_task on the deferred task list if it
315 // cannot be run right now. Returns true if the task was run.
316 bool DeferOrRunPendingTask(const PendingTask& pending_task);
318 // Adds the pending task to delayed_work_queue_.
319 void AddToDelayedWorkQueue(const PendingTask& pending_task);
321 // Load tasks from the incoming_queue_ into work_queue_ if the latter is
322 // empty. The former requires a lock to access, while the latter is directly
323 // accessible on this thread.
324 void ReloadWorkQueue();
326 // Delete tasks that haven't run yet without running them. Used in the
327 // destructor to make sure all the task's destructors get called. Returns
328 // true if some work was done.
329 bool DeletePendingTasks();
331 // Post a task to our incomming queue.
332 void PostTask_Helper(const tracked_objects::Location& from_here, Task* task,
333 int delay_ms, bool nestable);
335 // base::MessagePump::Delegate methods:
336 virtual bool DoWork();
337 virtual bool DoDelayedWork(Time* next_delayed_work_time);
338 virtual bool DoIdleWork();
340 // Start recording histogram info about events and action IF it was enabled
341 // and IF the statistics recorder can accept a registration of our histogram.
342 void StartHistogrammer();
344 // Add occurence of event to our histogram, so that we can see what is being
345 // done in a specific MessageLoop instance (i.e., specific thread).
346 // If message_histogram_ is NULL, this is a no-op.
347 void HistogramEvent(int event);
349 static const LinearHistogram::DescriptionPair event_descriptions_[];
350 static bool enable_histogrammer_;
352 Type type_;
354 // A list of tasks that need to be processed by this instance. Note that
355 // this queue is only accessed (push/pop) by our current thread.
356 TaskQueue work_queue_;
358 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
359 DelayedTaskQueue delayed_work_queue_;
361 // A queue of non-nestable tasks that we had to defer because when it came
362 // time to execute them we were in a nested message loop. They will execute
363 // once we're out of nested message loops.
364 TaskQueue deferred_non_nestable_work_queue_;
366 scoped_refptr<base::MessagePump> pump_;
368 ObserverList<DestructionObserver> destruction_observers_;
370 // A recursion block that prevents accidentally running additonal tasks when
371 // insider a (accidentally induced?) nested message pump.
372 bool nestable_tasks_allowed_;
374 bool exception_restoration_;
376 std::string thread_name_;
377 // A profiling histogram showing the counts of various messages and events.
378 scoped_ptr<LinearHistogram> message_histogram_;
380 // A null terminated list which creates an incoming_queue of tasks that are
381 // aquired under a mutex for processing on this instance's thread. These tasks
382 // have not yet been sorted out into items for our work_queue_ vs items that
383 // will be handled by the TimerManager.
384 TaskQueue incoming_queue_;
385 // Protect access to incoming_queue_.
386 Lock incoming_queue_lock_;
388 RunState* state_;
390 // The next sequence number to use for delayed tasks.
391 int next_sequence_num_;
393 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
396 //-----------------------------------------------------------------------------
397 // MessageLoopForUI extends MessageLoop with methods that are particular to a
398 // MessageLoop instantiated with TYPE_UI.
400 // This class is typically used like so:
401 // MessageLoopForUI::current()->...call some method...
403 class MessageLoopForUI : public MessageLoop {
404 public:
405 MessageLoopForUI() : MessageLoop(TYPE_UI) {
408 // Returns the MessageLoopForUI of the current thread.
409 static MessageLoopForUI* current() {
410 MessageLoop* loop = MessageLoop::current();
411 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
412 return static_cast<MessageLoopForUI*>(loop);
415 #if defined(OS_WIN)
416 typedef base::MessagePumpWin::Dispatcher Dispatcher;
417 typedef base::MessagePumpWin::Observer Observer;
419 // Please see MessagePumpWin for definitions of these methods.
420 void Run(Dispatcher* dispatcher);
421 void AddObserver(Observer* observer);
422 void RemoveObserver(Observer* observer);
423 void WillProcessMessage(const MSG& message);
424 void DidProcessMessage(const MSG& message);
425 void PumpOutPendingPaintMessages();
427 protected:
428 // TODO(rvargas): Make this platform independent.
429 base::MessagePumpWin* pump_ui() {
430 return static_cast<base::MessagePumpForUI*>(pump_.get());
432 #endif // defined(OS_WIN)
435 // Do not add any member variables to MessageLoopForUI! This is important b/c
436 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
437 // data that you need should be stored on the MessageLoop's pump_ instance.
438 COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
439 MessageLoopForUI_should_not_have_extra_member_variables);
441 //-----------------------------------------------------------------------------
442 // MessageLoopForIO extends MessageLoop with methods that are particular to a
443 // MessageLoop instantiated with TYPE_IO.
445 // This class is typically used like so:
446 // MessageLoopForIO::current()->...call some method...
448 class MessageLoopForIO : public MessageLoop {
449 public:
450 MessageLoopForIO() : MessageLoop(TYPE_IO) {
453 // Returns the MessageLoopForIO of the current thread.
454 static MessageLoopForIO* current() {
455 MessageLoop* loop = MessageLoop::current();
456 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
457 return static_cast<MessageLoopForIO*>(loop);
460 #if defined(OS_WIN)
461 typedef base::MessagePumpForIO::Watcher Watcher;
463 // Please see MessagePumpWin for definitions of these methods.
464 void WatchObject(HANDLE object, Watcher* watcher);
466 protected:
467 // TODO(rvargas): Make this platform independent.
468 base::MessagePumpForIO* pump_io() {
469 return static_cast<base::MessagePumpForIO*>(pump_.get());
472 #elif defined(OS_POSIX)
473 typedef base::MessagePumpLibevent::Watcher Watcher;
475 // Please see MessagePumpLibevent for definitions of these methods.
476 void WatchSocket(int socket, short interest_mask,
477 struct event* e, Watcher* watcher);
478 void UnwatchSocket(struct event* e);
479 #endif // defined(OS_POSIX)
482 // Do not add any member variables to MessageLoopForIO! This is important b/c
483 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
484 // data that you need should be stored on the MessageLoop's pump_ instance.
485 COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
486 MessageLoopForIO_should_not_have_extra_member_variables);
488 #endif // BASE_MESSAGE_LOOP_H_