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.

745 lines
19KB

  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. /*
  19. This file contains posix routines that are common to both the Linux and Mac builds.
  20. It gets included directly in the cpp files for these platforms.
  21. */
  22. //==============================================================================
  23. CriticalSection::CriticalSection() throw()
  24. {
  25. pthread_mutexattr_t atts;
  26. pthread_mutexattr_init (&atts);
  27. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  28. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  29. pthread_mutex_init (&internal, &atts);
  30. }
  31. CriticalSection::~CriticalSection() throw()
  32. {
  33. pthread_mutex_destroy (&internal);
  34. }
  35. void CriticalSection::enter() const throw()
  36. {
  37. pthread_mutex_lock (&internal);
  38. }
  39. bool CriticalSection::tryEnter() const throw()
  40. {
  41. return pthread_mutex_trylock (&internal) == 0;
  42. }
  43. void CriticalSection::exit() const throw()
  44. {
  45. pthread_mutex_unlock (&internal);
  46. }
  47. //==============================================================================
  48. class WaitableEventImpl
  49. {
  50. public:
  51. WaitableEventImpl (const bool manualReset_)
  52. : triggered (false),
  53. manualReset (manualReset_)
  54. {
  55. pthread_cond_init (&condition, 0);
  56. pthread_mutexattr_t atts;
  57. pthread_mutexattr_init (&atts);
  58. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  59. pthread_mutex_init (&mutex, &atts);
  60. }
  61. ~WaitableEventImpl()
  62. {
  63. pthread_cond_destroy (&condition);
  64. pthread_mutex_destroy (&mutex);
  65. }
  66. bool wait (const int timeOutMillisecs) throw()
  67. {
  68. pthread_mutex_lock (&mutex);
  69. if (! triggered)
  70. {
  71. if (timeOutMillisecs < 0)
  72. {
  73. do
  74. {
  75. pthread_cond_wait (&condition, &mutex);
  76. }
  77. while (! triggered);
  78. }
  79. else
  80. {
  81. struct timeval now;
  82. gettimeofday (&now, 0);
  83. struct timespec time;
  84. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  85. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  86. if (time.tv_nsec >= 1000000000)
  87. {
  88. time.tv_nsec -= 1000000000;
  89. time.tv_sec++;
  90. }
  91. do
  92. {
  93. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  94. {
  95. pthread_mutex_unlock (&mutex);
  96. return false;
  97. }
  98. }
  99. while (! triggered);
  100. }
  101. }
  102. if (! manualReset)
  103. triggered = false;
  104. pthread_mutex_unlock (&mutex);
  105. return true;
  106. }
  107. void signal() throw()
  108. {
  109. pthread_mutex_lock (&mutex);
  110. triggered = true;
  111. pthread_cond_broadcast (&condition);
  112. pthread_mutex_unlock (&mutex);
  113. }
  114. void reset() throw()
  115. {
  116. pthread_mutex_lock (&mutex);
  117. triggered = false;
  118. pthread_mutex_unlock (&mutex);
  119. }
  120. private:
  121. pthread_cond_t condition;
  122. pthread_mutex_t mutex;
  123. bool triggered;
  124. const bool manualReset;
  125. WaitableEventImpl (const WaitableEventImpl&);
  126. WaitableEventImpl& operator= (const WaitableEventImpl&);
  127. };
  128. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  129. : internal (new WaitableEventImpl (manualReset))
  130. {
  131. }
  132. WaitableEvent::~WaitableEvent() throw()
  133. {
  134. delete static_cast <WaitableEventImpl*> (internal);
  135. }
  136. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  137. {
  138. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  139. }
  140. void WaitableEvent::signal() const throw()
  141. {
  142. static_cast <WaitableEventImpl*> (internal)->signal();
  143. }
  144. void WaitableEvent::reset() const throw()
  145. {
  146. static_cast <WaitableEventImpl*> (internal)->reset();
  147. }
  148. //==============================================================================
  149. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  150. {
  151. struct timespec time;
  152. time.tv_sec = millisecs / 1000;
  153. time.tv_nsec = (millisecs % 1000) * 1000000;
  154. nanosleep (&time, 0);
  155. }
  156. //==============================================================================
  157. const juce_wchar File::separator = '/';
  158. const String File::separatorString ("/");
  159. //==============================================================================
  160. const File File::getCurrentWorkingDirectory()
  161. {
  162. HeapBlock<char> heapBuffer;
  163. char localBuffer [1024];
  164. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  165. int bufferSize = 4096;
  166. while (cwd == 0 && errno == ERANGE)
  167. {
  168. heapBuffer.malloc (bufferSize);
  169. cwd = getcwd (heapBuffer, bufferSize - 1);
  170. bufferSize += 1024;
  171. }
  172. return File (String::fromUTF8 (cwd));
  173. }
  174. bool File::setAsCurrentWorkingDirectory() const
  175. {
  176. return chdir (getFullPathName().toUTF8()) == 0;
  177. }
  178. //==============================================================================
  179. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  180. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  181. #else
  182. typedef struct stat juce_statStruct;
  183. #endif
  184. static bool juce_stat (const String& fileName, juce_statStruct& info)
  185. {
  186. return fileName.isNotEmpty()
  187. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  188. && (stat64 (fileName.toUTF8(), &info) == 0);
  189. #else
  190. && (stat (fileName.toUTF8(), &info) == 0);
  191. #endif
  192. }
  193. bool File::isDirectory() const
  194. {
  195. juce_statStruct info;
  196. return fullPath.isEmpty()
  197. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  198. }
  199. bool File::exists() const
  200. {
  201. return fullPath.isNotEmpty()
  202. && access (fullPath.toUTF8(), F_OK) == 0;
  203. }
  204. bool File::existsAsFile() const
  205. {
  206. return exists() && ! isDirectory();
  207. }
  208. int64 File::getSize() const
  209. {
  210. juce_statStruct info;
  211. return juce_stat (fullPath, info) ? info.st_size : 0;
  212. }
  213. //==============================================================================
  214. bool File::hasWriteAccess() const
  215. {
  216. if (exists())
  217. return access (fullPath.toUTF8(), W_OK) == 0;
  218. if ((! isDirectory()) && fullPath.containsChar (separator))
  219. return getParentDirectory().hasWriteAccess();
  220. return false;
  221. }
  222. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223. {
  224. juce_statStruct info;
  225. if (! juce_stat (fullPath, info))
  226. return false;
  227. info.st_mode &= 0777; // Just permissions
  228. if (shouldBeReadOnly)
  229. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  230. else
  231. // Give everybody write permission?
  232. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  233. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  234. }
  235. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  236. {
  237. modificationTime = 0;
  238. accessTime = 0;
  239. creationTime = 0;
  240. juce_statStruct info;
  241. if (juce_stat (fullPath, info))
  242. {
  243. modificationTime = (int64) info.st_mtime * 1000;
  244. accessTime = (int64) info.st_atime * 1000;
  245. creationTime = (int64) info.st_ctime * 1000;
  246. }
  247. }
  248. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  249. {
  250. struct utimbuf times;
  251. times.actime = (time_t) (accessTime / 1000);
  252. times.modtime = (time_t) (modificationTime / 1000);
  253. return utime (fullPath.toUTF8(), &times) == 0;
  254. }
  255. bool File::deleteFile() const
  256. {
  257. if (! exists())
  258. return true;
  259. else if (isDirectory())
  260. return rmdir (fullPath.toUTF8()) == 0;
  261. else
  262. return remove (fullPath.toUTF8()) == 0;
  263. }
  264. bool File::moveInternal (const File& dest) const
  265. {
  266. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  267. return true;
  268. if (hasWriteAccess() && copyInternal (dest))
  269. {
  270. if (deleteFile())
  271. return true;
  272. dest.deleteFile();
  273. }
  274. return false;
  275. }
  276. void File::createDirectoryInternal (const String& fileName) const
  277. {
  278. mkdir (fileName.toUTF8(), 0777);
  279. }
  280. //==============================================================================
  281. int64 juce_fileSetPosition (void* handle, int64 pos)
  282. {
  283. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  284. return pos;
  285. return -1;
  286. }
  287. void FileInputStream::openHandle()
  288. {
  289. totalSize = file.getSize();
  290. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  291. if (f != -1)
  292. fileHandle = (void*) f;
  293. }
  294. void FileInputStream::closeHandle()
  295. {
  296. if (fileHandle != 0)
  297. {
  298. close ((int) (pointer_sized_int) fileHandle);
  299. fileHandle = 0;
  300. }
  301. }
  302. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  303. {
  304. if (fileHandle != 0)
  305. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  306. return 0;
  307. }
  308. //==============================================================================
  309. void FileOutputStream::openHandle()
  310. {
  311. if (file.exists())
  312. {
  313. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  314. if (f != -1)
  315. {
  316. currentPosition = lseek (f, 0, SEEK_END);
  317. if (currentPosition >= 0)
  318. fileHandle = (void*) f;
  319. else
  320. close (f);
  321. }
  322. }
  323. else
  324. {
  325. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  326. if (f != -1)
  327. fileHandle = (void*) f;
  328. }
  329. }
  330. void FileOutputStream::closeHandle()
  331. {
  332. if (fileHandle != 0)
  333. {
  334. close ((int) (pointer_sized_int) fileHandle);
  335. fileHandle = 0;
  336. }
  337. }
  338. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  339. {
  340. if (fileHandle != 0)
  341. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  342. return 0;
  343. }
  344. void FileOutputStream::flushInternal()
  345. {
  346. if (fileHandle != 0)
  347. fsync ((int) (pointer_sized_int) fileHandle);
  348. }
  349. //==============================================================================
  350. const File juce_getExecutableFile()
  351. {
  352. Dl_info exeInfo;
  353. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  354. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  355. }
  356. //==============================================================================
  357. // if this file doesn't exist, find a parent of it that does..
  358. static bool juce_doStatFS (File f, struct statfs& result)
  359. {
  360. for (int i = 5; --i >= 0;)
  361. {
  362. if (f.exists())
  363. break;
  364. f = f.getParentDirectory();
  365. }
  366. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  367. }
  368. int64 File::getBytesFreeOnVolume() const
  369. {
  370. struct statfs buf;
  371. if (juce_doStatFS (*this, buf))
  372. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  373. return 0;
  374. }
  375. int64 File::getVolumeTotalSize() const
  376. {
  377. struct statfs buf;
  378. if (juce_doStatFS (*this, buf))
  379. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  380. return 0;
  381. }
  382. const String File::getVolumeLabel() const
  383. {
  384. #if JUCE_MAC
  385. struct VolAttrBuf
  386. {
  387. u_int32_t length;
  388. attrreference_t mountPointRef;
  389. char mountPointSpace [MAXPATHLEN];
  390. } attrBuf;
  391. struct attrlist attrList;
  392. zerostruct (attrList);
  393. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  394. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  395. File f (*this);
  396. for (;;)
  397. {
  398. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  399. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  400. (int) attrBuf.mountPointRef.attr_length);
  401. const File parent (f.getParentDirectory());
  402. if (f == parent)
  403. break;
  404. f = parent;
  405. }
  406. #endif
  407. return String::empty;
  408. }
  409. int File::getVolumeSerialNumber() const
  410. {
  411. return 0; // xxx
  412. }
  413. //==============================================================================
  414. void juce_runSystemCommand (const String& command)
  415. {
  416. int result = system (command.toUTF8());
  417. (void) result;
  418. }
  419. const String juce_getOutputFromCommand (const String& command)
  420. {
  421. // slight bodge here, as we just pipe the output into a temp file and read it...
  422. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  423. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  424. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  425. String result (tempFile.loadFileAsString());
  426. tempFile.deleteFile();
  427. return result;
  428. }
  429. //==============================================================================
  430. class InterProcessLock::Pimpl
  431. {
  432. public:
  433. Pimpl (const String& name, const int timeOutMillisecs)
  434. : handle (0), refCount (1)
  435. {
  436. #if JUCE_MAC
  437. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  438. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  439. #else
  440. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  441. #endif
  442. temp.create();
  443. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  444. if (handle != 0)
  445. {
  446. struct flock fl;
  447. zerostruct (fl);
  448. fl.l_whence = SEEK_SET;
  449. fl.l_type = F_WRLCK;
  450. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  451. for (;;)
  452. {
  453. const int result = fcntl (handle, F_SETLK, &fl);
  454. if (result >= 0)
  455. return;
  456. if (errno != EINTR)
  457. {
  458. if (timeOutMillisecs == 0
  459. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  460. break;
  461. Thread::sleep (10);
  462. }
  463. }
  464. }
  465. closeFile();
  466. }
  467. ~Pimpl()
  468. {
  469. closeFile();
  470. }
  471. void closeFile()
  472. {
  473. if (handle != 0)
  474. {
  475. struct flock fl;
  476. zerostruct (fl);
  477. fl.l_whence = SEEK_SET;
  478. fl.l_type = F_UNLCK;
  479. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  480. {}
  481. close (handle);
  482. handle = 0;
  483. }
  484. }
  485. int handle, refCount;
  486. };
  487. InterProcessLock::InterProcessLock (const String& name_)
  488. : name (name_)
  489. {
  490. }
  491. InterProcessLock::~InterProcessLock()
  492. {
  493. }
  494. bool InterProcessLock::enter (const int timeOutMillisecs)
  495. {
  496. const ScopedLock sl (lock);
  497. if (pimpl == 0)
  498. {
  499. pimpl = new Pimpl (name, timeOutMillisecs);
  500. if (pimpl->handle == 0)
  501. pimpl = 0;
  502. }
  503. else
  504. {
  505. pimpl->refCount++;
  506. }
  507. return pimpl != 0;
  508. }
  509. void InterProcessLock::exit()
  510. {
  511. const ScopedLock sl (lock);
  512. // Trying to release the lock too many times!
  513. jassert (pimpl != 0);
  514. if (pimpl != 0 && --(pimpl->refCount) == 0)
  515. pimpl = 0;
  516. }
  517. //==============================================================================
  518. void JUCE_API juce_threadEntryPoint (void*);
  519. void* threadEntryProc (void* userData)
  520. {
  521. JUCE_AUTORELEASEPOOL
  522. juce_threadEntryPoint (userData);
  523. return 0;
  524. }
  525. void* juce_createThread (void* userData)
  526. {
  527. pthread_t handle = 0;
  528. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  529. {
  530. pthread_detach (handle);
  531. return (void*) handle;
  532. }
  533. return 0;
  534. }
  535. void juce_killThread (void* handle)
  536. {
  537. if (handle != 0)
  538. pthread_cancel ((pthread_t) handle);
  539. }
  540. void juce_setCurrentThreadName (const String& /*name*/)
  541. {
  542. }
  543. bool juce_setThreadPriority (void* handle, int priority)
  544. {
  545. struct sched_param param;
  546. int policy;
  547. priority = jlimit (0, 10, priority);
  548. if (handle == 0)
  549. handle = (void*) pthread_self();
  550. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  551. return false;
  552. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  553. const int minPriority = sched_get_priority_min (policy);
  554. const int maxPriority = sched_get_priority_max (policy);
  555. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  556. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  557. }
  558. Thread::ThreadID Thread::getCurrentThreadId()
  559. {
  560. return (ThreadID) pthread_self();
  561. }
  562. void Thread::yield()
  563. {
  564. sched_yield();
  565. }
  566. //==============================================================================
  567. /* Remove this macro if you're having problems compiling the cpu affinity
  568. calls (the API for these has changed about quite a bit in various Linux
  569. versions, and a lot of distros seem to ship with obsolete versions)
  570. */
  571. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  572. #define SUPPORT_AFFINITIES 1
  573. #endif
  574. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  575. {
  576. #if SUPPORT_AFFINITIES
  577. cpu_set_t affinity;
  578. CPU_ZERO (&affinity);
  579. for (int i = 0; i < 32; ++i)
  580. if ((affinityMask & (1 << i)) != 0)
  581. CPU_SET (i, &affinity);
  582. /*
  583. N.B. If this line causes a compile error, then you've probably not got the latest
  584. version of glibc installed.
  585. If you don't want to update your copy of glibc and don't care about cpu affinities,
  586. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  587. */
  588. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  589. sched_yield();
  590. #else
  591. /* affinities aren't supported because either the appropriate header files weren't found,
  592. or the SUPPORT_AFFINITIES macro was turned off
  593. */
  594. jassertfalse;
  595. #endif
  596. }