Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_MessageManager.cpp 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. MessageManager::MessageManager() noexcept
  18. : quitMessagePosted (false),
  19. quitMessageReceived (false),
  20. messageThreadId (Thread::getCurrentThreadId()),
  21. threadWithLock (0)
  22. {
  23. if (JUCEApplicationBase::isStandaloneApp())
  24. Thread::setCurrentThreadName ("Juce Message Thread");
  25. }
  26. MessageManager::~MessageManager() noexcept
  27. {
  28. broadcaster = nullptr;
  29. doPlatformSpecificShutdown();
  30. jassert (instance == this);
  31. instance = nullptr; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  32. }
  33. MessageManager* MessageManager::instance = nullptr;
  34. MessageManager* MessageManager::getInstance()
  35. {
  36. if (instance == nullptr)
  37. {
  38. instance = new MessageManager();
  39. doPlatformSpecificInitialisation();
  40. }
  41. return instance;
  42. }
  43. MessageManager* MessageManager::getInstanceWithoutCreating() noexcept
  44. {
  45. return instance;
  46. }
  47. void MessageManager::deleteInstance()
  48. {
  49. deleteAndZero (instance);
  50. }
  51. //==============================================================================
  52. void MessageManager::MessageBase::post()
  53. {
  54. MessageManager* const mm = MessageManager::instance;
  55. if (mm == nullptr || mm->quitMessagePosted || ! postMessageToSystemQueue (this))
  56. Ptr deleter (this); // (this will delete messages that were just created with a 0 ref count)
  57. }
  58. //==============================================================================
  59. #if JUCE_MODAL_LOOPS_PERMITTED && ! (JUCE_MAC || JUCE_IOS)
  60. void MessageManager::runDispatchLoop()
  61. {
  62. runDispatchLoopUntil (-1);
  63. }
  64. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  65. {
  66. jassert (isThisTheMessageThread()); // must only be called by the message thread
  67. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  68. while (! quitMessageReceived)
  69. {
  70. JUCE_TRY
  71. {
  72. if (! dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  73. Thread::sleep (1);
  74. }
  75. JUCE_CATCH_EXCEPTION
  76. if (millisecondsToRunFor >= 0 && Time::currentTimeMillis() >= endTime)
  77. break;
  78. }
  79. return ! quitMessageReceived;
  80. }
  81. class MessageManager::QuitMessage : public MessageManager::MessageBase
  82. {
  83. public:
  84. QuitMessage() {}
  85. void messageCallback() override
  86. {
  87. if (MessageManager* const mm = MessageManager::instance)
  88. mm->quitMessageReceived = true;
  89. }
  90. JUCE_DECLARE_NON_COPYABLE (QuitMessage)
  91. };
  92. void MessageManager::stopDispatchLoop()
  93. {
  94. (new QuitMessage())->post();
  95. quitMessagePosted = true;
  96. }
  97. #endif
  98. //==============================================================================
  99. class AsyncFunctionCallback : public MessageManager::MessageBase
  100. {
  101. public:
  102. AsyncFunctionCallback (MessageCallbackFunction* const f, void* const param)
  103. : result (nullptr), func (f), parameter (param)
  104. {}
  105. void messageCallback() override
  106. {
  107. result = (*func) (parameter);
  108. finished.signal();
  109. }
  110. WaitableEvent finished;
  111. void* volatile result;
  112. private:
  113. MessageCallbackFunction* const func;
  114. void* const parameter;
  115. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCallback)
  116. };
  117. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* const func, void* const parameter)
  118. {
  119. if (isThisTheMessageThread())
  120. return func (parameter);
  121. // If this thread has the message manager locked, then this will deadlock!
  122. jassert (! currentThreadHasLockedMessageManager());
  123. const ReferenceCountedObjectPtr<AsyncFunctionCallback> message (new AsyncFunctionCallback (func, parameter));
  124. message->post();
  125. message->finished.wait();
  126. return message->result;
  127. }
  128. //==============================================================================
  129. void MessageManager::deliverBroadcastMessage (const String& value)
  130. {
  131. if (broadcaster != nullptr)
  132. broadcaster->sendActionMessage (value);
  133. }
  134. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  135. {
  136. if (broadcaster == nullptr)
  137. broadcaster = new ActionBroadcaster();
  138. broadcaster->addActionListener (listener);
  139. }
  140. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  141. {
  142. if (broadcaster != nullptr)
  143. broadcaster->removeActionListener (listener);
  144. }
  145. //==============================================================================
  146. bool MessageManager::isThisTheMessageThread() const noexcept
  147. {
  148. return Thread::getCurrentThreadId() == messageThreadId;
  149. }
  150. void MessageManager::setCurrentThreadAsMessageThread()
  151. {
  152. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  153. if (messageThreadId != thisThread)
  154. {
  155. messageThreadId = thisThread;
  156. // This is needed on windows to make sure the message window is created by this thread
  157. doPlatformSpecificShutdown();
  158. doPlatformSpecificInitialisation();
  159. }
  160. }
  161. bool MessageManager::currentThreadHasLockedMessageManager() const noexcept
  162. {
  163. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  164. return thisThread == messageThreadId || thisThread == threadWithLock;
  165. }
  166. //==============================================================================
  167. //==============================================================================
  168. /* The only safe way to lock the message thread while another thread does
  169. some work is by posting a special message, whose purpose is to tie up the event
  170. loop until the other thread has finished its business.
  171. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  172. get locked before making an event callback, because if the same OS lock gets indirectly
  173. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  174. in Cocoa).
  175. */
  176. class MessageManagerLock::BlockingMessage : public MessageManager::MessageBase
  177. {
  178. public:
  179. BlockingMessage() noexcept {}
  180. void messageCallback() override
  181. {
  182. lockedEvent.signal();
  183. releaseEvent.wait();
  184. }
  185. WaitableEvent lockedEvent, releaseEvent;
  186. JUCE_DECLARE_NON_COPYABLE (BlockingMessage)
  187. };
  188. //==============================================================================
  189. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  190. : blockingMessage(), locked (attemptLock (threadToCheck, nullptr))
  191. {
  192. }
  193. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  194. : blockingMessage(), locked (attemptLock (nullptr, jobToCheckForExitSignal))
  195. {
  196. }
  197. bool MessageManagerLock::attemptLock (Thread* const threadToCheck, ThreadPoolJob* const job)
  198. {
  199. MessageManager* const mm = MessageManager::instance;
  200. if (mm == nullptr)
  201. return false;
  202. if (mm->currentThreadHasLockedMessageManager())
  203. return true;
  204. if (threadToCheck == nullptr && job == nullptr)
  205. {
  206. mm->lockingLock.enter();
  207. }
  208. else
  209. {
  210. while (! mm->lockingLock.tryEnter())
  211. {
  212. if ((threadToCheck != nullptr && threadToCheck->threadShouldExit())
  213. || (job != nullptr && job->shouldExit()))
  214. return false;
  215. Thread::yield();
  216. }
  217. }
  218. blockingMessage = new BlockingMessage();
  219. blockingMessage->post();
  220. while (! blockingMessage->lockedEvent.wait (20))
  221. {
  222. if ((threadToCheck != nullptr && threadToCheck->threadShouldExit())
  223. || (job != nullptr && job->shouldExit()))
  224. {
  225. blockingMessage->releaseEvent.signal();
  226. blockingMessage = nullptr;
  227. mm->lockingLock.exit();
  228. return false;
  229. }
  230. }
  231. jassert (mm->threadWithLock == 0);
  232. mm->threadWithLock = Thread::getCurrentThreadId();
  233. return true;
  234. }
  235. MessageManagerLock::~MessageManagerLock() noexcept
  236. {
  237. if (blockingMessage != nullptr)
  238. {
  239. MessageManager* const mm = MessageManager::instance;
  240. jassert (mm == nullptr || mm->currentThreadHasLockedMessageManager());
  241. blockingMessage->releaseEvent.signal();
  242. blockingMessage = nullptr;
  243. if (mm != nullptr)
  244. {
  245. mm->threadWithLock = 0;
  246. mm->lockingLock.exit();
  247. }
  248. }
  249. }
  250. //==============================================================================
  251. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  252. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  253. {
  254. JUCE_AUTORELEASEPOOL
  255. {
  256. MessageManager::getInstance();
  257. }
  258. }
  259. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  260. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  261. {
  262. JUCE_AUTORELEASEPOOL
  263. {
  264. DeletedAtShutdown::deleteAll();
  265. MessageManager::deleteInstance();
  266. }
  267. }
  268. ScopedJuceInitialiser_GUI::ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  269. ScopedJuceInitialiser_GUI::~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }