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.

486 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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. JUCE_VERSION_ID
  23. if (JUCEApplicationBase::isStandaloneApp())
  24. Thread::setCurrentThreadName ("JUCE Message Thread");
  25. }
  26. MessageManager::~MessageManager() noexcept
  27. {
  28. broadcaster.reset();
  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. auto* mm = MessageManager::instance;
  55. if (mm == nullptr || mm->quitMessagePosted.get() != 0 || ! 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_MAC || JUCE_IOS || JUCE_ANDROID)
  64. // implemented in platform-specific code (juce_linux_Messaging.cpp and juce_win32_Messaging.cpp)
  65. bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  66. class MessageManager::QuitMessage : public MessageManager::MessageBase
  67. {
  68. public:
  69. QuitMessage() {}
  70. void messageCallback() override
  71. {
  72. if (auto* mm = MessageManager::instance)
  73. mm->quitMessageReceived = true;
  74. }
  75. JUCE_DECLARE_NON_COPYABLE (QuitMessage)
  76. };
  77. void MessageManager::runDispatchLoop()
  78. {
  79. jassert (isThisTheMessageThread()); // must only be called by the message thread
  80. while (quitMessageReceived.get() == 0)
  81. {
  82. JUCE_TRY
  83. {
  84. if (! dispatchNextMessageOnSystemQueue (false))
  85. Thread::sleep (1);
  86. }
  87. JUCE_CATCH_EXCEPTION
  88. }
  89. }
  90. void MessageManager::stopDispatchLoop()
  91. {
  92. (new QuitMessage())->post();
  93. quitMessagePosted = true;
  94. }
  95. #if JUCE_MODAL_LOOPS_PERMITTED
  96. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  97. {
  98. jassert (isThisTheMessageThread()); // must only be called by the message thread
  99. auto endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  100. while (quitMessageReceived.get() == 0)
  101. {
  102. JUCE_TRY
  103. {
  104. if (! dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  105. Thread::sleep (1);
  106. }
  107. JUCE_CATCH_EXCEPTION
  108. if (millisecondsToRunFor >= 0 && Time::currentTimeMillis() >= endTime)
  109. break;
  110. }
  111. return quitMessageReceived.get() == 0;
  112. }
  113. #endif
  114. #endif
  115. //==============================================================================
  116. class AsyncFunctionCallback : public MessageManager::MessageBase
  117. {
  118. public:
  119. AsyncFunctionCallback (MessageCallbackFunction* const f, void* const param)
  120. : func (f), parameter (param)
  121. {}
  122. void messageCallback() override
  123. {
  124. result = (*func) (parameter);
  125. finished.signal();
  126. }
  127. WaitableEvent finished;
  128. std::atomic<void*> result { nullptr };
  129. private:
  130. MessageCallbackFunction* const func;
  131. void* const parameter;
  132. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCallback)
  133. };
  134. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  135. {
  136. if (isThisTheMessageThread())
  137. return func (parameter);
  138. // If this thread has the message manager locked, then this will deadlock!
  139. jassert (! currentThreadHasLockedMessageManager());
  140. const ReferenceCountedObjectPtr<AsyncFunctionCallback> message (new AsyncFunctionCallback (func, parameter));
  141. if (message->post())
  142. {
  143. message->finished.wait();
  144. return message->result.load();
  145. }
  146. jassertfalse; // the OS message queue failed to send the message!
  147. return nullptr;
  148. }
  149. bool MessageManager::callAsync (std::function<void()> fn)
  150. {
  151. struct AsyncCallInvoker : public MessageBase
  152. {
  153. AsyncCallInvoker (std::function<void()> f) : callback (std::move (f)) {}
  154. void messageCallback() override { callback(); }
  155. std::function<void()> callback;
  156. };
  157. return (new AsyncCallInvoker (std::move (fn)))->post();
  158. }
  159. //==============================================================================
  160. void MessageManager::deliverBroadcastMessage (const String& value)
  161. {
  162. if (broadcaster != nullptr)
  163. broadcaster->sendActionMessage (value);
  164. }
  165. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  166. {
  167. if (broadcaster == nullptr)
  168. broadcaster.reset (new ActionBroadcaster());
  169. broadcaster->addActionListener (listener);
  170. }
  171. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  172. {
  173. if (broadcaster != nullptr)
  174. broadcaster->removeActionListener (listener);
  175. }
  176. //==============================================================================
  177. bool MessageManager::isThisTheMessageThread() const noexcept
  178. {
  179. return Thread::getCurrentThreadId() == messageThreadId;
  180. }
  181. void MessageManager::setCurrentThreadAsMessageThread()
  182. {
  183. auto thisThread = Thread::getCurrentThreadId();
  184. if (messageThreadId != thisThread)
  185. {
  186. messageThreadId = thisThread;
  187. #if JUCE_WINDOWS
  188. // This is needed on windows to make sure the message window is created by this thread
  189. doPlatformSpecificShutdown();
  190. doPlatformSpecificInitialisation();
  191. #endif
  192. }
  193. }
  194. bool MessageManager::currentThreadHasLockedMessageManager() const noexcept
  195. {
  196. auto thisThread = Thread::getCurrentThreadId();
  197. return thisThread == messageThreadId || thisThread == threadWithLock.get();
  198. }
  199. bool MessageManager::existsAndIsLockedByCurrentThread() noexcept
  200. {
  201. if (auto i = getInstanceWithoutCreating())
  202. return i->currentThreadHasLockedMessageManager();
  203. return false;
  204. }
  205. bool MessageManager::existsAndIsCurrentThread() noexcept
  206. {
  207. if (auto i = getInstanceWithoutCreating())
  208. return i->isThisTheMessageThread();
  209. return false;
  210. }
  211. //==============================================================================
  212. //==============================================================================
  213. /* The only safe way to lock the message thread while another thread does
  214. some work is by posting a special message, whose purpose is to tie up the event
  215. loop until the other thread has finished its business.
  216. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  217. get locked before making an event callback, because if the same OS lock gets indirectly
  218. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  219. in Cocoa).
  220. */
  221. struct MessageManager::Lock::BlockingMessage : public MessageManager::MessageBase
  222. {
  223. BlockingMessage (const MessageManager::Lock* parent) noexcept
  224. : owner (parent)
  225. {}
  226. void messageCallback() override
  227. {
  228. {
  229. ScopedLock lock (ownerCriticalSection);
  230. if (auto* o = owner.get())
  231. o->messageCallback();
  232. }
  233. releaseEvent.wait();
  234. }
  235. CriticalSection ownerCriticalSection;
  236. Atomic<const MessageManager::Lock*> owner;
  237. WaitableEvent releaseEvent;
  238. JUCE_DECLARE_NON_COPYABLE (BlockingMessage)
  239. };
  240. //==============================================================================
  241. MessageManager::Lock::Lock() {}
  242. MessageManager::Lock::~Lock() { exit(); }
  243. void MessageManager::Lock::enter() const noexcept { tryAcquire (true); }
  244. bool MessageManager::Lock::tryEnter() const noexcept { return tryAcquire (false); }
  245. bool MessageManager::Lock::tryAcquire (bool lockIsMandatory) const noexcept
  246. {
  247. auto* mm = MessageManager::instance;
  248. if (mm == nullptr)
  249. {
  250. jassertfalse;
  251. return false;
  252. }
  253. if (! lockIsMandatory && (abortWait.get() != 0))
  254. {
  255. abortWait.set (0);
  256. return false;
  257. }
  258. if (mm->currentThreadHasLockedMessageManager())
  259. return true;
  260. try
  261. {
  262. blockingMessage = *new BlockingMessage (this);
  263. }
  264. catch (...)
  265. {
  266. jassert (! lockIsMandatory);
  267. return false;
  268. }
  269. if (! blockingMessage->post())
  270. {
  271. // post of message failed while trying to get the lock
  272. jassert (! lockIsMandatory);
  273. blockingMessage = nullptr;
  274. return false;
  275. }
  276. do
  277. {
  278. while (abortWait.get() == 0)
  279. lockedEvent.wait (-1);
  280. abortWait.set (0);
  281. if (lockGained.get() != 0)
  282. {
  283. mm->threadWithLock = Thread::getCurrentThreadId();
  284. return true;
  285. }
  286. } while (lockIsMandatory);
  287. // we didn't get the lock
  288. blockingMessage->releaseEvent.signal();
  289. {
  290. ScopedLock lock (blockingMessage->ownerCriticalSection);
  291. lockGained.set (0);
  292. blockingMessage->owner.set (nullptr);
  293. }
  294. blockingMessage = nullptr;
  295. return false;
  296. }
  297. void MessageManager::Lock::exit() const noexcept
  298. {
  299. if (lockGained.compareAndSetBool (false, true))
  300. {
  301. auto* mm = MessageManager::instance;
  302. jassert (mm == nullptr || mm->currentThreadHasLockedMessageManager());
  303. lockGained.set (0);
  304. if (mm != nullptr)
  305. mm->threadWithLock = {};
  306. if (blockingMessage != nullptr)
  307. {
  308. blockingMessage->releaseEvent.signal();
  309. blockingMessage = nullptr;
  310. }
  311. }
  312. }
  313. void MessageManager::Lock::messageCallback() const
  314. {
  315. lockGained.set (1);
  316. abort();
  317. }
  318. void MessageManager::Lock::abort() const noexcept
  319. {
  320. abortWait.set (1);
  321. lockedEvent.signal();
  322. }
  323. //==============================================================================
  324. MessageManagerLock::MessageManagerLock (Thread* threadToCheck)
  325. : locked (attemptLock (threadToCheck, nullptr))
  326. {}
  327. MessageManagerLock::MessageManagerLock (ThreadPoolJob* jobToCheck)
  328. : locked (attemptLock (nullptr, jobToCheck))
  329. {}
  330. bool MessageManagerLock::attemptLock (Thread* threadToCheck, ThreadPoolJob* jobToCheck)
  331. {
  332. jassert (threadToCheck == nullptr || jobToCheck == nullptr);
  333. if (threadToCheck != nullptr)
  334. threadToCheck->addListener (this);
  335. if (jobToCheck != nullptr)
  336. jobToCheck->addListener (this);
  337. // tryEnter may have a spurious abort (return false) so keep checking the condition
  338. while ((threadToCheck == nullptr || ! threadToCheck->threadShouldExit())
  339. && (jobToCheck == nullptr || ! jobToCheck->shouldExit()))
  340. {
  341. if (mmLock.tryEnter())
  342. break;
  343. }
  344. if (threadToCheck != nullptr)
  345. {
  346. threadToCheck->removeListener (this);
  347. if (threadToCheck->threadShouldExit())
  348. return false;
  349. }
  350. if (jobToCheck != nullptr)
  351. {
  352. jobToCheck->removeListener (this);
  353. if (jobToCheck->shouldExit())
  354. return false;
  355. }
  356. return true;
  357. }
  358. MessageManagerLock::~MessageManagerLock() { mmLock.exit(); }
  359. void MessageManagerLock::exitSignalSent()
  360. {
  361. mmLock.abort();
  362. }
  363. //==============================================================================
  364. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  365. {
  366. JUCE_AUTORELEASEPOOL
  367. {
  368. MessageManager::getInstance();
  369. }
  370. }
  371. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  372. {
  373. JUCE_AUTORELEASEPOOL
  374. {
  375. DeletedAtShutdown::deleteAll();
  376. MessageManager::deleteInstance();
  377. }
  378. }
  379. static int numScopedInitInstances = 0;
  380. ScopedJuceInitialiser_GUI::ScopedJuceInitialiser_GUI() { if (numScopedInitInstances++ == 0) initialiseJuce_GUI(); }
  381. ScopedJuceInitialiser_GUI::~ScopedJuceInitialiser_GUI() { if (--numScopedInitInstances == 0) shutdownJuce_GUI(); }
  382. } // namespace juce