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.

448 lines
15KB

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