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