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_PUMP_MAC_H_
31 #define BASE_MESSAGE_PUMP_MAC_H_
34 #include "base/message_pump.h"
36 #include <CoreFoundation/CoreFoundation.h>
38 #if !defined(__OBJC__)
39 class NSAutoreleasePool
;
40 #else // !defined(__OBJC__)
41 #import <AppKit/AppKit.h>
43 // Clients must subclass NSApplication and implement this protocol if they use
45 @protocol CrAppProtocol
46 // Must return true if -[NSApplication sendEvent:] is currently on the stack.
47 // See the comment for |CreateAutoreleasePool()| in the cc file for why this is
49 - (BOOL
)isHandlingSendEvent
;
51 #endif // !defined(__OBJC__)
57 class MessagePumpCFRunLoopBase
: public MessagePump
{
58 // Needs access to CreateAutoreleasePool.
59 friend class MessagePumpScopedAutoreleasePool
;
61 MessagePumpCFRunLoopBase();
63 // Subclasses should implement the work they need to do in MessagePump::Run
64 // in the DoRun method. MessagePumpCFRunLoopBase::Run calls DoRun directly.
65 // This arrangement is used because MessagePumpCFRunLoopBase needs to set
66 // up and tear down things before and after the "meat" of DoRun.
67 virtual void Run(Delegate
* delegate
) OVERRIDE
;
68 virtual void DoRun(Delegate
* delegate
) = 0;
70 virtual void ScheduleWork() OVERRIDE
;
71 virtual void ScheduleDelayedWork(const TimeTicks
& delayed_work_time
) OVERRIDE
;
74 virtual ~MessagePumpCFRunLoopBase();
76 // Accessors for private data members to be used by subclasses.
77 CFRunLoopRef
run_loop() const { return run_loop_
; }
78 int nesting_level() const { return nesting_level_
; }
79 int run_nesting_level() const { return run_nesting_level_
; }
81 // Return an autorelease pool to wrap around any work being performed.
82 // In some cases, CreateAutoreleasePool may return nil intentionally to
83 // preventing an autorelease pool from being created, allowing any
84 // objects autoreleased by work to fall into the current autorelease pool.
85 virtual NSAutoreleasePool
* CreateAutoreleasePool();
88 // Timer callback scheduled by ScheduleDelayedWork. This does not do any
89 // work, but it signals work_source_ so that delayed work can be performed
90 // within the appropriate priority constraints.
91 static void RunDelayedWorkTimer(CFRunLoopTimerRef timer
, void* info
);
93 // Perform highest-priority work. This is associated with work_source_
94 // signalled by ScheduleWork or RunDelayedWorkTimer. The static method calls
95 // the instance method; the instance method returns true if it resignalled
96 // work_source_ to be called again from the loop.
97 static void RunWorkSource(void* info
);
100 // Perform idle-priority work. This is normally called by PreWaitObserver,
101 // but is also associated with idle_work_source_. When this function
102 // actually does perform idle work, it will resignal that source. The
103 // static method calls the instance method; the instance method returns
104 // true if idle work was done.
105 static void RunIdleWorkSource(void* info
);
108 // Perform work that may have been deferred because it was not runnable
109 // within a nested run loop. This is associated with
110 // nesting_deferred_work_source_ and is signalled by
111 // MaybeScheduleNestingDeferredWork when returning from a nested loop,
112 // so that an outer loop will be able to perform the necessary tasks if it
113 // permits nestable tasks.
114 static void RunNestingDeferredWorkSource(void* info
);
115 bool RunNestingDeferredWork();
117 // Schedules possible nesting-deferred work to be processed before the run
118 // loop goes to sleep, exits, or begins processing sources at the top of its
119 // loop. If this function detects that a nested loop had run since the
120 // previous attempt to schedule nesting-deferred work, it will schedule a
121 // call to RunNestingDeferredWorkSource.
122 void MaybeScheduleNestingDeferredWork();
124 // Observer callback responsible for performing idle-priority work, before
125 // the run loop goes to sleep. Associated with idle_work_observer_.
126 static void PreWaitObserver(CFRunLoopObserverRef observer
,
127 CFRunLoopActivity activity
, void* info
);
129 // Observer callback called before the run loop processes any sources.
130 // Associated with pre_source_observer_.
131 static void PreSourceObserver(CFRunLoopObserverRef observer
,
132 CFRunLoopActivity activity
, void* info
);
134 // Observer callback called when the run loop starts and stops, at the
135 // beginning and end of calls to CFRunLoopRun. This is used to maintain
136 // nesting_level_. Associated with enter_exit_observer_.
137 static void EnterExitObserver(CFRunLoopObserverRef observer
,
138 CFRunLoopActivity activity
, void* info
);
140 // Called by EnterExitObserver after performing maintenance on nesting_level_.
141 // This allows subclasses an opportunity to perform additional processing on
142 // the basis of run loops starting and stopping.
143 virtual void EnterExitRunLoop(CFRunLoopActivity activity
);
145 // The thread's run loop.
146 CFRunLoopRef run_loop_
;
148 // The timer, sources, and observers are described above alongside their
150 CFRunLoopTimerRef delayed_work_timer_
;
151 CFRunLoopSourceRef work_source_
;
152 CFRunLoopSourceRef idle_work_source_
;
153 CFRunLoopSourceRef nesting_deferred_work_source_
;
154 CFRunLoopObserverRef pre_wait_observer_
;
155 CFRunLoopObserverRef pre_source_observer_
;
156 CFRunLoopObserverRef enter_exit_observer_
;
158 // (weak) Delegate passed as an argument to the innermost Run call.
161 // The time that delayed_work_timer_ is scheduled to fire. This is tracked
162 // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_)
163 // to be able to reset the timer properly after waking from system sleep.
164 // See PowerStateNotification.
165 CFAbsoluteTime delayed_work_fire_time_
;
167 // The recursion depth of the currently-executing CFRunLoopRun loop on the
168 // run loop's thread. 0 if no run loops are running inside of whatever scope
169 // the object was created in.
172 // The recursion depth (calculated in the same way as nesting_level_) of the
173 // innermost executing CFRunLoopRun loop started by a call to Run.
174 int run_nesting_level_
;
176 // The deepest (numerically highest) recursion depth encountered since the
177 // most recent attempt to run nesting-deferred work.
178 int deepest_nesting_level_
;
180 // "Delegateless" work flags are set when work is ready to be performed but
181 // must wait until a delegate is available to process it. This can happen
182 // when a MessagePumpCFRunLoopBase is instantiated and work arrives without
183 // any call to Run on the stack. The Run method will check for delegateless
184 // work on entry and redispatch it as needed once a delegate is available.
185 bool delegateless_work_
;
186 bool delegateless_idle_work_
;
188 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase
);
191 class MessagePumpCFRunLoop
: public MessagePumpCFRunLoopBase
{
193 MessagePumpCFRunLoop();
195 virtual void DoRun(Delegate
* delegate
) OVERRIDE
;
196 virtual void Quit() OVERRIDE
;
199 virtual ~MessagePumpCFRunLoop();
202 virtual void EnterExitRunLoop(CFRunLoopActivity activity
) OVERRIDE
;
204 // True if Quit is called to stop the innermost MessagePump
205 // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_)
206 // is running inside the MessagePump's innermost Run call.
209 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop
);
212 class MessagePumpNSRunLoop
: public MessagePumpCFRunLoopBase
{
214 BASE_EXPORT
MessagePumpNSRunLoop();
216 virtual void DoRun(Delegate
* delegate
) OVERRIDE
;
217 virtual void Quit() OVERRIDE
;
220 virtual ~MessagePumpNSRunLoop();
223 // A source that doesn't do anything but provide something signalable
224 // attached to the run loop. This source will be signalled when Quit
225 // is called, to cause the loop to wake up so that it can stop.
226 CFRunLoopSourceRef quit_source_
;
228 // False after Quit is called.
231 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop
);
234 class MessagePumpNSApplication
: public MessagePumpCFRunLoopBase
{
236 MessagePumpNSApplication();
238 virtual void DoRun(Delegate
* delegate
) OVERRIDE
;
239 virtual void Quit() OVERRIDE
;
242 virtual ~MessagePumpNSApplication();
245 // False after Quit is called.
248 // True if DoRun is managing its own run loop as opposed to letting
249 // -[NSApplication run] handle it. The outermost run loop in the application
250 // is managed by -[NSApplication run], inner run loops are handled by a loop
252 bool running_own_loop_
;
254 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication
);
257 class MessagePumpCrApplication
: public MessagePumpNSApplication
{
259 MessagePumpCrApplication();
262 virtual ~MessagePumpCrApplication() {}
264 // Returns nil if NSApp is currently in the middle of calling
265 // -sendEvent. Requires NSApp implementing CrAppProtocol.
266 virtual NSAutoreleasePool
* CreateAutoreleasePool() OVERRIDE
;
269 DISALLOW_COPY_AND_ASSIGN(MessagePumpCrApplication
);
272 class MessagePumpMac
{
274 // If not on the main thread, returns a new instance of
275 // MessagePumpNSRunLoop.
277 // On the main thread, if NSApp exists and conforms to
278 // CrAppProtocol, creates an instances of MessagePumpCrApplication.
280 // Otherwise creates an instance of MessagePumpNSApplication using a
281 // default NSApplication.
282 static MessagePump
* Create();
284 // If a pump is created before the required CrAppProtocol is
285 // created, the wrong MessagePump subclass could be used.
286 // UsingCrApp() returns false if the message pump was created before
287 // NSApp was initialized, or if NSApp does not implement
288 // CrAppProtocol. NSApp must be initialized before calling.
289 BASE_EXPORT
static bool UsingCrApp();
291 // Wrapper to query -[NSApp isHandlingSendEvent] from C++ code.
292 // Requires NSApp to implement CrAppProtocol.
293 BASE_EXPORT
static bool IsHandlingSendEvent();
296 DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac
);
301 #endif // BASE_MESSAGE_PUMP_MAC_H_