| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #import "base/message_loop/message_pump_mac.h" | |
| 6 | |
| 7 #include <dlfcn.h> | |
| 8 #import <Foundation/Foundation.h> | |
| 9 | |
| 10 #include <limits> | |
| 11 | |
| 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" | |
| 18 | |
| 19 #if !defined(OS_IOS) | |
| 20 #import <AppKit/AppKit.h> | |
| 21 #endif // !defined(OS_IOS) | |
| 22 | |
| 23 namespace base { | |
| 24 | |
| 25 namespace { | |
| 26 | |
| 27 void CFRunLoopAddSourceToAllModes(CFRunLoopRef rl, CFRunLoopSourceRef source) { | |
| 28 CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); | |
| 29 CFRunLoopAddSource(rl, source, kMessageLoopExclusiveRunLoopMode); | |
| 30 } | |
| 31 | |
| 32 void CFRunLoopRemoveSourceFromAllModes(CFRunLoopRef rl, | |
| 33 CFRunLoopSourceRef source) { | |
| 34 CFRunLoopRemoveSource(rl, source, kCFRunLoopCommonModes); | |
| 35 CFRunLoopRemoveSource(rl, source, kMessageLoopExclusiveRunLoopMode); | |
| 36 } | |
| 37 | |
| 38 void CFRunLoopAddTimerToAllModes(CFRunLoopRef rl, CFRunLoopTimerRef timer) { | |
| 39 CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes); | |
| 40 CFRunLoopAddTimer(rl, timer, kMessageLoopExclusiveRunLoopMode); | |
| 41 } | |
| 42 | |
| 43 void CFRunLoopRemoveTimerFromAllModes(CFRunLoopRef rl, | |
| 44 CFRunLoopTimerRef timer) { | |
| 45 CFRunLoopRemoveTimer(rl, timer, kCFRunLoopCommonModes); | |
| 46 CFRunLoopRemoveTimer(rl, timer, kMessageLoopExclusiveRunLoopMode); | |
| 47 } | |
| 48 | |
| 49 void CFRunLoopAddObserverToAllModes(CFRunLoopRef rl, | |
| 50 CFRunLoopObserverRef observer) { | |
| 51 CFRunLoopAddObserver(rl, observer, kCFRunLoopCommonModes); | |
| 52 CFRunLoopAddObserver(rl, observer, kMessageLoopExclusiveRunLoopMode); | |
| 53 } | |
| 54 | |
| 55 void CFRunLoopRemoveObserverFromAllModes(CFRunLoopRef rl, | |
| 56 CFRunLoopObserverRef observer) { | |
| 57 CFRunLoopRemoveObserver(rl, observer, kCFRunLoopCommonModes); | |
| 58 CFRunLoopRemoveObserver(rl, observer, kMessageLoopExclusiveRunLoopMode); | |
| 59 } | |
| 60 | |
| 61 void NoOp(void* info) { | |
| 62 } | |
| 63 | |
| 64 const CFTimeInterval kCFTimeIntervalMax = | |
| 65 std::numeric_limits<CFTimeInterval>::max(); | |
| 66 | |
| 67 #if !defined(OS_IOS) | |
| 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; | |
| 71 #endif | |
| 72 | |
| 73 // Call through to CFRunLoopTimerSetTolerance(), which is only available on | |
| 74 // OS X 10.9. | |
| 75 void SetTimerTolerance(CFRunLoopTimerRef timer, CFTimeInterval tolerance) { | |
| 76 typedef void (*CFRunLoopTimerSetTolerancePtr)(CFRunLoopTimerRef timer, | |
| 77 CFTimeInterval tolerance); | |
| 78 | |
| 79 static CFRunLoopTimerSetTolerancePtr settimertolerance_function_ptr; | |
| 80 | |
| 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]; | |
| 86 CHECK(path); | |
| 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")); | |
| 92 | |
| 93 dlclose(library_handle); | |
| 94 }); | |
| 95 | |
| 96 if (settimertolerance_function_ptr) | |
| 97 settimertolerance_function_ptr(timer, tolerance); | |
| 98 } | |
| 99 | |
| 100 } // namespace | |
| 101 | |
| 102 // static | |
| 103 const CFStringRef kMessageLoopExclusiveRunLoopMode = | |
| 104 CFSTR("kMessageLoopExclusiveRunLoopMode"); | |
| 105 | |
| 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 { | |
| 110 public: | |
| 111 explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump) : | |
| 112 pool_(pump->CreateAutoreleasePool()) { | |
| 113 } | |
| 114 ~MessagePumpScopedAutoreleasePool() { | |
| 115 [pool_ drain]; | |
| 116 } | |
| 117 | |
| 118 private: | |
| 119 NSAutoreleasePool* pool_; | |
| 120 DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool); | |
| 121 }; | |
| 122 | |
| 123 // Must be called on the run loop thread. | |
| 124 MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase() | |
| 125 : delegate_(NULL), | |
| 126 delayed_work_fire_time_(kCFTimeIntervalMax), | |
| 127 timer_slack_(base::TIMER_SLACK_NONE), | |
| 128 nesting_level_(0), | |
| 129 run_nesting_level_(0), | |
| 130 deepest_nesting_level_(0), | |
| 131 delegateless_work_(false), | |
| 132 delegateless_idle_work_(false) { | |
| 133 run_loop_ = CFRunLoopGetCurrent(); | |
| 134 CFRetain(run_loop_); | |
| 135 | |
| 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 | |
| 144 0, // flags | |
| 145 0, // priority | |
| 146 RunDelayedWorkTimer, | |
| 147 &timer_context); | |
| 148 CFRunLoopAddTimerToAllModes(run_loop_, delayed_work_timer_); | |
| 149 | |
| 150 CFRunLoopSourceContext source_context = CFRunLoopSourceContext(); | |
| 151 source_context.info = this; | |
| 152 source_context.perform = RunWorkSource; | |
| 153 work_source_ = CFRunLoopSourceCreate(NULL, // allocator | |
| 154 1, // priority | |
| 155 &source_context); | |
| 156 CFRunLoopAddSourceToAllModes(run_loop_, work_source_); | |
| 157 | |
| 158 source_context.perform = RunIdleWorkSource; | |
| 159 idle_work_source_ = CFRunLoopSourceCreate(NULL, // allocator | |
| 160 2, // priority | |
| 161 &source_context); | |
| 162 CFRunLoopAddSourceToAllModes(run_loop_, idle_work_source_); | |
| 163 | |
| 164 source_context.perform = RunNestingDeferredWorkSource; | |
| 165 nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL, // allocator | |
| 166 0, // priority | |
| 167 &source_context); | |
| 168 CFRunLoopAddSourceToAllModes(run_loop_, nesting_deferred_work_source_); | |
| 169 | |
| 170 CFRunLoopObserverContext observer_context = CFRunLoopObserverContext(); | |
| 171 observer_context.info = this; | |
| 172 pre_wait_observer_ = CFRunLoopObserverCreate(NULL, // allocator | |
| 173 kCFRunLoopBeforeWaiting, | |
| 174 true, // repeat | |
| 175 0, // priority | |
| 176 PreWaitObserver, | |
| 177 &observer_context); | |
| 178 CFRunLoopAddObserverToAllModes(run_loop_, pre_wait_observer_); | |
| 179 | |
| 180 pre_source_observer_ = CFRunLoopObserverCreate(NULL, // allocator | |
| 181 kCFRunLoopBeforeSources, | |
| 182 true, // repeat | |
| 183 0, // priority | |
| 184 PreSourceObserver, | |
| 185 &observer_context); | |
| 186 CFRunLoopAddObserverToAllModes(run_loop_, pre_source_observer_); | |
| 187 | |
| 188 enter_exit_observer_ = CFRunLoopObserverCreate(NULL, // allocator | |
| 189 kCFRunLoopEntry | | |
| 190 kCFRunLoopExit, | |
| 191 true, // repeat | |
| 192 0, // priority | |
| 193 EnterExitObserver, | |
| 194 &observer_context); | |
| 195 CFRunLoopAddObserverToAllModes(run_loop_, enter_exit_observer_); | |
| 196 } | |
| 197 | |
| 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_); | |
| 204 | |
| 205 CFRunLoopRemoveObserverFromAllModes(run_loop_, pre_source_observer_); | |
| 206 CFRelease(pre_source_observer_); | |
| 207 | |
| 208 CFRunLoopRemoveObserverFromAllModes(run_loop_, pre_wait_observer_); | |
| 209 CFRelease(pre_wait_observer_); | |
| 210 | |
| 211 CFRunLoopRemoveSourceFromAllModes(run_loop_, nesting_deferred_work_source_); | |
| 212 CFRelease(nesting_deferred_work_source_); | |
| 213 | |
| 214 CFRunLoopRemoveSourceFromAllModes(run_loop_, idle_work_source_); | |
| 215 CFRelease(idle_work_source_); | |
| 216 | |
| 217 CFRunLoopRemoveSourceFromAllModes(run_loop_, work_source_); | |
| 218 CFRelease(work_source_); | |
| 219 | |
| 220 CFRunLoopRemoveTimerFromAllModes(run_loop_, delayed_work_timer_); | |
| 221 CFRelease(delayed_work_timer_); | |
| 222 | |
| 223 CFRelease(run_loop_); | |
| 224 } | |
| 225 | |
| 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; | |
| 232 | |
| 233 Delegate* last_delegate = delegate_; | |
| 234 SetDelegate(delegate); | |
| 235 | |
| 236 DoRun(delegate); | |
| 237 | |
| 238 // Restore the previous state of the object. | |
| 239 SetDelegate(last_delegate); | |
| 240 run_nesting_level_ = last_run_nesting_level; | |
| 241 } | |
| 242 | |
| 243 void MessagePumpCFRunLoopBase::SetDelegate(Delegate* delegate) { | |
| 244 delegate_ = delegate; | |
| 245 | |
| 246 if (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 | |
| 249 // available. | |
| 250 if (delegateless_work_) { | |
| 251 CFRunLoopSourceSignal(work_source_); | |
| 252 delegateless_work_ = false; | |
| 253 } | |
| 254 if (delegateless_idle_work_) { | |
| 255 CFRunLoopSourceSignal(idle_work_source_); | |
| 256 delegateless_idle_work_ = false; | |
| 257 } | |
| 258 } | |
| 259 } | |
| 260 | |
| 261 // May be called on any thread. | |
| 262 void MessagePumpCFRunLoopBase::ScheduleWork() { | |
| 263 CFRunLoopSourceSignal(work_source_); | |
| 264 CFRunLoopWakeUp(run_loop_); | |
| 265 } | |
| 266 | |
| 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); | |
| 275 } else { | |
| 276 SetTimerTolerance(delayed_work_timer_, 0); | |
| 277 } | |
| 278 } | |
| 279 | |
| 280 void MessagePumpCFRunLoopBase::SetTimerSlack(TimerSlack timer_slack) { | |
| 281 timer_slack_ = timer_slack; | |
| 282 } | |
| 283 | |
| 284 // Called from the run loop. | |
| 285 // static | |
| 286 void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer, | |
| 287 void* info) { | |
| 288 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info); | |
| 289 | |
| 290 // The timer won't fire again until it's reset. | |
| 291 self->delayed_work_fire_time_ = kCFTimeIntervalMax; | |
| 292 | |
| 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_); | |
| 298 } | |
| 299 | |
| 300 // Called from the run loop. | |
| 301 // static | |
| 302 void MessagePumpCFRunLoopBase::RunWorkSource(void* info) { | |
| 303 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info); | |
| 304 base::mac::CallWithEHFrame(^{ | |
| 305 self->RunWork(); | |
| 306 }); | |
| 307 } | |
| 308 | |
| 309 // Called by MessagePumpCFRunLoopBase::RunWorkSource. | |
| 310 bool MessagePumpCFRunLoopBase::RunWork() { | |
| 311 if (!delegate_) { | |
| 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; | |
| 316 return false; | |
| 317 } | |
| 318 | |
| 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); | |
| 325 | |
| 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; | |
| 330 | |
| 331 TimeTicks next_time; | |
| 332 delegate_->DoDelayedWork(&next_time); | |
| 333 if (!did_work) { | |
| 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); | |
| 345 } else { | |
| 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 | |
| 348 // running. | |
| 349 resignal_work_source = true; | |
| 350 } | |
| 351 } | |
| 352 } | |
| 353 | |
| 354 if (resignal_work_source) { | |
| 355 CFRunLoopSourceSignal(work_source_); | |
| 356 } | |
| 357 | |
| 358 return resignal_work_source; | |
| 359 } | |
| 360 | |
| 361 // Called from the run loop. | |
| 362 // static | |
| 363 void MessagePumpCFRunLoopBase::RunIdleWorkSource(void* info) { | |
| 364 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info); | |
| 365 base::mac::CallWithEHFrame(^{ | |
| 366 self->RunIdleWork(); | |
| 367 }); | |
| 368 } | |
| 369 | |
| 370 // Called by MessagePumpCFRunLoopBase::RunIdleWorkSource. | |
| 371 bool MessagePumpCFRunLoopBase::RunIdleWork() { | |
| 372 if (!delegate_) { | |
| 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; | |
| 377 return false; | |
| 378 } | |
| 379 | |
| 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); | |
| 386 | |
| 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(); | |
| 390 if (did_work) { | |
| 391 CFRunLoopSourceSignal(idle_work_source_); | |
| 392 } | |
| 393 | |
| 394 return did_work; | |
| 395 } | |
| 396 | |
| 397 // Called from the run loop. | |
| 398 // static | |
| 399 void MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource(void* info) { | |
| 400 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info); | |
| 401 base::mac::CallWithEHFrame(^{ | |
| 402 self->RunNestingDeferredWork(); | |
| 403 }); | |
| 404 } | |
| 405 | |
| 406 // Called by MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource. | |
| 407 bool MessagePumpCFRunLoopBase::RunNestingDeferredWork() { | |
| 408 if (!delegate_) { | |
| 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. | |
| 413 return false; | |
| 414 } | |
| 415 | |
| 416 // Immediately try work in priority order. | |
| 417 if (!RunWork()) { | |
| 418 if (!RunIdleWork()) { | |
| 419 return false; | |
| 420 } | |
| 421 } else { | |
| 422 // Work was done. Arrange for the loop to try non-nestable idle work on | |
| 423 // a subsequent pass. | |
| 424 CFRunLoopSourceSignal(idle_work_source_); | |
| 425 } | |
| 426 | |
| 427 return true; | |
| 428 } | |
| 429 | |
| 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 | |
| 437 // was disallowed. | |
| 438 if (deepest_nesting_level_ > nesting_level_) { | |
| 439 deepest_nesting_level_ = nesting_level_; | |
| 440 CFRunLoopSourceSignal(nesting_deferred_work_source_); | |
| 441 } | |
| 442 } | |
| 443 | |
| 444 // Called from the run loop. | |
| 445 // static | |
| 446 void MessagePumpCFRunLoopBase::PreWaitObserver(CFRunLoopObserverRef observer, | |
| 447 CFRunLoopActivity activity, | |
| 448 void* info) { | |
| 449 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info); | |
| 450 base::mac::CallWithEHFrame(^{ | |
| 451 // Attempt to do some idle work before going to sleep. | |
| 452 self->RunIdleWork(); | |
| 453 | |
| 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 | |
| 457 // if appropriate. | |
| 458 self->MaybeScheduleNestingDeferredWork(); | |
| 459 }); | |
| 460 } | |
| 461 | |
| 462 // Called from the run loop. | |
| 463 // static | |
| 464 void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer, | |
| 465 CFRunLoopActivity activity, | |
| 466 void* info) { | |
| 467 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info); | |
| 468 | |
| 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 | |
| 473 // appropriate. | |
| 474 base::mac::CallWithEHFrame(^{ | |
| 475 self->MaybeScheduleNestingDeferredWork(); | |
| 476 }); | |
| 477 } | |
| 478 | |
| 479 // Called from the run loop. | |
| 480 // static | |
| 481 void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer, | |
| 482 CFRunLoopActivity activity, | |
| 483 void* info) { | |
| 484 MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info); | |
| 485 | |
| 486 switch (activity) { | |
| 487 case kCFRunLoopEntry: | |
| 488 ++self->nesting_level_; | |
| 489 if (self->nesting_level_ > self->deepest_nesting_level_) { | |
| 490 self->deepest_nesting_level_ = self->nesting_level_; | |
| 491 } | |
| 492 break; | |
| 493 | |
| 494 case kCFRunLoopExit: | |
| 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. | |
| 504 // | |
| 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 | |
| 510 // loop. | |
| 511 base::mac::CallWithEHFrame(^{ | |
| 512 self->MaybeScheduleNestingDeferredWork(); | |
| 513 }); | |
| 514 --self->nesting_level_; | |
| 515 break; | |
| 516 | |
| 517 default: | |
| 518 break; | |
| 519 } | |
| 520 | |
| 521 base::mac::CallWithEHFrame(^{ | |
| 522 self->EnterExitRunLoop(activity); | |
| 523 }); | |
| 524 } | |
| 525 | |
| 526 // Called by MessagePumpCFRunLoopBase::EnterExitRunLoop. The default | |
| 527 // implementation is a no-op. | |
| 528 void MessagePumpCFRunLoopBase::EnterExitRunLoop(CFRunLoopActivity activity) { | |
| 529 } | |
| 530 | |
| 531 // Base version returns a standard NSAutoreleasePool. | |
| 532 AutoreleasePoolType* MessagePumpCFRunLoopBase::CreateAutoreleasePool() { | |
| 533 return [[NSAutoreleasePool alloc] init]; | |
| 534 } | |
| 535 | |
| 536 MessagePumpCFRunLoop::MessagePumpCFRunLoop() | |
| 537 : quit_pending_(false) { | |
| 538 } | |
| 539 | |
| 540 MessagePumpCFRunLoop::~MessagePumpCFRunLoop() {} | |
| 541 | |
| 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. | |
| 549 int result; | |
| 550 do { | |
| 551 MessagePumpScopedAutoreleasePool autorelease_pool(this); | |
| 552 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, | |
| 553 kCFTimeIntervalMax, | |
| 554 false); | |
| 555 } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished); | |
| 556 } | |
| 557 | |
| 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()); | |
| 564 } else { | |
| 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; | |
| 571 } | |
| 572 } | |
| 573 | |
| 574 // Called by MessagePumpCFRunLoopBase::EnterExitObserver. | |
| 575 void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) { | |
| 576 if (activity == kCFRunLoopExit && | |
| 577 nesting_level() == run_nesting_level() && | |
| 578 quit_pending_) { | |
| 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 | |
| 582 // just inside Run. | |
| 583 CFRunLoopStop(run_loop()); | |
| 584 quit_pending_ = false; | |
| 585 } | |
| 586 } | |
| 587 | |
| 588 MessagePumpNSRunLoop::MessagePumpNSRunLoop() | |
| 589 : keep_running_(true) { | |
| 590 CFRunLoopSourceContext source_context = CFRunLoopSourceContext(); | |
| 591 source_context.perform = NoOp; | |
| 592 quit_source_ = CFRunLoopSourceCreate(NULL, // allocator | |
| 593 0, // priority | |
| 594 &source_context); | |
| 595 CFRunLoopAddSourceToAllModes(run_loop(), quit_source_); | |
| 596 } | |
| 597 | |
| 598 MessagePumpNSRunLoop::~MessagePumpNSRunLoop() { | |
| 599 CFRunLoopRemoveSourceFromAllModes(run_loop(), quit_source_); | |
| 600 CFRelease(quit_source_); | |
| 601 } | |
| 602 | |
| 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]]; | |
| 608 } | |
| 609 | |
| 610 keep_running_ = true; | |
| 611 } | |
| 612 | |
| 613 void MessagePumpNSRunLoop::Quit() { | |
| 614 keep_running_ = false; | |
| 615 CFRunLoopSourceSignal(quit_source_); | |
| 616 CFRunLoopWakeUp(run_loop()); | |
| 617 } | |
| 618 | |
| 619 #if defined(OS_IOS) | |
| 620 MessagePumpUIApplication::MessagePumpUIApplication() | |
| 621 : run_loop_(NULL) { | |
| 622 } | |
| 623 | |
| 624 MessagePumpUIApplication::~MessagePumpUIApplication() {} | |
| 625 | |
| 626 void MessagePumpUIApplication::DoRun(Delegate* delegate) { | |
| 627 NOTREACHED(); | |
| 628 } | |
| 629 | |
| 630 void MessagePumpUIApplication::Quit() { | |
| 631 NOTREACHED(); | |
| 632 } | |
| 633 | |
| 634 void MessagePumpUIApplication::Attach(Delegate* delegate) { | |
| 635 DCHECK(!run_loop_); | |
| 636 run_loop_ = new RunLoop(); | |
| 637 CHECK(run_loop_->BeforeRun()); | |
| 638 SetDelegate(delegate); | |
| 639 } | |
| 640 | |
| 641 #else | |
| 642 | |
| 643 MessagePumpNSApplication::MessagePumpNSApplication() | |
| 644 : keep_running_(true), | |
| 645 running_own_loop_(false) { | |
| 646 } | |
| 647 | |
| 648 MessagePumpNSApplication::~MessagePumpNSApplication() {} | |
| 649 | |
| 650 void MessagePumpNSApplication::DoRun(Delegate* delegate) { | |
| 651 bool last_running_own_loop_ = running_own_loop_; | |
| 652 | |
| 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(). | |
| 658 CHECK(NSApp); | |
| 659 | |
| 660 if (![NSApp isRunning]) { | |
| 661 running_own_loop_ = false; | |
| 662 // NSApplication manages autorelease pools itself when run this way. | |
| 663 [NSApp run]; | |
| 664 } else { | |
| 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 | |
| 672 dequeue:YES]; | |
| 673 if (event) { | |
| 674 [NSApp sendEvent:event]; | |
| 675 } | |
| 676 } | |
| 677 keep_running_ = true; | |
| 678 } | |
| 679 | |
| 680 running_own_loop_ = last_running_own_loop_; | |
| 681 } | |
| 682 | |
| 683 void MessagePumpNSApplication::Quit() { | |
| 684 if (!running_own_loop_) { | |
| 685 [[NSApplication sharedApplication] stop:nil]; | |
| 686 } else { | |
| 687 keep_running_ = false; | |
| 688 } | |
| 689 | |
| 690 // Send a fake event to wake the loop up. | |
| 691 [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined | |
| 692 location:NSZeroPoint | |
| 693 modifierFlags:0 | |
| 694 timestamp:0 | |
| 695 windowNumber:0 | |
| 696 context:NULL | |
| 697 subtype:0 | |
| 698 data1:0 | |
| 699 data2:0] | |
| 700 atStart:NO]; | |
| 701 } | |
| 702 | |
| 703 MessagePumpCrApplication::MessagePumpCrApplication() { | |
| 704 } | |
| 705 | |
| 706 MessagePumpCrApplication::~MessagePumpCrApplication() { | |
| 707 } | |
| 708 | |
| 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) | |
| 715 // | |
| 716 // #0 [NSWindowController autorelease] | |
| 717 // #1 DoAClose | |
| 718 // #2 MessagePumpCFRunLoopBase::DoWork() | |
| 719 // #3 [NSRunLoop run] | |
| 720 // #4 [NSButton performClick:] | |
| 721 // #5 [NSWindow sendEvent:] | |
| 722 // #6 [NSApp sendEvent:] | |
| 723 // #7 [NSApp run] | |
| 724 // | |
| 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. | |
| 736 // | |
| 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()) | |
| 742 return nil; | |
| 743 return MessagePumpNSApplication::CreateAutoreleasePool(); | |
| 744 } | |
| 745 | |
| 746 // static | |
| 747 bool MessagePumpMac::UsingCrApp() { | |
| 748 DCHECK([NSThread isMainThread]); | |
| 749 | |
| 750 // If NSApp is still not initialized, then the subclass used cannot | |
| 751 // be determined. | |
| 752 DCHECK(NSApp); | |
| 753 | |
| 754 // The pump was created using MessagePumpNSApplication. | |
| 755 if (g_not_using_cr_app) | |
| 756 return false; | |
| 757 | |
| 758 return [NSApp conformsToProtocol:@protocol(CrAppProtocol)]; | |
| 759 } | |
| 760 | |
| 761 // static | |
| 762 bool MessagePumpMac::IsHandlingSendEvent() { | |
| 763 DCHECK([NSApp conformsToProtocol:@protocol(CrAppProtocol)]); | |
| 764 NSObject<CrAppProtocol>* app = static_cast<NSObject<CrAppProtocol>*>(NSApp); | |
| 765 return [app isHandlingSendEvent]; | |
| 766 } | |
| 767 #endif // !defined(OS_IOS) | |
| 768 | |
| 769 // static | |
| 770 MessagePump* MessagePumpMac::Create() { | |
| 771 if ([NSThread isMainThread]) { | |
| 772 #if defined(OS_IOS) | |
| 773 return new MessagePumpUIApplication; | |
| 774 #else | |
| 775 if ([NSApp conformsToProtocol:@protocol(CrAppProtocol)]) | |
| 776 return new MessagePumpCrApplication; | |
| 777 | |
| 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; | |
| 785 #endif | |
| 786 } | |
| 787 | |
| 788 return new MessagePumpNSRunLoop; | |
| 789 } | |
| 790 | |
| 791 } // namespace base | |
| OLD | NEW |