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.

516 lines
14KB

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