1 /* 2 ============================================================================== 3 4 This file is part of the JUCE library. 5 Copyright (c) 2020 - Raw Material Software Limited 6 7 JUCE is an open source library subject to commercial or open-source 8 licensing. 9 10 The code included in this file is provided under the terms of the ISC license 11 http://www.isc.org/downloads/software-support-policy/isc-license. Permission 12 To use, copy, modify, and/or distribute this software for any purpose with or 13 without fee is hereby granted provided that the above copyright notice and 14 this permission notice appear in all copies. 15 16 JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER 17 EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE 18 DISCLAIMED. 19 20 ============================================================================== 21 */ 22 23 namespace juce 24 { 25 26 //============================================================================== 27 /* An internal message pump class used in OSX and iOS. */ 28 class MessageQueue 29 { 30 public: MessageQueue()31 MessageQueue() 32 { 33 #if JUCE_IOS 34 runLoop = CFRunLoopGetCurrent(); 35 #else 36 runLoop = CFRunLoopGetMain(); 37 #endif 38 39 CFRunLoopSourceContext sourceContext; 40 zerostruct (sourceContext); // (can't use "= { 0 }" on this object because it's typedef'ed as a C struct) 41 sourceContext.info = this; 42 sourceContext.perform = runLoopSourceCallback; 43 runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext); 44 CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes); 45 } 46 ~MessageQueue()47 ~MessageQueue() noexcept 48 { 49 CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes); 50 CFRunLoopSourceInvalidate (runLoopSource); 51 CFRelease (runLoopSource); 52 } 53 post(MessageManager::MessageBase * const message)54 void post (MessageManager::MessageBase* const message) 55 { 56 messages.add (message); 57 wakeUp(); 58 } 59 60 private: 61 ReferenceCountedArray<MessageManager::MessageBase, CriticalSection> messages; 62 CFRunLoopRef runLoop; 63 CFRunLoopSourceRef runLoopSource; 64 wakeUp()65 void wakeUp() noexcept 66 { 67 CFRunLoopSourceSignal (runLoopSource); 68 CFRunLoopWakeUp (runLoop); 69 } 70 deliverNextMessage()71 bool deliverNextMessage() 72 { 73 const MessageManager::MessageBase::Ptr nextMessage (messages.removeAndReturn (0)); 74 75 if (nextMessage == nullptr) 76 return false; 77 78 JUCE_AUTORELEASEPOOL 79 { 80 JUCE_TRY 81 { 82 nextMessage->messageCallback(); 83 } 84 JUCE_CATCH_EXCEPTION 85 } 86 87 return true; 88 } 89 runLoopCallback()90 void runLoopCallback() noexcept 91 { 92 for (int i = 4; --i >= 0;) 93 if (! deliverNextMessage()) 94 return; 95 96 wakeUp(); 97 } 98 runLoopSourceCallback(void * info)99 static void runLoopSourceCallback (void* info) noexcept 100 { 101 static_cast<MessageQueue*> (info)->runLoopCallback(); 102 } 103 }; 104 105 } // namespace juce 106