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.

485 lines
16KB

  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. #if JUCE_MSVC
  19. #pragma warning (push)
  20. #pragma warning (disable: 4514)
  21. #endif
  22. #if JUCE_MSVC
  23. #pragma warning (pop)
  24. #ifdef _INC_TIME_INL
  25. #define USE_NEW_SECURE_TIME_FNS
  26. #endif
  27. #endif
  28. //==============================================================================
  29. namespace TimeHelpers
  30. {
  31. struct tm millisToLocal (const int64 millis) noexcept
  32. {
  33. struct tm result;
  34. const int64 seconds = millis / 1000;
  35. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  36. {
  37. // use extended maths for dates beyond 1970 to 2037..
  38. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  39. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  40. const int days = (int) (jdm / literal64bit (86400));
  41. const int a = 32044 + days;
  42. const int b = (4 * a + 3) / 146097;
  43. const int c = a - (b * 146097) / 4;
  44. const int d = (4 * c + 3) / 1461;
  45. const int e = c - (d * 1461) / 4;
  46. const int m = (5 * e + 2) / 153;
  47. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  48. result.tm_mon = m + 2 - 12 * (m / 10);
  49. result.tm_year = b * 100 + d - 6700 + (m / 10);
  50. result.tm_wday = (days + 1) % 7;
  51. result.tm_yday = -1;
  52. int t = (int) (jdm % literal64bit (86400));
  53. result.tm_hour = t / 3600;
  54. t %= 3600;
  55. result.tm_min = t / 60;
  56. result.tm_sec = t % 60;
  57. result.tm_isdst = -1;
  58. }
  59. else
  60. {
  61. time_t now = static_cast <time_t> (seconds);
  62. #if JUCE_WINDOWS
  63. #ifdef USE_NEW_SECURE_TIME_FNS
  64. if (now >= 0 && now <= 0x793406fff)
  65. localtime_s (&result, &now);
  66. else
  67. zerostruct (result);
  68. #else
  69. result = *localtime (&now);
  70. #endif
  71. #else
  72. localtime_r (&now, &result); // more thread-safe
  73. #endif
  74. }
  75. return result;
  76. }
  77. int extendedModulo (const int64 value, const int modulo) noexcept
  78. {
  79. return (int) (value >= 0 ? (value % modulo)
  80. : (value - ((value / modulo) + 1) * modulo));
  81. }
  82. int doFTime (CharPointer_UTF32 dest, const size_t maxChars, const String& format, const struct tm* const tm) noexcept
  83. {
  84. #if JUCE_ANDROID
  85. HeapBlock <char> tempDest;
  86. tempDest.calloc (maxChars + 2);
  87. const int result = (int) strftime (tempDest, maxChars, format.toUTF8(), tm);
  88. if (result > 0)
  89. dest.writeAll (CharPointer_UTF8 (tempDest.getData()));
  90. return result;
  91. #elif JUCE_WINDOWS
  92. HeapBlock <wchar_t> tempDest;
  93. tempDest.calloc (maxChars + 2);
  94. const int result = (int) wcsftime (tempDest, maxChars, format.toWideCharPointer(), tm);
  95. if (result > 0)
  96. dest.writeAll (CharPointer_UTF16 (tempDest.getData()));
  97. return result;
  98. #else
  99. return (int) wcsftime (dest.getAddress(), maxChars, format.toUTF32(), tm);
  100. #endif
  101. }
  102. static uint32 lastMSCounterValue = 0;
  103. }
  104. //==============================================================================
  105. Time::Time() noexcept
  106. : millisSinceEpoch (0)
  107. {
  108. }
  109. Time::Time (const Time& other) noexcept
  110. : millisSinceEpoch (other.millisSinceEpoch)
  111. {
  112. }
  113. Time::Time (const int64 ms) noexcept
  114. : millisSinceEpoch (ms)
  115. {
  116. }
  117. Time::Time (const int year,
  118. const int month,
  119. const int day,
  120. const int hours,
  121. const int minutes,
  122. const int seconds,
  123. const int milliseconds,
  124. const bool useLocalTime) noexcept
  125. {
  126. jassert (year > 100); // year must be a 4-digit version
  127. if (year < 1971 || year >= 2038 || ! useLocalTime)
  128. {
  129. // use extended maths for dates beyond 1970 to 2037..
  130. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  131. : 0;
  132. const int a = (13 - month) / 12;
  133. const int y = year + 4800 - a;
  134. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  135. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  136. - 32045;
  137. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  138. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  139. + milliseconds;
  140. }
  141. else
  142. {
  143. struct tm t;
  144. t.tm_year = year - 1900;
  145. t.tm_mon = month;
  146. t.tm_mday = day;
  147. t.tm_hour = hours;
  148. t.tm_min = minutes;
  149. t.tm_sec = seconds;
  150. t.tm_isdst = -1;
  151. millisSinceEpoch = 1000 * (int64) mktime (&t);
  152. if (millisSinceEpoch < 0)
  153. millisSinceEpoch = 0;
  154. else
  155. millisSinceEpoch += milliseconds;
  156. }
  157. }
  158. Time::~Time() noexcept
  159. {
  160. }
  161. Time& Time::operator= (const Time& other) noexcept
  162. {
  163. millisSinceEpoch = other.millisSinceEpoch;
  164. return *this;
  165. }
  166. //==============================================================================
  167. int64 Time::currentTimeMillis() noexcept
  168. {
  169. static uint32 lastCounterResult = 0xffffffff;
  170. static int64 correction = 0;
  171. const uint32 now = getMillisecondCounter();
  172. // check the counter hasn't wrapped (also triggered the first time this function is called)
  173. if (now < lastCounterResult)
  174. {
  175. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  176. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  177. {
  178. // get the time once using normal library calls, and store the difference needed to
  179. // turn the millisecond counter into a real time.
  180. #if JUCE_WINDOWS
  181. struct _timeb t;
  182. #ifdef USE_NEW_SECURE_TIME_FNS
  183. _ftime_s (&t);
  184. #else
  185. _ftime (&t);
  186. #endif
  187. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  188. #else
  189. struct timeval tv;
  190. struct timezone tz;
  191. gettimeofday (&tv, &tz);
  192. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  193. #endif
  194. }
  195. }
  196. lastCounterResult = now;
  197. return correction + now;
  198. }
  199. //==============================================================================
  200. uint32 juce_millisecondsSinceStartup() noexcept;
  201. uint32 Time::getMillisecondCounter() noexcept
  202. {
  203. const uint32 now = juce_millisecondsSinceStartup();
  204. if (now < TimeHelpers::lastMSCounterValue)
  205. {
  206. // in multi-threaded apps this might be called concurrently, so
  207. // make sure that our last counter value only increases and doesn't
  208. // go backwards..
  209. if (now < TimeHelpers::lastMSCounterValue - 1000)
  210. TimeHelpers::lastMSCounterValue = now;
  211. }
  212. else
  213. {
  214. TimeHelpers::lastMSCounterValue = now;
  215. }
  216. return now;
  217. }
  218. uint32 Time::getApproximateMillisecondCounter() noexcept
  219. {
  220. if (TimeHelpers::lastMSCounterValue == 0)
  221. getMillisecondCounter();
  222. return TimeHelpers::lastMSCounterValue;
  223. }
  224. void Time::waitForMillisecondCounter (const uint32 targetTime) noexcept
  225. {
  226. for (;;)
  227. {
  228. const uint32 now = getMillisecondCounter();
  229. if (now >= targetTime)
  230. break;
  231. const int toWait = (int) (targetTime - now);
  232. if (toWait > 2)
  233. {
  234. Thread::sleep (jmin (20, toWait >> 1));
  235. }
  236. else
  237. {
  238. // xxx should consider using mutex_pause on the mac as it apparently
  239. // makes it seem less like a spinlock and avoids lowering the thread pri.
  240. for (int i = 10; --i >= 0;)
  241. Thread::yield();
  242. }
  243. }
  244. }
  245. //==============================================================================
  246. double Time::highResolutionTicksToSeconds (const int64 ticks) noexcept
  247. {
  248. return ticks / (double) getHighResolutionTicksPerSecond();
  249. }
  250. int64 Time::secondsToHighResolutionTicks (const double seconds) noexcept
  251. {
  252. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  253. }
  254. //==============================================================================
  255. Time JUCE_CALLTYPE Time::getCurrentTime() noexcept
  256. {
  257. return Time (currentTimeMillis());
  258. }
  259. //==============================================================================
  260. String Time::toString (const bool includeDate,
  261. const bool includeTime,
  262. const bool includeSeconds,
  263. const bool use24HourClock) const noexcept
  264. {
  265. String result;
  266. if (includeDate)
  267. {
  268. result << getDayOfMonth() << ' '
  269. << getMonthName (true) << ' '
  270. << getYear();
  271. if (includeTime)
  272. result << ' ';
  273. }
  274. if (includeTime)
  275. {
  276. const int mins = getMinutes();
  277. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  278. << (mins < 10 ? ":0" : ":") << mins;
  279. if (includeSeconds)
  280. {
  281. const int secs = getSeconds();
  282. result << (secs < 10 ? ":0" : ":") << secs;
  283. }
  284. if (! use24HourClock)
  285. result << (isAfternoon() ? "pm" : "am");
  286. }
  287. return result.trimEnd();
  288. }
  289. String Time::formatted (const String& format) const
  290. {
  291. size_t bufferSize = 128;
  292. HeapBlock<juce_wchar> buffer (128);
  293. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  294. while (TimeHelpers::doFTime (CharPointer_UTF32 (buffer.getData()), bufferSize, format, &t) <= 0)
  295. {
  296. bufferSize += 128;
  297. buffer.malloc (bufferSize);
  298. }
  299. return CharPointer_UTF32 (buffer.getData());
  300. }
  301. //==============================================================================
  302. int Time::getYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900; }
  303. int Time::getMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon; }
  304. int Time::getDayOfYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_yday; }
  305. int Time::getDayOfMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday; }
  306. int Time::getDayOfWeek() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday; }
  307. int Time::getHours() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour; }
  308. int Time::getMinutes() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min; }
  309. int Time::getSeconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60); }
  310. int Time::getMilliseconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch, 1000); }
  311. int Time::getHoursInAmPmFormat() const noexcept
  312. {
  313. const int hours = getHours();
  314. if (hours == 0)
  315. return 12;
  316. else if (hours <= 12)
  317. return hours;
  318. else
  319. return hours - 12;
  320. }
  321. bool Time::isAfternoon() const noexcept
  322. {
  323. return getHours() >= 12;
  324. }
  325. bool Time::isDaylightSavingTime() const noexcept
  326. {
  327. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  328. }
  329. String Time::getTimeZone() const noexcept
  330. {
  331. String zone[2];
  332. #if JUCE_WINDOWS
  333. _tzset();
  334. #ifdef USE_NEW_SECURE_TIME_FNS
  335. for (int i = 0; i < 2; ++i)
  336. {
  337. char name[128] = { 0 };
  338. size_t length;
  339. _get_tzname (&length, name, 127, i);
  340. zone[i] = name;
  341. }
  342. #else
  343. const char** const zonePtr = (const char**) _tzname;
  344. zone[0] = zonePtr[0];
  345. zone[1] = zonePtr[1];
  346. #endif
  347. #else
  348. tzset();
  349. const char** const zonePtr = (const char**) tzname;
  350. zone[0] = zonePtr[0];
  351. zone[1] = zonePtr[1];
  352. #endif
  353. if (isDaylightSavingTime())
  354. {
  355. zone[0] = zone[1];
  356. if (zone[0].length() > 3
  357. && zone[0].containsIgnoreCase ("daylight")
  358. && zone[0].contains ("GMT"))
  359. zone[0] = "BST";
  360. }
  361. return zone[0].substring (0, 3);
  362. }
  363. String Time::getMonthName (const bool threeLetterVersion) const
  364. {
  365. return getMonthName (getMonth(), threeLetterVersion);
  366. }
  367. String Time::getWeekdayName (const bool threeLetterVersion) const
  368. {
  369. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  370. }
  371. String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  372. {
  373. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  374. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  375. monthNumber %= 12;
  376. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  377. : longMonthNames [monthNumber]);
  378. }
  379. String Time::getWeekdayName (int day, const bool threeLetterVersion)
  380. {
  381. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  382. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  383. day %= 7;
  384. return TRANS (threeLetterVersion ? shortDayNames [day]
  385. : longDayNames [day]);
  386. }
  387. //==============================================================================
  388. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  389. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  390. Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  391. Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  392. Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  393. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  394. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  395. bool operator!= (const Time& time1, const Time& time2) { return time1.toMilliseconds() != time2.toMilliseconds(); }
  396. bool operator< (const Time& time1, const Time& time2) { return time1.toMilliseconds() < time2.toMilliseconds(); }
  397. bool operator> (const Time& time1, const Time& time2) { return time1.toMilliseconds() > time2.toMilliseconds(); }
  398. bool operator<= (const Time& time1, const Time& time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  399. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }