message_loop.h revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
1// 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" 16#include "base/message_loop/message_loop_proxy.h" 17#include "base/message_loop/message_pump.h" 18#include "base/observer_list.h" 19#include "base/pending_task.h" 20#include "base/sequenced_task_runner_helpers.h" 21#include "base/synchronization/lock.h" 22#include "base/time/time.h" 23#include "base/tracking_info.h" 24 25#if defined(OS_WIN) 26// We need this to declare base::MessagePumpWin::Dispatcher, which we should 27// really just eliminate. 28#include "base/message_loop/message_pump_win.h" 29#elif defined(OS_IOS) 30#include "base/message_loop/message_pump_io_ios.h" 31#elif defined(OS_POSIX) 32#include "base/message_loop/message_pump_libevent.h" 33#if !defined(OS_MACOSX) && !defined(OS_ANDROID) 34 35#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_NACL) 36#include "base/message_loop/message_pump_aurax11.h" 37#elif defined(USE_OZONE) && !defined(OS_NACL) 38#include "base/message_loop/message_pump_ozone.h" 39#else 40#include "base/message_loop/message_pump_gtk.h" 41#endif 42 43#endif 44#endif 45 46namespace base { 47 48class HistogramBase; 49class MessageLoopLockTest; 50class RunLoop; 51class ThreadTaskRunnerHandle; 52#if defined(OS_ANDROID) 53class MessagePumpForUI; 54#endif 55 56// A MessageLoop is used to process events for a particular thread. There is 57// at most one MessageLoop instance per thread. 58// 59// Events include at a minimum Task instances submitted to PostTask and its 60// variants. Depending on the type of message pump used by the MessageLoop 61// other events such as UI messages may be processed. On Windows APC calls (as 62// time permits) and signals sent to a registered set of HANDLEs may also be 63// processed. 64// 65// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called 66// on the thread where the MessageLoop's Run method executes. 67// 68// NOTE: MessageLoop has task reentrancy protection. This means that if a 69// task is being processed, a second task cannot start until the first task is 70// finished. Reentrancy can happen when processing a task, and an inner 71// message pump is created. That inner pump then processes native messages 72// which could implicitly start an inner task. Inner message pumps are created 73// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions 74// (DoDragDrop), printer functions (StartDoc) and *many* others. 75// 76// Sample workaround when inner task processing is needed: 77// HRESULT hr; 78// { 79// MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current()); 80// hr = DoDragDrop(...); // Implicitly runs a modal message loop. 81// } 82// // Process |hr| (the result returned by DoDragDrop()). 83// 84// Please be SURE your task is reentrant (nestable) and all global variables 85// are stable and accessible before calling SetNestableTasksAllowed(true). 86// 87class BASE_EXPORT MessageLoop : public MessagePump::Delegate { 88 public: 89 90#if !defined(OS_MACOSX) && !defined(OS_ANDROID) 91 typedef MessagePumpDispatcher Dispatcher; 92 typedef MessagePumpObserver Observer; 93#endif 94 95 // A MessageLoop has a particular type, which indicates the set of 96 // asynchronous events it may process in addition to tasks and timers. 97 // 98 // TYPE_DEFAULT 99 // This type of ML only supports tasks and timers. 100 // 101 // TYPE_UI 102 // This type of ML also supports native UI events (e.g., Windows messages). 103 // See also MessageLoopForUI. 104 // 105 // TYPE_IO 106 // This type of ML also supports asynchronous IO. See also 107 // MessageLoopForIO. 108 // 109 enum Type { 110 TYPE_DEFAULT, 111 TYPE_UI, 112 TYPE_IO 113 }; 114 115 // Normally, it is not necessary to instantiate a MessageLoop. Instead, it 116 // is typical to make use of the current thread's MessageLoop instance. 117 explicit MessageLoop(Type type = TYPE_DEFAULT); 118 virtual ~MessageLoop(); 119 120 // Returns the MessageLoop object for the current thread, or null if none. 121 static MessageLoop* current(); 122 123 static void EnableHistogrammer(bool enable_histogrammer); 124 125 typedef MessagePump* (MessagePumpFactory)(); 126 // Uses the given base::MessagePumpForUIFactory to override the default 127 // MessagePump implementation for 'TYPE_UI'. Returns true if the factory 128 // was successfully registered. 129 static bool InitMessagePumpForUIFactory(MessagePumpFactory* factory); 130 131 // A DestructionObserver is notified when the current MessageLoop is being 132 // destroyed. These observers are notified prior to MessageLoop::current() 133 // being changed to return NULL. This gives interested parties the chance to 134 // do final cleanup that depends on the MessageLoop. 135 // 136 // NOTE: Any tasks posted to the MessageLoop during this notification will 137 // not be run. Instead, they will be deleted. 138 // 139 class BASE_EXPORT DestructionObserver { 140 public: 141 virtual void WillDestroyCurrentMessageLoop() = 0; 142 143 protected: 144 virtual ~DestructionObserver(); 145 }; 146 147 // Add a DestructionObserver, which will start receiving notifications 148 // immediately. 149 void AddDestructionObserver(DestructionObserver* destruction_observer); 150 151 // Remove a DestructionObserver. It is safe to call this method while a 152 // DestructionObserver is receiving a notification callback. 153 void RemoveDestructionObserver(DestructionObserver* destruction_observer); 154 155 // The "PostTask" family of methods call the task's Run method asynchronously 156 // from within a message loop at some point in the future. 157 // 158 // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed 159 // with normal UI or IO event processing. With the PostDelayedTask variant, 160 // tasks are called after at least approximately 'delay_ms' have elapsed. 161 // 162 // The NonNestable variants work similarly except that they promise never to 163 // dispatch the task from a nested invocation of MessageLoop::Run. Instead, 164 // such tasks get deferred until the top-most MessageLoop::Run is executing. 165 // 166 // The MessageLoop takes ownership of the Task, and deletes it after it has 167 // been Run(). 168 // 169 // PostTask(from_here, task) is equivalent to 170 // PostDelayedTask(from_here, task, 0). 171 // 172 // The TryPostTask is meant for the cases where the calling thread cannot 173 // block. If posting the task will block, the call returns false, the task 174 // is not posted but the task is consumed anyways. 175 // 176 // NOTE: These methods may be called on any thread. The Task will be invoked 177 // on the thread that executes MessageLoop::Run(). 178 void PostTask(const tracked_objects::Location& from_here, 179 const Closure& task); 180 181 bool TryPostTask(const tracked_objects::Location& from_here, 182 const Closure& task); 183 184 void PostDelayedTask(const tracked_objects::Location& from_here, 185 const Closure& task, 186 TimeDelta delay); 187 188 void PostNonNestableTask(const tracked_objects::Location& from_here, 189 const Closure& task); 190 191 void PostNonNestableDelayedTask(const tracked_objects::Location& from_here, 192 const Closure& task, 193 TimeDelta delay); 194 195 // A variant on PostTask that deletes the given object. This is useful 196 // if the object needs to live until the next run of the MessageLoop (for 197 // example, deleting a RenderProcessHost from within an IPC callback is not 198 // good). 199 // 200 // NOTE: This method may be called on any thread. The object will be deleted 201 // on the thread that executes MessageLoop::Run(). If this is not the same 202 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit 203 // from RefCountedThreadSafe<T>! 204 template <class T> 205 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) { 206 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner( 207 this, from_here, object); 208 } 209 210 // A variant on PostTask that releases the given reference counted object 211 // (by calling its Release method). This is useful if the object needs to 212 // live until the next run of the MessageLoop, or if the object needs to be 213 // released on a particular thread. 214 // 215 // NOTE: This method may be called on any thread. The object will be 216 // released (and thus possibly deleted) on the thread that executes 217 // MessageLoop::Run(). If this is not the same as the thread that calls 218 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from 219 // RefCountedThreadSafe<T>! 220 template <class T> 221 void ReleaseSoon(const tracked_objects::Location& from_here, 222 const T* object) { 223 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner( 224 this, from_here, object); 225 } 226 227 // Deprecated: use RunLoop instead. 228 // Run the message loop. 229 void Run(); 230 231 // Deprecated: use RunLoop instead. 232 // Process all pending tasks, windows messages, etc., but don't wait/sleep. 233 // Return as soon as all items that can be run are taken care of. 234 void RunUntilIdle(); 235 236 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle(). 237 void Quit() { QuitWhenIdle(); } 238 239 // Deprecated: use RunLoop instead. 240 // 241 // Signals the Run method to return when it becomes idle. It will continue to 242 // process pending messages and future messages as long as they are enqueued. 243 // Warning: if the MessageLoop remains busy, it may never quit. Only use this 244 // Quit method when looping procedures (such as web pages) have been shut 245 // down. 246 // 247 // This method may only be called on the same thread that called Run, and Run 248 // must still be on the call stack. 249 // 250 // Use QuitClosure variants if you need to Quit another thread's MessageLoop, 251 // but note that doing so is fairly dangerous if the target thread makes 252 // nested calls to MessageLoop::Run. The problem being that you won't know 253 // which nested run loop you are quitting, so be careful! 254 void QuitWhenIdle(); 255 256 // Deprecated: use RunLoop instead. 257 // 258 // This method is a variant of Quit, that does not wait for pending messages 259 // to be processed before returning from Run. 260 void QuitNow(); 261 262 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure(). 263 static Closure QuitClosure() { return QuitWhenIdleClosure(); } 264 265 // Deprecated: use RunLoop instead. 266 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an 267 // arbitrary MessageLoop to QuitWhenIdle. 268 static Closure QuitWhenIdleClosure(); 269 270 // Returns true if this loop is |type|. This allows subclasses (especially 271 // those in tests) to specialize how they are identified. 272 virtual bool IsType(Type type) const; 273 274 // Returns the type passed to the constructor. 275 Type type() const { return type_; } 276 277 // Optional call to connect the thread name with this loop. 278 void set_thread_name(const std::string& thread_name) { 279 DCHECK(thread_name_.empty()) << "Should not rename this thread!"; 280 thread_name_ = thread_name; 281 } 282 const std::string& thread_name() const { return thread_name_; } 283 284 // Gets the message loop proxy associated with this message loop. 285 scoped_refptr<MessageLoopProxy> message_loop_proxy() { 286 return message_loop_proxy_.get(); 287 } 288 289 // Enables or disables the recursive task processing. This happens in the case 290 // of recursive message loops. Some unwanted message loop may occurs when 291 // using common controls or printer functions. By default, recursive task 292 // processing is disabled. 293 // 294 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods 295 // directly. In general nestable message loops are to be avoided. They are 296 // dangerous and difficult to get right, so please use with extreme caution. 297 // 298 // The specific case where tasks get queued is: 299 // - The thread is running a message loop. 300 // - It receives a task #1 and execute it. 301 // - The task #1 implicitly start a message loop, like a MessageBox in the 302 // unit test. This can also be StartDoc or GetSaveFileName. 303 // - The thread receives a task #2 before or while in this second message 304 // loop. 305 // - With NestableTasksAllowed set to true, the task #2 will run right away. 306 // Otherwise, it will get executed right after task #1 completes at "thread 307 // message loop level". 308 void SetNestableTasksAllowed(bool allowed); 309 bool NestableTasksAllowed() const; 310 311 // Enables nestable tasks on |loop| while in scope. 312 class ScopedNestableTaskAllower { 313 public: 314 explicit ScopedNestableTaskAllower(MessageLoop* loop) 315 : loop_(loop), 316 old_state_(loop_->NestableTasksAllowed()) { 317 loop_->SetNestableTasksAllowed(true); 318 } 319 ~ScopedNestableTaskAllower() { 320 loop_->SetNestableTasksAllowed(old_state_); 321 } 322 323 private: 324 MessageLoop* loop_; 325 bool old_state_; 326 }; 327 328 // Enables or disables the restoration during an exception of the unhandled 329 // exception filter that was active when Run() was called. This can happen 330 // if some third party code call SetUnhandledExceptionFilter() and never 331 // restores the previous filter. 332 void set_exception_restoration(bool restore) { 333 exception_restoration_ = restore; 334 } 335 336 // Returns true if we are currently running a nested message loop. 337 bool IsNested(); 338 339 // A TaskObserver is an object that receives task notifications from the 340 // MessageLoop. 341 // 342 // NOTE: A TaskObserver implementation should be extremely fast! 343 class BASE_EXPORT TaskObserver { 344 public: 345 TaskObserver(); 346 347 // This method is called before processing a task. 348 virtual void WillProcessTask(const PendingTask& pending_task) = 0; 349 350 // This method is called after processing a task. 351 virtual void DidProcessTask(const PendingTask& pending_task) = 0; 352 353 protected: 354 virtual ~TaskObserver(); 355 }; 356 357 // These functions can only be called on the same thread that |this| is 358 // running on. 359 void AddTaskObserver(TaskObserver* task_observer); 360 void RemoveTaskObserver(TaskObserver* task_observer); 361 362 // Returns true if the message loop has high resolution timers enabled. 363 // Provided for testing. 364 bool high_resolution_timers_enabled() { 365#if defined(OS_WIN) 366 return !high_resolution_timer_expiration_.is_null(); 367#else 368 return true; 369#endif 370 } 371 372 // When we go into high resolution timer mode, we will stay in hi-res mode 373 // for at least 1s. 374 static const int kHighResolutionTimerModeLeaseTimeMs = 1000; 375 376 // Asserts that the MessageLoop is "idle". 377 void AssertIdle() const; 378 379#if defined(OS_WIN) 380 void set_os_modal_loop(bool os_modal_loop) { 381 os_modal_loop_ = os_modal_loop; 382 } 383 384 bool os_modal_loop() const { 385 return os_modal_loop_; 386 } 387#endif // OS_WIN 388 389 // Can only be called from the thread that owns the MessageLoop. 390 bool is_running() const; 391 392 //---------------------------------------------------------------------------- 393 protected: 394 395#if defined(OS_WIN) 396 MessagePumpWin* pump_win() { 397 return static_cast<MessagePumpWin*>(pump_.get()); 398 } 399#elif defined(OS_POSIX) && !defined(OS_IOS) 400 MessagePumpLibevent* pump_libevent() { 401 return static_cast<MessagePumpLibevent*>(pump_.get()); 402 } 403#endif 404 405 scoped_refptr<MessagePump> pump_; 406 407 private: 408 friend class RunLoop; 409 friend class MessageLoopLockTest; 410 411 // A function to encapsulate all the exception handling capability in the 412 // stacks around the running of a main message loop. It will run the message 413 // loop in a SEH try block or not depending on the set_SEH_restoration() 414 // flag invoking respectively RunInternalInSEHFrame() or RunInternal(). 415 void RunHandler(); 416 417#if defined(OS_WIN) 418 __declspec(noinline) void RunInternalInSEHFrame(); 419#endif 420 421 // A surrounding stack frame around the running of the message loop that 422 // supports all saving and restoring of state, as is needed for any/all (ugly) 423 // recursive calls. 424 void RunInternal(); 425 426 // Called to process any delayed non-nestable tasks. 427 bool ProcessNextDelayedNonNestableTask(); 428 429 // Runs the specified PendingTask. 430 void RunTask(const PendingTask& pending_task); 431 432 // Calls RunTask or queues the pending_task on the deferred task list if it 433 // cannot be run right now. Returns true if the task was run. 434 bool DeferOrRunPendingTask(const PendingTask& pending_task); 435 436 // Adds the pending task to delayed_work_queue_. 437 void AddToDelayedWorkQueue(const PendingTask& pending_task); 438 439 // This function attempts to add pending task to our incoming_queue_. 440 // The append can only possibly fail when |use_try_lock| is true. 441 // 442 // When |use_try_lock| is true, then this call will avoid blocking if 443 // the related lock is already held, and will in that case (when the 444 // lock is contended) fail to perform the append, and will return false. 445 // 446 // If the call succeeds to append to the queue, then this call 447 // will return true. 448 // 449 // In all cases, the caller retains ownership of |pending_task|, but this 450 // function will reset the value of pending_task->task. This is needed to 451 // ensure that the posting call stack does not retain pending_task->task 452 // beyond this function call. 453 bool AddToIncomingQueue(PendingTask* pending_task, bool use_try_lock); 454 455 // Load tasks from the incoming_queue_ into work_queue_ if the latter is 456 // empty. The former requires a lock to access, while the latter is directly 457 // accessible on this thread. 458 void ReloadWorkQueue(); 459 460 // Delete tasks that haven't run yet without running them. Used in the 461 // destructor to make sure all the task's destructors get called. Returns 462 // true if some work was done. 463 bool DeletePendingTasks(); 464 465 // Calculates the time at which a PendingTask should run. 466 TimeTicks CalculateDelayedRuntime(TimeDelta delay); 467 468 // Start recording histogram info about events and action IF it was enabled 469 // and IF the statistics recorder can accept a registration of our histogram. 470 void StartHistogrammer(); 471 472 // Add occurrence of event to our histogram, so that we can see what is being 473 // done in a specific MessageLoop instance (i.e., specific thread). 474 // If message_histogram_ is NULL, this is a no-op. 475 void HistogramEvent(int event); 476 477 // MessagePump::Delegate methods: 478 virtual bool DoWork() OVERRIDE; 479 virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) OVERRIDE; 480 virtual bool DoIdleWork() OVERRIDE; 481 482 Type type_; 483 484 // A list of tasks that need to be processed by this instance. Note that 485 // this queue is only accessed (push/pop) by our current thread. 486 TaskQueue work_queue_; 487 488 // Contains delayed tasks, sorted by their 'delayed_run_time' property. 489 DelayedTaskQueue delayed_work_queue_; 490 491 // A recent snapshot of Time::Now(), used to check delayed_work_queue_. 492 TimeTicks recent_time_; 493 494 // A queue of non-nestable tasks that we had to defer because when it came 495 // time to execute them we were in a nested message loop. They will execute 496 // once we're out of nested message loops. 497 TaskQueue deferred_non_nestable_work_queue_; 498 499 ObserverList<DestructionObserver> destruction_observers_; 500 501 // A recursion block that prevents accidentally running additional tasks when 502 // insider a (accidentally induced?) nested message pump. 503 bool nestable_tasks_allowed_; 504 505 bool exception_restoration_; 506 507 std::string thread_name_; 508 // A profiling histogram showing the counts of various messages and events. 509 HistogramBase* message_histogram_; 510 511 // An incoming queue of tasks that are acquired under a mutex for processing 512 // on this instance's thread. These tasks have not yet been sorted out into 513 // items for our work_queue_ vs delayed_work_queue_. 514 TaskQueue incoming_queue_; 515 // Protect access to incoming_queue_. 516 mutable Lock incoming_queue_lock_; 517 518 RunLoop* run_loop_; 519 520#if defined(OS_WIN) 521 TimeTicks high_resolution_timer_expiration_; 522 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc 523 // which enter a modal message loop. 524 bool os_modal_loop_; 525#endif 526 527 // The next sequence number to use for delayed tasks. Updating this counter is 528 // protected by incoming_queue_lock_. 529 int next_sequence_num_; 530 531 ObserverList<TaskObserver> task_observers_; 532 533 // The message loop proxy associated with this message loop, if one exists. 534 scoped_refptr<MessageLoopProxy> message_loop_proxy_; 535 scoped_ptr<ThreadTaskRunnerHandle> thread_task_runner_handle_; 536 537 template <class T, class R> friend class base::subtle::DeleteHelperInternal; 538 template <class T, class R> friend class base::subtle::ReleaseHelperInternal; 539 540 void DeleteSoonInternal(const tracked_objects::Location& from_here, 541 void(*deleter)(const void*), 542 const void* object); 543 void ReleaseSoonInternal(const tracked_objects::Location& from_here, 544 void(*releaser)(const void*), 545 const void* object); 546 547 DISALLOW_COPY_AND_ASSIGN(MessageLoop); 548}; 549 550//----------------------------------------------------------------------------- 551// MessageLoopForUI extends MessageLoop with methods that are particular to a 552// MessageLoop instantiated with TYPE_UI. 553// 554// This class is typically used like so: 555// MessageLoopForUI::current()->...call some method... 556// 557class BASE_EXPORT MessageLoopForUI : public MessageLoop { 558 public: 559#if defined(OS_WIN) 560 typedef MessagePumpForUI::MessageFilter MessageFilter; 561#endif 562 563 MessageLoopForUI() : MessageLoop(TYPE_UI) { 564 } 565 566 // Returns the MessageLoopForUI of the current thread. 567 static MessageLoopForUI* current() { 568 MessageLoop* loop = MessageLoop::current(); 569 DCHECK(loop); 570 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type()); 571 return static_cast<MessageLoopForUI*>(loop); 572 } 573 574#if defined(OS_WIN) 575 void DidProcessMessage(const MSG& message); 576#endif // defined(OS_WIN) 577 578#if defined(OS_IOS) 579 // On iOS, the main message loop cannot be Run(). Instead call Attach(), 580 // which connects this MessageLoop to the UI thread's CFRunLoop and allows 581 // PostTask() to work. 582 void Attach(); 583#endif 584 585#if defined(OS_ANDROID) 586 // On Android, the UI message loop is handled by Java side. So Run() should 587 // never be called. Instead use Start(), which will forward all the native UI 588 // events to the Java message loop. 589 void Start(); 590#elif !defined(OS_MACOSX) 591 592 // Please see message_pump_win/message_pump_glib for definitions of these 593 // methods. 594 void AddObserver(Observer* observer); 595 void RemoveObserver(Observer* observer); 596 597#if defined(OS_WIN) 598 // Plese see MessagePumpForUI for definitions of this method. 599 void SetMessageFilter(scoped_ptr<MessageFilter> message_filter) { 600 pump_ui()->SetMessageFilter(message_filter.Pass()); 601 } 602#endif 603 604 protected: 605#if defined(USE_AURA) && defined(USE_X11) && !defined(OS_NACL) 606 friend class MessagePumpAuraX11; 607#endif 608#if defined(USE_OZONE) && !defined(OS_NACL) 609 friend class MessagePumpOzone; 610#endif 611 612 // TODO(rvargas): Make this platform independent. 613 MessagePumpForUI* pump_ui() { 614 return static_cast<MessagePumpForUI*>(pump_.get()); 615 } 616#endif // !defined(OS_MACOSX) 617}; 618 619// Do not add any member variables to MessageLoopForUI! This is important b/c 620// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra 621// data that you need should be stored on the MessageLoop's pump_ instance. 622COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI), 623 MessageLoopForUI_should_not_have_extra_member_variables); 624 625//----------------------------------------------------------------------------- 626// MessageLoopForIO extends MessageLoop with methods that are particular to a 627// MessageLoop instantiated with TYPE_IO. 628// 629// This class is typically used like so: 630// MessageLoopForIO::current()->...call some method... 631// 632class BASE_EXPORT MessageLoopForIO : public MessageLoop { 633 public: 634#if defined(OS_WIN) 635 typedef MessagePumpForIO::IOHandler IOHandler; 636 typedef MessagePumpForIO::IOContext IOContext; 637 typedef MessagePumpForIO::IOObserver IOObserver; 638#elif defined(OS_IOS) 639 typedef MessagePumpIOSForIO::Watcher Watcher; 640 typedef MessagePumpIOSForIO::FileDescriptorWatcher 641 FileDescriptorWatcher; 642 typedef MessagePumpIOSForIO::IOObserver IOObserver; 643 644 enum Mode { 645 WATCH_READ = MessagePumpIOSForIO::WATCH_READ, 646 WATCH_WRITE = MessagePumpIOSForIO::WATCH_WRITE, 647 WATCH_READ_WRITE = MessagePumpIOSForIO::WATCH_READ_WRITE 648 }; 649#elif defined(OS_POSIX) 650 typedef MessagePumpLibevent::Watcher Watcher; 651 typedef MessagePumpLibevent::FileDescriptorWatcher 652 FileDescriptorWatcher; 653 typedef MessagePumpLibevent::IOObserver IOObserver; 654 655 enum Mode { 656 WATCH_READ = MessagePumpLibevent::WATCH_READ, 657 WATCH_WRITE = MessagePumpLibevent::WATCH_WRITE, 658 WATCH_READ_WRITE = MessagePumpLibevent::WATCH_READ_WRITE 659 }; 660 661#endif 662 663 MessageLoopForIO() : MessageLoop(TYPE_IO) { 664 } 665 666 // Returns the MessageLoopForIO of the current thread. 667 static MessageLoopForIO* current() { 668 MessageLoop* loop = MessageLoop::current(); 669 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type()); 670 return static_cast<MessageLoopForIO*>(loop); 671 } 672 673 void AddIOObserver(IOObserver* io_observer) { 674 pump_io()->AddIOObserver(io_observer); 675 } 676 677 void RemoveIOObserver(IOObserver* io_observer) { 678 pump_io()->RemoveIOObserver(io_observer); 679 } 680 681#if defined(OS_WIN) 682 // Please see MessagePumpWin for definitions of these methods. 683 void RegisterIOHandler(HANDLE file, IOHandler* handler); 684 bool RegisterJobObject(HANDLE job, IOHandler* handler); 685 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter); 686 687 protected: 688 // TODO(rvargas): Make this platform independent. 689 MessagePumpForIO* pump_io() { 690 return static_cast<MessagePumpForIO*>(pump_.get()); 691 } 692 693#elif defined(OS_IOS) 694 // Please see MessagePumpIOSForIO for definition. 695 bool WatchFileDescriptor(int fd, 696 bool persistent, 697 Mode mode, 698 FileDescriptorWatcher *controller, 699 Watcher *delegate); 700 701 private: 702 MessagePumpIOSForIO* pump_io() { 703 return static_cast<MessagePumpIOSForIO*>(pump_.get()); 704 } 705 706#elif defined(OS_POSIX) 707 // Please see MessagePumpLibevent for definition. 708 bool WatchFileDescriptor(int fd, 709 bool persistent, 710 Mode mode, 711 FileDescriptorWatcher* controller, 712 Watcher* delegate); 713 714 private: 715 MessagePumpLibevent* pump_io() { 716 return static_cast<MessagePumpLibevent*>(pump_.get()); 717 } 718#endif // defined(OS_POSIX) 719}; 720 721// Do not add any member variables to MessageLoopForIO! This is important b/c 722// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra 723// data that you need should be stored on the MessageLoop's pump_ instance. 724COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO), 725 MessageLoopForIO_should_not_have_extra_member_variables); 726 727} // namespace base 728 729#endif // BASE_MESSAGE_LOOP_MESSAGE_LOOP_H_ 730