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.

383 lines
15KB

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