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.

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