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_loop/message_pump_mac.h"
8 #import <Foundation/Foundation.h>
12 #include "base/logging.h"
13 #include "base/mac/call_with_eh_frame.h"
14 #include "base/mac/scoped_cftyperef.h"
15 #include "base/message_loop/timer_slack.h"
16 #include "base/run_loop.h"
17 #include "base/time/time.h"
20 #import <AppKit/AppKit.h>
21 #endif // !defined(OS_IOS)
27 void CFRunLoopAddSourceToAllModes(CFRunLoopRef rl, CFRunLoopSourceRef source) {
28 CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes);
29 CFRunLoopAddSource(rl, source, kMessageLoopExclusiveRunLoopMode);
32 void CFRunLoopRemoveSourceFromAllModes(CFRunLoopRef rl,
33 CFRunLoopSourceRef source) {
34 CFRunLoopRemoveSource(rl, source, kCFRunLoopCommonModes);
35 CFRunLoopRemoveSource(rl, source, kMessageLoopExclusiveRunLoopMode);
38 void CFRunLoopAddTimerToAllModes(CFRunLoopRef rl, CFRunLoopTimerRef timer) {
39 CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes);
40 CFRunLoopAddTimer(rl, timer, kMessageLoopExclusiveRunLoopMode);
43 void CFRunLoopRemoveTimerFromAllModes(CFRunLoopRef rl,
44 CFRunLoopTimerRef timer) {
45 CFRunLoopRemoveTimer(rl, timer, kCFRunLoopCommonModes);
46 CFRunLoopRemoveTimer(rl, timer, kMessageLoopExclusiveRunLoopMode);
49 void CFRunLoopAddObserverToAllModes(CFRunLoopRef rl,
50 CFRunLoopObserverRef observer) {
51 CFRunLoopAddObserver(rl, observer, kCFRunLoopCommonModes);
52 CFRunLoopAddObserver(rl, observer, kMessageLoopExclusiveRunLoopMode);
55 void CFRunLoopRemoveObserverFromAllModes(CFRunLoopRef rl,
56 CFRunLoopObserverRef observer) {
57 CFRunLoopRemoveObserver(rl, observer, kCFRunLoopCommonModes);
58 CFRunLoopRemoveObserver(rl, observer, kMessageLoopExclusiveRunLoopMode);
61 void NoOp(void* info) {
64 const CFTimeInterval kCFTimeIntervalMax =
65 std::numeric_limits<CFTimeInterval>::max();
68 // Set to true if MessagePumpMac::Create() is called before NSApp is
69 // initialized. Only accessed from the main thread.
70 bool g_not_using_cr_app = false;
73 // Call through to CFRunLoopTimerSetTolerance(), which is only available on
75 void SetTimerTolerance(CFRunLoopTimerRef timer, CFTimeInterval tolerance) {
76 typedef void (*CFRunLoopTimerSetTolerancePtr)(CFRunLoopTimerRef timer,
77 CFTimeInterval tolerance);
79 static CFRunLoopTimerSetTolerancePtr settimertolerance_function_ptr;
81 static dispatch_once_t get_timer_tolerance_function_ptr_once;
82 dispatch_once(&get_timer_tolerance_function_ptr_once, ^{
83 NSBundle* bundle =[NSBundle
84 bundleWithPath:@"/System/Library/Frameworks/CoreFoundation.framework"];
85 const char* path = [[bundle executablePath] fileSystemRepresentation];
87 void* library_handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL);
88 CHECK(library_handle) << dlerror();
89 settimertolerance_function_ptr =
90 reinterpret_cast<CFRunLoopTimerSetTolerancePtr>(
91 dlsym(library_handle, "CFRunLoopTimerSetTolerance"));
93 dlclose(library_handle);
96 if (settimertolerance_function_ptr)
97 settimertolerance_function_ptr(timer, tolerance);
103 const CFStringRef kMessageLoopExclusiveRunLoopMode =
104 CFSTR("kMessageLoopExclusiveRunLoopMode");
106 // A scoper for autorelease pools created from message pump run loops.
107 // Avoids dirtying up the ScopedNSAutoreleasePool interface for the rare
108 // case where an autorelease pool needs to be passed in.
109 class MessagePumpScopedAutoreleasePool {
111 explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) :
112 pool_(pump->CreateAutoreleasePool()) {
114 ~MessagePumpScopedAutoreleasePool() {
119 NSAutoreleasePool* pool_;
120 DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool);
123 // Must be called on the run loop thread.
124 MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase()
126 delayed_work_fire_time_(kCFTimeIntervalMax),
127 timer_slack_(base::TIMER_SLACK_NONE),
129 run_nesting_level_(0),
130 deepest_nesting_level_(0),
131 delegateless_work_(false),
132 delegateless_idle_work_(false) {
133 run_loop_ = CFRunLoopGetCurrent();
136 // Set a repeating timer with a preposterous firing time and interval. The
137 // timer will effectively never fire as-is. The firing time will be adjusted
138 // as needed when ScheduleDelayedWork is called.
139 CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
140 timer_context.info = this;
141 delayed_work_timer_ = CFRunLoopTimerCreate(NULL, // allocator
142 kCFTimeIntervalMax, // fire time
143 kCFTimeIntervalMax, // interval
148 CFRunLoopAddTimerToAllModes(run_loop_, delayed_work_timer_);
150 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
151 source_context.info = this;
152 source_context.perform = RunWorkSource;
153 work_source_ = CFRunLoopSourceCreate(NULL, // allocator
156 CFRunLoopAddSourceToAllModes(run_loop_, work_source_);
158 source_context.perform = RunIdleWorkSource;
159 idle_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
162 CFRunLoopAddSourceToAllModes(run_loop_, idle_work_source_);
164 source_context.perform = RunNestingDeferredWorkSource;
165 nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
168 CFRunLoopAddSourceToAllModes(run_loop_, nesting_deferred_work_source_);
170 CFRunLoopObserverContext observer_context = CFRunLoopObserverContext();
171 observer_context.info = this;
172 pre_wait_observer_ = CFRunLoopObserverCreate(NULL, // allocator
173 kCFRunLoopBeforeWaiting,
178 CFRunLoopAddObserverToAllModes(run_loop_, pre_wait_observer_);
180 pre_source_observer_ = CFRunLoopObserverCreate(NULL, // allocator
181 kCFRunLoopBeforeSources,
186 CFRunLoopAddObserverToAllModes(run_loop_, pre_source_observer_);
188 enter_exit_observer_ = CFRunLoopObserverCreate(NULL, // allocator
195 CFRunLoopAddObserverToAllModes(run_loop_, enter_exit_observer_);
198 // Ideally called on the run loop thread. If other run loops were running
199 // lower on the run loop thread's stack when this object was created, the
200 // same number of run loops must be running when this object is destroyed.
201 MessagePumpCFRunLoopBase::~MessagePumpCFRunLoopBase() {
202 CFRunLoopRemoveObserverFromAllModes(run_loop_, enter_exit_observer_);
203 CFRelease(enter_exit_observer_);
205 CFRunLoopRemoveObserverFromAllModes(run_loop_, pre_source_observer_);
206 CFRelease(pre_source_observer_);
208 CFRunLoopRemoveObserverFromAllModes(run_loop_, pre_wait_observer_);
209 CFRelease(pre_wait_observer_);
211 CFRunLoopRemoveSourceFromAllModes(run_loop_, nesting_deferred_work_source_);
212 CFRelease(nesting_deferred_work_source_);
214 CFRunLoopRemoveSourceFromAllModes(run_loop_, idle_work_source_);
215 CFRelease(idle_work_source_);
217 CFRunLoopRemoveSourceFromAllModes(run_loop_, work_source_);
218 CFRelease(work_source_);
220 CFRunLoopRemoveTimerFromAllModes(run_loop_, delayed_work_timer_);
221 CFRelease(delayed_work_timer_);
223 CFRelease(run_loop_);
226 // Must be called on the run loop thread.
227 void MessagePumpCFRunLoopBase::Run(Delegate* delegate) {
228 // nesting_level_ will be incremented in EnterExitRunLoop, so set
229 // run_nesting_level_ accordingly.
230 int last_run_nesting_level = run_nesting_level_;
231 run_nesting_level_ = nesting_level_ + 1;
233 Delegate* last_delegate = delegate_;
234 SetDelegate(delegate);
238 // Restore the previous state of the object.
239 SetDelegate(last_delegate);
240 run_nesting_level_ = last_run_nesting_level;
243 void MessagePumpCFRunLoopBase::SetDelegate(Delegate* delegate) {
244 delegate_ = delegate;
247 // If any work showed up but could not be dispatched for want of a
248 // delegate, set it up for dispatch again now that a delegate is
250 if (delegateless_work_) {
251 CFRunLoopSourceSignal(work_source_);
252 delegateless_work_ = false;
254 if (delegateless_idle_work_) {
255 CFRunLoopSourceSignal(idle_work_source_);
256 delegateless_idle_work_ = false;
261 // May be called on any thread.
262 void MessagePumpCFRunLoopBase::ScheduleWork() {
263 CFRunLoopSourceSignal(work_source_);
264 CFRunLoopWakeUp(run_loop_);
267 // Must be called on the run loop thread.
268 void MessagePumpCFRunLoopBase::ScheduleDelayedWork(
269 const TimeTicks& delayed_work_time) {
270 TimeDelta delta = delayed_work_time - TimeTicks::Now();
271 delayed_work_fire_time_ = CFAbsoluteTimeGetCurrent() + delta.InSecondsF();
272 CFRunLoopTimerSetNextFireDate(delayed_work_timer_, delayed_work_fire_time_);
273 if (timer_slack_ == TIMER_SLACK_MAXIMUM) {
274 SetTimerTolerance(delayed_work_timer_, delta.InSecondsF() * 0.5);
276 SetTimerTolerance(delayed_work_timer_, 0);
280 void MessagePumpCFRunLoopBase::SetTimerSlack(TimerSlack timer_slack) {
281 timer_slack_ = timer_slack;
284 // Called from the run loop.
286 void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer,
288 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
290 // The timer won't fire again until it's reset.
291 self->delayed_work_fire_time_ = kCFTimeIntervalMax;
293 // CFRunLoopTimers fire outside of the priority scheme for CFRunLoopSources.
294 // In order to establish the proper priority in which work and delayed work
295 // are processed one for one, the timer used to schedule delayed work must
296 // signal a CFRunLoopSource used to dispatch both work and delayed work.
297 CFRunLoopSourceSignal(self->work_source_);
300 // Called from the run loop.
302 void MessagePumpCFRunLoopBase::RunWorkSource(void* info) {
303 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
304 base::mac::CallWithEHFrame(^{
309 // Called by MessagePumpCFRunLoopBase::RunWorkSource.
310 bool MessagePumpCFRunLoopBase::RunWork() {
312 // This point can be reached with a NULL delegate_ if Run is not on the
313 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
314 // here when a delegate is available.
315 delegateless_work_ = true;
319 // The NSApplication-based run loop only drains the autorelease pool at each
320 // UI event (NSEvent). The autorelease pool is not drained for each
321 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
322 // objects if the app is not currently handling a UI event to ensure they're
323 // released promptly even in the absence of UI events.
324 MessagePumpScopedAutoreleasePool autorelease_pool(this);
326 // Call DoWork and DoDelayedWork once, and if something was done, arrange to
327 // come back here again as long as the loop is still running.
328 bool did_work = delegate_->DoWork();
329 bool resignal_work_source = did_work;
332 delegate_->DoDelayedWork(&next_time);
334 // Determine whether there's more delayed work, and if so, if it needs to
335 // be done at some point in the future or if it's already time to do it.
336 // Only do these checks if did_work is false. If did_work is true, this
337 // function, and therefore any additional delayed work, will get another
338 // chance to run before the loop goes to sleep.
339 bool more_delayed_work = !next_time.is_null();
340 if (more_delayed_work) {
341 TimeDelta delay = next_time - TimeTicks::Now();
342 if (delay > TimeDelta()) {
343 // There's more delayed work to be done in the future.
344 ScheduleDelayedWork(next_time);
346 // There's more delayed work to be done, and its time is in the past.
347 // Arrange to come back here directly as long as the loop is still
349 resignal_work_source = true;
354 if (resignal_work_source) {
355 CFRunLoopSourceSignal(work_source_);
358 return resignal_work_source;
361 // Called from the run loop.
363 void MessagePumpCFRunLoopBase::RunIdleWorkSource(void* info) {
364 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
365 base::mac::CallWithEHFrame(^{
370 // Called by MessagePumpCFRunLoopBase::RunIdleWorkSource.
371 bool MessagePumpCFRunLoopBase::RunIdleWork() {
373 // This point can be reached with a NULL delegate_ if Run is not on the
374 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
375 // here when a delegate is available.
376 delegateless_idle_work_ = true;
380 // The NSApplication-based run loop only drains the autorelease pool at each
381 // UI event (NSEvent). The autorelease pool is not drained for each
382 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
383 // objects if the app is not currently handling a UI event to ensure they're
384 // released promptly even in the absence of UI events.
385 MessagePumpScopedAutoreleasePool autorelease_pool(this);
387 // Call DoIdleWork once, and if something was done, arrange to come back here
388 // again as long as the loop is still running.
389 bool did_work = delegate_->DoIdleWork();
391 CFRunLoopSourceSignal(idle_work_source_);
397 // Called from the run loop.
399 void MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource(void* info) {
400 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
401 base::mac::CallWithEHFrame(^{
402 self->RunNestingDeferredWork();
406 // Called by MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource.
407 bool MessagePumpCFRunLoopBase::RunNestingDeferredWork() {
409 // This point can be reached with a NULL delegate_ if Run is not on the
410 // stack but foreign code is spinning the CFRunLoop. There's no sense in
411 // attempting to do any work or signalling the work sources because
412 // without a delegate, work is not possible.
416 // Immediately try work in priority order.
418 if (!RunIdleWork()) {
422 // Work was done. Arrange for the loop to try non-nestable idle work on
423 // a subsequent pass.
424 CFRunLoopSourceSignal(idle_work_source_);
430 // Called before the run loop goes to sleep or exits, or processes sources.
431 void MessagePumpCFRunLoopBase::MaybeScheduleNestingDeferredWork() {
432 // deepest_nesting_level_ is set as run loops are entered. If the deepest
433 // level encountered is deeper than the current level, a nested loop
434 // (relative to the current level) ran since the last time nesting-deferred
435 // work was scheduled. When that situation is encountered, schedule
436 // nesting-deferred work in case any work was deferred because nested work
438 if (deepest_nesting_level_ > nesting_level_) {
439 deepest_nesting_level_ = nesting_level_;
440 CFRunLoopSourceSignal(nesting_deferred_work_source_);
444 // Called from the run loop.
446 void MessagePumpCFRunLoopBase::PreWaitObserver(CFRunLoopObserverRef observer,
447 CFRunLoopActivity activity,
449 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
450 base::mac::CallWithEHFrame(^{
451 // Attempt to do some idle work before going to sleep.
454 // The run loop is about to go to sleep. If any of the work done since it
455 // started or woke up resulted in a nested run loop running,
456 // nesting-deferred work may have accumulated. Schedule it for processing
458 self->MaybeScheduleNestingDeferredWork();
462 // Called from the run loop.
464 void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer,
465 CFRunLoopActivity activity,
467 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
469 // The run loop has reached the top of the loop and is about to begin
470 // processing sources. If the last iteration of the loop at this nesting
471 // level did not sleep or exit, nesting-deferred work may have accumulated
472 // if a nested loop ran. Schedule nesting-deferred work for processing if
474 base::mac::CallWithEHFrame(^{
475 self->MaybeScheduleNestingDeferredWork();
479 // Called from the run loop.
481 void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer,
482 CFRunLoopActivity activity,
484 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
487 case kCFRunLoopEntry:
488 ++self->nesting_level_;
489 if (self->nesting_level_ > self->deepest_nesting_level_) {
490 self->deepest_nesting_level_ = self->nesting_level_;
495 // Not all run loops go to sleep. If a run loop is stopped before it
496 // goes to sleep due to a CFRunLoopStop call, or if the timeout passed
497 // to CFRunLoopRunInMode expires, the run loop may proceed directly from
498 // handling sources to exiting without any sleep. This most commonly
499 // occurs when CFRunLoopRunInMode is passed a timeout of 0, causing it
500 // to make a single pass through the loop and exit without sleep. Some
501 // native loops use CFRunLoop in this way. Because PreWaitObserver will
502 // not be called in these case, MaybeScheduleNestingDeferredWork needs
503 // to be called here, as the run loop exits.
505 // MaybeScheduleNestingDeferredWork consults self->nesting_level_
506 // to determine whether to schedule nesting-deferred work. It expects
507 // the nesting level to be set to the depth of the loop that is going
508 // to sleep or exiting. It must be called before decrementing the
509 // value so that the value still corresponds to the level of the exiting
511 base::mac::CallWithEHFrame(^{
512 self->MaybeScheduleNestingDeferredWork();
514 --self->nesting_level_;
521 base::mac::CallWithEHFrame(^{
522 self->EnterExitRunLoop(activity);
526 // Called by MessagePumpCFRunLoopBase::EnterExitRunLoop. The default
527 // implementation is a no-op.
528 void MessagePumpCFRunLoopBase::EnterExitRunLoop(CFRunLoopActivity activity) {
531 // Base version returns a standard NSAutoreleasePool.
532 AutoreleasePoolType* MessagePumpCFRunLoopBase::CreateAutoreleasePool() {
533 return [[NSAutoreleasePool alloc] init];
536 MessagePumpCFRunLoop::MessagePumpCFRunLoop()
537 : quit_pending_(false) {
540 MessagePumpCFRunLoop::~MessagePumpCFRunLoop() {}
542 // Called by MessagePumpCFRunLoopBase::DoRun. If other CFRunLoopRun loops were
543 // running lower on the run loop thread's stack when this object was created,
544 // the same number of CFRunLoopRun loops must be running for the outermost call
545 // to Run. Run/DoRun are reentrant after that point.
546 void MessagePumpCFRunLoop::DoRun(Delegate* delegate) {
547 // This is completely identical to calling CFRunLoopRun(), except autorelease
548 // pool management is introduced.
551 MessagePumpScopedAutoreleasePool autorelease_pool(this);
552 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
555 } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished);
558 // Must be called on the run loop thread.
559 void MessagePumpCFRunLoop::Quit() {
560 // Stop the innermost run loop managed by this MessagePumpCFRunLoop object.
561 if (nesting_level() == run_nesting_level()) {
562 // This object is running the innermost loop, just stop it.
563 CFRunLoopStop(run_loop());
565 // There's another loop running inside the loop managed by this object.
566 // In other words, someone else called CFRunLoopRunInMode on the same
567 // thread, deeper on the stack than the deepest Run call. Don't preempt
568 // other run loops, just mark this object to quit the innermost Run as
569 // soon as the other inner loops not managed by Run are done.
570 quit_pending_ = true;
574 // Called by MessagePumpCFRunLoopBase::EnterExitObserver.
575 void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) {
576 if (activity == kCFRunLoopExit &&
577 nesting_level() == run_nesting_level() &&
579 // Quit was called while loops other than those managed by this object
580 // were running further inside a run loop managed by this object. Now
581 // that all unmanaged inner run loops are gone, stop the loop running
583 CFRunLoopStop(run_loop());
584 quit_pending_ = false;
588 MessagePumpNSRunLoop::MessagePumpNSRunLoop()
589 : keep_running_(true) {
590 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
591 source_context.perform = NoOp;
592 quit_source_ = CFRunLoopSourceCreate(NULL, // allocator
595 CFRunLoopAddSourceToAllModes(run_loop(), quit_source_);
598 MessagePumpNSRunLoop::~MessagePumpNSRunLoop() {
599 CFRunLoopRemoveSourceFromAllModes(run_loop(), quit_source_);
600 CFRelease(quit_source_);
603 void MessagePumpNSRunLoop::DoRun(Delegate* delegate) {
604 while (keep_running_) {
605 // NSRunLoop manages autorelease pools itself.
606 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
607 beforeDate:[NSDate distantFuture]];
610 keep_running_ = true;
613 void MessagePumpNSRunLoop::Quit() {
614 keep_running_ = false;
615 CFRunLoopSourceSignal(quit_source_);
616 CFRunLoopWakeUp(run_loop());
620 MessagePumpUIApplication::MessagePumpUIApplication()
624 MessagePumpUIApplication::~MessagePumpUIApplication() {}
626 void MessagePumpUIApplication::DoRun(Delegate* delegate) {
630 void MessagePumpUIApplication::Quit() {
634 void MessagePumpUIApplication::Attach(Delegate* delegate) {
636 run_loop_ = new RunLoop();
637 CHECK(run_loop_->BeforeRun());
638 SetDelegate(delegate);
643 MessagePumpNSApplication::MessagePumpNSApplication()
644 : keep_running_(true),
645 running_own_loop_(false) {
648 MessagePumpNSApplication::~MessagePumpNSApplication() {}
650 void MessagePumpNSApplication::DoRun(Delegate* delegate) {
651 bool last_running_own_loop_ = running_own_loop_;
653 // NSApp must be initialized by calling:
654 // [{some class which implements CrAppProtocol} sharedApplication]
655 // Most likely candidates are CrApplication or BrowserCrApplication.
656 // These can be initialized from C++ code by calling
657 // RegisterCrApp() or RegisterBrowserCrApp().
660 if (![NSApp isRunning]) {
661 running_own_loop_ = false;
662 // NSApplication manages autorelease pools itself when run this way.
665 running_own_loop_ = true;
666 NSDate* distant_future = [NSDate distantFuture];
667 while (keep_running_) {
668 MessagePumpScopedAutoreleasePool autorelease_pool(this);
669 NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
670 untilDate:distant_future
671 inMode:NSDefaultRunLoopMode
674 [NSApp sendEvent:event];
677 keep_running_ = true;
680 running_own_loop_ = last_running_own_loop_;
683 void MessagePumpNSApplication::Quit() {
684 if (!running_own_loop_) {
685 [[NSApplication sharedApplication] stop:nil];
687 keep_running_ = false;
690 // Send a fake event to wake the loop up.
691 [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
703 MessagePumpCrApplication::MessagePumpCrApplication() {
706 MessagePumpCrApplication::~MessagePumpCrApplication() {
709 // Prevents an autorelease pool from being created if the app is in the midst of
710 // handling a UI event because various parts of AppKit depend on objects that
711 // are created while handling a UI event to be autoreleased in the event loop.
712 // An example of this is NSWindowController. When a window with a window
713 // controller is closed it goes through a stack like this:
714 // (Several stack frames elided for clarity)
716 // #0 [NSWindowController autorelease]
718 // #2 MessagePumpCFRunLoopBase::DoWork()
719 // #3 [NSRunLoop run]
720 // #4 [NSButton performClick:]
721 // #5 [NSWindow sendEvent:]
722 // #6 [NSApp sendEvent:]
725 // -performClick: spins a nested run loop. If the pool created in DoWork was a
726 // standard NSAutoreleasePool, it would release the objects that were
727 // autoreleased into it once DoWork released it. This would cause the window
728 // controller, which autoreleased itself in frame #0, to release itself, and
729 // possibly free itself. Unfortunately this window controller controls the
730 // window in frame #5. When the stack is unwound to frame #5, the window would
731 // no longer exists and crashes may occur. Apple gets around this by never
732 // releasing the pool it creates in frame #4, and letting frame #7 clean it up
733 // when it cleans up the pool that wraps frame #7. When an autorelease pool is
734 // released it releases all other pools that were created after it on the
735 // autorelease pool stack.
737 // CrApplication is responsible for setting handlingSendEvent to true just
738 // before it sends the event through the event handling mechanism, and
739 // returning it to its previous value once the event has been sent.
740 AutoreleasePoolType* MessagePumpCrApplication::CreateAutoreleasePool() {
741 if (MessagePumpMac::IsHandlingSendEvent())
743 return MessagePumpNSApplication::CreateAutoreleasePool();
747 bool MessagePumpMac::UsingCrApp() {
748 DCHECK([NSThread isMainThread]);
750 // If NSApp is still not initialized, then the subclass used cannot
754 // The pump was created using MessagePumpNSApplication.
755 if (g_not_using_cr_app)
758 return [NSApp conformsToProtocol:@protocol(CrAppProtocol)];
762 bool MessagePumpMac::IsHandlingSendEvent() {
763 DCHECK([NSApp conformsToProtocol:@protocol(CrAppProtocol)]);
764 NSObject<CrAppProtocol>* app = static_cast<NSObject<CrAppProtocol>*>(NSApp);
765 return [app isHandlingSendEvent];
767 #endif // !defined(OS_IOS)
770 MessagePump* MessagePumpMac::Create() {
771 if ([NSThread isMainThread]) {
773 return new MessagePumpUIApplication;
775 if ([NSApp conformsToProtocol:@protocol(CrAppProtocol)])
776 return new MessagePumpCrApplication;
778 // The main-thread MessagePump implementations REQUIRE an NSApp.
779 // Executables which have specific requirements for their
780 // NSApplication subclass should initialize appropriately before
781 // creating an event loop.
782 [NSApplication sharedApplication];
783 g_not_using_cr_app = true;
784 return new MessagePumpNSApplication;
788 return new MessagePumpNSRunLoop;