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.

479 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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.reset();
  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.get() != 0 || ! 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. auto endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  67. while (quitMessageReceived.get() == 0)
  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.get() == 0;
  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.get() == 0)
  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. std::atomic<void*> result { nullptr };
  126. private:
  127. MessageCallbackFunction* const func;
  128. void* const parameter;
  129. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCallback)
  130. };
  131. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* 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.load();
  142. }
  143. jassertfalse; // the OS message queue failed to send the message!
  144. return nullptr;
  145. }
  146. bool MessageManager::callAsync (std::function<void()> fn)
  147. {
  148. struct AsyncCallInvoker : public MessageBase
  149. {
  150. AsyncCallInvoker (std::function<void()> f) : callback (std::move (f)) {}
  151. void messageCallback() override { callback(); }
  152. std::function<void()> callback;
  153. };
  154. return (new AsyncCallInvoker (std::move (fn)))->post();
  155. }
  156. //==============================================================================
  157. void MessageManager::deliverBroadcastMessage (const String& value)
  158. {
  159. if (broadcaster != nullptr)
  160. broadcaster->sendActionMessage (value);
  161. }
  162. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  163. {
  164. if (broadcaster == nullptr)
  165. broadcaster.reset (new ActionBroadcaster());
  166. broadcaster->addActionListener (listener);
  167. }
  168. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  169. {
  170. if (broadcaster != nullptr)
  171. broadcaster->removeActionListener (listener);
  172. }
  173. //==============================================================================
  174. bool MessageManager::isThisTheMessageThread() const noexcept
  175. {
  176. return Thread::getCurrentThreadId() == messageThreadId;
  177. }
  178. void MessageManager::setCurrentThreadAsMessageThread()
  179. {
  180. auto thisThread = Thread::getCurrentThreadId();
  181. if (messageThreadId != thisThread)
  182. {
  183. messageThreadId = thisThread;
  184. // This is needed on windows to make sure the message window is created by this thread
  185. doPlatformSpecificShutdown();
  186. doPlatformSpecificInitialisation();
  187. }
  188. }
  189. bool MessageManager::currentThreadHasLockedMessageManager() const noexcept
  190. {
  191. auto thisThread = Thread::getCurrentThreadId();
  192. return thisThread == messageThreadId || thisThread == threadWithLock.get();
  193. }
  194. bool MessageManager::existsAndIsLockedByCurrentThread() noexcept
  195. {
  196. if (auto i = getInstanceWithoutCreating())
  197. return i->currentThreadHasLockedMessageManager();
  198. return false;
  199. }
  200. bool MessageManager::existsAndIsCurrentThread() noexcept
  201. {
  202. if (auto i = getInstanceWithoutCreating())
  203. return i->isThisTheMessageThread();
  204. return false;
  205. }
  206. //==============================================================================
  207. //==============================================================================
  208. /* The only safe way to lock the message thread while another thread does
  209. some work is by posting a special message, whose purpose is to tie up the event
  210. loop until the other thread has finished its business.
  211. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  212. get locked before making an event callback, because if the same OS lock gets indirectly
  213. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  214. in Cocoa).
  215. */
  216. struct MessageManager::Lock::BlockingMessage : public MessageManager::MessageBase
  217. {
  218. BlockingMessage (const MessageManager::Lock* parent) noexcept
  219. : owner (parent)
  220. {}
  221. void messageCallback() override
  222. {
  223. {
  224. ScopedLock lock (ownerCriticalSection);
  225. if (auto* o = owner.get())
  226. o->messageCallback();
  227. }
  228. releaseEvent.wait();
  229. }
  230. CriticalSection ownerCriticalSection;
  231. Atomic<const MessageManager::Lock*> owner;
  232. WaitableEvent releaseEvent;
  233. JUCE_DECLARE_NON_COPYABLE (BlockingMessage)
  234. };
  235. //==============================================================================
  236. MessageManager::Lock::Lock() {}
  237. MessageManager::Lock::~Lock() { exit(); }
  238. void MessageManager::Lock::enter() const noexcept { tryAcquire (true); }
  239. bool MessageManager::Lock::tryEnter() const noexcept { return tryAcquire (false); }
  240. bool MessageManager::Lock::tryAcquire (bool lockIsMandatory) const noexcept
  241. {
  242. auto* mm = MessageManager::instance;
  243. if (mm == nullptr)
  244. {
  245. jassertfalse;
  246. return false;
  247. }
  248. if (! lockIsMandatory && (abortWait.get() != 0))
  249. {
  250. abortWait.set (0);
  251. return false;
  252. }
  253. if (mm->currentThreadHasLockedMessageManager())
  254. return true;
  255. try
  256. {
  257. blockingMessage = *new BlockingMessage (this);
  258. }
  259. catch (...)
  260. {
  261. jassert (! lockIsMandatory);
  262. return false;
  263. }
  264. if (! blockingMessage->post())
  265. {
  266. // post of message failed while trying to get the lock
  267. jassert (! lockIsMandatory);
  268. blockingMessage = nullptr;
  269. return false;
  270. }
  271. do
  272. {
  273. while (abortWait.get() == 0)
  274. lockedEvent.wait (-1);
  275. abortWait.set (0);
  276. if (lockGained.get() != 0)
  277. {
  278. mm->threadWithLock = Thread::getCurrentThreadId();
  279. return true;
  280. }
  281. } while (lockIsMandatory);
  282. // we didn't get the lock
  283. blockingMessage->releaseEvent.signal();
  284. {
  285. ScopedLock lock (blockingMessage->ownerCriticalSection);
  286. lockGained.set (0);
  287. blockingMessage->owner.set (nullptr);
  288. }
  289. blockingMessage = nullptr;
  290. return false;
  291. }
  292. void MessageManager::Lock::exit() const noexcept
  293. {
  294. if (lockGained.compareAndSetBool (false, true))
  295. {
  296. auto* mm = MessageManager::instance;
  297. jassert (mm == nullptr || mm->currentThreadHasLockedMessageManager());
  298. lockGained.set (0);
  299. if (mm != nullptr)
  300. mm->threadWithLock = {};
  301. if (blockingMessage != nullptr)
  302. {
  303. blockingMessage->releaseEvent.signal();
  304. blockingMessage = nullptr;
  305. }
  306. }
  307. }
  308. void MessageManager::Lock::messageCallback() const
  309. {
  310. lockGained.set (1);
  311. abort();
  312. }
  313. void MessageManager::Lock::abort() const noexcept
  314. {
  315. abortWait.set (1);
  316. lockedEvent.signal();
  317. }
  318. //==============================================================================
  319. MessageManagerLock::MessageManagerLock (Thread* threadToCheck)
  320. : locked (attemptLock (threadToCheck, nullptr))
  321. {}
  322. MessageManagerLock::MessageManagerLock (ThreadPoolJob* jobToCheck)
  323. : locked (attemptLock (nullptr, jobToCheck))
  324. {}
  325. bool MessageManagerLock::attemptLock (Thread* threadToCheck, ThreadPoolJob* jobToCheck)
  326. {
  327. jassert (threadToCheck == nullptr || jobToCheck == nullptr);
  328. if (threadToCheck != nullptr)
  329. threadToCheck->addListener (this);
  330. if (jobToCheck != nullptr)
  331. jobToCheck->addListener (this);
  332. // tryEnter may have a spurious abort (return false) so keep checking the condition
  333. while ((threadToCheck == nullptr || ! threadToCheck->threadShouldExit())
  334. && (jobToCheck == nullptr || ! jobToCheck->shouldExit()))
  335. {
  336. if (mmLock.tryEnter())
  337. break;
  338. }
  339. if (threadToCheck != nullptr)
  340. {
  341. threadToCheck->removeListener (this);
  342. if (threadToCheck->threadShouldExit())
  343. return false;
  344. }
  345. if (jobToCheck != nullptr)
  346. {
  347. jobToCheck->removeListener (this);
  348. if (jobToCheck->shouldExit())
  349. return false;
  350. }
  351. return true;
  352. }
  353. MessageManagerLock::~MessageManagerLock() { mmLock.exit(); }
  354. void MessageManagerLock::exitSignalSent()
  355. {
  356. mmLock.abort();
  357. }
  358. //==============================================================================
  359. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  360. {
  361. JUCE_AUTORELEASEPOOL
  362. {
  363. MessageManager::getInstance();
  364. }
  365. }
  366. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  367. {
  368. JUCE_AUTORELEASEPOOL
  369. {
  370. DeletedAtShutdown::deleteAll();
  371. MessageManager::deleteInstance();
  372. }
  373. }
  374. static int numScopedInitInstances = 0;
  375. ScopedJuceInitialiser_GUI::ScopedJuceInitialiser_GUI() { if (numScopedInitInstances++ == 0) initialiseJuce_GUI(); }
  376. ScopedJuceInitialiser_GUI::~ScopedJuceInitialiser_GUI() { if (--numScopedInitInstances == 0) shutdownJuce_GUI(); }
  377. } // namespace juce