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