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.

juce_MessageManager.h 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. class MessageManagerLock;
  20. class ThreadPoolJob;
  21. class ActionListener;
  22. class ActionBroadcaster;
  23. //==============================================================================
  24. #if JUCE_MODULE_AVAILABLE_juce_opengl
  25. class OpenGLContext;
  26. #endif
  27. //==============================================================================
  28. /** See MessageManager::callFunctionOnMessageThread() for use of this function type. */
  29. typedef void* (MessageCallbackFunction) (void* userData);
  30. //==============================================================================
  31. /**
  32. This class is in charge of the application's event-dispatch loop.
  33. @see Message, CallbackMessage, MessageManagerLock, JUCEApplication, JUCEApplicationBase
  34. */
  35. class JUCE_API MessageManager
  36. {
  37. public:
  38. //==============================================================================
  39. /** Returns the global instance of the MessageManager. */
  40. static MessageManager* getInstance();
  41. /** Returns the global instance of the MessageManager, or nullptr if it doesn't exist. */
  42. static MessageManager* getInstanceWithoutCreating() noexcept;
  43. /** Deletes the global MessageManager instance.
  44. Does nothing if no instance had been created.
  45. */
  46. static void deleteInstance();
  47. //==============================================================================
  48. /** Runs the event dispatch loop until a stop message is posted.
  49. This method is only intended to be run by the application's startup routine,
  50. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  51. @see stopDispatchLoop
  52. */
  53. void runDispatchLoop();
  54. /** Sends a signal that the dispatch loop should terminate.
  55. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  56. will be interrupted and will return.
  57. @see runDispatchLoop
  58. */
  59. void stopDispatchLoop();
  60. /** Returns true if the stopDispatchLoop() method has been called.
  61. */
  62. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; }
  63. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  64. /** Synchronously dispatches messages until a given time has elapsed.
  65. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  66. otherwise returns true.
  67. */
  68. bool runDispatchLoopUntil (int millisecondsToRunFor);
  69. #endif
  70. //==============================================================================
  71. /** Asynchronously invokes a function or C++11 lambda on the message thread. */
  72. template <typename FunctionType>
  73. static void callAsync (FunctionType functionToCall)
  74. {
  75. new AsyncCallInvoker<FunctionType> (functionToCall);
  76. }
  77. /** Calls a function using the message-thread.
  78. This can be used by any thread to cause this function to be called-back
  79. by the message thread. If it's the message-thread that's calling this method,
  80. then the function will just be called; if another thread is calling, a message
  81. will be posted to the queue, and this method will block until that message
  82. is delivered, the function is called, and the result is returned.
  83. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  84. thread has a critical section locked, which an unrelated message callback then tries to lock
  85. before the message thread gets round to processing this callback.
  86. @param callback the function to call - its signature must be @code
  87. void* myCallbackFunction (void*) @endcode
  88. @param userData a user-defined pointer that will be passed to the function that gets called
  89. @returns the value that the callback function returns.
  90. @see MessageManagerLock
  91. */
  92. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  93. /** Returns true if the caller-thread is the message thread. */
  94. bool isThisTheMessageThread() const noexcept;
  95. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  96. (Best to ignore this method unless you really know what you're doing..)
  97. @see getCurrentMessageThread
  98. */
  99. void setCurrentThreadAsMessageThread();
  100. /** Returns the ID of the current message thread, as set by setCurrentThreadAsMessageThread().
  101. (Best to ignore this method unless you really know what you're doing..)
  102. @see setCurrentThreadAsMessageThread
  103. */
  104. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  105. /** Returns true if the caller thread has currently got the message manager locked.
  106. see the MessageManagerLock class for more info about this.
  107. This will be true if the caller is the message thread, because that automatically
  108. gains a lock while a message is being dispatched.
  109. */
  110. bool currentThreadHasLockedMessageManager() const noexcept;
  111. //==============================================================================
  112. /** Sends a message to all other JUCE applications that are running.
  113. @param messageText the string that will be passed to the actionListenerCallback()
  114. method of the broadcast listeners in the other app.
  115. @see registerBroadcastListener, ActionListener
  116. */
  117. static void broadcastMessage (const String& messageText);
  118. /** Registers a listener to get told about broadcast messages.
  119. The actionListenerCallback() callback's string parameter
  120. is the message passed into broadcastMessage().
  121. @see broadcastMessage
  122. */
  123. void registerBroadcastListener (ActionListener* listener);
  124. /** Deregisters a broadcast listener. */
  125. void deregisterBroadcastListener (ActionListener* listener);
  126. //==============================================================================
  127. /** Internal class used as the base class for all message objects.
  128. You shouldn't need to use this directly - see the CallbackMessage or Message
  129. classes instead.
  130. */
  131. class JUCE_API MessageBase : public ReferenceCountedObject
  132. {
  133. public:
  134. MessageBase() noexcept {}
  135. virtual ~MessageBase() {}
  136. virtual void messageCallback() = 0;
  137. bool post();
  138. typedef ReferenceCountedObjectPtr<MessageBase> Ptr;
  139. JUCE_DECLARE_NON_COPYABLE (MessageBase)
  140. };
  141. //==============================================================================
  142. #ifndef DOXYGEN
  143. // Internal methods - do not use!
  144. void deliverBroadcastMessage (const String&);
  145. ~MessageManager() noexcept;
  146. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  147. #endif
  148. private:
  149. //==============================================================================
  150. MessageManager() noexcept;
  151. static MessageManager* instance;
  152. friend class MessageBase;
  153. class QuitMessage;
  154. friend class QuitMessage;
  155. friend class MessageManagerLock;
  156. ScopedPointer<ActionBroadcaster> broadcaster;
  157. bool quitMessagePosted = false, quitMessageReceived = false;
  158. Thread::ThreadID messageThreadId;
  159. Thread::ThreadID volatile threadWithLock = {};
  160. CriticalSection lockingLock;
  161. static bool postMessageToSystemQueue (MessageBase*);
  162. static void* exitModalLoopCallback (void*);
  163. static void doPlatformSpecificInitialisation();
  164. static void doPlatformSpecificShutdown();
  165. template <typename FunctionType>
  166. struct AsyncCallInvoker : public MessageBase
  167. {
  168. AsyncCallInvoker (FunctionType f) : callback (f) { post(); }
  169. void messageCallback() override { callback(); }
  170. FunctionType callback;
  171. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncCallInvoker)
  172. };
  173. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager)
  174. };
  175. //==============================================================================
  176. /** Used to make sure that the calling thread has exclusive access to the message loop.
  177. Because it's not thread-safe to call any of the Component or other UI classes
  178. from threads other than the message thread, one of these objects can be used to
  179. lock the message loop and allow this to be done. The message thread will be
  180. suspended for the lifetime of the MessageManagerLock object, so create one on
  181. the stack like this: @code
  182. void MyThread::run()
  183. {
  184. someData = 1234;
  185. const MessageManagerLock mmLock;
  186. // the event loop will now be locked so it's safe to make a few calls..
  187. myComponent->setBounds (newBounds);
  188. myComponent->repaint();
  189. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  190. }
  191. @endcode
  192. Obviously be careful not to create one of these and leave it lying around, or
  193. your app will grind to a halt!
  194. MessageManagerLocks are re-entrant, so can be safely nested if the current thread
  195. already has the lock.
  196. Another caveat is that using this in conjunction with other CriticalSections
  197. can create lots of interesting ways of producing a deadlock! In particular, if
  198. your message thread calls stopThread() for a thread that uses these locks,
  199. you'll get an (occasional) deadlock..
  200. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  201. */
  202. class JUCE_API MessageManagerLock
  203. {
  204. public:
  205. //==============================================================================
  206. /** Tries to acquire a lock on the message manager.
  207. The constructor attempts to gain a lock on the message loop, and the lock will be
  208. kept for the lifetime of this object.
  209. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  210. this method will keep checking whether the thread has been given the
  211. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  212. without gaining the lock. If you pass a thread, you must check whether the lock was
  213. successful by calling lockWasGained(). If this is false, your thread is being told to
  214. die, so you should take evasive action.
  215. If you pass nullptr for the thread object, it will wait indefinitely for the lock - be
  216. careful when doing this, because it's very easy to deadlock if your message thread
  217. attempts to call stopThread() on a thread just as that thread attempts to get the
  218. message lock.
  219. If the calling thread already has the lock, nothing will be done, so it's safe and
  220. quick to use these locks recursively.
  221. E.g.
  222. @code
  223. void run()
  224. {
  225. ...
  226. while (! threadShouldExit())
  227. {
  228. MessageManagerLock mml (Thread::getCurrentThread());
  229. if (! mml.lockWasGained())
  230. return; // another thread is trying to kill us!
  231. ..do some locked stuff here..
  232. }
  233. ..and now the MM is now unlocked..
  234. }
  235. @endcode
  236. */
  237. MessageManagerLock (Thread* threadToCheckForExitSignal = nullptr);
  238. //==============================================================================
  239. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  240. instead of a thread.
  241. See the MessageManagerLock (Thread*) constructor for details on how this works.
  242. */
  243. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  244. //==============================================================================
  245. struct BailOutChecker
  246. {
  247. virtual ~BailOutChecker() {}
  248. /** Return true if acquiring the lock should be aborted. */
  249. virtual bool shouldAbortAcquiringLock() = 0;
  250. };
  251. /** This is an abstraction of the other constructors. You can pass this constructor
  252. a functor which is periodically checked if attempting the lock should be aborted.
  253. See the MessageManagerLock (Thread*) constructor for details on how this works.
  254. */
  255. MessageManagerLock (BailOutChecker&);
  256. //==============================================================================
  257. /** Releases the current thread's lock on the message manager.
  258. Make sure this object is created and deleted by the same thread,
  259. otherwise there are no guarantees what will happen!
  260. */
  261. ~MessageManagerLock() noexcept;
  262. //==============================================================================
  263. /** Returns true if the lock was successfully acquired.
  264. (See the constructor that takes a Thread for more info).
  265. */
  266. bool lockWasGained() const noexcept { return locked; }
  267. private:
  268. class BlockingMessage;
  269. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  270. ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  271. struct ThreadChecker : BailOutChecker
  272. {
  273. ThreadChecker (Thread* const, ThreadPoolJob* const);
  274. // Required to supress VS2013 compiler warnings
  275. ThreadChecker& operator= (const ThreadChecker&) = delete;
  276. bool shouldAbortAcquiringLock() override;
  277. Thread* const threadToCheck;
  278. ThreadPoolJob* const job;
  279. };
  280. //==============================================================================
  281. ThreadChecker checker;
  282. bool locked;
  283. //==============================================================================
  284. bool attemptLock (BailOutChecker*);
  285. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock)
  286. };
  287. } // namespace juce