message_pump_mac.h revision dc0f95d653279beabeb9817299e2902918ba123e
1// Copyright (c) 2008 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_PUMP_MAC_H_ 31#define BASE_MESSAGE_PUMP_MAC_H_ 32#pragma once 33 34#include "base/message_pump.h" 35 36#include <CoreFoundation/CoreFoundation.h> 37#include <IOKit/IOKitLib.h> 38 39#if !defined(__OBJC__) 40class NSAutoreleasePool; 41#else // !defined(__OBJC__) 42#import <AppKit/AppKit.h> 43 44// Clients must subclass NSApplication and implement this protocol if they use 45// MessagePumpMac. 46@protocol CrAppProtocol 47// Must return true if -[NSApplication sendEvent:] is currently on the stack. 48// See the comment for |CreateAutoreleasePool()| in the cc file for why this is 49// necessary. 50- (BOOL)isHandlingSendEvent; 51@end 52#endif // !defined(__OBJC__) 53 54namespace base { 55 56class TimeTicks; 57 58class MessagePumpCFRunLoopBase : public MessagePump { 59 // Needs access to CreateAutoreleasePool. 60 friend class MessagePumpScopedAutoreleasePool; 61 public: 62 MessagePumpCFRunLoopBase(); 63 virtual ~MessagePumpCFRunLoopBase(); 64 65 // Subclasses should implement the work they need to do in MessagePump::Run 66 // in the DoRun method. MessagePumpCFRunLoopBase::Run calls DoRun directly. 67 // This arrangement is used because MessagePumpCFRunLoopBase needs to set 68 // up and tear down things before and after the "meat" of DoRun. 69 virtual void Run(Delegate* delegate); 70 virtual void DoRun(Delegate* delegate) = 0; 71 72 virtual void ScheduleWork(); 73 virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time); 74 75 protected: 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_; } 80 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(); 86 87 private: 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); 92 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); 98 bool RunWork(); 99 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); 106 bool RunIdleWork(); 107 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(); 116 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(); 123 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); 128 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); 133 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); 139 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); 144 145 // IOKit power state change notification callback, called when the system 146 // enters and leaves the sleep state. 147 static void PowerStateNotification(void* info, io_service_t service, 148 uint32_t message_type, 149 void* message_argument); 150 151 // The thread's run loop. 152 CFRunLoopRef run_loop_; 153 154 // The timer, sources, and observers are described above alongside their 155 // callbacks. 156 CFRunLoopTimerRef delayed_work_timer_; 157 CFRunLoopSourceRef work_source_; 158 CFRunLoopSourceRef idle_work_source_; 159 CFRunLoopSourceRef nesting_deferred_work_source_; 160 CFRunLoopObserverRef pre_wait_observer_; 161 CFRunLoopObserverRef pre_source_observer_; 162 CFRunLoopObserverRef enter_exit_observer_; 163 164 // Objects used for power state notification. See PowerStateNotification. 165 io_connect_t root_power_domain_; 166 IONotificationPortRef power_notification_port_; 167 io_object_t power_notification_object_; 168 169 // (weak) Delegate passed as an argument to the innermost Run call. 170 Delegate* delegate_; 171 172 // The time that delayed_work_timer_ is scheduled to fire. This is tracked 173 // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_) 174 // to be able to reset the timer properly after waking from system sleep. 175 // See PowerStateNotification. 176 CFAbsoluteTime delayed_work_fire_time_; 177 178 // The recursion depth of the currently-executing CFRunLoopRun loop on the 179 // run loop's thread. 0 if no run loops are running inside of whatever scope 180 // the object was created in. 181 int nesting_level_; 182 183 // The recursion depth (calculated in the same way as nesting_level_) of the 184 // innermost executing CFRunLoopRun loop started by a call to Run. 185 int run_nesting_level_; 186 187 // The deepest (numerically highest) recursion depth encountered since the 188 // most recent attempt to run nesting-deferred work. 189 int deepest_nesting_level_; 190 191 // "Delegateless" work flags are set when work is ready to be performed but 192 // must wait until a delegate is available to process it. This can happen 193 // when a MessagePumpCFRunLoopBase is instantiated and work arrives without 194 // any call to Run on the stack. The Run method will check for delegateless 195 // work on entry and redispatch it as needed once a delegate is available. 196 bool delegateless_work_; 197 bool delegateless_idle_work_; 198 199 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase); 200}; 201 202class MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase { 203 public: 204 MessagePumpCFRunLoop(); 205 206 virtual void DoRun(Delegate* delegate); 207 virtual void Quit(); 208 209 private: 210 virtual void EnterExitRunLoop(CFRunLoopActivity activity); 211 212 // True if Quit is called to stop the innermost MessagePump 213 // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_) 214 // is running inside the MessagePump's innermost Run call. 215 bool quit_pending_; 216 217 DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop); 218}; 219 220class MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase { 221 public: 222 MessagePumpNSRunLoop(); 223 virtual ~MessagePumpNSRunLoop(); 224 225 virtual void DoRun(Delegate* delegate); 226 virtual void Quit(); 227 228 private: 229 // A source that doesn't do anything but provide something signalable 230 // attached to the run loop. This source will be signalled when Quit 231 // is called, to cause the loop to wake up so that it can stop. 232 CFRunLoopSourceRef quit_source_; 233 234 // False after Quit is called. 235 bool keep_running_; 236 237 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop); 238}; 239 240class MessagePumpNSApplication : public MessagePumpCFRunLoopBase { 241 public: 242 MessagePumpNSApplication(); 243 244 virtual void DoRun(Delegate* delegate); 245 virtual void Quit(); 246 247 protected: 248 // Returns nil if NSApp is currently in the middle of calling -sendEvent. 249 virtual NSAutoreleasePool* CreateAutoreleasePool(); 250 251 private: 252 // False after Quit is called. 253 bool keep_running_; 254 255 // True if DoRun is managing its own run loop as opposed to letting 256 // -[NSApplication run] handle it. The outermost run loop in the application 257 // is managed by -[NSApplication run], inner run loops are handled by a loop 258 // in DoRun. 259 bool running_own_loop_; 260 261 DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication); 262}; 263 264class MessagePumpMac { 265 public: 266 // Returns a new instance of MessagePumpNSApplication if called on the main 267 // thread. Otherwise, returns a new instance of MessagePumpNSRunLoop. 268 static MessagePump* Create(); 269 270 private: 271 DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac); 272}; 273 274} // namespace base 275 276#endif // BASE_MESSAGE_PUMP_MAC_H_ 277