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>
13 #include "base/format_macros.h"
14 #include "base/logging.h"
15 #include "base/mac/scoped_cftyperef.h"
16 #include "base/message_loop/timer_slack.h"
17 #include "base/metrics/histogram.h"
18 #include "base/run_loop.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/time/time.h"
23 #import <AppKit/AppKit.h>
24 #endif // !defined(OS_IOS)
28 void NoOp(void* info) {
31 const CFTimeInterval kCFTimeIntervalMax =
32 std::numeric_limits<CFTimeInterval>::max();
35 // Set to true if MessagePumpMac::Create() is called before NSApp is
36 // initialized. Only accessed from the main thread.
37 bool g_not_using_cr_app = false;
40 // Call through to CFRunLoopTimerSetTolerance(), which is only available on
42 void SetTimerTolerance(CFRunLoopTimerRef timer, CFTimeInterval tolerance) {
43 typedef void (*CFRunLoopTimerSetTolerancePtr)(CFRunLoopTimerRef timer,
44 CFTimeInterval tolerance);
46 static CFRunLoopTimerSetTolerancePtr settimertolerance_function_ptr;
48 static dispatch_once_t get_timer_tolerance_function_ptr_once;
49 dispatch_once(&get_timer_tolerance_function_ptr_once, ^{
50 NSBundle* bundle =[NSBundle
51 bundleWithPath:@"/System/Library/Frameworks/CoreFoundation.framework"];
52 const char* path = [[bundle executablePath] fileSystemRepresentation];
54 void* library_handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL);
55 CHECK(library_handle) << dlerror();
56 settimertolerance_function_ptr =
57 reinterpret_cast<CFRunLoopTimerSetTolerancePtr>(
58 dlsym(library_handle, "CFRunLoopTimerSetTolerance"));
60 dlclose(library_handle);
63 if (settimertolerance_function_ptr)
64 settimertolerance_function_ptr(timer, tolerance);
71 // A scoper for autorelease pools created from message pump run loops.
72 // Avoids dirtying up the ScopedNSAutoreleasePool interface for the rare
73 // case where an autorelease pool needs to be passed in.
74 class MessagePumpScopedAutoreleasePool {
76 explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) :
77 pool_(pump->CreateAutoreleasePool()) {
79 ~MessagePumpScopedAutoreleasePool() {
84 NSAutoreleasePool* pool_;
85 DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool);
88 // This class is used to instrument the MessagePump to gather various timing
89 // data about when the underlying run loop is entered, when it is waiting, and
90 // when it is servicing its delegate.
92 // The metrics are gathered as UMA-tracked histograms. To gather the data over
93 // time, sampling is used, such that a new histogram is created for each metric
94 // every |sampling_interval| for |sampling_duration|. After sampling is
95 // complete, this class deletes itself.
96 class MessagePumpInstrumentation {
98 // Creates an instrument for the MessagePump on the current thread. Every
99 // |sampling_interval|, a new histogram will be created to track the metrics
100 // over time. After |sampling_duration|, this will delete itself, causing the
101 // WeakPtr to go NULL.
102 static WeakPtr<MessagePumpInstrumentation> Create(
103 const TimeDelta& sampling_interval,
104 const TimeDelta& sampling_duration) {
105 MessagePumpInstrumentation* instrument =
106 new MessagePumpInstrumentation(sampling_interval, sampling_duration);
107 return instrument->weak_ptr_factory_.GetWeakPtr();
110 // Starts the timer that runs the sampling instrumentation. Can be called
111 // multiple times as a noop.
112 void StartIfNeeded() {
116 sampling_start_time_ = generation_start_time_ = TimeTicks::Now();
118 CFRunLoopTimerContext timer_context = { .info = this };
119 timer_.reset(CFRunLoopTimerCreate(
121 (Time::Now() + sampling_interval_).ToCFAbsoluteTime(),
122 sampling_interval_.InSecondsF(),
125 &MessagePumpInstrumentation::TimerFired,
127 CFRunLoopAddTimer(CFRunLoopGetCurrent(),
129 kCFRunLoopCommonModes);
132 // Used to track kCFRunLoopEntry.
134 loop_run_times_.push(TimeTicks::Now());
137 // Used to track kCFRunLoopExit.
139 TimeDelta duration = TimeTicks::Now() - loop_run_times_.top();
140 loop_run_times_.pop();
141 GetHistogram(LOOP_CYCLE)->AddTime(duration);
144 // Used to track kCFRunLoopBeforeWaiting.
145 void WaitingStarted() {
146 loop_wait_times_.push(TimeTicks::Now());
149 // Used to track kCFRunLoopAfterWaiting.
150 void WaitingFinished() {
151 TimeDelta duration = TimeTicks::Now() - loop_wait_times_.top();
152 loop_wait_times_.pop();
153 GetHistogram(LOOP_WAIT)->AddTime(duration);
156 // Used to track when the MessagePump will invoke its |delegate|.
157 void WorkSourceEntered(MessagePump::Delegate* delegate) {
158 work_source_times_.push(TimeTicks::Now());
161 TimeDelta queuing_delay;
162 delegate->GetQueueingInformation(&queue_size, &queuing_delay);
163 GetHistogram(QUEUE_SIZE)->Add(queue_size);
164 GetHistogram(QUEUE_DELAY)->AddTime(queuing_delay);
168 // Used to track the completion of servicing the MessagePump::Delegate.
169 void WorkSourceExited() {
170 TimeDelta duration = TimeTicks::Now() - work_source_times_.top();
171 work_source_times_.pop();
172 GetHistogram(WORK_SOURCE)->AddTime(duration);
176 enum HistogramEvent {
177 // Time-based histograms:
178 LOOP_CYCLE, // LoopEntered/LoopExited
179 LOOP_WAIT, // WaitingStarted/WaitingEnded
180 WORK_SOURCE, // WorkSourceExited
181 QUEUE_DELAY, // WorkSourceEntered
183 // Value-based histograms:
184 // NOTE: Do not add value-based histograms before this event, only after.
185 QUEUE_SIZE, // WorkSourceEntered
190 MessagePumpInstrumentation(const TimeDelta& sampling_interval,
191 const TimeDelta& sampling_duration)
192 : weak_ptr_factory_(this),
193 sampling_interval_(sampling_interval),
194 sampling_duration_(sampling_duration),
195 sample_generation_(0) {
196 // Create all the histogram objects that will be used for sampling.
197 const char kHistogramName[] = "MessagePumpMac.%s.SampleMs.%" PRId64;
198 for (TimeDelta i; i < sampling_duration_; i += sampling_interval_) {
199 int64 sample = i.InMilliseconds();
201 // Generate the time-based histograms.
202 for (int j = LOOP_CYCLE; j < QUEUE_SIZE; ++j) {
203 std::string name = StringPrintf(kHistogramName,
204 NameForEnum(static_cast<HistogramEvent>(j)), sample);
205 histograms_[j].push_back(
206 Histogram::FactoryTimeGet(name, TimeDelta::FromMilliseconds(1),
207 sampling_interval_, 50,
208 HistogramBase::kUmaTargetedHistogramFlag));
211 // Generate the value-based histograms.
212 for (int j = QUEUE_SIZE; j < HISTOGRAM_EVENT_MAX; ++j) {
213 std::string name = StringPrintf(kHistogramName,
214 NameForEnum(static_cast<HistogramEvent>(j)), sample);
215 histograms_[j].push_back(
216 Histogram::FactoryGet(name, 1, 10000, 50,
217 HistogramBase::kUmaTargetedHistogramFlag));
222 ~MessagePumpInstrumentation() {
224 CFRunLoopTimerInvalidate(timer_);
227 const char* NameForEnum(HistogramEvent event) {
229 case LOOP_CYCLE: return "LoopCycle";
230 case LOOP_WAIT: return "Waiting";
231 case WORK_SOURCE: return "WorkSource";
232 case QUEUE_DELAY: return "QueueingDelay";
233 case QUEUE_SIZE: return "QueueSize";
240 static void TimerFired(CFRunLoopTimerRef timer, void* context) {
241 static_cast<MessagePumpInstrumentation*>(context)->TimerFired();
244 // Called by the run loop when the sampling_interval_ has elapsed. Advances
245 // the sample_generation_, which controls into which histogram data is
246 // recorded, while recording and accounting for timer skew. Will delete this
247 // object after |sampling_duration_| has elapsed.
249 TimeTicks now = TimeTicks::Now();
250 TimeDelta delta = now - generation_start_time_;
252 // The timer fired, so advance the generation by at least one.
253 ++sample_generation_;
255 // To account for large timer skew/drift, advance the generation by any
256 // more completed intervals.
257 for (TimeDelta skew_advance = delta - sampling_interval_;
258 skew_advance >= sampling_interval_;
259 skew_advance -= sampling_interval_) {
260 ++sample_generation_;
263 generation_start_time_ = now;
264 if (now >= sampling_start_time_ + sampling_duration_)
268 HistogramBase* GetHistogram(HistogramEvent event) {
269 DCHECK_LT(sample_generation_, histograms_[event].size());
270 return histograms_[event][sample_generation_];
273 // Vends the pointer to the Create()or.
274 WeakPtrFactory<MessagePumpInstrumentation> weak_ptr_factory_;
276 // The interval and duration of the sampling.
277 TimeDelta sampling_interval_;
278 TimeDelta sampling_duration_;
280 // The time at which sampling started.
281 TimeTicks sampling_start_time_;
283 // The timer that advances the sample_generation_ and sets the
284 // generation_start_time_ for the current sample interval.
285 base::ScopedCFTypeRef<CFRunLoopTimerRef> timer_;
287 // The two-dimensional array of histograms. The first dimension is the
288 // HistogramEvent type. The second is for the sampling intervals.
289 std::vector<HistogramBase*> histograms_[HISTOGRAM_EVENT_MAX];
291 // The index in the second dimension of histograms_, which controls in which
292 // sampled histogram events are recorded.
293 size_t sample_generation_;
295 // The last time at which the timer fired. This is used to track timer skew
296 // (i.e. it did not fire on time) and properly account for it when advancing
297 // samle_generation_.
298 TimeTicks generation_start_time_;
300 // MessagePump activations can be nested. Use a stack for each of the
301 // possibly reentrant HistogramEvent types to properly balance and calculate
302 // the timing information.
303 std::stack<TimeTicks> loop_run_times_;
304 std::stack<TimeTicks> loop_wait_times_;
305 std::stack<TimeTicks> work_source_times_;
307 DISALLOW_COPY_AND_ASSIGN(MessagePumpInstrumentation);
310 // Must be called on the run loop thread.
311 MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase()
313 delayed_work_fire_time_(kCFTimeIntervalMax),
314 timer_slack_(base::TIMER_SLACK_NONE),
316 run_nesting_level_(0),
317 deepest_nesting_level_(0),
318 delegateless_work_(false),
319 delegateless_idle_work_(false) {
320 run_loop_ = CFRunLoopGetCurrent();
323 // Set a repeating timer with a preposterous firing time and interval. The
324 // timer will effectively never fire as-is. The firing time will be adjusted
325 // as needed when ScheduleDelayedWork is called.
326 CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
327 timer_context.info = this;
328 delayed_work_timer_ = CFRunLoopTimerCreate(NULL, // allocator
329 kCFTimeIntervalMax, // fire time
330 kCFTimeIntervalMax, // interval
335 CFRunLoopAddTimer(run_loop_, delayed_work_timer_, kCFRunLoopCommonModes);
337 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
338 source_context.info = this;
339 source_context.perform = RunWorkSource;
340 work_source_ = CFRunLoopSourceCreate(NULL, // allocator
343 CFRunLoopAddSource(run_loop_, work_source_, kCFRunLoopCommonModes);
345 source_context.perform = RunIdleWorkSource;
346 idle_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
349 CFRunLoopAddSource(run_loop_, idle_work_source_, kCFRunLoopCommonModes);
351 source_context.perform = RunNestingDeferredWorkSource;
352 nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
355 CFRunLoopAddSource(run_loop_, nesting_deferred_work_source_,
356 kCFRunLoopCommonModes);
358 CFRunLoopObserverContext observer_context = CFRunLoopObserverContext();
359 observer_context.info = this;
360 pre_wait_observer_ = CFRunLoopObserverCreate(NULL, // allocator
361 kCFRunLoopBeforeWaiting |
362 kCFRunLoopAfterWaiting,
365 StartOrEndWaitObserver,
367 CFRunLoopAddObserver(run_loop_, pre_wait_observer_, kCFRunLoopCommonModes);
369 pre_source_observer_ = CFRunLoopObserverCreate(NULL, // allocator
370 kCFRunLoopBeforeSources,
375 CFRunLoopAddObserver(run_loop_, pre_source_observer_, kCFRunLoopCommonModes);
377 enter_exit_observer_ = CFRunLoopObserverCreate(NULL, // allocator
384 CFRunLoopAddObserver(run_loop_, enter_exit_observer_, kCFRunLoopCommonModes);
387 // Ideally called on the run loop thread. If other run loops were running
388 // lower on the run loop thread's stack when this object was created, the
389 // same number of run loops must be running when this object is destroyed.
390 MessagePumpCFRunLoopBase::~MessagePumpCFRunLoopBase() {
391 CFRunLoopRemoveObserver(run_loop_, enter_exit_observer_,
392 kCFRunLoopCommonModes);
393 CFRelease(enter_exit_observer_);
395 CFRunLoopRemoveObserver(run_loop_, pre_source_observer_,
396 kCFRunLoopCommonModes);
397 CFRelease(pre_source_observer_);
399 CFRunLoopRemoveObserver(run_loop_, pre_wait_observer_,
400 kCFRunLoopCommonModes);
401 CFRelease(pre_wait_observer_);
403 CFRunLoopRemoveSource(run_loop_, nesting_deferred_work_source_,
404 kCFRunLoopCommonModes);
405 CFRelease(nesting_deferred_work_source_);
407 CFRunLoopRemoveSource(run_loop_, idle_work_source_, kCFRunLoopCommonModes);
408 CFRelease(idle_work_source_);
410 CFRunLoopRemoveSource(run_loop_, work_source_, kCFRunLoopCommonModes);
411 CFRelease(work_source_);
413 CFRunLoopRemoveTimer(run_loop_, delayed_work_timer_, kCFRunLoopCommonModes);
414 CFRelease(delayed_work_timer_);
416 CFRelease(run_loop_);
419 // Must be called on the run loop thread.
420 void MessagePumpCFRunLoopBase::Run(Delegate* delegate) {
421 // nesting_level_ will be incremented in EnterExitRunLoop, so set
422 // run_nesting_level_ accordingly.
423 int last_run_nesting_level = run_nesting_level_;
424 run_nesting_level_ = nesting_level_ + 1;
426 Delegate* last_delegate = delegate_;
427 SetDelegate(delegate);
431 // Restore the previous state of the object.
432 SetDelegate(last_delegate);
433 run_nesting_level_ = last_run_nesting_level;
436 void MessagePumpCFRunLoopBase::SetDelegate(Delegate* delegate) {
437 delegate_ = delegate;
440 // If any work showed up but could not be dispatched for want of a
441 // delegate, set it up for dispatch again now that a delegate is
443 if (delegateless_work_) {
444 CFRunLoopSourceSignal(work_source_);
445 delegateless_work_ = false;
447 if (delegateless_idle_work_) {
448 CFRunLoopSourceSignal(idle_work_source_);
449 delegateless_idle_work_ = false;
454 void MessagePumpCFRunLoopBase::EnableInstrumentation() {
455 instrumentation_ = MessagePumpInstrumentation::Create(
456 TimeDelta::FromSeconds(1), TimeDelta::FromSeconds(15));
459 // May be called on any thread.
460 void MessagePumpCFRunLoopBase::ScheduleWork() {
461 CFRunLoopSourceSignal(work_source_);
462 CFRunLoopWakeUp(run_loop_);
465 // Must be called on the run loop thread.
466 void MessagePumpCFRunLoopBase::ScheduleDelayedWork(
467 const TimeTicks& delayed_work_time) {
468 TimeDelta delta = delayed_work_time - TimeTicks::Now();
469 delayed_work_fire_time_ = CFAbsoluteTimeGetCurrent() + delta.InSecondsF();
470 CFRunLoopTimerSetNextFireDate(delayed_work_timer_, delayed_work_fire_time_);
471 if (timer_slack_ == TIMER_SLACK_MAXIMUM) {
472 SetTimerTolerance(delayed_work_timer_, delta.InSecondsF() * 0.5);
474 SetTimerTolerance(delayed_work_timer_, 0);
478 void MessagePumpCFRunLoopBase::SetTimerSlack(TimerSlack timer_slack) {
479 timer_slack_ = timer_slack;
482 // Called from the run loop.
484 void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer,
486 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
488 // The timer won't fire again until it's reset.
489 self->delayed_work_fire_time_ = kCFTimeIntervalMax;
491 // CFRunLoopTimers fire outside of the priority scheme for CFRunLoopSources.
492 // In order to establish the proper priority in which work and delayed work
493 // are processed one for one, the timer used to schedule delayed work must
494 // signal a CFRunLoopSource used to dispatch both work and delayed work.
495 CFRunLoopSourceSignal(self->work_source_);
498 // Called from the run loop.
500 void MessagePumpCFRunLoopBase::RunWorkSource(void* info) {
501 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
505 // Called by MessagePumpCFRunLoopBase::RunWorkSource.
506 bool MessagePumpCFRunLoopBase::RunWork() {
508 // This point can be reached with a NULL delegate_ if Run is not on the
509 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
510 // here when a delegate is available.
511 delegateless_work_ = true;
515 if (instrumentation_)
516 instrumentation_->WorkSourceEntered(delegate_);
518 // The NSApplication-based run loop only drains the autorelease pool at each
519 // UI event (NSEvent). The autorelease pool is not drained for each
520 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
521 // objects if the app is not currently handling a UI event to ensure they're
522 // released promptly even in the absence of UI events.
523 MessagePumpScopedAutoreleasePool autorelease_pool(this);
525 // Call DoWork and DoDelayedWork once, and if something was done, arrange to
526 // come back here again as long as the loop is still running.
527 bool did_work = delegate_->DoWork();
528 bool resignal_work_source = did_work;
531 delegate_->DoDelayedWork(&next_time);
533 // Determine whether there's more delayed work, and if so, if it needs to
534 // be done at some point in the future or if it's already time to do it.
535 // Only do these checks if did_work is false. If did_work is true, this
536 // function, and therefore any additional delayed work, will get another
537 // chance to run before the loop goes to sleep.
538 bool more_delayed_work = !next_time.is_null();
539 if (more_delayed_work) {
540 TimeDelta delay = next_time - TimeTicks::Now();
541 if (delay > TimeDelta()) {
542 // There's more delayed work to be done in the future.
543 ScheduleDelayedWork(next_time);
545 // There's more delayed work to be done, and its time is in the past.
546 // Arrange to come back here directly as long as the loop is still
548 resignal_work_source = true;
553 if (resignal_work_source) {
554 CFRunLoopSourceSignal(work_source_);
557 if (instrumentation_)
558 instrumentation_->WorkSourceExited();
560 return resignal_work_source;
563 // Called from the run loop.
565 void MessagePumpCFRunLoopBase::RunIdleWorkSource(void* info) {
566 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
570 // Called by MessagePumpCFRunLoopBase::RunIdleWorkSource.
571 bool MessagePumpCFRunLoopBase::RunIdleWork() {
573 // This point can be reached with a NULL delegate_ if Run is not on the
574 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
575 // here when a delegate is available.
576 delegateless_idle_work_ = true;
580 // The NSApplication-based run loop only drains the autorelease pool at each
581 // UI event (NSEvent). The autorelease pool is not drained for each
582 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
583 // objects if the app is not currently handling a UI event to ensure they're
584 // released promptly even in the absence of UI events.
585 MessagePumpScopedAutoreleasePool autorelease_pool(this);
587 // Call DoIdleWork once, and if something was done, arrange to come back here
588 // again as long as the loop is still running.
589 bool did_work = delegate_->DoIdleWork();
591 CFRunLoopSourceSignal(idle_work_source_);
597 // Called from the run loop.
599 void MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource(void* info) {
600 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
601 self->RunNestingDeferredWork();
604 // Called by MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource.
605 bool MessagePumpCFRunLoopBase::RunNestingDeferredWork() {
607 // This point can be reached with a NULL delegate_ if Run is not on the
608 // stack but foreign code is spinning the CFRunLoop. There's no sense in
609 // attempting to do any work or signalling the work sources because
610 // without a delegate, work is not possible.
614 // Immediately try work in priority order.
616 if (!RunIdleWork()) {
620 // Work was done. Arrange for the loop to try non-nestable idle work on
621 // a subsequent pass.
622 CFRunLoopSourceSignal(idle_work_source_);
628 // Called before the run loop goes to sleep or exits, or processes sources.
629 void MessagePumpCFRunLoopBase::MaybeScheduleNestingDeferredWork() {
630 // deepest_nesting_level_ is set as run loops are entered. If the deepest
631 // level encountered is deeper than the current level, a nested loop
632 // (relative to the current level) ran since the last time nesting-deferred
633 // work was scheduled. When that situation is encountered, schedule
634 // nesting-deferred work in case any work was deferred because nested work
636 if (deepest_nesting_level_ > nesting_level_) {
637 deepest_nesting_level_ = nesting_level_;
638 CFRunLoopSourceSignal(nesting_deferred_work_source_);
642 // Called from the run loop.
644 void MessagePumpCFRunLoopBase::StartOrEndWaitObserver(
645 CFRunLoopObserverRef observer,
646 CFRunLoopActivity activity,
648 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
650 if (activity == kCFRunLoopAfterWaiting) {
651 if (self->instrumentation_)
652 self->instrumentation_->WaitingFinished();
656 // Attempt to do some idle work before going to sleep.
659 // The run loop is about to go to sleep. If any of the work done since it
660 // started or woke up resulted in a nested run loop running,
661 // nesting-deferred work may have accumulated. Schedule it for processing
663 self->MaybeScheduleNestingDeferredWork();
665 if (self->instrumentation_)
666 self->instrumentation_->WaitingStarted();
669 // Called from the run loop.
671 void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer,
672 CFRunLoopActivity activity,
674 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
676 // The run loop has reached the top of the loop and is about to begin
677 // processing sources. If the last iteration of the loop at this nesting
678 // level did not sleep or exit, nesting-deferred work may have accumulated
679 // if a nested loop ran. Schedule nesting-deferred work for processing if
681 self->MaybeScheduleNestingDeferredWork();
684 // Called from the run loop.
686 void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer,
687 CFRunLoopActivity activity,
689 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
692 case kCFRunLoopEntry:
693 if (self->instrumentation_)
694 self->instrumentation_->LoopEntered();
696 ++self->nesting_level_;
697 if (self->nesting_level_ > self->deepest_nesting_level_) {
698 self->deepest_nesting_level_ = self->nesting_level_;
703 // Not all run loops go to sleep. If a run loop is stopped before it
704 // goes to sleep due to a CFRunLoopStop call, or if the timeout passed
705 // to CFRunLoopRunInMode expires, the run loop may proceed directly from
706 // handling sources to exiting without any sleep. This most commonly
707 // occurs when CFRunLoopRunInMode is passed a timeout of 0, causing it
708 // to make a single pass through the loop and exit without sleep. Some
709 // native loops use CFRunLoop in this way. Because StartOrEndWaitObserver
710 // will not be called in these case, MaybeScheduleNestingDeferredWork
711 // needs to be called here, as the run loop exits.
713 // MaybeScheduleNestingDeferredWork consults self->nesting_level_
714 // to determine whether to schedule nesting-deferred work. It expects
715 // the nesting level to be set to the depth of the loop that is going
716 // to sleep or exiting. It must be called before decrementing the
717 // value so that the value still corresponds to the level of the exiting
719 self->MaybeScheduleNestingDeferredWork();
720 --self->nesting_level_;
722 if (self->instrumentation_)
723 self->instrumentation_->LoopExited();
730 self->EnterExitRunLoop(activity);
733 // Called by MessagePumpCFRunLoopBase::EnterExitRunLoop. The default
734 // implementation is a no-op.
735 void MessagePumpCFRunLoopBase::EnterExitRunLoop(CFRunLoopActivity activity) {
738 // Base version returns a standard NSAutoreleasePool.
739 AutoreleasePoolType* MessagePumpCFRunLoopBase::CreateAutoreleasePool() {
740 return [[NSAutoreleasePool alloc] init];
743 MessagePumpCFRunLoop::MessagePumpCFRunLoop()
744 : quit_pending_(false) {
747 MessagePumpCFRunLoop::~MessagePumpCFRunLoop() {}
749 // Called by MessagePumpCFRunLoopBase::DoRun. If other CFRunLoopRun loops were
750 // running lower on the run loop thread's stack when this object was created,
751 // the same number of CFRunLoopRun loops must be running for the outermost call
752 // to Run. Run/DoRun are reentrant after that point.
753 void MessagePumpCFRunLoop::DoRun(Delegate* delegate) {
754 // This is completely identical to calling CFRunLoopRun(), except autorelease
755 // pool management is introduced.
758 MessagePumpScopedAutoreleasePool autorelease_pool(this);
759 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
762 } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished);
765 // Must be called on the run loop thread.
766 void MessagePumpCFRunLoop::Quit() {
767 // Stop the innermost run loop managed by this MessagePumpCFRunLoop object.
768 if (nesting_level() == run_nesting_level()) {
769 // This object is running the innermost loop, just stop it.
770 CFRunLoopStop(run_loop());
772 // There's another loop running inside the loop managed by this object.
773 // In other words, someone else called CFRunLoopRunInMode on the same
774 // thread, deeper on the stack than the deepest Run call. Don't preempt
775 // other run loops, just mark this object to quit the innermost Run as
776 // soon as the other inner loops not managed by Run are done.
777 quit_pending_ = true;
781 // Called by MessagePumpCFRunLoopBase::EnterExitObserver.
782 void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) {
783 if (activity == kCFRunLoopExit &&
784 nesting_level() == run_nesting_level() &&
786 // Quit was called while loops other than those managed by this object
787 // were running further inside a run loop managed by this object. Now
788 // that all unmanaged inner run loops are gone, stop the loop running
790 CFRunLoopStop(run_loop());
791 quit_pending_ = false;
795 MessagePumpNSRunLoop::MessagePumpNSRunLoop()
796 : keep_running_(true) {
797 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
798 source_context.perform = NoOp;
799 quit_source_ = CFRunLoopSourceCreate(NULL, // allocator
802 CFRunLoopAddSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
805 MessagePumpNSRunLoop::~MessagePumpNSRunLoop() {
806 CFRunLoopRemoveSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
807 CFRelease(quit_source_);
810 void MessagePumpNSRunLoop::DoRun(Delegate* delegate) {
811 while (keep_running_) {
812 // NSRunLoop manages autorelease pools itself.
813 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
814 beforeDate:[NSDate distantFuture]];
817 keep_running_ = true;
820 void MessagePumpNSRunLoop::Quit() {
821 keep_running_ = false;
822 CFRunLoopSourceSignal(quit_source_);
823 CFRunLoopWakeUp(run_loop());
827 MessagePumpUIApplication::MessagePumpUIApplication()
831 MessagePumpUIApplication::~MessagePumpUIApplication() {}
833 void MessagePumpUIApplication::DoRun(Delegate* delegate) {
837 void MessagePumpUIApplication::Quit() {
841 void MessagePumpUIApplication::Attach(Delegate* delegate) {
843 run_loop_ = new RunLoop();
844 CHECK(run_loop_->BeforeRun());
845 SetDelegate(delegate);
850 MessagePumpNSApplication::MessagePumpNSApplication()
851 : keep_running_(true),
852 running_own_loop_(false) {
853 EnableInstrumentation();
856 MessagePumpNSApplication::~MessagePumpNSApplication() {}
858 void MessagePumpNSApplication::DoRun(Delegate* delegate) {
859 if (instrumentation_)
860 instrumentation_->StartIfNeeded();
862 bool last_running_own_loop_ = running_own_loop_;
864 // NSApp must be initialized by calling:
865 // [{some class which implements CrAppProtocol} sharedApplication]
866 // Most likely candidates are CrApplication or BrowserCrApplication.
867 // These can be initialized from C++ code by calling
868 // RegisterCrApp() or RegisterBrowserCrApp().
871 if (![NSApp isRunning]) {
872 running_own_loop_ = false;
873 // NSApplication manages autorelease pools itself when run this way.
876 running_own_loop_ = true;
877 NSDate* distant_future = [NSDate distantFuture];
878 while (keep_running_) {
879 MessagePumpScopedAutoreleasePool autorelease_pool(this);
880 NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
881 untilDate:distant_future
882 inMode:NSDefaultRunLoopMode
885 [NSApp sendEvent:event];
888 keep_running_ = true;
891 running_own_loop_ = last_running_own_loop_;
894 void MessagePumpNSApplication::Quit() {
895 if (!running_own_loop_) {
896 [[NSApplication sharedApplication] stop:nil];
898 keep_running_ = false;
901 // Send a fake event to wake the loop up.
902 [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
914 MessagePumpCrApplication::MessagePumpCrApplication() {
917 MessagePumpCrApplication::~MessagePumpCrApplication() {
920 // Prevents an autorelease pool from being created if the app is in the midst of
921 // handling a UI event because various parts of AppKit depend on objects that
922 // are created while handling a UI event to be autoreleased in the event loop.
923 // An example of this is NSWindowController. When a window with a window
924 // controller is closed it goes through a stack like this:
925 // (Several stack frames elided for clarity)
927 // #0 [NSWindowController autorelease]
929 // #2 MessagePumpCFRunLoopBase::DoWork()
930 // #3 [NSRunLoop run]
931 // #4 [NSButton performClick:]
932 // #5 [NSWindow sendEvent:]
933 // #6 [NSApp sendEvent:]
936 // -performClick: spins a nested run loop. If the pool created in DoWork was a
937 // standard NSAutoreleasePool, it would release the objects that were
938 // autoreleased into it once DoWork released it. This would cause the window
939 // controller, which autoreleased itself in frame #0, to release itself, and
940 // possibly free itself. Unfortunately this window controller controls the
941 // window in frame #5. When the stack is unwound to frame #5, the window would
942 // no longer exists and crashes may occur. Apple gets around this by never
943 // releasing the pool it creates in frame #4, and letting frame #7 clean it up
944 // when it cleans up the pool that wraps frame #7. When an autorelease pool is
945 // released it releases all other pools that were created after it on the
946 // autorelease pool stack.
948 // CrApplication is responsible for setting handlingSendEvent to true just
949 // before it sends the event through the event handling mechanism, and
950 // returning it to its previous value once the event has been sent.
951 AutoreleasePoolType* MessagePumpCrApplication::CreateAutoreleasePool() {
952 if (MessagePumpMac::IsHandlingSendEvent())
954 return MessagePumpNSApplication::CreateAutoreleasePool();
958 bool MessagePumpMac::UsingCrApp() {
959 DCHECK([NSThread isMainThread]);
961 // If NSApp is still not initialized, then the subclass used cannot
965 // The pump was created using MessagePumpNSApplication.
966 if (g_not_using_cr_app)
969 return [NSApp conformsToProtocol:@protocol(CrAppProtocol)];
973 bool MessagePumpMac::IsHandlingSendEvent() {
974 DCHECK([NSApp conformsToProtocol:@protocol(CrAppProtocol)]);
975 NSObject<CrAppProtocol>* app = static_cast<NSObject<CrAppProtocol>*>(NSApp);
976 return [app isHandlingSendEvent];
978 #endif // !defined(OS_IOS)
981 MessagePump* MessagePumpMac::Create() {
982 if ([NSThread isMainThread]) {
984 return new MessagePumpUIApplication;
986 if ([NSApp conformsToProtocol:@protocol(CrAppProtocol)])
987 return new MessagePumpCrApplication;
989 // The main-thread MessagePump implementations REQUIRE an NSApp.
990 // Executables which have specific requirements for their
991 // NSApplication subclass should initialize appropriately before
992 // creating an event loop.
993 [NSApplication sharedApplication];
994 g_not_using_cr_app = true;
995 return new MessagePumpNSApplication;
999 return new MessagePumpNSRunLoop;