message_pump_mac.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. // The basis for all native run loops on the Mac is the CFRunLoop. It can be
  5. // used directly, it can be used as the driving force behind the similar
  6. // Foundation NSRunLoop, and it can be used to implement higher-level event
  7. // loops such as the NSApplication event loop.
  8. //
  9. // This file introduces a basic CFRunLoop-based implementation of the
  10. // MessagePump interface called CFRunLoopBase. CFRunLoopBase contains all
  11. // of the machinery necessary to dispatch events to a delegate, but does not
  12. // implement the specific run loop. Concrete subclasses must provide their
  13. // own DoRun and DoQuit implementations.
  14. //
  15. // A concrete subclass that just runs a CFRunLoop loop is provided in
  16. // MessagePumpCFRunLoop. For an NSRunLoop, the similar MessagePumpNSRunLoop
  17. // is provided.
  18. //
  19. // For the application's event loop, an implementation based on AppKit's
  20. // NSApplication event system is provided in MessagePumpNSApplication.
  21. //
  22. // Typically, MessagePumpNSApplication only makes sense on a Cocoa
  23. // application's main thread. If a CFRunLoop-based message pump is needed on
  24. // any other thread, one of the other concrete subclasses is preferable.
  25. // MessagePumpMac::Create is defined, which returns a new NSApplication-based
  26. // or NSRunLoop-based MessagePump subclass depending on which thread it is
  27. // called on.
  28. #ifndef BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
  29. #define BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_
  30. #include "base/memory/raw_ptr.h"
  31. #include "base/message_loop/message_pump.h"
  32. #include <CoreFoundation/CoreFoundation.h>
  33. #include <memory>
  34. #include "base/containers/stack.h"
  35. #include "base/message_loop/timer_slack.h"
  36. #include "build/build_config.h"
  37. #include "third_party/abseil-cpp/absl/types/optional.h"
  38. #if defined(__OBJC__)
  39. #if BUILDFLAG(IS_IOS)
  40. #import <Foundation/Foundation.h>
  41. #else
  42. #import <AppKit/AppKit.h>
  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 // BUILDFLAG(IS_IOS)
  52. #endif // defined(__OBJC__)
  53. namespace base {
  54. class RunLoop;
  55. // AutoreleasePoolType is a proxy type for autorelease pools. Its definition
  56. // depends on the translation unit (TU) in which this header appears. In pure
  57. // C++ TUs, it is defined as a forward C++ class declaration (that is never
  58. // defined), because autorelease pools are an Objective-C concept. In Automatic
  59. // Reference Counting (ARC) Objective-C TUs, it is similarly defined as a
  60. // forward C++ class declaration, because clang will not allow the type
  61. // "NSAutoreleasePool" in such TUs. Finally, in Manual Retain Release (MRR)
  62. // Objective-C TUs, it is a type alias for NSAutoreleasePool. In all cases, a
  63. // method that takes or returns an NSAutoreleasePool* can use
  64. // AutoreleasePoolType* instead.
  65. #if !defined(__OBJC__) || __has_feature(objc_arc)
  66. class AutoreleasePoolType;
  67. #else // !defined(__OBJC__) || __has_feature(objc_arc)
  68. typedef NSAutoreleasePool AutoreleasePoolType;
  69. #endif // !defined(__OBJC__) || __has_feature(objc_arc)
  70. class BASE_EXPORT MessagePumpCFRunLoopBase : public MessagePump {
  71. public:
  72. MessagePumpCFRunLoopBase(const MessagePumpCFRunLoopBase&) = delete;
  73. MessagePumpCFRunLoopBase& operator=(const MessagePumpCFRunLoopBase&) = delete;
  74. static void InitializeFeatures();
  75. // MessagePump:
  76. void Run(Delegate* delegate) override;
  77. void Quit() override;
  78. void ScheduleWork() override;
  79. void ScheduleDelayedWork(
  80. const Delegate::NextWorkInfo& next_work_info) override;
  81. void SetTimerSlack(TimerSlack timer_slack) override;
  82. #if BUILDFLAG(IS_IOS)
  83. // Some iOS message pumps do not support calling |Run()| to spin the main
  84. // message loop directly. Instead, call |Attach()| to set up a delegate, then
  85. // |Detach()| before destroying the message pump. These methods do nothing if
  86. // the message pump supports calling |Run()| and |Quit()|.
  87. virtual void Attach(Delegate* delegate);
  88. virtual void Detach();
  89. #endif // BUILDFLAG(IS_IOS)
  90. protected:
  91. // Needs access to CreateAutoreleasePool.
  92. friend class MessagePumpScopedAutoreleasePool;
  93. friend class TestMessagePumpCFRunLoopBase;
  94. // Tasks will be pumped in the run loop modes described by
  95. // |initial_mode_mask|, which maps bits to the index of an internal array of
  96. // run loop mode identifiers.
  97. explicit MessagePumpCFRunLoopBase(int initial_mode_mask);
  98. ~MessagePumpCFRunLoopBase() override;
  99. // Subclasses should implement the work they need to do in MessagePump::Run
  100. // in the DoRun method. MessagePumpCFRunLoopBase::Run calls DoRun directly.
  101. // This arrangement is used because MessagePumpCFRunLoopBase needs to set
  102. // up and tear down things before and after the "meat" of DoRun.
  103. virtual void DoRun(Delegate* delegate) = 0;
  104. // Similar to DoRun, this allows subclasses to perform custom handling when
  105. // quitting a run loop. Return true if the quit took effect immediately;
  106. // otherwise call OnDidQuit() when the quit is actually applied (e.g., a
  107. // nested native runloop exited).
  108. virtual bool DoQuit() = 0;
  109. // Should be called by subclasses to signal when a deferred quit takes place.
  110. void OnDidQuit();
  111. // Accessors for private data members to be used by subclasses.
  112. CFRunLoopRef run_loop() const { return run_loop_; }
  113. int nesting_level() const { return nesting_level_; }
  114. int run_nesting_level() const { return run_nesting_level_; }
  115. bool keep_running() const { return keep_running_; }
  116. #if BUILDFLAG(IS_IOS)
  117. void OnAttach();
  118. void OnDetach();
  119. #endif
  120. // Sets this pump's delegate. Signals the appropriate sources if
  121. // |delegateless_work_| is true. |delegate| can be NULL.
  122. void SetDelegate(Delegate* delegate);
  123. // Return an autorelease pool to wrap around any work being performed.
  124. // In some cases, CreateAutoreleasePool may return nil intentionally to
  125. // preventing an autorelease pool from being created, allowing any
  126. // objects autoreleased by work to fall into the current autorelease pool.
  127. virtual AutoreleasePoolType* CreateAutoreleasePool();
  128. // Enable and disable entries in |enabled_modes_| to match |mode_mask|.
  129. void SetModeMask(int mode_mask);
  130. // Get the current mode mask from |enabled_modes_|.
  131. int GetModeMask() const;
  132. private:
  133. class ScopedModeEnabler;
  134. // The maximum number of run loop modes that can be monitored.
  135. static constexpr int kNumModes = 4;
  136. // Timer callback scheduled by ScheduleDelayedWork. This does not do any
  137. // work, but it signals |work_source_| so that delayed work can be performed
  138. // within the appropriate priority constraints.
  139. static void RunDelayedWorkTimer(CFRunLoopTimerRef timer, void* info);
  140. // Perform highest-priority work. This is associated with |work_source_|
  141. // signalled by ScheduleWork or RunDelayedWorkTimer. The static method calls
  142. // the instance method; the instance method returns true if it resignalled
  143. // |work_source_| to be called again from the loop.
  144. static void RunWorkSource(void* info);
  145. bool RunWork();
  146. // Perform idle-priority work. This is normally called by PreWaitObserver,
  147. // but is also associated with |idle_work_source_|. When this function
  148. // actually does perform idle work, it will resignal that source. The
  149. // static method calls the instance method.
  150. static void RunIdleWorkSource(void* info);
  151. void RunIdleWork();
  152. // Perform work that may have been deferred because it was not runnable
  153. // within a nested run loop. This is associated with
  154. // |nesting_deferred_work_source_| and is signalled by
  155. // MaybeScheduleNestingDeferredWork when returning from a nested loop,
  156. // so that an outer loop will be able to perform the necessary tasks if it
  157. // permits nestable tasks.
  158. static void RunNestingDeferredWorkSource(void* info);
  159. void RunNestingDeferredWork();
  160. // Called before the run loop goes to sleep to notify delegate.
  161. void BeforeWait();
  162. // Schedules possible nesting-deferred work to be processed before the run
  163. // loop goes to sleep, exits, or begins processing sources at the top of its
  164. // loop. If this function detects that a nested loop had run since the
  165. // previous attempt to schedule nesting-deferred work, it will schedule a
  166. // call to RunNestingDeferredWorkSource.
  167. void MaybeScheduleNestingDeferredWork();
  168. // Observer callback responsible for performing idle-priority work, before
  169. // the run loop goes to sleep. Associated with |pre_wait_observer_|.
  170. static void PreWaitObserver(CFRunLoopObserverRef observer,
  171. CFRunLoopActivity activity, void* info);
  172. static void AfterWaitObserver(CFRunLoopObserverRef observer,
  173. CFRunLoopActivity activity,
  174. void* info);
  175. // Observer callback called before the run loop processes any sources.
  176. // Associated with |pre_source_observer_|.
  177. static void PreSourceObserver(CFRunLoopObserverRef observer,
  178. CFRunLoopActivity activity, void* info);
  179. // Observer callback called when the run loop starts and stops, at the
  180. // beginning and end of calls to CFRunLoopRun. This is used to maintain
  181. // |nesting_level_|. Associated with |enter_exit_observer_|.
  182. static void EnterExitObserver(CFRunLoopObserverRef observer,
  183. CFRunLoopActivity activity, void* info);
  184. // Called by EnterExitObserver after performing maintenance on
  185. // |nesting_level_|. This allows subclasses an opportunity to perform
  186. // additional processing on the basis of run loops starting and stopping.
  187. virtual void EnterExitRunLoop(CFRunLoopActivity activity);
  188. // Gets rid of the top work item scope.
  189. void PopWorkItemScope();
  190. // Starts tracking a new work item.
  191. void PushWorkItemScope();
  192. // The thread's run loop.
  193. CFRunLoopRef run_loop_;
  194. // The enabled modes. Posted tasks may run in any non-null entry.
  195. std::unique_ptr<ScopedModeEnabler> enabled_modes_[kNumModes];
  196. // The timer, sources, and observers are described above alongside their
  197. // callbacks.
  198. CFRunLoopTimerRef delayed_work_timer_;
  199. CFRunLoopSourceRef work_source_;
  200. CFRunLoopSourceRef idle_work_source_;
  201. CFRunLoopSourceRef nesting_deferred_work_source_;
  202. CFRunLoopObserverRef pre_wait_observer_;
  203. CFRunLoopObserverRef after_wait_observer_;
  204. CFRunLoopObserverRef pre_source_observer_;
  205. CFRunLoopObserverRef enter_exit_observer_;
  206. // (weak) Delegate passed as an argument to the innermost Run call.
  207. raw_ptr<Delegate> delegate_;
  208. base::TimerSlack timer_slack_;
  209. // Time at which `delayed_work_timer_` is set to fire.
  210. base::TimeTicks delayed_work_scheduled_at_ = base::TimeTicks::Max();
  211. // The recursion depth of the currently-executing CFRunLoopRun loop on the
  212. // run loop's thread. 0 if no run loops are running inside of whatever scope
  213. // the object was created in.
  214. int nesting_level_;
  215. // The recursion depth (calculated in the same way as |nesting_level_|) of the
  216. // innermost executing CFRunLoopRun loop started by a call to Run.
  217. int run_nesting_level_;
  218. // The deepest (numerically highest) recursion depth encountered since the
  219. // most recent attempt to run nesting-deferred work.
  220. int deepest_nesting_level_;
  221. // Whether we should continue running application tasks. Set to false when
  222. // Quit() is called for the innermost run loop.
  223. bool keep_running_;
  224. // "Delegateless" work flags are set when work is ready to be performed but
  225. // must wait until a delegate is available to process it. This can happen
  226. // when a MessagePumpCFRunLoopBase is instantiated and work arrives without
  227. // any call to Run on the stack. The Run method will check for delegateless
  228. // work on entry and redispatch it as needed once a delegate is available.
  229. bool delegateless_work_;
  230. bool delegateless_idle_work_;
  231. // Used to keep track of the native event work items processed by the message
  232. // pump. Made of optionals because tracking can be suspended when it's
  233. // determined the loop is not processing a native event but the depth of the
  234. // stack should match |nesting_level_| at all times. A nullopt is also used
  235. // as a stand-in during delegateless operation.
  236. base::stack<absl::optional<base::MessagePump::Delegate::ScopedDoWorkItem>>
  237. stack_;
  238. };
  239. class BASE_EXPORT MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase {
  240. public:
  241. MessagePumpCFRunLoop();
  242. MessagePumpCFRunLoop(const MessagePumpCFRunLoop&) = delete;
  243. MessagePumpCFRunLoop& operator=(const MessagePumpCFRunLoop&) = delete;
  244. ~MessagePumpCFRunLoop() override;
  245. void DoRun(Delegate* delegate) override;
  246. bool DoQuit() override;
  247. private:
  248. void EnterExitRunLoop(CFRunLoopActivity activity) override;
  249. // True if Quit is called to stop the innermost MessagePump
  250. // (|innermost_quittable_|) but some other CFRunLoopRun loop
  251. // (|nesting_level_|) is running inside the MessagePump's innermost Run call.
  252. bool quit_pending_;
  253. };
  254. class BASE_EXPORT MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase {
  255. public:
  256. MessagePumpNSRunLoop();
  257. MessagePumpNSRunLoop(const MessagePumpNSRunLoop&) = delete;
  258. MessagePumpNSRunLoop& operator=(const MessagePumpNSRunLoop&) = delete;
  259. ~MessagePumpNSRunLoop() override;
  260. void DoRun(Delegate* delegate) override;
  261. bool DoQuit() override;
  262. private:
  263. // A source that doesn't do anything but provide something signalable
  264. // attached to the run loop. This source will be signalled when Quit
  265. // is called, to cause the loop to wake up so that it can stop.
  266. CFRunLoopSourceRef quit_source_;
  267. };
  268. #if BUILDFLAG(IS_IOS)
  269. // This is a fake message pump. It attaches sources to the main thread's
  270. // CFRunLoop, so PostTask() will work, but it is unable to drive the loop
  271. // directly, so calling Run() or Quit() are errors.
  272. class MessagePumpUIApplication : public MessagePumpCFRunLoopBase {
  273. public:
  274. MessagePumpUIApplication();
  275. MessagePumpUIApplication(const MessagePumpUIApplication&) = delete;
  276. MessagePumpUIApplication& operator=(const MessagePumpUIApplication&) = delete;
  277. ~MessagePumpUIApplication() override;
  278. void DoRun(Delegate* delegate) override;
  279. bool DoQuit() override;
  280. // MessagePumpCFRunLoopBase.
  281. // MessagePumpUIApplication can not spin the main message loop directly.
  282. // Instead, call |Attach()| to set up a delegate. It is an error to call
  283. // |Run()|.
  284. void Attach(Delegate* delegate) override;
  285. void Detach() override;
  286. private:
  287. RunLoop* run_loop_;
  288. };
  289. #else
  290. // While in scope, permits posted tasks to be run in private AppKit run loop
  291. // modes that would otherwise make the UI unresponsive. E.g., menu fade out.
  292. class BASE_EXPORT ScopedPumpMessagesInPrivateModes {
  293. public:
  294. ScopedPumpMessagesInPrivateModes();
  295. ScopedPumpMessagesInPrivateModes(const ScopedPumpMessagesInPrivateModes&) =
  296. delete;
  297. ScopedPumpMessagesInPrivateModes& operator=(
  298. const ScopedPumpMessagesInPrivateModes&) = delete;
  299. ~ScopedPumpMessagesInPrivateModes();
  300. int GetModeMaskForTest();
  301. };
  302. class MessagePumpNSApplication : public MessagePumpCFRunLoopBase {
  303. public:
  304. MessagePumpNSApplication();
  305. MessagePumpNSApplication(const MessagePumpNSApplication&) = delete;
  306. MessagePumpNSApplication& operator=(const MessagePumpNSApplication&) = delete;
  307. ~MessagePumpNSApplication() override;
  308. void DoRun(Delegate* delegate) override;
  309. bool DoQuit() override;
  310. private:
  311. friend class ScopedPumpMessagesInPrivateModes;
  312. void EnterExitRunLoop(CFRunLoopActivity activity) override;
  313. // True if DoRun is managing its own run loop as opposed to letting
  314. // -[NSApplication run] handle it. The outermost run loop in the application
  315. // is managed by -[NSApplication run], inner run loops are handled by a loop
  316. // in DoRun.
  317. bool running_own_loop_;
  318. // True if Quit() was called while a modal window was shown and needed to be
  319. // deferred.
  320. bool quit_pending_;
  321. };
  322. class MessagePumpCrApplication : public MessagePumpNSApplication {
  323. public:
  324. MessagePumpCrApplication();
  325. MessagePumpCrApplication(const MessagePumpCrApplication&) = delete;
  326. MessagePumpCrApplication& operator=(const MessagePumpCrApplication&) = delete;
  327. ~MessagePumpCrApplication() override;
  328. protected:
  329. // Returns nil if NSApp is currently in the middle of calling
  330. // -sendEvent. Requires NSApp implementing CrAppProtocol.
  331. AutoreleasePoolType* CreateAutoreleasePool() override;
  332. };
  333. #endif // BUILDFLAG(IS_IOS)
  334. class BASE_EXPORT MessagePumpMac {
  335. public:
  336. MessagePumpMac() = delete;
  337. MessagePumpMac(const MessagePumpMac&) = delete;
  338. MessagePumpMac& operator=(const MessagePumpMac&) = delete;
  339. // If not on the main thread, returns a new instance of
  340. // MessagePumpNSRunLoop.
  341. //
  342. // On the main thread, if NSApp exists and conforms to
  343. // CrAppProtocol, creates an instances of MessagePumpCrApplication.
  344. //
  345. // Otherwise creates an instance of MessagePumpNSApplication using a
  346. // default NSApplication.
  347. static std::unique_ptr<MessagePump> Create();
  348. #if !BUILDFLAG(IS_IOS)
  349. // If a pump is created before the required CrAppProtocol is
  350. // created, the wrong MessagePump subclass could be used.
  351. // UsingCrApp() returns false if the message pump was created before
  352. // NSApp was initialized, or if NSApp does not implement
  353. // CrAppProtocol. NSApp must be initialized before calling.
  354. static bool UsingCrApp();
  355. // Wrapper to query -[NSApp isHandlingSendEvent] from C++ code.
  356. // Requires NSApp to implement CrAppProtocol.
  357. static bool IsHandlingSendEvent();
  358. #endif // !BUILDFLAG(IS_IOS)
  359. };
  360. // Tasks posted to the message loop are posted under this mode, as well
  361. // as kCFRunLoopCommonModes.
  362. extern const CFStringRef BASE_EXPORT kMessageLoopExclusiveRunLoopMode;
  363. } // namespace base
  364. #endif // BASE_MESSAGE_LOOP_MESSAGE_PUMP_MAC_H_