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.

461 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. namespace TimeHelpers
  22. {
  23. static struct tm millisToLocal (const int64 millis) noexcept
  24. {
  25. struct tm result;
  26. const int64 seconds = millis / 1000;
  27. if (seconds < 86400LL || seconds >= 2145916800LL)
  28. {
  29. // use extended maths for dates beyond 1970 to 2037..
  30. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  31. const int64 jdm = seconds + timeZoneAdjustment + 210866803200LL;
  32. const int days = (int) (jdm / 86400LL);
  33. const int a = 32044 + days;
  34. const int b = (4 * a + 3) / 146097;
  35. const int c = a - (b * 146097) / 4;
  36. const int d = (4 * c + 3) / 1461;
  37. const int e = c - (d * 1461) / 4;
  38. const int m = (5 * e + 2) / 153;
  39. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  40. result.tm_mon = m + 2 - 12 * (m / 10);
  41. result.tm_year = b * 100 + d - 6700 + (m / 10);
  42. result.tm_wday = (days + 1) % 7;
  43. result.tm_yday = -1;
  44. int t = (int) (jdm % 86400LL);
  45. result.tm_hour = t / 3600;
  46. t %= 3600;
  47. result.tm_min = t / 60;
  48. result.tm_sec = t % 60;
  49. result.tm_isdst = -1;
  50. }
  51. else
  52. {
  53. time_t now = static_cast<time_t> (seconds);
  54. #if JUCE_WINDOWS && JUCE_MINGW
  55. return *localtime (&now);
  56. #elif JUCE_WINDOWS
  57. if (now >= 0 && now <= 0x793406fff)
  58. localtime_s (&result, &now);
  59. else
  60. zerostruct (result);
  61. #else
  62. localtime_r (&now, &result); // more thread-safe
  63. #endif
  64. }
  65. return result;
  66. }
  67. static int extendedModulo (const int64 value, const int modulo) noexcept
  68. {
  69. return (int) (value >= 0 ? (value % modulo)
  70. : (value - ((value / modulo) + 1) * modulo));
  71. }
  72. static inline String formatString (const String& format, const struct tm* const tm)
  73. {
  74. #if JUCE_ANDROID
  75. typedef CharPointer_UTF8 StringType;
  76. #elif JUCE_WINDOWS
  77. typedef CharPointer_UTF16 StringType;
  78. #else
  79. typedef CharPointer_UTF32 StringType;
  80. #endif
  81. for (size_t bufferSize = 256; ; bufferSize += 256)
  82. {
  83. HeapBlock<StringType::CharType> buffer (bufferSize);
  84. #if JUCE_ANDROID
  85. const size_t numChars = strftime (buffer, bufferSize - 1, format.toUTF8(), tm);
  86. #elif JUCE_WINDOWS
  87. const size_t numChars = wcsftime (buffer, bufferSize - 1, format.toWideCharPointer(), tm);
  88. #else
  89. const size_t numChars = wcsftime (buffer, bufferSize - 1, format.toUTF32(), tm);
  90. #endif
  91. if (numChars > 0 || format.isEmpty())
  92. return String (StringType (buffer),
  93. StringType (buffer) + (int) numChars);
  94. }
  95. }
  96. static uint32 lastMSCounterValue = 0;
  97. }
  98. //==============================================================================
  99. Time::Time() noexcept
  100. : millisSinceEpoch (0)
  101. {
  102. }
  103. Time::Time (const Time& other) noexcept
  104. : millisSinceEpoch (other.millisSinceEpoch)
  105. {
  106. }
  107. Time::Time (const int64 ms) noexcept
  108. : millisSinceEpoch (ms)
  109. {
  110. }
  111. Time::Time (const int year,
  112. const int month,
  113. const int day,
  114. const int hours,
  115. const int minutes,
  116. const int seconds,
  117. const int milliseconds,
  118. const bool useLocalTime) noexcept
  119. {
  120. jassert (year > 100); // year must be a 4-digit version
  121. if (year < 1971 || year >= 2038 || ! useLocalTime)
  122. {
  123. // use extended maths for dates beyond 1970 to 2037..
  124. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  125. : 0;
  126. const int a = (13 - month) / 12;
  127. const int y = year + 4800 - a;
  128. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  129. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  130. - 32045;
  131. const int64 s = ((int64) jd) * 86400LL - 210866803200LL;
  132. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  133. + milliseconds;
  134. }
  135. else
  136. {
  137. struct tm t;
  138. t.tm_year = year - 1900;
  139. t.tm_mon = month;
  140. t.tm_mday = day;
  141. t.tm_hour = hours;
  142. t.tm_min = minutes;
  143. t.tm_sec = seconds;
  144. t.tm_isdst = -1;
  145. millisSinceEpoch = 1000 * (int64) mktime (&t);
  146. if (millisSinceEpoch < 0)
  147. millisSinceEpoch = 0;
  148. else
  149. millisSinceEpoch += milliseconds;
  150. }
  151. }
  152. Time::~Time() noexcept
  153. {
  154. }
  155. Time& Time::operator= (const Time& other) noexcept
  156. {
  157. millisSinceEpoch = other.millisSinceEpoch;
  158. return *this;
  159. }
  160. //==============================================================================
  161. int64 Time::currentTimeMillis() noexcept
  162. {
  163. #if JUCE_WINDOWS && ! JUCE_MINGW
  164. struct _timeb t;
  165. _ftime_s (&t);
  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. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  265. return TimeHelpers::formatString (format, &t);
  266. }
  267. //==============================================================================
  268. int Time::getYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900; }
  269. int Time::getMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon; }
  270. int Time::getDayOfYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_yday; }
  271. int Time::getDayOfMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday; }
  272. int Time::getDayOfWeek() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday; }
  273. int Time::getHours() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour; }
  274. int Time::getMinutes() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min; }
  275. int Time::getSeconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60); }
  276. int Time::getMilliseconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch, 1000); }
  277. int Time::getHoursInAmPmFormat() const noexcept
  278. {
  279. const int hours = getHours();
  280. if (hours == 0) return 12;
  281. if (hours <= 12) return hours;
  282. return hours - 12;
  283. }
  284. bool Time::isAfternoon() const noexcept
  285. {
  286. return getHours() >= 12;
  287. }
  288. bool Time::isDaylightSavingTime() const noexcept
  289. {
  290. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  291. }
  292. String Time::getTimeZone() const noexcept
  293. {
  294. String zone[2];
  295. #if JUCE_MSVC
  296. _tzset();
  297. for (int i = 0; i < 2; ++i)
  298. {
  299. char name[128] = { 0 };
  300. size_t length;
  301. _get_tzname (&length, name, 127, i);
  302. zone[i] = name;
  303. }
  304. #else
  305. #if JUCE_MINGW
  306. #warning "Can't find a replacement for tzset on mingw - ideas welcome!"
  307. #else
  308. tzset();
  309. #endif
  310. const char** const zonePtr = (const char**) tzname;
  311. zone[0] = zonePtr[0];
  312. zone[1] = zonePtr[1];
  313. #endif
  314. if (isDaylightSavingTime())
  315. {
  316. zone[0] = zone[1];
  317. if (zone[0].length() > 3
  318. && zone[0].containsIgnoreCase ("daylight")
  319. && zone[0].contains ("GMT"))
  320. zone[0] = "BST";
  321. }
  322. return zone[0].substring (0, 3);
  323. }
  324. String Time::getMonthName (const bool threeLetterVersion) const
  325. {
  326. return getMonthName (getMonth(), threeLetterVersion);
  327. }
  328. String Time::getWeekdayName (const bool threeLetterVersion) const
  329. {
  330. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  331. }
  332. static const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  333. static const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  334. String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  335. {
  336. monthNumber %= 12;
  337. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  338. : longMonthNames [monthNumber]);
  339. }
  340. String Time::getWeekdayName (int day, const bool threeLetterVersion)
  341. {
  342. static const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  343. static const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  344. day %= 7;
  345. return TRANS (threeLetterVersion ? shortDayNames [day]
  346. : longDayNames [day]);
  347. }
  348. //==============================================================================
  349. Time& Time::operator+= (RelativeTime delta) noexcept { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  350. Time& Time::operator-= (RelativeTime delta) noexcept { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  351. Time operator+ (Time time, RelativeTime delta) noexcept { Time t (time); return t += delta; }
  352. Time operator- (Time time, RelativeTime delta) noexcept { Time t (time); return t -= delta; }
  353. Time operator+ (RelativeTime delta, Time time) noexcept { Time t (time); return t += delta; }
  354. const RelativeTime operator- (Time time1, Time time2) noexcept { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  355. bool operator== (Time time1, Time time2) noexcept { return time1.toMilliseconds() == time2.toMilliseconds(); }
  356. bool operator!= (Time time1, Time time2) noexcept { return time1.toMilliseconds() != time2.toMilliseconds(); }
  357. bool operator< (Time time1, Time time2) noexcept { return time1.toMilliseconds() < time2.toMilliseconds(); }
  358. bool operator> (Time time1, Time time2) noexcept { return time1.toMilliseconds() > time2.toMilliseconds(); }
  359. bool operator<= (Time time1, Time time2) noexcept { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  360. bool operator>= (Time time1, Time time2) noexcept { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  361. static int getMonthNumberForCompileDate (const String& m) noexcept
  362. {
  363. for (int i = 0; i < 12; ++i)
  364. if (m.equalsIgnoreCase (shortMonthNames[i]))
  365. return i;
  366. // If you hit this because your compiler has a non-standard __DATE__ format,
  367. // let me know so we can add support for it!
  368. jassertfalse;
  369. return 0;
  370. }
  371. Time Time::getCompilationDate()
  372. {
  373. StringArray dateTokens;
  374. dateTokens.addTokens (__DATE__, true);
  375. dateTokens.removeEmptyStrings (true);
  376. return Time (dateTokens[2].getIntValue(),
  377. getMonthNumberForCompileDate (dateTokens[0]),
  378. dateTokens[1].getIntValue(), 12, 0);
  379. }