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 // 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.
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.
16 // A concrete subclass that just runs a CFRunLoop loop is provided in
17 // MessagePumpCFRunLoop. For an NSRunLoop, the similar MessagePumpNSRunLoop
20 // For the application's event loop, an implementation based on AppKit's
21 // NSApplication event system is provided in MessagePumpNSApplication.
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
30 #ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
31 #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
33 #include "base/message_loop/message_pump.h"
35 #include "base/basictypes.h"
37 #include <CoreFoundation/CoreFoundation.h>
39 #include "base/memory/weak_ptr.h"
43 #import <Foundation/Foundation.h>
45 #import <AppKit/AppKit.h>
47 // Clients must subclass NSApplication and implement this protocol if they use
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
53 - (BOOL)isHandlingSendEvent;
55 #endif // !defined(OS_IOS)
56 #endif // defined(__OBJC__)
60 class MessagePumpInstrumentation;
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)
80 class MessagePumpCFRunLoopBase : public MessagePump {
81 // Needs access to CreateAutoreleasePool.
82 friend class MessagePumpScopedAutoreleasePool;
84 MessagePumpCFRunLoopBase();
85 virtual ~MessagePumpCFRunLoopBase();
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;
94 virtual void ScheduleWork() OVERRIDE;
95 virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) OVERRIDE;
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_; }
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);
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();
113 // Enables instrumentation of the MessagePump. See MessagePumpInstrumentation
114 // in the implementation for details.
115 void EnableInstrumentation();
116 WeakPtr<MessagePumpInstrumentation> instrumentation_;
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);
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);
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);
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();
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();
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);
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);
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);
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);
176 // The thread's run loop.
177 CFRunLoopRef run_loop_;
179 // The timer, sources, and observers are described above alongside their
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_;
189 // (weak) Delegate passed as an argument to the innermost Run call.
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_;
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.
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_;
207 // The deepest (numerically highest) recursion depth encountered since the
208 // most recent attempt to run nesting-deferred work.
209 int deepest_nesting_level_;
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_;
219 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase);
222 class MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase {
224 MessagePumpCFRunLoop();
225 virtual ~MessagePumpCFRunLoop();
227 virtual void DoRun(Delegate* delegate) OVERRIDE;
228 virtual void Quit() OVERRIDE;
231 virtual void EnterExitRunLoop(CFRunLoopActivity activity) OVERRIDE;
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.
238 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop);
241 class MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase {
243 BASE_EXPORT MessagePumpNSRunLoop();
244 virtual ~MessagePumpNSRunLoop();
246 virtual void DoRun(Delegate* delegate) OVERRIDE;
247 virtual void Quit() OVERRIDE;
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_;
255 // False after Quit is called.
258 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop);
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 {
267 MessagePumpUIApplication();
268 virtual ~MessagePumpUIApplication();
269 virtual void DoRun(Delegate* delegate) OVERRIDE;
270 virtual void Quit() OVERRIDE;
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);
279 DISALLOW_COPY_AND_ASSIGN(MessagePumpUIApplication);
284 class MessagePumpNSApplication : public MessagePumpCFRunLoopBase {
286 MessagePumpNSApplication();
287 virtual ~MessagePumpNSApplication();
289 virtual void DoRun(Delegate* delegate) OVERRIDE;
290 virtual void Quit() OVERRIDE;
293 // False after Quit is called.
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
300 bool running_own_loop_;
302 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication);
305 class MessagePumpCrApplication : public MessagePumpNSApplication {
307 MessagePumpCrApplication();
308 virtual ~MessagePumpCrApplication();
311 // Returns nil if NSApp is currently in the middle of calling
312 // -sendEvent. Requires NSApp implementing CrAppProtocol.
313 virtual AutoreleasePoolType* CreateAutoreleasePool() OVERRIDE;
316 DISALLOW_COPY_AND_ASSIGN(MessagePumpCrApplication);
318 #endif // !defined(OS_IOS)
320 class MessagePumpMac {
322 // If not on the main thread, returns a new instance of
323 // MessagePumpNSRunLoop.
325 // On the main thread, if NSApp exists and conforms to
326 // CrAppProtocol, creates an instances of MessagePumpCrApplication.
328 // Otherwise creates an instance of MessagePumpNSApplication using a
329 // default NSApplication.
330 static MessagePump* Create();
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();
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)
346 DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac);
351 #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_