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.

517 lines
16KB

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