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.
5 #import "base/message_pump_mac.h"
7 #import <Foundation/Foundation.h>
11 #include "base/logging.h"
12 #include "base/run_loop.h"
13 #include "base/time.h"
16 #import <AppKit/AppKit.h>
17 #endif // !defined(OS_IOS)
21 void NoOp(void* info) {
24 const CFTimeInterval kCFTimeIntervalMax =
25 std::numeric_limits<CFTimeInterval>::max();
27 // Set to true if MessagePumpMac::Create() is called before NSApp is
28 // initialized. Only accessed from the main thread.
29 bool not_using_crapp = false;
35 // A scoper for autorelease pools created from message pump run loops.
36 // Avoids dirtying up the ScopedNSAutoreleasePool interface for the rare
37 // case where an autorelease pool needs to be passed in.
38 class MessagePumpScopedAutoreleasePool {
40 explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) :
41 pool_(pump->CreateAutoreleasePool()) {
43 ~MessagePumpScopedAutoreleasePool() {
48 NSAutoreleasePool* pool_;
49 DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool);
52 // Must be called on the run loop thread.
53 MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase()
55 delayed_work_fire_time_(kCFTimeIntervalMax),
57 run_nesting_level_(0),
58 deepest_nesting_level_(0),
59 delegateless_work_(false),
60 delegateless_idle_work_(false) {
61 run_loop_ = CFRunLoopGetCurrent();
64 // Set a repeating timer with a preposterous firing time and interval. The
65 // timer will effectively never fire as-is. The firing time will be adjusted
66 // as needed when ScheduleDelayedWork is called.
67 CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
68 timer_context.info = this;
69 delayed_work_timer_ = CFRunLoopTimerCreate(NULL, // allocator
70 kCFTimeIntervalMax, // fire time
71 kCFTimeIntervalMax, // interval
76 CFRunLoopAddTimer(run_loop_, delayed_work_timer_, kCFRunLoopCommonModes);
78 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
79 source_context.info = this;
80 source_context.perform = RunWorkSource;
81 work_source_ = CFRunLoopSourceCreate(NULL, // allocator
84 CFRunLoopAddSource(run_loop_, work_source_, kCFRunLoopCommonModes);
86 source_context.perform = RunIdleWorkSource;
87 idle_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
90 CFRunLoopAddSource(run_loop_, idle_work_source_, kCFRunLoopCommonModes);
92 source_context.perform = RunNestingDeferredWorkSource;
93 nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
96 CFRunLoopAddSource(run_loop_, nesting_deferred_work_source_,
97 kCFRunLoopCommonModes);
99 CFRunLoopObserverContext observer_context = CFRunLoopObserverContext();
100 observer_context.info = this;
101 pre_wait_observer_ = CFRunLoopObserverCreate(NULL, // allocator
102 kCFRunLoopBeforeWaiting,
107 CFRunLoopAddObserver(run_loop_, pre_wait_observer_, kCFRunLoopCommonModes);
109 pre_source_observer_ = CFRunLoopObserverCreate(NULL, // allocator
110 kCFRunLoopBeforeSources,
115 CFRunLoopAddObserver(run_loop_, pre_source_observer_, kCFRunLoopCommonModes);
117 enter_exit_observer_ = CFRunLoopObserverCreate(NULL, // allocator
124 CFRunLoopAddObserver(run_loop_, enter_exit_observer_, kCFRunLoopCommonModes);
127 // Ideally called on the run loop thread. If other run loops were running
128 // lower on the run loop thread's stack when this object was created, the
129 // same number of run loops must be running when this object is destroyed.
130 MessagePumpCFRunLoopBase::~MessagePumpCFRunLoopBase() {
131 CFRunLoopRemoveObserver(run_loop_, enter_exit_observer_,
132 kCFRunLoopCommonModes);
133 CFRelease(enter_exit_observer_);
135 CFRunLoopRemoveObserver(run_loop_, pre_source_observer_,
136 kCFRunLoopCommonModes);
137 CFRelease(pre_source_observer_);
139 CFRunLoopRemoveObserver(run_loop_, pre_wait_observer_,
140 kCFRunLoopCommonModes);
141 CFRelease(pre_wait_observer_);
143 CFRunLoopRemoveSource(run_loop_, nesting_deferred_work_source_,
144 kCFRunLoopCommonModes);
145 CFRelease(nesting_deferred_work_source_);
147 CFRunLoopRemoveSource(run_loop_, idle_work_source_, kCFRunLoopCommonModes);
148 CFRelease(idle_work_source_);
150 CFRunLoopRemoveSource(run_loop_, work_source_, kCFRunLoopCommonModes);
151 CFRelease(work_source_);
153 CFRunLoopRemoveTimer(run_loop_, delayed_work_timer_, kCFRunLoopCommonModes);
154 CFRelease(delayed_work_timer_);
156 CFRelease(run_loop_);
159 // Must be called on the run loop thread.
160 void MessagePumpCFRunLoopBase::Run(Delegate* delegate) {
161 // nesting_level_ will be incremented in EnterExitRunLoop, so set
162 // run_nesting_level_ accordingly.
163 int last_run_nesting_level = run_nesting_level_;
164 run_nesting_level_ = nesting_level_ + 1;
166 Delegate* last_delegate = delegate_;
167 SetDelegate(delegate);
171 // Restore the previous state of the object.
172 SetDelegate(last_delegate);
173 run_nesting_level_ = last_run_nesting_level;
176 void MessagePumpCFRunLoopBase::SetDelegate(Delegate* delegate) {
177 delegate_ = delegate;
180 // If any work showed up but could not be dispatched for want of a
181 // delegate, set it up for dispatch again now that a delegate is
183 if (delegateless_work_) {
184 CFRunLoopSourceSignal(work_source_);
185 delegateless_work_ = false;
187 if (delegateless_idle_work_) {
188 CFRunLoopSourceSignal(idle_work_source_);
189 delegateless_idle_work_ = false;
194 // May be called on any thread.
195 void MessagePumpCFRunLoopBase::ScheduleWork() {
196 CFRunLoopSourceSignal(work_source_);
197 CFRunLoopWakeUp(run_loop_);
200 // Must be called on the run loop thread.
201 void MessagePumpCFRunLoopBase::ScheduleDelayedWork(
202 const TimeTicks& delayed_work_time) {
203 TimeDelta delta = delayed_work_time - TimeTicks::Now();
204 delayed_work_fire_time_ = CFAbsoluteTimeGetCurrent() + delta.InSecondsF();
205 CFRunLoopTimerSetNextFireDate(delayed_work_timer_, delayed_work_fire_time_);
208 // Called from the run loop.
210 void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer,
212 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
214 // The timer won't fire again until it's reset.
215 self->delayed_work_fire_time_ = kCFTimeIntervalMax;
217 // CFRunLoopTimers fire outside of the priority scheme for CFRunLoopSources.
218 // In order to establish the proper priority in which work and delayed work
219 // are processed one for one, the timer used to schedule delayed work must
220 // signal a CFRunLoopSource used to dispatch both work and delayed work.
221 CFRunLoopSourceSignal(self->work_source_);
224 // Called from the run loop.
226 void MessagePumpCFRunLoopBase::RunWorkSource(void* info) {
227 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
231 // Called by MessagePumpCFRunLoopBase::RunWorkSource.
232 bool MessagePumpCFRunLoopBase::RunWork() {
234 // This point can be reached with a NULL delegate_ if Run is not on the
235 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
236 // here when a delegate is available.
237 delegateless_work_ = true;
241 // The NSApplication-based run loop only drains the autorelease pool at each
242 // UI event (NSEvent). The autorelease pool is not drained for each
243 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
244 // objects if the app is not currently handling a UI event to ensure they're
245 // released promptly even in the absence of UI events.
246 MessagePumpScopedAutoreleasePool autorelease_pool(this);
248 // Call DoWork and DoDelayedWork once, and if something was done, arrange to
249 // come back here again as long as the loop is still running.
250 bool did_work = delegate_->DoWork();
251 bool resignal_work_source = did_work;
254 delegate_->DoDelayedWork(&next_time);
256 // Determine whether there's more delayed work, and if so, if it needs to
257 // be done at some point in the future or if it's already time to do it.
258 // Only do these checks if did_work is false. If did_work is true, this
259 // function, and therefore any additional delayed work, will get another
260 // chance to run before the loop goes to sleep.
261 bool more_delayed_work = !next_time.is_null();
262 if (more_delayed_work) {
263 TimeDelta delay = next_time - TimeTicks::Now();
264 if (delay > TimeDelta()) {
265 // There's more delayed work to be done in the future.
266 ScheduleDelayedWork(next_time);
268 // There's more delayed work to be done, and its time is in the past.
269 // Arrange to come back here directly as long as the loop is still
271 resignal_work_source = true;
276 if (resignal_work_source) {
277 CFRunLoopSourceSignal(work_source_);
280 return resignal_work_source;
283 // Called from the run loop.
285 void MessagePumpCFRunLoopBase::RunIdleWorkSource(void* info) {
286 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
290 // Called by MessagePumpCFRunLoopBase::RunIdleWorkSource.
291 bool MessagePumpCFRunLoopBase::RunIdleWork() {
293 // This point can be reached with a NULL delegate_ if Run is not on the
294 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
295 // here when a delegate is available.
296 delegateless_idle_work_ = true;
300 // The NSApplication-based run loop only drains the autorelease pool at each
301 // UI event (NSEvent). The autorelease pool is not drained for each
302 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
303 // objects if the app is not currently handling a UI event to ensure they're
304 // released promptly even in the absence of UI events.
305 MessagePumpScopedAutoreleasePool autorelease_pool(this);
307 // Call DoIdleWork once, and if something was done, arrange to come back here
308 // again as long as the loop is still running.
309 bool did_work = delegate_->DoIdleWork();
311 CFRunLoopSourceSignal(idle_work_source_);
317 // Called from the run loop.
319 void MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource(void* info) {
320 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
321 self->RunNestingDeferredWork();
324 // Called by MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource.
325 bool MessagePumpCFRunLoopBase::RunNestingDeferredWork() {
327 // This point can be reached with a NULL delegate_ if Run is not on the
328 // stack but foreign code is spinning the CFRunLoop. There's no sense in
329 // attempting to do any work or signalling the work sources because
330 // without a delegate, work is not possible.
334 // Immediately try work in priority order.
336 if (!RunIdleWork()) {
340 // Work was done. Arrange for the loop to try non-nestable idle work on
341 // a subsequent pass.
342 CFRunLoopSourceSignal(idle_work_source_);
348 // Called before the run loop goes to sleep or exits, or processes sources.
349 void MessagePumpCFRunLoopBase::MaybeScheduleNestingDeferredWork() {
350 // deepest_nesting_level_ is set as run loops are entered. If the deepest
351 // level encountered is deeper than the current level, a nested loop
352 // (relative to the current level) ran since the last time nesting-deferred
353 // work was scheduled. When that situation is encountered, schedule
354 // nesting-deferred work in case any work was deferred because nested work
356 if (deepest_nesting_level_ > nesting_level_) {
357 deepest_nesting_level_ = nesting_level_;
358 CFRunLoopSourceSignal(nesting_deferred_work_source_);
362 // Called from the run loop.
364 void MessagePumpCFRunLoopBase::PreWaitObserver(CFRunLoopObserverRef observer,
365 CFRunLoopActivity activity,
367 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
369 // Attempt to do some idle work before going to sleep.
372 // The run loop is about to go to sleep. If any of the work done since it
373 // started or woke up resulted in a nested run loop running,
374 // nesting-deferred work may have accumulated. Schedule it for processing
376 self->MaybeScheduleNestingDeferredWork();
379 // Called from the run loop.
381 void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer,
382 CFRunLoopActivity activity,
384 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
386 // The run loop has reached the top of the loop and is about to begin
387 // processing sources. If the last iteration of the loop at this nesting
388 // level did not sleep or exit, nesting-deferred work may have accumulated
389 // if a nested loop ran. Schedule nesting-deferred work for processing if
391 self->MaybeScheduleNestingDeferredWork();
394 // Called from the run loop.
396 void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer,
397 CFRunLoopActivity activity,
399 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
402 case kCFRunLoopEntry:
403 ++self->nesting_level_;
404 if (self->nesting_level_ > self->deepest_nesting_level_) {
405 self->deepest_nesting_level_ = self->nesting_level_;
410 // Not all run loops go to sleep. If a run loop is stopped before it
411 // goes to sleep due to a CFRunLoopStop call, or if the timeout passed
412 // to CFRunLoopRunInMode expires, the run loop may proceed directly from
413 // handling sources to exiting without any sleep. This most commonly
414 // occurs when CFRunLoopRunInMode is passed a timeout of 0, causing it
415 // to make a single pass through the loop and exit without sleep. Some
416 // native loops use CFRunLoop in this way. Because PreWaitObserver will
417 // not be called in these case, MaybeScheduleNestingDeferredWork needs
418 // to be called here, as the run loop exits.
420 // MaybeScheduleNestingDeferredWork consults self->nesting_level_
421 // to determine whether to schedule nesting-deferred work. It expects
422 // the nesting level to be set to the depth of the loop that is going
423 // to sleep or exiting. It must be called before decrementing the
424 // value so that the value still corresponds to the level of the exiting
426 self->MaybeScheduleNestingDeferredWork();
427 --self->nesting_level_;
434 self->EnterExitRunLoop(activity);
437 // Called by MessagePumpCFRunLoopBase::EnterExitRunLoop. The default
438 // implementation is a no-op.
439 void MessagePumpCFRunLoopBase::EnterExitRunLoop(CFRunLoopActivity activity) {
442 // Base version returns a standard NSAutoreleasePool.
443 NSAutoreleasePool* MessagePumpCFRunLoopBase::CreateAutoreleasePool() {
444 return [[NSAutoreleasePool alloc] init];
447 MessagePumpCFRunLoop::MessagePumpCFRunLoop()
448 : quit_pending_(false) {
451 MessagePumpCFRunLoop::~MessagePumpCFRunLoop() {}
453 // Called by MessagePumpCFRunLoopBase::DoRun. If other CFRunLoopRun loops were
454 // running lower on the run loop thread's stack when this object was created,
455 // the same number of CFRunLoopRun loops must be running for the outermost call
456 // to Run. Run/DoRun are reentrant after that point.
457 void MessagePumpCFRunLoop::DoRun(Delegate* delegate) {
458 // This is completely identical to calling CFRunLoopRun(), except autorelease
459 // pool management is introduced.
462 MessagePumpScopedAutoreleasePool autorelease_pool(this);
463 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
466 } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished);
469 // Must be called on the run loop thread.
470 void MessagePumpCFRunLoop::Quit() {
471 // Stop the innermost run loop managed by this MessagePumpCFRunLoop object.
472 if (nesting_level() == run_nesting_level()) {
473 // This object is running the innermost loop, just stop it.
474 CFRunLoopStop(run_loop());
476 // There's another loop running inside the loop managed by this object.
477 // In other words, someone else called CFRunLoopRunInMode on the same
478 // thread, deeper on the stack than the deepest Run call. Don't preempt
479 // other run loops, just mark this object to quit the innermost Run as
480 // soon as the other inner loops not managed by Run are done.
481 quit_pending_ = true;
485 // Called by MessagePumpCFRunLoopBase::EnterExitObserver.
486 void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) {
487 if (activity == kCFRunLoopExit &&
488 nesting_level() == run_nesting_level() &&
490 // Quit was called while loops other than those managed by this object
491 // were running further inside a run loop managed by this object. Now
492 // that all unmanaged inner run loops are gone, stop the loop running
494 CFRunLoopStop(run_loop());
495 quit_pending_ = false;
499 MessagePumpNSRunLoop::MessagePumpNSRunLoop()
500 : keep_running_(true) {
501 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
502 source_context.perform = NoOp;
503 quit_source_ = CFRunLoopSourceCreate(NULL, // allocator
506 CFRunLoopAddSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
509 MessagePumpNSRunLoop::~MessagePumpNSRunLoop() {
510 CFRunLoopRemoveSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
511 CFRelease(quit_source_);
514 void MessagePumpNSRunLoop::DoRun(Delegate* delegate) {
515 while (keep_running_) {
516 // NSRunLoop manages autorelease pools itself.
517 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
518 beforeDate:[NSDate distantFuture]];
521 keep_running_ = true;
524 void MessagePumpNSRunLoop::Quit() {
525 keep_running_ = false;
526 CFRunLoopSourceSignal(quit_source_);
527 CFRunLoopWakeUp(run_loop());
531 MessagePumpUIApplication::MessagePumpUIApplication()
535 MessagePumpUIApplication::~MessagePumpUIApplication() {}
537 void MessagePumpUIApplication::DoRun(Delegate* delegate) {
541 void MessagePumpUIApplication::Quit() {
545 void MessagePumpUIApplication::Attach(Delegate* delegate) {
547 run_loop_ = new base::RunLoop();
548 CHECK(run_loop_->BeforeRun());
549 SetDelegate(delegate);
554 MessagePumpNSApplication::MessagePumpNSApplication()
555 : keep_running_(true),
556 running_own_loop_(false) {
559 MessagePumpNSApplication::~MessagePumpNSApplication() {}
561 void MessagePumpNSApplication::DoRun(Delegate* delegate) {
562 bool last_running_own_loop_ = running_own_loop_;
564 // NSApp must be initialized by calling:
565 // [{some class which implements CrAppProtocol} sharedApplication]
566 // Most likely candidates are CrApplication or BrowserCrApplication.
567 // These can be initialized from C++ code by calling
568 // RegisterCrApp() or RegisterBrowserCrApp().
571 if (![NSApp isRunning]) {
572 running_own_loop_ = false;
573 // NSApplication manages autorelease pools itself when run this way.
576 running_own_loop_ = true;
577 NSDate* distant_future = [NSDate distantFuture];
578 while (keep_running_) {
579 MessagePumpScopedAutoreleasePool autorelease_pool(this);
580 NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
581 untilDate:distant_future
582 inMode:NSDefaultRunLoopMode
585 [NSApp sendEvent:event];
588 keep_running_ = true;
591 running_own_loop_ = last_running_own_loop_;
594 void MessagePumpNSApplication::Quit() {
595 if (!running_own_loop_) {
596 [[NSApplication sharedApplication] stop:nil];
598 keep_running_ = false;
601 // Send a fake event to wake the loop up.
602 [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
603 location:NSMakePoint(0, 0)
614 MessagePumpCrApplication::MessagePumpCrApplication() {
617 // Prevents an autorelease pool from being created if the app is in the midst of
618 // handling a UI event because various parts of AppKit depend on objects that
619 // are created while handling a UI event to be autoreleased in the event loop.
620 // An example of this is NSWindowController. When a window with a window
621 // controller is closed it goes through a stack like this:
622 // (Several stack frames elided for clarity)
624 // #0 [NSWindowController autorelease]
626 // #2 MessagePumpCFRunLoopBase::DoWork()
627 // #3 [NSRunLoop run]
628 // #4 [NSButton performClick:]
629 // #5 [NSWindow sendEvent:]
630 // #6 [NSApp sendEvent:]
633 // -performClick: spins a nested run loop. If the pool created in DoWork was a
634 // standard NSAutoreleasePool, it would release the objects that were
635 // autoreleased into it once DoWork released it. This would cause the window
636 // controller, which autoreleased itself in frame #0, to release itself, and
637 // possibly free itself. Unfortunately this window controller controls the
638 // window in frame #5. When the stack is unwound to frame #5, the window would
639 // no longer exists and crashes may occur. Apple gets around this by never
640 // releasing the pool it creates in frame #4, and letting frame #7 clean it up
641 // when it cleans up the pool that wraps frame #7. When an autorelease pool is
642 // released it releases all other pools that were created after it on the
643 // autorelease pool stack.
645 // CrApplication is responsible for setting handlingSendEvent to true just
646 // before it sends the event through the event handling mechanism, and
647 // returning it to its previous value once the event has been sent.
648 NSAutoreleasePool* MessagePumpCrApplication::CreateAutoreleasePool() {
649 if (MessagePumpMac::IsHandlingSendEvent())
651 return MessagePumpNSApplication::CreateAutoreleasePool();
655 bool MessagePumpMac::UsingCrApp() {
656 DCHECK([NSThread isMainThread]);
658 // If NSApp is still not initialized, then the subclass used cannot
662 // The pump was created using MessagePumpNSApplication.
666 return [NSApp conformsToProtocol:@protocol(CrAppProtocol)];
670 bool MessagePumpMac::IsHandlingSendEvent() {
671 DCHECK([NSApp conformsToProtocol:@protocol(CrAppProtocol)]);
672 NSObject<CrAppProtocol>* app = static_cast<NSObject<CrAppProtocol>*>(NSApp);
673 return [app isHandlingSendEvent];
675 #endif // !defined(OS_IOS)
678 MessagePump* MessagePumpMac::Create() {
679 if ([NSThread isMainThread]) {
681 return new MessagePumpUIApplication;
683 if ([NSApp conformsToProtocol:@protocol(CrAppProtocol)])
684 return new MessagePumpCrApplication;
686 // The main-thread MessagePump implementations REQUIRE an NSApp.
687 // Executables which have specific requirements for their
688 // NSApplication subclass should initialize appropriately before
689 // creating an event loop.
690 [NSApplication sharedApplication];
691 not_using_crapp = true;
692 return new MessagePumpNSApplication;
696 return new MessagePumpNSRunLoop;