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.

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