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

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