Add missing pnacl libraries and headers and tools.
[chromium-blink-merge.git] / base / message_loop.h
blob5013615b8cfb2161227928106eb5721dc19f097b
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_OZONE) && !defined(OS_NACL)
38 #include "base/message_pump_ozone.h"
39 #else
40 #include "base/message_pump_gtk.h"
41 #endif
43 #endif
44 #endif
46 namespace base {
47 class HistogramBase;
48 class MessageLoopLockTest;
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 // The TryPostTask is meant for the cases where the calling thread cannot
172 // block. If posting the task will block, the call returns false, the task
173 // is not posted but the task is consumed anyways.
175 // NOTE: These methods may be called on any thread. The Task will be invoked
176 // on the thread that executes MessageLoop::Run().
177 void PostTask(
178 const tracked_objects::Location& from_here,
179 const base::Closure& task);
181 bool TryPostTask(
182 const tracked_objects::Location& from_here,
183 const base::Closure& task);
185 void PostDelayedTask(
186 const tracked_objects::Location& from_here,
187 const base::Closure& task,
188 base::TimeDelta delay);
190 void PostNonNestableTask(
191 const tracked_objects::Location& from_here,
192 const base::Closure& task);
194 void PostNonNestableDelayedTask(
195 const tracked_objects::Location& from_here,
196 const base::Closure& task,
197 base::TimeDelta delay);
199 // A variant on PostTask that deletes the given object. This is useful
200 // if the object needs to live until the next run of the MessageLoop (for
201 // example, deleting a RenderProcessHost from within an IPC callback is not
202 // good).
204 // NOTE: This method may be called on any thread. The object will be deleted
205 // on the thread that executes MessageLoop::Run(). If this is not the same
206 // as the thread that calls PostDelayedTask(FROM_HERE, ), then T MUST inherit
207 // from RefCountedThreadSafe<T>!
208 template <class T>
209 void DeleteSoon(const tracked_objects::Location& from_here, const T* object) {
210 base::subtle::DeleteHelperInternal<T, void>::DeleteViaSequencedTaskRunner(
211 this, from_here, object);
214 // A variant on PostTask that releases the given reference counted object
215 // (by calling its Release method). This is useful if the object needs to
216 // live until the next run of the MessageLoop, or if the object needs to be
217 // released on a particular thread.
219 // NOTE: This method may be called on any thread. The object will be
220 // released (and thus possibly deleted) on the thread that executes
221 // MessageLoop::Run(). If this is not the same as the thread that calls
222 // PostDelayedTask(FROM_HERE, ), then T MUST inherit from
223 // RefCountedThreadSafe<T>!
224 template <class T>
225 void ReleaseSoon(const tracked_objects::Location& from_here,
226 const T* object) {
227 base::subtle::ReleaseHelperInternal<T, void>::ReleaseViaSequencedTaskRunner(
228 this, from_here, object);
231 // Deprecated: use RunLoop instead.
232 // Run the message loop.
233 void Run();
235 // Deprecated: use RunLoop instead.
236 // Process all pending tasks, windows messages, etc., but don't wait/sleep.
237 // Return as soon as all items that can be run are taken care of.
238 void RunUntilIdle();
240 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdle().
241 void Quit() { QuitWhenIdle(); }
243 // Deprecated: use RunLoop instead.
245 // Signals the Run method to return when it becomes idle. It will continue to
246 // process pending messages and future messages as long as they are enqueued.
247 // Warning: if the MessageLoop remains busy, it may never quit. Only use this
248 // Quit method when looping procedures (such as web pages) have been shut
249 // down.
251 // This method may only be called on the same thread that called Run, and Run
252 // must still be on the call stack.
254 // Use QuitClosure variants if you need to Quit another thread's MessageLoop,
255 // but note that doing so is fairly dangerous if the target thread makes
256 // nested calls to MessageLoop::Run. The problem being that you won't know
257 // which nested run loop you are quitting, so be careful!
258 void QuitWhenIdle();
260 // Deprecated: use RunLoop instead.
262 // This method is a variant of Quit, that does not wait for pending messages
263 // to be processed before returning from Run.
264 void QuitNow();
266 // TODO(jbates) remove this. crbug.com/131220. See QuitWhenIdleClosure().
267 static base::Closure QuitClosure() { return QuitWhenIdleClosure(); }
269 // Deprecated: use RunLoop instead.
270 // Construct a Closure that will call QuitWhenIdle(). Useful to schedule an
271 // arbitrary MessageLoop to QuitWhenIdle.
272 static base::Closure QuitWhenIdleClosure();
274 // Returns true if this loop is |type|. This allows subclasses (especially
275 // those in tests) to specialize how they are identified.
276 virtual bool IsType(Type type) const;
278 // Returns the type passed to the constructor.
279 Type type() const { return type_; }
281 // Optional call to connect the thread name with this loop.
282 void set_thread_name(const std::string& thread_name) {
283 DCHECK(thread_name_.empty()) << "Should not rename this thread!";
284 thread_name_ = thread_name;
286 const std::string& thread_name() const { return thread_name_; }
288 // Gets the message loop proxy associated with this message loop.
289 scoped_refptr<base::MessageLoopProxy> message_loop_proxy() {
290 return message_loop_proxy_.get();
293 // Enables or disables the recursive task processing. This happens in the case
294 // of recursive message loops. Some unwanted message loop may occurs when
295 // using common controls or printer functions. By default, recursive task
296 // processing is disabled.
298 // Please utilize |ScopedNestableTaskAllower| instead of calling these methods
299 // directly. In general nestable message loops are to be avoided. They are
300 // dangerous and difficult to get right, so please use with extreme caution.
302 // The specific case where tasks get queued is:
303 // - The thread is running a message loop.
304 // - It receives a task #1 and execute it.
305 // - The task #1 implicitly start a message loop, like a MessageBox in the
306 // unit test. This can also be StartDoc or GetSaveFileName.
307 // - The thread receives a task #2 before or while in this second message
308 // loop.
309 // - With NestableTasksAllowed set to true, the task #2 will run right away.
310 // Otherwise, it will get executed right after task #1 completes at "thread
311 // message loop level".
312 void SetNestableTasksAllowed(bool allowed);
313 bool NestableTasksAllowed() const;
315 // Enables nestable tasks on |loop| while in scope.
316 class ScopedNestableTaskAllower {
317 public:
318 explicit ScopedNestableTaskAllower(MessageLoop* loop)
319 : loop_(loop),
320 old_state_(loop_->NestableTasksAllowed()) {
321 loop_->SetNestableTasksAllowed(true);
323 ~ScopedNestableTaskAllower() {
324 loop_->SetNestableTasksAllowed(old_state_);
327 private:
328 MessageLoop* loop_;
329 bool old_state_;
332 // Enables or disables the restoration during an exception of the unhandled
333 // exception filter that was active when Run() was called. This can happen
334 // if some third party code call SetUnhandledExceptionFilter() and never
335 // restores the previous filter.
336 void set_exception_restoration(bool restore) {
337 exception_restoration_ = restore;
340 // Returns true if we are currently running a nested message loop.
341 bool IsNested();
343 // A TaskObserver is an object that receives task notifications from the
344 // MessageLoop.
346 // NOTE: A TaskObserver implementation should be extremely fast!
347 class BASE_EXPORT TaskObserver {
348 public:
349 TaskObserver();
351 // This method is called before processing a task.
352 virtual void WillProcessTask(const base::PendingTask& pending_task) = 0;
354 // This method is called after processing a task.
355 virtual void DidProcessTask(const base::PendingTask& pending_task) = 0;
357 protected:
358 virtual ~TaskObserver();
361 // These functions can only be called on the same thread that |this| is
362 // running on.
363 void AddTaskObserver(TaskObserver* task_observer);
364 void RemoveTaskObserver(TaskObserver* task_observer);
366 // Returns true if the message loop has high resolution timers enabled.
367 // Provided for testing.
368 bool high_resolution_timers_enabled() {
369 #if defined(OS_WIN)
370 return !high_resolution_timer_expiration_.is_null();
371 #else
372 return true;
373 #endif
376 // When we go into high resolution timer mode, we will stay in hi-res mode
377 // for at least 1s.
378 static const int kHighResolutionTimerModeLeaseTimeMs = 1000;
380 // Asserts that the MessageLoop is "idle".
381 void AssertIdle() const;
383 #if defined(OS_WIN)
384 void set_os_modal_loop(bool os_modal_loop) {
385 os_modal_loop_ = os_modal_loop;
388 bool os_modal_loop() const {
389 return os_modal_loop_;
391 #endif // OS_WIN
393 // Can only be called from the thread that owns the MessageLoop.
394 bool is_running() const;
396 //----------------------------------------------------------------------------
397 protected:
399 #if defined(OS_WIN)
400 base::MessagePumpWin* pump_win() {
401 return static_cast<base::MessagePumpWin*>(pump_.get());
403 #elif defined(OS_POSIX) && !defined(OS_IOS)
404 base::MessagePumpLibevent* pump_libevent() {
405 return static_cast<base::MessagePumpLibevent*>(pump_.get());
407 #endif
409 scoped_refptr<base::MessagePump> pump_;
411 private:
412 friend class base::RunLoop;
413 friend class base::MessageLoopLockTest;
415 // A function to encapsulate all the exception handling capability in the
416 // stacks around the running of a main message loop. It will run the message
417 // loop in a SEH try block or not depending on the set_SEH_restoration()
418 // flag invoking respectively RunInternalInSEHFrame() or RunInternal().
419 void RunHandler();
421 #if defined(OS_WIN)
422 __declspec(noinline) void RunInternalInSEHFrame();
423 #endif
425 // A surrounding stack frame around the running of the message loop that
426 // supports all saving and restoring of state, as is needed for any/all (ugly)
427 // recursive calls.
428 void RunInternal();
430 // Called to process any delayed non-nestable tasks.
431 bool ProcessNextDelayedNonNestableTask();
433 // Runs the specified PendingTask.
434 void RunTask(const base::PendingTask& pending_task);
436 // Calls RunTask or queues the pending_task on the deferred task list if it
437 // cannot be run right now. Returns true if the task was run.
438 bool DeferOrRunPendingTask(const base::PendingTask& pending_task);
440 // Adds the pending task to delayed_work_queue_.
441 void AddToDelayedWorkQueue(const base::PendingTask& pending_task);
443 // This function attempts to add pending task to our incoming_queue_.
444 // The append can only possibly fail when |use_try_lock| is true.
446 // When |use_try_lock| is true, then this call will avoid blocking if
447 // the related lock is already held, and will in that case (when the
448 // lock is contended) fail to perform the append, and will return false.
450 // If the call succeeds to append to the queue, then this call
451 // will return true.
453 // In all cases, the caller retains ownership of |pending_task|, but this
454 // function will reset the value of pending_task->task. This is needed to
455 // ensure that the posting call stack does not retain pending_task->task
456 // beyond this function call.
457 bool AddToIncomingQueue(base::PendingTask* pending_task, bool use_try_lock);
459 // Load tasks from the incoming_queue_ into work_queue_ if the latter is
460 // empty. The former requires a lock to access, while the latter is directly
461 // accessible on this thread.
462 void ReloadWorkQueue();
464 // Delete tasks that haven't run yet without running them. Used in the
465 // destructor to make sure all the task's destructors get called. Returns
466 // true if some work was done.
467 bool DeletePendingTasks();
469 // Calculates the time at which a PendingTask should run.
470 base::TimeTicks CalculateDelayedRuntime(base::TimeDelta delay);
472 // Start recording histogram info about events and action IF it was enabled
473 // and IF the statistics recorder can accept a registration of our histogram.
474 void StartHistogrammer();
476 // Add occurrence of event to our histogram, so that we can see what is being
477 // done in a specific MessageLoop instance (i.e., specific thread).
478 // If message_histogram_ is NULL, this is a no-op.
479 void HistogramEvent(int event);
481 // base::MessagePump::Delegate methods:
482 virtual bool DoWork() OVERRIDE;
483 virtual bool DoDelayedWork(base::TimeTicks* next_delayed_work_time) OVERRIDE;
484 virtual bool DoIdleWork() OVERRIDE;
486 Type type_;
488 // A list of tasks that need to be processed by this instance. Note that
489 // this queue is only accessed (push/pop) by our current thread.
490 base::TaskQueue work_queue_;
492 // Contains delayed tasks, sorted by their 'delayed_run_time' property.
493 base::DelayedTaskQueue delayed_work_queue_;
495 // A recent snapshot of Time::Now(), used to check delayed_work_queue_.
496 base::TimeTicks recent_time_;
498 // A queue of non-nestable tasks that we had to defer because when it came
499 // time to execute them we were in a nested message loop. They will execute
500 // once we're out of nested message loops.
501 base::TaskQueue deferred_non_nestable_work_queue_;
503 ObserverList<DestructionObserver> destruction_observers_;
505 // A recursion block that prevents accidentally running additional tasks when
506 // insider a (accidentally induced?) nested message pump.
507 bool nestable_tasks_allowed_;
509 bool exception_restoration_;
511 std::string thread_name_;
512 // A profiling histogram showing the counts of various messages and events.
513 base::HistogramBase* message_histogram_;
515 // An incoming queue of tasks that are acquired under a mutex for processing
516 // on this instance's thread. These tasks have not yet been sorted out into
517 // items for our work_queue_ vs delayed_work_queue_.
518 base::TaskQueue incoming_queue_;
519 // Protect access to incoming_queue_.
520 mutable base::Lock incoming_queue_lock_;
522 base::RunLoop* run_loop_;
524 #if defined(OS_WIN)
525 base::TimeTicks high_resolution_timer_expiration_;
526 // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
527 // which enter a modal message loop.
528 bool os_modal_loop_;
529 #endif
531 // The next sequence number to use for delayed tasks. Updating this counter is
532 // protected by incoming_queue_lock_.
533 int next_sequence_num_;
535 ObserverList<TaskObserver> task_observers_;
537 // The message loop proxy associated with this message loop, if one exists.
538 scoped_refptr<base::MessageLoopProxy> message_loop_proxy_;
539 scoped_ptr<base::ThreadTaskRunnerHandle> thread_task_runner_handle_;
541 template <class T, class R> friend class base::subtle::DeleteHelperInternal;
542 template <class T, class R> friend class base::subtle::ReleaseHelperInternal;
544 void DeleteSoonInternal(const tracked_objects::Location& from_here,
545 void(*deleter)(const void*),
546 const void* object);
547 void ReleaseSoonInternal(const tracked_objects::Location& from_here,
548 void(*releaser)(const void*),
549 const void* object);
551 DISALLOW_COPY_AND_ASSIGN(MessageLoop);
554 //-----------------------------------------------------------------------------
555 // MessageLoopForUI extends MessageLoop with methods that are particular to a
556 // MessageLoop instantiated with TYPE_UI.
558 // This class is typically used like so:
559 // MessageLoopForUI::current()->...call some method...
561 class BASE_EXPORT MessageLoopForUI : public MessageLoop {
562 public:
563 #if defined(OS_WIN)
564 typedef base::MessagePumpForUI::MessageFilter MessageFilter;
565 #endif
567 MessageLoopForUI() : MessageLoop(TYPE_UI) {
570 // Returns the MessageLoopForUI of the current thread.
571 static MessageLoopForUI* current() {
572 MessageLoop* loop = MessageLoop::current();
573 DCHECK(loop);
574 DCHECK_EQ(MessageLoop::TYPE_UI, loop->type());
575 return static_cast<MessageLoopForUI*>(loop);
578 #if defined(OS_WIN)
579 void DidProcessMessage(const MSG& message);
580 #endif // defined(OS_WIN)
582 #if defined(OS_IOS)
583 // On iOS, the main message loop cannot be Run(). Instead call Attach(),
584 // which connects this MessageLoop to the UI thread's CFRunLoop and allows
585 // PostTask() to work.
586 void Attach();
587 #endif
589 #if defined(OS_ANDROID)
590 // On Android, the UI message loop is handled by Java side. So Run() should
591 // never be called. Instead use Start(), which will forward all the native UI
592 // events to the Java message loop.
593 void Start();
594 #elif !defined(OS_MACOSX)
596 // Please see message_pump_win/message_pump_glib for definitions of these
597 // methods.
598 void AddObserver(Observer* observer);
599 void RemoveObserver(Observer* observer);
601 #if defined(OS_WIN)
602 // Plese see MessagePumpForUI for definitions of this method.
603 void SetMessageFilter(scoped_ptr<MessageFilter> message_filter) {
604 pump_ui()->SetMessageFilter(message_filter.Pass());
606 #endif
608 protected:
609 #if defined(USE_AURA) && defined(USE_X11) && !defined(OS_NACL)
610 friend class base::MessagePumpAuraX11;
611 #endif
612 #if defined(USE_OZONE) && !defined(OS_NACL)
613 friend class base::MessagePumpOzone;
614 #endif
616 // TODO(rvargas): Make this platform independent.
617 base::MessagePumpForUI* pump_ui() {
618 return static_cast<base::MessagePumpForUI*>(pump_.get());
620 #endif // !defined(OS_MACOSX)
623 // Do not add any member variables to MessageLoopForUI! This is important b/c
624 // MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
625 // data that you need should be stored on the MessageLoop's pump_ instance.
626 COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
627 MessageLoopForUI_should_not_have_extra_member_variables);
629 //-----------------------------------------------------------------------------
630 // MessageLoopForIO extends MessageLoop with methods that are particular to a
631 // MessageLoop instantiated with TYPE_IO.
633 // This class is typically used like so:
634 // MessageLoopForIO::current()->...call some method...
636 class BASE_EXPORT MessageLoopForIO : public MessageLoop {
637 public:
638 #if defined(OS_WIN)
639 typedef base::MessagePumpForIO::IOHandler IOHandler;
640 typedef base::MessagePumpForIO::IOContext IOContext;
641 typedef base::MessagePumpForIO::IOObserver IOObserver;
642 #elif defined(OS_IOS)
643 typedef base::MessagePumpIOSForIO::Watcher Watcher;
644 typedef base::MessagePumpIOSForIO::FileDescriptorWatcher
645 FileDescriptorWatcher;
646 typedef base::MessagePumpIOSForIO::IOObserver IOObserver;
648 enum Mode {
649 WATCH_READ = base::MessagePumpIOSForIO::WATCH_READ,
650 WATCH_WRITE = base::MessagePumpIOSForIO::WATCH_WRITE,
651 WATCH_READ_WRITE = base::MessagePumpIOSForIO::WATCH_READ_WRITE
653 #elif defined(OS_POSIX)
654 typedef base::MessagePumpLibevent::Watcher Watcher;
655 typedef base::MessagePumpLibevent::FileDescriptorWatcher
656 FileDescriptorWatcher;
657 typedef base::MessagePumpLibevent::IOObserver IOObserver;
659 enum Mode {
660 WATCH_READ = base::MessagePumpLibevent::WATCH_READ,
661 WATCH_WRITE = base::MessagePumpLibevent::WATCH_WRITE,
662 WATCH_READ_WRITE = base::MessagePumpLibevent::WATCH_READ_WRITE
665 #endif
667 MessageLoopForIO() : MessageLoop(TYPE_IO) {
670 // Returns the MessageLoopForIO of the current thread.
671 static MessageLoopForIO* current() {
672 MessageLoop* loop = MessageLoop::current();
673 DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
674 return static_cast<MessageLoopForIO*>(loop);
677 void AddIOObserver(IOObserver* io_observer) {
678 pump_io()->AddIOObserver(io_observer);
681 void RemoveIOObserver(IOObserver* io_observer) {
682 pump_io()->RemoveIOObserver(io_observer);
685 #if defined(OS_WIN)
686 // Please see MessagePumpWin for definitions of these methods.
687 void RegisterIOHandler(HANDLE file, IOHandler* handler);
688 bool RegisterJobObject(HANDLE job, IOHandler* handler);
689 bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
691 protected:
692 // TODO(rvargas): Make this platform independent.
693 base::MessagePumpForIO* pump_io() {
694 return static_cast<base::MessagePumpForIO*>(pump_.get());
697 #elif defined(OS_IOS)
698 // Please see MessagePumpIOSForIO for definition.
699 bool WatchFileDescriptor(int fd,
700 bool persistent,
701 Mode mode,
702 FileDescriptorWatcher *controller,
703 Watcher *delegate);
705 private:
706 base::MessagePumpIOSForIO* pump_io() {
707 return static_cast<base::MessagePumpIOSForIO*>(pump_.get());
710 #elif defined(OS_POSIX)
711 // Please see MessagePumpLibevent for definition.
712 bool WatchFileDescriptor(int fd,
713 bool persistent,
714 Mode mode,
715 FileDescriptorWatcher* controller,
716 Watcher* delegate);
718 private:
719 base::MessagePumpLibevent* pump_io() {
720 return static_cast<base::MessagePumpLibevent*>(pump_.get());
722 #endif // defined(OS_POSIX)
725 // Do not add any member variables to MessageLoopForIO! This is important b/c
726 // MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
727 // data that you need should be stored on the MessageLoop's pump_ instance.
728 COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
729 MessageLoopForIO_should_not_have_extra_member_variables);
731 } // namespace base
733 #endif // BASE_MESSAGE_LOOP_H_