1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
class Timer::TimerThread : private Thread,
private DeletedAtShutdown,
private AsyncUpdater
{
public:
using LockType = CriticalSection; // (mysteriously, using a SpinLock here causes problems on some XP machines..)
TimerThread() : Thread ("JUCE Timer")
{
timers.reserve (32);
triggerAsyncUpdate();
}
~TimerThread() override
{
signalThreadShouldExit();
callbackArrived.signal();
stopThread (4000);
jassert (instance == this || instance == nullptr);
if (instance == this)
instance = nullptr;
}
void run() override
{
auto lastTime = Time::getMillisecondCounter();
ReferenceCountedObjectPtr<CallTimersMessage> messageToSend (new CallTimersMessage());
while (! threadShouldExit())
{
auto now = Time::getMillisecondCounter();
auto elapsed = (int) (now >= lastTime ? (now - lastTime)
: (std::numeric_limits<uint32>::max() - (lastTime - now)));
lastTime = now;
auto timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
if (timeUntilFirstTimer <= 0)
{
if (callbackArrived.wait (0))
{
// already a message in flight - do nothing..
}
else
{
messageToSend->post();
if (! callbackArrived.wait (300))
{
// Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
// when the app has a modal loop), so this is how long to wait before assuming the
// message has been lost and trying again.
messageToSend->post();
}
continue;
}
}
// don't wait for too long because running this loop also helps keep the
// Time::getApproximateMillisecondTimer value stay up-to-date
wait (jlimit (1, 100, timeUntilFirstTimer));
}
}
void callTimers()
{
auto timeout = Time::getMillisecondCounter() + 100;
const LockType::ScopedLockType sl (lock);
while (! timers.empty())
{
auto& first = timers.front();
if (first.countdownMs > 0)
break;
auto* timer = first.timer;
first.countdownMs = timer->timerPeriodMs;
shuffleTimerBackInQueue (0);
notify();
const LockType::ScopedUnlockType ul (lock);
JUCE_TRY
{
timer->timerCallback();
}
JUCE_CATCH_EXCEPTION
// avoid getting stuck in a loop if a timer callback repeatedly takes too long
if (Time::getMillisecondCounter() > timeout)
break;
}
callbackArrived.signal();
}
void callTimersSynchronously()
{
if (! isThreadRunning())
{
// (This is relied on by some plugins in cases where the MM has
// had to restart and the async callback never started)
cancelPendingUpdate();
triggerAsyncUpdate();
}
callTimers();
}
static inline void add (Timer* tim) noexcept
{
if (instance == nullptr)
instance = new TimerThread();
instance->addTimer (tim);
}
static inline void remove (Timer* tim) noexcept
{
if (instance != nullptr)
instance->removeTimer (tim);
}
static inline void resetCounter (Timer* tim) noexcept
{
if (instance != nullptr)
instance->resetTimerCounter (tim);
}
static TimerThread* instance;
static LockType lock;
private:
struct TimerCountdown
{
Timer* timer;
int countdownMs;
};
std::vector<TimerCountdown> timers;
WaitableEvent callbackArrived;
struct CallTimersMessage : public MessageManager::MessageBase
{
CallTimersMessage() {}
void messageCallback() override
{
if (instance != nullptr)
instance->callTimers();
}
};
//==============================================================================
void addTimer (Timer* t)
{
// Trying to add a timer that's already here - shouldn't get to this point,
// so if you get this assertion, let me know!
jassert (std::find_if (timers.begin(), timers.end(),
[t](TimerCountdown i) { return i.timer == t; }) == timers.end());
auto pos = timers.size();
timers.push_back ({ t, t->timerPeriodMs });
t->positionInQueue = pos;
shuffleTimerForwardInQueue (pos);
notify();
}
void removeTimer (Timer* t)
{
auto pos = t->positionInQueue;
auto lastIndex = timers.size() - 1;
jassert (pos <= lastIndex);
jassert (timers[pos].timer == t);
for (auto i = pos; i < lastIndex; ++i)
{
timers[i] = timers[i + 1];
timers[i].timer->positionInQueue = i;
}
timers.pop_back();
}
void resetTimerCounter (Timer* t) noexcept
{
auto pos = t->positionInQueue;
jassert (pos < timers.size());
jassert (timers[pos].timer == t);
auto lastCountdown = timers[pos].countdownMs;
auto newCountdown = t->timerPeriodMs;
if (newCountdown != lastCountdown)
{
timers[pos].countdownMs = newCountdown;
if (newCountdown > lastCountdown)
shuffleTimerBackInQueue (pos);
else
shuffleTimerForwardInQueue (pos);
notify();
}
}
void shuffleTimerBackInQueue (size_t pos)
{
auto numTimers = timers.size();
if (pos < numTimers - 1)
{
auto t = timers[pos];
for (;;)
{
auto next = pos + 1;
if (next == numTimers || timers[next].countdownMs >= t.countdownMs)
break;
timers[pos] = timers[next];
timers[pos].timer->positionInQueue = pos;
++pos;
}
timers[pos] = t;
t.timer->positionInQueue = pos;
}
}
void shuffleTimerForwardInQueue (size_t pos)
{
if (pos > 0)
{
auto t = timers[pos];
while (pos > 0)
{
auto& prev = timers[(size_t) pos - 1];
if (prev.countdownMs <= t.countdownMs)
break;
timers[pos] = prev;
timers[pos].timer->positionInQueue = pos;
--pos;
}
timers[pos] = t;
t.timer->positionInQueue = pos;
}
}
int getTimeUntilFirstTimer (int numMillisecsElapsed)
{
const LockType::ScopedLockType sl (lock);
if (timers.empty())
return 1000;
for (auto& t : timers)
t.countdownMs -= numMillisecsElapsed;
return timers.front().countdownMs;
}
void handleAsyncUpdate() override
{
startThread (7);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TimerThread)
};
Timer::TimerThread* Timer::TimerThread::instance = nullptr;
Timer::TimerThread::LockType Timer::TimerThread::lock;
//==============================================================================
Timer::Timer() noexcept {}
Timer::Timer (const Timer&) noexcept {}
Timer::~Timer()
{
stopTimer();
}
void Timer::startTimer (int interval) noexcept
{
// If you're calling this before (or after) the MessageManager is
// running, then you're not going to get any timer callbacks!
JUCE_ASSERT_MESSAGE_MANAGER_EXISTS
const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
bool wasStopped = (timerPeriodMs == 0);
timerPeriodMs = jmax (1, interval);
if (wasStopped)
TimerThread::add (this);
else
TimerThread::resetCounter (this);
}
void Timer::startTimerHz (int timerFrequencyHz) noexcept
{
if (timerFrequencyHz > 0)
startTimer (1000 / timerFrequencyHz);
else
stopTimer();
}
void Timer::stopTimer() noexcept
{
const TimerThread::LockType::ScopedLockType sl (TimerThread::lock);
if (timerPeriodMs > 0)
{
TimerThread::remove (this);
timerPeriodMs = 0;
}
}
void JUCE_CALLTYPE Timer::callPendingTimersSynchronously()
{
if (TimerThread::instance != nullptr)
TimerThread::instance->callTimersSynchronously();
}
struct LambdaInvoker : private Timer
{
LambdaInvoker (int milliseconds, std::function<void()> f) : function (f)
{
startTimer (milliseconds);
}
void timerCallback() override
{
auto f = function;
delete this;
f();
}
std::function<void()> function;
JUCE_DECLARE_NON_COPYABLE (LambdaInvoker)
};
void JUCE_CALLTYPE Timer::callAfterDelay (int milliseconds, std::function<void()> f)
{
new LambdaInvoker (milliseconds, f);
}
} // namespace juce
|