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.

488 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. const std::lock_guard<std::mutex> lock { messageThreadIdMutex };
  180. return Thread::getCurrentThreadId() == messageThreadId;
  181. }
  182. void MessageManager::setCurrentThreadAsMessageThread()
  183. {
  184. auto thisThread = Thread::getCurrentThreadId();
  185. const std::lock_guard<std::mutex> lock { messageThreadIdMutex };
  186. if (std::exchange (messageThreadId, thisThread) != thisThread)
  187. {
  188. #if JUCE_WINDOWS
  189. // This is needed on windows to make sure the message window is created by this thread
  190. doPlatformSpecificShutdown();
  191. doPlatformSpecificInitialisation();
  192. #endif
  193. }
  194. }
  195. bool MessageManager::currentThreadHasLockedMessageManager() const noexcept
  196. {
  197. auto thisThread = Thread::getCurrentThreadId();
  198. return thisThread == messageThreadId || thisThread == threadWithLock.get();
  199. }
  200. bool MessageManager::existsAndIsLockedByCurrentThread() noexcept
  201. {
  202. if (auto i = getInstanceWithoutCreating())
  203. return i->currentThreadHasLockedMessageManager();
  204. return false;
  205. }
  206. bool MessageManager::existsAndIsCurrentThread() noexcept
  207. {
  208. if (auto i = getInstanceWithoutCreating())
  209. return i->isThisTheMessageThread();
  210. return false;
  211. }
  212. //==============================================================================
  213. //==============================================================================
  214. /* The only safe way to lock the message thread while another thread does
  215. some work is by posting a special message, whose purpose is to tie up the event
  216. loop until the other thread has finished its business.
  217. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  218. get locked before making an event callback, because if the same OS lock gets indirectly
  219. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  220. in Cocoa).
  221. */
  222. struct MessageManager::Lock::BlockingMessage : public MessageManager::MessageBase
  223. {
  224. BlockingMessage (const MessageManager::Lock* parent) noexcept
  225. : owner (parent)
  226. {}
  227. void messageCallback() override
  228. {
  229. {
  230. ScopedLock lock (ownerCriticalSection);
  231. if (auto* o = owner.get())
  232. o->messageCallback();
  233. }
  234. releaseEvent.wait();
  235. }
  236. CriticalSection ownerCriticalSection;
  237. Atomic<const MessageManager::Lock*> owner;
  238. WaitableEvent releaseEvent;
  239. JUCE_DECLARE_NON_COPYABLE (BlockingMessage)
  240. };
  241. //==============================================================================
  242. MessageManager::Lock::Lock() {}
  243. MessageManager::Lock::~Lock() { exit(); }
  244. void MessageManager::Lock::enter() const noexcept { tryAcquire (true); }
  245. bool MessageManager::Lock::tryEnter() const noexcept { return tryAcquire (false); }
  246. bool MessageManager::Lock::tryAcquire (bool lockIsMandatory) const noexcept
  247. {
  248. auto* mm = MessageManager::instance;
  249. if (mm == nullptr)
  250. {
  251. jassertfalse;
  252. return false;
  253. }
  254. if (! lockIsMandatory && (abortWait.get() != 0))
  255. {
  256. abortWait.set (0);
  257. return false;
  258. }
  259. if (mm->currentThreadHasLockedMessageManager())
  260. return true;
  261. try
  262. {
  263. blockingMessage = *new BlockingMessage (this);
  264. }
  265. catch (...)
  266. {
  267. jassert (! lockIsMandatory);
  268. return false;
  269. }
  270. if (! blockingMessage->post())
  271. {
  272. // post of message failed while trying to get the lock
  273. jassert (! lockIsMandatory);
  274. blockingMessage = nullptr;
  275. return false;
  276. }
  277. do
  278. {
  279. while (abortWait.get() == 0)
  280. lockedEvent.wait (-1);
  281. abortWait.set (0);
  282. if (lockGained.get() != 0)
  283. {
  284. mm->threadWithLock = Thread::getCurrentThreadId();
  285. return true;
  286. }
  287. } while (lockIsMandatory);
  288. // we didn't get the lock
  289. blockingMessage->releaseEvent.signal();
  290. {
  291. ScopedLock lock (blockingMessage->ownerCriticalSection);
  292. lockGained.set (0);
  293. blockingMessage->owner.set (nullptr);
  294. }
  295. blockingMessage = nullptr;
  296. return false;
  297. }
  298. void MessageManager::Lock::exit() const noexcept
  299. {
  300. if (lockGained.compareAndSetBool (false, true))
  301. {
  302. auto* mm = MessageManager::instance;
  303. jassert (mm == nullptr || mm->currentThreadHasLockedMessageManager());
  304. lockGained.set (0);
  305. if (mm != nullptr)
  306. mm->threadWithLock = {};
  307. if (blockingMessage != nullptr)
  308. {
  309. blockingMessage->releaseEvent.signal();
  310. blockingMessage = nullptr;
  311. }
  312. }
  313. }
  314. void MessageManager::Lock::messageCallback() const
  315. {
  316. lockGained.set (1);
  317. abort();
  318. }
  319. void MessageManager::Lock::abort() const noexcept
  320. {
  321. abortWait.set (1);
  322. lockedEvent.signal();
  323. }
  324. //==============================================================================
  325. MessageManagerLock::MessageManagerLock (Thread* threadToCheck)
  326. : locked (attemptLock (threadToCheck, nullptr))
  327. {}
  328. MessageManagerLock::MessageManagerLock (ThreadPoolJob* jobToCheck)
  329. : locked (attemptLock (nullptr, jobToCheck))
  330. {}
  331. bool MessageManagerLock::attemptLock (Thread* threadToCheck, ThreadPoolJob* jobToCheck)
  332. {
  333. jassert (threadToCheck == nullptr || jobToCheck == nullptr);
  334. if (threadToCheck != nullptr)
  335. threadToCheck->addListener (this);
  336. if (jobToCheck != nullptr)
  337. jobToCheck->addListener (this);
  338. // tryEnter may have a spurious abort (return false) so keep checking the condition
  339. while ((threadToCheck == nullptr || ! threadToCheck->threadShouldExit())
  340. && (jobToCheck == nullptr || ! jobToCheck->shouldExit()))
  341. {
  342. if (mmLock.tryEnter())
  343. break;
  344. }
  345. if (threadToCheck != nullptr)
  346. {
  347. threadToCheck->removeListener (this);
  348. if (threadToCheck->threadShouldExit())
  349. return false;
  350. }
  351. if (jobToCheck != nullptr)
  352. {
  353. jobToCheck->removeListener (this);
  354. if (jobToCheck->shouldExit())
  355. return false;
  356. }
  357. return true;
  358. }
  359. MessageManagerLock::~MessageManagerLock() { mmLock.exit(); }
  360. void MessageManagerLock::exitSignalSent()
  361. {
  362. mmLock.abort();
  363. }
  364. //==============================================================================
  365. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  366. {
  367. JUCE_AUTORELEASEPOOL
  368. {
  369. MessageManager::getInstance();
  370. }
  371. }
  372. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  373. {
  374. JUCE_AUTORELEASEPOOL
  375. {
  376. DeletedAtShutdown::deleteAll();
  377. MessageManager::deleteInstance();
  378. }
  379. }
  380. static int numScopedInitInstances = 0;
  381. ScopedJuceInitialiser_GUI::ScopedJuceInitialiser_GUI() { if (numScopedInitInstances++ == 0) initialiseJuce_GUI(); }
  382. ScopedJuceInitialiser_GUI::~ScopedJuceInitialiser_GUI() { if (--numScopedInitInstances == 0) shutdownJuce_GUI(); }
  383. } // namespace juce