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.

379 lines
15KB

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