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