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