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.

378 lines
11KB

  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. class Timer::TimerThread : private Thread,
  19. private DeletedAtShutdown,
  20. private AsyncUpdater
  21. {
  22. public:
  23. typedef CriticalSection LockType; // (mysteriously, using a SpinLock here causes problems on some XP machines..)
  24. TimerThread()
  25. : Thread ("Juce Timer"),
  26. firstTimer (nullptr),
  27. callbackNeeded (0)
  28. {
  29. triggerAsyncUpdate();
  30. }
  31. ~TimerThread() noexcept
  32. {
  33. stopThread (4000);
  34. jassert (instance == this || instance == nullptr);
  35. if (instance == this)
  36. instance = nullptr;
  37. }
  38. void run()
  39. {
  40. uint32 lastTime = Time::getMillisecondCounter();
  41. MessageManager::MessageBase::Ptr messageToSend (new CallTimersMessage());
  42. while (! threadShouldExit())
  43. {
  44. const uint32 now = Time::getMillisecondCounter();
  45. if (now == lastTime)
  46. {
  47. wait (1);
  48. continue;
  49. }
  50. const int elapsed = (int) (now >= lastTime ? (now - lastTime)
  51. : (std::numeric_limits<uint32>::max() - (lastTime - now)));
  52. lastTime = now;
  53. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  54. if (timeUntilFirstTimer <= 0)
  55. {
  56. /* If we managed to set the atomic boolean to true then send a message, this is needed
  57. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  58. but if it fails it means the message-thread changed the value from under us so at least
  59. some processing is happenening and we can just loop around and try again
  60. */
  61. if (callbackNeeded.compareAndSetBool (1, 0))
  62. {
  63. messageToSend->post();
  64. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  65. when the app has a modal loop), so this is how long to wait before assuming the
  66. message has been lost and trying again.
  67. */
  68. const uint32 messageDeliveryTimeout = now + 300;
  69. while (callbackNeeded.get() != 0)
  70. {
  71. wait (4);
  72. if (threadShouldExit())
  73. return;
  74. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  75. {
  76. messageToSend->post();
  77. break;
  78. }
  79. }
  80. }
  81. }
  82. else
  83. {
  84. // don't wait for too long because running this loop also helps keep the
  85. // Time::getApproximateMillisecondTimer value stay up-to-date
  86. wait (jlimit (1, 50, timeUntilFirstTimer));
  87. }
  88. }
  89. }
  90. void callTimers()
  91. {
  92. const LockType::ScopedLockType sl (lock);
  93. while (firstTimer != nullptr && firstTimer->countdownMs <= 0)
  94. {
  95. Timer* const t = firstTimer;
  96. t->countdownMs = t->periodMs;
  97. removeTimer (t);
  98. addTimer (t);
  99. const LockType::ScopedUnlockType ul (lock);
  100. JUCE_TRY
  101. {
  102. t->timerCallback();
  103. }
  104. JUCE_CATCH_EXCEPTION
  105. }
  106. /* This is needed as a memory barrier to make sure all processing of current timers is done
  107. before the boolean is set. This set should never fail since if it was false in the first place,
  108. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  109. get a message then the value is true and the other thread can only set it to true again and
  110. we will get another callback to set it to false.
  111. */
  112. callbackNeeded.set (0);
  113. }
  114. void callTimersSynchronously()
  115. {
  116. if (! isThreadRunning())
  117. {
  118. // (This is relied on by some plugins in cases where the MM has
  119. // had to restart and the async callback never started)
  120. cancelPendingUpdate();
  121. triggerAsyncUpdate();
  122. }
  123. callTimers();
  124. }
  125. static inline void add (Timer* const tim) noexcept
  126. {
  127. if (instance == nullptr)
  128. instance = new TimerThread();
  129. instance->addTimer (tim);
  130. }
  131. static inline void remove (Timer* const tim) noexcept
  132. {
  133. if (instance != nullptr)
  134. instance->removeTimer (tim);
  135. }
  136. static inline void resetCounter (Timer* const tim, const int newCounter) noexcept
  137. {
  138. if (instance != nullptr)
  139. {
  140. tim->countdownMs = newCounter;
  141. tim->periodMs = newCounter;
  142. if ((tim->next != nullptr && tim->next->countdownMs < tim->countdownMs)
  143. || (tim->previous != nullptr && tim->previous->countdownMs > tim->countdownMs))
  144. {
  145. instance->removeTimer (tim);
  146. instance->addTimer (tim);
  147. }
  148. }
  149. }
  150. static TimerThread* instance;
  151. static LockType lock;
  152. private:
  153. Timer* volatile firstTimer;
  154. Atomic <int> callbackNeeded;
  155. struct CallTimersMessage : public MessageManager::MessageBase
  156. {
  157. CallTimersMessage() {}
  158. void messageCallback()
  159. {
  160. if (instance != nullptr)
  161. instance->callTimers();
  162. }
  163. };
  164. //==============================================================================
  165. void addTimer (Timer* const t) noexcept
  166. {
  167. #if JUCE_DEBUG
  168. // trying to add a timer that's already here - shouldn't get to this point,
  169. // so if you get this assertion, let me know!
  170. jassert (! timerExists (t));
  171. #endif
  172. Timer* i = firstTimer;
  173. if (i == nullptr || i->countdownMs > t->countdownMs)
  174. {
  175. t->next = firstTimer;
  176. firstTimer = t;
  177. }
  178. else
  179. {
  180. while (i->next != nullptr && i->next->countdownMs <= t->countdownMs)
  181. i = i->next;
  182. jassert (i != nullptr);
  183. t->next = i->next;
  184. t->previous = i;
  185. i->next = t;
  186. }
  187. if (t->next != nullptr)
  188. t->next->previous = t;
  189. jassert ((t->next == nullptr || t->next->countdownMs >= t->countdownMs)
  190. && (t->previous == nullptr || t->previous->countdownMs <= t->countdownMs));
  191. notify();
  192. }
  193. void removeTimer (Timer* const t) noexcept
  194. {
  195. #if JUCE_DEBUG
  196. // trying to remove a timer that's not here - shouldn't get to this point,
  197. // so if you get this assertion, let me know!
  198. jassert (timerExists (t));
  199. #endif
  200. if (t->previous != nullptr)
  201. {
  202. jassert (firstTimer != t);
  203. t->previous->next = t->next;
  204. }
  205. else
  206. {
  207. jassert (firstTimer == t);
  208. firstTimer = t->next;
  209. }
  210. if (t->next != nullptr)
  211. t->next->previous = t->previous;
  212. t->next = nullptr;
  213. t->previous = nullptr;
  214. }
  215. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  216. {
  217. const LockType::ScopedLockType sl (lock);
  218. for (Timer* t = firstTimer; t != nullptr; t = t->next)
  219. t->countdownMs -= numMillisecsElapsed;
  220. return firstTimer != nullptr ? firstTimer->countdownMs : 1000;
  221. }
  222. void handleAsyncUpdate()
  223. {
  224. startThread (7);
  225. }
  226. #if JUCE_DEBUG
  227. bool timerExists (Timer* const t) const noexcept
  228. {
  229. for (Timer* tt = firstTimer; tt != nullptr; tt = tt->next)
  230. if (tt == t)
  231. return true;
  232. return false;
  233. }
  234. #endif
  235. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
  236. };
  237. Timer::TimerThread* Timer::TimerThread::instance = nullptr;
  238. Timer::TimerThread::LockType Timer::TimerThread::lock;
  239. //==============================================================================
  240. #if JUCE_DEBUG
  241. static SortedSet <Timer*> activeTimers;
  242. #endif
  243. Timer::Timer() noexcept
  244. : countdownMs (0),
  245. periodMs (0),
  246. previous (nullptr),
  247. next (nullptr)
  248. {
  249. #if JUCE_DEBUG
  250. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  251. activeTimers.add (this);
  252. #endif
  253. }
  254. Timer::Timer (const Timer&) noexcept
  255. : countdownMs (0),
  256. periodMs (0),
  257. previous (nullptr),
  258. next (nullptr)
  259. {
  260. #if JUCE_DEBUG
  261. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  262. activeTimers.add (this);
  263. #endif
  264. }
  265. Timer::~Timer()
  266. {
  267. stopTimer();
  268. #if JUCE_DEBUG
  269. activeTimers.removeValue (this);
  270. #endif
  271. }
  272. void Timer::startTimer (const int interval) noexcept
  273. {
  274. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  275. #if JUCE_DEBUG
  276. // this isn't a valid object! Your timer might be a dangling pointer or something..
  277. jassert (activeTimers.contains (this));
  278. #endif
  279. if (periodMs == 0)
  280. {
  281. countdownMs = interval;
  282. periodMs = jmax (1, interval);
  283. TimerThread::add (this);
  284. }
  285. else
  286. {
  287. TimerThread::resetCounter (this, interval);
  288. }
  289. }
  290. void Timer::stopTimer() noexcept
  291. {
  292. const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
  293. #if JUCE_DEBUG
  294. // this isn't a valid object! Your timer might be a dangling pointer or something..
  295. jassert (activeTimers.contains (this));
  296. #endif
  297. if (periodMs > 0)
  298. {
  299. TimerThread::remove (this);
  300. periodMs = 0;
  301. }
  302. }
  303. void JUCE_CALLTYPE Timer::callPendingTimersSynchronously()
  304. {
  305. if (TimerThread::instance != nullptr)
  306. TimerThread::instance->callTimersSynchronously();
  307. }