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.

447 lines
15KB

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