message_pump_mac.h revision 21d179b334e59e9a3bfcaed4c4430bef1bc5759d
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 delayed_work_source_ so that delayed work can be
90  // performed 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.  The static method calls the instance method;
95  // the instance method returns true if work was done.
96  static void RunWorkSource(void* info);
97  bool RunWork();
98
99  // Perform delayed-priority work.  This is associated with
100  // delayed_work_source_ signalled by RunDelayedWorkTimer, and is responsible
101  // for calling ScheduleDelayedWork again if appropriate.  The static method
102  // calls the instance method; the instance method returns true if more
103  // delayed work is available.
104  static void RunDelayedWorkSource(void* info);
105  bool RunDelayedWork();
106
107  // Perform idle-priority work.  This is normally called by PreWaitObserver,
108  // but is also associated with idle_work_source_.  When this function
109  // actually does perform idle work, it will resignal that source.  The
110  // static method calls the instance method; the instance method returns
111  // true if idle work was done.
112  static void RunIdleWorkSource(void* info);
113  bool RunIdleWork();
114
115  // Perform work that may have been deferred because it was not runnable
116  // within a nested run loop.  This is associated with
117  // nesting_deferred_work_source_ and is signalled by
118  // MaybeScheduleNestingDeferredWork when returning from a nested loop,
119  // so that an outer loop will be able to perform the necessary tasks if it
120  // permits nestable tasks.
121  static void RunNestingDeferredWorkSource(void* info);
122  bool RunNestingDeferredWork();
123
124  // Schedules possible nesting-deferred work to be processed before the run
125  // loop goes to sleep, exits, or begins processing sources at the top of its
126  // loop.  If this function detects that a nested loop had run since the
127  // previous attempt to schedule nesting-deferred work, it will schedule a
128  // call to RunNestingDeferredWorkSource.
129  void MaybeScheduleNestingDeferredWork();
130
131  // Observer callback responsible for performing idle-priority work, before
132  // the run loop goes to sleep.  Associated with idle_work_observer_.
133  static void PreWaitObserver(CFRunLoopObserverRef observer,
134                              CFRunLoopActivity activity, void* info);
135
136  // Observer callback called before the run loop processes any sources.
137  // Associated with pre_source_observer_.
138  static void PreSourceObserver(CFRunLoopObserverRef observer,
139                                CFRunLoopActivity activity, void* info);
140
141  // Observer callback called when the run loop starts and stops, at the
142  // beginning and end of calls to CFRunLoopRun.  This is used to maintain
143  // nesting_level_.  Associated with enter_exit_observer_.
144  static void EnterExitObserver(CFRunLoopObserverRef observer,
145                                CFRunLoopActivity activity, void* info);
146
147  // Called by EnterExitObserver after performing maintenance on nesting_level_.
148  // This allows subclasses an opportunity to perform additional processing on
149  // the basis of run loops starting and stopping.
150  virtual void EnterExitRunLoop(CFRunLoopActivity activity);
151
152  // IOKit power state change notification callback, called when the system
153  // enters and leaves the sleep state.
154  static void PowerStateNotification(void* info, io_service_t service,
155                                     uint32_t message_type,
156                                     void* message_argument);
157
158  // The thread's run loop.
159  CFRunLoopRef run_loop_;
160
161  // The timer, sources, and observers are described above alongside their
162  // callbacks.
163  CFRunLoopTimerRef delayed_work_timer_;
164  CFRunLoopSourceRef work_source_;
165  CFRunLoopSourceRef delayed_work_source_;
166  CFRunLoopSourceRef idle_work_source_;
167  CFRunLoopSourceRef nesting_deferred_work_source_;
168  CFRunLoopObserverRef pre_wait_observer_;
169  CFRunLoopObserverRef pre_source_observer_;
170  CFRunLoopObserverRef enter_exit_observer_;
171
172  // Objects used for power state notification.  See PowerStateNotification.
173  io_connect_t root_power_domain_;
174  IONotificationPortRef power_notification_port_;
175  io_object_t power_notification_object_;
176
177  // (weak) Delegate passed as an argument to the innermost Run call.
178  Delegate* delegate_;
179
180  // The time that delayed_work_timer_ is scheduled to fire.  This is tracked
181  // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_)
182  // to be able to reset the timer properly after waking from system sleep.
183  // See PowerStateNotification.
184  CFAbsoluteTime delayed_work_fire_time_;
185
186  // The recursion depth of the currently-executing CFRunLoopRun loop on the
187  // run loop's thread.  0 if no run loops are running inside of whatever scope
188  // the object was created in.
189  int nesting_level_;
190
191  // The recursion depth (calculated in the same way as nesting_level_) of the
192  // innermost executing CFRunLoopRun loop started by a call to Run.
193  int run_nesting_level_;
194
195  // The deepest (numerically highest) recursion depth encountered since the
196  // most recent attempt to run nesting-deferred work.
197  int deepest_nesting_level_;
198
199  // "Delegateless" work flags are set when work is ready to be performed but
200  // must wait until a delegate is available to process it.  This can happen
201  // when a MessagePumpCFRunLoopBase is instantiated and work arrives without
202  // any call to Run on the stack.  The Run method will check for delegateless
203  // work on entry and redispatch it as needed once a delegate is available.
204  bool delegateless_work_;
205  bool delegateless_delayed_work_;
206  bool delegateless_idle_work_;
207
208  DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase);
209};
210
211class MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase {
212 public:
213  MessagePumpCFRunLoop();
214
215  virtual void DoRun(Delegate* delegate);
216  virtual void Quit();
217
218 private:
219  virtual void EnterExitRunLoop(CFRunLoopActivity activity);
220
221  // True if Quit is called to stop the innermost MessagePump
222  // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_)
223  // is running inside the MessagePump's innermost Run call.
224  bool quit_pending_;
225
226  DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop);
227};
228
229class MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase {
230 public:
231  MessagePumpNSRunLoop();
232  virtual ~MessagePumpNSRunLoop();
233
234  virtual void DoRun(Delegate* delegate);
235  virtual void Quit();
236
237 private:
238  // A source that doesn't do anything but provide something signalable
239  // attached to the run loop.  This source will be signalled when Quit
240  // is called, to cause the loop to wake up so that it can stop.
241  CFRunLoopSourceRef quit_source_;
242
243  // False after Quit is called.
244  bool keep_running_;
245
246  DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop);
247};
248
249class MessagePumpNSApplication : public MessagePumpCFRunLoopBase {
250 public:
251  MessagePumpNSApplication();
252
253  virtual void DoRun(Delegate* delegate);
254  virtual void Quit();
255
256 protected:
257  // Returns nil if NSApp is currently in the middle of calling -sendEvent.
258  virtual NSAutoreleasePool* CreateAutoreleasePool();
259
260 private:
261  // False after Quit is called.
262  bool keep_running_;
263
264  // True if DoRun is managing its own run loop as opposed to letting
265  // -[NSApplication run] handle it.  The outermost run loop in the application
266  // is managed by -[NSApplication run], inner run loops are handled by a loop
267  // in DoRun.
268  bool running_own_loop_;
269
270  DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication);
271};
272
273class MessagePumpMac {
274 public:
275  // Returns a new instance of MessagePumpNSApplication if called on the main
276  // thread.  Otherwise, returns a new instance of MessagePumpNSRunLoop.
277  static MessagePump* Create();
278
279 private:
280  DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac);
281};
282
283}  // namespace base
284
285#endif  // BASE_MESSAGE_PUMP_MAC_H_
286