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)
30 void CFRunLoopAddSourceToAllModes(CFRunLoopRef rl, CFRunLoopSourceRef source) {
31 CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes);
32 CFRunLoopAddSource(rl, source, kMessageLoopExclusiveRunLoopMode);
35 void CFRunLoopRemoveSourceFromAllModes(CFRunLoopRef rl,
36 CFRunLoopSourceRef source) {
37 CFRunLoopRemoveSource(rl, source, kCFRunLoopCommonModes);
38 CFRunLoopRemoveSource(rl, source, kMessageLoopExclusiveRunLoopMode);
41 void CFRunLoopAddTimerToAllModes(CFRunLoopRef rl, CFRunLoopTimerRef timer) {
42 CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes);
43 CFRunLoopAddTimer(rl, timer, kMessageLoopExclusiveRunLoopMode);
46 void CFRunLoopRemoveTimerFromAllModes(CFRunLoopRef rl,
47 CFRunLoopTimerRef timer) {
48 CFRunLoopRemoveTimer(rl, timer, kCFRunLoopCommonModes);
49 CFRunLoopRemoveTimer(rl, timer, kMessageLoopExclusiveRunLoopMode);
52 void CFRunLoopAddObserverToAllModes(CFRunLoopRef rl,
53 CFRunLoopObserverRef observer) {
54 CFRunLoopAddObserver(rl, observer, kCFRunLoopCommonModes);
55 CFRunLoopAddObserver(rl, observer, kMessageLoopExclusiveRunLoopMode);
58 void CFRunLoopRemoveObserverFromAllModes(CFRunLoopRef rl,
59 CFRunLoopObserverRef observer) {
60 CFRunLoopRemoveObserver(rl, observer, kCFRunLoopCommonModes);
61 CFRunLoopRemoveObserver(rl, observer, kMessageLoopExclusiveRunLoopMode);
64 void NoOp(void* info) {
67 const CFTimeInterval kCFTimeIntervalMax =
68 std::numeric_limits<CFTimeInterval>::max();
71 // Set to true if MessagePumpMac::Create() is called before NSApp is
72 // initialized. Only accessed from the main thread.
73 bool g_not_using_cr_app = false;
76 // Call through to CFRunLoopTimerSetTolerance(), which is only available on
78 void SetTimerTolerance(CFRunLoopTimerRef timer, CFTimeInterval tolerance) {
79 typedef void (*CFRunLoopTimerSetTolerancePtr)(CFRunLoopTimerRef timer,
80 CFTimeInterval tolerance);
82 static CFRunLoopTimerSetTolerancePtr settimertolerance_function_ptr;
84 static dispatch_once_t get_timer_tolerance_function_ptr_once;
85 dispatch_once(&get_timer_tolerance_function_ptr_once, ^{
86 NSBundle* bundle =[NSBundle
87 bundleWithPath:@"/System/Library/Frameworks/CoreFoundation.framework"];
88 const char* path = [[bundle executablePath] fileSystemRepresentation];
90 void* library_handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL);
91 CHECK(library_handle) << dlerror();
92 settimertolerance_function_ptr =
93 reinterpret_cast<CFRunLoopTimerSetTolerancePtr>(
94 dlsym(library_handle, "CFRunLoopTimerSetTolerance"));
96 dlclose(library_handle);
99 if (settimertolerance_function_ptr)
100 settimertolerance_function_ptr(timer, tolerance);
106 const CFStringRef kMessageLoopExclusiveRunLoopMode =
107 CFSTR("kMessageLoopExclusiveRunLoopMode");
109 // A scoper for autorelease pools created from message pump run loops.
110 // Avoids dirtying up the ScopedNSAutoreleasePool interface for the rare
111 // case where an autorelease pool needs to be passed in.
112 class MessagePumpScopedAutoreleasePool {
114 explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) :
115 pool_(pump->CreateAutoreleasePool()) {
117 ~MessagePumpScopedAutoreleasePool() {
122 NSAutoreleasePool* pool_;
123 DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool);
126 // This class is used to instrument the MessagePump to gather various timing
127 // data about when the underlying run loop is entered, when it is waiting, and
128 // when it is servicing its delegate.
130 // The metrics are gathered as UMA-tracked histograms. To gather the data over
131 // time, sampling is used, such that a new histogram is created for each metric
132 // every |sampling_interval| for |sampling_duration|. After sampling is
133 // complete, this class deletes itself.
134 class MessagePumpInstrumentation {
136 // Creates an instrument for the MessagePump on the current thread. Every
137 // |sampling_interval|, a new histogram will be created to track the metrics
138 // over time. After |sampling_duration|, this will delete itself, causing the
139 // WeakPtr to go NULL.
140 static WeakPtr<MessagePumpInstrumentation> Create(
141 const TimeDelta& sampling_interval,
142 const TimeDelta& sampling_duration) {
143 MessagePumpInstrumentation* instrument =
144 new MessagePumpInstrumentation(sampling_interval, sampling_duration);
145 return instrument->weak_ptr_factory_.GetWeakPtr();
148 // Starts the timer that runs the sampling instrumentation. Can be called
149 // multiple times as a noop.
150 void StartIfNeeded() {
154 sampling_start_time_ = generation_start_time_ = TimeTicks::Now();
156 CFRunLoopTimerContext timer_context = { .info = this };
157 timer_.reset(CFRunLoopTimerCreate(
159 (Time::Now() + sampling_interval_).ToCFAbsoluteTime(),
160 sampling_interval_.InSecondsF(),
163 &MessagePumpInstrumentation::TimerFired,
165 CFRunLoopAddTimerToAllModes(CFRunLoopGetCurrent(), timer_);
168 // Used to track kCFRunLoopEntry.
170 loop_run_times_.push(TimeTicks::Now());
173 // Used to track kCFRunLoopExit.
175 TimeDelta duration = TimeTicks::Now() - loop_run_times_.top();
176 loop_run_times_.pop();
177 GetHistogram(LOOP_CYCLE)->AddTime(duration);
180 // Used to track kCFRunLoopBeforeWaiting.
181 void WaitingStarted() {
182 loop_wait_times_.push(TimeTicks::Now());
185 // Used to track kCFRunLoopAfterWaiting.
186 void WaitingFinished() {
187 TimeDelta duration = TimeTicks::Now() - loop_wait_times_.top();
188 loop_wait_times_.pop();
189 GetHistogram(LOOP_WAIT)->AddTime(duration);
192 // Used to track when the MessagePump will invoke its |delegate|.
193 void WorkSourceEntered(MessagePump::Delegate* delegate) {
194 work_source_times_.push(TimeTicks::Now());
197 TimeDelta queuing_delay;
198 delegate->GetQueueingInformation(&queue_size, &queuing_delay);
199 GetHistogram(QUEUE_SIZE)->Add(queue_size);
200 GetHistogram(QUEUE_DELAY)->AddTime(queuing_delay);
204 // Used to track the completion of servicing the MessagePump::Delegate.
205 void WorkSourceExited() {
206 TimeDelta duration = TimeTicks::Now() - work_source_times_.top();
207 work_source_times_.pop();
208 GetHistogram(WORK_SOURCE)->AddTime(duration);
212 enum HistogramEvent {
213 // Time-based histograms:
214 LOOP_CYCLE, // LoopEntered/LoopExited
215 LOOP_WAIT, // WaitingStarted/WaitingEnded
216 WORK_SOURCE, // WorkSourceExited
217 QUEUE_DELAY, // WorkSourceEntered
219 // Value-based histograms:
220 // NOTE: Do not add value-based histograms before this event, only after.
221 QUEUE_SIZE, // WorkSourceEntered
226 MessagePumpInstrumentation(const TimeDelta& sampling_interval,
227 const TimeDelta& sampling_duration)
228 : weak_ptr_factory_(this),
229 sampling_interval_(sampling_interval),
230 sampling_duration_(sampling_duration),
231 sample_generation_(0) {
232 // Create all the histogram objects that will be used for sampling.
233 const char kHistogramName[] = "MessagePumpMac.%s.SampleMs.%" PRId64;
234 for (TimeDelta i; i < sampling_duration_; i += sampling_interval_) {
235 int64 sample = i.InMilliseconds();
237 // Generate the time-based histograms.
238 for (int j = LOOP_CYCLE; j < QUEUE_SIZE; ++j) {
239 std::string name = StringPrintf(kHistogramName,
240 NameForEnum(static_cast<HistogramEvent>(j)), sample);
241 histograms_[j].push_back(
242 Histogram::FactoryTimeGet(name, TimeDelta::FromMilliseconds(1),
243 sampling_interval_, 50,
244 HistogramBase::kUmaTargetedHistogramFlag));
247 // Generate the value-based histograms.
248 for (int j = QUEUE_SIZE; j < HISTOGRAM_EVENT_MAX; ++j) {
249 std::string name = StringPrintf(kHistogramName,
250 NameForEnum(static_cast<HistogramEvent>(j)), sample);
251 histograms_[j].push_back(
252 Histogram::FactoryGet(name, 1, 10000, 50,
253 HistogramBase::kUmaTargetedHistogramFlag));
258 ~MessagePumpInstrumentation() {
260 CFRunLoopTimerInvalidate(timer_);
263 const char* NameForEnum(HistogramEvent event) {
265 case LOOP_CYCLE: return "LoopCycle";
266 case LOOP_WAIT: return "Waiting";
267 case WORK_SOURCE: return "WorkSource";
268 case QUEUE_DELAY: return "QueueingDelay";
269 case QUEUE_SIZE: return "QueueSize";
276 static void TimerFired(CFRunLoopTimerRef timer, void* context) {
277 static_cast<MessagePumpInstrumentation*>(context)->TimerFired();
280 // Called by the run loop when the sampling_interval_ has elapsed. Advances
281 // the sample_generation_, which controls into which histogram data is
282 // recorded, while recording and accounting for timer skew. Will delete this
283 // object after |sampling_duration_| has elapsed.
285 TimeTicks now = TimeTicks::Now();
286 TimeDelta delta = now - generation_start_time_;
288 // The timer fired, so advance the generation by at least one.
289 ++sample_generation_;
291 // To account for large timer skew/drift, advance the generation by any
292 // more completed intervals.
293 for (TimeDelta skew_advance = delta - sampling_interval_;
294 skew_advance >= sampling_interval_;
295 skew_advance -= sampling_interval_) {
296 ++sample_generation_;
299 generation_start_time_ = now;
300 if (now >= sampling_start_time_ + sampling_duration_)
304 HistogramBase* GetHistogram(HistogramEvent event) {
305 DCHECK_LT(sample_generation_, histograms_[event].size());
306 return histograms_[event][sample_generation_];
309 // Vends the pointer to the Create()or.
310 WeakPtrFactory<MessagePumpInstrumentation> weak_ptr_factory_;
312 // The interval and duration of the sampling.
313 TimeDelta sampling_interval_;
314 TimeDelta sampling_duration_;
316 // The time at which sampling started.
317 TimeTicks sampling_start_time_;
319 // The timer that advances the sample_generation_ and sets the
320 // generation_start_time_ for the current sample interval.
321 base::ScopedCFTypeRef<CFRunLoopTimerRef> timer_;
323 // The two-dimensional array of histograms. The first dimension is the
324 // HistogramEvent type. The second is for the sampling intervals.
325 std::vector<HistogramBase*> histograms_[HISTOGRAM_EVENT_MAX];
327 // The index in the second dimension of histograms_, which controls in which
328 // sampled histogram events are recorded.
329 size_t sample_generation_;
331 // The last time at which the timer fired. This is used to track timer skew
332 // (i.e. it did not fire on time) and properly account for it when advancing
333 // samle_generation_.
334 TimeTicks generation_start_time_;
336 // MessagePump activations can be nested. Use a stack for each of the
337 // possibly reentrant HistogramEvent types to properly balance and calculate
338 // the timing information.
339 std::stack<TimeTicks> loop_run_times_;
340 std::stack<TimeTicks> loop_wait_times_;
341 std::stack<TimeTicks> work_source_times_;
343 DISALLOW_COPY_AND_ASSIGN(MessagePumpInstrumentation);
346 // Must be called on the run loop thread.
347 MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase()
349 delayed_work_fire_time_(kCFTimeIntervalMax),
350 timer_slack_(base::TIMER_SLACK_NONE),
352 run_nesting_level_(0),
353 deepest_nesting_level_(0),
354 delegateless_work_(false),
355 delegateless_idle_work_(false) {
356 run_loop_ = CFRunLoopGetCurrent();
359 // Set a repeating timer with a preposterous firing time and interval. The
360 // timer will effectively never fire as-is. The firing time will be adjusted
361 // as needed when ScheduleDelayedWork is called.
362 CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
363 timer_context.info = this;
364 delayed_work_timer_ = CFRunLoopTimerCreate(NULL, // allocator
365 kCFTimeIntervalMax, // fire time
366 kCFTimeIntervalMax, // interval
371 CFRunLoopAddTimerToAllModes(run_loop_, delayed_work_timer_);
373 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
374 source_context.info = this;
375 source_context.perform = RunWorkSource;
376 work_source_ = CFRunLoopSourceCreate(NULL, // allocator
379 CFRunLoopAddSourceToAllModes(run_loop_, work_source_);
381 source_context.perform = RunIdleWorkSource;
382 idle_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
385 CFRunLoopAddSourceToAllModes(run_loop_, idle_work_source_);
387 source_context.perform = RunNestingDeferredWorkSource;
388 nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
391 CFRunLoopAddSourceToAllModes(run_loop_, nesting_deferred_work_source_);
393 CFRunLoopObserverContext observer_context = CFRunLoopObserverContext();
394 observer_context.info = this;
395 pre_wait_observer_ = CFRunLoopObserverCreate(NULL, // allocator
396 kCFRunLoopBeforeWaiting |
397 kCFRunLoopAfterWaiting,
400 StartOrEndWaitObserver,
402 CFRunLoopAddObserverToAllModes(run_loop_, pre_wait_observer_);
404 pre_source_observer_ = CFRunLoopObserverCreate(NULL, // allocator
405 kCFRunLoopBeforeSources,
410 CFRunLoopAddObserverToAllModes(run_loop_, pre_source_observer_);
412 enter_exit_observer_ = CFRunLoopObserverCreate(NULL, // allocator
419 CFRunLoopAddObserverToAllModes(run_loop_, enter_exit_observer_);
422 // Ideally called on the run loop thread. If other run loops were running
423 // lower on the run loop thread's stack when this object was created, the
424 // same number of run loops must be running when this object is destroyed.
425 MessagePumpCFRunLoopBase::~MessagePumpCFRunLoopBase() {
426 CFRunLoopRemoveObserverFromAllModes(run_loop_, enter_exit_observer_);
427 CFRelease(enter_exit_observer_);
429 CFRunLoopRemoveObserverFromAllModes(run_loop_, pre_source_observer_);
430 CFRelease(pre_source_observer_);
432 CFRunLoopRemoveObserverFromAllModes(run_loop_, pre_wait_observer_);
433 CFRelease(pre_wait_observer_);
435 CFRunLoopRemoveSourceFromAllModes(run_loop_, nesting_deferred_work_source_);
436 CFRelease(nesting_deferred_work_source_);
438 CFRunLoopRemoveSourceFromAllModes(run_loop_, idle_work_source_);
439 CFRelease(idle_work_source_);
441 CFRunLoopRemoveSourceFromAllModes(run_loop_, work_source_);
442 CFRelease(work_source_);
444 CFRunLoopRemoveTimerFromAllModes(run_loop_, delayed_work_timer_);
445 CFRelease(delayed_work_timer_);
447 CFRelease(run_loop_);
450 // Must be called on the run loop thread.
451 void MessagePumpCFRunLoopBase::Run(Delegate* delegate) {
452 // nesting_level_ will be incremented in EnterExitRunLoop, so set
453 // run_nesting_level_ accordingly.
454 int last_run_nesting_level = run_nesting_level_;
455 run_nesting_level_ = nesting_level_ + 1;
457 Delegate* last_delegate = delegate_;
458 SetDelegate(delegate);
462 // Restore the previous state of the object.
463 SetDelegate(last_delegate);
464 run_nesting_level_ = last_run_nesting_level;
467 void MessagePumpCFRunLoopBase::SetDelegate(Delegate* delegate) {
468 delegate_ = delegate;
471 // If any work showed up but could not be dispatched for want of a
472 // delegate, set it up for dispatch again now that a delegate is
474 if (delegateless_work_) {
475 CFRunLoopSourceSignal(work_source_);
476 delegateless_work_ = false;
478 if (delegateless_idle_work_) {
479 CFRunLoopSourceSignal(idle_work_source_);
480 delegateless_idle_work_ = false;
485 void MessagePumpCFRunLoopBase::EnableInstrumentation() {
486 instrumentation_ = MessagePumpInstrumentation::Create(
487 TimeDelta::FromSeconds(1), TimeDelta::FromSeconds(15));
490 // May be called on any thread.
491 void MessagePumpCFRunLoopBase::ScheduleWork() {
492 CFRunLoopSourceSignal(work_source_);
493 CFRunLoopWakeUp(run_loop_);
496 // Must be called on the run loop thread.
497 void MessagePumpCFRunLoopBase::ScheduleDelayedWork(
498 const TimeTicks& delayed_work_time) {
499 TimeDelta delta = delayed_work_time - TimeTicks::Now();
500 delayed_work_fire_time_ = CFAbsoluteTimeGetCurrent() + delta.InSecondsF();
501 CFRunLoopTimerSetNextFireDate(delayed_work_timer_, delayed_work_fire_time_);
502 if (timer_slack_ == TIMER_SLACK_MAXIMUM) {
503 SetTimerTolerance(delayed_work_timer_, delta.InSecondsF() * 0.5);
505 SetTimerTolerance(delayed_work_timer_, 0);
509 void MessagePumpCFRunLoopBase::SetTimerSlack(TimerSlack timer_slack) {
510 timer_slack_ = timer_slack;
513 // Called from the run loop.
515 void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer,
517 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
519 // The timer won't fire again until it's reset.
520 self->delayed_work_fire_time_ = kCFTimeIntervalMax;
522 // CFRunLoopTimers fire outside of the priority scheme for CFRunLoopSources.
523 // In order to establish the proper priority in which work and delayed work
524 // are processed one for one, the timer used to schedule delayed work must
525 // signal a CFRunLoopSource used to dispatch both work and delayed work.
526 CFRunLoopSourceSignal(self->work_source_);
529 // Called from the run loop.
531 void MessagePumpCFRunLoopBase::RunWorkSource(void* info) {
532 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
536 // Called by MessagePumpCFRunLoopBase::RunWorkSource.
537 bool MessagePumpCFRunLoopBase::RunWork() {
539 // This point can be reached with a NULL delegate_ if Run is not on the
540 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
541 // here when a delegate is available.
542 delegateless_work_ = true;
546 if (instrumentation_)
547 instrumentation_->WorkSourceEntered(delegate_);
549 // The NSApplication-based run loop only drains the autorelease pool at each
550 // UI event (NSEvent). The autorelease pool is not drained for each
551 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
552 // objects if the app is not currently handling a UI event to ensure they're
553 // released promptly even in the absence of UI events.
554 MessagePumpScopedAutoreleasePool autorelease_pool(this);
556 // Call DoWork and DoDelayedWork once, and if something was done, arrange to
557 // come back here again as long as the loop is still running.
558 bool did_work = delegate_->DoWork();
559 bool resignal_work_source = did_work;
562 delegate_->DoDelayedWork(&next_time);
564 // Determine whether there's more delayed work, and if so, if it needs to
565 // be done at some point in the future or if it's already time to do it.
566 // Only do these checks if did_work is false. If did_work is true, this
567 // function, and therefore any additional delayed work, will get another
568 // chance to run before the loop goes to sleep.
569 bool more_delayed_work = !next_time.is_null();
570 if (more_delayed_work) {
571 TimeDelta delay = next_time - TimeTicks::Now();
572 if (delay > TimeDelta()) {
573 // There's more delayed work to be done in the future.
574 ScheduleDelayedWork(next_time);
576 // There's more delayed work to be done, and its time is in the past.
577 // Arrange to come back here directly as long as the loop is still
579 resignal_work_source = true;
584 if (resignal_work_source) {
585 CFRunLoopSourceSignal(work_source_);
588 if (instrumentation_)
589 instrumentation_->WorkSourceExited();
591 return resignal_work_source;
594 // Called from the run loop.
596 void MessagePumpCFRunLoopBase::RunIdleWorkSource(void* info) {
597 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
601 // Called by MessagePumpCFRunLoopBase::RunIdleWorkSource.
602 bool MessagePumpCFRunLoopBase::RunIdleWork() {
604 // This point can be reached with a NULL delegate_ if Run is not on the
605 // stack but foreign code is spinning the CFRunLoop. Arrange to come back
606 // here when a delegate is available.
607 delegateless_idle_work_ = true;
611 // The NSApplication-based run loop only drains the autorelease pool at each
612 // UI event (NSEvent). The autorelease pool is not drained for each
613 // CFRunLoopSource target that's run. Use a local pool for any autoreleased
614 // objects if the app is not currently handling a UI event to ensure they're
615 // released promptly even in the absence of UI events.
616 MessagePumpScopedAutoreleasePool autorelease_pool(this);
618 // Call DoIdleWork once, and if something was done, arrange to come back here
619 // again as long as the loop is still running.
620 bool did_work = delegate_->DoIdleWork();
622 CFRunLoopSourceSignal(idle_work_source_);
628 // Called from the run loop.
630 void MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource(void* info) {
631 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
632 self->RunNestingDeferredWork();
635 // Called by MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource.
636 bool MessagePumpCFRunLoopBase::RunNestingDeferredWork() {
638 // This point can be reached with a NULL delegate_ if Run is not on the
639 // stack but foreign code is spinning the CFRunLoop. There's no sense in
640 // attempting to do any work or signalling the work sources because
641 // without a delegate, work is not possible.
645 // Immediately try work in priority order.
647 if (!RunIdleWork()) {
651 // Work was done. Arrange for the loop to try non-nestable idle work on
652 // a subsequent pass.
653 CFRunLoopSourceSignal(idle_work_source_);
659 // Called before the run loop goes to sleep or exits, or processes sources.
660 void MessagePumpCFRunLoopBase::MaybeScheduleNestingDeferredWork() {
661 // deepest_nesting_level_ is set as run loops are entered. If the deepest
662 // level encountered is deeper than the current level, a nested loop
663 // (relative to the current level) ran since the last time nesting-deferred
664 // work was scheduled. When that situation is encountered, schedule
665 // nesting-deferred work in case any work was deferred because nested work
667 if (deepest_nesting_level_ > nesting_level_) {
668 deepest_nesting_level_ = nesting_level_;
669 CFRunLoopSourceSignal(nesting_deferred_work_source_);
673 // Called from the run loop.
675 void MessagePumpCFRunLoopBase::StartOrEndWaitObserver(
676 CFRunLoopObserverRef observer,
677 CFRunLoopActivity activity,
679 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
681 if (activity == kCFRunLoopAfterWaiting) {
682 if (self->instrumentation_)
683 self->instrumentation_->WaitingFinished();
687 // Attempt to do some idle work before going to sleep.
690 // The run loop is about to go to sleep. If any of the work done since it
691 // started or woke up resulted in a nested run loop running,
692 // nesting-deferred work may have accumulated. Schedule it for processing
694 self->MaybeScheduleNestingDeferredWork();
696 if (self->instrumentation_)
697 self->instrumentation_->WaitingStarted();
700 // Called from the run loop.
702 void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer,
703 CFRunLoopActivity activity,
705 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
707 // The run loop has reached the top of the loop and is about to begin
708 // processing sources. If the last iteration of the loop at this nesting
709 // level did not sleep or exit, nesting-deferred work may have accumulated
710 // if a nested loop ran. Schedule nesting-deferred work for processing if
712 self->MaybeScheduleNestingDeferredWork();
715 // Called from the run loop.
717 void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer,
718 CFRunLoopActivity activity,
720 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
723 case kCFRunLoopEntry:
724 if (self->instrumentation_)
725 self->instrumentation_->LoopEntered();
727 ++self->nesting_level_;
728 if (self->nesting_level_ > self->deepest_nesting_level_) {
729 self->deepest_nesting_level_ = self->nesting_level_;
734 // Not all run loops go to sleep. If a run loop is stopped before it
735 // goes to sleep due to a CFRunLoopStop call, or if the timeout passed
736 // to CFRunLoopRunInMode expires, the run loop may proceed directly from
737 // handling sources to exiting without any sleep. This most commonly
738 // occurs when CFRunLoopRunInMode is passed a timeout of 0, causing it
739 // to make a single pass through the loop and exit without sleep. Some
740 // native loops use CFRunLoop in this way. Because StartOrEndWaitObserver
741 // will not be called in these case, MaybeScheduleNestingDeferredWork
742 // needs to be called here, as the run loop exits.
744 // MaybeScheduleNestingDeferredWork consults self->nesting_level_
745 // to determine whether to schedule nesting-deferred work. It expects
746 // the nesting level to be set to the depth of the loop that is going
747 // to sleep or exiting. It must be called before decrementing the
748 // value so that the value still corresponds to the level of the exiting
750 self->MaybeScheduleNestingDeferredWork();
751 --self->nesting_level_;
753 if (self->instrumentation_)
754 self->instrumentation_->LoopExited();
761 self->EnterExitRunLoop(activity);
764 // Called by MessagePumpCFRunLoopBase::EnterExitRunLoop. The default
765 // implementation is a no-op.
766 void MessagePumpCFRunLoopBase::EnterExitRunLoop(CFRunLoopActivity activity) {
769 // Base version returns a standard NSAutoreleasePool.
770 AutoreleasePoolType* MessagePumpCFRunLoopBase::CreateAutoreleasePool() {
771 return [[NSAutoreleasePool alloc] init];
774 MessagePumpCFRunLoop::MessagePumpCFRunLoop()
775 : quit_pending_(false) {
778 MessagePumpCFRunLoop::~MessagePumpCFRunLoop() {}
780 // Called by MessagePumpCFRunLoopBase::DoRun. If other CFRunLoopRun loops were
781 // running lower on the run loop thread's stack when this object was created,
782 // the same number of CFRunLoopRun loops must be running for the outermost call
783 // to Run. Run/DoRun are reentrant after that point.
784 void MessagePumpCFRunLoop::DoRun(Delegate* delegate) {
785 // This is completely identical to calling CFRunLoopRun(), except autorelease
786 // pool management is introduced.
789 MessagePumpScopedAutoreleasePool autorelease_pool(this);
790 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode,
793 } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished);
796 // Must be called on the run loop thread.
797 void MessagePumpCFRunLoop::Quit() {
798 // Stop the innermost run loop managed by this MessagePumpCFRunLoop object.
799 if (nesting_level() == run_nesting_level()) {
800 // This object is running the innermost loop, just stop it.
801 CFRunLoopStop(run_loop());
803 // There's another loop running inside the loop managed by this object.
804 // In other words, someone else called CFRunLoopRunInMode on the same
805 // thread, deeper on the stack than the deepest Run call. Don't preempt
806 // other run loops, just mark this object to quit the innermost Run as
807 // soon as the other inner loops not managed by Run are done.
808 quit_pending_ = true;
812 // Called by MessagePumpCFRunLoopBase::EnterExitObserver.
813 void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) {
814 if (activity == kCFRunLoopExit &&
815 nesting_level() == run_nesting_level() &&
817 // Quit was called while loops other than those managed by this object
818 // were running further inside a run loop managed by this object. Now
819 // that all unmanaged inner run loops are gone, stop the loop running
821 CFRunLoopStop(run_loop());
822 quit_pending_ = false;
826 MessagePumpNSRunLoop::MessagePumpNSRunLoop()
827 : keep_running_(true) {
828 CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
829 source_context.perform = NoOp;
830 quit_source_ = CFRunLoopSourceCreate(NULL, // allocator
833 CFRunLoopAddSourceToAllModes(run_loop(), quit_source_);
836 MessagePumpNSRunLoop::~MessagePumpNSRunLoop() {
837 CFRunLoopRemoveSourceFromAllModes(run_loop(), quit_source_);
838 CFRelease(quit_source_);
841 void MessagePumpNSRunLoop::DoRun(Delegate* delegate) {
842 while (keep_running_) {
843 // NSRunLoop manages autorelease pools itself.
844 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
845 beforeDate:[NSDate distantFuture]];
848 keep_running_ = true;
851 void MessagePumpNSRunLoop::Quit() {
852 keep_running_ = false;
853 CFRunLoopSourceSignal(quit_source_);
854 CFRunLoopWakeUp(run_loop());
858 MessagePumpUIApplication::MessagePumpUIApplication()
862 MessagePumpUIApplication::~MessagePumpUIApplication() {}
864 void MessagePumpUIApplication::DoRun(Delegate* delegate) {
868 void MessagePumpUIApplication::Quit() {
872 void MessagePumpUIApplication::Attach(Delegate* delegate) {
874 run_loop_ = new RunLoop();
875 CHECK(run_loop_->BeforeRun());
876 SetDelegate(delegate);
881 MessagePumpNSApplication::MessagePumpNSApplication()
882 : keep_running_(true),
883 running_own_loop_(false) {
884 EnableInstrumentation();
887 MessagePumpNSApplication::~MessagePumpNSApplication() {}
889 void MessagePumpNSApplication::DoRun(Delegate* delegate) {
890 if (instrumentation_)
891 instrumentation_->StartIfNeeded();
893 bool last_running_own_loop_ = running_own_loop_;
895 // NSApp must be initialized by calling:
896 // [{some class which implements CrAppProtocol} sharedApplication]
897 // Most likely candidates are CrApplication or BrowserCrApplication.
898 // These can be initialized from C++ code by calling
899 // RegisterCrApp() or RegisterBrowserCrApp().
902 if (![NSApp isRunning]) {
903 running_own_loop_ = false;
904 // NSApplication manages autorelease pools itself when run this way.
907 running_own_loop_ = true;
908 NSDate* distant_future = [NSDate distantFuture];
909 while (keep_running_) {
910 MessagePumpScopedAutoreleasePool autorelease_pool(this);
911 NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
912 untilDate:distant_future
913 inMode:NSDefaultRunLoopMode
916 [NSApp sendEvent:event];
919 keep_running_ = true;
922 running_own_loop_ = last_running_own_loop_;
925 void MessagePumpNSApplication::Quit() {
926 if (!running_own_loop_) {
927 [[NSApplication sharedApplication] stop:nil];
929 keep_running_ = false;
932 // Send a fake event to wake the loop up.
933 [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
945 MessagePumpCrApplication::MessagePumpCrApplication() {
948 MessagePumpCrApplication::~MessagePumpCrApplication() {
951 // Prevents an autorelease pool from being created if the app is in the midst of
952 // handling a UI event because various parts of AppKit depend on objects that
953 // are created while handling a UI event to be autoreleased in the event loop.
954 // An example of this is NSWindowController. When a window with a window
955 // controller is closed it goes through a stack like this:
956 // (Several stack frames elided for clarity)
958 // #0 [NSWindowController autorelease]
960 // #2 MessagePumpCFRunLoopBase::DoWork()
961 // #3 [NSRunLoop run]
962 // #4 [NSButton performClick:]
963 // #5 [NSWindow sendEvent:]
964 // #6 [NSApp sendEvent:]
967 // -performClick: spins a nested run loop. If the pool created in DoWork was a
968 // standard NSAutoreleasePool, it would release the objects that were
969 // autoreleased into it once DoWork released it. This would cause the window
970 // controller, which autoreleased itself in frame #0, to release itself, and
971 // possibly free itself. Unfortunately this window controller controls the
972 // window in frame #5. When the stack is unwound to frame #5, the window would
973 // no longer exists and crashes may occur. Apple gets around this by never
974 // releasing the pool it creates in frame #4, and letting frame #7 clean it up
975 // when it cleans up the pool that wraps frame #7. When an autorelease pool is
976 // released it releases all other pools that were created after it on the
977 // autorelease pool stack.
979 // CrApplication is responsible for setting handlingSendEvent to true just
980 // before it sends the event through the event handling mechanism, and
981 // returning it to its previous value once the event has been sent.
982 AutoreleasePoolType* MessagePumpCrApplication::CreateAutoreleasePool() {
983 if (MessagePumpMac::IsHandlingSendEvent())
985 return MessagePumpNSApplication::CreateAutoreleasePool();
989 bool MessagePumpMac::UsingCrApp() {
990 DCHECK([NSThread isMainThread]);
992 // If NSApp is still not initialized, then the subclass used cannot
996 // The pump was created using MessagePumpNSApplication.
997 if (g_not_using_cr_app)
1000 return [NSApp conformsToProtocol:@protocol(CrAppProtocol)];
1004 bool MessagePumpMac::IsHandlingSendEvent() {
1005 DCHECK([NSApp conformsToProtocol:@protocol(CrAppProtocol)]);
1006 NSObject<CrAppProtocol>* app = static_cast<NSObject<CrAppProtocol>*>(NSApp);
1007 return [app isHandlingSendEvent];
1009 #endif // !defined(OS_IOS)
1012 MessagePump* MessagePumpMac::Create() {
1013 if ([NSThread isMainThread]) {
1015 return new MessagePumpUIApplication;
1017 if ([NSApp conformsToProtocol:@protocol(CrAppProtocol)])
1018 return new MessagePumpCrApplication;
1020 // The main-thread MessagePump implementations REQUIRE an NSApp.
1021 // Executables which have specific requirements for their
1022 // NSApplication subclass should initialize appropriately before
1023 // creating an event loop.
1024 [NSApplication sharedApplication];
1025 g_not_using_cr_app = true;
1026 return new MessagePumpNSApplication;
1030 return new MessagePumpNSRunLoop;