The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

338 lines
10KB

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