Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / base / message_loop / message_pump_mac.h
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.
4
5 // The basis for all native run loops on the Mac is the CFRunLoop.  It can be
6 // used directly, it can be used as the driving force behind the similar
7 // Foundation NSRunLoop, and it can be used to implement higher-level event
8 // loops such as the NSApplication event loop.
9 //
10 // This file introduces a basic CFRunLoop-based implementation of the
11 // MessagePump interface called CFRunLoopBase.  CFRunLoopBase contains all
12 // of the machinery necessary to dispatch events to a delegate, but does not
13 // implement the specific run loop.  Concrete subclasses must provide their
14 // own DoRun and Quit implementations.
15 //
16 // A concrete subclass that just runs a CFRunLoop loop is provided in
17 // MessagePumpCFRunLoop.  For an NSRunLoop, the similar MessagePumpNSRunLoop
18 // is provided.
19 //
20 // For the application's event loop, an implementation based on AppKit's
21 // NSApplication event system is provided in MessagePumpNSApplication.
22 //
23 // Typically, MessagePumpNSApplication only makes sense on a Cocoa
24 // application's main thread.  If a CFRunLoop-based message pump is needed on
25 // any other thread, one of the other concrete subclasses is preferrable.
26 // MessagePumpMac::Create is defined, which returns a new NSApplication-based
27 // or NSRunLoop-based MessagePump subclass depending on which thread it is
28 // called on.
29
30 #ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
31 #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
32
33 #include "base/message_loop/message_pump.h"
34
35 #include "base/basictypes.h"
36
37 #include <CoreFoundation/CoreFoundation.h>
38
39 #include "base/memory/weak_ptr.h"
40
41 #if defined(__OBJC__)
42 #if defined(OS_IOS)
43 #import <Foundation/Foundation.h>
44 #else
45 #import <AppKit/AppKit.h>
46
47 // Clients must subclass NSApplication and implement this protocol if they use
48 // MessagePumpMac.
49 @protocol CrAppProtocol
50 // Must return true if -[NSApplication sendEvent:] is currently on the stack.
51 // See the comment for |CreateAutoreleasePool()| in the cc file for why this is
52 // necessary.
53 - (BOOL)isHandlingSendEvent;
54 @end
55 #endif  // !defined(OS_IOS)
56 #endif  // defined(__OBJC__)
57
58 namespace base {
59
60 class MessagePumpInstrumentation;
61 class RunLoop;
62 class TimeTicks;
63
64 // AutoreleasePoolType is a proxy type for autorelease pools. Its definition
65 // depends on the translation unit (TU) in which this header appears. In pure
66 // C++ TUs, it is defined as a forward C++ class declaration (that is never
67 // defined), because autorelease pools are an Objective-C concept. In Automatic
68 // Reference Counting (ARC) Objective-C TUs, it is similarly defined as a
69 // forward C++ class declaration, because clang will not allow the type
70 // "NSAutoreleasePool" in such TUs. Finally, in Manual Retain Release (MRR)
71 // Objective-C TUs, it is a type alias for NSAutoreleasePool. In all cases, a
72 // method that takes or returns an NSAutoreleasePool* can use
73 // AutoreleasePoolType* instead.
74 #if !defined(__OBJC__) || __has_feature(objc_arc)
75 class AutoreleasePoolType;
76 #else   // !defined(__OBJC__) || __has_feature(objc_arc)
77 typedef NSAutoreleasePool AutoreleasePoolType;
78 #endif  // !defined(__OBJC__) || __has_feature(objc_arc)
79
80 class MessagePumpCFRunLoopBase : public MessagePump {
81   // Needs access to CreateAutoreleasePool.
82   friend class MessagePumpScopedAutoreleasePool;
83  public:
84   MessagePumpCFRunLoopBase();
85   virtual ~MessagePumpCFRunLoopBase();
86
87   // Subclasses should implement the work they need to do in MessagePump::Run
88   // in the DoRun method.  MessagePumpCFRunLoopBase::Run calls DoRun directly.
89   // This arrangement is used because MessagePumpCFRunLoopBase needs to set
90   // up and tear down things before and after the "meat" of DoRun.
91   virtual void Run(Delegate* delegate) OVERRIDE;
92   virtual void DoRun(Delegate* delegate) = 0;
93
94   virtual void ScheduleWork() OVERRIDE;
95   virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) OVERRIDE;
96
97  protected:
98   // Accessors for private data members to be used by subclasses.
99   CFRunLoopRef run_loop() const { return run_loop_; }
100   int nesting_level() const { return nesting_level_; }
101   int run_nesting_level() const { return run_nesting_level_; }
102
103   // Sets this pump's delegate.  Signals the appropriate sources if
104   // |delegateless_work_| is true.  |delegate| can be NULL.
105   void SetDelegate(Delegate* delegate);
106
107   // Return an autorelease pool to wrap around any work being performed.
108   // In some cases, CreateAutoreleasePool may return nil intentionally to
109   // preventing an autorelease pool from being created, allowing any
110   // objects autoreleased by work to fall into the current autorelease pool.
111   virtual AutoreleasePoolType* CreateAutoreleasePool();
112
113   // Enables instrumentation of the MessagePump. See MessagePumpInstrumentation
114   // in the implementation for details.
115   void EnableInstrumentation();
116   WeakPtr<MessagePumpInstrumentation> instrumentation_;
117
118  private:
119   // Timer callback scheduled by ScheduleDelayedWork.  This does not do any
120   // work, but it signals work_source_ so that delayed work can be performed
121   // within the appropriate priority constraints.
122   static void RunDelayedWorkTimer(CFRunLoopTimerRef timer, void* info);
123
124   // Perform highest-priority work.  This is associated with work_source_
125   // signalled by ScheduleWork or RunDelayedWorkTimer.  The static method calls
126   // the instance method; the instance method returns true if it resignalled
127   // work_source_ to be called again from the loop.
128   static void RunWorkSource(void* info);
129   bool RunWork();
130
131   // Perform idle-priority work.  This is normally called by
132   // StartOrEndWaitObserver, but is also associated with idle_work_source_. When
133   // this function actually does perform idle work, it will resignal that
134   // source.  The static method calls the instance method; the instance method
135   // returns true if idle work was done.
136   static void RunIdleWorkSource(void* info);
137   bool RunIdleWork();
138
139   // Perform work that may have been deferred because it was not runnable
140   // within a nested run loop.  This is associated with
141   // nesting_deferred_work_source_ and is signalled by
142   // MaybeScheduleNestingDeferredWork when returning from a nested loop,
143   // so that an outer loop will be able to perform the necessary tasks if it
144   // permits nestable tasks.
145   static void RunNestingDeferredWorkSource(void* info);
146   bool RunNestingDeferredWork();
147
148   // Schedules possible nesting-deferred work to be processed before the run
149   // loop goes to sleep, exits, or begins processing sources at the top of its
150   // loop.  If this function detects that a nested loop had run since the
151   // previous attempt to schedule nesting-deferred work, it will schedule a
152   // call to RunNestingDeferredWorkSource.
153   void MaybeScheduleNestingDeferredWork();
154
155   // Observer callback responsible for performing idle-priority work, before
156   // the run loop goes to sleep.  Associated with idle_work_observer_.
157   static void StartOrEndWaitObserver(CFRunLoopObserverRef observer,
158                                      CFRunLoopActivity activity, void* info);
159
160   // Observer callback called before the run loop processes any sources.
161   // Associated with pre_source_observer_.
162   static void PreSourceObserver(CFRunLoopObserverRef observer,
163                                 CFRunLoopActivity activity, void* info);
164
165   // Observer callback called when the run loop starts and stops, at the
166   // beginning and end of calls to CFRunLoopRun.  This is used to maintain
167   // nesting_level_.  Associated with enter_exit_observer_.
168   static void EnterExitObserver(CFRunLoopObserverRef observer,
169                                 CFRunLoopActivity activity, void* info);
170
171   // Called by EnterExitObserver after performing maintenance on nesting_level_.
172   // This allows subclasses an opportunity to perform additional processing on
173   // the basis of run loops starting and stopping.
174   virtual void EnterExitRunLoop(CFRunLoopActivity activity);
175
176   // The thread's run loop.
177   CFRunLoopRef run_loop_;
178
179   // The timer, sources, and observers are described above alongside their
180   // callbacks.
181   CFRunLoopTimerRef delayed_work_timer_;
182   CFRunLoopSourceRef work_source_;
183   CFRunLoopSourceRef idle_work_source_;
184   CFRunLoopSourceRef nesting_deferred_work_source_;
185   CFRunLoopObserverRef pre_wait_observer_;
186   CFRunLoopObserverRef pre_source_observer_;
187   CFRunLoopObserverRef enter_exit_observer_;
188
189   // (weak) Delegate passed as an argument to the innermost Run call.
190   Delegate* delegate_;
191
192   // The time that delayed_work_timer_ is scheduled to fire.  This is tracked
193   // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_)
194   // to be able to reset the timer properly after waking from system sleep.
195   // See PowerStateNotification.
196   CFAbsoluteTime delayed_work_fire_time_;
197
198   // The recursion depth of the currently-executing CFRunLoopRun loop on the
199   // run loop's thread.  0 if no run loops are running inside of whatever scope
200   // the object was created in.
201   int nesting_level_;
202
203   // The recursion depth (calculated in the same way as nesting_level_) of the
204   // innermost executing CFRunLoopRun loop started by a call to Run.
205   int run_nesting_level_;
206
207   // The deepest (numerically highest) recursion depth encountered since the
208   // most recent attempt to run nesting-deferred work.
209   int deepest_nesting_level_;
210
211   // "Delegateless" work flags are set when work is ready to be performed but
212   // must wait until a delegate is available to process it.  This can happen
213   // when a MessagePumpCFRunLoopBase is instantiated and work arrives without
214   // any call to Run on the stack.  The Run method will check for delegateless
215   // work on entry and redispatch it as needed once a delegate is available.
216   bool delegateless_work_;
217   bool delegateless_idle_work_;
218
219   DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase);
220 };
221
222 class MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase {
223  public:
224   MessagePumpCFRunLoop();
225   virtual ~MessagePumpCFRunLoop();
226
227   virtual void DoRun(Delegate* delegate) OVERRIDE;
228   virtual void Quit() OVERRIDE;
229
230  private:
231   virtual void EnterExitRunLoop(CFRunLoopActivity activity) OVERRIDE;
232
233   // True if Quit is called to stop the innermost MessagePump
234   // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_)
235   // is running inside the MessagePump's innermost Run call.
236   bool quit_pending_;
237
238   DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop);
239 };
240
241 class MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase {
242  public:
243   BASE_EXPORT MessagePumpNSRunLoop();
244   virtual ~MessagePumpNSRunLoop();
245
246   virtual void DoRun(Delegate* delegate) OVERRIDE;
247   virtual void Quit() OVERRIDE;
248
249  private:
250   // A source that doesn't do anything but provide something signalable
251   // attached to the run loop.  This source will be signalled when Quit
252   // is called, to cause the loop to wake up so that it can stop.
253   CFRunLoopSourceRef quit_source_;
254
255   // False after Quit is called.
256   bool keep_running_;
257
258   DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop);
259 };
260
261 #if defined(OS_IOS)
262 // This is a fake message pump.  It attaches sources to the main thread's
263 // CFRunLoop, so PostTask() will work, but it is unable to drive the loop
264 // directly, so calling Run() or Quit() are errors.
265 class MessagePumpUIApplication : public MessagePumpCFRunLoopBase {
266  public:
267   MessagePumpUIApplication();
268   virtual ~MessagePumpUIApplication();
269   virtual void DoRun(Delegate* delegate) OVERRIDE;
270   virtual void Quit() OVERRIDE;
271
272   // This message pump can not spin the main message loop directly.  Instead,
273   // call |Attach()| to set up a delegate.  It is an error to call |Run()|.
274   virtual void Attach(Delegate* delegate);
275
276  private:
277   RunLoop* run_loop_;
278
279   DISALLOW_COPY_AND_ASSIGN(MessagePumpUIApplication);
280 };
281
282 #else
283
284 class MessagePumpNSApplication : public MessagePumpCFRunLoopBase {
285  public:
286   MessagePumpNSApplication();
287   virtual ~MessagePumpNSApplication();
288
289   virtual void DoRun(Delegate* delegate) OVERRIDE;
290   virtual void Quit() OVERRIDE;
291
292  private:
293   // False after Quit is called.
294   bool keep_running_;
295
296   // True if DoRun is managing its own run loop as opposed to letting
297   // -[NSApplication run] handle it.  The outermost run loop in the application
298   // is managed by -[NSApplication run], inner run loops are handled by a loop
299   // in DoRun.
300   bool running_own_loop_;
301
302   DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication);
303 };
304
305 class MessagePumpCrApplication : public MessagePumpNSApplication {
306  public:
307   MessagePumpCrApplication();
308   virtual ~MessagePumpCrApplication();
309
310  protected:
311   // Returns nil if NSApp is currently in the middle of calling
312   // -sendEvent.  Requires NSApp implementing CrAppProtocol.
313   virtual AutoreleasePoolType* CreateAutoreleasePool() OVERRIDE;
314
315  private:
316   DISALLOW_COPY_AND_ASSIGN(MessagePumpCrApplication);
317 };
318 #endif  // !defined(OS_IOS)
319
320 class MessagePumpMac {
321  public:
322   // If not on the main thread, returns a new instance of
323   // MessagePumpNSRunLoop.
324   //
325   // On the main thread, if NSApp exists and conforms to
326   // CrAppProtocol, creates an instances of MessagePumpCrApplication.
327   //
328   // Otherwise creates an instance of MessagePumpNSApplication using a
329   // default NSApplication.
330   static MessagePump* Create();
331
332 #if !defined(OS_IOS)
333   // If a pump is created before the required CrAppProtocol is
334   // created, the wrong MessagePump subclass could be used.
335   // UsingCrApp() returns false if the message pump was created before
336   // NSApp was initialized, or if NSApp does not implement
337   // CrAppProtocol.  NSApp must be initialized before calling.
338   BASE_EXPORT static bool UsingCrApp();
339
340   // Wrapper to query -[NSApp isHandlingSendEvent] from C++ code.
341   // Requires NSApp to implement CrAppProtocol.
342   BASE_EXPORT static bool IsHandlingSendEvent();
343 #endif  // !defined(OS_IOS)
344
345  private:
346   DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac);
347 };
348
349 }  // namespace base
350
351 #endif  // BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_