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.

453 lines
13KB

  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.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 || ! 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.get();
  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. struct MessageManager::Lock::BlockingMessage : public MessageManager::MessageBase
  195. {
  196. BlockingMessage (const MessageManager::Lock* parent) noexcept
  197. // need a const_cast here as VS2013 doesn't like a const pointer to be in an atomic
  198. : owner (const_cast<MessageManager::Lock*> (parent)) {}
  199. void messageCallback() override
  200. {
  201. {
  202. ScopedLock lock (ownerCriticalSection);
  203. if (auto* o = owner.get())
  204. o->messageCallback();
  205. }
  206. releaseEvent.wait();
  207. }
  208. CriticalSection ownerCriticalSection;
  209. Atomic<MessageManager::Lock*> owner;
  210. WaitableEvent releaseEvent;
  211. JUCE_DECLARE_NON_COPYABLE (BlockingMessage)
  212. };
  213. //==============================================================================
  214. MessageManager::Lock::Lock() {}
  215. MessageManager::Lock::~Lock() { exit(); }
  216. void MessageManager::Lock::enter() const noexcept { tryAcquire (true); }
  217. bool MessageManager::Lock::tryEnter() const noexcept { return tryAcquire (false); }
  218. bool MessageManager::Lock::tryAcquire (bool lockIsMandatory) const noexcept
  219. {
  220. auto* mm = MessageManager::instance;
  221. if (mm == nullptr)
  222. {
  223. jassertfalse;
  224. return false;
  225. }
  226. if (! lockIsMandatory && (abortWait.get() != 0))
  227. {
  228. abortWait.set (0);
  229. return false;
  230. }
  231. if (mm->currentThreadHasLockedMessageManager())
  232. return true;
  233. try
  234. {
  235. blockingMessage = new BlockingMessage (this);
  236. }
  237. catch (...)
  238. {
  239. jassert (! lockIsMandatory);
  240. return false;
  241. }
  242. if (! blockingMessage->post())
  243. {
  244. // post of message failed while trying to get the lock
  245. jassert (! lockIsMandatory);
  246. blockingMessage = nullptr;
  247. return false;
  248. }
  249. do
  250. {
  251. while (abortWait.get() == 0)
  252. lockedEvent.wait (-1);
  253. abortWait.set (0);
  254. if (lockGained.get() != 0)
  255. {
  256. mm->threadWithLock = Thread::getCurrentThreadId();
  257. return true;
  258. }
  259. } while (lockIsMandatory);
  260. // we didn't get the lock
  261. blockingMessage->releaseEvent.signal();
  262. {
  263. ScopedLock lock (blockingMessage->ownerCriticalSection);
  264. lockGained.set (0);
  265. blockingMessage->owner.set (nullptr);
  266. }
  267. blockingMessage = nullptr;
  268. return false;
  269. }
  270. void MessageManager::Lock::exit() const noexcept
  271. {
  272. if (lockGained.compareAndSetBool (false, true))
  273. {
  274. auto* mm = MessageManager::instance;
  275. jassert (mm == nullptr || mm->currentThreadHasLockedMessageManager());
  276. lockGained.set (0);
  277. if (mm != nullptr)
  278. mm->threadWithLock = 0;
  279. if (blockingMessage != nullptr)
  280. {
  281. blockingMessage->releaseEvent.signal();
  282. blockingMessage = nullptr;
  283. }
  284. }
  285. }
  286. void MessageManager::Lock::messageCallback() const
  287. {
  288. lockGained.set (1);
  289. abort();
  290. }
  291. void MessageManager::Lock::abort() const noexcept
  292. {
  293. abortWait.set (1);
  294. lockedEvent.signal();
  295. }
  296. //==============================================================================
  297. MessageManagerLock::MessageManagerLock (Thread* threadToCheck)
  298. : locked (attemptLock (threadToCheck, nullptr))
  299. {}
  300. MessageManagerLock::MessageManagerLock (ThreadPoolJob* jobToCheck)
  301. : locked (attemptLock (nullptr, jobToCheck))
  302. {}
  303. bool MessageManagerLock::attemptLock (Thread* threadToCheck, ThreadPoolJob* jobToCheck)
  304. {
  305. jassert (threadToCheck == nullptr || jobToCheck == nullptr);
  306. if (threadToCheck != nullptr)
  307. threadToCheck->addListener (this);
  308. if (jobToCheck != nullptr)
  309. jobToCheck->addListener (this);
  310. // tryEnter may have a spurious abort (return false) so keep checking the condition
  311. while ((threadToCheck == nullptr || ! threadToCheck->threadShouldExit())
  312. && (jobToCheck == nullptr || ! jobToCheck->shouldExit()))
  313. {
  314. if (mmLock.tryEnter())
  315. break;
  316. }
  317. if (threadToCheck != nullptr)
  318. {
  319. threadToCheck->removeListener (this);
  320. if (threadToCheck->threadShouldExit())
  321. return false;
  322. }
  323. if (jobToCheck != nullptr)
  324. {
  325. jobToCheck->removeListener (this);
  326. if (jobToCheck->shouldExit())
  327. return false;
  328. }
  329. return true;
  330. }
  331. MessageManagerLock::~MessageManagerLock() noexcept { mmLock.exit(); }
  332. void MessageManagerLock::exitSignalSent()
  333. {
  334. mmLock.abort();
  335. }
  336. //==============================================================================
  337. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI();
  338. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  339. {
  340. JUCE_AUTORELEASEPOOL
  341. {
  342. MessageManager::getInstance();
  343. }
  344. }
  345. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI();
  346. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  347. {
  348. JUCE_AUTORELEASEPOOL
  349. {
  350. DeletedAtShutdown::deleteAll();
  351. MessageManager::deleteInstance();
  352. }
  353. }
  354. static int numScopedInitInstances = 0;
  355. ScopedJuceInitialiser_GUI::ScopedJuceInitialiser_GUI() { if (numScopedInitInstances++ == 0) initialiseJuce_GUI(); }
  356. ScopedJuceInitialiser_GUI::~ScopedJuceInitialiser_GUI() { if (--numScopedInitInstances == 0) shutdownJuce_GUI(); }
  357. } // namespace juce