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