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.

485 lines
19KB

  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. class MessageManagerLock;
  20. class ThreadPoolJob;
  21. class ActionListener;
  22. class ActionBroadcaster;
  23. //==============================================================================
  24. /** See MessageManager::callFunctionOnMessageThread() for use of this function type. */
  25. using MessageCallbackFunction = void* (void* userData);
  26. //==============================================================================
  27. /**
  28. This class is in charge of the application's event-dispatch loop.
  29. @see Message, CallbackMessage, MessageManagerLock, JUCEApplication, JUCEApplicationBase
  30. @tags{Events}
  31. */
  32. class JUCE_API MessageManager final
  33. {
  34. public:
  35. //==============================================================================
  36. /** Returns the global instance of the MessageManager. */
  37. static MessageManager* getInstance();
  38. /** Returns the global instance of the MessageManager, or nullptr if it doesn't exist. */
  39. static MessageManager* getInstanceWithoutCreating() noexcept;
  40. /** Deletes the global MessageManager instance.
  41. Does nothing if no instance had been created.
  42. */
  43. static void deleteInstance();
  44. //==============================================================================
  45. /** Runs the event dispatch loop until a stop message is posted.
  46. This method is only intended to be run by the application's startup routine,
  47. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  48. @see stopDispatchLoop
  49. */
  50. void runDispatchLoop();
  51. /** Sends a signal that the dispatch loop should terminate.
  52. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  53. will be interrupted and will return.
  54. @see runDispatchLoop
  55. */
  56. void stopDispatchLoop();
  57. /** Returns true if the stopDispatchLoop() method has been called.
  58. */
  59. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted.get() != 0; }
  60. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  61. /** Synchronously dispatches messages until a given time has elapsed.
  62. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  63. otherwise returns true.
  64. */
  65. bool runDispatchLoopUntil (int millisecondsToRunFor);
  66. #endif
  67. //==============================================================================
  68. /** Asynchronously invokes a function or C++11 lambda on the message thread.
  69. @returns true if the message was successfully posted to the message queue,
  70. or false otherwise.
  71. */
  72. static bool callAsync (std::function<void()> functionToCall);
  73. /** Calls a function using the message-thread.
  74. This can be used by any thread to cause this function to be called-back
  75. by the message thread. If it's the message-thread that's calling this method,
  76. then the function will just be called; if another thread is calling, a message
  77. will be posted to the queue, and this method will block until that message
  78. is delivered, the function is called, and the result is returned.
  79. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  80. thread has a critical section locked, which an unrelated message callback then tries to lock
  81. before the message thread gets round to processing this callback.
  82. @param callback the function to call - its signature must be @code
  83. void* myCallbackFunction (void*) @endcode
  84. @param userData a user-defined pointer that will be passed to the function that gets called
  85. @returns the value that the callback function returns.
  86. @see MessageManagerLock
  87. */
  88. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  89. /** Returns true if the caller-thread is the message thread. */
  90. bool isThisTheMessageThread() const noexcept;
  91. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  92. (Best to ignore this method unless you really know what you're doing..)
  93. @see getCurrentMessageThread
  94. */
  95. void setCurrentThreadAsMessageThread();
  96. /** Returns the ID of the current message thread, as set by setCurrentThreadAsMessageThread().
  97. (Best to ignore this method unless you really know what you're doing..)
  98. @see setCurrentThreadAsMessageThread
  99. */
  100. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  101. /** Returns true if the caller thread has currently got the message manager locked.
  102. see the MessageManagerLock class for more info about this.
  103. This will be true if the caller is the message thread, because that automatically
  104. gains a lock while a message is being dispatched.
  105. */
  106. bool currentThreadHasLockedMessageManager() const noexcept;
  107. /** Returns true if there's an instance of the MessageManager, and if the current thread
  108. has the lock on it.
  109. */
  110. static bool existsAndIsLockedByCurrentThread() noexcept;
  111. /** Returns true if there's an instance of the MessageManager, and if the current thread
  112. is running it.
  113. */
  114. static bool existsAndIsCurrentThread() noexcept;
  115. //==============================================================================
  116. /** Sends a message to all other JUCE applications that are running.
  117. @param messageText the string that will be passed to the actionListenerCallback()
  118. method of the broadcast listeners in the other app.
  119. @see registerBroadcastListener, ActionListener
  120. */
  121. static void broadcastMessage (const String& messageText);
  122. /** Registers a listener to get told about broadcast messages.
  123. The actionListenerCallback() callback's string parameter
  124. is the message passed into broadcastMessage().
  125. @see broadcastMessage
  126. */
  127. void registerBroadcastListener (ActionListener* listener);
  128. /** Deregisters a broadcast listener. */
  129. void deregisterBroadcastListener (ActionListener* listener);
  130. //==============================================================================
  131. /** Internal class used as the base class for all message objects.
  132. You shouldn't need to use this directly - see the CallbackMessage or Message
  133. classes instead.
  134. */
  135. class JUCE_API MessageBase : public ReferenceCountedObject
  136. {
  137. public:
  138. MessageBase() = default;
  139. ~MessageBase() override = default;
  140. virtual void messageCallback() = 0;
  141. bool post();
  142. using Ptr = ReferenceCountedObjectPtr<MessageBase>;
  143. JUCE_DECLARE_NON_COPYABLE (MessageBase)
  144. };
  145. //==============================================================================
  146. /** A lock you can use to lock the message manager. You can use this class with
  147. the RAII-based ScopedLock classes.
  148. */
  149. class JUCE_API Lock
  150. {
  151. public:
  152. /**
  153. Creates a new critical section to exclusively access methods which can
  154. only be called when the message manager is locked.
  155. Unlike CrititcalSection, multiple instances of this lock class provide
  156. exclusive access to a single resource - the MessageManager.
  157. */
  158. Lock();
  159. /** Destructor. */
  160. ~Lock();
  161. /** Acquires the message manager lock.
  162. If the caller thread already has exclusive access to the MessageManager, this method
  163. will return immediately.
  164. If another thread is currently using the MessageManager, this will wait until that
  165. thread releases the lock to the MessageManager.
  166. This call will only exit if the lock was acquired by this thread. Calling abort while
  167. a thread is waiting for enter to finish, will have no effect.
  168. @see exit, abort
  169. */
  170. void enter() const noexcept;
  171. /** Attempts to lock the message manager and exits if abort is called.
  172. This method behaves identically to enter, except that it will abort waiting for
  173. the lock if the abort method is called.
  174. Unlike other JUCE critical sections, this method **will** block waiting for the lock.
  175. To ensure predictable behaviour, you should re-check your abort condition if tryEnter
  176. returns false.
  177. This method can be used if you want to do some work while waiting for the
  178. MessageManagerLock:
  179. void doWorkWhileWaitingForMessageManagerLock()
  180. {
  181. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock);
  182. while (! mmLock.isLocked())
  183. {
  184. while (workQueue.size() > 0)
  185. {
  186. auto work = workQueue.pop();
  187. doSomeWork (work);
  188. }
  189. // this will block until we either have the lock or there is work
  190. mmLock.retryLock();
  191. }
  192. // we have the mmlock
  193. // do some message manager stuff like resizing and painting components
  194. }
  195. // called from another thread
  196. void addWorkToDo (Work work)
  197. {
  198. queue.push (work);
  199. messageManagerLock.abort();
  200. }
  201. @returns false if waiting for a lock was aborted, true if the lock was acquired.
  202. @see enter, abort, ScopedTryLock
  203. */
  204. bool tryEnter() const noexcept;
  205. /** Releases the message manager lock.
  206. @see enter, ScopedLock
  207. */
  208. void exit() const noexcept;
  209. /** Unblocks a thread which is waiting in tryEnter
  210. Call this method if you want to unblock a thread which is waiting for the
  211. MessageManager lock in tryEnter.
  212. This method does not have any effect on a thread waiting for a lock in enter.
  213. @see tryEnter
  214. */
  215. void abort() const noexcept;
  216. //==============================================================================
  217. /** Provides the type of scoped lock to use with a CriticalSection. */
  218. using ScopedLockType = GenericScopedLock<Lock>;
  219. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  220. using ScopedUnlockType = GenericScopedUnlock<Lock>;
  221. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  222. using ScopedTryLockType = GenericScopedTryLock<Lock>;
  223. private:
  224. struct BlockingMessage;
  225. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  226. bool tryAcquire (bool) const noexcept;
  227. void messageCallback() const;
  228. //==============================================================================
  229. mutable ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  230. WaitableEvent lockedEvent;
  231. mutable Atomic<int> abortWait, lockGained;
  232. };
  233. //==============================================================================
  234. #ifndef DOXYGEN
  235. // Internal methods - do not use!
  236. void deliverBroadcastMessage (const String&);
  237. ~MessageManager() noexcept;
  238. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  239. #endif
  240. private:
  241. //==============================================================================
  242. MessageManager() noexcept;
  243. static MessageManager* instance;
  244. friend class MessageBase;
  245. class QuitMessage;
  246. friend class QuitMessage;
  247. friend class MessageManagerLock;
  248. std::unique_ptr<ActionBroadcaster> broadcaster;
  249. Atomic<int> quitMessagePosted { 0 }, quitMessageReceived { 0 };
  250. Thread::ThreadID messageThreadId;
  251. Atomic<Thread::ThreadID> threadWithLock;
  252. static bool postMessageToSystemQueue (MessageBase*);
  253. static void* exitModalLoopCallback (void*);
  254. static void doPlatformSpecificInitialisation();
  255. static void doPlatformSpecificShutdown();
  256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager)
  257. };
  258. //==============================================================================
  259. /** Used to make sure that the calling thread has exclusive access to the message loop.
  260. Because it's not thread-safe to call any of the Component or other UI classes
  261. from threads other than the message thread, one of these objects can be used to
  262. lock the message loop and allow this to be done. The message thread will be
  263. suspended for the lifetime of the MessageManagerLock object, so create one on
  264. the stack like this: @code
  265. void MyThread::run()
  266. {
  267. someData = 1234;
  268. const MessageManagerLock mmLock;
  269. // the event loop will now be locked so it's safe to make a few calls..
  270. myComponent->setBounds (newBounds);
  271. myComponent->repaint();
  272. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  273. }
  274. @endcode
  275. Obviously be careful not to create one of these and leave it lying around, or
  276. your app will grind to a halt!
  277. MessageManagerLocks are re-entrant, so can be safely nested if the current thread
  278. already has the lock.
  279. Another caveat is that using this in conjunction with other CriticalSections
  280. can create lots of interesting ways of producing a deadlock! In particular, if
  281. your message thread calls stopThread() for a thread that uses these locks,
  282. you'll get an (occasional) deadlock..
  283. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  284. @tags{Events}
  285. */
  286. class JUCE_API MessageManagerLock : private Thread::Listener
  287. {
  288. public:
  289. //==============================================================================
  290. /** Tries to acquire a lock on the message manager.
  291. The constructor attempts to gain a lock on the message loop, and the lock will be
  292. kept for the lifetime of this object.
  293. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  294. this method will keep checking whether the thread has been given the
  295. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  296. without gaining the lock. If you pass a thread, you must check whether the lock was
  297. successful by calling lockWasGained(). If this is false, your thread is being told to
  298. die, so you should take evasive action.
  299. If you pass nullptr for the thread object, it will wait indefinitely for the lock - be
  300. careful when doing this, because it's very easy to deadlock if your message thread
  301. attempts to call stopThread() on a thread just as that thread attempts to get the
  302. message lock.
  303. If the calling thread already has the lock, nothing will be done, so it's safe and
  304. quick to use these locks recursively.
  305. E.g.
  306. @code
  307. void run()
  308. {
  309. ...
  310. while (! threadShouldExit())
  311. {
  312. MessageManagerLock mml (Thread::getCurrentThread());
  313. if (! mml.lockWasGained())
  314. return; // another thread is trying to kill us!
  315. ..do some locked stuff here..
  316. }
  317. ..and now the MM is now unlocked..
  318. }
  319. @endcode
  320. */
  321. MessageManagerLock (Thread* threadToCheckForExitSignal = nullptr);
  322. //==============================================================================
  323. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  324. instead of a thread.
  325. See the MessageManagerLock (Thread*) constructor for details on how this works.
  326. */
  327. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  328. //==============================================================================
  329. /** Releases the current thread's lock on the message manager.
  330. Make sure this object is created and deleted by the same thread,
  331. otherwise there are no guarantees what will happen!
  332. */
  333. ~MessageManagerLock() override;
  334. //==============================================================================
  335. /** Returns true if the lock was successfully acquired.
  336. (See the constructor that takes a Thread for more info).
  337. */
  338. bool lockWasGained() const noexcept { return locked; }
  339. private:
  340. //==============================================================================
  341. MessageManager::Lock mmLock;
  342. bool locked;
  343. //==============================================================================
  344. bool attemptLock (Thread*, ThreadPoolJob*);
  345. void exitSignalSent() override;
  346. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock)
  347. };
  348. //==============================================================================
  349. /** This macro is used to catch unsafe use of functions which expect to only be called
  350. on the message thread, or when a MessageManagerLock is in place.
  351. It will also fail if you try to use the function before the message manager has been
  352. created, which could happen if you accidentally invoke it during a static constructor.
  353. */
  354. #define JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED \
  355. jassert (juce::MessageManager::existsAndIsLockedByCurrentThread());
  356. /** This macro is used to catch unsafe use of functions which expect to only be called
  357. on the message thread.
  358. It will also fail if you try to use the function before the message manager has been
  359. created, which could happen if you accidentally invoke it during a static constructor.
  360. */
  361. #define JUCE_ASSERT_MESSAGE_THREAD \
  362. jassert (juce::MessageManager::existsAndIsCurrentThread());
  363. /** This macro is used to catch unsafe use of functions which expect to not be called
  364. outside the lifetime of the MessageManager.
  365. */
  366. #define JUCE_ASSERT_MESSAGE_MANAGER_EXISTS \
  367. jassert (juce::MessageManager::getInstanceWithoutCreating() != nullptr);
  368. } // namespace juce