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 #include "base/message_loop/timer_slack.h" 41 42 #if defined(__OBJC__) 43 #if defined(OS_IOS) 44 #import <Foundation/Foundation.h> 45 #else 46 #import <AppKit/AppKit.h> 47 48 // Clients must subclass NSApplication and implement this protocol if they use 49 // MessagePumpMac. 50 @protocol CrAppProtocol 51 // Must return true if -[NSApplication sendEvent:] is currently on the stack. 52 // See the comment for |CreateAutoreleasePool()| in the cc file for why this is 53 // necessary. 54 - (BOOL)isHandlingSendEvent; 55 @end 56 #endif // !defined(OS_IOS) 57 #endif // defined(__OBJC__) 58 59 namespace base { 60 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 virtual void SetTimerSlack(TimerSlack timer_slack) OVERRIDE; 97 98 protected: 99 // Accessors for private data members to be used by subclasses. run_loop()100 CFRunLoopRef run_loop() const { return run_loop_; } nesting_level()101 int nesting_level() const { return nesting_level_; } run_nesting_level()102 int run_nesting_level() const { return run_nesting_level_; } 103 104 // Sets this pump's delegate. Signals the appropriate sources if 105 // |delegateless_work_| is true. |delegate| can be NULL. 106 void SetDelegate(Delegate* delegate); 107 108 // Return an autorelease pool to wrap around any work being performed. 109 // In some cases, CreateAutoreleasePool may return nil intentionally to 110 // preventing an autorelease pool from being created, allowing any 111 // objects autoreleased by work to fall into the current autorelease pool. 112 virtual AutoreleasePoolType* CreateAutoreleasePool(); 113 114 private: 115 // Timer callback scheduled by ScheduleDelayedWork. This does not do any 116 // work, but it signals work_source_ so that delayed work can be performed 117 // within the appropriate priority constraints. 118 static void RunDelayedWorkTimer(CFRunLoopTimerRef timer, void* info); 119 120 // Perform highest-priority work. This is associated with work_source_ 121 // signalled by ScheduleWork or RunDelayedWorkTimer. The static method calls 122 // the instance method; the instance method returns true if it resignalled 123 // work_source_ to be called again from the loop. 124 static void RunWorkSource(void* info); 125 bool RunWork(); 126 127 // Perform idle-priority work. This is normally called by PreWaitObserver, 128 // but is also associated with idle_work_source_. When this function 129 // actually does perform idle work, it will resignal that source. The 130 // static method calls the instance method; the instance method returns 131 // true if idle work was done. 132 static void RunIdleWorkSource(void* info); 133 bool RunIdleWork(); 134 135 // Perform work that may have been deferred because it was not runnable 136 // within a nested run loop. This is associated with 137 // nesting_deferred_work_source_ and is signalled by 138 // MaybeScheduleNestingDeferredWork when returning from a nested loop, 139 // so that an outer loop will be able to perform the necessary tasks if it 140 // permits nestable tasks. 141 static void RunNestingDeferredWorkSource(void* info); 142 bool RunNestingDeferredWork(); 143 144 // Schedules possible nesting-deferred work to be processed before the run 145 // loop goes to sleep, exits, or begins processing sources at the top of its 146 // loop. If this function detects that a nested loop had run since the 147 // previous attempt to schedule nesting-deferred work, it will schedule a 148 // call to RunNestingDeferredWorkSource. 149 void MaybeScheduleNestingDeferredWork(); 150 151 // Observer callback responsible for performing idle-priority work, before 152 // the run loop goes to sleep. Associated with idle_work_observer_. 153 static void PreWaitObserver(CFRunLoopObserverRef observer, 154 CFRunLoopActivity activity, void* info); 155 156 // Observer callback called before the run loop processes any sources. 157 // Associated with pre_source_observer_. 158 static void PreSourceObserver(CFRunLoopObserverRef observer, 159 CFRunLoopActivity activity, void* info); 160 161 // Observer callback called when the run loop starts and stops, at the 162 // beginning and end of calls to CFRunLoopRun. This is used to maintain 163 // nesting_level_. Associated with enter_exit_observer_. 164 static void EnterExitObserver(CFRunLoopObserverRef observer, 165 CFRunLoopActivity activity, void* info); 166 167 // Called by EnterExitObserver after performing maintenance on nesting_level_. 168 // This allows subclasses an opportunity to perform additional processing on 169 // the basis of run loops starting and stopping. 170 virtual void EnterExitRunLoop(CFRunLoopActivity activity); 171 172 // The thread's run loop. 173 CFRunLoopRef run_loop_; 174 175 // The timer, sources, and observers are described above alongside their 176 // callbacks. 177 CFRunLoopTimerRef delayed_work_timer_; 178 CFRunLoopSourceRef work_source_; 179 CFRunLoopSourceRef idle_work_source_; 180 CFRunLoopSourceRef nesting_deferred_work_source_; 181 CFRunLoopObserverRef pre_wait_observer_; 182 CFRunLoopObserverRef pre_source_observer_; 183 CFRunLoopObserverRef enter_exit_observer_; 184 185 // (weak) Delegate passed as an argument to the innermost Run call. 186 Delegate* delegate_; 187 188 // The time that delayed_work_timer_ is scheduled to fire. This is tracked 189 // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_) 190 // to be able to reset the timer properly after waking from system sleep. 191 // See PowerStateNotification. 192 CFAbsoluteTime delayed_work_fire_time_; 193 194 base::TimerSlack timer_slack_; 195 196 // The recursion depth of the currently-executing CFRunLoopRun loop on the 197 // run loop's thread. 0 if no run loops are running inside of whatever scope 198 // the object was created in. 199 int nesting_level_; 200 201 // The recursion depth (calculated in the same way as nesting_level_) of the 202 // innermost executing CFRunLoopRun loop started by a call to Run. 203 int run_nesting_level_; 204 205 // The deepest (numerically highest) recursion depth encountered since the 206 // most recent attempt to run nesting-deferred work. 207 int deepest_nesting_level_; 208 209 // "Delegateless" work flags are set when work is ready to be performed but 210 // must wait until a delegate is available to process it. This can happen 211 // when a MessagePumpCFRunLoopBase is instantiated and work arrives without 212 // any call to Run on the stack. The Run method will check for delegateless 213 // work on entry and redispatch it as needed once a delegate is available. 214 bool delegateless_work_; 215 bool delegateless_idle_work_; 216 217 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase); 218 }; 219 220 class BASE_EXPORT MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase { 221 public: 222 MessagePumpCFRunLoop(); 223 virtual ~MessagePumpCFRunLoop(); 224 225 virtual void DoRun(Delegate* delegate) OVERRIDE; 226 virtual void Quit() OVERRIDE; 227 228 private: 229 virtual void EnterExitRunLoop(CFRunLoopActivity activity) OVERRIDE; 230 231 // True if Quit is called to stop the innermost MessagePump 232 // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_) 233 // is running inside the MessagePump's innermost Run call. 234 bool quit_pending_; 235 236 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop); 237 }; 238 239 class BASE_EXPORT MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase { 240 public: 241 MessagePumpNSRunLoop(); 242 virtual ~MessagePumpNSRunLoop(); 243 244 virtual void DoRun(Delegate* delegate) OVERRIDE; 245 virtual void Quit() OVERRIDE; 246 247 private: 248 // A source that doesn't do anything but provide something signalable 249 // attached to the run loop. This source will be signalled when Quit 250 // is called, to cause the loop to wake up so that it can stop. 251 CFRunLoopSourceRef quit_source_; 252 253 // False after Quit is called. 254 bool keep_running_; 255 256 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop); 257 }; 258 259 #if defined(OS_IOS) 260 // This is a fake message pump. It attaches sources to the main thread's 261 // CFRunLoop, so PostTask() will work, but it is unable to drive the loop 262 // directly, so calling Run() or Quit() are errors. 263 class MessagePumpUIApplication : public MessagePumpCFRunLoopBase { 264 public: 265 MessagePumpUIApplication(); 266 virtual ~MessagePumpUIApplication(); 267 virtual void DoRun(Delegate* delegate) OVERRIDE; 268 virtual void Quit() OVERRIDE; 269 270 // This message pump can not spin the main message loop directly. Instead, 271 // call |Attach()| to set up a delegate. It is an error to call |Run()|. 272 virtual void Attach(Delegate* delegate); 273 274 private: 275 RunLoop* run_loop_; 276 277 DISALLOW_COPY_AND_ASSIGN(MessagePumpUIApplication); 278 }; 279 280 #else 281 282 class MessagePumpNSApplication : public MessagePumpCFRunLoopBase { 283 public: 284 MessagePumpNSApplication(); 285 virtual ~MessagePumpNSApplication(); 286 287 virtual void DoRun(Delegate* delegate) OVERRIDE; 288 virtual void Quit() OVERRIDE; 289 290 private: 291 // False after Quit is called. 292 bool keep_running_; 293 294 // True if DoRun is managing its own run loop as opposed to letting 295 // -[NSApplication run] handle it. The outermost run loop in the application 296 // is managed by -[NSApplication run], inner run loops are handled by a loop 297 // in DoRun. 298 bool running_own_loop_; 299 300 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication); 301 }; 302 303 class MessagePumpCrApplication : public MessagePumpNSApplication { 304 public: 305 MessagePumpCrApplication(); 306 virtual ~MessagePumpCrApplication(); 307 308 protected: 309 // Returns nil if NSApp is currently in the middle of calling 310 // -sendEvent. Requires NSApp implementing CrAppProtocol. 311 virtual AutoreleasePoolType* CreateAutoreleasePool() OVERRIDE; 312 313 private: 314 DISALLOW_COPY_AND_ASSIGN(MessagePumpCrApplication); 315 }; 316 #endif // !defined(OS_IOS) 317 318 class BASE_EXPORT MessagePumpMac { 319 public: 320 // If not on the main thread, returns a new instance of 321 // MessagePumpNSRunLoop. 322 // 323 // On the main thread, if NSApp exists and conforms to 324 // CrAppProtocol, creates an instances of MessagePumpCrApplication. 325 // 326 // Otherwise creates an instance of MessagePumpNSApplication using a 327 // default NSApplication. 328 static MessagePump* Create(); 329 330 #if !defined(OS_IOS) 331 // If a pump is created before the required CrAppProtocol is 332 // created, the wrong MessagePump subclass could be used. 333 // UsingCrApp() returns false if the message pump was created before 334 // NSApp was initialized, or if NSApp does not implement 335 // CrAppProtocol. NSApp must be initialized before calling. 336 static bool UsingCrApp(); 337 338 // Wrapper to query -[NSApp isHandlingSendEvent] from C++ code. 339 // Requires NSApp to implement CrAppProtocol. 340 static bool IsHandlingSendEvent(); 341 #endif // !defined(OS_IOS) 342 343 private: 344 DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac); 345 }; 346 347 // Tasks posted to the message loop are posted under this mode, as well 348 // as kCFRunLoopCommonModes. 349 extern const CFStringRef BASE_EXPORT kMessageLoopExclusiveRunLoopMode; 350 351 } // namespace base 352 353 #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_ 354