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.

344 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. #ifndef JUCE_MESSAGEMANAGER_H_INCLUDED
  24. #define JUCE_MESSAGEMANAGER_H_INCLUDED
  25. class MessageManagerLock;
  26. class ThreadPoolJob;
  27. class ActionListener;
  28. class ActionBroadcaster;
  29. //==============================================================================
  30. /** See MessageManager::callFunctionOnMessageThread() for use of this function type. */
  31. typedef void* (MessageCallbackFunction) (void* userData);
  32. //==============================================================================
  33. /**
  34. This class is in charge of the application's event-dispatch loop.
  35. @see Message, CallbackMessage, MessageManagerLock, JUCEApplication, JUCEApplicationBase
  36. */
  37. class JUCE_API MessageManager
  38. {
  39. public:
  40. //==============================================================================
  41. /** Returns the global instance of the MessageManager. */
  42. static MessageManager* getInstance();
  43. /** Returns the global instance of the MessageManager, or nullptr if it doesn't exist. */
  44. static MessageManager* getInstanceWithoutCreating() noexcept;
  45. /** Deletes the global MessageManager instance.
  46. Does nothing if no instance had been created.
  47. */
  48. static void deleteInstance();
  49. //==============================================================================
  50. /** Runs the event dispatch loop until a stop message is posted.
  51. This method is only intended to be run by the application's startup routine,
  52. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  53. @see stopDispatchLoop
  54. */
  55. void runDispatchLoop();
  56. /** Sends a signal that the dispatch loop should terminate.
  57. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  58. will be interrupted and will return.
  59. @see runDispatchLoop
  60. */
  61. void stopDispatchLoop();
  62. /** Returns true if the stopDispatchLoop() method has been called.
  63. */
  64. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  65. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  66. /** Synchronously dispatches messages until a given time has elapsed.
  67. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  68. otherwise returns true.
  69. */
  70. bool runDispatchLoopUntil (int millisecondsToRunFor);
  71. #endif
  72. //==============================================================================
  73. #if JUCE_COMPILER_SUPPORTS_LAMBDAS
  74. /** Asynchronously invokes a function or C++11 lambda on the message thread.
  75. Internally this uses the CallbackMessage class to invoke the callback.
  76. */
  77. static void callAsync (std::function<void(void)>);
  78. #endif
  79. /** Calls a function using the message-thread.
  80. This can be used by any thread to cause this function to be called-back
  81. by the message thread. If it's the message-thread that's calling this method,
  82. then the function will just be called; if another thread is calling, a message
  83. will be posted to the queue, and this method will block until that message
  84. is delivered, the function is called, and the result is returned.
  85. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  86. thread has a critical section locked, which an unrelated message callback then tries to lock
  87. before the message thread gets round to processing this callback.
  88. @param callback the function to call - its signature must be @code
  89. void* myCallbackFunction (void*) @endcode
  90. @param userData a user-defined pointer that will be passed to the function that gets called
  91. @returns the value that the callback function returns.
  92. @see MessageManagerLock
  93. */
  94. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  95. /** Returns true if the caller-thread is the message thread. */
  96. bool isThisTheMessageThread() const noexcept;
  97. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  98. (Best to ignore this method unless you really know what you're doing..)
  99. @see getCurrentMessageThread
  100. */
  101. void setCurrentThreadAsMessageThread();
  102. /** Returns the ID of the current message thread, as set by setCurrentThreadAsMessageThread().
  103. (Best to ignore this method unless you really know what you're doing..)
  104. @see setCurrentThreadAsMessageThread
  105. */
  106. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  107. /** Returns true if the caller thread has currently got the message manager locked.
  108. see the MessageManagerLock class for more info about this.
  109. This will be true if the caller is the message thread, because that automatically
  110. gains a lock while a message is being dispatched.
  111. */
  112. bool currentThreadHasLockedMessageManager() const noexcept;
  113. //==============================================================================
  114. /** Sends a message to all other JUCE applications that are running.
  115. @param messageText the string that will be passed to the actionListenerCallback()
  116. method of the broadcast listeners in the other app.
  117. @see registerBroadcastListener, ActionListener
  118. */
  119. static void broadcastMessage (const String& messageText);
  120. /** Registers a listener to get told about broadcast messages.
  121. The actionListenerCallback() callback's string parameter
  122. is the message passed into broadcastMessage().
  123. @see broadcastMessage
  124. */
  125. void registerBroadcastListener (ActionListener* listener);
  126. /** Deregisters a broadcast listener. */
  127. void deregisterBroadcastListener (ActionListener* listener);
  128. //==============================================================================
  129. /** Internal class used as the base class for all message objects.
  130. You shouldn't need to use this directly - see the CallbackMessage or Message
  131. classes instead.
  132. */
  133. class JUCE_API MessageBase : public ReferenceCountedObject
  134. {
  135. public:
  136. MessageBase() noexcept {}
  137. virtual ~MessageBase() {}
  138. virtual void messageCallback() = 0;
  139. bool post();
  140. typedef ReferenceCountedObjectPtr<MessageBase> Ptr;
  141. JUCE_DECLARE_NON_COPYABLE (MessageBase)
  142. };
  143. //==============================================================================
  144. #ifndef DOXYGEN
  145. // Internal methods - do not use!
  146. void deliverBroadcastMessage (const String&);
  147. ~MessageManager() noexcept;
  148. #endif
  149. private:
  150. //==============================================================================
  151. MessageManager() noexcept;
  152. static MessageManager* instance;
  153. friend class MessageBase;
  154. class QuitMessage;
  155. friend class QuitMessage;
  156. friend class MessageManagerLock;
  157. ScopedPointer<ActionBroadcaster> broadcaster;
  158. bool quitMessagePosted, quitMessageReceived;
  159. Thread::ThreadID messageThreadId;
  160. Thread::ThreadID volatile threadWithLock;
  161. CriticalSection lockingLock;
  162. static bool postMessageToSystemQueue (MessageBase*);
  163. static void* exitModalLoopCallback (void*);
  164. static void doPlatformSpecificInitialisation();
  165. static void doPlatformSpecificShutdown();
  166. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  167. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager)
  168. };
  169. //==============================================================================
  170. /** Used to make sure that the calling thread has exclusive access to the message loop.
  171. Because it's not thread-safe to call any of the Component or other UI classes
  172. from threads other than the message thread, one of these objects can be used to
  173. lock the message loop and allow this to be done. The message thread will be
  174. suspended for the lifetime of the MessageManagerLock object, so create one on
  175. the stack like this: @code
  176. void MyThread::run()
  177. {
  178. someData = 1234;
  179. const MessageManagerLock mmLock;
  180. // the event loop will now be locked so it's safe to make a few calls..
  181. myComponent->setBounds (newBounds);
  182. myComponent->repaint();
  183. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  184. }
  185. @endcode
  186. Obviously be careful not to create one of these and leave it lying around, or
  187. your app will grind to a halt!
  188. MessageManagerLocks are re-entrant, so can be safely nested if the current thread
  189. already has the lock.
  190. Another caveat is that using this in conjunction with other CriticalSections
  191. can create lots of interesting ways of producing a deadlock! In particular, if
  192. your message thread calls stopThread() for a thread that uses these locks,
  193. you'll get an (occasional) deadlock..
  194. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  195. */
  196. class JUCE_API MessageManagerLock
  197. {
  198. public:
  199. //==============================================================================
  200. /** Tries to acquire a lock on the message manager.
  201. The constructor attempts to gain a lock on the message loop, and the lock will be
  202. kept for the lifetime of this object.
  203. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  204. this method will keep checking whether the thread has been given the
  205. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  206. without gaining the lock. If you pass a thread, you must check whether the lock was
  207. successful by calling lockWasGained(). If this is false, your thread is being told to
  208. die, so you should take evasive action.
  209. If you pass nullptr for the thread object, it will wait indefinitely for the lock - be
  210. careful when doing this, because it's very easy to deadlock if your message thread
  211. attempts to call stopThread() on a thread just as that thread attempts to get the
  212. message lock.
  213. If the calling thread already has the lock, nothing will be done, so it's safe and
  214. quick to use these locks recursively.
  215. E.g.
  216. @code
  217. void run()
  218. {
  219. ...
  220. while (! threadShouldExit())
  221. {
  222. MessageManagerLock mml (Thread::getCurrentThread());
  223. if (! mml.lockWasGained())
  224. return; // another thread is trying to kill us!
  225. ..do some locked stuff here..
  226. }
  227. ..and now the MM is now unlocked..
  228. }
  229. @endcode
  230. */
  231. MessageManagerLock (Thread* threadToCheckForExitSignal = nullptr);
  232. //==============================================================================
  233. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  234. instead of a thread.
  235. See the MessageManagerLock (Thread*) constructor for details on how this works.
  236. */
  237. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  238. //==============================================================================
  239. /** Releases the current thread's lock on the message manager.
  240. Make sure this object is created and deleted by the same thread,
  241. otherwise there are no guarantees what will happen!
  242. */
  243. ~MessageManagerLock() noexcept;
  244. //==============================================================================
  245. /** Returns true if the lock was successfully acquired.
  246. (See the constructor that takes a Thread for more info).
  247. */
  248. bool lockWasGained() const noexcept { return locked; }
  249. private:
  250. class BlockingMessage;
  251. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  252. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  253. bool locked;
  254. bool attemptLock (Thread*, ThreadPoolJob*);
  255. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock)
  256. };
  257. #endif // JUCE_MESSAGEMANAGER_H_INCLUDED