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.

330 lines
13KB

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