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.

500 lines
20KB

  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. /** Returns true if there's an instance of the MessageManager, and if the current thread
  113. has the lock on it.
  114. */
  115. static bool existsAndIsLockedByCurrentThread() noexcept;
  116. /** Returns true if there's an instance of the MessageManager, and if the current thread
  117. is running it.
  118. */
  119. static bool existsAndIsCurrentThread() noexcept;
  120. //==============================================================================
  121. /** Sends a message to all other JUCE applications that are running.
  122. @param messageText the string that will be passed to the actionListenerCallback()
  123. method of the broadcast listeners in the other app.
  124. @see registerBroadcastListener, ActionListener
  125. */
  126. static void broadcastMessage (const String& messageText);
  127. /** Registers a listener to get told about broadcast messages.
  128. The actionListenerCallback() callback's string parameter
  129. is the message passed into broadcastMessage().
  130. @see broadcastMessage
  131. */
  132. void registerBroadcastListener (ActionListener* listener);
  133. /** Deregisters a broadcast listener. */
  134. void deregisterBroadcastListener (ActionListener* listener);
  135. //==============================================================================
  136. /** Internal class used as the base class for all message objects.
  137. You shouldn't need to use this directly - see the CallbackMessage or Message
  138. classes instead.
  139. */
  140. class JUCE_API MessageBase : public ReferenceCountedObject
  141. {
  142. public:
  143. MessageBase() noexcept {}
  144. virtual ~MessageBase() {}
  145. virtual void messageCallback() = 0;
  146. bool post();
  147. using Ptr = ReferenceCountedObjectPtr<MessageBase>;
  148. JUCE_DECLARE_NON_COPYABLE (MessageBase)
  149. };
  150. //==============================================================================
  151. /** A lock you can use to lock the message manager. You can use this class with
  152. the RAII-based ScopedLock classes.
  153. */
  154. class Lock
  155. {
  156. public:
  157. /**
  158. Creates a new critical section to exclusively access methods which can
  159. only be called when the message manager is locked.
  160. Unlike CrititcalSection, multiple instances of this lock class provide
  161. exclusive access to a single resource - the MessageManager.
  162. */
  163. Lock();
  164. /** Destructor. */
  165. ~Lock();
  166. /** Acquires the message manager lock.
  167. If the caller thread already has exclusive access to the MessageManager, this method
  168. will return immediately.
  169. If another thread is currently using the MessageManager, this will wait until that
  170. thread releases the lock to the MessageManager.
  171. This call will only exit if the lock was accquired by this thread. Calling abort while
  172. a thread is waiting for enter to finish, will have no effect.
  173. @see exit, abort
  174. */
  175. void enter() const noexcept;
  176. /** Attempts to lock the meesage manager and exits if abort is called.
  177. This method behaves identically to enter, except that it will abort waiting for
  178. the lock if the abort method is called.
  179. Unlike other JUCE critical sections, this method **will** block waiting for the lock.
  180. To ensure predictable behaviour, you should re-check your abort condition if tryEnter
  181. returns false.
  182. This method can be used if you want to do some work while waiting for the
  183. MessageManagerLock:
  184. void doWorkWhileWaitingForMessageManagerLock()
  185. {
  186. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock);
  187. while (! mmLock.isLocked())
  188. {
  189. while (workQueue.size() > 0)
  190. {
  191. auto work = workQueue.pop();
  192. doSomeWork (work);
  193. }
  194. // this will block until we either have the lock or there is work
  195. mmLock.retryLock();
  196. }
  197. // we have the mmlock
  198. // do some message manager stuff like resizing and painting components
  199. }
  200. // called from another thread
  201. void addWorkToDo (Work work)
  202. {
  203. queue.push (work);
  204. messageManagerLock.abort();
  205. }
  206. @returns false if waiting for a lock was aborted, true if the lock was accquired.
  207. @see enter, abort, ScopedTryLock
  208. */
  209. bool tryEnter() const noexcept;
  210. /** Releases the message manager lock.
  211. @see enter, ScopedLock
  212. */
  213. void exit() const noexcept;
  214. /** Unblocks a thread which is waiting in tryEnter
  215. Call this method if you want to unblock a thread which is waiting for the
  216. MessageManager lock in tryEnter.
  217. This method does not have any effetc on a thread waiting for a lock in enter.
  218. @see tryEnter
  219. */
  220. void abort() const noexcept;
  221. //==============================================================================
  222. /** Provides the type of scoped lock to use with a CriticalSection. */
  223. using ScopedLockType = GenericScopedLock<Lock>;
  224. /** Provides the type of scoped unlocker to use with a CriticalSection. */
  225. using ScopedUnlockType = GenericScopedUnlock<Lock>;
  226. /** Provides the type of scoped try-locker to use with a CriticalSection. */
  227. using ScopedTryLockType = GenericScopedTryLock<Lock>;
  228. private:
  229. struct BlockingMessage;
  230. friend class ReferenceCountedObjectPtr<BlockingMessage>;
  231. bool tryAcquire (bool) const noexcept;
  232. void messageCallback() const;
  233. //==============================================================================
  234. mutable ReferenceCountedObjectPtr<BlockingMessage> blockingMessage;
  235. WaitableEvent lockedEvent;
  236. mutable Atomic<int> abortWait, lockGained;
  237. };
  238. //==============================================================================
  239. #ifndef DOXYGEN
  240. // Internal methods - do not use!
  241. void deliverBroadcastMessage (const String&);
  242. ~MessageManager() noexcept;
  243. #endif
  244. private:
  245. //==============================================================================
  246. MessageManager() noexcept;
  247. static MessageManager* instance;
  248. friend class MessageBase;
  249. class QuitMessage;
  250. friend class QuitMessage;
  251. friend class MessageManagerLock;
  252. std::unique_ptr<ActionBroadcaster> broadcaster;
  253. Atomic<int> quitMessagePosted { 0 }, quitMessageReceived { 0 };
  254. Thread::ThreadID messageThreadId;
  255. Atomic<Thread::ThreadID> threadWithLock;
  256. static bool postMessageToSystemQueue (MessageBase*);
  257. static void* exitModalLoopCallback (void*);
  258. static void doPlatformSpecificInitialisation();
  259. static void doPlatformSpecificShutdown();
  260. static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  261. template <typename FunctionType>
  262. struct AsyncCallInvoker : public MessageBase
  263. {
  264. AsyncCallInvoker (FunctionType f) : callback (f) { post(); }
  265. void messageCallback() override { callback(); }
  266. FunctionType callback;
  267. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AsyncCallInvoker)
  268. };
  269. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager)
  270. };
  271. //==============================================================================
  272. /** Used to make sure that the calling thread has exclusive access to the message loop.
  273. Because it's not thread-safe to call any of the Component or other UI classes
  274. from threads other than the message thread, one of these objects can be used to
  275. lock the message loop and allow this to be done. The message thread will be
  276. suspended for the lifetime of the MessageManagerLock object, so create one on
  277. the stack like this: @code
  278. void MyThread::run()
  279. {
  280. someData = 1234;
  281. const MessageManagerLock mmLock;
  282. // the event loop will now be locked so it's safe to make a few calls..
  283. myComponent->setBounds (newBounds);
  284. myComponent->repaint();
  285. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  286. }
  287. @endcode
  288. Obviously be careful not to create one of these and leave it lying around, or
  289. your app will grind to a halt!
  290. MessageManagerLocks are re-entrant, so can be safely nested if the current thread
  291. already has the lock.
  292. Another caveat is that using this in conjunction with other CriticalSections
  293. can create lots of interesting ways of producing a deadlock! In particular, if
  294. your message thread calls stopThread() for a thread that uses these locks,
  295. you'll get an (occasional) deadlock..
  296. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  297. @tags{Events}
  298. */
  299. class JUCE_API MessageManagerLock : private Thread::Listener
  300. {
  301. public:
  302. //==============================================================================
  303. /** Tries to acquire a lock on the message manager.
  304. The constructor attempts to gain a lock on the message loop, and the lock will be
  305. kept for the lifetime of this object.
  306. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  307. this method will keep checking whether the thread has been given the
  308. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  309. without gaining the lock. If you pass a thread, you must check whether the lock was
  310. successful by calling lockWasGained(). If this is false, your thread is being told to
  311. die, so you should take evasive action.
  312. If you pass nullptr for the thread object, it will wait indefinitely for the lock - be
  313. careful when doing this, because it's very easy to deadlock if your message thread
  314. attempts to call stopThread() on a thread just as that thread attempts to get the
  315. message lock.
  316. If the calling thread already has the lock, nothing will be done, so it's safe and
  317. quick to use these locks recursively.
  318. E.g.
  319. @code
  320. void run()
  321. {
  322. ...
  323. while (! threadShouldExit())
  324. {
  325. MessageManagerLock mml (Thread::getCurrentThread());
  326. if (! mml.lockWasGained())
  327. return; // another thread is trying to kill us!
  328. ..do some locked stuff here..
  329. }
  330. ..and now the MM is now unlocked..
  331. }
  332. @endcode
  333. */
  334. MessageManagerLock (Thread* threadToCheckForExitSignal = nullptr);
  335. //==============================================================================
  336. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  337. instead of a thread.
  338. See the MessageManagerLock (Thread*) constructor for details on how this works.
  339. */
  340. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal);
  341. //==============================================================================
  342. /** Releases the current thread's lock on the message manager.
  343. Make sure this object is created and deleted by the same thread,
  344. otherwise there are no guarantees what will happen!
  345. */
  346. ~MessageManagerLock() noexcept;
  347. //==============================================================================
  348. /** Returns true if the lock was successfully acquired.
  349. (See the constructor that takes a Thread for more info).
  350. */
  351. bool lockWasGained() const noexcept { return locked; }
  352. private:
  353. //==============================================================================
  354. MessageManager::Lock mmLock;
  355. bool locked;
  356. //==============================================================================
  357. bool attemptLock (Thread*, ThreadPoolJob*);
  358. void exitSignalSent() override;
  359. JUCE_DECLARE_NON_COPYABLE (MessageManagerLock)
  360. };
  361. //==============================================================================
  362. /** This macro is used to catch unsafe use of functions which expect to only be called
  363. on the message thread, or when a MessageManagerLock is in place.
  364. It will also fail if you try to use the function before the message manager has been
  365. created, which could happen if you accidentally invoke it during a static constructor.
  366. */
  367. #define JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED \
  368. jassert (juce::MessageManager::existsAndIsLockedByCurrentThread());
  369. /** This macro is used to catch unsafe use of functions which expect to only be called
  370. on the message thread.
  371. It will also fail if you try to use the function before the message manager has been
  372. created, which could happen if you accidentally invoke it during a static constructor.
  373. */
  374. #define JUCE_ASSERT_MESSAGE_THREAD \
  375. jassert (juce::MessageManager::existsAndIsCurrentThread());
  376. /** This macro is used to catch unsafe use of functions which expect to not be called
  377. outside the lifetime of the MessageManager.
  378. */
  379. #define JUCE_ASSERT_MESSAGE_MANAGER_EXISTS \
  380. jassert (juce::MessageManager::getInstanceWithoutCreating() != nullptr);
  381. } // namespace juce