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.

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