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.

466 lines
18KB

  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. using MessageCallbackFunction = void* (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. @tags{Events}
  35. */
  36. class JUCE_API MessageManager final
  37. {
  38. public:
  39. //==============================================================================
  40. /** Returns the global instance of the MessageManager. */
  41. static MessageManager* getInstance();
  42. /** Returns the global instance of the MessageManager, or nullptr if it doesn't exist. */
  43. static MessageManager* getInstanceWithoutCreating() noexcept;
  44. /** Deletes the global MessageManager instance.
  45. Does nothing if no instance had been created.
  46. */
  47. static void deleteInstance();
  48. //==============================================================================
  49. /** Runs the event dispatch loop until a stop message is posted.
  50. This method is only intended to be run by the application's startup routine,
  51. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  52. @see stopDispatchLoop
  53. */
  54. void runDispatchLoop();
  55. /** Sends a signal that the dispatch loop should terminate.
  56. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  57. will be interrupted and will return.
  58. @see runDispatchLoop
  59. */
  60. void stopDispatchLoop();
  61. /** Returns true if the stopDispatchLoop() method has been called.
  62. */
  63. bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted.get() != 0; }
  64. #if JUCE_MODAL_LOOPS_PERMITTED || DOXYGEN
  65. /** Synchronously dispatches messages until a given time has elapsed.
  66. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  67. otherwise returns true.
  68. */
  69. bool runDispatchLoopUntil (int millisecondsToRunFor);
  70. #endif
  71. //==============================================================================
  72. /** Asynchronously invokes a function or C++11 lambda on the message thread. */
  73. template <typename FunctionType>
  74. static void callAsync (FunctionType functionToCall)
  75. {
  76. new AsyncCallInvoker<FunctionType> (functionToCall);
  77. }
  78. /** Calls a function using the message-thread.
  79. This can be used by any thread to cause this function to be called-back
  80. by the message thread. If it's the message-thread that's calling this method,
  81. then the function will just be called; if another thread is calling, a message
  82. will be posted to the queue, and this method will block until that message
  83. is delivered, the function is called, and the result is returned.
  84. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  85. thread has a critical section locked, which an unrelated message callback then tries to lock
  86. before the message thread gets round to processing this callback.
  87. @param callback the function to call - its signature must be @code
  88. void* myCallbackFunction (void*) @endcode
  89. @param userData a user-defined pointer that will be passed to the function that gets called
  90. @returns the value that the callback function returns.
  91. @see MessageManagerLock
  92. */
  93. void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData);
  94. /** Returns true if the caller-thread is the message thread. */
  95. bool isThisTheMessageThread() const noexcept;
  96. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  97. (Best to ignore this method unless you really know what you're doing..)
  98. @see getCurrentMessageThread
  99. */
  100. void setCurrentThreadAsMessageThread();
  101. /** Returns the ID of the current message thread, as set by setCurrentThreadAsMessageThread().
  102. (Best to ignore this method unless you really know what you're doing..)
  103. @see setCurrentThreadAsMessageThread
  104. */
  105. Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; }
  106. /** Returns true if the caller thread has currently got the message manager locked.
  107. see the MessageManagerLock class for more info about this.
  108. This will be true if the caller is the message thread, because that automatically
  109. gains a lock while a message is being dispatched.
  110. */
  111. bool currentThreadHasLockedMessageManager() const noexcept;
  112. //==============================================================================
  113. /** Sends a message to all other JUCE applications that are running.
  114. @param messageText the string that will be passed to the actionListenerCallback()
  115. method of the broadcast listeners in the other app.
  116. @see registerBroadcastListener, ActionListener
  117. */
  118. static void broadcastMessage (const String& messageText);
  119. /** Registers a listener to get told about broadcast messages.
  120. The actionListenerCallback() callback's string parameter
  121. is the message passed into broadcastMessage().
  122. @see broadcastMessage
  123. */
  124. void registerBroadcastListener (ActionListener* listener);
  125. /** Deregisters a broadcast listener. */
  126. void deregisterBroadcastListener (ActionListener* listener);
  127. //==============================================================================
  128. /** Internal class used as the base class for all message objects.
  129. You shouldn't need to use this directly - see the CallbackMessage or Message
  130. classes instead.
  131. */
  132. class JUCE_API MessageBase : public ReferenceCountedObject
  133. {
  134. public:
  135. MessageBase() noexcept {}
  136. virtual ~MessageBase() {}
  137. virtual void messageCallback() = 0;
  138. bool post();
  139. using Ptr = ReferenceCountedObjectPtr<MessageBase>;
  140. JUCE_DECLARE_NON_COPYABLE (MessageBase)
  141. };
  142. //==============================================================================
  143. /** A lock you can use to lock the message manager. You can use this class with
  144. the RAII-based ScopedLock classes.
  145. */
  146. class Lock
  147. {
  148. public:
  149. /**
  150. Creates a new critical section to exclusively access methods which can
  151. only be called when the message manager is locked.
  152. Unlike CrititcalSection, multiple instances of this lock class provide
  153. exclusive access to a single resource - the MessageManager.
  154. */
  155. Lock();
  156. /** Destructor. */
  157. ~Lock();
  158. /** Acquires the message manager lock.
  159. If the caller thread already has exclusive access to the MessageManager, this method
  160. will return immediately.
  161. If another thread is currently using the MessageManager, this will wait until that
  162. thread releases the lock to the MessageManager.
  163. This call will only exit if the lock was accquired by this thread. Calling abort while
  164. a thread is waiting for enter to finish, will have no effect.
  165. @see exit, abort
  166. */
  167. void enter() const noexcept;
  168. /** Attempts to lock the meesage manager and exits if abort is called.
  169. This method behaves identically to enter, except that it will abort waiting for
  170. the lock if the abort method is called.
  171. Unlike other JUCE critical sections, this method **will** block waiting for the lock.
  172. To ensure predictable behaviour, you should re-check your abort condition if tryEnter
  173. returns false.
  174. This method can be used if you want to do some work while waiting for the
  175. MessageManagerLock:
  176. void doWorkWhileWaitingForMessageManagerLock()
  177. {
  178. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock);
  179. while (! mmLock.isLocked())
  180. {
  181. while (workQueue.size() > 0)
  182. {
  183. auto work = workQueue.pop();
  184. doSomeWork (work);
  185. }
  186. // this will block until we either have the lock or there is work
  187. mmLock.retryLock();
  188. }
  189. // we have the mmlock
  190. // do some message manager stuff like resizing and painting components
  191. }
  192. // called from another thread
  193. void addWorkToDo (Work work)
  194. {
  195. queue.push (work);
  196. messageManagerLock.abort();
  197. }
  198. @returns false if waiting for a lock was aborted, true if the lock was accquired.
  199. @see enter, abort, ScopedTryLock
  200. */
  201. bool tryEnter() const noexcept;
  202. /** Releases the message manager lock.
  203. @see enter, ScopedLock
  204. */
  205. void exit() const noexcept;
  206. /** Unblocks a thread which is waiting in tryEnter
  207. Call this method if you want to unblock a thread which is waiting for the
  208. MessageManager lock in tryEnter.
  209. This method does not have any effetc on a thread waiting for a lock in enter.
  210. @see tryEnter
  211. */
  212. void abort() const noexcept;
  213. //==============================================================================
  214. /** Provides the type of scoped lock to use with a CriticalSection. */
  215. using ScopedLockType = GenericScopedLock<Lock>;
  216. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  217. using ScopedUnlockType = GenericScopedUnlock<Lock>;
  218. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  219. using ScopedTryLockType = GenericScopedTryLock<Lock>;
  220. private:
  221. struct BlockingMessage;
  222. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  223. bool tryAcquire (bool) const noexcept;
  224. void messageCallback() const;
  225. //==============================================================================
  226. mutable ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  227. WaitableEvent lockedEvent;
  228. mutable Atomic<int> abortWait, lockGained;
  229. };
  230. //==============================================================================
  231. #ifndef DOXYGEN
  232. // Internal methods - do not use!
  233. void deliverBroadcastMessage (const String&);
  234. ~MessageManager() noexcept;
  235. #endif
  236. private:
  237. //==============================================================================
  238. MessageManager() noexcept;
  239. static MessageManager* instance;
  240. friend class MessageBase;
  241. class QuitMessage;
  242. friend class QuitMessage;
  243. friend class MessageManagerLock;
  244. std::unique_ptr<ActionBroadcaster> broadcaster;
  245. Atomic<int> quitMessagePosted { 0 }, quitMessageReceived { 0 };
  246. Thread::ThreadID messageThreadId;
  247. Atomic<Thread::ThreadID> threadWithLock;
  248. static bool postMessageToSystemQueue (MessageBase*);
  249. static void* exitModalLoopCallback (void*);
  250. static void doPlatformSpecificInitialisation();
  251. static void doPlatformSpecificShutdown();
  252. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  253. template <typename FunctionType>
  254. struct AsyncCallInvoker : public MessageBase
  255. {
  256. AsyncCallInvoker (FunctionType f) : callback (f) { post(); }
  257. void messageCallback() override { callback(); }
  258. FunctionType callback;
  259. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncCallInvoker)
  260. };
  261. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager)
  262. };
  263. //==============================================================================
  264. /** Used to make sure that the calling thread has exclusive access to the message loop.
  265. Because it's not thread-safe to call any of the Component or other UI classes
  266. from threads other than the message thread, one of these objects can be used to
  267. lock the message loop and allow this to be done. The message thread will be
  268. suspended for the lifetime of the MessageManagerLock object, so create one on
  269. the stack like this: @code
  270. void MyThread::run()
  271. {
  272. someData = 1234;
  273. const MessageManagerLock mmLock;
  274. // the event loop will now be locked so it's safe to make a few calls..
  275. myComponent->setBounds (newBounds);
  276. myComponent->repaint();
  277. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  278. }
  279. @endcode
  280. Obviously be careful not to create one of these and leave it lying around, or
  281. your app will grind to a halt!
  282. MessageManagerLocks are re-entrant, so can be safely nested if the current thread
  283. already has the lock.
  284. Another caveat is that using this in conjunction with other CriticalSections
  285. can create lots of interesting ways of producing a deadlock! In particular, if
  286. your message thread calls stopThread() for a thread that uses these locks,
  287. you'll get an (occasional) deadlock..
  288. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  289. @tags{Events}
  290. */
  291. class JUCE_API MessageManagerLock : private Thread::Listener
  292. {
  293. public:
  294. //==============================================================================
  295. /** Tries to acquire a lock on the message manager.
  296. The constructor attempts to gain a lock on the message loop, and the lock will be
  297. kept for the lifetime of this object.
  298. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  299. this method will keep checking whether the thread has been given the
  300. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  301. without gaining the lock. If you pass a thread, you must check whether the lock was
  302. successful by calling lockWasGained(). If this is false, your thread is being told to
  303. die, so you should take evasive action.
  304. If you pass nullptr for the thread object, it will wait indefinitely for the lock - be
  305. careful when doing this, because it's very easy to deadlock if your message thread
  306. attempts to call stopThread() on a thread just as that thread attempts to get the
  307. message lock.
  308. If the calling thread already has the lock, nothing will be done, so it's safe and
  309. quick to use these locks recursively.
  310. E.g.
  311. @code
  312. void run()
  313. {
  314. ...
  315. while (! threadShouldExit())
  316. {
  317. MessageManagerLock mml (Thread::getCurrentThread());
  318. if (! mml.lockWasGained())
  319. return; // another thread is trying to kill us!
  320. ..do some locked stuff here..
  321. }
  322. ..and now the MM is now unlocked..
  323. }
  324. @endcode
  325. */
  326. MessageManagerLock (Thread* threadToCheckForExitSignal = nullptr);
  327. //==============================================================================
  328. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  329. instead of a thread.
  330. See the MessageManagerLock (Thread*) constructor for details on how this works.
  331. */
  332. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  333. //==============================================================================
  334. /** Releases the current thread's lock on the message manager.
  335. Make sure this object is created and deleted by the same thread,
  336. otherwise there are no guarantees what will happen!
  337. */
  338. ~MessageManagerLock() noexcept;
  339. //==============================================================================
  340. /** Returns true if the lock was successfully acquired.
  341. (See the constructor that takes a Thread for more info).
  342. */
  343. bool lockWasGained() const noexcept { return locked; }
  344. private:
  345. //==============================================================================
  346. MessageManager::Lock mmLock;
  347. bool locked;
  348. //==============================================================================
  349. bool attemptLock (Thread*, ThreadPoolJob*);
  350. void exitSignalSent() override;
  351. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock)
  352. };
  353. } // namespace juce