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.

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