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.

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