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.

338 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #ifndef JUCE_MESSAGEMANAGER_H_INCLUDED
  18. #define JUCE_MESSAGEMANAGER_H_INCLUDED
  19. class MessageManagerLock;
  20. class ThreadPoolJob;
  21. class ActionListener;
  22. class ActionBroadcaster;
  23. //==============================================================================
  24. /** See MessageManager::callFunctionOnMessageThread() for use of this function type. */
  25. typedef void* (MessageCallbackFunction) (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. */
  31. class JUCE_API MessageManager
  32. {
  33. public:
  34. //==============================================================================
  35. /** Returns the global instance of the MessageManager. */
  36. static MessageManager* getInstance();
  37. /** Returns the global instance of the MessageManager, or nullptr if it doesn't exist. */
  38. static MessageManager* getInstanceWithoutCreating() noexcept;
  39. /** Deletes the global MessageManager instance.
  40. Does nothing if no instance had been created.
  41. */
  42. static void deleteInstance();
  43. //==============================================================================
  44. /** Runs the event dispatch loop until a stop message is posted.
  45. This method is only intended to be run by the application's startup routine,
  46. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  47. @see stopDispatchLoop
  48. */
  49. void runDispatchLoop();
  50. /** Sends a signal that the dispatch loop should terminate.
  51. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  52. will be interrupted and will return.
  53. @see runDispatchLoop
  54. */
  55. void stopDispatchLoop();
  56. /** Returns true if the stopDispatchLoop() method has been called.
  57. */
  58. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  59. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  60. /** Synchronously dispatches messages until a given time has elapsed.
  61. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  62. otherwise returns true.
  63. */
  64. bool runDispatchLoopUntil (int millisecondsToRunFor);
  65. #endif
  66. //==============================================================================
  67. #if JUCE_COMPILER_SUPPORTS_LAMBDAS
  68. /** Asynchronously invokes a function or C++11 lambda on the message thread.
  69. Internally this uses the CallbackMessage class to invoke the callback.
  70. */
  71. static void callAsync (std::function<void(void)>);
  72. #endif
  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. //==============================================================================
  108. /** Sends a message to all other JUCE applications that are running.
  109. @param messageText the string that will be passed to the actionListenerCallback()
  110. method of the broadcast listeners in the other app.
  111. @see registerBroadcastListener, ActionListener
  112. */
  113. static void broadcastMessage (const String& messageText);
  114. /** Registers a listener to get told about broadcast messages.
  115. The actionListenerCallback() callback's string parameter
  116. is the message passed into broadcastMessage().
  117. @see broadcastMessage
  118. */
  119. void registerBroadcastListener (ActionListener* listener);
  120. /** Deregisters a broadcast listener. */
  121. void deregisterBroadcastListener (ActionListener* listener);
  122. //==============================================================================
  123. /** Internal class used as the base class for all message objects.
  124. You shouldn't need to use this directly - see the CallbackMessage or Message
  125. classes instead.
  126. */
  127. class JUCE_API MessageBase : public ReferenceCountedObject
  128. {
  129. public:
  130. MessageBase() noexcept {}
  131. virtual ~MessageBase() {}
  132. virtual void messageCallback() = 0;
  133. bool post();
  134. typedef ReferenceCountedObjectPtr<MessageBase> Ptr;
  135. JUCE_DECLARE_NON_COPYABLE (MessageBase)
  136. };
  137. //==============================================================================
  138. #ifndef DOXYGEN
  139. // Internal methods - do not use!
  140. void deliverBroadcastMessage (const String&);
  141. ~MessageManager() noexcept;
  142. #endif
  143. private:
  144. //==============================================================================
  145. MessageManager() noexcept;
  146. static MessageManager* instance;
  147. friend class MessageBase;
  148. class QuitMessage;
  149. friend class QuitMessage;
  150. friend class MessageManagerLock;
  151. ScopedPointer<ActionBroadcaster> broadcaster;
  152. bool quitMessagePosted, quitMessageReceived;
  153. Thread::ThreadID messageThreadId;
  154. Thread::ThreadID volatile threadWithLock;
  155. CriticalSection lockingLock;
  156. static bool postMessageToSystemQueue (MessageBase*);
  157. static void* exitModalLoopCallback (void*);
  158. static void doPlatformSpecificInitialisation();
  159. static void doPlatformSpecificShutdown();
  160. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  161. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager)
  162. };
  163. //==============================================================================
  164. /** Used to make sure that the calling thread has exclusive access to the message loop.
  165. Because it's not thread-safe to call any of the Component or other UI classes
  166. from threads other than the message thread, one of these objects can be used to
  167. lock the message loop and allow this to be done. The message thread will be
  168. suspended for the lifetime of the MessageManagerLock object, so create one on
  169. the stack like this: @code
  170. void MyThread::run()
  171. {
  172. someData = 1234;
  173. const MessageManagerLock mmLock;
  174. // the event loop will now be locked so it's safe to make a few calls..
  175. myComponent->setBounds (newBounds);
  176. myComponent->repaint();
  177. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  178. }
  179. @endcode
  180. Obviously be careful not to create one of these and leave it lying around, or
  181. your app will grind to a halt!
  182. MessageManagerLocks are re-entrant, so can be safely nested if the current thread
  183. already has the lock.
  184. Another caveat is that using this in conjunction with other CriticalSections
  185. can create lots of interesting ways of producing a deadlock! In particular, if
  186. your message thread calls stopThread() for a thread that uses these locks,
  187. you'll get an (occasional) deadlock..
  188. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  189. */
  190. class JUCE_API MessageManagerLock
  191. {
  192. public:
  193. //==============================================================================
  194. /** Tries to acquire a lock on the message manager.
  195. The constructor attempts to gain a lock on the message loop, and the lock will be
  196. kept for the lifetime of this object.
  197. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  198. this method will keep checking whether the thread has been given the
  199. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  200. without gaining the lock. If you pass a thread, you must check whether the lock was
  201. successful by calling lockWasGained(). If this is false, your thread is being told to
  202. die, so you should take evasive action.
  203. If you pass nullptr for the thread object, it will wait indefinitely for the lock - be
  204. careful when doing this, because it's very easy to deadlock if your message thread
  205. attempts to call stopThread() on a thread just as that thread attempts to get the
  206. message lock.
  207. If the calling thread already has the lock, nothing will be done, so it's safe and
  208. quick to use these locks recursively.
  209. E.g.
  210. @code
  211. void run()
  212. {
  213. ...
  214. while (! threadShouldExit())
  215. {
  216. MessageManagerLock mml (Thread::getCurrentThread());
  217. if (! mml.lockWasGained())
  218. return; // another thread is trying to kill us!
  219. ..do some locked stuff here..
  220. }
  221. ..and now the MM is now unlocked..
  222. }
  223. @endcode
  224. */
  225. MessageManagerLock (Thread* threadToCheckForExitSignal = nullptr);
  226. //==============================================================================
  227. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  228. instead of a thread.
  229. See the MessageManagerLock (Thread*) constructor for details on how this works.
  230. */
  231. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  232. //==============================================================================
  233. /** Releases the current thread's lock on the message manager.
  234. Make sure this object is created and deleted by the same thread,
  235. otherwise there are no guarantees what will happen!
  236. */
  237. ~MessageManagerLock() noexcept;
  238. //==============================================================================
  239. /** Returns true if the lock was successfully acquired.
  240. (See the constructor that takes a Thread for more info).
  241. */
  242. bool lockWasGained() const noexcept { return locked; }
  243. private:
  244. class BlockingMessage;
  245. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  246. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  247. bool locked;
  248. bool attemptLock (Thread*, ThreadPoolJob*);
  249. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock)
  250. };
  251. #endif // JUCE_MESSAGEMANAGER_H_INCLUDED