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