+const char *CYHandleCommand(CYPool &pool, const std::string &code) {
+ bool dispatch;
+#ifdef __APPLE__
+ CFRunLoopRef loop(CFRunLoopGetMain());
+ if (CFStringRef mode = CFRunLoopCopyCurrentMode(loop)) {
+ dispatch = true;
+ CFRelease(mode);
+ } else
+#endif
+ dispatch = false;
+
+ CYExecute_ execute = {pool, code.c_str()};
+
+ pthread_mutex_init(&execute.mutex_, NULL);
+ pthread_cond_init(&execute.condition_, NULL);
+
+ if (!dispatch)
+ CYPerform(&execute);
+#ifdef __APPLE__
+ else {
+ CFRunLoopSourceContext context;
+ memset(&context, 0, sizeof(context));
+ context.version = 0;
+ context.info = &execute;
+ context.perform = &CYPerform;
+
+ CFRunLoopSourceRef source(CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context));
+
+ pthread_mutex_lock(&execute.mutex_);
+
+ CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes);
+ CFRunLoopSourceSignal(source);
+
+ CFRunLoopWakeUp(loop);
+ pthread_cond_wait(&execute.condition_, &execute.mutex_);
+ pthread_mutex_unlock(&execute.mutex_);
+
+ CFRunLoopRemoveSource(loop, source, kCFRunLoopCommonModes);
+ CFRelease(source);
+ }
+#endif
+
+ pthread_cond_destroy(&execute.condition_);
+ pthread_mutex_destroy(&execute.mutex_);
+
+ return execute.data_;
+}
+