1// Copyright (c) 2011 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
38#if !defined(__OBJC__)
39class NSAutoreleasePool;
40#else  // !defined(__OBJC__)
41#import <AppKit/AppKit.h>
42
43// Clients must subclass NSApplication and implement this protocol if they use
44// MessagePumpMac.
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
48// necessary.
49- (BOOL)isHandlingSendEvent;
50@end
51#endif  // !defined(__OBJC__)
52
53namespace base {
54
55class TimeTicks;
56
57class MessagePumpCFRunLoopBase : public MessagePump {
58  // Needs access to CreateAutoreleasePool.
59  friend class MessagePumpScopedAutoreleasePool;
60 public:
61  MessagePumpCFRunLoopBase();
62  virtual ~MessagePumpCFRunLoopBase();
63
64  // Subclasses should implement the work they need to do in MessagePump::Run
65  // in the DoRun method.  MessagePumpCFRunLoopBase::Run calls DoRun directly.
66  // This arrangement is used because MessagePumpCFRunLoopBase needs to set
67  // up and tear down things before and after the "meat" of DoRun.
68  virtual void Run(Delegate* delegate);
69  virtual void DoRun(Delegate* delegate) = 0;
70
71  virtual void ScheduleWork();
72  virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
73
74 protected:
75  // Accessors for private data members to be used by subclasses.
76  CFRunLoopRef run_loop() const { return run_loop_; }
77  int nesting_level() const { return nesting_level_; }
78  int run_nesting_level() const { return run_nesting_level_; }
79
80  // Return an autorelease pool to wrap around any work being performed.
81  // In some cases, CreateAutoreleasePool may return nil intentionally to
82  // preventing an autorelease pool from being created, allowing any
83  // objects autoreleased by work to fall into the current autorelease pool.
84  virtual NSAutoreleasePool* CreateAutoreleasePool();
85
86 private:
87  // Timer callback scheduled by ScheduleDelayedWork.  This does not do any
88  // work, but it signals work_source_ so that delayed work can be performed
89  // within the appropriate priority constraints.
90  static void RunDelayedWorkTimer(CFRunLoopTimerRef timer, void* info);
91
92  // Perform highest-priority work.  This is associated with work_source_
93  // signalled by ScheduleWork or RunDelayedWorkTimer.  The static method calls
94  // the instance method; the instance method returns true if it resignalled
95  // work_source_ to be called again from the loop.
96  static void RunWorkSource(void* info);
97  bool RunWork();
98
99  // Perform idle-priority work.  This is normally called by PreWaitObserver,
100  // but is also associated with idle_work_source_.  When this function
101  // actually does perform idle work, it will resignal that source.  The
102  // static method calls the instance method; the instance method returns
103  // true if idle work was done.
104  static void RunIdleWorkSource(void* info);
105  bool RunIdleWork();
106
107  // Perform work that may have been deferred because it was not runnable
108  // within a nested run loop.  This is associated with
109  // nesting_deferred_work_source_ and is signalled by
110  // MaybeScheduleNestingDeferredWork when returning from a nested loop,
111  // so that an outer loop will be able to perform the necessary tasks if it
112  // permits nestable tasks.
113  static void RunNestingDeferredWorkSource(void* info);
114  bool RunNestingDeferredWork();
115
116  // Schedules possible nesting-deferred work to be processed before the run
117  // loop goes to sleep, exits, or begins processing sources at the top of its
118  // loop.  If this function detects that a nested loop had run since the
119  // previous attempt to schedule nesting-deferred work, it will schedule a
120  // call to RunNestingDeferredWorkSource.
121  void MaybeScheduleNestingDeferredWork();
122
123  // Observer callback responsible for performing idle-priority work, before
124  // the run loop goes to sleep.  Associated with idle_work_observer_.
125  static void PreWaitObserver(CFRunLoopObserverRef observer,
126                              CFRunLoopActivity activity, void* info);
127
128  // Observer callback called before the run loop processes any sources.
129  // Associated with pre_source_observer_.
130  static void PreSourceObserver(CFRunLoopObserverRef observer,
131                                CFRunLoopActivity activity, void* info);
132
133  // Observer callback called when the run loop starts and stops, at the
134  // beginning and end of calls to CFRunLoopRun.  This is used to maintain
135  // nesting_level_.  Associated with enter_exit_observer_.
136  static void EnterExitObserver(CFRunLoopObserverRef observer,
137                                CFRunLoopActivity activity, void* info);
138
139  // Called by EnterExitObserver after performing maintenance on nesting_level_.
140  // This allows subclasses an opportunity to perform additional processing on
141  // the basis of run loops starting and stopping.
142  virtual void EnterExitRunLoop(CFRunLoopActivity activity);
143
144  // The thread's run loop.
145  CFRunLoopRef run_loop_;
146
147  // The timer, sources, and observers are described above alongside their
148  // callbacks.
149  CFRunLoopTimerRef delayed_work_timer_;
150  CFRunLoopSourceRef work_source_;
151  CFRunLoopSourceRef idle_work_source_;
152  CFRunLoopSourceRef nesting_deferred_work_source_;
153  CFRunLoopObserverRef pre_wait_observer_;
154  CFRunLoopObserverRef pre_source_observer_;
155  CFRunLoopObserverRef enter_exit_observer_;
156
157  // (weak) Delegate passed as an argument to the innermost Run call.
158  Delegate* delegate_;
159
160  // The time that delayed_work_timer_ is scheduled to fire.  This is tracked
161  // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_)
162  // to be able to reset the timer properly after waking from system sleep.
163  // See PowerStateNotification.
164  CFAbsoluteTime delayed_work_fire_time_;
165
166  // The recursion depth of the currently-executing CFRunLoopRun loop on the
167  // run loop's thread.  0 if no run loops are running inside of whatever scope
168  // the object was created in.
169  int nesting_level_;
170
171  // The recursion depth (calculated in the same way as nesting_level_) of the
172  // innermost executing CFRunLoopRun loop started by a call to Run.
173  int run_nesting_level_;
174
175  // The deepest (numerically highest) recursion depth encountered since the
176  // most recent attempt to run nesting-deferred work.
177  int deepest_nesting_level_;
178
179  // "Delegateless" work flags are set when work is ready to be performed but
180  // must wait until a delegate is available to process it.  This can happen
181  // when a MessagePumpCFRunLoopBase is instantiated and work arrives without
182  // any call to Run on the stack.  The Run method will check for delegateless
183  // work on entry and redispatch it as needed once a delegate is available.
184  bool delegateless_work_;
185  bool delegateless_idle_work_;
186
187  DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase);
188};
189
190class MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase {
191 public:
192  MessagePumpCFRunLoop();
193
194  virtual void DoRun(Delegate* delegate);
195  virtual void Quit();
196
197 private:
198  virtual void EnterExitRunLoop(CFRunLoopActivity activity);
199
200  // True if Quit is called to stop the innermost MessagePump
201  // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_)
202  // is running inside the MessagePump's innermost Run call.
203  bool quit_pending_;
204
205  DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop);
206};
207
208class MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase {
209 public:
210  MessagePumpNSRunLoop();
211  virtual ~MessagePumpNSRunLoop();
212
213  virtual void DoRun(Delegate* delegate);
214  virtual void Quit();
215
216 private:
217  // A source that doesn't do anything but provide something signalable
218  // attached to the run loop.  This source will be signalled when Quit
219  // is called, to cause the loop to wake up so that it can stop.
220  CFRunLoopSourceRef quit_source_;
221
222  // False after Quit is called.
223  bool keep_running_;
224
225  DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop);
226};
227
228class MessagePumpNSApplication : public MessagePumpCFRunLoopBase {
229 public:
230  MessagePumpNSApplication();
231
232  virtual void DoRun(Delegate* delegate);
233  virtual void Quit();
234
235 protected:
236  // Returns nil if NSApp is currently in the middle of calling -sendEvent.
237  virtual NSAutoreleasePool* CreateAutoreleasePool();
238
239 private:
240  // False after Quit is called.
241  bool keep_running_;
242
243  // True if DoRun is managing its own run loop as opposed to letting
244  // -[NSApplication run] handle it.  The outermost run loop in the application
245  // is managed by -[NSApplication run], inner run loops are handled by a loop
246  // in DoRun.
247  bool running_own_loop_;
248
249  DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication);
250};
251
252class MessagePumpMac {
253 public:
254  // Returns a new instance of MessagePumpNSApplication if called on the main
255  // thread.  Otherwise, returns a new instance of MessagePumpNSRunLoop.
256  static MessagePump* Create();
257
258 private:
259  DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac);
260};
261
262}  // namespace base
263
264#endif  // BASE_MESSAGE_PUMP_MAC_H_
265