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 10.0KB

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