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.

388 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. MessageManager::MessageManager() noexcept
  20. : messageThreadId (Thread::getCurrentThreadId())
  21. {
  22. if (JUCEApplicationBase::isStandaloneApp())
  23. Thread::setCurrentThreadName ("Juce Message Thread");
  24. }
  25. MessageManager::~MessageManager() noexcept
  26. {
  27. broadcaster = nullptr;
  28. doPlatformSpecificShutdown();
  29. jassert (instance == this);
  30. instance = nullptr; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31. }
  32. MessageManager* MessageManager::instance = nullptr;
  33. MessageManager* MessageManager::getInstance()
  34. {
  35. if (instance == nullptr)
  36. {
  37. instance = new MessageManager();
  38. doPlatformSpecificInitialisation();
  39. }
  40. return instance;
  41. }
  42. MessageManager* MessageManager::getInstanceWithoutCreating() noexcept
  43. {
  44. return instance;
  45. }
  46. void MessageManager::deleteInstance()
  47. {
  48. deleteAndZero (instance);
  49. }
  50. //==============================================================================
  51. bool MessageManager::MessageBase::post()
  52. {
  53. auto* mm = MessageManager::instance;
  54. if (mm == nullptr || mm->quitMessagePosted || ! postMessageToSystemQueue (this))
  55. {
  56. Ptr deleter (this); // (this will delete messages that were just created with a 0 ref count)
  57. return false;
  58. }
  59. return true;
  60. }
  61. //==============================================================================
  62. #if JUCE_MODAL_LOOPS_PERMITTED && ! (JUCE_MAC || JUCE_IOS)
  63. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  64. {
  65. jassert (isThisTheMessageThread()); // must only be called by the message thread
  66. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  67. while (! quitMessageReceived)
  68. {
  69. JUCE_TRY
  70. {
  71. if (! dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  72. Thread::sleep (1);
  73. }
  74. JUCE_CATCH_EXCEPTION
  75. if (millisecondsToRunFor >= 0 && Time::currentTimeMillis() >= endTime)
  76. break;
  77. }
  78. return ! quitMessageReceived;
  79. }
  80. #endif
  81. #if ! (JUCE_MAC || JUCE_IOS || JUCE_ANDROID)
  82. class MessageManager::QuitMessage : public MessageManager::MessageBase
  83. {
  84. public:
  85. QuitMessage() {}
  86. void messageCallback() override
  87. {
  88. if (auto* mm = MessageManager::instance)
  89. mm->quitMessageReceived = true;
  90. }
  91. JUCE_DECLARE_NON_COPYABLE (QuitMessage)
  92. };
  93. void MessageManager::runDispatchLoop()
  94. {
  95. jassert (isThisTheMessageThread()); // must only be called by the message thread
  96. while (! quitMessageReceived)
  97. {
  98. JUCE_TRY
  99. {
  100. if (! dispatchNextMessageOnSystemQueue (false))
  101. Thread::sleep (1);
  102. }
  103. JUCE_CATCH_EXCEPTION
  104. }
  105. }
  106. void MessageManager::stopDispatchLoop()
  107. {
  108. (new QuitMessage())->post();
  109. quitMessagePosted = true;
  110. }
  111. #endif
  112. //==============================================================================
  113. class AsyncFunctionCallback : public MessageManager::MessageBase
  114. {
  115. public:
  116. AsyncFunctionCallback (MessageCallbackFunction* const f, void* const param)
  117. : func (f), parameter (param)
  118. {}
  119. void messageCallback() override
  120. {
  121. result = (*func) (parameter);
  122. finished.signal();
  123. }
  124. WaitableEvent finished;
  125. void* volatile result = nullptr;
  126. private:
  127. MessageCallbackFunction* const func;
  128. void* const parameter;
  129. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCallback)
  130. };
  131. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* const func, void* const parameter)
  132. {
  133. if (isThisTheMessageThread())
  134. return func (parameter);
  135. // If this thread has the message manager locked, then this will deadlock!
  136. jassert (! currentThreadHasLockedMessageManager());
  137. const ReferenceCountedObjectPtr<AsyncFunctionCallback> message (new AsyncFunctionCallback (func, parameter));
  138. if (message->post())
  139. {
  140. message->finished.wait();
  141. return message->result;
  142. }
  143. jassertfalse; // the OS message queue failed to send the message!
  144. return nullptr;
  145. }
  146. //==============================================================================
  147. void MessageManager::deliverBroadcastMessage (const String& value)
  148. {
  149. if (broadcaster != nullptr)
  150. broadcaster->sendActionMessage (value);
  151. }
  152. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  153. {
  154. if (broadcaster == nullptr)
  155. broadcaster = new ActionBroadcaster();
  156. broadcaster->addActionListener (listener);
  157. }
  158. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  159. {
  160. if (broadcaster != nullptr)
  161. broadcaster->removeActionListener (listener);
  162. }
  163. //==============================================================================
  164. bool MessageManager::isThisTheMessageThread() const noexcept
  165. {
  166. return Thread::getCurrentThreadId() == messageThreadId;
  167. }
  168. void MessageManager::setCurrentThreadAsMessageThread()
  169. {
  170. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  171. if (messageThreadId != thisThread)
  172. {
  173. messageThreadId = thisThread;
  174. // This is needed on windows to make sure the message window is created by this thread
  175. doPlatformSpecificShutdown();
  176. doPlatformSpecificInitialisation();
  177. }
  178. }
  179. bool MessageManager::currentThreadHasLockedMessageManager() const noexcept
  180. {
  181. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  182. return thisThread == messageThreadId || thisThread == threadWithLock;
  183. }
  184. //==============================================================================
  185. //==============================================================================
  186. /* The only safe way to lock the message thread while another thread does
  187. some work is by posting a special message, whose purpose is to tie up the event
  188. loop until the other thread has finished its business.
  189. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  190. get locked before making an event callback, because if the same OS lock gets indirectly
  191. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  192. in Cocoa).
  193. */
  194. class MessageManagerLock::BlockingMessage : public MessageManager::MessageBase
  195. {
  196. public:
  197. BlockingMessage() noexcept {}
  198. void messageCallback() override
  199. {
  200. lockedEvent.signal();
  201. releaseEvent.wait();
  202. }
  203. WaitableEvent lockedEvent, releaseEvent;
  204. JUCE_DECLARE_NON_COPYABLE (BlockingMessage)
  205. };
  206. //==============================================================================
  207. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  208. : blockingMessage(), checker (threadToCheck, nullptr),
  209. locked (attemptLock (threadToCheck != nullptr ? &checker : nullptr))
  210. {
  211. }
  212. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  213. : blockingMessage(), checker (nullptr, jobToCheckForExitSignal),
  214. locked (attemptLock (jobToCheckForExitSignal != nullptr ? &checker : nullptr))
  215. {
  216. }
  217. MessageManagerLock::MessageManagerLock (BailOutChecker& bailOutChecker)
  218. : blockingMessage(), checker (nullptr, nullptr),
  219. locked (attemptLock (&bailOutChecker))
  220. {
  221. }
  222. bool MessageManagerLock::attemptLock (BailOutChecker* bailOutChecker)
  223. {
  224. auto* mm = MessageManager::instance;
  225. if (mm == nullptr)
  226. return false;
  227. if (mm->currentThreadHasLockedMessageManager())
  228. return true;
  229. if (bailOutChecker == nullptr)
  230. {
  231. mm->lockingLock.enter();
  232. }
  233. else
  234. {
  235. while (! mm->lockingLock.tryEnter())
  236. {
  237. if (bailOutChecker->shouldAbortAcquiringLock())
  238. return false;
  239. Thread::yield();
  240. }
  241. }
  242. blockingMessage = new BlockingMessage();
  243. if (! blockingMessage->post())
  244. {
  245. blockingMessage = nullptr;
  246. return false;
  247. }
  248. while (! blockingMessage->lockedEvent.wait (20))
  249. {
  250. if (bailOutChecker != nullptr && bailOutChecker->shouldAbortAcquiringLock())
  251. {
  252. blockingMessage->releaseEvent.signal();
  253. blockingMessage = nullptr;
  254. mm->lockingLock.exit();
  255. return false;
  256. }
  257. }
  258. jassert (mm->threadWithLock == 0);
  259. mm->threadWithLock = Thread::getCurrentThreadId();
  260. return true;
  261. }
  262. MessageManagerLock::~MessageManagerLock() noexcept
  263. {
  264. if (blockingMessage != nullptr)
  265. {
  266. auto* mm = MessageManager::instance;
  267. jassert (mm == nullptr || mm->currentThreadHasLockedMessageManager());
  268. blockingMessage->releaseEvent.signal();
  269. blockingMessage = nullptr;
  270. if (mm != nullptr)
  271. {
  272. mm->threadWithLock = 0;
  273. mm->lockingLock.exit();
  274. }
  275. }
  276. }
  277. //==============================================================================
  278. MessageManagerLock::ThreadChecker::ThreadChecker (Thread* const threadToUse,
  279. ThreadPoolJob* const threadJobToUse)
  280. : threadToCheck (threadToUse), job (threadJobToUse)
  281. {
  282. }
  283. bool MessageManagerLock::ThreadChecker::shouldAbortAcquiringLock()
  284. {
  285. return (threadToCheck != nullptr && threadToCheck->threadShouldExit())
  286. || (job != nullptr && job->shouldExit());
  287. }
  288. //==============================================================================
  289. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  290. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  291. {
  292. JUCE_AUTORELEASEPOOL
  293. {
  294. MessageManager::getInstance();
  295. }
  296. }
  297. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  298. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  299. {
  300. JUCE_AUTORELEASEPOOL
  301. {
  302. DeletedAtShutdown::deleteAll();
  303. MessageManager::deleteInstance();
  304. }
  305. }
  306. static int numScopedInitInstances = 0;
  307. ScopedJuceInitialiser_GUI::ScopedJuceInitialiser_GUI() { if (numScopedInitInstances++ == 0) initialiseJuce_GUI(); }
  308. ScopedJuceInitialiser_GUI::~ScopedJuceInitialiser_GUI() { if (--numScopedInitInstances == 0) shutdownJuce_GUI(); }
  309. } // namespace juce